This commit is contained in:
wuls 2023-05-23 11:31:48 +08:00 committed by Nate Moore
parent 31f822e27d
commit f257895e43
6 changed files with 87 additions and 32 deletions

View file

@ -30,7 +30,6 @@
"build": "astro-scripts build \"src/**/*.ts\" && tsc", "build": "astro-scripts build \"src/**/*.ts\" && tsc",
"build:ci": "astro-scripts build \"src/**/*.ts\"", "build:ci": "astro-scripts build \"src/**/*.ts\"",
"dev": "astro-scripts dev \"src/**/*.ts\"", "dev": "astro-scripts dev \"src/**/*.ts\"",
"t": "mocha --exit --timeout 20000 test/url-protocol.test.js",
"test": "mocha --exit --timeout 20000 test/" "test": "mocha --exit --timeout 20000 test/"
}, },
"dependencies": { "dependencies": {

View file

@ -1,13 +1,48 @@
import os from 'os' import os from 'os'
export function getNetworkAddress(){ interface ReturnValOpt {
const interfaces = os.networkInterfaces(); local: string[]
const ips: string[] = []; network: string[]
Object.keys(interfaces).forEach((nic) => {
interfaces[nic]!.forEach((details) => {
if (details.family === 'IPv4' && !details.internal) {
ips.push(details.address);
}
});
});
return ips?.[0] ? ips?.[0] : '127.0.0.1';
} }
const wildcardHosts = new Set([
'0.0.0.0',
'::',
'0000:0000:0000:0000:0000:0000:0000:0000',
])
type Protocol = 'http' | 'https'
export function getNetworkAddress(protocol: Protocol = 'http', hostname: string, port:number, base?:string) {
const returnVal:ReturnValOpt = {
local: [],
network: []
}
Object.values(os.networkInterfaces())
.flatMap((nInterface) => nInterface ?? [])
.filter(
(detail) =>
detail &&
detail.address &&
(detail.family === 'IPv4' ||
// @ts-expect-error Node 18.0 - 18.3 returns number
detail.family === 4),
)
.forEach((detail) => {
let host = detail.address.replace('127.0.0.1', hostname === undefined || wildcardHosts.has(hostname) ? 'localhost' : hostname)
// ipv6 host
if (host.includes(':')) {
host = `[${host}]`
}
const url = `${protocol}://${host}:${port}${base ? base : ''}`
if (detail.address.includes('127.0.0.1')) {
returnVal.local.push(url)
} else {
returnVal.network.push(url)
}
})
return returnVal
}

View file

@ -59,9 +59,6 @@ const preview: CreatePreviewServer = async function ({
return pathname; return pathname;
} }
if (!host){
host = getNetworkAddress()
}
const server = createServer( const server = createServer(
{ {
@ -72,9 +69,23 @@ const preview: CreatePreviewServer = async function ({
}, },
handler handler
); );
const address = getNetworkAddress('http', host!, port)
if(host === undefined ){
// eslint-disable-next-line no-console
console.log(
`Preview server listening on
\t
local: ${address.local[0]}
\t
network: ${address.network[0]}
` );
}else{
// eslint-disable-next-line no-console
console.log(`Preview server listening on \t
${address.local[0]}`);
}
// eslint-disable-next-line no-console
console.log(`Preview server listening on http://${host}:${port}`);
return server; return server;
}; };

View file

@ -40,11 +40,14 @@ export default function startServer(app: NodeApp, options: Options) {
const port = process.env.PORT ? Number(process.env.PORT) : options.port ?? 8080; const port = process.env.PORT ? Number(process.env.PORT) : options.port ?? 8080;
const { client } = resolvePaths(options); const { client } = resolvePaths(options);
const handler = middleware(app, options.mode); const handler = middleware(app, options.mode);
// Allow to provide host value at runtime // Allow to provide host value at runtime
const host = getResolvedHostForHttpServer( const host = getResolvedHostForHttpServer(
process.env.HOST !== undefined && process.env.HOST !== '' ? process.env.HOST : options.host process.env.HOST !== undefined && process.env.HOST !== '' ? process.env.HOST : options.host
); );
const server = createServer( const server = createServer(
{ {
client, client,
@ -54,11 +57,23 @@ export default function startServer(app: NodeApp, options: Options) {
}, },
handler handler
); );
const protocol = server.server instanceof https.Server ? 'https' : 'http'; const protocol = server.server instanceof https.Server ? 'https' : 'http';
const address = getNetworkAddress(protocol, host!, port)
// eslint-disable-next-line no-console if(host === undefined ){
console.log(`Server listening on ${protocol}://${host}:${port}`); // eslint-disable-next-line no-console
console.log(
`Preview server listening on
\t
local: ${address.local[0]}
\t
network: ${address.network[0]}
` );
}else{
// eslint-disable-next-line no-console
console.log(`Preview server listening on \t
${address.local[0]}`);
}
return { return {
server, server,

View file

@ -5,9 +5,5 @@
"dependencies": { "dependencies": {
"astro": "workspace:*", "astro": "workspace:*",
"@astrojs/node": "workspace:*" "@astrojs/node": "workspace:*"
},
"scripts": {
"build": "astro build",
"preview": "astro preview"
} }
} }

View file

@ -1,7 +1,6 @@
import { expect } from 'chai'; import { expect } from 'chai';
import { TLSSocket } from 'node:tls'; import { getNetworkAddress } from '../dist/get-network-address.js'
import nodejs from '../dist/index.js'; import { fetch } from 'undici';
import { createRequestAndResponse, loadFixture } from './test-utils.js';
describe('URL protocol', () => { describe('URL protocol', () => {
/** @type {import('./test-utils').Fixture} */ /** @type {import('./test-utils').Fixture} */
@ -26,10 +25,10 @@ describe('URL protocol', () => {
devPreview = await fixture.preview(); devPreview = await fixture.preview();
}); });
it('test host is true ', () => { it('test host is true ', async () => {
const host = devPreview.host const address = getNetworkAddress('http', undefined, 3000)
const ishost = () => host.startsWith('127') || host.startsWith('loc') const res = await fetch(address.network[0])
expect(!ishost()).eq(true) expect(res.status).to.equal(200);
}); });
}) })
it('return http when non-secure', async () => { it('return http when non-secure', async () => {