@torpor/build 1.8.4 → 1.8.6

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.
@@ -1 +1 @@
1
- export { t as default } from "../Server-C0PGzSQO.mjs";
1
+ export { t as default } from "../Server-dcRbdPXf.mjs";
package/dist/server.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as HeaderHelper, r as CookieHelper, t as ServerEvent } from "./ServerEvent-BY4f3RVF.mjs";
2
- import { t as Server } from "./Server-C0PGzSQO.mjs";
2
+ import { t as Server } from "./Server-dcRbdPXf.mjs";
3
3
  import { t as flattenHeaders } from "./flattenHeaders-DM5qsSqO.mjs";
4
4
  import { PassThrough, Readable } from "node:stream";
5
5
  import { ServerResponse } from "node:http";
@@ -1 +1 @@
1
- {"version":3,"file":"serverEntry-BGii8bB6.d.mts","names":[],"sources":["../src/site/serverHandlers.ts","../src/site/serverEntry.ts"],"mappings":";;;;;;KA8CY,cAAc,IAAI,aAAa,sBAAsB,QAAQ;;;cCpC5D,QAAQ;cAKR,MAAM"}
1
+ {"version":3,"file":"serverEntry-BGii8bB6.d.mts","names":[],"sources":["../src/site/serverHandlers.ts","../src/site/serverEntry.ts"],"mappings":";;;;;;KA+CY,cAAc,IAAI,aAAa,sBAAsB,QAAQ;;;cCrC5D,QAAQ;cAKR,MAAM"}
@@ -1,6 +1,6 @@
1
1
  import { t as Router } from "./Router-C4ADUfhv.mjs";
2
2
  import { o as setBasePath } from "./basePath-DQnbHc7o.mjs";
3
- import { t as createServerLoad } from "./serverHandlers-BpKfaFsD.mjs";
3
+ import { t as createServerLoad } from "./serverHandlers-CSBUEgJt.mjs";
4
4
  import manifest from "@torpor/build/manifest";
5
5
  //#region src/site/serverEntry.ts
6
6
  setBasePath(manifest.base);
