mirror of
https://github.com/withastro/astro.git
synced 2025-02-17 22:44:24 -05:00
[ci] format
This commit is contained in:
parent
d6edc75408
commit
9680cf2780
14 changed files with 148 additions and 153 deletions
|
@ -42,18 +42,18 @@ const REROUTABLE_STATUS_CODES = new Set([404, 500]);
|
||||||
export interface RenderOptions {
|
export interface RenderOptions {
|
||||||
/**
|
/**
|
||||||
* Whether to automatically add all cookies written by `Astro.cookie.set()` to the response headers.
|
* Whether to automatically add all cookies written by `Astro.cookie.set()` to the response headers.
|
||||||
*
|
*
|
||||||
* When set to `true`, they will be added to the `Set-Cookie` header as comma-separated key=value pairs. You can use the standard `response.headers.getSetCookie()` API to read them individually.
|
* When set to `true`, they will be added to the `Set-Cookie` header as comma-separated key=value pairs. You can use the standard `response.headers.getSetCookie()` API to read them individually.
|
||||||
*
|
*
|
||||||
* When set to `false`, the cookies will only be available from `App.getSetCookieFromResponse(response)`.
|
* When set to `false`, the cookies will only be available from `App.getSetCookieFromResponse(response)`.
|
||||||
*
|
*
|
||||||
* @default {false}
|
* @default {false}
|
||||||
*/
|
*/
|
||||||
addCookieHeader?: boolean;
|
addCookieHeader?: boolean;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The client IP address that will be made available as `Astro.clientAddress` in pages, and as `ctx.clientAddress` in API routes and middleware.
|
* The client IP address that will be made available as `Astro.clientAddress` in pages, and as `ctx.clientAddress` in API routes and middleware.
|
||||||
*
|
*
|
||||||
* Default: `request[Symbol.for("astro.clientAddress")]`
|
* Default: `request[Symbol.for("astro.clientAddress")]`
|
||||||
*/
|
*/
|
||||||
clientAddress?: string;
|
clientAddress?: string;
|
||||||
|
@ -65,7 +65,7 @@ export interface RenderOptions {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* **Advanced API**: you probably do not need to use this.
|
* **Advanced API**: you probably do not need to use this.
|
||||||
*
|
*
|
||||||
* Default: `app.match(request)`
|
* Default: `app.match(request)`
|
||||||
*/
|
*/
|
||||||
routeData?: RouteData;
|
routeData?: RouteData;
|
||||||
|
@ -196,12 +196,10 @@ export class App {
|
||||||
|
|
||||||
if (
|
if (
|
||||||
routeDataOrOptions &&
|
routeDataOrOptions &&
|
||||||
(
|
('addCookieHeader' in routeDataOrOptions ||
|
||||||
'addCookieHeader' in routeDataOrOptions ||
|
|
||||||
'clientAddress' in routeDataOrOptions ||
|
'clientAddress' in routeDataOrOptions ||
|
||||||
'locals' in routeDataOrOptions ||
|
'locals' in routeDataOrOptions ||
|
||||||
'routeData' in routeDataOrOptions
|
'routeData' in routeDataOrOptions)
|
||||||
)
|
|
||||||
) {
|
) {
|
||||||
if ('addCookieHeader' in routeDataOrOptions) {
|
if ('addCookieHeader' in routeDataOrOptions) {
|
||||||
addCookieHeader = routeDataOrOptions.addCookieHeader;
|
addCookieHeader = routeDataOrOptions.addCookieHeader;
|
||||||
|
@ -226,7 +224,7 @@ export class App {
|
||||||
Reflect.set(request, localsSymbol, locals);
|
Reflect.set(request, localsSymbol, locals);
|
||||||
}
|
}
|
||||||
if (clientAddress) {
|
if (clientAddress) {
|
||||||
Reflect.set(request, clientAddressSymbol, clientAddress)
|
Reflect.set(request, clientAddressSymbol, clientAddress);
|
||||||
}
|
}
|
||||||
// Handle requests with duplicate slashes gracefully by cloning with a cleaned-up request URL
|
// Handle requests with duplicate slashes gracefully by cloning with a cleaned-up request URL
|
||||||
if (request.url !== collapseDuplicateSlashes(request.url)) {
|
if (request.url !== collapseDuplicateSlashes(request.url)) {
|
||||||
|
@ -323,7 +321,7 @@ export class App {
|
||||||
* @param response The response to read cookies from.
|
* @param response The response to read cookies from.
|
||||||
* @returns An iterator that yields key-value pairs as equal-sign-separated strings.
|
* @returns An iterator that yields key-value pairs as equal-sign-separated strings.
|
||||||
*/
|
*/
|
||||||
static getSetCookieFromResponse = getSetCookiesFromResponse
|
static getSetCookieFromResponse = getSetCookiesFromResponse;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates the render context of the current route
|
* Creates the render context of the current route
|
||||||
|
|
|
@ -33,11 +33,7 @@ export class NodeApp extends App {
|
||||||
* @deprecated Instead of passing `RouteData` and locals individually, pass an object with `routeData` and `locals` properties.
|
* @deprecated Instead of passing `RouteData` and locals individually, pass an object with `routeData` and `locals` properties.
|
||||||
* See https://github.com/withastro/astro/pull/9199 for more information.
|
* See https://github.com/withastro/astro/pull/9199 for more information.
|
||||||
*/
|
*/
|
||||||
render(
|
render(request: NodeRequest | Request, routeData?: RouteData, locals?: object): Promise<Response>;
|
||||||
request: NodeRequest | Request,
|
|
||||||
routeData?: RouteData,
|
|
||||||
locals?: object
|
|
||||||
): Promise<Response>;
|
|
||||||
render(
|
render(
|
||||||
req: NodeRequest | Request,
|
req: NodeRequest | Request,
|
||||||
routeDataOrOptions?: RouteData | RenderOptions,
|
routeDataOrOptions?: RouteData | RenderOptions,
|
||||||
|
@ -55,26 +51,24 @@ export class NodeApp extends App {
|
||||||
* ```js
|
* ```js
|
||||||
* import { NodeApp } from 'astro/app/node';
|
* import { NodeApp } from 'astro/app/node';
|
||||||
* import { createServer } from 'node:http';
|
* import { createServer } from 'node:http';
|
||||||
*
|
*
|
||||||
* const server = createServer(async (req, res) => {
|
* const server = createServer(async (req, res) => {
|
||||||
* const request = NodeApp.createRequest(req);
|
* const request = NodeApp.createRequest(req);
|
||||||
* const response = await app.render(request);
|
* const response = await app.render(request);
|
||||||
* await NodeApp.writeResponse(response, res);
|
* await NodeApp.writeResponse(response, res);
|
||||||
* })
|
* })
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
static createRequest(
|
static createRequest(req: NodeRequest, { skipBody = false } = {}): Request {
|
||||||
req: NodeRequest,
|
const protocol =
|
||||||
{ skipBody = false } = {}
|
req.headers['x-forwarded-proto'] ??
|
||||||
): Request {
|
|
||||||
const protocol = req.headers['x-forwarded-proto'] ??
|
|
||||||
('encrypted' in req.socket && req.socket.encrypted ? 'https' : 'http');
|
('encrypted' in req.socket && req.socket.encrypted ? 'https' : 'http');
|
||||||
const hostname = req.headers.host || req.headers[':authority'];
|
const hostname = req.headers.host || req.headers[':authority'];
|
||||||
const url = `${protocol}://${hostname}${req.url}`;
|
const url = `${protocol}://${hostname}${req.url}`;
|
||||||
const options: RequestInit = {
|
const options: RequestInit = {
|
||||||
method: req.method || 'GET',
|
method: req.method || 'GET',
|
||||||
headers: makeRequestHeaders(req),
|
headers: makeRequestHeaders(req),
|
||||||
}
|
};
|
||||||
const bodyAllowed = options.method !== 'HEAD' && options.method !== 'GET' && skipBody === false;
|
const bodyAllowed = options.method !== 'HEAD' && options.method !== 'GET' && skipBody === false;
|
||||||
if (bodyAllowed) {
|
if (bodyAllowed) {
|
||||||
Object.assign(options, makeRequestBody(req));
|
Object.assign(options, makeRequestBody(req));
|
||||||
|
@ -91,14 +85,14 @@ export class NodeApp extends App {
|
||||||
* ```js
|
* ```js
|
||||||
* import { NodeApp } from 'astro/app/node';
|
* import { NodeApp } from 'astro/app/node';
|
||||||
* import { createServer } from 'node:http';
|
* import { createServer } from 'node:http';
|
||||||
*
|
*
|
||||||
* const server = createServer(async (req, res) => {
|
* const server = createServer(async (req, res) => {
|
||||||
* const request = NodeApp.createRequest(req);
|
* const request = NodeApp.createRequest(req);
|
||||||
* const response = await app.render(request);
|
* const response = await app.render(request);
|
||||||
* await NodeApp.writeResponse(response, res);
|
* await NodeApp.writeResponse(response, res);
|
||||||
* })
|
* })
|
||||||
* ```
|
* ```
|
||||||
* @param source WhatWG Response
|
* @param source WhatWG Response
|
||||||
* @param destination NodeJS ServerResponse
|
* @param destination NodeJS ServerResponse
|
||||||
*/
|
*/
|
||||||
static async writeResponse(source: Response, destination: ServerResponse) {
|
static async writeResponse(source: Response, destination: ServerResponse) {
|
||||||
|
@ -111,8 +105,11 @@ export class NodeApp extends App {
|
||||||
// Cancelling the reader may reject not just because of
|
// Cancelling the reader may reject not just because of
|
||||||
// an error in the ReadableStream's cancel callback, but
|
// an error in the ReadableStream's cancel callback, but
|
||||||
// also because of an error anywhere in the stream.
|
// also because of an error anywhere in the stream.
|
||||||
reader.cancel().catch(err => {
|
reader.cancel().catch((err) => {
|
||||||
console.error(`There was an uncaught error in the middle of the stream while rendering ${destination.req.url}.`, err);
|
console.error(
|
||||||
|
`There was an uncaught error in the middle of the stream while rendering ${destination.req.url}.`,
|
||||||
|
err
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
let result = await reader.read();
|
let result = await reader.read();
|
||||||
|
@ -120,13 +117,13 @@ export class NodeApp extends App {
|
||||||
destination.write(result.value);
|
destination.write(result.value);
|
||||||
result = await reader.read();
|
result = await reader.read();
|
||||||
}
|
}
|
||||||
// the error will be logged by the "on end" callback above
|
// the error will be logged by the "on end" callback above
|
||||||
} catch {
|
} catch {
|
||||||
destination.write('Internal server error');
|
destination.write('Internal server error');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
destination.end();
|
destination.end();
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeRequestHeaders(req: NodeRequest): Headers {
|
function makeRequestHeaders(req: NodeRequest): Headers {
|
||||||
|
|
|
@ -397,29 +397,29 @@ export const a11y: AuditRuleWithSelector[] = [
|
||||||
|
|
||||||
const inputElements = element.querySelectorAll('input');
|
const inputElements = element.querySelectorAll('input');
|
||||||
for (const input of inputElements) {
|
for (const input of inputElements) {
|
||||||
// Check for alt attribute if input type is image
|
// Check for alt attribute if input type is image
|
||||||
if (input.type === 'image') {
|
if (input.type === 'image') {
|
||||||
const altAttribute = input.getAttribute('alt');
|
const altAttribute = input.getAttribute('alt');
|
||||||
if (altAttribute && altAttribute.trim() !== '') return false;
|
if (altAttribute && altAttribute.trim() !== '') return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for aria-label
|
||||||
|
const inputAriaLabel = input.getAttribute('aria-label')?.trim();
|
||||||
|
if (inputAriaLabel && inputAriaLabel !== '') return false;
|
||||||
|
|
||||||
|
// Check for aria-labelledby
|
||||||
|
const inputAriaLabelledby = input.getAttribute('aria-labelledby')?.trim();
|
||||||
|
if (inputAriaLabelledby) {
|
||||||
|
const ids = inputAriaLabelledby.split(' ');
|
||||||
|
for (const id of ids) {
|
||||||
|
const referencedElement = document.getElementById(id);
|
||||||
|
if (referencedElement && referencedElement.innerText.trim() !== '') return false;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
// Check for aria-label
|
|
||||||
const inputAriaLabel = input.getAttribute('aria-label')?.trim();
|
// Check for title
|
||||||
if (inputAriaLabel && inputAriaLabel !== '') return false;
|
const title = input.getAttribute('title')?.trim();
|
||||||
|
if (title && title !== '') return false;
|
||||||
// Check for aria-labelledby
|
|
||||||
const inputAriaLabelledby = input.getAttribute('aria-labelledby')?.trim();
|
|
||||||
if (inputAriaLabelledby) {
|
|
||||||
const ids = inputAriaLabelledby.split(' ');
|
|
||||||
for (const id of ids) {
|
|
||||||
const referencedElement = document.getElementById(id);
|
|
||||||
if (referencedElement && referencedElement.innerText.trim() !== '') return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check for title
|
|
||||||
const title = input.getAttribute('title')?.trim();
|
|
||||||
if (title && title !== '') return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// If all checks fail, return true indicating missing content
|
// If all checks fail, return true indicating missing content
|
||||||
|
|
|
@ -93,18 +93,20 @@ describe('Astro.cookies', () => {
|
||||||
const request = new Request('http://example.com/set-value', {
|
const request = new Request('http://example.com/set-value', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
});
|
});
|
||||||
const response = await app.render(request, { addCookieHeader: true })
|
const response = await app.render(request, { addCookieHeader: true });
|
||||||
expect(response.status).to.equal(200);
|
expect(response.status).to.equal(200);
|
||||||
expect(response.headers.get("Set-Cookie")).to.be.a('string').and.satisfy(value => value.startsWith("admin=true; Expires="));
|
expect(response.headers.get('Set-Cookie'))
|
||||||
|
.to.be.a('string')
|
||||||
|
.and.satisfy((value) => value.startsWith('admin=true; Expires='));
|
||||||
});
|
});
|
||||||
|
|
||||||
it('app.render can exclude the cookie from the Set-Cookie header', async () => {
|
it('app.render can exclude the cookie from the Set-Cookie header', async () => {
|
||||||
const request = new Request('http://example.com/set-value', {
|
const request = new Request('http://example.com/set-value', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
});
|
});
|
||||||
const response = await app.render(request, { addCookieHeader: false })
|
const response = await app.render(request, { addCookieHeader: false });
|
||||||
expect(response.status).to.equal(200);
|
expect(response.status).to.equal(200);
|
||||||
expect(response.headers.get("Set-Cookie")).to.equal(null);
|
expect(response.headers.get('Set-Cookie')).to.equal(null);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('Early returning a Response still includes set headers', async () => {
|
it('Early returning a Response still includes set headers', async () => {
|
||||||
|
|
|
@ -33,7 +33,7 @@ describe('Astro.clientAddress', () => {
|
||||||
it('app.render can provide the address', async () => {
|
it('app.render can provide the address', async () => {
|
||||||
const app = await fixture.loadTestAdapterApp();
|
const app = await fixture.loadTestAdapterApp();
|
||||||
const request = new Request('http://example.com/');
|
const request = new Request('http://example.com/');
|
||||||
const response = await app.render(request, { clientAddress: "1.1.1.1" });
|
const response = await app.render(request, { clientAddress: '1.1.1.1' });
|
||||||
const html = await response.text();
|
const html = await response.text();
|
||||||
const $ = cheerio.load(html);
|
const $ = cheerio.load(html);
|
||||||
expect($('#address').text()).to.equal('1.1.1.1');
|
expect($('#address').text()).to.equal('1.1.1.1');
|
||||||
|
|
|
@ -1,20 +1,24 @@
|
||||||
import os from "node:os";
|
import os from 'node:os';
|
||||||
import type http from "node:http";
|
import type http from 'node:http';
|
||||||
import https from "node:https";
|
import https from 'node:https';
|
||||||
import type { AstroIntegrationLogger } from "astro";
|
import type { AstroIntegrationLogger } from 'astro';
|
||||||
import type { Options } from './types.js';
|
import type { Options } from './types.js';
|
||||||
import type { AddressInfo } from "node:net";
|
import type { AddressInfo } from 'node:net';
|
||||||
|
|
||||||
export async function logListeningOn(logger: AstroIntegrationLogger, server: http.Server | https.Server, options: Pick<Options, "host">) {
|
export async function logListeningOn(
|
||||||
await new Promise<void>(resolve => server.once('listening', resolve))
|
logger: AstroIntegrationLogger,
|
||||||
const protocol = server instanceof https.Server ? 'https' : 'http';
|
server: http.Server | https.Server,
|
||||||
// Allow to provide host value at runtime
|
options: Pick<Options, 'host'>
|
||||||
|
) {
|
||||||
|
await new Promise<void>((resolve) => server.once('listening', resolve));
|
||||||
|
const protocol = server instanceof https.Server ? 'https' : 'http';
|
||||||
|
// 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 { port } = server.address() as AddressInfo;
|
const { port } = server.address() as AddressInfo;
|
||||||
const address = getNetworkAddress(protocol, host, port);
|
const address = getNetworkAddress(protocol, host, port);
|
||||||
|
|
||||||
if (host === undefined) {
|
if (host === undefined) {
|
||||||
logger.info(
|
logger.info(
|
||||||
`Server listening on \n local: ${address.local[0]} \t\n network: ${address.network[0]}\n`
|
`Server listening on \n local: ${address.local[0]} \t\n network: ${address.network[0]}\n`
|
||||||
|
|
|
@ -1,34 +1,32 @@
|
||||||
import { createAppHandler } from './serve-app.js';
|
import { createAppHandler } from './serve-app.js';
|
||||||
import type { RequestHandler } from "./types.js";
|
import type { RequestHandler } from './types.js';
|
||||||
import type { NodeApp } from "astro/app/node";
|
import type { NodeApp } from 'astro/app/node';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a middleware that can be used with Express, Connect, etc.
|
* Creates a middleware that can be used with Express, Connect, etc.
|
||||||
*
|
*
|
||||||
* Similar to `createAppHandler` but can additionally be placed in the express
|
* Similar to `createAppHandler` but can additionally be placed in the express
|
||||||
* chain as an error middleware.
|
* chain as an error middleware.
|
||||||
*
|
*
|
||||||
* https://expressjs.com/en/guide/using-middleware.html#middleware.error-handling
|
* https://expressjs.com/en/guide/using-middleware.html#middleware.error-handling
|
||||||
*/
|
*/
|
||||||
export default function createMiddleware(
|
export default function createMiddleware(app: NodeApp): RequestHandler {
|
||||||
app: NodeApp,
|
const handler = createAppHandler(app);
|
||||||
): RequestHandler {
|
const logger = app.getAdapterLogger();
|
||||||
const handler = createAppHandler(app)
|
// using spread args because express trips up if the function's
|
||||||
const logger = app.getAdapterLogger()
|
// stringified body includes req, res, next, locals directly
|
||||||
// using spread args because express trips up if the function's
|
return async function (...args) {
|
||||||
// stringified body includes req, res, next, locals directly
|
// assume normal invocation at first
|
||||||
return async function (...args) {
|
const [req, res, next, locals] = args;
|
||||||
// assume normal invocation at first
|
// short circuit if it is an error invocation
|
||||||
const [req, res, next, locals] = args;
|
if (req instanceof Error) {
|
||||||
// short circuit if it is an error invocation
|
const error = req;
|
||||||
if (req instanceof Error) {
|
if (next) {
|
||||||
const error = req;
|
return next(error);
|
||||||
if (next) {
|
} else {
|
||||||
return next(error);
|
throw error;
|
||||||
} else {
|
}
|
||||||
throw error;
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
await handler(req, res, next, locals);
|
await handler(req, res, next, locals);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
@ -39,5 +37,5 @@ export default function createMiddleware(
|
||||||
res.end();
|
res.end();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,16 +33,16 @@ const createPreviewServer: CreatePreviewServer = async function (preview) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const host = preview.host ?? "localhost"
|
const host = preview.host ?? 'localhost';
|
||||||
const port = preview.port ?? 4321
|
const port = preview.port ?? 4321;
|
||||||
const server = createServer(ssrHandler, host, port);
|
const server = createServer(ssrHandler, host, port);
|
||||||
logListeningOn(preview.logger, server.server, options)
|
logListeningOn(preview.logger, server.server, options);
|
||||||
await new Promise<void>((resolve, reject) => {
|
await new Promise<void>((resolve, reject) => {
|
||||||
server.server.once('listening', resolve);
|
server.server.once('listening', resolve);
|
||||||
server.server.once('error', reject);
|
server.server.once('error', reject);
|
||||||
server.server.listen(port, host);
|
server.server.listen(port, host);
|
||||||
});
|
});
|
||||||
return server;
|
return server;
|
||||||
};
|
};
|
||||||
|
|
||||||
export { createPreviewServer as default }
|
export { createPreviewServer as default };
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
import { NodeApp } from "astro/app/node"
|
import { NodeApp } from 'astro/app/node';
|
||||||
import type { RequestHandler } from "./types.js";
|
import type { RequestHandler } from './types.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a Node.js http listener for on-demand rendered pages, compatible with http.createServer and Connect middleware.
|
* Creates a Node.js http listener for on-demand rendered pages, compatible with http.createServer and Connect middleware.
|
||||||
|
@ -7,21 +7,21 @@ import type { RequestHandler } from "./types.js";
|
||||||
* Intended to be used in both standalone and middleware mode.
|
* Intended to be used in both standalone and middleware mode.
|
||||||
*/
|
*/
|
||||||
export function createAppHandler(app: NodeApp): RequestHandler {
|
export function createAppHandler(app: NodeApp): RequestHandler {
|
||||||
return async (req, res, next, locals) => {
|
return async (req, res, next, locals) => {
|
||||||
const request = NodeApp.createRequest(req);
|
const request = NodeApp.createRequest(req);
|
||||||
const routeData = app.match(request);
|
const routeData = app.match(request);
|
||||||
if (routeData) {
|
if (routeData) {
|
||||||
const response = await app.render(request, {
|
const response = await app.render(request, {
|
||||||
addCookieHeader: true,
|
addCookieHeader: true,
|
||||||
locals,
|
locals,
|
||||||
routeData,
|
routeData,
|
||||||
});
|
});
|
||||||
await NodeApp.writeResponse(response, res);
|
await NodeApp.writeResponse(response, res);
|
||||||
} else if (next) {
|
} else if (next) {
|
||||||
return next();
|
return next();
|
||||||
} else {
|
} else {
|
||||||
const response = await app.render(req);
|
const response = await app.render(req);
|
||||||
await NodeApp.writeResponse(response, res);
|
await NodeApp.writeResponse(response, res);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
import path from "node:path";
|
import path from 'node:path';
|
||||||
import url from "node:url";
|
import url from 'node:url';
|
||||||
import send from "send";
|
import send from 'send';
|
||||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
||||||
import type { Options } from "./types.js";
|
import type { Options } from './types.js';
|
||||||
import type { NodeApp } from "astro/app/node";
|
import type { NodeApp } from 'astro/app/node';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a Node.js http listener for static files and prerendered pages.
|
* Creates a Node.js http listener for static files and prerendered pages.
|
||||||
|
@ -16,7 +16,7 @@ export function createStaticHandler(app: NodeApp, options: Options) {
|
||||||
/**
|
/**
|
||||||
* @param ssr The SSR handler to be called if the static handler does not find a matching file.
|
* @param ssr The SSR handler to be called if the static handler does not find a matching file.
|
||||||
*/
|
*/
|
||||||
return (req: IncomingMessage, res: ServerResponse, ssr: () => unknown) => {
|
return (req: IncomingMessage, res: ServerResponse, ssr: () => unknown) => {
|
||||||
if (req.url) {
|
if (req.url) {
|
||||||
let pathname = app.removeBase(req.url);
|
let pathname = app.removeBase(req.url);
|
||||||
pathname = decodeURI(new URL(pathname, 'http://host').pathname);
|
pathname = decodeURI(new URL(pathname, 'http://host').pathname);
|
||||||
|
@ -39,7 +39,7 @@ export function createStaticHandler(app: NodeApp, options: Options) {
|
||||||
ssr();
|
ssr();
|
||||||
});
|
});
|
||||||
stream.on('headers', (_res: ServerResponse) => {
|
stream.on('headers', (_res: ServerResponse) => {
|
||||||
// assets in dist/_astro are hashed and should get the immutable header
|
// assets in dist/_astro are hashed and should get the immutable header
|
||||||
if (pathname.startsWith(`/${options.assets}/`)) {
|
if (pathname.startsWith(`/${options.assets}/`)) {
|
||||||
// This is the "far future" cache header, used for static files whose name includes their digest hash.
|
// This is the "far future" cache header, used for static files whose name includes their digest hash.
|
||||||
// 1 year (31,536,000 seconds) is convention.
|
// 1 year (31,536,000 seconds) is convention.
|
||||||
|
|
|
@ -11,9 +11,7 @@ export function createExports(manifest: SSRManifest, options: Options) {
|
||||||
return {
|
return {
|
||||||
options: options,
|
options: options,
|
||||||
handler:
|
handler:
|
||||||
options.mode === "middleware"
|
options.mode === 'middleware' ? createMiddleware(app) : createStandaloneHandler(app, options),
|
||||||
? createMiddleware(app)
|
|
||||||
: createStandaloneHandler(app, options),
|
|
||||||
startServer: () => startServer(app, options),
|
startServer: () => startServer(app, options),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,13 +12,13 @@ import type { PreviewServer } from 'astro';
|
||||||
export default function standalone(app: NodeApp, options: Options) {
|
export default function standalone(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;
|
||||||
// Allow to provide host value at runtime
|
// Allow to provide host value at runtime
|
||||||
const hostOptions = typeof options.host === "boolean" ? "localhost" : options.host
|
const hostOptions = typeof options.host === 'boolean' ? 'localhost' : options.host;
|
||||||
const host = process.env.HOST ?? hostOptions;
|
const host = process.env.HOST ?? hostOptions;
|
||||||
const handler = createStandaloneHandler(app, options);
|
const handler = createStandaloneHandler(app, options);
|
||||||
const server = createServer(handler, host, port);
|
const server = createServer(handler, host, port);
|
||||||
server.server.listen(port, host)
|
server.server.listen(port, host);
|
||||||
if (process.env.ASTRO_NODE_LOGGING !== "disabled") {
|
if (process.env.ASTRO_NODE_LOGGING !== 'disabled') {
|
||||||
logListeningOn(app.getAdapterLogger(), server.server, options)
|
logListeningOn(app.getAdapterLogger(), server.server, options);
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
server,
|
server,
|
||||||
|
@ -40,15 +40,11 @@ export function createStandaloneHandler(app: NodeApp, options: Options) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
staticHandler(req, res, () => appHandler(req, res));
|
staticHandler(req, res, () => appHandler(req, res));
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// also used by preview entrypoint
|
// also used by preview entrypoint
|
||||||
export function createServer(
|
export function createServer(listener: http.RequestListener, host: string, port: number) {
|
||||||
listener: http.RequestListener,
|
|
||||||
host: string,
|
|
||||||
port: number
|
|
||||||
) {
|
|
||||||
let httpServer: http.Server | https.Server;
|
let httpServer: http.Server | https.Server;
|
||||||
|
|
||||||
if (process.env.SERVER_CERT_PATH && process.env.SERVER_KEY_PATH) {
|
if (process.env.SERVER_CERT_PATH && process.env.SERVER_KEY_PATH) {
|
||||||
|
@ -69,7 +65,7 @@ export function createServer(
|
||||||
httpServer.addListener('close', resolve);
|
httpServer.addListener('close', resolve);
|
||||||
httpServer.addListener('error', reject);
|
httpServer.addListener('error', reject);
|
||||||
});
|
});
|
||||||
|
|
||||||
const previewable = {
|
const previewable = {
|
||||||
host,
|
host,
|
||||||
port,
|
port,
|
||||||
|
@ -80,7 +76,7 @@ export function createServer(
|
||||||
await new Promise((resolve, reject) => {
|
await new Promise((resolve, reject) => {
|
||||||
httpServer.destroy((err) => (err ? reject(err) : resolve(undefined)));
|
httpServer.destroy((err) => (err ? reject(err) : resolve(undefined)));
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
} satisfies PreviewServer;
|
} satisfies PreviewServer;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
|
@ -2,8 +2,8 @@ import httpMocks from 'node-mocks-http';
|
||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
import { loadFixture as baseLoadFixture } from '../../../astro/test/test-utils.js';
|
import { loadFixture as baseLoadFixture } from '../../../astro/test/test-utils.js';
|
||||||
|
|
||||||
process.env.ASTRO_NODE_AUTOSTART = "disabled";
|
process.env.ASTRO_NODE_AUTOSTART = 'disabled';
|
||||||
process.env.ASTRO_NODE_LOGGING = "disabled";
|
process.env.ASTRO_NODE_LOGGING = 'disabled';
|
||||||
/**
|
/**
|
||||||
* @typedef {import('../../../astro/test/test-utils').Fixture} Fixture
|
* @typedef {import('../../../astro/test/test-utils').Fixture} Fixture
|
||||||
*/
|
*/
|
||||||
|
|
|
@ -9,12 +9,14 @@ export const createExports = (manifest: SSRManifest) => {
|
||||||
const app = new NodeApp(manifest);
|
const app = new NodeApp(manifest);
|
||||||
const handler = async (req: IncomingMessage, res: ServerResponse) => {
|
const handler = async (req: IncomingMessage, res: ServerResponse) => {
|
||||||
const clientAddress = req.headers['x-forwarded-for'] as string | undefined;
|
const clientAddress = req.headers['x-forwarded-for'] as string | undefined;
|
||||||
const localsHeader = req.headers[ASTRO_LOCALS_HEADER]
|
const localsHeader = req.headers[ASTRO_LOCALS_HEADER];
|
||||||
const locals =
|
const locals =
|
||||||
typeof localsHeader === "string" ? JSON.parse(localsHeader)
|
typeof localsHeader === 'string'
|
||||||
: Array.isArray(localsHeader) ? JSON.parse(localsHeader[0])
|
? JSON.parse(localsHeader)
|
||||||
: {};
|
: Array.isArray(localsHeader)
|
||||||
const webResponse = await app.render(req, { locals, clientAddress })
|
? JSON.parse(localsHeader[0])
|
||||||
|
: {};
|
||||||
|
const webResponse = await app.render(req, { locals, clientAddress });
|
||||||
await NodeApp.writeResponse(webResponse, res);
|
await NodeApp.writeResponse(webResponse, res);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue