@ngrok/app-server 0.4.1 → 0.5.1

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 (119) hide show
  1. package/README.md +223 -64
  2. package/dist/brotli-only-BVAagKt3.js +63 -0
  3. package/dist/build-id-CwMbED1n.js +245 -0
  4. package/dist/{build-manifest-DBMWe3Lx.js → build-manifest-CoBztw_6.js} +13 -4
  5. package/dist/bun-BCz6K_Xv.js +1 -2
  6. package/dist/check-count-DQl5z_qe.js +17 -0
  7. package/dist/cli.js +9 -6
  8. package/dist/client-browser.d.ts +2 -3
  9. package/dist/client-browser.js +1 -1
  10. package/dist/client.d.ts +5 -4
  11. package/dist/client.js +9 -6
  12. package/dist/{compress-Cp5NfXCC.js → compress-2w3jqBh7.js} +2 -3
  13. package/dist/{compression-CT2mWlKM.js → compression-uJxu0JVb.js} +32 -5
  14. package/dist/content-types-Le-5BNEC.js +10 -0
  15. package/dist/{create-server-Bp1yILQk.js → create-server-DVTZun6D.js} +617 -306
  16. package/dist/create-server-PA0qniaK.js +3 -0
  17. package/dist/{create-server-X2GR-U6t.d.ts → create-server-UVsHFQyK.d.ts} +116 -54
  18. package/dist/deno-aqhikNMG.js +1 -2
  19. package/dist/{entry-BoxCqc6w.js → entry-CMhX3yf8.js} +85 -65
  20. package/dist/entry-CvZ4U0ia.js +3 -0
  21. package/dist/{entry-DZTCaL3d.d.ts → entry-DBq_3s8X.d.ts} +10 -36
  22. package/dist/entry-protocol-C30UPXzy.js +14 -0
  23. package/dist/entry-source-DSE5NAJu.js +70 -0
  24. package/dist/entry-source-SHoE-DUP.js +3 -0
  25. package/dist/exit-Hh-O3gp4.js +83 -0
  26. package/dist/{header-hook-Vzw9J9BY.js → header-hook-JfqaTt34.js} +69 -23
  27. package/dist/{index-B8LsM6Mh.d.ts → index-gzGs53Ue.d.ts} +43 -38
  28. package/dist/index.d.ts +88 -44
  29. package/dist/index.js +216 -84
  30. package/dist/listen-options-7TaXjyrk.js +1 -2
  31. package/dist/{load-entry-CCPWbsrj.js → load-entry-Bgq1_HDV.js} +11 -12
  32. package/dist/{log-DQAS5gGT.js → log-DfC9D5_T.js} +70 -49
  33. package/dist/{node-D6m6e6EI.js → node-DQPrMFyc.js} +20 -8
  34. package/dist/node-DyKDFII0.js +263 -0
  35. package/dist/node-vite.d.ts +2 -3
  36. package/dist/node-vite.js +1 -1
  37. package/dist/node.d.ts +41 -64
  38. package/dist/node.js +3 -3
  39. package/dist/react-router-vite.d.ts +2 -3
  40. package/dist/react-router-vite.js +1 -1
  41. package/dist/react-router.d.ts +6 -17
  42. package/dist/react-router.js +9 -14
  43. package/dist/request-context-Cslbrscf.js +163 -0
  44. package/dist/{response-edge-CU8ZvL_F.js → response-edge-Ow5Pi5qF.js} +13 -10
  45. package/dist/{response-writer-D7KHfr8n.js → response-writer-Dd4Ey99f.js} +57 -21
  46. package/dist/{script-hashes-CU7P9oZU.js → script-hashes-BdvJ0QI_.js} +2 -3
  47. package/dist/serve-AatMo9k6.js +26 -0
  48. package/dist/{stale-build-navigation-rg5xxmTr.js → stale-build-navigation-Qf_Lem39.js} +4 -5
  49. package/dist/{stale-build-navigation-ypV7Ow4o.d.ts → stale-build-navigation-WjhD8zHi.d.ts} +4 -4
  50. package/dist/start-DYFyGKsM.js +470 -0
  51. package/dist/static-files-BdTPam5b.js +438 -0
  52. package/dist/static-pages-6IBHdYQc.d.ts +30 -0
  53. package/dist/tanstack-start-vite.d.ts +2 -3
  54. package/dist/tanstack-start-vite.js +1 -1
  55. package/dist/tanstack-start.d.ts +3 -4
  56. package/dist/tanstack-start.js +2 -3
  57. package/dist/tcp-3v4pmnYU.js +58 -0
  58. package/dist/testing.d.ts +8 -6
  59. package/dist/testing.js +19 -17
  60. package/dist/{trailing-slash-D2QWKWEu.d.ts → trailing-slash-C-yBKCib.d.ts} +2 -3
  61. package/dist/{types-MgFtkNQW.d.ts → types-KsKRDwAv.d.ts} +97 -46
  62. package/dist/vercel-pages.d.ts +3 -16
  63. package/dist/vercel-pages.js +1 -2
  64. package/dist/vercel-vite.d.ts +4 -5
  65. package/dist/vercel-vite.js +48 -44
  66. package/dist/vercel.d.ts +13 -10
  67. package/dist/vercel.js +48 -35
  68. package/dist/{vite-D4hfj3ph.js → vite-Brb8YR9I.js} +2 -7
  69. package/dist/{vite-B-GfswoH.js → vite-CHppJWp_.js} +5 -7
  70. package/dist/{vite-DyrhyKEr.js → vite-DjlHdyTM.js} +2 -7
  71. package/dist/vite.d.ts +2 -2
  72. package/dist/vite.js +885 -2
  73. package/package.json +13 -12
  74. package/dist/brotli-only-DrA29Ecw.js +0 -97
  75. package/dist/brotli-only-DrA29Ecw.js.map +0 -1
  76. package/dist/build-id-B0448vZH.js +0 -151
  77. package/dist/build-id-B0448vZH.js.map +0 -1
  78. package/dist/build-manifest-DBMWe3Lx.js.map +0 -1
  79. package/dist/bun-BCz6K_Xv.js.map +0 -1
  80. package/dist/cli.js.map +0 -1
  81. package/dist/client.js.map +0 -1
  82. package/dist/compress-Cp5NfXCC.js.map +0 -1
  83. package/dist/compression-CT2mWlKM.js.map +0 -1
  84. package/dist/create-server-Bp1yILQk.js.map +0 -1
  85. package/dist/deno-aqhikNMG.js.map +0 -1
  86. package/dist/entry-BoxCqc6w.js.map +0 -1
  87. package/dist/header-hook-Vzw9J9BY.js.map +0 -1
  88. package/dist/index.js.map +0 -1
  89. package/dist/listen-options-7TaXjyrk.js.map +0 -1
  90. package/dist/load-entry-CCPWbsrj.js.map +0 -1
  91. package/dist/log-DQAS5gGT.js.map +0 -1
  92. package/dist/node-CVVdk2N6.js +0 -334
  93. package/dist/node-CVVdk2N6.js.map +0 -1
  94. package/dist/node-D6m6e6EI.js.map +0 -1
  95. package/dist/react-router.js.map +0 -1
  96. package/dist/request-context-Bxdbk5P1.js +0 -80
  97. package/dist/request-context-Bxdbk5P1.js.map +0 -1
  98. package/dist/response-edge-CU8ZvL_F.js.map +0 -1
  99. package/dist/response-writer-D7KHfr8n.js.map +0 -1
  100. package/dist/script-hashes-CU7P9oZU.js.map +0 -1
  101. package/dist/serve-W4WacdOw.js +0 -29
  102. package/dist/serve-W4WacdOw.js.map +0 -1
  103. package/dist/stale-build-navigation-rg5xxmTr.js.map +0 -1
  104. package/dist/start-j0VlxeiI.js +0 -324
  105. package/dist/start-j0VlxeiI.js.map +0 -1
  106. package/dist/static-files-C2ea8KQ6.js +0 -310
  107. package/dist/static-files-C2ea8KQ6.js.map +0 -1
  108. package/dist/tanstack-start.js.map +0 -1
  109. package/dist/tcp-BgDXbjOG.js +0 -42
  110. package/dist/tcp-BgDXbjOG.js.map +0 -1
  111. package/dist/testing.js.map +0 -1
  112. package/dist/vercel-pages.js.map +0 -1
  113. package/dist/vercel-vite.js.map +0 -1
  114. package/dist/vercel.js.map +0 -1
  115. package/dist/vite-B-GfswoH.js.map +0 -1
  116. package/dist/vite-D4hfj3ph.js.map +0 -1
  117. package/dist/vite-DPiSKHDn.js +0 -870
  118. package/dist/vite-DPiSKHDn.js.map +0 -1
  119. package/dist/vite-DyrhyKEr.js.map +0 -1
