@ngrok/app-server 0.3.1 → 0.3.3

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 (65) hide show
  1. package/README.md +83 -27
  2. package/dist/{build-id-C6sYO9Yp.js → build-id-B0448vZH.js} +27 -2
  3. package/dist/build-id-B0448vZH.js.map +1 -0
  4. package/dist/{build-manifest-UDNk81Ce.js → build-manifest-DBMWe3Lx.js} +12 -2
  5. package/dist/build-manifest-DBMWe3Lx.js.map +1 -0
  6. package/dist/cli.js +2 -2
  7. package/dist/client-browser.js +1 -1
  8. package/dist/client.js +1 -1
  9. package/dist/{entry-CM6Ma-Tv.d.ts → create-server-D4-nVOVJ.d.ts} +56 -70
  10. package/dist/{create-server-DkTeIJ8L.js → create-server-jMl2ltHD.js} +454 -394
  11. package/dist/create-server-jMl2ltHD.js.map +1 -0
  12. package/dist/entry-BPrgE_6K.d.ts +94 -0
  13. package/dist/entry-D9H4LA9c.js +351 -0
  14. package/dist/entry-D9H4LA9c.js.map +1 -0
  15. package/dist/{index-Bo5G9LuQ.d.ts → index-Db7dspq6.d.ts} +6 -1
  16. package/dist/index.d.ts +5 -14
  17. package/dist/index.js +3 -3
  18. package/dist/{load-entry-CmkdlmDX.js → load-entry-D7r0mjEp.js} +4 -4
  19. package/dist/{load-entry-CmkdlmDX.js.map → load-entry-D7r0mjEp.js.map} +1 -1
  20. package/dist/{node-BFH82eeL.js → node-C1qudLs_.js} +2 -2
  21. package/dist/{node-BFH82eeL.js.map → node-C1qudLs_.js.map} +1 -1
  22. package/dist/node-vite.d.ts +1 -1
  23. package/dist/node.d.ts +1 -1
  24. package/dist/node.js +1 -1
  25. package/dist/react-router-vite.d.ts +1 -1
  26. package/dist/react-router.d.ts +3 -2
  27. package/dist/react-router.js +31 -2
  28. package/dist/react-router.js.map +1 -1
  29. package/dist/request-context-BtQ87VYb.js.map +1 -1
  30. package/dist/{script-hashes-hqUk6kG7.js → script-hashes-C6hQ5XnP.js} +22 -4
  31. package/dist/script-hashes-C6hQ5XnP.js.map +1 -0
  32. package/dist/{serve-Cc-ADdhZ.js → serve-E0hSGe6_.js} +2 -2
  33. package/dist/{serve-Cc-ADdhZ.js.map → serve-E0hSGe6_.js.map} +1 -1
  34. package/dist/{stale-build-navigation-PnMLtTF8.js → stale-build-navigation-rg5xxmTr.js} +2 -2
  35. package/dist/{stale-build-navigation-PnMLtTF8.js.map → stale-build-navigation-rg5xxmTr.js.map} +1 -1
  36. package/dist/{start-Cb3kknlF.js → start-CifYPRq1.js} +34 -6
  37. package/dist/start-CifYPRq1.js.map +1 -0
  38. package/dist/tanstack-start-vite.d.ts +1 -1
  39. package/dist/tanstack-start.d.ts +2 -2
  40. package/dist/testing.d.ts +56 -0
  41. package/dist/testing.js +114 -0
  42. package/dist/testing.js.map +1 -0
  43. package/dist/{trailing-slash-DX7NB88H.d.ts → trailing-slash-CFSv_Gzx.d.ts} +2 -2
  44. package/dist/{types-DLYxYS6M.d.ts → types-j29vspx_.d.ts} +16 -2
  45. package/dist/vercel-pages.d.ts +32 -0
  46. package/dist/vercel-pages.js +54 -0
  47. package/dist/vercel-pages.js.map +1 -0
  48. package/dist/vercel-vite.d.ts +30 -9
  49. package/dist/vercel-vite.js +160 -17
  50. package/dist/vercel-vite.js.map +1 -1
  51. package/dist/vercel.d.ts +2 -2
  52. package/dist/vercel.js +2 -2
  53. package/dist/{vite-iioAoxSt.js → vite-BDREIgiH.js} +45 -33
  54. package/dist/vite-BDREIgiH.js.map +1 -0
  55. package/dist/vite.d.ts +1 -1
  56. package/dist/vite.js +1 -1
  57. package/package.json +5 -1
  58. package/dist/build-id-C6sYO9Yp.js.map +0 -1
  59. package/dist/build-manifest-UDNk81Ce.js.map +0 -1
  60. package/dist/create-server-DkTeIJ8L.js.map +0 -1
  61. package/dist/entry-CenmvESk.js +0 -116
  62. package/dist/entry-CenmvESk.js.map +0 -1
  63. package/dist/script-hashes-hqUk6kG7.js.map +0 -1
  64. package/dist/start-Cb3kknlF.js.map +0 -1
  65. package/dist/vite-iioAoxSt.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vite-BDREIgiH.js","names":["constants"],"sources":["../src/vite/standalone.ts","../src/vite/index.ts"],"sourcesContent":["import { cpSync, existsSync, readdirSync, readFileSync, realpathSync } from \"node:fs\";\nimport { basename, dirname, join, sep } from \"node:path\";\n\n/**\n * A package name: an optional scope and a name, each with no `/` or `\\` and\n * no `.` at the start. Why: a name such as `..` or `../x` in a manifest must\n * not move a copy out of `node_modules`.\n */\nconst PACKAGE_NAME = /^(?:@[^./\\\\][^/\\\\]*\\/)?[^./\\\\][^/\\\\]*$/u;\n\n/**\n * The package names in the dependency `fields` of the `package.json` in\n * `directory`. It skips a key that is not a package name.\n *\n * @example\n * dependencyNames(\"/app/node_modules/react-dom\", [\"peerDependencies\"]); // => [\"react\"]\n */\nexport function dependencyNames(directory: string, fields: readonly string[]): string[] {\n\tconst manifest: unknown = JSON.parse(readFileSync(join(directory, \"package.json\"), \"utf8\"));\n\tconst names = fields.flatMap((field) => {\n\t\tconst value: unknown =\n\t\t\ttypeof manifest === \"object\" && manifest != null ? Reflect.get(manifest, field) : undefined;\n\t\treturn typeof value === \"object\" && value != null\n\t\t\t? Object.keys(value).filter((name) => PACKAGE_NAME.test(name))\n\t\t\t: [];\n\t});\n\treturn [...new Set(names)];\n}\n\n/**\n * The package name of a bare import.\n *\n * @example\n * packageName(\"@scope/name/sub/path\"); // => \"@scope/name\"\n */\nexport function packageName(specifier: string): string {\n\tconst parts = specifier.split(\"/\");\n\treturn parts.slice(0, specifier.startsWith(\"@\") ? 2 : 1).join(\"/\");\n}\n\n/**\n * Code that finds a file next to its own module: a relative `new URL()` on\n * `import.meta.url`, `fileURLToPath(import.meta.url)`, or\n * `import.meta.dirname`.\n */\nconst OWN_FILE =\n\t/new\\s+URL\\(\\s*(?<quote>[\"'`])\\.{1,2}\\/[^\"'`]*\\k<quote>\\s*,\\s*import\\.meta\\.url\\s*\\)|fileURLToPath\\(\\s*import\\.meta\\.url\\s*\\)|import\\.meta\\.(?:dirname|filename)\\b/u;\n\n/**\n * Whether the module `file` finds a file next to itself, such as\n * `@vercel/og`, which reads `resvg.wasm` through\n * `new URL(\"./resvg.wasm\", import.meta.url)`. Why: in the bundle,\n * `import.meta.url` is the URL of the bundle, so the file is not there.\n *\n * @example\n * readsOwnFiles(\"/app/node_modules/@vercel/og/dist/index.node.js\"); // => true\n */\nexport function readsOwnFiles(file: string): boolean {\n\treturn OWN_FILE.test(readFileSync(file, \"utf8\"));\n}\n\n/**\n * The real path of the directory of package `name`, as Node finds it from the\n * directory `from`: in each `node_modules` directory above `from`. Else\n * `undefined`. The real path follows the symbolic links of pnpm's layout.\n *\n * @example\n * findPackage(\"react\", \"/app/build/server\"); // => \"/app/node_modules/.pnpm/react@19.3.1/node_modules/react\"\n */\nexport function findPackage(name: string, from: string): string | undefined {\n\tfor (let directory = from; ; directory = dirname(directory)) {\n\t\tconst candidate = join(directory, \"node_modules\", name);\n\t\tif (basename(directory) !== \"node_modules\" && existsSync(join(candidate, \"package.json\"))) {\n\t\t\treturn realpathSync(candidate);\n\t\t}\n\t\tif (dirname(directory) === directory) {\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n\n/**\n * The directory of package `name` that holds `file`: the nearest directory\n * above `file` at `node_modules/<name>`. Else `undefined`, such as for a file\n * of a linked workspace package.\n *\n * @example\n * packageDirectoryOf(\"/app/node_modules/react/cjs/react.js\", \"react\"); // => \"/app/node_modules/react\"\n */\nexport function packageDirectoryOf(file: string, name: string): string | undefined {\n\tfor (\n\t\tlet directory = dirname(file);\n\t\tdirectory !== dirname(directory);\n\t\tdirectory = dirname(directory)\n\t) {\n\t\tif (directory.endsWith(`${sep}${join(\"node_modules\", name)}`)) {\n\t\t\t// Why the real path: `findPackage` gives real paths, and the two must compare equal.\n\t\t\treturn realpathSync(directory);\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** Whether a `.node` file is in `directory`, outside its `node_modules`. */\nfunction hasNodeFile(directory: string): boolean {\n\treturn readdirSync(directory, { withFileTypes: true }).some((entry) =>\n\t\tentry.isDirectory()\n\t\t\t? entry.name !== \"node_modules\" && hasNodeFile(join(entry.parentPath, entry.name))\n\t\t\t: entry.name.endsWith(\".node\"),\n\t);\n}\n\n/**\n * Whether the package in `directory` loads a native addon: a `.node` file is\n * in the package, or in a package of its `dependencies` or\n * `optionalDependencies`. The second case finds a package that gets its addon\n * from a package for each platform, such as `oxc-parser` from\n * `@oxc-parser/binding-darwin-arm64`. Only the installed platform package is\n * there. `scans` keeps the result for each directory that the function\n * searched, so a call with the same map does not search a directory again.\n *\n * @example\n * isNativePackage(\"/app/node_modules/better-sqlite3\"); // => true\n */\nexport function isNativePackage(directory: string, scans = new Map<string, boolean>()): boolean {\n\tconst scan = (path: string): boolean => {\n\t\tconst found = scans.get(path) ?? hasNodeFile(path);\n\t\tscans.set(path, found);\n\t\treturn found;\n\t};\n\treturn (\n\t\tscan(directory) ||\n\t\tdependencyNames(directory, [\"dependencies\", \"optionalDependencies\"]).some((name) => {\n\t\t\tconst dependency = findPackage(name, directory);\n\t\t\treturn dependency != null && scan(dependency);\n\t\t})\n\t);\n}\n\n/**\n * The `node_modules` directories where Node looks for a package that the\n * package at `destination` imports, nearest first, down to `target`.\n */\nfunction lookupDirectories(destination: string, target: string): string[] {\n\tconst directories: string[] = [];\n\tfor (let directory = destination; ; directory = dirname(directory)) {\n\t\tif (basename(directory) !== \"node_modules\") {\n\t\t\tdirectories.push(join(directory, \"node_modules\"));\n\t\t}\n\t\tif (directory === dirname(target)) {\n\t\t\treturn directories;\n\t\t}\n\t}\n}\n\n/**\n * Copies each package, whole, with the installed packages of its\n * `dependencies`, `optionalDependencies`, and `peerDependencies`, into the\n * `node_modules` directory `target`. Node then finds each package from a file\n * next to `target`, with no install. The copy follows symbolic links. A\n * dependency goes to the top of `target`. If another copy of that package is\n * nearer in the lookup path of the package that needs it, the dependency goes\n * into that package's own `node_modules`.\n *\n * @example\n * copyPackages(new Map([[\"oxc-parser\", \"/app/node_modules/oxc-parser\"]]), \"/app/build/server/node_modules\");\n */\nexport function copyPackages(packages: ReadonlyMap<string, string>, target: string): void {\n\t// Why a map of destinations: a later lookup must know which copy is at each path.\n\tconst sources = new Map<string, string>();\n\tconst queue: string[] = [];\n\tconst add = (destination: string, source: string) => {\n\t\tsources.set(destination, source);\n\t\tqueue.push(destination);\n\t};\n\tfor (const [name, source] of packages) {\n\t\tadd(join(target, name), source);\n\t}\n\t// Why breadth first: a package places all its own dependencies before a dependency looks up\n\t// its own, so a later copy never hides an earlier lookup.\n\tfor (const destination of queue) {\n\t\tconst source = sources.get(destination) ?? \"\";\n\t\tcpSync(source, destination, {\n\t\t\trecursive: true,\n\t\t\tdereference: true,\n\t\t\tfilter: (path) => path !== join(source, \"node_modules\"),\n\t\t});\n\t\tfor (const name of dependencyNames(source, [\n\t\t\t\"dependencies\",\n\t\t\t\"optionalDependencies\",\n\t\t\t\"peerDependencies\",\n\t\t])) {\n\t\t\tconst dependency = findPackage(name, source);\n\t\t\tconst found = lookupDirectories(destination, target)\n\t\t\t\t.map((directory) => join(directory, name))\n\t\t\t\t.find((path) => sources.has(path));\n\t\t\tif (dependency != null && (found == null || sources.get(found) !== dependency)) {\n\t\t\t\tadd(join(found == null ? target : join(destination, \"node_modules\"), name), dependency);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { createHash } from \"node:crypto\";\nimport {\n\texistsSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { isBuiltin } from \"node:module\";\nimport {\n\tbasename,\n\tdirname,\n\textname,\n\tisAbsolute,\n\tjoin,\n\tposix,\n\trelative,\n\tresolve,\n\tsep,\n} from \"node:path\";\nimport { brotliCompressSync, constants, gzipSync } from \"node:zlib\";\nimport { getPath } from \"hono/utils/url\";\nimport type { Environment, Plugin, PreviewServer, ResolvedConfig, Rolldown } from \"vite\";\nimport { BUILD_MANIFEST_FILE, DEFAULT_ASSETS_PATH, manifestKey } from \"../core/build-manifest.js\";\nimport type { BuildManifest } from \"../core/build-manifest.js\";\nimport { copyName, isCompressible, MIN_COMPRESS_BYTES } from \"../core/compression.js\";\nimport type { Encoding } from \"../core/compression.js\";\nimport { contentType } from \"../core/static-files.js\";\nimport { scriptHashesOf } from \"../node/script-hashes.js\";\nimport { node } from \"../node/vite.js\";\nimport { reactRouterAdapter } from \"../react-router/vite.js\";\nimport { tanstackStartAdapter } from \"../tanstack-start/vite.js\";\nimport {\n\tcopyPackages,\n\tdependencyNames,\n\tfindPackage,\n\tisNativePackage,\n\tpackageDirectoryOf,\n\tpackageName,\n\treadsOwnFiles,\n} from \"./standalone.js\";\n\n/** The module ID of the server entry that {@link appServer} generates. */\nexport const SERVER_ENTRY_ID = \"virtual:@ngrok/app-server/entry\";\nconst RESOLVED_SERVER_ENTRY_ID = `\\0${SERVER_ENTRY_ID}`;\n\n/** The Vite environment that builds the server. */\nconst SERVER_ENVIRONMENT = \"ssr\";\n\n/** A bare import, such as `react` or `@scope/name/path`: not a path, a `\\0` ID, or a `node:` or `virtual:` ID. */\nconst BARE_IMPORT = /^[\\w@][^:]*$/u;\n\n/** The file extensions of a module that Node imports as it is, with no transform by Vite. */\nconst JAVASCRIPT_EXTENSIONS = new Set([\"\", \".js\", \".mjs\", \".cjs\"]);\n\n/** The header that turns on Node's header store for a response, so `finish` can read every header. */\nconst CAPTURE_MARKER = \"x-app-server-capture\";\n\n/**\n * Headers that describe one transfer, not the resource. The server sets its\n * own, and a cookie must never replay to every visitor. `Vary` is left out\n * because the preview server adds `Vary: Origin` to every response.\n */\nconst UNCAPTURED_HEADERS = new Set([\n\tCAPTURE_MARKER,\n\t\"connection\",\n\t\"content-encoding\",\n\t\"content-length\",\n\t\"date\",\n\t\"etag\",\n\t\"keep-alive\",\n\t\"last-modified\",\n\t\"set-cookie\",\n\t\"transfer-encoding\",\n\t\"vary\",\n]);\n\n/**\n * The build side of a framework adapter. The Vite config imports it, such as\n * `reactRouterAdapter()` from `@ngrok/app-server/react-router/vite`.\n */\nexport type FrameworkBuild = {\n\t/** A name for logs and errors. */\n\tname: string;\n\t/** The Vite ID of the framework's server module, such as `virtual:react-router/server-build`. */\n\tserverModule: string;\n\t/**\n\t * The module whose `runtime` export makes the run side from the server\n\t * module. It has the type `FrameworkRuntimeFactory`.\n\t */\n\truntimeModule: string;\n\t/**\n\t * The source of an object literal with more options for `runtime`, such as\n\t * a build constant of the framework. The bundler replaces the constants in\n\t * it, because the source is part of the server entry.\n\t */\n\truntimeOptions?: string;\n\t/** Whether a preview server runs the framework's prerender pass. */\n\tisPrerenderPass: (server: PreviewServer) => boolean;\n\t/** Throws for a config that the adapter does not support, so the build fails, not the first request. */\n\tvalidate?: (config: ResolvedConfig) => void;\n};\n\n/**\n * The build side of a host adapter. The Vite config imports it, such as\n * `node()` from `@ngrok/app-server/node/vite`.\n */\nexport type HostBuild = {\n\t/** A name for logs and errors. */\n\tname: string;\n\t/** The module whose `host` export is the run side, a `HostRuntime`. */\n\truntimeModule: string;\n\t/** The file name of the server entry in the server build, such as `app-server.js`. */\n\tentryFileName: string;\n\t/**\n\t * Writes the host's deploy output, such as Vercel's `.vercel/output`. It\n\t * runs after each prerender pass and after the build, so it can run two\n\t * times. Why after the pass too: when `appServer` comes before the\n\t * framework's plugin, the pass runs after the build. Why sync: Vite does\n\t * not wait for the end of that pass.\n\t */\n\toutput?: (build: HostOutput) => void;\n};\n\n/** What a host's `output` gets: the absolute paths of the build. */\nexport type HostOutput = {\n\t/** The Vite root. */\n\troot: string;\n\t/** The client build, such as `build/client`. */\n\tclientDirectory: string;\n\t/** The server entry, such as `build/server/app-server.js`. */\n\tentryFile: string;\n\t/**\n\t * The URL path of Vite's `build.assetsDir` in the client build, such as\n\t * `/assets/`. Its files have content hashes in their names.\n\t */\n\tassetsPath: string;\n};\n\n/** Options for {@link appServer}. */\nexport type AppServerOptions = {\n\t/**\n\t * The framework adapter. When omitted, the plugin finds the React Router or\n\t * TanStack Start plugin in the Vite config. It throws when it finds neither\n\t * or both.\n\t */\n\tframework?: FrameworkBuild;\n\t/** The host adapter. Default `node()`. */\n\thost?: HostBuild;\n\t/**\n\t * The module whose default export is the app from `createServer`, relative\n\t * to the Vite root. When omitted, the plugin uses `server.ts`, else\n\t * `server.js`, in the Vite root. When neither exists, the server uses its\n\t * default plugins.\n\t */\n\tapp?: string;\n};\n\n/** The built-in framework adapters, each with the name of the Vite plugin that marks its framework. */\nconst FRAMEWORKS = [\n\t// Why not the `react-router` plugin: React Router's child compiler drops that plugin and keeps\n\t// this one, which serves the server module.\n\t{ plugin: \"react-router:virtual-modules\", adapter: reactRouterAdapter },\n\t{ plugin: \"tanstack-react-start:config\", adapter: tanstackStartAdapter },\n];\n\n/** The adapter of the one built-in framework whose plugin is in the Vite config. */\nfunction detectFramework(plugins: readonly Plugin[]): FrameworkBuild {\n\tconst names = new Set(plugins.map((plugin) => plugin.name));\n\tconst [found, ...others] = FRAMEWORKS.filter(({ plugin }) => names.has(plugin));\n\tif (found == null) {\n\t\tthrow new Error(\n\t\t\t\"@ngrok/app-server found no React Router or TanStack Start plugin in the Vite config. Add the framework's plugin, or pass `framework` to `appServer`.\",\n\t\t);\n\t}\n\tif (others.length > 0) {\n\t\tthrow new Error(\n\t\t\t\"@ngrok/app-server found the React Router and the TanStack Start plugins in the Vite config. Pass `framework` to `appServer`.\",\n\t\t);\n\t}\n\treturn found.adapter();\n}\n\n/** The absolute path of `server.ts` or `server.js` in `root`, else `undefined` for the default app. */\nfunction defaultApp(root: string): string | undefined {\n\treturn [\"server.ts\", \"server.js\"]\n\t\t.map((name) => join(root, name))\n\t\t.find((path) => existsSync(path));\n}\n\n/** What {@link serverEntrySource} needs. */\ntype EntrySource = {\n\tframework: Pick<FrameworkBuild, \"serverModule\" | \"runtimeModule\" | \"runtimeOptions\">;\n\thost: Pick<HostBuild, \"runtimeModule\">;\n\t/** The absolute path of the app module, else `undefined` for the default app. */\n\tappModule: string | undefined;\n\t/** The source of an expression that gives the client build: a path or a `file:` URL. */\n\tclientDirectory: string;\n};\n\n/**\n * The source of the server entry. When a runtime runs the file as its main\n * module, such as `node build/server/app-server.js`, the entry starts the\n * server. When the CLI imports it, the CLI starts the server.\n */\nexport function serverEntrySource({\n\tframework,\n\thost,\n\tappModule,\n\tclientDirectory,\n}: EntrySource): string {\n\tconst modules = [\n\t\tframework.serverModule,\n\t\t// Why from the bundle: the CLI calls this export, so the server runs on the bundle's copy of\n\t\t// this package and of the framework, the same copies as the app and the routes.\n\t\t\"@ngrok/app-server\",\n\t\tframework.runtimeModule,\n\t\thost.runtimeModule,\n\t\t...(appModule == null ? [] : [appModule]),\n\t];\n\treturn [\n\t\t// Why before the imports: React reads `NODE_ENV` when it loads. Why dynamic imports: a static\n\t\t// import loads before this line.\n\t\t\"if (import.meta.main) {\",\n\t\t'\\tprocess.env.NODE_ENV ??= \"production\";',\n\t\t'\\tif (typeof process.setSourceMapsEnabled === \"function\") {',\n\t\t\"\\t\\tprocess.setSourceMapsEnabled(true);\",\n\t\t\"\\t}\",\n\t\t\"}\",\n\t\t`const [serverModule, { createEntry, createServer }, { runtime }, hostModule${appModule == null ? \"\" : \", { default: app }\"}] = await Promise.all([`,\n\t\t...modules.map((module) => `\\timport(${JSON.stringify(module)}),`),\n\t\t\"]);\",\n\t\t...(appModule == null\n\t\t\t? [\n\t\t\t\t\t`const app = createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\", trustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0) });`,\n\t\t\t\t]\n\t\t\t: []),\n\t\t`export const appServer = createEntry({`,\n\t\t`\\tapp,`,\n\t\t`\\thost: hostModule.host,`,\n\t\t`\\tclientDirectory: ${clientDirectory},`,\n\t\t`\\tframework: (mode) => runtime(serverModule, { ${framework.runtimeOptions == null ? \"\" : `...${framework.runtimeOptions}, `}mode }),`,\n\t\t`});`,\n\t\t// Why: a serverless host's function file calls the run side through the bundle's copy.\n\t\t\"export { hostModule };\",\n\t\t\"if (import.meta.main) {\",\n\t\t\"\\tawait appServer.start();\",\n\t\t\"}\",\n\t].join(\"\\n\");\n}\n\n/** The paths of the build that a host's `output` gets. */\nfunction hostOutput(config: ResolvedConfig, host: HostBuild): HostOutput {\n\treturn {\n\t\troot: config.root,\n\t\tclientDirectory: outDir(config, \"client\"),\n\t\tentryFile: join(outDir(config, SERVER_ENVIRONMENT), host.entryFileName),\n\t\tassetsPath: urlPathOfAssetsDir(\n\t\t\tconfig.environments.client?.build.assetsDir ?? config.build.assetsDir,\n\t\t),\n\t};\n}\n\n/**\n * The URL path of Vite's `build.assetsDir`. Why the default for the root: an\n * immutable cache on each file of the client build would keep an old page.\n *\n * @example\n * urlPathOfAssetsDir(\"blog-assets/build\"); // => \"/blog-assets/build/\"\n */\nfunction urlPathOfAssetsDir(assetsDir: string): string {\n\tconst path = posix.normalize(`/${assetsDir.replaceAll(\"\\\\\", \"/\")}/`);\n\treturn path === \"/\" ? DEFAULT_ASSETS_PATH : path;\n}\n\n/** The absolute path of an environment's build output. */\nfunction outDir(config: ResolvedConfig, environment: string): string {\n\treturn resolve(\n\t\tconfig.root,\n\t\tconfig.environments[environment]?.build.outDir ?? config.build.outDir,\n\t);\n}\n\n/**\n * Whether `id` is a JavaScript file, which Node imports from `node_modules`\n * as it is. Why: a plugin can resolve a bare import to a virtual module, and\n * Vite transforms a JSON file or an asset, such as `?raw` on a file with no\n * extension.\n */\nfunction isJavaScriptFile(id: string): boolean {\n\treturn isAbsolute(id) && !id.includes(\"?\") && JAVASCRIPT_EXTENSIONS.has(extname(id));\n}\n\n/**\n * A `require.resolve()` or an `import.meta.resolve()` of a string literal.\n * The `source` group is the string.\n */\nconst RESOLVE_CALL =\n\t/\\b(?:require|import\\.meta)\\.resolve\\(\\s*(?<quote>[\"'`])(?<source>[^\"'`$]+)\\k<quote>/gu;\n\n/** The dependency fields of the app's `package.json` that can name a package the server imports. */\nconst APP_DEPENDENCY_FIELDS = [\"dependencies\", \"optionalDependencies\", \"devDependencies\"];\n\n/** Whether `environment` builds the server. */\nfunction isServerBuild(environment: Pick<Environment, \"name\" | \"mode\">): boolean {\n\treturn environment.name === SERVER_ENVIRONMENT && environment.mode === \"build\";\n}\n\n/**\n * Makes the server build run with no install. The build bundles each\n * dependency, except the packages that the app keeps external (`ssr.external`\n * or the bundler's `external`), each native package (see `isNativePackage`),\n * each package that reads a file next to its own module (see `readsOwnFiles`),\n * and each package that the bundle shares with a package that the app keeps\n * external: the whole package of an external subpath, and each peer, at each\n * level. Those stay external, so the plugin copies each one, whole, with its\n * dependencies, into `node_modules` in the server build. It also writes a `package.json` there, so\n * Node, Bun, and Deno load the build as ES modules and find that `node_modules`.\n */\nfunction standalone(): Plugin {\n\t// Why a value for each name: two copies of one external package cannot share one `node_modules`.\n\tconst externals = new Map<string, string | undefined>();\n\t// Why: the bundle and an external package must share one copy of a package, such as `react`.\n\tconst shared = new Set<string>();\n\tconst natives = new Map<string, boolean>();\n\t// Why: many packages share one dependency, and each search reads its whole directory.\n\tconst scans = new Map<string, boolean>();\n\tconst isNative = (directory: string): boolean => {\n\t\tconst native = natives.get(directory) ?? isNativePackage(directory, scans);\n\t\tnatives.set(directory, native);\n\t\treturn native;\n\t};\n\t// Why: many modules import one package, and each check reads the file.\n\tconst ownFiles = new Map<string, boolean>();\n\t// Why `existsSync`: another plugin can give a module that is not on disk.\n\tconst readsOwnFile = (file: string): boolean => {\n\t\tconst reads = ownFiles.get(file) ?? (existsSync(file) && readsOwnFiles(file));\n\t\townFiles.set(file, reads);\n\t\treturn reads;\n\t};\n\t// Why: a package that stays external after the bundle holds one of its peers gets a second copy.\n\tconst inBundle = new Set<string>();\n\t/**\n\t * Whether the bundled module `file` of package `name` must stay external:\n\t * the package is native, or `file` reads a file next to it. Then the\n\t * package and each of its peers stay external, so the bundle shares them.\n\t */\n\tconst staysExternal = (\n\t\t{ name, file, directory }: { name: string; file: string; directory: string | undefined },\n\t\tlogger: Environment[\"logger\"],\n\t): boolean => {\n\t\tconst native = directory != null && isNative(directory);\n\t\tif (directory == null || (!native && !readsOwnFile(file))) {\n\t\t\tinBundle.add(name);\n\t\t\treturn false;\n\t\t}\n\t\tconst group = withPeers([{ name, from: directory }]);\n\t\tconst held = [...group].find((peer) => inBundle.has(peer));\n\t\t// Why bundle it: a second copy of a peer, such as `react`, breaks more than a lost file.\n\t\tif (held != null && !native) {\n\t\t\tlogger.warn(\n\t\t\t\t`@ngrok/app-server bundles \"${name}\", but it reads a file next to its own module, so the server can fail when it reads that file. The bundle already holds \"${held}\", so \"${name}\" cannot stay external alone. Add \"${name}\" to \\`ssr.external\\`.`,\n\t\t\t);\n\t\t\tinBundle.add(name);\n\t\t\treturn false;\n\t\t}\n\t\tfor (const peer of group) {\n\t\t\tshared.add(peer);\n\t\t}\n\t\treturn true;\n\t};\n\treturn {\n\t\tname: \"@ngrok/app-server:standalone\",\n\t\t// Why `pre`: Vite's resolver runs before a plugin with no `enforce`, so that plugin cannot keep\n\t\t// a native package out of the bundle.\n\t\tenforce: \"pre\",\n\t\tconfig: (config, { command }) => {\n\t\t\tconst ssr = config.environments?.[SERVER_ENVIRONMENT]?.resolve;\n\t\t\t// Why a build only: in development, Vite loads each dependency from `node_modules`. Why not\n\t\t\t// with the app's value: Vite merges `true` over a list, and `noExternal: true` wins over\n\t\t\t// `external: true`, so the app's value then has no effect.\n\t\t\treturn command === \"build\" &&\n\t\t\t\tconfig.ssr?.noExternal == null &&\n\t\t\t\tssr?.noExternal == null &&\n\t\t\t\tconfig.ssr?.external !== true &&\n\t\t\t\tssr?.external !== true\n\t\t\t\t? { ssr: { noExternal: true } }\n\t\t\t\t: undefined;\n\t\t},\n\t\tbuildStart() {\n\t\t\tif (!isServerBuild(this.environment)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\texternals.clear();\n\t\t\tshared.clear();\n\t\t\tnatives.clear();\n\t\t\tscans.clear();\n\t\t\townFiles.clear();\n\t\t\tinBundle.clear();\n\t\t\tconst { resolve: resolveOptions, build, root } = this.environment.config;\n\t\t\tconst kept = [\n\t\t\t\t...(resolveOptions.external === true ? [] : resolveOptions.external),\n\t\t\t\t...[build.rolldownOptions.external].flat(),\n\t\t\t];\n\t\t\tconst names = kept.flatMap((id) =>\n\t\t\t\ttypeof id === \"string\" && BARE_IMPORT.test(id) ? [packageName(id)] : [],\n\t\t\t);\n\t\t\tconst patterns = kept.filter(\n\t\t\t\t(id): id is Exclude<typeof id, string | undefined> => id != null && typeof id !== \"string\",\n\t\t\t);\n\t\t\t// Why the app's dependencies: the bundler never shows the plugin an import that a `RegExp` or\n\t\t\t// a function keeps external, so the build must find their peers before it bundles.\n\t\t\tconst matched =\n\t\t\t\tpatterns.length === 0 || !existsSync(join(root, \"package.json\"))\n\t\t\t\t\t? []\n\t\t\t\t\t: dependencyNames(root, APP_DEPENDENCY_FIELDS).filter((name) =>\n\t\t\t\t\t\t\tpatterns.some((pattern) => matchesExternal(pattern, name)),\n\t\t\t\t\t\t);\n\t\t\t// Why with no import: the app can read a file of a package at run time, such as through\n\t\t\t// `require.resolve`.\n\t\t\tfor (const name of names) {\n\t\t\t\tconst directory = findPackage(name, root);\n\t\t\t\tif (directory != null) {\n\t\t\t\t\texternals.set(name, directory);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const name of withPeers(\n\t\t\t\t[...names, ...matched].map((dependency) => ({ name: dependency, from: root })),\n\t\t\t)) {\n\t\t\t\tshared.add(name);\n\t\t\t}\n\t\t},\n\t\tresolveId: {\n\t\t\tfilter: { id: BARE_IMPORT },\n\t\t\tasync handler(source, importer, options) {\n\t\t\t\tif (!isServerBuild(this.environment) || isBuiltin(source)) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tconst resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n\t\t\t\tconst bundled = resolved?.external === false;\n\t\t\t\tif (resolved == null || (bundled && !isJavaScriptFile(resolved.id))) {\n\t\t\t\t\treturn resolved;\n\t\t\t\t}\n\t\t\t\tconst name = packageName(source);\n\t\t\t\t// Why the resolved file first: Vite can pick another copy than Node, such as for\n\t\t\t\t// `resolve.dedupe`.\n\t\t\t\tconst directory =\n\t\t\t\t\t(bundled ? packageDirectoryOf(resolved.id, name) : undefined) ??\n\t\t\t\t\tfindPackage(\n\t\t\t\t\t\tname,\n\t\t\t\t\t\timporter != null && isAbsolute(importer)\n\t\t\t\t\t\t\t? dirname(importer)\n\t\t\t\t\t\t\t: this.environment.config.root,\n\t\t\t\t\t);\n\t\t\t\tif (\n\t\t\t\t\tbundled &&\n\t\t\t\t\t!shared.has(name) &&\n\t\t\t\t\t!staysExternal({ name, file: resolved.id, directory }, this.environment.logger)\n\t\t\t\t) {\n\t\t\t\t\treturn resolved;\n\t\t\t\t}\n\t\t\t\tconst known = externals.get(name);\n\t\t\t\tif (known != null && directory != null && known !== directory) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`@ngrok/app-server found two copies of \"${name}\" that stay external, and the server build can hold one: ${known} and ${directory}. Install one version of \"${name}\".`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\texternals.set(name, known ?? directory);\n\t\t\t\treturn bundled ? { id: source, external: true } : resolved;\n\t\t\t},\n\t\t},\n\t\ttransform: {\n\t\t\t// Why only the app's code: a package that resolves a file of another package at run time,\n\t\t\t// such as an optional binary, would copy a large package that the server never reads.\n\t\t\tfilter: {\n\t\t\t\tid: { exclude: /[\\\\/]node_modules[\\\\/]/u },\n\t\t\t\tcode: /\\b(?:require|import\\.meta)\\.resolve\\(/u,\n\t\t\t},\n\t\t\thandler(code, id) {\n\t\t\t\tif (!isServerBuild(this.environment)) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\t// Why: the server reads a file of the package at run time, so the build must hold the package.\n\t\t\t\tfor (const { groups } of code.matchAll(RESOLVE_CALL)) {\n\t\t\t\t\tconst source = groups?.source ?? \"\";\n\t\t\t\t\tconst name = packageName(source);\n\t\t\t\t\tconst directory =\n\t\t\t\t\t\tBARE_IMPORT.test(source) && !isBuiltin(source) && !externals.has(name)\n\t\t\t\t\t\t\t? findPackage(name, isAbsolute(id) ? dirname(id) : this.environment.config.root)\n\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t// Why only a package it finds: the module-graph pass in `writeBundle` can find it from another importer.\n\t\t\t\t\tif (directory != null) {\n\t\t\t\t\t\texternals.set(name, directory);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t},\n\t\t},\n\t\twriteBundle() {\n\t\t\tif (!isServerBuild(this.environment)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Why: the bundler does not call `resolveId` for a package in its own `external` option. Why\n\t\t\t// from the importer: with pnpm, only the importer's `node_modules` holds its dependencies.\n\t\t\tfor (const importer of this.getModuleIds()) {\n\t\t\t\tconst info = this.getModuleInfo(importer);\n\t\t\t\tfor (const id of [...(info?.importedIds ?? []), ...(info?.dynamicallyImportedIds ?? [])]) {\n\t\t\t\t\tconst name = packageName(id);\n\t\t\t\t\tif (BARE_IMPORT.test(id) && !isBuiltin(id) && !externals.has(name)) {\n\t\t\t\t\t\texternals.set(\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tfindPackage(\n\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\tisAbsolute(importer) ? dirname(importer) : this.environment.config.root,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst directory = outDir(this.environment.getTopLevelConfig(), SERVER_ENVIRONMENT);\n\t\t\tconst found = new Map<string, string>();\n\t\t\tfor (const [name, source] of externals) {\n\t\t\t\tif (source == null) {\n\t\t\t\t\tthis.environment.logger.warn(\n\t\t\t\t\t\t`@ngrok/app-server cannot find \"${name}\", which stays external, so the server build does not hold it. The server fails if it imports \"${name}\".`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tfound.set(name, source);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst target = join(directory, \"node_modules\");\n\t\t\trmSync(target, { recursive: true, force: true });\n\t\t\tcopyPackages(found, target);\n\t\t\twriteFileSync(join(directory, \"package.json\"), `${JSON.stringify({ type: \"module\" })}\\n`);\n\t\t\tif (found.size > 0) {\n\t\t\t\tthis.environment.logger.info(\n\t\t\t\t\t`@ngrok/app-server copied the external packages ${[...found.keys()].join(\", \")}, with their dependencies, into ${target}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Whether the app's `RegExp` or function external keeps the package `name`\n * external. Why `false` when the function throws: the build calls it with no\n * importer, and a function that reads the importer can throw.\n */\nfunction matchesExternal(\n\tpattern: RegExp | ((id: string, importer: string | undefined, isResolved: boolean) => unknown),\n\tname: string,\n): boolean {\n\tif (typeof pattern !== \"function\") {\n\t\treturn name.search(pattern) !== -1;\n\t}\n\ttry {\n\t\treturn pattern(name, undefined, false) === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Each package of `start` and each of its peers, at each level. Why each\n * level: a peer can have peers, such as `react` for `react-router`.\n */\nfunction withPeers(start: { name: string; from: string }[]): Set<string> {\n\tconst names = new Set<string>();\n\tconst queue = [...start];\n\tfor (const { name, from } of queue) {\n\t\tconst directory = names.has(name) ? undefined : findPackage(name, from);\n\t\tnames.add(name);\n\t\tif (directory != null) {\n\t\t\tfor (const peer of dependencyNames(directory, [\"peerDependencies\"])) {\n\t\t\t\tqueue.push({ name: peer, from: directory });\n\t\t\t}\n\t\t}\n\t}\n\treturn names;\n}\n\n/** Writes `.app-server.json` into the client build. */\nfunction writeBuildManifest(clientDirectory: string, manifest: BuildManifest): void {\n\tmkdirSync(clientDirectory, { recursive: true });\n\twriteFileSync(\n\t\tjoin(clientDirectory, BUILD_MANIFEST_FILE),\n\t\t`${JSON.stringify(manifest, null, \"\\t\")}\\n`,\n\t);\n}\n\n/**\n * Writes the build ID and the script hashes of the client build\n * ({@link scriptHashesOf}) into `.app-server.json`, and keeps the rest of the\n * file. Why after the build too: a build with no prerender pass can have HTML\n * files, such as `public/offline.html`.\n */\nfunction completeBuildManifest(clientDirectory: string, buildId: string | undefined): void {\n\tif (!existsSync(clientDirectory)) {\n\t\treturn;\n\t}\n\tconst path = join(clientDirectory, BUILD_MANIFEST_FILE);\n\tconst recorded: unknown = existsSync(path) ? JSON.parse(readFileSync(path, \"utf8\")) : undefined;\n\twriteBuildManifest(clientDirectory, {\n\t\tprerendered: [],\n\t\theaders: {},\n\t\t...(typeof recorded === \"object\" && recorded != null ? recorded : {}),\n\t\t...(buildId == null ? {} : { buildId }),\n\t\tscriptHashes: scriptHashesOf(clientDirectory),\n\t});\n}\n\n/**\n * The ID of a client build: a hash of the name and the content of each file\n * in its bundle. Why the bundle: it is the code that an open tab runs, so the\n * ID changes when that code changes, and not for a change to the server, a\n * `public/` file, or a prerendered page. Why the content, not the file\n * names: a name has a content hash only when the output names ask for one.\n */\nfunction bundleBuildId(bundle: Rolldown.OutputBundle): string {\n\tconst hash = createHash(\"sha256\");\n\t// Why `<`, not `localeCompare`: the order of `localeCompare` changes with the locale of the\n\t// machine, so two machines would give one bundle two IDs.\n\tfor (const file of Object.values(bundle).toSorted((first, second) =>\n\t\tfirst.fileName < second.fileName ? -1 : 1,\n\t)) {\n\t\thash.update(`${file.fileName}\\0`);\n\t\thash.update(file.type === \"chunk\" ? file.code : file.source);\n\t\thash.update(\"\\0\");\n\t}\n\t// Why 16 hex digits: 64 bits keep two builds apart, and the ID goes in each document's headers.\n\treturn hash.digest(\"hex\").slice(0, 16);\n}\n\n/** The path of each file under `directory` that is not a dotfile, in code unit order. */\nfunction filesIn(directory: string): string[] {\n\tif (!existsSync(directory)) {\n\t\treturn [];\n\t}\n\treturn readdirSync(directory, { recursive: true, withFileTypes: true })\n\t\t.filter((entry) => entry.isFile() && !entry.name.startsWith(\".\"))\n\t\t.map((entry) => relative(directory, join(entry.parentPath, entry.name)).split(sep).join(\"/\"))\n\t\t.toSorted();\n}\n\n/** The client build, as its `writeBundle` hook saw it. */\ntype ClientBuild = {\n\t/** The {@link bundleBuildId} of the client bundle. */\n\tbundleId: string;\n\t/** The assets directory of the client build, such as `build/client/assets`. */\n\tassetsDirectory: string;\n\t/** The files in the assets directory ({@link filesIn}) after the client build wrote its bundle. */\n\tassets: ReadonlySet<string>;\n};\n\n/**\n * The ID of the whole build: the {@link bundleBuildId} of the client bundle,\n * with the name and the content of each file that a later build step added to\n * the assets directory. Why: React Router writes its route manifest\n * (`assets/manifest-*.js`) during the server build, and a route change, such\n * as a new path for one module, can keep the client bundle the same.\n */\nfunction appBuildId({ bundleId, assetsDirectory, assets }: ClientBuild): string {\n\tconst added = filesIn(assetsDirectory).filter((file) => !assets.has(file));\n\tif (added.length === 0) {\n\t\treturn bundleId;\n\t}\n\tconst hash = createHash(\"sha256\").update(bundleId);\n\tfor (const file of added) {\n\t\thash.update(`\\0${file}\\0`);\n\t\thash.update(readFileSync(join(assetsDirectory, file)));\n\t}\n\treturn hash.digest(\"hex\").slice(0, 16);\n}\n\n/**\n * The `buildId` and the `assetsPath` of the build manifest that the client\n * build wrote. Why keep them: the prerender pass runs after the client build,\n * which knows them.\n */\nfunction clientBuildFields(clientDirectory: string): Pick<BuildManifest, \"buildId\" | \"assetsPath\"> {\n\tconst path = join(clientDirectory, BUILD_MANIFEST_FILE);\n\tconst manifest: unknown = existsSync(path) ? JSON.parse(readFileSync(path, \"utf8\")) : undefined;\n\tif (typeof manifest !== \"object\" || manifest == null) {\n\t\treturn {};\n\t}\n\treturn {\n\t\t...(\"buildId\" in manifest && typeof manifest.buildId === \"string\"\n\t\t\t? { buildId: manifest.buildId }\n\t\t\t: {}),\n\t\t...(\"assetsPath\" in manifest && typeof manifest.assetsPath === \"string\"\n\t\t\t? { assetsPath: manifest.assetsPath }\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Records each 2xx path and the headers of each non-document response while\n * the framework's prerender pass runs. It writes them to `.app-server.json` in\n * the client build when the preview server closes, with the script hashes of\n * each HTML file.\n */\nfunction capture(server: PreviewServer, afterPass: () => void): void {\n\tconst clientDirectory = outDir(server.config, \"client\");\n\tconst started = Date.now();\n\tconst paths = new Set<string>();\n\tconst headers: BuildManifest[\"headers\"] = {};\n\tserver.middlewares.use((request, response, next) => {\n\t\t// Why `getPath`: the static stages look a file up by Hono's decoded path, such as `/café.json`.\n\t\tconst pathname = getPath(new Request(new URL(request.url ?? \"/\", \"http://localhost\")));\n\t\t// Why: Node keeps the headers that `writeHead` gets readable only when a header was set first.\n\t\tresponse.setHeader(CAPTURE_MARKER, \"1\");\n\t\tresponse.once(\"finish\", () => {\n\t\t\tif (response.statusCode < 200 || response.statusCode >= 300) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst key = manifestKey(pathname);\n\t\t\tpaths.add(key);\n\t\t\t// Why skip documents: the framework sets their headers for each request (a nonce, the\n\t\t\t// host), so the headers of the build's request are wrong for every other one.\n\t\t\tif (String(response.getHeader(\"content-type\") ?? \"\").startsWith(\"text/html\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst recorded: Record<string, string> = {};\n\t\t\tfor (const [name, value] of Object.entries(response.getHeaders())) {\n\t\t\t\t// Why skip index names: after a `setHeader`, Node stores a flat header array from\n\t\t\t\t// `writeHead`, as TanStack Start's preview server sends, under its indexes too.\n\t\t\t\tif (!UNCAPTURED_HEADERS.has(name) && !/^\\d+$/u.test(name) && value != null) {\n\t\t\t\t\trecorded[name] = Array.isArray(value) ? value.join(\", \") : String(value);\n\t\t\t\t}\n\t\t\t}\n\t\t\theaders[key] = recorded;\n\t\t});\n\t\tnext();\n\t});\n\tserver.httpServer.once(\"close\", () => {\n\t\twriteBuildManifest(clientDirectory, {\n\t\t\t...clientBuildFields(clientDirectory),\n\t\t\tprerendered: [...paths].toSorted(),\n\t\t\theaders: Object.fromEntries(\n\t\t\t\tObject.entries(headers).toSorted(([first], [second]) => first.localeCompare(second)),\n\t\t\t),\n\t\t\tscriptHashes: scriptHashesOf(clientDirectory),\n\t\t});\n\t\t// Why here too: the copy step of `buildApp` runs before this pass when `appServer` comes\n\t\t// before the framework's plugin. Why sync: Vite does not wait for this listener.\n\t\t// Why each file that the pass changed, not each path: a path does not name its file, as\n\t\t// TanStack Start can write `/page` to `page.html`. Why 2 s early: a file system can keep the\n\t\t// modification time in steps of 1 or 2 s.\n\t\twriteAllCopies(clientDirectory, { changedSince: started - 2000 });\n\t\tafterPass();\n\t});\n}\n\n/**\n * The brotli quality of the copies. Why 9, not the highest (11): on a docs\n * build with 70 MB of text, 11 adds 46 s to the build and 9 adds 0.6 s. The\n * copies of 9 are 9% larger, and still 25% smaller than the gzip copies.\n */\nconst BROTLI_QUALITY = 9;\n\n/**\n * Writes the compressed copies (`.<file>.gz` and `.<file>.br`) of the file at\n * `path` when the server compresses the file: a compressible type of 1 KiB\n * or more. It writes a copy only when it is smaller: the gzip copy than the\n * file, and the brotli copy than the gzip copy. Else it removes an old copy,\n * so a copy from an earlier build never replaces a changed file.\n */\nfunction writeCopies(path: string): void {\n\tconst bytes =\n\t\tisCompressible(contentType(path, {})) &&\n\t\tstatSync(path, { throwIfNoEntry: false })?.isFile() === true\n\t\t\t? readFileSync(path)\n\t\t\t: undefined;\n\t// Why the highest gzip level: the build compresses each file once, and each response sends fewer bytes.\n\tconst gzip =\n\t\tbytes == null || bytes.byteLength < MIN_COMPRESS_BYTES\n\t\t\t? undefined\n\t\t\t: gzipSync(bytes, { level: constants.Z_BEST_COMPRESSION });\n\tconst gzipCopy =\n\t\tgzip != null && bytes != null && gzip.byteLength < bytes.byteLength ? gzip : undefined;\n\tconst brotli =\n\t\tgzipCopy == null || bytes == null\n\t\t\t? undefined\n\t\t\t: brotliCompressSync(bytes, {\n\t\t\t\t\tparams: {\n\t\t\t\t\t\t[constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_TEXT,\n\t\t\t\t\t\t[constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY,\n\t\t\t\t\t\t[constants.BROTLI_PARAM_SIZE_HINT]: bytes.byteLength,\n\t\t\t\t\t},\n\t\t\t\t});\n\tconst brotliCopy =\n\t\tbrotli != null && gzipCopy != null && brotli.byteLength < gzipCopy.byteLength\n\t\t\t? brotli\n\t\t\t: undefined;\n\tconst copies: readonly (readonly [Encoding, Uint8Array | undefined])[] = [\n\t\t[\"gzip\", gzipCopy],\n\t\t[\"br\", brotliCopy],\n\t];\n\tfor (const [encoding, copy] of copies) {\n\t\tconst copyPath = join(dirname(path), copyName(basename(path), encoding));\n\t\tif (copy == null) {\n\t\t\trmSync(copyPath, { force: true });\n\t\t} else {\n\t\t\twriteFileSync(copyPath, copy);\n\t\t}\n\t}\n}\n\n/**\n * Runs {@link writeCopies} for each file in the client build, except dotfiles\n * such as the copies, and except a link or a file in a linked directory. With `changedSince`, only for a file that changed at or\n * after that time, in milliseconds since the epoch.\n */\nfunction writeAllCopies(\n\tclientDirectory: string,\n\t{ changedSince }: { changedSince?: number } = {},\n): void {\n\tif (!existsSync(clientDirectory)) {\n\t\treturn;\n\t}\n\tfor (const path of filesInside(clientDirectory)) {\n\t\t// Why skip dotfiles: the server never sends one, such as `.app-server.json`.\n\t\tif (\n\t\t\t!basename(path).startsWith(\".\") &&\n\t\t\t(changedSince == null ||\n\t\t\t\t(statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? 0) >= changedSince)\n\t\t) {\n\t\t\twriteCopies(path);\n\t\t}\n\t}\n}\n\n/**\n * The path of each file under `directory`. Why not through a link: a copy goes\n * next to its file, so a file in a linked directory would get its copies in\n * the link's target, outside the client build.\n */\nfunction filesInside(directory: string): string[] {\n\treturn readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {\n\t\tconst path = join(directory, entry.name);\n\t\tif (entry.isDirectory()) {\n\t\t\treturn filesInside(path);\n\t\t}\n\t\treturn entry.isFile() ? [path] : [];\n\t});\n}\n\n/**\n * The Vite plugin for `@ngrok/app-server`. Put it next to the framework's\n * plugin.\n *\n * - It adds the server entry to the server build, such as\n * `build/server/app-server.js` on the node host. The entry bundles the app\n * (the default export of `app`) with the framework's server module, so the\n * server gets the app's path aliases and its one copy of the framework.\n * The framework's own entry does not change. When a runtime runs the entry\n * as its main module, the entry starts the server.\n * - In a build, it bundles each dependency into the server build. It copies\n * each package that stays external into `node_modules` in the server build.\n * So the build directory runs with no install.\n * - After the client build, it writes `.app-server.json` in the client\n * build with the build ID: a hash of the client bundle. After the build,\n * it adds the files that the server build wrote to the client's assets\n * directory, such as React Router's route manifest. The `buildId` plugin\n * sends the ID.\n * - During the framework's prerender pass, it records each prerendered path\n * and the headers of each prerendered file that is not an HTML document into\n * `.app-server.json` in the client build. The `prerendered` plugin replays\n * the headers. A document's headers depend on its request, so they are not\n * recorded.\n * - After the build and after the prerender pass, it records the hash of each\n * inline script of each HTML file in `.app-server.json`, for the\n * `contentSecurityPolicy` plugin. It also writes a gzip copy (`.<file>.gz`)\n * and a brotli copy (`.<file>.br`) next to each text file of 1 KiB or more\n * in the client build, HTML included. The static stages send a copy, so the\n * server does not compress these files for each request.\n *\n * @example\n * // vite.config.ts\n * export default defineConfig({ plugins: [reactRouter(), appServer()] });\n */\nexport function appServer(options: AppServerOptions = {}): Plugin[] {\n\tconst host = options.host ?? node();\n\t// Why one value: `configResolved` sets all three, so no hook sees a config with no framework.\n\tlet resolved:\n\t\t| { config: ResolvedConfig; framework: FrameworkBuild; appModule: string | undefined }\n\t\t| undefined;\n\tlet clientBuild: ClientBuild | undefined;\n\tconst copies: Plugin = {\n\t\tname: \"@ngrok/app-server:compressed-copies\",\n\t\t// Why last: the framework prerenders in a `buildApp` hook of an `enforce: \"post\"` plugin.\n\t\tenforce: \"post\",\n\t\tbuildApp: {\n\t\t\torder: \"post\",\n\t\t\thandler: async (builder) => {\n\t\t\t\tconst clientDirectory = outDir(builder.config, \"client\");\n\t\t\t\tcompleteBuildManifest(\n\t\t\t\t\tclientDirectory,\n\t\t\t\t\tclientBuild == null ? undefined : appBuildId(clientBuild),\n\t\t\t\t);\n\t\t\t\twriteAllCopies(clientDirectory);\n\t\t\t\thost.output?.(hostOutput(builder.config, host));\n\t\t\t},\n\t\t},\n\t};\n\tconst main: Plugin = {\n\t\tname: \"@ngrok/app-server\",\n\t\tconfigResolved: (config) => {\n\t\t\tconst framework = options.framework ?? detectFramework(config.plugins);\n\t\t\tframework.validate?.(config);\n\t\t\tresolved = {\n\t\t\t\tconfig,\n\t\t\t\tframework,\n\t\t\t\tappModule:\n\t\t\t\t\toptions.app == null ? defaultApp(config.root) : resolve(config.root, options.app),\n\t\t\t};\n\t\t},\n\t\tbuildStart() {\n\t\t\t// Why a chunk and not an input: the framework's own entry stays the same, and its prerender\n\t\t\t// preview reads that entry.\n\t\t\tif (isServerBuild(this.environment)) {\n\t\t\t\tthis.emitFile({ type: \"chunk\", id: SERVER_ENTRY_ID, fileName: host.entryFileName });\n\t\t\t}\n\t\t},\n\t\twriteBundle(output, bundle) {\n\t\t\tif (this.environment.name === \"client\") {\n\t\t\t\tconst directory = output.dir ?? outDir(this.environment.config, \"client\");\n\t\t\t\tconst assetsDirectory = join(directory, this.environment.config.build.assetsDir);\n\t\t\t\tclientBuild = {\n\t\t\t\t\tbundleId: bundleBuildId(bundle),\n\t\t\t\t\tassetsDirectory,\n\t\t\t\t\tassets: new Set(filesIn(assetsDirectory)),\n\t\t\t\t};\n\t\t\t\twriteBuildManifest(directory, {\n\t\t\t\t\tbuildId: clientBuild.bundleId,\n\t\t\t\t\tassetsPath: urlPathOfAssetsDir(this.environment.config.build.assetsDir),\n\t\t\t\t\tprerendered: [],\n\t\t\t\t\theaders: {},\n\t\t\t\t\tscriptHashes: {},\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\trenderStart(output) {\n\t\t\t// Why: the server entry uses `import.meta.url`, and the CLI loads it as an ES module.\n\t\t\tif (this.environment.name === SERVER_ENVIRONMENT && output.format !== \"es\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`@ngrok/app-server needs an ES module server build, and this build has the format \"${output.format}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t\tresolveId: (id) => (id === SERVER_ENTRY_ID ? RESOLVED_SERVER_ENTRY_ID : undefined),\n\t\tload(id) {\n\t\t\tif (id !== RESOLVED_SERVER_ENTRY_ID || resolved == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst { config, framework, appModule } = resolved;\n\t\t\tconst clientDirectory = outDir(config, \"client\");\n\t\t\tconst serverDirectory = outDir(config, SERVER_ENVIRONMENT);\n\t\t\tconst fromClient = relative(clientDirectory, serverDirectory);\n\t\t\t// Why: the static stages serve each file in the client build, so they would serve the server's\n\t\t\t// code. Why a build only: development serves no build directory.\n\t\t\tif (\n\t\t\t\tthis.environment.mode === \"build\" &&\n\t\t\t\t!fromClient.startsWith(\"..\") &&\n\t\t\t\t!isAbsolute(fromClient)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`@ngrok/app-server needs the server build outside the client build, and both are in ${clientDirectory}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Why a URL in a build: the build can move, and the client build stays next to it.\n\t\t\tconst fromEntry = relative(\n\t\t\t\tdirname(join(serverDirectory, host.entryFileName)),\n\t\t\t\tclientDirectory,\n\t\t\t).replaceAll(\"\\\\\", \"/\");\n\t\t\treturn serverEntrySource({\n\t\t\t\tframework,\n\t\t\t\thost,\n\t\t\t\tappModule,\n\t\t\t\tclientDirectory:\n\t\t\t\t\tthis.environment.mode === \"build\"\n\t\t\t\t\t\t? `new URL(${JSON.stringify(`${fromEntry}/`)}, import.meta.url).href`\n\t\t\t\t\t\t: JSON.stringify(clientDirectory),\n\t\t\t});\n\t\t},\n\t\tconfigurePreviewServer: (server) => {\n\t\t\tif (resolved?.framework.isPrerenderPass(server) === true) {\n\t\t\t\t// Why the preview's config: the framework starts the preview with a new instance of this plugin.\n\t\t\t\tcapture(server, () => host.output?.(hostOutput(server.config, host)));\n\t\t\t}\n\t\t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,IAAI,UAAU,UAAU,gBAAgB,MAAM,MAAM,MAEnD,QAAQ,cAAc,KAAK,SAAS,WAAW,OAAO,QAAQ,IAAI,CAAC,CAAC;GAEtE;EAEU;EAAG;GAvGb,MAAM;GAEN,SAAS;GACT,UAAU;IACT,OAAO;IACP,SAAS,OAAO,YAAY;KAC3B,MAAM,kBAAkB,OAAO,QAAQ,QAAQ,QAAQ;KACvD,sBACC,iBACA,eAAe,OAAO,SAAY,WAAW,WAAW,CACzD;KACA,eAAe,eAAe;KAC9B,KAAK,SAAS,WAAW,QAAQ,QAAQ,IAAI,CAAC;IAC/C;GACD;EAyFkB;EAAG,WAAW;CAAC;AACnC"}
