@ngrok/app-server 0.3.1 → 0.3.2

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 (39) hide show
  1. package/README.md +32 -12
  2. package/dist/cli.js +2 -2
  3. package/dist/{create-server-DkTeIJ8L.js → create-server-D0De6R7Q.js} +23 -13
  4. package/dist/create-server-D0De6R7Q.js.map +1 -0
  5. package/dist/{entry-CM6Ma-Tv.d.ts → create-server-kzZWd_Lo.d.ts} +10 -61
  6. package/dist/entry-DuGgSKeB.d.ts +58 -0
  7. package/dist/{entry-CenmvESk.js → entry-UDsxuqBC.js} +2 -2
  8. package/dist/{entry-CenmvESk.js.map → entry-UDsxuqBC.js.map} +1 -1
  9. package/dist/index.d.ts +4 -3
  10. package/dist/index.js +2 -2
  11. package/dist/{load-entry-CmkdlmDX.js → load-entry-Bodyd2Ok.js} +4 -4
  12. package/dist/{load-entry-CmkdlmDX.js.map → load-entry-Bodyd2Ok.js.map} +1 -1
  13. package/dist/{node-BFH82eeL.js → node-C1qudLs_.js} +2 -2
  14. package/dist/{node-BFH82eeL.js.map → node-C1qudLs_.js.map} +1 -1
  15. package/dist/node.d.ts +1 -1
  16. package/dist/node.js +1 -1
  17. package/dist/react-router.d.ts +1 -1
  18. package/dist/request-context-BtQ87VYb.js.map +1 -1
  19. package/dist/{script-hashes-hqUk6kG7.js → script-hashes-C6hQ5XnP.js} +22 -4
  20. package/dist/script-hashes-C6hQ5XnP.js.map +1 -0
  21. package/dist/{serve-Cc-ADdhZ.js → serve-caOkS3o5.js} +2 -2
  22. package/dist/{serve-Cc-ADdhZ.js.map → serve-caOkS3o5.js.map} +1 -1
  23. package/dist/{start-Cb3kknlF.js → start-DREqYrZh.js} +4 -4
  24. package/dist/{start-Cb3kknlF.js.map → start-DREqYrZh.js.map} +1 -1
  25. package/dist/tanstack-start.d.ts +2 -2
  26. package/dist/testing.d.ts +56 -0
  27. package/dist/testing.js +114 -0
  28. package/dist/testing.js.map +1 -0
  29. package/dist/{trailing-slash-DX7NB88H.d.ts → trailing-slash-BrymAEGv.d.ts} +2 -2
  30. package/dist/{types-DLYxYS6M.d.ts → types-CEvzAmcn.d.ts} +2 -2
  31. package/dist/vercel.d.ts +2 -2
  32. package/dist/vercel.js +2 -2
  33. package/dist/{vite-iioAoxSt.js → vite-tTxVimP6.js} +2 -15
  34. package/dist/vite-tTxVimP6.js.map +1 -0
  35. package/dist/vite.js +1 -1
  36. package/package.json +5 -1
  37. package/dist/create-server-DkTeIJ8L.js.map +0 -1
  38. package/dist/script-hashes-hqUk6kG7.js.map +0 -1
  39. package/dist/vite-iioAoxSt.js.map +0 -1
@@ -0,0 +1,58 @@
1
+ import { a as FrameworkRuntime, c as HostRuntime, d as ListenerBindings, h as Mode, r as FetchHandler, t as AppServerEnv } from "./types-CEvzAmcn.js";
2
+ import { t as AppServer } from "./create-server-kzZWd_Lo.js";
3
+ import { MiddlewareHandler } from "hono";
4
+ /** The version of the contract between the CLI and the `appServer` export of a build. */
5
+ declare const ENTRY_PROTOCOL = 2;
6
+ /**
7
+ * What a server build exports as `appServer`. The CLI calls it, so the copy
8
+ * of this package in the build runs the server, and the CLI's copy runs
9
+ * nothing.
10
+ */
11
+ type AppServerEntry = {
12
+ /** The CLI refuses an entry with another version. */
13
+ protocol: typeof ENTRY_PROTOCOL;
14
+ /** The app. Two entries with the same app share its plugins. */
15
+ app: AppServer;
16
+ /**
17
+ * Production: runs each plugin's `setup` and listens. When the host's
18
+ * lifecycle stops, such as on `SIGTERM`, it shuts down.
19
+ */
20
+ start: () => Promise<void>;
21
+ /**
22
+ * Production, for a serverless host: answers one request, and does not
23
+ * listen. The first call runs each plugin's `setup`.
24
+ */
25
+ fetch: FetchHandler;
26
+ /** Development: answers one request with the dev server inside the pipeline. */
27
+ fetchDev: (request: Request, bindings: ListenerBindings, devServer: MiddlewareHandler<AppServerEnv>) => Promise<Response>;
28
+ /** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */
29
+ stopPlugins: () => Promise<void>;
30
+ /** Aborts `shutdownSignal()` of this copy of the package. */
31
+ abortShutdownSignal: () => void;
32
+ };
33
+ /** Options for {@link createEntry}. */
34
+ type CreateEntryOptions = {
35
+ /** The app from `createServer`. */
36
+ app: AppServer;
37
+ /** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */
38
+ host: HostRuntime;
39
+ /** Makes the run side of the framework adapter for a mode. */
40
+ framework: (mode: Mode) => FrameworkRuntime;
41
+ /**
42
+ * The client build, as a file path or a `file:` URL. The entry that the
43
+ * Vite plugin generates sets it.
44
+ * @default the framework's `clientDirectory`
45
+ */
46
+ clientDirectory?: string;
47
+ };
48
+ /**
49
+ * The `appServer` export of a server build: an app from `createServer`, the
50
+ * host, and the framework adapter for each mode. The `appServer` Vite plugin
51
+ * generates this export. Call this for a build without the plugin.
52
+ *
53
+ * @example
54
+ * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
55
+ */
56
+ declare function createEntry({ app, host, framework, clientDirectory }: CreateEntryOptions): AppServerEntry;
57
+ export { CreateEntryOptions as n, createEntry as r, AppServerEntry as t };
58
+ //# sourceMappingURL=entry-DuGgSKeB.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { t as errorAttributes } from "./log-BP6xXXZl.js";
2
- import { _ as abortShutdownSignal, r as serverInternals } from "./create-server-DkTeIJ8L.js";
2
+ import { _ as abortShutdownSignal, r as serverInternals } from "./create-server-D0De6R7Q.js";
3
3
  import { a as keptFiles } from "./static-files-Beju9riB.js";
4
4
  import { r as readBuildManifest } from "./build-manifest-UDNk81Ce.js";
5
5
 
@@ -113,4 +113,4 @@ function isAppServerEntry(value) {
113
113
  }
114
114
 
115
115
  export { isAppServerEntry as n, createEntry as t };
