@torpor/build 1.9.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.
Files changed (107) hide show
  1. package/README.md +1 -1
  2. package/dist/{SessionHelper-MaodMaLU.d.mts → CacheOptions-C4-ebVt9.d.mts} +58 -8
  3. package/dist/CacheOptions-C4-ebVt9.d.mts.map +1 -0
  4. package/dist/{MiddlewareFunction-BZilnEei.d.mts → MiddlewareFunction-DMYxjzF4.d.mts} +31 -2
  5. package/dist/MiddlewareFunction-DMYxjzF4.d.mts.map +1 -0
  6. package/dist/{Router-By9Nlg39.d.mts → Router-DyK3DTWQ.d.mts} +4 -4
  7. package/dist/Router-DyK3DTWQ.d.mts.map +1 -0
  8. package/dist/{Server-dcRbdPXf.mjs → Server-BCijhgZp.mjs} +3 -3
  9. package/dist/{Server-dcRbdPXf.mjs.map → Server-BCijhgZp.mjs.map} +1 -1
  10. package/dist/{Server-qn5Ws_d0.d.mts → Server-ClwvuilS.d.mts} +2 -2
  11. package/dist/{Server-qn5Ws_d0.d.mts.map → Server-ClwvuilS.d.mts.map} +1 -1
  12. package/dist/{ServerEvent-BY4f3RVF.mjs → ServerEvent-BBRkd4Ya.mjs} +136 -31
  13. package/dist/ServerEvent-BBRkd4Ya.mjs.map +1 -0
  14. package/dist/{ServerHook-W111nEhe.d.mts → ServerHook-DY-NSG6n.d.mts} +2 -2
  15. package/dist/{ServerHook-W111nEhe.d.mts.map → ServerHook-DY-NSG6n.d.mts.map} +1 -1
  16. package/dist/{ServerLoadEvent-BH6oG1o6.d.mts → ServerLoadEvent-CpcgsKCU.d.mts} +32 -8
  17. package/dist/ServerLoadEvent-CpcgsKCU.d.mts.map +1 -0
  18. package/dist/{Site-DGZJB7Do.d.mts → Site-BEMQW1_y.d.mts} +216 -11
  19. package/dist/Site-BEMQW1_y.d.mts.map +1 -0
  20. package/dist/{basePath-DQnbHc7o.mjs → basePath-B6hmOMl4.mjs} +89 -4
  21. package/dist/basePath-B6hmOMl4.mjs.map +1 -0
  22. package/dist/bin/index.js +37 -2
  23. package/dist/bin/index.js.map +1 -1
  24. package/dist/clientEntry.mjs +10 -5
  25. package/dist/clientEntry.mjs.map +1 -1
  26. package/dist/dev.d.mts +2 -2
  27. package/dist/dev.mjs +2 -2
  28. package/dist/{devPlugin-lLzauETn.mjs → devPlugin-BGrTpcC2.mjs} +3 -3
  29. package/dist/{devPlugin-lLzauETn.mjs.map → devPlugin-BGrTpcC2.mjs.map} +1 -1
  30. package/dist/discovery.d.mts +1 -1
  31. package/dist/discovery.mjs +1 -1
  32. package/dist/index.d.mts +22 -6
  33. package/dist/index.d.mts.map +1 -1
  34. package/dist/index.mjs +10 -0
  35. package/dist/index.mjs.map +1 -1
  36. package/dist/{load-BODDzmH0.mjs → load-Dw187nJ_.mjs} +95 -52
  37. package/dist/load-Dw187nJ_.mjs.map +1 -0
  38. package/dist/nav.d.mts +30 -3
  39. package/dist/nav.d.mts.map +1 -1
  40. package/dist/nav.mjs +40 -12
  41. package/dist/nav.mjs.map +1 -1
  42. package/dist/nodeDev.d.mts +1 -1
  43. package/dist/nodeDev.mjs +1 -1
  44. package/dist/openapi.d.mts +24 -80
  45. package/dist/openapi.d.mts.map +1 -1
  46. package/dist/openapi.mjs +36 -1
  47. package/dist/openapi.mjs.map +1 -0
  48. package/dist/{plugin-D8Www11B.mjs → plugin-BQsMnkTj.mjs} +42 -3
  49. package/dist/plugin-BQsMnkTj.mjs.map +1 -0
  50. package/dist/{read-DxMVAh5Y.mjs → read-CPW2iPum.mjs} +21 -2
  51. package/dist/read-CPW2iPum.mjs.map +1 -0
  52. package/dist/{response-C5EZsszY.mjs → response-B4UoOJvv.mjs} +3 -24
  53. package/dist/response-B4UoOJvv.mjs.map +1 -0
  54. package/dist/response.mjs +2 -2
  55. package/dist/run.d.mts +1 -1
  56. package/dist/run.d.mts.map +1 -1
  57. package/dist/run.mjs +1 -1
  58. package/dist/{runHooks-D5p1Rh7i.mjs → runHooks-C7kt7SEo.mjs} +36 -2
  59. package/dist/runHooks-C7kt7SEo.mjs.map +1 -0
  60. package/dist/{runOpenApi-C5yMpQU1.mjs → runOpenApi-DK-QnYEr.mjs} +279 -35
  61. package/dist/runOpenApi-DK-QnYEr.mjs.map +1 -0
  62. package/dist/server/Server.d.mts +1 -1
  63. package/dist/server/Server.mjs +1 -1
  64. package/dist/server.d.mts +30 -6
  65. package/dist/server.d.mts.map +1 -1
  66. package/dist/server.mjs +47 -3
  67. package/dist/server.mjs.map +1 -1
  68. package/dist/{serverEntry-BGii8bB6.d.mts → serverEntry-BFad1k1C.d.mts} +3 -3
  69. package/dist/serverEntry-BFad1k1C.d.mts.map +1 -0
  70. package/dist/{serverEntry-D1hE-Jzt.mjs → serverEntry-DAT7o7o2.mjs} +3 -5
  71. package/dist/serverEntry-DAT7o7o2.mjs.map +1 -0
  72. package/dist/serverEntry.d.mts +1 -1
  73. package/dist/serverEntry.mjs +1 -1
  74. package/dist/{serverHandlers-CSBUEgJt.mjs → serverHandlers-B1L8I72-.mjs} +434 -202
  75. package/dist/serverHandlers-B1L8I72-.mjs.map +1 -0
  76. package/dist/{sitemap-xmE0zfme.d.mts → sitemap-CKmagPyL.d.mts} +2 -2
  77. package/dist/{sitemap-xmE0zfme.d.mts.map → sitemap-CKmagPyL.d.mts.map} +1 -1
  78. package/dist/{sitemap-4imxJVrG.mjs → sitemap-DdzFjGlo.mjs} +2 -2
  79. package/dist/{sitemap-4imxJVrG.mjs.map → sitemap-DdzFjGlo.mjs.map} +1 -1
  80. package/dist/state.d.mts +1 -4
  81. package/dist/state.d.mts.map +1 -1
  82. package/dist/state.mjs +1 -1
  83. package/dist/test.d.mts +2 -2
  84. package/dist/test.mjs +2 -2
  85. package/dist/{unprocessable-DwAG44Rh.mjs → unprocessable-BZXwyN0n.mjs} +23 -2
  86. package/dist/unprocessable-BZXwyN0n.mjs.map +1 -0
  87. package/package.json +10 -7
  88. package/src/types/manifest.d.ts +3 -0
  89. package/dist/MiddlewareFunction-BZilnEei.d.mts.map +0 -1
  90. package/dist/Router-By9Nlg39.d.mts.map +0 -1
  91. package/dist/ServerEvent-BY4f3RVF.mjs.map +0 -1
  92. package/dist/ServerLoadEvent-BH6oG1o6.d.mts.map +0 -1
  93. package/dist/SessionHelper-MaodMaLU.d.mts.map +0 -1
  94. package/dist/Site-DGZJB7Do.d.mts.map +0 -1
  95. package/dist/_page-CW6SLuT4.mjs +0 -14
  96. package/dist/_page-CW6SLuT4.mjs.map +0 -1
  97. package/dist/basePath-DQnbHc7o.mjs.map +0 -1
  98. package/dist/load-BODDzmH0.mjs.map +0 -1
  99. package/dist/plugin-D8Www11B.mjs.map +0 -1
  100. package/dist/read-DxMVAh5Y.mjs.map +0 -1
  101. package/dist/response-C5EZsszY.mjs.map +0 -1
  102. package/dist/runHooks-D5p1Rh7i.mjs.map +0 -1
  103. package/dist/runOpenApi-C5yMpQU1.mjs.map +0 -1
  104. package/dist/serverEntry-BGii8bB6.d.mts.map +0 -1
  105. package/dist/serverEntry-D1hE-Jzt.mjs.map +0 -1
  106. package/dist/serverHandlers-CSBUEgJt.mjs.map +0 -1
  107. package/dist/unprocessable-DwAG44Rh.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runOpenApi-DK-QnYEr.mjs","names":["path","path","path","path","path","dependencyNames","path","path","path","fs","fs","path","asAliasArray","path","path","createViteServer","isInside","path","path","createViteServer","path","path","fs","path"],"sources":["../src/utils/tsconfigAliases.ts","../src/site/checkRoutes.ts","../src/site/checkLayoutSlots.ts","../src/site/manifest.ts","../src/utils/torporPackages.ts","../src/run/clientPreloads.ts","../src/run/pageSizes.ts","../src/run/runPrerender.ts","../src/run/runBuild.ts","../src/run/depCache.ts","../src/run/loadSite.ts","../src/run/staleTorpCopies.ts","../src/run/runDev.ts","../src/server/contentType.ts","../src/run/assetHeaders.ts","../src/run/runPreview.ts","../src/run/run.ts","../src/run/runOpenApi.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface AliasEntry {\n\tfind: string | RegExp;\n\treplacement: string;\n}\n\n/**\n * Reads `tsconfig.json` `compilerOptions.paths` (relative to `baseUrl`,\n * defaulting to the tsconfig directory) and converts them to Vite\n * `resolve.alias` entries. Only handles paths declared in the root tsconfig\n * (not inherited via `extends`).\n */\nexport default function tsconfigAliases(root: string): AliasEntry[] {\n\tconst file = path.join(root, \"tsconfig.json\");\n\tlet paths: Record<string, string[]> | undefined;\n\tlet baseUrl: string;\n\ttry {\n\t\tconst tsconfig = JSON.parse(stripJsonc(readFileSync(file, \"utf-8\")));\n\t\tconst compilerOptions = tsconfig.compilerOptions ?? {};\n\t\tbaseUrl = compilerOptions.baseUrl ? path.resolve(root, compilerOptions.baseUrl) : root;\n\t\tpaths = compilerOptions.paths;\n\t} catch {\n\t\treturn [];\n\t}\n\tif (!paths) return [];\n\n\tconst aliases: AliasEntry[] = [];\n\tfor (const [pattern, targets] of Object.entries(paths)) {\n\t\tconst target = targets?.[0];\n\t\tif (!target) continue;\n\t\tif (pattern.endsWith(\"*\")) {\n\t\t\t// `@/*` -> `./src/*`: match the literal prefix (`@/`) and rewrite to\n\t\t\t// the target dir. A string `find` is used (not a RegExp) because\n\t\t\t// Vite applies prefix-string aliases during SSR transform, which is\n\t\t\t// what makes path aliases resolve in the SSR module runner.\n\t\t\tconst find = pattern.slice(0, -1);\n\t\t\tconst targetDir = target.slice(0, -1);\n\t\t\taliases.push({\n\t\t\t\tfind,\n\t\t\t\treplacement: `${path.resolve(baseUrl, targetDir)}/`,\n\t\t\t});\n\t\t} else {\n\t\t\taliases.push({ find: pattern, replacement: path.resolve(baseUrl, target) });\n\t\t}\n\t}\n\treturn aliases;\n}\n\n/**\n * Strips JSONC comments and trailing commas so `tsconfig.json` (which permits\n * both) can be parsed with `JSON.parse`. String contents are preserved.\n */\nexport function stripJsonc(text: string): string {\n\tlet out = \"\";\n\tfor (let i = 0; i < text.length;) {\n\t\tconst c = text[i];\n\t\tif (c === '\"' || c === \"'\") {\n\t\t\tconst quote = c;\n\t\t\tout += c;\n\t\t\ti++;\n\t\t\twhile (i < text.length) {\n\t\t\t\tif (text[i] === \"\\\\\") {\n\t\t\t\t\tout += text[i] + (text[i + 1] ?? \"\");\n\t\t\t\t\ti += 2;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst cc = text[i++];\n\t\t\t\tout += cc;\n\t\t\t\tif (cc === quote) break;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (c === \"/\" && text[i + 1] === \"/\") {\n\t\t\ti += 2;\n\t\t\twhile (i < text.length && text[i] !== \"\\n\") i++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (c === \"/\" && text[i + 1] === \"*\") {\n\t\t\ti += 2;\n\t\t\twhile (i < text.length && !(text[i] === \"*\" && text[i + 1] === \"/\")) i++;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tout += c;\n\t\ti++;\n\t}\n\treturn out.replace(/,(\\s*[}\\]])/g, \"$1\");\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type Route from \"../types/Route\";\nimport {\n\tERROR_ROUTE,\n\tHOOK_ROUTE,\n\tHOOK_SERVER_ROUTE,\n\tLAYOUT_ROUTE,\n\tLAYOUT_SERVER_ROUTE,\n\tPAGE_SERVER_ROUTE,\n\tSERVER_ROUTE,\n} from \"../types/RouteType\";\nimport tsconfigAliases, { type AliasEntry } from \"../utils/tsconfigAliases\";\nimport type Site from \"./Site\";\n\n/**\n * A problem found in a route file's type annotations by `checkRoutes`.\n */\nexport interface RouteCheckIssue {\n\t/** The route file, relative to the site root */\n\tfile: string;\n\t/** 1-based line number of the annotation */\n\tline: number;\n\tseverity: \"error\" | \"warning\";\n\tmessage: string;\n}\n\nconst ENDPOINT_TYPES = [\n\t\"PageServerEndPoint\",\n\t\"LayoutServerEndPoint\",\n\t\"PageEndPoint\",\n\t\"ServerEndPoint\",\n\t\"ServerHook\",\n];\n\nconst USAGE_RE = new RegExp(`\\\\b(satisfies|as|:)\\\\s*\\\\b(${ENDPOINT_TYPES.join(\"|\")})\\\\b`, \"g\");\n\nconst TYPE_NAME_RE = new RegExp(`^(?:${ENDPOINT_TYPES.join(\"|\")})\\\\b`);\n\n/**\n * Checks the route files of a site against their type annotations:\n *\n * - Route path annotations (e.g. `PageServerEndPoint<\"/posts/[id]\">`) must\n * match the route derived from the file's location, so types can't silently\n * lie when files move\n * - Exports that widen the endpoint type (`satisfies T as T`, `as T`, or a\n * variable annotation) are flagged, because they destroy `PageData` /\n * `PageForm` / param inference\n * - Routes with dynamic params but no route annotation are flagged, because\n * their params are loosely typed\n *\n * Only `.ts` route files are checked; annotations are matched by the standard\n * type names (renamed imports are not detected). Best-effort, source-level —\n * comments mentioning these patterns may produce false positives.\n */\nexport function checkRoutes(site: Site): RouteCheckIssue[] {\n\tconst issues: RouteCheckIssue[] = [];\n\tfor (const route of site.routes) {\n\t\tissues.push(...checkRoute(site, route));\n\t}\n\treturn issues;\n}\n\n/**\n * Checks a single route's file. Returns no issues for routes without a `.ts`\n * file (`.torp` components, inline endpoints, `.js` files).\n */\nexport function checkRoute(site: Site, route: Route): RouteCheckIssue[] {\n\tif (!route.file || !route.file.endsWith(\".ts\")) return [];\n\tlet source: string;\n\ttry {\n\t\tsource = readFileSync(path.join(site.root, route.file), \"utf8\");\n\t} catch {\n\t\treturn [];\n\t}\n\treturn checkRouteSource(source, route.file, expectedAnnotationPath(route), typeNameFor(route));\n}\n\n/**\n * Checks a single route file's source. Exported for reuse (e.g. re-checking a\n * changed file during dev).\n * @param source The route file's source code\n * @param file The file path, relative to the site root (used in messages)\n * @param expected The route path derived from the file's location\n * @param typeName The endpoint type name conventionally used by this route\n * type (used in suggestions)\n */\nexport function checkRouteSource(\n\tsource: string,\n\tfile: string,\n\texpected: string,\n\ttypeName: string,\n): RouteCheckIssue[] {\n\tconst issues: RouteCheckIssue[] = [];\n\tlet sawAnnotation = false;\n\tUSAGE_RE.lastIndex = 0;\n\tfor (let m = USAGE_RE.exec(source); m; m = USAGE_RE.exec(source)) {\n\t\tsawAnnotation = true;\n\t\tconst kind = m[1];\n\t\tconst usedTypeName = m[2];\n\t\tconst { routePath, end } = parseTypeArgs(source, m.index + m[0].length);\n\t\tconst line = lineOf(source, m.index);\n\t\tif (routePath !== undefined && routePath !== expected) {\n\t\t\tissues.push({\n\t\t\t\tfile,\n\t\t\t\tline,\n\t\t\t\tseverity: \"error\",\n\t\t\t\tmessage: `Route annotation \"${routePath}\" doesn't match this file's route \"${expected}\" (derived from its location). Did the file move?`,\n\t\t\t});\n\t\t}\n\t\tif (kind === \"as\" || kind === \":\") {\n\t\t\tissues.push({\n\t\t\t\tfile,\n\t\t\t\tline,\n\t\t\t\tseverity: \"warning\",\n\t\t\t\tmessage:\n\t\t\t\t\tkind === \"as\"\n\t\t\t\t\t\t? `The \\`as ${usedTypeName}\\` cast widens the exported type, so PageData/PageForm/param inference falls back to loose types. Use \\`satisfies ${usedTypeName}${routePathArg(expected, routePath)}\\` without a cast instead.`\n\t\t\t\t\t\t: `The variable annotation widens the exported type, so PageData/PageForm/param inference falls back to loose types. Use \\`satisfies ${usedTypeName}${routePathArg(expected, routePath)}\\` on the default export instead.`,\n\t\t\t});\n\t\t} else {\n\t\t\tconst cast = parseAsCast(source, end);\n\t\t\tif (cast) {\n\t\t\t\tissues.push({\n\t\t\t\t\tfile,\n\t\t\t\t\tline,\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tmessage: `The \\`as\\` cast after \\`satisfies\\` widens the exported type, so PageData/PageForm/param inference falls back to loose types. Use \\`satisfies ${usedTypeName}${routePathArg(expected, routePath ?? cast.routePath)}\\` on its own.`,\n\t\t\t\t});\n\t\t\t\tif (cast.routePath !== undefined && cast.routePath !== expected) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tfile,\n\t\t\t\t\t\tline,\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tmessage: `Route annotation \"${cast.routePath}\" doesn't match this file's route \"${expected}\" (derived from its location). Did the file move?`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\t// Skip the `as T` so it isn't reported again as a separate cast\n\t\t\t\tUSAGE_RE.lastIndex = cast.end;\n\t\t\t} else if (routePath === undefined && expected.includes(\"[\")) {\n\t\t\t\tissues.push({\n\t\t\t\t\tfile,\n\t\t\t\t\tline,\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tmessage: `No route path on the annotation, so params are loosely typed. Use \\`satisfies ${usedTypeName}<\"${expected}\">\\`.`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\tif (!sawAnnotation && file.endsWith(\".ts\") && expected.includes(\"[\")) {\n\t\tissues.push({\n\t\t\tfile,\n\t\t\tline: 1,\n\t\t\tseverity: \"warning\",\n\t\t\tmessage: `No route annotation, so params are loosely typed. Add \\`satisfies ${typeName}<\"${expected}\">\\` to the default export.`,\n\t\t});\n\t}\n\treturn issues;\n}\n\n/**\n * Prints issues to the console and returns the number of errors.\n */\nexport function reportRouteIssues(issues: RouteCheckIssue[]): number {\n\tfor (const issue of issues) {\n\t\tconsole.error(`[torpor] ${issue.severity}: ${issue.file}:${issue.line} ${issue.message}`);\n\t}\n\treturn issues.filter((i) => i.severity === \"error\").length;\n}\n\nconst MAKE_API_RE = /\\bmakeApi\\s*<\\s*([\"'])([^\"']+)\\1\\s*,\\s*typeof\\s+([A-Za-z_$][\\w$]*)/g;\n\nconst DEFAULT_IMPORT_RE = /\\bimport\\s+(?:type\\s+)?([A-Za-z_$][\\w$]*)\\s+from\\s*([\"'])([^\"']+)\\2/g;\n\nconst SKIP_DIRS = new Set([\"node_modules\", \"dist\", \".git\", \".torpor\", \".vite\", \"coverage\"]);\n\nconst SOURCE_FILE_RE = /\\.(ts|js|torp)$/;\n\n/**\n * Precomputed state for checking `makeApi` calls: the site root, its route\n * files keyed by path, and tsconfig path aliases for resolving imports.\n */\nexport interface ApiCallCheck {\n\troot: string;\n\troutesByFile: Map<string, Route>;\n\taliases: AliasEntry[];\n}\n\n/**\n * Creates the shared state used by `checkApiCallSource`, so per-file checks\n * (e.g. re-checking a changed file during dev) don't rebuild it.\n */\nexport function createApiCallCheck(site: Site): ApiCallCheck {\n\tconst routesByFile = new Map<string, Route>();\n\tfor (const route of site.routes) {\n\t\tif (route.file) routesByFile.set(route.file.replaceAll(\"\\\\\", \"/\"), route);\n\t}\n\treturn { root: site.root, routesByFile, aliases: tsconfigAliases(site.root) };\n}\n\n/**\n * Checks `makeApi<Route, typeof endpoint>` calls across the site's source\n * files: the `Route` argument must match the route derived from the imported\n * endpoint file's location. Calls whose endpoint isn't a type-only import of\n * a known route file are skipped.\n */\nexport function checkApiCalls(site: Site): RouteCheckIssue[] {\n\tconst check = createApiCallCheck(site);\n\tconst issues: RouteCheckIssue[] = [];\n\tfor (const file of walkSourceFiles(site.root)) {\n\t\tlet source: string;\n\t\ttry {\n\t\t\tsource = readFileSync(file, \"utf8\");\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tissues.push(...checkApiCallSource(source, file, check));\n\t}\n\treturn issues;\n}\n\n/**\n * Checks the `makeApi` calls in a single file's source.\n * @param source The file's source code\n * @param file The file's absolute path (used to resolve relative imports and\n * to derive the path shown in messages)\n * @param check Shared state from `createApiCallCheck`\n */\nexport function checkApiCallSource(\n\tsource: string,\n\tfile: string,\n\tcheck: ApiCallCheck,\n): RouteCheckIssue[] {\n\tconst imports = new Map<string, string>();\n\tfor (let m = DEFAULT_IMPORT_RE.exec(source); m; m = DEFAULT_IMPORT_RE.exec(source)) {\n\t\timports.set(m[1], m[3]);\n\t}\n\tconst issues: RouteCheckIssue[] = [];\n\tfor (let m = MAKE_API_RE.exec(source); m; m = MAKE_API_RE.exec(source)) {\n\t\tconst specifier = imports.get(m[3]);\n\t\tif (!specifier) continue;\n\t\tconst resolved = resolveSpecifier(specifier, file, check);\n\t\tif (!resolved) continue;\n\t\tconst relFile = path.relative(check.root, resolved).replaceAll(\"\\\\\", \"/\");\n\t\tconst route = check.routesByFile.get(relFile);\n\t\tif (!route) continue;\n\t\tconst expected = expectedAnnotationPath(route);\n\t\tif (m[2] !== expected) {\n\t\t\tissues.push({\n\t\t\t\tfile: path.relative(check.root, file).replaceAll(\"\\\\\", \"/\"),\n\t\t\t\tline: lineOf(source, m.index),\n\t\t\t\tseverity: \"error\",\n\t\t\t\tmessage: `makeApi route \"${m[2]}\" doesn't match the endpoint's route \"${expected}\" (derived from ${relFile}). Did the endpoint move?`,\n\t\t\t});\n\t\t}\n\t}\n\treturn issues;\n}\n\n/**\n * Resolves an import specifier to an existing file: relative specifiers are\n * resolved against the importing file, others against tsconfig path aliases.\n * Bare module specifiers that match no alias return undefined.\n */\nexport function resolveSpecifier(\n\tspecifier: string,\n\tfromFile: string,\n\tcheck: ApiCallCheck,\n): string | undefined {\n\tlet candidate: string | undefined;\n\tif (specifier.startsWith(\"./\") || specifier.startsWith(\"../\")) {\n\t\tcandidate = path.resolve(path.dirname(fromFile), specifier);\n\t} else {\n\t\tfor (const alias of check.aliases) {\n\t\t\tif (typeof alias.find === \"string\") {\n\t\t\t\tif (specifier.startsWith(alias.find)) {\n\t\t\t\t\tcandidate = path.resolve(alias.replacement, specifier.slice(alias.find.length));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else if (alias.find.test(specifier)) {\n\t\t\t\tcandidate = specifier.replace(alias.find, alias.replacement);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (!candidate) return undefined;\n\tconst probes = [\n\t\tcandidate,\n\t\t`${candidate}.ts`,\n\t\t`${candidate}.js`,\n\t\tpath.join(candidate, \"index.ts\"),\n\t\tpath.join(candidate, \"index.js\"),\n\t];\n\tfor (const probe of probes) {\n\t\tif (existsSync(probe) && statSync(probe).isFile()) return probe;\n\t}\n\treturn undefined;\n}\n\nfunction walkSourceFiles(root: string): string[] {\n\tconst files: string[] = [];\n\tconst visit = (dir: string): void => {\n\t\tlet entries;\n\t\ttry {\n\t\t\tentries = readdirSync(dir, { withFileTypes: true });\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tif (!SKIP_DIRS.has(entry.name)) visit(path.join(dir, entry.name));\n\t\t\t} else if (\n\t\t\t\tentry.isFile() &&\n\t\t\t\tSOURCE_FILE_RE.test(entry.name) &&\n\t\t\t\t!entry.name.endsWith(\".d.ts\")\n\t\t\t) {\n\t\t\t\tfiles.push(path.join(dir, entry.name));\n\t\t\t}\n\t\t}\n\t};\n\tvisit(root);\n\treturn files;\n}\n\n/**\n * The route path a file's annotation should use, derived from its manifest\n * entry: internal suffixes (`/~server`, `/_layout` etc) are stripped so e.g.\n * `posts/[id]/+page.server.ts` expects `\"/posts/[id]\"`.\n */\nexport function expectedAnnotationPath(route: Route): string {\n\tlet p = route.path;\n\tswitch (route.type) {\n\t\tcase PAGE_SERVER_ROUTE:\n\t\t\tp = p.replace(/\\/~server$/, \"\");\n\t\t\tbreak;\n\t\tcase LAYOUT_ROUTE:\n\t\t\tp = p.replace(/\\/_layout$/, \"\");\n\t\t\tbreak;\n\t\tcase LAYOUT_SERVER_ROUTE:\n\t\t\tp = p.replace(/\\/_layout\\/~server$/, \"\");\n\t\t\tbreak;\n\t\tcase HOOK_ROUTE:\n\t\t\tp = p.replace(/\\/_hook$/, \"\");\n\t\t\tbreak;\n\t\tcase HOOK_SERVER_ROUTE:\n\t\t\tp = p.replace(/\\/_hook\\/~server$/, \"\");\n\t\t\tbreak;\n\t\tcase ERROR_ROUTE:\n\t\t\tp = p.replace(/\\/_error$/, \"\");\n\t\t\tbreak;\n\t}\n\treturn p === \"\" ? \"/\" : p;\n}\n\nfunction typeNameFor(route: Route): string {\n\tswitch (route.type) {\n\t\tcase PAGE_SERVER_ROUTE:\n\t\t\treturn \"PageServerEndPoint\";\n\t\tcase LAYOUT_SERVER_ROUTE:\n\t\t\treturn \"LayoutServerEndPoint\";\n\t\tcase SERVER_ROUTE:\n\t\t\treturn \"ServerEndPoint\";\n\t\tcase HOOK_ROUTE:\n\t\tcase HOOK_SERVER_ROUTE:\n\t\t\treturn \"ServerHook\";\n\t\tdefault:\n\t\t\treturn \"PageEndPoint\";\n\t}\n}\n\n/**\n * Parses the type arguments that follow an endpoint type name, returning the\n * first argument when it is a string literal (the route path), plus the index\n * after the closing `>` (or after the type name when there are no arguments).\n */\nfunction parseTypeArgs(\n\tsource: string,\n\tstart: number,\n): { routePath: string | undefined; end: number } {\n\tlet i = start;\n\twhile (i < source.length && /\\s/.test(source[i])) i++;\n\tif (source[i] !== \"<\") return { routePath: undefined, end: i };\n\ti++;\n\tlet depth = 1;\n\tlet routePath: string | undefined;\n\tlet seenComma = false;\n\twhile (i < source.length) {\n\t\tconst c = source[i];\n\t\tif (c === '\"' || c === \"'\") {\n\t\t\tconst quote = c;\n\t\t\tlet j = i + 1;\n\t\t\twhile (j < source.length && source[j] !== quote) {\n\t\t\t\tif (source[j] === \"\\\\\") j++;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tif (routePath === undefined && !seenComma) routePath = source.slice(i + 1, j);\n\t\t\ti = j + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (c === \"<\") depth++;\n\t\telse if (c === \">\") {\n\t\t\tdepth--;\n\t\t\tif (depth === 0) return { routePath, end: i + 1 };\n\t\t} else if (c === \",\" && routePath === undefined) {\n\t\t\tseenComma = true;\n\t\t}\n\t\ti++;\n\t}\n\treturn { routePath, end: i };\n}\n\n/**\n * Parses an `as T`-style cast that follows a `satisfies T` usage, returning\n * its optional route path argument and the index after the cast.\n */\nfunction parseAsCast(\n\tsource: string,\n\tstart: number,\n): { routePath: string | undefined; end: number } | undefined {\n\tlet i = start;\n\twhile (i < source.length && /\\s/.test(source[i])) i++;\n\tif (!/^as\\b/.test(source.slice(i, i + 3))) return undefined;\n\ti += 2;\n\twhile (i < source.length && /\\s/.test(source[i])) i++;\n\tif (!TYPE_NAME_RE.test(source.slice(i))) return undefined;\n\ti = i + source.slice(i).match(TYPE_NAME_RE)![0].length;\n\treturn parseTypeArgs(source, i);\n}\n\nfunction routePathArg(expected: string, actual: string | undefined): string {\n\t// Keep the user's own (correct) path when widening a properly-annotated\n\t// export; otherwise suggest the path derived from the file's location\n\treturn `<\"${actual ?? expected}\">`;\n}\n\nfunction lineOf(source: string, index: number): number {\n\tlet line = 1;\n\tfor (let i = 0; i < index; i++) {\n\t\tif (source[i] === \"\\n\") line++;\n\t}\n\treturn line;\n}\n","import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { parse } from \"@torpor/view/compile\";\nimport type Route from \"../types/Route\";\nimport { LAYOUT_ROUTE } from \"../types/RouteType\";\nimport type Site from \"./Site\";\nimport { createApiCallCheck, resolveSpecifier, type RouteCheckIssue } from \"./checkRoutes\";\n\n/**\n * The default import of a `.torp` component from a `.ts`/`.js` route file,\n * e.g. `import component from \"@/views/Layout.torp\"`.\n */\nconst DEFAULT_TORP_IMPORT_RE = /import\\s+[A-Za-z_$][\\w$]*\\s+from\\s*[\"']([^\"']+\\.torp)[\"']/;\n\n/**\n * Checks that every `_layout` route renders its default `<slot />`.\n *\n * The layout engine composes pages by passing each layout (and finally the\n * page) as the default slot of its parent, so a layout that never renders\n * `<slot />` drops its entire content: the server renders the layout's own\n * markup with an empty content area (no error), and the first client-side\n * navigation that reuses the layout fails on a null slot region.\n *\n * Runs at build time (failing the build) and at dev startup. Best-effort and\n * static: a layout that renders `<slot />` conditionally (inside `@if`)\n * passes here, and is caught at request time by the server render warning\n * (see site/layoutSlots.ts).\n */\nexport function checkLayoutSlots(site: Site): RouteCheckIssue[] {\n\tconst issues: RouteCheckIssue[] = [];\n\tfor (const route of site.routes) {\n\t\tif (route.type === LAYOUT_ROUTE) {\n\t\t\tissues.push(...checkLayoutSlot(site, route));\n\t\t}\n\t}\n\treturn issues;\n}\n\n/**\n * Checks a single layout route's component (the `.torp` route file itself,\n * or the `.torp` file its `.ts`/`.js` endpoint re-exports as its default\n * import). Routes without a file (inline endpoints) can't hold a component,\n * so they are skipped.\n */\nexport function checkLayoutSlot(site: Site, route: Route): RouteCheckIssue[] {\n\tif (route.type !== LAYOUT_ROUTE || !route.file) return [];\n\n\tconst check = createApiCallCheck(site);\n\n\t// The component is either the route file itself (.torp) or a .ts/.js\n\t// endpoint re-exporting a .torp component as its default export\n\tlet torpFile = path.join(site.root, route.file);\n\tif (!route.file.endsWith(\".torp\")) {\n\t\tconst source = readIfExists(torpFile);\n\t\tif (source === undefined) return [];\n\t\tconst match = DEFAULT_TORP_IMPORT_RE.exec(source);\n\t\tif (!match) return [];\n\t\tconst resolved = resolveSpecifier(match[1], torpFile, check);\n\t\tif (!resolved) return [];\n\t\ttorpFile = resolved;\n\t}\n\n\tconst source = readIfExists(torpFile);\n\tif (source === undefined) return [];\n\n\t// Parse errors are reported when the file is compiled, not here\n\tconst parsed = parse(source);\n\tif (!parsed.ok || !parsed.template) return [];\n\tif (rendersDefaultSlot(parsed.template)) return [];\n\n\treturn [\n\t\t{\n\t\t\tfile: route.file,\n\t\t\tline: 1,\n\t\t\tseverity: \"error\",\n\t\t\tmessage:\n\t\t\t\t\"The layout never renders <slot />, so pages under it render without their content. \" +\n\t\t\t\t\"Every _layout component must render <slot />, or pass it down to a child component \" +\n\t\t\t\t\"it renders.\",\n\t\t},\n\t];\n}\n\nfunction readIfExists(file: string): string | undefined {\n\ttry {\n\t\tif (!existsSync(file) || !statSync(file).isFile()) return undefined;\n\t\treturn readFileSync(file, \"utf8\");\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Walks a parsed template looking for a default `<slot />` anywhere in the\n * render tree — including nested inside a child component element, which is\n * how a layout passes the page slot down (e.g. `<Shell><slot /></Shell>`).\n */\n// HACK: no types on the internal parse tree nodes (same as the prettier plugin)\nfunction rendersDefaultSlot(template: any): boolean {\n\tconst component = template.components?.[0];\n\tif (!component) return false;\n\treturn walk(component.markup);\n}\n\nfunction walk(node: any): boolean {\n\tif (\n\t\t(node.type === \"element\" || node.type === \"special\") &&\n\t\tnode.tagName === \"slot\" &&\n\t\t!node.attributes?.some((a: any) => a.name === \"name\")\n\t) {\n\t\treturn true;\n\t}\n\treturn (node.children ?? []).some(walk);\n}\n","import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Plugin } from \"vite\";\nimport type { ResolvedOpenApiOptions } from \"../openapi/types\";\nimport { OPEN_API_STATE_KEY } from \"../openapi/plugin\";\nimport { normalizeBasePath, normalizeOrigin } from \"./basePath\";\nimport Site from \"./Site\";\nimport type ModulePreloads from \"../types/ModulePreloads\";\nimport { SERVER_ROUTE } from \"../types/RouteType\";\n\nexport const MANIFEST_MODULE_ID = \"@torpor/build/manifest\";\n\nconst moduleId = MANIFEST_MODULE_ID;\n\nconst LOAD_EXPORT_RE =\n\t/[{,]\\s*load\\s*[:(]|\\bexport\\s+(?:async\\s+)?(?:function|const|let|var)\\s+load\\b|\\bexport\\s*\\{[^}]*\\bload\\b/;\n\nexport function hasLoadExport(source: string): boolean {\n\treturn LOAD_EXPORT_RE.test(source);\n}\n\n/**\n * A Vite plugin that provides information about the app to both clientEntry and\n * serverEntry.\n */\nexport default function manifest(\n\tsite: Site,\n\tserver = false,\n\tdev = false,\n\t// The client chunks each page needs, from the client build (production\n\t// server builds only)\n\tpreloads?: ModulePreloads,\n): Plugin {\n\treturn {\n\t\tname: \"torpor-manifest\",\n\t\tresolveId: {\n\t\t\torder: \"pre\",\n\t\t\thandler(id) {\n\t\t\t\tif (id === moduleId) {\n\t\t\t\t\treturn id;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t// @ts-ignore\n\t\tload(id, viteOptions) {\n\t\t\tif (id === moduleId) {\n\t\t\t\tlet serverRequest = server && !!viteOptions?.ssr;\n\n\t\t\t\t// Validate here, so bad config fails the build\n\t\t\t\tconst base = normalizeBasePath(site.basePath);\n\t\t\t\tif (site.sitemap && !site.origin) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`site.sitemap requires site.origin to be set (it is the host of the urls)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (site.origin) {\n\t\t\t\t\tnormalizeOrigin(site.origin);\n\t\t\t\t}\n\t\t\t\tif (typeof site.sitemap === \"object\" && site.sitemap !== null) {\n\t\t\t\t\tif (site.sitemap.path !== undefined && !site.sitemap.path.startsWith(\"/\")) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`The sitemap path must be an absolute path (e.g. \"/sitemap.xml\"), got \"${site.sitemap.path}\"`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (typeof site.sitemap === \"string\" && !site.sitemap.startsWith(\"/\")) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`The sitemap path must be an absolute path (e.g. \"/sitemap.xml\"), got \"${site.sitemap}\"`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// If there are inline endpoints, site plugins, an OpenAPI\n\t\t\t\t// document or an env schema, and we're building for the server,\n\t\t\t\t// we need to import the config file to access them. On the\n\t\t\t\t// client, the config file is never imported, keeping server\n\t\t\t\t// code out of the client bundle.\n\t\t\t\tconst hasInline = site.routes.some((r) => r.endPoint && !r.file);\n\t\t\t\tconst hasPlugins = site.plugins.length > 0;\n\t\t\t\tconst hasOpenApi = site.pluginState.has(OPEN_API_STATE_KEY);\n\t\t\t\tconst hasEnv = !!site.env;\n\t\t\t\tconst hasMiddleware = site.middleware.length > 0;\n\t\t\t\tconst hasRuntimeSitemap = typeof site.sitemap === \"object\" && site.sitemap !== null;\n\t\t\t\tconst configImport =\n\t\t\t\t\thasInline || hasPlugins || hasOpenApi || hasEnv || hasRuntimeSitemap || hasMiddleware\n\t\t\t\t\t\t? serverRequest && site.configFile\n\t\t\t\t\t\t\t? `import __site from ${JSON.stringify(site.configFile)};`\n\t\t\t\t\t\t\t: \"\"\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\t// The env schema is handed to @torpor/build/env at startup, so\n\t\t\t\t// that `env()` calls in route code can validate against it\n\t\t\t\tconst envGlue =\n\t\t\t\t\tserverRequest && hasEnv && site.configFile\n\t\t\t\t\t\t? `import { setEnvSchema } from \"@torpor/build/env\";\nsetEnvSchema(__site.env);`\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\t// Site plugins are run when the server starts up (in dev and in\n\t\t\t\t// production), so that routes they register are available at\n\t\t\t\t// runtime. Top-level await is fine here: this module is only\n\t\t\t\t// loaded through Vite's SSR pipeline\n\t\t\t\tconst pluginLoop =\n\t\t\t\t\tserverRequest && hasPlugins\n\t\t\t\t\t\t? `for (const __plugin of __site.plugins ?? []) { await __plugin(__site); }`\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\t// The OpenAPI document endpoint is generated code (rather than an\n\t\t\t\t// inline endpoint) because it must load each route file -- which\n\t\t\t\t// only works from module code that Vite processes/bundles. The\n\t\t\t\t// options live in `site.pluginState` (set by the plugin), so they\n\t\t\t\t// are available both here and in the generated runtime code\n\t\t\t\tconst openApiOptions = site.pluginState.get(OPEN_API_STATE_KEY) as\n\t\t\t\t\t| ResolvedOpenApiOptions\n\t\t\t\t\t| undefined;\n\t\t\t\tconst openApiGlue =\n\t\t\t\t\tserverRequest && openApiOptions && site.configFile\n\t\t\t\t\t\t? openApiGlueCode(site, openApiOptions)\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\tconst openApiRoute =\n\t\t\t\t\tserverRequest && openApiOptions\n\t\t\t\t\t\t? `{ path: ${JSON.stringify(openApiOptions.path)}, type: ${SERVER_ROUTE}, endPoint: () => Promise.resolve({ default: { get: __openApiGet } }), subFolder: undefined },`\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\t// A runtime sitemap, when `site.sitemap` is a `{ get }` config:\n\t\t\t\t// a server endpoint that reads urls and serves the XML\n\t\t\t\tconst sitemapOptions =\n\t\t\t\t\ttypeof site.sitemap === \"object\" && site.sitemap !== null ? site.sitemap : undefined;\n\t\t\t\tconst sitemapGlue =\n\t\t\t\t\tserverRequest && sitemapOptions && site.configFile\n\t\t\t\t\t\t? `\nimport { sitemapResponse } from \"@torpor/build/discovery\";\nasync function __sitemapGet(event) {\n\treturn await sitemapResponse(__site.sitemap, ${JSON.stringify(base)}, event);\n}\n`\n\t\t\t\t\t\t: \"\";\n\t\t\t\tconst sitemapRoute =\n\t\t\t\t\tserverRequest && sitemapOptions\n\t\t\t\t\t\t? `{ path: ${JSON.stringify(sitemapOptions.path ?? \"/sitemap.xml\")}, type: ${SERVER_ROUTE}, endPoint: () => Promise.resolve({ default: { get: __sitemapGet } }), subFolder: undefined },`\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\treturn `\n${!serverRequest ? \"const load = { default: { load: true } };\" : \"\"}\n${configImport}\n${envGlue}\n${pluginLoop}\n${openApiGlue}\n${sitemapGlue}\nexport default {\n base: ${JSON.stringify(base)},\n viewTransitions: ${!!site.viewTransitions},\n dev: ${!!dev},\n ${serverRequest && hasMiddleware ? \"middleware: __site.middleware ?? [],\" : \"\"}\n ${serverRequest && preloads ? `preloads: ${JSON.stringify(preloads)},` : \"\"}\n routes: [\n ${site.routes\n\t\t\t.map((r) => {\n\t\t\t\tlet endPoint: string;\n\t\t\t\tif (!r.file) {\n\t\t\t\t\t// Inline endpoint (no file)\n\t\t\t\t\tif (serverRequest) {\n\t\t\t\t\t\tconst key = `${r.path}:${r.type}`;\n\t\t\t\t\t\tendPoint = `() => Promise.resolve({ default: __site.inlineEndPoints[${JSON.stringify(key)}] })`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Client-side stub: check if the inline\n\t\t\t\t\t\t// endpoint has a load function\n\t\t\t\t\t\tconst haveLoad =\n\t\t\t\t\t\t\ttypeof (r.endPoint as Record<string, unknown> | undefined)?.load === \"function\";\n\t\t\t\t\t\tendPoint = haveLoad ? \"() => load\" : \"undefined\";\n\t\t\t\t\t}\n\t\t\t\t} else if (serverRequest || !/server\\.(ts|js)$/.test(r.file)) {\n\t\t\t\t\tconst filePath = path.join(site.root, r.file);\n\t\t\t\t\t// NOTE: No `@vite-ignore` here, so that Vite processes the import:\n\t\t\t\t\t// in dev the module runner transforms the file on the fly, and in\n\t\t\t\t\t// a production build Rollup bundles the route into a chunk and\n\t\t\t\t\t// rewrites the import -- leaving the raw source path in place\n\t\t\t\t\t// would hand Node/wrangler `.ts`/`.torp` files it can't load\n\t\t\t\t\tconst importExpr = `() => import(\"${filePath}\")`;\n\t\t\t\t\t// A .torp file's default export is a component, so wrap it\n\t\t\t\t\t// as a PageEndPoint ({ component }) for the entries\n\t\t\t\t\tendPoint = r.file.endsWith(\".torp\")\n\t\t\t\t\t\t? `${importExpr}.then((m) => ({ default: { component: m.default } }))`\n\t\t\t\t\t\t: importExpr;\n\t\t\t\t} else {\n\t\t\t\t\t// On the client, for a server route, we need to check\n\t\t\t\t\t// whether there's a load function and set a dummy endPoint\n\t\t\t\t\t// if so. The correct endpoint will be hit in clientEntry\n\t\t\t\t\tconst haveLoad = hasLoadExport(readFileSync(path.join(site.root, r.file), \"utf8\"));\n\t\t\t\t\tendPoint = haveLoad ? \"() => load\" : \"undefined\";\n\t\t\t\t}\n\t\t\t\tconst sub = r.subFolder ? `\"${r.subFolder}\"` : \"undefined\";\n\t\t\t\treturn `{ path: \"${r.path}\", type: ${r.type}, endPoint: ${endPoint}, subFolder: ${sub} },`;\n\t\t\t})\n\t\t\t.join(\"\\n \")}\n ${openApiRoute}\n ${sitemapRoute}\n ],\n};\n`;\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Generates the module code for the OpenAPI document endpoint: a map of\n * route path to endpoint loader, and a handler (from `createOpenApiHandler`)\n * that builds the document from them. Exported so its wiring can be tested.\n */\nexport function openApiGlueCode(site: Site, options: ResolvedOpenApiOptions): string {\n\tconst loaders = site.routes\n\t\t.filter((r) => r.type === SERVER_ROUTE)\n\t\t// Don't document the docs page itself\n\t\t.filter((r) => r.path !== options.docs)\n\t\t.map((r) => {\n\t\t\tif (!r.file) {\n\t\t\t\tconst key = `${r.path}:${r.type}`;\n\t\t\t\treturn `${JSON.stringify(r.path)}: () => Promise.resolve({ default: __site.inlineEndPoints[${JSON.stringify(key)}] })`;\n\t\t\t}\n\t\t\tconst filePath = path.join(site.root, r.file);\n\t\t\treturn `${JSON.stringify(r.path)}: () => import(${JSON.stringify(filePath)})`;\n\t\t})\n\t\t.join(\",\\n \");\n\n\treturn `\nimport { createOpenApiHandler, OPEN_API_STATE_KEY } from \"@torpor/build/openapi\";\nconst __openApiRoutes = {\n ${loaders}\n};\n// The handler is called with the request's event, so the extend hook can\n// build a document from it (e.g. one document per route param)\nconst __openApiGet = createOpenApiHandler(\n __openApiRoutes,\n () => __site.pluginState.get(OPEN_API_STATE_KEY),\n);\n`;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire, isBuiltin } from \"node:module\";\nimport path from \"node:path\";\nimport type { UserConfig } from \"vite\";\n\nexport type PackageJson = {\n\tname?: string;\n\ttorpor?: string | boolean;\n\texports?: unknown;\n\tdependencies?: Record<string, string>;\n\tdevDependencies?: Record<string, string>;\n\toptionalDependencies?: Record<string, string>;\n\tpeerDependencies?: Record<string, string>;\n\t[key: string]: unknown;\n};\n\n/**\n * Finds packages installed in the site that ship `.torp` files, e.g. icon\n * libraries like phosphor-torpor. These packages need the torpor compiler, so\n * they can't go through Vite's default pipelines: dep optimization parses\n * their files as plain JavaScript (and fails on torpor syntax like `@render`\n * or `import type` from an uncompiled source), and SSR externalization would\n * leave raw `.torp` imports that neither Node nor workerd can load.\n *\n * A package is a torpor package when it declares a `torpor` entry in its\n * package.json, or when any of its export targets is a `.torp` file. The\n * entry is usually a path (`\"torpor\": \"./lib/index.js\"`, mirroring the\n * `svelte` field convention), but packages that ship compiled output can\n * just mark themselves with `\"torpor\": true`.\n *\n * @param siteRoot The root folder of the site\n * @returns The names of the torpor packages found (may be empty)\n */\nexport default function findTorporPackages(siteRoot: string): string[] {\n\tconst { torporPackages } = collectPackages(siteRoot);\n\treturn [...torporPackages];\n}\n\n/**\n * Walks the site's dependency tree, collecting:\n *\n * - `torporPackages`: packages that ship `.torp` files and so need the torpor\n * compiler (they can't be externalized or prebundled as JavaScript)\n * - `plainDeps`: plain (non-torpor) direct dependencies of those packages.\n * Once a torpor package is bundled into the SSR build, its bare imports of\n * plain dependencies stay in the emitted bundle as external imports -- and\n * under pnpm's strict node_modules layout the app can't resolve them at\n * runtime (they're only linked inside the torpor package's own\n * node_modules), so they must be bundled too. Dependencies *of* a bundled\n * plain package don't need this: they resolve (and inline) at build time\n * from the package's own location.\n */\nfunction collectPackages(siteRoot: string): {\n\ttorporPackages: Set<string>;\n\tplainDeps: Set<string>;\n} {\n\tconst torporPackages = new Set<string>();\n\tconst plainDeps = new Set<string>();\n\n\tconst sitePackageJson = path.resolve(siteRoot, \"package.json\");\n\tif (!existsSync(sitePackageJson)) return { torporPackages, plainDeps };\n\n\tconst pkg: PackageJson = JSON.parse(readFileSync(sitePackageJson, \"utf8\"));\n\tconst visited = new Set<string>();\n\n\tconst rootRequire = createRequire(sitePackageJson);\n\tfor (const name of dependencyNames(pkg)) {\n\t\tcollectPackage(name, rootRequire, torporPackages, plainDeps, visited, false);\n\t}\n\treturn { torporPackages, plainDeps };\n}\n\n/**\n * Adds `optimizeDeps.exclude` and `ssr.noExternal` entries for packages that\n * ship `.torp` files, so that they are served/bundled through the torpor\n * compiler instead.\n *\n * The exclusions are mirrored into the SSR optimizer too: Vite's SSR\n * environment optimizer has its own `optimizeDeps` settings, and without the\n * mirror it still prebundles the package and parses its raw `.torp` files as\n * JavaScript. That only shows up on a cold dep cache (a warm cache from before\n * the package was installed masks it), so the root-level exclusion is not\n * enough.\n */\nexport function addTorporPackageConfig(siteRoot: string, config: UserConfig): void {\n\tconst { torporPackages, plainDeps } = collectPackages(siteRoot);\n\tif (torporPackages.size === 0) return;\n\n\tconfig.optimizeDeps ??= {};\n\tconfig.optimizeDeps.exclude = mergeUnique(config.optimizeDeps.exclude, [...torporPackages]);\n\n\tconfig.ssr ??= {};\n\tconst noExternal = config.ssr.noExternal;\n\t// Plain dependencies of torpor packages go through the normal pipelines in\n\t// the browser/optimizer; they only must not be left external in the SSR\n\t// build (see collectPackages)\n\tconst bundlePackages = [...torporPackages, ...plainDeps];\n\tif (noExternal === undefined) {\n\t\tconfig.ssr.noExternal = bundlePackages;\n\t} else if (Array.isArray(noExternal)) {\n\t\tnoExternal.push(...bundlePackages);\n\t}\n\t// For `true` (bundle everything) or string/regex values there is nothing\n\t// sensible to merge, and they already bundle more than we need\n\n\t// The SSR dep optimizer has its own config (the legacy `ssr.optimizeDeps`\n\t// form and the environment-scoped form used by Vite's environment API).\n\t// Mirror the exclusions into both so a cold start doesn't parse `.torp`\n\t// files as JS.\n\tconfig.ssr.optimizeDeps ??= {};\n\tconfig.ssr.optimizeDeps.exclude = mergeUnique(config.ssr.optimizeDeps.exclude, [\n\t\t...torporPackages,\n\t]);\n\n\tconfig.environments ??= {};\n\tconfig.environments.ssr ??= {};\n\tconfig.environments.ssr.optimizeDeps ??= {};\n\tconfig.environments.ssr.optimizeDeps.exclude = mergeUnique(\n\t\tconfig.environments.ssr.optimizeDeps.exclude,\n\t\t[...torporPackages],\n\t);\n}\n\n/** Appends values to an exclusion list without introducing duplicates. */\nfunction mergeUnique(existing: string[] | undefined, values: string[]): string[] {\n\treturn [...new Set([...(existing ?? []), ...values])];\n}\n\nfunction dependencyNames(pkg: PackageJson): string[] {\n\treturn [\n\t\t...Object.keys(pkg.dependencies ?? {}),\n\t\t...Object.keys(pkg.devDependencies ?? {}),\n\t\t...Object.keys(pkg.optionalDependencies ?? {}),\n\t\t...Object.keys(pkg.peerDependencies ?? {}),\n\t];\n}\n\nfunction collectPackage(\n\tname: string,\n\trequire: NodeRequire,\n\ttorporPackages: Set<string>,\n\tplainDeps: Set<string>,\n\tvisited: Set<string>,\n\tbelowTorpor: boolean,\n): void {\n\t// Some packages shadow Node builtins (e.g. a dependency literally named\n\t// \"path\"), and builtins can't contain .torp files\n\tif (isBuiltin(name)) return;\n\n\tconst packageJsonPath = resolvePackageJson(name, require);\n\tif (!packageJsonPath) return;\n\t// A package can be reached both through a plain path (where nothing needs\n\t// bundling) and through a torpor package (where it does), so the visited\n\t// key includes the path's bundling state\n\tconst visitKey = `${packageJsonPath}\\n${belowTorpor}`;\n\tif (visited.has(visitKey)) return;\n\tvisited.add(visitKey);\n\n\tlet pkg: PackageJson;\n\ttry {\n\t\tpkg = JSON.parse(readFileSync(packageJsonPath, \"utf8\"));\n\t} catch {\n\t\treturn;\n\t}\n\n\tconst isTorpor = isTorporPackage(pkg);\n\tif (isTorpor) {\n\t\ttorporPackages.add(pkg.name ?? name);\n\t} else if (belowTorpor) {\n\t\t// A plain dependency of a package that gets bundled into the SSR build\n\t\tplainDeps.add(pkg.name ?? name);\n\t}\n\n\t// Recurse into the package's own dependencies, resolved relative to it\n\t// (pnpm keeps transitive deps out of the site's top-level node_modules).\n\t// Only the direct dependencies of a bundled (torpor) package are forced\n\t// into the SSR bundle; below a bundled plain package everything resolves\n\t// at build time\n\tconst depRequire = createRequire(packageJsonPath);\n\tfor (const depName of dependencyNames(pkg)) {\n\t\tcollectPackage(depName, depRequire, torporPackages, plainDeps, visited, isTorpor);\n\t}\n}\n\nfunction isTorporPackage(pkg: PackageJson): boolean {\n\tif (pkg.torpor === true || typeof pkg.torpor === \"string\") return true;\n\treturn exportsIncludeTorp(pkg.exports);\n}\n\nfunction exportsIncludeTorp(exports: unknown): boolean {\n\tif (typeof exports === \"string\") return exports.endsWith(\".torp\");\n\tif (Array.isArray(exports)) return exports.some(exportsIncludeTorp);\n\tif (exports && typeof exports === \"object\") {\n\t\treturn Object.values(exports).some(exportsIncludeTorp);\n\t}\n\treturn false;\n}\n\nfunction resolvePackageJson(name: string, require: NodeRequire): string | undefined {\n\t// require.resolve returns the name itself for Node builtins, so guard\n\t// everything below with absolute path checks\n\ttry {\n\t\tconst packageJson = require.resolve(`${name}/package.json`);\n\t\treturn path.isAbsolute(packageJson) ? packageJson : undefined;\n\t} catch {\n\t\tlet entry: string;\n\t\ttry {\n\t\t\tentry = require.resolve(name);\n\t\t} catch {\n\t\t\t// Not resolvable through Node's resolver -- either the package\n\t\t\t// isn't installed (e.g. an optional peer), or its `exports` map\n\t\t\t// has no `.` or `./package.json` entry and both lookups above\n\t\t\t// threw ERR_PACKAGE_PATH_NOT_EXPORTED. Try the standard\n\t\t\t// node_modules lookup paths directly\n\t\t\treturn resolveFromNodeModules(name, require);\n\t\t}\n\t\tif (!path.isAbsolute(entry)) return undefined;\n\t\tlet dir = path.dirname(entry);\n\t\twhile (true) {\n\t\t\tconst packageJson = path.join(dir, \"package.json\");\n\t\t\tif (existsSync(packageJson)) return packageJson;\n\t\t\tconst parent = path.dirname(dir);\n\t\t\tif (parent === dir) return undefined;\n\t\t\tdir = parent;\n\t\t}\n\t}\n}\n\n/**\n * Finds a package's package.json by checking the standard node_modules\n * lookup paths directly, for packages that Node's resolver can't load\n * (`ERR_PACKAGE_PATH_NOT_EXPORTED`).\n */\nfunction resolveFromNodeModules(name: string, require: NodeRequire): string | undefined {\n\tfor (const dir of require.resolve.paths(name) ?? []) {\n\t\tif (!path.isAbsolute(dir)) continue;\n\t\tconst packageJson = path.join(dir, ...name.split(\"/\"), \"package.json\");\n\t\tif (existsSync(packageJson)) return packageJson;\n\t}\n\treturn undefined;\n}\n","import path from \"node:path\";\nimport type ModulePreloads from \"../types/ModulePreloads\";\n\n/** An entry in Vite's build manifest (`.vite/manifest.json`). */\nexport interface ViteManifestChunk {\n\tfile: string;\n\tsrc?: string;\n\tname?: string;\n\tisEntry?: boolean;\n\timports?: string[];\n\tcss?: string[];\n}\n\n/**\n * Works out which chunks each page needs, from the client build's manifest,\n * so the server can emit `<link rel=\"modulepreload\">` tags for them.\n *\n * Without them the browser only sees the client entry script (at the end of\n * the HTML), and finds the page's own chunks once the entry has downloaded\n * and run: a waterfall of HTML, then the entry, then the route's chunks,\n * then their imports. Each list is a chunk's file plus everything it\n * statically imports, transitively; dynamic imports are left to load when\n * they're needed.\n *\n * @param manifest The parsed `.vite/manifest.json`\n * @param root The client build's resolved Vite root, which manifest keys\n * and `src` paths are relative to\n * @param routes Route paths and their absolute source files (page and\n * layout components)\n * @param readStylesheet Reads a stylesheet by its output path (e.g.\n * `assets/x.css`), to find the component styles it contains\n */\nexport default function clientPreloads(\n\tmanifest: Record<string, ViteManifestChunk>,\n\troot: string,\n\troutes: { path: string; file: string }[],\n\treadStylesheet: (file: string) => string = () => \"\",\n): ModulePreloads {\n\tconst closure = (key: string, seen = new Set<string>()): string[] => {\n\t\tif (seen.has(key)) return [];\n\t\tseen.add(key);\n\t\tconst chunk = manifest[key];\n\t\tif (!chunk) return [];\n\t\tconst files = [`/${chunk.file}`];\n\t\tfor (const imported of chunk.imports ?? []) {\n\t\t\tfiles.push(...closure(imported, seen));\n\t\t}\n\t\treturn files;\n\t};\n\n\t// Manifest keys are source paths relative to the Vite root\n\tconst keysByFile = new Map<string, string>();\n\tfor (const [key, chunk] of Object.entries(manifest)) {\n\t\tkeysByFile.set(path.resolve(root, chunk.src ?? key), key);\n\t}\n\n\tconst entryKey = Object.keys(manifest).find(\n\t\t(key) => manifest[key].isEntry && manifest[key].name === \"clientEntry\",\n\t);\n\tconst entry = entryKey ? closure(entryKey) : [];\n\tconst inEntry = new Set(entry);\n\n\t// Stylesheets follow the same static imports. Component styles are\n\t// imported by the component's module (`import \"<hash>.css\"`), so each\n\t// lands in the stylesheet of the chunk the component is bundled into\n\tconst stylesClosure = (key: string, seen = new Set<string>()): string[] => {\n\t\tif (seen.has(key)) return [];\n\t\tseen.add(key);\n\t\tconst chunk = manifest[key];\n\t\tif (!chunk) return [];\n\t\tconst files = (chunk.css ?? []).map((file) => `/${file}`);\n\t\tfor (const imported of chunk.imports ?? []) {\n\t\t\tfiles.push(...stylesClosure(imported, seen));\n\t\t}\n\t\treturn files;\n\t};\n\tconst entryStyles = entryKey ? unique(stylesClosure(entryKey)) : [];\n\tconst inEntryStyles = new Set(entryStyles);\n\n\tconst preloads: Record<string, string[]> = {};\n\tconst routeStyles: Record<string, string[]> = {};\n\tfor (const route of routes) {\n\t\tconst key = keysByFile.get(path.resolve(route.file));\n\t\tif (!key) continue;\n\t\tconst files = closure(key).filter((file) => !inEntry.has(file));\n\t\tif (files.length > 0) {\n\t\t\tpreloads[route.path] = files;\n\t\t}\n\t\tconst styles = unique(stylesClosure(key)).filter((file) => !inEntryStyles.has(file));\n\t\tif (styles.length > 0) {\n\t\t\trouteStyles[route.path] = styles;\n\t\t}\n\t}\n\n\t// The component styles in each stylesheet: every scoped rule carries its\n\t// component's `torp-<hash>` class, and a component's styles are bundled\n\t// as one unit, so any occurrence means the whole block is there\n\tconst hashes: Record<string, string[]> = {};\n\tfor (const file of new Set([...entryStyles, ...Object.values(routeStyles).flat()])) {\n\t\tconst found = new Set<string>();\n\t\tfor (const match of readStylesheet(file.slice(1)).matchAll(/\\.torp-([a-z0-9]+)/g)) {\n\t\t\tfound.add(match[1]);\n\t\t}\n\t\tif (found.size > 0) {\n\t\t\thashes[file] = [...found];\n\t\t}\n\t}\n\n\treturn {\n\t\tentry,\n\t\troutes: preloads,\n\t\tstyles: { entry: entryStyles, routes: routeStyles, hashes },\n\t};\n}\n\nfunction unique(files: string[]): string[] {\n\treturn [...new Set(files)];\n}\n","import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { gzipSync } from \"node:zlib\";\nimport Router from \"../site/Router\";\nimport type Budgets from \"../types/Budgets\";\nimport type ModulePreloads from \"../types/ModulePreloads\";\nimport { PAGE_ROUTE } from \"../types/RouteType\";\n\n/** How much JavaScript one page loads before it hydrates. */\nexport interface PageSize {\n\tpath: string;\n\tfiles: number;\n\traw: number;\n\tgzip: number;\n}\n\n/** How many of the heaviest pages the build report lists. */\nconst REPORT_LIMIT = 10;\n\n/**\n * Works out how much JavaScript each page route loads before it hydrates:\n * the client entry's chunks, its layouts' and its own, as preloaded by the\n * server (see clientPreloads). Chunks loaded later through dynamic imports\n * aren't counted.\n *\n * @param preloads The client chunks per route, from the client build\n * @param routes The site's routes (path, type and sub folder)\n * @param clientFolder The client build's output folder (`dist/client`)\n */\nexport default function pageSizes(\n\tpreloads: ModulePreloads,\n\troutes: { path: string; type: number; subFolder?: string }[],\n\tclientFolder: string,\n): PageSize[] {\n\t// The router works out each page's layouts, the same way it does when\n\t// serving them\n\tconst router = new Router().addPages(\n\t\troutes.map((r) => ({\n\t\t\tpath: r.path,\n\t\t\ttype: r.type,\n\t\t\tendPoint: () => Promise.resolve({}),\n\t\t\tsubFolder: r.subFolder,\n\t\t})),\n\t);\n\n\tconst sizes = new Map<string, { raw: number; gzip: number }>();\n\tconst sizeOf = (file: string) => {\n\t\tlet size = sizes.get(file);\n\t\tif (!size) {\n\t\t\tconst content = readFileSync(path.join(clientFolder, file));\n\t\t\tsize = { raw: content.length, gzip: gzipSync(content).length };\n\t\t\tsizes.set(file, size);\n\t\t}\n\t\treturn size;\n\t};\n\n\tconst result: PageSize[] = [];\n\tfor (const route of router.routes) {\n\t\tif (route.handler.type !== PAGE_ROUTE) continue;\n\t\tconst handler = router.match(route.path, new URLSearchParams())?.handler;\n\t\tconst files = new Set(preloads.entry);\n\t\tfor (const layout of handler?.path === route.path ? (handler.layouts ?? []) : []) {\n\t\t\tfor (const file of preloads.routes[layout.path] ?? []) files.add(file);\n\t\t}\n\t\tfor (const file of preloads.routes[route.path] ?? []) files.add(file);\n\n\t\tlet raw = 0;\n\t\tlet gzip = 0;\n\t\tfor (const file of files) {\n\t\t\tconst size = sizeOf(file);\n\t\t\traw += size.raw;\n\t\t\tgzip += size.gzip;\n\t\t}\n\t\tresult.push({ path: route.path, files: files.size, raw, gzip });\n\t}\n\treturn result.sort((a, b) => b.gzip - a.gzip || a.path.localeCompare(b.path));\n}\n\n/** The pages over the JavaScript budget, if one is set. */\nexport function overBudget(pages: PageSize[], budgets: Budgets | undefined): PageSize[] {\n\tconst limit = budgets?.js;\n\tif (limit === undefined) return [];\n\treturn pages.filter((page) => page.gzip > limit);\n}\n\n/**\n * The build report: the heaviest pages (all of them, when there are few),\n * then every page over the budget.\n */\nexport function formatPageSizes(pages: PageSize[], budgets: Budgets | undefined): string {\n\tif (pages.length === 0) return \"\";\n\tconst over = overBudget(pages, budgets);\n\tconst shown = pages.slice(0, REPORT_LIMIT);\n\tconst width = Math.max(...shown.map((page) => page.path.length));\n\tconst row = (page: PageSize) =>\n\t\t` ${page.path.padEnd(width)} ${kb(page.gzip).padStart(9)} ` +\n\t\t`(${kb(page.raw)} raw, ${page.files} file${page.files === 1 ? \"\" : \"s\"})`;\n\n\tlet lines = [\"[torpor] JavaScript loaded by each page before it hydrates (gzipped):\"];\n\tlines.push(...shown.map(row));\n\tif (pages.length > shown.length) {\n\t\tconst rest = pages.length - shown.length;\n\t\tconst lightest = pages[pages.length - 1];\n\t\tlines.push(\n\t\t\t` ...and ${rest} more page${rest === 1 ? \"\" : \"s\"}, down to ${kb(lightest.gzip)} (${lightest.path})`,\n\t\t);\n\t}\n\tif (budgets?.js !== undefined) {\n\t\tif (over.length === 0) {\n\t\t\tlines.push(` All pages are within the ${kb(budgets.js)} budget.`);\n\t\t} else {\n\t\t\tlines.push(\n\t\t\t\t`[torpor] ${over.length} page${over.length === 1 ? \" is\" : \"s are\"} over the ` +\n\t\t\t\t\t`${kb(budgets.js)} JavaScript budget (site.budgets.js):`,\n\t\t\t);\n\t\t\tconst overWidth = Math.max(...over.map((page) => page.path.length));\n\t\t\tlines.push(\n\t\t\t\t...over.map(\n\t\t\t\t\t(page) =>\n\t\t\t\t\t\t` ${page.path.padEnd(overWidth)} ${kb(page.gzip).padStart(9)} ` +\n\t\t\t\t\t\t`(+${kb(page.gzip - budgets.js!)})`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction kb(bytes: number): string {\n\treturn `${(bytes / 1000).toFixed(1)} kB`;\n}\n","import { addBaseToPath, normalizeBasePath } from \"../site/basePath.ts\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport ServerEvent from \"../server/ServerEvent\";\nimport { sitemapXml } from \"../discovery/sitemap\";\nimport prepareTemplate from \"./prepareTemplate\";\nimport type Site from \"../site/Site\";\nimport { ERROR_ROUTE, PAGE_ROUTE, PAGE_SERVER_ROUTE, LAYOUT_ROUTE } from \"../types/RouteType\";\n\n/**\n * How a `prerender` flag can appear on an endpoint: `true`/`false` to\n * include/exclude a page, or a `params` entry list for a dynamic route.\n */\nexport type PrerenderFlag = boolean | { params: Record<string, unknown>[] };\n\n/** The route shapes the prerenderer resolves from (Router.routes, Site.routes). */\ntype RouteLike = {\n\tpath: string;\n\ttype: number;\n\tendPoint: () => Promise<any>;\n\tsubFolder?: string;\n};\n\nexport type PrerenderPath = {\n\tpath: string;\n\tparams: Record<string, string> | undefined;\n};\n\n/**\n * Resolves which page paths should be prerendered, from the routes of a\n * built site, testing in order:\n *\n * 1. the page endpoint's own `prerender` flag, or the inferred-params one\n * on the sibling `+page.server` endpoint\n * 2. the nearest ancestor `_layout` endpoint's flag\n * 3. the site-level `site.prerender` setting: a boolean default, or a\n * longest-match map of exact paths (`/about`) and prefixes (`/blog/**`)\n *\n * @param routes The site's routes, including layouts and page server\n * endpoints, with lazy endpoint loaders\n * @param siteFlag The `site.prerender` value\n * @returns The paths to prerender, with route params for dynamic ones\n */\nexport async function resolvePrerenderPaths(\n\troutes: RouteLike[],\n\tsiteFlag: boolean | Record<string, boolean> | undefined,\n): Promise<PrerenderPath[]> {\n\tconst result: PrerenderPath[] = [];\n\n\tfor (const route of routes.filter((r) => r.type === PAGE_ROUTE)) {\n\t\tconst base = route.path.replace(/\\/$/, \"\");\n\n\t\tconst pageFlag = (await endpointFlag(route.endPoint)) as PrerenderFlag | undefined;\n\t\tconst serverRoute = routes.find(\n\t\t\t(r) => r.type === PAGE_SERVER_ROUTE && r.path === `${base}/~server`,\n\t\t);\n\t\tconst serverFlag = serverRoute\n\t\t\t? ((await endpointFlag(serverRoute.endPoint)) as PrerenderFlag | undefined)\n\t\t\t: undefined;\n\n\t\tconst entries = paramsEntriesOf(pageFlag) ?? paramsEntriesOf(serverFlag);\n\t\tconst ownFlag =\n\t\t\tpageFlag === undefined\n\t\t\t\t? serverFlag === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: Boolean(serverFlag)\n\t\t\t\t: Boolean(pageFlag);\n\t\tconst resolved =\n\t\t\townFlag ?? (await nearestLayoutFlag(routes, route)) ?? siteResolve(route.path, siteFlag);\n\t\tif (!resolved) continue;\n\n\t\tif (/\\[[^\\]]+\\]/.test(route.path)) {\n\t\t\tif (!entries?.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`The route \"${route.path}\" is marked for prerendering, but it has dynamic ` +\n\t\t\t\t\t\t`segments and no params entries were declared. Set ` +\n\t\t\t\t\t\t`\\`prerender: { params: [...] }\\` on its endpoint.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const entry of entries) {\n\t\t\t\tresult.push({ path: expandPath(route.path, entry), params: toStringParams(entry) });\n\t\t\t}\n\t\t} else {\n\t\t\tresult.push({ path: route.path || \"/\", params: undefined });\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction paramsEntriesOf(flag: PrerenderFlag | undefined): Record<string, unknown>[] | undefined {\n\treturn typeof flag === \"object\" && flag !== null ? flag.params : undefined;\n}\n\n/**\n * Renders the prerenderable routes to static HTML files in the client\n * output, plus the `_error` page as `404.html` when the site has one.\n *\n * Called by `tb build` after the client and server builds, when the built\n * server entry (with its routes) can be imported directly, and before the\n * adapter's postbuild -- so a prerendered site ships as plain files and\n * any static host can serve it.\n *\n * @param site The loaded site config\n * @returns The number of HTML files written\n */\nexport default async function runPrerender(site: Site): Promise<number> {\n\tconst serverFolder = path.join(site.outputFolder, \"server\");\n\tconst clientFolder = path.join(site.outputFolder, \"client\");\n\tconst serverEntryPath = path.join(serverFolder, \"serverEntry.js\");\n\n\t// Load the built server entry, with its routes baked in\n\tconst serverEntry = (await import(pathToFileURL(serverEntryPath).href)) as {\n\t\tload: (ev: unknown, template: string | undefined) => Promise<Response>;\n\t\trouter: { routes: { path: string; handler: RouteLike }[] };\n\t};\n\tconst routes = serverEntry.router.routes.map((r) => r.handler);\n\n\t// Deserialize the client entry asset name the same way the Cloudflare\n\t// adapter does, so the template works the same for prerendered output\n\tlet template: string | undefined;\n\tconst siteHtml = path.join(clientFolder, \"site.html\");\n\tif (existsSync(siteHtml)) {\n\t\tconst assets = path.join(clientFolder, \"assets\");\n\t\tlet clientScript = (await fs.readdir(assets)).find((f) => f.startsWith(\"clientEntry-\"));\n\t\tif (!clientScript) {\n\t\t\tthrow new Error(\"clientEntry.js not found\");\n\t\t}\n\t\ttemplate = prepareTemplate(await fs.readFile(siteHtml, \"utf-8\"), `/assets/${clientScript}`);\n\t}\n\n\tconst entries = await resolvePrerenderPaths(routes, site.prerender);\n\tconst base = normalizeBasePath(site.basePath);\n\n\t// Load functions may read the environment (env() uses globalThis.adapter)\n\t// @ts-ignore\n\tglobalThis.adapter ??= { env: process.env };\n\n\tconst failures: string[] = [];\n\tconst skipped: string[] = [];\n\tlet written = 0;\n\tfor (const entry of entries) {\n\t\t// The server only answers requests under the site's base path\n\t\tconst url = `http://torpor.build${addBaseToPath(entry.path, base)}`;\n\t\tconst request = new Request(url);\n\t\tconst serverEvent = new ServerEvent(request, entry.params, new URL(url));\n\t\t// A page render embeds its server data as a `t-server-data` script (see\n\t\t// serverHandlers.loadView), so a prerendered page with a server load\n\t\t// hydrates with that data on a static host, with no `~server` request\n\t\tconst response = await serverEntry.load(serverEvent, template);\n\n\t\tif (isRedirect(response)) {\n\t\t\t// Load functions redirect for auth and first-run setup, which is\n\t\t\t// expected on a fresh site -- skip the page rather than failing\n\t\t\t// the build, so a site can ship before it's initialized\n\t\t\tskipped.push(`${entry.path} (status ${response.status})`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (response.status < 200 || response.status > 299) {\n\t\t\tfailures.push(`${entry.path} (status ${await responseStatus(response)})`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!response.headers.get(\"Content-Type\")?.includes(\"text/html\")) {\n\t\t\tfailures.push(`${entry.path} (not an HTML response)`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait writeFileForPath(clientFolder, entry.path, await response.text());\n\t\twritten++;\n\t}\n\n\t// The error page is useful on every static host, so render it whenever\n\t// the site has one, even when nothing else is prerendered: 404.html for\n\t// missing pages, and 500.html for the hosts that match error pages by\n\t// status. Requesting each with its status in the query yields that\n\t// status -- that's the page rendering correctly, not a failure\n\tconst errorRoute = routes.find((r) => r.type === ERROR_ROUTE);\n\tif (errorRoute && template !== undefined) {\n\t\tfor (const status of [404, 500]) {\n\t\t\tconst url = `http://torpor.build${addBaseToPath(\"/_error\", base)}?status=${status}`;\n\t\t\tconst serverEvent = new ServerEvent(new Request(url), undefined, new URL(url));\n\t\t\tconst response = await serverEntry.load(serverEvent, template);\n\t\t\tif (isRedirect(response)) {\n\t\t\t\t// The layout may redirect before the error page renders (e.g.\n\t\t\t\t// to a setup page on a fresh site) -- skip it; the host's\n\t\t\t\t// default error page is used instead\n\t\t\t\tskipped.push(`/_error (status ${response.status})`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tresponse.status === status &&\n\t\t\t\tresponse.headers.get(\"Content-Type\")?.includes(\"text/html\")\n\t\t\t) {\n\t\t\t\tawait fs.writeFile(path.join(clientFolder, `${status}.html`), await response.text());\n\t\t\t} else {\n\t\t\t\tfailures.push(`/_error (status ${await responseStatus(response)})`);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (skipped.length) {\n\t\tconsole.log(\n\t\t\t`Skipped prerendering ${skipped.length} route${skipped.length === 1 ? \"\" : \"s\"} ` +\n\t\t\t\t`(redirected):\\n` +\n\t\t\t\tskipped.map((s) => ` - ${s}`).join(\"\\n\"),\n\t\t);\n\t}\n\n\tif (failures.length) {\n\t\tthrow new Error(\n\t\t\t`Prerendering failed for ${failures.length} route${failures.length === 1 ? \"\" : \"s\"}:\\n` +\n\t\t\t\tfailures.map((f) => ` - ${f}`).join(\"\\n\"),\n\t\t);\n\t}\n\n\t// The sitemap, if configured, lists the URLs that were just rendered:\n\t// the set of pages that are actually static, which is exactly what a\n\t// build-time sitemap can honestly represent\n\tif (site.sitemap && site.origin && entries.length > 0) {\n\t\tconst sitemap = sitemapXml(\n\t\t\tsite.origin,\n\t\t\tbase,\n\t\t\tentries.map((entry) => entry.path),\n\t\t);\n\t\tawait fs.writeFile(\n\t\t\tpath.join(\n\t\t\t\tclientFolder,\n\t\t\t\ttypeof site.sitemap === \"string\" ? site.sitemap.slice(1) : \"sitemap.xml\",\n\t\t\t),\n\t\t\tsitemap,\n\t\t);\n\t}\n\n\treturn written;\n}\n\n/**\n * Writes an HTML file for a route path, e.g. `/` into `index.html` and\n * `/about` into `about/index.html`. Guards against route param values\n * escaping the client folder.\n */\nasync function writeFileForPath(\n\tclientFolder: string,\n\troutePath: string,\n\thtml: string,\n): Promise<void> {\n\tconst rel = routePath === \"/\" ? \"index.html\" : routePath.slice(1) + \"/index.html\";\n\tconst out = path.resolve(clientFolder, rel);\n\tconst relSafe = path.relative(clientFolder, out);\n\tif (relSafe.startsWith(\"..\") || path.isAbsolute(relSafe)) {\n\t\tthrow new Error(`The prerendered path \"${routePath}\" escaped ${clientFolder}`);\n\t}\n\tawait fs.mkdir(path.dirname(out), { recursive: true });\n\tawait fs.writeFile(out, html);\n}\n\nasync function endpointFlag(loader: () => Promise<any>): Promise<PrerenderFlag | undefined> {\n\tconst endPoint = (await loader())?.default;\n\treturn (endPoint as { prerender?: PrerenderFlag } | undefined)?.prerender;\n}\n\n/**\n * The nearest ancestor `_layout`'s flag for a page path, or undefined when\n * no layout sets one. Layouts apply within the same subFolder.\n */\nasync function nearestLayoutFlag(\n\troutes: RouteLike[],\n\troute: RouteLike,\n): Promise<boolean | undefined> {\n\tlet flag: boolean | undefined;\n\tlet flagLength = -1;\n\tfor (const candidate of routes) {\n\t\tif (candidate.type !== LAYOUT_ROUTE || candidate.subFolder !== route.subFolder) continue;\n\t\tconst base = candidate.path.replace(/\\/_layout$/, \"\");\n\t\tconst isAncestor = base === \"\" || route.path === base || route.path.startsWith(base + \"/\");\n\t\tif (!isAncestor) continue;\n\t\tconst flagOfLayout = (await endpointFlag(candidate.endPoint)) as boolean | undefined;\n\t\tif (flagOfLayout !== undefined && base.length > flagLength) {\n\t\t\tflag = flagOfLayout;\n\t\t\tflagLength = base.length;\n\t\t}\n\t}\n\treturn flag;\n}\n\nfunction siteResolve(\n\troutePath: string,\n\tsiteFlag: boolean | Record<string, boolean> | undefined,\n): boolean | undefined {\n\tif (siteFlag === undefined) return undefined;\n\tif (typeof siteFlag === \"boolean\") return siteFlag;\n\n\tlet flag: boolean | undefined;\n\tlet flagLength = -1;\n\tfor (const [pattern, value] of Object.entries(siteFlag)) {\n\t\tconst base = pattern.replace(/\\/\\*\\*$/, \"\");\n\t\tconst isPrefixMatch =\n\t\t\tbase !== pattern && (routePath === base || routePath.startsWith(base + \"/\"));\n\t\tif ((pattern === routePath || isPrefixMatch) && pattern.length > flagLength) {\n\t\t\tflag = value;\n\t\t\tflagLength = pattern.length;\n\t\t}\n\t}\n\treturn flag;\n}\n\nfunction toStringParams(entry: Record<string, unknown>): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(entry)) {\n\t\tresult[key] = String(value);\n\t}\n\treturn result;\n}\n\n/**\n * Fills a route path's `[param]` and `[...rest]` segments with the values\n * from a params entry.\n */\nexport function expandPath(routePath: string, entry: Record<string, unknown>): string {\n\treturn routePath.replace(/\\[([^\\]]+)\\]/g, (_match, name: string) => {\n\t\tconst key = name.replace(/^\\.\\.\\./, \"\");\n\t\tif (!(key in entry)) {\n\t\t\tthrow new Error(`Missing param \"${key}\" for the route \"${routePath}\" (prerendering)`);\n\t\t}\n\t\treturn String(entry[key]);\n\t});\n}\n\nfunction isRedirect(response: Response): boolean {\n\treturn response.status >= 300 && response.status < 400;\n}\n\nasync function responseStatus(response: Response): Promise<string> {\n\treturn `${response.status}${response.status === 303 ? \" redirect\" : \"\"}`;\n}\n","import torpor from \"@torpor/unplugin/vite\";\nimport { configDotenv } from \"dotenv\";\nimport { existsSync, promises as fs, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { build, defineConfig, type AliasOptions } from \"vite\";\nimport Site from \"../site/Site\";\nimport { checkApiCalls, checkRoutes, reportRouteIssues } from \"../site/checkRoutes\";\nimport { checkLayoutSlots } from \"../site/checkLayoutSlots\";\nimport { normalizeBasePath } from \"../site/basePath.ts\";\nimport manifest from \"../site/manifest.ts\";\nimport tsconfigAliases, { type AliasEntry } from \"../utils/tsconfigAliases\";\nimport { addTorporPackageConfig } from \"../utils/torporPackages\";\nimport { siteEntryPaths } from \"../utils/entryPaths\";\nimport clientPreloads, { type ViteManifestChunk } from \"./clientPreloads\";\nimport pageSizes, { formatPageSizes, overBudget } from \"./pageSizes\";\nimport runPrerender from \"./runPrerender\";\n\n// TODO: Don't cache index.html in dev?\n// TODO: Don't reload layouts during client routing\n// TODO: Call the correct +page and +server routes when in the same folder\n\nexport default async function runBuild(site: Site): Promise<void> {\n\t// Load environment variables from a `.env` file, with defaults if not\n\t// set -- prerendering goes through the full load pipeline, so route\n\t// `load` functions can hit the database at build time\n\tconfigDotenv();\n\n\t// Check route type annotations and makeApi calls against the routes\n\t// derived from file locations, and check that layouts render their slot;\n\t// errors fail the build before anything is written\n\tlet errorCount = reportRouteIssues(checkRoutes(site));\n\terrorCount += reportRouteIssues(checkApiCalls(site));\n\terrorCount += reportRouteIssues(checkLayoutSlots(site));\n\tif (errorCount > 0) {\n\t\tthrow new Error(\n\t\t\t`Route type check failed with ${errorCount} error${errorCount === 1 ? \"\" : \"s\"} (see above)`,\n\t\t);\n\t}\n\n\t// Delete the output folder if it exists\n\tconst distFolder = site.outputFolder;\n\tif (existsSync(distFolder)) {\n\t\tawait fs.rm(distFolder, { recursive: true });\n\t}\n\tconst clientFolder = path.join(distFolder, \"client\");\n\tconst serverFolder = path.join(distFolder, \"server\");\n\n\t// HOOK: Prebuild\n\tif (site.adapter.prebuild) {\n\t\tawait site.adapter.prebuild(site);\n\t}\n\n\t// TODO: From a setting\n\t// An endpoints-only site has no site.html, so everything template-related\n\t// is optional\n\tconst siteHtml = path.resolve(site.root, \"src/site.html\");\n\tconst hasSiteHtml = existsSync(siteHtml);\n\n\t// Production always bundles the compiled entry files from the installed\n\t// package, so builds don't depend on (unshipped) framework sources\n\tconst entries = siteEntryPaths(site.root, false);\n\tconst clientScript = entries.clientEntry;\n\tconst serverScript = entries.serverEntry;\n\n\t// Build the client assets, including site.html and the route files\n\t// EXCLUDING anything with `server.js` in the name\n\tconst clientConfig = structuredClone(site.viteConfig ?? {});\n\t// Resolve tsconfig path aliases (e.g. `@/*`). Previously provided by the\n\t// default `vite-tsconfig-paths` plugin on Site; vite-plus handles it inline\n\t// for the client, but hardcodes tsconfigPaths:false on the SSR\n\t// externalization path, so mirror tsconfig `compilerOptions.paths` as Vite\n\t// `resolve.alias` to resolve them during transform for both client and SSR\n\tclientConfig.resolve ??= {};\n\tclientConfig.resolve.tsconfigPaths ??= true;\n\tclientConfig.resolve.alias = [\n\t\t...asAliasArray(clientConfig.resolve.alias),\n\t\t...tsconfigAliases(site.root),\n\t];\n\t// The client build's resolved root, which its manifest's keys are\n\t// relative to\n\tlet clientRoot = site.root;\n\tclientConfig.plugins = [\n\t\tmanifest(site),\n\t\ttorpor(),\n\t\t...site.vitePlugins,\n\t\t{\n\t\t\tname: \"torpor-client-root\",\n\t\t\tconfigResolved(config) {\n\t\t\t\tclientRoot = config.root;\n\t\t\t},\n\t\t},\n\t];\n\tclientConfig.build ??= {};\n\tclientConfig.build.outDir = clientFolder;\n\t// The client's own asset URLs -- the stylesheets and chunks Vite's\n\t// preload helper loads on client navigation, and `url()`s in CSS -- carry\n\t// the base path. The server rewrites the URLs in rendered HTML itself\n\t// (see rewriteBaseInHtml), and leaves ones that already have the base\n\t// alone\n\tconst base = normalizeBasePath(site.basePath);\n\tif (base) {\n\t\tclientConfig.base ??= base + \"/\";\n\t}\n\t// Root-level host files (robots.txt, favicon.ico, .well-known/*, etc) in\n\t// src/public are copied verbatim into the client output root, and served\n\t// from the same folder by the dev server\n\tconst publicDir = path.resolve(site.root, \"src/public\");\n\tif (existsSync(publicDir)) {\n\t\tclientConfig.publicDir = publicDir;\n\t}\n\tclientConfig.build.rollupOptions ??= {};\n\tclientConfig.build.rollupOptions.input = [\n\t\t...(hasSiteHtml ? [siteHtml] : []),\n\t\tclientScript,\n\t\t...site.routes\n\t\t\t.filter((r) => r.file && !/server\\.(ts|js)$/.test(r.file))\n\t\t\t.map((r) => path.resolve(site.root, r.file!)),\n\t\t...site.inputs.filter((f) => !/server\\.(ts|js)$/.test(f)),\n\t];\n\tclientConfig.build.ssrManifest = true;\n\t// The build manifest says which chunks each route needs, so pages can\n\t// preload them (see clientPreloads)\n\tclientConfig.build.manifest ??= true;\n\tawait build(defineConfig(clientConfig));\n\n\tconst manifestFile = path.join(\n\t\tclientFolder,\n\t\ttypeof clientConfig.build.manifest === \"string\"\n\t\t\t? clientConfig.build.manifest\n\t\t\t: \".vite/manifest.json\",\n\t);\n\tconst preloads = existsSync(manifestFile)\n\t\t? clientPreloads(\n\t\t\t\tJSON.parse(await fs.readFile(manifestFile, \"utf-8\")) as Record<string, ViteManifestChunk>,\n\t\t\t\tclientRoot,\n\t\t\t\tsite.routes\n\t\t\t\t\t.filter((r) => r.file && !/server\\.(ts|js)$/.test(r.file))\n\t\t\t\t\t.map((r) => ({ path: r.path, file: path.resolve(site.root, r.file!) })),\n\t\t\t\t(file) => readFileSync(path.join(clientFolder, file), \"utf-8\"),\n\t\t\t)\n\t\t: undefined;\n\n\t// Build the server assets, including the server entry script and the route\n\t// files\n\tconst serverConfig = structuredClone(site.viteConfig ?? {});\n\t// Resolve tsconfig path aliases (e.g. `@/*`), as above\n\tserverConfig.resolve ??= {};\n\tserverConfig.resolve.tsconfigPaths ??= true;\n\tserverConfig.resolve.alias = [\n\t\t...asAliasArray(serverConfig.resolve.alias),\n\t\t...tsconfigAliases(site.root),\n\t];\n\t// Report how much JavaScript the pages load, and check the budget, before\n\t// spending time on the server build\n\tif (preloads) {\n\t\tconst pages = pageSizes(preloads, site.routes, clientFolder);\n\t\tconst report = formatPageSizes(pages, site.budgets);\n\t\tconst over = overBudget(pages, site.budgets);\n\t\tif (over.length > 0) {\n\t\t\tconsole.warn(report);\n\t\t\tif (site.budgets?.fail) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${over.length} page${over.length === 1 ? \" is\" : \"s are\"} over the JavaScript budget (see above)`,\n\t\t\t\t);\n\t\t\t}\n\t\t} else if (report) {\n\t\t\tconsole.log(report);\n\t\t}\n\t}\n\n\tserverConfig.plugins = [manifest(site, true, false, preloads), torpor(), ...site.vitePlugins];\n\tserverConfig.build ??= {};\n\tserverConfig.build.outDir = serverFolder;\n\t// Bundle packages that ship `.torp` files into the server build, as they\n\t// need the torpor compiler (Node/workerd can't load them externalized)\n\taddTorporPackageConfig(site.root, serverConfig);\n\tserverConfig.build.rollupOptions ??= {};\n\tserverConfig.build.rollupOptions.input = [\n\t\tserverScript,\n\t\t...site.routes.filter((r) => r.file).map((r) => path.resolve(site.root, r.file!)),\n\t\t...site.inputs,\n\t];\n\tserverConfig.build.ssr = serverScript;\n\tawait build(defineConfig(serverConfig));\n\n\t// Move the site.html file into /client\n\t// HACK: Should do this in Rollup if possible?\n\tif (hasSiteHtml) {\n\t\tawait fs.rename(\n\t\t\tpath.join(clientFolder, \"src\", \"site.html\"),\n\t\t\tpath.join(clientFolder, \"site.html\"),\n\t\t);\n\t\tawait fs.rm(path.join(clientFolder, \"src\"), { recursive: true });\n\t}\n\n\t// Prerender routes marked with `prerender` -- including everything\n\t// inherited from layouts and site.prerender -- to static HTML files in\n\t// the client output, plus the error page as 404.html. Any static host\n\t// can then serve dist/client directly\n\tconst prerendered = await runPrerender(site);\n\tif (prerendered > 0) {\n\t\tconsole.log(`[torpor] Prerendered ${prerendered} route${prerendered === 1 ? \"\" : \"s\"}`);\n\t}\n\n\t// HOOK: Postbuild\n\tif (site.adapter.postbuild) {\n\t\tawait site.adapter.postbuild(site);\n\t}\n}\n\nfunction asAliasArray(alias: AliasOptions | undefined): AliasEntry[] {\n\t// Normalize an existing `resolve.alias` value (array | object | undefined)\n\t// into an array so we can concatenate our tsconfig-derived aliases.\n\tif (!alias) return [];\n\tif (Array.isArray(alias)) return alias;\n\treturn Object.entries(alias).map(([find, replacement]) => ({ find, replacement }));\n}\n","import { createHash } from \"node:crypto\";\nimport {\n\texistsSync,\n\treadFileSync,\n\treaddirSync,\n\trealpathSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport type { PackageJson } from \"../utils/torporPackages\";\n\n/**\n * Vite's dep-optimization cache (node_modules/.vite) keys off the lockfile\n * and config, but not the content of workspace packages. When a workspace\n * package is rebuilt while the cache holds prebundled copies of it, dev SSR\n * keeps executing the stale modules -- producing bizarre errors (missing\n * runtime identifiers, \"$cache must be used in a getter\", ...) that only a\n * manual cache delete fixes.\n *\n * clearStaleDepCache runs at `tb --dev` startup: it fingerprints every\n * workspace package the site depends on (path, size and mtime of each file)\n * and, when the fingerprint differs from the previous run, deletes the cache\n * so Vite re-optimizes from the rebuilt packages.\n *\n * Live rebuilds while the server is up are still not hot-invalidated (that\n * needs a watcher feeding Vite's module graph); this closes the \"restart and\n * hope you remember the trick\" gap.\n */\n\nconst STORE_NAME = \".torpor-dev-cache.json\";\n\n/**\n * The dep cache a dev server should use: Vite's default\n * (`<siteRoot>/node_modules/.vite`) would be shared by every app whose\n * `site.root` is the same -- e.g. a workspace package that owns the views and\n * is used by both a web and an Electron app. Those apps have different configs\n * (aliases, plugins, adapter), so they optimize different dep graphs; sharing\n * one directory makes each rewrite the other's `_metadata.json` (browser\n * hashes go stale, Vite answers 504) and lets one app's startup clear the\n * other's running cache. Derive a directory from the config file instead.\n */\nexport function defaultDepCacheDir(siteRoot: string, configFile?: string): string {\n\tconst base = path.join(siteRoot, \"node_modules\", \".vite\");\n\tif (!configFile) return base;\n\tconst absolute = path.resolve(configFile);\n\tconst name = path\n\t\t.basename(absolute)\n\t\t.replace(/\\.[^.]+$/, \"\")\n\t\t.replace(/[^\\w.-]+/g, \"-\");\n\tconst hash = createHash(\"sha1\").update(absolute).digest(\"hex\").slice(0, 8);\n\treturn path.join(base, `${name}-${hash}`);\n}\n\n/**\n * Clears the dev dep cache when workspace packages changed since the last dev\n * run. Returns true when the cache was removed.\n *\n * @param cacheDir The Vite cache directory (see `defaultDepCacheDir`). Defaults\n * to `<siteRoot>/node_modules/.vite`.\n */\nexport function clearStaleDepCache(\n\tsiteRoot: string,\n\tcacheDir: string = path.join(siteRoot, \"node_modules\", \".vite\"),\n\tlog?: (message: string) => void,\n): boolean {\n\ttry {\n\t\tconst workspaceRoot = findWorkspaceRoot(siteRoot);\n\t\tif (!workspaceRoot) return false;\n\n\t\tconst storePath = path.join(siteRoot, \"node_modules\", STORE_NAME);\n\n\t\tconst fingerprint = fingerprintWorkspacePackages(siteRoot, workspaceRoot);\n\t\tif (fingerprint === undefined) return false;\n\n\t\tconst previous = readStore(storePath);\n\n\t\tlet cleared = false;\n\t\tif (existsSync(cacheDir) && previous !== fingerprint) {\n\t\t\trmSync(cacheDir, { recursive: true, force: true });\n\t\t\tcleared = true;\n\t\t\tlog?.(\"Workspace packages changed; clearing the Vite dep cache\");\n\t\t}\n\t\twriteFileSync(storePath, JSON.stringify({ fingerprint }));\n\n\t\treturn cleared;\n\t} catch (e) {\n\t\tif (process.env.TORPOR_DEBUG_CACHE) throw e;\n\t\t// Never break dev startup over cache bookkeeping\n\t\treturn false;\n\t}\n}\n\nexport function findWorkspaceRoot(from: string): string | undefined {\n\tlet dir = path.resolve(from);\n\twhile (true) {\n\t\t// pnpm-style marker, or a root package.json declaring npm workspaces\n\t\tif (existsSync(path.join(dir, \"pnpm-workspace.yaml\"))) {\n\t\t\treturn dir;\n\t\t}\n\t\tif (hasWorkspacesField(dir)) {\n\t\t\treturn dir;\n\t\t}\n\t\tconst parent = path.dirname(dir);\n\t\tif (parent === dir) return undefined;\n\t\tdir = parent;\n\t}\n}\n\nfunction hasWorkspacesField(dir: string): boolean {\n\tconst packageJsonPath = path.join(dir, \"package.json\");\n\tif (!existsSync(packageJsonPath)) return false;\n\ttry {\n\t\tconst pkg: PackageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\"));\n\t\treturn Array.isArray(pkg.workspaces) && pkg.workspaces.length > 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction readStore(storePath: string): string | undefined {\n\tif (!existsSync(storePath)) return undefined;\n\ttry {\n\t\tconst store = JSON.parse(readFileSync(storePath, \"utf8\")) as { fingerprint?: string };\n\t\treturn store.fingerprint;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Resolves every site dependency that lives inside the workspace to its\n * package folder. Shared with the other dev-startup checks (e.g. the stale\n * .torp copy report), which need the same set of packages.\n */\nexport function workspaceDependencyDirs(siteRoot: string, workspaceRoot: string): string[] {\n\tconst sitePackageJson = path.join(siteRoot, \"package.json\");\n\tif (!existsSync(sitePackageJson)) return [];\n\n\tconst pkg: PackageJson = JSON.parse(readFileSync(sitePackageJson, \"utf8\"));\n\tconst require = createRequire(sitePackageJson);\n\n\tconst packageDirs = new Set<string>();\n\tfor (const name of dependencyNames(pkg)) {\n\t\tconst dir = resolvePackageDir(name, require);\n\t\tif (dir && insideWorkspace(realpathSync(dir), workspaceRoot)) {\n\t\t\tpackageDirs.add(realpathSync(dir));\n\t\t}\n\t}\n\treturn [...packageDirs].sort();\n}\n\nfunction fingerprintWorkspacePackages(siteRoot: string, workspaceRoot: string): string | undefined {\n\tconst sitePackageJson = path.join(siteRoot, \"package.json\");\n\tif (!existsSync(sitePackageJson)) return undefined;\n\n\tconst packageDirs = workspaceDependencyDirs(siteRoot, workspaceRoot);\n\tif (packageDirs.length === 0) return undefined;\n\n\tconst hash = createHash(\"sha1\");\n\tfor (let dir of packageDirs) {\n\t\thash.update(`package:${dir}\\n`);\n\t\tfingerprintDir(dir, dir, hash);\n\t}\n\treturn hash.digest(\"hex\");\n}\n\nfunction dependencyNames(pkg: PackageJson): string[] {\n\treturn [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})];\n}\n\nfunction resolvePackageDir(name: string, require: NodeRequire): string | undefined {\n\ttry {\n\t\tconst packageJsonPath = require.resolve(`${name}/package.json`);\n\t\treturn path.dirname(packageJsonPath);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction insideWorkspace(dir: string, workspaceRoot: string): boolean {\n\tconst relative = path.relative(workspaceRoot, dir);\n\treturn relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\nfunction fingerprintDir(dir: string, root: string, hash: import(\"node:crypto\").Hash): void {\n\tfor (let entry of readdirSync(dir, { withFileTypes: true })) {\n\t\tif (entry.name === \"node_modules\" || entry.name === \".git\") continue;\n\t\tconst full = path.join(dir, entry.name);\n\t\tif (entry.isDirectory()) {\n\t\t\tfingerprintDir(full, root, hash);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!entry.isFile()) continue;\n\t\tconst stats = statSync(full);\n\t\t// NOTE: hash.update takes (data, encoding) -- join into one string\n\t\thash.update(\n\t\t\t`file:${path.relative(root, full).replaceAll(\"\\\\\", \"/\")}:${stats.size}:${Math.floor(stats.mtimeMs)}\\n`,\n\t\t);\n\t}\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { createServer as createViteServer, type ViteDevServer } from \"vite\";\nimport Site from \"../site/Site\";\n\n/**\n * Finds the site.config.js/ts file in the given folder.\n */\nexport function findConfigFile(folder: string): string {\n\tconst jsConfigFile = path.join(folder, \"site.config.js\");\n\tconst tsConfigFile = path.join(folder, \"site.config.ts\");\n\tif (fs.existsSync(jsConfigFile)) return jsConfigFile;\n\tif (fs.existsSync(tsConfigFile)) return tsConfigFile;\n\tthrow new Error(\"site.config file not found\");\n}\n\n/**\n * Creates the temporary Vite server used to load the site config, so that\n * local TS imports (e.g. a routes.ts file) and path aliases are resolved\n * correctly. Kept separate from the app's dev server: the config is loaded\n * before that server exists.\n */\nexport function createConfigVite(): Promise<ViteDevServer> {\n\treturn createViteServer({\n\t\tserver: { middlewareMode: true },\n\t\tappType: \"custom\",\n\t\tresolve: { tsconfigPaths: true },\n\t\toptimizeDeps: { noDiscovery: true },\n\t});\n}\n\n/**\n * Loads (or, when the config module has been invalidated, re-loads) the site\n * config through an existing config Vite server and runs its plugins.\n */\nexport async function loadSiteFromVite(vite: ViteDevServer, configFile: string): Promise<Site> {\n\tconst site = (await vite.ssrLoadModule(configFile)).default as Site;\n\tsite.configFile = configFile;\n\n\tif (!site || !site.root || !site.routes) {\n\t\tthrow new Error(\"Invalid site in config file\");\n\t}\n\n\t// Run the site's plugins. The manifest plugin also runs them when the\n\t// server starts up (dev SSR and production), so that plugin routes are\n\t// registered in the runtime as well\n\tfor (const plugin of site.plugins) {\n\t\tawait plugin(site);\n\t}\n\n\treturn site;\n}\n\n/**\n * Looks for and loads a site.config.js/ts file in the working directory,\n * running the site's plugins. The Vite server used to load the config is\n * returned as well, so that (for example) route files can be loaded through\n * it; callers are responsible for closing it.\n */\nexport async function loadSite(folder: string): Promise<{ site: Site; vite: ViteDevServer }> {\n\tconst configFile = findConfigFile(folder);\n\n\tconst vite = await createConfigVite();\n\ttry {\n\t\tconst site = await loadSiteFromVite(vite, configFile);\n\t\treturn { site, vite };\n\t} catch (error) {\n\t\tawait vite.close();\n\t\tthrow error;\n\t}\n}\n\n/**\n * The site-root files the config depends on -- the config itself and any\n * modules it imports (e.g. a `routes.ts` that calls `addRoute`). The dev\n * server watches these so route changes defined in code are picked up, not\n * just edits to `site.config.ts` itself.\n */\nexport function configDependencyFiles(vite: ViteDevServer, root: string): Set<string> {\n\tconst files = new Set<string>();\n\tconst graph = vite.environments.ssr.moduleGraph;\n\tfor (const mod of graph.idToModuleMap.values()) {\n\t\tif (mod.file && isInside(root, mod.file)) {\n\t\t\tfiles.add(mod.file);\n\t\t}\n\t}\n\treturn files;\n}\n\nfunction isInside(dir: string, file: string): boolean {\n\tconst rel = path.relative(dir, file);\n\treturn rel === \"\" || (!rel.startsWith(\"..\") && !path.isAbsolute(rel));\n}\n","import { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { PackageJson } from \"../utils/torporPackages\";\nimport { findWorkspaceRoot, workspaceDependencyDirs } from \"./depCache\";\n\n/**\n * Workspace packages that ship copies of their .torp components (e.g.\n * @torpor/ui copies its src .torp files into dist/ during its build) can go\n * stale: a site resolves the package to its dist folder, so edits to src\n * silently keep serving the OLD components until the package is rebuilt.\n * The symptom is confusing -- e.g. a TypeError about a renamed slot prop\n * after a component's API changed.\n *\n * reportStaleTorpCopies runs at `tb --dev` startup: for every workspace\n * dependency with both src and dist folders, it compares the .torp files and\n * reports anything missing from dist, differing from src, or left over in\n * dist without a src file.\n */\n\n/**\n * Reports stale dist .torp copies in the site's workspace dependencies.\n * Never throws -- a broken check must not break dev startup.\n */\nexport function reportStaleTorpCopies(siteRoot: string, log?: (message: string) => void): void {\n\ttry {\n\t\tconst workspaceRoot = findWorkspaceRoot(siteRoot);\n\t\tif (!workspaceRoot) return;\n\n\t\tfor (const dir of workspaceDependencyDirs(siteRoot, workspaceRoot)) {\n\t\t\tconst srcFolder = path.join(dir, \"src\");\n\t\t\tconst distFolder = path.join(dir, \"dist\");\n\t\t\t// Only packages that ship dist copies of src .torp files are\n\t\t\t// checked; packages without the folders (or with neither .torp\n\t\t\t// set) are skipped\n\t\t\tif (!existsSync(srcFolder) || !existsSync(distFolder)) continue;\n\t\t\tconst src = collectTorpFiles(srcFolder);\n\t\t\tconst dist = collectTorpFiles(distFolder);\n\t\t\tif (src.size === 0 && dist.size === 0) continue;\n\n\t\t\tconst problems: string[] = [];\n\t\t\tfor (const [rel, content] of src) {\n\t\t\t\tconst distContent = dist.get(rel);\n\t\t\t\tif (distContent === undefined) {\n\t\t\t\t\tproblems.push(`${rel} (not copied to dist)`);\n\t\t\t\t} else if (distContent !== content) {\n\t\t\t\t\tproblems.push(`${rel} (differs from src)`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const rel of dist.keys()) {\n\t\t\t\tif (!src.has(rel)) {\n\t\t\t\t\tproblems.push(`${rel} (left over in dist, no src file)`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (problems.length === 0) continue;\n\n\t\t\tconst shown = problems\n\t\t\t\t.slice(0, 5)\n\t\t\t\t.map((p) => ` ${p}`)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst more = problems.length > 5 ? `\\n ... and ${problems.length - 5} more` : \"\";\n\t\t\tlog?.(\n\t\t\t\t`${packageLabel(dir, workspaceRoot)}'s dist .torp copies are stale, so the site is ` +\n\t\t\t\t\t`serving OLD components:\\n${shown}${more}\\n` +\n\t\t\t\t\t`Rebuild the package (e.g. \\`pnpm build\\` in ` +\n\t\t\t\t\t`${path.relative(workspaceRoot, dir) || \".\"}) and restart \\`tb --dev\\`.`,\n\t\t\t);\n\t\t}\n\t} catch (e) {\n\t\tif (process.env.TORPOR_DEBUG_CACHE) throw e;\n\t}\n}\n\nfunction collectTorpFiles(folder: string): Map<string, string> {\n\tconst files = new Map<string, string>();\n\tcollect(folder, folder, files);\n\treturn files;\n}\n\nfunction collect(folder: string, root: string, files: Map<string, string>): void {\n\tfor (const entry of readdirSync(folder, { withFileTypes: true })) {\n\t\tif (entry.name === \"node_modules\" || entry.name === \".git\") continue;\n\t\tconst full = path.join(folder, entry.name);\n\t\tif (entry.isDirectory()) {\n\t\t\tcollect(full, root, files);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!entry.isFile() || !entry.name.endsWith(\".torp\")) continue;\n\t\tfiles.set(path.relative(root, full).replaceAll(\"\\\\\", \"/\"), readFileSync(full, \"utf8\"));\n\t}\n}\n\nfunction packageLabel(dir: string, workspaceRoot: string): string {\n\ttry {\n\t\tconst pkg: PackageJson = JSON.parse(readFileSync(path.join(dir, \"package.json\"), \"utf8\"));\n\t\tif (pkg.name) return pkg.name;\n\t} catch {\n\t\t// Fall through to the relative path\n\t}\n\treturn path.relative(workspaceRoot, dir) || dir;\n}\n","import torpor from \"@torpor/unplugin/vite\";\nimport { configDotenv } from \"dotenv\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n\ttype AliasOptions,\n\tcreateServer as createViteServer,\n\ttype Plugin,\n\ttype UserConfig,\n\ttype ViteDevServer,\n} from \"vite\";\nimport Site from \"../site/Site.ts\";\nimport {\n\tcheckApiCallSource,\n\tcheckApiCalls,\n\tcheckRoute,\n\tcheckRoutes,\n\tcreateApiCallCheck,\n\ttype RouteCheckIssue,\n\treportRouteIssues,\n} from \"../site/checkRoutes\";\nimport manifest, { MANIFEST_MODULE_ID } from \"../site/manifest.ts\";\nimport { checkLayoutSlot, checkLayoutSlots } from \"../site/checkLayoutSlots\";\nimport { LAYOUT_ROUTE } from \"../types/RouteType\";\nimport tsconfigAliases, { type AliasEntry } from \"../utils/tsconfigAliases\";\nimport { addTorporPackageConfig } from \"../utils/torporPackages\";\nimport { detectSourceMode, siteEntryPaths } from \"../utils/entryPaths\";\nimport devPlugin from \"./devPlugin.ts\";\nimport { clearStaleDepCache, defaultDepCacheDir } from \"./depCache\";\nimport { configDependencyFiles, loadSite } from \"./loadSite.ts\";\nimport { reportStaleTorpCopies } from \"./staleTorpCopies\";\n\n/**\n * @param configVite The Vite server used to load the site config (see\n * `loadSite`). Its module graph tells the dev server which files the config\n * imports, so `addRoute` calls in those files (e.g. a `routes.ts`) trigger a\n * route reload too. Without it, only file-based routes are reloaded.\n */\nexport default async function runDev(site: Site, configVite?: ViteDevServer): Promise<void> {\n\t// Create the Vite dev server. Unlike the previous middleware-mode setup, we\n\t// let Vite own the HTTP server (so HMR/websockets work natively) and let the\n\t// adapter's `dev()` plugin(s) handle SSR via configureServer.\n\tconst config = structuredClone(site.viteConfig ?? {});\n\tconfig.appType = \"custom\";\n\tconfig.server ??= {};\n\tconfig.server.host ??= \"localhost\";\n\t// Give each site config its own dep cache. Vite's default lives under\n\t// `site.root`, which several apps may share (e.g. a web and an Electron app\n\t// that both build from the same views package); sharing it lets them\n\t// rewrite each other's optimized deps and clear each other's cache\n\tconst cacheDir = config.cacheDir\n\t\t? path.resolve(site.root, config.cacheDir)\n\t\t: defaultDepCacheDir(site.root, site.configFile);\n\tconfig.cacheDir = cacheDir;\n\t// Root-level host files (robots.txt, favicon.ico, etc) in src/public are\n\t// served by Vite's middleware in dev and copied into the build output\n\tconst publicDir = path.resolve(site.root, \"src/public\");\n\tif (existsSync(publicDir)) {\n\t\tconfig.publicDir = publicDir;\n\t}\n\t// Resolve tsconfig path aliases (e.g. `@/*`). Previously provided by the\n\t// default `vite-tsconfig-paths` plugin on Site; vite-plus handles it inline\n\tconfig.resolve ??= {};\n\tconfig.resolve.tsconfigPaths ??= true;\n\t// When the framework itself is linked into the app (workspace/link:\n\t// installs), resolve `@torpor/view` and `@torpor/build/dev` from source via\n\t// their `torpor:source` export conditions, so framework changes take effect\n\t// without rebuilding dist. Registry installs run the compiled dist.\n\t//\n\t// Note: this must be a custom condition, not Vite's built-in `development`\n\t// one — Vite's dev server activates `development` by default, which made\n\t// registry installs resolve the unpublished `src/` files and fail.\n\tconst sourceMode = detectSourceMode(site.root);\n\tif (sourceMode) {\n\t\tconfig.resolve.conditions ??= [];\n\t\tconfig.resolve.conditions.push(\"torpor:source\");\n\t}\n\t// vite-plus' `tsconfigPaths` isn't honored by the SSR module-runner's\n\t// externalization path (it hardcodes tsconfigPaths:false), so dev SSR can't\n\t// resolve path aliases. Mirror tsconfig `compilerOptions.paths` as Vite\n\t// `resolve.alias` so they resolve during transform for both client and SSR.\n\tconfig.resolve.alias = [...asAliasArray(config.resolve.alias), ...tsconfigAliases(site.root)];\n\n\t// The adapter provides the dev-runtime plugin(s); fall back to the\n\t// framework's Node-runtime plugin when it doesn't.\n\tconst adapterDev = site.adapter.dev?.(site);\n\tconst devPlugins = normalizePlugins(adapterDev ?? devPlugin(site, sourceMode));\n\n\tconfig.plugins = [\n\t\tmanifest(site, true, true),\n\t\ttorpor({ dev: true }),\n\t\t...devPlugins,\n\t\t...site.vitePlugins,\n\t];\n\n\t// HACK: To be able to import `.torp` files from barrel files in\n\t// node_modules, we need to add their libraries to `ssr.noExternal` in\n\t// site.config.ts, and let the dep optimizer know how to compile them\n\t// here. The optimizer is a rolldown build, so it needs a rolldown-shaped\n\t// plugin (the vite export) -- an esbuild-shaped one is silently ignored\n\taddTorpOptimizerSettings((config.optimizeDeps ??= {}));\n\n\t// Packages that ship `.torp` files (e.g. icon libraries) need the torpor\n\t// compiler: dep optimization would parse them as plain JavaScript and\n\t// fail, and SSR externalization would leave raw `.torp` imports that\n\t// Node/workerd can't load. Exclude them from optimization and mark them\n\t// for SSR bundling so they go through the torpor plugin\n\taddTorporPackageConfig(site.root, config);\n\n\t// The SSR environment optimizer has its own settings; mirror the compiler\n\t// setup there too. Without this, a cold dep cache still prebundles torpor\n\t// packages (and parses their `.torp` files as JS) even though the root\n\t// optimizer excludes them.\n\taddTorpOptimizerSettings(((config.ssr ??= {}).optimizeDeps ??= {}));\n\taddTorpOptimizerSettings((((config.environments ??= {}).ssr ??= {}).optimizeDeps ??= {}));\n\n\t// Workspace packages may have been rebuilt since the last dev run; drop\n\t// this config's Vite dep cache so SSR never executes stale prebundled\n\t// modules\n\tclearStaleDepCache(site.root, cacheDir, (message) => console.log(`\\n${message}`));\n\n\t// A workspace package with dist .torp copies (e.g. @torpor/ui) whose src\n\t// changed without a rebuild serves OLD components to the site, silently;\n\t// report the drift so it can be fixed with a rebuild\n\treportStaleTorpCopies(site.root, (message) => console.log(`\\n${message}`));\n\n\t// Load environment variables from a `.env` file, with defaults if not set\n\tconfigDotenv();\n\n\tprocess.env.PROTOCOL ??= \"http:\";\n\tprocess.env.HOST ??= \"localhost\";\n\tprocess.env.PORT ??= \"7059\";\n\n\t// Honor PORT (env or .env) for the dev server port, matching --preview;\n\t// fall back to the default when it doesn't parse to a number\n\tconst envPort = parseInt(process.env.PORT);\n\tif (!Number.isNaN(envPort)) {\n\t\tconfig.server.port ??= envPort;\n\t}\n\n\tconst connectingUrl = `${process.env.PROTOCOL}//${process.env.HOST}:${process.env.PORT}`;\n\tconsole.log(`\\nConnecting to ${connectingUrl}`);\n\n\tsilenceRollupOptionsDeprecation();\n\n\tconst vite = await createViteServer(config);\n\n\t// Load the SSR entry once before binding the listener: it triggers Vite's\n\t// first dependency optimization, which otherwise settles down (reloading\n\t// the server) right after \"Listening on ...\" -- dropping any request in\n\t// flight at that moment, so clients see an empty reply\n\tawait warmServerEntry(vite, site, sourceMode);\n\n\tawait vite.listen();\n\n\twatchRoutes(site, vite, configVite);\n\n\tconst listeningUrl = vite.resolvedUrls?.local?.[0] ?? connectingUrl;\n\tconsole.log(`Listening on ${listeningUrl}\\n`);\n}\n\n/**\n * Loads the SSR entry so the first dependency optimization (and any\n * optimizer-driven server reload) happens before the listener is bound,\n * rather than on the first real request.\n */\nasync function warmServerEntry(\n\tvite: ViteDevServer,\n\tsite: Site,\n\tsourceMode: boolean,\n): Promise<void> {\n\ttry {\n\t\tconst { serverEntry } = siteEntryPaths(site.root, sourceMode);\n\t\tawait vite.ssrLoadModule(serverEntry);\n\t} catch (e) {\n\t\t// Never block startup over warmup -- the first real request surfaces\n\t\t// errors as before\n\t\tif (process.env.TORPOR_DEBUG_WARMUP) throw e;\n\t}\n}\n\n/**\n * Reports route type issues at startup, then re-checks route files and\n * `makeApi` calls as they change so annotation problems surface during\n * development without failing the dev server.\n *\n * Also watches the config's import graph and the registered route folders,\n * re-loading the site config when route definitions change (edits to\n * `site.config.ts` or a `routes.ts` it imports) or when route files are added\n * or removed. The re-loaded state is swapped onto the live site, the generated\n * manifest invalidated, and a full client reload triggered, so the running\n * server picks up the change without a restart.\n */\nfunction watchRoutes(site: Site, vite: ViteDevServer, configVite?: ViteDevServer): void {\n\treportRouteIssues(checkRoutes(site));\n\treportRouteIssues(checkApiCalls(site));\n\treportRouteIssues(checkLayoutSlots(site));\n\n\t// Map absolute route file paths to their manifest entries, so changed\n\t// files can be re-checked against their derived route. Layout route files\n\t// are included for their slot check (a .torp layout is its own component)\n\tconst buildRouteFiles = (): Map<string, (typeof site.routes)[number]> =>\n\t\tnew Map(\n\t\t\tsite.routes\n\t\t\t\t.filter(\n\t\t\t\t\t(r) => r.file?.endsWith(\".ts\") || (r.file?.endsWith(\".torp\") && r.type === LAYOUT_ROUTE),\n\t\t\t\t)\n\t\t\t\t.map((r) => [path.resolve(site.root, r.file!), r]),\n\t\t);\n\tlet routeFiles = buildRouteFiles();\n\tconst apiCheck = createApiCallCheck(site);\n\t// Only report when a file's issues change, to avoid repeating the same\n\t// warnings on every save\n\tconst reported = new Map<string, string>();\n\n\tconst report = (file: string, issues: RouteCheckIssue[]) => {\n\t\tconst key = JSON.stringify(issues);\n\t\tif (reported.get(file) === key) return;\n\t\treported.set(file, key);\n\t\treportRouteIssues(issues);\n\t};\n\n\tconst recheck = (file: string): void => {\n\t\tconst route = routeFiles.get(file);\n\t\tif (route) {\n\t\t\treport(\n\t\t\t\tfile,\n\t\t\t\troute.type === LAYOUT_ROUTE ? checkLayoutSlot(site, route) : checkRoute(site, route),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (!/\\.(ts|js|torp)$/.test(file)) return;\n\t\tlet source: string;\n\t\ttry {\n\t\t\tsource = readFileSync(file, \"utf8\");\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\treport(file, checkApiCallSource(source, file, apiCheck));\n\t};\n\n\t// Files that affect the route table: the config's import graph (addRoute\n\t// definitions, plugins, inline endpoints) and the route folders (route\n\t// files are read from disk by addRouteFolder, not imported). Recomputed\n\t// after each reload, since the config may start importing new files.\n\t//\n\t// The config and the modules it imports live beside the config file, which\n\t// can sit outside `site.root` once the config reassigns it (e.g. Mallet\n\t// points `site.root` at a subpackage). Reload and watch from that folder,\n\t// not the mutable `site.root`, so a route change doesn't throw\n\t// \"site.config file not found\" and leave the client stale.\n\tconst configFolder = site.configFile ? path.dirname(site.configFile) : site.root;\n\tlet configDeps =\n\t\tconfigVite && site.configFile\n\t\t\t? configDependencyFiles(configVite, configFolder)\n\t\t\t: new Set<string>();\n\tconst inRouteFolder = (file: string): boolean =>\n\t\tsite.routeFolders.some((f) => isInside(path.resolve(site.root, f.folder), file));\n\n\t// Re-load the site config and swap its route state onto the live site.\n\t// Serialized so concurrent add/unlink events (e.g. a folder rename) can't\n\t// interleave, and guarded so a bad config save doesn't crash the server\n\tlet pending = Promise.resolve();\n\tconst reload = (): void => {\n\t\tif (!site.configFile) return;\n\t\tpending = pending\n\t\t\t.then(async () => {\n\t\t\t\t// Load the config on a fresh server rather than re-loading it\n\t\t\t\t// through the one that first read it: doing that from inside\n\t\t\t\t// its own watcher cycle deadlocks\n\t\t\t\tconst { site: fresh, vite: freshVite } = await loadSite(configFolder);\n\t\t\t\ttry {\n\t\t\t\t\tconfigDeps = configDependencyFiles(freshVite, configFolder);\n\t\t\t\t\tif (!site.applyRouteState(fresh)) return;\n\t\t\t\t} finally {\n\t\t\t\t\tawait freshVite.close();\n\t\t\t\t}\n\t\t\t\trouteFiles = buildRouteFiles();\n\t\t\t\treportRouteIssues(checkRoutes(site));\n\t\t\t\treportRouteIssues(checkApiCalls(site));\n\t\t\t\treportRouteIssues(checkLayoutSlots(site));\n\t\t\t\tinvalidateManifest(vite);\n\t\t\t\tvite.ws.send({ type: \"full-reload\", path: \"*\" });\n\t\t\t})\n\t\t\t.catch((e) => console.error(e));\n\t};\n\n\t// Route-file edits are `change` events and are handled by `recheck`/HMR\n\t// (the route path is derived from the filename, so an edit doesn't change\n\t// the route table); only file-set events and config-dependency edits need\n\t// a reload\n\tvite.watcher.on(\"change\", (file) => {\n\t\trecheck(file);\n\t\tif (configDeps.has(file)) reload();\n\t});\n\tvite.watcher.on(\"add\", (file) => {\n\t\trecheck(file);\n\t\tif (configDeps.has(file) || inRouteFolder(file)) reload();\n\t});\n\tconst onRemove = (file: string) => {\n\t\tif (configDeps.has(file) || inRouteFolder(file)) reload();\n\t};\n\tvite.watcher.on(\"unlink\", onRemove);\n\tvite.watcher.on(\"addDir\", onRemove);\n\tvite.watcher.on(\"unlinkDir\", onRemove);\n}\n\nfunction isInside(dir: string, file: string): boolean {\n\tconst rel = path.relative(dir, file);\n\treturn rel === \"\" || (!rel.startsWith(\"..\") && !path.isAbsolute(rel));\n}\n\n/**\n * Invalidates the generated `@torpor/build/manifest` module in every\n * environment, so the server entry re-runs with the rebuilt route table on the\n * next request and the client gets the new manifest on reload.\n */\nfunction invalidateManifest(vite: ViteDevServer): void {\n\tfor (const env of Object.values(vite.environments)) {\n\t\tconst mod = env.moduleGraph.getModuleById(MANIFEST_MODULE_ID);\n\t\tif (mod) env.moduleGraph.invalidateModule(mod);\n\t}\n}\n\nfunction normalizePlugins(plugins: Plugin | Plugin[] | void): Plugin[] {\n\tif (!plugins) return [];\n\treturn Array.isArray(plugins) ? plugins : [plugins];\n}\n\nfunction asAliasArray(alias: AliasOptions | undefined): AliasEntry[] {\n\t// Normalize an existing `resolve.alias` value (array | object | undefined)\n\t// into an array so we can concatenate our tsconfig-derived aliases.\n\tif (!alias) return [];\n\tif (Array.isArray(alias)) return alias;\n\treturn Object.entries(alias).map(([find, replacement]) => ({ find, replacement }));\n}\n\n/**\n * Teaches a dep optimizer how to compile `.torp` files. The optimizer is a\n * rolldown build, so it needs a rolldown-shaped plugin (the vite export) — an\n * esbuild-shaped one is silently ignored. Applied to the root optimizer and\n * to each SSR optimizer, which keeps its own settings.\n */\nfunction addTorpOptimizerSettings(optimizeDeps: NonNullable<UserConfig[\"optimizeDeps\"]>): void {\n\toptimizeDeps.extensions ??= [];\n\tif (!optimizeDeps.extensions.includes(\".torp\")) {\n\t\toptimizeDeps.extensions.push(\".torp\");\n\t}\n\toptimizeDeps.rolldownOptions ??= {};\n\toptimizeDeps.rolldownOptions.plugins ??= [torpor()];\n}\n\n/**\n * Drops Vite's `optimizeDeps.rollupOptions` deprecation warning, which it\n * prints on every dev start (and on internal restarts) even though the config\n * above sets the new key, and nothing ever sets the old one.\n *\n * It's a bug in vite-plus-core's compat proxy, present through 8.3.8000: to\n * migrate `rollupOptions` to `rolldownOptions` it defines `rollupOptions` as an\n * enumerable getter that returns `rolldownOptions`; `resolveDepOptimizationOptions`\n * then merges the config's `optimizeDeps` into the defaults (`for...in` sees the\n * getter, `rolldownOptions` is merged into a *new* object), and the two keys\n * end up pointing at different objects -- which is the warning's condition.\n * It only fires when the config pre-sets `optimizeDeps.rolldownOptions`, as\n * `addTorpOptimizerSettings` must to run the torpor plugin in the dep\n * optimizer, so it's the framework's config that trips it on every app.\n *\n * The message is noise (the optimizer runs on `rolldownOptions`, the torpor\n * plugin included), so it's filtered. A user debugging dep optimization can\n * still see the underlying trace with `VITE_DEPRECATION_TRACE=1`, which goes\n * through `console.trace` and is left alone. Remove this once the proxy stops\n * resurrecting the deprecated key.\n */\nfunction silenceRollupOptionsDeprecation(): void {\n\tconst warn = console.warn;\n\tconsole.warn = (...args: unknown[]) => {\n\t\tif (typeof args[0] === \"string\" && args[0].startsWith(\"`optimizeDeps.rollupOptions`\")) {\n\t\t\treturn;\n\t\t}\n\t\twarn.apply(console, args);\n\t};\n}\n","// From https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types\n\nexport default function contentType(extension: string): string {\n\treturn types[extension] || \"application/octet-stream\";\n}\n\nconst types: Record<string, string> = {\n\t\".aac\": \"audio/aac\",\n\t\".abw\": \"application/x-abiword\",\n\t\".apng\": \"image/apng\",\n\t\".arc\": \"application/x-freearc\",\n\t\".avif\": \"image/avif\",\n\t\".avi\": \"video/x-msvideo\",\n\t\".azw\": \"application/vnd.amazon.ebook\",\n\t\".bin\": \"application/octet-stream\",\n\t\".bmp\": \"image/bmp\",\n\t\".bz\": \"application/x-bzip\",\n\t\".bz2\": \"application/x-bzip2\",\n\t\".cda\": \"application/x-cdf\",\n\t\".csh\": \"application/x-csh\",\n\t\".css\": \"text/css\",\n\t\".csv\": \"text/csv\",\n\t\".doc\": \"application/msword\",\n\t\".docx\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n\t\".eot\": \"application/vnd.ms-fontobject\",\n\t\".epub\": \"application/epub+zip\",\n\t\".gz\": \"application/gzip\",\n\t\".gif\": \"image/gif\",\n\t\".htm\": \"text/html\",\n\t\".html\": \"text/html\",\n\t\".ico\": \"image/vnd.microsoft.icon\",\n\t\".ics\": \"text/calendar\",\n\t\".jar\": \"application/java-archive\",\n\t\".jpeg\": \"image/jpeg\",\n\t\".jpg\": \"image/jpeg\",\n\t\".js\": \"text/javascript\",\n\t\".json\": \"application/json\",\n\t\".jsonld\": \"application/ld+json\",\n\t\".mid\": \"audio/midi\",\n\t\".midi\": \"audio/midi\",\n\t\".mjs\": \"text/javascript\",\n\t\".mp3\": \"audio/mpeg\",\n\t\".mp4\": \"video/mp4\",\n\t\".mpeg\": \"video/mpeg\",\n\t\".mpkg\": \"application/vnd.apple.installer+xml\",\n\t\".odp\": \"application/vnd.oasis.opendocument.presentation\",\n\t\".ods\": \"application/vnd.oasis.opendocument.spreadsheet\",\n\t\".odt\": \"application/vnd.oasis.opendocument.text\",\n\t\".oga\": \"audio/ogg\",\n\t\".ogv\": \"video/ogg\",\n\t\".ogx\": \"application/ogg\",\n\t\".opus\": \"audio/ogg\",\n\t\".otf\": \"font/otf\",\n\t\".png\": \"image/png\",\n\t\".pdf\": \"application/pdf\",\n\t\".php\": \"application/x-httpd-php\",\n\t\".ppt\": \"application/vnd.ms-powerpoint\",\n\t\".pptx\": \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n\t\".rar\": \"application/vnd.rar\",\n\t\".rtf\": \"application/rtf\",\n\t\".sh\": \"application/x-sh\",\n\t\".svg\": \"image/svg+xml\",\n\t\".tar\": \"application/x-tar\",\n\t\".tif\": \"image/tiff\",\n\t\".tiff\": \"image/tiff\",\n\t\".ts\": \"video/mp2t\",\n\t\".ttf\": \"font/ttf\",\n\t\".txt\": \"text/plain\",\n\t\".vsd\": \"application/vnd.visio\",\n\t\".wav\": \"audio/wav\",\n\t\".weba\": \"audio/webm\",\n\t\".webm\": \"video/webm\",\n\t\".webp\": \"image/webp\",\n\t\".woff\": \"font/woff\",\n\t\".woff2\": \"font/woff2\",\n\t\".xhtml\": \"application/xhtml+xml\",\n\t\".xls\": \"application/vnd.ms-excel\",\n\t\".xlsx\": \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n\t\".xml\": \"application/xml\",\n\t\".xul\": \"application/vnd.mozilla.xul+xml\",\n\t\".zip\": \"application/zip\",\n\t\".3gp\": \"video/3gpp\",\n\t\".3g2\": \"video/3gpp2\",\n\t\".7z\": \"application/x-7z-compressed\",\n};\n","import path from \"node:path\";\nimport contentType from \"../server/contentType.ts\";\n\n/**\n * The cache policy for content-hashed build assets. Their names change\n * whenever their content does, so browsers and CDNs can keep them for a year\n * without revalidating; a new deploy references new names.\n */\nexport const IMMUTABLE_CACHE_CONTROL = \"public, max-age=31536000, immutable\";\n\n/**\n * Whether a file in `assets/` has a Vite content hash in its name (e.g.\n * `clientEntry-BUKMQ_H9.js`). Files a site's `src/public/assets` folder put\n * there keep their own names, so they're not hashed and must not be cached\n * forever.\n */\nexport function isHashedAsset(file: string): boolean {\n\treturn /-[A-Za-z0-9_-]{8}\\.[A-Za-z0-9]+$/.test(path.basename(file));\n}\n\n/** The response headers for a file served from `dist/client/assets`. */\nexport function assetHeaders(file: string): Record<string, string> {\n\tconst headers: Record<string, string> = { \"Content-Type\": contentType(path.extname(file)) };\n\tif (isHashedAsset(file)) {\n\t\theaders[\"Cache-Control\"] = IMMUTABLE_CACHE_CONTROL;\n\t}\n\treturn headers;\n}\n","import { configDotenv } from \"dotenv\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport { normalizeBasePath } from \"../site/basePath.ts\";\nimport Site from \"../site/Site\";\nimport { assetHeaders } from \"./assetHeaders.ts\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\nimport runBuild from \"./runBuild\";\n\nexport default async function runPreview(site: Site): Promise<void> {\n\t// Build the site\n\tawait runBuild(site);\n\n\tconst distFolder = site.outputFolder;\n\tconst clientFolder = path.join(distFolder, \"client\");\n\tconst serverFolder = path.join(distFolder, \"server\");\n\n\t// Read site.html if present, and find the client script file in /assets.\n\t// An endpoints-only site has no site.html, and no template is needed\n\tlet template: string | undefined;\n\tconst siteHtml = path.join(clientFolder, \"site.html\");\n\tif (existsSync(siteHtml)) {\n\t\tlet clientScript = (await fs.readdir(path.join(clientFolder, \"assets\"))).find((f) =>\n\t\t\tf.startsWith(\"clientEntry-\"),\n\t\t);\n\t\tif (!clientScript) {\n\t\t\tthrow new Error(\"clientEntry.js not found\");\n\t\t}\n\t\tclientScript = `/assets/${clientScript}`;\n\n\t\ttemplate = await fs.readFile(siteHtml, \"utf-8\");\n\n\t\t// Prepare site.html so that we can just splice components into it\n\t\ttemplate = prepareTemplate(template, clientScript);\n\t}\n\n\t// Configure the server\n\tconst server = new Server();\n\n\t// Serve dist/client/assets statically, under the site's base path (the\n\t// URLs rendered pages and the client use). Hashed files are cached for a\n\t// year, since a deploy that changes one gives it a new name\n\tconst base = normalizeBasePath(site.basePath);\n\tserver.add(`${base}/assets/*`, async (ev) => {\n\t\ttry {\n\t\t\tconst url = new URL(ev.request.url);\n\t\t\tconst file = path.join(clientFolder, url.pathname.slice(base.length));\n\t\t\tif (existsSync(file)) {\n\t\t\t\tconst body = await fs.readFile(file);\n\t\t\t\treturn new Response(body, { status: 200, headers: assetHeaders(file) });\n\t\t\t}\n\t\t} catch (e: any) {\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tconst serverScript = path.resolve(serverFolder, \"serverEntry.js\");\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry\n\t\t\tconst { load } = await import(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Load environment variables from a `.env` file, with defaults if not set\n\tconfigDotenv();\n\n\tprocess.env.PROTOCOL ??= \"http:\";\n\tprocess.env.HOST ??= \"localhost\";\n\tprocess.env.PORT ??= \"7059\";\n\n\t// Serve the site\n\tawait site.adapter.serve(server, site);\n}\n","import runBuild from \"./runBuild\";\nimport runDev from \"./runDev\";\nimport { loadSite } from \"./loadSite\";\nimport runPreview from \"./runPreview\";\n\nexport { loadSite };\n\nexport default async function run(\n\tfolder: string,\n\tmode: \"dev\" | \"build\" | \"preview\",\n): Promise<void> {\n\tconst { site, vite } = await loadSite(folder);\n\ttry {\n\t\tswitch (mode) {\n\t\t\tcase \"dev\": {\n\t\t\t\t// The config Vite server is passed along so the dev server can\n\t\t\t\t// watch the config's import graph and re-load it when route\n\t\t\t\t// definitions (e.g. a routes.ts) change\n\t\t\t\tawait runDev(site, vite);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"build\": {\n\t\t\t\tawait runBuild(site);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"preview\": {\n\t\t\t\tawait runPreview(site);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconsole.log(\"No mode passed, running in dev\");\n\t\t\t\tawait runDev(site, vite);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tawait vite.close();\n\t}\n}\n","import { writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { ViteDevServer } from \"vite\";\nimport buildOpenApiDocument from \"../openapi/document\";\nimport { OPEN_API_STATE_KEY } from \"../openapi/plugin\";\nimport type { OpenApiEndPoint, OpenApiRouteEntry, ResolvedOpenApiOptions } from \"../openapi/types\";\nimport type Site from \"../site/Site\";\nimport { SERVER_ROUTE } from \"../types/RouteType\";\n\n/**\n * Writes an OpenAPI document for the site's +server endpoints to a file.\n * Route files are loaded through the supplied Vite server, so this must be\n * called while the server from `loadSite` is still open.\n */\nexport default async function runOpenApi(\n\tsite: Site,\n\tvite: ViteDevServer,\n\toutFile = \"openapi.json\",\n): Promise<void> {\n\tconst options = site.pluginState.get(OPEN_API_STATE_KEY) as ResolvedOpenApiOptions | undefined;\n\tif (!options) {\n\t\tthrow new Error(\n\t\t\t'No OpenAPI options found. Add the openApi() plugin to site.plugins to use \"tb --openapi\"',\n\t\t);\n\t}\n\n\tconst entries: OpenApiRouteEntry[] = [];\n\tfor (const route of site.routes) {\n\t\tif (route.type !== SERVER_ROUTE) {\n\t\t\tcontinue;\n\t\t}\n\t\t// Don't document the docs page itself\n\t\tif (options.docs && route.path === options.docs) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (route.endPoint && !route.file) {\n\t\t\t// Inline endpoint\n\t\t\tentries.push({ path: route.path, endPoint: route.endPoint as OpenApiEndPoint });\n\t\t} else if (route.file) {\n\t\t\tconst file = path.resolve(site.root, route.file);\n\t\t\tconst mod = await vite.ssrLoadModule(file);\n\t\t\tentries.push({ path: route.path, endPoint: mod.default });\n\t\t}\n\t}\n\n\tconst doc = buildOpenApiDocument(entries, options);\n\tawait writeFile(path.resolve(site.root, outFile), JSON.stringify(doc, null, 2) + \"\\n\");\n\n\tif (options.extend) {\n\t\tconsole.log(\n\t\t\t'Note: the openApi() \"extend\" hook runs per request, so the written document is the base document',\n\t\t);\n\t}\n\tconsole.log(\n\t\t`OpenAPI document written to ${outFile} (${Object.keys(doc.paths ?? {}).length} paths)`,\n\t);\n}\n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AAI,QAAQ,QACX,QAAQ,IACP,oGACD;CAED,QAAQ,IACP,+BAA+B,QAAQ,IAAI,OAAO,KAAK,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC,OAAO,QAChF;AACD"}
@@ -1,2 +1,2 @@
1
- import { t as Server } from "../Server-qn5Ws_d0.mjs";
1
+ import { t as Server } from "../Server-ClwvuilS.mjs";
2
2
  export { Server as default };
@@ -1 +1 @@
1
- export { t as default } from "../Server-dcRbdPXf.mjs";
1
+ export { t as default } from "../Server-BCijhgZp.mjs";
package/dist/server.d.mts CHANGED
@@ -1,9 +1,33 @@
1
- import { i as CookieHelper, n as HeaderHelper } from "./SessionHelper-MaodMaLU.mjs";
2
- import { n as ServerEvent, t as MiddlewareFunction } from "./MiddlewareFunction-BZilnEei.mjs";
3
- import { t as Server } from "./Server-qn5Ws_d0.mjs";
4
- import { r as ServerLoadEvent } from "./ServerLoadEvent-BH6oG1o6.mjs";
5
- import { t as ServerHook } from "./ServerHook-W111nEhe.mjs";
1
+ import { a as CookieHelper, r as HeaderHelper, t as CacheOptions } from "./CacheOptions-C4-ebVt9.mjs";
2
+ import { n as ServerEvent, t as MiddlewareFunction } from "./MiddlewareFunction-DMYxjzF4.mjs";
3
+ import { t as Server } from "./Server-ClwvuilS.mjs";
4
+ import { r as ServerLoadEvent } from "./ServerLoadEvent-CpcgsKCU.mjs";
5
+ import { t as ServerHook } from "./ServerHook-DY-NSG6n.mjs";
6
6
  import { IncomingMessage, ServerResponse } from "node:http";
7
+ //#region src/server/dedupe.d.ts
8
+ /**
9
+ * Wraps a function so that it runs once per request for each set of
10
+ * arguments: the root layout and the page can both call `getUser(event, id)`
11
+ * and only hit the database once. Nothing is kept between requests, so the
12
+ * data is never stale.
13
+ *
14
+ * ```ts
15
+ * const getUser = dedupe((event, id: string) => db.users.find(id));
16
+ *
17
+ * // In any load, hook or action of the same request
18
+ * const user = await getUser(event, id);
19
+ * ```
20
+ *
21
+ * Arguments are compared by their JSON. A call that throws (or returns a
22
+ * promise that rejects) isn't kept, so a later call can retry.
23
+ *
24
+ * @param fn The function to wrap. Its first argument is the event of the
25
+ * request (anything with a `request`), followed by its own arguments
26
+ */
27
+ declare function dedupe<E extends {
28
+ request: Request;
29
+ }, A extends unknown[], R>(fn: (event: E, ...args: A) => R): (event: E, ...args: A) => R;
30
+ //#endregion
7
31
  //#region src/server/invokeHook.d.ts
8
32
  /**
9
33
  * Invokes a server hook's `enter` function and returns its `Response`, so
@@ -33,5 +57,5 @@ type NextFunction = (err?: unknown) => void;
33
57
  type ConnectMiddleware<PlatformRequest extends IncomingMessage = IncomingMessage, PlatformResponse extends ServerResponse = ServerResponse> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => void | Promise<void>;
34
58
  type ConnectMiddlewareBoolean<PlatformRequest extends IncomingMessage = IncomingMessage, PlatformResponse extends ServerResponse = ServerResponse> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => boolean | Promise<boolean>;
35
59
  //#endregion
36
- export { CookieHelper, HeaderHelper, Server, ServerEvent, connectMiddleware, invokeHook };
60
+ export { type CacheOptions, CookieHelper, HeaderHelper, Server, ServerEvent, connectMiddleware, dedupe, invokeHook };
37
61
  //# sourceMappingURL=server.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server/invokeHook.ts","../src/server/connect/connectMiddleware.ts"],"mappings":";;;;;;;;;;;;;;;;;iBAa8B,WAAW,8CACxC,MAAM,WAAW,QACjB,OAAO,gBAAgB,SACrB,QAAQ;;;;;;;;;;;;;iBCGa,kBACvB,SAAS,oBAAoB,2BAC3B;KAuDE,gBAAgB;KAChB,kBACJ,wBAAwB,kBAAkB,iBAC1C,yBAAyB,iBAAiB,mBACtC,KAAK,iBAAiB,KAAK,kBAAkB,MAAM,wBAAwB;KAC3E,yBACJ,wBAAwB,kBAAkB,iBAC1C,yBAAyB,iBAAiB,mBACtC,KAAK,iBAAiB,KAAK,kBAAkB,MAAM,2BAA2B"}
1
+ {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server/dedupe.ts","../src/server/invokeHook.ts","../src/server/connect/connectMiddleware.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;iBAwBwB,OAAO;EAAY,SAAS;GAAW,qBAAqB,GACnF,KAAK,OAAO,MAAM,MAAM,MAAM,KAC3B,OAAO,MAAM,MAAM,MAAM;;;;;;;;;;;;;iBCbC,WAAW,8CACxC,MAAM,WAAW,QACjB,OAAO,gBAAgB,SACrB,QAAQ;;;;;;;;;;;;;iBCGa,kBACvB,SAAS,oBAAoB,2BAC3B;KAuDE,gBAAgB;KAChB,kBACJ,wBAAwB,kBAAkB,iBAC1C,yBAAyB,iBAAiB,mBACtC,KAAK,iBAAiB,KAAK,kBAAkB,MAAM,wBAAwB;KAC3E,yBACJ,wBAAwB,kBAAkB,iBAC1C,yBAAyB,iBAAiB,mBACtC,KAAK,iBAAiB,KAAK,kBAAkB,MAAM,2BAA2B"}
package/dist/server.mjs CHANGED
@@ -1,8 +1,52 @@
1
- import { n as HeaderHelper, r as CookieHelper, t as ServerEvent } from "./ServerEvent-BY4f3RVF.mjs";
2
- import { t as Server } from "./Server-dcRbdPXf.mjs";
1
+ import { n as HeaderHelper, r as CookieHelper, t as ServerEvent } from "./ServerEvent-BBRkd4Ya.mjs";
2
+ import { t as Server } from "./Server-BCijhgZp.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";
6
+ //#region src/server/dedupe.ts
7
+ const results = /* @__PURE__ */ new WeakMap();
8
+ /**
9
+ * Wraps a function so that it runs once per request for each set of
10
+ * arguments: the root layout and the page can both call `getUser(event, id)`
11
+ * and only hit the database once. Nothing is kept between requests, so the
12
+ * data is never stale.
13
+ *
14
+ * ```ts
15
+ * const getUser = dedupe((event, id: string) => db.users.find(id));
16
+ *
17
+ * // In any load, hook or action of the same request
18
+ * const user = await getUser(event, id);
19
+ * ```
20
+ *
21
+ * Arguments are compared by their JSON. A call that throws (or returns a
22
+ * promise that rejects) isn't kept, so a later call can retry.
23
+ *
24
+ * @param fn The function to wrap. Its first argument is the event of the
25
+ * request (anything with a `request`), followed by its own arguments
26
+ */
27
+ function dedupe(fn) {
28
+ return (event, ...args) => {
29
+ let calls = results.get(event.request);
30
+ if (!calls) {
31
+ calls = /* @__PURE__ */ new Map();
32
+ results.set(event.request, calls);
33
+ }
34
+ let byArgs = calls.get(fn);
35
+ if (!byArgs) {
36
+ byArgs = /* @__PURE__ */ new Map();
37
+ calls.set(fn, byArgs);
38
+ }
39
+ const key = JSON.stringify(args);
40
+ if (byArgs.has(key)) return byArgs.get(key);
41
+ const result = fn(event, ...args);
42
+ byArgs.set(key, result);
43
+ if (result instanceof Promise) result.catch(() => {
44
+ if (byArgs.get(key) === result) byArgs.delete(key);
45
+ });
46
+ return result;
47
+ };
48
+ }
49
+ //#endregion
6
50
  //#region src/server/invokeHook.ts
7
51
  /**
8
52
  * Invokes a server hook's `enter` function and returns its `Response`, so
@@ -144,6 +188,6 @@ const statusCodesWithoutBody = [
144
188
  304
145
189
  ];
146
190
  //#endregion
147
- export { CookieHelper, HeaderHelper, Server, ServerEvent, connectMiddleware, invokeHook };
191
+ export { CookieHelper, HeaderHelper, Server, ServerEvent, connectMiddleware, dedupe, invokeHook };
148
192
 
149
193
  //# sourceMappingURL=server.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":[],"sources":["../src/server/invokeHook.ts","../src/server/connect/nodeMessageToNodeResponse.ts","../src/server/connect/requestToNodeMessage.ts","../src/server/connect/connectMiddleware.ts"],"sourcesContent":["import type ServerHook from \"../types/ServerHook\";\nimport type ServerLoadEvent from \"../types/ServerLoadEvent\";\n\n/**\n * Invokes a server hook's `enter` function and returns its `Response`, so\n * in-process callers can short-circuit when the hook returns one (a redirect\n * for unauthenticated users, etc).\n *\n * This exists because a hook declared with\n * `export default { ... } satisfies ServerHook<\"/api\">` keeps the\n * implementation's inferred return type -- usually `void` -- so calling\n * `hook.enter(event)` directly doesn't type the result as `Response | void`.\n */\nexport default async function invokeHook<Route extends string | undefined = undefined>(\n\thook: ServerHook<Route>,\n\tevent: ServerLoadEvent<Route>,\n): Promise<Response | undefined> {\n\treturn (await hook.enter?.(event)) ?? undefined;\n}\n","import {\n\ttype IncomingMessage,\n\ttype OutgoingHttpHeader,\n\ttype OutgoingHttpHeaders,\n\tServerResponse,\n} from \"node:http\";\nimport { PassThrough, Readable } from \"node:stream\";\n\n// From https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/createServerResponse.ts\n\n/**\n * Creates a custom ServerResponse object that allows for intercepting and\n * streaming the response.\n *\n * @param incomingMessage The incoming HTTP request message.\n * @returns An object containing the custom ServerResponse and a function that\n * takes a callback to invoke when the response is readable, providing an object\n * with the readable stream, headers and status code.\n */\nexport default function nodeMessageToNodeResponse(\n\tincomingMessage: IncomingMessage,\n): ServerResponseResponse {\n\tconst res = new ServerResponse(incomingMessage);\n\tconst passThrough = new PassThrough();\n\tlet handled = false;\n\n\tconst onReadable = (\n\t\tcb: (result: { readable: Readable; headers: OutgoingHttpHeaders; status: number }) => void,\n\t) => {\n\t\tconst handleReadable = () => {\n\t\t\tif (handled) return;\n\t\t\thandled = true;\n\t\t\tcb({\n\t\t\t\treadable: Readable.from(passThrough),\n\t\t\t\theaders: res.getHeaders(),\n\t\t\t\tstatus: res.statusCode,\n\t\t\t});\n\t\t};\n\n\t\tpassThrough.once(\"readable\", handleReadable);\n\t\tpassThrough.once(\"end\", handleReadable);\n\t};\n\n\tpassThrough.once(\"finish\", () => {\n\t\tres.emit(\"finish\");\n\t});\n\tpassThrough.once(\"close\", () => {\n\t\tres.destroy();\n\t\tres.emit(\"close\");\n\t});\n\tpassThrough.on(\"drain\", () => {\n\t\tres.emit(\"drain\");\n\t});\n\n\tres.write = passThrough.write.bind(passThrough);\n\tres.end = passThrough.end.bind(passThrough) as any;\n\n\tres.writeHead = function writeHead(\n\t\tstatusCode: number,\n\t\tstatusMessage?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\theaders?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t): ServerResponse {\n\t\tres.statusCode = statusCode;\n\t\tif (typeof statusMessage === \"object\") {\n\t\t\theaders = statusMessage;\n\t\t\tstatusMessage = undefined;\n\t\t}\n\t\tif (headers) {\n\t\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\t\tif (value !== undefined) {\n\t\t\t\t\tres.setHeader(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t};\n\n\treturn {\n\t\tres,\n\t\tonReadable,\n\t};\n}\n\ninterface ServerResponseResponse {\n\tres: ServerResponse;\n\tonReadable: (\n\t\tcb: (result: { readable: Readable; headers: OutgoingHttpHeaders; status: number }) => void,\n\t) => void;\n}\n","import { type IncomingMessage } from \"node:http\";\nimport { Readable } from \"node:stream\";\n\n// From https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/connectToWeb.ts\n\nconst DUMMY_BASE_URL = \"http://localhost\";\n\n/**\n * Creates an IncomingMessage object from a web Request.\n *\n * The request body is intentionally not forwarded: this is only used to wrap\n * Connect-style middlewares (e.g. Vite's dev middleware), which don't read\n * the body. The actual route handler later reads `ev.request.body` directly,\n * and forwarding the body here would consume it and break the handler.\n *\n * @param {Request} request - The web Request object.\n * @returns {IncomingMessage} An IncomingMessage-like object compatible with Node.js HTTP module.\n */\nexport default function requestToNodeMessage(request: Request): IncomingMessage {\n\tconst parsedUrl = new URL(request.url, DUMMY_BASE_URL);\n\tconst pathAndQuery = (parsedUrl.pathname || \"\") + (parsedUrl.search || \"\");\n\tconst body = Readable.from([]);\n\n\treturn Object.assign(body, {\n\t\turl: pathAndQuery,\n\t\tmethod: request.method,\n\t\theaders: Object.fromEntries(request.headers),\n\t}) as IncomingMessage;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport type MiddlewareFunction from \"../types/MiddlewareFunction\";\nimport flattenHeaders from \"./flattenHeaders\";\nimport nodeMessageToNodeResponse from \"./nodeMessageToNodeResponse\";\nimport requestToNodeMessage from \"./requestToNodeMessage\";\n\n// From https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/connectToWeb.ts\n\n/**\n * Converts a Connect-style middleware to a torpor middleware.\n *\n * If the Connect handler writes a response, it is returned from the `enter`\n * hook and the middleware chain is short-circuited. If the handler calls\n * `next()`, the rest of the chain runs after this middleware completes.\n *\n * @param handler - The Connect-style middleware function to be converted.\n * @returns A middleware whose `enter` hook handles the web request.\n */\nexport default function connectMiddleware(\n\thandler: ConnectMiddleware | ConnectMiddlewareBoolean,\n): MiddlewareFunction {\n\treturn {\n\t\tenter: (ev) =>\n\t\t\tnew Promise<Response | void>((resolve, reject) => {\n\t\t\t\tconst req = requestToNodeMessage(ev.request);\n\t\t\t\tconst { res, onReadable } = nodeMessageToNodeResponse(req);\n\n\t\t\t\tonReadable(({ readable, headers, status }) => {\n\t\t\t\t\tconst responseBody: ReadableStream | null = statusCodesWithoutBody.includes(status)\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: (Readable.toWeb(readable) as unknown as ReadableStream);\n\t\t\t\t\tresolve(\n\t\t\t\t\t\tnew Response(responseBody, {\n\t\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t\theaders: flattenHeaders(headers),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t});\n\n\t\t\t\tconst cnext = (error?: unknown) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\t// eslint-disable-next-line no-base-to-string\n\t\t\t\t\t\treject(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// The Connect handler is passing the request on\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tPromise.resolve(handler(req, res, cnext))\n\t\t\t\t\t.then((handled) => {\n\t\t\t\t\t\tif (handled === false) {\n\t\t\t\t\t\t\tres.destroy();\n\t\t\t\t\t\t\t// Returning false signals that the request was handled,\n\t\t\t\t\t\t\t// so return an empty response to stop the chain\n\t\t\t\t\t\t\tresolve(new Response(null, { status: 200 }));\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.catch((e: unknown) => {\n\t\t\t\t\t\tcnext(e);\n\t\t\t\t\t});\n\t\t\t}),\n\t};\n}\n\nconst statusCodesWithoutBody = [\n\t100, // Continue\n\t101, // Switching Protocols\n\t102, // Processing (WebDAV)\n\t103, // Early Hints\n\t204, // No Content\n\t205, // Reset Content\n\t304, // Not Modified\n];\n\ntype NextFunction = (err?: unknown) => void;\ntype ConnectMiddleware<\n\tPlatformRequest extends IncomingMessage = IncomingMessage,\n\tPlatformResponse extends ServerResponse = ServerResponse,\n> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => void | Promise<void>;\ntype ConnectMiddlewareBoolean<\n\tPlatformRequest extends IncomingMessage = IncomingMessage,\n\tPlatformResponse extends ServerResponse = ServerResponse,\n> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => boolean | Promise<boolean>;\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,eAA8B,WAC7B,MACA,OACgC;CAChC,OAAQ,MAAM,KAAK,QAAQ,KAAK,KAAM,KAAA;AACvC;;;;;;;;;;;;ACCA,SAAwB,0BACvB,iBACyB;CACzB,MAAM,MAAM,IAAI,eAAe,eAAe;CAC9C,MAAM,cAAc,IAAI,YAAY;CACpC,IAAI,UAAU;CAEd,MAAM,cACL,OACI;EACJ,MAAM,uBAAuB;GAC5B,IAAI,SAAS;GACb,UAAU;GACV,GAAG;IACF,UAAU,SAAS,KAAK,WAAW;IACnC,SAAS,IAAI,WAAW;IACxB,QAAQ,IAAI;GACb,CAAC;EACF;EAEA,YAAY,KAAK,YAAY,cAAc;EAC3C,YAAY,KAAK,OAAO,cAAc;CACvC;CAEA,YAAY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;IAC1B;IACA,SAAS,eAAe,OAAO;GAChC,CAAC,CACF;EACD,CAAC;EAED,MAAM,SAAS,UAAoB;GAClC,IAAI,OAEH,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;QAGhE,QAAQ;EAEV;EAEA,QAAQ,QAAQ,QAAQ,KAAK,KAAK,KAAK,CAAC,CAAC,CACvC,MAAM,YAAY;GAClB,IAAI,YAAY,OAAO;IACtB,IAAI,QAAQ;IAGZ,QAAQ,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC,CAAC;GAC5C;EACD,CAAC,CAAC,CACD,OAAO,MAAe;GACtB,MAAM,CAAC;EACR,CAAC;CACH,CAAC,EACH;AACD;AAEA,MAAM,yBAAyB;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;AACD"}