package/dist/vite.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as SERVER_ENTRY_ID, i as HostOutput, n as FrameworkBuild, o as appServer, r as HostBuild, s as serverEntrySource, t as AppServerOptions } from "./index-Bo5G9LuQ.js";
1
+ import { a as SERVER_ENTRY_ID, i as HostOutput, n as FrameworkBuild, o as appServer, r as HostBuild, s as serverEntrySource, t as AppServerOptions } from "./index-Db7dspq6.js";
2
2
  export { AppServerOptions, FrameworkBuild, HostBuild, HostOutput, SERVER_ENTRY_ID, appServer, serverEntrySource };
package/dist/vite.js CHANGED
@@ -1,3 +1,3 @@
1
- import { n as appServer, r as serverEntrySource, t as SERVER_ENTRY_ID } from "./vite-iioAoxSt.js";
1
+ import { n as appServer, r as serverEntrySource, t as SERVER_ENTRY_ID } from "./vite-BDREIgiH.js";
2
2
 
3
3
  export { SERVER_ENTRY_ID, appServer, serverEntrySource };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngrok/app-server",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "A composable Hono app server for React Router and TanStack Start: prerendered pages, streamed compression, structured logs, and clean shutdown on Node, Bun, Deno, and Vercel.",
5
5
  "homepage": "https://github.com/ngrok/app-server#readme",