package/dist/vite.js CHANGED
@@ -1,3 +1,886 @@
1
- import { n as appServer, r as serverEntrySource, t as SERVER_ENTRY_ID } from "./vite-DPiSKHDn.js";
1
+ import { a as manifestKey, i as SERVER_ENTRY_FILE, n as DEFAULT_ASSETS_PATH, t as BUILD_MANIFEST_FILE } from "./build-manifest-CoBztw_6.js";
2
+ import { n as MIN_COMPRESS_BYTES, o as isCompressible, r as copyName, t as COPY_ENCODINGS } from "./compression-uJxu0JVb.js";
3
+ import { t as contentType } from "./static-files-BdTPam5b.js";
4
+ import { n as scriptHashesOf } from "./script-hashes-BdvJ0QI_.js";
5
+ import { t as node } from "./vite-Brb8YR9I.js";
6
+ import { t as reactRouterAdapter } from "./vite-CHppJWp_.js";
7
+ import { t as tanstackStartAdapter } from "./vite-DjlHdyTM.js";
8
+ import { i as serverEntrySource, n as SERVER_ENTRY_ID, t as RESOLVED_SERVER_ENTRY_ID } from "./entry-source-DSE5NAJu.js";
9
+ import { isBuiltin } from "node:module";
10
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
11
+ import { getPath } from "hono/utils/url";
12
+ import { basename, dirname, extname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
13
+ import { brotliCompressSync, constants as constants$1, gzipSync } from "node:zlib";
14
+ import { createHash } from "node:crypto";
2
15
 
3
- export { SERVER_ENTRY_ID, appServer, serverEntrySource };
16
+ // src/vite/standalone.ts
17
+ /**
18
+ * A package name: an optional scope and a name, each with no `/` or `\` and
19
+ * no `.` at the start. Why: a name such as `..` or `../x` in a manifest must
20
+ * not move a copy out of `node_modules`.
21
+ */
22
+ const PACKAGE_NAME = /^(?:@[^./\\][^/\\]*\/)?[^./\\][^/\\]*$/u;
23
+ /**
24
+ * The package names in the dependency `fields` of the `package.json` in
25
+ * `directory`. It skips a key that is not a package name.
26
+ *
27
+ * @example
28
+ * dependencyNames("/app/node_modules/react-dom", ["peerDependencies"]); // => ["react"]
29
+ */
30
+ function dependencyNames(directory, fields) {
31
+ const manifest = JSON.parse(readFileSync(join(directory, "package.json"), "utf8"));
32
+ const names = fields.flatMap((field) => {
33
+ const value = typeof manifest === "object" && manifest != null ? Reflect.get(manifest, field) : void 0;
34
+ return typeof value === "object" && value != null ? Object.keys(value).filter((name) => PACKAGE_NAME.test(name)) : [];
35
+ });
36
+ return [...new Set(names)];
37
+ }
38
+ /**
39
+ * The package name of a bare import.
40
+ *
41
+ * @example
42
+ * packageName("@scope/name/sub/path"); // => "@scope/name"
43
+ */
44
+ function packageName(specifier) {
45
+ return specifier.split("/").slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
46
+ }
47
+ /**
48
+ * Code that finds a file next to its own module: a relative `new URL()` on
49
+ * `import.meta.url`, `fileURLToPath(import.meta.url)`, `import.meta.dirname`,
50
+ * or `import.meta.filename`.
51
+ */
52
+ const OWN_FILE = /new\s+URL\(\s*(?<quote>["'`])\.{1,2}\/[^"'`]*\k<quote>\s*,\s*import\.meta\.url\s*\)|fileURLToPath\(\s*import\.meta\.url\s*\)|import\.meta\.(?:dirname|filename)\b/u;
53
+ /**
54
+ * Whether the module `file` finds a file next to itself, such as
55
+ * `@vercel/og`, which reads `resvg.wasm` through
56
+ * `new URL("./resvg.wasm", import.meta.url)`. Why: in the bundle,
57
+ * `import.meta.url` is the URL of the bundle, so the file is not there.
58
+ *
59
+ * @example
60
+ * readsOwnFiles("/app/node_modules/@vercel/og/dist/index.node.js"); // => true
61
+ */
62
+ function readsOwnFiles(file) {
63
+ return OWN_FILE.test(readFileSync(file, "utf8"));
64
+ }
65
+ /**
66
+ * The real path of the directory of package `name`, as Node finds it from the
67
+ * directory `from`: in each `node_modules` directory above `from`. Else
68
+ * `undefined`. The real path follows the symbolic links of pnpm's layout.
69
+ *
70
+ * @example
71
+ * findPackage("react", "/app/build/server"); // => "/app/node_modules/.pnpm/react@19.3.1/node_modules/react"
72
+ */
73
+ function findPackage(name, from) {
74
+ for (let directory = from;; directory = dirname(directory)) {
75
+ const candidate = join(directory, "node_modules", name);
76
+ if (basename(directory) !== "node_modules" && existsSync(join(candidate, "package.json"))) return realpathSync(candidate);
77
+ if (dirname(directory) === directory) return;
78
+ }
79
+ }
80
+ /**
81
+ * The directory of package `name` that holds `file`: the nearest directory
82
+ * above `file` at `node_modules/<name>`. Else `undefined`, such as for a file
83
+ * of a linked workspace package.
84
+ *
85
+ * @example
86
+ * packageDirectoryOf("/app/node_modules/react/cjs/react.js", "react"); // => "/app/node_modules/react"
87
+ */
88
+ function packageDirectoryOf(file, name) {
89
+ for (let directory = dirname(file); directory !== dirname(directory); directory = dirname(directory)) if (directory.endsWith(`${sep}${join("node_modules", name)}`)) return realpathSync(directory);
90
+ }
91
+ /** Whether a `.node` file is in `directory`, outside its `node_modules`. */
92
+ function hasNodeFile(directory) {
93
+ return readdirSync(directory, { withFileTypes: true }).some((entry) => entry.isDirectory() ? entry.name !== "node_modules" && hasNodeFile(join(entry.parentPath, entry.name)) : entry.name.endsWith(".node"));
94
+ }
95
+ /**
96
+ * Whether the package in `directory` loads a native addon: a `.node` file is
97
+ * in the package, or in a package of its `dependencies` or
98
+ * `optionalDependencies`. The second case finds a package that gets its addon
99
+ * from a package for each platform, such as `oxc-parser` from
100
+ * `@oxc-parser/binding-darwin-arm64`. Only the installed platform package is
101
+ * there. `scans` keeps the result for each directory that the function
102
+ * searched, so a call with the same map does not search a directory again.
103
+ *
104
+ * @example
105
+ * isNativePackage("/app/node_modules/better-sqlite3"); // => true
106
+ */
107
+ function isNativePackage(directory, scans = /* @__PURE__ */ new Map()) {
108
+ const scan = (path) => {
109
+ const found = scans.get(path) ?? hasNodeFile(path);
110
+ scans.set(path, found);
111
+ return found;
112
+ };
113
+ return scan(directory) || dependencyNames(directory, ["dependencies", "optionalDependencies"]).some((name) => {
114
+ const dependency = findPackage(name, directory);
115
+ return dependency != null && scan(dependency);
116
+ });
117
+ }
118
+ /**
119
+ * The `node_modules` directories where Node looks for a package that the
120
+ * package at `destination` imports, nearest first, down to `target`.
121
+ */
122
+ function lookupDirectories(destination, target) {
123
+ const directories = [];
124
+ for (let directory = destination;; directory = dirname(directory)) {
125
+ if (basename(directory) !== "node_modules") directories.push(join(directory, "node_modules"));
126
+ if (directory === dirname(target)) return directories;
127
+ }
128
+ }
129
+ /**
130
+ * Copies each package, whole, with the installed packages of its
131
+ * `dependencies`, `optionalDependencies`, and `peerDependencies`, into the
132
+ * `node_modules` directory `target`, except the packages in `omit`. Node then
133
+ * finds each package from a file next to `target`, with no install. The copy
134
+ * follows symbolic links. A dependency goes to the top of `target`. If another
135
+ * copy of that package is nearer in the lookup path of the package that needs
136
+ * it, the dependency goes into that package's own `node_modules`.
137
+ *
138
+ * @example
139
+ * copyPackages(new Map([["oxc-parser", "/app/node_modules/oxc-parser"]]), "/app/build/server/node_modules");
140
+ */
141
+ function copyPackages(packages, target, { omit = /* @__PURE__ */ new Set() } = {}) {
142
+ const copied = /* @__PURE__ */ new Map();
143
+ const queue = [];
144
+ const add = (destination, name, source) => {
145
+ const copy = {
146
+ name,
147
+ source,
148
+ dependencies: []
149
+ };
150
+ copied.set(destination, copy);
151
+ queue.push([destination, copy]);
152
+ };
153
+ for (const [name, source] of packages) if (!omit.has(name)) add(join(target, name), name, source);
154
+ for (const [destination, copy] of queue) {
155
+ const { source } = copy;
156
+ cpSync(source, destination, {
157
+ recursive: true,
158
+ dereference: true,
159
+ filter: (path) => path !== join(source, "node_modules")
160
+ });
161
+ for (const name of dependencyNames(source, [
162
+ "dependencies",
163
+ "optionalDependencies",
164
+ "peerDependencies"
165
+ ])) {
166
+ const dependency = findPackage(name, source);
167
+ const found = lookupDirectories(destination, target).map((directory) => join(directory, name)).find((path) => copied.has(path));
168
+ if (dependency != null && !omit.has(name)) {
169
+ if (found == null || copied.get(found)?.source !== dependency) {
170
+ const placed = join(found == null ? target : join(destination, "node_modules"), name);
171
+ add(placed, name, dependency);
172
+ copy.dependencies.push(placed);
173
+ } else copy.dependencies.push(found);
174
+ }
175
+ }
176
+ }
177
+ return copied;
178
+ }
179
+ /** Each file under `directory`, except in a `node_modules` directory. */
180
+ function ownFiles(directory) {
181
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
182
+ const path = join(entry.parentPath, entry.name);
183
+ if (entry.isDirectory()) return entry.name === "node_modules" ? [] : ownFiles(path);
184
+ return [path];
185
+ });
186
+ }
187
+ /** Removes each empty directory in `directory`, and `directory` when it is then empty. */
188
+ function removeEmptyDirectories(directory) {
189
+ for (const entry of readdirSync(directory, { withFileTypes: true })) if (entry.isDirectory()) removeEmptyDirectories(join(directory, entry.name));
190
+ if (readdirSync(directory).length === 0) rmSync(directory, { recursive: true });
191
+ }
192
+ /**
193
+ * The export conditions of each runtime that the server runs on, besides
194
+ * `import`, `require`, and `default`. Why each: Bun and Deno take their own
195
+ * entry of a package before its `node` entry.
196
+ */
197
+ const RUNTIME_CONDITIONS = [
198
+ ["node"],
199
+ ["bun", "node"],
200
+ ["deno", "node"]
201
+ ];
202
+ /**
203
+ * A `require.resolve()` or an `import.meta.resolve()` of a string literal.
204
+ * The `source` group is the string.
205
+ */
206
+ const RESOLVE_CALL = /\b(?:require|import\.meta)\.resolve\(\s*(?<quote>["'`])(?<source>[^"'`$]+)\k<quote>/gu;
207
+ /** Code that finds a file next to its own module in a way that `@vercel/nft` does not follow. */
208
+ const UNTRACED_OWN_FILE = /import\.meta\.(?:dirname|filename)\b/u;
209
+ /** The warning of `@vercel/nft` for a module that it cannot parse, such as a TypeScript file, so it finds no import of it. */
210
+ const UNPARSED = /^Failed to parse (?<file>.+) as module:/u;
211
+ /**
212
+ * Removes each file of a package in `copied` that the server build in
213
+ * `serverDirectory` cannot load, as `@vercel/nft` traces it from each module
214
+ * of the build. A package that no traced file is in goes away whole. Each
215
+ * package for which `whole` is true, and each package that it depends on,
216
+ * keeps each file. Why: a native package can load a library through the
217
+ * system's loader, such as `sharp` loads libvips, and a trace cannot see it.
218
+ * The trace misses the files that a module loads through
219
+ * {@link UNTRACED_OWN_FILE}, the imports of a module that it cannot parse,
220
+ * and a file that {@link RESOLVE_CALL} finds through the `exports` of a
221
+ * package. So the package of such a module, or the package that it
222
+ * resolves, keeps each file, with each package that it depends on.
223
+ *
224
+ * @example
225
+ * await removeUntraced("/app/build/server", copied, (copy) => isNativePackage(copy.source));
226
+ */
227
+ async function removeUntraced(serverDirectory, copied, whole) {
228
+ const kept = /* @__PURE__ */ new Set();
229
+ const keep = (destination) => {
230
+ if (!kept.has(destination)) {
231
+ kept.add(destination);
232
+ for (const dependency of copied.get(destination)?.dependencies ?? []) keep(dependency);
233
+ }
234
+ };
235
+ for (const [destination, copy] of copied) if (whole(copy)) keep(destination);
236
+ if (kept.size === copied.size) return;
237
+ const { nodeFileTrace } = await import("@vercel/nft");
238
+ const modules = ownFiles(serverDirectory).filter((file) => /\.[cm]?js$/u.test(file));
239
+ const cache = {};
240
+ const traces = await Promise.all(RUNTIME_CONDITIONS.map(async (conditions) => nodeFileTrace(modules, {
241
+ base: serverDirectory,
242
+ mixedModules: true,
243
+ conditions,
244
+ cache
245
+ })));
246
+ const traced = new Set(traces.flatMap(({ fileList }) => [...fileList].map((file) => join(serverDirectory, file))));
247
+ const real = realpathSync(serverDirectory);
248
+ const unparsed = new Set(traces.flatMap(({ warnings }) => [...warnings].flatMap(({ message }) => {
249
+ const file = UNPARSED.exec(message)?.groups?.file;
250
+ return file == null ? [] : [join(serverDirectory, relative(real, file))];
251
+ })));
252
+ const present = [...copied.keys()].filter((destination) => existsSync(destination));
253
+ for (const destination of present.filter((each) => !kept.has(each))) {
254
+ const loaded = ownFiles(destination).filter((file) => traced.has(file));
255
+ const code = loaded.filter((file) => /\.[cm]?js$/u.test(file)).map((file) => readFileSync(file, "utf8"));
256
+ if (loaded.some((file) => unparsed.has(file)) || code.some((each) => UNTRACED_OWN_FILE.test(each))) keep(destination);
257
+ const resolved = new Set(code.flatMap((each) => [...each.matchAll(RESOLVE_CALL)].map(({ groups }) => packageName(groups?.source ?? ""))));
258
+ for (const each of [destination, ...copied.get(destination)?.dependencies ?? []]) if (resolved.has(copied.get(each)?.name ?? "")) keep(each);
259
+ }
260
+ for (const destination of present.filter((each) => !kept.has(each))) {
261
+ const files = ownFiles(destination);
262
+ const used = files.some((file) => traced.has(file));
263
+ for (const file of files) if (!traced.has(file) && !(used && basename(file) === "package.json")) rmSync(file);
264
+ }
265
+ removeEmptyDirectories(join(serverDirectory, "node_modules"));
266
+ }
267
+
268
+ // src/vite/index.ts
269
+ /** The Vite environment that builds the server. */
270
+ const SERVER_ENVIRONMENT = "ssr";
271
+ /** A bare import, such as `react` or `@scope/name/path`: not a path, a `\0` ID, or a `node:` or `virtual:` ID. */
272
+ const BARE_IMPORT = /^[\w@][^:]*$/u;
273
+ /** The file extensions of a module that Node imports as it is, with no transform by Vite. */
274
+ const JAVASCRIPT_EXTENSIONS = /* @__PURE__ */ new Set([
275
+ "",
276
+ ".js",
277
+ ".mjs",
278
+ ".cjs"
279
+ ]);
280
+ /** The header that turns on Node's header store for a response, so `finish` can read every header. */
281
+ const CAPTURE_MARKER = "x-app-server-capture";
282
+ /**
283
+ * Headers that describe one transfer, not the resource. The server sets its
284
+ * own, and a cookie must never replay to every visitor. `Vary` is left out
285
+ * because the preview server adds `Vary: Origin` to every response.
286
+ */
287
+ const UNCAPTURED_HEADERS = /* @__PURE__ */ new Set([
288
+ CAPTURE_MARKER,
289
+ "connection",
290
+ "content-encoding",
291
+ "content-length",
292
+ "date",
293
+ "etag",
294
+ "keep-alive",
295
+ "last-modified",
296
+ "set-cookie",
297
+ "transfer-encoding",
298
+ "vary"
299
+ ]);
300
+ /** The built-in framework adapters, each with the name of the Vite plugin that marks its framework. */
301
+ const FRAMEWORKS = [{
302
+ plugin: "react-router:virtual-modules",
303
+ adapter: reactRouterAdapter
304
+ }, {
305
+ plugin: "tanstack-react-start:config",
306
+ adapter: tanstackStartAdapter
307
+ }];
308
+ /** The adapter of the one built-in framework whose plugin is in the Vite config. */
309
+ function detectFramework(plugins) {
310
+ const names = new Set(plugins.map((plugin) => plugin.name));
311
+ const [found, ...others] = FRAMEWORKS.filter(({ plugin }) => names.has(plugin));
312
+ if (found == null) throw new Error("@ngrok/app-server found no React Router or TanStack Start plugin in the Vite config. Add the framework's plugin, or pass `framework` to `appServer`.");
313
+ if (others.length > 0) throw new Error("@ngrok/app-server found the React Router and the TanStack Start plugins in the Vite config. Pass `framework` to `appServer`.");
314
+ return found.adapter();
315
+ }
316
+ /** The absolute path of `server.ts` or `server.js` in `root`, else `undefined` for the default app. */
317
+ function defaultApp(root) {
318
+ return ["server.ts", "server.js"].map((name) => join(root, name)).find((path) => existsSync(path));
319
+ }
320
+ /**
321
+ * The logger of the build whose post step ran, by Vite root. Why in the
322
+ * module: the framework starts its prerender preview with a new instance of
323
+ * this plugin and its own log level, which is `silent` for React Router. So
324
+ * what the host's `output` prints after that pass needs the logger of the build.
325
+ */
326
+ const buildLoggers = /* @__PURE__ */ new Map();
327
+ /** What a host's `output` gets for the build of `config`. */
328
+ function hostOutput(config) {
329
+ return {
330
+ root: config.root,
331
+ clientDirectory: outDir(config, "client"),
332
+ entryFile: join(outDir(config, SERVER_ENVIRONMENT), SERVER_ENTRY_FILE),
333
+ assetsPath: assetsPathOf(config),
334
+ logger: buildLoggers.get(config.root) ?? config.logger
335
+ };
336
+ }
337
+ /** The URL path of Vite's `build.assetsDir` in the client build of `config`. */
338
+ function assetsPathOf(config) {
339
+ return urlPathOfAssetsDir(config.environments.client?.build.assetsDir ?? config.build.assetsDir);
340
+ }
341
+ /**
342
+ * The URL path of Vite's `build.assetsDir`. Why the default for the root: an
343
+ * immutable cache on each file of the client build would keep an old page.
344
+ *
345
+ * @example
346
+ * urlPathOfAssetsDir("blog-assets/build"); // => "/blog-assets/build/"
347
+ */
348
+ function urlPathOfAssetsDir(assetsDir) {
349
+ const path = posix.normalize(`/${assetsDir.replaceAll("\\", "/")}/`);
350
+ return path === "/" ? DEFAULT_ASSETS_PATH : path;
351
+ }
352
+ /** The absolute path of an environment's build output. */
353
+ function outDir(config, environment) {
354
+ return resolve(config.root, config.environments[environment]?.build.outDir ?? config.build.outDir);
355
+ }
356
+ /**
357
+ * Whether `id` is a JavaScript file, which Node imports from `node_modules`
358
+ * as it is. Why: a plugin can resolve a bare import to a virtual module, and
359
+ * Vite transforms a JSON file or an asset, such as `?raw` on a file with no
360
+ * extension.
361
+ */
362
+ function isJavaScriptFile(id) {
363
+ return isAbsolute(id) && !id.includes("?") && JAVASCRIPT_EXTENSIONS.has(extname(id));
364
+ }
365
+ /** The dependency fields of the app's `package.json` that can name a package the server imports. */
366
+ const APP_DEPENDENCY_FIELDS = [
367
+ "dependencies",
368
+ "optionalDependencies",
369
+ "devDependencies"
370
+ ];
371
+ /** Whether `environment` builds the server. */
372
+ function isServerBuild(environment) {
373
+ return environment.name === SERVER_ENVIRONMENT && environment.mode === "build";
374
+ }
375
+ /**
376
+ * Makes the server build run with no install. The build bundles each
377
+ * dependency, except the packages that the app keeps external (`ssr.external`
378
+ * or the bundler's `external`), each native package (see `isNativePackage`),
379
+ * each package that reads a file next to its own module (see `readsOwnFiles`),
380
+ * and each package that the bundle shares with a package that the app keeps
381
+ * external: the whole package of an external subpath, and each peer, at each
382
+ * level. Those stay external, so the plugin copies each one, with its
383
+ * dependencies, into `node_modules` in the server build, and then removes each
384
+ * file that the build cannot load (see `removeUntraced`). A package in
385
+ * `ssr.external`, and a package that the app reads at run time, such as
386
+ * through `require.resolve`, keep each file. It also writes a `package.json` there, so Node, Bun, and
387
+ * Deno load the build as ES modules and find that `node_modules`.
388
+ */
389
+ function standalone({ whole = [], omit = [] } = {}) {
390
+ const readByApp = /* @__PURE__ */ new Set();
391
+ const externals = /* @__PURE__ */ new Map();
392
+ const shared = /* @__PURE__ */ new Set();
393
+ const natives = /* @__PURE__ */ new Map();
394
+ const scans = /* @__PURE__ */ new Map();
395
+ const isNative = (directory) => {
396
+ const native = natives.get(directory) ?? isNativePackage(directory, scans);
397
+ natives.set(directory, native);
398
+ return native;
399
+ };
400
+ const ownFiles = /* @__PURE__ */ new Map();
401
+ const readsOwnFile = (file) => {
402
+ const reads = ownFiles.get(file) ?? (existsSync(file) && readsOwnFiles(file));
403
+ ownFiles.set(file, reads);
404
+ return reads;
405
+ };
406
+ const inBundle = /* @__PURE__ */ new Set();
407
+ /**
408
+ * Whether the bundled module `file` of package `name` must stay external:
409
+ * the package is native, or `file` reads a file next to it. Then the
410
+ * package and each of its peers stay external, so the bundle shares them.
411
+ */
412
+ const staysExternal = ({ name, file, directory }, logger) => {
413
+ const native = directory != null && isNative(directory);
414
+ if (directory == null || !native && !readsOwnFile(file)) {
415
+ inBundle.add(name);
416
+ return false;
417
+ }
418
+ const group = withPeers([{
419
+ name,
420
+ from: directory
421
+ }]);
422
+ const held = [...group].find((peer) => inBundle.has(peer));
423
+ if (held != null && !native) {
424
+ logger.warn(`@ngrok/app-server bundles "${name}", but it reads a file next to its own module, so the server can fail when it reads that file. The bundle already holds "${held}", so "${name}" cannot stay external alone. Add "${name}" to \`ssr.external\`.`);
425
+ inBundle.add(name);
426
+ return false;
427
+ }
428
+ for (const peer of group) shared.add(peer);
429
+ return true;
430
+ };
431
+ return {
432
+ name: "@ngrok/app-server:standalone",
433
+ enforce: "pre",
434
+ config: (config, { command }) => {
435
+ const ssr = config.environments?.[SERVER_ENVIRONMENT]?.resolve;
436
+ return command === "build" && config.ssr?.noExternal == null && ssr?.noExternal == null && config.ssr?.external !== true && ssr?.external !== true ? { ssr: { noExternal: true } } : void 0;
437
+ },
438
+ buildStart() {
439
+ if (!isServerBuild(this.environment)) return;
440
+ externals.clear();
441
+ readByApp.clear();
442
+ shared.clear();
443
+ natives.clear();
444
+ scans.clear();
445
+ ownFiles.clear();
446
+ inBundle.clear();
447
+ const { resolve: resolveOptions, build, root } = this.environment.config;
448
+ const kept = [...resolveOptions.external === true ? [] : resolveOptions.external, ...[build.rolldownOptions.external].flat()];
449
+ const names = kept.flatMap((id) => typeof id === "string" && BARE_IMPORT.test(id) ? [packageName(id)] : []);
450
+ const patterns = kept.filter((id) => id != null && typeof id !== "string");
451
+ const matched = patterns.length === 0 || !existsSync(join(root, "package.json")) ? [] : dependencyNames(root, APP_DEPENDENCY_FIELDS).filter((name) => patterns.some((pattern) => matchesExternal(pattern, name)));
452
+ for (const name of names) {
453
+ const directory = findPackage(name, root);
454
+ if (directory != null) {
455
+ externals.set(name, directory);
456
+ readByApp.add(name);
457
+ }
458
+ }
459
+ for (const name of withPeers([...names, ...matched].map((dependency) => ({
460
+ name: dependency,
461
+ from: root
462
+ })))) shared.add(name);
463
+ },
464
+ resolveId: {
465
+ filter: { id: BARE_IMPORT },
466
+ async handler(source, importer, options) {
467
+ if (!isServerBuild(this.environment) || isBuiltin(source)) return null;
468
+ const resolved = await this.resolve(source, importer, {
469
+ ...options,
470
+ skipSelf: true
471
+ });
472
+ const bundled = resolved?.external === false;
473
+ if (resolved == null || bundled && !isJavaScriptFile(resolved.id)) return resolved;
474
+ const name = packageName(source);
475
+ const directory = (bundled ? packageDirectoryOf(resolved.id, name) : void 0) ?? findPackage(name, importer != null && isAbsolute(importer) ? dirname(importer) : this.environment.config.root);
476
+ if (bundled && !shared.has(name) && !staysExternal({
477
+ name,
478
+ file: resolved.id,
479
+ directory
480
+ }, this.environment.logger)) return resolved;
481
+ const known = externals.get(name);
482
+ if (known != null && directory != null && known !== directory) throw new Error(`@ngrok/app-server found two copies of "${name}" that stay external, and the server build can hold one: ${known} and ${directory}. Install one version of "${name}".`);
483
+ externals.set(name, known ?? directory);
484
+ return bundled ? {
485
+ id: source,
486
+ external: true
487
+ } : resolved;
488
+ }
489
+ },
490
+ transform: {
491
+ filter: {
492
+ id: { exclude: /[\\/]node_modules[\\/]/u },
493
+ code: /\b(?:require|import\.meta)\.resolve\(/u
494
+ },
495
+ handler(code, id) {
496
+ if (!isServerBuild(this.environment)) return null;
497
+ for (const { groups } of code.matchAll(RESOLVE_CALL)) {
498
+ const source = groups?.source ?? "";
499
+ const name = packageName(source);
500
+ const directory = BARE_IMPORT.test(source) && !isBuiltin(source) && !externals.has(name) ? findPackage(name, isAbsolute(id) ? dirname(id) : this.environment.config.root) : void 0;
501
+ if (directory != null) externals.set(name, directory);
502
+ if (BARE_IMPORT.test(source) && !isBuiltin(source)) readByApp.add(name);
503
+ }
504
+ return null;
505
+ }
506
+ },
507
+ async writeBundle() {
508
+ if (!isServerBuild(this.environment)) return;
509
+ for (const importer of this.getModuleIds()) {
510
+ const info = this.getModuleInfo(importer);
511
+ for (const id of [...info?.importedIds ?? [], ...info?.dynamicallyImportedIds ?? []]) {
512
+ const name = packageName(id);
513
+ if (BARE_IMPORT.test(id) && !isBuiltin(id) && !externals.has(name)) externals.set(name, findPackage(name, isAbsolute(importer) ? dirname(importer) : this.environment.config.root));
514
+ }
515
+ }
516
+ const directory = outDir(this.environment.getTopLevelConfig(), SERVER_ENVIRONMENT);
517
+ const found = /* @__PURE__ */ new Map();
518
+ for (const [name, source] of externals) if (source == null) this.environment.logger.warn(`@ngrok/app-server cannot find "${name}", which stays external, so the server build does not hold it. The server fails if it imports "${name}".`);
519
+ else found.set(name, source);
520
+ const target = join(directory, "node_modules");
521
+ rmSync(target, {
522
+ recursive: true,
523
+ force: true
524
+ });
525
+ const copied = copyPackages(found, target, { omit: new Set(omit) });
526
+ const kept = /* @__PURE__ */ new Set([...whole, ...readByApp]);
527
+ await removeUntraced(directory, copied, ({ name, source }) => kept.has(name) || isNative(source));
528
+ writeFileSync(join(directory, "package.json"), `${JSON.stringify({ type: "module" })}\n`);
529
+ if (found.size > 0) this.environment.logger.info(`@ngrok/app-server copied the external packages ${[...found.keys()].join(", ")}, with the files of their dependencies that the server build loads, into ${target}.`);
530
+ }
531
+ };
532
+ }
533
+ /**
534
+ * Whether the app's `RegExp` or function external keeps the package `name`
535
+ * external. Why `false` when the function throws: the build calls it with no
536
+ * importer, and a function that reads the importer can throw.
537
+ */
538
+ function matchesExternal(pattern, name) {
539
+ if (typeof pattern !== "function") return name.search(pattern) !== -1;
540
+ try {
541
+ return pattern(name, void 0, false) === true;
542
+ } catch {
543
+ return false;
544
+ }
545
+ }
546
+ /**
547
+ * Each package of `start` and each of its peers, at each level. Why each
548
+ * level: a peer can have peers, such as `react` for `react-router`.
549
+ */
550
+ function withPeers(start) {
551
+ const names = /* @__PURE__ */ new Set();
552
+ const queue = [...start];
553
+ for (const { name, from } of queue) {
554
+ const directory = names.has(name) ? void 0 : findPackage(name, from);
555
+ names.add(name);
556
+ if (directory != null) for (const peer of dependencyNames(directory, ["peerDependencies"])) queue.push({
557
+ name: peer,
558
+ from: directory
559
+ });
560
+ }
561
+ return names;
562
+ }
563
+ /** Writes `.app-server.json` into the client build. */
564
+ function writeBuildManifest(clientDirectory, manifest) {
565
+ mkdirSync(clientDirectory, { recursive: true });
566
+ writeFileSync(join(clientDirectory, BUILD_MANIFEST_FILE), `${JSON.stringify(manifest, null, " ")}\n`);
567
+ }
568
+ /**
569
+ * Writes the build ID and the script hashes of the client build
570
+ * ({@link scriptHashesOf}) into `.app-server.json`, removes `incomplete`, and
571
+ * keeps the rest of the file. Why the script hashes of each build: a build
572
+ * with no prerender pass can have HTML files, such as `public/offline.html`.
573
+ */
574
+ function completeBuildManifest(clientDirectory, buildId) {
575
+ if (!existsSync(clientDirectory)) return;
576
+ const path = join(clientDirectory, BUILD_MANIFEST_FILE);
577
+ const recorded = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : void 0;
578
+ writeBuildManifest(clientDirectory, {
579
+ prerendered: [],
580
+ headers: {},
581
+ ...typeof recorded === "object" && recorded != null ? recorded : {},
582
+ ...buildId == null ? {} : { buildId },
583
+ scriptHashes: scriptHashesOf(clientDirectory),
584
+ incomplete: void 0
585
+ });
586
+ }
587
+ /**
588
+ * The ID of a client build: a hash of the name and the content of each file
589
+ * in its bundle. Why the bundle: it is the code that an open tab runs, so the
590
+ * ID changes when that code changes, and not for a change to the server, a
591
+ * `public/` file, or a prerendered page. Why the content, not the file
592
+ * names: a name has a content hash only when the output names ask for one.
593
+ */
594
+ function bundleBuildId(bundle) {
595
+ const hash = createHash("sha256");
596
+ for (const file of Object.values(bundle).toSorted((first, second) => first.fileName < second.fileName ? -1 : 1)) {
597
+ hash.update(`${file.fileName}\0`);
598
+ hash.update(file.type === "chunk" ? file.code : file.source);
599
+ hash.update("\0");
600
+ }
601
+ return hash.digest("hex").slice(0, 16);
602
+ }
603
+ /** The path of each file under `directory` that is not a dotfile, in code unit order. */
604
+ function filesIn(directory) {
605
+ if (!existsSync(directory)) return [];
606
+ return readdirSync(directory, {
607
+ recursive: true,
608
+ withFileTypes: true
609
+ }).filter((entry) => entry.isFile() && !entry.name.startsWith(".")).map((entry) => relative(directory, join(entry.parentPath, entry.name)).split(sep).join("/")).toSorted();
610
+ }
611
+ /**
612
+ * The ID of the whole build: the {@link bundleBuildId} of the client bundle,
613
+ * with the name and the content of each file that a later build step added to
614
+ * the assets directory. Why: React Router writes its route manifest
615
+ * (`assets/manifest-*.js`) during the server build, and a route change, such
616
+ * as a new path for one module, can keep the client bundle the same.
617
+ */
618
+ function appBuildId({ bundleId, assetsDirectory, assets }) {
619
+ const added = filesIn(assetsDirectory).filter((file) => !assets.has(file));
620
+ if (added.length === 0) return bundleId;
621
+ const hash = createHash("sha256").update(bundleId);
622
+ for (const file of added) {
623
+ hash.update(`\0${file}\0`);
624
+ hash.update(readFileSync(join(assetsDirectory, file)));
625
+ }
626
+ return hash.digest("hex").slice(0, 16);
627
+ }
628
+ /**
629
+ * The `buildId`, the `assetsPath`, and `incomplete` of the build manifest
630
+ * that the client build wrote. Why keep them: the prerender pass runs after
631
+ * the client build, which knows them.
632
+ */
633
+ function clientBuildFields(clientDirectory) {
634
+ const path = join(clientDirectory, BUILD_MANIFEST_FILE);
635
+ const manifest = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : void 0;
636
+ if (typeof manifest !== "object" || manifest == null) return {};
637
+ return {
638
+ ..."buildId" in manifest && typeof manifest.buildId === "string" ? { buildId: manifest.buildId } : {},
639
+ ..."assetsPath" in manifest && typeof manifest.assetsPath === "string" ? { assetsPath: manifest.assetsPath } : {},
640
+ ..."incomplete" in manifest && manifest.incomplete === true ? { incomplete: true } : {}
641
+ };
642
+ }
643
+ /**
644
+ * Records each 2xx path and the headers of each non-document response while
645
+ * the framework's prerender pass runs. It writes them to `.app-server.json` in
646
+ * the client build when the preview server closes. When the post step of the
647
+ * build ran before the pass, it also does the work of that step for the files
648
+ * of the pass: the script hashes, the copies (see {@link writeAllCopies}), and
649
+ * `afterPass`.
650
+ */
651
+ function capture(server, { afterPass, ...copies }) {
652
+ const clientDirectory = outDir(server.config, "client");
653
+ const started = Date.now();
654
+ const paths = /* @__PURE__ */ new Set();
655
+ const headers = {};
656
+ server.middlewares.use((request, response, next) => {
657
+ const pathname = getPath(new Request(new URL(request.url ?? "/", "http://localhost")));
658
+ response.setHeader(CAPTURE_MARKER, "1");
659
+ response.once("finish", () => {
660
+ if (response.statusCode < 200 || response.statusCode >= 300) return;
661
+ const key = manifestKey(pathname);
662
+ paths.add(key);
663
+ if (String(response.getHeader("content-type") ?? "").startsWith("text/html")) return;
664
+ const recorded = {};
665
+ 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);
666
+ headers[key] = recorded;
667
+ });
668
+ next();
669
+ });
670
+ server.httpServer.once("close", () => {
671
+ const recorded = clientBuildFields(clientDirectory);
672
+ const afterPostStep = recorded.incomplete !== true;
673
+ writeBuildManifest(clientDirectory, {
674
+ ...recorded,
675
+ prerendered: [...paths].toSorted(),
676
+ headers: Object.fromEntries(Object.entries(headers).toSorted(([first], [second]) => first.localeCompare(second))),
677
+ scriptHashes: afterPostStep ? scriptHashesOf(clientDirectory) : {}
678
+ });
679
+ if (afterPostStep) {
680
+ writeAllCopies(clientDirectory, {
681
+ ...copies,
682
+ changedSince: started - 2e3
683
+ });
684
+ afterPass();
685
+ }
686
+ });
687
+ }
688
+ /**
689
+ * The brotli quality of the copies. Why 9, not the highest (11): on a docs
690
+ * build with 70 MB of text, 11 adds 46 s to the build and 9 adds 0.6 s. The
691
+ * copies of 9 are 9% larger, and still 25% smaller than the gzip copies.
692
+ */
693
+ const BROTLI_QUALITY = 9;
694
+ /**
695
+ * The bytes of the file at `path` when the server compresses the file: a
696
+ * compressible type of 1 KiB or more. `contentTypes` are the framework's
697
+ * types, as the server reads them.
698
+ */
699
+ function compressibleBytes(path, contentTypes) {
700
+ if (!isCompressible(contentType(path, contentTypes)) || statSync(path, { throwIfNoEntry: false })?.isFile() !== true) return;
701
+ const bytes = readFileSync(path);
702
+ return bytes.byteLength < 1024 ? void 0 : bytes;
703
+ }
704
+ /** `copy` when it is smaller than `source`. */
705
+ function ifSmaller(copy, source) {
706
+ return copy.byteLength < source.byteLength ? copy : void 0;
707
+ }
708
+ /**
709
+ * Writes the compressed copies (`.<file>.gz` and `.<file>.br`) of the file at
710
+ * `path` when the server compresses the file ({@link compressibleBytes}). It
711
+ * writes only the `encodings`, and a copy only when it is smaller: the gzip
712
+ * copy than the file, and the brotli copy than the gzip copy. With no gzip in
713
+ * `encodings`, it writes the brotli copy when it is smaller than the file.
714
+ * Else it removes an old copy, so a copy from an earlier build never replaces
715
+ * a changed file.
716
+ */
717
+ function writeCopies(path, { contentTypes, encodings }) {
718
+ const bytes = encodings.length === 0 ? void 0 : compressibleBytes(path, contentTypes);
719
+ const gzip = bytes != null && encodings.includes("gzip") ? ifSmaller(gzipSync(bytes, { level: constants$1.Z_BEST_COMPRESSION }), bytes) : void 0;
720
+ const brotli = bytes != null && encodings.includes("br") && (gzip != null || !encodings.includes("gzip")) ? ifSmaller(brotliCompressSync(bytes, { params: {
721
+ [constants$1.BROTLI_PARAM_MODE]: constants$1.BROTLI_MODE_TEXT,
722
+ [constants$1.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY,
723
+ [constants$1.BROTLI_PARAM_SIZE_HINT]: bytes.byteLength
724
+ } }), gzip ?? bytes) : void 0;
725
+ const copies = [["gzip", gzip], ["br", brotli]];
726
+ for (const [encoding, copy] of copies) {
727
+ const copyPath = join(dirname(path), copyName(basename(path), encoding));
728
+ if (copy == null) rmSync(copyPath, { force: true });
729
+ else writeFileSync(copyPath, copy);
730
+ }
731
+ }
732
+ /**
733
+ * Runs {@link writeCopies} for each file in the client build, except dotfiles
734
+ * such as the copies, and except a link or a file in a linked directory.
735
+ */
736
+ function writeAllCopies(clientDirectory, { contentTypes = {}, encodingsOf, changedSince }) {
737
+ if (!existsSync(clientDirectory)) return;
738
+ for (const path of filesInside(clientDirectory)) if (!basename(path).startsWith(".") && (changedSince == null || (statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? 0) >= changedSince)) writeCopies(path, {
739
+ contentTypes,
740
+ encodings: encodingsOf(`/${relative(clientDirectory, path).split(sep).join("/")}`)
741
+ });
742
+ }
743
+ /**
744
+ * The path of each file under `directory`. Why not through a link: a copy goes
745
+ * next to its file, so a file in a linked directory would get its copies in
746
+ * the link's target, outside the client build.
747
+ */
748
+ function filesInside(directory) {
749
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
750
+ const path = join(directory, entry.name);
751
+ if (entry.isDirectory()) return filesInside(path);
752
+ return entry.isFile() ? [path] : [];
753
+ });
754
+ }
755
+ /**
756
+ * The Vite plugin for `@ngrok/app-server`. Put it next to the framework's
757
+ * plugin.
758
+ *
759
+ * - It adds the server entry to the server build, such as
760
+ * `build/server/app-server.js`. The entry bundles the app
761
+ * (the default export of `app`) with the framework's server module, so the
762
+ * server gets the app's path aliases and its one copy of the framework.
763
+ * The framework's own entry does not change. When a runtime runs the entry
764
+ * as its main module, the entry starts the server.
765
+ * - In a build, it bundles each dependency into the server build. It copies
766
+ * each package that stays external into `node_modules` in the server build.
767
+ * So the build directory runs with no install.
768
+ * - After the client build, it writes `.app-server.json` in the client
769
+ * build with the build ID: a hash of the client bundle. After the build,
770
+ * it adds the files that the server build wrote to the client's assets
771
+ * directory, such as React Router's route manifest. The `buildId` plugin
772
+ * sends the ID.
773
+ * - During the framework's prerender pass, it records each prerendered path
774
+ * and the headers of each prerendered file that is not an HTML document into
775
+ * `.app-server.json` in the client build. The `prerendered` plugin replays
776
+ * the headers. A document's headers depend on its request, so they are not
777
+ * recorded.
778
+ * - After the build and after the prerender pass, it records the hash of each
779
+ * inline script of each HTML file in `.app-server.json`, for the
780
+ * `contentSecurityPolicy` plugin. It also writes a gzip copy (`.<file>.gz`)
781
+ * and a brotli copy (`.<file>.br`) next to each text file of 1 KiB or more
782
+ * in the client build, HTML included. The static stages send a copy, so the
783
+ * server does not compress these files for each request. A host can ask
784
+ * for fewer copies with `copies` of `HostBuild`, as `vercel()` does.
785
+ *
786
+ * @example
787
+ * // vite.config.ts
788
+ * export default defineConfig({ plugins: [reactRouter(), appServer()] });
789
+ */
790
+ function appServer(options = {}) {
791
+ const host = options.host ?? node();
792
+ let resolved;
793
+ let clientBuild;
794
+ /** The `CopyOptions` of the build of `config`: the types of the framework and the encodings of the host. */
795
+ const copyOptions = (config) => ({
796
+ contentTypes: resolved?.framework.contentTypes,
797
+ encodingsOf: (path) => host.copies?.({
798
+ path,
799
+ assetsPath: assetsPathOf(config)
800
+ }) ?? COPY_ENCODINGS
801
+ });
802
+ return [
803
+ {
804
+ name: "@ngrok/app-server",
805
+ configResolved: (config) => {
806
+ const framework = options.framework ?? detectFramework(config.plugins);
807
+ if (config.base !== "/") throw new Error(`@ngrok/app-server serves a build at "/" only, and this config has the base "${config.base}".`);
808
+ resolved = {
809
+ config,
810
+ framework,
811
+ appModule: options.app == null ? defaultApp(config.root) : resolve(config.root, options.app)
812
+ };
813
+ },
814
+ async buildStart() {
815
+ if (isServerBuild(this.environment)) this.emitFile({
816
+ type: "chunk",
817
+ id: SERVER_ENTRY_ID,
818
+ fileName: SERVER_ENTRY_FILE
819
+ });
820
+ const appModule = options.app == null ? void 0 : resolved?.appModule;
821
+ if (appModule != null && (this.environment.mode === "dev" || isServerBuild(this.environment)) && await this.resolve(appModule) == null) throw new Error(`@ngrok/app-server found no module at ${appModule} for the \`app\` option. Give a path from the Vite root, ${resolved?.config.root}.`);
822
+ },
823
+ writeBundle(output, bundle) {
824
+ if (this.environment.name === "client") {
825
+ const directory = output.dir ?? outDir(this.environment.config, "client");
826
+ const assetsDirectory = join(directory, this.environment.config.build.assetsDir);
827
+ clientBuild = {
828
+ bundleId: bundleBuildId(bundle),
829
+ assetsDirectory,
830
+ assets: new Set(filesIn(assetsDirectory))
831
+ };
832
+ writeBuildManifest(directory, {
833
+ buildId: clientBuild.bundleId,
834
+ assetsPath: urlPathOfAssetsDir(this.environment.config.build.assetsDir),
835
+ prerendered: [],
836
+ headers: {},
837
+ scriptHashes: {},
838
+ incomplete: true
839
+ });
840
+ }
841
+ },
842
+ renderStart(output) {
843
+ if (this.environment.name === SERVER_ENVIRONMENT && output.format !== "es") throw new Error(`@ngrok/app-server needs an ES module server build, and this build has the format "${output.format}".`);
844
+ },
845
+ resolveId: (id) => id === "virtual:@ngrok/app-server/entry" ? RESOLVED_SERVER_ENTRY_ID : void 0,
846
+ load(id) {
847
+ if (id !== "\0virtual:@ngrok/app-server/entry" || resolved == null) return null;
848
+ const { config, framework, appModule } = resolved;
849
+ const clientDirectory = outDir(config, "client");
850
+ const serverDirectory = outDir(config, SERVER_ENVIRONMENT);
851
+ const fromClient = relative(clientDirectory, serverDirectory);
852
+ if (this.environment.mode === "build" && !fromClient.startsWith("..") && !isAbsolute(fromClient)) throw new Error(`@ngrok/app-server needs the server build outside the client build, and both are in ${clientDirectory}.`);
853
+ const fromEntry = relative(serverDirectory, clientDirectory).replaceAll("\\", "/");
854
+ return serverEntrySource({
855
+ framework,
856
+ host,
857
+ appModule,
858
+ clientDirectory: this.environment.mode === "build" ? `new URL(${JSON.stringify(`${fromEntry}/`)}, import.meta.url).href` : JSON.stringify(clientDirectory)
859
+ });
860
+ },
861
+ configurePreviewServer: (server) => {
862
+ if (resolved?.framework.isPrerenderPass(server) === true) capture(server, {
863
+ ...copyOptions(server.config),
864
+ afterPass: () => host.output?.(hostOutput(server.config))
865
+ });
866
+ }
867
+ },
868
+ {
869
+ name: "@ngrok/app-server:compressed-copies",
870
+ enforce: "post",
871
+ buildApp: {
872
+ order: "post",
873
+ handler: async (builder) => {
874
+ const clientDirectory = outDir(builder.config, "client");
875
+ completeBuildManifest(clientDirectory, clientBuild == null ? void 0 : appBuildId(clientBuild));
876
+ writeAllCopies(clientDirectory, copyOptions(builder.config));
877
+ buildLoggers.set(builder.config.root, builder.config.logger);
878
+ host.output?.(hostOutput(builder.config));
879
+ }
880
+ }
881
+ },
882
+ standalone(options.externals)
883
+ ];
884
+ }
885
+
886
+ export { appServer };