@@ -10,4 +10,4 @@ const load = createServerLoad(router, manifest.base, manifest.middleware ?? [],
10
10
  //#endregion
11
11
  export { router as n, load as t };
12
12
 
13
- //# sourceMappingURL=serverEntry-DdNjmynd.mjs.map
13
+ //# sourceMappingURL=serverEntry-D1hE-Jzt.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"serverEntry-DdNjmynd.mjs","names":[],"sources":["../src/site/serverEntry.ts"],"sourcesContent":["import manifest from \"@torpor/build/manifest\";\nimport Router from \"./Router.ts\";\nimport { setBasePath } from \"./basePath.ts\";\nimport { type ServerLoad, createServerLoad } from \"./serverHandlers.ts\";\n\n// Put adapter-specific functionality in the `adapter` property of\n// globalThis for now\nsetBasePath(manifest.base);\n\n// Build the router from the Site object created by the user\nexport const router: Router = new Router();\nrouter.addPages(manifest.routes);\n\n//console.log(`routes:\\n ${router.routes.map((r) => r.path).join(\"\\n \")}`);\n\nexport const load: ServerLoad = createServerLoad(\n\trouter,\n\tmanifest.base,\n\tmanifest.middleware ?? [],\n\tmanifest.dev ?? false,\n);\n"],"mappings":";;;;;AAOA,YAAY,SAAS,IAAI;AAGzB,MAAa,SAAiB,IAAI,OAAO;AACzC,OAAO,SAAS,SAAS,MAAM;AAI/B,MAAa,OAAmB,iBAC/B,QACA,SAAS,MACT,SAAS,cAAc,CAAC,GACxB,SAAS,OAAO,KACjB"}
1
+ {"version":3,"file":"serverEntry-D1hE-Jzt.mjs","names":[],"sources":["../src/site/serverEntry.ts"],"sourcesContent":["import manifest from \"@torpor/build/manifest\";\nimport Router from \"./Router.ts\";\nimport { setBasePath } from \"./basePath.ts\";\nimport { type ServerLoad, createServerLoad } from \"./serverHandlers.ts\";\n\n// Put adapter-specific functionality in the `adapter` property of\n// globalThis for now\nsetBasePath(manifest.base);\n\n// Build the router from the Site object created by the user\nexport const router: Router = new Router();\nrouter.addPages(manifest.routes);\n\n//console.log(`routes:\\n ${router.routes.map((r) => r.path).join(\"\\n \")}`);\n\nexport const load: ServerLoad = createServerLoad(\n\trouter,\n\tmanifest.base,\n\tmanifest.middleware ?? [],\n\tmanifest.dev ?? false,\n);\n"],"mappings":";;;;;AAOA,YAAY,SAAS,IAAI;AAGzB,MAAa,SAAiB,IAAI,OAAO;AACzC,OAAO,SAAS,SAAS,MAAM;AAI/B,MAAa,OAAmB,iBAC/B,QACA,SAAS,MACT,SAAS,cAAc,CAAC,GACxB,SAAS,OAAO,KACjB"}
@@ -1 +1 @@
1
- export { t as load, n as router } from "./serverEntry-DdNjmynd.mjs";
1
+ export { t as load, n as router } from "./serverEntry-D1hE-Jzt.mjs";
@@ -2,6 +2,7 @@ import { a as rewriteBaseInHtml, n as getBasePath, o as setBasePath, s as stripB
2
2
  import { i as findErrorRoute, r as DATA_REUSE_HEADER, t as readResponseBody } from "./read-DxMVAh5Y.mjs";
3
3
  import { a as splitDeferred, r as jsonForScript } from "./internal-BItAKrmV.mjs";
4
4
  import { n as ok, r as notFound, t as unprocessable } from "./unprocessable-DwAG44Rh.mjs";
5
+ import { t as runHooks } from "./runHooks-D5p1Rh7i.mjs";
5
6
  import { n as ValidationError, t as validate } from "./validate-Ok4krlkX.mjs";
6
7
  import { $watch } from "@torpor/view/ssr";
7
8
  //#region src/form/formDataToRecord.ts
@@ -243,19 +244,18 @@ function createServerLoad(router, basePath = "", middleware = [], dev = false) {
243
244
  const routeMiddleware = [];
244
245
  const endPointModule = handler.serverEndPoint ? (await handler.serverEndPoint())?.default : handler.type === 1 || handler.type === 3 ? (await resolveModule(handler))?.default : void 0;
245
246
  if (Array.isArray(endPointModule?.middleware)) routeMiddleware.push(...endPointModule.middleware);
246
- let enteredRoute = 0;
247
- let routeResponse = void 0;
248
- try {
249
- for (; enteredRoute < routeMiddleware.length && !routeResponse; enteredRoute++) {
250
- const result = await routeMiddleware[enteredRoute].enter?.(ev);
251
- if (result) routeResponse = result;
252
- }
253
- if (routeResponse) return routeResponse;
247
+ const { response: routeResponse, error } = await runHooks([{
248
+ hooks: routeMiddleware,
249
+ arg: ev
250
+ }], async () => {
254
251
  switch (handler.type) {
255
252
  case 0:
256
253
  case 4:
257
254
  if (ev.request.method === "GET") return handleResponse(ev, url, template, await loadView(ev, url, handler, params, template));
258
- else if (ev.request.method === "POST") return handleResponse(ev, url, template, await runAction(ev, url, handler, handler.serverEndPoint && (await handler.serverEndPoint()).default, params, query, template), true);
255
+ else if (ev.request.method === "POST") {
256
+ const serverEndPoint = handler.serverEndPoint && (await handler.serverEndPoint()).default;
257
+ return handleResponse(ev, url, template, await runAction(ev, url, handler, serverEndPoint, params, query, template), true);
258
+ }
259
259
  break;
260
260
  case 1:
261
261
  case 5:
@@ -265,46 +265,39 @@ function createServerLoad(router, basePath = "", middleware = [], dev = false) {
265
265
  return handleResponse(ev, url, template, await runAction(ev, url, handler, serverEndPoint, params, query, template), true);
266
266
  }
267
267
  break;
268
- case 3: return await loadData(ev, url, handler, ev.request.method.toLowerCase().replace("delete", "del"), params);
268
+ case 3: {
269
+ const functionName = ev.request.method.toLowerCase().replace("delete", "del");
270
+ return await loadData(ev, url, handler, functionName, params);
271
+ }
269
272
  case 6:
270
273
  case 7: break;
271
274
  case 8: return await loadView(ev, url, handler, params, template, $page.status);
272
275
  }
273
- } finally {
274
- while (enteredRoute > 0) {
275
- enteredRoute--;
276
- await routeMiddleware[enteredRoute].exit?.(ev);
277
- }
278
- }
279
- return notFound();
276
+ }, { event: ev });
277
+ if (error) throw error;
278
+ return routeResponse ?? notFound();
280
279
  };
281
280
  return async function load(ev, template) {
282
- let entered = 0;
283
- try {
284
- let response = void 0;
285
- for (; entered < middleware.length && !response; entered++) {
286
- const result = await middleware[entered].enter?.(ev);
287
- if (result) response = result;
288
- }
289
- if (response) return response;
281
+ const { response, error } = await runHooks([{
282
+ hooks: middleware,
283
+ arg: ev
284
+ }], async () => {
290
285
  return await handle(ev, template);
291
- } catch (error) {
292
- ev.error = error;
293
- try {
294
- const url = stripBaseFromUrl(ev.url, basePath) ?? ev.url;
295
- if (router.match(url.pathname, url.searchParams)?.handler.type !== 3) {
296
- $page.url = url;
297
- const response = await renderErrorPage(ev, url, template, router, 500, error instanceof Error ? error.message : String(error));
298
- if (response) return response;
299
- }
300
- } catch {}
301
- throw error;
302
- } finally {
303
- while (entered > 0) {
304
- entered--;
305
- await middleware[entered].exit?.(ev);
286
+ }, {
287
+ event: ev,
288
+ onError: async (ev, error) => {
289
+ try {
290
+ const url = stripBaseFromUrl(ev.url, basePath) ?? ev.url;
291
+ if (router.match(url.pathname, url.searchParams)?.handler.type !== 3) {
292
+ $page.url = url;
293
+ return await renderErrorPage(ev, url, template, router, 500, error instanceof Error ? error.message : String(error));
294
+ }
295
+ } catch {}
296
+ throw error;
306
297
  }
307
- }
298
+ });
299
+ if (error && !response) throw error;
300
+ return response;
308
301
  };
309
302
  }
310
303
  /**
@@ -360,20 +353,14 @@ async function loadData(ev, url, handler, functionName, params) {
360
353
  const values = schema ? functionName === "get" || functionName === "head" || functionName === "load" ? { query: await validate(schema, searchParamsToRecord(url.searchParams)) } : { json: await validate(schema, await ev.json()) } : {};
361
354
  const serverParams = buildServerParams(ev, url, params, values);
362
355
  const hooks = handler.serverHooks ? await loadServerHooks(handler) : [];
363
- let entered = 0;
364
- let enterResponse = void 0;
365
- try {
366
- for (; entered < hooks.length && !enterResponse; entered++) {
367
- const hookResult = await hooks[entered].enter?.(serverParams);
368
- if (hookResult) enterResponse = hookResult;
369
- }
370
- return enterResponse || await handlerFn(serverParams) || ok();
371
- } finally {
372
- while (entered > 0) {
373
- entered--;
374
- await hooks[entered].exit?.(serverParams);
375
- }
376
- }
356
+ const { response, error } = await runHooks([{
357
+ hooks,
358
+ arg: serverParams
359
+ }], async () => {
360
+ return await handlerFn(serverParams) || void 0;
361
+ });
362
+ if (error) throw error;
363
+ return response || ok();
377
364
  } catch (error) {
378
365
  const response = validationErrorResponse(error);
379
366
  if (response) return response;
@@ -414,19 +401,13 @@ async function loadPageData(ev, pageUrl, handler, params, reusedLayouts) {
414
401
  const serverHooks = await loadServerHooks(handler);
415
402
  const routeMiddleware = Array.isArray(serverEndPoint?.middleware) ? serverEndPoint.middleware : [];
416
403
  const loads = [];
417
- let enteredMiddleware = 0;
418
- let entered = 0;
419
- let enterResponse = void 0;
420
- try {
421
- for (; enteredMiddleware < routeMiddleware.length && !enterResponse; enteredMiddleware++) {
422
- const middlewareResult = await routeMiddleware[enteredMiddleware].enter?.(ev);
423
- if (middlewareResult) enterResponse = middlewareResult;
424
- }
425
- for (; entered < serverHooks.length && !enterResponse; entered++) {
426
- const hookResult = await serverHooks[entered].enter?.(serverParams);
427
- if (hookResult) enterResponse = hookResult;
428
- }
429
- if (enterResponse) return enterResponse;
404
+ const { response, error } = await runHooks([{
405
+ hooks: routeMiddleware,
406
+ arg: ev
407
+ }, {
408
+ hooks: serverHooks,
409
+ arg: serverParams
410
+ }], async () => {
430
411
  for (const layout of handler.layouts ?? []) {
431
412
  if (reusedLayouts.has(layout.path)) {
432
413
  loads.push(null);
@@ -440,16 +421,9 @@ async function loadPageData(ev, pageUrl, handler, params, reusedLayouts) {
440
421
  if (pageResult instanceof Response) return pageResult;
441
422
  loads.push(pageResult);
442
423
  return serverDataResponse(loads);
443
- } finally {
444
- while (entered > 0) {
445
- entered--;
446
- await serverHooks[entered].exit?.(serverParams);
447
- }
448
- while (enteredMiddleware > 0) {
449
- enteredMiddleware--;
450
- await routeMiddleware[enteredMiddleware].exit?.(ev);
451
- }
452
- }
424
+ }, { event: ev });
425
+ if (error) throw error;
426
+ return response;
453
427
  }
454
428
  /**
455
429
  * Splits each route's server data into critical values and deferred entries,
@@ -577,15 +551,11 @@ async function loadView(ev, url, handler, params, template, status, form, fromFo
577
551
  }
578
552
  const serverParams = buildServerParams(ev, url, params, query ? { query } : {}, appData);
579
553
  const serverHooks = fromForm ? [] : await loadServerHooks(handler);
580
- let entered = 0;
581
- let enterResponse = void 0;
582
554
  let deferredEntries = [];
583
- try {
584
- for (; entered < serverHooks.length && !enterResponse; entered++) {
585
- const hookResult = await serverHooks[entered].enter?.(serverParams);
586
- if (hookResult) enterResponse = hookResult;
587
- }
588
- if (enterResponse) return enterResponse;
555
+ const { response, error } = await runHooks([{
556
+ hooks: serverHooks,
557
+ arg: serverParams
558
+ }], async () => {
589
559
  let data = {};
590
560
  const loads = [];
591
561
  if (handler.layouts) for (let layout of handler.layouts) {
@@ -640,7 +610,8 @@ async function loadView(ev, url, handler, params, template, status, form, fromFo
640
610
  params,
641
611
  data
642
612
  };
643
- const headPoints = [clientEndPoint, ...await Promise.all((handler.layouts ?? []).map(async (layout) => await layout.endPoint()))].reverse();
613
+ const layoutEndPoints = await Promise.all((handler.layouts ?? []).map(async (layout) => await layout.endPoint()));
614
+ const headPoints = [clientEndPoint, ...layoutEndPoints].reverse();
644
615
  for (const endPoint of headPoints) {
645
616
  const headElements = typeof endPoint.head === "function" ? await endPoint.head(event) : endPoint.head;
646
617
  if (headElements) headData += headElements.map((element) => markupOf(element)).join("");
@@ -671,12 +642,9 @@ async function loadView(ev, url, handler, params, template, status, form, fromFo
671
642
  status: status ?? 200,
672
643
  headers: { "Content-Type": "text/html" }
673
644
  });
674
- } finally {
675
- while (entered > 0) {
676
- entered--;
677
- await serverHooks[entered].exit?.(serverParams);
678
- }
679
- }
645
+ });
646
+ if (error) throw error;
647
+ return response;
680
648
  }
681
649
  /**
682
650
  * Streams a rendered page whose server data contained deferred values. The
@@ -756,20 +724,15 @@ async function runAction(ev, url, handler, serverEndPoint, params, query, templa
756
724
  const form = schema ? await validate(schema, await formDataToRecord(ev.request)) : void 0;
757
725
  serverParams = buildServerParams(ev, url, params, form ? { form } : {});
758
726
  const serverHooks = await loadServerHooks(handler);
759
- let entered = 0;
760
- let enterResponse = void 0;
761
- try {
762
- for (; entered < serverHooks.length && !enterResponse; entered++) {
763
- const hookResult = await serverHooks[entered].enter?.(serverParams);
764
- if (hookResult) enterResponse = hookResult;
765
- }
766
- result = enterResponse || await action(serverParams);
767
- } finally {
768
- while (entered > 0) {
769
- entered--;
770
- await serverHooks[entered].exit?.(serverParams);
771
- }
772
- }
727
+ const actionParams = serverParams;
728
+ const { response: hookResponse, error: hookError } = await runHooks([{
729
+ hooks: serverHooks,
730
+ arg: actionParams
731
+ }], async () => {
732
+ return await action(actionParams) || void 0;
733
+ });
734
+ if (hookError) throw hookError;
735
+ result = hookResponse;
773
736
  } catch (error) {
774
737
  const response = validationErrorResponse(error);
775
738
  if (response) return response;
@@ -900,4 +863,4 @@ function escapeHtml(value) {
900
863
  //#endregion
901
864
  export { createServerLoad as t };
902
865
 
903
- //# sourceMappingURL=serverHandlers-BpKfaFsD.mjs.map
866
+ //# sourceMappingURL=serverHandlers-CSBUEgJt.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverHandlers-CSBUEgJt.mjs","names":[],"sources":["../src/form/formDataToRecord.ts","../src/state/$serverPage.ts","../src/utils/searchParamsToRecord.ts","../src/validation/endpoint.ts","../src/site/layoutSlots.ts","../src/site/mergeHead.ts","../src/site/serverHandlers.ts"],"sourcesContent":["import type { FormDataRecord } from \"../types/ServerLoadEvent\";\n\n/**\n * Converts the submitted fields of a form request into a plain record: one\n * value per field, or an array when a field was submitted with multiple\n * values (e.g. a multi select). File inputs pass through as `File` values;\n * coercing them is left to the schema or the action.\n *\n * @param request The request (or FormData directly)\n * @returns The field values\n */\nexport default async function formDataToRecord(\n\trequest: Request | FormData,\n): Promise<FormDataRecord> {\n\tconst formData = request instanceof FormData ? request : await request.formData();\n\tconst result: FormDataRecord = {};\n\tfor (const key of formData.keys()) {\n\t\tif (key in result) continue;\n\t\tconst values = formData.getAll(key);\n\t\tresult[key] = values.length > 1 ? values : values[0];\n\t}\n\treturn result;\n}\n","import { $watch } from \"@torpor/view/ssr\";\nimport type PageState from \"../types/PageState\";\n\nconst PAGE_SYMBOL: unique symbol = Symbol.for(\"torp.Page\");\n\n// The server request path has no reactive subscribers, so the state is\n// stored plainly ($watch from `@torpor/view/ssr` is a no-op that returns\n// the object itself) instead of through a reactive proxy. Shares the same\n// `globalThis` slot as the client `$page`, so both variants always see the\n// same state object whichever loads first.\nconst $page: PageState =\n\t// @ts-ignore\n\t(globalThis[PAGE_SYMBOL] ??= $watch({\n\t\tstatus: 404,\n\t\turl: new URL(\"http://localhost\"),\n\t\tform: undefined,\n\t\tflash: undefined,\n\t\terror: {\n\t\t\tmessage: \"\",\n\t\t},\n\t}));\n\nexport default $page;\n","import type { QueryRecord } from \"../types/ServerLoadEvent\";\n\n/**\n * Converts a URL's query string into a plain record: one string per param,\n * or an array when a param was repeated.\n *\n * @param searchParams The URL's search params\n * @returns The param values\n */\nexport default function searchParamsToRecord(searchParams: URLSearchParams): QueryRecord {\n\tconst result: QueryRecord = {};\n\tfor (const key of searchParams.keys()) {\n\t\tif (key in result) continue;\n\t\tconst values = searchParams.getAll(key);\n\t\tresult[key] = values.length > 1 ? values : values[0];\n\t}\n\treturn result;\n}\n","import type PageServerEndPoint from \"../types/PageServerEndPoint\";\nimport type ServerEndPoint from \"../types/ServerEndPoint\";\nimport type { StandardSchemaV1 } from \"../types/StandardSchema\";\nimport type ServerEvent from \"../server/ServerEvent\";\nimport searchParamsToRecord from \"../utils/searchParamsToRecord\";\nimport unprocessable from \"../response/unprocessable\";\nimport ValidationError from \"./ValidationError\";\nimport validate from \"./validate\";\n\n/**\n * Loose views of an endpoint's schema map, keyed by handler/action name (plus\n * the reserved `params` key). The type-level constraint differs per endpoint\n * type, but the runtime treats them the same.\n */\ntype Schemas = Record<string, StandardSchemaV1 | undefined>;\n\ntype EndPoint = ServerEndPoint | PageServerEndPoint;\n\n/**\n * Gets the standard schema declared for a handler or action, if any. The\n * schemas map is keyed by name; the runtime treats it as a loose record.\n */\nexport function endpointSchema(endPoint: EndPoint, name: string): StandardSchemaV1 | undefined {\n\treturn (endPoint.schema as Schemas | undefined)?.[name];\n}\n\n/**\n * Validates the route params against the endpoint's `params` schema, if it\n * declares one, returning the coerced params. Throws a ValidationError when\n * they don't match, which callers turn into a 404 (params come from the URL,\n * so a failed validation means the resource doesn't exist).\n *\n * @param endPoint The endpoint declaring the (optional) `params` schema\n * @param params The route params from the matched route\n * @returns The validated params\n */\nexport async function validateEndpointParams(\n\tendPoint: EndPoint,\n\tparams: Record<string, any>,\n): Promise<Record<string, any>> {\n\tconst schema = endpointSchema(endPoint, \"params\");\n\treturn schema ? ((await validate(schema, params)) as Record<string, any>) : params;\n}\n\n/**\n * Validates a handler's input against its schema: get/head handlers and load\n * functions validate the URL's query string, other handlers validate the JSON\n * request body. Returns the validated values (an empty object when no schema\n * is declared), which callers pass through to the handler's event.\n *\n * @param schema The handler's (optional) schema\n * @param functionName The handler name (`get`, `post`, `load`, etc)\n * @param url The request URL, for the query string\n * @param ev The server event, for the request body\n * @returns The validated values\n */\nexport async function validateHandlerInput(\n\tschema: StandardSchemaV1 | undefined,\n\tfunctionName: string,\n\turl: URL,\n\tev: ServerEvent,\n): Promise<{ json?: unknown; form?: unknown; query?: unknown }> {\n\tif (!schema) return {};\n\tif (functionName === \"get\" || functionName === \"head\" || functionName === \"load\") {\n\t\treturn { query: await validate(schema, searchParamsToRecord(url.searchParams)) };\n\t}\n\treturn { json: await validate(schema, await ev.json()) };\n}\n\n/**\n * Turns a ValidationError thrown during endpoint validation into a 422\n * response with the schema's issues. Returns undefined for any other error,\n * which callers should rethrow.\n *\n * @param error The error thrown by a handler or validation\n * @returns A 422 response, or undefined when the error isn't a validation failure\n */\nexport function validationErrorResponse(error: unknown): Response | undefined {\n\tif (error instanceof ValidationError) {\n\t\treturn unprocessable({ message: error.message, issues: error.issues });\n\t}\n\treturn undefined;\n}\n","/**\n * Layouts are composed by the layout engine passing each layout (and finally\n * the page) as the default slot of its parent — so every `_layout` component\n * must render `<slot />`, or pass the default slot down to a child component\n * it renders. A layout that doesn't drops its entire content: the server\n * renders the layout's own markup with an empty content area (no error), and\n * the first client-side navigation that reuses the layout crashes on a null\n * slot region.\n *\n * The static `checkLayoutSlots` check catches this at build/dev time; these\n * helpers report it at request time for the cases static analysis can't see\n * (e.g. a `<slot />` rendered conditionally inside `@if`). They are\n * server-side only — nothing here is imported into the client bundle.\n */\n\n/**\n * Returns the path of the outermost layout that never rendered its\n * `<slot />`, or undefined when every level rendered.\n *\n * Slot level j (1-based) is the slot render that layout j - 1 receives: the\n * root layout (layouts[0]) renders level 1, layout i renders level i + 1,\n * and level layouts.length renders the page. A broken level makes every\n * deeper level unreachable, so the first level that never ran identifies\n * the offending layout.\n */\nexport function findMissingSlotLayout(\n\tlayouts: readonly { path: string }[],\n\tinvokedLevels: ReadonlySet<number>,\n): string | undefined {\n\tfor (let level = 1; level <= layouts.length; level++) {\n\t\tif (!invokedLevels.has(level)) {\n\t\t\treturn layouts[level - 1].path;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nconst warnedLayouts = new Set<string>();\n\n/**\n * Reports a layout that dropped its slot content. The condition is a genuine\n * rendering bug (the page content is missing from the output), so it is not\n * dev-gated — but it warns only once per layout path to avoid per-request\n * noise.\n */ export function warnMissingSlotContent(layoutPath: string): void {\n\tif (warnedLayouts.has(layoutPath)) return;\n\twarnedLayouts.add(layoutPath);\n\tconsole.warn(\n\t\t`[torpor] The layout at \"${layoutPath}\" never rendered <slot />, so the page content ` +\n\t\t\t`was not included in the render. Every _layout component must render <slot /> (or ` +\n\t\t\t`pass the default slot down to a child component it renders).`,\n\t);\n}\n","const TITLE_REGEX = /<title(?:\\s[^>]*)?>[\\s\\S]*?<\\/title>/g;\nconst FIRST_TITLE_REGEX = /<title(?:\\s[^>]*)?>[\\s\\S]*?<\\/title>/;\n\n/**\n * Merges the head string rendered by a page (and its layouts) into the site\n * template. The first <title> in the head string -- the page's, since pages\n * render before the layouts around them -- wins, overriding both any later\n * component title (e.g. from a child component) and a static <title> in the\n * template itself. All other head content (styles, meta elements, etc) is\n * appended where %COMPONENT_HEAD% sits in the template, before </head>.\n */\nexport default function mergeHead(template: string, head: string): string {\n\tconst titles = head.match(TITLE_REGEX);\n\tlet html = template;\n\tlet headHtml = head;\n\tif (titles?.length) {\n\t\theadHtml = head.replace(TITLE_REGEX, \"\");\n\t\thtml = html.replace(FIRST_TITLE_REGEX, \"\");\n\t\theadHtml = titles[0] + headHtml;\n\t}\n\treturn html.replace(\"%COMPONENT_HEAD%\", headHtml);\n}\n","import { type ServerComponent, type ServerSlotRender } from \"@torpor/view/ssr\";\nimport { DATA_REUSE_HEADER, DATA_REQUEST_HEADER } from \"../dataRequest.ts\";\nimport { type DeferredMeta, jsonForScript, splitDeferred } from \"../deferred.ts\";\nimport formDataToRecord from \"../form/formDataToRecord.ts\";\nimport notFound from \"../response/notFound.ts\";\nimport ok from \"../response/ok.ts\";\nimport { readResponseBody } from \"../response/read.ts\";\nimport ServerEvent from \"../server/ServerEvent.ts\";\nimport runHooks from \"../server/runHooks.ts\";\nimport type MiddlewareFunction from \"../server/types/MiddlewareFunction\";\nimport $page from \"../state/$serverPage.ts\";\nimport type PageEndPoint from \"../types/PageEndPoint.ts\";\nimport type { HeadElement } from \"../types/PageEndPoint.ts\";\nimport type PageLoadEvent from \"../types/PageLoadEvent.ts\";\nimport type PageServerEndPoint from \"../types/PageServerEndPoint.ts\";\nimport type RouteHandler from \"../types/RouteHandler.ts\";\nimport type ServerRequest from \"../types/ServerRequest.ts\";\nimport {\n\tERROR_ROUTE,\n\tHOOK_ROUTE,\n\tHOOK_SERVER_ROUTE,\n\tLAYOUT_ROUTE,\n\tLAYOUT_SERVER_ROUTE,\n\tPAGE_ROUTE,\n\tPAGE_SERVER_ROUTE,\n\tSERVER_ROUTE,\n} from \"../types/RouteType\";\nimport type ServerEndPoint from \"../types/ServerEndPoint.ts\";\nimport type ServerHook from \"../types/ServerHook.ts\";\nimport type ServerLoadEvent from \"../types/ServerLoadEvent.ts\";\nimport searchParamsToRecord from \"../utils/searchParamsToRecord.ts\";\nimport validate from \"../validation/validate.ts\";\nimport ValidationError from \"../validation/ValidationError.ts\";\nimport {\n\tendpointSchema,\n\tvalidateEndpointParams,\n\tvalidationErrorResponse,\n} from \"../validation/endpoint.ts\";\nimport { findMissingSlotLayout, warnMissingSlotContent } from \"./layoutSlots.ts\";\nimport { getBasePath, rewriteBaseInHtml, setBasePath, stripBaseFromUrl } from \"./basePath.ts\";\nimport findErrorRoute from \"./findErrorRoute.ts\";\nimport mergeHead from \"./mergeHead.ts\";\nimport type Router from \"./Router.ts\";\n\n/**\n * The site's request handler, as created by `createServerLoad`.\n */\nexport type ServerLoad = (ev: ServerEvent, template?: string) => Promise<Response>;\n\n/** Whether the site is running under `tb --dev` (set by `createServerLoad`). */\nlet devMode = false;\n\n/** Route paths already reminded about embedded-data caching, so it warns once. */\nconst warnedEmbedRoutes = new Set<string>();\n\n/**\n * Dev-only reminder for a page that embeds its server data in the HTML (so a\n * shared cache could serve one user's data to another) without an explicit\n * `Cache-Control`. Setting any `Cache-Control` — `private`/`no-store` for\n * user-specific data, `public` for pages that are safe to share — silences it.\n * Warns once per route path.\n */\nfunction warnUncachedEmbeddedData(ev: ServerEvent, path: string): void {\n\tif (!devMode || warnedEmbedRoutes.has(path)) return;\n\t// Only an explicitly-set response header counts; header names are\n\t// case-insensitive, so scan rather than a single map lookup\n\tfor (const name of ev.headers.headers.keys()) {\n\t\tif (name.toLowerCase() === \"cache-control\") return;\n\t}\n\twarnedEmbedRoutes.add(path);\n\tconsole.warn(\n\t\t`[torpor] The page at \"${path}\" embeds its server load data in the HTML but sets no ` +\n\t\t\t`Cache-Control, so a shared cache could serve one user's data to another. Set it on ` +\n\t\t\t`the response from a load or hook — \"private, no-cache\" (or \"no-store\") for ` +\n\t\t\t`user-specific data, or \"public\" if the page is safe to share.`,\n\t);\n}\n\n/**\n * Creates the site's request handler for the given router. This is kept\n * separate from serverEntry, which imports the virtual\n * `@torpor/build/manifest` module (it only exists when a site runs or\n * builds), so that tests can exercise the handlers with their own routes.\n *\n * @param router The router, built from the site's routes\n * @param basePath The site's base path, stripped from incoming URLs before\n * routing (see basePath.ts)\n * @param middleware Global middleware (from `site.middleware`), run for\n * every request before routing -- including requests that won't match a\n * route\n * @returns The request handler, which takes the site template\n */\nexport function createServerLoad(\n\trouter: Router,\n\tbasePath = \"\",\n\tmiddleware: MiddlewareFunction[] = [],\n\tdev = false,\n): ServerLoad {\n\t// The base path is shared through module state, so that everything that\n\t// generates URLs (HTML attributes, redirect locations) sees the same\n\t// value the router strips\n\tsetBasePath(basePath);\n\tdevMode = dev;\n\n\t/**\n\t * Finalizes the response of a load or action. Successful responses and\n\t * redirects pass through; an error response gets the site's error page\n\t * rendered at the requested url, with the error's status code -- the\n\t * address bar keeps the url the user asked for, so a transient failure\n\t * (a random db hiccup, say) can be refreshed, and a typo in the path can\n\t * be seen and fixed.\n\t */\n\tasync function handleResponse(\n\t\tev: ServerEvent,\n\t\turl: URL,\n\t\ttemplate: string | undefined,\n\t\tresponse: Response,\n\t\tfromForm = false,\n\t): Promise<Response> {\n\t\t// Success codes and redirect codes are acceptable\n\t\tif (response.status >= 200 && response.status <= 399) {\n\t\t\treturn response;\n\t\t}\n\n\t\t// 4xx error codes are acceptable from form actions\n\t\tif (fromForm && response.status >= 400 && response.status <= 499) {\n\t\t\treturn response;\n\t\t}\n\n\t\t// Read a clone, not the response itself: when the error page can't\n\t\t// render (e.g. its own load redirects), the original response is\n\t\t// returned below and its body must still be readable\n\t\tlet message = await response.clone().text();\n\t\tif (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\ttry {\n\t\t\t\tconst data = JSON.parse(message);\n\t\t\t\tmessage = data.message ?? message;\n\t\t\t} catch {\n\t\t\t\t// Not actually json, so show the raw body\n\t\t\t}\n\t\t}\n\t\tconst rendered = await renderErrorPage(ev, url, template, router, response.status, message);\n\t\t// No error page (or rendering it failed), so the response is passed\n\t\t// through as-is\n\t\treturn rendered ?? response;\n\t}\n\n\tconst handle = async (ev: ServerEvent, template?: string): Promise<Response> => {\n\t\t// The base is stripped before routing, so that everything below (route\n\t\t// matching, params, user code reading `event.url`) is base-free.\n\t\t// Requests that don't carry the base aren't ours\n\t\tconst url = stripBaseFromUrl(ev.url, basePath);\n\t\tif (!url) {\n\t\t\t// Like any other error, the error page is rendered at the\n\t\t\t// requested url rather than redirecting into the site\n\t\t\t$page.url = ev.url;\n\t\t\tconst response = await renderErrorPage(ev, ev.url, template, router, 404, \"Not found\");\n\t\t\treturn response ?? notFound();\n\t\t}\n\t\tconst path = url.pathname;\n\t\tconst query = url.searchParams;\n\n\t\t// A client data request: one GET to `<page url>/~server` returns the\n\t\t// server data for the page and all of its layouts, with hooks running\n\t\t// once against the page url. It doesn't need a registered `~server`\n\t\t// route (a page may have no `+page.server.ts` but still have layouts\n\t\t// with server loads)\n\t\tif (\n\t\t\tev.request.method === \"GET\" &&\n\t\t\tev.request.headers.has(DATA_REQUEST_HEADER) &&\n\t\t\tpath.endsWith(\"/~server\")\n\t\t) {\n\t\t\tconst pagePath = path.slice(0, -\"/~server\".length) || \"/\";\n\t\t\tconst pageUrl = new URL(pagePath + url.search, url);\n\t\t\tconst pageRoute = router.match(pagePath, query);\n\t\t\tif (pageRoute) {\n\t\t\t\t$page.url = pageUrl;\n\t\t\t\treturn await loadPageData(\n\t\t\t\t\tev,\n\t\t\t\t\tpageUrl,\n\t\t\t\t\tpageRoute.handler,\n\t\t\t\t\tpageRoute.params ?? {},\n\t\t\t\t\treusedLayoutPaths(ev),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t//console.log(`handling ${ev.request.method} for '${path}'${query.size ? ` with ${query}` : \"\"}`);\n\n\t\t// Update $page before routing, so that a request that doesn't match\n\t\t// any route (and gets the error page) still sees this url\n\t\t$page.url = url;\n\t\tif (path.endsWith(\"/_error\")) {\n\t\t\t$page.status = parseInt(query.get(\"status\") ?? \"404\");\n\t\t\t$page.error = { message: query.get(\"message\") ?? \"\" };\n\t\t} else {\n\t\t\t$page.status = 200;\n\t\t\t$page.error = { message: \"\" };\n\t\t}\n\n\t\tlet route = router.match(path, query);\n\t\tif (!route) {\n\t\t\t// If the route wasn't found, the user may be posting a form to a\n\t\t\t// +page.server.ts route that doesn't have a corresponding +page.ts\n\t\t\t// route, which is allowed, so check for that as well\n\t\t\tif (ev.request.method === \"POST\" && !path.endsWith(\"/~server\")) {\n\t\t\t\tconst serverPath =\n\t\t\t\t\t(path.endsWith(\"/\") ? path.substring(0, path.length - 1) : path) + \"/~server\";\n\t\t\t\troute = router.match(serverPath, query);\n\t\t\t}\n\t\t}\n\t\tif (!route) {\n\t\t\treturn handleResponse(ev, url, template, notFound());\n\t\t}\n\t\tconst handler = route.handler;\n\t\tconst params = route.params || {};\n\t\t// Route middleware, declared on the route's server endpoint\n\t\t// (+page.server.ts / +server.ts). Runs after the global middleware and\n\t\t// before folder hooks, so a guard can skip data loading entirely\n\t\tconst routeMiddleware: MiddlewareFunction[] = [];\n\t\tconst endPointModule = handler.serverEndPoint\n\t\t\t? (await handler.serverEndPoint())?.default\n\t\t\t: handler.type === PAGE_SERVER_ROUTE || handler.type === SERVER_ROUTE\n\t\t\t\t? (await resolveModule(handler))?.default\n\t\t\t\t: undefined;\n\t\tif (Array.isArray(endPointModule?.middleware)) {\n\t\t\trouteMiddleware.push(...endPointModule.middleware);\n\t\t}\n\n\t\t// TODO: Hit the server hook out here\n\t\t// We could maybe set up data loading as middleware on a route??????\n\n\t\t// Run the route's middleware around the handler: enter hooks in order\n\t\t// (a Response short-circuits the request), exit hooks in reverse\n\t\tconst { response: routeResponse, error } = await runHooks(\n\t\t\t[{ hooks: routeMiddleware, arg: ev }],\n\t\t\tasync () => {\n\t\t\t\tswitch (handler.type) {\n\t\t\t\t\tcase PAGE_ROUTE:\n\t\t\t\t\tcase LAYOUT_ROUTE: {\n\t\t\t\t\t\t// It's a /+page.ts or /_layout.ts endpoint\n\t\t\t\t\t\tif (ev.request.method === \"GET\") {\n\t\t\t\t\t\t\treturn handleResponse(\n\t\t\t\t\t\t\t\tev,\n\t\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\t\ttemplate,\n\t\t\t\t\t\t\t\tawait loadView(ev, url, handler, params, template),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else if (ev.request.method === \"POST\") {\n\t\t\t\t\t\t\t// The server end point comes from the sibling /+page.server.ts, if applicable\n\t\t\t\t\t\t\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\t\t\t\t\t\t\thandler.serverEndPoint && (await handler.serverEndPoint()).default;\n\t\t\t\t\t\t\treturn handleResponse(\n\t\t\t\t\t\t\t\tev,\n\t\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\t\ttemplate,\n\t\t\t\t\t\t\t\tawait runAction(ev, url, handler, serverEndPoint, params, query, template),\n\t\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase PAGE_SERVER_ROUTE:\n\t\t\t\t\tcase LAYOUT_SERVER_ROUTE: {\n\t\t\t\t\t\t// It's a /+page.server.ts or /_layout.server.ts endpoint\n\t\t\t\t\t\tif (ev.request.method === \"GET\") {\n\t\t\t\t\t\t\treturn await loadData(ev, url, handler, \"load\", params);\n\t\t\t\t\t\t} else if (ev.request.method === \"POST\") {\n\t\t\t\t\t\t\tconst serverEndPoint: PageServerEndPoint | undefined = (await resolveModule(handler))\n\t\t\t\t\t\t\t\t.default;\n\t\t\t\t\t\t\treturn handleResponse(\n\t\t\t\t\t\t\t\tev,\n\t\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\t\ttemplate,\n\t\t\t\t\t\t\t\tawait runAction(ev, url, handler, serverEndPoint, params, query, template),\n\t\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase SERVER_ROUTE: {\n\t\t\t\t\t\t// It's a /+server.ts endpoint\n\t\t\t\t\t\tconst functionName = ev.request.method.toLowerCase().replace(\"delete\", \"del\");\n\t\t\t\t\t\treturn await loadData(ev, url, handler, functionName, params);\n\t\t\t\t\t}\n\t\t\t\t\tcase HOOK_ROUTE:\n\t\t\t\t\tcase HOOK_SERVER_ROUTE: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase ERROR_ROUTE: {\n\t\t\t\t\t\t// A direct request for the error page (e.g. a bookmark of\n\t\t\t\t\t\t// the url it used to be redirected to, or the prerender\n\t\t\t\t\t\t// writing 404.html). It responds with the requested status\n\t\t\t\t\t\t// rather than 200\n\t\t\t\t\t\treturn await loadView(ev, url, handler, params, template, $page.status);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t},\n\t\t\t{ event: ev },\n\t\t);\n\t\tif (error) {\n\t\t\tthrow error;\n\t\t}\n\n\t\treturn routeResponse ?? notFound();\n\t};\n\n\treturn async function load(ev: ServerEvent, template?: string): Promise<Response> {\n\t\t// Global middleware, from `site.middleware`: runs for every request\n\t\t// before routing, including ones that won't match a route\n\t\t// (maintenance mode, legacy url redirects, etc)\n\t\tconst { response, error } = await runHooks(\n\t\t\t[{ hooks: middleware, arg: ev }],\n\t\t\tasync () => {\n\t\t\t\treturn await handle(ev, template);\n\t\t\t},\n\t\t\t{\n\t\t\t\tevent: ev,\n\t\t\t\tonError: async (ev, error) => {\n\t\t\t\t\t// A thrown exception (a load or component crashing, say) gets the\n\t\t\t\t\t// error page rendered at the requested url, like an error response\n\t\t\t\t\t// would -- unless the request was for an api endpoint (json in,\n\t\t\t\t\t// json out), or there is no error page, or rendering it failed, in\n\t\t\t\t\t// which case the error is rethrown for the server adapters\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst url = stripBaseFromUrl(ev.url, basePath) ?? ev.url;\n\t\t\t\t\t\tconst match = router.match(url.pathname, url.searchParams);\n\t\t\t\t\t\tif (match?.handler.type !== SERVER_ROUTE) {\n\t\t\t\t\t\t\t$page.url = url;\n\t\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\t\treturn await renderErrorPage(ev, url, template, router, 500, message);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Fall through to the rethrow\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tif (error && !response) {\n\t\t\tthrow error;\n\t\t}\n\t\t// handle() always returns a Response (notFound() on a fall-through)\n\t\treturn response as Response;\n\t};\n}\n\n/**\n * Resolves the route's endpoint module, caching it on the handler so warm\n * requests don't pay for the loader promise.\n */\nasync function resolveModule(handler: RouteHandler): Promise<any> {\n\treturn (handler.resolvedModule ??= await (handler.modulePromise ??= handler.endPoint()));\n}\n\nasync function loadServerHooks(handler: RouteHandler): Promise<ServerHook[]> {\n\tif (!handler.serverHooks) return [];\n\t// Resolve each hook module once and cache the result on the handler\n\treturn (handler.resolvedHooks ??= Promise.all(\n\t\thandler.serverHooks.map(async (load) => (await load()).default),\n\t));\n}\n\n/**\n * Renders the site's nearest error page for a url, with the given status\n * code and message, at the url itself. Returns undefined when the site has\n * no matching error route, or when rendering the error page failed -- the\n * caller passes the original response or error through instead.\n *\n * The error page runs through the normal view pipeline, so it is rendered\n * inside the layouts of its route (e.g. the root `/_error` gets the root\n * `_layout`).\n */\nasync function renderErrorPage(\n\tev: ServerEvent,\n\turl: URL,\n\ttemplate: string | undefined,\n\trouter: Router,\n\tstatus: number,\n\tmessage: string,\n): Promise<Response | undefined> {\n\tconst errorPath = findErrorRoute(router, url.pathname);\n\tif (!errorPath) {\n\t\treturn undefined;\n\t}\n\t// Matched (rather than picked off `router.routes`) so that the error\n\t// route's layouts, server endpoint and hooks get loaded\n\tconst errorRoute = router.match(errorPath, new URLSearchParams());\n\tif (!errorRoute) {\n\t\treturn undefined;\n\t}\n\n\t$page.status = status;\n\t$page.error = { message };\n\n\ttry {\n\t\tconst response = await loadView(ev, url, errorRoute.handler, {}, template, status);\n\t\t// A load or layout of the error page can itself fail -- loadView\n\t\t// returns its response, which (unlike a rendered error page) won't\n\t\t// be html. The caller passes the original response through instead\n\t\tif (response.headers.get(\"Content-Type\")?.includes(\"text/html\")) {\n\t\t\treturn response;\n\t\t}\n\t\treturn undefined;\n\t} catch (error) {\n\t\t// The error page itself blew up; the caller's original response or\n\t\t// error is the better fallback\n\t\tconsole.log(error);\n\t\treturn undefined;\n\t}\n}\n\nasync function loadData(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tfunctionName: string,\n\tparams: Record<string, any>,\n) {\n\t// The endpoint module is cached on the handler, so once warm this is a\n\t// plain property read\n\tconst mod = handler.resolvedModule ?? (await resolveModule(handler));\n\tconst serverEndPoint: ServerEndPoint | undefined = mod?.default;\n\t// `functionName` is computed from the request method, so the handlers are\n\t// accessed through a loose record\n\tconst handlerFn = (\n\t\tserverEndPoint as unknown as Record<string, ServerRequest | undefined> | undefined\n\t)?.[functionName];\n\tif (!serverEndPoint || !handlerFn) {\n\t\treturn notFound();\n\t}\n\n\t// Route params come from the URL, so a failed validation means the\n\t// resource doesn't exist. Only endpoints declaring a params schema pay\n\t// for validation\n\tconst paramsSchema = endpointSchema(serverEndPoint, \"params\");\n\tif (paramsSchema) {\n\t\ttry {\n\t\t\tparams = (await validate(paramsSchema, params)) as Record<string, any>;\n\t\t} catch (error) {\n\t\t\tif (error instanceof ValidationError) return notFound();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\ttry {\n\t\t// If the endpoint declares a schema for this handler, validate its\n\t\t// input up front and reject with 422 if it fails. get/head/load\n\t\t// schemas validate the query string; other schemas validate the json\n\t\t// body. Endpoints without a schema skip straight to the handler\n\t\tconst schema = endpointSchema(serverEndPoint, functionName);\n\t\tconst values = schema\n\t\t\t? functionName === \"get\" || functionName === \"head\" || functionName === \"load\"\n\t\t\t\t? { query: await validate(schema, searchParamsToRecord(url.searchParams)) }\n\t\t\t\t: { json: await validate(schema, await ev.json()) }\n\t\t\t: {};\n\n\t\tconst serverParams = buildServerParams(ev, url, params, values);\n\n\t\t// Hooks are resolved once per handler; routes without hooks don't\n\t\t// await anything here\n\t\tconst hooks = handler.serverHooks ? await loadServerHooks(handler) : [];\n\n\t\tconst { response, error } = await runHooks([{ hooks, arg: serverParams }], async () => {\n\t\t\treturn (await handlerFn(serverParams)) || undefined;\n\t\t});\n\t\tif (error) {\n\t\t\tthrow error;\n\t\t}\n\n\t\t// A hook's enter response short-circuits the request; otherwise, if\n\t\t// there was no response returned from load (such as errors or a\n\t\t// redirect), send an ok response\n\t\treturn response || ok();\n\t} catch (error) {\n\t\tconst response = validationErrorResponse(error);\n\t\tif (response) return response;\n\t\tthrow error;\n\t}\n}\n\n/**\n * Handles a client data request (see `DATA_REQUEST_HEADER`). Runs the folder\n * hooks once against the page url, then loads the server data for each layout\n * (root to leaf) and the page, returning `{ loads: [...] }` -- one entry per\n * layout plus the page, in the same order as `handler.layouts`. The client\n * runs its own load functions and merges the server entries in.\n *\n * A load that redirects or fails short-circuits the whole request, so the\n * client can fall back to a full page load (redirect) or render the error\n * page (failure), exactly as it would with a single page load.\n */\nasync function loadPageData(\n\tev: ServerEvent,\n\tpageUrl: URL,\n\thandler: RouteHandler,\n\tparams: Record<string, any>,\n\treusedLayouts: Set<string>,\n): Promise<Response> {\n\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\thandler.serverEndPoint && (await handler.serverEndPoint())?.default;\n\n\t// Validate params and the load query against the page's server endpoint\n\t// schemas, mirroring a normal page render. Params come from the url, so a\n\t// failed params validation means the resource doesn't exist\n\tlet query: unknown;\n\tif (serverEndPoint) {\n\t\ttry {\n\t\t\tparams = await validateEndpointParams(serverEndPoint, params);\n\t\t} catch (error) {\n\t\t\tif (error instanceof ValidationError) return notFound();\n\t\t\tthrow error;\n\t\t}\n\t\tconst loadSchema = endpointSchema(serverEndPoint, \"load\");\n\t\tif (loadSchema) {\n\t\t\ttry {\n\t\t\t\tquery = await validate(loadSchema, searchParamsToRecord(pageUrl.searchParams));\n\t\t\t} catch (error) {\n\t\t\t\tconst response = validationErrorResponse(error);\n\t\t\t\tif (response) return response;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst serverParams = buildServerParams(ev, pageUrl, params, query ? { query } : {});\n\tconst serverHooks = await loadServerHooks(handler);\n\t// Route middleware, declared on the page's server endpoint. Runs before\n\t// the folder hooks, like it does for a normal request\n\tconst routeMiddleware = Array.isArray(serverEndPoint?.middleware)\n\t\t? serverEndPoint.middleware\n\t\t: [];\n\n\t// One entry per layout (root to leaf) followed by the page itself\n\tconst loads: (Record<string, any> | null)[] = [];\n\n\tconst { response, error } = await runHooks(\n\t\t[\n\t\t\t// Route middleware, declared on the page's server endpoint. Runs\n\t\t\t// before the folder hooks, like it does for a normal request\n\t\t\t{ hooks: routeMiddleware, arg: ev },\n\t\t\t// Hooks run from the root down; a hook's enter can return a Response\n\t\t\t// to short-circuit the request (e.g. an auth redirect)\n\t\t\t{ hooks: serverHooks, arg: serverParams },\n\t\t],\n\t\tasync () => {\n\t\t\tfor (const layout of handler.layouts ?? []) {\n\t\t\t\t// A reused layout keeps its cached data on the client, so skip its\n\t\t\t\t// load (and any side effects) but keep the slot aligned\n\t\t\t\tif (reusedLayouts.has(layout.path)) {\n\t\t\t\t\tloads.push(null);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst layoutServerEndPoint: PageServerEndPoint | undefined =\n\t\t\t\t\tlayout.serverEndPoint && (await layout.serverEndPoint())?.default;\n\t\t\t\tconst result = await loadRouteServerData(layoutServerEndPoint, serverParams);\n\t\t\t\tif (result instanceof Response) return result;\n\t\t\t\tloads.push(result);\n\t\t\t}\n\n\t\t\tconst pageResult = await loadRouteServerData(serverEndPoint, serverParams);\n\t\t\tif (pageResult instanceof Response) return pageResult;\n\t\t\tloads.push(pageResult);\n\n\t\t\treturn serverDataResponse(loads);\n\t\t},\n\t\t{ event: ev },\n\t);\n\tif (error) {\n\t\tthrow error;\n\t}\n\treturn response as Response;\n}\n\ntype LoadDeferredEntry = {\n\tid: string;\n\tmeta: DeferredMeta;\n\tpromise: PromiseLike<unknown>;\n};\n\n/**\n * Splits each route's server data into critical values and deferred entries,\n * assigning ids in response order. Both the streaming data response and the\n * SSR-embedded payload use this so their ids/paths line up.\n */\nfunction splitLoads(loads: (Record<string, any> | null)[]): {\n\tcriticalLoads: (Record<string, any> | null)[];\n\tentries: LoadDeferredEntry[];\n} {\n\tconst entries: LoadDeferredEntry[] = [];\n\tconst criticalLoads = loads.map((load, index) => {\n\t\tif (load === null) return null;\n\t\tconst { critical, entries: splitEntries } = splitDeferred(load);\n\t\tfor (const entry of splitEntries) {\n\t\t\tconst id = `d${entries.length}`;\n\t\t\tentries.push({\n\t\t\t\tid,\n\t\t\t\tmeta: { id, index, path: entry.path },\n\t\t\t\tpromise: entry.promise,\n\t\t\t});\n\t\t}\n\t\treturn critical as Record<string, any>;\n\t});\n\treturn { criticalLoads, entries };\n}\n\n/**\n * Serializes a data request's loads. Critical (non-promise) values go in the\n * first frame as one JSON object per route; promise-valued properties are\n * announced in the same frame and then streamed as NDJSON frames, so a\n * navigation can mount as soon as the critical data arrives.\n */\nfunction serverDataResponse(loads: (Record<string, any> | null)[]): Response {\n\tconst { criticalLoads, entries } = splitLoads(loads);\n\n\tif (entries.length === 0) {\n\t\treturn new Response(JSON.stringify({ loads: criticalLoads }), {\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t});\n\t}\n\n\tconst first = {\n\t\ttype: \"data\",\n\t\tloads: criticalLoads,\n\t\tdeferred: entries.map((entry) => entry.meta),\n\t};\n\tconst encoder = new TextEncoder();\n\tlet cancelled = false;\n\tconst stream = new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst write = (frame: object) => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(JSON.stringify(frame) + \"\\n\"));\n\t\t\t\t} catch {\n\t\t\t\t\t// The client went away; the promise handlers below finish\n\t\t\t\t\t// without anything left to write to\n\t\t\t\t}\n\t\t\t};\n\t\t\twrite(first);\n\t\t\tvoid Promise.all(\n\t\t\t\tentries.map(async (entry) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\twrite({ type: \"value\", id: entry.id, value: await entry.promise });\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\twrite({ type: \"error\", id: entry.id, message: errorMessage(error) });\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t).finally(() => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// Already closed by an aborted stream\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tcancel() {\n\t\t\tcancelled = true;\n\t\t},\n\t});\n\treturn new Response(stream, {\n\t\theaders: { \"Content-Type\": \"application/x-ndjson\" },\n\t});\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Runs a single route's server load (if any) as part of a data request.\n * Returns the loaded data, `null` when the route has no load, or the raw\n * Response when the load redirected or failed.\n */\nasync function loadRouteServerData(\n\tserverEndPoint: PageServerEndPoint | undefined,\n\tserverParams: ServerLoadEvent,\n): Promise<Record<string, any> | null | Response> {\n\tif (!serverEndPoint?.load) return null;\n\tconst response = await serverEndPoint.load(serverParams);\n\tif (!response) return null;\n\tif (!response.ok) return response;\n\treturn (await readResponseBody(response)) ?? null;\n}\n\nasync function loadView(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tparams: Record<string, any>,\n\ttemplate: string | undefined,\n\t// The status to respond with: a form action's result status, or an\n\t// error page's status (404, 500, ...). Defaults to 200\n\tstatus?: number,\n\tform?: Record<string, string | number>,\n\tfromForm?: boolean,\n\t// The appData that the server hooks populated around the form action,\n\t// passed through so the re-render's loads see the same data\n\tappData?: Record<string, any>,\n) {\n\t// There must be a client endpoint with a component\n\tconst clientEndPoint: PageEndPoint | undefined = (await resolveModule(handler)).default;\n\tif (!clientEndPoint?.component) {\n\t\treturn notFound();\n\t}\n\n\t// Consume the flash message when a page is rendered (but not for API\n\t// requests), so that the following page -- and only that page -- can show\n\t// it. For a form action that re-renders instead of redirecting, the\n\t// message is set and read within this request\n\t$page.flash = ev.flash.get();\n\n\t// The template comes from site.html, which endpoints-only sites don't have\n\tif (!template) {\n\t\tthrow new Error(\n\t\t\t\"Page routes require a src/site.html file, which was not found; add it, or remove page/layout routes to serve endpoints only\",\n\t\t);\n\t}\n\n\t// There may be a server endpoint\n\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\thandler.serverEndPoint && (await handler.serverEndPoint())?.default;\n\n\t// Validate the route params and the load query against the server\n\t// endpoint's schemas, if it declares any. Params come from the URL, so a\n\t// failed validation means the resource doesn't exist; a failed query goes\n\t// to the error page like any other load failure\n\tlet query: unknown;\n\tif (serverEndPoint) {\n\t\ttry {\n\t\t\tparams = await validateEndpointParams(serverEndPoint, params);\n\t\t} catch (error) {\n\t\t\tif (error instanceof ValidationError) return notFound();\n\t\t\tthrow error;\n\t\t}\n\t\tconst loadSchema = endpointSchema(serverEndPoint, \"load\");\n\t\tif (loadSchema) {\n\t\t\tconst queryRecord = searchParamsToRecord(url.searchParams);\n\t\t\ttry {\n\t\t\t\tquery = await validate(loadSchema, queryRecord);\n\t\t\t} catch (error) {\n\t\t\t\t// A form re-render's url is the POST's, and a form action can\n\t\t\t\t// drop query params that the load schema requires, so failing\n\t\t\t\t// validation here would lose the form errors. Fall back to the\n\t\t\t\t// raw query values instead and let the load make of them what\n\t\t\t\t// it can\n\t\t\t\tif (fromForm) {\n\t\t\t\t\tquery = queryRecord;\n\t\t\t\t} else {\n\t\t\t\t\tconst response = validationErrorResponse(error);\n\t\t\t\t\tif (response) return response;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Maybe hit the server hooks -- unless they already ran for this request,\n\t// which is the case when the view is re-rendered after a form action. In\n\t// that case the hooks' appData is passed through, so that the loads below\n\t// see the same data (e.g. the user set by an auth hook) as the action did\n\tconst serverParams = buildServerParams(ev, url, params, query ? { query } : {}, appData);\n\tconst serverHooks = fromForm ? [] : await loadServerHooks(handler);\n\t// Promise-valued server data, streamed to the client after the critical\n\t// data (see the embedding block below)\n\tlet deferredEntries: LoadDeferredEntry[] = [];\n\n\t// Hooks run around the view render: enter hooks in order (a Response\n\t// short-circuits the render), exit hooks in reverse\n\tconst { response, error } = await runHooks(\n\t\t[{ hooks: serverHooks, arg: serverParams }],\n\t\tasync () => {\n\t\t\t// Pass the data into $props\n\t\t\t// TODO: Promise.all\n\t\t\t// NOTE: We're loading data from top to bottom, overriding as we go, and I'm\n\t\t\t// not sure if this is the best way to go\n\t\t\tlet data = {};\n\t\t\t// Each route's server-only data (root layout to page), embedded into\n\t\t\t// the HTML so the first hydration doesn't refetch it (nav/loadData.ts)\n\t\t\tconst loads: (Record<string, any> | null)[] = [];\n\t\t\tif (handler.layouts) {\n\t\t\t\tfor (let layout of handler.layouts) {\n\t\t\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await layout.endPoint())?.default;\n\t\t\t\t\tconst layoutServerEndPoint: PageServerEndPoint | undefined =\n\t\t\t\t\t\tlayout.serverEndPoint && (await layout.serverEndPoint())?.default;\n\t\t\t\t\tconst layoutResponse = await loadClientAndServerData(\n\t\t\t\t\t\turl,\n\t\t\t\t\t\tparams,\n\t\t\t\t\t\tserverParams,\n\t\t\t\t\t\tdata,\n\t\t\t\t\t\tlayoutEndPoint,\n\t\t\t\t\t\tlayoutServerEndPoint,\n\t\t\t\t\t\tloads,\n\t\t\t\t\t);\n\t\t\t\t\tif (layoutResponse?.ok === false) {\n\t\t\t\t\t\treturn layoutResponse;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet endPointResponse = await loadClientAndServerData(\n\t\t\t\turl,\n\t\t\t\tparams,\n\t\t\t\tserverParams,\n\t\t\t\tdata,\n\t\t\t\tclientEndPoint,\n\t\t\t\tserverEndPoint,\n\t\t\t\tloads,\n\t\t\t);\n\t\t\tif (endPointResponse?.ok === false) {\n\t\t\t\treturn endPointResponse;\n\t\t\t}\n\t\t\tlet $props: Record<string, any> = { data, form };\n\n\t\t\tlet styles = \"\";\n\n\t\t\t// If there are layouts, work our way upwards, pushing each component into\n\t\t\t// the default slot of its parent\n\t\t\t// TODO: Also handle layout server data\n\t\t\t// TODO: There's probably a nicer way to do this with reducers or something\n\t\t\tlet component = clientEndPoint.component as ServerComponent;\n\t\t\tlet slots: Record<string, ServerSlotRender> | undefined = undefined;\n\t\t\t// Which slot levels actually ran during the render below, so a layout\n\t\t\t// that never rendered its <slot /> (silently dropping the page\n\t\t\t// content) can be reported (see findMissingSlotLayout)\n\t\t\tconst invokedLevels = new Set<number>();\n\t\t\tconst trackSlot = (level: number, slot: ServerSlotRender): ServerSlotRender => {\n\t\t\t\treturn ($slot, $context) => {\n\t\t\t\t\tinvokedLevels.add(level);\n\t\t\t\t\treturn slot($slot, $context);\n\t\t\t\t};\n\t\t\t};\n\t\t\tif (handler.layouts) {\n\t\t\t\tlet slotFunctions: ServerSlotRender[] = [];\n\t\t\t\t// The last slot function will render the client component\n\t\t\t\tslotFunctions[handler.layouts.length] = trackSlot(\n\t\t\t\t\thandler.layouts.length,\n\t\t\t\t\tasync (_, $context) => {\n\t\t\t\t\t\tlet { body, head } = await (clientEndPoint.component as ServerComponent)(\n\t\t\t\t\t\t\t$props,\n\t\t\t\t\t\t\t$context,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tstyles += head;\n\t\t\t\t\t\treturn body;\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tfor (let i = handler.layouts.length - 1; i >= 0; i--) {\n\t\t\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await handler.layouts[i].endPoint())\n\t\t\t\t\t\t?.default;\n\t\t\t\t\tif (layoutEndPoint?.component) {\n\t\t\t\t\t\tif (i === 0) {\n\t\t\t\t\t\t\tcomponent = layoutEndPoint.component as ServerComponent;\n\t\t\t\t\t\t\tslots = { _: slotFunctions[i + 1] };\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tslotFunctions[i] = trackSlot(i, async (_, $context) => {\n\t\t\t\t\t\t\t\tlet { body, head } = await (layoutEndPoint.component as ServerComponent)(\n\t\t\t\t\t\t\t\t\t$props,\n\t\t\t\t\t\t\t\t\t$context,\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t_: slotFunctions[i + 1],\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tstyles += head;\n\t\t\t\t\t\t\t\treturn body;\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet html;\n\t\t\ttry {\n\t\t\t\tlet { body, head } = await component($props, undefined, slots);\n\n\t\t\t\t// Render the page's (and its layouts') head element data, if the\n\t\t\t\t// endpoint declared any. Layouts lose to the page (the nearest\n\t\t\t\t// endpoint wins, as with @head content), and everything loses to\n\t\t\t\t// the first title in the compiled head -- which mergeHead keeps\n\t\t\t\tlet headData = \"\";\n\t\t\t\tconst event = { url, params, data } as PageLoadEvent;\n\t\t\t\tconst layoutEndPoints = await Promise.all(\n\t\t\t\t\t(handler.layouts ?? []).map(async (layout) => await layout.endPoint()),\n\t\t\t\t);\n\t\t\t\tconst headPoints = [clientEndPoint, ...layoutEndPoints].reverse();\n\t\t\t\tfor (const endPoint of headPoints) {\n\t\t\t\t\tconst headElements =\n\t\t\t\t\t\ttypeof endPoint.head === \"function\" ? await endPoint.head(event) : endPoint.head;\n\t\t\t\t\tif (headElements) {\n\t\t\t\t\t\theadData += headElements.map((element: HeadElement) => markupOf(element)).join(\"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Put the form info in a hidden input so that it can be accessed on the client\n\t\t\t\tif (form) {\n\t\t\t\t\tbody += `\\n<input type=\"hidden\" id=\"t-form-data\" value='${JSON.stringify(form).replaceAll(\"'\", \"\\\\'\")}' />`;\n\t\t\t\t}\n\n\t\t\t\t// Embed the routes' server-only data as json so the client's first\n\t\t\t\t// hydration reads it instead of making a `/~server` round trip\n\t\t\t\t// (nav/loadData.ts consumes it once and removes it). The condition\n\t\t\t\t// mirrors the client's `hasServerData`, so a route with only hooks or\n\t\t\t\t// actions still ships an all-null array that saves the refetch.\n\t\t\t\t// Promise values are left out and streamed as small scripts after\n\t\t\t\t// the page, so the render doesn't wait for them.\n\t\t\t\tif (routeHasServerData(handler)) {\n\t\t\t\t\tconst { criticalLoads, entries } = splitLoads(loads);\n\t\t\t\t\tdeferredEntries = entries;\n\t\t\t\t\tconst payload: {\n\t\t\t\t\t\tloads: (Record<string, any> | null)[];\n\t\t\t\t\t\tdeferred?: DeferredMeta[];\n\t\t\t\t\t} = { loads: criticalLoads };\n\t\t\t\t\tif (entries.length > 0) {\n\t\t\t\t\t\tpayload.deferred = entries.map((entry) => entry.meta);\n\t\t\t\t\t}\n\t\t\t\t\tconst json = JSON.stringify(payload).replaceAll(\"<\", \"\\\\u003c\");\n\t\t\t\t\tbody += `\\n<script type=\"application/json\" id=\"t-server-data\">${json}</script>`;\n\t\t\t\t\t// Nudge towards an explicit cache policy only when real data\n\t\t\t\t\t// was embedded (a payload of only nulls carries nothing)\n\t\t\t\t\tif (loads.some((load) => load !== null)) {\n\t\t\t\t\t\twarnUncachedEmbeddedData(ev, handler.path);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tstyles += head;\n\t\t\t\thtml = rewriteBaseInHtml(\n\t\t\t\t\tmergeHead(template, styles + headData).replace(\"%COMPONENT_BODY%\", body),\n\t\t\t\t\tgetBasePath(),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\t// TODO: Show a proper Error component\n\t\t\t\thtml = '<span style=\"color: red\">Script syntax error</span><p>' + error + \"</p>\";\n\t\t\t\tdeferredEntries = [];\n\t\t\t\tconsole.log(error);\n\t\t\t}\n\n\t\t\t// A layout that never rendered <slot /> silently drops the whole page\n\t\t\t// content from the output; find and report the outermost one\n\t\t\tif (handler.layouts) {\n\t\t\t\tconst missingLayout = findMissingSlotLayout(handler.layouts, invokedLevels);\n\t\t\t\tif (missingLayout !== undefined) {\n\t\t\t\t\twarnMissingSlotContent(missingLayout);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (deferredEntries.length > 0) {\n\t\t\t\treturn streamHtmlResponse(html, status ?? 200, deferredEntries);\n\t\t\t}\n\n\t\t\treturn new Response(html, {\n\t\t\t\tstatus: status ?? 200,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t);\n\tif (error) {\n\t\tthrow error;\n\t}\n\treturn response as Response;\n}\n\n/**\n * Streams a rendered page whose server data contained deferred values. The\n * page HTML (with skeletons/`with` branches) is sent immediately, then each\n * deferred value arrives as a tiny script that resolves its promise in the\n * client's hydration store. This is not component streaming: the SSR markup\n * for deferred values comes from the client's `$async`/`@await` boundaries.\n */\nfunction streamHtmlResponse(html: string, status: number, entries: LoadDeferredEntry[]): Response {\n\tconst encoder = new TextEncoder();\n\tconst bodyEnd = html.lastIndexOf(\"</body>\");\n\tconst before = bodyEnd === -1 ? html : html.slice(0, bodyEnd);\n\tconst after = bodyEnd === -1 ? \"\" : html.slice(bodyEnd);\n\tlet cancelled = false;\n\tconst stream = new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst write = (text: string) => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t} catch {\n\t\t\t\t\t// Client disconnected\n\t\t\t\t}\n\t\t\t};\n\t\t\twrite(before + deferredBootstrapScript());\n\t\t\tvoid Promise.all(\n\t\t\t\tentries.map(async (entry) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\twrite(deferredScript(entry.id, await entry.promise, false));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\twrite(deferredScript(entry.id, errorMessage(error), true));\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t).finally(() => {\n\t\t\t\twrite(after);\n\t\t\t\tif (cancelled) return;\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// Already closed\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tcancel() {\n\t\t\tcancelled = true;\n\t\t},\n\t});\n\treturn new Response(stream, {\n\t\tstatus,\n\t\theaders: { \"Content-Type\": \"text/html\" },\n\t});\n}\n\n/**\n * Creates the client-side deferred store before the inline resolve scripts\n * run. Guarded so a page with multiple deferred payloads doesn't replace a\n * store that still holds pending promises.\n */\nfunction deferredBootstrapScript(): string {\n\treturn (\n\t\t\"<script>(()=>{const g=globalThis;if(g.__torporDeferred)return;\" +\n\t\t\"const e=new Map();const get=id=>{let x=e.get(id);if(!x){let resolve,reject;\" +\n\t\t\"const promise=new Promise((res,rej)=>{resolve=res;reject=rej});promise.catch(()=>{});\" +\n\t\t\"x={promise,resolve,reject};e.set(id,x)}return x};\" +\n\t\t\"g.__torporDeferred={get,resolve:(id,v)=>get(id).resolve(v),\" +\n\t\t\"reject:(id,m)=>get(id).reject(m instanceof Error?m:new Error(String(m)))}})()</script>\"\n\t);\n}\n\n/** A script that settles one deferred entry in the hydration store. */\nfunction deferredScript(id: string, value: unknown, rejected: boolean): string {\n\tconst payload = rejected ? JSON.stringify(String(value)) : jsonForScript(value);\n\treturn `<script>__torporDeferred.${rejected ? \"reject\" : \"resolve\"}(${JSON.stringify(id)},${payload})</script>`;\n}\n\nasync function runAction(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tserverEndPoint: PageServerEndPoint | undefined,\n\tparams: Record<string, any>,\n\tquery: URLSearchParams,\n\ttemplate: string | undefined,\n) {\n\t// The action name rides in the query, so look for a `?/name` key rather\n\t// than taking the first key -- the url may carry ordinary load query\n\t// params as well (e.g. `?page=3&/like`, or a default action posted to a\n\t// url that already has a query). A key that names a declared action also\n\t// matches (e.g. `?set`), and a form without an action attribute calls the\n\t// `default` action\n\tconst queryKeys = Array.from(query.keys());\n\tconst actionKey =\n\t\tqueryKeys.find((key) => key.startsWith(\"/\")) ??\n\t\tqueryKeys.find((key) => !!serverEndPoint?.actions?.[key.replace(/^\\//, \"\")]);\n\tconst actionName = (actionKey ?? \"default\").replace(/^\\//, \"\");\n\tif (serverEndPoint?.actions) {\n\t\tconst action = serverEndPoint.actions[actionName];\n\t\tif (action) {\n\t\t\tif (actionName === \"load\" || actionName === \"params\") {\n\t\t\t\t// These names are reserved in the endpoint's schema map: `load`\n\t\t\t\t// validates the query string and `params` the route params, so\n\t\t\t\t// an action with one of these names would get the wrong schema\n\t\t\t\t// applied to its form data\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`The action name \"${actionName}\" is reserved. ` +\n\t\t\t\t\t\t`Rename the action (and its schema key, if any), e.g. to \"save\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Route params come from the URL, so a failed validation means the\n\t\t\t// resource doesn't exist\n\t\t\ttry {\n\t\t\t\tparams = await validateEndpointParams(serverEndPoint, params);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof ValidationError) return notFound();\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tlet result: Response | undefined | void;\n\t\t\t// The event that the hooks and action run with. It's kept around so\n\t\t\t// that the view re-render below can pass its appData (populated by\n\t\t\t// the hooks' enter functions) through to the loads\n\t\t\tlet serverParams: ServerLoadEvent | undefined = undefined;\n\t\t\ttry {\n\t\t\t\t// If the endpoint declares a schema for this action, validate the\n\t\t\t\t// submitted form data up front and reject with 422 if it fails\n\t\t\t\tconst schema = endpointSchema(serverEndPoint, actionName);\n\t\t\t\tconst form = schema\n\t\t\t\t\t? await validate(schema, await formDataToRecord(ev.request))\n\t\t\t\t\t: undefined;\n\n\t\t\t\tserverParams = buildServerParams(ev, url, params, form ? { form } : {});\n\n\t\t\t\tconst serverHooks = await loadServerHooks(handler);\n\t\t\t\t// Hooks run from the root down; a hook's enter can return a\n\t\t\t\t// Response to short-circuit the action\n\t\t\t\tconst actionParams = serverParams;\n\t\t\t\tconst { response: hookResponse, error: hookError } = await runHooks(\n\t\t\t\t\t[{ hooks: serverHooks, arg: actionParams }],\n\t\t\t\t\tasync () => {\n\t\t\t\t\t\treturn (await action(actionParams)) || undefined;\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (hookError) {\n\t\t\t\t\tthrow hookError;\n\t\t\t\t}\n\t\t\t\tresult = hookResponse;\n\t\t\t} catch (error) {\n\t\t\t\tconst response = validationErrorResponse(error);\n\t\t\t\tif (response) return response;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (ev.request.headers.has(\"X-Torpor-Form-Submit\")) {\n\t\t\t\t// If the form was submitted from javascript, just return the\n\t\t\t\t// response and it will be handled on the client\n\t\t\t\t// TODO: Should we make the user return a response??\n\t\t\t\tresult ??= ok();\n\n\t\t\t\t// If it's a redirect, we need to stop the browser handling it\n\t\t\t\tif (result.status >= 300 && result.status <= 399) {\n\t\t\t\t\tconst location = result.headers.get(\"Location\") ?? \"\";\n\t\t\t\t\tresult = ok();\n\t\t\t\t\tresult.headers.set(\"X-Torpor-Form-Redirect\", \"\");\n\t\t\t\t\tresult.headers.set(\"Location\", location);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t} else if (\n\t\t\t\t!result ||\n\t\t\t\t(result.status >= 200 && result.status <= 299) ||\n\t\t\t\t(result.status >= 400 && result.status <= 499)\n\t\t\t) {\n\t\t\t\t// If the form was submitted without javascript, and there was\n\t\t\t\t// no result, an ok result, or a 4xx error, re-render the view\n\t\t\t\t// with the form result. The server hooks already ran around the\n\t\t\t\t// action, so they are not run again here -- but their appData\n\t\t\t\t// is passed through, so that loads guarding on it (e.g. an\n\t\t\t\t// auth hook's user) re-render the page instead of erroring\n\t\t\t\t// Keep the query string, so that loads validating the query see\n\t\t\t\t// the same values as the original GET. If the form action\n\t\t\t\t// dropped params that the load schema requires, loadView falls\n\t\t\t\t// back to the raw query instead of failing validation\n\t\t\t\tconst newUrl = new URL(url.pathname + url.search, url);\n\t\t\t\tconst formStatus = result?.status;\n\t\t\t\tlet formMessage = await result?.text();\n\t\t\t\tif (formMessage && result?.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\t$page.form = JSON.parse(formMessage);\n\t\t\t\t\tformMessage = undefined;\n\t\t\t\t} else {\n\t\t\t\t\t$page.form = {};\n\t\t\t\t}\n\t\t\t\t// Set status and message if they haven't already been set,\n\t\t\t\t// which means that you can just return e.g. forbidden() or\n\t\t\t\t// forbidden(\"no!\") and there will be something you can work\n\t\t\t\t// with in your component, or you can set a completely custom\n\t\t\t\t// object with whatever info you need\n\t\t\t\t$page.form!.status ??= formStatus ?? 0;\n\t\t\t\t$page.form!.message ??= formMessage ?? \"\";\n\t\t\t\treturn await loadView(\n\t\t\t\t\tev,\n\t\t\t\t\tnewUrl,\n\t\t\t\t\thandler,\n\t\t\t\t\tparams,\n\t\t\t\t\ttemplate,\n\t\t\t\t\tformStatus,\n\t\t\t\t\t$page.form,\n\t\t\t\t\ttrue,\n\t\t\t\t\tserverParams?.appData,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// If the form was submitted without javascript and there was a\n\t\t\t\t// redirect or server error, just return the result to handle it\n\t\t\t\t// as normal\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn notFound();\n}\n\n/**\n * Whether the route has any server-side code to run (a page or layout server\n * endpoint, or a folder hook) — the same condition the client uses to decide\n * whether to make a `/~server` request (nav/loadData.ts's `hasServerData`).\n * When it holds, the render embeds a server-data payload so the first\n * hydration skips that request.\n */\nfunction routeHasServerData(handler: RouteHandler): boolean {\n\tif (handler.serverHooks && handler.serverHooks.length > 0) return true;\n\tif (handler.serverEndPoint) return true;\n\treturn (handler.layouts ?? []).some((layout) => !!layout.serverEndPoint);\n}\n\nasync function loadClientAndServerData(\n\turl: URL,\n\tparams: Record<string, any>,\n\tserverParams: ServerLoadEvent,\n\tdata: Record<string, any>,\n\tclientEndPoint?: PageEndPoint,\n\tserverEndPoint?: PageServerEndPoint,\n\tloads?: (Record<string, any> | null)[],\n) {\n\tif (clientEndPoint?.load) {\n\t\tconst clientParams = buildClientParams(url, params, data);\n\t\tconst clientResponse = await clientEndPoint.load(clientParams);\n\t\tif (clientResponse) {\n\t\t\tif (clientResponse.ok) {\n\t\t\t\tconst clientData = await readResponseBody(clientResponse);\n\t\t\t\tif (clientData) Object.assign(data, clientData);\n\t\t\t} else {\n\t\t\t\treturn clientResponse;\n\t\t\t}\n\t\t}\n\t}\n\tlet serverData: Record<string, any> | null = null;\n\tif (serverEndPoint?.load) {\n\t\tconst serverResponse = await serverEndPoint.load(serverParams);\n\t\tif (serverResponse) {\n\t\t\tif (serverResponse.ok) {\n\t\t\t\tserverData = (await readResponseBody(serverResponse)) ?? null;\n\t\t\t\tif (serverData) Object.assign(data, serverData);\n\t\t\t} else {\n\t\t\t\treturn serverResponse;\n\t\t\t}\n\t\t}\n\t}\n\t// Record this route's server-only data, aligned with the page and its\n\t// layouts (root to leaf), so the render can embed it for hydration\n\tloads?.push(serverData);\n}\n\nfunction buildClientParams(url: URL, params: Record<string, any>, data: Record<string, any>) {\n\treturn {\n\t\turl,\n\t\tparams,\n\t\tdata,\n\t};\n}\n\n/**\n * The layout paths a data request asked to reuse, from the `X-Torpor-Reuse`\n * header (a JSON array). A malformed header is ignored rather than failing the\n * request -- the client just gets the layouts loaded again.\n */\nfunction reusedLayoutPaths(ev: ServerEvent): Set<string> {\n\tconst header = ev.request.headers.get(DATA_REUSE_HEADER);\n\tif (!header) return new Set();\n\ttry {\n\t\tconst paths = JSON.parse(header) as unknown;\n\t\tif (Array.isArray(paths)) {\n\t\t\treturn new Set(paths.filter((p): p is string => typeof p === \"string\"));\n\t\t}\n\t} catch {\n\t\t// Not valid json\n\t}\n\treturn new Set();\n}\n\n/**\n * The url user code (hooks, loads, actions, `@head`) should see. Client-side\n * data fetches append `/~server` to the page url, but that suffix is an\n * internal detail: without stripping it, `event.url.pathname` would differ\n * between the server-rendered page and its `~server` request, so a hook\n * guarding on the path (e.g. `path !== \"/setup\"`) would misfire.\n */\nfunction requestUrl(url: URL): URL {\n\tif (!url.pathname.endsWith(\"/~server\")) return url;\n\tconst path = url.pathname.slice(0, -\"/~server\".length) || \"/\";\n\treturn new URL(path + url.search, url);\n}\n\nfunction buildServerParams(\n\tev: ServerEvent,\n\turl: URL,\n\tparams: Record<string, any>,\n\tvalues: { json?: unknown; form?: unknown; query?: unknown } = {},\n\tappData: Record<string, any> = {},\n): ServerLoadEvent {\n\tconst logicalUrl = requestUrl(url);\n\treturn {\n\t\turl: logicalUrl,\n\t\tparams,\n\t\tappData,\n\t\trequest: ev.request,\n\t\t// The inputs may have been validated already, in which case the request\n\t\t// body has been consumed and the parsed values are returned instead.\n\t\t// Their types come from the endpoint's schemas, so they are loosely\n\t\t// typed here\n\t\tjson: (): Promise<any> =>\n\t\t\tvalues.json !== undefined ? Promise.resolve(values.json) : ev.json(),\n\t\tform: (): Promise<any> =>\n\t\t\tvalues.form !== undefined ? Promise.resolve(values.form) : formDataToRecord(ev.request),\n\t\tquery: (): Promise<any> =>\n\t\t\tvalues.query !== undefined\n\t\t\t\t? Promise.resolve(values.query)\n\t\t\t\t: Promise.resolve(searchParamsToRecord(logicalUrl.searchParams)),\n\t\tcookies: ev.cookies,\n\t\theaders: ev.headers,\n\t\tsession: ev.session,\n\t\tflash: ev.flash,\n\t\tadapter: ev.adapter,\n\t};\n}\n\n/**\n * Renders a head element as markup. Attribute values are escaped, since\n * they can come from user data (e.g. a post title passed to `seo()`).\n */\nfunction markupOf(element: HeadElement): string {\n\tif (\"title\" in element) {\n\t\treturn `<title>${escapeHtml(element.title)}</title>`;\n\t}\n\tif (\"name\" in element) {\n\t\treturn `<meta name=\"${escapeHtml(element.name)}\" content=\"${escapeHtml(element.content)}\" />`;\n\t}\n\treturn `<meta property=\"${escapeHtml(element.property)}\" content=\"${escapeHtml(element.content)}\" />`;\n}\n\nfunction escapeHtml(value: string): string {\n\treturn value\n\t\t.replaceAll(\"&\", \"&amp;\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AI,IAAI,GAAG,KAAK;EACpE,YACC,OAAO,SAAS,KAAA,IAAY,QAAQ,QAAQ,OAAO,IAAI,IAAI,iBAAiB,GAAG,OAAO;EACvF,aACC,OAAO,UAAU,KAAA,IACd,QAAQ,QAAQ,OAAO,KAAK,IAC5B,QAAQ,QAAQ,qBAAqB,WAAW,YAAY,CAAC;EACjE,SAAS,GAAG;EACZ,SAAS,GAAG;EACZ,SAAS,GAAG;EACZ,OAAO,GAAG;EACV,SAAS,GAAG;CACb;AACD;;;;;AAMA,SAAS,SAAS,SAA8B;CAC/C,IAAI,WAAW,SACd,OAAO,UAAU,WAAW,QAAQ,KAAK,EAAE;CAE5C,IAAI,UAAU,SACb,OAAO,eAAe,WAAW,QAAQ,IAAI,EAAE,aAAa,WAAW,QAAQ,OAAO,EAAE;CAEzF,OAAO,mBAAmB,WAAW,QAAQ,QAAQ,EAAE,aAAa,WAAW,QAAQ,OAAO,EAAE;AACjG;AAEA,SAAS,WAAW,OAAuB;CAC1C,OAAO,MACL,WAAW,KAAK,OAAO,CAAC,CACxB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,MAAK,QAAQ;AAC3B"}
package/dist/test.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as Router } from "./Router-C4ADUfhv.mjs";
2
2
  import { t as ServerEvent } from "./ServerEvent-BY4f3RVF.mjs";
