@patternfly/patternfly-doc-core 1.2.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.astro/collections/textContent.schema.json +6 -0
- package/README.md +11 -10
- package/astro.config.mjs +8 -1
- package/cli/buildPropsData.ts +113 -0
- package/cli/cli.ts +52 -6
- package/cli/getConfig.ts +6 -0
- package/cli/hasFile.ts +5 -0
- package/cli/templates/pf-docs.config.mjs +13 -2
- package/cli/tsDocGen.js +199 -0
- package/dist/cli/buildPropsData.js +68 -0
- package/dist/cli/cli.js +37 -4
- package/dist/cli/hasFile.js +4 -0
- package/dist/cli/templates/pf-docs.config.mjs +12 -1
- package/dist/cli/tsDocGen.js +153 -0
- package/dist/cli/tsconfig.tsbuildinfo +1 -1
- package/dist/client/_astro/_page_.SnUmZn2y.css +1 -0
- package/dist/client/design-foundations/typography/index.html +219 -0
- package/dist/client/design-foundations/usage-and-behavior/index.html +368 -0
- package/dist/client/get-started/contribute/index.html +115 -0
- package/dist/client/index.html +42 -0
- package/dist/server/_@astrojs-ssr-adapter.mjs +1 -0
- package/dist/server/_noop-middleware.mjs +3 -0
- package/dist/server/chunks/PropsTables_D_v4KAMn.mjs +1826 -0
- package/dist/server/chunks/_@astrojs-ssr-adapter_ByVMUK8O.mjs +3621 -0
- package/dist/server/chunks/_astro_assets_CLOMnm-3.mjs +1507 -0
- package/dist/server/chunks/_astro_data-layer-content_DDGBHvtb.mjs +1 -0
- package/dist/server/chunks/angle-down-icon_BNJvzYv-.mjs +3970 -0
- package/dist/server/chunks/astro/server_D4f31GMD.mjs +2769 -0
- package/dist/server/chunks/astro-designed-error-pages_CpHpbfhr.mjs +282 -0
- package/dist/server/chunks/consts_BmVDRGlB.mjs +32 -0
- package/dist/server/chunks/content-assets_DleWbedO.mjs +1 -0
- package/dist/server/chunks/content-modules_Dz-S_Wwv.mjs +1 -0
- package/dist/server/chunks/path_Cvt6sEOY.mjs +58 -0
- package/dist/server/chunks/sharp_BYpUyJGL.mjs +88 -0
- package/dist/server/entry.mjs +45 -0
- package/dist/server/manifest_Bln0Ib60.mjs +102 -0
- package/dist/server/pages/_image.astro.mjs +132 -0
- package/dist/server/pages/_section_/_---page_.astro.mjs +1 -0
- package/dist/server/pages/_section_/_page_/_---tab_.astro.mjs +1 -0
- package/dist/server/pages/index.astro.mjs +1 -0
- package/dist/server/pages/props.astro.mjs +25 -0
- package/dist/server/renderers.mjs +259 -0
- package/jest.config.ts +1 -1
- package/package.json +4 -1
- package/pf-docs.config.mjs +31 -0
- package/src/components/PropsTable.tsx +3 -3
- package/src/components/PropsTables.astro +38 -0
- package/src/content.config.ts +1 -0
- package/src/pages/[section]/[...page].astro +16 -8
- package/src/pages/[section]/[page]/[...tab].astro +4 -1
- package/src/pages/props.ts +17 -0
- package/textContent/contribute.md +1 -0
- package/dist/design-foundations/typography/index.html +0 -193
- package/dist/design-foundations/usage-and-behavior/index.html +0 -342
- package/dist/get-started/contribute/index.html +0 -89
- package/dist/index.html +0 -42
- /package/dist/{PF-HorizontalLogo-Color.svg → client/PF-HorizontalLogo-Color.svg} +0 -0
- /package/dist/{PF-HorizontalLogo-Reverse.svg → client/PF-HorizontalLogo-Reverse.svg} +0 -0
- /package/dist/{_astro → client/_astro}/Button.C3_jB5tC.js +0 -0
- /package/dist/{_astro → client/_astro}/ClientRouter.astro_astro_type_script_index_0_lang.Cainpjm5.js +0 -0
- /package/dist/{_astro → client/_astro}/Navigation.Cede__Ud.js +0 -0
- /package/dist/{_astro → client/_astro}/PageContext.C7BqCh9N.js +0 -0
- /package/dist/{_astro → client/_astro}/PageToggle.DDEjruql.js +0 -0
- /package/dist/{_astro → client/_astro}/RedHatDisplayVF-Italic.CRpusWc8.woff2 +0 -0
- /package/dist/{_astro → client/_astro}/RedHatDisplayVF.CYDHf1NI.woff2 +0 -0
- /package/dist/{_astro → client/_astro}/RedHatMonoVF-Italic.DGQo2ogW.woff2 +0 -0
- /package/dist/{_astro → client/_astro}/RedHatMonoVF.C4fMH6Vz.woff2 +0 -0
- /package/dist/{_astro → client/_astro}/RedHatTextVF-Italic.Dkj_WqbA.woff2 +0 -0
- /package/dist/{_astro → client/_astro}/RedHatTextVF.wYvZ7prR.woff2 +0 -0
- /package/dist/{_astro → client/_astro}/Toolbar.TAdHxLSQ.js +0 -0
- /package/dist/{_astro → client/_astro}/_page_.CXyz_BEo.css +0 -0
- /package/dist/{_astro → client/_astro}/_page_.DVvr_Mfl.css +0 -0
- /package/dist/{_astro → client/_astro}/client.CeeiqVaE.js +0 -0
- /package/dist/{_astro → client/_astro}/divider.BSD-oFoh.js +0 -0
- /package/dist/{_astro → client/_astro}/fa-solid-900.DguXoeIz.woff2 +0 -0
- /package/dist/{_astro → client/_astro}/index.CTH3fVMn.js +0 -0
- /package/dist/{_astro → client/_astro}/page.B65lVdBS.js +0 -0
- /package/dist/{_astro → client/_astro}/pf-v6-pficon.Dy6oiu9u.woff2 +0 -0
- /package/dist/{avatarImg.svg → client/avatarImg.svg} +0 -0
- /package/dist/{avatarImgDark.svg → client/avatarImgDark.svg} +0 -0
- /package/dist/{content → client/content}/typography/line-height.png +0 -0
- /package/dist/{favicon.svg → client/favicon.svg} +0 -0
|
@@ -0,0 +1,3621 @@
|
|
|
1
|
+
import { n as decryptString, o as createSlotValueFromString, p as isAstroComponentFactory, r as renderComponent, b as renderTemplate, q as ROUTE_TYPE_HEADER, s as REROUTE_DIRECTIVE_HEADER, A as AstroError, t as i18nNoLocaleFoundInPath, v as ResponseSentError, M as MiddlewareNoDataOrNextCalled, w as MiddlewareNotAResponse, x as originPathnameSymbol, y as RewriteWithBodyUsed, G as GetStaticPathsRequired, I as InvalidGetStaticPathsReturn, z as InvalidGetStaticPathsEntry, B as GetStaticPathsExpectedParams, C as GetStaticPathsInvalidRouteParam, P as PageNumberParamNotFound, D as DEFAULT_404_COMPONENT, N as NoMatchingStaticPathFound, E as PrerenderDynamicEndpointPathCollide, F as ReservedSlotName, H as renderSlotToString, J as renderJSX, K as chunkToString, L as isRenderInstruction, O as ForbiddenRewrite, S as SessionStorageSaveError, Q as SessionStorageInitError, T as ASTRO_VERSION, V as LocalsReassigned, W as PrerenderClientAddressNotAvailable, X as clientAddressSymbol, Y as ClientAddressNotAvailable, Z as StaticClientAddressNotAvailable, _ as AstroResponseHeadersReassigned, $ as responseSentSymbol$1, a0 as renderPage, a1 as REWRITE_DIRECTIVE_HEADER_KEY, a2 as REWRITE_DIRECTIVE_HEADER_VALUE, a3 as renderEndpoint, a4 as LocalsNotAnObject, a5 as REROUTABLE_STATUS_CODES } from './astro/server_D4f31GMD.mjs';
|
|
2
|
+
import { bold, red, yellow, dim, blue } from 'kleur/colors';
|
|
3
|
+
import 'clsx';
|
|
4
|
+
import { serialize, parse } from 'cookie';
|
|
5
|
+
import { g as getActionQueryString, d as deserializeActionResult, D as DEFAULT_404_ROUTE, a as default404Instance, N as NOOP_MIDDLEWARE_FN, e as ensure404Route } from './astro-designed-error-pages_CpHpbfhr.mjs';
|
|
6
|
+
import 'es-module-lexer';
|
|
7
|
+
import buffer from 'node:buffer';
|
|
8
|
+
import crypto$1 from 'node:crypto';
|
|
9
|
+
import { Http2ServerResponse } from 'node:http2';
|
|
10
|
+
import { a as appendForwardSlash$1, j as joinPaths, b as removeTrailingForwardSlash, p as prependForwardSlash$1, t as trimSlashes, f as fileExtension, s as slash, c as collapseDuplicateTrailingSlashes, h as hasFileExtension$1 } from './path_Cvt6sEOY.mjs';
|
|
11
|
+
import { unflatten as unflatten$1, stringify as stringify$1 } from 'devalue';
|
|
12
|
+
import { createStorage, builtinDrivers } from 'unstorage';
|
|
13
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import http from 'node:http';
|
|
16
|
+
import https from 'node:https';
|
|
17
|
+
import enableDestroy from 'server-destroy';
|
|
18
|
+
import os from 'node:os';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import url from 'node:url';
|
|
21
|
+
import send from 'send';
|
|
22
|
+
|
|
23
|
+
function shouldAppendForwardSlash(trailingSlash, buildFormat) {
|
|
24
|
+
switch (trailingSlash) {
|
|
25
|
+
case "always":
|
|
26
|
+
return true;
|
|
27
|
+
case "never":
|
|
28
|
+
return false;
|
|
29
|
+
case "ignore": {
|
|
30
|
+
switch (buildFormat) {
|
|
31
|
+
case "directory":
|
|
32
|
+
return true;
|
|
33
|
+
case "preserve":
|
|
34
|
+
case "file":
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function redirectIsExternal(redirect) {
|
|
42
|
+
if (typeof redirect === "string") {
|
|
43
|
+
return redirect.startsWith("http://") || redirect.startsWith("https://");
|
|
44
|
+
} else {
|
|
45
|
+
return redirect.destination.startsWith("http://") || redirect.destination.startsWith("https://");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
async function renderRedirect(renderContext) {
|
|
49
|
+
const {
|
|
50
|
+
request: { method },
|
|
51
|
+
routeData
|
|
52
|
+
} = renderContext;
|
|
53
|
+
const { redirect, redirectRoute } = routeData;
|
|
54
|
+
const status = redirectRoute && typeof redirect === "object" ? redirect.status : method === "GET" ? 301 : 308;
|
|
55
|
+
const headers = { location: encodeURI(redirectRouteGenerate(renderContext)) };
|
|
56
|
+
if (redirect && redirectIsExternal(redirect)) {
|
|
57
|
+
if (typeof redirect === "string") {
|
|
58
|
+
return Response.redirect(redirect, status);
|
|
59
|
+
} else {
|
|
60
|
+
return Response.redirect(redirect.destination, status);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return new Response(null, { status, headers });
|
|
64
|
+
}
|
|
65
|
+
function redirectRouteGenerate(renderContext) {
|
|
66
|
+
const {
|
|
67
|
+
params,
|
|
68
|
+
routeData: { redirect, redirectRoute }
|
|
69
|
+
} = renderContext;
|
|
70
|
+
if (typeof redirectRoute !== "undefined") {
|
|
71
|
+
return redirectRoute?.generate(params) || redirectRoute?.pathname || "/";
|
|
72
|
+
} else if (typeof redirect === "string") {
|
|
73
|
+
if (redirectIsExternal(redirect)) {
|
|
74
|
+
return redirect;
|
|
75
|
+
} else {
|
|
76
|
+
let target = redirect;
|
|
77
|
+
for (const param of Object.keys(params)) {
|
|
78
|
+
const paramValue = params[param];
|
|
79
|
+
target = target.replace(`[${param}]`, paramValue).replace(`[...${param}]`, paramValue);
|
|
80
|
+
}
|
|
81
|
+
return target;
|
|
82
|
+
}
|
|
83
|
+
} else if (typeof redirect === "undefined") {
|
|
84
|
+
return "/";
|
|
85
|
+
}
|
|
86
|
+
return redirect.destination;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const SERVER_ISLAND_ROUTE = "/_server-islands/[name]";
|
|
90
|
+
const SERVER_ISLAND_COMPONENT = "_server-islands.astro";
|
|
91
|
+
const SERVER_ISLAND_BASE_PREFIX = "_server-islands";
|
|
92
|
+
function badRequest(reason) {
|
|
93
|
+
return new Response(null, {
|
|
94
|
+
status: 400,
|
|
95
|
+
statusText: "Bad request: " + reason
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
async function getRequestData(request) {
|
|
99
|
+
switch (request.method) {
|
|
100
|
+
case "GET": {
|
|
101
|
+
const url = new URL(request.url);
|
|
102
|
+
const params = url.searchParams;
|
|
103
|
+
if (!params.has("s") || !params.has("e") || !params.has("p")) {
|
|
104
|
+
return badRequest("Missing required query parameters.");
|
|
105
|
+
}
|
|
106
|
+
const rawSlots = params.get("s");
|
|
107
|
+
try {
|
|
108
|
+
return {
|
|
109
|
+
componentExport: params.get("e"),
|
|
110
|
+
encryptedProps: params.get("p"),
|
|
111
|
+
slots: JSON.parse(rawSlots)
|
|
112
|
+
};
|
|
113
|
+
} catch {
|
|
114
|
+
return badRequest("Invalid slots format.");
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
case "POST": {
|
|
118
|
+
try {
|
|
119
|
+
const raw = await request.text();
|
|
120
|
+
const data = JSON.parse(raw);
|
|
121
|
+
return data;
|
|
122
|
+
} catch {
|
|
123
|
+
return badRequest("Request format is invalid.");
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
default: {
|
|
127
|
+
return new Response(null, { status: 405 });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function createEndpoint(manifest) {
|
|
132
|
+
const page = async (result) => {
|
|
133
|
+
const params = result.params;
|
|
134
|
+
if (!params.name) {
|
|
135
|
+
return new Response(null, {
|
|
136
|
+
status: 400,
|
|
137
|
+
statusText: "Bad request"
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
const componentId = params.name;
|
|
141
|
+
const data = await getRequestData(result.request);
|
|
142
|
+
if (data instanceof Response) {
|
|
143
|
+
return data;
|
|
144
|
+
}
|
|
145
|
+
const imp = manifest.serverIslandMap?.get(componentId);
|
|
146
|
+
if (!imp) {
|
|
147
|
+
return new Response(null, {
|
|
148
|
+
status: 404,
|
|
149
|
+
statusText: "Not found"
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
const key = await manifest.key;
|
|
153
|
+
const encryptedProps = data.encryptedProps;
|
|
154
|
+
const propString = encryptedProps === "" ? "{}" : await decryptString(key, encryptedProps);
|
|
155
|
+
const props = JSON.parse(propString);
|
|
156
|
+
const componentModule = await imp();
|
|
157
|
+
let Component = componentModule[data.componentExport];
|
|
158
|
+
const slots = {};
|
|
159
|
+
for (const prop in data.slots) {
|
|
160
|
+
slots[prop] = createSlotValueFromString(data.slots[prop]);
|
|
161
|
+
}
|
|
162
|
+
result.response.headers.set("X-Robots-Tag", "noindex");
|
|
163
|
+
if (isAstroComponentFactory(Component)) {
|
|
164
|
+
const ServerIsland = Component;
|
|
165
|
+
Component = function(...args) {
|
|
166
|
+
return ServerIsland.apply(this, args);
|
|
167
|
+
};
|
|
168
|
+
Object.assign(Component, ServerIsland);
|
|
169
|
+
Component.propagation = "self";
|
|
170
|
+
}
|
|
171
|
+
return renderTemplate`${renderComponent(result, "Component", Component, props, slots)}`;
|
|
172
|
+
};
|
|
173
|
+
page.isAstroComponentFactory = true;
|
|
174
|
+
const instance = {
|
|
175
|
+
default: page,
|
|
176
|
+
partial: true
|
|
177
|
+
};
|
|
178
|
+
return instance;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function matchRoute(pathname, manifest) {
|
|
182
|
+
return manifest.routes.find((route) => {
|
|
183
|
+
return route.pattern.test(pathname) || route.fallbackRoutes.some((fallbackRoute) => fallbackRoute.pattern.test(pathname));
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
const ROUTE404_RE = /^\/404\/?$/;
|
|
187
|
+
const ROUTE500_RE = /^\/500\/?$/;
|
|
188
|
+
function isRoute404(route) {
|
|
189
|
+
return ROUTE404_RE.test(route);
|
|
190
|
+
}
|
|
191
|
+
function isRoute500(route) {
|
|
192
|
+
return ROUTE500_RE.test(route);
|
|
193
|
+
}
|
|
194
|
+
function isRoute404or500(route) {
|
|
195
|
+
return isRoute404(route.route) || isRoute500(route.route);
|
|
196
|
+
}
|
|
197
|
+
function isRouteServerIsland(route) {
|
|
198
|
+
return route.component === SERVER_ISLAND_COMPONENT;
|
|
199
|
+
}
|
|
200
|
+
function isRequestServerIsland(request, base = "") {
|
|
201
|
+
const url = new URL(request.url);
|
|
202
|
+
const pathname = base === "/" ? url.pathname.slice(base.length) : url.pathname.slice(base.length + 1);
|
|
203
|
+
return pathname.startsWith(SERVER_ISLAND_BASE_PREFIX);
|
|
204
|
+
}
|
|
205
|
+
function requestIs404Or500(request, base = "") {
|
|
206
|
+
const url = new URL(request.url);
|
|
207
|
+
const pathname = url.pathname.slice(base.length);
|
|
208
|
+
return isRoute404(pathname) || isRoute500(pathname);
|
|
209
|
+
}
|
|
210
|
+
function isRouteExternalRedirect(route) {
|
|
211
|
+
return !!(route.type === "redirect" && route.redirect && redirectIsExternal(route.redirect));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function createI18nMiddleware(i18n, base, trailingSlash, format) {
|
|
215
|
+
if (!i18n) return (_, next) => next();
|
|
216
|
+
const payload = {
|
|
217
|
+
...i18n,
|
|
218
|
+
trailingSlash,
|
|
219
|
+
base,
|
|
220
|
+
format};
|
|
221
|
+
const _redirectToDefaultLocale = redirectToDefaultLocale(payload);
|
|
222
|
+
const _noFoundForNonLocaleRoute = notFound(payload);
|
|
223
|
+
const _requestHasLocale = requestHasLocale(payload.locales);
|
|
224
|
+
const _redirectToFallback = redirectToFallback(payload);
|
|
225
|
+
const prefixAlways = (context, response) => {
|
|
226
|
+
const url = context.url;
|
|
227
|
+
if (url.pathname === base + "/" || url.pathname === base) {
|
|
228
|
+
return _redirectToDefaultLocale(context);
|
|
229
|
+
} else if (!_requestHasLocale(context)) {
|
|
230
|
+
return _noFoundForNonLocaleRoute(context, response);
|
|
231
|
+
}
|
|
232
|
+
return void 0;
|
|
233
|
+
};
|
|
234
|
+
const prefixOtherLocales = (context, response) => {
|
|
235
|
+
let pathnameContainsDefaultLocale = false;
|
|
236
|
+
const url = context.url;
|
|
237
|
+
for (const segment of url.pathname.split("/")) {
|
|
238
|
+
if (normalizeTheLocale(segment) === normalizeTheLocale(i18n.defaultLocale)) {
|
|
239
|
+
pathnameContainsDefaultLocale = true;
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (pathnameContainsDefaultLocale) {
|
|
244
|
+
const newLocation = url.pathname.replace(`/${i18n.defaultLocale}`, "");
|
|
245
|
+
response.headers.set("Location", newLocation);
|
|
246
|
+
return _noFoundForNonLocaleRoute(context);
|
|
247
|
+
}
|
|
248
|
+
return void 0;
|
|
249
|
+
};
|
|
250
|
+
return async (context, next) => {
|
|
251
|
+
const response = await next();
|
|
252
|
+
const type = response.headers.get(ROUTE_TYPE_HEADER);
|
|
253
|
+
const isReroute = response.headers.get(REROUTE_DIRECTIVE_HEADER);
|
|
254
|
+
if (isReroute === "no" && typeof i18n.fallback === "undefined") {
|
|
255
|
+
return response;
|
|
256
|
+
}
|
|
257
|
+
if (type !== "page" && type !== "fallback") {
|
|
258
|
+
return response;
|
|
259
|
+
}
|
|
260
|
+
if (requestIs404Or500(context.request, base)) {
|
|
261
|
+
return response;
|
|
262
|
+
}
|
|
263
|
+
if (isRequestServerIsland(context.request, base)) {
|
|
264
|
+
return response;
|
|
265
|
+
}
|
|
266
|
+
const { currentLocale } = context;
|
|
267
|
+
switch (i18n.strategy) {
|
|
268
|
+
// NOTE: theoretically, we should never hit this code path
|
|
269
|
+
case "manual": {
|
|
270
|
+
return response;
|
|
271
|
+
}
|
|
272
|
+
case "domains-prefix-other-locales": {
|
|
273
|
+
if (localeHasntDomain(i18n, currentLocale)) {
|
|
274
|
+
const result = prefixOtherLocales(context, response);
|
|
275
|
+
if (result) {
|
|
276
|
+
return result;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
case "pathname-prefix-other-locales": {
|
|
282
|
+
const result = prefixOtherLocales(context, response);
|
|
283
|
+
if (result) {
|
|
284
|
+
return result;
|
|
285
|
+
}
|
|
286
|
+
break;
|
|
287
|
+
}
|
|
288
|
+
case "domains-prefix-always-no-redirect": {
|
|
289
|
+
if (localeHasntDomain(i18n, currentLocale)) {
|
|
290
|
+
const result = _noFoundForNonLocaleRoute(context, response);
|
|
291
|
+
if (result) {
|
|
292
|
+
return result;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
case "pathname-prefix-always-no-redirect": {
|
|
298
|
+
const result = _noFoundForNonLocaleRoute(context, response);
|
|
299
|
+
if (result) {
|
|
300
|
+
return result;
|
|
301
|
+
}
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
304
|
+
case "pathname-prefix-always": {
|
|
305
|
+
const result = prefixAlways(context, response);
|
|
306
|
+
if (result) {
|
|
307
|
+
return result;
|
|
308
|
+
}
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
case "domains-prefix-always": {
|
|
312
|
+
if (localeHasntDomain(i18n, currentLocale)) {
|
|
313
|
+
const result = prefixAlways(context, response);
|
|
314
|
+
if (result) {
|
|
315
|
+
return result;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
break;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return _redirectToFallback(context, response);
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
function localeHasntDomain(i18n, currentLocale) {
|
|
325
|
+
for (const domainLocale of Object.values(i18n.domainLookupTable)) {
|
|
326
|
+
if (domainLocale === currentLocale) {
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function requestHasLocale(locales) {
|
|
334
|
+
return function(context) {
|
|
335
|
+
return pathHasLocale(context.url.pathname, locales);
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
function pathHasLocale(path, locales) {
|
|
339
|
+
const segments = path.split("/");
|
|
340
|
+
for (const segment of segments) {
|
|
341
|
+
for (const locale of locales) {
|
|
342
|
+
if (typeof locale === "string") {
|
|
343
|
+
if (normalizeTheLocale(segment) === normalizeTheLocale(locale)) {
|
|
344
|
+
return true;
|
|
345
|
+
}
|
|
346
|
+
} else if (segment === locale.path) {
|
|
347
|
+
return true;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
return false;
|
|
352
|
+
}
|
|
353
|
+
function getPathByLocale(locale, locales) {
|
|
354
|
+
for (const loopLocale of locales) {
|
|
355
|
+
if (typeof loopLocale === "string") {
|
|
356
|
+
if (loopLocale === locale) {
|
|
357
|
+
return loopLocale;
|
|
358
|
+
}
|
|
359
|
+
} else {
|
|
360
|
+
for (const code of loopLocale.codes) {
|
|
361
|
+
if (code === locale) {
|
|
362
|
+
return loopLocale.path;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
throw new AstroError(i18nNoLocaleFoundInPath);
|
|
368
|
+
}
|
|
369
|
+
function normalizeTheLocale(locale) {
|
|
370
|
+
return locale.replaceAll("_", "-").toLowerCase();
|
|
371
|
+
}
|
|
372
|
+
function toCodes(locales) {
|
|
373
|
+
return locales.map((loopLocale) => {
|
|
374
|
+
if (typeof loopLocale === "string") {
|
|
375
|
+
return loopLocale;
|
|
376
|
+
} else {
|
|
377
|
+
return loopLocale.codes[0];
|
|
378
|
+
}
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
function redirectToDefaultLocale({
|
|
382
|
+
trailingSlash,
|
|
383
|
+
format,
|
|
384
|
+
base,
|
|
385
|
+
defaultLocale
|
|
386
|
+
}) {
|
|
387
|
+
return function(context, statusCode) {
|
|
388
|
+
if (shouldAppendForwardSlash(trailingSlash, format)) {
|
|
389
|
+
return context.redirect(`${appendForwardSlash$1(joinPaths(base, defaultLocale))}`, statusCode);
|
|
390
|
+
} else {
|
|
391
|
+
return context.redirect(`${joinPaths(base, defaultLocale)}`, statusCode);
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
function notFound({ base, locales, fallback }) {
|
|
396
|
+
return function(context, response) {
|
|
397
|
+
if (response?.headers.get(REROUTE_DIRECTIVE_HEADER) === "no" && typeof fallback === "undefined") {
|
|
398
|
+
return response;
|
|
399
|
+
}
|
|
400
|
+
const url = context.url;
|
|
401
|
+
const isRoot = url.pathname === base + "/" || url.pathname === base;
|
|
402
|
+
if (!(isRoot || pathHasLocale(url.pathname, locales))) {
|
|
403
|
+
if (response) {
|
|
404
|
+
response.headers.set(REROUTE_DIRECTIVE_HEADER, "no");
|
|
405
|
+
return new Response(response.body, {
|
|
406
|
+
status: 404,
|
|
407
|
+
headers: response.headers
|
|
408
|
+
});
|
|
409
|
+
} else {
|
|
410
|
+
return new Response(null, {
|
|
411
|
+
status: 404,
|
|
412
|
+
headers: {
|
|
413
|
+
[REROUTE_DIRECTIVE_HEADER]: "no"
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
return void 0;
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
function redirectToFallback({
|
|
422
|
+
fallback,
|
|
423
|
+
locales,
|
|
424
|
+
defaultLocale,
|
|
425
|
+
strategy,
|
|
426
|
+
base,
|
|
427
|
+
fallbackType
|
|
428
|
+
}) {
|
|
429
|
+
return async function(context, response) {
|
|
430
|
+
if (response.status >= 300 && fallback) {
|
|
431
|
+
const fallbackKeys = fallback ? Object.keys(fallback) : [];
|
|
432
|
+
const segments = context.url.pathname.split("/");
|
|
433
|
+
const urlLocale = segments.find((segment) => {
|
|
434
|
+
for (const locale of locales) {
|
|
435
|
+
if (typeof locale === "string") {
|
|
436
|
+
if (locale === segment) {
|
|
437
|
+
return true;
|
|
438
|
+
}
|
|
439
|
+
} else if (locale.path === segment) {
|
|
440
|
+
return true;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
return false;
|
|
444
|
+
});
|
|
445
|
+
if (urlLocale && fallbackKeys.includes(urlLocale)) {
|
|
446
|
+
const fallbackLocale = fallback[urlLocale];
|
|
447
|
+
const pathFallbackLocale = getPathByLocale(fallbackLocale, locales);
|
|
448
|
+
let newPathname;
|
|
449
|
+
if (pathFallbackLocale === defaultLocale && strategy === "pathname-prefix-other-locales") {
|
|
450
|
+
if (context.url.pathname.includes(`${base}`)) {
|
|
451
|
+
newPathname = context.url.pathname.replace(`/${urlLocale}`, ``);
|
|
452
|
+
} else {
|
|
453
|
+
newPathname = context.url.pathname.replace(`/${urlLocale}`, `/`);
|
|
454
|
+
}
|
|
455
|
+
} else {
|
|
456
|
+
newPathname = context.url.pathname.replace(`/${urlLocale}`, `/${pathFallbackLocale}`);
|
|
457
|
+
}
|
|
458
|
+
if (fallbackType === "rewrite") {
|
|
459
|
+
return await context.rewrite(newPathname + context.url.search);
|
|
460
|
+
} else {
|
|
461
|
+
return context.redirect(newPathname + context.url.search);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
return response;
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const DELETED_EXPIRATION = /* @__PURE__ */ new Date(0);
|
|
470
|
+
const DELETED_VALUE = "deleted";
|
|
471
|
+
const responseSentSymbol = Symbol.for("astro.responseSent");
|
|
472
|
+
class AstroCookie {
|
|
473
|
+
constructor(value) {
|
|
474
|
+
this.value = value;
|
|
475
|
+
}
|
|
476
|
+
json() {
|
|
477
|
+
if (this.value === void 0) {
|
|
478
|
+
throw new Error(`Cannot convert undefined to an object.`);
|
|
479
|
+
}
|
|
480
|
+
return JSON.parse(this.value);
|
|
481
|
+
}
|
|
482
|
+
number() {
|
|
483
|
+
return Number(this.value);
|
|
484
|
+
}
|
|
485
|
+
boolean() {
|
|
486
|
+
if (this.value === "false") return false;
|
|
487
|
+
if (this.value === "0") return false;
|
|
488
|
+
return Boolean(this.value);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
class AstroCookies {
|
|
492
|
+
#request;
|
|
493
|
+
#requestValues;
|
|
494
|
+
#outgoing;
|
|
495
|
+
#consumed;
|
|
496
|
+
constructor(request) {
|
|
497
|
+
this.#request = request;
|
|
498
|
+
this.#requestValues = null;
|
|
499
|
+
this.#outgoing = null;
|
|
500
|
+
this.#consumed = false;
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Astro.cookies.delete(key) is used to delete a cookie. Using this method will result
|
|
504
|
+
* in a Set-Cookie header added to the response.
|
|
505
|
+
* @param key The cookie to delete
|
|
506
|
+
* @param options Options related to this deletion, such as the path of the cookie.
|
|
507
|
+
*/
|
|
508
|
+
delete(key, options) {
|
|
509
|
+
const {
|
|
510
|
+
// @ts-expect-error
|
|
511
|
+
maxAge: _ignoredMaxAge,
|
|
512
|
+
// @ts-expect-error
|
|
513
|
+
expires: _ignoredExpires,
|
|
514
|
+
...sanitizedOptions
|
|
515
|
+
} = options || {};
|
|
516
|
+
const serializeOptions = {
|
|
517
|
+
expires: DELETED_EXPIRATION,
|
|
518
|
+
...sanitizedOptions
|
|
519
|
+
};
|
|
520
|
+
this.#ensureOutgoingMap().set(key, [
|
|
521
|
+
DELETED_VALUE,
|
|
522
|
+
serialize(key, DELETED_VALUE, serializeOptions),
|
|
523
|
+
false
|
|
524
|
+
]);
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Astro.cookies.get(key) is used to get a cookie value. The cookie value is read from the
|
|
528
|
+
* request. If you have set a cookie via Astro.cookies.set(key, value), the value will be taken
|
|
529
|
+
* from that set call, overriding any values already part of the request.
|
|
530
|
+
* @param key The cookie to get.
|
|
531
|
+
* @returns An object containing the cookie value as well as convenience methods for converting its value.
|
|
532
|
+
*/
|
|
533
|
+
get(key, options = void 0) {
|
|
534
|
+
if (this.#outgoing?.has(key)) {
|
|
535
|
+
let [serializedValue, , isSetValue] = this.#outgoing.get(key);
|
|
536
|
+
if (isSetValue) {
|
|
537
|
+
return new AstroCookie(serializedValue);
|
|
538
|
+
} else {
|
|
539
|
+
return void 0;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
const values = this.#ensureParsed(options);
|
|
543
|
+
if (key in values) {
|
|
544
|
+
const value = values[key];
|
|
545
|
+
return new AstroCookie(value);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Astro.cookies.has(key) returns a boolean indicating whether this cookie is either
|
|
550
|
+
* part of the initial request or set via Astro.cookies.set(key)
|
|
551
|
+
* @param key The cookie to check for.
|
|
552
|
+
* @returns
|
|
553
|
+
*/
|
|
554
|
+
has(key, options = void 0) {
|
|
555
|
+
if (this.#outgoing?.has(key)) {
|
|
556
|
+
let [, , isSetValue] = this.#outgoing.get(key);
|
|
557
|
+
return isSetValue;
|
|
558
|
+
}
|
|
559
|
+
const values = this.#ensureParsed(options);
|
|
560
|
+
return !!values[key];
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Astro.cookies.set(key, value) is used to set a cookie's value. If provided
|
|
564
|
+
* an object it will be stringified via JSON.stringify(value). Additionally you
|
|
565
|
+
* can provide options customizing how this cookie will be set, such as setting httpOnly
|
|
566
|
+
* in order to prevent the cookie from being read in client-side JavaScript.
|
|
567
|
+
* @param key The name of the cookie to set.
|
|
568
|
+
* @param value A value, either a string or other primitive or an object.
|
|
569
|
+
* @param options Options for the cookie, such as the path and security settings.
|
|
570
|
+
*/
|
|
571
|
+
set(key, value, options) {
|
|
572
|
+
if (this.#consumed) {
|
|
573
|
+
const warning = new Error(
|
|
574
|
+
"Astro.cookies.set() was called after the cookies had already been sent to the browser.\nThis may have happened if this method was called in an imported component.\nPlease make sure that Astro.cookies.set() is only called in the frontmatter of the main page."
|
|
575
|
+
);
|
|
576
|
+
warning.name = "Warning";
|
|
577
|
+
console.warn(warning);
|
|
578
|
+
}
|
|
579
|
+
let serializedValue;
|
|
580
|
+
if (typeof value === "string") {
|
|
581
|
+
serializedValue = value;
|
|
582
|
+
} else {
|
|
583
|
+
let toStringValue = value.toString();
|
|
584
|
+
if (toStringValue === Object.prototype.toString.call(value)) {
|
|
585
|
+
serializedValue = JSON.stringify(value);
|
|
586
|
+
} else {
|
|
587
|
+
serializedValue = toStringValue;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
const serializeOptions = {};
|
|
591
|
+
if (options) {
|
|
592
|
+
Object.assign(serializeOptions, options);
|
|
593
|
+
}
|
|
594
|
+
this.#ensureOutgoingMap().set(key, [
|
|
595
|
+
serializedValue,
|
|
596
|
+
serialize(key, serializedValue, serializeOptions),
|
|
597
|
+
true
|
|
598
|
+
]);
|
|
599
|
+
if (this.#request[responseSentSymbol]) {
|
|
600
|
+
throw new AstroError({
|
|
601
|
+
...ResponseSentError
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Merges a new AstroCookies instance into the current instance. Any new cookies
|
|
607
|
+
* will be added to the current instance, overwriting any existing cookies with the same name.
|
|
608
|
+
*/
|
|
609
|
+
merge(cookies) {
|
|
610
|
+
const outgoing = cookies.#outgoing;
|
|
611
|
+
if (outgoing) {
|
|
612
|
+
for (const [key, value] of outgoing) {
|
|
613
|
+
this.#ensureOutgoingMap().set(key, value);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Astro.cookies.header() returns an iterator for the cookies that have previously
|
|
619
|
+
* been set by either Astro.cookies.set() or Astro.cookies.delete().
|
|
620
|
+
* This method is primarily used by adapters to set the header on outgoing responses.
|
|
621
|
+
* @returns
|
|
622
|
+
*/
|
|
623
|
+
*headers() {
|
|
624
|
+
if (this.#outgoing == null) return;
|
|
625
|
+
for (const [, value] of this.#outgoing) {
|
|
626
|
+
yield value[1];
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Behaves the same as AstroCookies.prototype.headers(),
|
|
631
|
+
* but allows a warning when cookies are set after the instance is consumed.
|
|
632
|
+
*/
|
|
633
|
+
static consume(cookies) {
|
|
634
|
+
cookies.#consumed = true;
|
|
635
|
+
return cookies.headers();
|
|
636
|
+
}
|
|
637
|
+
#ensureParsed(options = void 0) {
|
|
638
|
+
if (!this.#requestValues) {
|
|
639
|
+
this.#parse(options);
|
|
640
|
+
}
|
|
641
|
+
if (!this.#requestValues) {
|
|
642
|
+
this.#requestValues = {};
|
|
643
|
+
}
|
|
644
|
+
return this.#requestValues;
|
|
645
|
+
}
|
|
646
|
+
#ensureOutgoingMap() {
|
|
647
|
+
if (!this.#outgoing) {
|
|
648
|
+
this.#outgoing = /* @__PURE__ */ new Map();
|
|
649
|
+
}
|
|
650
|
+
return this.#outgoing;
|
|
651
|
+
}
|
|
652
|
+
#parse(options = void 0) {
|
|
653
|
+
const raw = this.#request.headers.get("cookie");
|
|
654
|
+
if (!raw) {
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
this.#requestValues = parse(raw, options);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
const astroCookiesSymbol = Symbol.for("astro.cookies");
|
|
662
|
+
function attachCookiesToResponse(response, cookies) {
|
|
663
|
+
Reflect.set(response, astroCookiesSymbol, cookies);
|
|
664
|
+
}
|
|
665
|
+
function getCookiesFromResponse(response) {
|
|
666
|
+
let cookies = Reflect.get(response, astroCookiesSymbol);
|
|
667
|
+
if (cookies != null) {
|
|
668
|
+
return cookies;
|
|
669
|
+
} else {
|
|
670
|
+
return void 0;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
function* getSetCookiesFromResponse(response) {
|
|
674
|
+
const cookies = getCookiesFromResponse(response);
|
|
675
|
+
if (!cookies) {
|
|
676
|
+
return [];
|
|
677
|
+
}
|
|
678
|
+
for (const headerValue of AstroCookies.consume(cookies)) {
|
|
679
|
+
yield headerValue;
|
|
680
|
+
}
|
|
681
|
+
return [];
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const dateTimeFormat = new Intl.DateTimeFormat([], {
|
|
685
|
+
hour: "2-digit",
|
|
686
|
+
minute: "2-digit",
|
|
687
|
+
second: "2-digit",
|
|
688
|
+
hour12: false
|
|
689
|
+
});
|
|
690
|
+
const levels = {
|
|
691
|
+
debug: 20,
|
|
692
|
+
info: 30,
|
|
693
|
+
warn: 40,
|
|
694
|
+
error: 50,
|
|
695
|
+
silent: 90
|
|
696
|
+
};
|
|
697
|
+
function log(opts, level, label, message, newLine = true) {
|
|
698
|
+
const logLevel = opts.level;
|
|
699
|
+
const dest = opts.dest;
|
|
700
|
+
const event = {
|
|
701
|
+
label,
|
|
702
|
+
level,
|
|
703
|
+
message,
|
|
704
|
+
newLine
|
|
705
|
+
};
|
|
706
|
+
if (!isLogLevelEnabled(logLevel, level)) {
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
dest.write(event);
|
|
710
|
+
}
|
|
711
|
+
function isLogLevelEnabled(configuredLogLevel, level) {
|
|
712
|
+
return levels[configuredLogLevel] <= levels[level];
|
|
713
|
+
}
|
|
714
|
+
function info(opts, label, message, newLine = true) {
|
|
715
|
+
return log(opts, "info", label, message, newLine);
|
|
716
|
+
}
|
|
717
|
+
function warn(opts, label, message, newLine = true) {
|
|
718
|
+
return log(opts, "warn", label, message, newLine);
|
|
719
|
+
}
|
|
720
|
+
function error(opts, label, message, newLine = true) {
|
|
721
|
+
return log(opts, "error", label, message, newLine);
|
|
722
|
+
}
|
|
723
|
+
function debug(...args) {
|
|
724
|
+
if ("_astroGlobalDebug" in globalThis) {
|
|
725
|
+
globalThis._astroGlobalDebug(...args);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
function getEventPrefix({ level, label }) {
|
|
729
|
+
const timestamp = `${dateTimeFormat.format(/* @__PURE__ */ new Date())}`;
|
|
730
|
+
const prefix = [];
|
|
731
|
+
if (level === "error" || level === "warn") {
|
|
732
|
+
prefix.push(bold(timestamp));
|
|
733
|
+
prefix.push(`[${level.toUpperCase()}]`);
|
|
734
|
+
} else {
|
|
735
|
+
prefix.push(timestamp);
|
|
736
|
+
}
|
|
737
|
+
if (label) {
|
|
738
|
+
prefix.push(`[${label}]`);
|
|
739
|
+
}
|
|
740
|
+
if (level === "error") {
|
|
741
|
+
return red(prefix.join(" "));
|
|
742
|
+
}
|
|
743
|
+
if (level === "warn") {
|
|
744
|
+
return yellow(prefix.join(" "));
|
|
745
|
+
}
|
|
746
|
+
if (prefix.length === 1) {
|
|
747
|
+
return dim(prefix[0]);
|
|
748
|
+
}
|
|
749
|
+
return dim(prefix[0]) + " " + blue(prefix.splice(1).join(" "));
|
|
750
|
+
}
|
|
751
|
+
class Logger {
|
|
752
|
+
options;
|
|
753
|
+
constructor(options) {
|
|
754
|
+
this.options = options;
|
|
755
|
+
}
|
|
756
|
+
info(label, message, newLine = true) {
|
|
757
|
+
info(this.options, label, message, newLine);
|
|
758
|
+
}
|
|
759
|
+
warn(label, message, newLine = true) {
|
|
760
|
+
warn(this.options, label, message, newLine);
|
|
761
|
+
}
|
|
762
|
+
error(label, message, newLine = true) {
|
|
763
|
+
error(this.options, label, message, newLine);
|
|
764
|
+
}
|
|
765
|
+
debug(label, ...messages) {
|
|
766
|
+
debug(label, ...messages);
|
|
767
|
+
}
|
|
768
|
+
level() {
|
|
769
|
+
return this.options.level;
|
|
770
|
+
}
|
|
771
|
+
forkIntegrationLogger(label) {
|
|
772
|
+
return new AstroIntegrationLogger(this.options, label);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
class AstroIntegrationLogger {
|
|
776
|
+
options;
|
|
777
|
+
label;
|
|
778
|
+
constructor(logging, label) {
|
|
779
|
+
this.options = logging;
|
|
780
|
+
this.label = label;
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Creates a new logger instance with a new label, but the same log options.
|
|
784
|
+
*/
|
|
785
|
+
fork(label) {
|
|
786
|
+
return new AstroIntegrationLogger(this.options, label);
|
|
787
|
+
}
|
|
788
|
+
info(message) {
|
|
789
|
+
info(this.options, this.label, message);
|
|
790
|
+
}
|
|
791
|
+
warn(message) {
|
|
792
|
+
warn(this.options, this.label, message);
|
|
793
|
+
}
|
|
794
|
+
error(message) {
|
|
795
|
+
error(this.options, this.label, message);
|
|
796
|
+
}
|
|
797
|
+
debug(message) {
|
|
798
|
+
debug(this.label, message);
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
const consoleLogDestination = {
|
|
803
|
+
write(event) {
|
|
804
|
+
let dest = console.error;
|
|
805
|
+
if (levels[event.level] < levels["error"]) {
|
|
806
|
+
dest = console.log;
|
|
807
|
+
}
|
|
808
|
+
if (event.label === "SKIP_FORMAT") {
|
|
809
|
+
dest(event.message);
|
|
810
|
+
} else {
|
|
811
|
+
dest(getEventPrefix(event) + " " + event.message);
|
|
812
|
+
}
|
|
813
|
+
return true;
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
|
|
817
|
+
const ACTION_API_CONTEXT_SYMBOL = Symbol.for("astro.actionAPIContext");
|
|
818
|
+
|
|
819
|
+
function hasActionPayload(locals) {
|
|
820
|
+
return "_actionPayload" in locals;
|
|
821
|
+
}
|
|
822
|
+
function createGetActionResult(locals) {
|
|
823
|
+
return (actionFn) => {
|
|
824
|
+
if (!hasActionPayload(locals) || actionFn.toString() !== getActionQueryString(locals._actionPayload.actionName)) {
|
|
825
|
+
return void 0;
|
|
826
|
+
}
|
|
827
|
+
return deserializeActionResult(locals._actionPayload.actionResult);
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
function createCallAction(context) {
|
|
831
|
+
return (baseAction, input) => {
|
|
832
|
+
Reflect.set(context, ACTION_API_CONTEXT_SYMBOL, true);
|
|
833
|
+
const action = baseAction.bind(context);
|
|
834
|
+
return action(input);
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function parseLocale(header) {
|
|
839
|
+
if (header === "*") {
|
|
840
|
+
return [{ locale: header, qualityValue: void 0 }];
|
|
841
|
+
}
|
|
842
|
+
const result = [];
|
|
843
|
+
const localeValues = header.split(",").map((str) => str.trim());
|
|
844
|
+
for (const localeValue of localeValues) {
|
|
845
|
+
const split = localeValue.split(";").map((str) => str.trim());
|
|
846
|
+
const localeName = split[0];
|
|
847
|
+
const qualityValue = split[1];
|
|
848
|
+
if (!split) {
|
|
849
|
+
continue;
|
|
850
|
+
}
|
|
851
|
+
if (qualityValue && qualityValue.startsWith("q=")) {
|
|
852
|
+
const qualityValueAsFloat = Number.parseFloat(qualityValue.slice("q=".length));
|
|
853
|
+
if (Number.isNaN(qualityValueAsFloat) || qualityValueAsFloat > 1) {
|
|
854
|
+
result.push({
|
|
855
|
+
locale: localeName,
|
|
856
|
+
qualityValue: void 0
|
|
857
|
+
});
|
|
858
|
+
} else {
|
|
859
|
+
result.push({
|
|
860
|
+
locale: localeName,
|
|
861
|
+
qualityValue: qualityValueAsFloat
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
} else {
|
|
865
|
+
result.push({
|
|
866
|
+
locale: localeName,
|
|
867
|
+
qualityValue: void 0
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
return result;
|
|
872
|
+
}
|
|
873
|
+
function sortAndFilterLocales(browserLocaleList, locales) {
|
|
874
|
+
const normalizedLocales = toCodes(locales).map(normalizeTheLocale);
|
|
875
|
+
return browserLocaleList.filter((browserLocale) => {
|
|
876
|
+
if (browserLocale.locale !== "*") {
|
|
877
|
+
return normalizedLocales.includes(normalizeTheLocale(browserLocale.locale));
|
|
878
|
+
}
|
|
879
|
+
return true;
|
|
880
|
+
}).sort((a, b) => {
|
|
881
|
+
if (a.qualityValue && b.qualityValue) {
|
|
882
|
+
return Math.sign(b.qualityValue - a.qualityValue);
|
|
883
|
+
}
|
|
884
|
+
return 0;
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
function computePreferredLocale(request, locales) {
|
|
888
|
+
const acceptHeader = request.headers.get("Accept-Language");
|
|
889
|
+
let result = void 0;
|
|
890
|
+
if (acceptHeader) {
|
|
891
|
+
const browserLocaleList = sortAndFilterLocales(parseLocale(acceptHeader), locales);
|
|
892
|
+
const firstResult = browserLocaleList.at(0);
|
|
893
|
+
if (firstResult && firstResult.locale !== "*") {
|
|
894
|
+
for (const currentLocale of locales) {
|
|
895
|
+
if (typeof currentLocale === "string") {
|
|
896
|
+
if (normalizeTheLocale(currentLocale) === normalizeTheLocale(firstResult.locale)) {
|
|
897
|
+
result = currentLocale;
|
|
898
|
+
}
|
|
899
|
+
} else {
|
|
900
|
+
for (const currentCode of currentLocale.codes) {
|
|
901
|
+
if (normalizeTheLocale(currentCode) === normalizeTheLocale(firstResult.locale)) {
|
|
902
|
+
result = currentLocale.path;
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
return result;
|
|
910
|
+
}
|
|
911
|
+
function computePreferredLocaleList(request, locales) {
|
|
912
|
+
const acceptHeader = request.headers.get("Accept-Language");
|
|
913
|
+
let result = [];
|
|
914
|
+
if (acceptHeader) {
|
|
915
|
+
const browserLocaleList = sortAndFilterLocales(parseLocale(acceptHeader), locales);
|
|
916
|
+
if (browserLocaleList.length === 1 && browserLocaleList.at(0).locale === "*") {
|
|
917
|
+
return locales.map((locale) => {
|
|
918
|
+
if (typeof locale === "string") {
|
|
919
|
+
return locale;
|
|
920
|
+
} else {
|
|
921
|
+
return locale.codes.at(0);
|
|
922
|
+
}
|
|
923
|
+
});
|
|
924
|
+
} else if (browserLocaleList.length > 0) {
|
|
925
|
+
for (const browserLocale of browserLocaleList) {
|
|
926
|
+
for (const loopLocale of locales) {
|
|
927
|
+
if (typeof loopLocale === "string") {
|
|
928
|
+
if (normalizeTheLocale(loopLocale) === normalizeTheLocale(browserLocale.locale)) {
|
|
929
|
+
result.push(loopLocale);
|
|
930
|
+
}
|
|
931
|
+
} else {
|
|
932
|
+
for (const code of loopLocale.codes) {
|
|
933
|
+
if (code === browserLocale.locale) {
|
|
934
|
+
result.push(loopLocale.path);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
return result;
|
|
943
|
+
}
|
|
944
|
+
function computeCurrentLocale(pathname, locales, defaultLocale) {
|
|
945
|
+
for (const segment of pathname.split("/")) {
|
|
946
|
+
for (const locale of locales) {
|
|
947
|
+
if (typeof locale === "string") {
|
|
948
|
+
if (!segment.includes(locale)) continue;
|
|
949
|
+
if (normalizeTheLocale(locale) === normalizeTheLocale(segment)) {
|
|
950
|
+
return locale;
|
|
951
|
+
}
|
|
952
|
+
} else {
|
|
953
|
+
if (locale.path === segment) {
|
|
954
|
+
return locale.codes.at(0);
|
|
955
|
+
} else {
|
|
956
|
+
for (const code of locale.codes) {
|
|
957
|
+
if (normalizeTheLocale(code) === normalizeTheLocale(segment)) {
|
|
958
|
+
return code;
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
for (const locale of locales) {
|
|
966
|
+
if (typeof locale === "string") {
|
|
967
|
+
if (locale === defaultLocale) {
|
|
968
|
+
return locale;
|
|
969
|
+
}
|
|
970
|
+
} else {
|
|
971
|
+
if (locale.path === defaultLocale) {
|
|
972
|
+
return locale.codes.at(0);
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
async function callMiddleware(onRequest, apiContext, responseFunction) {
|
|
979
|
+
let nextCalled = false;
|
|
980
|
+
let responseFunctionPromise = void 0;
|
|
981
|
+
const next = async (payload) => {
|
|
982
|
+
nextCalled = true;
|
|
983
|
+
responseFunctionPromise = responseFunction(apiContext, payload);
|
|
984
|
+
return responseFunctionPromise;
|
|
985
|
+
};
|
|
986
|
+
let middlewarePromise = onRequest(apiContext, next);
|
|
987
|
+
return await Promise.resolve(middlewarePromise).then(async (value) => {
|
|
988
|
+
if (nextCalled) {
|
|
989
|
+
if (typeof value !== "undefined") {
|
|
990
|
+
if (value instanceof Response === false) {
|
|
991
|
+
throw new AstroError(MiddlewareNotAResponse);
|
|
992
|
+
}
|
|
993
|
+
return value;
|
|
994
|
+
} else {
|
|
995
|
+
if (responseFunctionPromise) {
|
|
996
|
+
return responseFunctionPromise;
|
|
997
|
+
} else {
|
|
998
|
+
throw new AstroError(MiddlewareNotAResponse);
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
} else if (typeof value === "undefined") {
|
|
1002
|
+
throw new AstroError(MiddlewareNoDataOrNextCalled);
|
|
1003
|
+
} else if (value instanceof Response === false) {
|
|
1004
|
+
throw new AstroError(MiddlewareNotAResponse);
|
|
1005
|
+
} else {
|
|
1006
|
+
return value;
|
|
1007
|
+
}
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
function createRequest({
|
|
1012
|
+
url,
|
|
1013
|
+
headers,
|
|
1014
|
+
method = "GET",
|
|
1015
|
+
body = void 0,
|
|
1016
|
+
logger,
|
|
1017
|
+
isPrerendered = false,
|
|
1018
|
+
routePattern,
|
|
1019
|
+
init
|
|
1020
|
+
}) {
|
|
1021
|
+
const headersObj = isPrerendered ? void 0 : headers instanceof Headers ? headers : new Headers(
|
|
1022
|
+
// Filter out HTTP/2 pseudo-headers. These are internally-generated headers added to all HTTP/2 requests with trusted metadata about the request.
|
|
1023
|
+
// Examples include `:method`, `:scheme`, `:authority`, and `:path`.
|
|
1024
|
+
// They are always prefixed with a colon to distinguish them from other headers, and it is an error to add the to a Headers object manually.
|
|
1025
|
+
// See https://httpwg.org/specs/rfc7540.html#HttpRequest
|
|
1026
|
+
Object.entries(headers).filter(([name]) => !name.startsWith(":"))
|
|
1027
|
+
);
|
|
1028
|
+
if (typeof url === "string") url = new URL(url);
|
|
1029
|
+
if (isPrerendered) {
|
|
1030
|
+
url.search = "";
|
|
1031
|
+
}
|
|
1032
|
+
const request = new Request(url, {
|
|
1033
|
+
method,
|
|
1034
|
+
headers: headersObj,
|
|
1035
|
+
// body is made available only if the request is for a page that will be on-demand rendered
|
|
1036
|
+
body: isPrerendered ? null : body,
|
|
1037
|
+
...init
|
|
1038
|
+
});
|
|
1039
|
+
if (isPrerendered) {
|
|
1040
|
+
let _headers = request.headers;
|
|
1041
|
+
const { value, writable, ...headersDesc } = Object.getOwnPropertyDescriptor(request, "headers") || {};
|
|
1042
|
+
Object.defineProperty(request, "headers", {
|
|
1043
|
+
...headersDesc,
|
|
1044
|
+
get() {
|
|
1045
|
+
logger.warn(
|
|
1046
|
+
null,
|
|
1047
|
+
`\`Astro.request.headers\` was used when rendering the route \`${routePattern}'\`. \`Astro.request.headers\` is not available on prerendered pages. If you need access to request headers, make sure that the page is server-rendered using \`export const prerender = false;\` or by setting \`output\` to \`"server"\` in your Astro config to make all your pages server-rendered by default.`
|
|
1048
|
+
);
|
|
1049
|
+
return _headers;
|
|
1050
|
+
},
|
|
1051
|
+
set(newHeaders) {
|
|
1052
|
+
_headers = newHeaders;
|
|
1053
|
+
}
|
|
1054
|
+
});
|
|
1055
|
+
}
|
|
1056
|
+
return request;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
function findRouteToRewrite({
|
|
1060
|
+
payload,
|
|
1061
|
+
routes,
|
|
1062
|
+
request,
|
|
1063
|
+
trailingSlash,
|
|
1064
|
+
buildFormat,
|
|
1065
|
+
base
|
|
1066
|
+
}) {
|
|
1067
|
+
let newUrl = void 0;
|
|
1068
|
+
if (payload instanceof URL) {
|
|
1069
|
+
newUrl = payload;
|
|
1070
|
+
} else if (payload instanceof Request) {
|
|
1071
|
+
newUrl = new URL(payload.url);
|
|
1072
|
+
} else {
|
|
1073
|
+
newUrl = new URL(payload, new URL(request.url).origin);
|
|
1074
|
+
}
|
|
1075
|
+
let pathname = newUrl.pathname;
|
|
1076
|
+
const shouldAppendSlash = shouldAppendForwardSlash(trailingSlash, buildFormat);
|
|
1077
|
+
if (base !== "/" && newUrl.pathname.startsWith(base)) {
|
|
1078
|
+
pathname = shouldAppendSlash ? appendForwardSlash$1(newUrl.pathname) : removeTrailingForwardSlash(newUrl.pathname);
|
|
1079
|
+
pathname = pathname.slice(base.length);
|
|
1080
|
+
}
|
|
1081
|
+
if (!pathname.startsWith("/") && shouldAppendSlash && newUrl.pathname.endsWith("/")) {
|
|
1082
|
+
pathname = prependForwardSlash$1(pathname);
|
|
1083
|
+
}
|
|
1084
|
+
if (pathname === "/" && base !== "/" && !shouldAppendSlash) {
|
|
1085
|
+
pathname = "";
|
|
1086
|
+
}
|
|
1087
|
+
newUrl.pathname = joinPaths(...[base, pathname].filter(Boolean));
|
|
1088
|
+
const decodedPathname = decodeURI(pathname);
|
|
1089
|
+
let foundRoute;
|
|
1090
|
+
for (const route of routes) {
|
|
1091
|
+
if (route.pattern.test(decodedPathname)) {
|
|
1092
|
+
foundRoute = route;
|
|
1093
|
+
break;
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
if (foundRoute) {
|
|
1097
|
+
return {
|
|
1098
|
+
routeData: foundRoute,
|
|
1099
|
+
newUrl,
|
|
1100
|
+
pathname: decodedPathname
|
|
1101
|
+
};
|
|
1102
|
+
} else {
|
|
1103
|
+
const custom404 = routes.find((route) => route.route === "/404");
|
|
1104
|
+
if (custom404) {
|
|
1105
|
+
return { routeData: custom404, newUrl, pathname };
|
|
1106
|
+
} else {
|
|
1107
|
+
return { routeData: DEFAULT_404_ROUTE, newUrl, pathname };
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
function copyRequest(newUrl, oldRequest, isPrerendered, logger, routePattern) {
|
|
1112
|
+
if (oldRequest.bodyUsed) {
|
|
1113
|
+
throw new AstroError(RewriteWithBodyUsed);
|
|
1114
|
+
}
|
|
1115
|
+
return createRequest({
|
|
1116
|
+
url: newUrl,
|
|
1117
|
+
method: oldRequest.method,
|
|
1118
|
+
body: oldRequest.body,
|
|
1119
|
+
isPrerendered,
|
|
1120
|
+
logger,
|
|
1121
|
+
headers: isPrerendered ? {} : oldRequest.headers,
|
|
1122
|
+
routePattern,
|
|
1123
|
+
init: {
|
|
1124
|
+
referrer: oldRequest.referrer,
|
|
1125
|
+
referrerPolicy: oldRequest.referrerPolicy,
|
|
1126
|
+
mode: oldRequest.mode,
|
|
1127
|
+
credentials: oldRequest.credentials,
|
|
1128
|
+
cache: oldRequest.cache,
|
|
1129
|
+
redirect: oldRequest.redirect,
|
|
1130
|
+
integrity: oldRequest.integrity,
|
|
1131
|
+
signal: oldRequest.signal,
|
|
1132
|
+
keepalive: oldRequest.keepalive,
|
|
1133
|
+
// https://fetch.spec.whatwg.org/#dom-request-duplex
|
|
1134
|
+
// @ts-expect-error It isn't part of the types, but undici accepts it and it allows to carry over the body to a new request
|
|
1135
|
+
duplex: "half"
|
|
1136
|
+
}
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
1139
|
+
function setOriginPathname(request, pathname) {
|
|
1140
|
+
Reflect.set(request, originPathnameSymbol, encodeURIComponent(pathname));
|
|
1141
|
+
}
|
|
1142
|
+
function getOriginPathname(request) {
|
|
1143
|
+
const origin = Reflect.get(request, originPathnameSymbol);
|
|
1144
|
+
if (origin) {
|
|
1145
|
+
return decodeURIComponent(origin);
|
|
1146
|
+
}
|
|
1147
|
+
return new URL(request.url).pathname;
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
const FORM_CONTENT_TYPES = [
|
|
1151
|
+
"application/x-www-form-urlencoded",
|
|
1152
|
+
"multipart/form-data",
|
|
1153
|
+
"text/plain"
|
|
1154
|
+
];
|
|
1155
|
+
const SAFE_METHODS = ["GET", "HEAD", "OPTIONS"];
|
|
1156
|
+
function createOriginCheckMiddleware() {
|
|
1157
|
+
return defineMiddleware((context, next) => {
|
|
1158
|
+
const { request, url, isPrerendered } = context;
|
|
1159
|
+
if (isPrerendered) {
|
|
1160
|
+
return next();
|
|
1161
|
+
}
|
|
1162
|
+
if (SAFE_METHODS.includes(request.method)) {
|
|
1163
|
+
return next();
|
|
1164
|
+
}
|
|
1165
|
+
const isSameOrigin = request.headers.get("origin") === url.origin;
|
|
1166
|
+
const hasContentType = request.headers.has("content-type");
|
|
1167
|
+
if (hasContentType) {
|
|
1168
|
+
const formLikeHeader = hasFormLikeHeader(request.headers.get("content-type"));
|
|
1169
|
+
if (formLikeHeader && !isSameOrigin) {
|
|
1170
|
+
return new Response(`Cross-site ${request.method} form submissions are forbidden`, {
|
|
1171
|
+
status: 403
|
|
1172
|
+
});
|
|
1173
|
+
}
|
|
1174
|
+
} else {
|
|
1175
|
+
if (!isSameOrigin) {
|
|
1176
|
+
return new Response(`Cross-site ${request.method} form submissions are forbidden`, {
|
|
1177
|
+
status: 403
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
return next();
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
function hasFormLikeHeader(contentType) {
|
|
1185
|
+
if (contentType) {
|
|
1186
|
+
for (const FORM_CONTENT_TYPE of FORM_CONTENT_TYPES) {
|
|
1187
|
+
if (contentType.toLowerCase().includes(FORM_CONTENT_TYPE)) {
|
|
1188
|
+
return true;
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
return false;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
const VALID_PARAM_TYPES = ["string", "number", "undefined"];
|
|
1196
|
+
function validateGetStaticPathsParameter([key, value], route) {
|
|
1197
|
+
if (!VALID_PARAM_TYPES.includes(typeof value)) {
|
|
1198
|
+
throw new AstroError({
|
|
1199
|
+
...GetStaticPathsInvalidRouteParam,
|
|
1200
|
+
message: GetStaticPathsInvalidRouteParam.message(key, value, typeof value),
|
|
1201
|
+
location: {
|
|
1202
|
+
file: route
|
|
1203
|
+
}
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
function validateDynamicRouteModule(mod, {
|
|
1208
|
+
ssr,
|
|
1209
|
+
route
|
|
1210
|
+
}) {
|
|
1211
|
+
if ((!ssr || route.prerender) && !mod.getStaticPaths) {
|
|
1212
|
+
throw new AstroError({
|
|
1213
|
+
...GetStaticPathsRequired,
|
|
1214
|
+
location: { file: route.component }
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
function validateGetStaticPathsResult(result, logger, route) {
|
|
1219
|
+
if (!Array.isArray(result)) {
|
|
1220
|
+
throw new AstroError({
|
|
1221
|
+
...InvalidGetStaticPathsReturn,
|
|
1222
|
+
message: InvalidGetStaticPathsReturn.message(typeof result),
|
|
1223
|
+
location: {
|
|
1224
|
+
file: route.component
|
|
1225
|
+
}
|
|
1226
|
+
});
|
|
1227
|
+
}
|
|
1228
|
+
result.forEach((pathObject) => {
|
|
1229
|
+
if (typeof pathObject === "object" && Array.isArray(pathObject) || pathObject === null) {
|
|
1230
|
+
throw new AstroError({
|
|
1231
|
+
...InvalidGetStaticPathsEntry,
|
|
1232
|
+
message: InvalidGetStaticPathsEntry.message(
|
|
1233
|
+
Array.isArray(pathObject) ? "array" : typeof pathObject
|
|
1234
|
+
)
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
if (pathObject.params === void 0 || pathObject.params === null || pathObject.params && Object.keys(pathObject.params).length === 0) {
|
|
1238
|
+
throw new AstroError({
|
|
1239
|
+
...GetStaticPathsExpectedParams,
|
|
1240
|
+
location: {
|
|
1241
|
+
file: route.component
|
|
1242
|
+
}
|
|
1243
|
+
});
|
|
1244
|
+
}
|
|
1245
|
+
for (const [key, val] of Object.entries(pathObject.params)) {
|
|
1246
|
+
if (!(typeof val === "undefined" || typeof val === "string" || typeof val === "number")) {
|
|
1247
|
+
logger.warn(
|
|
1248
|
+
"router",
|
|
1249
|
+
`getStaticPaths() returned an invalid path param: "${key}". A string, number or undefined value was expected, but got \`${JSON.stringify(
|
|
1250
|
+
val
|
|
1251
|
+
)}\`.`
|
|
1252
|
+
);
|
|
1253
|
+
}
|
|
1254
|
+
if (typeof val === "string" && val === "") {
|
|
1255
|
+
logger.warn(
|
|
1256
|
+
"router",
|
|
1257
|
+
`getStaticPaths() returned an invalid path param: "${key}". \`undefined\` expected for an optional param, but got empty string.`
|
|
1258
|
+
);
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
function stringifyParams(params, route) {
|
|
1265
|
+
const validatedParams = Object.entries(params).reduce((acc, next) => {
|
|
1266
|
+
validateGetStaticPathsParameter(next, route.component);
|
|
1267
|
+
const [key, value] = next;
|
|
1268
|
+
if (value !== void 0) {
|
|
1269
|
+
acc[key] = typeof value === "string" ? trimSlashes(value) : value.toString();
|
|
1270
|
+
}
|
|
1271
|
+
return acc;
|
|
1272
|
+
}, {});
|
|
1273
|
+
return route.generate(validatedParams);
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
function generatePaginateFunction(routeMatch, base) {
|
|
1277
|
+
return function paginateUtility(data, args = {}) {
|
|
1278
|
+
let { pageSize: _pageSize, params: _params, props: _props } = args;
|
|
1279
|
+
const pageSize = _pageSize || 10;
|
|
1280
|
+
const paramName = "page";
|
|
1281
|
+
const additionalParams = _params || {};
|
|
1282
|
+
const additionalProps = _props || {};
|
|
1283
|
+
let includesFirstPageNumber;
|
|
1284
|
+
if (routeMatch.params.includes(`...${paramName}`)) {
|
|
1285
|
+
includesFirstPageNumber = false;
|
|
1286
|
+
} else if (routeMatch.params.includes(`${paramName}`)) {
|
|
1287
|
+
includesFirstPageNumber = true;
|
|
1288
|
+
} else {
|
|
1289
|
+
throw new AstroError({
|
|
1290
|
+
...PageNumberParamNotFound,
|
|
1291
|
+
message: PageNumberParamNotFound.message(paramName)
|
|
1292
|
+
});
|
|
1293
|
+
}
|
|
1294
|
+
const lastPage = Math.max(1, Math.ceil(data.length / pageSize));
|
|
1295
|
+
const result = [...Array(lastPage).keys()].map((num) => {
|
|
1296
|
+
const pageNum = num + 1;
|
|
1297
|
+
const start = pageSize === Infinity ? 0 : (pageNum - 1) * pageSize;
|
|
1298
|
+
const end = Math.min(start + pageSize, data.length);
|
|
1299
|
+
const params = {
|
|
1300
|
+
...additionalParams,
|
|
1301
|
+
[paramName]: includesFirstPageNumber || pageNum > 1 ? String(pageNum) : void 0
|
|
1302
|
+
};
|
|
1303
|
+
const current = addRouteBase(routeMatch.generate({ ...params }), base);
|
|
1304
|
+
const next = pageNum === lastPage ? void 0 : addRouteBase(routeMatch.generate({ ...params, page: String(pageNum + 1) }), base);
|
|
1305
|
+
const prev = pageNum === 1 ? void 0 : addRouteBase(
|
|
1306
|
+
routeMatch.generate({
|
|
1307
|
+
...params,
|
|
1308
|
+
page: !includesFirstPageNumber && pageNum - 1 === 1 ? void 0 : String(pageNum - 1)
|
|
1309
|
+
}),
|
|
1310
|
+
base
|
|
1311
|
+
);
|
|
1312
|
+
const first = pageNum === 1 ? void 0 : addRouteBase(
|
|
1313
|
+
routeMatch.generate({
|
|
1314
|
+
...params,
|
|
1315
|
+
page: includesFirstPageNumber ? "1" : void 0
|
|
1316
|
+
}),
|
|
1317
|
+
base
|
|
1318
|
+
);
|
|
1319
|
+
const last = pageNum === lastPage ? void 0 : addRouteBase(routeMatch.generate({ ...params, page: String(lastPage) }), base);
|
|
1320
|
+
return {
|
|
1321
|
+
params,
|
|
1322
|
+
props: {
|
|
1323
|
+
...additionalProps,
|
|
1324
|
+
page: {
|
|
1325
|
+
data: data.slice(start, end),
|
|
1326
|
+
start,
|
|
1327
|
+
end: end - 1,
|
|
1328
|
+
size: pageSize,
|
|
1329
|
+
total: data.length,
|
|
1330
|
+
currentPage: pageNum,
|
|
1331
|
+
lastPage,
|
|
1332
|
+
url: { current, next, prev, first, last }
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
};
|
|
1336
|
+
});
|
|
1337
|
+
return result;
|
|
1338
|
+
};
|
|
1339
|
+
}
|
|
1340
|
+
function addRouteBase(route, base) {
|
|
1341
|
+
let routeWithBase = joinPaths(base, route);
|
|
1342
|
+
if (routeWithBase === "") routeWithBase = "/";
|
|
1343
|
+
return routeWithBase;
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
async function callGetStaticPaths({
|
|
1347
|
+
mod,
|
|
1348
|
+
route,
|
|
1349
|
+
routeCache,
|
|
1350
|
+
logger,
|
|
1351
|
+
ssr,
|
|
1352
|
+
base
|
|
1353
|
+
}) {
|
|
1354
|
+
const cached = routeCache.get(route);
|
|
1355
|
+
if (!mod) {
|
|
1356
|
+
throw new Error("This is an error caused by Astro and not your code. Please file an issue.");
|
|
1357
|
+
}
|
|
1358
|
+
if (cached?.staticPaths) {
|
|
1359
|
+
return cached.staticPaths;
|
|
1360
|
+
}
|
|
1361
|
+
validateDynamicRouteModule(mod, { ssr, route });
|
|
1362
|
+
if (ssr && !route.prerender) {
|
|
1363
|
+
const entry = Object.assign([], { keyed: /* @__PURE__ */ new Map() });
|
|
1364
|
+
routeCache.set(route, { ...cached, staticPaths: entry });
|
|
1365
|
+
return entry;
|
|
1366
|
+
}
|
|
1367
|
+
let staticPaths = [];
|
|
1368
|
+
if (!mod.getStaticPaths) {
|
|
1369
|
+
throw new Error("Unexpected Error.");
|
|
1370
|
+
}
|
|
1371
|
+
staticPaths = await mod.getStaticPaths({
|
|
1372
|
+
// Q: Why the cast?
|
|
1373
|
+
// A: So users downstream can have nicer typings, we have to make some sacrifice in our internal typings, which necessitate a cast here
|
|
1374
|
+
paginate: generatePaginateFunction(route, base)
|
|
1375
|
+
});
|
|
1376
|
+
validateGetStaticPathsResult(staticPaths, logger, route);
|
|
1377
|
+
const keyedStaticPaths = staticPaths;
|
|
1378
|
+
keyedStaticPaths.keyed = /* @__PURE__ */ new Map();
|
|
1379
|
+
for (const sp of keyedStaticPaths) {
|
|
1380
|
+
const paramsKey = stringifyParams(sp.params, route);
|
|
1381
|
+
keyedStaticPaths.keyed.set(paramsKey, sp);
|
|
1382
|
+
}
|
|
1383
|
+
routeCache.set(route, { ...cached, staticPaths: keyedStaticPaths });
|
|
1384
|
+
return keyedStaticPaths;
|
|
1385
|
+
}
|
|
1386
|
+
class RouteCache {
|
|
1387
|
+
logger;
|
|
1388
|
+
cache = {};
|
|
1389
|
+
runtimeMode;
|
|
1390
|
+
constructor(logger, runtimeMode = "production") {
|
|
1391
|
+
this.logger = logger;
|
|
1392
|
+
this.runtimeMode = runtimeMode;
|
|
1393
|
+
}
|
|
1394
|
+
/** Clear the cache. */
|
|
1395
|
+
clearAll() {
|
|
1396
|
+
this.cache = {};
|
|
1397
|
+
}
|
|
1398
|
+
set(route, entry) {
|
|
1399
|
+
const key = this.key(route);
|
|
1400
|
+
if (this.runtimeMode === "production" && this.cache[key]?.staticPaths) {
|
|
1401
|
+
this.logger.warn(null, `Internal Warning: route cache overwritten. (${key})`);
|
|
1402
|
+
}
|
|
1403
|
+
this.cache[key] = entry;
|
|
1404
|
+
}
|
|
1405
|
+
get(route) {
|
|
1406
|
+
return this.cache[this.key(route)];
|
|
1407
|
+
}
|
|
1408
|
+
key(route) {
|
|
1409
|
+
return `${route.route}_${route.component}`;
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
function findPathItemByKey(staticPaths, params, route, logger) {
|
|
1413
|
+
const paramsKey = stringifyParams(params, route);
|
|
1414
|
+
const matchedStaticPath = staticPaths.keyed.get(paramsKey);
|
|
1415
|
+
if (matchedStaticPath) {
|
|
1416
|
+
return matchedStaticPath;
|
|
1417
|
+
}
|
|
1418
|
+
logger.debug("router", `findPathItemByKey() - Unexpected cache miss looking for ${paramsKey}`);
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
function createDefaultRoutes(manifest) {
|
|
1422
|
+
const root = new URL(manifest.hrefRoot);
|
|
1423
|
+
return [
|
|
1424
|
+
{
|
|
1425
|
+
instance: default404Instance,
|
|
1426
|
+
matchesComponent: (filePath) => filePath.href === new URL(DEFAULT_404_COMPONENT, root).href,
|
|
1427
|
+
route: DEFAULT_404_ROUTE.route,
|
|
1428
|
+
component: DEFAULT_404_COMPONENT
|
|
1429
|
+
},
|
|
1430
|
+
{
|
|
1431
|
+
instance: createEndpoint(manifest),
|
|
1432
|
+
matchesComponent: (filePath) => filePath.href === new URL(SERVER_ISLAND_COMPONENT, root).href,
|
|
1433
|
+
route: SERVER_ISLAND_ROUTE,
|
|
1434
|
+
component: SERVER_ISLAND_COMPONENT
|
|
1435
|
+
}
|
|
1436
|
+
];
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
class Pipeline {
|
|
1440
|
+
constructor(logger, manifest, runtimeMode, renderers, resolve, serverLike, streaming, adapterName = manifest.adapterName, clientDirectives = manifest.clientDirectives, inlinedScripts = manifest.inlinedScripts, compressHTML = manifest.compressHTML, i18n = manifest.i18n, middleware = manifest.middleware, routeCache = new RouteCache(logger, runtimeMode), site = manifest.site ? new URL(manifest.site) : void 0, defaultRoutes = createDefaultRoutes(manifest)) {
|
|
1441
|
+
this.logger = logger;
|
|
1442
|
+
this.manifest = manifest;
|
|
1443
|
+
this.runtimeMode = runtimeMode;
|
|
1444
|
+
this.renderers = renderers;
|
|
1445
|
+
this.resolve = resolve;
|
|
1446
|
+
this.serverLike = serverLike;
|
|
1447
|
+
this.streaming = streaming;
|
|
1448
|
+
this.adapterName = adapterName;
|
|
1449
|
+
this.clientDirectives = clientDirectives;
|
|
1450
|
+
this.inlinedScripts = inlinedScripts;
|
|
1451
|
+
this.compressHTML = compressHTML;
|
|
1452
|
+
this.i18n = i18n;
|
|
1453
|
+
this.middleware = middleware;
|
|
1454
|
+
this.routeCache = routeCache;
|
|
1455
|
+
this.site = site;
|
|
1456
|
+
this.defaultRoutes = defaultRoutes;
|
|
1457
|
+
this.internalMiddleware = [];
|
|
1458
|
+
if (i18n?.strategy !== "manual") {
|
|
1459
|
+
this.internalMiddleware.push(
|
|
1460
|
+
createI18nMiddleware(i18n, manifest.base, manifest.trailingSlash, manifest.buildFormat)
|
|
1461
|
+
);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
internalMiddleware;
|
|
1465
|
+
resolvedMiddleware = void 0;
|
|
1466
|
+
/**
|
|
1467
|
+
* Resolves the middleware from the manifest, and returns the `onRequest` function. If `onRequest` isn't there,
|
|
1468
|
+
* it returns a no-op function
|
|
1469
|
+
*/
|
|
1470
|
+
async getMiddleware() {
|
|
1471
|
+
if (this.resolvedMiddleware) {
|
|
1472
|
+
return this.resolvedMiddleware;
|
|
1473
|
+
} else if (this.middleware) {
|
|
1474
|
+
const middlewareInstance = await this.middleware();
|
|
1475
|
+
const onRequest = middlewareInstance.onRequest ?? NOOP_MIDDLEWARE_FN;
|
|
1476
|
+
if (this.manifest.checkOrigin) {
|
|
1477
|
+
this.resolvedMiddleware = sequence(createOriginCheckMiddleware(), onRequest);
|
|
1478
|
+
} else {
|
|
1479
|
+
this.resolvedMiddleware = onRequest;
|
|
1480
|
+
}
|
|
1481
|
+
return this.resolvedMiddleware;
|
|
1482
|
+
} else {
|
|
1483
|
+
this.resolvedMiddleware = NOOP_MIDDLEWARE_FN;
|
|
1484
|
+
return this.resolvedMiddleware;
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
function routeIsRedirect(route) {
|
|
1490
|
+
return route?.type === "redirect";
|
|
1491
|
+
}
|
|
1492
|
+
function routeIsFallback(route) {
|
|
1493
|
+
return route?.type === "fallback";
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
const RedirectComponentInstance = {
|
|
1497
|
+
default() {
|
|
1498
|
+
return new Response(null, {
|
|
1499
|
+
status: 301
|
|
1500
|
+
});
|
|
1501
|
+
}
|
|
1502
|
+
};
|
|
1503
|
+
const RedirectSinglePageBuiltModule = {
|
|
1504
|
+
page: () => Promise.resolve(RedirectComponentInstance),
|
|
1505
|
+
onRequest: (_, next) => next(),
|
|
1506
|
+
renderers: []
|
|
1507
|
+
};
|
|
1508
|
+
|
|
1509
|
+
async function getProps(opts) {
|
|
1510
|
+
const { logger, mod, routeData: route, routeCache, pathname, serverLike, base } = opts;
|
|
1511
|
+
if (!route || route.pathname) {
|
|
1512
|
+
return {};
|
|
1513
|
+
}
|
|
1514
|
+
if (routeIsRedirect(route) || routeIsFallback(route) || route.component === DEFAULT_404_COMPONENT) {
|
|
1515
|
+
return {};
|
|
1516
|
+
}
|
|
1517
|
+
const staticPaths = await callGetStaticPaths({
|
|
1518
|
+
mod,
|
|
1519
|
+
route,
|
|
1520
|
+
routeCache,
|
|
1521
|
+
logger,
|
|
1522
|
+
ssr: serverLike,
|
|
1523
|
+
base
|
|
1524
|
+
});
|
|
1525
|
+
const params = getParams(route, pathname);
|
|
1526
|
+
const matchedStaticPath = findPathItemByKey(staticPaths, params, route, logger);
|
|
1527
|
+
if (!matchedStaticPath && (serverLike ? route.prerender : true)) {
|
|
1528
|
+
throw new AstroError({
|
|
1529
|
+
...NoMatchingStaticPathFound,
|
|
1530
|
+
message: NoMatchingStaticPathFound.message(pathname),
|
|
1531
|
+
hint: NoMatchingStaticPathFound.hint([route.component])
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
if (mod) {
|
|
1535
|
+
validatePrerenderEndpointCollision(route, mod, params);
|
|
1536
|
+
}
|
|
1537
|
+
const props = matchedStaticPath?.props ? { ...matchedStaticPath.props } : {};
|
|
1538
|
+
return props;
|
|
1539
|
+
}
|
|
1540
|
+
function getParams(route, pathname) {
|
|
1541
|
+
if (!route.params.length) return {};
|
|
1542
|
+
const paramsMatch = route.pattern.exec(pathname) || route.fallbackRoutes.map((fallbackRoute) => fallbackRoute.pattern.exec(pathname)).find((x) => x);
|
|
1543
|
+
if (!paramsMatch) return {};
|
|
1544
|
+
const params = {};
|
|
1545
|
+
route.params.forEach((key, i) => {
|
|
1546
|
+
if (key.startsWith("...")) {
|
|
1547
|
+
params[key.slice(3)] = paramsMatch[i + 1] ? paramsMatch[i + 1] : void 0;
|
|
1548
|
+
} else {
|
|
1549
|
+
params[key] = paramsMatch[i + 1];
|
|
1550
|
+
}
|
|
1551
|
+
});
|
|
1552
|
+
return params;
|
|
1553
|
+
}
|
|
1554
|
+
function validatePrerenderEndpointCollision(route, mod, params) {
|
|
1555
|
+
if (route.type === "endpoint" && mod.getStaticPaths) {
|
|
1556
|
+
const lastSegment = route.segments[route.segments.length - 1];
|
|
1557
|
+
const paramValues = Object.values(params);
|
|
1558
|
+
const lastParam = paramValues[paramValues.length - 1];
|
|
1559
|
+
if (lastSegment.length === 1 && lastSegment[0].dynamic && lastParam === void 0) {
|
|
1560
|
+
throw new AstroError({
|
|
1561
|
+
...PrerenderDynamicEndpointPathCollide,
|
|
1562
|
+
message: PrerenderDynamicEndpointPathCollide.message(route.route),
|
|
1563
|
+
hint: PrerenderDynamicEndpointPathCollide.hint(route.component),
|
|
1564
|
+
location: {
|
|
1565
|
+
file: route.component
|
|
1566
|
+
}
|
|
1567
|
+
});
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
function getFunctionExpression(slot) {
|
|
1573
|
+
if (!slot) return;
|
|
1574
|
+
const expressions = slot?.expressions?.filter((e) => isRenderInstruction(e) === false);
|
|
1575
|
+
if (expressions?.length !== 1) return;
|
|
1576
|
+
return expressions[0];
|
|
1577
|
+
}
|
|
1578
|
+
class Slots {
|
|
1579
|
+
#result;
|
|
1580
|
+
#slots;
|
|
1581
|
+
#logger;
|
|
1582
|
+
constructor(result, slots, logger) {
|
|
1583
|
+
this.#result = result;
|
|
1584
|
+
this.#slots = slots;
|
|
1585
|
+
this.#logger = logger;
|
|
1586
|
+
if (slots) {
|
|
1587
|
+
for (const key of Object.keys(slots)) {
|
|
1588
|
+
if (this[key] !== void 0) {
|
|
1589
|
+
throw new AstroError({
|
|
1590
|
+
...ReservedSlotName,
|
|
1591
|
+
message: ReservedSlotName.message(key)
|
|
1592
|
+
});
|
|
1593
|
+
}
|
|
1594
|
+
Object.defineProperty(this, key, {
|
|
1595
|
+
get() {
|
|
1596
|
+
return true;
|
|
1597
|
+
},
|
|
1598
|
+
enumerable: true
|
|
1599
|
+
});
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
has(name) {
|
|
1604
|
+
if (!this.#slots) return false;
|
|
1605
|
+
return Boolean(this.#slots[name]);
|
|
1606
|
+
}
|
|
1607
|
+
async render(name, args = []) {
|
|
1608
|
+
if (!this.#slots || !this.has(name)) return;
|
|
1609
|
+
const result = this.#result;
|
|
1610
|
+
if (!Array.isArray(args)) {
|
|
1611
|
+
this.#logger.warn(
|
|
1612
|
+
null,
|
|
1613
|
+
`Expected second parameter to be an array, received a ${typeof args}. If you're trying to pass an array as a single argument and getting unexpected results, make sure you're passing your array as a item of an array. Ex: Astro.slots.render('default', [["Hello", "World"]])`
|
|
1614
|
+
);
|
|
1615
|
+
} else if (args.length > 0) {
|
|
1616
|
+
const slotValue = this.#slots[name];
|
|
1617
|
+
const component = typeof slotValue === "function" ? await slotValue(result) : await slotValue;
|
|
1618
|
+
const expression = getFunctionExpression(component);
|
|
1619
|
+
if (expression) {
|
|
1620
|
+
const slot = async () => typeof expression === "function" ? expression(...args) : expression;
|
|
1621
|
+
return await renderSlotToString(result, slot).then((res) => {
|
|
1622
|
+
return res;
|
|
1623
|
+
});
|
|
1624
|
+
}
|
|
1625
|
+
if (typeof component === "function") {
|
|
1626
|
+
return await renderJSX(result, component(...args)).then(
|
|
1627
|
+
(res) => res != null ? String(res) : res
|
|
1628
|
+
);
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
const content = await renderSlotToString(result, this.#slots[name]);
|
|
1632
|
+
const outHTML = chunkToString(result, content);
|
|
1633
|
+
return outHTML;
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
function sequence(...handlers) {
|
|
1638
|
+
const filtered = handlers.filter((h) => !!h);
|
|
1639
|
+
const length = filtered.length;
|
|
1640
|
+
if (!length) {
|
|
1641
|
+
return defineMiddleware((_context, next) => {
|
|
1642
|
+
return next();
|
|
1643
|
+
});
|
|
1644
|
+
}
|
|
1645
|
+
return defineMiddleware((context, next) => {
|
|
1646
|
+
let carriedPayload = void 0;
|
|
1647
|
+
return applyHandle(0, context);
|
|
1648
|
+
function applyHandle(i, handleContext) {
|
|
1649
|
+
const handle = filtered[i];
|
|
1650
|
+
const result = handle(handleContext, async (payload) => {
|
|
1651
|
+
if (i < length - 1) {
|
|
1652
|
+
if (payload) {
|
|
1653
|
+
let newRequest;
|
|
1654
|
+
if (payload instanceof Request) {
|
|
1655
|
+
newRequest = payload;
|
|
1656
|
+
} else if (payload instanceof URL) {
|
|
1657
|
+
newRequest = new Request(payload, handleContext.request);
|
|
1658
|
+
} else {
|
|
1659
|
+
newRequest = new Request(
|
|
1660
|
+
new URL(payload, handleContext.url.origin),
|
|
1661
|
+
handleContext.request
|
|
1662
|
+
);
|
|
1663
|
+
}
|
|
1664
|
+
const pipeline = Reflect.get(handleContext, apiContextRoutesSymbol);
|
|
1665
|
+
const { routeData, pathname } = await pipeline.tryRewrite(
|
|
1666
|
+
payload,
|
|
1667
|
+
handleContext.request
|
|
1668
|
+
);
|
|
1669
|
+
if (pipeline.serverLike === true && handleContext.isPrerendered === false && routeData.prerender === true) {
|
|
1670
|
+
throw new AstroError({
|
|
1671
|
+
...ForbiddenRewrite,
|
|
1672
|
+
message: ForbiddenRewrite.message(
|
|
1673
|
+
handleContext.url.pathname,
|
|
1674
|
+
pathname,
|
|
1675
|
+
routeData.component
|
|
1676
|
+
),
|
|
1677
|
+
hint: ForbiddenRewrite.hint(routeData.component)
|
|
1678
|
+
});
|
|
1679
|
+
}
|
|
1680
|
+
carriedPayload = payload;
|
|
1681
|
+
handleContext.request = newRequest;
|
|
1682
|
+
handleContext.url = new URL(newRequest.url);
|
|
1683
|
+
handleContext.cookies = new AstroCookies(newRequest);
|
|
1684
|
+
handleContext.params = getParams(routeData, pathname);
|
|
1685
|
+
}
|
|
1686
|
+
return applyHandle(i + 1, handleContext);
|
|
1687
|
+
} else {
|
|
1688
|
+
return next(payload ?? carriedPayload);
|
|
1689
|
+
}
|
|
1690
|
+
});
|
|
1691
|
+
return result;
|
|
1692
|
+
}
|
|
1693
|
+
});
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
function defineMiddleware(fn) {
|
|
1697
|
+
return fn;
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
const PERSIST_SYMBOL = Symbol();
|
|
1701
|
+
const DEFAULT_COOKIE_NAME = "astro-session";
|
|
1702
|
+
const VALID_COOKIE_REGEX = /^[\w-]+$/;
|
|
1703
|
+
const unflatten = (parsed, _) => {
|
|
1704
|
+
return unflatten$1(parsed, {
|
|
1705
|
+
URL: (href) => new URL(href)
|
|
1706
|
+
});
|
|
1707
|
+
};
|
|
1708
|
+
const stringify = (data, _) => {
|
|
1709
|
+
return stringify$1(data, {
|
|
1710
|
+
// Support URL objects
|
|
1711
|
+
URL: (val) => val instanceof URL && val.href
|
|
1712
|
+
});
|
|
1713
|
+
};
|
|
1714
|
+
class AstroSession {
|
|
1715
|
+
// The cookies object.
|
|
1716
|
+
#cookies;
|
|
1717
|
+
// The session configuration.
|
|
1718
|
+
#config;
|
|
1719
|
+
// The cookie config
|
|
1720
|
+
#cookieConfig;
|
|
1721
|
+
// The cookie name
|
|
1722
|
+
#cookieName;
|
|
1723
|
+
// The unstorage object for the session driver.
|
|
1724
|
+
#storage;
|
|
1725
|
+
#data;
|
|
1726
|
+
// The session ID. A v4 UUID.
|
|
1727
|
+
#sessionID;
|
|
1728
|
+
// Sessions to destroy. Needed because we won't have the old session ID after it's destroyed locally.
|
|
1729
|
+
#toDestroy = /* @__PURE__ */ new Set();
|
|
1730
|
+
// Session keys to delete. Used for partial data sets to avoid overwriting the deleted value.
|
|
1731
|
+
#toDelete = /* @__PURE__ */ new Set();
|
|
1732
|
+
// Whether the session is dirty and needs to be saved.
|
|
1733
|
+
#dirty = false;
|
|
1734
|
+
// Whether the session cookie has been set.
|
|
1735
|
+
#cookieSet = false;
|
|
1736
|
+
// The local data is "partial" if it has not been loaded from storage yet and only
|
|
1737
|
+
// contains values that have been set or deleted in-memory locally.
|
|
1738
|
+
// We do this to avoid the need to block on loading data when it is only being set.
|
|
1739
|
+
// When we load the data from storage, we need to merge it with the local partial data,
|
|
1740
|
+
// preserving in-memory changes and deletions.
|
|
1741
|
+
#partial = true;
|
|
1742
|
+
constructor(cookies, {
|
|
1743
|
+
cookie: cookieConfig = DEFAULT_COOKIE_NAME,
|
|
1744
|
+
...config
|
|
1745
|
+
}) {
|
|
1746
|
+
this.#cookies = cookies;
|
|
1747
|
+
let cookieConfigObject;
|
|
1748
|
+
if (typeof cookieConfig === "object") {
|
|
1749
|
+
const { name = DEFAULT_COOKIE_NAME, ...rest } = cookieConfig;
|
|
1750
|
+
this.#cookieName = name;
|
|
1751
|
+
cookieConfigObject = rest;
|
|
1752
|
+
} else {
|
|
1753
|
+
this.#cookieName = cookieConfig || DEFAULT_COOKIE_NAME;
|
|
1754
|
+
}
|
|
1755
|
+
this.#cookieConfig = {
|
|
1756
|
+
sameSite: "lax",
|
|
1757
|
+
secure: true,
|
|
1758
|
+
path: "/",
|
|
1759
|
+
...cookieConfigObject,
|
|
1760
|
+
httpOnly: true
|
|
1761
|
+
};
|
|
1762
|
+
this.#config = config;
|
|
1763
|
+
}
|
|
1764
|
+
/**
|
|
1765
|
+
* Gets a session value. Returns `undefined` if the session or value does not exist.
|
|
1766
|
+
*/
|
|
1767
|
+
async get(key) {
|
|
1768
|
+
return (await this.#ensureData()).get(key)?.data;
|
|
1769
|
+
}
|
|
1770
|
+
/**
|
|
1771
|
+
* Checks if a session value exists.
|
|
1772
|
+
*/
|
|
1773
|
+
async has(key) {
|
|
1774
|
+
return (await this.#ensureData()).has(key);
|
|
1775
|
+
}
|
|
1776
|
+
/**
|
|
1777
|
+
* Gets all session values.
|
|
1778
|
+
*/
|
|
1779
|
+
async keys() {
|
|
1780
|
+
return (await this.#ensureData()).keys();
|
|
1781
|
+
}
|
|
1782
|
+
/**
|
|
1783
|
+
* Gets all session values.
|
|
1784
|
+
*/
|
|
1785
|
+
async values() {
|
|
1786
|
+
return [...(await this.#ensureData()).values()].map((entry) => entry.data);
|
|
1787
|
+
}
|
|
1788
|
+
/**
|
|
1789
|
+
* Gets all session entries.
|
|
1790
|
+
*/
|
|
1791
|
+
async entries() {
|
|
1792
|
+
return [...(await this.#ensureData()).entries()].map(([key, entry]) => [key, entry.data]);
|
|
1793
|
+
}
|
|
1794
|
+
/**
|
|
1795
|
+
* Deletes a session value.
|
|
1796
|
+
*/
|
|
1797
|
+
delete(key) {
|
|
1798
|
+
this.#data?.delete(key);
|
|
1799
|
+
if (this.#partial) {
|
|
1800
|
+
this.#toDelete.add(key);
|
|
1801
|
+
}
|
|
1802
|
+
this.#dirty = true;
|
|
1803
|
+
}
|
|
1804
|
+
/**
|
|
1805
|
+
* Sets a session value. The session is created if it does not exist.
|
|
1806
|
+
*/
|
|
1807
|
+
set(key, value, { ttl } = {}) {
|
|
1808
|
+
if (!key) {
|
|
1809
|
+
throw new AstroError({
|
|
1810
|
+
...SessionStorageSaveError,
|
|
1811
|
+
message: "The session key was not provided."
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
let cloned;
|
|
1815
|
+
try {
|
|
1816
|
+
cloned = unflatten(JSON.parse(stringify(value)));
|
|
1817
|
+
} catch (err) {
|
|
1818
|
+
throw new AstroError(
|
|
1819
|
+
{
|
|
1820
|
+
...SessionStorageSaveError,
|
|
1821
|
+
message: `The session data for ${key} could not be serialized.`,
|
|
1822
|
+
hint: "See the devalue library for all supported types: https://github.com/rich-harris/devalue"
|
|
1823
|
+
},
|
|
1824
|
+
{ cause: err }
|
|
1825
|
+
);
|
|
1826
|
+
}
|
|
1827
|
+
if (!this.#cookieSet) {
|
|
1828
|
+
this.#setCookie();
|
|
1829
|
+
this.#cookieSet = true;
|
|
1830
|
+
}
|
|
1831
|
+
this.#data ??= /* @__PURE__ */ new Map();
|
|
1832
|
+
const lifetime = ttl ?? this.#config.ttl;
|
|
1833
|
+
const expires = typeof lifetime === "number" ? Date.now() + lifetime * 1e3 : lifetime;
|
|
1834
|
+
this.#data.set(key, {
|
|
1835
|
+
data: cloned,
|
|
1836
|
+
expires
|
|
1837
|
+
});
|
|
1838
|
+
this.#dirty = true;
|
|
1839
|
+
}
|
|
1840
|
+
/**
|
|
1841
|
+
* Destroys the session, clearing the cookie and storage if it exists.
|
|
1842
|
+
*/
|
|
1843
|
+
destroy() {
|
|
1844
|
+
this.#destroySafe();
|
|
1845
|
+
}
|
|
1846
|
+
/**
|
|
1847
|
+
* Regenerates the session, creating a new session ID. The existing session data is preserved.
|
|
1848
|
+
*/
|
|
1849
|
+
async regenerate() {
|
|
1850
|
+
let data = /* @__PURE__ */ new Map();
|
|
1851
|
+
try {
|
|
1852
|
+
data = await this.#ensureData();
|
|
1853
|
+
} catch (err) {
|
|
1854
|
+
console.error("Failed to load session data during regeneration:", err);
|
|
1855
|
+
}
|
|
1856
|
+
const oldSessionId = this.#sessionID;
|
|
1857
|
+
this.#sessionID = crypto.randomUUID();
|
|
1858
|
+
this.#data = data;
|
|
1859
|
+
await this.#setCookie();
|
|
1860
|
+
if (oldSessionId && this.#storage) {
|
|
1861
|
+
this.#storage.removeItem(oldSessionId).catch((err) => {
|
|
1862
|
+
console.error("Failed to remove old session data:", err);
|
|
1863
|
+
});
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
// Persists the session data to storage.
|
|
1867
|
+
// This is called automatically at the end of the request.
|
|
1868
|
+
// Uses a symbol to prevent users from calling it directly.
|
|
1869
|
+
async [PERSIST_SYMBOL]() {
|
|
1870
|
+
if (!this.#dirty && !this.#toDestroy.size) {
|
|
1871
|
+
return;
|
|
1872
|
+
}
|
|
1873
|
+
const storage = await this.#ensureStorage();
|
|
1874
|
+
if (this.#dirty && this.#data) {
|
|
1875
|
+
const data = await this.#ensureData();
|
|
1876
|
+
this.#toDelete.forEach((key2) => data.delete(key2));
|
|
1877
|
+
const key = this.#ensureSessionID();
|
|
1878
|
+
let serialized;
|
|
1879
|
+
try {
|
|
1880
|
+
serialized = stringify(data);
|
|
1881
|
+
} catch (err) {
|
|
1882
|
+
throw new AstroError(
|
|
1883
|
+
{
|
|
1884
|
+
...SessionStorageSaveError,
|
|
1885
|
+
message: SessionStorageSaveError.message(
|
|
1886
|
+
"The session data could not be serialized.",
|
|
1887
|
+
this.#config.driver
|
|
1888
|
+
)
|
|
1889
|
+
},
|
|
1890
|
+
{ cause: err }
|
|
1891
|
+
);
|
|
1892
|
+
}
|
|
1893
|
+
await storage.setItem(key, serialized);
|
|
1894
|
+
this.#dirty = false;
|
|
1895
|
+
}
|
|
1896
|
+
if (this.#toDestroy.size > 0) {
|
|
1897
|
+
const cleanupPromises = [...this.#toDestroy].map(
|
|
1898
|
+
(sessionId) => storage.removeItem(sessionId).catch((err) => {
|
|
1899
|
+
console.error(`Failed to clean up session ${sessionId}:`, err);
|
|
1900
|
+
})
|
|
1901
|
+
);
|
|
1902
|
+
await Promise.all(cleanupPromises);
|
|
1903
|
+
this.#toDestroy.clear();
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
get sessionID() {
|
|
1907
|
+
return this.#sessionID;
|
|
1908
|
+
}
|
|
1909
|
+
/**
|
|
1910
|
+
* Sets the session cookie.
|
|
1911
|
+
*/
|
|
1912
|
+
async #setCookie() {
|
|
1913
|
+
if (!VALID_COOKIE_REGEX.test(this.#cookieName)) {
|
|
1914
|
+
throw new AstroError({
|
|
1915
|
+
...SessionStorageSaveError,
|
|
1916
|
+
message: "Invalid cookie name. Cookie names can only contain letters, numbers, and dashes."
|
|
1917
|
+
});
|
|
1918
|
+
}
|
|
1919
|
+
const value = this.#ensureSessionID();
|
|
1920
|
+
this.#cookies.set(this.#cookieName, value, this.#cookieConfig);
|
|
1921
|
+
}
|
|
1922
|
+
/**
|
|
1923
|
+
* Attempts to load the session data from storage, or creates a new data object if none exists.
|
|
1924
|
+
* If there is existing partial data, it will be merged into the new data object.
|
|
1925
|
+
*/
|
|
1926
|
+
async #ensureData() {
|
|
1927
|
+
const storage = await this.#ensureStorage();
|
|
1928
|
+
if (this.#data && !this.#partial) {
|
|
1929
|
+
return this.#data;
|
|
1930
|
+
}
|
|
1931
|
+
this.#data ??= /* @__PURE__ */ new Map();
|
|
1932
|
+
const raw = await storage.get(this.#ensureSessionID());
|
|
1933
|
+
if (!raw) {
|
|
1934
|
+
return this.#data;
|
|
1935
|
+
}
|
|
1936
|
+
try {
|
|
1937
|
+
const storedMap = unflatten(raw);
|
|
1938
|
+
if (!(storedMap instanceof Map)) {
|
|
1939
|
+
await this.#destroySafe();
|
|
1940
|
+
throw new AstroError({
|
|
1941
|
+
...SessionStorageInitError,
|
|
1942
|
+
message: SessionStorageInitError.message(
|
|
1943
|
+
"The session data was an invalid type.",
|
|
1944
|
+
this.#config.driver
|
|
1945
|
+
)
|
|
1946
|
+
});
|
|
1947
|
+
}
|
|
1948
|
+
const now = Date.now();
|
|
1949
|
+
for (const [key, value] of storedMap) {
|
|
1950
|
+
const expired = typeof value.expires === "number" && value.expires < now;
|
|
1951
|
+
if (!this.#data.has(key) && !this.#toDelete.has(key) && !expired) {
|
|
1952
|
+
this.#data.set(key, value);
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
this.#partial = false;
|
|
1956
|
+
return this.#data;
|
|
1957
|
+
} catch (err) {
|
|
1958
|
+
await this.#destroySafe();
|
|
1959
|
+
if (err instanceof AstroError) {
|
|
1960
|
+
throw err;
|
|
1961
|
+
}
|
|
1962
|
+
throw new AstroError(
|
|
1963
|
+
{
|
|
1964
|
+
...SessionStorageInitError,
|
|
1965
|
+
message: SessionStorageInitError.message(
|
|
1966
|
+
"The session data could not be parsed.",
|
|
1967
|
+
this.#config.driver
|
|
1968
|
+
)
|
|
1969
|
+
},
|
|
1970
|
+
{ cause: err }
|
|
1971
|
+
);
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
/**
|
|
1975
|
+
* Safely destroys the session, clearing the cookie and storage if it exists.
|
|
1976
|
+
*/
|
|
1977
|
+
#destroySafe() {
|
|
1978
|
+
if (this.#sessionID) {
|
|
1979
|
+
this.#toDestroy.add(this.#sessionID);
|
|
1980
|
+
}
|
|
1981
|
+
if (this.#cookieName) {
|
|
1982
|
+
this.#cookies.delete(this.#cookieName, this.#cookieConfig);
|
|
1983
|
+
}
|
|
1984
|
+
this.#sessionID = void 0;
|
|
1985
|
+
this.#data = void 0;
|
|
1986
|
+
this.#dirty = true;
|
|
1987
|
+
}
|
|
1988
|
+
/**
|
|
1989
|
+
* Returns the session ID, generating a new one if it does not exist.
|
|
1990
|
+
*/
|
|
1991
|
+
#ensureSessionID() {
|
|
1992
|
+
this.#sessionID ??= this.#cookies.get(this.#cookieName)?.value ?? crypto.randomUUID();
|
|
1993
|
+
return this.#sessionID;
|
|
1994
|
+
}
|
|
1995
|
+
/**
|
|
1996
|
+
* Ensures the storage is initialized.
|
|
1997
|
+
* This is called automatically when a storage operation is needed.
|
|
1998
|
+
*/
|
|
1999
|
+
async #ensureStorage() {
|
|
2000
|
+
if (this.#storage) {
|
|
2001
|
+
return this.#storage;
|
|
2002
|
+
}
|
|
2003
|
+
if (this.#config.driver === "test") {
|
|
2004
|
+
this.#storage = this.#config.options.mockStorage;
|
|
2005
|
+
return this.#storage;
|
|
2006
|
+
}
|
|
2007
|
+
if (this.#config.driver === "fs" || this.#config.driver === "fsLite" || this.#config.driver === "fs-lite") {
|
|
2008
|
+
this.#config.options ??= {};
|
|
2009
|
+
this.#config.driver = "fs-lite";
|
|
2010
|
+
this.#config.options.base ??= ".astro/session";
|
|
2011
|
+
}
|
|
2012
|
+
if (!this.#config?.driver) {
|
|
2013
|
+
throw new AstroError({
|
|
2014
|
+
...SessionStorageInitError,
|
|
2015
|
+
message: SessionStorageInitError.message(
|
|
2016
|
+
"No driver was defined in the session configuration and the adapter did not provide a default driver."
|
|
2017
|
+
)
|
|
2018
|
+
});
|
|
2019
|
+
}
|
|
2020
|
+
let driver = null;
|
|
2021
|
+
const driverPackage = await resolveSessionDriver(this.#config.driver);
|
|
2022
|
+
try {
|
|
2023
|
+
if (this.#config.driverModule) {
|
|
2024
|
+
driver = (await this.#config.driverModule()).default;
|
|
2025
|
+
} else if (driverPackage) {
|
|
2026
|
+
driver = (await import(driverPackage)).default;
|
|
2027
|
+
}
|
|
2028
|
+
} catch (err) {
|
|
2029
|
+
if (err.code === "ERR_MODULE_NOT_FOUND") {
|
|
2030
|
+
throw new AstroError(
|
|
2031
|
+
{
|
|
2032
|
+
...SessionStorageInitError,
|
|
2033
|
+
message: SessionStorageInitError.message(
|
|
2034
|
+
err.message.includes(`Cannot find package '${driverPackage}'`) ? "The driver module could not be found." : err.message,
|
|
2035
|
+
this.#config.driver
|
|
2036
|
+
)
|
|
2037
|
+
},
|
|
2038
|
+
{ cause: err }
|
|
2039
|
+
);
|
|
2040
|
+
}
|
|
2041
|
+
throw err;
|
|
2042
|
+
}
|
|
2043
|
+
if (!driver) {
|
|
2044
|
+
throw new AstroError({
|
|
2045
|
+
...SessionStorageInitError,
|
|
2046
|
+
message: SessionStorageInitError.message(
|
|
2047
|
+
"The module did not export a driver.",
|
|
2048
|
+
this.#config.driver
|
|
2049
|
+
)
|
|
2050
|
+
});
|
|
2051
|
+
}
|
|
2052
|
+
try {
|
|
2053
|
+
this.#storage = createStorage({
|
|
2054
|
+
driver: driver(this.#config.options)
|
|
2055
|
+
});
|
|
2056
|
+
return this.#storage;
|
|
2057
|
+
} catch (err) {
|
|
2058
|
+
throw new AstroError(
|
|
2059
|
+
{
|
|
2060
|
+
...SessionStorageInitError,
|
|
2061
|
+
message: SessionStorageInitError.message("Unknown error", this.#config.driver)
|
|
2062
|
+
},
|
|
2063
|
+
{ cause: err }
|
|
2064
|
+
);
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
async function resolveSessionDriver(driver) {
|
|
2069
|
+
if (!driver) {
|
|
2070
|
+
return null;
|
|
2071
|
+
}
|
|
2072
|
+
try {
|
|
2073
|
+
if (driver === "fs") {
|
|
2074
|
+
return await import.meta.resolve(builtinDrivers.fsLite);
|
|
2075
|
+
}
|
|
2076
|
+
if (driver in builtinDrivers) {
|
|
2077
|
+
return await import.meta.resolve(builtinDrivers[driver]);
|
|
2078
|
+
}
|
|
2079
|
+
} catch {
|
|
2080
|
+
return null;
|
|
2081
|
+
}
|
|
2082
|
+
return driver;
|
|
2083
|
+
}
|
|
2084
|
+
|
|
2085
|
+
const apiContextRoutesSymbol = Symbol.for("context.routes");
|
|
2086
|
+
class RenderContext {
|
|
2087
|
+
constructor(pipeline, locals, middleware, pathname, request, routeData, status, clientAddress, cookies = new AstroCookies(request), params = getParams(routeData, pathname), url = new URL(request.url), props = {}, partial = void 0, session = pipeline.manifest.sessionConfig ? new AstroSession(cookies, pipeline.manifest.sessionConfig) : void 0) {
|
|
2088
|
+
this.pipeline = pipeline;
|
|
2089
|
+
this.locals = locals;
|
|
2090
|
+
this.middleware = middleware;
|
|
2091
|
+
this.pathname = pathname;
|
|
2092
|
+
this.request = request;
|
|
2093
|
+
this.routeData = routeData;
|
|
2094
|
+
this.status = status;
|
|
2095
|
+
this.clientAddress = clientAddress;
|
|
2096
|
+
this.cookies = cookies;
|
|
2097
|
+
this.params = params;
|
|
2098
|
+
this.url = url;
|
|
2099
|
+
this.props = props;
|
|
2100
|
+
this.partial = partial;
|
|
2101
|
+
this.session = session;
|
|
2102
|
+
}
|
|
2103
|
+
/**
|
|
2104
|
+
* A flag that tells the render content if the rewriting was triggered
|
|
2105
|
+
*/
|
|
2106
|
+
isRewriting = false;
|
|
2107
|
+
/**
|
|
2108
|
+
* A safety net in case of loops
|
|
2109
|
+
*/
|
|
2110
|
+
counter = 0;
|
|
2111
|
+
static async create({
|
|
2112
|
+
locals = {},
|
|
2113
|
+
middleware,
|
|
2114
|
+
pathname,
|
|
2115
|
+
pipeline,
|
|
2116
|
+
request,
|
|
2117
|
+
routeData,
|
|
2118
|
+
clientAddress,
|
|
2119
|
+
status = 200,
|
|
2120
|
+
props,
|
|
2121
|
+
partial = void 0
|
|
2122
|
+
}) {
|
|
2123
|
+
const pipelineMiddleware = await pipeline.getMiddleware();
|
|
2124
|
+
setOriginPathname(request, pathname);
|
|
2125
|
+
return new RenderContext(
|
|
2126
|
+
pipeline,
|
|
2127
|
+
locals,
|
|
2128
|
+
sequence(...pipeline.internalMiddleware, middleware ?? pipelineMiddleware),
|
|
2129
|
+
pathname,
|
|
2130
|
+
request,
|
|
2131
|
+
routeData,
|
|
2132
|
+
status,
|
|
2133
|
+
clientAddress,
|
|
2134
|
+
void 0,
|
|
2135
|
+
void 0,
|
|
2136
|
+
void 0,
|
|
2137
|
+
props,
|
|
2138
|
+
partial
|
|
2139
|
+
);
|
|
2140
|
+
}
|
|
2141
|
+
/**
|
|
2142
|
+
* The main function of the RenderContext.
|
|
2143
|
+
*
|
|
2144
|
+
* Use this function to render any route known to Astro.
|
|
2145
|
+
* It attempts to render a route. A route can be a:
|
|
2146
|
+
*
|
|
2147
|
+
* - page
|
|
2148
|
+
* - redirect
|
|
2149
|
+
* - endpoint
|
|
2150
|
+
* - fallback
|
|
2151
|
+
*/
|
|
2152
|
+
async render(componentInstance, slots = {}) {
|
|
2153
|
+
const { cookies, middleware, pipeline } = this;
|
|
2154
|
+
const { logger, serverLike, streaming, manifest } = pipeline;
|
|
2155
|
+
const props = Object.keys(this.props).length > 0 ? this.props : await getProps({
|
|
2156
|
+
mod: componentInstance,
|
|
2157
|
+
routeData: this.routeData,
|
|
2158
|
+
routeCache: this.pipeline.routeCache,
|
|
2159
|
+
pathname: this.pathname,
|
|
2160
|
+
logger,
|
|
2161
|
+
serverLike,
|
|
2162
|
+
base: manifest.base
|
|
2163
|
+
});
|
|
2164
|
+
const apiContext = this.createAPIContext(props);
|
|
2165
|
+
this.counter++;
|
|
2166
|
+
if (this.counter === 4) {
|
|
2167
|
+
return new Response("Loop Detected", {
|
|
2168
|
+
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/508
|
|
2169
|
+
status: 508,
|
|
2170
|
+
statusText: "Astro detected a loop where you tried to call the rewriting logic more than four times."
|
|
2171
|
+
});
|
|
2172
|
+
}
|
|
2173
|
+
const lastNext = async (ctx, payload) => {
|
|
2174
|
+
if (payload) {
|
|
2175
|
+
pipeline.logger.debug("router", "Called rewriting to:", payload);
|
|
2176
|
+
const {
|
|
2177
|
+
routeData,
|
|
2178
|
+
componentInstance: newComponent,
|
|
2179
|
+
pathname,
|
|
2180
|
+
newUrl
|
|
2181
|
+
} = await pipeline.tryRewrite(payload, this.request);
|
|
2182
|
+
if (this.pipeline.serverLike === true && this.routeData.prerender === false && routeData.prerender === true) {
|
|
2183
|
+
throw new AstroError({
|
|
2184
|
+
...ForbiddenRewrite,
|
|
2185
|
+
message: ForbiddenRewrite.message(this.pathname, pathname, routeData.component),
|
|
2186
|
+
hint: ForbiddenRewrite.hint(routeData.component)
|
|
2187
|
+
});
|
|
2188
|
+
}
|
|
2189
|
+
this.routeData = routeData;
|
|
2190
|
+
componentInstance = newComponent;
|
|
2191
|
+
if (payload instanceof Request) {
|
|
2192
|
+
this.request = payload;
|
|
2193
|
+
} else {
|
|
2194
|
+
this.request = copyRequest(
|
|
2195
|
+
newUrl,
|
|
2196
|
+
this.request,
|
|
2197
|
+
// need to send the flag of the previous routeData
|
|
2198
|
+
routeData.prerender,
|
|
2199
|
+
this.pipeline.logger,
|
|
2200
|
+
this.routeData.route
|
|
2201
|
+
);
|
|
2202
|
+
}
|
|
2203
|
+
this.isRewriting = true;
|
|
2204
|
+
this.url = new URL(this.request.url);
|
|
2205
|
+
this.cookies = new AstroCookies(this.request);
|
|
2206
|
+
this.params = getParams(routeData, pathname);
|
|
2207
|
+
this.pathname = pathname;
|
|
2208
|
+
this.status = 200;
|
|
2209
|
+
}
|
|
2210
|
+
let response2;
|
|
2211
|
+
switch (this.routeData.type) {
|
|
2212
|
+
case "endpoint": {
|
|
2213
|
+
response2 = await renderEndpoint(
|
|
2214
|
+
componentInstance,
|
|
2215
|
+
ctx,
|
|
2216
|
+
this.routeData.prerender,
|
|
2217
|
+
logger
|
|
2218
|
+
);
|
|
2219
|
+
break;
|
|
2220
|
+
}
|
|
2221
|
+
case "redirect":
|
|
2222
|
+
return renderRedirect(this);
|
|
2223
|
+
case "page": {
|
|
2224
|
+
const result = await this.createResult(componentInstance);
|
|
2225
|
+
try {
|
|
2226
|
+
response2 = await renderPage(
|
|
2227
|
+
result,
|
|
2228
|
+
componentInstance?.default,
|
|
2229
|
+
props,
|
|
2230
|
+
slots,
|
|
2231
|
+
streaming,
|
|
2232
|
+
this.routeData
|
|
2233
|
+
);
|
|
2234
|
+
} catch (e) {
|
|
2235
|
+
result.cancelled = true;
|
|
2236
|
+
throw e;
|
|
2237
|
+
}
|
|
2238
|
+
response2.headers.set(ROUTE_TYPE_HEADER, "page");
|
|
2239
|
+
if (this.routeData.route === "/404" || this.routeData.route === "/500") {
|
|
2240
|
+
response2.headers.set(REROUTE_DIRECTIVE_HEADER, "no");
|
|
2241
|
+
}
|
|
2242
|
+
if (this.isRewriting) {
|
|
2243
|
+
response2.headers.set(REWRITE_DIRECTIVE_HEADER_KEY, REWRITE_DIRECTIVE_HEADER_VALUE);
|
|
2244
|
+
}
|
|
2245
|
+
break;
|
|
2246
|
+
}
|
|
2247
|
+
case "fallback": {
|
|
2248
|
+
return new Response(null, { status: 500, headers: { [ROUTE_TYPE_HEADER]: "fallback" } });
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
const responseCookies = getCookiesFromResponse(response2);
|
|
2252
|
+
if (responseCookies) {
|
|
2253
|
+
cookies.merge(responseCookies);
|
|
2254
|
+
}
|
|
2255
|
+
return response2;
|
|
2256
|
+
};
|
|
2257
|
+
if (isRouteExternalRedirect(this.routeData)) {
|
|
2258
|
+
return renderRedirect(this);
|
|
2259
|
+
}
|
|
2260
|
+
const response = await callMiddleware(middleware, apiContext, lastNext);
|
|
2261
|
+
if (response.headers.get(ROUTE_TYPE_HEADER)) {
|
|
2262
|
+
response.headers.delete(ROUTE_TYPE_HEADER);
|
|
2263
|
+
}
|
|
2264
|
+
attachCookiesToResponse(response, cookies);
|
|
2265
|
+
return response;
|
|
2266
|
+
}
|
|
2267
|
+
createAPIContext(props) {
|
|
2268
|
+
const context = this.createActionAPIContext();
|
|
2269
|
+
const redirect = (path, status = 302) => new Response(null, { status, headers: { Location: path } });
|
|
2270
|
+
Reflect.set(context, apiContextRoutesSymbol, this.pipeline);
|
|
2271
|
+
return Object.assign(context, {
|
|
2272
|
+
props,
|
|
2273
|
+
redirect,
|
|
2274
|
+
getActionResult: createGetActionResult(context.locals),
|
|
2275
|
+
callAction: createCallAction(context)
|
|
2276
|
+
});
|
|
2277
|
+
}
|
|
2278
|
+
async #executeRewrite(reroutePayload) {
|
|
2279
|
+
this.pipeline.logger.debug("router", "Calling rewrite: ", reroutePayload);
|
|
2280
|
+
const { routeData, componentInstance, newUrl, pathname } = await this.pipeline.tryRewrite(
|
|
2281
|
+
reroutePayload,
|
|
2282
|
+
this.request
|
|
2283
|
+
);
|
|
2284
|
+
if (this.pipeline.serverLike === true && this.routeData.prerender === false && routeData.prerender === true) {
|
|
2285
|
+
throw new AstroError({
|
|
2286
|
+
...ForbiddenRewrite,
|
|
2287
|
+
message: ForbiddenRewrite.message(this.pathname, pathname, routeData.component),
|
|
2288
|
+
hint: ForbiddenRewrite.hint(routeData.component)
|
|
2289
|
+
});
|
|
2290
|
+
}
|
|
2291
|
+
this.routeData = routeData;
|
|
2292
|
+
if (reroutePayload instanceof Request) {
|
|
2293
|
+
this.request = reroutePayload;
|
|
2294
|
+
} else {
|
|
2295
|
+
this.request = copyRequest(
|
|
2296
|
+
newUrl,
|
|
2297
|
+
this.request,
|
|
2298
|
+
// need to send the flag of the previous routeData
|
|
2299
|
+
routeData.prerender,
|
|
2300
|
+
this.pipeline.logger,
|
|
2301
|
+
this.routeData.route
|
|
2302
|
+
);
|
|
2303
|
+
}
|
|
2304
|
+
this.url = new URL(this.request.url);
|
|
2305
|
+
this.cookies = new AstroCookies(this.request);
|
|
2306
|
+
this.params = getParams(routeData, pathname);
|
|
2307
|
+
this.pathname = pathname;
|
|
2308
|
+
this.isRewriting = true;
|
|
2309
|
+
this.status = 200;
|
|
2310
|
+
return await this.render(componentInstance);
|
|
2311
|
+
}
|
|
2312
|
+
createActionAPIContext() {
|
|
2313
|
+
const renderContext = this;
|
|
2314
|
+
const { cookies, params, pipeline, url, session } = this;
|
|
2315
|
+
const generator = `Astro v${ASTRO_VERSION}`;
|
|
2316
|
+
const rewrite = async (reroutePayload) => {
|
|
2317
|
+
return await this.#executeRewrite(reroutePayload);
|
|
2318
|
+
};
|
|
2319
|
+
return {
|
|
2320
|
+
cookies,
|
|
2321
|
+
routePattern: this.routeData.route,
|
|
2322
|
+
isPrerendered: this.routeData.prerender,
|
|
2323
|
+
get clientAddress() {
|
|
2324
|
+
return renderContext.getClientAddress();
|
|
2325
|
+
},
|
|
2326
|
+
get currentLocale() {
|
|
2327
|
+
return renderContext.computeCurrentLocale();
|
|
2328
|
+
},
|
|
2329
|
+
generator,
|
|
2330
|
+
get locals() {
|
|
2331
|
+
return renderContext.locals;
|
|
2332
|
+
},
|
|
2333
|
+
set locals(_) {
|
|
2334
|
+
throw new AstroError(LocalsReassigned);
|
|
2335
|
+
},
|
|
2336
|
+
params,
|
|
2337
|
+
get preferredLocale() {
|
|
2338
|
+
return renderContext.computePreferredLocale();
|
|
2339
|
+
},
|
|
2340
|
+
get preferredLocaleList() {
|
|
2341
|
+
return renderContext.computePreferredLocaleList();
|
|
2342
|
+
},
|
|
2343
|
+
rewrite,
|
|
2344
|
+
request: this.request,
|
|
2345
|
+
site: pipeline.site,
|
|
2346
|
+
url,
|
|
2347
|
+
get originPathname() {
|
|
2348
|
+
return getOriginPathname(renderContext.request);
|
|
2349
|
+
},
|
|
2350
|
+
session
|
|
2351
|
+
};
|
|
2352
|
+
}
|
|
2353
|
+
async createResult(mod) {
|
|
2354
|
+
const { cookies, pathname, pipeline, routeData, status } = this;
|
|
2355
|
+
const { clientDirectives, inlinedScripts, compressHTML, manifest, renderers, resolve } = pipeline;
|
|
2356
|
+
const { links, scripts, styles } = await pipeline.headElements(routeData);
|
|
2357
|
+
const componentMetadata = await pipeline.componentMetadata(routeData) ?? manifest.componentMetadata;
|
|
2358
|
+
const headers = new Headers({ "Content-Type": "text/html" });
|
|
2359
|
+
const partial = typeof this.partial === "boolean" ? this.partial : Boolean(mod.partial);
|
|
2360
|
+
const actionResult = hasActionPayload(this.locals) ? deserializeActionResult(this.locals._actionPayload.actionResult) : void 0;
|
|
2361
|
+
const response = {
|
|
2362
|
+
status: actionResult?.error ? actionResult?.error.status : status,
|
|
2363
|
+
statusText: actionResult?.error ? actionResult?.error.type : "OK",
|
|
2364
|
+
get headers() {
|
|
2365
|
+
return headers;
|
|
2366
|
+
},
|
|
2367
|
+
// Disallow `Astro.response.headers = new Headers`
|
|
2368
|
+
set headers(_) {
|
|
2369
|
+
throw new AstroError(AstroResponseHeadersReassigned);
|
|
2370
|
+
}
|
|
2371
|
+
};
|
|
2372
|
+
const result = {
|
|
2373
|
+
base: manifest.base,
|
|
2374
|
+
userAssetsBase: manifest.userAssetsBase,
|
|
2375
|
+
cancelled: false,
|
|
2376
|
+
clientDirectives,
|
|
2377
|
+
inlinedScripts,
|
|
2378
|
+
componentMetadata,
|
|
2379
|
+
compressHTML,
|
|
2380
|
+
cookies,
|
|
2381
|
+
/** This function returns the `Astro` faux-global */
|
|
2382
|
+
createAstro: (astroGlobal, props, slots) => this.createAstro(result, astroGlobal, props, slots),
|
|
2383
|
+
links,
|
|
2384
|
+
params: this.params,
|
|
2385
|
+
partial,
|
|
2386
|
+
pathname,
|
|
2387
|
+
renderers,
|
|
2388
|
+
resolve,
|
|
2389
|
+
response,
|
|
2390
|
+
request: this.request,
|
|
2391
|
+
scripts,
|
|
2392
|
+
styles,
|
|
2393
|
+
actionResult,
|
|
2394
|
+
serverIslandNameMap: manifest.serverIslandNameMap ?? /* @__PURE__ */ new Map(),
|
|
2395
|
+
key: manifest.key,
|
|
2396
|
+
trailingSlash: manifest.trailingSlash,
|
|
2397
|
+
_metadata: {
|
|
2398
|
+
hasHydrationScript: false,
|
|
2399
|
+
rendererSpecificHydrationScripts: /* @__PURE__ */ new Set(),
|
|
2400
|
+
hasRenderedHead: false,
|
|
2401
|
+
renderedScripts: /* @__PURE__ */ new Set(),
|
|
2402
|
+
hasDirectives: /* @__PURE__ */ new Set(),
|
|
2403
|
+
headInTree: false,
|
|
2404
|
+
extraHead: [],
|
|
2405
|
+
propagators: /* @__PURE__ */ new Set()
|
|
2406
|
+
}
|
|
2407
|
+
};
|
|
2408
|
+
return result;
|
|
2409
|
+
}
|
|
2410
|
+
#astroPagePartial;
|
|
2411
|
+
/**
|
|
2412
|
+
* The Astro global is sourced in 3 different phases:
|
|
2413
|
+
* - **Static**: `.generator` and `.glob` is printed by the compiler, instantiated once per process per astro file
|
|
2414
|
+
* - **Page-level**: `.request`, `.cookies`, `.locals` etc. These remain the same for the duration of the request.
|
|
2415
|
+
* - **Component-level**: `.props`, `.slots`, and `.self` are unique to each _use_ of each component.
|
|
2416
|
+
*
|
|
2417
|
+
* The page level partial is used as the prototype of the user-visible `Astro` global object, which is instantiated once per use of a component.
|
|
2418
|
+
*/
|
|
2419
|
+
createAstro(result, astroStaticPartial, props, slotValues) {
|
|
2420
|
+
let astroPagePartial;
|
|
2421
|
+
if (this.isRewriting) {
|
|
2422
|
+
astroPagePartial = this.#astroPagePartial = this.createAstroPagePartial(
|
|
2423
|
+
result,
|
|
2424
|
+
astroStaticPartial
|
|
2425
|
+
);
|
|
2426
|
+
} else {
|
|
2427
|
+
astroPagePartial = this.#astroPagePartial ??= this.createAstroPagePartial(
|
|
2428
|
+
result,
|
|
2429
|
+
astroStaticPartial
|
|
2430
|
+
);
|
|
2431
|
+
}
|
|
2432
|
+
const astroComponentPartial = { props, self: null };
|
|
2433
|
+
const Astro = Object.assign(
|
|
2434
|
+
Object.create(astroPagePartial),
|
|
2435
|
+
astroComponentPartial
|
|
2436
|
+
);
|
|
2437
|
+
let _slots;
|
|
2438
|
+
Object.defineProperty(Astro, "slots", {
|
|
2439
|
+
get: () => {
|
|
2440
|
+
if (!_slots) {
|
|
2441
|
+
_slots = new Slots(
|
|
2442
|
+
result,
|
|
2443
|
+
slotValues,
|
|
2444
|
+
this.pipeline.logger
|
|
2445
|
+
);
|
|
2446
|
+
}
|
|
2447
|
+
return _slots;
|
|
2448
|
+
}
|
|
2449
|
+
});
|
|
2450
|
+
return Astro;
|
|
2451
|
+
}
|
|
2452
|
+
createAstroPagePartial(result, astroStaticPartial) {
|
|
2453
|
+
const renderContext = this;
|
|
2454
|
+
const { cookies, locals, params, pipeline, url, session } = this;
|
|
2455
|
+
const { response } = result;
|
|
2456
|
+
const redirect = (path, status = 302) => {
|
|
2457
|
+
if (this.request[responseSentSymbol$1]) {
|
|
2458
|
+
throw new AstroError({
|
|
2459
|
+
...ResponseSentError
|
|
2460
|
+
});
|
|
2461
|
+
}
|
|
2462
|
+
return new Response(null, { status, headers: { Location: path } });
|
|
2463
|
+
};
|
|
2464
|
+
const rewrite = async (reroutePayload) => {
|
|
2465
|
+
return await this.#executeRewrite(reroutePayload);
|
|
2466
|
+
};
|
|
2467
|
+
return {
|
|
2468
|
+
generator: astroStaticPartial.generator,
|
|
2469
|
+
glob: astroStaticPartial.glob,
|
|
2470
|
+
routePattern: this.routeData.route,
|
|
2471
|
+
isPrerendered: this.routeData.prerender,
|
|
2472
|
+
cookies,
|
|
2473
|
+
session,
|
|
2474
|
+
get clientAddress() {
|
|
2475
|
+
return renderContext.getClientAddress();
|
|
2476
|
+
},
|
|
2477
|
+
get currentLocale() {
|
|
2478
|
+
return renderContext.computeCurrentLocale();
|
|
2479
|
+
},
|
|
2480
|
+
params,
|
|
2481
|
+
get preferredLocale() {
|
|
2482
|
+
return renderContext.computePreferredLocale();
|
|
2483
|
+
},
|
|
2484
|
+
get preferredLocaleList() {
|
|
2485
|
+
return renderContext.computePreferredLocaleList();
|
|
2486
|
+
},
|
|
2487
|
+
locals,
|
|
2488
|
+
redirect,
|
|
2489
|
+
rewrite,
|
|
2490
|
+
request: this.request,
|
|
2491
|
+
response,
|
|
2492
|
+
site: pipeline.site,
|
|
2493
|
+
getActionResult: createGetActionResult(locals),
|
|
2494
|
+
get callAction() {
|
|
2495
|
+
return createCallAction(this);
|
|
2496
|
+
},
|
|
2497
|
+
url,
|
|
2498
|
+
get originPathname() {
|
|
2499
|
+
return getOriginPathname(renderContext.request);
|
|
2500
|
+
}
|
|
2501
|
+
};
|
|
2502
|
+
}
|
|
2503
|
+
getClientAddress() {
|
|
2504
|
+
const { pipeline, request, routeData, clientAddress } = this;
|
|
2505
|
+
if (routeData.prerender) {
|
|
2506
|
+
throw new AstroError(PrerenderClientAddressNotAvailable);
|
|
2507
|
+
}
|
|
2508
|
+
if (clientAddress) {
|
|
2509
|
+
return clientAddress;
|
|
2510
|
+
}
|
|
2511
|
+
if (clientAddressSymbol in request) {
|
|
2512
|
+
return Reflect.get(request, clientAddressSymbol);
|
|
2513
|
+
}
|
|
2514
|
+
if (pipeline.adapterName) {
|
|
2515
|
+
throw new AstroError({
|
|
2516
|
+
...ClientAddressNotAvailable,
|
|
2517
|
+
message: ClientAddressNotAvailable.message(pipeline.adapterName)
|
|
2518
|
+
});
|
|
2519
|
+
}
|
|
2520
|
+
throw new AstroError(StaticClientAddressNotAvailable);
|
|
2521
|
+
}
|
|
2522
|
+
/**
|
|
2523
|
+
* API Context may be created multiple times per request, i18n data needs to be computed only once.
|
|
2524
|
+
* So, it is computed and saved here on creation of the first APIContext and reused for later ones.
|
|
2525
|
+
*/
|
|
2526
|
+
#currentLocale;
|
|
2527
|
+
computeCurrentLocale() {
|
|
2528
|
+
const {
|
|
2529
|
+
url,
|
|
2530
|
+
pipeline: { i18n },
|
|
2531
|
+
routeData
|
|
2532
|
+
} = this;
|
|
2533
|
+
if (!i18n) return;
|
|
2534
|
+
const { defaultLocale, locales, strategy } = i18n;
|
|
2535
|
+
const fallbackTo = strategy === "pathname-prefix-other-locales" || strategy === "domains-prefix-other-locales" ? defaultLocale : void 0;
|
|
2536
|
+
if (this.#currentLocale) {
|
|
2537
|
+
return this.#currentLocale;
|
|
2538
|
+
}
|
|
2539
|
+
let computedLocale;
|
|
2540
|
+
if (isRouteServerIsland(routeData)) {
|
|
2541
|
+
let referer = this.request.headers.get("referer");
|
|
2542
|
+
if (referer) {
|
|
2543
|
+
if (URL.canParse(referer)) {
|
|
2544
|
+
referer = new URL(referer).pathname;
|
|
2545
|
+
}
|
|
2546
|
+
computedLocale = computeCurrentLocale(referer, locales, defaultLocale);
|
|
2547
|
+
}
|
|
2548
|
+
} else {
|
|
2549
|
+
let pathname = routeData.pathname;
|
|
2550
|
+
if (!routeData.pattern.test(url.pathname)) {
|
|
2551
|
+
for (const fallbackRoute of routeData.fallbackRoutes) {
|
|
2552
|
+
if (fallbackRoute.pattern.test(url.pathname)) {
|
|
2553
|
+
pathname = fallbackRoute.pathname;
|
|
2554
|
+
break;
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
}
|
|
2558
|
+
pathname = pathname && !isRoute404or500(routeData) ? pathname : url.pathname;
|
|
2559
|
+
computedLocale = computeCurrentLocale(pathname, locales, defaultLocale);
|
|
2560
|
+
}
|
|
2561
|
+
this.#currentLocale = computedLocale ?? fallbackTo;
|
|
2562
|
+
return this.#currentLocale;
|
|
2563
|
+
}
|
|
2564
|
+
#preferredLocale;
|
|
2565
|
+
computePreferredLocale() {
|
|
2566
|
+
const {
|
|
2567
|
+
pipeline: { i18n },
|
|
2568
|
+
request
|
|
2569
|
+
} = this;
|
|
2570
|
+
if (!i18n) return;
|
|
2571
|
+
return this.#preferredLocale ??= computePreferredLocale(request, i18n.locales);
|
|
2572
|
+
}
|
|
2573
|
+
#preferredLocaleList;
|
|
2574
|
+
computePreferredLocaleList() {
|
|
2575
|
+
const {
|
|
2576
|
+
pipeline: { i18n },
|
|
2577
|
+
request
|
|
2578
|
+
} = this;
|
|
2579
|
+
if (!i18n) return;
|
|
2580
|
+
return this.#preferredLocaleList ??= computePreferredLocaleList(request, i18n.locales);
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
|
|
2584
|
+
function getAssetsPrefix(fileExtension, assetsPrefix) {
|
|
2585
|
+
if (!assetsPrefix) return "";
|
|
2586
|
+
if (typeof assetsPrefix === "string") return assetsPrefix;
|
|
2587
|
+
const dotLessFileExtension = fileExtension.slice(1);
|
|
2588
|
+
if (assetsPrefix[dotLessFileExtension]) {
|
|
2589
|
+
return assetsPrefix[dotLessFileExtension];
|
|
2590
|
+
}
|
|
2591
|
+
return assetsPrefix.fallback;
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
function createAssetLink(href, base, assetsPrefix) {
|
|
2595
|
+
if (assetsPrefix) {
|
|
2596
|
+
const pf = getAssetsPrefix(fileExtension(href), assetsPrefix);
|
|
2597
|
+
return joinPaths(pf, slash(href));
|
|
2598
|
+
} else if (base) {
|
|
2599
|
+
return prependForwardSlash$1(joinPaths(base, slash(href)));
|
|
2600
|
+
} else {
|
|
2601
|
+
return href;
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2604
|
+
function createStylesheetElement(stylesheet, base, assetsPrefix) {
|
|
2605
|
+
if (stylesheet.type === "inline") {
|
|
2606
|
+
return {
|
|
2607
|
+
props: {},
|
|
2608
|
+
children: stylesheet.content
|
|
2609
|
+
};
|
|
2610
|
+
} else {
|
|
2611
|
+
return {
|
|
2612
|
+
props: {
|
|
2613
|
+
rel: "stylesheet",
|
|
2614
|
+
href: createAssetLink(stylesheet.src, base, assetsPrefix)
|
|
2615
|
+
},
|
|
2616
|
+
children: ""
|
|
2617
|
+
};
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
function createStylesheetElementSet(stylesheets, base, assetsPrefix) {
|
|
2621
|
+
return new Set(stylesheets.map((s) => createStylesheetElement(s, base, assetsPrefix)));
|
|
2622
|
+
}
|
|
2623
|
+
function createModuleScriptElement(script, base, assetsPrefix) {
|
|
2624
|
+
if (script.type === "external") {
|
|
2625
|
+
return createModuleScriptElementWithSrc(script.value, base, assetsPrefix);
|
|
2626
|
+
} else {
|
|
2627
|
+
return {
|
|
2628
|
+
props: {
|
|
2629
|
+
type: "module"
|
|
2630
|
+
},
|
|
2631
|
+
children: script.value
|
|
2632
|
+
};
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
function createModuleScriptElementWithSrc(src, base, assetsPrefix) {
|
|
2636
|
+
return {
|
|
2637
|
+
props: {
|
|
2638
|
+
type: "module",
|
|
2639
|
+
src: createAssetLink(src, base, assetsPrefix)
|
|
2640
|
+
},
|
|
2641
|
+
children: ""
|
|
2642
|
+
};
|
|
2643
|
+
}
|
|
2644
|
+
|
|
2645
|
+
function redirectTemplate({ status, location, from }) {
|
|
2646
|
+
const delay = status === 302 ? 2 : 0;
|
|
2647
|
+
return `<!doctype html>
|
|
2648
|
+
<title>Redirecting to: ${location}</title>
|
|
2649
|
+
<meta http-equiv="refresh" content="${delay};url=${location}">
|
|
2650
|
+
<meta name="robots" content="noindex">
|
|
2651
|
+
<link rel="canonical" href="${location}">
|
|
2652
|
+
<body>
|
|
2653
|
+
<a href="${location}">Redirecting ${from ? `from <code>${from}</code> ` : ""}to <code>${location}</code></a>
|
|
2654
|
+
</body>`;
|
|
2655
|
+
}
|
|
2656
|
+
|
|
2657
|
+
class AppPipeline extends Pipeline {
|
|
2658
|
+
#manifestData;
|
|
2659
|
+
static create(manifestData, {
|
|
2660
|
+
logger,
|
|
2661
|
+
manifest,
|
|
2662
|
+
runtimeMode,
|
|
2663
|
+
renderers,
|
|
2664
|
+
resolve,
|
|
2665
|
+
serverLike,
|
|
2666
|
+
streaming,
|
|
2667
|
+
defaultRoutes
|
|
2668
|
+
}) {
|
|
2669
|
+
const pipeline = new AppPipeline(
|
|
2670
|
+
logger,
|
|
2671
|
+
manifest,
|
|
2672
|
+
runtimeMode,
|
|
2673
|
+
renderers,
|
|
2674
|
+
resolve,
|
|
2675
|
+
serverLike,
|
|
2676
|
+
streaming,
|
|
2677
|
+
void 0,
|
|
2678
|
+
void 0,
|
|
2679
|
+
void 0,
|
|
2680
|
+
void 0,
|
|
2681
|
+
void 0,
|
|
2682
|
+
void 0,
|
|
2683
|
+
void 0,
|
|
2684
|
+
void 0,
|
|
2685
|
+
defaultRoutes
|
|
2686
|
+
);
|
|
2687
|
+
pipeline.#manifestData = manifestData;
|
|
2688
|
+
return pipeline;
|
|
2689
|
+
}
|
|
2690
|
+
headElements(routeData) {
|
|
2691
|
+
const routeInfo = this.manifest.routes.find((route) => route.routeData === routeData);
|
|
2692
|
+
const links = /* @__PURE__ */ new Set();
|
|
2693
|
+
const scripts = /* @__PURE__ */ new Set();
|
|
2694
|
+
const styles = createStylesheetElementSet(routeInfo?.styles ?? []);
|
|
2695
|
+
for (const script of routeInfo?.scripts ?? []) {
|
|
2696
|
+
if ("stage" in script) {
|
|
2697
|
+
if (script.stage === "head-inline") {
|
|
2698
|
+
scripts.add({
|
|
2699
|
+
props: {},
|
|
2700
|
+
children: script.children
|
|
2701
|
+
});
|
|
2702
|
+
}
|
|
2703
|
+
} else {
|
|
2704
|
+
scripts.add(createModuleScriptElement(script));
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
return { links, styles, scripts };
|
|
2708
|
+
}
|
|
2709
|
+
componentMetadata() {
|
|
2710
|
+
}
|
|
2711
|
+
async getComponentByRoute(routeData) {
|
|
2712
|
+
const module = await this.getModuleForRoute(routeData);
|
|
2713
|
+
return module.page();
|
|
2714
|
+
}
|
|
2715
|
+
async tryRewrite(payload, request) {
|
|
2716
|
+
const { newUrl, pathname, routeData } = findRouteToRewrite({
|
|
2717
|
+
payload,
|
|
2718
|
+
request,
|
|
2719
|
+
routes: this.manifest?.routes.map((r) => r.routeData),
|
|
2720
|
+
trailingSlash: this.manifest.trailingSlash,
|
|
2721
|
+
buildFormat: this.manifest.buildFormat,
|
|
2722
|
+
base: this.manifest.base
|
|
2723
|
+
});
|
|
2724
|
+
const componentInstance = await this.getComponentByRoute(routeData);
|
|
2725
|
+
return { newUrl, pathname, componentInstance, routeData };
|
|
2726
|
+
}
|
|
2727
|
+
async getModuleForRoute(route) {
|
|
2728
|
+
for (const defaultRoute of this.defaultRoutes) {
|
|
2729
|
+
if (route.component === defaultRoute.component) {
|
|
2730
|
+
return {
|
|
2731
|
+
page: () => Promise.resolve(defaultRoute.instance),
|
|
2732
|
+
renderers: []
|
|
2733
|
+
};
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
if (route.type === "redirect") {
|
|
2737
|
+
return RedirectSinglePageBuiltModule;
|
|
2738
|
+
} else {
|
|
2739
|
+
if (this.manifest.pageMap) {
|
|
2740
|
+
const importComponentInstance = this.manifest.pageMap.get(route.component);
|
|
2741
|
+
if (!importComponentInstance) {
|
|
2742
|
+
throw new Error(
|
|
2743
|
+
`Unexpectedly unable to find a component instance for route ${route.route}`
|
|
2744
|
+
);
|
|
2745
|
+
}
|
|
2746
|
+
return await importComponentInstance();
|
|
2747
|
+
} else if (this.manifest.pageModule) {
|
|
2748
|
+
return this.manifest.pageModule;
|
|
2749
|
+
}
|
|
2750
|
+
throw new Error(
|
|
2751
|
+
"Astro couldn't find the correct page to render, probably because it wasn't correctly mapped for SSR usage. This is an internal error, please file an issue."
|
|
2752
|
+
);
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
|
|
2757
|
+
class App {
|
|
2758
|
+
#manifest;
|
|
2759
|
+
#manifestData;
|
|
2760
|
+
#logger = new Logger({
|
|
2761
|
+
dest: consoleLogDestination,
|
|
2762
|
+
level: "info"
|
|
2763
|
+
});
|
|
2764
|
+
#baseWithoutTrailingSlash;
|
|
2765
|
+
#pipeline;
|
|
2766
|
+
#adapterLogger;
|
|
2767
|
+
#renderOptionsDeprecationWarningShown = false;
|
|
2768
|
+
constructor(manifest, streaming = true) {
|
|
2769
|
+
this.#manifest = manifest;
|
|
2770
|
+
this.#manifestData = {
|
|
2771
|
+
routes: manifest.routes.map((route) => route.routeData)
|
|
2772
|
+
};
|
|
2773
|
+
ensure404Route(this.#manifestData);
|
|
2774
|
+
this.#baseWithoutTrailingSlash = removeTrailingForwardSlash(this.#manifest.base);
|
|
2775
|
+
this.#pipeline = this.#createPipeline(this.#manifestData, streaming);
|
|
2776
|
+
this.#adapterLogger = new AstroIntegrationLogger(
|
|
2777
|
+
this.#logger.options,
|
|
2778
|
+
this.#manifest.adapterName
|
|
2779
|
+
);
|
|
2780
|
+
}
|
|
2781
|
+
getAdapterLogger() {
|
|
2782
|
+
return this.#adapterLogger;
|
|
2783
|
+
}
|
|
2784
|
+
/**
|
|
2785
|
+
* Creates a pipeline by reading the stored manifest
|
|
2786
|
+
*
|
|
2787
|
+
* @param manifestData
|
|
2788
|
+
* @param streaming
|
|
2789
|
+
* @private
|
|
2790
|
+
*/
|
|
2791
|
+
#createPipeline(manifestData, streaming = false) {
|
|
2792
|
+
return AppPipeline.create(manifestData, {
|
|
2793
|
+
logger: this.#logger,
|
|
2794
|
+
manifest: this.#manifest,
|
|
2795
|
+
runtimeMode: "production",
|
|
2796
|
+
renderers: this.#manifest.renderers,
|
|
2797
|
+
defaultRoutes: createDefaultRoutes(this.#manifest),
|
|
2798
|
+
resolve: async (specifier) => {
|
|
2799
|
+
if (!(specifier in this.#manifest.entryModules)) {
|
|
2800
|
+
throw new Error(`Unable to resolve [${specifier}]`);
|
|
2801
|
+
}
|
|
2802
|
+
const bundlePath = this.#manifest.entryModules[specifier];
|
|
2803
|
+
if (bundlePath.startsWith("data:") || bundlePath.length === 0) {
|
|
2804
|
+
return bundlePath;
|
|
2805
|
+
} else {
|
|
2806
|
+
return createAssetLink(bundlePath, this.#manifest.base, this.#manifest.assetsPrefix);
|
|
2807
|
+
}
|
|
2808
|
+
},
|
|
2809
|
+
serverLike: true,
|
|
2810
|
+
streaming
|
|
2811
|
+
});
|
|
2812
|
+
}
|
|
2813
|
+
set setManifestData(newManifestData) {
|
|
2814
|
+
this.#manifestData = newManifestData;
|
|
2815
|
+
}
|
|
2816
|
+
removeBase(pathname) {
|
|
2817
|
+
if (pathname.startsWith(this.#manifest.base)) {
|
|
2818
|
+
return pathname.slice(this.#baseWithoutTrailingSlash.length + 1);
|
|
2819
|
+
}
|
|
2820
|
+
return pathname;
|
|
2821
|
+
}
|
|
2822
|
+
/**
|
|
2823
|
+
* It removes the base from the request URL, prepends it with a forward slash and attempts to decoded it.
|
|
2824
|
+
*
|
|
2825
|
+
* If the decoding fails, it logs the error and return the pathname as is.
|
|
2826
|
+
* @param request
|
|
2827
|
+
* @private
|
|
2828
|
+
*/
|
|
2829
|
+
#getPathnameFromRequest(request) {
|
|
2830
|
+
const url = new URL(request.url);
|
|
2831
|
+
const pathname = prependForwardSlash$1(this.removeBase(url.pathname));
|
|
2832
|
+
try {
|
|
2833
|
+
return decodeURI(pathname);
|
|
2834
|
+
} catch (e) {
|
|
2835
|
+
this.getAdapterLogger().error(e.toString());
|
|
2836
|
+
return pathname;
|
|
2837
|
+
}
|
|
2838
|
+
}
|
|
2839
|
+
match(request) {
|
|
2840
|
+
const url = new URL(request.url);
|
|
2841
|
+
if (this.#manifest.assets.has(url.pathname)) return void 0;
|
|
2842
|
+
let pathname = this.#computePathnameFromDomain(request);
|
|
2843
|
+
if (!pathname) {
|
|
2844
|
+
pathname = prependForwardSlash$1(this.removeBase(url.pathname));
|
|
2845
|
+
}
|
|
2846
|
+
let routeData = matchRoute(decodeURI(pathname), this.#manifestData);
|
|
2847
|
+
if (!routeData || routeData.prerender) return void 0;
|
|
2848
|
+
return routeData;
|
|
2849
|
+
}
|
|
2850
|
+
#computePathnameFromDomain(request) {
|
|
2851
|
+
let pathname = void 0;
|
|
2852
|
+
const url = new URL(request.url);
|
|
2853
|
+
if (this.#manifest.i18n && (this.#manifest.i18n.strategy === "domains-prefix-always" || this.#manifest.i18n.strategy === "domains-prefix-other-locales" || this.#manifest.i18n.strategy === "domains-prefix-always-no-redirect")) {
|
|
2854
|
+
let host = request.headers.get("X-Forwarded-Host");
|
|
2855
|
+
let protocol = request.headers.get("X-Forwarded-Proto");
|
|
2856
|
+
if (protocol) {
|
|
2857
|
+
protocol = protocol + ":";
|
|
2858
|
+
} else {
|
|
2859
|
+
protocol = url.protocol;
|
|
2860
|
+
}
|
|
2861
|
+
if (!host) {
|
|
2862
|
+
host = request.headers.get("Host");
|
|
2863
|
+
}
|
|
2864
|
+
if (host && protocol) {
|
|
2865
|
+
host = host.split(":")[0];
|
|
2866
|
+
try {
|
|
2867
|
+
let locale;
|
|
2868
|
+
const hostAsUrl = new URL(`${protocol}//${host}`);
|
|
2869
|
+
for (const [domainKey, localeValue] of Object.entries(
|
|
2870
|
+
this.#manifest.i18n.domainLookupTable
|
|
2871
|
+
)) {
|
|
2872
|
+
const domainKeyAsUrl = new URL(domainKey);
|
|
2873
|
+
if (hostAsUrl.host === domainKeyAsUrl.host && hostAsUrl.protocol === domainKeyAsUrl.protocol) {
|
|
2874
|
+
locale = localeValue;
|
|
2875
|
+
break;
|
|
2876
|
+
}
|
|
2877
|
+
}
|
|
2878
|
+
if (locale) {
|
|
2879
|
+
pathname = prependForwardSlash$1(
|
|
2880
|
+
joinPaths(normalizeTheLocale(locale), this.removeBase(url.pathname))
|
|
2881
|
+
);
|
|
2882
|
+
if (url.pathname.endsWith("/")) {
|
|
2883
|
+
pathname = appendForwardSlash$1(pathname);
|
|
2884
|
+
}
|
|
2885
|
+
}
|
|
2886
|
+
} catch (e) {
|
|
2887
|
+
this.#logger.error(
|
|
2888
|
+
"router",
|
|
2889
|
+
`Astro tried to parse ${protocol}//${host} as an URL, but it threw a parsing error. Check the X-Forwarded-Host and X-Forwarded-Proto headers.`
|
|
2890
|
+
);
|
|
2891
|
+
this.#logger.error("router", `Error: ${e}`);
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2895
|
+
return pathname;
|
|
2896
|
+
}
|
|
2897
|
+
#redirectTrailingSlash(pathname) {
|
|
2898
|
+
const { trailingSlash } = this.#manifest;
|
|
2899
|
+
if (pathname === "/" || pathname.startsWith("/_")) {
|
|
2900
|
+
return pathname;
|
|
2901
|
+
}
|
|
2902
|
+
const path = collapseDuplicateTrailingSlashes(pathname, trailingSlash !== "never");
|
|
2903
|
+
if (path !== pathname) {
|
|
2904
|
+
return path;
|
|
2905
|
+
}
|
|
2906
|
+
if (trailingSlash === "ignore") {
|
|
2907
|
+
return pathname;
|
|
2908
|
+
}
|
|
2909
|
+
if (trailingSlash === "always" && !hasFileExtension$1(pathname)) {
|
|
2910
|
+
return appendForwardSlash$1(pathname);
|
|
2911
|
+
}
|
|
2912
|
+
if (trailingSlash === "never") {
|
|
2913
|
+
return removeTrailingForwardSlash(pathname);
|
|
2914
|
+
}
|
|
2915
|
+
return pathname;
|
|
2916
|
+
}
|
|
2917
|
+
async render(request, renderOptions) {
|
|
2918
|
+
let routeData;
|
|
2919
|
+
let locals;
|
|
2920
|
+
let clientAddress;
|
|
2921
|
+
let addCookieHeader;
|
|
2922
|
+
const url = new URL(request.url);
|
|
2923
|
+
const redirect = this.#redirectTrailingSlash(url.pathname);
|
|
2924
|
+
if (redirect !== url.pathname) {
|
|
2925
|
+
const status = request.method === "GET" ? 301 : 308;
|
|
2926
|
+
return new Response(redirectTemplate({ status, location: redirect, from: request.url }), {
|
|
2927
|
+
status,
|
|
2928
|
+
headers: {
|
|
2929
|
+
location: redirect + url.search
|
|
2930
|
+
}
|
|
2931
|
+
});
|
|
2932
|
+
}
|
|
2933
|
+
addCookieHeader = renderOptions?.addCookieHeader;
|
|
2934
|
+
clientAddress = renderOptions?.clientAddress ?? Reflect.get(request, clientAddressSymbol);
|
|
2935
|
+
routeData = renderOptions?.routeData;
|
|
2936
|
+
locals = renderOptions?.locals;
|
|
2937
|
+
if (routeData) {
|
|
2938
|
+
this.#logger.debug(
|
|
2939
|
+
"router",
|
|
2940
|
+
"The adapter " + this.#manifest.adapterName + " provided a custom RouteData for ",
|
|
2941
|
+
request.url
|
|
2942
|
+
);
|
|
2943
|
+
this.#logger.debug("router", "RouteData:\n" + routeData);
|
|
2944
|
+
}
|
|
2945
|
+
if (locals) {
|
|
2946
|
+
if (typeof locals !== "object") {
|
|
2947
|
+
const error = new AstroError(LocalsNotAnObject);
|
|
2948
|
+
this.#logger.error(null, error.stack);
|
|
2949
|
+
return this.#renderError(request, { status: 500, error, clientAddress });
|
|
2950
|
+
}
|
|
2951
|
+
}
|
|
2952
|
+
if (!routeData) {
|
|
2953
|
+
routeData = this.match(request);
|
|
2954
|
+
this.#logger.debug("router", "Astro matched the following route for " + request.url);
|
|
2955
|
+
this.#logger.debug("router", "RouteData:\n" + routeData);
|
|
2956
|
+
}
|
|
2957
|
+
if (!routeData) {
|
|
2958
|
+
this.#logger.debug("router", "Astro hasn't found routes that match " + request.url);
|
|
2959
|
+
this.#logger.debug("router", "Here's the available routes:\n", this.#manifestData);
|
|
2960
|
+
return this.#renderError(request, { locals, status: 404, clientAddress });
|
|
2961
|
+
}
|
|
2962
|
+
const pathname = this.#getPathnameFromRequest(request);
|
|
2963
|
+
const defaultStatus = this.#getDefaultStatusCode(routeData, pathname);
|
|
2964
|
+
let response;
|
|
2965
|
+
let session;
|
|
2966
|
+
try {
|
|
2967
|
+
const mod = await this.#pipeline.getModuleForRoute(routeData);
|
|
2968
|
+
const renderContext = await RenderContext.create({
|
|
2969
|
+
pipeline: this.#pipeline,
|
|
2970
|
+
locals,
|
|
2971
|
+
pathname,
|
|
2972
|
+
request,
|
|
2973
|
+
routeData,
|
|
2974
|
+
status: defaultStatus,
|
|
2975
|
+
clientAddress
|
|
2976
|
+
});
|
|
2977
|
+
session = renderContext.session;
|
|
2978
|
+
response = await renderContext.render(await mod.page());
|
|
2979
|
+
} catch (err) {
|
|
2980
|
+
this.#logger.error(null, err.stack || err.message || String(err));
|
|
2981
|
+
return this.#renderError(request, { locals, status: 500, error: err, clientAddress });
|
|
2982
|
+
} finally {
|
|
2983
|
+
await session?.[PERSIST_SYMBOL]();
|
|
2984
|
+
}
|
|
2985
|
+
if (REROUTABLE_STATUS_CODES.includes(response.status) && response.headers.get(REROUTE_DIRECTIVE_HEADER) !== "no") {
|
|
2986
|
+
return this.#renderError(request, {
|
|
2987
|
+
locals,
|
|
2988
|
+
response,
|
|
2989
|
+
status: response.status,
|
|
2990
|
+
// We don't have an error to report here. Passing null means we pass nothing intentionally
|
|
2991
|
+
// while undefined means there's no error
|
|
2992
|
+
error: response.status === 500 ? null : void 0,
|
|
2993
|
+
clientAddress
|
|
2994
|
+
});
|
|
2995
|
+
}
|
|
2996
|
+
if (response.headers.has(REROUTE_DIRECTIVE_HEADER)) {
|
|
2997
|
+
response.headers.delete(REROUTE_DIRECTIVE_HEADER);
|
|
2998
|
+
}
|
|
2999
|
+
if (addCookieHeader) {
|
|
3000
|
+
for (const setCookieHeaderValue of App.getSetCookieFromResponse(response)) {
|
|
3001
|
+
response.headers.append("set-cookie", setCookieHeaderValue);
|
|
3002
|
+
}
|
|
3003
|
+
}
|
|
3004
|
+
Reflect.set(response, responseSentSymbol$1, true);
|
|
3005
|
+
return response;
|
|
3006
|
+
}
|
|
3007
|
+
setCookieHeaders(response) {
|
|
3008
|
+
return getSetCookiesFromResponse(response);
|
|
3009
|
+
}
|
|
3010
|
+
/**
|
|
3011
|
+
* Reads all the cookies written by `Astro.cookie.set()` onto the passed response.
|
|
3012
|
+
* For example,
|
|
3013
|
+
* ```ts
|
|
3014
|
+
* for (const cookie_ of App.getSetCookieFromResponse(response)) {
|
|
3015
|
+
* const cookie: string = cookie_
|
|
3016
|
+
* }
|
|
3017
|
+
* ```
|
|
3018
|
+
* @param response The response to read cookies from.
|
|
3019
|
+
* @returns An iterator that yields key-value pairs as equal-sign-separated strings.
|
|
3020
|
+
*/
|
|
3021
|
+
static getSetCookieFromResponse = getSetCookiesFromResponse;
|
|
3022
|
+
/**
|
|
3023
|
+
* If it is a known error code, try sending the according page (e.g. 404.astro / 500.astro).
|
|
3024
|
+
* This also handles pre-rendered /404 or /500 routes
|
|
3025
|
+
*/
|
|
3026
|
+
async #renderError(request, {
|
|
3027
|
+
locals,
|
|
3028
|
+
status,
|
|
3029
|
+
response: originalResponse,
|
|
3030
|
+
skipMiddleware = false,
|
|
3031
|
+
error,
|
|
3032
|
+
clientAddress
|
|
3033
|
+
}) {
|
|
3034
|
+
const errorRoutePath = `/${status}${this.#manifest.trailingSlash === "always" ? "/" : ""}`;
|
|
3035
|
+
const errorRouteData = matchRoute(errorRoutePath, this.#manifestData);
|
|
3036
|
+
const url = new URL(request.url);
|
|
3037
|
+
if (errorRouteData) {
|
|
3038
|
+
if (errorRouteData.prerender) {
|
|
3039
|
+
const maybeDotHtml = errorRouteData.route.endsWith(`/${status}`) ? ".html" : "";
|
|
3040
|
+
const statusURL = new URL(
|
|
3041
|
+
`${this.#baseWithoutTrailingSlash}/${status}${maybeDotHtml}`,
|
|
3042
|
+
url
|
|
3043
|
+
);
|
|
3044
|
+
if (statusURL.toString() !== request.url) {
|
|
3045
|
+
const response2 = await fetch(statusURL.toString());
|
|
3046
|
+
const override = { status };
|
|
3047
|
+
return this.#mergeResponses(response2, originalResponse, override);
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
const mod = await this.#pipeline.getModuleForRoute(errorRouteData);
|
|
3051
|
+
let session;
|
|
3052
|
+
try {
|
|
3053
|
+
const renderContext = await RenderContext.create({
|
|
3054
|
+
locals,
|
|
3055
|
+
pipeline: this.#pipeline,
|
|
3056
|
+
middleware: skipMiddleware ? NOOP_MIDDLEWARE_FN : void 0,
|
|
3057
|
+
pathname: this.#getPathnameFromRequest(request),
|
|
3058
|
+
request,
|
|
3059
|
+
routeData: errorRouteData,
|
|
3060
|
+
status,
|
|
3061
|
+
props: { error },
|
|
3062
|
+
clientAddress
|
|
3063
|
+
});
|
|
3064
|
+
session = renderContext.session;
|
|
3065
|
+
const response2 = await renderContext.render(await mod.page());
|
|
3066
|
+
return this.#mergeResponses(response2, originalResponse);
|
|
3067
|
+
} catch {
|
|
3068
|
+
if (skipMiddleware === false) {
|
|
3069
|
+
return this.#renderError(request, {
|
|
3070
|
+
locals,
|
|
3071
|
+
status,
|
|
3072
|
+
response: originalResponse,
|
|
3073
|
+
skipMiddleware: true,
|
|
3074
|
+
clientAddress
|
|
3075
|
+
});
|
|
3076
|
+
}
|
|
3077
|
+
} finally {
|
|
3078
|
+
await session?.[PERSIST_SYMBOL]();
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
const response = this.#mergeResponses(new Response(null, { status }), originalResponse);
|
|
3082
|
+
Reflect.set(response, responseSentSymbol$1, true);
|
|
3083
|
+
return response;
|
|
3084
|
+
}
|
|
3085
|
+
#mergeResponses(newResponse, originalResponse, override) {
|
|
3086
|
+
if (!originalResponse) {
|
|
3087
|
+
if (override !== void 0) {
|
|
3088
|
+
return new Response(newResponse.body, {
|
|
3089
|
+
status: override.status,
|
|
3090
|
+
statusText: newResponse.statusText,
|
|
3091
|
+
headers: newResponse.headers
|
|
3092
|
+
});
|
|
3093
|
+
}
|
|
3094
|
+
return newResponse;
|
|
3095
|
+
}
|
|
3096
|
+
const status = override?.status ? override.status : originalResponse.status === 200 ? newResponse.status : originalResponse.status;
|
|
3097
|
+
try {
|
|
3098
|
+
originalResponse.headers.delete("Content-type");
|
|
3099
|
+
} catch {
|
|
3100
|
+
}
|
|
3101
|
+
const mergedHeaders = new Map([
|
|
3102
|
+
...Array.from(newResponse.headers),
|
|
3103
|
+
...Array.from(originalResponse.headers)
|
|
3104
|
+
]);
|
|
3105
|
+
const newHeaders = new Headers();
|
|
3106
|
+
for (const [name, value] of mergedHeaders) {
|
|
3107
|
+
newHeaders.set(name, value);
|
|
3108
|
+
}
|
|
3109
|
+
return new Response(newResponse.body, {
|
|
3110
|
+
status,
|
|
3111
|
+
statusText: status === 200 ? newResponse.statusText : originalResponse.statusText,
|
|
3112
|
+
// If you're looking at here for possible bugs, it means that it's not a bug.
|
|
3113
|
+
// With the middleware, users can meddle with headers, and we should pass to the 404/500.
|
|
3114
|
+
// If users see something weird, it's because they are setting some headers they should not.
|
|
3115
|
+
//
|
|
3116
|
+
// Although, we don't want it to replace the content-type, because the error page must return `text/html`
|
|
3117
|
+
headers: newHeaders
|
|
3118
|
+
});
|
|
3119
|
+
}
|
|
3120
|
+
#getDefaultStatusCode(routeData, pathname) {
|
|
3121
|
+
if (!routeData.pattern.test(pathname)) {
|
|
3122
|
+
for (const fallbackRoute of routeData.fallbackRoutes) {
|
|
3123
|
+
if (fallbackRoute.pattern.test(pathname)) {
|
|
3124
|
+
return 302;
|
|
3125
|
+
}
|
|
3126
|
+
}
|
|
3127
|
+
}
|
|
3128
|
+
const route = removeTrailingForwardSlash(routeData.route);
|
|
3129
|
+
if (route.endsWith("/404")) return 404;
|
|
3130
|
+
if (route.endsWith("/500")) return 500;
|
|
3131
|
+
return 200;
|
|
3132
|
+
}
|
|
3133
|
+
}
|
|
3134
|
+
|
|
3135
|
+
const createOutgoingHttpHeaders = (headers) => {
|
|
3136
|
+
if (!headers) {
|
|
3137
|
+
return void 0;
|
|
3138
|
+
}
|
|
3139
|
+
const nodeHeaders = Object.fromEntries(headers.entries());
|
|
3140
|
+
if (Object.keys(nodeHeaders).length === 0) {
|
|
3141
|
+
return void 0;
|
|
3142
|
+
}
|
|
3143
|
+
if (headers.has("set-cookie")) {
|
|
3144
|
+
const cookieHeaders = headers.getSetCookie();
|
|
3145
|
+
if (cookieHeaders.length > 1) {
|
|
3146
|
+
nodeHeaders["set-cookie"] = cookieHeaders;
|
|
3147
|
+
}
|
|
3148
|
+
}
|
|
3149
|
+
return nodeHeaders;
|
|
3150
|
+
};
|
|
3151
|
+
|
|
3152
|
+
function apply() {
|
|
3153
|
+
if (!globalThis.crypto) {
|
|
3154
|
+
Object.defineProperty(globalThis, "crypto", {
|
|
3155
|
+
value: crypto$1.webcrypto
|
|
3156
|
+
});
|
|
3157
|
+
}
|
|
3158
|
+
if (!globalThis.File) {
|
|
3159
|
+
Object.defineProperty(globalThis, "File", {
|
|
3160
|
+
value: buffer.File
|
|
3161
|
+
});
|
|
3162
|
+
}
|
|
3163
|
+
}
|
|
3164
|
+
|
|
3165
|
+
class NodeApp extends App {
|
|
3166
|
+
match(req) {
|
|
3167
|
+
if (!(req instanceof Request)) {
|
|
3168
|
+
req = NodeApp.createRequest(req, {
|
|
3169
|
+
skipBody: true
|
|
3170
|
+
});
|
|
3171
|
+
}
|
|
3172
|
+
return super.match(req);
|
|
3173
|
+
}
|
|
3174
|
+
render(req, routeDataOrOptions, maybeLocals) {
|
|
3175
|
+
if (!(req instanceof Request)) {
|
|
3176
|
+
req = NodeApp.createRequest(req);
|
|
3177
|
+
}
|
|
3178
|
+
return super.render(req, routeDataOrOptions, maybeLocals);
|
|
3179
|
+
}
|
|
3180
|
+
/**
|
|
3181
|
+
* Converts a NodeJS IncomingMessage into a web standard Request.
|
|
3182
|
+
* ```js
|
|
3183
|
+
* import { NodeApp } from 'astro/app/node';
|
|
3184
|
+
* import { createServer } from 'node:http';
|
|
3185
|
+
*
|
|
3186
|
+
* const server = createServer(async (req, res) => {
|
|
3187
|
+
* const request = NodeApp.createRequest(req);
|
|
3188
|
+
* const response = await app.render(request);
|
|
3189
|
+
* await NodeApp.writeResponse(response, res);
|
|
3190
|
+
* })
|
|
3191
|
+
* ```
|
|
3192
|
+
*/
|
|
3193
|
+
static createRequest(req, { skipBody = false } = {}) {
|
|
3194
|
+
const isEncrypted = "encrypted" in req.socket && req.socket.encrypted;
|
|
3195
|
+
const getFirstForwardedValue = (multiValueHeader) => {
|
|
3196
|
+
return multiValueHeader?.toString()?.split(",").map((e) => e.trim())?.[0];
|
|
3197
|
+
};
|
|
3198
|
+
const forwardedProtocol = getFirstForwardedValue(req.headers["x-forwarded-proto"]);
|
|
3199
|
+
const protocol = forwardedProtocol ?? (isEncrypted ? "https" : "http");
|
|
3200
|
+
const forwardedHostname = getFirstForwardedValue(req.headers["x-forwarded-host"]);
|
|
3201
|
+
const hostname = forwardedHostname ?? req.headers.host ?? req.headers[":authority"];
|
|
3202
|
+
const port = getFirstForwardedValue(req.headers["x-forwarded-port"]);
|
|
3203
|
+
const portInHostname = typeof hostname === "string" && /:\d+$/.test(hostname);
|
|
3204
|
+
const hostnamePort = portInHostname ? hostname : `${hostname}${port ? `:${port}` : ""}`;
|
|
3205
|
+
const url = `${protocol}://${hostnamePort}${req.url}`;
|
|
3206
|
+
const options = {
|
|
3207
|
+
method: req.method || "GET",
|
|
3208
|
+
headers: makeRequestHeaders(req)
|
|
3209
|
+
};
|
|
3210
|
+
const bodyAllowed = options.method !== "HEAD" && options.method !== "GET" && skipBody === false;
|
|
3211
|
+
if (bodyAllowed) {
|
|
3212
|
+
Object.assign(options, makeRequestBody(req));
|
|
3213
|
+
}
|
|
3214
|
+
const request = new Request(url, options);
|
|
3215
|
+
const forwardedClientIp = getFirstForwardedValue(req.headers["x-forwarded-for"]);
|
|
3216
|
+
const clientIp = forwardedClientIp || req.socket?.remoteAddress;
|
|
3217
|
+
if (clientIp) {
|
|
3218
|
+
Reflect.set(request, clientAddressSymbol, clientIp);
|
|
3219
|
+
}
|
|
3220
|
+
return request;
|
|
3221
|
+
}
|
|
3222
|
+
/**
|
|
3223
|
+
* Streams a web-standard Response into a NodeJS Server Response.
|
|
3224
|
+
* ```js
|
|
3225
|
+
* import { NodeApp } from 'astro/app/node';
|
|
3226
|
+
* import { createServer } from 'node:http';
|
|
3227
|
+
*
|
|
3228
|
+
* const server = createServer(async (req, res) => {
|
|
3229
|
+
* const request = NodeApp.createRequest(req);
|
|
3230
|
+
* const response = await app.render(request);
|
|
3231
|
+
* await NodeApp.writeResponse(response, res);
|
|
3232
|
+
* })
|
|
3233
|
+
* ```
|
|
3234
|
+
* @param source WhatWG Response
|
|
3235
|
+
* @param destination NodeJS ServerResponse
|
|
3236
|
+
*/
|
|
3237
|
+
static async writeResponse(source, destination) {
|
|
3238
|
+
const { status, headers, body, statusText } = source;
|
|
3239
|
+
if (!(destination instanceof Http2ServerResponse)) {
|
|
3240
|
+
destination.statusMessage = statusText;
|
|
3241
|
+
}
|
|
3242
|
+
destination.writeHead(status, createOutgoingHttpHeaders(headers));
|
|
3243
|
+
if (!body) return destination.end();
|
|
3244
|
+
try {
|
|
3245
|
+
const reader = body.getReader();
|
|
3246
|
+
destination.on("close", () => {
|
|
3247
|
+
reader.cancel().catch((err) => {
|
|
3248
|
+
console.error(
|
|
3249
|
+
`There was an uncaught error in the middle of the stream while rendering ${destination.req.url}.`,
|
|
3250
|
+
err
|
|
3251
|
+
);
|
|
3252
|
+
});
|
|
3253
|
+
});
|
|
3254
|
+
let result = await reader.read();
|
|
3255
|
+
while (!result.done) {
|
|
3256
|
+
destination.write(result.value);
|
|
3257
|
+
result = await reader.read();
|
|
3258
|
+
}
|
|
3259
|
+
destination.end();
|
|
3260
|
+
} catch (err) {
|
|
3261
|
+
destination.write("Internal server error", () => {
|
|
3262
|
+
err instanceof Error ? destination.destroy(err) : destination.destroy();
|
|
3263
|
+
});
|
|
3264
|
+
}
|
|
3265
|
+
}
|
|
3266
|
+
}
|
|
3267
|
+
function makeRequestHeaders(req) {
|
|
3268
|
+
const headers = new Headers();
|
|
3269
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
3270
|
+
if (value === void 0) {
|
|
3271
|
+
continue;
|
|
3272
|
+
}
|
|
3273
|
+
if (Array.isArray(value)) {
|
|
3274
|
+
for (const item of value) {
|
|
3275
|
+
headers.append(name, item);
|
|
3276
|
+
}
|
|
3277
|
+
} else {
|
|
3278
|
+
headers.append(name, value);
|
|
3279
|
+
}
|
|
3280
|
+
}
|
|
3281
|
+
return headers;
|
|
3282
|
+
}
|
|
3283
|
+
function makeRequestBody(req) {
|
|
3284
|
+
if (req.body !== void 0) {
|
|
3285
|
+
if (typeof req.body === "string" && req.body.length > 0) {
|
|
3286
|
+
return { body: Buffer.from(req.body) };
|
|
3287
|
+
}
|
|
3288
|
+
if (typeof req.body === "object" && req.body !== null && Object.keys(req.body).length > 0) {
|
|
3289
|
+
return { body: Buffer.from(JSON.stringify(req.body)) };
|
|
3290
|
+
}
|
|
3291
|
+
if (typeof req.body === "object" && req.body !== null && typeof req.body[Symbol.asyncIterator] !== "undefined") {
|
|
3292
|
+
return asyncIterableToBodyProps(req.body);
|
|
3293
|
+
}
|
|
3294
|
+
}
|
|
3295
|
+
return asyncIterableToBodyProps(req);
|
|
3296
|
+
}
|
|
3297
|
+
function asyncIterableToBodyProps(iterable) {
|
|
3298
|
+
return {
|
|
3299
|
+
// Node uses undici for the Request implementation. Undici accepts
|
|
3300
|
+
// a non-standard async iterable for the body.
|
|
3301
|
+
// @ts-expect-error
|
|
3302
|
+
body: iterable,
|
|
3303
|
+
// The duplex property is required when using a ReadableStream or async
|
|
3304
|
+
// iterable for the body. The type definitions do not include the duplex
|
|
3305
|
+
// property because they are not up-to-date.
|
|
3306
|
+
duplex: "half"
|
|
3307
|
+
};
|
|
3308
|
+
}
|
|
3309
|
+
|
|
3310
|
+
apply();
|
|
3311
|
+
|
|
3312
|
+
function createAppHandler(app) {
|
|
3313
|
+
const als = new AsyncLocalStorage();
|
|
3314
|
+
const logger = app.getAdapterLogger();
|
|
3315
|
+
process.on("unhandledRejection", (reason) => {
|
|
3316
|
+
const requestUrl = als.getStore();
|
|
3317
|
+
logger.error(`Unhandled rejection while rendering ${requestUrl}`);
|
|
3318
|
+
console.error(reason);
|
|
3319
|
+
});
|
|
3320
|
+
return async (req, res, next, locals) => {
|
|
3321
|
+
let request;
|
|
3322
|
+
try {
|
|
3323
|
+
request = NodeApp.createRequest(req);
|
|
3324
|
+
} catch (err) {
|
|
3325
|
+
logger.error(`Could not render ${req.url}`);
|
|
3326
|
+
console.error(err);
|
|
3327
|
+
res.statusCode = 500;
|
|
3328
|
+
res.end("Internal Server Error");
|
|
3329
|
+
return;
|
|
3330
|
+
}
|
|
3331
|
+
const routeData = app.match(request);
|
|
3332
|
+
if (routeData) {
|
|
3333
|
+
const response = await als.run(
|
|
3334
|
+
request.url,
|
|
3335
|
+
() => app.render(request, {
|
|
3336
|
+
addCookieHeader: true,
|
|
3337
|
+
locals,
|
|
3338
|
+
routeData
|
|
3339
|
+
})
|
|
3340
|
+
);
|
|
3341
|
+
await NodeApp.writeResponse(response, res);
|
|
3342
|
+
} else if (next) {
|
|
3343
|
+
return next();
|
|
3344
|
+
} else {
|
|
3345
|
+
const response = await app.render(req);
|
|
3346
|
+
await NodeApp.writeResponse(response, res);
|
|
3347
|
+
}
|
|
3348
|
+
};
|
|
3349
|
+
}
|
|
3350
|
+
|
|
3351
|
+
function createMiddleware(app) {
|
|
3352
|
+
const handler = createAppHandler(app);
|
|
3353
|
+
const logger = app.getAdapterLogger();
|
|
3354
|
+
return async (...args) => {
|
|
3355
|
+
const [req, res, next, locals] = args;
|
|
3356
|
+
if (req instanceof Error) {
|
|
3357
|
+
const error = req;
|
|
3358
|
+
if (next) {
|
|
3359
|
+
return next(error);
|
|
3360
|
+
} else {
|
|
3361
|
+
throw error;
|
|
3362
|
+
}
|
|
3363
|
+
}
|
|
3364
|
+
try {
|
|
3365
|
+
await handler(req, res, next, locals);
|
|
3366
|
+
} catch (err) {
|
|
3367
|
+
logger.error(`Could not render ${req.url}`);
|
|
3368
|
+
console.error(err);
|
|
3369
|
+
if (!res.headersSent) {
|
|
3370
|
+
res.writeHead(500, `Server error`);
|
|
3371
|
+
res.end();
|
|
3372
|
+
}
|
|
3373
|
+
}
|
|
3374
|
+
};
|
|
3375
|
+
}
|
|
3376
|
+
|
|
3377
|
+
const wildcardHosts = /* @__PURE__ */ new Set(["0.0.0.0", "::", "0000:0000:0000:0000:0000:0000:0000:0000"]);
|
|
3378
|
+
async function logListeningOn(logger, server, configuredHost) {
|
|
3379
|
+
await new Promise((resolve) => server.once("listening", resolve));
|
|
3380
|
+
const protocol = server instanceof https.Server ? "https" : "http";
|
|
3381
|
+
const host = getResolvedHostForHttpServer(configuredHost);
|
|
3382
|
+
const { port } = server.address();
|
|
3383
|
+
const address = getNetworkAddress(protocol, host, port);
|
|
3384
|
+
if (host === void 0 || wildcardHosts.has(host)) {
|
|
3385
|
+
logger.info(
|
|
3386
|
+
`Server listening on
|
|
3387
|
+
local: ${address.local[0]}
|
|
3388
|
+
network: ${address.network[0]}
|
|
3389
|
+
`
|
|
3390
|
+
);
|
|
3391
|
+
} else {
|
|
3392
|
+
logger.info(`Server listening on ${address.local[0]}`);
|
|
3393
|
+
}
|
|
3394
|
+
}
|
|
3395
|
+
function getResolvedHostForHttpServer(host) {
|
|
3396
|
+
if (host === false) {
|
|
3397
|
+
return "localhost";
|
|
3398
|
+
} else if (host === true) {
|
|
3399
|
+
return void 0;
|
|
3400
|
+
} else {
|
|
3401
|
+
return host;
|
|
3402
|
+
}
|
|
3403
|
+
}
|
|
3404
|
+
function getNetworkAddress(protocol = "http", hostname, port, base) {
|
|
3405
|
+
const NetworkAddress = {
|
|
3406
|
+
local: [],
|
|
3407
|
+
network: []
|
|
3408
|
+
};
|
|
3409
|
+
Object.values(os.networkInterfaces()).flatMap((nInterface) => nInterface ?? []).filter(
|
|
3410
|
+
(detail) => detail && detail.address && (detail.family === "IPv4" || // @ts-expect-error Node 18.0 - 18.3 returns number
|
|
3411
|
+
detail.family === 4)
|
|
3412
|
+
).forEach((detail) => {
|
|
3413
|
+
let host = detail.address.replace(
|
|
3414
|
+
"127.0.0.1",
|
|
3415
|
+
hostname === void 0 || wildcardHosts.has(hostname) ? "localhost" : hostname
|
|
3416
|
+
);
|
|
3417
|
+
if (host.includes(":")) {
|
|
3418
|
+
host = `[${host}]`;
|
|
3419
|
+
}
|
|
3420
|
+
const url = `${protocol}://${host}:${port}${""}`;
|
|
3421
|
+
if (detail.address.includes("127.0.0.1")) {
|
|
3422
|
+
NetworkAddress.local.push(url);
|
|
3423
|
+
} else {
|
|
3424
|
+
NetworkAddress.network.push(url);
|
|
3425
|
+
}
|
|
3426
|
+
});
|
|
3427
|
+
return NetworkAddress;
|
|
3428
|
+
}
|
|
3429
|
+
|
|
3430
|
+
const WITH_FILE_EXT = /\/[^/]+\.\w+$/;
|
|
3431
|
+
function hasFileExtension(path) {
|
|
3432
|
+
return WITH_FILE_EXT.test(path);
|
|
3433
|
+
}
|
|
3434
|
+
|
|
3435
|
+
function createStaticHandler(app, options) {
|
|
3436
|
+
const client = resolveClientDir(options);
|
|
3437
|
+
return (req, res, ssr) => {
|
|
3438
|
+
if (req.url) {
|
|
3439
|
+
const [urlPath, urlQuery] = req.url.split("?");
|
|
3440
|
+
const filePath = path.join(client, app.removeBase(urlPath));
|
|
3441
|
+
let isDirectory = false;
|
|
3442
|
+
try {
|
|
3443
|
+
isDirectory = fs.lstatSync(filePath).isDirectory();
|
|
3444
|
+
} catch {
|
|
3445
|
+
}
|
|
3446
|
+
const { trailingSlash = "ignore" } = options;
|
|
3447
|
+
const hasSlash = urlPath.endsWith("/");
|
|
3448
|
+
let pathname = urlPath;
|
|
3449
|
+
switch (trailingSlash) {
|
|
3450
|
+
case "never": {
|
|
3451
|
+
if (isDirectory && urlPath !== "/" && hasSlash) {
|
|
3452
|
+
pathname = urlPath.slice(0, -1) + (urlQuery ? "?" + urlQuery : "");
|
|
3453
|
+
res.statusCode = 301;
|
|
3454
|
+
res.setHeader("Location", pathname);
|
|
3455
|
+
return res.end();
|
|
3456
|
+
}
|
|
3457
|
+
if (isDirectory && !hasSlash) {
|
|
3458
|
+
pathname = `${urlPath}/index.html`;
|
|
3459
|
+
}
|
|
3460
|
+
break;
|
|
3461
|
+
}
|
|
3462
|
+
case "ignore": {
|
|
3463
|
+
if (isDirectory && !hasSlash) {
|
|
3464
|
+
pathname = `${urlPath}/index.html`;
|
|
3465
|
+
}
|
|
3466
|
+
break;
|
|
3467
|
+
}
|
|
3468
|
+
case "always": {
|
|
3469
|
+
if (!hasSlash && !hasFileExtension(urlPath)) {
|
|
3470
|
+
pathname = urlPath + "/" + (urlQuery ? "?" + urlQuery : "");
|
|
3471
|
+
res.statusCode = 301;
|
|
3472
|
+
res.setHeader("Location", pathname);
|
|
3473
|
+
return res.end();
|
|
3474
|
+
}
|
|
3475
|
+
break;
|
|
3476
|
+
}
|
|
3477
|
+
}
|
|
3478
|
+
pathname = prependForwardSlash(app.removeBase(pathname));
|
|
3479
|
+
const stream = send(req, pathname, {
|
|
3480
|
+
root: client,
|
|
3481
|
+
dotfiles: pathname.startsWith("/.well-known/") ? "allow" : "deny"
|
|
3482
|
+
});
|
|
3483
|
+
let forwardError = false;
|
|
3484
|
+
stream.on("error", (err) => {
|
|
3485
|
+
if (forwardError) {
|
|
3486
|
+
console.error(err.toString());
|
|
3487
|
+
res.writeHead(500);
|
|
3488
|
+
res.end("Internal server error");
|
|
3489
|
+
return;
|
|
3490
|
+
}
|
|
3491
|
+
ssr();
|
|
3492
|
+
});
|
|
3493
|
+
stream.on("headers", (_res) => {
|
|
3494
|
+
if (pathname.startsWith(`/${options.assets}/`)) {
|
|
3495
|
+
_res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
|
3496
|
+
}
|
|
3497
|
+
});
|
|
3498
|
+
stream.on("file", () => {
|
|
3499
|
+
forwardError = true;
|
|
3500
|
+
});
|
|
3501
|
+
stream.pipe(res);
|
|
3502
|
+
} else {
|
|
3503
|
+
ssr();
|
|
3504
|
+
}
|
|
3505
|
+
};
|
|
3506
|
+
}
|
|
3507
|
+
function resolveClientDir(options) {
|
|
3508
|
+
const clientURLRaw = new URL(options.client);
|
|
3509
|
+
const serverURLRaw = new URL(options.server);
|
|
3510
|
+
const rel = path.relative(url.fileURLToPath(serverURLRaw), url.fileURLToPath(clientURLRaw));
|
|
3511
|
+
const serverFolder = path.basename(options.server);
|
|
3512
|
+
let serverEntryFolderURL = path.dirname(import.meta.url);
|
|
3513
|
+
while (!serverEntryFolderURL.endsWith(serverFolder)) {
|
|
3514
|
+
serverEntryFolderURL = path.dirname(serverEntryFolderURL);
|
|
3515
|
+
}
|
|
3516
|
+
const serverEntryURL = serverEntryFolderURL + "/entry.mjs";
|
|
3517
|
+
const clientURL = new URL(appendForwardSlash(rel), serverEntryURL);
|
|
3518
|
+
const client = url.fileURLToPath(clientURL);
|
|
3519
|
+
return client;
|
|
3520
|
+
}
|
|
3521
|
+
function prependForwardSlash(pth) {
|
|
3522
|
+
return pth.startsWith("/") ? pth : "/" + pth;
|
|
3523
|
+
}
|
|
3524
|
+
function appendForwardSlash(pth) {
|
|
3525
|
+
return pth.endsWith("/") ? pth : pth + "/";
|
|
3526
|
+
}
|
|
3527
|
+
|
|
3528
|
+
const hostOptions = (host) => {
|
|
3529
|
+
if (typeof host === "boolean") {
|
|
3530
|
+
return host ? "0.0.0.0" : "localhost";
|
|
3531
|
+
}
|
|
3532
|
+
return host;
|
|
3533
|
+
};
|
|
3534
|
+
function standalone(app, options) {
|
|
3535
|
+
const port = process.env.PORT ? Number(process.env.PORT) : options.port ?? 8080;
|
|
3536
|
+
const host = process.env.HOST ?? hostOptions(options.host);
|
|
3537
|
+
const handler = createStandaloneHandler(app, options);
|
|
3538
|
+
const server = createServer(handler, host, port);
|
|
3539
|
+
server.server.listen(port, host);
|
|
3540
|
+
if (process.env.ASTRO_NODE_LOGGING !== "disabled") {
|
|
3541
|
+
logListeningOn(app.getAdapterLogger(), server.server, host);
|
|
3542
|
+
}
|
|
3543
|
+
return {
|
|
3544
|
+
server,
|
|
3545
|
+
done: server.closed()
|
|
3546
|
+
};
|
|
3547
|
+
}
|
|
3548
|
+
function createStandaloneHandler(app, options) {
|
|
3549
|
+
const appHandler = createAppHandler(app);
|
|
3550
|
+
const staticHandler = createStaticHandler(app, options);
|
|
3551
|
+
return (req, res) => {
|
|
3552
|
+
try {
|
|
3553
|
+
decodeURI(req.url);
|
|
3554
|
+
} catch {
|
|
3555
|
+
res.writeHead(400);
|
|
3556
|
+
res.end("Bad request.");
|
|
3557
|
+
return;
|
|
3558
|
+
}
|
|
3559
|
+
staticHandler(req, res, () => appHandler(req, res));
|
|
3560
|
+
};
|
|
3561
|
+
}
|
|
3562
|
+
function createServer(listener, host, port) {
|
|
3563
|
+
let httpServer;
|
|
3564
|
+
if (process.env.SERVER_CERT_PATH && process.env.SERVER_KEY_PATH) {
|
|
3565
|
+
httpServer = https.createServer(
|
|
3566
|
+
{
|
|
3567
|
+
key: fs.readFileSync(process.env.SERVER_KEY_PATH),
|
|
3568
|
+
cert: fs.readFileSync(process.env.SERVER_CERT_PATH)
|
|
3569
|
+
},
|
|
3570
|
+
listener
|
|
3571
|
+
);
|
|
3572
|
+
} else {
|
|
3573
|
+
httpServer = http.createServer(listener);
|
|
3574
|
+
}
|
|
3575
|
+
enableDestroy(httpServer);
|
|
3576
|
+
const closed = new Promise((resolve, reject) => {
|
|
3577
|
+
httpServer.addListener("close", resolve);
|
|
3578
|
+
httpServer.addListener("error", reject);
|
|
3579
|
+
});
|
|
3580
|
+
const previewable = {
|
|
3581
|
+
host,
|
|
3582
|
+
port,
|
|
3583
|
+
closed() {
|
|
3584
|
+
return closed;
|
|
3585
|
+
},
|
|
3586
|
+
async stop() {
|
|
3587
|
+
await new Promise((resolve, reject) => {
|
|
3588
|
+
httpServer.destroy((err) => err ? reject(err) : resolve(void 0));
|
|
3589
|
+
});
|
|
3590
|
+
}
|
|
3591
|
+
};
|
|
3592
|
+
return {
|
|
3593
|
+
server: httpServer,
|
|
3594
|
+
...previewable
|
|
3595
|
+
};
|
|
3596
|
+
}
|
|
3597
|
+
|
|
3598
|
+
function createExports(manifest, options) {
|
|
3599
|
+
const app = new NodeApp(manifest);
|
|
3600
|
+
options.trailingSlash = manifest.trailingSlash;
|
|
3601
|
+
return {
|
|
3602
|
+
options,
|
|
3603
|
+
handler: options.mode === "middleware" ? createMiddleware(app) : createStandaloneHandler(app, options),
|
|
3604
|
+
startServer: () => standalone(app, options)
|
|
3605
|
+
};
|
|
3606
|
+
}
|
|
3607
|
+
function start(manifest, options) {
|
|
3608
|
+
if (options.mode !== "standalone" || process.env.ASTRO_NODE_AUTOSTART === "disabled") {
|
|
3609
|
+
return;
|
|
3610
|
+
}
|
|
3611
|
+
const app = new NodeApp(manifest);
|
|
3612
|
+
standalone(app, options);
|
|
3613
|
+
}
|
|
3614
|
+
|
|
3615
|
+
const serverEntrypointModule = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
|
|
3616
|
+
__proto__: null,
|
|
3617
|
+
createExports,
|
|
3618
|
+
start
|
|
3619
|
+
}, Symbol.toStringTag, { value: 'Module' }));
|
|
3620
|
+
|
|
3621
|
+
export { start as a, createExports as c, serverEntrypointModule as s };
|