@ngrok/app-server 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +610 -76
  2. package/dist/build-id-C6sYO9Yp.js +126 -0
  3. package/dist/build-id-C6sYO9Yp.js.map +1 -0
  4. package/dist/{build-manifest-8NfD1wnO.js → build-manifest-UDNk81Ce.js} +24 -6
  5. package/dist/build-manifest-UDNk81Ce.js.map +1 -0
  6. package/dist/cli.js +45 -25
  7. package/dist/cli.js.map +1 -1
  8. package/dist/client.d.ts +141 -0
  9. package/dist/client.js +326 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/compression-7_gToa8R.js +97 -0
  12. package/dist/compression-7_gToa8R.js.map +1 -0
  13. package/dist/create-server-iE1-s6Bi.js +1409 -0
  14. package/dist/create-server-iE1-s6Bi.js.map +1 -0
  15. package/dist/{deno-DNRgzHrk.js → deno-aqhikNMG.js} +2 -2
  16. package/dist/deno-aqhikNMG.js.map +1 -0
  17. package/dist/entry-DZ3qo7qF.js +116 -0
  18. package/dist/entry-DZ3qo7qF.js.map +1 -0
  19. package/dist/entry-DmJEqVfd.d.ts +622 -0
  20. package/dist/gzip-Doi4wqjX.js +294 -0
  21. package/dist/gzip-Doi4wqjX.js.map +1 -0
  22. package/dist/header-hook-Vzw9J9BY.js +159 -0
  23. package/dist/header-hook-Vzw9J9BY.js.map +1 -0
  24. package/dist/{index-oSE-tYRW.d.ts → index-Bo5G9LuQ.d.ts} +53 -14
  25. package/dist/index.d.ts +99 -269
  26. package/dist/index.js +47 -59
  27. package/dist/index.js.map +1 -1
  28. package/dist/listen-options-7TaXjyrk.js.map +1 -1
  29. package/dist/{load-entry-C03qqmhr.js → load-entry-AfYS_zS9.js} +8 -4
  30. package/dist/{load-entry-C03qqmhr.js.map → load-entry-AfYS_zS9.js.map} +1 -1
  31. package/dist/log-BP6xXXZl.js +122 -0
  32. package/dist/log-BP6xXXZl.js.map +1 -0
  33. package/dist/node-BFH82eeL.js +333 -0
  34. package/dist/node-BFH82eeL.js.map +1 -0
  35. package/dist/node-tBVQPjQv.js +41 -0
  36. package/dist/node-tBVQPjQv.js.map +1 -0
  37. package/dist/node-vite.d.ts +5 -4
  38. package/dist/node-vite.js +2 -17
  39. package/dist/node.d.ts +23 -4
  40. package/dist/node.js +2 -2
  41. package/dist/react-router-vite.d.ts +4 -3
  42. package/dist/react-router-vite.js +2 -20
  43. package/dist/react-router.d.ts +1 -1
  44. package/dist/react-router.js +8 -7
  45. package/dist/react-router.js.map +1 -1
  46. package/dist/request-context-BtQ87VYb.js +40 -0
  47. package/dist/request-context-BtQ87VYb.js.map +1 -0
  48. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  49. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  50. package/dist/response-writer-B7FoJjEE.js +289 -0
  51. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  52. package/dist/script-hashes-hqUk6kG7.js +53 -0
  53. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  54. package/dist/{serve-Cleo8RMO.js → serve-CDNgThjk.js} +3 -3
  55. package/dist/{serve-Cleo8RMO.js.map → serve-CDNgThjk.js.map} +1 -1
  56. package/dist/{start-CINALHxy.js → start-TLIprD74.js} +14 -19
  57. package/dist/start-TLIprD74.js.map +1 -0
  58. package/dist/static-files-Beju9riB.js +302 -0
  59. package/dist/static-files-Beju9riB.js.map +1 -0
  60. package/dist/tanstack-start-vite.d.ts +6 -5
  61. package/dist/tanstack-start-vite.js +2 -23
  62. package/dist/tanstack-start.d.ts +19 -2
  63. package/dist/tanstack-start.js +5 -14
  64. package/dist/tanstack-start.js.map +1 -1
  65. package/dist/{tcp-C-9AmFuM.js → tcp-Dd1Mt6sN.js} +6 -5
  66. package/dist/{tcp-C-9AmFuM.js.map → tcp-Dd1Mt6sN.js.map} +1 -1
  67. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  68. package/dist/types-DLYxYS6M.d.ts +392 -0
  69. package/dist/vercel-vite.d.ts +35 -0
  70. package/dist/vercel-vite.js +142 -0
  71. package/dist/vercel-vite.js.map +1 -0
  72. package/dist/vercel.d.ts +35 -0
  73. package/dist/vercel.js +89 -0
  74. package/dist/vercel.js.map +1 -0
  75. package/dist/vite-B-GfswoH.js +22 -0
  76. package/dist/vite-B-GfswoH.js.map +1 -0
  77. package/dist/vite-D4hfj3ph.js +19 -0
  78. package/dist/vite-D4hfj3ph.js.map +1 -0
  79. package/dist/vite-DyrhyKEr.js +25 -0
  80. package/dist/vite-DyrhyKEr.js.map +1 -0
  81. package/dist/vite-iioAoxSt.js +752 -0
  82. package/dist/vite-iioAoxSt.js.map +1 -0
  83. package/dist/vite.d.ts +2 -2
  84. package/dist/vite.js +1 -1
  85. package/package.json +24 -4
  86. package/dist/build-manifest-8NfD1wnO.js.map +0 -1
  87. package/dist/deno-DNRgzHrk.js.map +0 -1
  88. package/dist/entry-BkdUub2S.js +0 -638
  89. package/dist/entry-BkdUub2S.js.map +0 -1
  90. package/dist/log-CsjaKM8U.js +0 -59
  91. package/dist/log-CsjaKM8U.js.map +0 -1
  92. package/dist/node-CG7qXuWZ.js +0 -58
  93. package/dist/node-CG7qXuWZ.js.map +0 -1
  94. package/dist/node-YWPGmzAk.js +0 -215
  95. package/dist/node-YWPGmzAk.js.map +0 -1
  96. package/dist/node-ZMowKZDB.js +0 -3
  97. package/dist/node-vite.js.map +0 -1
  98. package/dist/react-router-vite.js.map +0 -1
  99. package/dist/start-CINALHxy.js.map +0 -1
  100. package/dist/tanstack-start-vite.js.map +0 -1
  101. package/dist/types-BfCkS7kQ.d.ts +0 -203
  102. package/dist/vite-mYZ2Y69u.js +0 -144
  103. package/dist/vite-mYZ2Y69u.js.map +0 -1