1
+ {"version":3,"file":"server.mjs","names":[],"sources":["../src/server/dedupe.ts","../src/server/invokeHook.ts","../src/server/connect/nodeMessageToNodeResponse.ts","../src/server/connect/requestToNodeMessage.ts","../src/server/connect/connectMiddleware.ts"],"sourcesContent":["// The results of each request's deduped calls, keyed by the request so that\n// they go when the request does. Loads, hooks and middleware all see the same\n// Request object, whichever event they get\nconst results = new WeakMap<Request, Map<Function, Map<string, unknown>>>();\n\n/**\n * Wraps a function so that it runs once per request for each set of\n * arguments: the root layout and the page can both call `getUser(event, id)`\n * and only hit the database once. Nothing is kept between requests, so the\n * data is never stale.\n *\n * ```ts\n * const getUser = dedupe((event, id: string) => db.users.find(id));\n *\n * // In any load, hook or action of the same request\n * const user = await getUser(event, id);\n * ```\n *\n * Arguments are compared by their JSON. A call that throws (or returns a\n * promise that rejects) isn't kept, so a later call can retry.\n *\n * @param fn The function to wrap. Its first argument is the event of the\n * request (anything with a `request`), followed by its own arguments\n */\nexport default function dedupe<E extends { request: Request }, A extends unknown[], R>(\n\tfn: (event: E, ...args: A) => R,\n): (event: E, ...args: A) => R {\n\treturn (event: E, ...args: A): R => {\n\t\tlet calls = results.get(event.request);\n\t\tif (!calls) {\n\t\t\tcalls = new Map();\n\t\t\tresults.set(event.request, calls);\n\t\t}\n\t\tlet byArgs = calls.get(fn);\n\t\tif (!byArgs) {\n\t\t\tbyArgs = new Map();\n\t\t\tcalls.set(fn, byArgs);\n\t\t}\n\t\tconst key = JSON.stringify(args);\n\t\tif (byArgs.has(key)) {\n\t\t\treturn byArgs.get(key) as R;\n\t\t}\n\t\tconst result = fn(event, ...args);\n\t\tbyArgs.set(key, result);\n\t\tif (result instanceof Promise) {\n\t\t\tresult.catch(() => {\n\t\t\t\tif (byArgs.get(key) === result) byArgs.delete(key);\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t};\n}\n","import type ServerHook from \"../types/ServerHook\";\nimport type ServerLoadEvent from \"../types/ServerLoadEvent\";\n\n/**\n * Invokes a server hook's `enter` function and returns its `Response`, so\n * in-process callers can short-circuit when the hook returns one (a redirect\n * for unauthenticated users, etc).\n *\n * This exists because a hook declared with\n * `export default { ... } satisfies ServerHook<\"/api\">` keeps the\n * implementation's inferred return type -- usually `void` -- so calling\n * `hook.enter(event)` directly doesn't type the result as `Response | void`.\n */\nexport default async function invokeHook<Route extends string | undefined = undefined>(\n\thook: ServerHook<Route>,\n\tevent: ServerLoadEvent<Route>,\n): Promise<Response | undefined> {\n\treturn (await hook.enter?.(event)) ?? undefined;\n}\n","import {\n\ttype IncomingMessage,\n\ttype OutgoingHttpHeader,\n\ttype OutgoingHttpHeaders,\n\tServerResponse,\n} from \"node:http\";\nimport { PassThrough, Readable } from \"node:stream\";\n\n// From https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/createServerResponse.ts\n\n/**\n * Creates a custom ServerResponse object that allows for intercepting and\n * streaming the response.\n *\n * @param incomingMessage The incoming HTTP request message.\n * @returns An object containing the custom ServerResponse and a function that\n * takes a callback to invoke when the response is readable, providing an object\n * with the readable stream, headers and status code.\n */\nexport default function nodeMessageToNodeResponse(\n\tincomingMessage: IncomingMessage,\n): ServerResponseResponse {\n\tconst res = new ServerResponse(incomingMessage);\n\tconst passThrough = new PassThrough();\n\tlet handled = false;\n\n\tconst onReadable = (\n\t\tcb: (result: { readable: Readable; headers: OutgoingHttpHeaders; status: number }) => void,\n\t) => {\n\t\tconst handleReadable = () => {\n\t\t\tif (handled) return;\n\t\t\thandled = true;\n\t\t\tcb({\n\t\t\t\treadable: Readable.from(passThrough),\n\t\t\t\theaders: res.getHeaders(),\n\t\t\t\tstatus: res.statusCode,\n\t\t\t});\n\t\t};\n\n\t\tpassThrough.once(\"readable\", handleReadable);\n\t\tpassThrough.once(\"end\", handleReadable);\n\t};\n\n\tpassThrough.once(\"finish\", () => {\n\t\tres.emit(\"finish\");\n\t});\n\tpassThrough.once(\"close\", () => {\n\t\tres.destroy();\n\t\tres.emit(\"close\");\n\t});\n\tpassThrough.on(\"drain\", () => {\n\t\tres.emit(\"drain\");\n\t});\n\n\tres.write = passThrough.write.bind(passThrough);\n\tres.end = passThrough.end.bind(passThrough) as any;\n\n\tres.writeHead = function writeHead(\n\t\tstatusCode: number,\n\t\tstatusMessage?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\theaders?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t): ServerResponse {\n\t\tres.statusCode = statusCode;\n\t\tif (typeof statusMessage === \"object\") {\n\t\t\theaders = statusMessage;\n\t\t\tstatusMessage = undefined;\n\t\t}\n\t\tif (headers) {\n\t\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\t\tif (value !== undefined) {\n\t\t\t\t\tres.setHeader(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t};\n\n\treturn {\n\t\tres,\n\t\tonReadable,\n\t};\n}\n\ninterface ServerResponseResponse {\n\tres: ServerResponse;\n\tonReadable: (\n\t\tcb: (result: { readable: Readable; headers: OutgoingHttpHeaders; status: number }) => void,\n\t) => void;\n}\n","import { type IncomingMessage } from \"node:http\";\nimport { Readable } from \"node:stream\";\n\n// From https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/connectToWeb.ts\n\nconst DUMMY_BASE_URL = \"http://localhost\";\n\n/**\n * Creates an IncomingMessage object from a web Request.\n *\n * The request body is intentionally not forwarded: this is only used to wrap\n * Connect-style middlewares (e.g. Vite's dev middleware), which don't read\n * the body. The actual route handler later reads `ev.request.body` directly,\n * and forwarding the body here would consume it and break the handler.\n *\n * @param {Request} request - The web Request object.\n * @returns {IncomingMessage} An IncomingMessage-like object compatible with Node.js HTTP module.\n */\nexport default function requestToNodeMessage(request: Request): IncomingMessage {\n\tconst parsedUrl = new URL(request.url, DUMMY_BASE_URL);\n\tconst pathAndQuery = (parsedUrl.pathname || \"\") + (parsedUrl.search || \"\");\n\tconst body = Readable.from([]);\n\n\treturn Object.assign(body, {\n\t\turl: pathAndQuery,\n\t\tmethod: request.method,\n\t\theaders: Object.fromEntries(request.headers),\n\t}) as IncomingMessage;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport type MiddlewareFunction from \"../types/MiddlewareFunction\";\nimport flattenHeaders from \"./flattenHeaders\";\nimport nodeMessageToNodeResponse from \"./nodeMessageToNodeResponse\";\nimport requestToNodeMessage from \"./requestToNodeMessage\";\n\n// From https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/connectToWeb.ts\n\n/**\n * Converts a Connect-style middleware to a torpor middleware.\n *\n * If the Connect handler writes a response, it is returned from the `enter`\n * hook and the middleware chain is short-circuited. If the handler calls\n * `next()`, the rest of the chain runs after this middleware completes.\n *\n * @param handler - The Connect-style middleware function to be converted.\n * @returns A middleware whose `enter` hook handles the web request.\n */\nexport default function connectMiddleware(\n\thandler: ConnectMiddleware | ConnectMiddlewareBoolean,\n): MiddlewareFunction {\n\treturn {\n\t\tenter: (ev) =>\n\t\t\tnew Promise<Response | void>((resolve, reject) => {\n\t\t\t\tconst req = requestToNodeMessage(ev.request);\n\t\t\t\tconst { res, onReadable } = nodeMessageToNodeResponse(req);\n\n\t\t\t\tonReadable(({ readable, headers, status }) => {\n\t\t\t\t\tconst responseBody: ReadableStream | null = statusCodesWithoutBody.includes(status)\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: (Readable.toWeb(readable) as unknown as ReadableStream);\n\t\t\t\t\tresolve(\n\t\t\t\t\t\tnew Response(responseBody, {\n\t\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t\theaders: flattenHeaders(headers),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t});\n\n\t\t\t\tconst cnext = (error?: unknown) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\t// eslint-disable-next-line no-base-to-string\n\t\t\t\t\t\treject(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// The Connect handler is passing the request on\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tPromise.resolve(handler(req, res, cnext))\n\t\t\t\t\t.then((handled) => {\n\t\t\t\t\t\tif (handled === false) {\n\t\t\t\t\t\t\tres.destroy();\n\t\t\t\t\t\t\t// Returning false signals that the request was handled,\n\t\t\t\t\t\t\t// so return an empty response to stop the chain\n\t\t\t\t\t\t\tresolve(new Response(null, { status: 200 }));\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.catch((e: unknown) => {\n\t\t\t\t\t\tcnext(e);\n\t\t\t\t\t});\n\t\t\t}),\n\t};\n}\n\nconst statusCodesWithoutBody = [\n\t100, // Continue\n\t101, // Switching Protocols\n\t102, // Processing (WebDAV)\n\t103, // Early Hints\n\t204, // No Content\n\t205, // Reset Content\n\t304, // Not Modified\n];\n\ntype NextFunction = (err?: unknown) => void;\ntype ConnectMiddleware<\n\tPlatformRequest extends IncomingMessage = IncomingMessage,\n\tPlatformResponse extends ServerResponse = ServerResponse,\n> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => void | Promise<void>;\ntype ConnectMiddlewareBoolean<\n\tPlatformRequest extends IncomingMessage = IncomingMessage,\n\tPlatformResponse extends ServerResponse = ServerResponse,\n> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => boolean | Promise<boolean>;\n"],"mappings":";;;;;;AAGA,MAAM,0BAAU,IAAI,QAAsD;;;;;;;;;;;;;;;;;;;;AAqB1E,SAAwB,OACvB,IAC8B;CAC9B,QAAQ,OAAU,GAAG,SAAe;EACnC,IAAI,QAAQ,QAAQ,IAAI,MAAM,OAAO;EACrC,IAAI,CAAC,OAAO;GACX,wBAAQ,IAAI,IAAI;GAChB,QAAQ,IAAI,MAAM,SAAS,KAAK;EACjC;EACA,IAAI,SAAS,MAAM,IAAI,EAAE;EACzB,IAAI,CAAC,QAAQ;GACZ,yBAAS,IAAI,IAAI;GACjB,MAAM,IAAI,IAAI,MAAM;EACrB;EACA,MAAM,MAAM,KAAK,UAAU,IAAI;EAC/B,IAAI,OAAO,IAAI,GAAG,GACjB,OAAO,OAAO,IAAI,GAAG;EAEtB,MAAM,SAAS,GAAG,OAAO,GAAG,IAAI;EAChC,OAAO,IAAI,KAAK,MAAM;EACtB,IAAI,kBAAkB,SACrB,OAAO,YAAY;GAClB,IAAI,OAAO,IAAI,GAAG,MAAM,QAAQ,OAAO,OAAO,GAAG;EAClD,CAAC;EAEF,OAAO;CACR;AACD;;;;;;;;;;;;;ACtCA,eAA8B,WAC7B,MACA,OACgC;CAChC,OAAQ,MAAM,KAAK,QAAQ,KAAK,KAAM,KAAA;AACvC;;;;;;;;;;;;ACCA,SAAwB,0BACvB,iBACyB;CACzB,MAAM,MAAM,IAAI,eAAe,eAAe;CAC9C,MAAM,cAAc,IAAI,YAAY;CACpC,IAAI,UAAU;CAEd,MAAM,cACL,OACI;EACJ,MAAM,uBAAuB;GAC5B,IAAI,SAAS;GACb,UAAU;GACV,GAAG;IACF,UAAU,SAAS,KAAK,WAAW;IACnC,SAAS,IAAI,WAAW;IACxB,QAAQ,IAAI;GACb,CAAC;EAC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uBAAuB,SAAS,MAAM,IAC/E,OACC,SAAS,MAAM,QAAQ;GAC3B,QACC,IAAI,SAAS,cAAc;IAC1B;IACA,SAAS,eAAe,OAAO;GAChC,CAAC,CACF;EACD,CAAC;EAED,MAAM,SAAS,UAAoB;GAClC,IAAI,OAEH,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;QAGhE,QAAQ;EAEV;EAEA,QAAQ,QAAQ,QAAQ,KAAK,KAAK,KAAK,CAAC,CAAC,CACvC,MAAM,YAAY;GAClB,IAAI,YAAY,OAAO;IACtB,IAAI,QAAQ;IAGZ,QAAQ,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC,CAAC;GAC5C;EACD,CAAC,CAAC,CACD,OAAO,MAAe;GACtB,MAAM,CAAC;EACR,CAAC;CACH,CAAC,EACH;AACD;AAEA,MAAM,yBAAyB;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;AACD"}
@@ -1,5 +1,5 @@
1
- import { n as ServerEvent } from "./MiddlewareFunction-BZilnEei.mjs";
2
- import { t as Router } from "./Router-By9Nlg39.mjs";
1
+ import { n as ServerEvent } from "./MiddlewareFunction-DMYxjzF4.mjs";
2
+ import { t as Router } from "./Router-DyK3DTWQ.mjs";
3
3
  //#region src/site/serverHandlers.d.ts
4
4
  /**
5
5
  * The site's request handler, as created by `createServerLoad`.
@@ -11,4 +11,4 @@ declare const router: Router;
11
11
  declare const load: ServerLoad;
12
12
  //#endregion
13
13
  export { router as n, load as t };
14
- //# sourceMappingURL=serverEntry-BGii8bB6.d.mts.map
14
+ //# sourceMappingURL=serverEntry-BFad1k1C.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverEntry-BFad1k1C.d.mts","names":[],"sources":["../src/site/serverHandlers.ts","../src/site/serverEntry.ts"],"mappings":";;;;;;KAsDY,cAAc,IAAI,aAAa,sBAAsB,QAAQ;;;cC9C5D,QAAQ;cAKR,MAAM"}