6
6
  "bugs": {
@@ -62,6 +62,10 @@
62
62
  "types": "./dist/vercel-vite.d.ts",
63
63
  "import": "./dist/vercel-vite.js"
64
64
  },
65
+ "./testing": {
66
+ "types": "./dist/testing.d.ts",
67
+ "import": "./dist/testing.js"
68
+ },
65
69
  "./vite": {
66
70
  "types": "./dist/vite.d.ts",
67
71
  "import": "./dist/vite.js"
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-id-C6sYO9Yp.js","names":[],"sources":["../src/core/plugin-options.ts","../src/core/plugins/build-id.ts"],"sourcesContent":["import type { Plugin } from \"./types.js\";\n\n/**\n * The option of `defaultPlugins()` that places each plugin, by plugin\n * object. Why the object, not the name: an app plugin can have any name.\n */\nconst options = new WeakMap<Plugin, string>();\n\n/**\n * Marks `plugin` as the plugin of the `option` of `defaultPlugins()`, so\n * `createServer` finds it in the plugin list.\n *\n * @example\n * return optionPlugin(\"noindex\", { name: \"noindex\", middleware });\n */\nexport function optionPlugin<P extends Plugin>(option: string, plugin: P): P {\n\toptions.set(plugin, option);\n\treturn plugin;\n}\n\n/**\n * Stops startup when `plugins` has two plugins of one option of\n * `defaultPlugins()`, such as two `buildId()`. Why: two copies do not fail.\n * One sets its headers over the other, so a value that the app gave is lost.\n *\n * @example\n * checkOptionPlugins([...defaultPlugins(), buildId({ value: \"v42\" })]); // throws\n */\nexport function checkOptionPlugins(plugins: readonly Plugin[]): void {\n\tconst seen = new Set<string>();\n\tfor (const plugin of plugins) {\n\t\tconst option = options.get(plugin);\n\t\tif (option != null && seen.has(option)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The plugin list has the ${plugin.name} plugin two times, so one replaces the other. Keep one: set the \"${option}\" option of defaultPlugins(), and do not also add the plugin.`,\n\t\t\t);\n\t\t}\n\t\tif (option != null) {\n\t\t\tseen.add(option);\n\t\t}\n\t}\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport type { Plugin, ResponseHeaders, SetupInfo } from \"../types.js\";\n\n/** The header that {@link buildId} sets by default. */\nexport const BUILD_ID_HEADER = \"X-Build-Id\";\n\n/**\n * The `Server-Timing` metric that holds the build of a response. Why\n * `Server-Timing`: a script can read it from the performance entries, with no\n * request and no change to the document's HTML.\n */\nexport const BUILD_ID_METRIC = \"build\";\n\n/** Options for {@link buildId}. */\nexport type BuildIdOptions = {\n\t/** @default \"X-Build-Id\" */\n\theader?: string;\n\t/**\n\t * The deployed build, such as the image tag. With no value or `\"\"`, the\n\t * plugin sends the ID that the `appServer` Vite plugin derives from the\n\t * client build. In development, it then sends no build.\n\t * @default the `buildId` of `.app-server.json` in the client build\n\t */\n\tvalue?: string | undefined;\n\t/**\n\t * More request paths whose responses carry the build in `Server-Timing`,\n\t * such as the app's proxy routes to its API. A tab then finds a new build\n\t * in the requests that it already sends. They get no build header, because\n\t * the header marks the router's own responses. A response that a cache can\n\t * use again without the server gets no build, so a cached copy never\n\t * reports an old build. It runs in a header hook, so it can run more than\n\t * once for one request.\n\t *\n\t * @example\n\t * buildId({ paths: (path) => path.startsWith(\"/api/\") });\n\t */\n\tpaths?: (path: string) => boolean;\n};\n\n/**\n * Whether a cache can use the response again without the server: it has a\n * fresh time, a stale time, or a date that a cache can guess a fresh time from.\n */\nfunction isReusable(response: ResponseHeaders): boolean {\n\tconst cacheControl = response.get(\"Cache-Control\") ?? \"\";\n\tif (/\\b(?:no-store|no-cache)\\b/iu.test(cacheControl)) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t/\\b(?:max-age|s-maxage|stale-while-revalidate|stale-if-error)\\s*=\\s*\"?0*[1-9]/iu.test(\n\t\t\tcacheControl,\n\t\t) ||\n\t\t/\\bpublic\\b/iu.test(cacheControl) ||\n\t\tDate.parse(response.get(\"Expires\") ?? \"\") > Date.now() ||\n\t\tresponse.has(\"Last-Modified\")\n\t);\n}\n\n/** The metrics of a `Server-Timing` header, such as `build;desc=\"v42\"`. */\nexport function serverTimingMetrics(header: string | null): string[] {\n\t// Why match the quoted strings: a comma or an escaped quote in a description does not end a metric.\n\treturn (header?.match(/(?:[^\",]|\"(?:[^\"\\\\]|\\\\.)*\")+/gu) ?? [])\n\t\t.map((metric) => metric.trim())\n\t\t.filter((metric) => metric !== \"\");\n}\n\n/** Whether a `Server-Timing` metric is a build. */\nexport function isBuildMetric(metric: string): boolean {\n\treturn metric.split(\";\")[0]?.trim().toLowerCase() === BUILD_ID_METRIC;\n}\n\n/** The `Server-Timing` metrics of `header` that are not a build. */\nfunction otherMetrics(header: string | null): string[] {\n\treturn serverTimingMetrics(header).filter((metric) => !isBuildMetric(metric));\n}\n\n/** The data check before `setup` runs. */\nfunction noDataRequests(): boolean {\n\treturn false;\n}\n\n/** A `Server-Timing` quoted string with the characters of `value`. */\nfunction quoted(value: string): string {\n\treturn `\"${value.replaceAll(/[\"\\\\]/gu, String.raw`\\$&`)}\"`;\n}\n\n/** The `build` metric of `value`, or `undefined` for no build. */\nfunction buildMetric(value: string | undefined): string | undefined {\n\treturn value == null ? undefined : `${BUILD_ID_METRIC};desc=${quoted(value)}`;\n}\n\n/**\n * Sets a build ID header on documents and on the framework's data responses,\n * such as React Router `.data` files, so a client can see that a deploy\n * happened under it. Each of them also gets the build as\n * `Server-Timing: build;desc=\"<value>\"`. The `paths` option adds the metric\n * to more routes, such as API proxy routes. The plugin removes the build\n * header and the `build` metric of an upstream API from each other\n * response, so the client reads only this app's build.\n * `staleBuildReactRouter()` and `staleBuildTanStack()` from `@ngrok/app-server/client` read the metric\n * from the document, and from a response that the browser fetches with no\n * script, such as a prefetch.\n *\n * With no `value`, it sends the build ID that the `appServer` Vite plugin\n * derives from the client build. Development and a build with no\n * `.app-server.json` then get no build.\n *\n * @example\n * buildId({ value: process.env.IMAGE_TAG });\n */\nexport function buildId({\n\theader = BUILD_ID_HEADER,\n\tvalue: given,\n\tpaths,\n}: BuildIdOptions = {}): Plugin {\n\t// Why `\"\"` too: a deploy can set the variable with no value, such as `IMAGE_TAG=`.\n\tconst explicit = given === \"\" ? undefined : given;\n\tlet value = explicit;\n\tlet timing = buildMetric(value);\n\tlet isDataRequest: SetupInfo[\"isDataRequest\"] = noDataRequests;\n\treturn optionPlugin(\"buildId\", {\n\t\tname: \"build-id\",\n\t\tsetup: (info) => {\n\t\t\t({ isDataRequest } = info);\n\t\t\tvalue = explicit ?? info.buildId;\n\t\t\ttiming = buildMetric(value);\n\t\t},\n\t\t// Why: a 304 has no `Content-Type`, so a document that did not change on disk must still\n\t\t// answer 200 when the build ID changes.\n\t\tetagPart: () => value,\n\t\tmiddleware: async (context, next) =>\n\t\t\twithHeaderHook(context, next, (response) => {\n\t\t\t\tconst { path } = context.req;\n\t\t\t\tconst isRouter =\n\t\t\t\t\t(response.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false) || isDataRequest(path);\n\t\t\t\tconst isStamped = isRouter || (paths?.(path) === true && !isReusable(response));\n\t\t\t\t// Why remove the build of an upstream API: the client must read only this app's build.\n\t\t\t\tconst before = response.get(\"Server-Timing\");\n\t\t\t\tconst metrics = [\n\t\t\t\t\t...otherMetrics(before),\n\t\t\t\t\t...(isStamped && timing != null ? [timing] : []),\n\t\t\t\t].join(\", \");\n\t\t\t\tif (metrics === \"\") {\n\t\t\t\t\tresponse.delete(\"Server-Timing\");\n\t\t\t\t} else if (metrics !== before) {\n\t\t\t\t\tresponse.set(\"Server-Timing\", metrics);\n\t\t\t\t}\n\t\t\t\tif (isRouter && value != null) {\n\t\t\t\t\tresponse.set(header, value);\n\t\t\t\t} else {\n\t\t\t\t\tresponse.delete(header);\n\t\t\t\t}\n\t\t\t}),\n\t});\n}\n"],"mappings":";;;;;;;AAMA,MAAM,0BAAU,IAAI,QAAwB;;;;;;;;AAS5C,SAAgB,aAA+B,QAAgB,QAAc;CAC5E,QAAQ,IAAI,QAAQ,MAAM;CAC1B,OAAO;AACR;;;;;;;;;AAUA,SAAgB,mBAAmB,SAAkC;CACpE,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,UAAU,SAAS;EAC7B,MAAM,SAAS,QAAQ,IAAI,MAAM;EAC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C5C,IAAI,QAAQ;CACZ,IAAI,SAAS,YAAY,KAAK;CAC9B,IAAI,gBAA4C;CAChD,OAAO,aAAa,WAAW;EAC9B,MAAM;EACN,QAAQ,SAAS;GAChB,CAAC,CAAE,iBAAkB;GACrB,QAAQ,YAAY,KAAK;GACzB,SAAS,YAAY,KAAK;EAC3B;EAGA,gBAAgB;EAChB,YAAY,OAAO,SAAS,SAC3B,eAAe,SAAS,OAAO,aAAa;GAC3C,MAAM,EAAE,SAAS,QAAQ;GACzB,MAAM,YACJ,SAAS,IAAI,cAAc,CAAC,EAAE,WAAW,WAAW,KAAK,UAAU,cAAc,IAAI;GACvF,MAAM,YAAY,YAAa,QAAQ,IAAI,MAAM,QAAQ,CAAC,WAAW,QAAQ;GAE7E,MAAM,SAAS,SAAS,IAAI,eAAe;GAC3C,MAAM,UAAU,CACf,GAAG,aAAa,MAAM,GACtB,GAAI,aAAa,UAAU,OAAO,CAAC,MAAM,IAAI,CAAC,CAC/C,CAAC,CAAC,KAAK,IAAI;GACX,IAAI,YAAY,IACf,SAAS,OAAO,eAAe;QACzB,IAAI,YAAY,QACtB,SAAS,IAAI,iBAAiB,OAAO;GAEtC,IAAI,YAAY,SAAS,MACxB,SAAS,IAAI,QAAQ,KAAK;QAE1B,SAAS,OAAO,MAAM;EAExB,CAAC;CACH,CAAC;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-manifest-UDNk81Ce.js","names":[],"sources":["../src/core/build-manifest.ts"],"sourcesContent":["import type { StaticFiles } from \"./types.js\";\n\n/**\n * The file under the client build that the Vite plugin writes after the\n * client build and again after the prerender pass. It is a dotfile, so the\n * static stages never serve it.\n */\nexport const BUILD_MANIFEST_FILE = \".app-server.json\";\n\n/** What the Vite plugin records about the client build. */\nexport type BuildManifest = {\n\t/**\n\t * The ID of the client build: a hash of the files that the client build\n\t * writes. The `buildId` plugin sends it by default.\n\t */\n\tbuildId?: string;\n\t/** The URL paths that answered with a 2xx, sorted. */\n\tprerendered: string[];\n\t/** The headers of each prerendered file that is not an HTML document, by URL path. */\n\theaders: Record<string, Record<string, string>>;\n\t/**\n\t * The base64 `SHA-256` of each inline script of each HTML file in the client\n\t * build, by the file's URL path, such as `/about/index.html`. A CSP trusts\n\t * the scripts of a prerendered page by these hashes.\n\t */\n\tscriptHashes: Record<string, string[]>;\n};\n\n/**\n * The key for a URL path in {@link BuildManifest}: the path with no trailing\n * slash, so `/a/` and `/a` share headers. The root stays `/`.\n *\n * @example\n * manifestKey(\"/components/button/\"); // => \"/components/button\"\n */\nexport function manifestKey(pathname: string): string {\n\tconst trimmed = pathname.replace(/\\/+$/u, \"\");\n\treturn trimmed === \"\" ? \"/\" : trimmed;\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t!Array.isArray(value) &&\n\t\tObject.values(value).every((entry) => typeof entry === \"string\")\n\t);\n}\n\nfunction isStringList(value: unknown): value is string[] {\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n\n/** The `buildId` of a parsed manifest, which can have none. A value that is not a string throws. */\nfunction buildIdOf(manifest: object): Pick<BuildManifest, \"buildId\"> {\n\tif (!(\"buildId\" in manifest)) {\n\t\treturn {};\n\t}\n\tif (typeof manifest.buildId !== \"string\") {\n\t\tthrow new TypeError(`${BUILD_MANIFEST_FILE}: the \"buildId\" must be a string.`);\n\t}\n\treturn { buildId: manifest.buildId };\n}\n\n/**\n * Reads the build manifest of a client build. A build with no file has an\n * empty one. A file in any other shape throws, so a bad build stops startup.\n */\nexport async function readBuildManifest(files: StaticFiles): Promise<BuildManifest> {\n\tconst path = `/${BUILD_MANIFEST_FILE}`;\n\tif ((await files.stat(path))?.kind !== \"file\") {\n\t\treturn { prerendered: [], headers: {}, scriptHashes: {} };\n\t}\n\tconst parsed: unknown = await new Response(await files.open(path)).json();\n\tif (\n\t\ttypeof parsed !== \"object\" ||\n\t\tparsed == null ||\n\t\t!(\"prerendered\" in parsed) ||\n\t\t!isStringList(parsed.prerendered) ||\n\t\t!(\"headers\" in parsed) ||\n\t\ttypeof parsed.headers !== \"object\" ||\n\t\tparsed.headers == null ||\n\t\t!(\"scriptHashes\" in parsed) ||\n\t\ttypeof parsed.scriptHashes !== \"object\" ||\n\t\tparsed.scriptHashes == null\n\t) {\n\t\tthrow new Error(\n\t\t\t`${BUILD_MANIFEST_FILE} must hold a \"prerendered\" list and the \"headers\" and \"scriptHashes\" objects.`,\n\t\t);\n\t}\n\tconst headers: Record<string, Record<string, string>> = {};\n\tfor (const [key, value] of Object.entries(parsed.headers)) {\n\t\tif (!isStringRecord(value)) {\n\t\t\tthrow new Error(`${BUILD_MANIFEST_FILE}: the headers for ${key} must be strings.`);\n\t\t}\n\t\theaders[key] = value;\n\t}\n\tconst scriptHashes: Record<string, string[]> = {};\n\tfor (const [key, value] of Object.entries(parsed.scriptHashes)) {\n\t\tif (!isStringList(value)) {\n\t\t\tthrow new Error(`${BUILD_MANIFEST_FILE}: the script hashes for ${key} must be strings.`);\n\t\t}\n\t\tscriptHashes[key] = value;\n\t}\n\treturn {\n\t\t...buildIdOf(parsed),\n\t\tprerendered: parsed.prerendered,\n\t\theaders,\n\t\tscriptHashes,\n\t};\n}\n"],"mappings":";;;;;;AAOA,MAAa,sBAAsB;;;;;;;;AA4BnC,SAAgB,YAAY,UAA0B;CACrD,MAAM,UAAU,SAAS,QAAQ,SAAS,EAAE;CAC5C,OAAO,YAAY,KAAK,MAAM;AAC/B;AAEA,SAAS,eAAe,OAAiD;CACxE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,CAAC,MAAM,QAAQ,KAAK,KACpB,OAAO,OAAO,KAAK,CAAC,CAAC,OAAO,UAAU,OAAO,UAAU,QAAQ;AAEjE;AAEA,SAAS,aAAa,OAAmC;CACxD,OAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,UAAU,OAAO,UAAU,QAAQ;AAChF;;AAGA,SAAS,UAAU,UAAkD;CAC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js","names":["isFilePath"],"sources":["../src/core/plugins/access-log.ts","../src/core/plugins/body-limit.ts","../src/core/shutdown.ts","../src/core/plugins/health.ts","../src/core/plugins/noindex.ts","../src/core/plugins/private-documents.ts","../src/core/safe-local-path.ts","../src/core/plugins/trailing-slash.ts","../src/core/plugins/redirects.ts","../src/core/plugins/security-headers.ts","../src/core/plugins/request-id.ts","../src/core/prefers-markdown.ts","../src/core/plugins/static.ts","../src/core/plugins/streaming-compress.ts","../src/core/create-server.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport { withHeaderHook } from \"../header-hook.js\";\nimport { errorAttributes } from \"../log.js\";\nimport { onResponseSent } from \"../response-edge.js\";\nimport type { AppServerEnv, Plugin, SentResponse } from \"../types.js\";\n\n/** Options for {@link accessLog}. */\nexport type AccessLogOptions = {\n\t/**\n\t * Replace each query value with `REDACTED`, so a single-use code in a URL\n\t * never reaches a log.\n\t * @default true\n\t */\n\tredactQuery?: boolean;\n\t/**\n\t * More attributes for each request line, such as the app's user ID. It\n\t * runs when the line goes out, with what went out. Read a response header\n\t * from `sent.headers`, not from `c.res`, which can lack the changes of the\n\t * header hooks.\n\t */\n\tattributes?: (\n\t\tcontext: Context<AppServerEnv>,\n\t\tsent: SentResponse,\n\t) => Readonly<Record<string, unknown>>;\n\t/**\n\t * Set `Server-Timing: app;dur=<ms>` on each HTML document: the time until\n\t * the response headers were ready. The browser's DevTools show it.\n\t * @default false\n\t */\n\tserverTiming?: boolean;\n};\n\n/**\n * A URL's path and query, with each query value replaced when `redact` is set.\n *\n * @example\n * loggedUrl(new URL(\"https://example.com/verify?code=123\"), { redact: true }); // => \"/verify?code=REDACTED\"\n */\nexport function loggedUrl(url: URL, { redact }: { redact: boolean }): string {\n\tif (!redact || url.search === \"\") {\n\t\treturn `${url.pathname}${url.search}`;\n\t}\n\tconst query = [...url.searchParams.keys()]\n\t\t.map((key) => `${encodeURIComponent(key)}=REDACTED`)\n\t\t.join(\"&\");\n\treturn `${url.pathname}?${query}`;\n}\n\n/** A `Referer` with its query redacted like {@link loggedUrl}. A value that is not a URL is dropped. */\nfunction loggedReferer(referer: string | undefined, { redact }: { redact: boolean }) {\n\tif (referer == null || !redact) {\n\t\treturn referer;\n\t}\n\tconst url = URL.parse(referer);\n\treturn url == null ? undefined : `${url.origin}${loggedUrl(url, { redact })}`;\n}\n\n/**\n * One log line per request, static hits included, with Datadog standard\n * attribute names. The line goes out when the response ends or the client\n * disconnects, so a streamed response logs its full duration and size. It\n * logs the response that leaves the server, after each stage. A listener\n * with an `edge`, such as the node listener, counts the bytes.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });\n * // {\"level\":\"info\",\"message\":\"request\",\"http.status_code\":200,\"network.bytes_written\":5120,\"duration\":1830000,...}\n */\nexport function accessLog({\n\tredactQuery = true,\n\tattributes,\n\tserverTiming = false,\n}: AccessLogOptions = {}): Plugin {\n\treturn {\n\t\tname: \"access-log\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst started = performance.now();\n\t\t\t// Why a hook: it runs when the head is ready, which is the time that the header gives.\n\t\t\tawait (serverTiming\n\t\t\t\t? withHeaderHook(context, next, (headers) => {\n\t\t\t\t\t\tif (headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false) {\n\t\t\t\t\t\t\theaders.append(\n\t\t\t\t\t\t\t\t\"Server-Timing\",\n\t\t\t\t\t\t\t\t`app;dur=${(performance.now() - started).toFixed(1)}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t: next());\n\t\t\t// Why a catch: a log line must never change the response or stop its stream. The listener can\n\t\t\t// call the report from an event of its socket, where a throw stops the process.\n\t\t\tonResponseSent(context, (sent) => {\n\t\t\t\tconst line = lineAttributes(context, sent, started);\n\t\t\t\ttry {\n\t\t\t\t\tcontext\n\t\t\t\t\t\t.get(\"logger\")\n\t\t\t\t\t\t.info(\"request\", attributes == null ? line : { ...line, ...attributes(context, sent) });\n\t\t\t\t} catch (error) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcontext.get(\"logger\").error(\"access log attributes failed\", {\n\t\t\t\t\t\t\t...line,\n\t\t\t\t\t\t\t...errorAttributes(error),\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Why drop it: the sink failed twice, so no line can go out.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t};\n\n\t/** `href` as {@link loggedUrl} logs it. */\n\tfunction requestUrl(href: string): string {\n\t\tconst start = href.indexOf(\"/\", href.indexOf(\"//\") + 2);\n\t\t// Why no parse for a path alone: a request URL is the `href` of a parsed URL, or one that the\n\t\t// Node.js listener checked holds no character that a parse changes. So its path is the `pathname`.\n\t\tif (start !== -1 && !href.includes(\"?\", start) && !href.includes(\"#\", start)) {\n\t\t\treturn href.slice(start);\n\t\t}\n\t\treturn loggedUrl(new URL(href), { redact: redactQuery });\n\t}\n\n\tfunction lineAttributes(\n\t\tcontext: Context<AppServerEnv>,\n\t\t{ status, bytes, aborted }: SentResponse,\n\t\tstarted: number,\n\t): Record<string, unknown> {\n\t\tconst line: Record<string, unknown> = {\n\t\t\t\"http.url\": requestUrl(context.req.url),\n\t\t\t\"http.status_code\": status,\n\t\t\t\"http.useragent\": context.req.header(\"User-Agent\"),\n\t\t\t\"http.referer\": loggedReferer(context.req.header(\"Referer\"), { redact: redactQuery }),\n\t\t\t\"network.client.ip\": context.get(\"clientAddress\"),\n\t\t\t\"network.bytes_written\": bytes,\n\t\t\t// Why nanoseconds: Datadog's standard `duration` attribute is in nanoseconds.\n\t\t\tduration: Math.round((performance.now() - started) * 1_000_000),\n\t\t};\n\t\tif (aborted) {\n\t\t\tline[\"http.client_aborted\"] = true;\n\t\t}\n\t\treturn line;\n\t}\n}\n","import { HTTPException } from \"hono/http-exception\";\nimport { replaceResponse } from \"../header-hook.js\";\nimport type { Plugin } from \"../types.js\";\n\n// Why: GET and HEAD have no body, and the Fetch `Request` constructor rejects the other three.\nconst NO_BODY_METHODS = new Set([\"GET\", \"HEAD\", \"CONNECT\", \"TRACE\", \"TRACK\"]);\n\n/** Options for {@link bodyLimit}. */\nexport type BodyLimitOptions = {\n\t/** The largest request body, in bytes. */\n\tmaxBytes: number;\n};\n\n/** The 413 response. */\nfunction tooLarge(): Response {\n\treturn new Response(\"Payload Too Large\", { status: 413 });\n}\n\n/**\n * Sends a 413 for a request body that is larger than `maxBytes`. A request\n * whose `Content-Length` is too large gets the 413 before the app reads the\n * body, and a request whose `Content-Length` fits goes on unchanged. A\n * streamed body with no `Content-Length` errors when it passes the limit. When the app reads the body before it answers, the response\n * becomes a 413. When the app streams the body into its response, the\n * response stream errors. A `maxBytes` that is not a whole number of 0 or\n * more stops startup.\n *\n * Why not `hono/body-limit`: it reads a streamed body into memory before the\n * next stage runs, so an upload cannot stream.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), bodyLimit({ maxBytes: 1_048_576 })] });\n */\nexport function bodyLimit({ maxBytes }: BodyLimitOptions): Plugin {\n\tif (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {\n\t\tthrow new RangeError(`bodyLimit needs a maxBytes of 0 or more whole bytes, not ${maxBytes}.`);\n\t}\n\treturn {\n\t\tname: \"body-limit\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst { raw } = context.req;\n\t\t\tif (NO_BODY_METHODS.has(raw.method)) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tconst length = context.req.header(\"Content-Length\");\n\t\t\t// Why no stream count: the host's HTTP parser ends the body at its `Content-Length`. The\n\t\t\t// original request also keeps the fast body reads of `@hono/node-server`.\n\t\t\tif (\n\t\t\t\tlength != null &&\n\t\t\t\t/^\\d+$/u.test(length) &&\n\t\t\t\tcontext.req.header(\"Transfer-Encoding\") == null\n\t\t\t) {\n\t\t\t\treturn Number(length) > maxBytes ? tooLarge() : next();\n\t\t\t}\n\t\t\tlet bytes = 0;\n\t\t\tlet exceeded = false;\n\t\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\t\t\tconst limited = new ReadableStream<Uint8Array>(\n\t\t\t\t{\n\t\t\t\t\tasync pull(controller) {\n\t\t\t\t\t\t// Why on the first read: on Node, `raw.body` starts to read the socket, and a dev\n\t\t\t\t\t\t// server middleware that answers the request reads it there.\n\t\t\t\t\t\treader ??= raw.body?.getReader();\n\t\t\t\t\t\tconst chunk = await reader?.read();\n\t\t\t\t\t\tif (chunk == null || chunk.done) {\n\t\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbytes += chunk.value.byteLength;\n\t\t\t\t\t\tif (bytes > maxBytes) {\n\t\t\t\t\t\t\texceeded = true;\n\t\t\t\t\t\t\t// Why an `HTTPException`: `onError` sends its 413 and logs no error.\n\t\t\t\t\t\t\tcontroller.error(\n\t\t\t\t\t\t\t\tnew HTTPException(413, {\n\t\t\t\t\t\t\t\t\tmessage: \"The request body is larger than the body limit.\",\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait reader?.cancel();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontroller.enqueue(chunk.value);\n\t\t\t\t\t},\n\t\t\t\t\t// Why `raw.body`: if the app cancels before its first read, no reader exists yet.\n\t\t\t\t\tcancel: async (reason) => (reader ?? raw.body)?.cancel(reason),\n\t\t\t\t},\n\t\t\t\t// Why 0: the stream reads nothing until the app reads it.\n\t\t\t\t{ highWaterMark: 0 },\n\t\t\t);\n\t\t\t// Why a new request from its parts: `new Request(raw)` reads `raw.body` on Node. `duplex`: a\n\t\t\t// request with a stream body needs it, and the DOM types lack it.\n\t\t\tconst init: RequestInit & { duplex: \"half\" } = {\n\t\t\t\tmethod: raw.method,\n\t\t\t\theaders: raw.headers,\n\t\t\t\tsignal: raw.signal,\n\t\t\t\tbody: limited,\n\t\t\t\tduplex: \"half\",\n\t\t\t};\n\t\t\tcontext.req.raw = new Request(raw.url, init);\n\t\t\tawait next();\n\t\t\tif (exceeded) {\n\t\t\t\tawait context.res.body?.cancel();\n\t\t\t\treplaceResponse(context, tooLarge());\n\t\t\t}\n\t\t},\n\t};\n}\n","let controller = new AbortController();\nlet stopping = false;\n\n/**\n * A signal that aborts when the server starts to shut down. Read it for each\n * request: each start of a server makes a new one. A handler that\n * holds a response open, such as an event stream, stops on it so that the\n * drain does not wait for the deadline.\n *\n * @example\n * const timer = setInterval(sendUpdate, 1_000);\n * shutdownSignal().addEventListener(\"abort\", () => clearInterval(timer), { once: true });\n */\nexport function shutdownSignal(): AbortSignal {\n\treturn controller.signal;\n}\n\n/** Replaces {@link shutdownSignal} with a new one that has not aborted, and clears {@link isStopping}. */\nexport function renewShutdownSignal(): void {\n\tcontroller = new AbortController();\n\tstopping = false;\n}\n\n/** Marks the server as stopping, before the shutdown delay and the drain. */\nexport function markStopping(): void {\n\tstopping = true;\n}\n\n/** Whether the server got a stop signal. It is true during the shutdown delay, before {@link shutdownSignal} aborts. */\nexport function isStopping(): boolean {\n\treturn stopping;\n}\n\n/** Aborts {@link shutdownSignal}. */\nexport function abortShutdownSignal(): void {\n\tcontroller.abort();\n}\n","import { errorAttributes } from \"../log.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport { isStopping } from \"../shutdown.js\";\nimport type { Plugin, RequestLogger } from \"../types.js\";\n\n/** Options for {@link health}. */\nexport type HealthOptions = {\n\t/** @default \"/livez\" */\n\tlivePath?: string;\n\t/** @default \"/readyz\" */\n\treadyPath?: string;\n\t/**\n\t * An app check for readiness, such as a database ping. A `false` or a\n\t * throw makes the server not ready. When the check starts to fail, one\n\t * warn line goes to the log, and when it passes again, one info line.\n\t */\n\tready?: () => boolean | Promise<boolean>;\n};\n\n/** A probe answer that no cache keeps. */\nfunction probe(text: string, status: 200 | 503): Response {\n\treturn new Response(text, {\n\t\tstatus,\n\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\", \"Cache-Control\": \"no-store\" },\n\t});\n}\n\n/**\n * Answers the liveness and readiness probes of a load balancer or\n * Kubernetes. `livePath` always answers 200. `readyPath` answers 200 until\n * the server gets a stop signal, then 503. With `shutdownDelayMs` on\n * `createServer`, the listeners serve on for that time, so the load\n * balancer removes the server before the drain starts.\n *\n * `defaultPlugins()` runs it first, so a probe skips the access log. Its\n * `health` option takes these options, and `false` turns it off.\n *\n * @example\n * createServer({\n * \tplugins: defaultPlugins({ health: { ready: async () => db.ping() } }),\n * \tshutdownDelayMs: 5_000,\n * });\n */\nexport function health({\n\tlivePath = \"/livez\",\n\treadyPath = \"/readyz\",\n\tready,\n}: HealthOptions = {}): Plugin {\n\t// Why log on a change only: a probe comes every few seconds.\n\tlet appFailing = false;\n\tconst appCheck = async (logger: RequestLogger): Promise<boolean> => {\n\t\tif (ready == null) {\n\t\t\treturn true;\n\t\t}\n\t\tlet passed = false;\n\t\tlet failure: Record<string, unknown> = {};\n\t\ttry {\n\t\t\tpassed = await ready();\n\t\t} catch (error) {\n\t\t\tfailure = errorAttributes(error);\n\t\t}\n\t\tif (!passed && !appFailing) {\n\t\t\tlogger.warn(\"readiness check failed\", failure);\n\t\t} else if (passed && appFailing) {\n\t\t\tlogger.info(\"readiness check passed\");\n\t\t}\n\t\tappFailing = !passed;\n\t\treturn passed;\n\t};\n\tconst isReady = async (logger: RequestLogger) => {\n\t\tif (isStopping()) {\n\t\t\treturn false;\n\t\t}\n\t\tconst appReady = await appCheck(logger);\n\t\t// Why check again: a stop signal can come while the app check runs.\n\t\treturn appReady && !isStopping();\n\t};\n\treturn optionPlugin(\"health\", {\n\t\tname: \"health\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst { method, path } = context.req;\n\t\t\tif (method !== \"GET\" && method !== \"HEAD\") {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tif (path === livePath) {\n\t\t\t\treturn probe(\"ok\", 200);\n\t\t\t}\n\t\t\tif (path === readyPath) {\n\t\t\t\treturn (await isReady(context.get(\"logger\"))) ? probe(\"ok\", 200) : probe(\"not ready\", 503);\n\t\t\t}\n\t\t\treturn next();\n\t\t},\n\t});\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport type { Plugin } from \"../types.js\";\n\n/**\n * Sets `X-Robots-Tag: noindex, nofollow` on each response, so a search\n * engine does not index a preview deploy. Turn it on from the environment\n * with the `noindex` option of `defaultPlugins()`, which puts it before the\n * static stages, so it also sees prerendered pages.\n *\n * @example\n * defaultPlugins({ noindex: process.env.PREVIEW === \"1\" });\n */\nexport function noindex(): Plugin {\n\treturn optionPlugin(\"noindex\", {\n\t\tname: \"noindex\",\n\t\tmiddleware: async (context, next) =>\n\t\t\twithHeaderHook(context, next, (response) => {\n\t\t\t\tresponse.set(\"X-Robots-Tag\", \"noindex, nofollow\");\n\t\t\t}),\n\t});\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport type { Plugin, SetupInfo } from \"../types.js\";\n\n/** The data check before `setup` runs. */\nfunction noDataRequests(): boolean {\n\treturn false;\n}\n\n/**\n * Sets `Cache-Control: private, no-cache` on each HTML document and each\n * framework data response, such as a React Router `.data` request, that has\n * no `Cache-Control`. A shared cache then never keeps a page or loader data\n * that the server rendered for one user. A response with its own\n * `Cache-Control` keeps it. A resource route that sends per-user JSON sets\n * its own `Cache-Control`.\n *\n * Put it after the static stages, so it sees only the responses of the app's\n * routes and the framework. `defaultPlugins()` puts it last.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), assets(), prerendered(), privateDocuments()] });\n */\nexport function privateDocuments(): Plugin {\n\tlet isDataRequest: SetupInfo[\"isDataRequest\"] = noDataRequests;\n\treturn {\n\t\tname: \"private-documents\",\n\t\tsetup: (info) => {\n\t\t\t({ isDataRequest } = info);\n\t\t},\n\t\tmiddleware: async (context, next) =>\n\t\t\twithHeaderHook(context, next, (headers) => {\n\t\t\t\tif (\n\t\t\t\t\t!headers.has(\"Cache-Control\") &&\n\t\t\t\t\t((headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false) ||\n\t\t\t\t\t\tisDataRequest(context.req.path))\n\t\t\t\t) {\n\t\t\t\t\theaders.set(\"Cache-Control\", \"private, no-cache\");\n\t\t\t\t}\n\t\t\t}),\n\t};\n}\n","/**\n * Whether `value` is a safe same-origin path for a `Location` header. The\n * value starts with one `/`, the next character is not `/` or `\\`, and each\n * character is printable ASCII (0x20 to 0x7E).\n *\n * The check stops these attacks:\n *\n * - An open redirect: `//evil.com`, `/\\evil.com`, and `https://evil.com` go to\n * another host. A browser reads `/\\` as `//`.\n * - A scheme that does not navigate, such as `javascript:` or `data:`.\n * - A control character, such as CR or LF, that splits the response.\n *\n * Why strict: a short allow list is easy to audit. The check rejects some safe\n * values, such as a path with raw UTF-8. Percent-encode the path first.\n *\n * Ported from the ngrok frontend `isSafeLocalPath`, with its test cases.\n *\n * @example\n * isSafeLocalPath(\"/components/button?tab=props\"); // => true\n * isSafeLocalPath(\"//evil.com/foo\"); // => false\n * isSafeLocalPath(\"/café\"); // => false\n */\nexport function isSafeLocalPath(value: string): boolean {\n\treturn /^\\/(?![/\\\\])/u.test(value) && !/[^\\u0020-\\u007E]/u.test(value);\n}\n","import type { Context, MiddlewareHandler } from \"hono\";\nimport { matchedRoutes } from \"hono/route\";\nimport { isSafeLocalPath } from \"../safe-local-path.js\";\nimport { findStaticFile } from \"../static-files.js\";\nimport type { AppServerEnv, Plugin, StaticFiles } from \"../types.js\";\n\n/**\n * How a page URL ends:\n *\n * - `never`: with no trailing slash, such as `/docs/button`.\n * - `always`: with a trailing slash, such as `/docs/button/`.\n * - `preserve`: as the request has it. The server sends no redirect.\n */\nexport type TrailingSlash = \"never\" | \"always\" | \"preserve\";\n\n/** Options for {@link trailingSlash}. */\nexport type TrailingSlashOptions = {\n\tmode: TrailingSlash;\n};\n\n/** Whether the last segment of a URL path has a dot, as a file name such as `llms.txt` or `x.data` has. */\nfunction isFilePath(path: string): boolean {\n\treturn path.slice(path.lastIndexOf(\"/\") + 1).includes(\".\");\n}\n\n/** `path` with no trailing slashes. Why a scan, not `/\\/+$/`: that regex takes quadratic time on a long run of slashes inside the path. */\nexport function trimTrailingSlashes(path: string): string {\n\tlet end = path.length;\n\twhile (end > 0 && path[end - 1] === \"/\") {\n\t\tend -= 1;\n\t}\n\treturn path.slice(0, end);\n}\n\n/** The URL path in `mode`, or the path unchanged when `mode` keeps it. */\nfunction canonicalPath(path: string, mode: TrailingSlash): string {\n\tconst trimmed = trimTrailingSlashes(path);\n\tif (trimmed === \"\") {\n\t\treturn \"/\";\n\t}\n\tif (mode === \"never\") {\n\t\treturn trimmed;\n\t}\n\tif (mode === \"always\") {\n\t\treturn `${trimmed}/`;\n\t}\n\treturn path;\n}\n\n/**\n * Whether one of the app's own Hono routes matches the request. Why the\n * path: the plugins and the framework match at `/*`, and Hono matches a\n * route path strictly, so a redirect would move the request off its route.\n */\nfunction hasAppRoute(context: Context<AppServerEnv>): boolean {\n\treturn matchedRoutes(context).some((route) => route.path !== \"/*\");\n}\n\n/** Whether `path`, a decoded URL path, names a file in `files`, not a directory. */\nasync function isStaticFile(files: StaticFiles, path: string): Promise<boolean> {\n\treturn (await findStaticFile(files, path))?.path === path;\n}\n\n/**\n * Sends a 308 from a page URL to the same URL in `mode`, so each page has one\n * URL. It applies to rendered and prerendered pages, because the server cannot\n * tell which paths have a route. The redirect keeps the query string.\n *\n * It sends no redirect for `/`, a method other than GET or HEAD, a data\n * request of the framework, a path that one of the app's own Hono routes\n * matches, such as `app.get(\"/livez\")`, or a path that already has the\n * mode's form. `always` adds no slash to a file in the client build, such as\n * `/LICENSE`, or to a path whose last segment has a dot, such as `/llms.txt`.\n *\n * Set the same mode in the framework's router when it has one. Else the two\n * redirects loop: the server sends `/x` to `/x/`, and the router sends `/x/`\n * back to `/x`. For TanStack Start, check the mode against the router with\n * `RouterTrailingSlash` from `@ngrok/app-server/tanstack-start`. React Router\n * has no trailing-slash option, so it answers both forms itself.\n *\n * @example\n * createServer({ plugins: defaultPlugins({ trailingSlash: \"always\" }) });\n */\nexport function trailingSlash({ mode }: TrailingSlashOptions): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"trailing-slash\",\n\t\tsetup: (info) => {\n\t\t\tif (mode === \"preserve\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method } = context.req;\n\t\t\t\tif (\n\t\t\t\t\t(method !== \"GET\" && method !== \"HEAD\") ||\n\t\t\t\t\tinfo.isDataRequest(context.req.path) ||\n\t\t\t\t\thasAppRoute(context)\n\t\t\t\t) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\t// Why the raw URL: Hono decodes `path`, but a `Location` must keep the percent-encoding.\n\t\t\t\tconst url = new URL(context.req.url);\n\t\t\t\tconst path = canonicalPath(url.pathname, mode);\n\t\t\t\tconst location = `${path}${url.search}`;\n\t\t\t\t// Why the check: a path such as `//evil.com/` must not make a `Location` to another host.\n\t\t\t\tif (path === url.pathname || !isSafeLocalPath(location)) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\t// Why the decoded path: `/llms%2Etxt` names the file `/llms.txt`.\n\t\t\t\tif (\n\t\t\t\t\tmode === \"always\" &&\n\t\t\t\t\t(isFilePath(context.req.path) || (await isStaticFile(info.files, context.req.path)))\n\t\t\t\t) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\treturn context.redirect(location, 308);\n\t\t\t};\n\t\t},\n\t\tmiddleware: async (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n","import { isSafeLocalPath } from \"../safe-local-path.js\";\nimport type { Plugin } from \"../types.js\";\nimport { trimTrailingSlashes } from \"./trailing-slash.js\";\nimport type { TrailingSlash } from \"./trailing-slash.js\";\n\n/** One redirect of a {@link redirects} table. */\nexport type RedirectRule = {\n\t/**\n\t * The old URL path. A `:name` segment matches one path segment, and a `*`\n\t * last segment matches the rest of the path, or nothing: `/docs/*` also\n\t * matches `/docs`. A trailing slash does not change the match. Write the\n\t * path as it is in the URL, percent-encoded.\n\t */\n\tfrom: string;\n\t/**\n\t * The new URL: a local path, or an absolute `http` or `https` URL. It can\n\t * use each `:name` and the `*` of `from`. An absolute URL is\n\t * percent-encoded as UTF-8.\n\t */\n\tto: string;\n\t/** @default 301 */\n\tstatus?: 301 | 308;\n};\n\n/** A rule, compiled at startup. */\ntype CompiledRule = {\n\t/** The `from` path with no trailing slash. */\n\tkey: string;\n\tpattern: RegExp | undefined;\n\tto: string;\n\tstatus: 301 | 308;\n\t/** The origin of an absolute `to`, else `undefined`. */\n\torigin: string | undefined;\n\t/** The position of the rule in the table. */\n\tindex: number;\n};\n\nconst PARAM = /^:(?<name>[A-Za-z_]\\w*)$/u;\nconst TARGET_TOKEN = /:(?<name>[A-Za-z_]\\w*)|\\*/gu;\n\n/** `path` with no trailing slashes, and `/` for the root. */\nfunction matchKey(path: string): string {\n\treturn trimTrailingSlashes(path) || \"/\";\n}\n\n/** The pattern of `from`, with a named group for each `:name` and for `*`, or `undefined` for an exact path. */\nfunction compilePattern(from: string): { pattern: RegExp | undefined; names: Set<string> } {\n\tconst segments = matchKey(from).split(\"/\").slice(1);\n\tconst names = new Set<string>();\n\tconst parts = segments.map((segment, index) => {\n\t\tconst name = PARAM.exec(segment)?.groups?.name;\n\t\tif (name != null) {\n\t\t\tif (names.has(name)) {\n\t\t\t\tthrow new Error(`The redirect from ${from} uses :${name} twice.`);\n\t\t\t}\n\t\t\tnames.add(name);\n\t\t\treturn `/(?<${name}>[^/]+)`;\n\t\t}\n\t\tif (segment === \"*\") {\n\t\t\tif (index !== segments.length - 1) {\n\t\t\t\tthrow new Error(`The redirect from ${from} has a * that is not the last segment.`);\n\t\t\t}\n\t\t\tnames.add(\"*\");\n\t\t\t// Why `$`: a `:name` cannot have it, so the group name is free. Why optional: `/docs/*`\n\t\t\t// also moves `/docs`.\n\t\t\treturn \"(?:/(?<$splat>.*))?\";\n\t\t}\n\t\treturn `/${segment.replaceAll(/[$()*+.?[\\\\\\]^{|}]/gu, String.raw`\\$&`)}`;\n\t});\n\treturn {\n\t\tpattern: names.size === 0 ? undefined : new RegExp(`^${parts.join(\"\")}$`, \"u\"),\n\t\tnames,\n\t};\n}\n\n/** Compiles a rule, and throws for a rule that is not valid, so a bad table stops startup. */\nfunction compileRule({ from, to, status = 301 }: RedirectRule, index: number): CompiledRule {\n\tif (!from.startsWith(\"/\")) {\n\t\tthrow new Error(`A redirect must be from a path that starts with \"/\", not ${from}.`);\n\t}\n\tconst { pattern, names } = compilePattern(from);\n\tfor (const token of to.matchAll(TARGET_TOKEN)) {\n\t\tconst name = token.groups?.name ?? \"*\";\n\t\tif (!names.has(name)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The redirect from ${from} to ${to} uses ${token[0]}, which ${from} does not have.`,\n\t\t\t);\n\t\t}\n\t}\n\tif (to.startsWith(\"/\")) {\n\t\tif (!isSafeLocalPath(to)) {\n\t\t\tthrow new Error(`The redirect from ${from} goes to ${to}, which is not a safe local path.`);\n\t\t}\n\t\treturn { key: matchKey(from), pattern, to, status, origin: undefined, index };\n\t}\n\tconst url = URL.parse(to);\n\tif (url == null || (url.protocol !== \"https:\" && url.protocol !== \"http:\")) {\n\t\tthrow new Error(`A redirect must go to a local path or an http(s) URL, not ${to}.`);\n\t}\n\t// Why `href`: a `Location` must be ASCII, and it percent-encodes the rest as UTF-8.\n\treturn { key: matchKey(from), pattern, to: url.href, status, origin: url.origin, index };\n}\n\n/** The target of `rule` for the values that its pattern matched. */\nfunction fill(to: string, groups: Readonly<Record<string, string | undefined>>): string {\n\tconst queryStart = to.indexOf(\"?\");\n\treturn to.replaceAll(TARGET_TOKEN, (token, name: string | undefined, offset: number) => {\n\t\tconst value = name == null ? (groups.$splat ?? \"\") : (groups[name] ?? token);\n\t\t// Why: a path segment can have `&`, `=`, and `+`, but in a query they split or change the value.\n\t\treturn queryStart !== -1 && offset > queryStart\n\t\t\t? value.replaceAll(/[&+=]/gu, (char) => encodeURIComponent(char))\n\t\t\t: value;\n\t});\n}\n\n/** `target` with no trailing slash on its path, as the `never` mode of `trailingSlash` wants. */\nfunction withoutTrailingSlash(target: string): string {\n\tconst pathEnd = target.search(/[#?]/u);\n\tconst path = pathEnd === -1 ? target : target.slice(0, pathEnd);\n\tconst rest = pathEnd === -1 ? \"\" : target.slice(pathEnd);\n\treturn `${trimTrailingSlashes(path) || \"/\"}${rest}`;\n}\n\n/** `target` with the query string of the request added, before the fragment of `target`. */\nfunction withQuery(target: string, search: string): string {\n\tif (search === \"\") {\n\t\treturn target;\n\t}\n\tconst hashIndex = target.indexOf(\"#\");\n\tconst path = hashIndex === -1 ? target : target.slice(0, hashIndex);\n\tconst hash = hashIndex === -1 ? \"\" : target.slice(hashIndex);\n\treturn `${path}${path.includes(\"?\") ? `&${search.slice(1)}` : search}${hash}`;\n}\n\n/**\n * Sends a redirect from each old URL path in `rules` to its new URL, with\n * the query string. The first rule that matches wins. An exact path is a\n * map lookup. A rule with `:name` or `*` is a pattern.\n *\n * The rules compile at startup, and a rule that is not valid stops startup.\n * A local target must be a safe local path. An absolute target must keep the\n * origin that its rule names. A request whose values break either check goes\n * on to the next stage, and so does a request that is already at its\n * target. It applies to GET and HEAD only.\n *\n * Put it before `trailingSlash`, so `/old/` gets one redirect to the final\n * URL, and give it the same `trailingSlash` mode. In `never` mode, a local\n * target loses its trailing slash, so `trailingSlash` does not redirect it\n * again. `defaultPlugins({ redirects })` does both.\n *\n * @example\n * redirects([\n * \t{ from: \"/blog/:slug\", to: \"/articles/:slug\" },\n * \t{ from: \"/docs/*\", to: \"https://docs.example.com/*\", status: 308 },\n * ]);\n */\nexport function redirects(\n\trules: readonly RedirectRule[],\n\t{ trailingSlash = \"preserve\" }: { trailingSlash?: TrailingSlash } = {},\n): Plugin {\n\tconst compiled = rules.map((rule, index) => compileRule(rule, index));\n\tconst exact = new Map<string, CompiledRule>();\n\tfor (const rule of compiled.toReversed()) {\n\t\t// Why reversed: the first rule for a path wins.\n\t\tif (rule.pattern == null) {\n\t\t\texact.set(rule.key, rule);\n\t\t}\n\t}\n\tconst patterns = compiled.filter((rule) => rule.pattern != null);\n\tconst find = (path: string): { rule: CompiledRule; target: string } | undefined => {\n\t\tconst exactRule = exact.get(path);\n\t\tfor (const rule of patterns) {\n\t\t\tif (exactRule != null && rule.index > exactRule.index) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tconst groups = rule.pattern?.exec(path)?.groups;\n\t\t\tif (groups != null) {\n\t\t\t\treturn { rule, target: fill(rule.to, groups) };\n\t\t\t}\n\t\t}\n\t\treturn exactRule == null ? undefined : { rule: exactRule, target: exactRule.to };\n\t};\n\treturn {\n\t\tname: \"redirects\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst { method } = context.req;\n\t\t\tif (method !== \"GET\" && method !== \"HEAD\") {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\t// Why the raw URL: Hono decodes `path`, but a `Location` must keep the percent-encoding.\n\t\t\tconst url = new URL(context.req.url);\n\t\t\tconst found = find(matchKey(url.pathname));\n\t\t\tif (found == null) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tconst target =\n\t\t\t\ttrailingSlash === \"never\" && found.rule.origin == null\n\t\t\t\t\t? withoutTrailingSlash(found.target)\n\t\t\t\t\t: found.target;\n\t\t\tconst location = withQuery(target, url.search);\n\t\t\t// Why: a rule such as `/tags/:tag` to `/tags/:tag/` also matches its own target.\n\t\t\tif (new URL(location, url).href === url.href) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tconst safe =\n\t\t\t\tfound.rule.origin == null\n\t\t\t\t\t? isSafeLocalPath(location)\n\t\t\t\t\t: URL.parse(location)?.origin === found.rule.origin;\n\t\t\treturn safe ? context.redirect(location, found.rule.status) : next();\n\t\t},\n\t};\n}\n","import type { Context } from \"hono\";\nimport { withHeaderHook } from \"../header-hook.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport type { AppServerEnv, Plugin } from \"../types.js\";\n\n/** The headers that {@link securityHeaders} sets, by name. */\nexport type SecurityHeaderValues = {\n\t\"X-Content-Type-Options\"?: string | false;\n\t\"Referrer-Policy\"?: string | false;\n\t\"Cross-Origin-Opener-Policy\"?: string | false;\n\t/** Sent on an HTTPS request only. */\n\t\"Strict-Transport-Security\"?: string | false;\n\t/**\n\t * A policy that the plugin adds to each response, next to the app's own\n\t * policy. It has no default.\n\t */\n\t\"Content-Security-Policy\"?: string | false;\n};\n\n// Why no `includeSubDomains`: a browser keeps HSTS for a year, and on an apex domain it would force\n// HTTPS on each subdomain. An app adds it when it knows each subdomain serves HTTPS.\nconst DEFAULT_SECURITY_HEADERS: SecurityHeaderValues = {\n\t\"X-Content-Type-Options\": \"nosniff\",\n\t\"Referrer-Policy\": \"strict-origin-when-cross-origin\",\n\t\"Cross-Origin-Opener-Policy\": \"same-origin\",\n\t\"Strict-Transport-Security\": \"max-age=31536000\",\n};\n\n/** Options for {@link securityHeaders}. */\nexport type SecurityHeadersOptions = {\n\t/** Values that replace the defaults. `false` turns a header off. */\n\theaders?: SecurityHeaderValues;\n};\n\n/**\n * Sets safe default security headers on each response:\n *\n * - `X-Content-Type-Options: nosniff`\n * - `Referrer-Policy: strict-origin-when-cross-origin`\n * - `Cross-Origin-Opener-Policy: same-origin`\n * - `Strict-Transport-Security: max-age=31536000`, on an HTTPS request only\n *\n * A response that has a header keeps its own value. The exception is\n * `Content-Security-Policy`, which has no default: the plugin adds a set\n * value as a second policy, and a browser enforces both.\n * `defaultPlugins()` puts it before the static stages, so it also sees\n * prerendered pages.\n *\n * @example\n * defaultPlugins({\n * \tsecurityHeaders: {\n * \t\theaders: {\n * \t\t\t\"Cross-Origin-Opener-Policy\": \"same-origin-allow-popups\",\n * \t\t\t\"Content-Security-Policy\": \"frame-ancestors 'none'\",\n * \t\t},\n * \t},\n * });\n */\nexport function securityHeaders({ headers = {} }: SecurityHeadersOptions = {}): Plugin {\n\tconst values = Object.entries({ ...DEFAULT_SECURITY_HEADERS, ...headers })\n\t\t.filter((entry): entry is [string, string] => typeof entry[1] === \"string\")\n\t\t.map(([name, value]) => [name, oneLine(value)] as const);\n\treturn {\n\t\tname: \"security-headers\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst isHttps = context.req.url.startsWith(\"https:\");\n\t\t\tawait withHeaderHook(context, next, (response) => {\n\t\t\t\tfor (const [name, value] of values) {\n\t\t\t\t\tif (name === \"Content-Security-Policy\") {\n\t\t\t\t\t\tresponse.append(name, value);\n\t\t\t\t\t} else if (!response.has(name) && (name !== \"Strict-Transport-Security\" || isHttps)) {\n\t\t\t\t\t\tresponse.set(name, value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t};\n}\n\n/**\n * `value` on one line. Why: a header value cannot hold a line break, and a\n * policy written over several lines treats each run of whitespace as one space.\n */\nfunction oneLine(value: string): string {\n\treturn value.replaceAll(/\\s+/gu, \" \").trim();\n}\n\n/** Options for {@link contentSecurityPolicy}. */\nexport type ContentSecurityPolicyOptions = {\n\t/**\n\t * The `Content-Security-Policy` of an HTML document. `scriptSrc` is the\n\t * source list that trusts the document's scripts. Put it in `script-src`.\n\t * `context` is the request, so the policy can change by path. It runs in a\n\t * header hook, so it can run more than once for one request.\n\t */\n\tpolicy: (scriptSrc: string, context: Context<AppServerEnv>) => string;\n};\n\n/** A new random nonce: 16 bytes in base64. */\nfunction randomNonce(): string {\n\treturn btoa(String.fromCodePoint(...crypto.getRandomValues(new Uint8Array(16))));\n}\n\n/**\n * Sets the `Content-Security-Policy` from `policy` on each HTML document. The\n * policy trusts the document's scripts, and only them:\n *\n * - A rendered document gets `'nonce-…' 'strict-dynamic'` with a new nonce\n * for each request. The app reads the nonce from `requestContext()` and\n * gives it to the framework's render, so each inline script gets it.\n * - A prerendered document gets `'self'` and the hash of each of its inline\n * scripts, which the Vite plugin records. Its file has one nonce for every\n * visitor, so a nonce protects nothing. Why no `'strict-dynamic'`: a hash,\n * unlike a nonce, does not carry to the imports of an inline module script.\n *\n * The `contentSecurityPolicy` option of `defaultPlugins()` takes these\n * options, and puts the plugin before the static stages, so it sees the\n * prerendered documents. A response that has a `Content-Security-Policy`\n * keeps it.\n *\n * @example\n * defaultPlugins({\n * \tcontentSecurityPolicy: {\n * \t\tpolicy: (scriptSrc) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,\n * \t},\n * });\n */\nexport function contentSecurityPolicy({ policy }: ContentSecurityPolicyOptions): Plugin {\n\tlet scriptHashes: ReadonlyMap<string, readonly string[]> = new Map();\n\treturn optionPlugin(\"contentSecurityPolicy\", {\n\t\tname: \"content-security-policy\",\n\t\tsetup: (info) => {\n\t\t\t({ scriptHashes } = info);\n\t\t},\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst nonce = randomNonce();\n\t\t\tcontext.set(\"cspNonce\", nonce);\n\t\t\t// Why a header hook: in development, the dev server sends its own response, such as a file of\n\t\t\t// Vite's public directory, and runs the hooks before it sends the head.\n\t\t\tawait withHeaderHook(context, next, (headers) => {\n\t\t\t\t// Why `staticDocument` too: a 304 has no `Content-Type`, and a browser replaces the cached policy with its policy.\n\t\t\t\tconst file = context.get(\"staticDocument\");\n\t\t\t\tconst hashes =\n\t\t\t\t\tcontext.get(\"documentScriptHashes\") ??\n\t\t\t\t\t(file == null ? undefined : (scriptHashes.get(file) ?? []));\n\t\t\t\tif (\n\t\t\t\t\theaders.has(\"Content-Security-Policy\") ||\n\t\t\t\t\t(hashes == null && !(headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false))\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t// Why `'self'` only for a file with no hashes: the policy fails closed, so a missed script shows in a test.\n\t\t\t\tconst scriptSrc =\n\t\t\t\t\thashes == null\n\t\t\t\t\t\t? `'nonce-${nonce}' 'strict-dynamic'`\n\t\t\t\t\t\t: [\"'self'\", ...hashes.map((hash) => `'sha256-${hash}'`)].join(\" \");\n\t\t\t\theaders.set(\"Content-Security-Policy\", oneLine(policy(scriptSrc, context)));\n\t\t\t});\n\t\t},\n\t});\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport type { Plugin } from \"../types.js\";\n\n/** Options for {@link requestId}. */\nexport type RequestIdOptions = {\n\t/** @default \"X-Request-Id\" */\n\theaderName?: string;\n\t/**\n\t * Also log the trace IDs as `dd.trace_id` and `dd.span_id`, the lower 64\n\t * bits in decimal, so Datadog connects each log line to its trace.\n\t * @default false\n\t */\n\tdatadogTraceIds?: boolean;\n};\n\n/** An incoming request ID that the plugin keeps: up to 255 word characters, `-`, and `=`. */\nconst VALID_ID = /^[\\w\\-=]{1,255}$/u;\n\n/** A W3C `traceparent`: version, trace ID, parent ID, and flags, in lowercase hex. */\nconst TRACEPARENT =\n\t/^(?<version>[\\da-f]{2})-(?<traceId>[\\da-f]{32})-(?<spanId>[\\da-f]{16})-[\\da-f]{2}(?<rest>-.*)?$/u;\n\n/**\n * The trace IDs of a valid W3C `traceparent` header, else `undefined`. A\n * version `ff`, an ID of all zeros, and extra fields in version `00` are not valid.\n *\n * @example\n * parseTraceparent(\"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01\");\n * // => { traceId: \"4bf92f3577b34da6a3ce929d0e0e4736\", spanId: \"00f067aa0ba902b7\" }\n */\nexport function parseTraceparent(\n\theader: string | undefined,\n): { traceId: string; spanId: string } | undefined {\n\tconst groups = TRACEPARENT.exec(header?.trim() ?? \"\")?.groups;\n\tif (\n\t\tgroups?.version == null ||\n\t\tgroups.traceId == null ||\n\t\tgroups.spanId == null ||\n\t\tgroups.version === \"ff\" ||\n\t\t(groups.version === \"00\" && groups.rest != null) ||\n\t\t/^0+$/u.test(groups.traceId) ||\n\t\t/^0+$/u.test(groups.spanId)\n\t) {\n\t\treturn undefined;\n\t}\n\treturn { traceId: groups.traceId, spanId: groups.spanId };\n}\n\n/** The log attributes for the trace IDs. */\nfunction traceAttributes(\n\t{ traceId, spanId }: { traceId: string; spanId: string },\n\t{ datadog }: { datadog: boolean },\n): Record<string, string> {\n\treturn {\n\t\ttrace_id: traceId,\n\t\tspan_id: spanId,\n\t\t...(datadog\n\t\t\t? {\n\t\t\t\t\t\"dd.trace_id\": BigInt(`0x${traceId.slice(16)}`).toString(),\n\t\t\t\t\t\"dd.span_id\": BigInt(`0x${spanId}`).toString(),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/**\n * Gives each request an ID: a valid incoming header (up to 255 word\n * characters, `-`, and `=`), else a new UUID. The ID goes on the response, on\n * every log line, and into the framework's context.\n *\n * A valid W3C `traceparent` header adds `trace_id` and `span_id` to each log\n * line of the request.\n *\n * @example\n * const app = createServer({ plugins: [requestId()] });\n * const response = await app.request(\"/\", { headers: { \"X-Request-Id\": \"abc-123\" } });\n * response.headers.get(\"X-Request-Id\"); // => \"abc-123\"\n */\nexport function requestId({\n\theaderName = \"X-Request-Id\",\n\tdatadogTraceIds = false,\n}: RequestIdOptions = {}): Plugin {\n\treturn {\n\t\tname: \"request-id\",\n\t\tmiddleware: async (context, next) => {\n\t\t\tconst trace = parseTraceparent(context.req.header(\"traceparent\"));\n\t\t\tif (trace != null) {\n\t\t\t\tcontext.set(\"logAttributes\", {\n\t\t\t\t\t...context.get(\"logAttributes\"),\n\t\t\t\t\t...traceAttributes(trace, { datadog: datadogTraceIds }),\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst incoming = context.req.header(headerName);\n\t\t\tconst id = incoming != null && VALID_ID.test(incoming) ? incoming : crypto.randomUUID();\n\t\t\tcontext.set(\"requestId\", id);\n\t\t\t// Why a header hook: a dev server middleware sends its own response, and runs the hooks first.\n\t\t\tawait withHeaderHook(context, next, (headers) => {\n\t\t\t\theaders.set(headerName, id);\n\t\t\t});\n\t\t},\n\t};\n}\n","/** One media range of an `Accept` header. */\ntype MediaRange = {\n\t/** The media type in lowercase, such as `text/html` or `*\\/*`. */\n\ttype: string;\n\t/** The `q` value, from 0 to 1. */\n\tquality: number;\n\t/** The `charset` parameter in lowercase, when the range has one. */\n\tcharset: string | undefined;\n};\n\n/** A `q` value as RFC 9110 writes it: 0 to 1, with up to three decimals. */\nconst QVALUE = /^(?:0(?:\\.\\d{0,3})?|1(?:\\.0{0,3})?)$/u;\n\n/** The charset of each answer that a caller of {@link prefersMarkdown} sends. */\n// oxlint-disable-next-line unicorn/text-encoding-identifier-case -- HTTP names the charset `utf-8`.\nconst CHARSET = \"utf-8\";\n\n/**\n * The parts of `value` between each `separator`. Why a scan, not `split`: a\n * quoted parameter value can hold a `,` or a `;`.\n */\nfunction splitOutsideQuotes(value: string, separator: string): string[] {\n\tconst parts: string[] = [];\n\tlet part = \"\";\n\tlet quoted = false;\n\tlet escaped = false;\n\tfor (const character of value) {\n\t\tif (!quoted && character === separator) {\n\t\t\tparts.push(part);\n\t\t\tpart = \"\";\n\t\t} else {\n\t\t\tif (escaped) {\n\t\t\t\tescaped = false;\n\t\t\t} else if (quoted && character === \"\\\\\") {\n\t\t\t\tescaped = true;\n\t\t\t} else if (character === '\"') {\n\t\t\t\tquoted = !quoted;\n\t\t\t}\n\t\t\tpart += character;\n\t\t}\n\t}\n\tparts.push(part);\n\treturn parts;\n}\n\n/** The parameters of a media range, by lowercase name, with quotes removed. */\nfunction parameterMap(parameters: readonly string[]): Map<string, string> {\n\treturn new Map(\n\t\tparameters.map((parameter) => {\n\t\t\tconst index = parameter.indexOf(\"=\");\n\t\t\tconst name = (index === -1 ? parameter : parameter.slice(0, index)).trim().toLowerCase();\n\t\t\tconst value = index === -1 ? \"\" : parameter.slice(index + 1).trim();\n\t\t\tconst unquoted = /^\".*\"$/su.test(value)\n\t\t\t\t? value.slice(1, -1).replaceAll(/\\\\(?<character>.)/gsu, \"$<character>\")\n\t\t\t\t: value;\n\t\t\treturn [name, unquoted];\n\t\t}),\n\t);\n}\n\n/**\n * The media ranges of an `Accept` header. A missing `q` counts as 1, the RFC\n * 9110 default. Why a malformed `q` also counts as 1: the client still named\n * the media type.\n */\nfunction mediaRanges(accept: string): MediaRange[] {\n\treturn splitOutsideQuotes(accept, \",\").map((entry) => {\n\t\tconst [type = \"\", ...parameters] = splitOutsideQuotes(entry, \";\");\n\t\tconst parameterValues = parameterMap(parameters);\n\t\tconst quality = parameterValues.get(\"q\") ?? \"1\";\n\t\treturn {\n\t\t\ttype: type.trim().toLowerCase(),\n\t\t\tquality: QVALUE.test(quality) ? Number(quality) : 1,\n\t\t\tcharset: parameterValues.get(\"charset\")?.toLowerCase(),\n\t\t};\n\t});\n}\n\n/**\n * The `q` of an answer of `type` in UTF-8, from the most specific ranges with\n * that type, or `undefined` when no range matches it. A range with\n * `charset=utf-8` is more specific than a range with no charset. A range with\n * another charset does not match. Other parameters, such as `variant`, do not\n * change the match.\n */\nfunction qualityOf(ranges: readonly MediaRange[], type: string): number | undefined {\n\tconst matches = ranges.filter(\n\t\t(range) => range.type === type && (range.charset == null || range.charset === CHARSET),\n\t);\n\tconst withCharset = matches.filter((range) => range.charset === CHARSET);\n\tconst specific = withCharset.length > 0 ? withCharset : matches;\n\treturn specific.length === 0 ? undefined : Math.max(...specific.map((range) => range.quality));\n}\n\n/**\n * Whether a request asks for markdown before HTML, per\n * https://acceptmarkdown.com. Use it to choose between the HTML and the\n * markdown answer for one URL.\n *\n * The rules:\n *\n * - Only an explicit `text/markdown` range counts for markdown. A wildcard,\n * such as `*\\/*` or `text/*`, never selects markdown, so a browser and a\n * client with no `Accept` get HTML.\n * - `text/markdown;q=0` refuses markdown.\n * - The `q` of markdown must be equal to or higher than the `q` of HTML. The\n * `q` of HTML comes from the most specific range that matches it:\n * `text/html`, then `text/*`, then `*\\/*`. A tie selects markdown, because\n * the client named it.\n * - Both answers are UTF-8. A range with `charset=utf-8` is more specific\n * than a range with no charset, and a range with another charset does not\n * match. Other parameters, such as `variant`, do not change the match.\n * - Media types and parameter names are not case-sensitive. A quoted\n * parameter value can hold a `,` or a `;`.\n *\n * When the answer for a URL depends on this function, send `Vary: Accept` on\n * both the HTML and the markdown answer. Else a shared cache can give the\n * markdown to a browser.\n *\n * @example\n * prefersMarkdown(new Request(\"https://example.com/\", { headers: { Accept: \"text/markdown\" } }));\n * // => true\n * prefersMarkdown(new Request(\"https://example.com/\", { headers: { Accept: \"text/html, text/markdown;q=0.5\" } }));\n * // => false\n */\nexport function prefersMarkdown(request: Request): boolean {\n\tconst accept = request.headers.get(\"Accept\");\n\t// Why the substring check: a browser never names markdown, and it skips the parse of its long `Accept`.\n\tif (accept == null || !/markdown/iu.test(accept)) {\n\t\treturn false;\n\t}\n\tconst ranges = mediaRanges(accept);\n\tconst markdown = qualityOf(ranges, \"text/markdown\") ?? 0;\n\tconst html =\n\t\tqualityOf(ranges, \"text/html\") ?? qualityOf(ranges, \"text/*\") ?? qualityOf(ranges, \"*/*\") ?? 0;\n\treturn markdown > 0 && markdown >= html;\n}\n","import type { Context, MiddlewareHandler } from \"hono\";\nimport { getPath } from \"hono/utils/url\";\nimport { manifestKey } from \"../build-manifest.js\";\nimport { writableHeaders } from \"../header-hook.js\";\nimport { prefersMarkdown } from \"../prefers-markdown.js\";\nimport { contentType, findStaticFile, isFilePath, staticResponse } from \"../static-files.js\";\nimport { withVary } from \"../vary.js\";\nimport type { StaticFile } from \"../static-files.js\";\nimport type { AppServerEnv, Plugin, StaticFiles } from \"../types.js\";\nimport { trimTrailingSlashes } from \"./trailing-slash.js\";\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n/**\n * Serves the hashed files under `/assets/` with a one-year immutable cache.\n * A missing asset gets a plain 404 with `Cache-Control: no-store`, not a\n * rendered page. In development, the dev server serves the source modules,\n * the HMR client, and the CSS here instead.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });\n */\nexport function assets(): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"assets\",\n\t\tsetup: (info) => {\n\t\t\tif (info.mode === \"development\") {\n\t\t\t\tstage = info.devServer;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst { files, contentTypes } = info;\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method, path } = context.req;\n\t\t\t\tif (!path.startsWith(\"/assets/\") || (method !== \"GET\" && method !== \"HEAD\")) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\tconst file = await findStaticFile(files, path);\n\t\t\t\tif (file == null) {\n\t\t\t\t\t// Why `no-store`: an old tab asks for the chunks of the build it runs, and a CDN must not keep the miss.\n\t\t\t\t\treturn context.text(\"Not Found\", 404, { \"Cache-Control\": \"no-store\" });\n\t\t\t\t}\n\t\t\t\treturn staticResponse(context, {\n\t\t\t\t\tfiles,\n\t\t\t\t\tfile,\n\t\t\t\t\theaders: { \"Cache-Control\": IMMUTABLE },\n\t\t\t\t\tcontentTypes,\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t\tmiddleware: async (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n\n/** Options for {@link prerendered}. */\nexport type PrerenderedOptions = {\n\t/**\n\t * Extra headers for a served file, by its URL path. They replace the\n\t * headers captured at build time.\n\t */\n\theaders?: (\n\t\tpath: string,\n\t\tcontext: Context<AppServerEnv>,\n\t) => Readonly<Record<string, string>> | undefined;\n\t/**\n\t * Maps a request path to the URL path of the file to serve, for content\n\t * negotiation. Return the path unchanged to serve the usual file. The\n\t * returned path follows the rules of a request path: one URL for each\n\t * file, no dotfiles, and nothing outside the client build. When the\n\t * answer depends on a request header, add a `Vary` for it in a plugin.\n\t */\n\trewrite?: (path: string, context: Context<AppServerEnv>) => string;\n\t/**\n\t * Serves the markdown twin of a page, such as `/docs/button.md` for\n\t * `/docs/button`, to a request that {@link prefersMarkdown} accepts. A\n\t * page has a twin when `twinOf` names a file in the client build. `twinOf`\n\t * gets the request path and the request's Hono context, the same as\n\t * `rewrite`. It returns `undefined` for a request with no twin.\n\t *\n\t * - A request that prefers markdown gets the twin, with the twin's\n\t * captured headers. `rewrite` does not run for it.\n\t * - Each answer for a path with a twin gets `Vary: Accept`: the twin, the\n\t * prerendered HTML, and the framework's answer. The server adds\n\t * `Accept` to the `Vary` header and keeps the values in it.\n\t * - Each answer for a path with a twin, except the twin, gets\n\t * `Link: <twin>; rel=\"alternate\"; type=\"text/markdown\"`, so a client can\n\t * find the twin.\n\t * - A path with no twin gets no `Vary: Accept` and no `Link`, so a request\n\t * for the twin's own URL gets none.\n\t * - In development, the client build has no twins. A request that prefers\n\t * markdown gets the framework's answer for the twin's URL, so an edit\n\t * shows at once. When the framework knows the paths that the build will\n\t * prerender, as React Router does, only those twins count. An error, or\n\t * an answer that is not markdown, gives the HTML.\n\t * - A plugin after `prerendered` does not see a twin, as it does not see\n\t * a prerendered file.\n\t *\n\t * `true` uses the default `twinOf`: the path with no trailing slash plus\n\t * `.md`, and `/index.md` for `/`. The returned path follows the rules of a\n\t * request path.\n\t *\n\t * @example\n\t * prerendered({ markdownTwins: { twinOf: (path) => `/markdown${path}.md` } });\n\t */\n\tmarkdownTwins?: boolean | { twinOf: TwinOf };\n\t/**\n\t * Sends a request path to the next stage, with no file lookup. Use it for\n\t * private pages, so the auth check in the app or the framework runs for\n\t * them. A data request has its own path, such as `/app.data` in React\n\t * Router.\n\t *\n\t * @example\n\t * prerendered({ skip: (path) => path === \"/app\" || path.startsWith(\"/app/\") || path.startsWith(\"/app.\") });\n\t */\n\tskip?: (path: string) => boolean;\n\t/**\n\t * The `Cache-Control` of a served file, by the file's URL path, such as\n\t * `/about/index.html`. `undefined` sends none. A header that the build\n\t * captured, and the `headers` option, win over it.\n\t *\n\t * The default gives an HTML page, a markdown file, and a data file of the\n\t * framework `public, max-age=0, must-revalidate`, so a visitor always sees\n\t * the newest page and its markdown twin, and a 304 keeps it fast. It gives every other file\n\t * `public, max-age=3600, stale-while-revalidate=86400`.\n\t *\n\t * @example\n\t * prerendered({ cacheControl: (path) => (path.startsWith(\"/images/\") ? \"public, max-age=86400\" : undefined) });\n\t */\n\tcacheControl?: (path: string) => string | undefined;\n};\n\n/** Maps a request to the URL path of its markdown twin, or `undefined` when it has none. */\ntype TwinOf = (path: string, context: Context<AppServerEnv>) => string | undefined;\n\nconst REVALIDATE = \"public, max-age=0, must-revalidate\";\nconst ONE_HOUR = \"public, max-age=3600, stale-while-revalidate=86400\";\n\n/** The default markdown twin of a page: `/docs/button.md` for `/docs/button`, and `/index.md` for `/`. */\nfunction defaultTwinOf(path: string): string {\n\treturn `${trimTrailingSlashes(path) || \"/index\"}.md`;\n}\n\n/** The file of the markdown twin of the request, or `undefined` when the page has none. */\nasync function findTwin(\n\tfiles: StaticFiles,\n\tcontext: Context<AppServerEnv>,\n\ttwinOf: TwinOf | undefined,\n): Promise<{ path: string; file: StaticFile } | undefined> {\n\tconst twinPath = twinOf?.(context.req.path, context);\n\tconst file = twinPath == null ? undefined : await findStaticFile(files, twinPath);\n\treturn twinPath == null || file == null ? undefined : { path: twinPath, file };\n}\n\n/** Adds `Vary: Accept` to the answer for a path with a twin, so a shared cache keeps both answers. */\nfunction varyOnAccept(context: Context<AppServerEnv>): void {\n\tconst vary = withVary(context.res.headers.get(\"Vary\"), \"Accept\");\n\tif (vary != null) {\n\t\twritableHeaders(context).set(\"Vary\", vary);\n\t}\n}\n\n/**\n * The percent-encoded URL path for a decoded path, so it holds no space,\n * `>`, or non-ASCII character. Why the replace: a URL removes a tab or a\n * newline, which a file name can hold.\n */\nfunction urlPath(path: string): string {\n\treturn new URL(\n\t\tpath.replaceAll(/[\\t\\n\\r]/gu, (character) => encodeURIComponent(character)),\n\t\t\"http://localhost\",\n\t).pathname;\n}\n\n/** Adds a `Link` to the twin at `twinPath`, so a client that does not ask for markdown can find it. */\nfunction linkToTwin(context: Context<AppServerEnv>, twinPath: string): void {\n\twritableHeaders(context).append(\n\t\t\"Link\",\n\t\t`<${urlPath(twinPath)}>; rel=\"alternate\"; type=\"text/markdown\"`,\n\t);\n}\n\n/**\n * The development stage of `markdownTwins`. The client build has no twins\n * then, so a request that prefers markdown gets the framework's answer for\n * the twin's URL: the route that prerenders the twin. A twin path that is not\n * in `prerenderedPaths`, an error, or an answer that is not markdown sends the\n * request on for the HTML.\n */\nfunction developmentTwins(\n\ttwinOf: TwinOf,\n\tskip: PrerenderedOptions[\"skip\"],\n\tprerenderedPaths: ReadonlySet<string> | undefined,\n): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { method, path } = context.req;\n\t\tconst twinPath =\n\t\t\t(method === \"GET\" || method === \"HEAD\") &&\n\t\t\tskip?.(path) !== true &&\n\t\t\tprefersMarkdown(context.req.raw)\n\t\t\t\t? twinOf(path, context)\n\t\t\t\t: undefined;\n\t\t// Why both checks: production has no twin that the build does not prerender, or at a path that fails `isFilePath`.\n\t\tif (\n\t\t\ttwinPath == null ||\n\t\t\t(prerenderedPaths != null && !prerenderedPaths.has(twinPath)) ||\n\t\t\t!isFilePath(twinPath)\n\t\t) {\n\t\t\treturn next();\n\t\t}\n\t\tconst url = new URL(context.req.url);\n\t\turl.pathname = urlPath(twinPath);\n\t\t// Why: the URL can change the path, for example `%2e%2e` to `..`. Then the framework answers a path that `twinOf` did not name.\n\t\tif (getPath(new Request(url)) !== twinPath) {\n\t\t\treturn next();\n\t\t}\n\t\tconst { headers, signal } = context.req.raw;\n\t\t// Why no `Request` as the init: the Node.js listener's request is not one that `Request` can copy.\n\t\tconst twin = new Request(url, { method, headers, signal });\n\t\tconst response = await context.env.framework.fetch(twin, context);\n\t\t// Why only markdown: production serves a twin from a `.md` file, so an HTML page or an error is no twin.\n\t\t// A 304 has no body to check, and it answers a validator from the twin.\n\t\tconst markdown =\n\t\t\tresponse.headers.get(\"Content-Type\")?.toLowerCase().startsWith(\"text/markdown\") === true;\n\t\tif (response.status !== 304 && !(response.ok && markdown)) {\n\t\t\tawait response.body?.cancel();\n\t\t\treturn next();\n\t\t}\n\t\tcontext.res = response;\n\t\tvaryOnAccept(context);\n\t};\n}\n\n/** The `twinOf` function that the `markdownTwins` option selects, or `undefined` when it is off. */\nfunction twinOfOption(markdownTwins: PrerenderedOptions[\"markdownTwins\"]): TwinOf | undefined {\n\tif (markdownTwins === true) {\n\t\treturn defaultTwinOf;\n\t}\n\tif (markdownTwins == null || markdownTwins === false) {\n\t\treturn undefined;\n\t}\n\treturn markdownTwins.twinOf;\n}\n\n/**\n * Serves the client build: prerendered pages at their own URL with a 200,\n * plus every other file in it. It sends no redirect. The `trailingSlash`\n * plugin does. Each response gets\n * the headers its loader sent at build time (the `appServer` Vite plugin\n * captures them), a `Cache-Control` (see `cacheControl`), an ETag, and a 304\n * for a matching `If-None-Match`. A GET with one byte range gets a 206. A path\n * with no file goes on to the framework. In development, only\n * `markdownTwins` runs.\n *\n * At startup, it warns about each prerendered path that has no file.\n *\n * @example\n * prerendered({\n * \theaders: (path) => (path.startsWith(\"/api/\") ? { \"Access-Control-Allow-Origin\": \"*\" } : undefined),\n * });\n */\nexport function prerendered(options: PrerenderedOptions = {}): Plugin {\n\tlet stage: MiddlewareHandler<AppServerEnv> | undefined;\n\treturn {\n\t\tname: \"prerendered\",\n\t\tsetup: async (info) => {\n\t\t\tconst twinOf = twinOfOption(options.markdownTwins);\n\t\t\tif (info.mode === \"development\") {\n\t\t\t\tconst paths = info.prerenderedPaths;\n\t\t\t\tstage =\n\t\t\t\t\ttwinOf == null\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: developmentTwins(twinOf, options.skip, paths == null ? undefined : new Set(paths));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst { files, contentTypes, capturedHeaders } = info;\n\t\t\tconst missing: string[] = [];\n\t\t\tfor (const path of info.prerenderedPaths) {\n\t\t\t\tif ((await findStaticFile(files, path)) == null) {\n\t\t\t\t\tmissing.push(path);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (missing.length > 0) {\n\t\t\t\t// Why a warning: a path with no file falls through to the framework, which still answers.\n\t\t\t\tinfo.logger.log(\"warn\", \"prerendered paths with no file\", {\n\t\t\t\t\t\"app_server.missing_paths\": missing,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst cacheControl =\n\t\t\t\toptions.cacheControl ??\n\t\t\t\t((path: string) => {\n\t\t\t\t\tconst type = contentType(path, contentTypes);\n\t\t\t\t\treturn type.startsWith(\"text/html\") ||\n\t\t\t\t\t\ttype.startsWith(\"text/markdown\") ||\n\t\t\t\t\t\tinfo.isDataRequest(path)\n\t\t\t\t\t\t? REVALIDATE\n\t\t\t\t\t\t: ONE_HOUR;\n\t\t\t\t});\n\t\t\tconst serve = async (context: Context<AppServerEnv>, path: string, file: StaticFile) => {\n\t\t\t\tconst value = cacheControl(file.path);\n\t\t\t\tconst headers = new Headers(value == null ? undefined : { \"Cache-Control\": value });\n\t\t\t\t// Why `Headers`: the build captures lowercase names, and each layer must replace the one before it in any case.\n\t\t\t\tfor (const layer of [\n\t\t\t\t\tcapturedHeaders.get(manifestKey(path)),\n\t\t\t\t\toptions.headers?.(path, context),\n\t\t\t\t]) {\n\t\t\t\t\tfor (const [name, layerValue] of Object.entries(layer ?? {})) {\n\t\t\t\t\t\theaders.set(name, layerValue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn staticResponse(context, {\n\t\t\t\t\tfiles,\n\t\t\t\t\tfile,\n\t\t\t\t\theaders: Object.fromEntries(headers),\n\t\t\t\t\tcontentTypes,\n\t\t\t\t});\n\t\t\t};\n\t\t\tstage = async (context, next) => {\n\t\t\t\tconst { method } = context.req;\n\t\t\t\tif ((method !== \"GET\" && method !== \"HEAD\") || options.skip?.(context.req.path) === true) {\n\t\t\t\t\treturn next();\n\t\t\t\t}\n\t\t\t\tconst twin = await findTwin(files, context, twinOf);\n\t\t\t\tconst preferred = twin != null && prefersMarkdown(context.req.raw) ? twin : undefined;\n\t\t\t\tconst path =\n\t\t\t\t\tpreferred?.path ?? options.rewrite?.(context.req.path, context) ?? context.req.path;\n\t\t\t\tconst file = preferred?.file ?? (await findStaticFile(files, path));\n\t\t\t\tif (file == null) {\n\t\t\t\t\tawait next();\n\t\t\t\t} else {\n\t\t\t\t\tcontext.res = await serve(context, path, file);\n\t\t\t\t}\n\t\t\t\tif (twin != null) {\n\t\t\t\t\tvaryOnAccept(context);\n\t\t\t\t}\n\t\t\t\tif (twin != null && preferred == null) {\n\t\t\t\t\tlinkToTwin(context, twin.path);\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tmiddleware: async (context, next) => (stage == null ? next() : stage(context, next)),\n\t};\n}\n","import {\n\tforbidsTransform,\n\tisCompressible,\n\tMIN_COMPRESS_BYTES,\n\tpreferredEncoding,\n\treadIfQueued,\n} from \"../compression.js\";\nimport type { ReadResult } from \"../compression.js\";\nimport { hookedHeaders, replaceResponse, withHeaderHook } from \"../header-hook.js\";\nimport type { Plugin, SetupInfo } from \"../types.js\";\nimport { withVary } from \"../vary.js\";\n\n/** The chunks that a body has queued, and the read that is still open, if any. */\ntype Queued = { chunks: Uint8Array[]; done: boolean; pending: Promise<ReadResult> | undefined };\n\n/**\n * The most bytes that one pull of {@link replay} joins. Why 16 KiB: a source\n * that makes a chunk on each read looks queued, so the join can read ahead of\n * the client by this size, the default read-ahead of a Node.js stream.\n */\nexport const MAX_JOINED_BYTES = 16 * 1024;\n\n/**\n * Reads at most two chunks that `reader` has queued, and never waits for\n * more. Why two: a body from a string or a buffer queues its bytes and its\n * end, so the plugin can see that it is small. `@hono/node-server` reads a\n * body the same way to find its length.\n */\nasync function readQueued(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<Queued> {\n\tconst chunks: Uint8Array[] = [];\n\tfor (let count = 0; count < 2; count += 1) {\n\t\tconst next = await readIfQueued(reader);\n\t\tif (\"pending\" in next) {\n\t\t\treturn { chunks, done: false, pending: next.pending };\n\t\t}\n\t\tif (next.result.done) {\n\t\t\treturn { chunks, done: true, pending: undefined };\n\t\t}\n\t\tchunks.push(next.result.value);\n\t}\n\treturn { chunks, done: false, pending: undefined };\n}\n\nfunction join(chunks: Uint8Array[], size: number): Uint8Array {\n\tconst [first] = chunks;\n\tif (chunks.length === 1 && first != null) {\n\t\treturn first;\n\t}\n\tconst joined = new Uint8Array(size);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tjoined.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\treturn joined;\n}\n\n/**\n * The body again: the queued chunks, then the rest of `reader`. Each pull\n * waits for one chunk at most, and joins it with the chunks that are queued\n * after it, up to {@link MAX_JOINED_BYTES}. Why join: gzip flushes after each\n * chunk, and each flush costs more than the bytes. A renderer such as React\n * queues many small chunks at once. A chunk that comes later still goes out on\n * its own. A chunk that does not fit waits for the next pull, and an empty\n * chunk ends the join. When `queued` has the end, the first pull sends the\n * chunks and closes.\n */\nfunction replay(\n\treader: ReadableStreamDefaultReader<Uint8Array>,\n\tqueued: Queued,\n): ReadableStream<Uint8Array> {\n\tconst chunks = [...queued.chunks];\n\tlet { pending, done } = queued;\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\tconst parts: Uint8Array[] = [];\n\t\t\t\tlet size = 0;\n\t\t\t\tconst fits = (chunk: Uint8Array) =>\n\t\t\t\t\tparts.length === 0 || size + chunk.byteLength <= MAX_JOINED_BYTES;\n\t\t\t\tfor (let [chunk] = chunks; chunk != null && fits(chunk); [chunk] = chunks) {\n\t\t\t\t\tchunks.shift();\n\t\t\t\t\tparts.push(chunk);\n\t\t\t\t\tsize += chunk.byteLength;\n\t\t\t\t}\n\t\t\t\tif (parts.length === 0) {\n\t\t\t\t\tconst result = await (pending ?? reader.read());\n\t\t\t\t\tpending = undefined;\n\t\t\t\t\tif (result.done) {\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tparts.push(result.value);\n\t\t\t\t\tsize = result.value.byteLength;\n\t\t\t\t}\n\t\t\t\t// Why no read when `done`: the host reads a body the same way as `readQueued`, and it sends\n\t\t\t\t// a body with its `Content-Length` only when the body ends within that read.\n\t\t\t\twhile (chunks.length === 0 && pending == null && !done && size < MAX_JOINED_BYTES) {\n\t\t\t\t\t// oxlint-disable-next-line no-await-in-loop -- each read takes only a chunk that is queued already.\n\t\t\t\t\tconst next = await readIfQueued(reader);\n\t\t\t\t\tif (\"pending\" in next) {\n\t\t\t\t\t\t({ pending } = next);\n\t\t\t\t\t} else if (next.result.done) {\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t} else if (next.result.value.byteLength === 0) {\n\t\t\t\t\t\t// Why stop: empty chunks add no bytes, so a source of them would hold the join open.\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (fits(next.result.value)) {\n\t\t\t\t\t\tparts.push(next.result.value);\n\t\t\t\t\t\tsize += next.result.value.byteLength;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchunks.push(next.result.value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontroller.enqueue(join(parts, size));\n\t\t\t\tif (done && chunks.length === 0) {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: async (reason) => reader.cancel(reason),\n\t\t},\n\t\t// Why 0: the stream reads its source only when the consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/**\n * `response` with the gzip `body` and its headers. Why not in a header hook:\n * the body and its headers go together, also to the code that an outer stage\n * runs after its `next()`.\n */\nfunction gzipped(\n\tresponse: Response,\n\tbody: ReadableStream<Uint8Array>,\n\t{ hasLength }: { hasLength: boolean },\n): Response {\n\tconst replacement = new Response(body, response);\n\treplacement.headers.set(\"Content-Encoding\", \"gzip\");\n\t// Why the flag: a delete costs as much as a set, and a streamed page has no length.\n\tif (hasLength) {\n\t\treplacement.headers.delete(\"Content-Length\");\n\t}\n\t// Why: a range of the gzip bytes cannot be served, because each response compresses again.\n\treplacement.headers.delete(\"Accept-Ranges\");\n\treturn replacement;\n}\n\n/**\n * Gzips text responses and flushes after each chunk, so a streamed page shell\n * or a server-sent event reaches the client at once. Chunks that the body has\n * queued together are one chunk, up to 16 KiB. `hono/compress` holds a\n * stream until it ends. Skips a response that is already encoded, a partial\n * response, one marked `no-transform`, and one whose `Content-Length` is\n * under 1 KiB. It adds `Accept-Encoding` to the `Vary` of each response that\n * it can gzip. The host gives the gzip stream. On a host with none, the\n * plugin does nothing.\n *\n * @example\n * createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });\n */\nexport function streamingCompress(): Plugin {\n\tlet gzip: SetupInfo[\"gzip\"];\n\treturn {\n\t\tname: \"streaming-compress\",\n\t\tsetup: (info) => {\n\t\t\t({ gzip } = info);\n\t\t},\n\t\tmiddleware: async (context, next) => {\n\t\t\tif (gzip == null) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\t// Why a hook for `Vary`: the code after `next()` decides, and a response that the plugin does\n\t\t\t// not gzip then needs no copy for it.\n\t\t\tlet gzipping = false;\n\t\t\tawait withHeaderHook(context, next, (headers) => {\n\t\t\t\t// Why: the bytes of a type that the plugin never gzips, such as an image, do not vary by\n\t\t\t\t// `Accept-Encoding`. A response with no type, such as a 304, keeps the `Vary` of its 200.\n\t\t\t\tconst type = headers.get(\"Content-Type\");\n\t\t\t\tconst vary =\n\t\t\t\t\ttype == null || isCompressible(type)\n\t\t\t\t\t\t? withVary(headers.get(\"Vary\"), \"Accept-Encoding\")\n\t\t\t\t\t\t: undefined;\n\t\t\t\tif (vary != null) {\n\t\t\t\t\theaders.set(\"Vary\", vary);\n\t\t\t\t}\n\t\t\t\t// Why: the hook of an inner stage can set the length of the body before gzip.\n\t\t\t\tif (gzipping) {\n\t\t\t\t\theaders.delete(\"Content-Length\");\n\t\t\t\t}\n\t\t\t});\n\t\t\tconst response = context.res;\n\t\t\tconst type = response.headers.get(\"Content-Type\");\n\t\t\tif (type != null && !isCompressible(type)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst length = response.headers.get(\"Content-Length\");\n\t\t\tconst { body } = response;\n\t\t\tif (\n\t\t\t\ttype == null ||\n\t\t\t\tbody == null ||\n\t\t\t\tcontext.req.method === \"HEAD\" ||\n\t\t\t\t(length != null && Number(length) < MIN_COMPRESS_BYTES) ||\n\t\t\t\tpreferredEncoding(context.req.header(\"Accept-Encoding\"), [\"gzip\"]) == null ||\n\t\t\t\tresponse.headers.has(\"Content-Encoding\") ||\n\t\t\t\t// Why: gzip changes the bytes, so a `Content-Range` would no longer match them.\n\t\t\t\tresponse.headers.has(\"Content-Range\") ||\n\t\t\t\tforbidsTransform(response.headers.get(\"Cache-Control\"))\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet source: ReadableStream<Uint8Array> = body;\n\t\t\tlet compress = true;\n\t\t\tif (length == null) {\n\t\t\t\tconst reader = body.getReader();\n\t\t\t\tconst queued = await readQueued(reader);\n\t\t\t\tconst size = queued.chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n\t\t\t\t// Why: gzip makes a small body larger, and a body from a string has no `Content-Length`.\n\t\t\t\tcompress = !queued.done || size >= MIN_COMPRESS_BYTES;\n\t\t\t\tsource = replay(reader, queued);\n\t\t\t}\n\t\t\t// Why the hooks: a header hook of a later stage can set these headers, and it runs only where\n\t\t\t// the response leaves.\n\t\t\tif (compress) {\n\t\t\t\tconst hooked = hookedHeaders(context, response.headers);\n\t\t\t\tcompress =\n\t\t\t\t\t!hooked.has(\"Content-Encoding\") &&\n\t\t\t\t\t!hooked.has(\"Content-Range\") &&\n\t\t\t\t\t!forbidsTransform(hooked.get(\"Cache-Control\"));\n\t\t\t}\n\t\t\tif (compress) {\n\t\t\t\tgzipping = true;\n\t\t\t\treplaceResponse(context, gzipped(response, gzip(source), { hasLength: length != null }));\n\t\t\t} else if (source !== body) {\n\t\t\t\treplaceResponse(context, new Response(source, response));\n\t\t\t}\n\t\t},\n\t};\n}\n","import { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport type { ErrorHandler, HTTPResponseError } from \"hono/types\";\nimport { errorAttributes, jsonSink, requestLogger } from \"./log.js\";\nimport { accessLog } from \"./plugins/access-log.js\";\nimport type { AccessLogOptions } from \"./plugins/access-log.js\";\nimport { bodyLimit } from \"./plugins/body-limit.js\";\nimport { buildId } from \"./plugins/build-id.js\";\nimport type { BuildIdOptions } from \"./plugins/build-id.js\";\nimport { health } from \"./plugins/health.js\";\nimport type { HealthOptions } from \"./plugins/health.js\";\nimport { noindex } from \"./plugins/noindex.js\";\nimport { privateDocuments } from \"./plugins/private-documents.js\";\nimport { redirects } from \"./plugins/redirects.js\";\nimport type { RedirectRule } from \"./plugins/redirects.js\";\nimport { contentSecurityPolicy, securityHeaders } from \"./plugins/security-headers.js\";\nimport type {\n\tContentSecurityPolicyOptions,\n\tSecurityHeadersOptions,\n} from \"./plugins/security-headers.js\";\nimport { requestId } from \"./plugins/request-id.js\";\nimport type { RequestIdOptions } from \"./plugins/request-id.js\";\nimport type { RuntimeEnv } from \"./plugins/runtime-env.js\";\nimport { assets, prerendered } from \"./plugins/static.js\";\nimport type { PrerenderedOptions } from \"./plugins/static.js\";\nimport { streamingCompress } from \"./plugins/streaming-compress.js\";\nimport { trailingSlash } from \"./plugins/trailing-slash.js\";\nimport type { TrailingSlash } from \"./plugins/trailing-slash.js\";\nimport { checkOptionPlugins } from \"./plugin-options.js\";\nimport { withRequestContext } from \"./request-context.js\";\nimport { finishResponse } from \"./response-edge.js\";\nimport { abortShutdownSignal, markStopping, renewShutdownSignal } from \"./shutdown.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkRuntime,\n\tHeaderHook,\n\tListener,\n\tLogSink,\n\tPlugin,\n\tRequestStore,\n\tSentResponse,\n\tSetupInfo,\n} from \"./types.js\";\n\n/** The response for `error`, as `onError` gives it for a stage that throws. */\nfunction answerError(error: Error | HTTPResponseError, context: Context<AppServerEnv>): Response {\n\t// Why no `instanceof`: the app's routes can throw an `HTTPException` from another copy of Hono.\n\tif (\"getResponse\" in error && typeof error.getResponse === \"function\") {\n\t\tconst response: unknown = error.getResponse();\n\t\tif (response instanceof Response) {\n\t\t\treturn response;\n\t\t}\n\t}\n\tcontext.get(\"logger\").error(\"unhandled error\", errorAttributes(error));\n\treturn context.text(\"Internal Server Error\", 500);\n}\n\n// Why a WeakMap: only this copy of the package reads an app's internals, through `createEntry`.\nconst appInternals = new WeakMap<AppServer, ServerInternals>();\n\n/** A Hono app from {@link createServer}. Add routes to it before you export it. */\nexport type AppServer = Hono<AppServerEnv>;\n\n/** A server that listens. */\nexport type RunningServer = {\n\t/** The URL of each listener. */\n\turls: readonly string[];\n\t/**\n\t * Marks the server as not ready, and waits for the shutdown delay. Then it\n\t * aborts `shutdownSignal()` and runs each plugin's `onShutdown` while the\n\t * listeners stop and drain open requests. Both stop at the deadline.\n\t */\n\tshutdown: () => Promise<void>;\n};\n\n/** What `createEntry` calls on an app. */\nexport type ServerInternals = {\n\tlogger: LogSink;\n\t/** Runs each plugin's `setup` once and adds the framework handler after the app's routes. */\n\tprepare: (info: SetupInfo) => Promise<void>;\n\t/**\n\t * Starts the app's listeners, else `defaultListeners`, the host's. Call\n\t * `prepare` first. Throws when neither has a listener.\n\t */\n\tlisten: (\n\t\tframework: FrameworkRuntime,\n\t\tdefaultListeners: readonly Listener[] | undefined,\n\t) => Promise<RunningServer>;\n\t/** Runs each plugin's `onShutdown` once, and stops waiting for them at the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Sets the storage for `requestContext()` in this app's requests. `createEntry` sets the host's. */\n\tsetRequestStore: (store: RequestStore | undefined) => void;\n};\n\n/** Why 10 MiB: a form or an avatar upload fits, and a body cannot fill the memory. */\nconst DEFAULT_BODY_LIMIT = 10 * 1024 * 1024;\n\n/** Options for {@link defaultPlugins}. */\nexport type DefaultPluginsOptions = {\n\t/**\n\t * The options of the liveness and readiness probes. `false` turns them\n\t * off, such as for an app with its own `/livez` route. See {@link health}.\n\t * @default {}\n\t */\n\thealth?: HealthOptions | false;\n\trequestId?: RequestIdOptions;\n\taccessLog?: AccessLogOptions;\n\tprerendered?: PrerenderedOptions;\n\t/**\n\t * Redirects from old URL paths to new URLs. They run before\n\t * `trailingSlash`, so an old URL gets one redirect. See {@link redirects}.\n\t */\n\tredirects?: readonly RedirectRule[];\n\t/**\n\t * How a page URL ends. Set the same mode in the framework's router when it\n\t * has one, else the redirects loop. See {@link trailingSlash}.\n\t * @default \"never\"\n\t */\n\ttrailingSlash?: TrailingSlash;\n\t/**\n\t * The largest request body, in bytes. A larger body gets a 413. `false`\n\t * turns the limit off. See {@link bodyLimit}.\n\t * @default 10485760 (10 MiB)\n\t */\n\tbodyLimit?: number | false;\n\t/**\n\t * The options of the security headers. `false` turns them off. See\n\t * {@link securityHeaders}.\n\t */\n\tsecurityHeaders?: SecurityHeadersOptions | false;\n\t/**\n\t * Sets `X-Robots-Tag: noindex, nofollow` on each response, such as on a\n\t * preview deploy. See {@link noindex}.\n\t * @default false\n\t */\n\tnoindex?: boolean;\n\t/**\n\t * The options of the build ID on each document and data response. `false`\n\t * turns it off. See {@link buildId}.\n\t * @default {}, with the ID that the `appServer` Vite plugin derives from the client build\n\t */\n\tbuildId?: BuildIdOptions | false;\n\t/**\n\t * The options of the `Content-Security-Policy` of each HTML document. It\n\t * has no default. See {@link contentSecurityPolicy}.\n\t */\n\tcontentSecurityPolicy?: ContentSecurityPolicyOptions;\n\t/**\n\t * The plugin from `runtimeEnv(schema)`. It writes the public values into\n\t * each HTML document, prerendered pages included.\n\t */\n\tenv?: RuntimeEnv<unknown>;\n\t/**\n\t * The app's own plugins that see every response, prerendered pages\n\t * included, such as an auth check. They go after the plugins of the\n\t * options above and before the static stages.\n\t */\n\tbeforeStatic?: readonly Plugin[];\n};\n\n/**\n * The default pipeline, in order: `health`, `requestId`, `accessLog`,\n * `streamingCompress`, `securityHeaders`, `bodyLimit`, `noindex` (when\n * set), `buildId`, `contentSecurityPolicy` (when set), `env` (when set), the\n * `beforeStatic` plugins, `assets`, `redirects` (when the option has rules),\n * `trailingSlash`, `prerendered`, and `privateDocuments`. It is a plain\n * array, so an app can filter it or splice into it.\n *\n * @example\n * createServer({\n * \tplugins: defaultPlugins({ env, noindex: process.env.PREVIEW === \"1\", health: { ready: async () => db.ping() } }),\n * });\n */\nexport function defaultPlugins(options: DefaultPluginsOptions = {}): Plugin[] {\n\tconst maxBytes = options.bodyLimit ?? DEFAULT_BODY_LIMIT;\n\treturn [\n\t\t// Why first: a probe skips the access log, and a load balancer gets its answer with no other work.\n\t\t...(options.health === false ? [] : [health(options.health)]),\n\t\trequestId(options.requestId),\n\t\taccessLog(options.accessLog),\n\t\tstreamingCompress(),\n\t\t// Why before `bodyLimit`: its 413 must also get the security headers.\n\t\t...(options.securityHeaders === false ? [] : [securityHeaders(options.securityHeaders)]),\n\t\t...(maxBytes === false ? [] : [bodyLimit({ maxBytes })]),\n\t\t// Why before the static stages: these plugins must see the prerendered pages. Why before\n\t\t// `beforeStatic`: an app plugin, such as an auth check, then gets the CSP nonce, and its own\n\t\t// responses get these headers. Their order among themselves changes no response.\n\t\t...(options.noindex === true ? [noindex()] : []),\n\t\t...(options.buildId === false ? [] : [buildId(options.buildId)]),\n\t\t...(options.contentSecurityPolicy == null\n\t\t\t? []\n\t\t\t: [contentSecurityPolicy(options.contentSecurityPolicy)]),\n\t\t...(options.env == null ? [] : [options.env]),\n\t\t...(options.beforeStatic ?? []),\n\t\tassets(),\n\t\t...(options.redirects == null || options.redirects.length === 0\n\t\t\t? []\n\t\t\t: [redirects(options.redirects, { trailingSlash: options.trailingSlash ?? \"never\" })]),\n\t\t// Why after `assets`: in development, the dev server there answers Vite's paths, such as `/@vite/client`.\n\t\ttrailingSlash({ mode: options.trailingSlash ?? \"never\" }),\n\t\tprerendered(options.prerendered),\n\t\t// Why last: it must see only the responses of the app's routes and the framework.\n\t\tprivateDocuments(),\n\t];\n}\n\n/** Options for {@link createServer}. */\nexport type CreateServerOptions = {\n\t/** @default defaultPlugins() */\n\tplugins?: readonly Plugin[];\n\t/** @default jsonSink() */\n\tlogger?: LogSink;\n\t/** @default the host's listeners, such as `[tcp()]` on the node host */\n\tlisteners?: readonly Listener[];\n\t/**\n\t * Read the request scheme from `X-Forwarded-Proto`. Set it only behind a\n\t * proxy that overwrites that header, else a client can spoof it.\n\t * @default false\n\t */\n\ttrustForwardedProto?: boolean;\n\t/**\n\t * How many proxies in front of the server add the address they got a\n\t * request from to `X-Forwarded-For`. With N, the client address is the\n\t * Nth address from the right of that header. A header with fewer\n\t * addresses gives its leftmost address. Set it only to the number of\n\t * proxies that you run, else a client can spoof its address.\n\t * @default 0, the address of the socket\n\t */\n\ttrustedProxyHops?: number;\n\t/**\n\t * How long the listeners serve on after a stop signal, before the drain\n\t * starts. During this time, the `health` plugin's readiness probe answers\n\t * 503, so a load balancer stops sending requests first. The drain deadline\n\t * starts after the delay.\n\t * @default 0\n\t */\n\tshutdownDelayMs?: number;\n\t/**\n\t * How long open requests get to finish after the drain starts.\n\t * @default 10000\n\t */\n\tshutdownDeadlineMs?: number;\n};\n\n/**\n * The client address in an `X-Forwarded-For` header, with `hops` trusted\n * proxies, or `undefined` when the header has no address.\n */\nfunction forwardedClient(header: string | undefined, hops: number): string | undefined {\n\tconst addresses = (header ?? \"\")\n\t\t.split(\",\")\n\t\t.map((address) => address.trim())\n\t\t.filter((address) => address !== \"\");\n\treturn addresses[Math.max(0, addresses.length - hops)];\n}\n\n/** Why: `setTimeout` turns a longer delay into 1 ms. */\nconst MAX_TIMER_MS = 2_147_483_647;\n\n/** Throws for a value that is not an integer from 0 to `max`, so a bad option stops startup. */\nfunction checkCount(name: string, value: number, max = Number.MAX_SAFE_INTEGER): void {\n\tif (!Number.isInteger(value) || value < 0 || value > max) {\n\t\tconst range = max === Number.MAX_SAFE_INTEGER ? \"of 0 or more\" : `from 0 to ${max}`;\n\t\tthrow new Error(`${name} must be an integer ${range}, not ${value}.`);\n\t}\n}\n\n/**\n * The request with the scheme from `X-Forwarded-Proto`, when that header holds one.\n *\n * @example\n * withForwardedProto(new Request(\"http://example.com/\", { headers: { \"X-Forwarded-Proto\": \"https\" } })).url;\n * // => \"https://example.com/\"\n */\nexport function withForwardedProto(request: Request): Request {\n\tconst proto = request.headers.get(\"X-Forwarded-Proto\");\n\t// Why check the scheme first: a new `Request` costs a copy of the request on each call.\n\tif ((proto !== \"http\" && proto !== \"https\") || request.url.startsWith(`${proto}:`)) {\n\t\treturn request;\n\t}\n\tconst url = new URL(request.url);\n\turl.protocol = `${proto}:`;\n\t// Why copy it first: the Node listener gives a light request, which `new Request` copies only as\n\t// its first argument. As the second, its getters throw \"Illegal invocation\".\n\tconst copy = new Request(url, new Request(request));\n\t// Why: a `Request` cannot hold TRACE, so the Node listener gives a GET request that says TRACE.\n\t// The copy must say TRACE too, or a GET route answers it.\n\tif (copy.method !== request.method) {\n\t\tObject.defineProperty(copy, \"method\", { value: request.method });\n\t}\n\treturn copy;\n}\n\n/**\n * A thrown value as an `Error`. Hono sends only an `Error` to `onError`, and\n * rethrows any other value.\n */\nfunction asError(error: unknown): Error {\n\treturn error instanceof Error\n\t\t? error\n\t\t: new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });\n}\n\n/** Whether `work` settles before `ms` pass. */\nasync function settlesWithin(work: Promise<void>, ms: number): Promise<boolean> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst settled = await Promise.race([\n\t\twork.then(() => true),\n\t\tnew Promise<boolean>((resolve) => {\n\t\t\ttimer = setTimeout(resolve, ms, false);\n\t\t}),\n\t]);\n\tclearTimeout(timer);\n\treturn settled;\n}\n\n/**\n * Builds an app server: a Hono app that runs the plugins in list order, then\n * the app's own routes, then the framework. It does not listen; the\n * `app-server` CLI starts it.\n *\n * Two plugins of one option of `defaultPlugins()`, such as two `buildId()`,\n * stop startup.\n *\n * @example\n * // server.ts\n * const app = createServer({ logger: slogSink, plugins: defaultPlugins({ env }) });\n * app.get(\"/api/status\", (c) => c.json({ ok: true }));\n * export default app;\n */\nexport function createServer({\n\tplugins = defaultPlugins(),\n\tlogger = jsonSink(),\n\tlisteners,\n\ttrustForwardedProto = false,\n\ttrustedProxyHops = 0,\n\tshutdownDelayMs = 0,\n\tshutdownDeadlineMs = 10_000,\n}: CreateServerOptions = {}): AppServer {\n\tcheckOptionPlugins(plugins);\n\tcheckCount(\"trustedProxyHops\", trustedProxyHops);\n\tcheckCount(\"shutdownDelayMs\", shutdownDelayMs, MAX_TIMER_MS);\n\tcheckCount(\"shutdownDeadlineMs\", shutdownDeadlineMs, MAX_TIMER_MS);\n\tconst app = new Hono<AppServerEnv>();\n\t// Why keep the handler: a header hook that throws gets the app's `onError` answer, as a stage does.\n\tlet onError: ErrorHandler<AppServerEnv> = answerError;\n\tconst setOnError = app.onError.bind(app);\n\tapp.onError = (handler) => {\n\t\tonError = handler;\n\t\treturn setOnError(handler);\n\t};\n\tapp.onError(answerError);\n\tconst answerThrown = async (thrown: unknown, context: Context<AppServerEnv>) =>\n\t\tonError(asError(thrown), context);\n\tlet requestStore: RequestStore | undefined;\n\tif (trustForwardedProto) {\n\t\t// Why wrap `fetch`: every plugin and route, not only the framework, must see the trusted scheme.\n\t\tconst dispatch = app.fetch;\n\t\tapp.fetch = async (request, ...rest) => dispatch(withForwardedProto(request), ...rest);\n\t}\n\tapp.use(async (context, next) => {\n\t\tconst requestLog = requestLogger(logger, context);\n\t\tcontext.set(\"logger\", requestLog);\n\t\tconst remoteAddress = context.env?.remoteAddress;\n\t\tcontext.set(\n\t\t\t\"clientAddress\",\n\t\t\ttrustedProxyHops === 0\n\t\t\t\t? remoteAddress\n\t\t\t\t: (forwardedClient(context.req.header(\"X-Forwarded-For\"), trustedProxyHops) ??\n\t\t\t\t\t\tremoteAddress),\n\t\t);\n\t\t// Why lists here: each stage's header hook then changes the head once, where the response\n\t\t// leaves, and each report gets the response that leaves.\n\t\tconst hooks: HeaderHook[] = [];\n\t\tconst reports: ((sent: SentResponse) => void)[] = [];\n\t\tcontext.set(\"headerHooks\", hooks);\n\t\tcontext.set(\"sentReports\", reports);\n\t\tconst given = context.env?.edge;\n\t\t// Why claim before the stages: a request that the app sends through itself again with `c.env`\n\t\t// gets the same edge, and must change its own response.\n\t\tconst edge = given?.claim(requestLog) === true ? given : undefined;\n\t\t// Why finish in the request context: a header hook can read `requestContext()`.\n\t\tawait withRequestContext(requestStore, context, async () => {\n\t\t\tawait next();\n\t\t\tconst finishing = finishResponse(context, { hooks, reports, edge, fail: answerThrown });\n\t\t\tif (finishing != null) {\n\t\t\t\tawait finishing;\n\t\t\t}\n\t\t});\n\t\t// Why cancel: Hono drops the body of a HEAD response without a cancel, so a stream would run on.\n\t\tif (context.req.method === \"HEAD\") {\n\t\t\tawait context.res.body?.cancel();\n\t\t}\n\t});\n\t// Why `asError` at each step: a value that is not an `Error` becomes one where it is thrown,\n\t// so `onError` answers at once and each earlier plugin still sees the 500 after its `next`.\n\tfor (const { middleware, etagPart } of plugins) {\n\t\tapp.use(async (context, next) => {\n\t\t\tconst part = etagPart?.();\n\t\t\tif (part != null) {\n\t\t\t\tcontext.set(\"etagParts\", [...(context.get(\"etagParts\") ?? []), part]);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn await (middleware == null ? next() : middleware(context, next));\n\t\t\t} catch (error) {\n\t\t\t\tthrow asError(error);\n\t\t\t}\n\t\t});\n\t}\n\tapp.use(async (_, next) => {\n\t\ttry {\n\t\t\tawait next();\n\t\t} catch (error) {\n\t\t\tthrow asError(error);\n\t\t}\n\t});\n\n\tlet prepared: Promise<void> | undefined;\n\tlet running: RunningServer | undefined;\n\tlet stoppingPlugins: Promise<void> | undefined;\n\tconst internals: ServerInternals = {\n\t\tlogger,\n\t\tsetRequestStore: (store) => {\n\t\t\trequestStore = store;\n\t\t},\n\t\tprepare: async (info) => {\n\t\t\tprepared ??= (async () => {\n\t\t\t\tfor (const plugin of plugins) {\n\t\t\t\t\tawait plugin.setup?.(info);\n\t\t\t\t}\n\t\t\t\tapp.all(\"*\", async (context) => context.env.framework.fetch(context.req.raw, context));\n\t\t\t})().catch((error: unknown) => {\n\t\t\t\t// Why: the next request on a serverless host runs each `setup` again.\n\t\t\t\tprepared = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\treturn prepared;\n\t\t},\n\t\tlisten: async (framework, defaultListeners) => {\n\t\t\tif (running != null) {\n\t\t\t\tthrow new Error(\"This app server is already listening.\");\n\t\t\t}\n\t\t\tconst chosen = listeners ?? defaultListeners ?? [];\n\t\t\tif (chosen.length === 0) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"This app server has no listener: the app sets none, and the host has none. A serverless host calls the entry's `fetch`.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\trenewShutdownSignal();\n\t\t\tlet deadlinePassed = false;\n\t\t\tconst fetch: FetchHandler = async (request, bindings) => {\n\t\t\t\tconst response = await app.fetch(request, { ...bindings, framework });\n\t\t\t\t// Why: after the drain deadline, the listener closed the connection, so no one reads this\n\t\t\t\t// body. A cancel stops its producer, which can otherwise keep the process alive.\n\t\t\t\tif (deadlinePassed) {\n\t\t\t\t\tawait response.body?.cancel();\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t};\n\t\t\tconst starts = await Promise.allSettled(\n\t\t\t\tchosen.map(async (listener) => listener.start(fetch, { trustForwardedProto })),\n\t\t\t);\n\t\t\tconst started = starts.flatMap((start) =>\n\t\t\t\tstart.status === \"fulfilled\" ? [start.value] : [],\n\t\t\t);\n\t\t\tconst failed = starts.find((start) => start.status === \"rejected\");\n\t\t\tif (failed != null) {\n\t\t\t\t// Why stop the others: the caller gets no handle to stop them.\n\t\t\t\tawait Promise.all(started.map(async (listener) => listener.stop({ deadlineMs: 0 })));\n\t\t\t\tthrow failed.reason;\n\t\t\t}\n\t\t\tconst urls = started.map((listener) => listener.url);\n\t\t\tlogger.log(\"info\", \"listening\", { \"app_server.urls\": urls });\n\t\t\tlet stopping: Promise<void> | undefined;\n\t\t\trunning = {\n\t\t\t\turls,\n\t\t\t\tshutdown: async () => {\n\t\t\t\t\tstopping ??= (async () => {\n\t\t\t\t\t\tmarkStopping();\n\t\t\t\t\t\tif (shutdownDelayMs > 0) {\n\t\t\t\t\t\t\tlogger.log(\"info\", \"waiting before the drain\", {\n\t\t\t\t\t\t\t\t\"app_server.delay_ms\": shutdownDelayMs,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tawait new Promise((resolve) => {\n\t\t\t\t\t\t\t\tsetTimeout(resolve, shutdownDelayMs);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogger.log(\"info\", \"draining\", { \"app_server.deadline_ms\": shutdownDeadlineMs });\n\t\t\t\t\t\tabortShutdownSignal();\n\t\t\t\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\t\t\t\tdeadlinePassed = true;\n\t\t\t\t\t\t}, shutdownDeadlineMs);\n\t\t\t\t\t\t// Why at the same time: a plugin that hangs must not keep the listeners open.\n\t\t\t\t\t\t// Why settle all: the process exits after shutdown, so one failed stop must not cut\n\t\t\t\t\t\t// the other stops short.\n\t\t\t\t\t\tconst results = await Promise.allSettled([\n\t\t\t\t\t\t\tinternals.stopPlugins(),\n\t\t\t\t\t\t\t...started.map(async (listener) => listener.stop({ deadlineMs: shutdownDeadlineMs })),\n\t\t\t\t\t\t]);\n\t\t\t\t\t\tclearTimeout(deadline);\n\t\t\t\t\t\tconst rejected = results.find((result) => result.status === \"rejected\");\n\t\t\t\t\t\tif (rejected != null) {\n\t\t\t\t\t\t\tthrow rejected.reason;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogger.log(\"info\", \"stopped\", {});\n\t\t\t\t\t})();\n\t\t\t\t\treturn stopping;\n\t\t\t\t},\n\t\t\t};\n\t\t\treturn running;\n\t\t},\n\t\tstopPlugins: async () => {\n\t\t\tstoppingPlugins ??= (async () => {\n\t\t\t\tconst hooks = (async () => {\n\t\t\t\t\tconst results = await Promise.allSettled(\n\t\t\t\t\t\tplugins.map(async (plugin) => plugin.onShutdown?.()),\n\t\t\t\t\t);\n\t\t\t\t\tfor (const result of results) {\n\t\t\t\t\t\tif (result.status === \"rejected\") {\n\t\t\t\t\t\t\tlogger.log(\"error\", \"plugin shutdown failed\", errorAttributes(result.reason));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\tif (!(await settlesWithin(hooks, shutdownDeadlineMs))) {\n\t\t\t\t\tlogger.log(\"warn\", \"plugin shutdown passed the deadline\", {\n\t\t\t\t\t\t\"app_server.deadline_ms\": shutdownDeadlineMs,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn stoppingPlugins;\n\t\t},\n\t};\n\tappInternals.set(app, internals);\n\treturn app;\n}\n\n/** The internals of an app from {@link createServer} of this copy of the package, else `undefined`. */\nexport function serverInternals(app: AppServer): ServerInternals | undefined {\n\treturn appInternals.get(app);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,UAAU,KAAU,EAAE,UAAuC;CAC5E,IAAI,CAAC,UAAU,IAAI,WAAW,IAC7B,OAAO,GAAG,IAAI,WAAW,IAAI;CAE9B,MAAM,QAAQ,CAAC,GAAG,IAAI,aAAa,KAAK,CAAC,CAAC,CACxC,KAAK,QAAQ,GAAG,mBAAmB,GAAG,EAAE,UAAU,CAAC,CACnD,KAAK,GAAG;CACV,OAAO,GAAG,IAAI,SAAS,GAAG;AAC3B;;AAGA,SAAS,cAAc,SAA6B,EAAE,UAA+B;CACpF,IAAI,WAAW,QAAQ,CAAC,QACvB,OAAO;CAER,MAAM,MAAM,IAAI,MAAM,OAAO;CAC7B,OAAO,OAAO,OAAO,SAAY,GAAG,IAAI,SAAS,UAAU,KAAK,EAAE,OAAO,CAAC;AAC3E;;;;;;;;;;;;AAaA,SAAgB,UAAU,EACzB,cAAc,MACd,YACA,eAAe,UACM,CAAC,GAAW;CACjC,OAAO;EACN,MAAM;EACN,YAAY,OAAO,SAAS,SAAS;GACpC,MAAM,UAAU,YAAY,IAAI;GAEhC,OAAO,eACJ,eAAe,SAAS,OAAO,YAAY;IAC3C,IAAI,QAAQ,IAAI,cAAc,CAAC,EA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