3
- import { t as createServerLoad } from "./serverHandlers-BpKfaFsD.mjs";
3
+ import { t as createServerLoad } from "./serverHandlers-CSBUEgJt.mjs";
4
4
  import fpath from "node:path";
5
5
  //#region src/test/runTest.ts
6
6
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torpor/build",
3
- "version": "1.8.4",
3
+ "version": "1.8.6",
4
4
  "description": "A framework for building sites and apps with Torpor",
5
5
  "type": "module",
6
6
  "exports": {
@@ -80,8 +80,8 @@
80
80
  "author": "",
81
81
  "license": "ISC",
82
82
  "dependencies": {
83
- "@torpor/unplugin": "^1.2.8",
84
- "@torpor/view": "^1.2.5",
83
+ "@torpor/unplugin": "^1.2.10",
84
+ "@torpor/view": "^1.3.0",
85
85
  "cookie": "^2.0.1",
86
86
  "dotenv": "^18.0.8",
87
87
  "vite": "npm:@voidzero-dev/vite-plus-core@1.2.0",
@@ -1 +0,0 @@
1
- {"version":3,"file":"Server-C0PGzSQO.mjs","names":[],"sources":["../src/server/Server.ts"],"sourcesContent":["import PathTrie from \"../utils/pathTrie\";\nimport ServerEvent from \"./ServerEvent\";\nimport type MiddlewareFunction from \"./types/MiddlewareFunction\";\nimport type ServerFunction from \"./types/ServerFunction\";\n\n/**\n * A Fetch API Request/Response server.\n */\nexport default class Server {\n\t// TODO: We don't use any of the routes, just add(\"*\") in runDev/runBuild...\n\troutes: RouteHandler[] = [];\n\t// Match index for the routes above\n\t#trie = new PathTrie<RouteHandler>();\n\t// TODO: We only use the Vite middleware here\n\tmiddleware: MiddlewareFunction[] = [];\n\n\tconstructor() {\n\t\tthis.routes = [];\n\t\tthis.middleware = [];\n\t}\n\n\t/**\n\t * The standard Fetch API method that should work in any runtime (including\n\t * Node with polyfills).\n\t * @returns\n\t */\n\tfetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n\t\t// Use the request as-is when we were given one, so that the adapter\n\t\t// doesn't pay for constructing it twice\n\t\tconst request = input instanceof Request && !init ? input : new Request(input, init);\n\t\tconst url = new URL(request.url);\n\t\tconst match = this.match(url.pathname);\n\t\tlet ev = new ServerEvent(request, match?.params, url);\n\n\t\tif (this.middleware.length) {\n\t\t\t// Route-scoped middleware is set on server endpoints (or globally on\n\t\t\t// `site.middleware`); this list is the low-level, per-Server primitive\n\t\t\tlet entered = 0;\n\t\t\tlet response: Response | undefined = undefined;\n\t\t\tlet error: unknown = undefined;\n\t\t\ttry {\n\t\t\t\tfor (; entered < this.middleware.length && !response; entered++) {\n\t\t\t\t\t// A middleware returns a Response to short-circuit the request\n\t\t\t\t\tconst result = await this.middleware[entered].enter?.(ev);\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tresponse = result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!response && match) {\n\t\t\t\t\tconst result = await match.fn(ev);\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tresponse = result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\t// Exits can handle the error by returning a Response; if none\n\t\t\t\t// does, it is rethrown below\n\t\t\t\terror = e;\n\t\t\t\tev.error = e;\n\t\t\t} finally {\n\t\t\t\tif (response) {\n\t\t\t\t\tev.response = response;\n\t\t\t\t}\n\t\t\t\t// Run exit hooks in reverse order for the middleware that were\n\t\t\t\t// entered. An exit hook can return a Response to replace the\n\t\t\t\t// response, or to handle ev.error\n\t\t\t\twhile (entered > 0) {\n\t\t\t\t\tentered--;\n\t\t\t\t\tconst result = await this.middleware[entered].exit?.(ev);\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tresponse = result;\n\t\t\t\t\t\tev.response = result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (error && !response) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} else if (match) {\n\t\t\tev.response = await match.fn(ev);\n\t\t} else {\n\t\t\treturn new Response(null, { status: 404 });\n\t\t}\n\n\t\t// TODO: Should I be returning 200 if there's no response? Because it's not an error??\n\t\tev.response ??= new Response(null, { status: 200 });\n\t\tev.addHeaders();\n\n\t\treturn ev.response;\n\t};\n\n\t/**\n\t * Adds a server function at a route path.\n\t * @param path The route path pattern.\n\t * @param fn The function to call when the pattern is matched.\n\t * @returns\n\t */\n\tadd(path: string, fn: ServerFunction): Server {\n\t\tlet handler = new RouteHandler(path, fn);\n\t\tthis.routes.push(handler);\n\t\tthis.#trie.insert(path, handler);\n\t\tthis.#sortRoutes();\n\t\treturn this;\n\t}\n\n\tmatch(path: string): Match | undefined {\n\t\tconst found = this.#trie.match(path);\n\t\tif (found) {\n\t\t\treturn {\n\t\t\t\tfn: found.value.fn,\n\t\t\t\tparams: found.params,\n\t\t\t};\n\t\t}\n\t\tconsole.log(`Server path not found: ${path}`);\n\t}\n\n\t// TODO:\n\t//use(path: string, ...fn: MiddlewareFunction[])\n\tuse(...fn: MiddlewareFunction[]): Server {\n\t\tthis.middleware = this.middleware.concat(fn);\n\t\treturn this;\n\t}\n\n\t#sortRoutes() {\n\t\tthis.routes = this.routes.sort((a, b) => {\n\t\t\t// Sort [param]s after paths\n\t\t\t// There might be a quicker/easier way to do this\n\t\t\tfor (let i = 0; i < Math.min(a.path.length, b.path.length); i++) {\n\t\t\t\tif (a.path[i] === \"[\" && b.path[i] !== \"[\") {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else if (b.path[i] === \"[\" && a.path[i] !== \"[\") {\n\t\t\t\t\treturn -1;\n\t\t\t\t} else if (a.path[i] === b.path[i]) {\n\t\t\t\t\t// Keep going...\n\t\t\t\t} else {\n\t\t\t\t\treturn a.path[i].localeCompare(b.path[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn a.path.length - b.path.length;\n\t\t});\n\t}\n}\n\nclass RouteHandler {\n\tpath: string;\n\tfn: ServerFunction;\n\n\tconstructor(path: string, fn: ServerFunction) {\n\t\tthis.path = path;\n\t\tthis.fn = fn;\n\t}\n}\n\n//class MiddlewareHandler {\n//\tpath: string;\n//\tregex: RegExp;\n//\tfn: MiddlewareFunction;\n//\n//\tconstructor(path: string, fn: MiddlewareFunction) {\n//\t\tthis.path = path;\n//\t\tthis.regex = pathToRegex(path);\n//\t\tthis.fn = fn;\n//\t}\n//}\n\ninterface Match {\n\tfn: ServerFunction;\n\tparams?: Record<string, string>;\n}\n"],"mappings":";;;;;;AAQA,IAAqB,SAArB,MAA4B;CAE3B,SAAyB,CAAC;CAE1B,QAAQ,IAAI,SAAuB;CAEnC,aAAmC,CAAC;CAEpC,cAAc;EACb,KAAK,SAAS,CAAC;EACf,KAAK,aAAa,CAAC;CAC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