116
- //# sourceMappingURL=entry-CenmvESk.js.map
116
+ //# sourceMappingURL=entry-UDsxuqBC.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"entry-CenmvESk.js","names":[],"sources":["../src/core/entry.ts"],"sourcesContent":["import type { MiddlewareHandler } from \"hono\";\nimport { readBuildManifest } from \"./build-manifest.js\";\nimport { serverInternals } from \"./create-server.js\";\nimport type { AppServer } from \"./create-server.js\";\nimport { errorAttributes } from \"./log.js\";\nimport { abortShutdownSignal } from \"./shutdown.js\";\nimport { keptFiles } from \"./static-files.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkRuntime,\n\tHostRuntime,\n\tListenerBindings,\n\tMode,\n\tSetupInfo,\n} from \"./types.js\";\n\n/** The version of the contract between the CLI and the `appServer` export of a build. */\nexport const ENTRY_PROTOCOL = 2;\n\n/**\n * What a server build exports as `appServer`. The CLI calls it, so the copy\n * of this package in the build runs the server, and the CLI's copy runs\n * nothing.\n */\nexport type AppServerEntry = {\n\t/** The CLI refuses an entry with another version. */\n\tprotocol: typeof ENTRY_PROTOCOL;\n\t/** The app. Two entries with the same app share its plugins. */\n\tapp: AppServer;\n\t/**\n\t * Production: runs each plugin's `setup` and listens. When the host's\n\t * lifecycle stops, such as on `SIGTERM`, it shuts down.\n\t */\n\tstart: () => Promise<void>;\n\t/**\n\t * Production, for a serverless host: answers one request, and does not\n\t * listen. The first call runs each plugin's `setup`.\n\t */\n\tfetch: FetchHandler;\n\t/** Development: answers one request with the dev server inside the pipeline. */\n\tfetchDev: (\n\t\trequest: Request,\n\t\tbindings: ListenerBindings,\n\t\tdevServer: MiddlewareHandler<AppServerEnv>,\n\t) => Promise<Response>;\n\t/** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Aborts `shutdownSignal()` of this copy of the package. */\n\tabortShutdownSignal: () => void;\n};\n\n/** Options for {@link createEntry}. */\nexport type CreateEntryOptions = {\n\t/** The app from `createServer`. */\n\tapp: AppServer;\n\t/** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */\n\thost: HostRuntime;\n\t/** Makes the run side of the framework adapter for a mode. */\n\tframework: (mode: Mode) => FrameworkRuntime;\n\t/**\n\t * The client build, as a file path or a `file:` URL. The entry that the\n\t * Vite plugin generates sets it.\n\t * @default the framework's `clientDirectory`\n\t */\n\tclientDirectory?: string;\n};\n\n/**\n * The `appServer` export of a server build: an app from `createServer`, the\n * host, and the framework adapter for each mode. The `appServer` Vite plugin\n * generates this export. Call this for a build without the plugin.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport function createEntry({\n\tapp,\n\thost,\n\tframework,\n\tclientDirectory,\n}: CreateEntryOptions): AppServerEntry {\n\tconst internals = serverInternals(app);\n\tif (internals == null) {\n\t\tthrow new Error(\n\t\t\t\"The app is not from `createServer()` of the copy of @ngrok/app-server in this build.\",\n\t\t);\n\t}\n\tinternals.setRequestStore(host.storage);\n\tconst setupInfo = async (runtime: FrameworkRuntime) => {\n\t\tconst directory = clientDirectory ?? runtime.clientDirectory;\n\t\tif (directory == null) {\n\t\t\tthrow new Error(\n\t\t\t\t`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`,\n\t\t\t);\n\t\t}\n\t\tconst files = host.files(directory);\n\t\treturn {\n\t\t\tfiles,\n\t\t\tisDataRequest: runtime.isDataRequest ?? (() => false),\n\t\t\tcontentTypes: runtime.contentTypes ?? {},\n\t\t\tgzip: host.gzip,\n\t\t\tlogger: internals.logger,\n\t\t};\n\t};\n\t/** Runs each plugin's `setup` for production, and gives the framework's run side. */\n\tconst prepareProduction = async (): Promise<FrameworkRuntime> => {\n\t\tconst runtime = framework(\"production\");\n\t\tconst shared = await setupInfo(runtime);\n\t\tconst snapshot = await shared.files.snapshot?.();\n\t\t// Why only with a snapshot: it promises that the client build does not change while the server runs.\n\t\tconst files = snapshot == null ? shared.files : keptFiles(snapshot);\n\t\tconst manifest = await readBuildManifest(files);\n\t\tconst info: SetupInfo = {\n\t\t\t...shared,\n\t\t\tfiles,\n\t\t\tmode: \"production\",\n\t\t\tprerenderedPaths: runtime.prerenderedPaths ?? manifest.prerendered,\n\t\t\tcapturedHeaders: new Map(Object.entries(manifest.headers)),\n\t\t\tscriptHashes: new Map(Object.entries(manifest.scriptHashes)),\n\t\t\tbuildId: manifest.buildId,\n\t\t};\n\t\tawait internals.prepare(info);\n\t\treturn runtime;\n\t};\n\tlet preparing: Promise<FrameworkRuntime> | undefined;\n\t/**\n\t * The production run side, set up once. Why forget a failure: a serverless\n\t * instance stays up, so the next request runs each `setup` again.\n\t */\n\tconst production = async (): Promise<FrameworkRuntime> => {\n\t\tpreparing ??= prepareProduction().catch((error: unknown) => {\n\t\t\tpreparing = undefined;\n\t\t\tthrow error;\n\t\t});\n\t\treturn preparing;\n\t};\n\tlet development: FrameworkRuntime | undefined;\n\treturn {\n\t\tprotocol: ENTRY_PROTOCOL,\n\t\tapp,\n\t\tstart: async () => {\n\t\t\tconst runtime = await production();\n\t\t\tconst server = await internals.listen(runtime, host.listeners?.());\n\t\t\thost.lifecycle?.onStop(async () =>\n\t\t\t\tserver.shutdown().catch((error: unknown) => {\n\t\t\t\t\tinternals.logger.log(\"error\", \"shutdown failed\", errorAttributes(error));\n\t\t\t\t\tthrow error;\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tfetch: async (request, bindings) => {\n\t\t\t// Why log it: the host sends a 500 with no log, and no app handler runs before setup ends.\n\t\t\tconst runtime = await production().catch((error: unknown) => {\n\t\t\t\tinternals.logger.log(\"error\", \"setup failed\", errorAttributes(error));\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: runtime });\n\t\t},\n\t\tfetchDev: async (request, bindings, devServer) => {\n\t\t\tdevelopment ??= framework(\"development\");\n\t\t\tawait internals.prepare({\n\t\t\t\t...(await setupInfo(development)),\n\t\t\t\tmode: \"development\",\n\t\t\t\tdevServer,\n\t\t\t\tprerenderedPaths: development.prerenderedPaths,\n\t\t\t\tcapturedHeaders: new Map(),\n\t\t\t\tscriptHashes: new Map(),\n\t\t\t\t// Why none: development has no client build, and Vite's HMR updates an open tab after each edit.\n\t\t\t\tbuildId: undefined,\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: development });\n\t\t},\n\t\tstopPlugins: internals.stopPlugins,\n\t\tabortShutdownSignal,\n\t};\n}\n\n/**\n * Whether a value is an entry of this protocol version.\n *\n * @example\n * isAppServerEntry((await import(\"./build/server/app-server.js\")).appServer); // => true\n */\nexport function isAppServerEntry(value: unknown): value is AppServerEntry {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"protocol\" in value &&\n\t\tvalue.protocol === ENTRY_PROTOCOL\n\t);\n}\n"],"mappings":";;;;;;;AAkBA,MAAa,iBAAiB;;;;;;;;;AA0D9B,SAAgB,YAAY,EAC3B,KACA,MACA,WACA,mBACsC;CACtC,MAAM,YAAY,gBAAgB,GAAG;CACrC,IAAI,aAAa,MAChB,MAAM,IAAI,MACT,sFACD;CAED,UAAU,gBAAgB,KAAK,OAAO;CACtC,MAAM,YAAY,OAAO,YAA8B;EACtD,MAAM,YAAY,mBAAmB,QAAQ;EAC7C,IAAI,aAAa,MAChB,MAAM,IAAI,MACT,2CAA2C,QAAQ,KAAK,yCACzD;EAGD,OAAO;GACN,OAFa,KAAK,MAAM,SAEpB;GACJ,eAAe,QAAQ,wBAAwB;GAC/C,cAAc,QAAQ,gBAAgB,CAAC;GACvC,MAAM,KAAK;GACX,QAAQ,UAAU;EACnB;CACD;;CAEA,MAAM,oBAAoB,YAAuC;EAChE,MAAM,UAAU,UAAU,YAAY;EACtC,MAAM,SAAS,MAAM,UAAU,OAAO;EACtC,MAAM,WAAW,MAAM,OAAO,MAAM,WAAW;EAE/C,MAAM,QAAQ,YAAY,OAAO,OAAO,QAAQ,UAAU,QAAQ;EAClE,MAAM,WAAW,MAAM,kBAAkB,KAAK;EAC9C,MAAM,OAAkB;GACvB,GAAG;GACH;GACA,MAAM;GACN,kBAAkB,QAAQ,oBAAoB,SAAS;GACvD,iBAAiB,IAAI,IAAI,OAAO,QAAQ,SAAS,OAAO,CAAC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MAAM;AAER"}
1
+ {"version":3,"file":"entry-UDsxuqBC.js","names":[],"sources":["../src/core/entry.ts"],"sourcesContent":["import type { MiddlewareHandler } from \"hono\";\nimport { readBuildManifest } from \"./build-manifest.js\";\nimport { serverInternals } from \"./create-server.js\";\nimport type { AppServer } from \"./create-server.js\";\nimport { errorAttributes } from \"./log.js\";\nimport { abortShutdownSignal } from \"./shutdown.js\";\nimport { keptFiles } from \"./static-files.js\";\nimport type {\n\tAppServerEnv,\n\tFetchHandler,\n\tFrameworkRuntime,\n\tHostRuntime,\n\tListenerBindings,\n\tMode,\n\tSetupInfo,\n} from \"./types.js\";\n\n/** The version of the contract between the CLI and the `appServer` export of a build. */\nexport const ENTRY_PROTOCOL = 2;\n\n/**\n * What a server build exports as `appServer`. The CLI calls it, so the copy\n * of this package in the build runs the server, and the CLI's copy runs\n * nothing.\n */\nexport type AppServerEntry = {\n\t/** The CLI refuses an entry with another version. */\n\tprotocol: typeof ENTRY_PROTOCOL;\n\t/** The app. Two entries with the same app share its plugins. */\n\tapp: AppServer;\n\t/**\n\t * Production: runs each plugin's `setup` and listens. When the host's\n\t * lifecycle stops, such as on `SIGTERM`, it shuts down.\n\t */\n\tstart: () => Promise<void>;\n\t/**\n\t * Production, for a serverless host: answers one request, and does not\n\t * listen. The first call runs each plugin's `setup`.\n\t */\n\tfetch: FetchHandler;\n\t/** Development: answers one request with the dev server inside the pipeline. */\n\tfetchDev: (\n\t\trequest: Request,\n\t\tbindings: ListenerBindings,\n\t\tdevServer: MiddlewareHandler<AppServerEnv>,\n\t) => Promise<Response>;\n\t/** Runs each plugin's `onShutdown` once, up to the shutdown deadline. */\n\tstopPlugins: () => Promise<void>;\n\t/** Aborts `shutdownSignal()` of this copy of the package. */\n\tabortShutdownSignal: () => void;\n};\n\n/** Options for {@link createEntry}. */\nexport type CreateEntryOptions = {\n\t/** The app from `createServer`. */\n\tapp: AppServer;\n\t/** The run side of the host adapter, such as `host` from `@ngrok/app-server/node`. */\n\thost: HostRuntime;\n\t/** Makes the run side of the framework adapter for a mode. */\n\tframework: (mode: Mode) => FrameworkRuntime;\n\t/**\n\t * The client build, as a file path or a `file:` URL. The entry that the\n\t * Vite plugin generates sets it.\n\t * @default the framework's `clientDirectory`\n\t */\n\tclientDirectory?: string;\n};\n\n/**\n * The `appServer` export of a server build: an app from `createServer`, the\n * host, and the framework adapter for each mode. The `appServer` Vite plugin\n * generates this export. Call this for a build without the plugin.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport function createEntry({\n\tapp,\n\thost,\n\tframework,\n\tclientDirectory,\n}: CreateEntryOptions): AppServerEntry {\n\tconst internals = serverInternals(app);\n\tif (internals == null) {\n\t\tthrow new Error(\n\t\t\t\"The app is not from `createServer()` of the copy of @ngrok/app-server in this build.\",\n\t\t);\n\t}\n\tinternals.setRequestStore(host.storage);\n\tconst setupInfo = async (runtime: FrameworkRuntime) => {\n\t\tconst directory = clientDirectory ?? runtime.clientDirectory;\n\t\tif (directory == null) {\n\t\t\tthrow new Error(\n\t\t\t\t`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`,\n\t\t\t);\n\t\t}\n\t\tconst files = host.files(directory);\n\t\treturn {\n\t\t\tfiles,\n\t\t\tisDataRequest: runtime.isDataRequest ?? (() => false),\n\t\t\tcontentTypes: runtime.contentTypes ?? {},\n\t\t\tgzip: host.gzip,\n\t\t\tlogger: internals.logger,\n\t\t};\n\t};\n\t/** Runs each plugin's `setup` for production, and gives the framework's run side. */\n\tconst prepareProduction = async (): Promise<FrameworkRuntime> => {\n\t\tconst runtime = framework(\"production\");\n\t\tconst shared = await setupInfo(runtime);\n\t\tconst snapshot = await shared.files.snapshot?.();\n\t\t// Why only with a snapshot: it promises that the client build does not change while the server runs.\n\t\tconst files = snapshot == null ? shared.files : keptFiles(snapshot);\n\t\tconst manifest = await readBuildManifest(files);\n\t\tconst info: SetupInfo = {\n\t\t\t...shared,\n\t\t\tfiles,\n\t\t\tmode: \"production\",\n\t\t\tprerenderedPaths: runtime.prerenderedPaths ?? manifest.prerendered,\n\t\t\tcapturedHeaders: new Map(Object.entries(manifest.headers)),\n\t\t\tscriptHashes: new Map(Object.entries(manifest.scriptHashes)),\n\t\t\tbuildId: manifest.buildId,\n\t\t};\n\t\tawait internals.prepare(info);\n\t\treturn runtime;\n\t};\n\tlet preparing: Promise<FrameworkRuntime> | undefined;\n\t/**\n\t * The production run side, set up once. Why forget a failure: a serverless\n\t * instance stays up, so the next request runs each `setup` again.\n\t */\n\tconst production = async (): Promise<FrameworkRuntime> => {\n\t\tpreparing ??= prepareProduction().catch((error: unknown) => {\n\t\t\tpreparing = undefined;\n\t\t\tthrow error;\n\t\t});\n\t\treturn preparing;\n\t};\n\tlet development: FrameworkRuntime | undefined;\n\treturn {\n\t\tprotocol: ENTRY_PROTOCOL,\n\t\tapp,\n\t\tstart: async () => {\n\t\t\tconst runtime = await production();\n\t\t\tconst server = await internals.listen(runtime, host.listeners?.());\n\t\t\thost.lifecycle?.onStop(async () =>\n\t\t\t\tserver.shutdown().catch((error: unknown) => {\n\t\t\t\t\tinternals.logger.log(\"error\", \"shutdown failed\", errorAttributes(error));\n\t\t\t\t\tthrow error;\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t\tfetch: async (request, bindings) => {\n\t\t\t// Why log it: the host sends a 500 with no log, and no app handler runs before setup ends.\n\t\t\tconst runtime = await production().catch((error: unknown) => {\n\t\t\t\tinternals.logger.log(\"error\", \"setup failed\", errorAttributes(error));\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: runtime });\n\t\t},\n\t\tfetchDev: async (request, bindings, devServer) => {\n\t\t\tdevelopment ??= framework(\"development\");\n\t\t\tawait internals.prepare({\n\t\t\t\t...(await setupInfo(development)),\n\t\t\t\tmode: \"development\",\n\t\t\t\tdevServer,\n\t\t\t\tprerenderedPaths: development.prerenderedPaths,\n\t\t\t\tcapturedHeaders: new Map(),\n\t\t\t\tscriptHashes: new Map(),\n\t\t\t\t// Why none: development has no client build, and Vite's HMR updates an open tab after each edit.\n\t\t\t\tbuildId: undefined,\n\t\t\t});\n\t\t\treturn app.fetch(request, { ...bindings, framework: development });\n\t\t},\n\t\tstopPlugins: internals.stopPlugins,\n\t\tabortShutdownSignal,\n\t};\n}\n\n/**\n * Whether a value is an entry of this protocol version.\n *\n * @example\n * isAppServerEntry((await import(\"./build/server/app-server.js\")).appServer); // => true\n */\nexport function isAppServerEntry(value: unknown): value is AppServerEntry {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t\"protocol\" in value &&\n\t\tvalue.protocol === ENTRY_PROTOCOL\n\t);\n}\n"],"mappings":";;;;;;;AAkBA,MAAa,iBAAiB;;;;;;;;;AA0D9B,SAAgB,YAAY,EAC3B,KACA,MACA,WACA,mBACsC;CACtC,MAAM,YAAY,gBAAgB,GAAG;CACrC,IAAI,aAAa,MAChB,MAAM,IAAI,MACT,sFACD;CAED,UAAU,gBAAgB,KAAK,OAAO;CACtC,MAAM,YAAY,OAAO,YAA8B;EACtD,MAAM,YAAY,mBAAmB,QAAQ;EAC7C,IAAI,aAAa,MAChB,MAAM,IAAI,MACT,2CAA2C,QAAQ,KAAK,yCACzD;EAGD,OAAO;GACN,OAFa,KAAK,MAAM,SAEpB;GACJ,eAAe,QAAQ,wBAAwB;GAC/C,cAAc,QAAQ,gBAAgB,CAAC;GACvC,MAAM,KAAK;GACX,QAAQ,UAAU;EACnB;CACD;;CAEA,MAAM,oBAAoB,YAAuC;EAChE,MAAM,UAAU,UAAU,YAAY;EACtC,MAAM,SAAS,MAAM,UAAU,OAAO;EACtC,MAAM,WAAW,MAAM,OAAO,MAAM,WAAW;EAE/C,MAAM,QAAQ,YAAY,OAAO,OAAO,QAAQ,UAAU,QAAQ;EAClE,MAAM,WAAW,MAAM,kBAAkB,KAAK;EAC9C,MAAM,OAAkB;GACvB,GAAG;GACH;GACA,MAAM;GACN,kBAA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;;AAQA,SAAgB,iBAAiB,OAAyC;CACzE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,cAAc,SACd,MAAM;AAER"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { C as SetupInfo, E as ResponseEdge, S as ServerBindings, T as StaticFiles, _ as RequestContext, a as FrameworkRuntime, b as ResponseHeaders, c as HostRuntime, d as ListenerBindings, f as ListenerStartOptions, g as Plugin, h as Mode, i as FileInfo, l as Lifecycle, m as LogSink, n as ByteRange, o as FrameworkRuntimeFactory, p as LogLevel, r as FetchHandler, s as HeaderHook, t as AppServerEnv, u as Listener, v as RequestLogger, w as StartedListener, x as SentResponse, y as RequestStore } from "./types-DLYxYS6M.js";
2
- import { A as BuildIdOptions, C as SecurityHeadersOptions, D as redirects, E as RedirectRule, M as AccessLogOptions, N as accessLog, O as HealthOptions, S as SecurityHeaderValues, T as securityHeaders, _ as StandardSchemaV1, a as CreateServerOptions, b as requestId, c as createServer, d as assets, f as prerendered, g as RuntimeEnvOptions, h as RuntimeEnv, i as AppServer, j as buildId, k as health, l as defaultPlugins, m as PUBLIC_ENV_SCRIPT_ID, n as CreateEntryOptions, o as DefaultPluginsOptions, p as InferOutput, r as createEntry, s as RunningServer, t as AppServerEntry, u as PrerenderedOptions, v as runtimeEnv, w as contentSecurityPolicy, x as ContentSecurityPolicyOptions, y as RequestIdOptions } from "./entry-CM6Ma-Tv.js";
3
- import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-DX7NB88H.js";
1
+ import { C as SetupInfo, E as ResponseEdge, S as ServerBindings, T as StaticFiles, _ as RequestContext, a as FrameworkRuntime, b as ResponseHeaders, c as HostRuntime, d as ListenerBindings, f as ListenerStartOptions, g as Plugin, h as Mode, i as FileInfo, l as Lifecycle, m as LogSink, n as ByteRange, o as FrameworkRuntimeFactory, p as LogLevel, r as FetchHandler, s as HeaderHook, t as AppServerEnv, u as Listener, v as RequestLogger, w as StartedListener, x as SentResponse, y as RequestStore } from "./types-CEvzAmcn.js";
2
+ import { A as accessLog, C as RedirectRule, D as BuildIdOptions, E as health, O as buildId, S as securityHeaders, T as HealthOptions, _ as requestId, a as createServer, b as SecurityHeadersOptions, c as assets, d as PUBLIC_ENV_SCRIPT_ID, f as RuntimeEnv, g as RequestIdOptions, h as runtimeEnv, i as RunningServer, k as AccessLogOptions, l as prerendered, m as StandardSchemaV1, n as CreateServerOptions, o as defaultPlugins, p as RuntimeEnvOptions, r as DefaultPluginsOptions, s as PrerenderedOptions, t as AppServer, u as InferOutput, v as ContentSecurityPolicyOptions, w as redirects, x as contentSecurityPolicy, y as SecurityHeaderValues } from "./create-server-kzZWd_Lo.js";
3
+ import { n as TrailingSlashOptions, r as trailingSlash, t as TrailingSlash } from "./trailing-slash-BrymAEGv.js";
4
+ import { n as CreateEntryOptions, r as createEntry, t as AppServerEntry } from "./entry-DuGgSKeB.js";
4
5
  import { Context, Next } from "hono";
5
6
  /** One server-sent event. */
6
7
  type ServerSentEvent = {
package/dist/index.js CHANGED
@@ -3,8 +3,8 @@ import { a as replaceResponse, o as withHeaderHook, s as writableHeaders } from
3
3
  import { r as buildId, s as optionPlugin } from "./build-id-C6sYO9Yp.js";
4
4
  import { r as jsonSink } from "./log-BP6xXXZl.js";
5
5
  import { t as ResponseEdge } from "./response-edge-Bc1-C_Cx.js";
6
- import { a as streamingCompress, b as accessLog, c as prefersMarkdown, d as securityHeaders, f as redirects, g as health, h as noindex, l as requestId, m as privateDocuments, n as defaultPlugins, o as assets, p as trailingSlash, s as prerendered, t as createServer, u as contentSecurityPolicy, v as shutdownSignal, y as bodyLimit } from "./create-server-DkTeIJ8L.js";
7
- import { t as createEntry } from "./entry-CenmvESk.js";
6
+ import { a as streamingCompress, b as accessLog, c as prefersMarkdown, d as securityHeaders, f as redirects, g as health, h as noindex, l as requestId, m as privateDocuments, n as defaultPlugins, o as assets, p as trailingSlash, s as prerendered, t as createServer, u as contentSecurityPolicy, v as shutdownSignal, y as bodyLimit } from "./create-server-D0De6R7Q.js";
7
+ import { t as createEntry } from "./entry-UDsxuqBC.js";
8
8
 
9
9
  // src/core/event-stream.ts
10
10
  function formatEvent({ data, event, id }) {
@@ -1,6 +1,6 @@
1
- import { t as createServer } from "./create-server-DkTeIJ8L.js";
2
- import { n as isAppServerEntry, t as createEntry } from "./entry-CenmvESk.js";
3
- import { t as host } from "./node-BFH82eeL.js";
1
+ import { t as createServer } from "./create-server-D0De6R7Q.js";
2
+ import { n as isAppServerEntry, t as createEntry } from "./entry-UDsxuqBC.js";
3
+ import { t as host } from "./node-C1qudLs_.js";
4
4
 
5
5
  // src/cli/load-entry.ts
6
6
  /** Entries that this copy made for plain React Router builds, by build module. */
@@ -34,4 +34,4 @@ async function loadEntry(build) {
34
34
  }
35
35
 
36
36
  export { loadEntry as t };
37
- //# sourceMappingURL=load-entry-CmkdlmDX.js.map
37
+ //# sourceMappingURL=load-entry-Bodyd2Ok.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"load-entry-CmkdlmDX.js","names":[],"sources":["../src/cli/load-entry.ts"],"sourcesContent":["import { createServer } from \"../core/create-server.js\";\nimport { createEntry, ENTRY_PROTOCOL, isAppServerEntry } from \"../core/entry.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { host } from \"../node/index.js\";\n\n/** Entries that this copy made for plain React Router builds, by build module. */\nconst plainEntries = new WeakMap<object, AppServerEntry>();\n\n/**\n * The entry that runs a server build: its `appServer` export when the\n * `appServer` Vite plugin made it, else this copy of the package over a\n * plain React Router build, on the node host, with the default plugins.\n */\nexport async function loadEntry(build: unknown): Promise<AppServerEntry> {\n\tif (typeof build !== \"object\" || build == null) {\n\t\tthrow new Error(\"The server build entry is not a module.\");\n\t}\n\tconst exported: unknown = Reflect.get(build, \"appServer\");\n\tif (exported != null) {\n\t\tif (!isAppServerEntry(exported)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The build's @ngrok/app-server does not use entry protocol ${ENTRY_PROTOCOL}. Install the same version of @ngrok/app-server that the build uses.`,\n\t\t\t);\n\t\t}\n\t\treturn exported;\n\t}\n\tconst known = plainEntries.get(build);\n\tif (known != null) {\n\t\treturn known;\n\t}\n\tconst { isServerBuild, runtime } = await import(\"../react-router/index.js\");\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server build entry is not a React Router server build.\");\n\t}\n\tconst entry = createEntry({\n\t\tapp: createServer({\n\t\t\ttrustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\",\n\t\t\ttrustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0),\n\t\t}),\n\t\thost,\n\t\tframework: (mode) => runtime(build, { mode }),\n\t});\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;;AAMA,MAAM,+BAAe,IAAI,QAAgC;;;;;;AAOzD,eAAsB,UAAU,OAAyC;CACxE,IAAI,OAAO,UAAU,YAAY,SAAS,MACzC,MAAM,IAAI,MAAM,yCAAyC;CAE1D,MAAM,WAAoB,QAAQ,IAAI,OAAO,WAAW;CACxD,IAAI,YAAY,MAAM;EACrB,IAAI,CAAC,iBAAiB,QAAQ,GAC7B,MAAM,IAAI,MACT,+DAA4E,qEAC7E;EAED,OAAO;CACR;CACA,MAAM,QAAQ,aAAa,IAAI,KAAK;CACpC,IAAI,SAAS,MACZ,OAAO;CAER,MAAM,EAAE,eAAe,YAAY,MAAM,OAAO;CAChD,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,4DAA4D;CAE7E,MAAM,QAAQ,YAAY;EACzB,KAAK,aAAa;GACjB,qBAAqB,QAAQ,IAAI,0BAA0B;GAC3D,kBAAkB,OAAO,QAAQ,IAAI,sBAAsB,CAAC;EAC7D,CAAC;EACD;EACA,YAAY,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;CAC7C,CAAC;CACD,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
1
+ {"version":3,"file":"load-entry-Bodyd2Ok.js","names":[],"sources":["../src/cli/load-entry.ts"],"sourcesContent":["import { createServer } from \"../core/create-server.js\";\nimport { createEntry, ENTRY_PROTOCOL, isAppServerEntry } from \"../core/entry.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { host } from \"../node/index.js\";\n\n/** Entries that this copy made for plain React Router builds, by build module. */\nconst plainEntries = new WeakMap<object, AppServerEntry>();\n\n/**\n * The entry that runs a server build: its `appServer` export when the\n * `appServer` Vite plugin made it, else this copy of the package over a\n * plain React Router build, on the node host, with the default plugins.\n */\nexport async function loadEntry(build: unknown): Promise<AppServerEntry> {\n\tif (typeof build !== \"object\" || build == null) {\n\t\tthrow new Error(\"The server build entry is not a module.\");\n\t}\n\tconst exported: unknown = Reflect.get(build, \"appServer\");\n\tif (exported != null) {\n\t\tif (!isAppServerEntry(exported)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The build's @ngrok/app-server does not use entry protocol ${ENTRY_PROTOCOL}. Install the same version of @ngrok/app-server that the build uses.`,\n\t\t\t);\n\t\t}\n\t\treturn exported;\n\t}\n\tconst known = plainEntries.get(build);\n\tif (known != null) {\n\t\treturn known;\n\t}\n\tconst { isServerBuild, runtime } = await import(\"../react-router/index.js\");\n\tif (!isServerBuild(build)) {\n\t\tthrow new Error(\"The server build entry is not a React Router server build.\");\n\t}\n\tconst entry = createEntry({\n\t\tapp: createServer({\n\t\t\ttrustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\",\n\t\t\ttrustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0),\n\t\t}),\n\t\thost,\n\t\tframework: (mode) => runtime(build, { mode }),\n\t});\n\tplainEntries.set(build, entry);\n\treturn entry;\n}\n"],"mappings":";;;;;;AAMA,MAAM,+BAAe,IAAI,QAAgC;;;;;;AAOzD,eAAsB,UAAU,OAAyC;CACxE,IAAI,OAAO,UAAU,YAAY,SAAS,MACzC,MAAM,IAAI,MAAM,yCAAyC;CAE1D,MAAM,WAAoB,QAAQ,IAAI,OAAO,WAAW;CACxD,IAAI,YAAY,MAAM;EACrB,IAAI,CAAC,iBAAiB,QAAQ,GAC7B,MAAM,IAAI,MACT,+DAA4E,qEAC7E;EAED,OAAO;CACR;CACA,MAAM,QAAQ,aAAa,IAAI,KAAK;CACpC,IAAI,SAAS,MACZ,OAAO;CAER,MAAM,EAAE,eAAe,YAAY,MAAM,OAAO;CAChD,IAAI,CAAC,cAAc,KAAK,GACvB,MAAM,IAAI,MAAM,4DAA4D;CAE7E,MAAM,QAAQ,YAAY;EACzB,KAAK,aAAa;GACjB,qBAAqB,QAAQ,IAAI,0BAA0B;GAC3D,kBAAkB,OAAO,QAAQ,IAAI,sBAAsB,CAAC;EAC7D,CAAC;EACD;EACA,YAAY,SAAS,QAAQ,OAAO,EAAE,KAAK,CAAC;CAC7C,CAAC;CACD,aAAa,IAAI,OAAO,KAAK;CAC7B,OAAO;AACR"}
@@ -1,7 +1,7 @@
1
1
  import { n as tcp } from "./tcp-Dd1Mt6sN.js";
2
2
  import { n as flushLogs } from "./log-BP6xXXZl.js";
3
3
  import { t as gzipStream } from "./gzip-Doi4wqjX.js";
4
- import { n as publicScriptHashes } from "./script-hashes-hqUk6kG7.js";
4
+ import { t as publicScriptHashes } from "./script-hashes-C6hQ5XnP.js";
5
5
  import { AsyncLocalStorage } from "node:async_hooks";
6
6
  import { setTimeout } from "node:timers";
7
7
  import { constants } from "node:fs";
@@ -330,4 +330,4 @@ const host = {
330
330
  };
331
331
 
332
332
  export { exitAfterFlush as i, devServerStage as n, nodeFiles as r, host as t };
333
- //# sourceMappingURL=node-BFH82eeL.js.map
333
+ //# sourceMappingURL=node-C1qudLs_.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-BFH82eeL.js","names":[],"sources":["../src/node/exit.ts","../src/node/files.ts","../src/node/dev-server.ts","../src/node/index.ts"],"sourcesContent":["import { setTimeout } from \"node:timers\";\nimport { flushLogs } from \"../core/log.js\";\n\n/** How long the exit waits for stdout and stderr. */\nconst FLUSH_TIMEOUT_MS = 1_000;\n\n/**\n * Exits the process after stdout and stderr write what they hold, so the last\n * log lines are not lost. The exit code is `process.exitCode`, else 0.\n *\n * Why exit at all: when shutdown is done, the server holds nothing open. A\n * timer that the app left, such as the render abort timer in React Router's\n * `entry.server`, would otherwise keep the stopped process alive.\n */\nexport function exitAfterFlush(): void {\n\tflushLogs();\n\tlet pending = 2;\n\tconst done = () => {\n\t\tpending -= 1;\n\t\tif (pending === 0) {\n\t\t\tprocess.exit();\n\t\t}\n\t};\n\tflush(process.stdout, done);\n\tflush(process.stderr, done);\n\t// Why a fallback: a reader that stops reading the pipe would hold the callbacks forever.\n\tsetTimeout(() => {\n\t\tprocess.exit();\n\t}, FLUSH_TIMEOUT_MS).unref();\n}\n\n/** Calls `done` after `stream` writes what it holds. */\nfunction flush(stream: NodeJS.WriteStream, done: () => void): void {\n\tif (\"Bun\" in globalThis) {\n\t\t// Why `end` on Bun: on Bun 1.3, the callback of a write runs before a full pipe takes the\n\t\t// earlier writes. The callback of `end` waits for them. A write after `end` still works on Bun.\n\t\tstream.end(done);\n\t\treturn;\n\t}\n\t// Why a write: its callback runs after each earlier write. A pipe on macOS writes async.\n\t// Why not `end` on Node: a write after `end` throws there.\n\tstream.write(\"\", done);\n}\n","import { constants } from \"node:fs\";\nimport { access, open, readdir, stat } from \"node:fs/promises\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ByteRange, FileInfo, StaticFiles } from \"../core/types.js\";\n\n/** Why: one read fills one chunk, so a slow client holds one chunk, not the whole file. */\nconst CHUNK_BYTES = 65_536;\n\n/**\n * A file's bytes, one chunk for each pull. With `range`, it reads only those\n * bytes. The file opens on the first pull and closes at the end, on an error,\n * or on cancel.\n *\n * Why open on the first pull: a stage can drop a response that no one reads,\n * such as when a later stage throws. Node.js 26 throws an uncaught error when\n * garbage collection closes an open `FileHandle`.\n */\nfunction fileStream(path: string, range: ByteRange | undefined): ReadableStream<Uint8Array> {\n\tlet handle: FileHandle | undefined;\n\tlet position = range?.start ?? 0;\n\tconst end = range == null ? Number.POSITIVE_INFINITY : range.end + 1;\n\tconst close = async () => {\n\t\tconst opened = handle;\n\t\thandle = undefined;\n\t\tawait opened?.close();\n\t};\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tconst length = Math.min(CHUNK_BYTES, end - position);\n\t\t\t\t\tif (length > 0) {\n\t\t\t\t\t\thandle ??= await open(path);\n\t\t\t\t\t}\n\t\t\t\t\tconst { bytesRead, buffer } =\n\t\t\t\t\t\tlength <= 0 || handle == null\n\t\t\t\t\t\t\t? { bytesRead: 0, buffer: new Uint8Array(0) }\n\t\t\t\t\t\t\t: await handle.read({ buffer: new Uint8Array(length), position });\n\t\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\t\tawait close();\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition += bytesRead;\n\t\t\t\t\t\tcontroller.enqueue(buffer.subarray(0, bytesRead));\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait close();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: close,\n\t\t},\n\t\t// Why 0: the stream opens and reads nothing until the consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/** The bytes of `range` in the file at `path`, usually from one read. */\nasync function readRange(path: string, range: ByteRange): Promise<Uint8Array> {\n\tconst buffer = new Uint8Array(range.end - range.start + 1);\n\tconst handle = await open(path);\n\ttry {\n\t\tlet filled = 0;\n\t\t// Why a loop: a read can give fewer bytes than it asks for before the end of the file.\n\t\twhile (filled < buffer.byteLength) {\n\t\t\tconst { bytesRead } = await handle.read({\n\t\t\t\tbuffer,\n\t\t\t\toffset: filled,\n\t\t\t\tposition: range.start + filled,\n\t\t\t});\n\t\t\tif (bytesRead === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfilled += bytesRead;\n\t\t}\n\t\treturn buffer.subarray(0, filled);\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\n/** A stream of one chunk. */\nfunction oneChunk(chunk: Uint8Array): ReadableStream<Uint8Array> {\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tif (chunk.byteLength > 0) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\t\t\tcontroller.close();\n\t\t},\n\t});\n}\n\n/** Why: these codes mean that nothing is at the path. Any other error, such as `EACCES`, throws. */\nconst MISSING_CODES = new Set([\"ENOENT\", \"ENOTDIR\", \"ENAMETOOLONG\"]);\n\n/** The value of `promise`, or `undefined` when it fails because nothing is at its path. */\nasync function orMissing<T>(promise: Promise<T>): Promise<T | undefined> {\n\ttry {\n\t\treturn await promise;\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && MISSING_CODES.has(String(error.code))) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/** The {@link FileInfo} of a file or a directory, else `undefined`. */\nfunction fileInfo(stats: Stats | undefined): FileInfo | undefined {\n\tif (stats?.isFile() === true) {\n\t\treturn { kind: \"file\", size: stats.size, mtimeMs: stats.mtimeMs };\n\t}\n\treturn stats?.isDirectory() === true\n\t\t? { kind: \"directory\", size: 0, mtimeMs: stats.mtimeMs }\n\t\t: undefined;\n}\n\n/**\n * The client build on the file system. A relative `clientDirectory` is\n * relative to the working directory.\n *\n * Its `snapshot` reads each file and directory once. It throws for an error\n * that does not mean a missing file, so the server does not start.\n *\n * @example\n * nodeFiles(\"build/client\").stat(\"/llms.txt\");\n */\nexport function nodeFiles(clientDirectory: string): StaticFiles {\n\t// Why `resolve` for a URL too: it drops the trailing `/` that the containment check needs gone.\n\tconst root = resolve(\n\t\tclientDirectory.startsWith(\"file:\") ? fileURLToPath(clientDirectory) : clientDirectory,\n\t);\n\t// Why a second check: the static stages check each path, and this check keeps a host that\n\t// gets a path from elsewhere inside the root too.\n\tconst filePath = (path: string) => {\n\t\tconst candidate = join(root, path);\n\t\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\t\tthrow new Error(`The path ${path} is outside the client build.`);\n\t\t}\n\t\treturn candidate;\n\t};\n\tconst files: StaticFiles = {\n\t\tstat: async (path) => fileInfo(await orMissing(stat(filePath(path)))),\n\t\topen: async (path, range) => {\n\t\t\tconst candidate = filePath(path);\n\t\t\tif (range != null && range.end - range.start < CHUNK_BYTES) {\n\t\t\t\treturn oneChunk(await readRange(candidate, range));\n\t\t\t}\n\t\t\t// Why: an unreadable file then gets a logged 500, not a 200 whose body fails. The check\n\t\t\t// holds no `FileHandle`, so a response that no one reads leaves nothing open.\n\t\t\tawait access(candidate, constants.R_OK);\n\t\t\treturn fileStream(candidate, range);\n\t\t},\n\t\tsnapshot: async () => {\n\t\t\tconst entries = new Map<string, FileInfo>();\n\t\t\t// Why the inodes of the parents: a symbolic link to a parent directory must not make the\n\t\t\t// walk endless. A link to another directory, such as a sibling, still lists its files.\n\t\t\tconst walk = async (\n\t\t\t\tpath: string,\n\t\t\t\tstats: Stats,\n\t\t\t\tparents: ReadonlySet<string>,\n\t\t\t): Promise<void> => {\n\t\t\t\tconst info = fileInfo(stats);\n\t\t\t\tif (info == null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentries.set(path, info);\n\t\t\t\tconst inode = `${stats.dev}:${stats.ino}`;\n\t\t\t\tif (info.kind === \"file\" || parents.has(inode)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst inside = new Set(parents).add(inode);\n\t\t\t\tconst prefix = path === \"/\" ? \"\" : path;\n\t\t\t\t// Why: a deploy can remove a directory between its `stat` and this read.\n\t\t\t\tconst names = (await orMissing(readdir(filePath(path)))) ?? [];\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tnames.map(async (name) => {\n\t\t\t\t\t\tconst childPath = `${prefix}/${name}`;\n\t\t\t\t\t\tconst childStats = await orMissing(stat(filePath(childPath)));\n\t\t\t\t\t\tif (childStats != null) {\n\t\t\t\t\t\t\tawait walk(childPath, childStats, inside);\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 rootStats = await orMissing(stat(root));\n\t\t\tif (rootStats != null) {\n\t\t\t\tawait walk(\"/\", rootStats, new Set());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstat: async (path) => {\n\t\t\t\t\tconst trimmed = path.length > 1 ? path.replace(/\\/$/u, \"\") : path;\n\t\t\t\t\tconst info = entries.get(trimmed);\n\t\t\t\t\t// Why only a directory after a `/`: as on the disk, `/docs/` finds `/docs`, and\n\t\t\t\t\t// `/llms.txt/` finds nothing.\n\t\t\t\t\treturn trimmed === path || info?.kind === \"directory\" ? info : undefined;\n\t\t\t\t},\n\t\t\t\topen: files.open,\n\t\t\t};\n\t\t},\n\t};\n\treturn files;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { OutgoingHttpHeader, OutgoingHttpHeaders } from \"node:http\";\nimport { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { MiddlewareHandler } from \"hono\";\nimport type { AppServerEnv, HeaderHook, ListenerBindings, ResponseHeaders } from \"../core/types.js\";\nimport { publicScriptHashes } from \"./script-hashes.js\";\n\n/** A Connect middleware, such as `vite.middlewares`. */\nexport type NodeMiddleware = (\n\trequest: IncomingMessage,\n\tresponse: ServerResponse,\n\tnext: (error?: unknown) => void,\n) => void;\n\n/** What a `node:http` listener passes to the app with each request. */\nexport type NodeBindings = ListenerBindings & {\n\t/** Node's request. */\n\tincoming?: IncomingMessage;\n\t/** Node's response. */\n\toutgoing?: ServerResponse;\n};\n\nfunction isServerResponse(value: unknown): value is ServerResponse {\n\treturn value instanceof ServerResponse;\n}\n\n/**\n * Makes `outgoing` run `hooks` before it sends its head, and returns the\n * function that undoes it. Why `writeHead`: Node calls it for each\n * response, also from `write` and `end`.\n */\nfunction runHooksAtHead(outgoing: ServerResponse, hooks: readonly HeaderHook[]): () => void {\n\tconst headers: ResponseHeaders = {\n\t\tget: (name) => {\n\t\t\tconst value = outgoing.getHeader(name);\n\t\t\treturn value == null ? null : String(value);\n\t\t},\n\t\thas: (name) => outgoing.hasHeader(name),\n\t\tset: (name, value) => {\n\t\t\toutgoing.setHeader(name, value);\n\t\t},\n\t\tappend: (name, value) => {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t},\n\t\tdelete: (name) => {\n\t\t\toutgoing.removeHeader(name);\n\t\t},\n\t};\n\tconst writeHead = outgoing.writeHead.bind(outgoing);\n\toutgoing.writeHead = (\n\t\tstatusCode: number,\n\t\treason?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\tvalues?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t) => {\n\t\tconst [message, given] = typeof reason === \"string\" ? [reason, values] : [undefined, reason];\n\t\t// Why: the hooks must see the headers that `writeHead` gets, such as the content type of a file.\n\t\tif (Array.isArray(given)) {\n\t\t\t// Why remove, then append: Node reads a flat `[name, value, …]` list so. A name replaces the old value and can repeat.\n\t\t\tconst names = given.filter((_, index) => index % 2 === 0).map(String);\n\t\t\tfor (const name of names) {\n\t\t\t\toutgoing.removeHeader(name);\n\t\t\t}\n\t\t\tfor (const [index, name] of names.entries()) {\n\t\t\t\tconst value = given[index * 2 + 1];\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.appendHeader(name, typeof value === \"number\" ? String(value) : value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (given != null) {\n\t\t\tfor (const [name, value] of Object.entries(given)) {\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.setHeader(name, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Why reversed: in production, the hook of an inner stage runs first, so an outer stage has the last word.\n\t\tfor (const hook of hooks.toReversed()) {\n\t\t\thook(headers);\n\t\t}\n\t\treturn message == null ? writeHead(statusCode) : writeHead(statusCode, message);\n\t};\n\treturn () => {\n\t\toutgoing.writeHead = writeHead;\n\t};\n}\n\n/** Options for {@link devServerStage}. */\nexport type DevServerStageOptions = {\n\t/**\n\t * The directory that the middleware serves as it is, and the URL base that\n\t * it serves the directory at, such as Vite's `publicDir` and `base`. An HTML\n\t * file from it gets the `contentSecurityPolicy` with the hashes of its\n\t * inline scripts, as it does in production. Why a function: a Vite restart\n\t * can change both.\n\t */\n\tpublicFiles?: () => { directory: string; base: string };\n};\n\n/** The script hashes of the public HTML file at `pathname`, or `undefined` when there is none. */\nfunction publicFileHashes(\n\t{ directory, base }: { directory: string; base: string },\n\tpathname: string,\n): string[] | undefined {\n\tconst prefix = base.replace(/\\/$/u, \"\");\n\t// Why both forms: in middleware mode, Vite's base middleware passes a path with no base on as it is.\n\treturn publicScriptHashes(\n\t\tdirectory,\n\t\tpathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : pathname,\n\t);\n}\n\n/**\n * Runs a Connect middleware, such as Vite's, inside the pipeline. The\n * middleware answers or calls `next`. A request with no Node request and\n * response goes on.\n *\n * @example\n * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {\n * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n * }));\n */\nexport function devServerStage(\n\tmiddleware: NodeMiddleware,\n\t{ publicFiles }: DevServerStageOptions = {},\n): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) {\n\t\t\treturn next();\n\t\t}\n\t\tconst hashes =\n\t\t\tpublicFiles == null\n\t\t\t\t? undefined\n\t\t\t\t: publicFileHashes(publicFiles(), new URL(context.req.url).pathname);\n\t\tconst earlierHashes = context.get(\"documentScriptHashes\");\n\t\tif (hashes != null) {\n\t\t\tcontext.set(\"documentScriptHashes\", hashes);\n\t\t}\n\t\t// Why before the middleware: it sends the headers itself, so the headers the earlier stages\n\t\t// set, such as the request ID, must be on `outgoing` first.\n\t\tfor (const [name, value] of context.res.headers) {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t}\n\t\tconst hooks = context.get(\"headerHooks\") ?? [];\n\t\tconst undoHooks = runHooksAtHead(outgoing, hooks);\n\t\tconst answered = await new Promise<boolean>((resolve, reject) => {\n\t\t\tconst onFinish = () => {\n\t\t\t\tresolve(true);\n\t\t\t};\n\t\t\toutgoing.once(\"finish\", onFinish);\n\t\t\tmiddleware(incoming, outgoing, (error) => {\n\t\t\t\toutgoing.off(\"finish\", onFinish);\n\t\t\t\t// Why: the later stages answer, and each hook runs on their response.\n\t\t\t\tundoHooks();\n\t\t\t\t// Why: the middleware did not send the public file, so its hashes do not apply.\n\t\t\t\tif (hashes != null) {\n\t\t\t\t\tcontext.set(\"documentScriptHashes\", earlierHashes);\n\t\t\t\t}\n\t\t\t\tif (error == null) {\n\t\t\t\t\tresolve(false);\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(\"The dev server middleware failed\", { cause: error }));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (answered) {\n\t\t\t// Why empty the list: the hooks ran on the head that the middleware sent, so the server must\n\t\t\t// not run them again on the response below.\n\t\t\thooks.length = 0;\n\t\t\t// Why a new response per request: the later stages set headers on it. The headers of\n\t\t\t// `RESPONSE_ALREADY_SENT` tell `@hono/node-server` to send nothing. The status and the\n\t\t\t// headers are the ones that the middleware sent, for the access log.\n\t\t\tconst headers = new Headers(RESPONSE_ALREADY_SENT.headers);\n\t\t\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\t\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\t\t\tif (each != null) {\n\t\t\t\t\t\theaders.append(name, String(each));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Response(null, { status: outgoing.statusCode, headers });\n\t\t}\n\t\treturn next();\n\t};\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context } from \"hono\";\nimport type { AppServerEnv, HostRuntime } from \"../core/types.js\";\nimport { exitAfterFlush } from \"./exit.js\";\nimport { nodeFiles } from \"./files.js\";\nimport { gzipStream } from \"./gzip.js\";\nimport { tcp } from \"./tcp.js\";\n\nexport {\n\t//,\n\tdevServerStage,\n} from \"./dev-server.js\";\nexport {\n\t//,\n\tnodeFiles,\n} from \"./files.js\";\nexport {\n\t//,\n\tparsePort,\n\ttcp,\n} from \"./tcp.js\";\n\nexport type {\n\t//,\n\tDevServerStageOptions,\n\tNodeBindings,\n\tNodeMiddleware,\n} from \"./dev-server.js\";\nexport type {\n\t//,\n\tTcpOptions,\n} from \"./tcp.js\";\n\nconst storage = new AsyncLocalStorage<Context<AppServerEnv>>();\n\n/**\n * The node host: one long-lived process on Node, Bun, or Deno, such as a\n * Docker image. It listens with `tcp()`, reads the client build from the file\n * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or\n * `SIGINT`, it shuts down, then exits the process.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"node\",\n\tfiles: nodeFiles,\n\tlisteners: () => [tcp()],\n\tstorage: {\n\t\trun: (value, work) => storage.run(value, work),\n\t\tget: () => storage.getStore(),\n\t},\n\tgzip: gzipStream,\n\tlifecycle: {\n\t\tonStop: (stop) => {\n\t\t\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\t\t\tprocess.once(signal, () => {\n\t\t\t\t\tstop()\n\t\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.finally(exitAfterFlush);\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t},\n};\n"],"mappings":";;;;;;;;;;;;;;;AAIA,MAAM,mBAAmB;;;;;;;;;AAUzB,SAAgB,iBAAuB;CACtC,UAAU;CACV,I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,MACZ,QAAQ,KAAK;SAEb,OAAO,IAAI,MAAM,oCAAoC,EAAE,OAAO,MAAM,CAAC,CAAC;GAExE,CAAC;EACF,CAAC,GACa;GAGb,MAAM,SAAS;GAIf,MAAM,UAAU,IAAI,QAAQ,sBAAsB,OAAO;GACzD,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,SAAS,WAAW,CAAC,GAC/D,KAAK,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK,GACvD,IAAI,QAAQ,MACX,QAAQ,OAAO,MAAM,OAAO,IAAI,CAAC;GAIpC,OAAO,IAAI,SAAS,MAAM;IAAE,QAAQ,SAAS;IAAY;GAAQ,CAAC;EACnE;EACA,OAAO,KAAK;CACb;AACD;;;ACvJA,MAAM,UAAU,IAAI,kBAAyC;;;;;;;;;;AAW7D,MAAa,OAAoB;CAChC,MAAM;CACN,OAAO;CACP,iBAAiB,CAAC,IAAI,CAAC;CACvB,SAAS;EACR,MAAM,OAAO,SAAS,QAAQ,IAAI,OAAO,IAAI;EAC7C,WAAW,QAAQ,SAAS;CAC7B;CACA,MAAM;CACN,WAAW,EACV,SAAS,SAAS;EACjB,KAAK,MAAM,UAAU,CAAC,WAAW,QAAQ,GACxC,QAAQ,KAAK,cAAc;GAC1B,KAAK,CAAC,CACJ,YAAY;IACZ,QAAQ,WAAW;GACpB,CAAC,CAAC,CACD,QAAQ,cAAc;EACzB,CAAC;CAEH,EACD;AACD"}
1
+ {"version":3,"file":"node-C1qudLs_.js","names":[],"sources":["../src/node/exit.ts","../src/node/files.ts","../src/node/dev-server.ts","../src/node/index.ts"],"sourcesContent":["import { setTimeout } from \"node:timers\";\nimport { flushLogs } from \"../core/log.js\";\n\n/** How long the exit waits for stdout and stderr. */\nconst FLUSH_TIMEOUT_MS = 1_000;\n\n/**\n * Exits the process after stdout and stderr write what they hold, so the last\n * log lines are not lost. The exit code is `process.exitCode`, else 0.\n *\n * Why exit at all: when shutdown is done, the server holds nothing open. A\n * timer that the app left, such as the render abort timer in React Router's\n * `entry.server`, would otherwise keep the stopped process alive.\n */\nexport function exitAfterFlush(): void {\n\tflushLogs();\n\tlet pending = 2;\n\tconst done = () => {\n\t\tpending -= 1;\n\t\tif (pending === 0) {\n\t\t\tprocess.exit();\n\t\t}\n\t};\n\tflush(process.stdout, done);\n\tflush(process.stderr, done);\n\t// Why a fallback: a reader that stops reading the pipe would hold the callbacks forever.\n\tsetTimeout(() => {\n\t\tprocess.exit();\n\t}, FLUSH_TIMEOUT_MS).unref();\n}\n\n/** Calls `done` after `stream` writes what it holds. */\nfunction flush(stream: NodeJS.WriteStream, done: () => void): void {\n\tif (\"Bun\" in globalThis) {\n\t\t// Why `end` on Bun: on Bun 1.3, the callback of a write runs before a full pipe takes the\n\t\t// earlier writes. The callback of `end` waits for them. A write after `end` still works on Bun.\n\t\tstream.end(done);\n\t\treturn;\n\t}\n\t// Why a write: its callback runs after each earlier write. A pipe on macOS writes async.\n\t// Why not `end` on Node: a write after `end` throws there.\n\tstream.write(\"\", done);\n}\n","import { constants } from \"node:fs\";\nimport { access, open, readdir, stat } from \"node:fs/promises\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport type { Stats } from \"node:fs\";\nimport { join, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ByteRange, FileInfo, StaticFiles } from \"../core/types.js\";\n\n/** Why: one read fills one chunk, so a slow client holds one chunk, not the whole file. */\nconst CHUNK_BYTES = 65_536;\n\n/**\n * A file's bytes, one chunk for each pull. With `range`, it reads only those\n * bytes. The file opens on the first pull and closes at the end, on an error,\n * or on cancel.\n *\n * Why open on the first pull: a stage can drop a response that no one reads,\n * such as when a later stage throws. Node.js 26 throws an uncaught error when\n * garbage collection closes an open `FileHandle`.\n */\nfunction fileStream(path: string, range: ByteRange | undefined): ReadableStream<Uint8Array> {\n\tlet handle: FileHandle | undefined;\n\tlet position = range?.start ?? 0;\n\tconst end = range == null ? Number.POSITIVE_INFINITY : range.end + 1;\n\tconst close = async () => {\n\t\tconst opened = handle;\n\t\thandle = undefined;\n\t\tawait opened?.close();\n\t};\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tconst length = Math.min(CHUNK_BYTES, end - position);\n\t\t\t\t\tif (length > 0) {\n\t\t\t\t\t\thandle ??= await open(path);\n\t\t\t\t\t}\n\t\t\t\t\tconst { bytesRead, buffer } =\n\t\t\t\t\t\tlength <= 0 || handle == null\n\t\t\t\t\t\t\t? { bytesRead: 0, buffer: new Uint8Array(0) }\n\t\t\t\t\t\t\t: await handle.read({ buffer: new Uint8Array(length), position });\n\t\t\t\t\tif (bytesRead === 0) {\n\t\t\t\t\t\tawait close();\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition += bytesRead;\n\t\t\t\t\t\tcontroller.enqueue(buffer.subarray(0, bytesRead));\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tawait close();\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel: close,\n\t\t},\n\t\t// Why 0: the stream opens and reads nothing until the consumer reads.\n\t\t{ highWaterMark: 0 },\n\t);\n}\n\n/** The bytes of `range` in the file at `path`, usually from one read. */\nasync function readRange(path: string, range: ByteRange): Promise<Uint8Array> {\n\tconst buffer = new Uint8Array(range.end - range.start + 1);\n\tconst handle = await open(path);\n\ttry {\n\t\tlet filled = 0;\n\t\t// Why a loop: a read can give fewer bytes than it asks for before the end of the file.\n\t\twhile (filled < buffer.byteLength) {\n\t\t\tconst { bytesRead } = await handle.read({\n\t\t\t\tbuffer,\n\t\t\t\toffset: filled,\n\t\t\t\tposition: range.start + filled,\n\t\t\t});\n\t\t\tif (bytesRead === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfilled += bytesRead;\n\t\t}\n\t\treturn buffer.subarray(0, filled);\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n\n/** A stream of one chunk. */\nfunction oneChunk(chunk: Uint8Array): ReadableStream<Uint8Array> {\n\treturn new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tif (chunk.byteLength > 0) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\t\t\tcontroller.close();\n\t\t},\n\t});\n}\n\n/** Why: these codes mean that nothing is at the path. Any other error, such as `EACCES`, throws. */\nconst MISSING_CODES = new Set([\"ENOENT\", \"ENOTDIR\", \"ENAMETOOLONG\"]);\n\n/** The value of `promise`, or `undefined` when it fails because nothing is at its path. */\nasync function orMissing<T>(promise: Promise<T>): Promise<T | undefined> {\n\ttry {\n\t\treturn await promise;\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && MISSING_CODES.has(String(error.code))) {\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/** The {@link FileInfo} of a file or a directory, else `undefined`. */\nfunction fileInfo(stats: Stats | undefined): FileInfo | undefined {\n\tif (stats?.isFile() === true) {\n\t\treturn { kind: \"file\", size: stats.size, mtimeMs: stats.mtimeMs };\n\t}\n\treturn stats?.isDirectory() === true\n\t\t? { kind: \"directory\", size: 0, mtimeMs: stats.mtimeMs }\n\t\t: undefined;\n}\n\n/**\n * The client build on the file system. A relative `clientDirectory` is\n * relative to the working directory.\n *\n * Its `snapshot` reads each file and directory once. It throws for an error\n * that does not mean a missing file, so the server does not start.\n *\n * @example\n * nodeFiles(\"build/client\").stat(\"/llms.txt\");\n */\nexport function nodeFiles(clientDirectory: string): StaticFiles {\n\t// Why `resolve` for a URL too: it drops the trailing `/` that the containment check needs gone.\n\tconst root = resolve(\n\t\tclientDirectory.startsWith(\"file:\") ? fileURLToPath(clientDirectory) : clientDirectory,\n\t);\n\t// Why a second check: the static stages check each path, and this check keeps a host that\n\t// gets a path from elsewhere inside the root too.\n\tconst filePath = (path: string) => {\n\t\tconst candidate = join(root, path);\n\t\tif (candidate !== root && !candidate.startsWith(`${root}${sep}`)) {\n\t\t\tthrow new Error(`The path ${path} is outside the client build.`);\n\t\t}\n\t\treturn candidate;\n\t};\n\tconst files: StaticFiles = {\n\t\tstat: async (path) => fileInfo(await orMissing(stat(filePath(path)))),\n\t\topen: async (path, range) => {\n\t\t\tconst candidate = filePath(path);\n\t\t\tif (range != null && range.end - range.start < CHUNK_BYTES) {\n\t\t\t\treturn oneChunk(await readRange(candidate, range));\n\t\t\t}\n\t\t\t// Why: an unreadable file then gets a logged 500, not a 200 whose body fails. The check\n\t\t\t// holds no `FileHandle`, so a response that no one reads leaves nothing open.\n\t\t\tawait access(candidate, constants.R_OK);\n\t\t\treturn fileStream(candidate, range);\n\t\t},\n\t\tsnapshot: async () => {\n\t\t\tconst entries = new Map<string, FileInfo>();\n\t\t\t// Why the inodes of the parents: a symbolic link to a parent directory must not make the\n\t\t\t// walk endless. A link to another directory, such as a sibling, still lists its files.\n\t\t\tconst walk = async (\n\t\t\t\tpath: string,\n\t\t\t\tstats: Stats,\n\t\t\t\tparents: ReadonlySet<string>,\n\t\t\t): Promise<void> => {\n\t\t\t\tconst info = fileInfo(stats);\n\t\t\t\tif (info == null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentries.set(path, info);\n\t\t\t\tconst inode = `${stats.dev}:${stats.ino}`;\n\t\t\t\tif (info.kind === \"file\" || parents.has(inode)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst inside = new Set(parents).add(inode);\n\t\t\t\tconst prefix = path === \"/\" ? \"\" : path;\n\t\t\t\t// Why: a deploy can remove a directory between its `stat` and this read.\n\t\t\t\tconst names = (await orMissing(readdir(filePath(path)))) ?? [];\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tnames.map(async (name) => {\n\t\t\t\t\t\tconst childPath = `${prefix}/${name}`;\n\t\t\t\t\t\tconst childStats = await orMissing(stat(filePath(childPath)));\n\t\t\t\t\t\tif (childStats != null) {\n\t\t\t\t\t\t\tawait walk(childPath, childStats, inside);\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 rootStats = await orMissing(stat(root));\n\t\t\tif (rootStats != null) {\n\t\t\t\tawait walk(\"/\", rootStats, new Set());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstat: async (path) => {\n\t\t\t\t\tconst trimmed = path.length > 1 ? path.replace(/\\/$/u, \"\") : path;\n\t\t\t\t\tconst info = entries.get(trimmed);\n\t\t\t\t\t// Why only a directory after a `/`: as on the disk, `/docs/` finds `/docs`, and\n\t\t\t\t\t// `/llms.txt/` finds nothing.\n\t\t\t\t\treturn trimmed === path || info?.kind === \"directory\" ? info : undefined;\n\t\t\t\t},\n\t\t\t\topen: files.open,\n\t\t\t};\n\t\t},\n\t};\n\treturn files;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { OutgoingHttpHeader, OutgoingHttpHeaders } from \"node:http\";\nimport { RESPONSE_ALREADY_SENT } from \"@hono/node-server/utils/response\";\nimport type { MiddlewareHandler } from \"hono\";\nimport type { AppServerEnv, HeaderHook, ListenerBindings, ResponseHeaders } from \"../core/types.js\";\nimport { publicScriptHashes } from \"./script-hashes.js\";\n\n/** A Connect middleware, such as `vite.middlewares`. */\nexport type NodeMiddleware = (\n\trequest: IncomingMessage,\n\tresponse: ServerResponse,\n\tnext: (error?: unknown) => void,\n) => void;\n\n/** What a `node:http` listener passes to the app with each request. */\nexport type NodeBindings = ListenerBindings & {\n\t/** Node's request. */\n\tincoming?: IncomingMessage;\n\t/** Node's response. */\n\toutgoing?: ServerResponse;\n};\n\nfunction isServerResponse(value: unknown): value is ServerResponse {\n\treturn value instanceof ServerResponse;\n}\n\n/**\n * Makes `outgoing` run `hooks` before it sends its head, and returns the\n * function that undoes it. Why `writeHead`: Node calls it for each\n * response, also from `write` and `end`.\n */\nfunction runHooksAtHead(outgoing: ServerResponse, hooks: readonly HeaderHook[]): () => void {\n\tconst headers: ResponseHeaders = {\n\t\tget: (name) => {\n\t\t\tconst value = outgoing.getHeader(name);\n\t\t\treturn value == null ? null : String(value);\n\t\t},\n\t\thas: (name) => outgoing.hasHeader(name),\n\t\tset: (name, value) => {\n\t\t\toutgoing.setHeader(name, value);\n\t\t},\n\t\tappend: (name, value) => {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t},\n\t\tdelete: (name) => {\n\t\t\toutgoing.removeHeader(name);\n\t\t},\n\t};\n\tconst writeHead = outgoing.writeHead.bind(outgoing);\n\toutgoing.writeHead = (\n\t\tstatusCode: number,\n\t\treason?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\tvalues?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t) => {\n\t\tconst [message, given] = typeof reason === \"string\" ? [reason, values] : [undefined, reason];\n\t\t// Why: the hooks must see the headers that `writeHead` gets, such as the content type of a file.\n\t\tif (Array.isArray(given)) {\n\t\t\t// Why remove, then append: Node reads a flat `[name, value, …]` list so. A name replaces the old value and can repeat.\n\t\t\tconst names = given.filter((_, index) => index % 2 === 0).map(String);\n\t\t\tfor (const name of names) {\n\t\t\t\toutgoing.removeHeader(name);\n\t\t\t}\n\t\t\tfor (const [index, name] of names.entries()) {\n\t\t\t\tconst value = given[index * 2 + 1];\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.appendHeader(name, typeof value === \"number\" ? String(value) : value);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (given != null) {\n\t\t\tfor (const [name, value] of Object.entries(given)) {\n\t\t\t\tif (value != null) {\n\t\t\t\t\toutgoing.setHeader(name, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Why reversed: in production, the hook of an inner stage runs first, so an outer stage has the last word.\n\t\tfor (const hook of hooks.toReversed()) {\n\t\t\thook(headers);\n\t\t}\n\t\treturn message == null ? writeHead(statusCode) : writeHead(statusCode, message);\n\t};\n\treturn () => {\n\t\toutgoing.writeHead = writeHead;\n\t};\n}\n\n/** Options for {@link devServerStage}. */\nexport type DevServerStageOptions = {\n\t/**\n\t * The directory that the middleware serves as it is, and the URL base that\n\t * it serves the directory at, such as Vite's `publicDir` and `base`. An HTML\n\t * file from it gets the `contentSecurityPolicy` with the hashes of its\n\t * inline scripts, as it does in production. Why a function: a Vite restart\n\t * can change both.\n\t */\n\tpublicFiles?: () => { directory: string; base: string };\n};\n\n/** The script hashes of the public HTML file at `pathname`, or `undefined` when there is none. */\nfunction publicFileHashes(\n\t{ directory, base }: { directory: string; base: string },\n\tpathname: string,\n): string[] | undefined {\n\tconst prefix = base.replace(/\\/$/u, \"\");\n\t// Why both forms: in middleware mode, Vite's base middleware passes a path with no base on as it is.\n\treturn publicScriptHashes(\n\t\tdirectory,\n\t\tpathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : pathname,\n\t);\n}\n\n/**\n * Runs a Connect middleware, such as Vite's, inside the pipeline. The\n * middleware answers or calls `next`. A request with no Node request and\n * response goes on.\n *\n * @example\n * entry.fetchDev(request, bindings, devServerStage(viteServer.middlewares, {\n * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n * }));\n */\nexport function devServerStage(\n\tmiddleware: NodeMiddleware,\n\t{ publicFiles }: DevServerStageOptions = {},\n): MiddlewareHandler<AppServerEnv> {\n\treturn async (context, next) => {\n\t\tconst { incoming, outgoing } = context.env;\n\t\tif (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) {\n\t\t\treturn next();\n\t\t}\n\t\tconst hashes =\n\t\t\tpublicFiles == null\n\t\t\t\t? undefined\n\t\t\t\t: publicFileHashes(publicFiles(), new URL(context.req.url).pathname);\n\t\tconst earlierHashes = context.get(\"documentScriptHashes\");\n\t\tif (hashes != null) {\n\t\t\tcontext.set(\"documentScriptHashes\", hashes);\n\t\t}\n\t\t// Why before the middleware: it sends the headers itself, so the headers the earlier stages\n\t\t// set, such as the request ID, must be on `outgoing` first.\n\t\tfor (const [name, value] of context.res.headers) {\n\t\t\toutgoing.appendHeader(name, value);\n\t\t}\n\t\tconst hooks = context.get(\"headerHooks\") ?? [];\n\t\tconst undoHooks = runHooksAtHead(outgoing, hooks);\n\t\tconst answered = await new Promise<boolean>((resolve, reject) => {\n\t\t\tconst onFinish = () => {\n\t\t\t\tresolve(true);\n\t\t\t};\n\t\t\toutgoing.once(\"finish\", onFinish);\n\t\t\tmiddleware(incoming, outgoing, (error) => {\n\t\t\t\toutgoing.off(\"finish\", onFinish);\n\t\t\t\t// Why: the later stages answer, and each hook runs on their response.\n\t\t\t\tundoHooks();\n\t\t\t\t// Why: the middleware did not send the public file, so its hashes do not apply.\n\t\t\t\tif (hashes != null) {\n\t\t\t\t\tcontext.set(\"documentScriptHashes\", earlierHashes);\n\t\t\t\t}\n\t\t\t\tif (error == null) {\n\t\t\t\t\tresolve(false);\n\t\t\t\t} else {\n\t\t\t\t\treject(new Error(\"The dev server middleware failed\", { cause: error }));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tif (answered) {\n\t\t\t// Why empty the list: the hooks ran on the head that the middleware sent, so the server must\n\t\t\t// not run them again on the response below.\n\t\t\thooks.length = 0;\n\t\t\t// Why a new response per request: the later stages set headers on it. The headers of\n\t\t\t// `RESPONSE_ALREADY_SENT` tell `@hono/node-server` to send nothing. The status and the\n\t\t\t// headers are the ones that the middleware sent, for the access log.\n\t\t\tconst headers = new Headers(RESPONSE_ALREADY_SENT.headers);\n\t\t\tfor (const [name, value] of Object.entries(outgoing.getHeaders())) {\n\t\t\t\tfor (const each of Array.isArray(value) ? value : [value]) {\n\t\t\t\t\tif (each != null) {\n\t\t\t\t\t\theaders.append(name, String(each));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Response(null, { status: outgoing.statusCode, headers });\n\t\t}\n\t\treturn next();\n\t};\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { Context } from \"hono\";\nimport type { AppServerEnv, HostRuntime } from \"../core/types.js\";\nimport { exitAfterFlush } from \"./exit.js\";\nimport { nodeFiles } from \"./files.js\";\nimport { gzipStream } from \"./gzip.js\";\nimport { tcp } from \"./tcp.js\";\n\nexport {\n\t//,\n\tdevServerStage,\n} from \"./dev-server.js\";\nexport {\n\t//,\n\tnodeFiles,\n} from \"./files.js\";\nexport {\n\t//,\n\tparsePort,\n\ttcp,\n} from \"./tcp.js\";\n\nexport type {\n\t//,\n\tDevServerStageOptions,\n\tNodeBindings,\n\tNodeMiddleware,\n} from \"./dev-server.js\";\nexport type {\n\t//,\n\tTcpOptions,\n} from \"./tcp.js\";\n\nconst storage = new AsyncLocalStorage<Context<AppServerEnv>>();\n\n/**\n * The node host: one long-lived process on Node, Bun, or Deno, such as a\n * Docker image. It listens with `tcp()`, reads the client build from the file\n * system, and keeps `requestContext()` in `AsyncLocalStorage`. On `SIGTERM` or\n * `SIGINT`, it shuts down, then exits the process.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"node\",\n\tfiles: nodeFiles,\n\tlisteners: () => [tcp()],\n\tstorage: {\n\t\trun: (value, work) => storage.run(value, work),\n\t\tget: () => storage.getStore(),\n\t},\n\tgzip: gzipStream,\n\tlifecycle: {\n\t\tonStop: (stop) => {\n\t\t\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\t\t\tprocess.once(signal, () => {\n\t\t\t\t\tstop()\n\t\t\t\t\t\t.catch(() => {\n\t\t\t\t\t\t\tprocess.exitCode = 1;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.finally(exitAfterFlush);\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t},\n};\n"],"mappings":";;;;;;;;;;;;;;;AAIA,MAAM,mBAAmB;;;;;;;;;AAUzB,SAAgB,iBAAuB;CACtC,UAAU;CACV,IAAI,UAAU;CACd,MAAM,aAAa;EAClB,WAAW;EACX,IAAI,YAAY,GACf,QAAQ,KAAK;CAEf;CACA,MAAM,QAAQ,QAAQ,IAAI;C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Gb,MAAM,SAAS;GAIf,MAAM,UAAU,IAAI,QAAQ,sBAAsB,OAAO;GACzD,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,SAAS,WAAW,CAAC,GAC/D,KAAK,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK,GACvD,IAAI,QAAQ,MACX,QAAQ,OAAO,MAAM,OAAO,IAAI,CAAC;GAIpC,OAAO,IAAI,SAAS,MAAM;IAAE,QAAQ,SAAS;IAAY;GAAQ,CAAC;EACnE;EACA,OAAO,KAAK;CACb;AACD;;;ACvJA,MAAM,UAAU,IAAI,kBAAyC;;;;;;;;;;AAW7D,MAAa,OAAoB;CAChC,MAAM;CACN,OAAO;CACP,iBAAiB,CAAC,IAAI,CAAC;CACvB,SAAS;EACR,MAAM,OAAO,SAAS,QAAQ,IAAI,OAAO,IAAI;EAC7C,WAAW,QAAQ,SAAS;CAC7B;CACA,MAAM;CACN,WAAW,EACV,SAAS,SAAS;EACjB,KAAK,MAAM,UAAU,CAAC,WAAW,QAAQ,GACxC,QAAQ,KAAK,cAAc;GAC1B,KAAK,CAAC,CACJ,YAAY;IACZ,QAAQ,WAAW;GACpB,CAAC,CAAC,CACD,QAAQ,cAAc;EACzB,CAAC;CAEH,EACD;AACD"}
package/dist/node.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { T as StaticFiles, c as HostRuntime, d as ListenerBindings, t as AppServerEnv, u as Listener } from "./types-DLYxYS6M.js";
1
+ import { T as StaticFiles, c as HostRuntime, d as ListenerBindings, t as AppServerEnv, u as Listener } from "./types-CEvzAmcn.js";
2
2
  import { MiddlewareHandler } from "hono";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  /** A Connect middleware, such as `vite.middlewares`. */
package/dist/node.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { n as tcp, t as parsePort } from "./tcp-Dd1Mt6sN.js";
2
- import { n as devServerStage, r as nodeFiles, t as host } from "./node-BFH82eeL.js";
2
+ import { n as devServerStage, r as nodeFiles, t as host } from "./node-C1qudLs_.js";
3
3
 
4
4
  export { devServerStage, host, nodeFiles, parsePort, tcp };
@@ -1,4 +1,4 @@
1
- import { _ as RequestContext, a as FrameworkRuntime, h as Mode } from "./types-DLYxYS6M.js";
1
+ import { _ as RequestContext, a as FrameworkRuntime, h as Mode } from "./types-CEvzAmcn.js";
2
2
  import { ServerBuild } from "react-router";
3
3
  /** What the server puts in React Router's context for each request. */
4
4
  export type AppServerContext = RequestContext;
@@ -1 +1 @@
1
- {"version":3,"file":"request-context-BtQ87VYb.js","names":[],"sources":["../src/core/request-context.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, RequestContext, RequestStore } from \"./types.js\";\n\n/**\n * Each store that a request ran in. Why a set: two entries in one process can\n * have two hosts, and each request uses the store of its own app.\n */\nconst stores = new Set<RequestStore>();\n\n/** The {@link RequestContext} values of a request. */\nexport function requestContextValues(context: Context<AppServerEnv>): RequestContext {\n\treturn {\n\t\trequestId: context.get(\"requestId\"),\n\t\tlogger: context.get(\"logger\"),\n\t\tcspNonce: context.get(\"cspNonce\"),\n\t\tclientAddress: context.get(\"clientAddress\"),\n\t};\n}\n\n/** Runs `work` in `store` with `context` as the request that {@link requestContext} reads. */\nexport async function withRequestContext(\n\tstore: RequestStore | undefined,\n\tcontext: Context<AppServerEnv>,\n\twork: () => Promise<void>,\n): Promise<void> {\n\tif (store == null) {\n\t\treturn work();\n\t}\n\tstores.add(store);\n\treturn store.run(context, work);\n}\n\n/**\n * The request ID, logger, and CSP nonce of the request that runs. It gives `undefined`\n * outside a server request, such as in a prerender pass, or on a host with no\n * request storage.\n *\n * @example\n * export async function loader() {\n * \trequestContext()?.logger.info(\"loading the dashboard\");\n * }\n */\nexport function requestContext(): RequestContext | undefined {\n\tfor (const store of stores) {\n\t\tconst context = store.get();\n\t\tif (context != null) {\n\t\t\treturn requestContextValues(context);\n\t\t}\n\t}\n\treturn undefined;\n}\n"],"mappings":";;;;;AAOA,MAAM,yBAAS,IAAI,IAAkB;;AAGrC,SAAgB,qBAAqB,SAAgD;CACpF,OAAO;EACN,WAAW,QAAQ,IAAI,WAAW;EAClC,QAAQ,QAAQ,IAAI,QAAQ;EAC5B,UAAU,QAAQ,IAAI,UAAU;EAChC,eAAe,QAAQ,IAAI,eAAe;CAC3C;AACD;;AAGA,eAAsB,mBACrB,OACA,SACA,MACgB;CAChB,IAAI,SAAS,MACZ,OAAO,KAAK;CAEb,OAAO,IAAI,KAAK;CAChB,OAAO,MAAM,IAAI,SAAS,IAAI;AAC/B;;;;;;;;;;;AAYA,SAAgB,iBAA6C;CAC5D,KAAK,MAAM,SAAS,QAAQ;EAC3B,MAAM,UAAU,MAAM,IAAI;EAC1B,IAAI,WAAW,MACd,OAAO,qBAAqB,OAAO;CAErC;AAED"}
1
+ {"version":3,"file":"request-context-BtQ87VYb.js","names":[],"sources":["../src/core/request-context.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { AppServerEnv, RequestContext, RequestStore } from \"./types.js\";\n\n/**\n * Each store that a request ran in. Why a set: two entries in one process can\n * have two hosts, and each request uses the store of its own app.\n */\nconst stores = new Set<RequestStore>();\n\n/** The {@link RequestContext} values of a request. */\nexport function requestContextValues(context: Context<AppServerEnv>): RequestContext {\n\treturn {\n\t\trequestId: context.get(\"requestId\"),\n\t\tlogger: context.get(\"logger\"),\n\t\tcspNonce: context.get(\"cspNonce\"),\n\t\tclientAddress: context.get(\"clientAddress\"),\n\t};\n}\n\n/** Runs `work` in `store` with `context` as the request that {@link requestContext} reads. */\nexport async function withRequestContext<Result>(\n\tstore: RequestStore | undefined,\n\tcontext: Context<AppServerEnv>,\n\twork: () => Promise<Result>,\n): Promise<Result> {\n\tif (store == null) {\n\t\treturn work();\n\t}\n\tstores.add(store);\n\treturn store.run(context, work);\n}\n\n/**\n * The request ID, logger, and CSP nonce of the request that runs. It gives `undefined`\n * outside a server request, such as in a prerender pass, or on a host with no\n * request storage.\n *\n * @example\n * export async function loader() {\n * \trequestContext()?.logger.info(\"loading the dashboard\");\n * }\n */\nexport function requestContext(): RequestContext | undefined {\n\tfor (const store of stores) {\n\t\tconst context = store.get();\n\t\tif (context != null) {\n\t\t\treturn requestContextValues(context);\n\t\t}\n\t}\n\treturn undefined;\n}\n"],"mappings":";;;;;AAOA,MAAM,yBAAS,IAAI,IAAkB;;AAGrC,SAAgB,qBAAqB,SAAgD;CACpF,OAAO;EACN,WAAW,QAAQ,IAAI,WAAW;EAClC,QAAQ,QAAQ,IAAI,QAAQ;EAC5B,UAAU,QAAQ,IAAI,UAAU;EAChC,eAAe,QAAQ,IAAI,eAAe;CAC3C;AACD;;AAGA,eAAsB,mBACrB,OACA,SACA,MACkB;CAClB,IAAI,SAAS,MACZ,OAAO,KAAK;CAEb,OAAO,IAAI,KAAK;CAChB,OAAO,MAAM,IAAI,SAAS,IAAI;AAC/B;;;;;;;;;;;AAYA,SAAgB,iBAA6C;CAC5D,KAAK,MAAM,SAAS,QAAQ;EAC3B,MAAM,UAAU,MAAM,IAAI;EAC1B,IAAI,WAAW,MACd,OAAO,qBAAqB,OAAO;CAErC;AAED"}
@@ -1,6 +1,6 @@
1
1
  import { t as contentType } from "./static-files-Beju9riB.js";
2
- import { readFileSync, statSync } from "node:fs";
3
- import { resolve, sep } from "node:path";
2
+ import { readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { join, relative, resolve, sep } from "node:path";
4
4
  import { createHash } from "node:crypto";
5
5
 
6
6
  // src/node/script-hashes.ts
@@ -48,6 +48,24 @@ function publicScriptHashes(directory, path) {
48
48
  return;
49
49
  }
50
50
  }
51
+ /**
52
+ * The {@link inlineScriptHashes} of each HTML file in the client build, by its URL path.
53
+ *
54
+ * @example
55
+ * scriptHashesOf("/app/build/client"); // => { "/about/index.html": ["…base64…"] }
56
+ */
57
+ function scriptHashesOf(clientDirectory) {
58
+ const hashes = {};
59
+ for (const entry of readdirSync(clientDirectory, {
60
+ recursive: true,
61
+ withFileTypes: true
62
+ })) if (entry.isFile() && contentType(entry.name, {}).startsWith("text/html")) {
63
+ const path = join(entry.parentPath, entry.name);
64
+ const urlPath = `/${relative(clientDirectory, path).split(sep).join("/")}`;
65
+ hashes[urlPath] = inlineScriptHashes(readFileSync(path, "utf8"));
66
+ }
67
+ return Object.fromEntries(Object.entries(hashes).toSorted(([first], [second]) => first.localeCompare(second)));
68
+ }
51
69
 
52
- export { publicScriptHashes as n, inlineScriptHashes as t };
53
- //# sourceMappingURL=script-hashes-hqUk6kG7.js.map
70
+ export { scriptHashesOf as n, publicScriptHashes as t };
71
+ //# sourceMappingURL=script-hashes-C6hQ5XnP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"script-hashes-C6hQ5XnP.js","names":[],"sources":["../src/node/script-hashes.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join, relative, resolve, sep } from \"node:path\";\nimport type { BuildManifest } from \"../core/build-manifest.js\";\nimport { contentType } from \"../core/static-files.js\";\n\n/**\n * An HTML comment, or a `<script>` element. The `attributes` group is the\n * script's attributes, and the `text` group is its text. Why the comment: a\n * `<script>` tag in a comment starts no element.\n */\nconst COMMENT_OR_SCRIPT =\n\t/<!--[\\s\\S]*?-->|<script(?=[\\s/>])(?<attributes>(?:[^>\"']|\"[^\"]*\"|'[^']*')*)>(?<text>[\\s\\S]*?)<\\/script(?=[\\s/>])/giu;\n\n/** An attribute value, so that a `src=` in a value is not the `src` attribute. */\nconst ATTRIBUTE_VALUE = /[=]\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+)/gu;\n\n/** A `src` attribute, in attributes with no values. */\nconst SRC_ATTRIBUTE = /(?:^|[\\s/])src(?:[\\s/=]|$)/iu;\n\n/**\n * The base64 `SHA-256` of each inline script in `html`, once each, in\n * document order. Why each type: a hash of a data block, such as JSON, trusts\n * no code, and a scan that skips a type that runs breaks the page. Why LF:\n * the browser changes each CRLF and CR to LF before it hashes a script.\n *\n * @example\n * inlineScriptHashes(\"<script>go()</script>\"); // => [\"…base64…\"]\n */\nexport function inlineScriptHashes(html: string): string[] {\n\tconst hashes: string[] = [];\n\tfor (const { groups } of html.replaceAll(/\\r\\n?/gu, \"\\n\").matchAll(COMMENT_OR_SCRIPT)) {\n\t\tif (\n\t\t\tgroups?.text != null &&\n\t\t\t!SRC_ATTRIBUTE.test((groups.attributes ?? \"\").replaceAll(ATTRIBUTE_VALUE, \"=\"))\n\t\t) {\n\t\t\thashes.push(createHash(\"sha256\").update(groups.text).digest(\"base64\"));\n\t\t}\n\t}\n\treturn [...new Set(hashes)];\n}\n\n/**\n * The {@link inlineScriptHashes} of the HTML file at the URL `path` in\n * `directory`, such as Vite's public directory, or `undefined` when it has no\n * such file. Why it reads the file for each call: a developer can edit it at\n * any time, and only a request for an HTML file reads it.\n *\n * @example\n * publicScriptHashes(\"/app/public\", \"/offline.html\"); // => [\"…base64…\"]\n */\nexport function publicScriptHashes(directory: string, path: string): string[] | undefined {\n\tif (directory === \"\") {\n\t\treturn undefined;\n\t}\n\t// Why one `try`: a path that does not decode, a path with a null byte, and a file that the\n\t// developer deletes or locks between the checks each throw. The middleware then answers.\n\ttry {\n\t\tconst decoded = decodeURIComponent(path);\n\t\tconst file = resolve(directory, `.${decoded}`);\n\t\t// Why: a path such as `/../secret.html` must not leave the directory.\n\t\tif (\n\t\t\t!contentType(decoded, {}).startsWith(\"text/html\") ||\n\t\t\t!file.startsWith(`${resolve(directory)}${sep}`) ||\n\t\t\tstatSync(file, { throwIfNoEntry: false })?.isFile() !== true\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn inlineScriptHashes(readFileSync(file, \"utf8\"));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * The {@link inlineScriptHashes} of each HTML file in the client build, by its URL path.\n *\n * @example\n * scriptHashesOf(\"/app/build/client\"); // => { \"/about/index.html\": [\"…base64…\"] }\n */\nexport function scriptHashesOf(clientDirectory: string): BuildManifest[\"scriptHashes\"] {\n\tconst hashes: BuildManifest[\"scriptHashes\"] = {};\n\tfor (const entry of readdirSync(clientDirectory, { recursive: true, withFileTypes: true })) {\n\t\t// Why `contentType`: the static stages send each file of an HTML type, such as `.htm`, as a document.\n\t\tif (entry.isFile() && contentType(entry.name, {}).startsWith(\"text/html\")) {\n\t\t\tconst path = join(entry.parentPath, entry.name);\n\t\t\tconst urlPath = `/${relative(clientDirectory, path).split(sep).join(\"/\")}`;\n\t\t\thashes[urlPath] = inlineScriptHashes(readFileSync(path, \"utf8\"));\n\t\t}\n\t}\n\treturn Object.fromEntries(\n\t\tObject.entries(hashes).toSorted(([first], [second]) => first.localeCompare(second)),\n\t);\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,oBACL;;AAGD,MAAM,kBAAkB;;AAGxB,MAAM,gBAAgB;;;;;;;;;;AAWtB,SAAgB,mBAAmB,MAAwB;CAC1D,MAAM,SAAmB,CAAC;CAC1B,KAAK,MAAM,EAAE,YAAY,KAAK,WAAW,WAAW,IAAI,CAAC,CAAC,SAAS,iBAAiB,GACnF,IACC,QAAQ,QAAQ,QAChB,CAAC,cAAc,MAAM,OAAO,cAAc,GAAE,CAAE,WAAW,iBAAiB,GAAG,CAAC,GAE9E,OAAO,KAAK,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,IAAI,CAAC,CAAC,OAAO,QAAQ,CAAC;CAGvE,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC3B;;;;;;;;;;AAWA,SAAgB,mBAAmB,WAAmB,MAAoC;CACzF,IAAI,cAAc,IACjB;CAID,IAAI;EACH,MAAM,UAAU,mBAAmB,IAAI;EACvC,MAAM,OAAO,QAAQ,WAAW,IAAI,SAAS;EAE7C,IACC,CAAC,YAAY,SAAS,CAAC,CAAC,CAAC,CAAC,WAAW,WAAW,KAChD,CAAC,KAAK,WAAW,GAAG,QAAQ,SAAS,IAAI,KAAK,KAC9C,SAAS,MAAM,EAAE,gBAAgB,MAAM,CAAC,CAAC,EAAE,OAAO,MAAM,MAExD;EAED,OAAO,mBAAmB,aAAa,MAAM,MAAM,CAAC;CACrD,QAAQ;EACP;CACD;AACD;;;;;;;AAQA,SAAgB,eAAe,iBAAwD;CACtF,MAAM,SAAwC,CAAC;CAC/C,KAAK,MAAM,SAAS,YAAY,iBAAiB;EAAE,WAAW;EAAM,eAAe;CAAK,CAAC,GAExF,IAAI,MAAM,OAAO,KAAK,YAAY,MAAM,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,WAAW,GAAG;EAC1E,MAAM,OAAO,KAAK,MAAM,YAAY,MAAM,IAAI;EAC9C,MAAM,UAAU,IAAI,SAAS,iBAAiB,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;EACvE,OAAO,WAAW,mBAAmB,aAAa,MAAM,MAAM,CAAC;CAChE;CAED,OAAO,OAAO,YACb,OAAO,QAAQ,MAAM,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,YAAY,MAAM,cAAc,MAAM,CAAC,CACnF;AACD"}
@@ -1,4 +1,4 @@
1
- import { t as loadEntry } from "./load-entry-CmkdlmDX.js";
1
+ import { t as loadEntry } from "./load-entry-Bodyd2Ok.js";
2
2
  import { existsSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
@@ -26,4 +26,4 @@ async function serve({ buildPath }) {
26
26
  }
27
27
 
28
28
  export { serve };
29
- //# sourceMappingURL=serve-Cc-ADdhZ.js.map
29
+ //# sourceMappingURL=serve-caOkS3o5.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"serve-Cc-ADdhZ.js","names":[],"sources":["../src/cli/serve.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadEntry } from \"./load-entry.js\";\n\n/**\n * Where `app-server serve` looks for the server build when no path is given:\n * the node host's entry in the React Router and Vite output layouts, then a\n * plain React Router build.\n */\nexport const DEFAULT_BUILD_PATHS = [\n\t\"build/server/app-server.js\",\n\t\"dist/server/app-server.js\",\n\t\"build/server/index.js\",\n];\n\n/**\n * Loads a production server build and starts it. The copy of this package in\n * the build runs the server when the build has one: see `loadEntry`.\n */\nexport async function serve({ buildPath }: { buildPath: string | undefined }): Promise<void> {\n\tconst path = buildPath ?? DEFAULT_BUILD_PATHS.find((candidate) => existsSync(candidate));\n\tif (path == null) {\n\t\tthrow new Error(\n\t\t\t`No server build found. Build the app, or pass its path. Looked for: ${DEFAULT_BUILD_PATHS.join(\", \")}.`,\n\t\t);\n\t}\n\tconst build: unknown = await import(pathToFileURL(resolve(path)).href);\n\tawait (await loadEntry(build)).start();\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,sBAAsB;CAClC;CACA;CACA;AACD;;;;;AAMA,eAAsB,MAAM,EAAE,aAA+D;CAC5F,MAAM,OAAO,aAAa,oBAAoB,MAAM,cAAc,WAAW,SAAS,CAAC;CACvF,IAAI,QAAQ,MACX,MAAM,IAAI,MACT,uEAAuE,oBAAoB,KAAK,IAAI,EAAE,EACvG;CAED,MAAM,QAAiB,MAAM,OAAO,cAAc,QAAQ,IAAI,CAAC,CAAC,CAAC;CACjE,OAAO,MAAM,UAAU,KAAK,EAAC,CAAE,MAAM;AACtC"}
1
+ {"version":3,"file":"serve-caOkS3o5.js","names":[],"sources":["../src/cli/serve.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadEntry } from \"./load-entry.js\";\n\n/**\n * Where `app-server serve` looks for the server build when no path is given:\n * the node host's entry in the React Router and Vite output layouts, then a\n * plain React Router build.\n */\nexport const DEFAULT_BUILD_PATHS = [\n\t\"build/server/app-server.js\",\n\t\"dist/server/app-server.js\",\n\t\"build/server/index.js\",\n];\n\n/**\n * Loads a production server build and starts it. The copy of this package in\n * the build runs the server when the build has one: see `loadEntry`.\n */\nexport async function serve({ buildPath }: { buildPath: string | undefined }): Promise<void> {\n\tconst path = buildPath ?? DEFAULT_BUILD_PATHS.find((candidate) => existsSync(candidate));\n\tif (path == null) {\n\t\tthrow new Error(\n\t\t\t`No server build found. Build the app, or pass its path. Looked for: ${DEFAULT_BUILD_PATHS.join(\", \")}.`,\n\t\t);\n\t}\n\tconst build: unknown = await import(pathToFileURL(resolve(path)).href);\n\tawait (await loadEntry(build)).start();\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,sBAAsB;CAClC;CACA;CACA;AACD;;;;;AAMA,eAAsB,MAAM,EAAE,aAA+D;CAC5F,MAAM,OAAO,aAAa,oBAAoB,MAAM,cAAc,WAAW,SAAS,CAAC;CACvF,IAAI,QAAQ,MACX,MAAM,IAAI,MACT,uEAAuE,oBAAoB,KAAK,IAAI,EAAE,EACvG;CAED,MAAM,QAAiB,MAAM,OAAO,cAAc,QAAQ,IAAI,CAAC,CAAC,CAAC;CACjE,OAAO,MAAM,UAAU,KAAK,EAAC,CAAE,MAAM;AACtC"}
@@ -1,9 +1,9 @@
1
1
  import { t as parsePort } from "./tcp-Dd1Mt6sN.js";
2
2
  import { r as jsonSink, t as errorAttributes } from "./log-BP6xXXZl.js";
3
- import { i as exitAfterFlush, n as devServerStage } from "./node-BFH82eeL.js";
3
+ import { i as exitAfterFlush, n as devServerStage } from "./node-C1qudLs_.js";
4
4
  import { t as requestListener } from "./response-writer-B7FoJjEE.js";
5
- import { t as SERVER_ENTRY_ID } from "./vite-iioAoxSt.js";
6
- import { t as loadEntry } from "./load-entry-CmkdlmDX.js";
5
+ import { t as SERVER_ENTRY_ID } from "./vite-tTxVimP6.js";
6
+ import { t as loadEntry } from "./load-entry-Bodyd2Ok.js";
7
7
  import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
8
8
  import { createServer } from "node:http";
9
9
  import { createServer as createServer$1 } from "node:net";
@@ -222,4 +222,4 @@ function viteHostname(host) {
222
222
  }
223
223
 
224
224
  export { start };
225
- //# sourceMappingURL=start-Cb3kknlF.js.map
225
+ //# sourceMappingURL=start-DREqYrZh.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"start-Cb3kknlF.js","names":["createServer","createHttpServer"],"sources":["../src/cli/served-apps.ts","../src/cli/start-port.ts","../src/cli/start.ts"],"sourcesContent":["import type { AppServerEntry } from \"../core/entry.js\";\n\ntype ServedApp = { entry: AppServerEntry; pending: number; replaced: boolean };\n\n/** What {@link servedApps} returns. */\ntype ServedApps = {\n\t/** Runs `handle` for a request that `entry` serves. */\n\tserve: <Result>(\n\t\tentry: AppServerEntry,\n\t\thandle: (entry: AppServerEntry) => Promise<Result>,\n\t) => Promise<Result>;\n\t/**\n\t * At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each\n\t * app still held. Resolves when the hooks finish or pass the deadline.\n\t */\n\tstopAll: () => Promise<void>;\n};\n\n/**\n * Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a\n * new app, and the old app's plugins still hold what their `setup` opened.\n * When the last request that the old app took returns, its `onShutdown` hooks\n * run, and the tracker lets go of it. A route edit makes a new entry with the\n * same app, which keeps its plugins.\n */\nexport function servedApps(): ServedApps {\n\tlet current: ServedApp | undefined;\n\tconst served = new Set<ServedApp>();\n\t// Why keep the app until its hooks settle: `stopAll` must wait for hooks that already run.\n\t// `stopPlugins` runs the hooks once, so a second call only waits.\n\tconst retire = async (app: ServedApp) => {\n\t\ttry {\n\t\t\tawait app.entry.stopPlugins();\n\t\t} finally {\n\t\t\tserved.delete(app);\n\t\t}\n\t};\n\treturn {\n\t\tserve: async (entry, handle) => {\n\t\t\tif (current?.entry.app === entry.app) {\n\t\t\t\tcurrent.entry = entry;\n\t\t\t} else {\n\t\t\t\tif (current != null) {\n\t\t\t\t\tcurrent.replaced = true;\n\t\t\t\t\tif (current.pending === 0) {\n\t\t\t\t\t\tvoid retire(current);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = { entry, pending: 0, replaced: false };\n\t\t\t\tserved.add(current);\n\t\t\t}\n\t\t\tconst app = current;\n\t\t\tapp.pending += 1;\n\t\t\ttry {\n\t\t\t\treturn await handle(entry);\n\t\t\t} finally {\n\t\t\t\tapp.pending -= 1;\n\t\t\t\tif (app.replaced && app.pending === 0) {\n\t\t\t\t\tvoid retire(app);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tstopAll: async () => {\n\t\t\tawait Promise.all(\n\t\t\t\tArray.from(served, async (app) => {\n\t\t\t\t\tapp.entry.abortShutdownSignal();\n\t\t\t\t\tawait retire(app);\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n","import { createServer } from \"node:net\";\nimport type { Server } from \"node:net\";\n\nconst MAX_PORT = 65_535;\n\n/** Options for {@link listenFromPort}. */\nexport type ListenFromPortOptions = {\n\t/** The first port to try. 0 lets the OS pick one. */\n\tport: number;\n\t/** @default every interface */\n\thostname?: string | undefined;\n\t/** When true, a port in use throws and no other port is tried. */\n\tstrictPort: boolean;\n\t/** Runs for each port in use before the next port is tried. */\n\tonPortInUse?: (port: number) => void;\n\t/**\n\t * Runs when `strictPort` is true and the server listens on `hostname`, but\n\t * another server holds the port on a wildcard address.\n\t */\n\tonWildcardInUse?: (port: number) => void;\n};\n\n/**\n * Starts `server` on `port`. When the port is in use, it tries each next port\n * up to 65535, like Vite and `react-router-serve` do in development.\n *\n * @returns the port that the server listens on\n */\nexport async function listenFromPort(\n\tserver: Server,\n\t{ port, hostname, strictPort, onPortInUse, onWildcardInUse }: ListenFromPortOptions,\n): Promise<number> {\n\tif (port === 0) {\n\t\tawait bind(server, port, hostname);\n\t\treturn boundPort(server, port);\n\t}\n\tif (strictPort) {\n\t\t// Why a warning and not an error: a server on one other address also fails the wildcard\n\t\t// check, and that server does not share `hostname`. Vite warns for the same reason.\n\t\tconst freeOnWildcard = hostname == null || (await isFreeOnWildcard(port));\n\t\tawait bind(server, port, hostname);\n\t\tif (!freeOnWildcard) {\n\t\t\tonWildcardInUse?.(port);\n\t\t}\n\t\treturn port;\n\t}\n\tfor (let candidate = port; candidate <= MAX_PORT; candidate++) {\n\t\t// Why the wildcard check: a server on `::` and a server on `localhost` can share a port, and\n\t\t// then the browser can reach the other server.\n\t\tif (hostname == null || (await isFreeOnWildcard(candidate))) {\n\t\t\ttry {\n\t\t\t\tawait bind(server, candidate, hostname);\n\t\t\t\treturn candidate;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isAddressInUse(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tonPortInUse?.(candidate);\n\t}\n\tthrow new Error(`No open port from ${port} to ${MAX_PORT}.`);\n}\n\nasync function bind(server: Server, port: number, hostname: string | undefined): Promise<void> {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tfunction onError(error: Error) {\n\t\t\tserver.off(\"listening\", onListening);\n\t\t\treject(error);\n\t\t}\n\t\tfunction onListening() {\n\t\t\tserver.off(\"error\", onError);\n\t\t\tresolve();\n\t\t}\n\t\tserver.once(\"error\", onError);\n\t\tserver.once(\"listening\", onListening);\n\t\tserver.listen(port, hostname);\n\t});\n}\n\nasync function isFreeOnWildcard(port: number): Promise<boolean> {\n\tconst probe = createServer();\n\ttry {\n\t\tawait bind(probe, port, undefined);\n\t} catch (error) {\n\t\tif (isAddressInUse(error)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n\tawait new Promise<void>((resolve) => {\n\t\tprobe.close(() => {\n\t\t\tresolve();\n\t\t});\n\t});\n\treturn true;\n}\n\nfunction boundPort(server: Server, fallback: number): number {\n\tconst address = server.address();\n\treturn typeof address === \"object\" && address != null ? address.port : fallback;\n}\n\nfunction isAddressInUse(error: unknown): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === \"EADDRINUSE\";\n}\n","import { createServer as createHttpServer } from \"node:http\";\nimport { errorAttributes, jsonSink } from \"../core/log.js\";\nimport { devServerStage } from \"../node/dev-server.js\";\nimport { exitAfterFlush } from \"../node/exit.js\";\nimport { listenerUrl } from \"../node/runtimes/listen-options.js\";\nimport { requestListener } from \"../node/response-writer.js\";\nimport { parsePort } from \"../node/tcp.js\";\nimport { SERVER_ENTRY_ID } from \"../vite/index.js\";\nimport { loadEntry } from \"./load-entry.js\";\nimport { servedApps } from \"./served-apps.js\";\nimport { listenFromPort } from \"./start-port.js\";\n\n/**\n * Runs the app in development: the same pipeline as production, with Vite in\n * middleware mode inside it. Each request loads the server entry through\n * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies\n * at once. HMR shares the port.\n *\n * The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the\n * server tries each next port, unless Vite's `server.strictPort` is true. The\n * host is `HOST`, else Vite's `server.host`.\n */\nexport async function start(): Promise<void> {\n\tconst vite = await import(\"vite\");\n\tconst httpServer = createHttpServer();\n\tconst viteServer = await vite.createServer({\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t});\n\t// Why read it for each request: a Vite restart, such as after a config edit, replaces the environments.\n\tconst ssrRunner = () => {\n\t\tconst { ssr } = viteServer.environments;\n\t\tif (ssr == null || !vite.isRunnableDevEnvironment(ssr)) {\n\t\t\tthrow new Error(\"Vite's SSR environment cannot run modules.\");\n\t\t}\n\t\treturn ssr.runner;\n\t};\n\tssrRunner();\n\tif (!viteServer.config.plugins.some((plugin) => plugin.name === \"@ngrok/app-server\")) {\n\t\tawait viteServer.close();\n\t\tthrow new Error(\n\t\t\t\"`app-server start` needs the `appServer` plugin from @ngrok/app-server/vite in the Vite config.\",\n\t\t);\n\t}\n\tconst devServer = devServerStage(viteServer.middlewares, {\n\t\tpublicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n\t});\n\tconst sink = jsonSink();\n\tconst apps = servedApps();\n\n\tconst listener = requestListener(async (request, bindings) => {\n\t\ttry {\n\t\t\treturn await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(SERVER_ENTRY_ID)),\n\t\t\t\tasync (entry) => entry.fetchDev(request, bindings, devServer),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tviteServer.ssrFixStacktrace(error);\n\t\t\t}\n\t\t\tsink.log(\"error\", \"dev request failed\", errorAttributes(error));\n\t\t\treturn new Response(error instanceof Error ? (error.stack ?? error.message) : String(error), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t});\n\t\t}\n\t});\n\thttpServer.on(\"request\", (request, response) => {\n\t\tvoid listener(request, response);\n\t});\n\n\tconst port =\n\t\tprocess.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);\n\tconst hostname = process.env.HOST || viteHostname(viteServer.config.server.host);\n\tconst boundPort = await listenFromPort(httpServer, {\n\t\tport,\n\t\thostname,\n\t\tstrictPort: viteServer.config.server.strictPort,\n\t\tonPortInUse: (inUse) => {\n\t\t\tsink.log(\"info\", \"port in use, trying the next port\", { \"server.port\": inUse });\n\t\t},\n\t\tonWildcardInUse: (inUse) => {\n\t\t\tsink.log(\"warn\", \"port in use on a wildcard address\", {\n\t\t\t\t\"server.port\": inUse,\n\t\t\t\t\"server.address\": hostname,\n\t\t\t});\n\t\t},\n\t});\n\tsink.log(\"info\", \"listening\", { \"app_server.urls\": [listenerUrl(hostname, boundPort)] });\n\n\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\tprocess.once(signal, () => {\n\t\t\tconst pluginsStopped = apps.stopAll();\n\t\t\thttpServer.closeAllConnections();\n\t\t\tconst httpClosed = new Promise<void>((resolve) => {\n\t\t\t\thttpServer.close(() => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst viteClosed = viteServer.close().catch((error: unknown) => {\n\t\t\t\tsink.log(\"error\", \"Vite close failed\", errorAttributes(error));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t});\n\t\t\tvoid Promise.all([pluginsStopped, httpClosed, viteClosed]).finally(exitAfterFlush);\n\t\t});\n\t}\n}\n\n/** The hostname for Vite's `server.host`: `true` is every interface, and no value is `localhost`. */\nfunction viteHostname(host: string | boolean | undefined): string | undefined {\n\tif (host === true) {\n\t\treturn undefined;\n\t}\n\treturn typeof host === \"string\" && host !== \"\" ? host : \"localhost\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,SAAgB,aAAyB;CACxC,IAAI;CACJ,MAAM,yBAAS,IAAI,IAAe;CAGlC,MAAM,SAAS,OAAO,QAAmB;EACxC,IAAI;GACH,MAAM,IAAI,MAAM,YAAY;EAC7B,UAAU;GACT,OAAO,OAAO,GAAG;EAClB;CACD;CACA,OAAO;EACN,OAAO,OAAO,OAAO,WAAW;GAC/B,IAAI,SAAS,MAAM,QAAQ,MAAM,KAChC,QAAQ,QAAQ;QACV;IACN,IAAI,WAAW,MAAM;KACpB,QAAQ,WAAW;KACnB,IAAI,QAAQ,YAAY,GACvB,AAAK,OAAO,OAAO;IAErB;IACA,UAAU;KAAE;KAAO,SAAS;KAAG,UAAU;IAAM;IAC/C,OAAO,IAAI,OAAO;GACnB;GACA,MAAM,MAAM;GACZ,IAAI,WAAW;GACf,IAAI;IACH,OAAO,MAAM,OAAO,KAAK;GAC1B,UAAU;IACT,IAAI,WAAW;IACf,IAAI,IAAI,YAAY,IAAI,YAAY,GACnC,AAAK,OAAO,GAAG;GAEjB;EACD;EACA,SAAS,YAAY;GACpB,MAAM,QAAQ,IACb,MAAM,KAAK,QAAQ,OAAO,QAAQ;IACjC,IAAI,MAAM,oBAAoB;IAC9B,MAAM,OAAO,GAAG;GACjB,CAAC,CACF;EACD;CACD;AACD;;;ACpEA,MAAM,WAAW;;;;;;;AAyBjB,eAAsB,eACrB,QACA,EAAE,MAAM,UAAU,YAAY,aAAa,mBACzB;CAClB,IAAI,SAAS,GAAG;EACf,MAAM,KAAK,QAAQ,MAAM,QAAQ;EACjC,OAAO,UAAU,QAAQ,IAAI;CAC9B;CACA,IAAI,YAAY;EAGf,MAAM,iB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,QAAQ;CAChC,CAAC;CAED,MAAM,OACL,QAAQ,IAAI,QAAQ,OAAO,WAAW,OAAO,OAAO,OAAO,UAAU,QAAQ,IAAI,IAAI;CACtF,MAAM,WAAW,QAAQ,IAAI,QAAQ,aAAa,WAAW,OAAO,OAAO,IAAI;CAC/E,MAAM,YAAY,MAAM,eAAe,YAAY;EAClD;EACA;EACA,YAAY,WAAW,OAAO,OAAO;EACrC,cAAc,UAAU;GACvB,KAAK,IAAI,QAAQ,qCAAqC,EAAE,eAAe,MAAM,CAAC;EAC/E;EACA,kBAAkB,UAAU;GAC3B,KAAK,IAAI,QAAQ,qCAAqC;IACrD,eAAe;IACf,kBAAkB;GACnB,CAAC;EACF;CACD,CAAC;CACD,KAAK,IAAI,QAAQ,aAAa,EAAE,mBAAmB,CAAC,YAAY,UAAU,SAAS,CAAC,EAAE,CAAC;CAEvF,KAAK,MAAM,UAAU,CAAC,WAAW,QAAQ,GACxC,QAAQ,KAAK,cAAc;EAC1B,MAAM,iBAAiB,KAAK,QAAQ;EACpC,WAAW,oBAAoB;EAC/B,MAAM,aAAa,IAAI,SAAe,YAAY;GACjD,WAAW,YAAY;IACtB,QAAQ;GACT,CAAC;EACF,CAAC;EACD,MAAM,aAAa,WAAW,MAAM,CAAC,CAAC,OAAO,UAAmB;GAC/D,KAAK,IAAI,SAAS,qBAAqB,gBAAgB,KAAK,CAAC;GAC7D,QAAQ,WAAW;EACpB,CAAC;EACD,AAAK,QAAQ,IAAI;GAAC;GAAgB;GAAY;EAAU,CAAC,CAAC,CAAC,QAAQ,cAAc;CAClF,CAAC;AAEH;;AAGA,SAAS,aAAa,MAAwD;CAC7E,IAAI,SAAS,MACZ;CAED,OAAO,OAAO,SAAS,YAAY,SAAS,KAAK,OAAO;AACzD"}
1
+ {"version":3,"file":"start-DREqYrZh.js","names":["createServer","createHttpServer"],"sources":["../src/cli/served-apps.ts","../src/cli/start-port.ts","../src/cli/start.ts"],"sourcesContent":["import type { AppServerEntry } from \"../core/entry.js\";\n\ntype ServedApp = { entry: AppServerEntry; pending: number; replaced: boolean };\n\n/** What {@link servedApps} returns. */\ntype ServedApps = {\n\t/** Runs `handle` for a request that `entry` serves. */\n\tserve: <Result>(\n\t\tentry: AppServerEntry,\n\t\thandle: (entry: AppServerEntry) => Promise<Result>,\n\t) => Promise<Result>;\n\t/**\n\t * At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each\n\t * app still held. Resolves when the hooks finish or pass the deadline.\n\t */\n\tstopAll: () => Promise<void>;\n};\n\n/**\n * Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a\n * new app, and the old app's plugins still hold what their `setup` opened.\n * When the last request that the old app took returns, its `onShutdown` hooks\n * run, and the tracker lets go of it. A route edit makes a new entry with the\n * same app, which keeps its plugins.\n */\nexport function servedApps(): ServedApps {\n\tlet current: ServedApp | undefined;\n\tconst served = new Set<ServedApp>();\n\t// Why keep the app until its hooks settle: `stopAll` must wait for hooks that already run.\n\t// `stopPlugins` runs the hooks once, so a second call only waits.\n\tconst retire = async (app: ServedApp) => {\n\t\ttry {\n\t\t\tawait app.entry.stopPlugins();\n\t\t} finally {\n\t\t\tserved.delete(app);\n\t\t}\n\t};\n\treturn {\n\t\tserve: async (entry, handle) => {\n\t\t\tif (current?.entry.app === entry.app) {\n\t\t\t\tcurrent.entry = entry;\n\t\t\t} else {\n\t\t\t\tif (current != null) {\n\t\t\t\t\tcurrent.replaced = true;\n\t\t\t\t\tif (current.pending === 0) {\n\t\t\t\t\t\tvoid retire(current);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = { entry, pending: 0, replaced: false };\n\t\t\t\tserved.add(current);\n\t\t\t}\n\t\t\tconst app = current;\n\t\t\tapp.pending += 1;\n\t\t\ttry {\n\t\t\t\treturn await handle(entry);\n\t\t\t} finally {\n\t\t\t\tapp.pending -= 1;\n\t\t\t\tif (app.replaced && app.pending === 0) {\n\t\t\t\t\tvoid retire(app);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tstopAll: async () => {\n\t\t\tawait Promise.all(\n\t\t\t\tArray.from(served, async (app) => {\n\t\t\t\t\tapp.entry.abortShutdownSignal();\n\t\t\t\t\tawait retire(app);\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n","import { createServer } from \"node:net\";\nimport type { Server } from \"node:net\";\n\nconst MAX_PORT = 65_535;\n\n/** Options for {@link listenFromPort}. */\nexport type ListenFromPortOptions = {\n\t/** The first port to try. 0 lets the OS pick one. */\n\tport: number;\n\t/** @default every interface */\n\thostname?: string | undefined;\n\t/** When true, a port in use throws and no other port is tried. */\n\tstrictPort: boolean;\n\t/** Runs for each port in use before the next port is tried. */\n\tonPortInUse?: (port: number) => void;\n\t/**\n\t * Runs when `strictPort` is true and the server listens on `hostname`, but\n\t * another server holds the port on a wildcard address.\n\t */\n\tonWildcardInUse?: (port: number) => void;\n};\n\n/**\n * Starts `server` on `port`. When the port is in use, it tries each next port\n * up to 65535, like Vite and `react-router-serve` do in development.\n *\n * @returns the port that the server listens on\n */\nexport async function listenFromPort(\n\tserver: Server,\n\t{ port, hostname, strictPort, onPortInUse, onWildcardInUse }: ListenFromPortOptions,\n): Promise<number> {\n\tif (port === 0) {\n\t\tawait bind(server, port, hostname);\n\t\treturn boundPort(server, port);\n\t}\n\tif (strictPort) {\n\t\t// Why a warning and not an error: a server on one other address also fails the wildcard\n\t\t// check, and that server does not share `hostname`. Vite warns for the same reason.\n\t\tconst freeOnWildcard = hostname == null || (await isFreeOnWildcard(port));\n\t\tawait bind(server, port, hostname);\n\t\tif (!freeOnWildcard) {\n\t\t\tonWildcardInUse?.(port);\n\t\t}\n\t\treturn port;\n\t}\n\tfor (let candidate = port; candidate <= MAX_PORT; candidate++) {\n\t\t// Why the wildcard check: a server on `::` and a server on `localhost` can share a port, and\n\t\t// then the browser can reach the other server.\n\t\tif (hostname == null || (await isFreeOnWildcard(candidate))) {\n\t\t\ttry {\n\t\t\t\tawait bind(server, candidate, hostname);\n\t\t\t\treturn candidate;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isAddressInUse(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tonPortInUse?.(candidate);\n\t}\n\tthrow new Error(`No open port from ${port} to ${MAX_PORT}.`);\n}\n\nasync function bind(server: Server, port: number, hostname: string | undefined): Promise<void> {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tfunction onError(error: Error) {\n\t\t\tserver.off(\"listening\", onListening);\n\t\t\treject(error);\n\t\t}\n\t\tfunction onListening() {\n\t\t\tserver.off(\"error\", onError);\n\t\t\tresolve();\n\t\t}\n\t\tserver.once(\"error\", onError);\n\t\tserver.once(\"listening\", onListening);\n\t\tserver.listen(port, hostname);\n\t});\n}\n\nasync function isFreeOnWildcard(port: number): Promise<boolean> {\n\tconst probe = createServer();\n\ttry {\n\t\tawait bind(probe, port, undefined);\n\t} catch (error) {\n\t\tif (isAddressInUse(error)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n\tawait new Promise<void>((resolve) => {\n\t\tprobe.close(() => {\n\t\t\tresolve();\n\t\t});\n\t});\n\treturn true;\n}\n\nfunction boundPort(server: Server, fallback: number): number {\n\tconst address = server.address();\n\treturn typeof address === \"object\" && address != null ? address.port : fallback;\n}\n\nfunction isAddressInUse(error: unknown): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === \"EADDRINUSE\";\n}\n","import { createServer as createHttpServer } from \"node:http\";\nimport { errorAttributes, jsonSink } from \"../core/log.js\";\nimport { devServerStage } from \"../node/dev-server.js\";\nimport { exitAfterFlush } from \"../node/exit.js\";\nimport { listenerUrl } from \"../node/runtimes/listen-options.js\";\nimport { requestListener } from \"../node/response-writer.js\";\nimport { parsePort } from \"../node/tcp.js\";\nimport { SERVER_ENTRY_ID } from \"../vite/index.js\";\nimport { loadEntry } from \"./load-entry.js\";\nimport { servedApps } from \"./served-apps.js\";\nimport { listenFromPort } from \"./start-port.js\";\n\n/**\n * Runs the app in development: the same pipeline as production, with Vite in\n * middleware mode inside it. Each request loads the server entry through\n * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies\n * at once. HMR shares the port.\n *\n * The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the\n * server tries each next port, unless Vite's `server.strictPort` is true. The\n * host is `HOST`, else Vite's `server.host`.\n */\nexport async function start(): Promise<void> {\n\tconst vite = await import(\"vite\");\n\tconst httpServer = createHttpServer();\n\tconst viteServer = await vite.createServer({\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t});\n\t// Why read it for each request: a Vite restart, such as after a config edit, replaces the environments.\n\tconst ssrRunner = () => {\n\t\tconst { ssr } = viteServer.environments;\n\t\tif (ssr == null || !vite.isRunnableDevEnvironment(ssr)) {\n\t\t\tthrow new Error(\"Vite's SSR environment cannot run modules.\");\n\t\t}\n\t\treturn ssr.runner;\n\t};\n\tssrRunner();\n\tif (!viteServer.config.plugins.some((plugin) => plugin.name === \"@ngrok/app-server\")) {\n\t\tawait viteServer.close();\n\t\tthrow new Error(\n\t\t\t\"`app-server start` needs the `appServer` plugin from @ngrok/app-server/vite in the Vite config.\",\n\t\t);\n\t}\n\tconst devServer = devServerStage(viteServer.middlewares, {\n\t\tpublicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n\t});\n\tconst sink = jsonSink();\n\tconst apps = servedApps();\n\n\tconst listener = requestListener(async (request, bindings) => {\n\t\ttry {\n\t\t\treturn await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(SERVER_ENTRY_ID)),\n\t\t\t\tasync (entry) => entry.fetchDev(request, bindings, devServer),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tviteServer.ssrFixStacktrace(error);\n\t\t\t}\n\t\t\tsink.log(\"error\", \"dev request failed\", errorAttributes(error));\n\t\t\treturn new Response(error instanceof Error ? (error.stack ?? error.message) : String(error), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t});\n\t\t}\n\t});\n\thttpServer.on(\"request\", (request, response) => {\n\t\tvoid listener(request, response);\n\t});\n\n\tconst port =\n\t\tprocess.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);\n\tconst hostname = process.env.HOST || viteHostname(viteServer.config.server.host);\n\tconst boundPort = await listenFromPort(httpServer, {\n\t\tport,\n\t\thostname,\n\t\tstrictPort: viteServer.config.server.strictPort,\n\t\tonPortInUse: (inUse) => {\n\t\t\tsink.log(\"info\", \"port in use, trying the next port\", { \"server.port\": inUse });\n\t\t},\n\t\tonWildcardInUse: (inUse) => {\n\t\t\tsink.log(\"warn\", \"port in use on a wildcard address\", {\n\t\t\t\t\"server.port\": inUse,\n\t\t\t\t\"server.address\": hostname,\n\t\t\t});\n\t\t},\n\t});\n\tsink.log(\"info\", \"listening\", { \"app_server.urls\": [listenerUrl(hostname, boundPort)] });\n\n\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\tprocess.once(signal, () => {\n\t\t\tconst pluginsStopped = apps.stopAll();\n\t\t\thttpServer.closeAllConnections();\n\t\t\tconst httpClosed = new Promise<void>((resolve) => {\n\t\t\t\thttpServer.close(() => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst viteClosed = viteServer.close().catch((error: unknown) => {\n\t\t\t\tsink.log(\"error\", \"Vite close failed\", errorAttributes(error));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t});\n\t\t\tvoid Promise.all([pluginsStopped, httpClosed, viteClosed]).finally(exitAfterFlush);\n\t\t});\n\t}\n}\n\n/** The hostname for Vite's `server.host`: `true` is every interface, and no value is `localhost`. */\nfunction viteHostname(host: string | boolean | undefined): string | undefined {\n\tif (host === true) {\n\t\treturn undefined;\n\t}\n\treturn typeof host === \"string\" && host !== \"\" ? host : \"localhost\";\n}\n"],"mappings":";;;;;;;;;;;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M,eAAe,YAAY;EAClD;EACA;EACA,YAAY,WAAW,OAAO,OAAO;EACrC,cAAc,UAAU;GACvB,KAAK,IAAI,QAAQ,qCAAqC,EAAE,eAAe,MAAM,CAAC;EAC/E;EACA,kBAAkB,UAAU;GAC3B,KAAK,IAAI,QAAQ,qCAAqC;IACrD,eAAe;IACf,kBAAkB;GACnB,CAAC;EACF;CACD,CAAC;CACD,KAAK,IAAI,QAAQ,aAAa,EAAE,mBAAmB,CAAC,YAAY,UAAU,SAAS,CAAC,EAAE,CAAC;CAEvF,KAAK,MAAM,UAAU,CAAC,WAAW,QAAQ,GACxC,QAAQ,KAAK,cAAc;EAC1B,MAAM,iBAAiB,KAAK,QAAQ;EACpC,WAAW,oBAAoB;EAC/B,MAAM,aAAa,IAAI,SAAe,YAAY;GACjD,WAAW,YAAY;IACtB,QAAQ;GACT,CAAC;EACF,CAAC;EACD,MAAM,aAAa,WAAW,MAAM,CAAC,CAAC,OAAO,UAAmB;GAC/D,KAAK,IAAI,SAAS,qBAAqB,gBAAgB,KAAK,CAAC;GAC7D,QAAQ,WAAW;EACpB,CAAC;EACD,AAAK,QAAQ,IAAI;GAAC;GAAgB;GAAY;EAAU,CAAC,CAAC,CAAC,QAAQ,cAAc;CAClF,CAAC;AAEH;;AAGA,SAAS,aAAa,MAAwD;CAC7E,IAAI,SAAS,MACZ;CAED,OAAO,OAAO,SAAS,YAAY,SAAS,KAAK,OAAO;AACzD"}
@@ -1,5 +1,5 @@
1
- import { a as FrameworkRuntime, h as Mode } from "./types-DLYxYS6M.js";
2
- import { t as TrailingSlash } from "./trailing-slash-DX7NB88H.js";
1
+ import { a as FrameworkRuntime, h as Mode } from "./types-CEvzAmcn.js";
2
+ import { t as TrailingSlash } from "./trailing-slash-BrymAEGv.js";
3
3
  import { AnyRouter, RegisteredRouter } from "@tanstack/react-router";
4
4
  /**
5
5
  * The `trailingSlash` mode of a TanStack router: the app's registered router
@@ -0,0 +1,56 @@
1
+ import { _ as RequestContext, a as FrameworkRuntime } from "./types-CEvzAmcn.js";
2
+ import { t as AppServer } from "./create-server-kzZWd_Lo.js";
3
+ /** Options for {@link createTestServer}. */
4
+ export type TestServerOptions = {
5
+ /**
6
+ * The app from `createServer`. Give each test server a new app, because an
7
+ * app runs the `setup` of its plugins one time.
8
+ */
9
+ app: AppServer;
10
+ /**
11
+ * The files of the client build, by their path in it, such as
12
+ * `providers/index.html`.
13
+ */
14
+ files?: Readonly<Record<string, string | Uint8Array>>;
15
+ /**
16
+ * The framework's answer to a request that no stage answers.
17
+ * @default a 404
18
+ */
19
+ framework?: FrameworkRuntime["fetch"];
20
+ };
21
+ /** What {@link createTestServer} gives. */
22
+ export type TestServer = {
23
+ /** Sends a request for `path`, such as `/providers?q=h100`, through the app. */
24
+ request: (path: string, init?: RequestInit) => Promise<Response>;
25
+ /**
26
+ * Cancels each body that the test did not read, runs each plugin's
27
+ * `onShutdown`, and removes the client build.
28
+ */
29
+ close: () => Promise<void>;
30
+ };
31
+ /**
32
+ * Starts an app in production mode over a client build of `files`, with no
33
+ * listener. It records the hashes of the inline scripts of each HTML file, as
34
+ * the build does, so `contentSecurityPolicy()` gives a prerendered page its
35
+ * CSP. `requestContext()` and `cspNonce()` work in the framework's answer.
36
+ *
37
+ * @example
38
+ * const server = await createTestServer({
39
+ * app: createServer({ plugins: defaultPlugins() }),
40
+ * files: { "providers/index.html": "<!doctype html><script>go()</script>" },
41
+ * framework: async () => new Response("rendered"),
42
+ * });
43
+ * const response = await server.request("/providers");
44
+ * await server.close();
45
+ */
46
+ export declare function createTestServer({ app, files, framework }: TestServerOptions): Promise<TestServer>;
47
+ /**
48
+ * Runs `work` as if in a server request, so `requestContext()` and
49
+ * `cspNonce()` give `values`. Use it to test a render. With no `logger`, the
50
+ * log lines go nowhere.
51
+ *
52
+ * @example
53
+ * const html = await withRequestContext({ cspNonce: "test-nonce" }, () => renderToString(<App />));
54
+ */
55
+ export declare function withRequestContext<Result>(values: Partial<RequestContext>, work: () => Result | Promise<Result>): Promise<Result>;
56
+ //# sourceMappingURL=testing.d.ts.map