@@ -1,203 +0,0 @@
1
- import { Context, MiddlewareHandler } from "hono";
2
- /** A log level the server writes. */
3
- type LogLevel = "debug" | "info" | "warn" | "error";
4
- /**
5
- * Where the server writes log lines. Pass the app's own formatter, or use
6
- * {@link jsonSink}. Attribute names are flat and dotted, such as `http.method`.
7
- */
8
- type LogSink = {
9
- log: (level: LogLevel, message: string, attributes: Readonly<Record<string, unknown>>) => void;
10
- };
11
- /** The logger for one request. Each line carries the request ID, method, and path. */
12
- type RequestLogger = Record<LogLevel, (message: string, attributes?: Readonly<Record<string, unknown>>) => void>;
13
- /** What {@link requestContext} gives for the request that runs. */
14
- type RequestContext = {
15
- /** The request ID, when the `requestId` plugin runs. */
16
- requestId: string | undefined;
17
- /** The request's logger. Its lines carry the request ID. */
18
- logger: RequestLogger;
19
- };
20
- /** The server mode. */
21
- type Mode = "production" | "development";
22
- /**
23
- * The run side of a framework adapter: the framework that answers each
24
- * request that no plugin or route answers.
25
- */
26
- type FrameworkRuntime = {
27
- /** A name for logs and errors. */
28
- name: string;
29
- /** Renders one request. */
30
- fetch: (request: Request, context: Context<AppServerEnv>) => Promise<Response>;
31
- /**
32
- * The client build, when the framework knows it. The entry that the Vite
33
- * plugin generates gives it instead.
34
- */
35
- clientDirectory?: string;
36
- /**
37
- * The URL paths that the build prerendered, when the framework knows them.
38
- * Else the server reads the paths that the Vite plugin captured.
39
- */
40
- prerenderedPaths?: readonly string[];
41
- /** Whether a URL path is a data request, such as a React Router `.data` file. */
42
- isDataRequest?: (path: string) => boolean;
43
- /** Content types that `mime` does not know, by file extension, such as `{ ".data": "text/x-script" }`. */
44
- contentTypes?: Readonly<Record<string, string>>;
45
- };
46
- /** Makes the run side of a framework adapter from the framework's server module. */
47
- type FrameworkRuntimeFactory = (serverModule: unknown, info: {
48
- mode: Mode;
49
- }) => FrameworkRuntime;
50
- /** What a host knows about a file under the client build. */
51
- type FileInfo = {
52
- kind: "file" | "directory";
53
- /** The size in bytes. */
54
- size: number;
55
- mtimeMs: number;
56
- };
57
- /**
58
- * The files of the client build. Each path is a URL path that the static
59
- * stages checked: it starts with `/`, and it has no `..`, no `//`, and no
60
- * `\`.
61
- */
62
- type StaticFiles = {
63
- /** What is at `path`, or `undefined` when nothing is there. */
64
- stat: (path: string) => Promise<FileInfo | undefined>;
65
- /** The bytes of the file at `path`. */
66
- open: (path: string) => Promise<ReadableStream<Uint8Array>>;
67
- };
68
- /** Request-scoped storage, such as `AsyncLocalStorage`. */
69
- type RequestStore = {
70
- /** Runs `work` with `value` as the stored value. */
71
- run: <Result>(value: Context<AppServerEnv>, work: () => Result) => Result;
72
- /** The stored value of the request that runs, else `undefined`. */
73
- get: () => Context<AppServerEnv> | undefined;
74
- };
75
- /** How a long-lived host stops. A serverless host has none. */
76
- type Lifecycle = {
77
- /**
78
- * Calls `stop` once when the host must stop, such as on `SIGTERM`. The host
79
- * exits when `stop` settles.
80
- */
81
- onStop: (stop: () => Promise<void>) => void;
82
- };
83
- /** The run side of a host adapter: where the server runs. */
84
- type HostRuntime = {
85
- /** A name for logs and errors. */
86
- name: string;
87
- /** The files of the client build at `clientDirectory`, a file path or a `file:` URL. */
88
- files: (clientDirectory: string) => StaticFiles;
89
- /** The listeners when the app sets none. */
90
- listeners: () => readonly Listener[];
91
- /** The storage for {@link requestContext}. Without it, `requestContext()` gives `undefined`. */
92
- storage?: RequestStore;
93
- /**
94
- * Gzips a byte stream and flushes after each chunk. Without it,
95
- * `streamingCompress` sends each response as it is.
96
- */
97
- gzip?: (source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>;
98
- lifecycle?: Lifecycle;
99
- };
100
- /**
101
- * What a listener passes to the app with each request. A host can add its own
102
- * values, such as Node's request and response.
103
- */
104
- type ListenerBindings = {
105
- /** The client's IP address, when the runtime knows it. */
106
- remoteAddress?: string | undefined;
107
- [binding: string]: unknown;
108
- };
109
- /** The Hono bindings of an app server: the listener's values and the framework. */
110
- type ServerBindings = ListenerBindings & {
111
- framework: FrameworkRuntime;
112
- };
113
- /** The Hono environment of an app server. */
114
- type AppServerEnv = {
115
- Bindings: ServerBindings;
116
- Variables: {
117
- /** The request ID, set by the `requestId` plugin. */
118
- requestId?: string;
119
- logger: RequestLogger;
120
- /**
121
- * The `etagPart` of each plugin that the request passed, in order. The
122
- * static stages add them to each file's ETag. The server sets this list.
123
- */
124
- etagParts?: readonly string[];
125
- };
126
- };
127
- /** The request handler that a listener calls. */
128
- type FetchHandler = (request: Request, bindings: ListenerBindings) => Response | Promise<Response>;
129
- /** What a plugin learns at startup, before the first request. */
130
- type SetupInfo = {
131
- /** The files of the client build. */
132
- files: StaticFiles;
133
- /** The URL paths that the build prerendered. */
134
- prerenderedPaths: readonly string[];
135
- /** The headers of each prerendered file, by URL path, that the Vite plugin captured. */
136
- capturedHeaders: ReadonlyMap<string, Readonly<Record<string, string>>>;
137
- /** Whether a URL path is a data request of the framework. */
138
- isDataRequest: (path: string) => boolean;
139
- /** Content types of the framework's files that `mime` does not know, by file extension. */
140
- contentTypes: Readonly<Record<string, string>>;
141
- /** The host's gzip stream, when it has one. */
142
- gzip: ((source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>) | undefined;
143
- logger: LogSink;
144
- } & ({
145
- mode: "production";
146
- } | {
147
- mode: "development";
148
- /** The dev server as a pipeline stage. It serves source modules, HMR, and CSS. */
149
- devServer: MiddlewareHandler<AppServerEnv>;
150
- });
151
- /**
152
- * One step of the request pipeline. Plugins run in list order, so the order is
153
- * the contract.
154
- *
155
- * @example
156
- * const livez: Plugin = {
157
- * name: "livez",
158
- * middleware: async (c, next) => (c.req.path === "/livez" ? c.text("ok") : next()),
159
- * };
160
- */
161
- type Plugin = {
162
- /** A name for logs and errors. */
163
- name: string;
164
- /** The Hono middleware for this step. */
165
- middleware?: MiddlewareHandler<AppServerEnv>;
166
- /** Runs once before the server takes requests. A thrown error stops startup. */
167
- setup?: (info: SetupInfo) => void | Promise<void>;
168
- /** Runs at shutdown while the listeners drain. The server stops waiting for it at the drain deadline. */
169
- onShutdown?: () => Promise<void>;
170
- /**
171
- * A value that this plugin's changes to a response depend on, such as the
172
- * env values it writes into each document. The server adds it to the ETag
173
- * of each static file that the request reaches after this plugin, so a 304
174
- * never keeps a response made with an old value. Return `undefined` when
175
- * the plugin changes nothing.
176
- */
177
- etagPart?: () => string | undefined;
178
- };
179
- /** A running listener. */
180
- type StartedListener = {
181
- /** The URL the listener answers on. */
182
- url: string;
183
- /**
184
- * Stops new connections and waits for open requests. At the deadline, it
185
- * closes the connections that are still open.
186
- */
187
- stop: (options: {
188
- deadlineMs: number;
189
- }) => Promise<void>;
190
- };
191
- /**
192
- * How the server receives connections, separate from the request pipeline.
193
- *
194
- * @example
195
- * createServer({ listeners: [tcp({ port: 8080 })] });
196
- */
197
- type Listener = {
198
- /** A name for logs. */
199
- name: string;
200
- start: (fetch: FetchHandler) => Promise<StartedListener>;
201
- };
202
- export { ServerBindings as _, FrameworkRuntimeFactory as a, StaticFiles as b, Listener as c, LogSink as d, Mode as f, RequestStore as g, RequestLogger as h, FrameworkRuntime as i, ListenerBindings as l, RequestContext as m, FetchHandler as n, HostRuntime as o, Plugin as p, FileInfo as r, Lifecycle as s, AppServerEnv as t, LogLevel as u, SetupInfo as v, StartedListener as y };
203
- //# sourceMappingURL=types-BfCkS7kQ.d.ts.map
@@ -1,144 +0,0 @@
1
- import { n as manifestKey, t as BUILD_MANIFEST_FILE } from "./build-manifest-8NfD1wnO.js";
2
- import { dirname, join, relative, resolve } from "node:path";
3
- import { mkdirSync, writeFileSync } from "node:fs";
4
-
5
- // src/vite/index.ts
6
- /** The module ID of the server entry that {@link appServer} generates. */
7
- const SERVER_ENTRY_ID = "virtual:@ngrok/app-server/entry";
8
- const RESOLVED_SERVER_ENTRY_ID = `\0${SERVER_ENTRY_ID}`;
9
- /** The Vite environment that builds the server. */
10
- const SERVER_ENVIRONMENT = "ssr";
11
- /** The header that turns on Node's header store for a response, so `finish` can read every header. */
12
- const CAPTURE_MARKER = "x-app-server-capture";
13
- /**
14
- * Headers that describe one transfer, not the resource. The server sets its
15
- * own, and a cookie must never replay to every visitor. `Vary` is left out
16
- * because the preview server adds `Vary: Origin` to every response.
17
- */
18
- const UNCAPTURED_HEADERS = /* @__PURE__ */ new Set([
19
- CAPTURE_MARKER,
20
- "connection",
21
- "content-encoding",
22
- "content-length",
23
- "date",
24
- "etag",
25
- "keep-alive",
26
- "last-modified",
27
- "set-cookie",
28
- "transfer-encoding",
29
- "vary"
30
- ]);
31
- /** The source of the server entry. */
32
- function serverEntrySource({ framework, host, appModule, clientDirectory }) {
33
- return [
34
- `import * as serverModule from ${JSON.stringify(framework.serverModule)};`,
35
- `import { createEntry, createServer } from "@ngrok/app-server";`,
36
- `import { runtime } from ${JSON.stringify(framework.runtimeModule)};`,
37
- `import { host } from ${JSON.stringify(host.runtimeModule)};`,
38
- ...appModule == null ? [`const app = createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === "1" });`] : [`import app from ${JSON.stringify(appModule)};`],
39
- `export const appServer = createEntry({`,
40
- `\tapp,`,
41
- `\thost,`,
42
- `\tclientDirectory: ${clientDirectory},`,
43
- `\tframework: (mode) => runtime(serverModule, { ${framework.runtimeOptions == null ? "" : `...${framework.runtimeOptions}, `}mode }),`,
44
- `});`
45
- ].join("\n");
46
- }
47
- /** The absolute path of an environment's build output. */
48
- function outDir(config, environment) {
49
- return resolve(config.root, config.environments[environment]?.build.outDir ?? config.build.outDir);
50
- }
51
- /**
52
- * Records each 2xx path and the headers of each non-document response while
53
- * the framework's prerender pass runs. It writes them to `.app-server.json` in
54
- * the client build when the preview server closes.
55
- */
56
- function capture(server) {
57
- const clientDirectory = outDir(server.config, "client");
58
- const paths = /* @__PURE__ */ new Set();
59
- const headers = {};
60
- server.middlewares.use((request, response, next) => {
61
- const { pathname } = new URL(request.url ?? "/", "http://localhost");
62
- response.setHeader(CAPTURE_MARKER, "1");
63
- response.once("finish", () => {
64
- if (response.statusCode < 200 || response.statusCode >= 300) return;
65
- const key = manifestKey(pathname);
66
- paths.add(key);
67
- if (String(response.getHeader("content-type") ?? "").startsWith("text/html")) return;
68
- const recorded = {};
69
- for (const [name, value] of Object.entries(response.getHeaders())) if (!UNCAPTURED_HEADERS.has(name) && !/^\d+$/u.test(name) && value != null) recorded[name] = Array.isArray(value) ? value.join(", ") : String(value);
70
- headers[key] = recorded;
71
- });
72
- next();
73
- });
74
- server.httpServer.once("close", () => {
75
- const manifest = {
76
- prerendered: [...paths].toSorted(),
77
- headers: Object.fromEntries(Object.entries(headers).toSorted(([first], [second]) => first.localeCompare(second)))
78
- };
79
- mkdirSync(clientDirectory, { recursive: true });
80
- writeFileSync(join(clientDirectory, BUILD_MANIFEST_FILE), `${JSON.stringify(manifest, null, " ")}\n`);
81
- });
82
- }
83
- /**
84
- * The Vite plugin for `@ngrok/app-server`. Put it next to the framework's
85
- * plugin.
86
- *
87
- * - It adds the server entry to the server build, such as
88
- * `build/server/app-server.js` on the node host. The entry bundles the app
89
- * (the default export of `app`) with the framework's server module, so the
90
- * server gets the app's path aliases and its one copy of the framework.
91
- * The framework's own entry does not change.
92
- * - During the framework's prerender pass, it records each prerendered path
93
- * and the headers of each prerendered file that is not an HTML document into
94
- * `.app-server.json` in the client build. The `prerendered` plugin replays
95
- * the headers. A document's headers depend on its request, so they are not
96
- * recorded.
97
- *
98
- * @example
99
- * // vite.config.ts
100
- * export default defineConfig({
101
- * plugins: [
102
- * reactRouter(),
103
- * appServer({ framework: reactRouterAdapter(), host: node(), app: "./server.ts" }),
104
- * ],
105
- * });
106
- */
107
- function appServer({ framework, host, app }) {
108
- let config;
109
- return {
110
- name: "@ngrok/app-server",
111
- configResolved: (resolved) => {
112
- config = resolved;
113
- framework.validate?.(resolved);
114
- },
115
- buildStart() {
116
- if (this.environment.name === SERVER_ENVIRONMENT && this.environment.mode === "build") this.emitFile({
117
- type: "chunk",
118
- id: SERVER_ENTRY_ID,
119
- fileName: host.entryFileName
120
- });
121
- },
122
- renderStart(options) {
123
- if (this.environment.name === SERVER_ENVIRONMENT && options.format !== "es") throw new Error(`@ngrok/app-server needs an ES module server build, and this build has the format "${options.format}".`);
124
- },
125
- resolveId: (id) => id === "virtual:@ngrok/app-server/entry" ? RESOLVED_SERVER_ENTRY_ID : void 0,
126
- load(id) {
127
- if (id !== RESOLVED_SERVER_ENTRY_ID || config == null) return null;
128
- const clientDirectory = outDir(config, "client");
129
- const fromEntry = relative(dirname(join(outDir(config, SERVER_ENVIRONMENT), host.entryFileName)), clientDirectory).replaceAll("\\", "/");
130
- return serverEntrySource({
131
- framework,
132
- host,
133
- appModule: app == null ? void 0 : resolve(config.root, app),
134
- clientDirectory: this.environment.mode === "build" ? `new URL(${JSON.stringify(`${fromEntry}/`)}, import.meta.url).href` : JSON.stringify(clientDirectory)
135
- });
136
- },
137
- configurePreviewServer: (server) => {
138
- if (framework.isPrerenderPass(server)) capture(server);
139
- }
140
- };
141
- }
142
-
143
- export { appServer as n, serverEntrySource as r, SERVER_ENTRY_ID as t };
144
- //# sourceMappingURL=vite-mYZ2Y69u.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"vite-mYZ2Y69u.js","names":[],"sources":["../src/vite/index.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport type { Plugin, PreviewServer, ResolvedConfig } from \"vite\";\nimport { BUILD_MANIFEST_FILE, manifestKey } from \"../core/build-manifest.js\";\nimport type { BuildManifest } from \"../core/build-manifest.js\";\n\n/** The module ID of the server entry that {@link appServer} generates. */\nexport const SERVER_ENTRY_ID = \"virtual:@ngrok/app-server/entry\";\nconst RESOLVED_SERVER_ENTRY_ID = `\\0${SERVER_ENTRY_ID}`;\n\n/** The Vite environment that builds the server. */\nconst SERVER_ENVIRONMENT = \"ssr\";\n\n/** The header that turns on Node's header store for a response, so `finish` can read every header. */\nconst CAPTURE_MARKER = \"x-app-server-capture\";\n\n/**\n * Headers that describe one transfer, not the resource. The server sets its\n * own, and a cookie must never replay to every visitor. `Vary` is left out\n * because the preview server adds `Vary: Origin` to every response.\n */\nconst UNCAPTURED_HEADERS = new Set([\n\tCAPTURE_MARKER,\n\t\"connection\",\n\t\"content-encoding\",\n\t\"content-length\",\n\t\"date\",\n\t\"etag\",\n\t\"keep-alive\",\n\t\"last-modified\",\n\t\"set-cookie\",\n\t\"transfer-encoding\",\n\t\"vary\",\n]);\n\n/**\n * The build side of a framework adapter. The Vite config imports it, such as\n * `reactRouterAdapter()` from `@ngrok/app-server/react-router/vite`.\n */\nexport type FrameworkBuild = {\n\t/** A name for logs and errors. */\n\tname: string;\n\t/** The Vite ID of the framework's server module, such as `virtual:react-router/server-build`. */\n\tserverModule: string;\n\t/**\n\t * The module whose `runtime` export makes the run side from the server\n\t * module. It has the type `FrameworkRuntimeFactory`.\n\t */\n\truntimeModule: string;\n\t/**\n\t * The source of an object literal with more options for `runtime`, such as\n\t * a build constant of the framework. The bundler replaces the constants in\n\t * it, because the source is part of the server entry.\n\t */\n\truntimeOptions?: string;\n\t/** Whether a preview server runs the framework's prerender pass. */\n\tisPrerenderPass: (server: PreviewServer) => boolean;\n\t/** Throws for a config that the adapter does not support, so the build fails, not the first request. */\n\tvalidate?: (config: ResolvedConfig) => void;\n};\n\n/**\n * The build side of a host adapter. The Vite config imports it, such as\n * `node()` from `@ngrok/app-server/node/vite`.\n */\nexport type HostBuild = {\n\t/** A name for logs and errors. */\n\tname: string;\n\t/** The module whose `host` export is the run side, a `HostRuntime`. */\n\truntimeModule: string;\n\t/** The file name of the server entry in the server build, such as `app-server.js`. */\n\tentryFileName: string;\n};\n\n/** Options for {@link appServer}. */\nexport type AppServerOptions = {\n\tframework: FrameworkBuild;\n\thost: HostBuild;\n\t/**\n\t * The module whose default export is the app from `createServer`, relative\n\t * to the Vite root. When omitted, the server uses its default plugins.\n\t */\n\tapp?: string;\n};\n\n/** What {@link serverEntrySource} needs. */\ntype EntrySource = {\n\tframework: Pick<FrameworkBuild, \"serverModule\" | \"runtimeModule\" | \"runtimeOptions\">;\n\thost: Pick<HostBuild, \"runtimeModule\">;\n\t/** The absolute path of the app module, else `undefined` for the default app. */\n\tappModule: string | undefined;\n\t/** The source of an expression that gives the client build: a path or a `file:` URL. */\n\tclientDirectory: string;\n};\n\n/** The source of the server entry. */\nexport function serverEntrySource({\n\tframework,\n\thost,\n\tappModule,\n\tclientDirectory,\n}: EntrySource): string {\n\treturn [\n\t\t`import * as serverModule from ${JSON.stringify(framework.serverModule)};`,\n\t\t// Why from the bundle: the CLI calls this export, so the server runs on the bundle's copy of\n\t\t// this package and of the framework, the same copies as the app and the routes.\n\t\t`import { createEntry, createServer } from \"@ngrok/app-server\";`,\n\t\t`import { runtime } from ${JSON.stringify(framework.runtimeModule)};`,\n\t\t`import { host } from ${JSON.stringify(host.runtimeModule)};`,\n\t\t...(appModule == null\n\t\t\t? [\n\t\t\t\t\t`const app = createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\" });`,\n\t\t\t\t]\n\t\t\t: [`import app from ${JSON.stringify(appModule)};`]),\n\t\t`export const appServer = createEntry({`,\n\t\t`\\tapp,`,\n\t\t`\\thost,`,\n\t\t`\\tclientDirectory: ${clientDirectory},`,\n\t\t`\\tframework: (mode) => runtime(serverModule, { ${framework.runtimeOptions == null ? \"\" : `...${framework.runtimeOptions}, `}mode }),`,\n\t\t`});`,\n\t].join(\"\\n\");\n}\n\n/** The absolute path of an environment's build output. */\nfunction outDir(config: ResolvedConfig, environment: string): string {\n\treturn resolve(\n\t\tconfig.root,\n\t\tconfig.environments[environment]?.build.outDir ?? config.build.outDir,\n\t);\n}\n\n/**\n * Records each 2xx path and the headers of each non-document response while\n * the framework's prerender pass runs. It writes them to `.app-server.json` in\n * the client build when the preview server closes.\n */\nfunction capture(server: PreviewServer): void {\n\tconst clientDirectory = outDir(server.config, \"client\");\n\tconst paths = new Set<string>();\n\tconst headers: BuildManifest[\"headers\"] = {};\n\tserver.middlewares.use((request, response, next) => {\n\t\tconst { pathname } = new URL(request.url ?? \"/\", \"http://localhost\");\n\t\t// Why: Node keeps the headers that `writeHead` gets readable only when a header was set first.\n\t\tresponse.setHeader(CAPTURE_MARKER, \"1\");\n\t\tresponse.once(\"finish\", () => {\n\t\t\tif (response.statusCode < 200 || response.statusCode >= 300) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst key = manifestKey(pathname);\n\t\t\tpaths.add(key);\n\t\t\t// Why skip documents: the framework sets their headers for each request (a nonce, the\n\t\t\t// host), so the headers of the build's request are wrong for every other one.\n\t\t\tif (String(response.getHeader(\"content-type\") ?? \"\").startsWith(\"text/html\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst recorded: Record<string, string> = {};\n\t\t\tfor (const [name, value] of Object.entries(response.getHeaders())) {\n\t\t\t\t// Why skip index names: after a `setHeader`, Node stores a flat header array from\n\t\t\t\t// `writeHead`, as TanStack Start's preview server sends, under its indexes too.\n\t\t\t\tif (!UNCAPTURED_HEADERS.has(name) && !/^\\d+$/u.test(name) && value != null) {\n\t\t\t\t\trecorded[name] = Array.isArray(value) ? value.join(\", \") : String(value);\n\t\t\t\t}\n\t\t\t}\n\t\t\theaders[key] = recorded;\n\t\t});\n\t\tnext();\n\t});\n\tserver.httpServer.once(\"close\", () => {\n\t\tconst manifest: BuildManifest = {\n\t\t\tprerendered: [...paths].toSorted(),\n\t\t\theaders: Object.fromEntries(\n\t\t\t\tObject.entries(headers).toSorted(([first], [second]) => first.localeCompare(second)),\n\t\t\t),\n\t\t};\n\t\tmkdirSync(clientDirectory, { recursive: true });\n\t\twriteFileSync(\n\t\t\tjoin(clientDirectory, BUILD_MANIFEST_FILE),\n\t\t\t`${JSON.stringify(manifest, null, \"\\t\")}\\n`,\n\t\t);\n\t});\n}\n\n/**\n * The Vite plugin for `@ngrok/app-server`. Put it next to the framework's\n * plugin.\n *\n * - It adds the server entry to the server build, such as\n * `build/server/app-server.js` on the node host. The entry bundles the app\n * (the default export of `app`) with the framework's server module, so the\n * server gets the app's path aliases and its one copy of the framework.\n * The framework's own entry does not change.\n * - During the framework's prerender pass, it records each prerendered path\n * and the headers of each prerendered file that is not an HTML document into\n * `.app-server.json` in the client build. The `prerendered` plugin replays\n * the headers. A document's headers depend on its request, so they are not\n * recorded.\n *\n * @example\n * // vite.config.ts\n * export default defineConfig({\n * \tplugins: [\n * \t\treactRouter(),\n * \t\tappServer({ framework: reactRouterAdapter(), host: node(), app: \"./server.ts\" }),\n * \t],\n * });\n */\nexport function appServer({ framework, host, app }: AppServerOptions): Plugin {\n\tlet config: ResolvedConfig | undefined;\n\treturn {\n\t\tname: \"@ngrok/app-server\",\n\t\tconfigResolved: (resolved) => {\n\t\t\tconfig = resolved;\n\t\t\tframework.validate?.(resolved);\n\t\t},\n\t\tbuildStart() {\n\t\t\t// Why a chunk and not an input: the framework's own entry stays the same, and its prerender\n\t\t\t// preview reads that entry.\n\t\t\tif (this.environment.name === SERVER_ENVIRONMENT && this.environment.mode === \"build\") {\n\t\t\t\tthis.emitFile({ type: \"chunk\", id: SERVER_ENTRY_ID, fileName: host.entryFileName });\n\t\t\t}\n\t\t},\n\t\trenderStart(options) {\n\t\t\t// Why: the server entry uses `import.meta.url`, and the CLI loads it as an ES module.\n\t\t\tif (this.environment.name === SERVER_ENVIRONMENT && options.format !== \"es\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`@ngrok/app-server needs an ES module server build, and this build has the format \"${options.format}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t\tresolveId: (id) => (id === SERVER_ENTRY_ID ? RESOLVED_SERVER_ENTRY_ID : undefined),\n\t\tload(id) {\n\t\t\tif (id !== RESOLVED_SERVER_ENTRY_ID || config == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst clientDirectory = outDir(config, \"client\");\n\t\t\t// Why a URL in a build: the build can move, and the client build stays next to it.\n\t\t\tconst fromEntry = relative(\n\t\t\t\tdirname(join(outDir(config, SERVER_ENVIRONMENT), host.entryFileName)),\n\t\t\t\tclientDirectory,\n\t\t\t).replaceAll(\"\\\\\", \"/\");\n\t\t\treturn serverEntrySource({\n\t\t\t\tframework,\n\t\t\t\thost,\n\t\t\t\tappModule: app == null ? undefined : resolve(config.root, app),\n\t\t\t\tclientDirectory:\n\t\t\t\t\tthis.environment.mode === \"build\"\n\t\t\t\t\t\t? `new URL(${JSON.stringify(`${fromEntry}/`)}, import.meta.url).href`\n\t\t\t\t\t\t: JSON.stringify(clientDirectory),\n\t\t\t});\n\t\t},\n\t\tconfigurePreviewServer: (server) => {\n\t\t\tif (framework.isPrerenderPass(server)) {\n\t\t\t\tcapture(server);\n\t\t\t}\n\t\t},\n\t};\n}\n"],"mappings":"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"}