@torpor/build 1.10.0 → 1.11.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/README.md +1 -1
- package/dist/{SessionHelper-MaodMaLU.d.mts → CacheOptions-C4-ebVt9.d.mts} +58 -8
- package/dist/CacheOptions-C4-ebVt9.d.mts.map +1 -0
- package/dist/{MiddlewareFunction-7rIvFkjl.d.mts → MiddlewareFunction-DMYxjzF4.d.mts} +25 -2
- package/dist/MiddlewareFunction-DMYxjzF4.d.mts.map +1 -0
- package/dist/{Router-Bxm7K20d.d.mts → Router-DyK3DTWQ.d.mts} +2 -2
- package/dist/{Router-Bxm7K20d.d.mts.map → Router-DyK3DTWQ.d.mts.map} +1 -1
- package/dist/{Server-Djd9-NkU.mjs → Server-BCijhgZp.mjs} +3 -3
- package/dist/{Server-Djd9-NkU.mjs.map → Server-BCijhgZp.mjs.map} +1 -1
- package/dist/{Server-hwbZ7P2g.d.mts → Server-ClwvuilS.d.mts} +2 -2
- package/dist/{Server-hwbZ7P2g.d.mts.map → Server-ClwvuilS.d.mts.map} +1 -1
- package/dist/{ServerEvent-L0rT_mBJ.mjs → ServerEvent-BBRkd4Ya.mjs} +127 -31
- package/dist/ServerEvent-BBRkd4Ya.mjs.map +1 -0
- package/dist/{ServerHook-CyVEr5OL.d.mts → ServerHook-DY-NSG6n.d.mts} +2 -2
- package/dist/{ServerHook-CyVEr5OL.d.mts.map → ServerHook-DY-NSG6n.d.mts.map} +1 -1
- package/dist/{ServerLoadEvent-F60w1TZt.d.mts → ServerLoadEvent-CpcgsKCU.d.mts} +19 -5
- package/dist/ServerLoadEvent-CpcgsKCU.d.mts.map +1 -0
- package/dist/{Site-CAeAqjkk.d.mts → Site-BEMQW1_y.d.mts} +31 -11
- package/dist/Site-BEMQW1_y.d.mts.map +1 -0
- package/dist/{basePath-DQnbHc7o.mjs → basePath-B6hmOMl4.mjs} +89 -4
- package/dist/basePath-B6hmOMl4.mjs.map +1 -0
- package/dist/bin/index.js +1 -1
- package/dist/clientEntry.mjs +10 -5
- package/dist/clientEntry.mjs.map +1 -1
- package/dist/dev.d.mts +2 -2
- package/dist/dev.mjs +2 -2
- package/dist/{devPlugin-D9b5uhzm.mjs → devPlugin-BGrTpcC2.mjs} +3 -3
- package/dist/{devPlugin-D9b5uhzm.mjs.map → devPlugin-BGrTpcC2.mjs.map} +1 -1
- package/dist/discovery.d.mts +1 -1
- package/dist/discovery.mjs +1 -1
- package/dist/index.d.mts +22 -6
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +10 -0
- package/dist/index.mjs.map +1 -1
- package/dist/{load-BODDzmH0.mjs → load-Dw187nJ_.mjs} +95 -52
- package/dist/load-Dw187nJ_.mjs.map +1 -0
- package/dist/nav.d.mts +2 -1
- package/dist/nav.d.mts.map +1 -1
- package/dist/nav.mjs +3 -3
- package/dist/nodeDev.d.mts +1 -1
- package/dist/nodeDev.mjs +1 -1
- package/dist/openapi.d.mts +2 -2
- package/dist/{read-DxMVAh5Y.mjs → read-CPW2iPum.mjs} +21 -2
- package/dist/read-CPW2iPum.mjs.map +1 -0
- package/dist/{response-C5EZsszY.mjs → response-B4UoOJvv.mjs} +3 -24
- package/dist/response-B4UoOJvv.mjs.map +1 -0
- package/dist/response.mjs +2 -2
- package/dist/run.d.mts +1 -1
- package/dist/run.d.mts.map +1 -1
- package/dist/run.mjs +1 -1
- package/dist/{runHooks-D5p1Rh7i.mjs → runHooks-C7kt7SEo.mjs} +36 -2
- package/dist/runHooks-C7kt7SEo.mjs.map +1 -0
- package/dist/{runOpenApi-BZ314IiI.mjs → runOpenApi-DK-QnYEr.mjs} +239 -18
- package/dist/runOpenApi-DK-QnYEr.mjs.map +1 -0
- package/dist/server/Server.d.mts +1 -1
- package/dist/server/Server.mjs +1 -1
- package/dist/server.d.mts +30 -6
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +47 -3
- package/dist/server.mjs.map +1 -1
- package/dist/{serverEntry-Da1PFlIU.d.mts → serverEntry-BFad1k1C.d.mts} +3 -3
- package/dist/serverEntry-BFad1k1C.d.mts.map +1 -0
- package/dist/{serverEntry-8YnfpKTj.mjs → serverEntry-DAT7o7o2.mjs} +3 -5
- package/dist/serverEntry-DAT7o7o2.mjs.map +1 -0
- package/dist/serverEntry.d.mts +1 -1
- package/dist/serverEntry.mjs +1 -1
- package/dist/{serverHandlers-Ba_35jpO.mjs → serverHandlers-B1L8I72-.mjs} +398 -192
- package/dist/serverHandlers-B1L8I72-.mjs.map +1 -0
- package/dist/{sitemap-CnIYTLhu.d.mts → sitemap-CKmagPyL.d.mts} +2 -2
- package/dist/{sitemap-CnIYTLhu.d.mts.map → sitemap-CKmagPyL.d.mts.map} +1 -1
- package/dist/{sitemap-4imxJVrG.mjs → sitemap-DdzFjGlo.mjs} +2 -2
- package/dist/{sitemap-4imxJVrG.mjs.map → sitemap-DdzFjGlo.mjs.map} +1 -1
- package/dist/state.d.mts +1 -4
- package/dist/state.d.mts.map +1 -1
- package/dist/state.mjs +1 -1
- package/dist/test.d.mts +2 -2
- package/dist/test.mjs +2 -2
- package/dist/{unprocessable-DwAG44Rh.mjs → unprocessable-BZXwyN0n.mjs} +23 -2
- package/dist/unprocessable-BZXwyN0n.mjs.map +1 -0
- package/package.json +3 -3
- package/src/types/manifest.d.ts +3 -0
- package/dist/MiddlewareFunction-7rIvFkjl.d.mts.map +0 -1
- package/dist/ServerEvent-L0rT_mBJ.mjs.map +0 -1
- package/dist/ServerLoadEvent-F60w1TZt.d.mts.map +0 -1
- package/dist/SessionHelper-MaodMaLU.d.mts.map +0 -1
- package/dist/Site-CAeAqjkk.d.mts.map +0 -1
- package/dist/_page-CW6SLuT4.mjs +0 -14
- package/dist/_page-CW6SLuT4.mjs.map +0 -1
- package/dist/basePath-DQnbHc7o.mjs.map +0 -1
- package/dist/load-BODDzmH0.mjs.map +0 -1
- package/dist/read-DxMVAh5Y.mjs.map +0 -1
- package/dist/response-C5EZsszY.mjs.map +0 -1
- package/dist/runHooks-D5p1Rh7i.mjs.map +0 -1
- package/dist/runOpenApi-BZ314IiI.mjs.map +0 -1
- package/dist/serverEntry-8YnfpKTj.mjs.map +0 -1
- package/dist/serverEntry-Da1PFlIU.d.mts.map +0 -1
- package/dist/serverHandlers-Ba_35jpO.mjs.map +0 -1
- package/dist/unprocessable-DwAG44Rh.mjs.map +0 -1
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import { a as rewriteBaseInHtml,
|
|
2
|
-
import {
|
|
1
|
+
import { a as rewriteBaseInHtml, s as stripBaseFromUrl } from "./basePath-B6hmOMl4.mjs";
|
|
2
|
+
import { a as findErrorRoute, i as parseErrorStatus, n as DATA_REQUEST_HEADER, r as DATA_REUSE_HEADER, t as readResponseBody } from "./read-CPW2iPum.mjs";
|
|
3
3
|
import { a as splitDeferred, r as jsonForScript } from "./internal-BItAKrmV.mjs";
|
|
4
|
-
import { n as ok, r as notFound, t as unprocessable } from "./unprocessable-
|
|
5
|
-
import { t as runHooks } from "./runHooks-
|
|
4
|
+
import { i as forbidden, n as ok, r as notFound, t as unprocessable } from "./unprocessable-BZXwyN0n.mjs";
|
|
5
|
+
import { a as setRequestPreloads, i as setRequestBase, n as requestBase, r as requestPreloads, t as runHooks } from "./runHooks-C7kt7SEo.mjs";
|
|
6
6
|
import { n as ValidationError, t as validate } from "./validate-Ok4krlkX.mjs";
|
|
7
|
-
import { $watch } from "@torpor/view/ssr";
|
|
8
7
|
//#region src/form/formDataToRecord.ts
|
|
9
8
|
/**
|
|
10
9
|
* Converts the submitted fields of a form request into a plain record: one
|
|
@@ -17,25 +16,15 @@ import { $watch } from "@torpor/view/ssr";
|
|
|
17
16
|
*/
|
|
18
17
|
async function formDataToRecord(request) {
|
|
19
18
|
const formData = request instanceof FormData ? request : await request.formData();
|
|
20
|
-
const result =
|
|
19
|
+
const result = Object.create(null);
|
|
21
20
|
for (const key of formData.keys()) {
|
|
22
|
-
if (key
|
|
21
|
+
if (Object.hasOwn(result, key)) continue;
|
|
23
22
|
const values = formData.getAll(key);
|
|
24
23
|
result[key] = values.length > 1 ? values : values[0];
|
|
25
24
|
}
|
|
26
25
|
return result;
|
|
27
26
|
}
|
|
28
27
|
//#endregion
|
|
29
|
-
//#region src/state/$serverPage.ts
|
|
30
|
-
const PAGE_SYMBOL = Symbol.for("torp.Page");
|
|
31
|
-
const $page = globalThis[PAGE_SYMBOL] ??= $watch({
|
|
32
|
-
status: 404,
|
|
33
|
-
url: new URL("http://localhost"),
|
|
34
|
-
form: void 0,
|
|
35
|
-
flash: void 0,
|
|
36
|
-
error: { message: "" }
|
|
37
|
-
});
|
|
38
|
-
//#endregion
|
|
39
28
|
//#region src/utils/searchParamsToRecord.ts
|
|
40
29
|
/**
|
|
41
30
|
* Converts a URL's query string into a plain record: one string per param,
|
|
@@ -45,9 +34,9 @@ const $page = globalThis[PAGE_SYMBOL] ??= $watch({
|
|
|
45
34
|
* @returns The param values
|
|
46
35
|
*/
|
|
47
36
|
function searchParamsToRecord(searchParams) {
|
|
48
|
-
const result =
|
|
37
|
+
const result = Object.create(null);
|
|
49
38
|
for (const key of searchParams.keys()) {
|
|
50
|
-
if (key
|
|
39
|
+
if (Object.hasOwn(result, key)) continue;
|
|
51
40
|
const values = searchParams.getAll(key);
|
|
52
41
|
result[key] = values.length > 1 ? values : values[0];
|
|
53
42
|
}
|
|
@@ -58,9 +47,15 @@ function searchParamsToRecord(searchParams) {
|
|
|
58
47
|
/**
|
|
59
48
|
* Gets the standard schema declared for a handler or action, if any. The
|
|
60
49
|
* schemas map is keyed by name; the runtime treats it as a loose record.
|
|
50
|
+
*
|
|
51
|
+
* Only own keys are considered: a plain read would resolve names like
|
|
52
|
+
* `toString` or `constructor` to members of `Object.prototype`, handing that
|
|
53
|
+
* function to `validate()` as though it were a schema.
|
|
61
54
|
*/
|
|
62
55
|
function endpointSchema(endPoint, name) {
|
|
63
|
-
|
|
56
|
+
const schemas = endPoint.schema;
|
|
57
|
+
if (schemas === void 0 || !Object.hasOwn(schemas, name)) return void 0;
|
|
58
|
+
return schemas[name];
|
|
64
59
|
}
|
|
65
60
|
/**
|
|
66
61
|
* Validates the route params against the endpoint's `params` schema, if it
|
|
@@ -154,6 +149,135 @@ function mergeHead(template, head) {
|
|
|
154
149
|
return html.replace("%COMPONENT_HEAD%", headHtml);
|
|
155
150
|
}
|
|
156
151
|
//#endregion
|
|
152
|
+
//#region src/site/requestPage.ts
|
|
153
|
+
const pages = /* @__PURE__ */ new WeakMap();
|
|
154
|
+
/**
|
|
155
|
+
* Gets the page state of the request `ev`, creating it on first use. Page
|
|
156
|
+
* renders pass it to their components as `$context.$page`.
|
|
157
|
+
*/
|
|
158
|
+
function pageOf(ev) {
|
|
159
|
+
let page = pages.get(ev);
|
|
160
|
+
if (!page) {
|
|
161
|
+
page = {
|
|
162
|
+
status: 404,
|
|
163
|
+
url: ev.url,
|
|
164
|
+
form: void 0,
|
|
165
|
+
flash: void 0,
|
|
166
|
+
error: { message: "" }
|
|
167
|
+
};
|
|
168
|
+
pages.set(ev, page);
|
|
169
|
+
}
|
|
170
|
+
return page;
|
|
171
|
+
}
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region src/site/responseCaching.ts
|
|
174
|
+
/** The default for responses that read or set cookies. */
|
|
175
|
+
const PRIVATE_DEFAULT = "private, no-cache";
|
|
176
|
+
let warnedPublicCookies = false;
|
|
177
|
+
/**
|
|
178
|
+
* A weak ETag for a response body, from a hash of its content. Content-based,
|
|
179
|
+
* so it changes whenever the body does: a matching `If-None-Match` only ever
|
|
180
|
+
* saves sending the same bytes again.
|
|
181
|
+
*/
|
|
182
|
+
async function etagOf(body) {
|
|
183
|
+
const digest = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(body));
|
|
184
|
+
let binary = "";
|
|
185
|
+
for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
|
|
186
|
+
return `W/"${btoa(binary).replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_")}"`;
|
|
187
|
+
}
|
|
188
|
+
/** Builds a `Cache-Control` value from merged cache options. */
|
|
189
|
+
function cacheControlOf(options) {
|
|
190
|
+
if (options.noStore) return "no-store";
|
|
191
|
+
const parts = [options.private ? "private" : "public"];
|
|
192
|
+
if (options.maxAge !== void 0) parts.push(`max-age=${options.maxAge}`);
|
|
193
|
+
else parts.push("no-cache");
|
|
194
|
+
if (options.sMaxAge !== void 0 && !options.private) parts.push(`s-maxage=${options.sMaxAge}`);
|
|
195
|
+
if (options.staleWhileRevalidate !== void 0) parts.push(`stale-while-revalidate=${options.staleWhileRevalidate}`);
|
|
196
|
+
return parts.join(", ");
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Applies the request's caching to its response, as the last step of
|
|
200
|
+
* handling it:
|
|
201
|
+
*
|
|
202
|
+
* - A response that read or set a cookie (the session, a flash message) is
|
|
203
|
+
* `private` unless the code that handled it explicitly said otherwise,
|
|
204
|
+
* so a CDN can't serve one user's page to another
|
|
205
|
+
* - The `event.cache()` settings become `Cache-Control` and `Vary` on 2xx
|
|
206
|
+
* GET responses, unless the response set its own `Cache-Control`
|
|
207
|
+
* - A response whose ETag matches the request's `If-None-Match` becomes a
|
|
208
|
+
* 304 without a body
|
|
209
|
+
*/
|
|
210
|
+
function finishCaching(ev, response, dev) {
|
|
211
|
+
const method = ev.request.method;
|
|
212
|
+
if (method !== "GET" && method !== "HEAD") return response;
|
|
213
|
+
const usesCookies = ev.cookies.read || ev.cookies.cookies.size > 0;
|
|
214
|
+
const options = ev.cacheOptions;
|
|
215
|
+
const ok = response.status >= 200 && response.status < 300;
|
|
216
|
+
const hasOwn = response.headers.has("Cache-Control") || hasHeader(ev, "Cache-Control");
|
|
217
|
+
let cacheControl;
|
|
218
|
+
let vary = [];
|
|
219
|
+
if (!hasOwn) {
|
|
220
|
+
if (ok && options) {
|
|
221
|
+
const merged = { ...options };
|
|
222
|
+
if (usesCookies && merged.private === void 0) merged.private = true;
|
|
223
|
+
else if (usesCookies && merged.private === false && dev && !warnedPublicCookies) {
|
|
224
|
+
warnedPublicCookies = true;
|
|
225
|
+
console.warn(`[torpor] ${ev.url.pathname} read or set a cookie but is cached with \`private: false\`, so shared caches (CDNs) may serve it to other users. Only do this if its content doesn't depend on the cookie.`);
|
|
226
|
+
}
|
|
227
|
+
cacheControl = cacheControlOf(merged);
|
|
228
|
+
vary = options.vary ?? [];
|
|
229
|
+
} else if (usesCookies) cacheControl = PRIVATE_DEFAULT;
|
|
230
|
+
else if (ok && ev.request.headers.has("X-Torpor-Data")) cacheControl = "no-cache";
|
|
231
|
+
}
|
|
232
|
+
if (cacheControl || vary.length > 0) {
|
|
233
|
+
response = mutable(response);
|
|
234
|
+
if (cacheControl) response.headers.set("Cache-Control", cacheControl);
|
|
235
|
+
for (const name of vary) response.headers.append("Vary", name);
|
|
236
|
+
}
|
|
237
|
+
const etag = response.headers.get("ETag");
|
|
238
|
+
if (etag && response.status === 200 && matches(ev.request.headers.get("If-None-Match"), etag)) {
|
|
239
|
+
const headers = new Headers();
|
|
240
|
+
for (const name of [
|
|
241
|
+
"Cache-Control",
|
|
242
|
+
"ETag",
|
|
243
|
+
"Vary",
|
|
244
|
+
"Content-Location",
|
|
245
|
+
"Expires"
|
|
246
|
+
]) {
|
|
247
|
+
const value = response.headers.get(name);
|
|
248
|
+
if (value) headers.set(name, value);
|
|
249
|
+
}
|
|
250
|
+
return new Response(null, {
|
|
251
|
+
status: 304,
|
|
252
|
+
headers
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
return response;
|
|
256
|
+
}
|
|
257
|
+
/** Whether a header was set through `event.headers`. */
|
|
258
|
+
function hasHeader(ev, name) {
|
|
259
|
+
const lower = name.toLowerCase();
|
|
260
|
+
for (const key of ev.headers.headers.keys()) if (key.toLowerCase() === lower) return true;
|
|
261
|
+
return false;
|
|
262
|
+
}
|
|
263
|
+
/** Whether an `If-None-Match` value matches an ETag (weak comparison). */
|
|
264
|
+
function matches(ifNoneMatch, etag) {
|
|
265
|
+
if (!ifNoneMatch) return false;
|
|
266
|
+
if (ifNoneMatch.trim() === "*") return true;
|
|
267
|
+
const opaque = (tag) => tag.trim().replace(/^W\//, "");
|
|
268
|
+
return ifNoneMatch.split(",").some((tag) => opaque(tag) === opaque(etag));
|
|
269
|
+
}
|
|
270
|
+
/** The response, or a copy whose headers can be changed. */
|
|
271
|
+
function mutable(response) {
|
|
272
|
+
try {
|
|
273
|
+
response.headers.set("X-Torpor-Probe", "1");
|
|
274
|
+
response.headers.delete("X-Torpor-Probe");
|
|
275
|
+
return response;
|
|
276
|
+
} catch {
|
|
277
|
+
return new Response(response.body, response);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
//#endregion
|
|
157
281
|
//#region src/site/serverHandlers.ts
|
|
158
282
|
/** Whether the site is running under `tb --dev` (set by `createServerLoad`). */
|
|
159
283
|
let devMode = false;
|
|
@@ -186,8 +310,7 @@ function warnUncachedEmbeddedData(ev, path) {
|
|
|
186
310
|
* route
|
|
187
311
|
* @returns The request handler, which takes the site template
|
|
188
312
|
*/
|
|
189
|
-
function createServerLoad(router, basePath = "", middleware = [], dev = false) {
|
|
190
|
-
setBasePath(basePath);
|
|
313
|
+
function createServerLoad(router, basePath = "", middleware = [], dev = false, preloads) {
|
|
191
314
|
devMode = dev;
|
|
192
315
|
/**
|
|
193
316
|
* Finalizes the response of a load or action. Successful responses and
|
|
@@ -207,29 +330,33 @@ function createServerLoad(router, basePath = "", middleware = [], dev = false) {
|
|
|
207
330
|
return await renderErrorPage(ev, url, template, router, response.status, message) ?? response;
|
|
208
331
|
}
|
|
209
332
|
const handle = async (ev, template) => {
|
|
333
|
+
setRequestBase(ev, basePath);
|
|
334
|
+
setRequestPreloads(ev, preloads);
|
|
210
335
|
const url = stripBaseFromUrl(ev.url, basePath);
|
|
211
336
|
if (!url) {
|
|
212
|
-
|
|
337
|
+
pageOf(ev).url = ev.url;
|
|
213
338
|
return await renderErrorPage(ev, ev.url, template, router, 404, "Not found") ?? notFound();
|
|
214
339
|
}
|
|
215
340
|
const path = url.pathname;
|
|
216
341
|
const query = url.searchParams;
|
|
217
|
-
|
|
342
|
+
const method = ev.request.method === "HEAD" ? "GET" : ev.request.method;
|
|
343
|
+
if (method === "GET" && ev.request.headers.has("X-Torpor-Data") && path.endsWith("/~server")) {
|
|
218
344
|
const pagePath = path.slice(0, -8) || "/";
|
|
219
345
|
const pageUrl = new URL(pagePath + url.search, url);
|
|
220
346
|
const pageRoute = router.match(pagePath, query);
|
|
221
347
|
if (pageRoute) {
|
|
222
|
-
|
|
348
|
+
pageOf(ev).url = pageUrl;
|
|
223
349
|
return await loadPageData(ev, pageUrl, pageRoute.handler, pageRoute.params ?? {}, reusedLayoutPaths(ev));
|
|
224
350
|
}
|
|
225
351
|
}
|
|
226
|
-
|
|
352
|
+
const page = pageOf(ev);
|
|
353
|
+
page.url = url;
|
|
227
354
|
if (path.endsWith("/_error")) {
|
|
228
|
-
|
|
229
|
-
|
|
355
|
+
page.status = parseErrorStatus(query.get("status"));
|
|
356
|
+
page.error = { message: query.get("message") ?? "" };
|
|
230
357
|
} else {
|
|
231
|
-
|
|
232
|
-
|
|
358
|
+
page.status = 200;
|
|
359
|
+
page.error = { message: "" };
|
|
233
360
|
}
|
|
234
361
|
let route = router.match(path, query);
|
|
235
362
|
if (!route) {
|
|
@@ -244,14 +371,18 @@ function createServerLoad(router, basePath = "", middleware = [], dev = false) {
|
|
|
244
371
|
const routeMiddleware = [];
|
|
245
372
|
const endPointModule = handler.serverEndPoint ? (await resolveServerModule(handler))?.default : handler.type === 1 || handler.type === 3 ? (await resolveModule(handler))?.default : void 0;
|
|
246
373
|
if (Array.isArray(endPointModule?.middleware)) routeMiddleware.push(...endPointModule.middleware);
|
|
374
|
+
const serverHooks = await loadServerHooks(handler);
|
|
247
375
|
const { response: routeResponse, error } = await runHooks([{
|
|
376
|
+
hooks: serverHooks,
|
|
377
|
+
arg: buildServerParams(ev, url, params)
|
|
378
|
+
}, {
|
|
248
379
|
hooks: routeMiddleware,
|
|
249
380
|
arg: ev
|
|
250
381
|
}], async () => {
|
|
251
382
|
switch (handler.type) {
|
|
252
383
|
case 0:
|
|
253
384
|
case 4:
|
|
254
|
-
if (
|
|
385
|
+
if (method === "GET") return handleResponse(ev, url, template, await loadView(ev, url, handler, params, template));
|
|
255
386
|
else if (ev.request.method === "POST") {
|
|
256
387
|
const serverEndPoint = handler.serverEndPoint && (await resolveServerModule(handler)).default;
|
|
257
388
|
return handleResponse(ev, url, template, await runAction(ev, url, handler, serverEndPoint, params, query, template), true);
|
|
@@ -259,19 +390,20 @@ function createServerLoad(router, basePath = "", middleware = [], dev = false) {
|
|
|
259
390
|
break;
|
|
260
391
|
case 1:
|
|
261
392
|
case 5:
|
|
262
|
-
if (
|
|
393
|
+
if (method === "GET") return await loadData(ev, url, handler, "load", params);
|
|
263
394
|
else if (ev.request.method === "POST") {
|
|
264
395
|
const serverEndPoint = (await resolveModule(handler)).default;
|
|
265
396
|
return handleResponse(ev, url, template, await runAction(ev, url, handler, serverEndPoint, params, query, template), true);
|
|
266
397
|
}
|
|
267
398
|
break;
|
|
268
399
|
case 3: {
|
|
269
|
-
|
|
400
|
+
let functionName = ev.request.method.toLowerCase().replace("delete", "del");
|
|
401
|
+
if (functionName === "head" && typeof endPointModule?.head !== "function") functionName = "get";
|
|
270
402
|
return await loadData(ev, url, handler, functionName, params);
|
|
271
403
|
}
|
|
272
404
|
case 6:
|
|
273
405
|
case 7: break;
|
|
274
|
-
case 8: return await loadView(ev, url, handler, params, template,
|
|
406
|
+
case 8: return await loadView(ev, url, handler, params, template, page.status);
|
|
275
407
|
}
|
|
276
408
|
}, { event: ev });
|
|
277
409
|
if (error) throw error;
|
|
@@ -289,7 +421,7 @@ function createServerLoad(router, basePath = "", middleware = [], dev = false) {
|
|
|
289
421
|
try {
|
|
290
422
|
const url = stripBaseFromUrl(ev.url, basePath) ?? ev.url;
|
|
291
423
|
if (router.match(url.pathname, url.searchParams)?.handler.type !== 3) {
|
|
292
|
-
|
|
424
|
+
pageOf(ev).url = url;
|
|
293
425
|
return await renderErrorPage(ev, url, template, router, 500, error instanceof Error ? error.message : String(error));
|
|
294
426
|
}
|
|
295
427
|
} catch {}
|
|
@@ -297,10 +429,66 @@ function createServerLoad(router, basePath = "", middleware = [], dev = false) {
|
|
|
297
429
|
}
|
|
298
430
|
});
|
|
299
431
|
if (error && !response) throw error;
|
|
300
|
-
|
|
432
|
+
const finished = finishCaching(ev, response, devMode);
|
|
433
|
+
return ev.request.method === "HEAD" ? withoutBody(finished) : finished;
|
|
301
434
|
};
|
|
302
435
|
}
|
|
303
436
|
/**
|
|
437
|
+
* The head tags for the page's client files and component styles.
|
|
438
|
+
*
|
|
439
|
+
* - `<link rel="modulepreload">` for the client chunks the page needs: the
|
|
440
|
+
* client entry's, then each layout's from the root down, then the page's.
|
|
441
|
+
* Without them the browser only finds the page's chunks after the entry
|
|
442
|
+
* script (at the end of the HTML) has downloaded and run.
|
|
443
|
+
* - `<link rel="stylesheet">` for the stylesheets those chunks import, which
|
|
444
|
+
* hold the components' scoped styles. The client loads the same files when
|
|
445
|
+
* it hydrates (through Vite's preload helper, which skips a stylesheet
|
|
446
|
+
* that's already linked), so linking them here means each component's
|
|
447
|
+
* styles arrive once -- the inline `<style>` copies the components rendered
|
|
448
|
+
* are left out for every style a linked stylesheet contains. Head
|
|
449
|
+
* stylesheets block rendering, so there's no flash of unstyled content.
|
|
450
|
+
*
|
|
451
|
+
* In dev there's no build manifest: the inline styles stay, tagged with
|
|
452
|
+
* their Vite module id, so the dev client adopts them instead of adding
|
|
453
|
+
* another copy.
|
|
454
|
+
*
|
|
455
|
+
* @param styles The head content the components rendered (their styles)
|
|
456
|
+
*/
|
|
457
|
+
function pageAssets(ev, handler, styles) {
|
|
458
|
+
const preloads = requestPreloads(ev);
|
|
459
|
+
if (!preloads) return devMode ? styles.replace(INLINE_STYLE_RE, (tag, hash) => tag.replace(`<style id='${hash}'`, `<style id='${hash}' data-vite-dev-id='${hash}.css'`)) : styles;
|
|
460
|
+
const routes = [...(handler.layouts ?? []).map((layout) => layout.path), handler.path];
|
|
461
|
+
const scripts = new Set(preloads.entry);
|
|
462
|
+
const stylesheets = new Set(preloads.styles.entry);
|
|
463
|
+
for (const route of routes) {
|
|
464
|
+
for (const file of preloads.routes[route] ?? []) scripts.add(file);
|
|
465
|
+
for (const file of preloads.styles.routes[route] ?? []) stylesheets.add(file);
|
|
466
|
+
}
|
|
467
|
+
const linked = /* @__PURE__ */ new Set();
|
|
468
|
+
let links = "";
|
|
469
|
+
for (const file of stylesheets) {
|
|
470
|
+
links += `<link rel="stylesheet" href="${file}">`;
|
|
471
|
+
for (const hash of preloads.styles.hashes[file] ?? []) linked.add(hash);
|
|
472
|
+
}
|
|
473
|
+
for (const file of scripts) links += `<link rel="modulepreload" href="${file}">`;
|
|
474
|
+
return links + styles.replace(INLINE_STYLE_RE, (tag, hash) => linked.has(hash) ? "" : tag);
|
|
475
|
+
}
|
|
476
|
+
/** A component's inline scoped style, as rendered by the server build. */
|
|
477
|
+
const INLINE_STYLE_RE = /<style id='([a-z0-9]+)'>[\s\S]*?<\/style>/g;
|
|
478
|
+
/**
|
|
479
|
+
* The response to a HEAD request: the same status and headers, with the body
|
|
480
|
+
* dropped (and cancelled, so a streamed body stops producing).
|
|
481
|
+
*/
|
|
482
|
+
function withoutBody(response) {
|
|
483
|
+
if (response.body === null) return response;
|
|
484
|
+
response.body.cancel().catch(() => {});
|
|
485
|
+
return new Response(null, {
|
|
486
|
+
status: response.status,
|
|
487
|
+
statusText: response.statusText,
|
|
488
|
+
headers: response.headers
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
304
492
|
* Resolves the route's endpoint module, caching the module on the handler so
|
|
305
493
|
* warm requests don't pay for the loader. The loader promise itself is never
|
|
306
494
|
* cached: a request that ends before it settles leaves it permanently
|
|
@@ -330,6 +518,17 @@ async function resolveServerModule(handler) {
|
|
|
330
518
|
* Resolves the route's folder hooks, caching the hook list on the handler as
|
|
331
519
|
* a value (never the promise -- see `resolveModule`).
|
|
332
520
|
*/
|
|
521
|
+
/**
|
|
522
|
+
* Loads a layout's server endpoint (_layout.server.ts), if it has one.
|
|
523
|
+
* Layouts can't declare `middleware`: it would run for the pages below the
|
|
524
|
+
* layout but not for the endpoints in the same folders, so a guard there
|
|
525
|
+
* would leave those open. Rather than ignore it, this throws.
|
|
526
|
+
*/
|
|
527
|
+
async function loadLayoutServerEndPoint(layout) {
|
|
528
|
+
const endPoint = layout.serverEndPoint && (await layout.serverEndPoint())?.default;
|
|
529
|
+
if (endPoint && "middleware" in endPoint && endPoint.middleware !== void 0) throw new Error(`The layout server endpoint for "${layout.path}" declares \`middleware\`, which isn't supported on layouts: it wouldn't guard the API endpoints in its folder. Move it into a _hook.server.ts in the same folder, which runs for every request below it.`);
|
|
530
|
+
return endPoint;
|
|
531
|
+
}
|
|
333
532
|
async function loadServerHooks(handler) {
|
|
334
533
|
if (!handler.serverHooks) return [];
|
|
335
534
|
if (devMode) return await Promise.all(handler.serverHooks.map(async (load) => (await load()).default));
|
|
@@ -351,10 +550,17 @@ async function renderErrorPage(ev, url, template, router, status, message) {
|
|
|
351
550
|
if (!errorPath) return;
|
|
352
551
|
const errorRoute = router.match(errorPath, new URLSearchParams());
|
|
353
552
|
if (!errorRoute) return;
|
|
354
|
-
|
|
355
|
-
|
|
553
|
+
const page = pageOf(ev);
|
|
554
|
+
page.status = status;
|
|
555
|
+
page.error = { message };
|
|
356
556
|
try {
|
|
357
|
-
const
|
|
557
|
+
const serverHooks = await loadServerHooks(errorRoute.handler);
|
|
558
|
+
const { response: hooked, error } = await runHooks([{
|
|
559
|
+
hooks: serverHooks,
|
|
560
|
+
arg: buildServerParams(ev, url, {})
|
|
561
|
+
}], () => loadView(ev, url, errorRoute.handler, {}, template, status));
|
|
562
|
+
if (error) throw error;
|
|
563
|
+
const response = hooked;
|
|
358
564
|
if (response.headers.get("Content-Type")?.includes("text/html")) return response;
|
|
359
565
|
return;
|
|
360
566
|
} catch (error) {
|
|
@@ -376,16 +582,7 @@ async function loadData(ev, url, handler, functionName, params) {
|
|
|
376
582
|
try {
|
|
377
583
|
const schema = endpointSchema(serverEndPoint, functionName);
|
|
378
584
|
const values = schema ? functionName === "get" || functionName === "head" || functionName === "load" ? { query: await validate(schema, searchParamsToRecord(url.searchParams)) } : { json: await validate(schema, await ev.json()) } : {};
|
|
379
|
-
|
|
380
|
-
const hooks = handler.serverHooks ? await loadServerHooks(handler) : [];
|
|
381
|
-
const { response, error } = await runHooks([{
|
|
382
|
-
hooks,
|
|
383
|
-
arg: serverParams
|
|
384
|
-
}], async () => {
|
|
385
|
-
return await handlerFn(serverParams) || void 0;
|
|
386
|
-
});
|
|
387
|
-
if (error) throw error;
|
|
388
|
-
return response || ok();
|
|
585
|
+
return await handlerFn(buildServerParams(ev, url, params, values)) || ok();
|
|
389
586
|
} catch (error) {
|
|
390
587
|
const response = validationErrorResponse(error);
|
|
391
588
|
if (response) return response;
|
|
@@ -405,47 +602,48 @@ async function loadData(ev, url, handler, functionName, params) {
|
|
|
405
602
|
*/
|
|
406
603
|
async function loadPageData(ev, pageUrl, handler, params, reusedLayouts) {
|
|
407
604
|
const serverEndPoint = handler.serverEndPoint && (await resolveServerModule(handler))?.default;
|
|
408
|
-
let query;
|
|
409
|
-
if (serverEndPoint) {
|
|
410
|
-
try {
|
|
411
|
-
params = await validateEndpointParams(serverEndPoint, params);
|
|
412
|
-
} catch (error) {
|
|
413
|
-
if (error instanceof ValidationError) return notFound();
|
|
414
|
-
throw error;
|
|
415
|
-
}
|
|
416
|
-
const loadSchema = endpointSchema(serverEndPoint, "load");
|
|
417
|
-
if (loadSchema) try {
|
|
418
|
-
query = await validate(loadSchema, searchParamsToRecord(pageUrl.searchParams));
|
|
419
|
-
} catch (error) {
|
|
420
|
-
const response = validationErrorResponse(error);
|
|
421
|
-
if (response) return response;
|
|
422
|
-
throw error;
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
const serverParams = buildServerParams(ev, pageUrl, params, query ? { query } : {});
|
|
426
605
|
const serverHooks = await loadServerHooks(handler);
|
|
427
606
|
const routeMiddleware = Array.isArray(serverEndPoint?.middleware) ? serverEndPoint.middleware : [];
|
|
428
607
|
const loads = [];
|
|
429
608
|
const { response, error } = await runHooks([{
|
|
609
|
+
hooks: serverHooks,
|
|
610
|
+
arg: buildServerParams(ev, pageUrl, params)
|
|
611
|
+
}, {
|
|
430
612
|
hooks: routeMiddleware,
|
|
431
613
|
arg: ev
|
|
432
|
-
}, {
|
|
433
|
-
hooks: serverHooks,
|
|
434
|
-
arg: serverParams
|
|
435
614
|
}], async () => {
|
|
615
|
+
let query;
|
|
616
|
+
if (serverEndPoint) {
|
|
617
|
+
try {
|
|
618
|
+
params = await validateEndpointParams(serverEndPoint, params);
|
|
619
|
+
} catch (error) {
|
|
620
|
+
if (error instanceof ValidationError) return notFound();
|
|
621
|
+
throw error;
|
|
622
|
+
}
|
|
623
|
+
const loadSchema = endpointSchema(serverEndPoint, "load");
|
|
624
|
+
if (loadSchema) try {
|
|
625
|
+
query = await validate(loadSchema, searchParamsToRecord(pageUrl.searchParams));
|
|
626
|
+
} catch (error) {
|
|
627
|
+
const response = validationErrorResponse(error);
|
|
628
|
+
if (response) return response;
|
|
629
|
+
throw error;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
const serverParams = buildServerParams(ev, pageUrl, params, query ? { query } : {});
|
|
436
633
|
for (const layout of handler.layouts ?? []) {
|
|
634
|
+
const layoutServerEndPoint = await loadLayoutServerEndPoint(layout);
|
|
437
635
|
if (reusedLayouts.has(layout.path)) {
|
|
438
636
|
loads.push(null);
|
|
439
637
|
continue;
|
|
440
638
|
}
|
|
441
|
-
const result = await loadRouteServerData(
|
|
639
|
+
const result = await loadRouteServerData(layoutServerEndPoint, serverParams);
|
|
442
640
|
if (result instanceof Response) return result;
|
|
443
641
|
loads.push(result);
|
|
444
642
|
}
|
|
445
643
|
const pageResult = await loadRouteServerData(serverEndPoint, serverParams);
|
|
446
644
|
if (pageResult instanceof Response) return pageResult;
|
|
447
645
|
loads.push(pageResult);
|
|
448
|
-
return serverDataResponse(loads);
|
|
646
|
+
return await serverDataResponse(loads);
|
|
449
647
|
}, { event: ev });
|
|
450
648
|
if (error) throw error;
|
|
451
649
|
return response;
|
|
@@ -484,9 +682,17 @@ function splitLoads(loads) {
|
|
|
484
682
|
* announced in the same frame and then streamed as NDJSON frames, so a
|
|
485
683
|
* navigation can mount as soon as the critical data arrives.
|
|
486
684
|
*/
|
|
487
|
-
function serverDataResponse(loads) {
|
|
685
|
+
async function serverDataResponse(loads) {
|
|
488
686
|
const { criticalLoads, entries } = splitLoads(loads);
|
|
489
|
-
|
|
687
|
+
const vary = `${DATA_REQUEST_HEADER}, ${DATA_REUSE_HEADER}`;
|
|
688
|
+
if (entries.length === 0) {
|
|
689
|
+
const body = JSON.stringify({ loads: criticalLoads });
|
|
690
|
+
return new Response(body, { headers: {
|
|
691
|
+
"Content-Type": "application/json",
|
|
692
|
+
ETag: await etagOf(body),
|
|
693
|
+
Vary: vary
|
|
694
|
+
} });
|
|
695
|
+
}
|
|
490
696
|
const first = {
|
|
491
697
|
type: "data",
|
|
492
698
|
loads: criticalLoads,
|
|
@@ -528,7 +734,10 @@ function serverDataResponse(loads) {
|
|
|
528
734
|
cancelled = true;
|
|
529
735
|
}
|
|
530
736
|
});
|
|
531
|
-
return new Response(stream, { headers: {
|
|
737
|
+
return new Response(stream, { headers: {
|
|
738
|
+
"Content-Type": "application/x-ndjson",
|
|
739
|
+
Vary: vary
|
|
740
|
+
} });
|
|
532
741
|
}
|
|
533
742
|
function errorMessage(error) {
|
|
534
743
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -545,10 +754,10 @@ async function loadRouteServerData(serverEndPoint, serverParams) {
|
|
|
545
754
|
if (!response.ok) return response;
|
|
546
755
|
return await readResponseBody(response) ?? null;
|
|
547
756
|
}
|
|
548
|
-
async function loadView(ev, url, handler, params, template, status, form, fromForm
|
|
757
|
+
async function loadView(ev, url, handler, params, template, status, form, fromForm) {
|
|
549
758
|
const clientEndPoint = (await resolveModule(handler)).default;
|
|
550
759
|
if (!clientEndPoint?.component) return notFound();
|
|
551
|
-
|
|
760
|
+
pageOf(ev).flash = ev.flash.get();
|
|
552
761
|
if (!template) throw new Error("Page routes require a src/site.html file, which was not found; add it, or remove page/layout routes to serve endpoints only");
|
|
553
762
|
const serverEndPoint = handler.serverEndPoint && (await resolveServerModule(handler))?.default;
|
|
554
763
|
let query;
|
|
@@ -574,102 +783,96 @@ async function loadView(ev, url, handler, params, template, status, form, fromFo
|
|
|
574
783
|
}
|
|
575
784
|
}
|
|
576
785
|
}
|
|
577
|
-
const serverParams = buildServerParams(ev, url, params, query ? { query } : {}
|
|
578
|
-
const serverHooks = fromForm ? [] : await loadServerHooks(handler);
|
|
786
|
+
const serverParams = buildServerParams(ev, url, params, query ? { query } : {});
|
|
579
787
|
let deferredEntries = [];
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
const
|
|
586
|
-
if (
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
const trackSlot = (level, slot) => {
|
|
603
|
-
return ($slot, $context) => {
|
|
604
|
-
invokedLevels.add(level);
|
|
605
|
-
return slot($slot, $context);
|
|
606
|
-
};
|
|
788
|
+
let data = {};
|
|
789
|
+
const loads = [];
|
|
790
|
+
if (handler.layouts) for (let layout of handler.layouts) {
|
|
791
|
+
const layoutEndPoint = (await layout.endPoint())?.default;
|
|
792
|
+
const layoutServerEndPoint = await loadLayoutServerEndPoint(layout);
|
|
793
|
+
const layoutResponse = await loadClientAndServerData(url, params, serverParams, data, layoutEndPoint, layoutServerEndPoint, loads);
|
|
794
|
+
if (layoutResponse?.ok === false) return layoutResponse;
|
|
795
|
+
}
|
|
796
|
+
let endPointResponse = await loadClientAndServerData(url, params, serverParams, data, clientEndPoint, serverEndPoint, loads);
|
|
797
|
+
if (endPointResponse?.ok === false) return endPointResponse;
|
|
798
|
+
let $props = {
|
|
799
|
+
data,
|
|
800
|
+
form
|
|
801
|
+
};
|
|
802
|
+
let styles = "";
|
|
803
|
+
let component = clientEndPoint.component;
|
|
804
|
+
let slots = void 0;
|
|
805
|
+
const invokedLevels = /* @__PURE__ */ new Set();
|
|
806
|
+
const trackSlot = (level, slot) => {
|
|
807
|
+
return ($slot, $context) => {
|
|
808
|
+
invokedLevels.add(level);
|
|
809
|
+
return slot($slot, $context);
|
|
607
810
|
};
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
}
|
|
811
|
+
};
|
|
812
|
+
if (handler.layouts) {
|
|
813
|
+
let slotFunctions = [];
|
|
814
|
+
slotFunctions[handler.layouts.length] = trackSlot(handler.layouts.length, async (_, $context) => {
|
|
815
|
+
let { body, head } = await clientEndPoint.component($props, $context);
|
|
816
|
+
styles += head;
|
|
817
|
+
return body;
|
|
818
|
+
});
|
|
819
|
+
for (let i = handler.layouts.length - 1; i >= 0; i--) {
|
|
820
|
+
const layoutEndPoint = (await handler.layouts[i].endPoint())?.default;
|
|
821
|
+
if (layoutEndPoint?.component) {
|
|
822
|
+
if (i === 0) {
|
|
823
|
+
component = layoutEndPoint.component;
|
|
824
|
+
slots = { _: slotFunctions[i + 1] };
|
|
825
|
+
} else slotFunctions[i] = trackSlot(i, async (_, $context) => {
|
|
826
|
+
let { body, head } = await layoutEndPoint.component($props, $context, { _: slotFunctions[i + 1] });
|
|
827
|
+
styles += head;
|
|
828
|
+
return body;
|
|
829
|
+
});
|
|
627
830
|
}
|
|
628
831
|
}
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
}
|
|
644
|
-
if (form) body += `\n<input type="hidden" id="t-form-data" value='${JSON.stringify(form).replaceAll("'", "\\'")}' />`;
|
|
645
|
-
if (routeHasServerData(handler)) {
|
|
646
|
-
const { criticalLoads, entries } = splitLoads(loads);
|
|
647
|
-
deferredEntries = entries;
|
|
648
|
-
const payload = { loads: criticalLoads };
|
|
649
|
-
if (entries.length > 0) payload.deferred = entries.map((entry) => entry.meta);
|
|
650
|
-
const json = JSON.stringify(payload).replaceAll("<", "\\u003c");
|
|
651
|
-
body += `\n<script type="application/json" id="t-server-data">${json}<\/script>`;
|
|
652
|
-
if (loads.some((load) => load !== null)) warnUncachedEmbeddedData(ev, handler.path);
|
|
653
|
-
}
|
|
654
|
-
styles += head;
|
|
655
|
-
html = rewriteBaseInHtml(mergeHead(template, styles + headData).replace("%COMPONENT_BODY%", body), getBasePath());
|
|
656
|
-
} catch (error) {
|
|
657
|
-
html = "<span style=\"color: red\">Script syntax error</span><p>" + error + "</p>";
|
|
658
|
-
deferredEntries = [];
|
|
659
|
-
console.log(error);
|
|
832
|
+
}
|
|
833
|
+
let html;
|
|
834
|
+
try {
|
|
835
|
+
let { body, head } = await component($props, { $page: pageOf(ev) }, slots);
|
|
836
|
+
let headData = "";
|
|
837
|
+
const event = {
|
|
838
|
+
url,
|
|
839
|
+
params,
|
|
840
|
+
data
|
|
841
|
+
};
|
|
842
|
+
const headPoints = [clientEndPoint, ...await Promise.all((handler.layouts ?? []).map(async (layout) => await layout.endPoint()))].reverse();
|
|
843
|
+
for (const endPoint of headPoints) {
|
|
844
|
+
const headElements = typeof endPoint.head === "function" ? await endPoint.head(event) : endPoint.head;
|
|
845
|
+
if (headElements) headData += headElements.map((element) => markupOf(element)).join("");
|
|
660
846
|
}
|
|
661
|
-
if (
|
|
662
|
-
|
|
663
|
-
|
|
847
|
+
if (form) body += `\n<script type="application/json" id="t-form-data">${jsonForScript(form)}<\/script>`;
|
|
848
|
+
if (routeHasServerData(handler)) {
|
|
849
|
+
const { criticalLoads, entries } = splitLoads(loads);
|
|
850
|
+
deferredEntries = entries;
|
|
851
|
+
const payload = { loads: criticalLoads };
|
|
852
|
+
if (entries.length > 0) payload.deferred = entries.map((entry) => entry.meta);
|
|
853
|
+
const json = JSON.stringify(payload).replaceAll("<", "\\u003c");
|
|
854
|
+
body += `\n<script type="application/json" id="t-server-data">${json}<\/script>`;
|
|
855
|
+
if (loads.some((load) => load !== null)) warnUncachedEmbeddedData(ev, handler.path);
|
|
856
|
+
}
|
|
857
|
+
styles += head;
|
|
858
|
+
html = rewriteBaseInHtml(mergeHead(template, pageAssets(ev, handler, styles) + headData).replace("%COMPONENT_BODY%", body), requestBase(ev));
|
|
859
|
+
} catch (error) {
|
|
860
|
+
html = "<span style=\"color: red\">Script syntax error</span><p>" + error + "</p>";
|
|
861
|
+
deferredEntries = [];
|
|
862
|
+
console.log(error);
|
|
863
|
+
}
|
|
864
|
+
if (handler.layouts) {
|
|
865
|
+
const missingLayout = findMissingSlotLayout(handler.layouts, invokedLevels);
|
|
866
|
+
if (missingLayout !== void 0) warnMissingSlotContent(missingLayout);
|
|
867
|
+
}
|
|
868
|
+
if (deferredEntries.length > 0) return streamHtmlResponse(html, status ?? 200, deferredEntries);
|
|
869
|
+
return new Response(html, {
|
|
870
|
+
status: status ?? 200,
|
|
871
|
+
headers: {
|
|
872
|
+
"Content-Type": "text/html",
|
|
873
|
+
ETag: await etagOf(html)
|
|
664
874
|
}
|
|
665
|
-
if (deferredEntries.length > 0) return streamHtmlResponse(html, status ?? 200, deferredEntries);
|
|
666
|
-
return new Response(html, {
|
|
667
|
-
status: status ?? 200,
|
|
668
|
-
headers: { "Content-Type": "text/html" }
|
|
669
|
-
});
|
|
670
875
|
});
|
|
671
|
-
if (error) throw error;
|
|
672
|
-
return response;
|
|
673
876
|
}
|
|
674
877
|
/**
|
|
675
878
|
* Streams a rendered page whose server data contained deferred values. The
|
|
@@ -726,15 +929,25 @@ function deferredBootstrapScript() {
|
|
|
726
929
|
}
|
|
727
930
|
/** A script that settles one deferred entry in the hydration store. */
|
|
728
931
|
function deferredScript(id, value, rejected) {
|
|
729
|
-
const payload = rejected ?
|
|
730
|
-
return `<script>__torporDeferred.${rejected ? "reject" : "resolve"}(${
|
|
932
|
+
const payload = jsonForScript(rejected ? String(value) : value);
|
|
933
|
+
return `<script>__torporDeferred.${rejected ? "reject" : "resolve"}(${jsonForScript(id)},${payload})<\/script>`;
|
|
731
934
|
}
|
|
732
935
|
async function runAction(ev, url, handler, serverEndPoint, params, query, template) {
|
|
936
|
+
const actions = serverEndPoint?.actions;
|
|
937
|
+
const hasAction = (name) => actions !== void 0 && Object.hasOwn(actions, name);
|
|
733
938
|
const queryKeys = Array.from(query.keys());
|
|
734
|
-
const actionName = (queryKeys.find((key) => key.startsWith("/")) ?? queryKeys.find((key) =>
|
|
735
|
-
if (serverEndPoint
|
|
736
|
-
const action =
|
|
939
|
+
const actionName = (queryKeys.find((key) => key.startsWith("/")) ?? queryKeys.find((key) => hasAction(key.replace(/^\//, ""))) ?? "default").replace(/^\//, "");
|
|
940
|
+
if (serverEndPoint !== void 0 && actions !== void 0 && Object.hasOwn(actions, actionName)) {
|
|
941
|
+
const action = actions[actionName];
|
|
737
942
|
if (action) {
|
|
943
|
+
const origin = ev.request.headers.get("Origin");
|
|
944
|
+
if (origin !== null) {
|
|
945
|
+
let sameOrigin = false;
|
|
946
|
+
try {
|
|
947
|
+
sameOrigin = new URL(origin).origin === url.origin;
|
|
948
|
+
} catch {}
|
|
949
|
+
if (!sameOrigin) return forbidden("Cross-site form submissions are forbidden");
|
|
950
|
+
}
|
|
738
951
|
if (actionName === "load" || actionName === "params") throw new Error(`The action name "${actionName}" is reserved. Rename the action (and its schema key, if any), e.g. to "save".`);
|
|
739
952
|
try {
|
|
740
953
|
params = await validateEndpointParams(serverEndPoint, params);
|
|
@@ -743,21 +956,11 @@ async function runAction(ev, url, handler, serverEndPoint, params, query, templa
|
|
|
743
956
|
throw error;
|
|
744
957
|
}
|
|
745
958
|
let result;
|
|
746
|
-
let serverParams = void 0;
|
|
747
959
|
try {
|
|
960
|
+
const values = {};
|
|
748
961
|
const schema = endpointSchema(serverEndPoint, actionName);
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
const serverHooks = await loadServerHooks(handler);
|
|
752
|
-
const actionParams = serverParams;
|
|
753
|
-
const { response: hookResponse, error: hookError } = await runHooks([{
|
|
754
|
-
hooks: serverHooks,
|
|
755
|
-
arg: actionParams
|
|
756
|
-
}], async () => {
|
|
757
|
-
return await action(actionParams) || void 0;
|
|
758
|
-
});
|
|
759
|
-
if (hookError) throw hookError;
|
|
760
|
-
result = hookResponse;
|
|
962
|
+
if (schema) values.form = await validate(schema, await formDataToRecord(await ev.formData()));
|
|
963
|
+
result = await action(buildServerParams(ev, url, params, values));
|
|
761
964
|
} catch (error) {
|
|
762
965
|
const response = validationErrorResponse(error);
|
|
763
966
|
if (response) return response;
|
|
@@ -776,13 +979,14 @@ async function runAction(ev, url, handler, serverEndPoint, params, query, templa
|
|
|
776
979
|
const newUrl = new URL(url.pathname + url.search, url);
|
|
777
980
|
const formStatus = result?.status;
|
|
778
981
|
let formMessage = await result?.text();
|
|
982
|
+
const page = pageOf(ev);
|
|
779
983
|
if (formMessage && result?.headers.get("Content-Type")?.includes("application/json")) {
|
|
780
|
-
|
|
984
|
+
page.form = JSON.parse(formMessage);
|
|
781
985
|
formMessage = void 0;
|
|
782
|
-
} else
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
return await loadView(ev, newUrl, handler, params, template, formStatus,
|
|
986
|
+
} else page.form = {};
|
|
987
|
+
page.form.status ??= formStatus ?? 0;
|
|
988
|
+
page.form.message ??= formMessage ?? "";
|
|
989
|
+
return await loadView(ev, newUrl, handler, params, template, formStatus, page.form, true);
|
|
786
990
|
} else return result;
|
|
787
991
|
}
|
|
788
992
|
}
|
|
@@ -856,12 +1060,12 @@ function requestUrl(url) {
|
|
|
856
1060
|
const path = url.pathname.slice(0, -8) || "/";
|
|
857
1061
|
return new URL(path + url.search, url);
|
|
858
1062
|
}
|
|
859
|
-
function buildServerParams(ev, url, params, values = {}
|
|
1063
|
+
function buildServerParams(ev, url, params, values = {}) {
|
|
860
1064
|
const logicalUrl = requestUrl(url);
|
|
861
1065
|
return {
|
|
862
1066
|
url: logicalUrl,
|
|
863
1067
|
params,
|
|
864
|
-
appData,
|
|
1068
|
+
appData: ev.appData,
|
|
865
1069
|
request: ev.request,
|
|
866
1070
|
json: () => values.json !== void 0 ? Promise.resolve(values.json) : ev.json(),
|
|
867
1071
|
form: async () => values.form !== void 0 ? Promise.resolve(values.form) : formDataToRecord(await ev.formData()),
|
|
@@ -871,6 +1075,8 @@ function buildServerParams(ev, url, params, values = {}, appData = {}) {
|
|
|
871
1075
|
headers: ev.headers,
|
|
872
1076
|
session: ev.session,
|
|
873
1077
|
flash: ev.flash,
|
|
1078
|
+
cache: (options) => ev.cache(options),
|
|
1079
|
+
waitUntil: (promise) => ev.waitUntil(promise),
|
|
874
1080
|
adapter: ev.adapter
|
|
875
1081
|
};
|
|
876
1082
|
}
|
|
@@ -889,4 +1095,4 @@ function escapeHtml(value) {
|
|
|
889
1095
|
//#endregion
|
|
890
1096
|
export { createServerLoad as t };
|
|
891
1097
|
|
|
892
|
-
//# sourceMappingURL=serverHandlers-
|
|
1098
|
+
//# sourceMappingURL=serverHandlers-B1L8I72-.mjs.map
|