@vite-hub/kv 0.0.4 → 0.3.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 (63) hide show
  1. package/README.md +110 -14
  2. package/dist/batch--v0ri69O.js +40 -0
  3. package/dist/cli-DpPhz_Ek.d.ts +163 -0
  4. package/dist/cli.d.ts +17 -0
  5. package/dist/cli.js +469 -0
  6. package/dist/cloudflare-env-lOtHHsgP.js +46 -0
  7. package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
  8. package/dist/cloudflare-kv-BIEUFzRT.js +187 -0
  9. package/dist/cloudflare-kv-local-BBw3ZT1K.js +71 -0
  10. package/dist/config-BXEVoZE3.js +250 -0
  11. package/dist/{dist-DDW1iC5f.js → create-storage-BGsrQKw3.js} +266 -115
  12. package/dist/cursor-history-BqIQePNP.js +165 -0
  13. package/dist/database-72Jk3VVk.js +250 -0
  14. package/dist/deno-kv-BM9mYdUp.js +128 -0
  15. package/dist/dev-peer-CHafxbtj.js +238 -0
  16. package/dist/driver-BwxgaQ-f.d.ts +15 -0
  17. package/dist/durability.d.ts +17 -0
  18. package/dist/durability.js +53 -0
  19. package/dist/error-diagnostics-BxqvtEIb.js +147 -0
  20. package/dist/errors-DbwufFZp.js +60 -0
  21. package/dist/errors.d.ts +23 -7
  22. package/dist/errors.js +2 -20
  23. package/dist/fs-lite-BLZId9_P.js +386 -0
  24. package/dist/fs-lite-RAoxu8L0.js +2 -0
  25. package/dist/index.d.ts +10 -4
  26. package/dist/index.js +364 -109
  27. package/dist/inspect-BIKQsqX4.js +118 -0
  28. package/dist/invariant-DolT9EEx.js +22 -0
  29. package/dist/main-F3Y22_uV.js +2353 -0
  30. package/dist/object-Da1zyPCR.js +11 -0
  31. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  32. package/dist/operations-B-WZ7P1h.js +1351 -0
  33. package/dist/operations-Ch-gKaey.js +441 -0
  34. package/dist/operations.d.ts +75 -0
  35. package/dist/operations.js +318 -0
  36. package/dist/redis-shared-E5mahECF.js +94 -0
  37. package/dist/results-p7nPCnaJ.js +6 -0
  38. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  39. package/dist/runtime/cloudflare-kv.d.ts +3 -4
  40. package/dist/runtime/cloudflare-kv.js +1 -23
  41. package/dist/runtime/cloudflare-request-env.d.ts +7 -0
  42. package/dist/runtime/cloudflare-request-env.js +11 -0
  43. package/dist/runtime/nitro-plugin.d.ts +12 -0
  44. package/dist/runtime/nitro-plugin.js +22 -0
  45. package/dist/runtime/redis-driver.d.ts +11 -0
  46. package/dist/runtime/redis-driver.js +113 -0
  47. package/dist/runtime/unstorage-driver.d.ts +14 -0
  48. package/dist/runtime/unstorage-driver.js +33 -0
  49. package/dist/runtime/upstash-driver.d.ts +4 -6
  50. package/dist/runtime/upstash-driver.js +60 -110
  51. package/dist/{driver-BT9WefKi.d.ts → types-Bj3EQoRg.d.ts} +16 -11
  52. package/dist/types-DEiKew_3.d.ts +312 -0
  53. package/dist/upstash-DDlqTttY.js +40 -0
  54. package/dist/utils2-FozcTsmb.js +31 -0
  55. package/dist/virtual-module.d.ts +2 -0
  56. package/dist/virtual.d.ts +1 -1
  57. package/dist/vite.d.ts +159 -14
  58. package/dist/vite.js +1329 -2898
  59. package/package.json +68 -19
  60. package/dist/config-aM9Ae7tH.js +0 -110
  61. package/dist/deno-kv-cJx3jU10.js +0 -69
  62. package/dist/fs-lite-BxzdiJSi.js +0 -79
  63. package/dist/types-CO0DRjJa.d.ts +0 -78
package/dist/vite.js CHANGED
@@ -1,139 +1,223 @@
1
- import { i as trimmed, n as isPlainObject, r as readEnv, t as normalizeKVOptions } from "./config-aM9Ae7tH.js";
2
- import { createRequire } from "node:module";
3
- import { existsSync, renameSync, rmSync } from "node:fs";
4
- import { cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
1
+ import { r as __toESM } from "./rolldown-runtime-CMFfr-1z.js";
2
+ import { a as resolve$1, i as relative$1, n as relativeDefinitionFile, r as dirname$1 } from "./inspect-BIKQsqX4.js";
3
+ import { n as isRecordOrFunction, t as isRecord } from "./object-Da1zyPCR.js";
4
+ import { A as writeViteHubDevServerFile, E as readViteHubDevServerFile, O as removeViteHubDevServerFile, _ as createNoExternalAddition, b as resolveViteHubProjectRoot, g as internalErrorDiagnostics, p as operationRpcPath, r as collectOperationContributions, v as hasNitroConfigContext, x as shouldSkipViteProviderBuild, y as isServerEnvironment } from "./operations-B-WZ7P1h.js";
5
+ import { n as invariantError, t as invariant } from "./invariant-DolT9EEx.js";
6
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
7
+ import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, n as kvRedisEnvWarning, o as resolveHostPreset, r as normalizeKVOptions } from "./config-BXEVoZE3.js";
8
+ import { n as resolveUpstashRuntimeValues } from "./upstash-DDlqTttY.js";
9
+ import { t as addViteHubDevPeerDevHandler } from "./dev-peer-CHafxbtj.js";
10
+ import "node:module";
11
+ import { copyFile, cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
12
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
13
+ import { existsSync, readFileSync, renameSync, rmSync } from "node:fs";
5
14
  import { tmpdir } from "node:os";
6
- import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
7
15
  import { fileURLToPath } from "node:url";
8
- //#region \0rolldown/runtime.js
9
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
10
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
16
+ import { createHash } from "node:crypto";
17
+ //#region ../internal/src/build/paths.ts
18
+ function resolveRuntimeModule(packageDir, modulePath) {
19
+ const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
20
+ return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
21
+ }
22
+ const packageDirs = /* @__PURE__ */ new Map();
23
+ function findPackageDir(file) {
24
+ const start = dirname$1(file);
25
+ const cached = packageDirs.get(start);
26
+ if (cached) return cached;
27
+ let dir = start;
28
+ while (!existsSync(resolve$1(dir, "package.json"))) {
29
+ const parent = dirname$1(dir);
30
+ invariant(parent !== dir, `a file that a package resolver found has a package.json above it (${file})`);
31
+ dir = parent;
32
+ }
33
+ packageDirs.set(start, dir);
34
+ return dir;
35
+ }
36
+ /**
37
+ * The absolute path of a module that the calling package builds, such as `ownModule(import.meta.url, "runtime/state")`.
38
+ * Owner plugins write this path into generated code, so the module needs no package export, and an app resolves it
39
+ * only when the owner's feature is on. It is the `dist` file, or the `src` file before the package is built.
40
+ */
41
+ function ownModule(importMetaUrl, modulePath) {
42
+ return resolveRuntimeModule(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
43
+ }
44
+ //#endregion
45
+ //#region ../internal/src/definition-catalog.ts
46
+ /** `writeFileIfChangedSync` for async callers. */
47
+ async function writeFileIfChanged(file, contents) {
48
+ if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
49
+ await mkdir(resolve$1(file, ".."), { recursive: true });
50
+ await writeFile(file, contents, "utf8");
51
+ }
52
+ //#endregion
53
+ //#region ../internal/src/nitro-kit.ts
54
+ function cloneArray(value) {
55
+ return Array.isArray(value) ? [...value] : [];
56
+ }
57
+ function sameHandler(left, right) {
58
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
59
+ }
60
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
61
+ function createNitroServerKit(value = {}) {
62
+ const config = isRecordOrFunction(value) ? { ...value } : {};
63
+ const handlers = cloneArray(config.handlers);
64
+ const plugins = cloneArray(config.plugins);
65
+ config.handlers = handlers;
66
+ config.plugins = plugins;
67
+ return {
68
+ config,
69
+ addHandler(handler, position = "end") {
70
+ if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
71
+ if (position === "start") handlers.unshift({ ...handler });
72
+ else handlers.push({ ...handler });
73
+ },
74
+ addPlugin(plugin, position = "end") {
75
+ if (plugins.includes(plugin)) return;
76
+ if (position === "start") plugins.unshift(plugin);
77
+ else plugins.push(plugin);
78
+ }
79
+ };
80
+ }
81
+ //#endregion
82
+ //#region ../internal/src/contributions.ts
83
+ function isThenable(value) {
84
+ return typeof value.then === "function";
85
+ }
86
+ async function flattenPlugins(value, plugins, seen) {
87
+ if (Array.isArray(value)) {
88
+ for (const item of value) await flattenPlugins(item, plugins, seen);
89
+ return;
90
+ }
91
+ if (!isRecord(value) || seen.has(value)) return;
92
+ seen.add(value);
93
+ if (isThenable(value)) {
94
+ await flattenPlugins(await value, plugins, seen);
95
+ return;
96
+ }
97
+ plugins.push(value);
98
+ }
99
+ /**
100
+ * Flattens Vite plugin options as `collectContributions` reads them: nested arrays and promised options become one
101
+ * list of plugin objects, and falsy entries are dropped. A plugin that filters itself out of `context.plugins` must
102
+ * filter this list, because `vitehub()` nests its plugins in an array.
103
+ */
104
+ async function flattenPluginOptions(plugins) {
105
+ const flattened = [];
106
+ await flattenPlugins(plugins ?? [], flattened, /* @__PURE__ */ new Set());
107
+ return flattened;
108
+ }
109
+ //#endregion
110
+ //#region ../internal/src/operations-vite.ts
111
+ const owners$1 = /* @__PURE__ */ new Set([
112
+ "@vite-hub/kv/vite",
113
+ "@vite-hub/blob/vite",
114
+ "@vite-hub/email/vite",
115
+ "@vite-hub/rate-limit/vite",
116
+ "@vite-hub/forms/vite",
117
+ "@vite-hub/sync/vite"
118
+ ]);
119
+ const discoveryInstalled = Symbol.for("vitehub.operations.dev.discovery");
120
+ /** Publish only the elected standalone transport; other Console policies retain their own discovery hook. */
121
+ function publishStandaloneOperationServer(server) {
122
+ const http = server.httpServer;
123
+ if (!http || server.config.server.middlewareMode || Reflect.get(server, discoveryInstalled)) return;
124
+ const root = resolve(server.config.root);
125
+ const handlers = Reflect.get(Object(Reflect.get(server.config, "nitro")), "handlers");
126
+ if (!Array.isArray(handlers) || !handlers.some((handler) => handler?.handler === resolve(root, ".vitehub/nitro/operations/rpc.mjs"))) return;
127
+ Reflect.set(server, discoveryInstalled, true);
128
+ let ownedUrl;
129
+ const write = () => {
130
+ const address = http.address();
131
+ if (!address || typeof address === "string") return;
132
+ const host = address.address === "::" || address.address === "0.0.0.0" ? "localhost" : address.family === "IPv6" ? `[${address.address}]` : address.address;
133
+ const url = server.resolvedUrls?.local[0] ?? `${server.config.server.https ? "https" : "http"}://${host}:${address.port}${server.config.base}`;
134
+ try {
135
+ writeViteHubDevServerFile(root, {
136
+ root,
137
+ url
138
+ });
139
+ ownedUrl = url;
140
+ } catch {}
141
+ };
142
+ if (http.listening) write();
143
+ else http.once("listening", write);
144
+ http.once("close", () => {
145
+ try {
146
+ if (ownedUrl && readViteHubDevServerFile(root)?.url === ownedUrl) removeViteHubDevServerFile(root);
147
+ } catch {}
148
+ });
149
+ }
150
+ /** Standalone primitives share one local Nitro RPC. The root integration owns its own access policy. */
151
+ async function installStandaloneOperationRpc(config, command, module) {
152
+ if (command !== "serve") return;
153
+ const plugins = await flattenPluginOptions(config.plugins);
154
+ if (plugins.some((plugin) => Reflect.get(plugin, "name") === "vite-hub/dependencies" || Reflect.get(plugin, "name") === "vite-hub/console")) return;
155
+ const contributions = (await collectOperationContributions(plugins)).filter((source) => source.runtime !== false);
156
+ const owner = contributions.find((source) => owners$1.has(source.plugin));
157
+ if (!owner || !contributions.some((source) => source.module === module && owners$1.has(source.plugin))) return;
158
+ const root = resolve(config.root ?? process.cwd());
159
+ const handler = resolve(root, ".vitehub/nitro/operations/rpc.mjs");
160
+ await writeFileIfChanged(handler, [
161
+ `import { createStandaloneOperationHandler } from ${JSON.stringify(owner.module)}`,
162
+ ...contributions.map((entry, index) => `import * as source${index} from ${JSON.stringify(entry.module)}`),
163
+ `export default createStandaloneOperationHandler([${contributions.map((entry, index) => `{ operations: source${index}[${JSON.stringify(entry.export)}], plugin: ${JSON.stringify(entry.plugin)} }`).join(", ")}], ${JSON.stringify(root)})`,
164
+ ""
165
+ ].join("\n"));
166
+ const kit = createNitroServerKit(Reflect.get(config, "nitro"));
167
+ kit.addHandler({
168
+ handler,
169
+ route: operationRpcPath
170
+ });
171
+ const devHandlers = kit.config.devHandlers;
172
+ const signed = Array.isArray(devHandlers) ? [...devHandlers] : [];
173
+ addViteHubDevPeerDevHandler(signed);
174
+ kit.config.devHandlers = signed;
175
+ Reflect.set(config, "nitro", kit.config);
176
+ }
177
+ //#endregion
178
+ //#region ../internal/src/durability.ts
179
+ /** The `durability` module next to the Vite plugin module at `importMetaUrl`, in source and in `dist`. */
180
+ function durabilityModuleFile(importMetaUrl) {
181
+ return fileURLToPath(new URL(importMetaUrl.endsWith(".ts") ? "./durability.ts" : "./durability.js", importMetaUrl));
182
+ }
11
183
  //#endregion
12
184
  //#region src/vite-config.ts
13
185
  const KV_VITE_PLUGIN_NAME = "@vite-hub/kv/vite";
14
186
  const KV_VIRTUAL_CONFIG_ID = "#vitehub/kv/config";
15
- function resolveHosting(input) {
16
- const env = input.env || process.env;
17
- return trimmed(input.hosting) ?? readEnv(env, "VITEHUB_HOSTING");
18
- }
19
187
  function resolveKVViteConfig(kv, input = {}) {
20
188
  const env = input.env || process.env;
21
- const hosting = resolveHosting(input);
189
+ const hosting = resolveHostPreset({
190
+ env,
191
+ hosting: input.hosting
192
+ });
22
193
  return {
23
194
  hosting,
24
195
  kv: normalizeKVOptions(kv, {
196
+ dev: input.dev,
25
197
  env,
26
- hosting
198
+ hosting,
199
+ postgresDatabase: input.postgresDatabase
27
200
  }) ?? false
28
201
  };
29
202
  }
30
203
  //#endregion
31
- //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
32
- const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
33
- function normalizeWindowsPath(input = "") {
34
- if (!input) return input;
35
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
36
- }
37
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
38
- const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
39
- const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
40
- function cwd() {
41
- if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
42
- return "/";
43
- }
44
- const resolve$1 = function(...arguments_) {
45
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
46
- let resolvedPath = "";
47
- let resolvedAbsolute = false;
48
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
49
- const path = index >= 0 ? arguments_[index] : cwd();
50
- if (!path || path.length === 0) continue;
51
- resolvedPath = `${path}/${resolvedPath}`;
52
- resolvedAbsolute = isAbsolute$1(path);
53
- }
54
- resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
55
- if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
56
- return resolvedPath.length > 0 ? resolvedPath : ".";
57
- };
58
- function normalizeString(path, allowAboveRoot) {
59
- let res = "";
60
- let lastSegmentLength = 0;
61
- let lastSlash = -1;
62
- let dots = 0;
63
- let char = null;
64
- for (let index = 0; index <= path.length; ++index) {
65
- if (index < path.length) char = path[index];
66
- else if (char === "/") break;
67
- else char = "/";
68
- if (char === "/") {
69
- if (lastSlash === index - 1 || dots === 1);
70
- else if (dots === 2) {
71
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
72
- if (res.length > 2) {
73
- const lastSlashIndex = res.lastIndexOf("/");
74
- if (lastSlashIndex === -1) {
75
- res = "";
76
- lastSegmentLength = 0;
77
- } else {
78
- res = res.slice(0, lastSlashIndex);
79
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
80
- }
81
- lastSlash = index;
82
- dots = 0;
83
- continue;
84
- } else if (res.length > 0) {
85
- res = "";
86
- lastSegmentLength = 0;
87
- lastSlash = index;
88
- dots = 0;
89
- continue;
90
- }
91
- }
92
- if (allowAboveRoot) {
93
- res += res.length > 0 ? "/.." : "..";
94
- lastSegmentLength = 2;
95
- }
96
- } else {
97
- if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
98
- else res = path.slice(lastSlash + 1, index);
99
- lastSegmentLength = index - lastSlash - 1;
100
- }
101
- lastSlash = index;
102
- dots = 0;
103
- } else if (char === "." && dots !== -1) ++dots;
104
- else dots = -1;
105
- }
106
- return res;
107
- }
108
- const isAbsolute$1 = function(p) {
109
- return _IS_ABSOLUTE_RE.test(p);
110
- };
111
- const relative$1 = function(from, to) {
112
- const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
113
- const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
114
- if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
115
- const _fromCopy = [..._from];
116
- for (const segment of _fromCopy) {
117
- if (_to[0] !== segment) break;
118
- _from.shift();
119
- _to.shift();
120
- }
121
- return [..._from.map(() => ".."), ..._to].join("/");
122
- };
123
- const dirname$1 = function(p) {
124
- const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
125
- if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
126
- return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
127
- };
128
- //#endregion
129
204
  //#region ../internal/src/build/client-output.ts
130
205
  function hasStaticIndex(clientDir) {
131
206
  return existsSync(resolve$1(clientDir, "index.html"));
132
207
  }
133
- async function copyClientOutput(clientDir, targetDir) {
208
+ async function copyClientOutput(clientDir, targetDir, excludedDirs = []) {
134
209
  const resolvedClientDir = resolve$1(clientDir);
135
210
  const resolvedTargetDir = resolve$1(targetDir);
136
211
  if (resolvedClientDir === resolvedTargetDir) return;
212
+ const excluded = /* @__PURE__ */ new Set();
213
+ for (const dir of excludedDirs) {
214
+ const resolved = resolve$1(dir);
215
+ if (resolved !== resolvedClientDir && resolved.startsWith(`${resolvedClientDir}/`)) excluded.add(resolved);
216
+ }
217
+ const filter = (source) => {
218
+ const resolved = resolve$1(source);
219
+ return ![...excluded].some((dir) => resolved === dir || resolved.startsWith(`${dir}/`));
220
+ };
137
221
  await rm(resolvedTargetDir, {
138
222
  force: true,
139
223
  recursive: true
@@ -143,10 +227,16 @@ async function copyClientOutput(clientDir, targetDir) {
143
227
  if (targetRelativePath && !targetRelativePath.startsWith("../")) {
144
228
  const [targetRootEntry] = targetRelativePath.split("/", 1);
145
229
  await mkdir(resolvedTargetDir, { recursive: true });
146
- await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), { recursive: true })));
230
+ await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), {
231
+ recursive: true,
232
+ filter
233
+ })));
147
234
  return;
148
235
  }
149
- await cp(resolvedClientDir, resolvedTargetDir, { recursive: true });
236
+ await cp(resolvedClientDir, resolvedTargetDir, {
237
+ recursive: true,
238
+ filter
239
+ });
150
240
  }
151
241
  //#endregion
152
242
  //#region ../internal/src/build/provider-output-config.ts
@@ -192,7 +282,7 @@ function isProviderJsonRecord(value) {
192
282
  }
193
283
  }
194
284
  function assertProviderJsonRecord(value) {
195
- if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
285
+ if (!isProviderJsonRecord(value)) throw internalErrorDiagnostics.INTERNAL_B0043({ message: "[vitehub] Provider output config must be a JSON object." });
196
286
  }
197
287
  function isFileNotFoundError(error) {
198
288
  return error instanceof Error && "code" in error && error.code === "ENOENT";
@@ -225,7 +315,7 @@ function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
225
315
  const key = getKeyedArrayEntryValue(entry, ownership.key);
226
316
  return key === void 0 ? [] : [key];
227
317
  });
228
- const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
318
+ const ownedKeys = /* @__PURE__ */ new Set([...ownership.values ?? [], ...replacementKeys]);
229
319
  return current.filter((entry) => {
230
320
  const key = getKeyedArrayEntryValue(entry, ownership.key);
231
321
  return key === void 0 || !ownedKeys.has(key);
@@ -242,2432 +332,95 @@ function mergeOwnedArrays(existing, value, arrays) {
242
332
  return next;
243
333
  }
244
334
  async function persistProviderJsonRecord(file, value, removeIfEmpty) {
245
- if (removeIfEmpty && !Object.keys(value).length) {
246
- await rm(file, { force: true });
247
- return;
248
- }
249
- await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
250
- }
251
- async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
252
- const existing = await readProviderJsonRecord(file) ?? {};
253
- const defaults = options.defaults ?? {};
254
- assertProviderJsonRecord(defaults);
255
- await persistProviderJsonRecord(file, mergeProviderOutputConfig({
256
- ...defaults,
257
- ...existing
258
- }, value, ownership), options.removeIfEmpty === true);
259
- }
260
- function mergeProviderOutputConfig(existing, value, ownership = {}) {
261
- assertProviderJsonRecord(existing);
262
- assertProviderJsonRecord(value);
263
- return {
264
- ...deleteOwnedFields(existing, ownership),
265
- ...mergeOwnedArrays(existing, value, ownership.arrays)
266
- };
267
- }
268
- function stringifyProviderOutputConfig(value) {
269
- assertProviderJsonRecord(value);
270
- return JSON.stringify(value, null, 2);
271
- }
272
- async function cleanProviderOutputConfig(file, ownership) {
273
- if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
274
- const existing = await readProviderJsonRecord(file);
275
- if (!existing) return;
276
- const next = deleteOwnedFields(existing, ownership, true);
277
- let changed = (ownership.keys ?? []).some((key) => key in existing);
278
- for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
279
- if (arrayOwnership.preserveOnCleanup) continue;
280
- if (!(field in existing)) continue;
281
- const current = existing[field];
282
- const retained = arrayOwnership.retainOnCleanup ?? [];
283
- const preserved = [...preserveUnownedKeyedArrayEntries(current, arrayOwnership, retained), ...retained];
284
- changed ||= retained.length > 0 || !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
285
- if (preserved.length) next[field] = preserved;
286
- }
287
- if (!changed) return;
288
- await persistProviderJsonRecord(file, next, true);
289
- }
290
- //#endregion
291
- //#region ../internal/src/build/user-entry.ts
292
- function toSafeAppName(rootDir) {
293
- return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
294
- }
295
- //#endregion
296
- //#region ../internal/src/build/cloudflare.ts
297
- function createDefaultCloudflareOutputRoot(rootDir) {
298
- return resolve(rootDir, "dist", toSafeAppName(rootDir));
299
- }
300
- async function writeCloudflareWranglerConfig(options) {
301
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
302
- const configFile = resolve(outputRoot, "wrangler.json");
303
- if (!options.wranglerConfig) {
304
- await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
305
- return;
306
- }
307
- await mkdir(outputRoot, { recursive: true });
308
- await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, {
309
- defaults: options.wranglerConfigDefaults,
310
- removeIfEmpty: true
311
- });
312
- }
313
- //#endregion
314
- //#region ../internal/src/build/esbuild.ts
315
- var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
316
- var __defProp = Object.defineProperty;
317
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
318
- var __getOwnPropNames = Object.getOwnPropertyNames;
319
- var __hasOwnProp = Object.prototype.hasOwnProperty;
320
- var __export = (target, all) => {
321
- for (var name in all) __defProp(target, name, {
322
- get: all[name],
323
- enumerable: true
324
- });
325
- };
326
- var __copyProps = (to, from, except, desc) => {
327
- if (from && typeof from === "object" || typeof from === "function") {
328
- for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
329
- get: () => from[key],
330
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
331
- });
332
- }
333
- return to;
334
- };
335
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
336
- var node_exports = {};
337
- __export(node_exports, {
338
- analyzeMetafile: () => analyzeMetafile,
339
- analyzeMetafileSync: () => analyzeMetafileSync,
340
- build: () => build,
341
- buildSync: () => buildSync,
342
- context: () => context,
343
- default: () => node_default,
344
- formatMessages: () => formatMessages,
345
- formatMessagesSync: () => formatMessagesSync,
346
- initialize: () => initialize,
347
- stop: () => stop,
348
- transform: () => transform,
349
- transformSync: () => transformSync,
350
- version: () => version
351
- });
352
- module.exports = __toCommonJS(node_exports);
353
- function encodePacket(packet) {
354
- let visit = (value) => {
355
- if (value === null) bb.write8(0);
356
- else if (typeof value === "boolean") {
357
- bb.write8(1);
358
- bb.write8(+value);
359
- } else if (typeof value === "number") {
360
- bb.write8(2);
361
- bb.write32(value | 0);
362
- } else if (typeof value === "string") {
363
- bb.write8(3);
364
- bb.write(encodeUTF8(value));
365
- } else if (value instanceof Uint8Array) {
366
- bb.write8(4);
367
- bb.write(value);
368
- } else if (value instanceof Array) {
369
- bb.write8(5);
370
- bb.write32(value.length);
371
- for (let item of value) visit(item);
372
- } else {
373
- let keys = Object.keys(value);
374
- bb.write8(6);
375
- bb.write32(keys.length);
376
- for (let key of keys) {
377
- bb.write(encodeUTF8(key));
378
- visit(value[key]);
379
- }
380
- }
381
- };
382
- let bb = new ByteBuffer();
383
- bb.write32(0);
384
- bb.write32(packet.id << 1 | +!packet.isRequest);
385
- visit(packet.value);
386
- writeUInt32LE(bb.buf, bb.len - 4, 0);
387
- return bb.buf.subarray(0, bb.len);
388
- }
389
- function decodePacket(bytes) {
390
- let visit = () => {
391
- switch (bb.read8()) {
392
- case 0: return null;
393
- case 1: return !!bb.read8();
394
- case 2: return bb.read32();
395
- case 3: return decodeUTF8(bb.read());
396
- case 4: return bb.read();
397
- case 5: {
398
- let count = bb.read32();
399
- let value2 = [];
400
- for (let i = 0; i < count; i++) value2.push(visit());
401
- return value2;
402
- }
403
- case 6: {
404
- let count = bb.read32();
405
- let value2 = {};
406
- for (let i = 0; i < count; i++) value2[decodeUTF8(bb.read())] = visit();
407
- return value2;
408
- }
409
- default: throw new Error("Invalid packet");
410
- }
411
- };
412
- let bb = new ByteBuffer(bytes);
413
- let id = bb.read32();
414
- let isRequest = (id & 1) === 0;
415
- id >>>= 1;
416
- let value = visit();
417
- if (bb.ptr !== bytes.length) throw new Error("Invalid packet");
418
- return {
419
- id,
420
- isRequest,
421
- value
422
- };
423
- }
424
- var ByteBuffer = class {
425
- constructor(buf = new Uint8Array(1024)) {
426
- this.buf = buf;
427
- this.len = 0;
428
- this.ptr = 0;
429
- }
430
- _write(delta) {
431
- if (this.len + delta > this.buf.length) {
432
- let clone = new Uint8Array((this.len + delta) * 2);
433
- clone.set(this.buf);
434
- this.buf = clone;
435
- }
436
- this.len += delta;
437
- return this.len - delta;
438
- }
439
- write8(value) {
440
- let offset = this._write(1);
441
- this.buf[offset] = value;
442
- }
443
- write32(value) {
444
- let offset = this._write(4);
445
- writeUInt32LE(this.buf, value, offset);
446
- }
447
- write(bytes) {
448
- let offset = this._write(4 + bytes.length);
449
- writeUInt32LE(this.buf, bytes.length, offset);
450
- this.buf.set(bytes, offset + 4);
451
- }
452
- _read(delta) {
453
- if (this.ptr + delta > this.buf.length) throw new Error("Invalid packet");
454
- this.ptr += delta;
455
- return this.ptr - delta;
456
- }
457
- read8() {
458
- return this.buf[this._read(1)];
459
- }
460
- read32() {
461
- return readUInt32LE(this.buf, this._read(4));
462
- }
463
- read() {
464
- let length = this.read32();
465
- let bytes = new Uint8Array(length);
466
- let ptr = this._read(bytes.length);
467
- bytes.set(this.buf.subarray(ptr, ptr + length));
468
- return bytes;
469
- }
470
- };
471
- var encodeUTF8;
472
- var decodeUTF8;
473
- var encodeInvariant;
474
- if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
475
- let encoder = new TextEncoder();
476
- let decoder = new TextDecoder();
477
- encodeUTF8 = (text) => encoder.encode(text);
478
- decodeUTF8 = (bytes) => decoder.decode(bytes);
479
- encodeInvariant = "new TextEncoder().encode(\"\")";
480
- } else if (typeof Buffer !== "undefined") {
481
- encodeUTF8 = (text) => Buffer.from(text);
482
- decodeUTF8 = (bytes) => {
483
- let { buffer, byteOffset, byteLength } = bytes;
484
- return Buffer.from(buffer, byteOffset, byteLength).toString();
485
- };
486
- encodeInvariant = "Buffer.from(\"\")";
487
- } else throw new Error("No UTF-8 codec found");
488
- if (!(encodeUTF8("") instanceof Uint8Array)) throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
489
-
490
- This indicates that your JavaScript environment is broken. You cannot use
491
- esbuild in this environment because esbuild relies on this invariant. This
492
- is not a problem with esbuild. You need to fix your environment instead.
493
- `);
494
- function readUInt32LE(buffer, offset) {
495
- return (buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24) >>> 0;
496
- }
497
- function writeUInt32LE(buffer, value, offset) {
498
- buffer[offset++] = value;
499
- buffer[offset++] = value >> 8;
500
- buffer[offset++] = value >> 16;
501
- buffer[offset++] = value >> 24;
502
- }
503
- var fromCharCode = String.fromCharCode;
504
- function throwSyntaxError(bytes, index, message) {
505
- const c = bytes[index];
506
- let line = 1;
507
- let column = 0;
508
- for (let i = 0; i < index; i++) if (bytes[i] === 10) {
509
- line++;
510
- column = 0;
511
- } else column++;
512
- throw new SyntaxError(message ? message : index === bytes.length ? "Unexpected end of input while parsing JSON" : c >= 32 && c <= 126 ? `Unexpected character ${fromCharCode(c)} in JSON at position ${index} (line ${line}, column ${column})` : `Unexpected byte 0x${c.toString(16)} in JSON at position ${index} (line ${line}, column ${column})`);
513
- }
514
- function JSON_parse(bytes) {
515
- if (!(bytes instanceof Uint8Array)) throw new Error(`JSON input must be a Uint8Array`);
516
- const propertyStack = [];
517
- const objectStack = [];
518
- const stateStack = [];
519
- const length = bytes.length;
520
- let property = null;
521
- let state = 0;
522
- let object;
523
- let i = 0;
524
- while (i < length) {
525
- let c = bytes[i++];
526
- if (c <= 32) continue;
527
- let value;
528
- if (state === 2 && property === null && c !== 34 && c !== 125) throwSyntaxError(bytes, --i);
529
- switch (c) {
530
- case 116:
531
- if (bytes[i++] !== 114 || bytes[i++] !== 117 || bytes[i++] !== 101) throwSyntaxError(bytes, --i);
532
- value = true;
533
- break;
534
- case 102:
535
- if (bytes[i++] !== 97 || bytes[i++] !== 108 || bytes[i++] !== 115 || bytes[i++] !== 101) throwSyntaxError(bytes, --i);
536
- value = false;
537
- break;
538
- case 110:
539
- if (bytes[i++] !== 117 || bytes[i++] !== 108 || bytes[i++] !== 108) throwSyntaxError(bytes, --i);
540
- value = null;
541
- break;
542
- case 45:
543
- case 46:
544
- case 48:
545
- case 49:
546
- case 50:
547
- case 51:
548
- case 52:
549
- case 53:
550
- case 54:
551
- case 55:
552
- case 56:
553
- case 57: {
554
- let index = i;
555
- value = fromCharCode(c);
556
- c = bytes[i];
557
- while (true) {
558
- switch (c) {
559
- case 43:
560
- case 45:
561
- case 46:
562
- case 48:
563
- case 49:
564
- case 50:
565
- case 51:
566
- case 52:
567
- case 53:
568
- case 54:
569
- case 55:
570
- case 56:
571
- case 57:
572
- case 101:
573
- case 69:
574
- value += fromCharCode(c);
575
- c = bytes[++i];
576
- continue;
577
- }
578
- break;
579
- }
580
- value = +value;
581
- if (isNaN(value)) throwSyntaxError(bytes, --index, "Invalid number");
582
- break;
583
- }
584
- case 34:
585
- value = "";
586
- while (true) {
587
- if (i >= length) throwSyntaxError(bytes, length);
588
- c = bytes[i++];
589
- if (c === 34) break;
590
- else if (c === 92) switch (bytes[i++]) {
591
- case 34:
592
- value += "\"";
593
- break;
594
- case 47:
595
- value += "/";
596
- break;
597
- case 92:
598
- value += "\\";
599
- break;
600
- case 98:
601
- value += "\b";
602
- break;
603
- case 102:
604
- value += "\f";
605
- break;
606
- case 110:
607
- value += "\n";
608
- break;
609
- case 114:
610
- value += "\r";
611
- break;
612
- case 116:
613
- value += " ";
614
- break;
615
- case 117: {
616
- let code = 0;
617
- for (let j = 0; j < 4; j++) {
618
- c = bytes[i++];
619
- code <<= 4;
620
- if (c >= 48 && c <= 57) code |= c - 48;
621
- else if (c >= 97 && c <= 102) code |= c + -87;
622
- else if (c >= 65 && c <= 70) code |= c + -55;
623
- else throwSyntaxError(bytes, --i);
624
- }
625
- value += fromCharCode(code);
626
- break;
627
- }
628
- default:
629
- throwSyntaxError(bytes, --i);
630
- break;
631
- }
632
- else if (c <= 127) value += fromCharCode(c);
633
- else if ((c & 224) === 192) value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
634
- else if ((c & 240) === 224) value += fromCharCode((c & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63);
635
- else if ((c & 248) == 240) {
636
- let codePoint = (c & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
637
- if (codePoint > 65535) {
638
- codePoint -= 65536;
639
- value += fromCharCode(codePoint >> 10 & 1023 | 55296);
640
- codePoint = 56320 | codePoint & 1023;
641
- }
642
- value += fromCharCode(codePoint);
643
- }
644
- }
645
- value[0];
646
- break;
647
- case 91:
648
- value = [];
649
- propertyStack.push(property);
650
- objectStack.push(object);
651
- stateStack.push(state);
652
- property = null;
653
- object = value;
654
- state = 1;
655
- continue;
656
- case 123:
657
- value = {};
658
- propertyStack.push(property);
659
- objectStack.push(object);
660
- stateStack.push(state);
661
- property = null;
662
- object = value;
663
- state = 2;
664
- continue;
665
- case 93:
666
- if (state !== 1) throwSyntaxError(bytes, --i);
667
- value = object;
668
- property = propertyStack.pop();
669
- object = objectStack.pop();
670
- state = stateStack.pop();
671
- break;
672
- case 125:
673
- if (state !== 2) throwSyntaxError(bytes, --i);
674
- value = object;
675
- property = propertyStack.pop();
676
- object = objectStack.pop();
677
- state = stateStack.pop();
678
- break;
679
- default: throwSyntaxError(bytes, --i);
680
- }
681
- c = bytes[i];
682
- while (c <= 32) c = bytes[++i];
683
- switch (state) {
684
- case 0:
685
- if (i === length) return value;
686
- break;
687
- case 1:
688
- object.push(value);
689
- if (c === 44) {
690
- i++;
691
- continue;
692
- }
693
- if (c === 93) continue;
694
- break;
695
- case 2:
696
- if (property === null) {
697
- property = value;
698
- if (c === 58) {
699
- i++;
700
- continue;
701
- }
702
- } else {
703
- object[property] = value;
704
- property = null;
705
- if (c === 44) {
706
- i++;
707
- continue;
708
- }
709
- if (c === 125) continue;
710
- }
711
- break;
712
- }
713
- break;
714
- }
715
- throwSyntaxError(bytes, i);
716
- }
717
- var quote = JSON.stringify;
718
- var buildLogLevelDefault = "warning";
719
- var transformLogLevelDefault = "silent";
720
- function validateAndJoinStringArray(values, what) {
721
- const toJoin = [];
722
- for (const value of values) {
723
- validateStringValue(value, what);
724
- if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`);
725
- toJoin.push(value);
726
- }
727
- return toJoin.join(",");
728
- }
729
- var canBeAnything = () => null;
730
- var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
731
- var mustBeString = (value) => typeof value === "string" ? null : "a string";
732
- var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
733
- var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
734
- var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
735
- var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
736
- var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
737
- var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
738
- var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
739
- var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
740
- var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
741
- var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
742
- var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
743
- var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
744
- var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
745
- var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
746
- var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
747
- function getFlag(object, keys, key, mustBeFn) {
748
- let value = object[key];
749
- keys[key + ""] = true;
750
- if (value === void 0) return void 0;
751
- let mustBe = mustBeFn(value);
752
- if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
753
- return value;
754
- }
755
- function checkForInvalidFlags(object, keys, where) {
756
- for (let key in object) if (!(key in keys)) throw new Error(`Invalid option ${where}: ${quote(key)}`);
757
- }
758
- function validateInitializeOptions(options) {
759
- let keys = /* @__PURE__ */ Object.create(null);
760
- let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
761
- let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
762
- let worker = getFlag(options, keys, "worker", mustBeBoolean);
763
- checkForInvalidFlags(options, keys, "in initialize() call");
764
- return {
765
- wasmURL,
766
- wasmModule,
767
- worker
768
- };
769
- }
770
- function validateMangleCache(mangleCache) {
771
- let validated;
772
- if (mangleCache !== void 0) {
773
- validated = /* @__PURE__ */ Object.create(null);
774
- for (let key in mangleCache) {
775
- let value = mangleCache[key];
776
- if (typeof value === "string" || value === false) validated[key] = value;
777
- else throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
778
- }
779
- }
780
- return validated;
781
- }
782
- function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
783
- let color = getFlag(options, keys, "color", mustBeBoolean);
784
- let logLevel = getFlag(options, keys, "logLevel", mustBeString);
785
- let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
786
- if (color !== void 0) flags.push(`--color=${color}`);
787
- else if (isTTY2) flags.push(`--color=true`);
788
- flags.push(`--log-level=${logLevel || logLevelDefault}`);
789
- flags.push(`--log-limit=${logLimit || 0}`);
790
- }
791
- function validateStringValue(value, what, key) {
792
- if (typeof value !== "string") throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
793
- return value;
794
- }
795
- function pushCommonFlags(flags, options, keys) {
796
- let legalComments = getFlag(options, keys, "legalComments", mustBeString);
797
- let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
798
- let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
799
- let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
800
- let format = getFlag(options, keys, "format", mustBeString);
801
- let globalName = getFlag(options, keys, "globalName", mustBeString);
802
- let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
803
- let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
804
- let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
805
- let minify = getFlag(options, keys, "minify", mustBeBoolean);
806
- let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
807
- let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
808
- let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
809
- let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
810
- let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
811
- let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
812
- let charset = getFlag(options, keys, "charset", mustBeString);
813
- let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
814
- let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
815
- let jsx = getFlag(options, keys, "jsx", mustBeString);
816
- let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
817
- let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
818
- let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
819
- let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
820
- let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
821
- let define = getFlag(options, keys, "define", mustBeObject);
822
- let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
823
- let supported = getFlag(options, keys, "supported", mustBeObject);
824
- let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
825
- let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
826
- let platform = getFlag(options, keys, "platform", mustBeString);
827
- let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
828
- let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
829
- if (legalComments) flags.push(`--legal-comments=${legalComments}`);
830
- if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
831
- if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
832
- if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
833
- if (format) flags.push(`--format=${format}`);
834
- if (globalName) flags.push(`--global-name=${globalName}`);
835
- if (platform) flags.push(`--platform=${platform}`);
836
- if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
837
- if (minify) flags.push("--minify");
838
- if (minifySyntax) flags.push("--minify-syntax");
839
- if (minifyWhitespace) flags.push("--minify-whitespace");
840
- if (minifyIdentifiers) flags.push("--minify-identifiers");
841
- if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
842
- if (charset) flags.push(`--charset=${charset}`);
843
- if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
844
- if (ignoreAnnotations) flags.push(`--ignore-annotations`);
845
- if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
846
- if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
847
- if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
848
- if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
849
- if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
850
- if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
851
- if (jsx) flags.push(`--jsx=${jsx}`);
852
- if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
853
- if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
854
- if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
855
- if (jsxDev) flags.push(`--jsx-dev`);
856
- if (jsxSideEffects) flags.push(`--jsx-side-effects`);
857
- if (define) for (let key in define) {
858
- if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
859
- flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
860
- }
861
- if (logOverride) for (let key in logOverride) {
862
- if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
863
- flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
864
- }
865
- if (supported) for (let key in supported) {
866
- if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
867
- const value = supported[key];
868
- if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
869
- flags.push(`--supported:${key}=${value}`);
870
- }
871
- if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
872
- if (keepNames) flags.push(`--keep-names`);
873
- }
874
- function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
875
- var _a2;
876
- let flags = [];
877
- let entries = [];
878
- let keys = /* @__PURE__ */ Object.create(null);
879
- let stdinContents = null;
880
- let stdinResolveDir = null;
881
- pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
882
- pushCommonFlags(flags, options, keys);
883
- let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
884
- let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
885
- let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
886
- let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
887
- let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
888
- let outfile = getFlag(options, keys, "outfile", mustBeString);
889
- let outdir = getFlag(options, keys, "outdir", mustBeString);
890
- let outbase = getFlag(options, keys, "outbase", mustBeString);
891
- let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
892
- let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
893
- let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
894
- let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
895
- let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
896
- let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
897
- let packages = getFlag(options, keys, "packages", mustBeString);
898
- let alias = getFlag(options, keys, "alias", mustBeObject);
899
- let loader = getFlag(options, keys, "loader", mustBeObject);
900
- let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
901
- let publicPath = getFlag(options, keys, "publicPath", mustBeString);
902
- let entryNames = getFlag(options, keys, "entryNames", mustBeString);
903
- let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
904
- let assetNames = getFlag(options, keys, "assetNames", mustBeString);
905
- let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
906
- let banner = getFlag(options, keys, "banner", mustBeObject);
907
- let footer = getFlag(options, keys, "footer", mustBeObject);
908
- let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
909
- let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
910
- let stdin = getFlag(options, keys, "stdin", mustBeObject);
911
- let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
912
- let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
913
- let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
914
- keys.plugins = true;
915
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
916
- if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
917
- if (bundle) flags.push("--bundle");
918
- if (allowOverwrite) flags.push("--allow-overwrite");
919
- if (splitting) flags.push("--splitting");
920
- if (preserveSymlinks) flags.push("--preserve-symlinks");
921
- if (metafile) flags.push(`--metafile`);
922
- if (outfile) flags.push(`--outfile=${outfile}`);
923
- if (outdir) flags.push(`--outdir=${outdir}`);
924
- if (outbase) flags.push(`--outbase=${outbase}`);
925
- if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
926
- if (packages) flags.push(`--packages=${packages}`);
927
- if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
928
- if (publicPath) flags.push(`--public-path=${publicPath}`);
929
- if (entryNames) flags.push(`--entry-names=${entryNames}`);
930
- if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
931
- if (assetNames) flags.push(`--asset-names=${assetNames}`);
932
- if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
933
- if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
934
- if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
935
- if (alias) for (let old in alias) {
936
- if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
937
- flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
938
- }
939
- if (banner) for (let type in banner) {
940
- if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
941
- flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
942
- }
943
- if (footer) for (let type in footer) {
944
- if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
945
- flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
946
- }
947
- if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`);
948
- if (loader) for (let ext in loader) {
949
- if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
950
- flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
951
- }
952
- if (outExtension) for (let ext in outExtension) {
953
- if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
954
- flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
955
- }
956
- if (entryPoints) if (Array.isArray(entryPoints)) for (let i = 0, n = entryPoints.length; i < n; i++) {
957
- let entryPoint = entryPoints[i];
958
- if (typeof entryPoint === "object" && entryPoint !== null) {
959
- let entryPointKeys = /* @__PURE__ */ Object.create(null);
960
- let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
961
- let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
962
- checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
963
- if (input === void 0) throw new Error("Missing property \"in\" for entry point at index " + i);
964
- if (output === void 0) throw new Error("Missing property \"out\" for entry point at index " + i);
965
- entries.push([output, input]);
966
- } else entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
967
- }
968
- else for (let key in entryPoints) entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
969
- if (stdin) {
970
- let stdinKeys = /* @__PURE__ */ Object.create(null);
971
- let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
972
- let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
973
- let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
974
- let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
975
- checkForInvalidFlags(stdin, stdinKeys, "in \"stdin\" object");
976
- if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
977
- if (loader2) flags.push(`--loader=${loader2}`);
978
- if (resolveDir) stdinResolveDir = resolveDir;
979
- if (typeof contents === "string") stdinContents = encodeUTF8(contents);
980
- else if (contents instanceof Uint8Array) stdinContents = contents;
981
- }
982
- let nodePaths = [];
983
- if (nodePathsInput) for (let value of nodePathsInput) {
984
- value += "";
985
- nodePaths.push(value);
986
- }
987
- return {
988
- entries,
989
- flags,
990
- write,
991
- stdinContents,
992
- stdinResolveDir,
993
- absWorkingDir,
994
- nodePaths,
995
- mangleCache: validateMangleCache(mangleCache)
996
- };
997
- }
998
- function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
999
- let flags = [];
1000
- let keys = /* @__PURE__ */ Object.create(null);
1001
- pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
1002
- pushCommonFlags(flags, options, keys);
1003
- let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
1004
- let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
1005
- let loader = getFlag(options, keys, "loader", mustBeString);
1006
- let banner = getFlag(options, keys, "banner", mustBeString);
1007
- let footer = getFlag(options, keys, "footer", mustBeString);
1008
- let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
1009
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
1010
- if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
1011
- if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
1012
- if (loader) flags.push(`--loader=${loader}`);
1013
- if (banner) flags.push(`--banner=${banner}`);
1014
- if (footer) flags.push(`--footer=${footer}`);
1015
- return {
1016
- flags,
1017
- mangleCache: validateMangleCache(mangleCache)
1018
- };
1019
- }
1020
- function createChannel(streamIn) {
1021
- const requestCallbacksByKey = {};
1022
- const closeData = {
1023
- didClose: false,
1024
- reason: ""
1025
- };
1026
- let responseCallbacks = {};
1027
- let nextRequestID = 0;
1028
- let nextBuildKey = 0;
1029
- let stdout = new Uint8Array(16 * 1024);
1030
- let stdoutUsed = 0;
1031
- let readFromStdout = (chunk) => {
1032
- let limit = stdoutUsed + chunk.length;
1033
- if (limit > stdout.length) {
1034
- let swap = new Uint8Array(limit * 2);
1035
- swap.set(stdout);
1036
- stdout = swap;
1037
- }
1038
- stdout.set(chunk, stdoutUsed);
1039
- stdoutUsed += chunk.length;
1040
- let offset = 0;
1041
- while (offset + 4 <= stdoutUsed) {
1042
- let length = readUInt32LE(stdout, offset);
1043
- if (offset + 4 + length > stdoutUsed) break;
1044
- offset += 4;
1045
- handleIncomingPacket(stdout.subarray(offset, offset + length));
1046
- offset += length;
1047
- }
1048
- if (offset > 0) {
1049
- stdout.copyWithin(0, offset, stdoutUsed);
1050
- stdoutUsed -= offset;
1051
- }
1052
- };
1053
- let afterClose = (error) => {
1054
- closeData.didClose = true;
1055
- if (error) closeData.reason = ": " + (error.message || error);
1056
- const text = "The service was stopped" + closeData.reason;
1057
- for (let id in responseCallbacks) responseCallbacks[id](text, null);
1058
- responseCallbacks = {};
1059
- };
1060
- let sendRequest = (refs, value, callback) => {
1061
- if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
1062
- let id = nextRequestID++;
1063
- responseCallbacks[id] = (error, response) => {
1064
- try {
1065
- callback(error, response);
1066
- } finally {
1067
- if (refs) refs.unref();
1068
- }
1069
- };
1070
- if (refs) refs.ref();
1071
- streamIn.writeToStdin(encodePacket({
1072
- id,
1073
- isRequest: true,
1074
- value
1075
- }));
1076
- };
1077
- let sendResponse = (id, value) => {
1078
- if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
1079
- streamIn.writeToStdin(encodePacket({
1080
- id,
1081
- isRequest: false,
1082
- value
1083
- }));
1084
- };
1085
- let handleRequest = async (id, request) => {
1086
- try {
1087
- if (request.command === "ping") {
1088
- sendResponse(id, {});
1089
- return;
1090
- }
1091
- if (typeof request.key === "number") {
1092
- const requestCallbacks = requestCallbacksByKey[request.key];
1093
- if (!requestCallbacks) return;
1094
- const callback = requestCallbacks[request.command];
1095
- if (callback) {
1096
- await callback(id, request);
1097
- return;
1098
- }
1099
- }
1100
- throw new Error(`Invalid command: ` + request.command);
1101
- } catch (e) {
1102
- const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
1103
- try {
1104
- sendResponse(id, { errors });
1105
- } catch {}
1106
- }
1107
- };
1108
- let isFirstPacket = true;
1109
- let handleIncomingPacket = (bytes) => {
1110
- if (isFirstPacket) {
1111
- isFirstPacket = false;
1112
- let binaryVersion = String.fromCharCode(...bytes);
1113
- if (binaryVersion !== "0.27.7") throw new Error(`Cannot start service: Host version "0.27.7" does not match binary version ${quote(binaryVersion)}`);
1114
- return;
1115
- }
1116
- let packet = decodePacket(bytes);
1117
- if (packet.isRequest) handleRequest(packet.id, packet.value);
1118
- else {
1119
- let callback = responseCallbacks[packet.id];
1120
- delete responseCallbacks[packet.id];
1121
- if (packet.value.error) callback(packet.value.error, {});
1122
- else callback(null, packet.value);
1123
- }
1124
- };
1125
- let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
1126
- let refCount = 0;
1127
- const buildKey = nextBuildKey++;
1128
- const requestCallbacks = {};
1129
- const buildRefs = {
1130
- ref() {
1131
- if (++refCount === 1) {
1132
- if (refs) refs.ref();
1133
- }
1134
- },
1135
- unref() {
1136
- if (--refCount === 0) {
1137
- delete requestCallbacksByKey[buildKey];
1138
- if (refs) refs.unref();
1139
- }
1140
- }
1141
- };
1142
- requestCallbacksByKey[buildKey] = requestCallbacks;
1143
- buildRefs.ref();
1144
- buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, (err, res) => {
1145
- try {
1146
- callback(err, res);
1147
- } finally {
1148
- buildRefs.unref();
1149
- }
1150
- });
1151
- };
1152
- let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
1153
- const details = createObjectStash();
1154
- let start = (inputPath) => {
1155
- try {
1156
- if (typeof input !== "string" && !(input instanceof Uint8Array)) throw new Error("The input to \"transform\" must be a string or a Uint8Array");
1157
- let { flags, mangleCache } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
1158
- let request = {
1159
- command: "transform",
1160
- flags,
1161
- inputFS: inputPath !== null,
1162
- input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
1163
- };
1164
- if (mangleCache) request.mangleCache = mangleCache;
1165
- sendRequest(refs, request, (error, response) => {
1166
- if (error) return callback(new Error(error), null);
1167
- let errors = replaceDetailsInMessages(response.errors, details);
1168
- let warnings = replaceDetailsInMessages(response.warnings, details);
1169
- let outstanding = 1;
1170
- let next = () => {
1171
- if (--outstanding === 0) {
1172
- let result = {
1173
- warnings,
1174
- code: response.code,
1175
- map: response.map,
1176
- mangleCache: void 0,
1177
- legalComments: void 0
1178
- };
1179
- if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
1180
- if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
1181
- callback(null, result);
1182
- }
1183
- };
1184
- if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
1185
- if (response.codeFS) {
1186
- outstanding++;
1187
- fs3.readFile(response.code, (err, contents) => {
1188
- if (err !== null) callback(err, null);
1189
- else {
1190
- response.code = contents;
1191
- next();
1192
- }
1193
- });
1194
- }
1195
- if (response.mapFS) {
1196
- outstanding++;
1197
- fs3.readFile(response.map, (err, contents) => {
1198
- if (err !== null) callback(err, null);
1199
- else {
1200
- response.map = contents;
1201
- next();
1202
- }
1203
- });
1204
- }
1205
- next();
1206
- });
1207
- } catch (e) {
1208
- let flags = [];
1209
- try {
1210
- pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
1211
- } catch {}
1212
- const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
1213
- sendRequest(refs, {
1214
- command: "error",
1215
- flags,
1216
- error
1217
- }, () => {
1218
- error.detail = details.load(error.detail);
1219
- callback(failureErrorWithLog("Transform failed", [error], []), null);
1220
- });
1221
- }
1222
- };
1223
- if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
1224
- let next = start;
1225
- start = () => fs3.writeFile(input, next);
1226
- }
1227
- start(null);
1228
- };
1229
- let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
1230
- if (!options) throw new Error(`Missing second argument in ${callName}() call`);
1231
- let keys = {};
1232
- let kind = getFlag(options, keys, "kind", mustBeString);
1233
- let color = getFlag(options, keys, "color", mustBeBoolean);
1234
- let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
1235
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
1236
- if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
1237
- if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
1238
- let request = {
1239
- command: "format-msgs",
1240
- messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
1241
- isWarning: kind === "warning"
1242
- };
1243
- if (color !== void 0) request.color = color;
1244
- if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
1245
- sendRequest(refs, request, (error, response) => {
1246
- if (error) return callback(new Error(error), null);
1247
- callback(null, response.messages);
1248
- });
1249
- };
1250
- let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
1251
- if (options === void 0) options = {};
1252
- let keys = {};
1253
- let color = getFlag(options, keys, "color", mustBeBoolean);
1254
- let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
1255
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
1256
- let request = {
1257
- command: "analyze-metafile",
1258
- metafile
1259
- };
1260
- if (color !== void 0) request.color = color;
1261
- if (verbose !== void 0) request.verbose = verbose;
1262
- sendRequest(refs, request, (error, response) => {
1263
- if (error) return callback(new Error(error), null);
1264
- callback(null, response.result);
1265
- });
1266
- };
1267
- return {
1268
- readFromStdout,
1269
- afterClose,
1270
- service: {
1271
- buildOrContext,
1272
- transform: transform2,
1273
- formatMessages: formatMessages2,
1274
- analyzeMetafile: analyzeMetafile2
1275
- }
1276
- };
1277
- }
1278
- function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
1279
- const details = createObjectStash();
1280
- const isContext = callName === "context";
1281
- const handleError = (e, pluginName) => {
1282
- const flags = [];
1283
- try {
1284
- pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
1285
- } catch {}
1286
- const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
1287
- sendRequest(refs, {
1288
- command: "error",
1289
- flags,
1290
- error: message
1291
- }, () => {
1292
- message.detail = details.load(message.detail);
1293
- callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
1294
- });
1295
- };
1296
- let plugins;
1297
- if (typeof options === "object") {
1298
- const value = options.plugins;
1299
- if (value !== void 0) {
1300
- if (!Array.isArray(value)) return handleError(/* @__PURE__ */ new Error(`"plugins" must be an array`), "");
1301
- plugins = value;
1302
- }
1303
- }
1304
- if (plugins && plugins.length > 0) {
1305
- if (streamIn.isSync) return handleError(/* @__PURE__ */ new Error("Cannot use plugins in synchronous API calls"), "");
1306
- handlePlugins(buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details).then((result) => {
1307
- if (!result.ok) return handleError(result.error, result.pluginName);
1308
- try {
1309
- buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
1310
- } catch (e) {
1311
- handleError(e, "");
1312
- }
1313
- }, (e) => handleError(e, ""));
1314
- return;
1315
- }
1316
- try {
1317
- buildOrContextContinue(null, (result, done) => done([], []), () => {});
1318
- } catch (e) {
1319
- handleError(e, "");
1320
- }
1321
- function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
1322
- const writeDefault = streamIn.hasFS;
1323
- const { entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir, nodePaths, mangleCache } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
1324
- if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
1325
- const request = {
1326
- command: "build",
1327
- key: buildKey,
1328
- entries,
1329
- flags,
1330
- write,
1331
- stdinContents,
1332
- stdinResolveDir,
1333
- absWorkingDir: absWorkingDir || defaultWD2,
1334
- nodePaths,
1335
- context: isContext
1336
- };
1337
- if (requestPlugins) request.plugins = requestPlugins;
1338
- if (mangleCache) request.mangleCache = mangleCache;
1339
- const buildResponseToResult = (response, callback2) => {
1340
- const result = {
1341
- errors: replaceDetailsInMessages(response.errors, details),
1342
- warnings: replaceDetailsInMessages(response.warnings, details),
1343
- outputFiles: void 0,
1344
- metafile: void 0,
1345
- mangleCache: void 0
1346
- };
1347
- const originalErrors = result.errors.slice();
1348
- const originalWarnings = result.warnings.slice();
1349
- if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
1350
- if (response.metafile && response.metafile.length) result.metafile = parseJSON(response.metafile);
1351
- if (response.mangleCache) result.mangleCache = response.mangleCache;
1352
- if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1353
- runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
1354
- if (originalErrors.length > 0 || onEndErrors.length > 0) return callback2(failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)), null, onEndErrors, onEndWarnings);
1355
- callback2(null, result, onEndErrors, onEndWarnings);
1356
- });
1357
- };
1358
- let latestResultPromise;
1359
- let provideLatestResult;
1360
- if (isContext) requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
1361
- buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
1362
- const response = {
1363
- errors: onEndErrors,
1364
- warnings: onEndWarnings
1365
- };
1366
- if (provideLatestResult) provideLatestResult(err, result);
1367
- latestResultPromise = void 0;
1368
- provideLatestResult = void 0;
1369
- sendResponse(id, response);
1370
- resolve();
1371
- });
1372
- });
1373
- sendRequest(refs, request, (error, response) => {
1374
- if (error) return callback(new Error(error), null);
1375
- if (!isContext) return buildResponseToResult(response, (err, res) => {
1376
- scheduleOnDisposeCallbacks();
1377
- return callback(err, res);
1378
- });
1379
- if (response.errors.length > 0) return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
1380
- let didDispose = false;
1381
- const result = {
1382
- rebuild: () => {
1383
- if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
1384
- let settlePromise;
1385
- provideLatestResult = (err, result2) => {
1386
- if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
1387
- };
1388
- const triggerAnotherBuild = () => {
1389
- sendRequest(refs, {
1390
- command: "rebuild",
1391
- key: buildKey
1392
- }, (error2, response2) => {
1393
- if (error2) reject(new Error(error2));
1394
- else if (settlePromise) settlePromise();
1395
- else triggerAnotherBuild();
1396
- });
1397
- };
1398
- triggerAnotherBuild();
1399
- });
1400
- return latestResultPromise;
1401
- },
1402
- watch: (options2 = {}) => new Promise((resolve, reject) => {
1403
- if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
1404
- const keys = {};
1405
- const delay = getFlag(options2, keys, "delay", mustBeInteger);
1406
- checkForInvalidFlags(options2, keys, `in watch() call`);
1407
- const request2 = {
1408
- command: "watch",
1409
- key: buildKey
1410
- };
1411
- if (delay) request2.delay = delay;
1412
- sendRequest(refs, request2, (error2) => {
1413
- if (error2) reject(new Error(error2));
1414
- else resolve(void 0);
1415
- });
1416
- }),
1417
- serve: (options2 = {}) => new Promise((resolve, reject) => {
1418
- if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
1419
- const keys = {};
1420
- const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
1421
- const host = getFlag(options2, keys, "host", mustBeString);
1422
- const servedir = getFlag(options2, keys, "servedir", mustBeString);
1423
- const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
1424
- const certfile = getFlag(options2, keys, "certfile", mustBeString);
1425
- const fallback = getFlag(options2, keys, "fallback", mustBeString);
1426
- const cors = getFlag(options2, keys, "cors", mustBeObject);
1427
- const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
1428
- checkForInvalidFlags(options2, keys, `in serve() call`);
1429
- const request2 = {
1430
- command: "serve",
1431
- key: buildKey,
1432
- onRequest: !!onRequest
1433
- };
1434
- if (port !== void 0) request2.port = port;
1435
- if (host !== void 0) request2.host = host;
1436
- if (servedir !== void 0) request2.servedir = servedir;
1437
- if (keyfile !== void 0) request2.keyfile = keyfile;
1438
- if (certfile !== void 0) request2.certfile = certfile;
1439
- if (fallback !== void 0) request2.fallback = fallback;
1440
- if (cors) {
1441
- const corsKeys = {};
1442
- const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
1443
- checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
1444
- if (Array.isArray(origin)) request2.corsOrigin = origin;
1445
- else if (origin !== void 0) request2.corsOrigin = [origin];
1446
- }
1447
- sendRequest(refs, request2, (error2, response2) => {
1448
- if (error2) return reject(new Error(error2));
1449
- if (onRequest) requestCallbacks["serve-request"] = (id, request3) => {
1450
- onRequest(request3.args);
1451
- sendResponse(id, {});
1452
- };
1453
- resolve(response2);
1454
- });
1455
- }),
1456
- cancel: () => new Promise((resolve) => {
1457
- if (didDispose) return resolve();
1458
- sendRequest(refs, {
1459
- command: "cancel",
1460
- key: buildKey
1461
- }, () => {
1462
- resolve();
1463
- });
1464
- }),
1465
- dispose: () => new Promise((resolve) => {
1466
- if (didDispose) return resolve();
1467
- didDispose = true;
1468
- sendRequest(refs, {
1469
- command: "dispose",
1470
- key: buildKey
1471
- }, () => {
1472
- resolve();
1473
- scheduleOnDisposeCallbacks();
1474
- refs.unref();
1475
- });
1476
- })
1477
- };
1478
- refs.ref();
1479
- callback(null, result);
1480
- });
1481
- }
1482
- }
1483
- var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
1484
- let onStartCallbacks = [];
1485
- let onEndCallbacks = [];
1486
- let onResolveCallbacks = {};
1487
- let onLoadCallbacks = {};
1488
- let onDisposeCallbacks = [];
1489
- let nextCallbackID = 0;
1490
- let i = 0;
1491
- let requestPlugins = [];
1492
- let isSetupDone = false;
1493
- plugins = [...plugins];
1494
- for (let item of plugins) {
1495
- let keys = {};
1496
- if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
1497
- const name = getFlag(item, keys, "name", mustBeString);
1498
- if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
1499
- try {
1500
- let setup = getFlag(item, keys, "setup", mustBeFunction);
1501
- if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
1502
- checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
1503
- let plugin = {
1504
- name,
1505
- onStart: false,
1506
- onEnd: false,
1507
- onResolve: [],
1508
- onLoad: []
1509
- };
1510
- i++;
1511
- let resolve = (path3, options = {}) => {
1512
- if (!isSetupDone) throw new Error("Cannot call \"resolve\" before plugin setup has completed");
1513
- if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`);
1514
- let keys2 = /* @__PURE__ */ Object.create(null);
1515
- let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
1516
- let importer = getFlag(options, keys2, "importer", mustBeString);
1517
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
1518
- let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
1519
- let kind = getFlag(options, keys2, "kind", mustBeString);
1520
- let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
1521
- let importAttributes = getFlag(options, keys2, "with", mustBeObject);
1522
- checkForInvalidFlags(options, keys2, "in resolve() call");
1523
- return new Promise((resolve2, reject) => {
1524
- const request = {
1525
- command: "resolve",
1526
- path: path3,
1527
- key: buildKey,
1528
- pluginName: name
1529
- };
1530
- if (pluginName != null) request.pluginName = pluginName;
1531
- if (importer != null) request.importer = importer;
1532
- if (namespace != null) request.namespace = namespace;
1533
- if (resolveDir != null) request.resolveDir = resolveDir;
1534
- if (kind != null) request.kind = kind;
1535
- else throw new Error(`Must specify "kind" when calling "resolve"`);
1536
- if (pluginData != null) request.pluginData = details.store(pluginData);
1537
- if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
1538
- sendRequest(refs, request, (error, response) => {
1539
- if (error !== null) reject(new Error(error));
1540
- else resolve2({
1541
- errors: replaceDetailsInMessages(response.errors, details),
1542
- warnings: replaceDetailsInMessages(response.warnings, details),
1543
- path: response.path,
1544
- external: response.external,
1545
- sideEffects: response.sideEffects,
1546
- namespace: response.namespace,
1547
- suffix: response.suffix,
1548
- pluginData: details.load(response.pluginData)
1549
- });
1550
- });
1551
- });
1552
- };
1553
- let promise = setup({
1554
- initialOptions,
1555
- resolve,
1556
- onStart(callback) {
1557
- let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onStart" callback registered here:`), streamIn, "onStart");
1558
- onStartCallbacks.push({
1559
- name,
1560
- callback,
1561
- note: registeredNote
1562
- });
1563
- plugin.onStart = true;
1564
- },
1565
- onEnd(callback) {
1566
- let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onEnd" callback registered here:`), streamIn, "onEnd");
1567
- onEndCallbacks.push({
1568
- name,
1569
- callback,
1570
- note: registeredNote
1571
- });
1572
- plugin.onEnd = true;
1573
- },
1574
- onResolve(options, callback) {
1575
- let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onResolve" callback registered here:`), streamIn, "onResolve");
1576
- let keys2 = {};
1577
- let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1578
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
1579
- checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
1580
- if (filter == null) throw new Error(`onResolve() call is missing a filter`);
1581
- let id = nextCallbackID++;
1582
- onResolveCallbacks[id] = {
1583
- name,
1584
- callback,
1585
- note: registeredNote
1586
- };
1587
- plugin.onResolve.push({
1588
- id,
1589
- filter: jsRegExpToGoRegExp(filter),
1590
- namespace: namespace || ""
1591
- });
1592
- },
1593
- onLoad(options, callback) {
1594
- let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onLoad" callback registered here:`), streamIn, "onLoad");
1595
- let keys2 = {};
1596
- let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1597
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
1598
- checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
1599
- if (filter == null) throw new Error(`onLoad() call is missing a filter`);
1600
- let id = nextCallbackID++;
1601
- onLoadCallbacks[id] = {
1602
- name,
1603
- callback,
1604
- note: registeredNote
1605
- };
1606
- plugin.onLoad.push({
1607
- id,
1608
- filter: jsRegExpToGoRegExp(filter),
1609
- namespace: namespace || ""
1610
- });
1611
- },
1612
- onDispose(callback) {
1613
- onDisposeCallbacks.push(callback);
1614
- },
1615
- esbuild: streamIn.esbuild
1616
- });
1617
- if (promise) await promise;
1618
- requestPlugins.push(plugin);
1619
- } catch (e) {
1620
- return {
1621
- ok: false,
1622
- error: e,
1623
- pluginName: name
1624
- };
1625
- }
1626
- }
1627
- requestCallbacks["on-start"] = async (id, request) => {
1628
- details.clear();
1629
- let response = {
1630
- errors: [],
1631
- warnings: []
1632
- };
1633
- await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
1634
- try {
1635
- let result = await callback();
1636
- if (result != null) {
1637
- if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
1638
- let keys = {};
1639
- let errors = getFlag(result, keys, "errors", mustBeArray);
1640
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
1641
- checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
1642
- if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
1643
- if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
1644
- }
1645
- } catch (e) {
1646
- response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
1647
- }
1648
- }));
1649
- sendResponse(id, response);
1650
- };
1651
- requestCallbacks["on-resolve"] = async (id, request) => {
1652
- let response = {}, name = "", callback, note;
1653
- for (let id2 of request.ids) try {
1654
- ({name, callback, note} = onResolveCallbacks[id2]);
1655
- let result = await callback({
1656
- path: request.path,
1657
- importer: request.importer,
1658
- namespace: request.namespace,
1659
- resolveDir: request.resolveDir,
1660
- kind: request.kind,
1661
- pluginData: details.load(request.pluginData),
1662
- with: request.with
1663
- });
1664
- if (result != null) {
1665
- if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
1666
- let keys = {};
1667
- let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1668
- let path3 = getFlag(result, keys, "path", mustBeString);
1669
- let namespace = getFlag(result, keys, "namespace", mustBeString);
1670
- let suffix = getFlag(result, keys, "suffix", mustBeString);
1671
- let external = getFlag(result, keys, "external", mustBeBoolean);
1672
- let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
1673
- let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1674
- let errors = getFlag(result, keys, "errors", mustBeArray);
1675
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
1676
- let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1677
- let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1678
- checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
1679
- response.id = id2;
1680
- if (pluginName != null) response.pluginName = pluginName;
1681
- if (path3 != null) response.path = path3;
1682
- if (namespace != null) response.namespace = namespace;
1683
- if (suffix != null) response.suffix = suffix;
1684
- if (external != null) response.external = external;
1685
- if (sideEffects != null) response.sideEffects = sideEffects;
1686
- if (pluginData != null) response.pluginData = details.store(pluginData);
1687
- if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1688
- if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1689
- if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1690
- if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1691
- break;
1692
- }
1693
- } catch (e) {
1694
- response = {
1695
- id: id2,
1696
- errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
1697
- };
1698
- break;
1699
- }
1700
- sendResponse(id, response);
1701
- };
1702
- requestCallbacks["on-load"] = async (id, request) => {
1703
- let response = {}, name = "", callback, note;
1704
- for (let id2 of request.ids) try {
1705
- ({name, callback, note} = onLoadCallbacks[id2]);
1706
- let result = await callback({
1707
- path: request.path,
1708
- namespace: request.namespace,
1709
- suffix: request.suffix,
1710
- pluginData: details.load(request.pluginData),
1711
- with: request.with
1712
- });
1713
- if (result != null) {
1714
- if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
1715
- let keys = {};
1716
- let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1717
- let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
1718
- let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
1719
- let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1720
- let loader = getFlag(result, keys, "loader", mustBeString);
1721
- let errors = getFlag(result, keys, "errors", mustBeArray);
1722
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
1723
- let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1724
- let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1725
- checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
1726
- response.id = id2;
1727
- if (pluginName != null) response.pluginName = pluginName;
1728
- if (contents instanceof Uint8Array) response.contents = contents;
1729
- else if (contents != null) response.contents = encodeUTF8(contents);
1730
- if (resolveDir != null) response.resolveDir = resolveDir;
1731
- if (pluginData != null) response.pluginData = details.store(pluginData);
1732
- if (loader != null) response.loader = loader;
1733
- if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1734
- if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1735
- if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1736
- if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1737
- break;
1738
- }
1739
- } catch (e) {
1740
- response = {
1741
- id: id2,
1742
- errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
1743
- };
1744
- break;
1745
- }
1746
- sendResponse(id, response);
1747
- };
1748
- let runOnEndCallbacks = (result, done) => done([], []);
1749
- if (onEndCallbacks.length > 0) runOnEndCallbacks = (result, done) => {
1750
- (async () => {
1751
- const onEndErrors = [];
1752
- const onEndWarnings = [];
1753
- for (const { name, callback, note } of onEndCallbacks) {
1754
- let newErrors;
1755
- let newWarnings;
1756
- try {
1757
- const value = await callback(result);
1758
- if (value != null) {
1759
- if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1760
- let keys = {};
1761
- let errors = getFlag(value, keys, "errors", mustBeArray);
1762
- let warnings = getFlag(value, keys, "warnings", mustBeArray);
1763
- checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1764
- if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
1765
- if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1766
- }
1767
- } catch (e) {
1768
- newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1769
- }
1770
- if (newErrors) {
1771
- onEndErrors.push(...newErrors);
1772
- try {
1773
- result.errors.push(...newErrors);
1774
- } catch {}
1775
- }
1776
- if (newWarnings) {
1777
- onEndWarnings.push(...newWarnings);
1778
- try {
1779
- result.warnings.push(...newWarnings);
1780
- } catch {}
1781
- }
1782
- }
1783
- done(onEndErrors, onEndWarnings);
1784
- })();
1785
- };
1786
- let scheduleOnDisposeCallbacks = () => {
1787
- for (const cb of onDisposeCallbacks) setTimeout(() => cb(), 0);
1788
- };
1789
- isSetupDone = true;
1790
- return {
1791
- ok: true,
1792
- requestPlugins,
1793
- runOnEndCallbacks,
1794
- scheduleOnDisposeCallbacks
1795
- };
1796
- };
1797
- function createObjectStash() {
1798
- const map = /* @__PURE__ */ new Map();
1799
- let nextID = 0;
1800
- return {
1801
- clear() {
1802
- map.clear();
1803
- },
1804
- load(id) {
1805
- return map.get(id);
1806
- },
1807
- store(value) {
1808
- if (value === void 0) return -1;
1809
- const id = nextID++;
1810
- map.set(id, value);
1811
- return id;
1812
- }
1813
- };
1814
- }
1815
- function extractCallerV8(e, streamIn, ident) {
1816
- let note;
1817
- let tried = false;
1818
- return () => {
1819
- if (tried) return note;
1820
- tried = true;
1821
- try {
1822
- let lines = (e.stack + "").split("\n");
1823
- lines.splice(1, 1);
1824
- let location = parseStackLinesV8(streamIn, lines, ident);
1825
- if (location) {
1826
- note = {
1827
- text: e.message,
1828
- location
1829
- };
1830
- return note;
1831
- }
1832
- } catch {}
1833
- };
1834
- }
1835
- function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1836
- let text = "Internal error";
1837
- let location = null;
1838
- try {
1839
- text = (e && e.message || e) + "";
1840
- } catch {}
1841
- try {
1842
- location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
1843
- } catch {}
1844
- return {
1845
- id: "",
1846
- pluginName,
1847
- text,
1848
- location,
1849
- notes: note ? [note] : [],
1850
- detail: stash ? stash.store(e) : -1
1851
- };
1852
- }
1853
- function parseStackLinesV8(streamIn, lines, ident) {
1854
- let at = " at ";
1855
- if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) for (let i = 1; i < lines.length; i++) {
1856
- let line = lines[i];
1857
- if (!line.startsWith(at)) continue;
1858
- line = line.slice(7);
1859
- while (true) {
1860
- let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
1861
- if (match) {
1862
- line = match[1];
1863
- continue;
1864
- }
1865
- match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
1866
- if (match) {
1867
- line = match[1];
1868
- continue;
1869
- }
1870
- match = /^(\S+):(\d+):(\d+)$/.exec(line);
1871
- if (match) {
1872
- let contents;
1873
- try {
1874
- contents = streamIn.readFileSync(match[1], "utf8");
1875
- } catch {
1876
- break;
1877
- }
1878
- let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
1879
- let column = +match[3] - 1;
1880
- let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
1881
- return {
1882
- file: match[1],
1883
- namespace: "file",
1884
- line: +match[2],
1885
- column: encodeUTF8(lineText.slice(0, column)).length,
1886
- length: encodeUTF8(lineText.slice(column, column + length)).length,
1887
- lineText: lineText + "\n" + lines.slice(1).join("\n"),
1888
- suggestion: ""
1889
- };
1890
- }
1891
- break;
1892
- }
1893
- }
1894
- return null;
1895
- }
1896
- function failureErrorWithLog(text, errors, warnings) {
1897
- let limit = 5;
1898
- text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, 6).map((e, i) => {
1899
- if (i === limit) return "\n...";
1900
- if (!e.location) return `
1901
- error: ${e.text}`;
1902
- let { file, line, column } = e.location;
1903
- return `
1904
- ${file}:${line}:${column}: ERROR: ${e.pluginName ? `[plugin: ${e.pluginName}] ` : ""}${e.text}`;
1905
- }).join("");
1906
- let error = new Error(text);
1907
- for (const [key, value] of [["errors", errors], ["warnings", warnings]]) Object.defineProperty(error, key, {
1908
- configurable: true,
1909
- enumerable: true,
1910
- get: () => value,
1911
- set: (value2) => Object.defineProperty(error, key, {
1912
- configurable: true,
1913
- enumerable: true,
1914
- value: value2
1915
- })
1916
- });
1917
- return error;
1918
- }
1919
- function replaceDetailsInMessages(messages, stash) {
1920
- for (const message of messages) message.detail = stash.load(message.detail);
1921
- return messages;
1922
- }
1923
- function sanitizeLocation(location, where, terminalWidth) {
1924
- if (location == null) return null;
1925
- let keys = {};
1926
- let file = getFlag(location, keys, "file", mustBeString);
1927
- let namespace = getFlag(location, keys, "namespace", mustBeString);
1928
- let line = getFlag(location, keys, "line", mustBeInteger);
1929
- let column = getFlag(location, keys, "column", mustBeInteger);
1930
- let length = getFlag(location, keys, "length", mustBeInteger);
1931
- let lineText = getFlag(location, keys, "lineText", mustBeString);
1932
- let suggestion = getFlag(location, keys, "suggestion", mustBeString);
1933
- checkForInvalidFlags(location, keys, where);
1934
- if (lineText) {
1935
- const relevantASCII = lineText.slice(0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80));
1936
- if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) lineText = relevantASCII;
1937
- }
1938
- return {
1939
- file: file || "",
1940
- namespace: namespace || "",
1941
- line: line || 0,
1942
- column: column || 0,
1943
- length: length || 0,
1944
- lineText: lineText || "",
1945
- suggestion: suggestion || ""
1946
- };
1947
- }
1948
- function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
1949
- let messagesClone = [];
1950
- let index = 0;
1951
- for (const message of messages) {
1952
- let keys = {};
1953
- let id = getFlag(message, keys, "id", mustBeString);
1954
- let pluginName = getFlag(message, keys, "pluginName", mustBeString);
1955
- let text = getFlag(message, keys, "text", mustBeString);
1956
- let location = getFlag(message, keys, "location", mustBeObjectOrNull);
1957
- let notes = getFlag(message, keys, "notes", mustBeArray);
1958
- let detail = getFlag(message, keys, "detail", canBeAnything);
1959
- let where = `in element ${index} of "${property}"`;
1960
- checkForInvalidFlags(message, keys, where);
1961
- let notesClone = [];
1962
- if (notes) for (const note of notes) {
1963
- let noteKeys = {};
1964
- let noteText = getFlag(note, noteKeys, "text", mustBeString);
1965
- let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
1966
- checkForInvalidFlags(note, noteKeys, where);
1967
- notesClone.push({
1968
- text: noteText || "",
1969
- location: sanitizeLocation(noteLocation, where, terminalWidth)
1970
- });
1971
- }
1972
- messagesClone.push({
1973
- id: id || "",
1974
- pluginName: pluginName || fallbackPluginName,
1975
- text: text || "",
1976
- location: sanitizeLocation(location, where, terminalWidth),
1977
- notes: notesClone,
1978
- detail: stash ? stash.store(detail) : -1
1979
- });
1980
- index++;
1981
- }
1982
- return messagesClone;
1983
- }
1984
- function sanitizeStringArray(values, property) {
1985
- const result = [];
1986
- for (const value of values) {
1987
- if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
1988
- result.push(value);
1989
- }
1990
- return result;
1991
- }
1992
- function sanitizeStringMap(map, property) {
1993
- const result = /* @__PURE__ */ Object.create(null);
1994
- for (const key in map) {
1995
- const value = map[key];
1996
- if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
1997
- result[key] = value;
1998
- }
1999
- return result;
2000
- }
2001
- function convertOutputFiles({ path: path3, contents, hash }) {
2002
- let text = null;
2003
- return {
2004
- path: path3,
2005
- contents,
2006
- hash,
2007
- get text() {
2008
- const binary = this.contents;
2009
- if (text === null || binary !== contents) {
2010
- contents = binary;
2011
- text = decodeUTF8(binary);
2012
- }
2013
- return text;
2014
- }
2015
- };
2016
- }
2017
- function jsRegExpToGoRegExp(regexp) {
2018
- let result = regexp.source;
2019
- if (regexp.flags) result = `(?${regexp.flags})${result}`;
2020
- return result;
2021
- }
2022
- function parseJSON(bytes) {
2023
- let text;
2024
- try {
2025
- text = decodeUTF8(bytes);
2026
- } catch {
2027
- return JSON_parse(bytes);
2028
- }
2029
- return JSON.parse(text);
2030
- }
2031
- var fs = __require("fs");
2032
- var os = __require("os");
2033
- var path = __require("path");
2034
- var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
2035
- var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
2036
- var packageDarwin_arm64 = "@esbuild/darwin-arm64";
2037
- var packageDarwin_x64 = "@esbuild/darwin-x64";
2038
- var knownWindowsPackages = {
2039
- "win32 arm64 LE": "@esbuild/win32-arm64",
2040
- "win32 ia32 LE": "@esbuild/win32-ia32",
2041
- "win32 x64 LE": "@esbuild/win32-x64"
2042
- };
2043
- var knownUnixlikePackages = {
2044
- "aix ppc64 BE": "@esbuild/aix-ppc64",
2045
- "android arm64 LE": "@esbuild/android-arm64",
2046
- "darwin arm64 LE": "@esbuild/darwin-arm64",
2047
- "darwin x64 LE": "@esbuild/darwin-x64",
2048
- "freebsd arm64 LE": "@esbuild/freebsd-arm64",
2049
- "freebsd x64 LE": "@esbuild/freebsd-x64",
2050
- "linux arm LE": "@esbuild/linux-arm",
2051
- "linux arm64 LE": "@esbuild/linux-arm64",
2052
- "linux ia32 LE": "@esbuild/linux-ia32",
2053
- "linux mips64el LE": "@esbuild/linux-mips64el",
2054
- "linux ppc64 LE": "@esbuild/linux-ppc64",
2055
- "linux riscv64 LE": "@esbuild/linux-riscv64",
2056
- "linux s390x BE": "@esbuild/linux-s390x",
2057
- "linux x64 LE": "@esbuild/linux-x64",
2058
- "linux loong64 LE": "@esbuild/linux-loong64",
2059
- "netbsd arm64 LE": "@esbuild/netbsd-arm64",
2060
- "netbsd x64 LE": "@esbuild/netbsd-x64",
2061
- "openbsd arm64 LE": "@esbuild/openbsd-arm64",
2062
- "openbsd x64 LE": "@esbuild/openbsd-x64",
2063
- "sunos x64 LE": "@esbuild/sunos-x64"
2064
- };
2065
- var knownWebAssemblyFallbackPackages = {
2066
- "android arm LE": "@esbuild/android-arm",
2067
- "android x64 LE": "@esbuild/android-x64",
2068
- "openharmony arm64 LE": "@esbuild/openharmony-arm64"
2069
- };
2070
- function pkgAndSubpathForCurrentPlatform() {
2071
- let pkg;
2072
- let subpath;
2073
- let isWASM = false;
2074
- let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
2075
- if (platformKey in knownWindowsPackages) {
2076
- pkg = knownWindowsPackages[platformKey];
2077
- subpath = "esbuild.exe";
2078
- } else if (platformKey in knownUnixlikePackages) {
2079
- pkg = knownUnixlikePackages[platformKey];
2080
- subpath = "bin/esbuild";
2081
- } else if (platformKey in knownWebAssemblyFallbackPackages) {
2082
- pkg = knownWebAssemblyFallbackPackages[platformKey];
2083
- subpath = "bin/esbuild";
2084
- isWASM = true;
2085
- } else throw new Error(`Unsupported platform: ${platformKey}`);
2086
- return {
2087
- pkg,
2088
- subpath,
2089
- isWASM
2090
- };
2091
- }
2092
- function pkgForSomeOtherPlatform() {
2093
- const libMainJS = __require.resolve("esbuild");
2094
- const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
2095
- if (path.basename(nodeModulesDirectory) === "node_modules") {
2096
- for (const unixKey in knownUnixlikePackages) try {
2097
- const pkg = knownUnixlikePackages[unixKey];
2098
- if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
2099
- } catch {}
2100
- for (const windowsKey in knownWindowsPackages) try {
2101
- const pkg = knownWindowsPackages[windowsKey];
2102
- if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
2103
- } catch {}
2104
- }
2105
- return null;
2106
- }
2107
- function downloadedBinPath(pkg, subpath) {
2108
- const esbuildLibDir = path.dirname(__require.resolve("esbuild"));
2109
- return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
2110
- }
2111
- function generateBinPath() {
2112
- if (isValidBinaryPath(ESBUILD_BINARY_PATH)) if (!fs.existsSync(ESBUILD_BINARY_PATH)) console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
2113
- else return {
2114
- binPath: ESBUILD_BINARY_PATH,
2115
- isWASM: false
2116
- };
2117
- const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
2118
- let binPath;
2119
- try {
2120
- binPath = __require.resolve(`${pkg}/${subpath}`);
2121
- } catch (e) {
2122
- binPath = downloadedBinPath(pkg, subpath);
2123
- if (!fs.existsSync(binPath)) {
2124
- try {
2125
- __require.resolve(pkg);
2126
- } catch {
2127
- const otherPkg = pkgForSomeOtherPlatform();
2128
- if (otherPkg) {
2129
- let suggestions = `
2130
- Specifically the "${otherPkg}" package is present but this platform
2131
- needs the "${pkg}" package instead. People often get into this
2132
- situation by installing esbuild on Windows or macOS and copying "node_modules"
2133
- into a Docker image that runs Linux, or by copying "node_modules" between
2134
- Windows and WSL environments.
2135
-
2136
- If you are installing with npm, you can try not copying the "node_modules"
2137
- directory when you copy the files over, and running "npm ci" or "npm install"
2138
- on the destination platform after the copy. Or you could consider using yarn
2139
- instead of npm which has built-in support for installing a package on multiple
2140
- platforms simultaneously.
2141
-
2142
- If you are installing with yarn, you can try listing both this platform and the
2143
- other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
2144
- feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
2145
- Keep in mind that this means multiple copies of esbuild will be present.
2146
- `;
2147
- if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) suggestions = `
2148
- Specifically the "${otherPkg}" package is present but this platform
2149
- needs the "${pkg}" package instead. People often get into this
2150
- situation by installing esbuild with npm running inside of Rosetta 2 and then
2151
- trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
2152
- 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
2153
-
2154
- If you are installing with npm, you can try ensuring that both npm and node are
2155
- not running under Rosetta 2 and then reinstalling esbuild. This likely involves
2156
- changing how you installed npm and/or node. For example, installing node with
2157
- the universal installer here should work: https://nodejs.org/en/download/. Or
2158
- you could consider using yarn instead of npm which has built-in support for
2159
- installing a package on multiple platforms simultaneously.
2160
-
2161
- If you are installing with yarn, you can try listing both "arm64" and "x64"
2162
- in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
2163
- https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
2164
- Keep in mind that this means multiple copies of esbuild will be present.
2165
- `;
2166
- throw new Error(`
2167
- You installed esbuild for another platform than the one you're currently using.
2168
- This won't work because esbuild is written with native code and needs to
2169
- install a platform-specific binary executable.
2170
- ${suggestions}
2171
- Another alternative is to use the "esbuild-wasm" package instead, which works
2172
- the same way on all platforms. But it comes with a heavy performance cost and
2173
- can sometimes be 10x slower than the "esbuild" package, so you may also not
2174
- want to do that.
2175
- `);
2176
- }
2177
- throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
2178
-
2179
- If you are installing esbuild with npm, make sure that you don't specify the
2180
- "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
2181
- of "package.json" is used by esbuild to install the correct binary executable
2182
- for your current platform.`);
2183
- }
2184
- throw e;
2185
- }
2186
- }
2187
- if (/\.zip\//.test(binPath)) {
2188
- let pnpapi;
2189
- try {
2190
- pnpapi = __require("pnpapi");
2191
- } catch (e) {}
2192
- if (pnpapi) {
2193
- const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
2194
- const binTargetPath = path.join(root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-0.27.7-${path.basename(subpath)}`);
2195
- if (!fs.existsSync(binTargetPath)) {
2196
- fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
2197
- fs.copyFileSync(binPath, binTargetPath);
2198
- fs.chmodSync(binTargetPath, 493);
2199
- }
2200
- return {
2201
- binPath: binTargetPath,
2202
- isWASM
2203
- };
2204
- }
2205
- }
2206
- return {
2207
- binPath,
2208
- isWASM
2209
- };
2210
- }
2211
- var child_process = __require("child_process");
2212
- var crypto = __require("crypto");
2213
- var path2 = __require("path");
2214
- var fs2 = __require("fs");
2215
- var os2 = __require("os");
2216
- var tty = __require("tty");
2217
- var worker_threads;
2218
- if (process.env.ESBUILD_WORKER_THREADS !== "0") {
2219
- try {
2220
- worker_threads = __require("worker_threads");
2221
- } catch {}
2222
- let [major, minor] = process.versions.node.split(".");
2223
- if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) worker_threads = void 0;
2224
- }
2225
- var _a;
2226
- var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.27.7";
2227
- var esbuildCommandAndArgs = () => {
2228
- if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) throw new Error(`The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle.
2229
-
2230
- More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.`);
2231
- {
2232
- const { binPath, isWASM } = generateBinPath();
2233
- if (isWASM) return ["node", [binPath]];
2234
- else return [binPath, []];
2235
- }
2236
- };
2237
- var isTTY = () => tty.isatty(2);
2238
- var fsSync = {
2239
- readFile(tempFile, callback) {
2240
- try {
2241
- let contents = fs2.readFileSync(tempFile, "utf8");
2242
- try {
2243
- fs2.unlinkSync(tempFile);
2244
- } catch {}
2245
- callback(null, contents);
2246
- } catch (err) {
2247
- callback(err, null);
2248
- }
2249
- },
2250
- writeFile(contents, callback) {
2251
- try {
2252
- let tempFile = randomFileName();
2253
- fs2.writeFileSync(tempFile, contents);
2254
- callback(tempFile);
2255
- } catch {
2256
- callback(null);
2257
- }
2258
- }
2259
- };
2260
- var fsAsync = {
2261
- readFile(tempFile, callback) {
2262
- try {
2263
- fs2.readFile(tempFile, "utf8", (err, contents) => {
2264
- try {
2265
- fs2.unlink(tempFile, () => callback(err, contents));
2266
- } catch {
2267
- callback(err, contents);
2268
- }
2269
- });
2270
- } catch (err) {
2271
- callback(err, null);
2272
- }
2273
- },
2274
- writeFile(contents, callback) {
2275
- try {
2276
- let tempFile = randomFileName();
2277
- fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
2278
- } catch {
2279
- callback(null);
2280
- }
2281
- }
2282
- };
2283
- var version = "0.27.7";
2284
- var build = (options) => ensureServiceIsRunning().build(options);
2285
- var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
2286
- var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
2287
- var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
2288
- var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
2289
- var buildSync = (options) => {
2290
- if (worker_threads && !isInternalWorkerThread) {
2291
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2292
- return workerThreadService.buildSync(options);
2293
- }
2294
- let result;
2295
- runServiceSync((service) => service.buildOrContext({
2296
- callName: "buildSync",
2297
- refs: null,
2298
- options,
2299
- isTTY: isTTY(),
2300
- defaultWD,
2301
- callback: (err, res) => {
2302
- if (err) throw err;
2303
- result = res;
2304
- }
2305
- }));
2306
- return result;
2307
- };
2308
- var transformSync = (input, options) => {
2309
- if (worker_threads && !isInternalWorkerThread) {
2310
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2311
- return workerThreadService.transformSync(input, options);
2312
- }
2313
- let result;
2314
- runServiceSync((service) => service.transform({
2315
- callName: "transformSync",
2316
- refs: null,
2317
- input,
2318
- options: options || {},
2319
- isTTY: isTTY(),
2320
- fs: fsSync,
2321
- callback: (err, res) => {
2322
- if (err) throw err;
2323
- result = res;
2324
- }
2325
- }));
2326
- return result;
2327
- };
2328
- var formatMessagesSync = (messages, options) => {
2329
- if (worker_threads && !isInternalWorkerThread) {
2330
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2331
- return workerThreadService.formatMessagesSync(messages, options);
2332
- }
2333
- let result;
2334
- runServiceSync((service) => service.formatMessages({
2335
- callName: "formatMessagesSync",
2336
- refs: null,
2337
- messages,
2338
- options,
2339
- callback: (err, res) => {
2340
- if (err) throw err;
2341
- result = res;
2342
- }
2343
- }));
2344
- return result;
2345
- };
2346
- var analyzeMetafileSync = (metafile, options) => {
2347
- if (worker_threads && !isInternalWorkerThread) {
2348
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2349
- return workerThreadService.analyzeMetafileSync(metafile, options);
2350
- }
2351
- let result;
2352
- runServiceSync((service) => service.analyzeMetafile({
2353
- callName: "analyzeMetafileSync",
2354
- refs: null,
2355
- metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2356
- options,
2357
- callback: (err, res) => {
2358
- if (err) throw err;
2359
- result = res;
2360
- }
2361
- }));
2362
- return result;
2363
- };
2364
- var stop = () => {
2365
- if (stopService) stopService();
2366
- if (workerThreadService) workerThreadService.stop();
2367
- return Promise.resolve();
2368
- };
2369
- var initializeWasCalled = false;
2370
- var initialize = (options) => {
2371
- options = validateInitializeOptions(options || {});
2372
- if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
2373
- if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
2374
- if (options.worker) throw new Error(`The "worker" option only works in the browser`);
2375
- if (initializeWasCalled) throw new Error("Cannot call \"initialize\" more than once");
2376
- ensureServiceIsRunning();
2377
- initializeWasCalled = true;
2378
- return Promise.resolve();
2379
- };
2380
- var defaultWD = process.cwd();
2381
- var longLivedService;
2382
- var stopService;
2383
- var ensureServiceIsRunning = () => {
2384
- if (longLivedService) return longLivedService;
2385
- let [command, args] = esbuildCommandAndArgs();
2386
- let child = child_process.spawn(command, args.concat(`--service=0.27.7`, "--ping"), {
2387
- windowsHide: true,
2388
- stdio: [
2389
- "pipe",
2390
- "pipe",
2391
- "inherit"
2392
- ],
2393
- cwd: defaultWD
2394
- });
2395
- let { readFromStdout, afterClose, service } = createChannel({
2396
- writeToStdin(bytes) {
2397
- child.stdin.write(bytes, (err) => {
2398
- if (err) afterClose(err);
2399
- });
2400
- },
2401
- readFileSync: fs2.readFileSync,
2402
- isSync: false,
2403
- hasFS: true,
2404
- esbuild: node_exports
2405
- });
2406
- child.stdin.on("error", afterClose);
2407
- child.on("error", afterClose);
2408
- const stdin = child.stdin;
2409
- const stdout = child.stdout;
2410
- stdout.on("data", readFromStdout);
2411
- stdout.on("end", afterClose);
2412
- stopService = () => {
2413
- stdin.destroy();
2414
- stdout.destroy();
2415
- child.kill();
2416
- initializeWasCalled = false;
2417
- longLivedService = void 0;
2418
- stopService = void 0;
2419
- };
2420
- let refCount = 0;
2421
- child.unref();
2422
- if (stdin.unref) stdin.unref();
2423
- if (stdout.unref) stdout.unref();
2424
- const refs = {
2425
- ref() {
2426
- if (++refCount === 1) child.ref();
2427
- },
2428
- unref() {
2429
- if (--refCount === 0) child.unref();
2430
- }
2431
- };
2432
- longLivedService = {
2433
- build: (options) => new Promise((resolve, reject) => {
2434
- service.buildOrContext({
2435
- callName: "build",
2436
- refs,
2437
- options,
2438
- isTTY: isTTY(),
2439
- defaultWD,
2440
- callback: (err, res) => err ? reject(err) : resolve(res)
2441
- });
2442
- }),
2443
- context: (options) => new Promise((resolve, reject) => service.buildOrContext({
2444
- callName: "context",
2445
- refs,
2446
- options,
2447
- isTTY: isTTY(),
2448
- defaultWD,
2449
- callback: (err, res) => err ? reject(err) : resolve(res)
2450
- })),
2451
- transform: (input, options) => new Promise((resolve, reject) => service.transform({
2452
- callName: "transform",
2453
- refs,
2454
- input,
2455
- options: options || {},
2456
- isTTY: isTTY(),
2457
- fs: fsAsync,
2458
- callback: (err, res) => err ? reject(err) : resolve(res)
2459
- })),
2460
- formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
2461
- callName: "formatMessages",
2462
- refs,
2463
- messages,
2464
- options,
2465
- callback: (err, res) => err ? reject(err) : resolve(res)
2466
- })),
2467
- analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
2468
- callName: "analyzeMetafile",
2469
- refs,
2470
- metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2471
- options,
2472
- callback: (err, res) => err ? reject(err) : resolve(res)
2473
- }))
2474
- };
2475
- return longLivedService;
2476
- };
2477
- var runServiceSync = (callback) => {
2478
- let [command, args] = esbuildCommandAndArgs();
2479
- let stdin = new Uint8Array();
2480
- let { readFromStdout, afterClose, service } = createChannel({
2481
- writeToStdin(bytes) {
2482
- if (stdin.length !== 0) throw new Error("Must run at most one command");
2483
- stdin = bytes;
2484
- },
2485
- isSync: true,
2486
- hasFS: true,
2487
- esbuild: node_exports
2488
- });
2489
- callback(service);
2490
- readFromStdout(child_process.execFileSync(command, args.concat(`--service=0.27.7`), {
2491
- cwd: defaultWD,
2492
- windowsHide: true,
2493
- input: stdin,
2494
- maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2495
- }));
2496
- afterClose(null);
2497
- };
2498
- var randomFileName = () => {
2499
- return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
2500
- };
2501
- var workerThreadService = null;
2502
- var startWorkerThreadService = (worker_threads2) => {
2503
- let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
2504
- let worker = new worker_threads2.Worker(__filename, {
2505
- workerData: {
2506
- workerPort,
2507
- defaultWD,
2508
- esbuildVersion: "0.27.7"
2509
- },
2510
- transferList: [workerPort],
2511
- execArgv: []
2512
- });
2513
- let nextID = 0;
2514
- let fakeBuildError = (text) => {
2515
- let error = /* @__PURE__ */ new Error(`Build failed with 1 error:
2516
- error: ${text}`);
2517
- error.errors = [{
2518
- id: "",
2519
- pluginName: "",
2520
- text,
2521
- location: null,
2522
- notes: [],
2523
- detail: void 0
2524
- }];
2525
- error.warnings = [];
2526
- return error;
2527
- };
2528
- let validateBuildSyncOptions = (options) => {
2529
- if (!options) return;
2530
- let plugins = options.plugins;
2531
- if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2532
- };
2533
- let applyProperties = (object, properties) => {
2534
- for (let key in properties) object[key] = properties[key];
2535
- };
2536
- let runCallSync = (command, args) => {
2537
- let id = nextID++;
2538
- let sharedBuffer = new SharedArrayBuffer(8);
2539
- let sharedBufferView = new Int32Array(sharedBuffer);
2540
- let msg = {
2541
- sharedBuffer,
2542
- id,
2543
- command,
2544
- args
2545
- };
2546
- worker.postMessage(msg);
2547
- let status = Atomics.wait(sharedBufferView, 0, 0);
2548
- if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
2549
- let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2550
- if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2551
- if (reject) {
2552
- applyProperties(reject, properties);
2553
- throw reject;
2554
- }
2555
- return resolve;
2556
- };
2557
- worker.unref();
2558
- return {
2559
- buildSync(options) {
2560
- validateBuildSyncOptions(options);
2561
- return runCallSync("build", [options]);
2562
- },
2563
- transformSync(input, options) {
2564
- return runCallSync("transform", [input, options]);
2565
- },
2566
- formatMessagesSync(messages, options) {
2567
- return runCallSync("formatMessages", [messages, options]);
2568
- },
2569
- analyzeMetafileSync(metafile, options) {
2570
- return runCallSync("analyzeMetafile", [metafile, options]);
2571
- },
2572
- stop() {
2573
- worker.terminate();
2574
- workerThreadService = null;
2575
- }
2576
- };
2577
- };
2578
- var startSyncServiceWorker = () => {
2579
- let workerPort = worker_threads.workerData.workerPort;
2580
- let parentPort = worker_threads.parentPort;
2581
- let extractProperties = (object) => {
2582
- let properties = {};
2583
- if (object && typeof object === "object") for (let key in object) properties[key] = object[key];
2584
- return properties;
2585
- };
2586
- try {
2587
- let service = ensureServiceIsRunning();
2588
- defaultWD = worker_threads.workerData.defaultWD;
2589
- parentPort.on("message", (msg) => {
2590
- (async () => {
2591
- let { sharedBuffer, id, command, args } = msg;
2592
- let sharedBufferView = new Int32Array(sharedBuffer);
2593
- try {
2594
- switch (command) {
2595
- case "build":
2596
- workerPort.postMessage({
2597
- id,
2598
- resolve: await service.build(args[0])
2599
- });
2600
- break;
2601
- case "transform":
2602
- workerPort.postMessage({
2603
- id,
2604
- resolve: await service.transform(args[0], args[1])
2605
- });
2606
- break;
2607
- case "formatMessages":
2608
- workerPort.postMessage({
2609
- id,
2610
- resolve: await service.formatMessages(args[0], args[1])
2611
- });
2612
- break;
2613
- case "analyzeMetafile":
2614
- workerPort.postMessage({
2615
- id,
2616
- resolve: await service.analyzeMetafile(args[0], args[1])
2617
- });
2618
- break;
2619
- default: throw new Error(`Invalid command: ${command}`);
2620
- }
2621
- } catch (reject) {
2622
- workerPort.postMessage({
2623
- id,
2624
- reject,
2625
- properties: extractProperties(reject)
2626
- });
2627
- }
2628
- Atomics.add(sharedBufferView, 0, 1);
2629
- Atomics.notify(sharedBufferView, 0, Infinity);
2630
- })();
2631
- });
2632
- } catch (reject) {
2633
- parentPort.on("message", (msg) => {
2634
- let { sharedBuffer, id } = msg;
2635
- let sharedBufferView = new Int32Array(sharedBuffer);
2636
- workerPort.postMessage({
2637
- id,
2638
- reject,
2639
- properties: extractProperties(reject)
2640
- });
2641
- Atomics.add(sharedBufferView, 0, 1);
2642
- Atomics.notify(sharedBufferView, 0, Infinity);
2643
- });
2644
- }
335
+ if (removeIfEmpty && !Object.keys(value).length) {
336
+ await rm(file, { force: true });
337
+ return;
338
+ }
339
+ await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
340
+ }
341
+ async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
342
+ const existing = await readProviderJsonRecord(file) ?? {};
343
+ const defaults = options.defaults ?? {};
344
+ assertProviderJsonRecord(defaults);
345
+ await persistProviderJsonRecord(file, mergeProviderOutputConfig({
346
+ ...defaults,
347
+ ...existing
348
+ }, value, ownership), options.removeIfEmpty === true);
349
+ }
350
+ function mergeProviderOutputConfig(existing, value, ownership = {}) {
351
+ assertProviderJsonRecord(existing);
352
+ assertProviderJsonRecord(value);
353
+ return {
354
+ ...deleteOwnedFields(existing, ownership),
355
+ ...mergeOwnedArrays(existing, value, ownership.arrays)
2645
356
  };
2646
- if (isInternalWorkerThread) startSyncServiceWorker();
2647
- var node_default = node_exports;
2648
- 0 && (module.exports = {
2649
- analyzeMetafile,
2650
- analyzeMetafileSync,
2651
- build,
2652
- buildSync,
2653
- context,
2654
- formatMessages,
2655
- formatMessagesSync,
2656
- initialize,
2657
- stop,
2658
- transform,
2659
- transformSync,
2660
- version
357
+ }
358
+ function stringifyProviderOutputConfig(value) {
359
+ assertProviderJsonRecord(value);
360
+ return JSON.stringify(value, null, 2);
361
+ }
362
+ async function cleanProviderOutputConfig(file, ownership) {
363
+ if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
364
+ const existing = await readProviderJsonRecord(file);
365
+ if (!existing) return;
366
+ const next = deleteOwnedFields(existing, ownership, true);
367
+ let changed = (ownership.keys ?? []).some((key) => key in existing);
368
+ for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
369
+ if (arrayOwnership.preserveOnCleanup) continue;
370
+ if (!(field in existing)) continue;
371
+ const current = existing[field];
372
+ const retained = arrayOwnership.retainOnCleanup ?? [];
373
+ const preserved = [...preserveUnownedKeyedArrayEntries(current, arrayOwnership, retained), ...retained];
374
+ changed ||= retained.length > 0 || !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
375
+ if (preserved.length) next[field] = preserved;
376
+ }
377
+ if (!changed) return;
378
+ await persistProviderJsonRecord(file, next, true);
379
+ }
380
+ //#endregion
381
+ //#region ../internal/src/build/user-entry.ts
382
+ function toSafeAppName(rootDir) {
383
+ return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
384
+ }
385
+ //#endregion
386
+ //#region ../internal/src/build/cloudflare.ts
387
+ function createDefaultCloudflareOutputRoot(rootDir) {
388
+ return resolve(rootDir, "dist", toSafeAppName(rootDir));
389
+ }
390
+ async function writeCloudflareWranglerConfig(options) {
391
+ const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
392
+ const configFile = resolve(outputRoot, "wrangler.json");
393
+ if (!options.wranglerConfig) {
394
+ await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
395
+ return;
396
+ }
397
+ await mkdir(outputRoot, { recursive: true });
398
+ await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, {
399
+ defaults: options.wranglerConfigDefaults,
400
+ removeIfEmpty: true
2661
401
  });
2662
- })))();
402
+ }
403
+ //#endregion
404
+ //#region ../internal/src/build/bundle-options.ts
405
+ const encodedAliasPrefixMarker = "\0vitehub-prefix:";
406
+ const encodedAliasExactMarker = "\0vitehub-exact:";
407
+ /** Select the runtime constants from one resolved Vite configuration. */
408
+ function resolveViteHubBundleDefines(config) {
409
+ const defines = {};
410
+ for (const name of ["__VITEHUB_PUBLIC_URL__", "__VITEHUB_APP_BASE_URL__"]) {
411
+ const value = config.define?.[name];
412
+ if (typeof value === "string") defines[name] = value;
413
+ }
414
+ return defines;
415
+ }
416
+ //#endregion
417
+ //#region ../internal/src/build/esbuild.ts
2663
418
  const viteRawNamespace = "vitehub-vite-raw";
2664
419
  const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
2665
420
  const markdownTemplateFileSuffix = ".template.md";
2666
421
  const markdownTemplateModuleQuery = "markdown-template";
2667
422
  const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
2668
423
  const skipResolvedAlias = "vitehubSkipResolvedAlias";
2669
- const encodedAliasPrefixMarker = "\0vitehub-prefix:";
2670
- const encodedAliasExactMarker = "\0vitehub-exact:";
2671
424
  const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
2672
425
  function normalizePathSeparators(path) {
2673
426
  return path.replaceAll("\\", "/");
@@ -2677,9 +430,9 @@ function escapeRegExp(value) {
2677
430
  }
2678
431
  function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
2679
432
  if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
2680
- if (!Array.isArray(exportsValue) && !isPlainObject(exportsValue)) return [];
433
+ if (!Array.isArray(exportsValue) && !isRecord(exportsValue)) return [];
2681
434
  const candidates = [];
2682
- const exportEntries = isPlainObject(exportsValue) && Object.keys(exportsValue).some((exportKey) => exportKey.startsWith(".")) ? Object.entries(exportsValue) : [[".", exportsValue]];
435
+ const exportEntries = isRecord(exportsValue) && Object.keys(exportsValue).some((exportKey) => exportKey.startsWith(".")) ? Object.entries(exportsValue) : [[".", exportsValue]];
2683
436
  for (const [exportKey, target] of exportEntries) {
2684
437
  const targets = [target];
2685
438
  while (targets.length) {
@@ -2696,12 +449,12 @@ function collectPackageExportCandidates(packageName, exportsValue, packageRelati
2696
449
  if (wildcard === void 0) continue;
2697
450
  candidates.push(`${packageName}${exportKey.slice(1).replace("*", wildcard)}`);
2698
451
  } else if (Array.isArray(value)) targets.push(...value);
2699
- else if (isPlainObject(value)) targets.push(...Object.values(value));
452
+ else if (isRecord(value)) targets.push(...Object.values(value));
2700
453
  }
2701
454
  }
2702
455
  return candidates;
2703
456
  }
2704
- function createResolvedAliasPlugin(aliases, aliasResolveDir) {
457
+ function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackageAliases = true) {
2705
458
  const entries = Object.entries(aliases || {});
2706
459
  if (!entries.length) return;
2707
460
  const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
@@ -2727,6 +480,17 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
2727
480
  const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
2728
481
  build.onResolve({ filter: /.*/ }, async (args) => {
2729
482
  if (args.pluginData?.[skipResolvedAlias]) return;
483
+ const resolveWithContext = (specifier) => build.resolve(specifier, {
484
+ importer: args.importer,
485
+ kind: args.kind,
486
+ namespace: args.namespace,
487
+ pluginData: {
488
+ ...args.pluginData,
489
+ [skipResolvedAlias]: true
490
+ },
491
+ resolveDir: args.resolveDir,
492
+ with: args.with
493
+ });
2730
494
  const aliases = await resolvedEntries;
2731
495
  let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
2732
496
  let matchedAlias = match?.specifier;
@@ -2743,128 +507,109 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
2743
507
  await canonicalizeSpecifier();
2744
508
  match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
2745
509
  }
2746
- if (!match && isAbsolute(args.path)) for (const alias of aliases) {
2747
- if (isAbsolute(alias.specifier)) continue;
2748
- const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
2749
- const aliasSegments = packageAlias.split("/");
2750
- if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
2751
- let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
2752
- if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
2753
- const scopeMarker = `/node_modules/${packageAlias}/`;
2754
- const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
2755
- const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
2756
- if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
2757
- }
2758
- const packageMarker = `/node_modules/${packageName}/`;
2759
- const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
2760
- const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
2761
- const cacheKey = [
2762
- alias.specifier,
2763
- alias.prefix,
2764
- resolutionScope,
2765
- args.importer,
2766
- args.resolveDir,
2767
- args.kind,
2768
- args.namespace,
2769
- JSON.stringify(args.with)
2770
- ].join("\0");
2771
- let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
2772
- if (!resolution) {
2773
- resolution = (async () => {
2774
- let resolvedAliasPath;
2775
- if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
2776
- else if (resolutionScope) {
2777
- const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
2778
- const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
2779
- if (!isPlainObject(parsedPackageJson)) return;
2780
- const packageJson = parsedPackageJson;
2781
- if (packageJson.exports === void 0 && !alias.prefix) {
2782
- const resolvedCandidate = await build.resolve(alias.specifier, {
2783
- importer: args.importer,
2784
- kind: args.kind,
2785
- namespace: args.namespace,
2786
- pluginData: {
2787
- ...args.pluginData,
2788
- [skipResolvedAlias]: true
2789
- },
2790
- resolveDir: args.resolveDir,
2791
- with: args.with
2792
- });
2793
- if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
2794
- canonical: alias.specifier,
2795
- normalized: alias.specifier,
2796
- publicSpecifier: alias.specifier
2797
- };
510
+ if (!match && (resolveEntryPackageAliases || args.kind !== "entry-point") && isAbsolute(args.path)) {
511
+ const candidates = [];
512
+ for (const alias of aliases) {
513
+ if (isAbsolute(alias.specifier)) continue;
514
+ const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
515
+ const aliasSegments = packageAlias.split("/");
516
+ if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
517
+ let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
518
+ if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
519
+ const scopeMarker = `/node_modules/${packageAlias}/`;
520
+ const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
521
+ const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
522
+ if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
523
+ }
524
+ const packageMarker = `/node_modules/${packageName}/`;
525
+ const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
526
+ const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
527
+ const cacheKey = [
528
+ alias.specifier,
529
+ alias.prefix,
530
+ resolutionScope,
531
+ normalizedSpecifier,
532
+ args.importer,
533
+ args.resolveDir,
534
+ args.kind,
535
+ args.namespace,
536
+ JSON.stringify(args.with)
537
+ ].join("\0");
538
+ let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
539
+ if (!resolution) {
540
+ resolution = (async () => {
541
+ let resolvedAliasPath;
542
+ if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
543
+ else if (resolutionScope) {
544
+ const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
545
+ const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
546
+ if (!isRecord(parsedPackageJson)) return;
547
+ const packageJson = parsedPackageJson;
548
+ if (packageJson.exports === void 0 && !alias.prefix) {
549
+ const resolvedCandidate = await resolveWithContext(alias.specifier);
550
+ if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
551
+ canonical: alias.specifier,
552
+ normalized: alias.specifier,
553
+ publicSpecifier: alias.specifier
554
+ };
555
+ return;
556
+ }
557
+ const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
558
+ for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
559
+ const resolvedCandidate = await resolveWithContext(publicSpecifier);
560
+ if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
561
+ if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
562
+ matchingPublicSpecifiers.add(publicSpecifier);
563
+ }
564
+ if (matchingPublicSpecifiers.size === 1) {
565
+ const publicSpecifier = [...matchingPublicSpecifiers][0];
566
+ if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
567
+ canonical: publicSpecifier,
568
+ normalized: publicSpecifier,
569
+ publicSpecifier
570
+ };
571
+ }
2798
572
  return;
573
+ } else {
574
+ const resolvedAlias = await resolveWithContext(alias.specifier);
575
+ if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
576
+ resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
2799
577
  }
2800
- const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
2801
- for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
2802
- const resolvedCandidate = await build.resolve(publicSpecifier, {
2803
- importer: args.importer,
2804
- kind: args.kind,
2805
- namespace: args.namespace,
2806
- pluginData: {
2807
- ...args.pluginData,
2808
- [skipResolvedAlias]: true
2809
- },
2810
- resolveDir: args.resolveDir,
2811
- with: args.with
2812
- });
2813
- if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
2814
- if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
2815
- matchingPublicSpecifiers.add(publicSpecifier);
2816
- }
2817
- if (matchingPublicSpecifiers.size === 1) {
2818
- const publicSpecifier = [...matchingPublicSpecifiers][0];
2819
- if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
2820
- canonical: publicSpecifier,
2821
- normalized: publicSpecifier,
2822
- publicSpecifier
2823
- };
2824
- }
2825
- return;
2826
- } else {
2827
- const resolvedAlias = await build.resolve(alias.specifier, {
2828
- importer: args.importer,
2829
- kind: args.kind,
2830
- namespace: args.namespace,
2831
- pluginData: {
2832
- ...args.pluginData,
2833
- [skipResolvedAlias]: true
2834
- },
2835
- resolveDir: args.resolveDir,
2836
- with: args.with
2837
- });
2838
- if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
2839
- resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
2840
- }
2841
- const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
2842
- return {
2843
- canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
2844
- normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
2845
- };
2846
- })();
2847
- if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
2848
- }
2849
- const paths = await resolution;
2850
- if (!paths) continue;
2851
- if (paths.publicSpecifier) {
2852
- match = alias;
2853
- matchedAlias = alias.specifier;
2854
- matchedSpecifier = paths.publicSpecifier;
2855
- break;
2856
- }
2857
- const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
2858
- let canonicalMatch = false;
2859
- if (!normalizedMatch && paths.canonical !== paths.normalized) {
2860
- await canonicalizeSpecifier();
2861
- canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
578
+ const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
579
+ return {
580
+ canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
581
+ normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
582
+ };
583
+ })();
584
+ if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
585
+ }
586
+ candidates.push({
587
+ alias,
588
+ resolution
589
+ });
2862
590
  }
2863
- if (normalizedMatch || canonicalMatch) {
2864
- match = alias;
2865
- matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
2866
- matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
2867
- break;
591
+ await Promise.allSettled(candidates.map((candidate) => candidate.resolution));
592
+ for (const { alias, resolution } of candidates) {
593
+ const paths = await resolution;
594
+ if (!paths) continue;
595
+ if (paths.publicSpecifier) {
596
+ match = alias;
597
+ matchedAlias = alias.specifier;
598
+ matchedSpecifier = paths.publicSpecifier;
599
+ break;
600
+ }
601
+ const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
602
+ let canonicalMatch = false;
603
+ if (!normalizedMatch && paths.canonical !== paths.normalized) {
604
+ await canonicalizeSpecifier();
605
+ canonicalMatch = alias.prefix ? canonicalSpecifier.startsWith(paths.canonical) : canonicalSpecifier === paths.canonical;
606
+ }
607
+ if (normalizedMatch || canonicalMatch) {
608
+ match = alias;
609
+ matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
610
+ matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
611
+ break;
612
+ }
2868
613
  }
2869
614
  }
2870
615
  matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
@@ -2872,18 +617,7 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
2872
617
  if (!match) return;
2873
618
  const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
2874
619
  if (!target) return;
2875
- const resolvedTarget = /^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target;
2876
- return build.resolve(resolvedTarget, {
2877
- importer: args.importer,
2878
- kind: args.kind,
2879
- namespace: args.namespace,
2880
- pluginData: {
2881
- ...args.pluginData,
2882
- [skipResolvedAlias]: true
2883
- },
2884
- resolveDir: args.resolveDir,
2885
- with: args.with
2886
- });
620
+ return resolveWithContext(/^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target);
2887
621
  });
2888
622
  }
2889
623
  };
@@ -2923,62 +657,20 @@ function createViteAliasPlugin(aliases) {
2923
657
  }
2924
658
  };
2925
659
  }
2926
- function stripMarkdownCode(template) {
2927
- let fence;
2928
- let inList = false;
2929
- let previousLineBlank = true;
2930
- return template.split("\n").map((line) => {
2931
- const content = line.replace(/^(?: {0,3}> ?)+/, "");
2932
- if (!fence) {
2933
- const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
2934
- const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
2935
- if (!opening) {
2936
- if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
2937
- else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
2938
- const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
2939
- previousLineBlank = content.trim() === "";
2940
- return indentedCode ? "" : line;
2941
- }
2942
- fence = {
2943
- marker: opening[1][0],
2944
- length: opening[1].length,
2945
- listIndented
2946
- };
2947
- previousLineBlank = false;
2948
- return "";
2949
- }
2950
- const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
2951
- if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
2952
- previousLineBlank = false;
2953
- return "";
2954
- }).join("\n");
2955
- }
2956
- function extractMarkdownTemplateImportSpecifiers(template) {
2957
- const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
2958
- const specifiers = /* @__PURE__ */ new Set();
2959
- for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
2960
- const token = match[1];
2961
- const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
2962
- specifiers.add(token.slice(0, token.length - trailing.length));
2963
- }
2964
- return [...specifiers];
2965
- }
2966
660
  function parseMarkdownTemplateRequest(id) {
661
+ if (id.includes("#")) return;
2967
662
  const queryIndex = id.indexOf("?");
2968
- const path = id.split(/[?#]/, 1)[0];
663
+ const path = id.split("?", 1)[0];
2969
664
  if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
2970
- const query = id.slice(queryIndex + 1).split("#", 1)[0];
2971
- if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
665
+ if (id.slice(queryIndex + 1) !== markdownTemplateModuleQuery) return;
2972
666
  return { path };
2973
667
  }
2974
- function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
668
+ function renderMarkdownTemplateModule(template) {
2975
669
  return [
2976
670
  `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
2977
671
  `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
2978
- `const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
2979
- `const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
2980
672
  "export default function render(data = {}) {",
2981
- " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
673
+ " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data })",
2982
674
  "}",
2983
675
  ""
2984
676
  ].join("\n");
@@ -3009,7 +701,7 @@ function createViteRawPlugin(rootDir, frameworkRuntime) {
3009
701
  namespace: viteMarkdownTemplateNamespace
3010
702
  }, async (args) => {
3011
703
  if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
3012
- return build.resolve("vite-hub/_internal/markdown-template", {
704
+ return build.resolve("vite-hub/markdown-template", {
3013
705
  importer: args.importer,
3014
706
  kind: args.kind,
3015
707
  resolveDir: args.resolveDir
@@ -3071,39 +763,7 @@ function createViteRawPlugin(rootDir, frameworkRuntime) {
3071
763
  filter: /.*/,
3072
764
  namespace: viteMarkdownTemplateNamespace
3073
765
  }, async (args) => ({
3074
- contents: await (async () => {
3075
- const template = await readFile(args.path, "utf8");
3076
- const imports = {};
3077
- const visited = new Set([args.path]);
3078
- const visit = async (source, importer) => {
3079
- for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
3080
- const key = `${importer}\0${specifier}`;
3081
- if (imports[key]) continue;
3082
- const resolved = await build.resolve(specifier, {
3083
- importer,
3084
- kind: "import-statement",
3085
- pluginData: {
3086
- ...args.pluginData,
3087
- [skipMarkdownTemplateResolve]: true
3088
- },
3089
- resolveDir: dirname(importer)
3090
- });
3091
- if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
3092
- if (resolved.external || resolved.namespace !== "file") throw new Error(`[vitehub] Could not resolve Markdown template import ${JSON.stringify(specifier)} from ${JSON.stringify(importer)} to a file.`);
3093
- const imported = {
3094
- id: resolved.path,
3095
- template: await readFile(resolved.path, "utf8")
3096
- };
3097
- imports[key] = imported;
3098
- if (!visited.has(imported.id)) {
3099
- visited.add(imported.id);
3100
- await visit(imported.template, imported.id);
3101
- }
3102
- }
3103
- };
3104
- await visit(template, args.path);
3105
- return renderMarkdownTemplateModule(template, args.path, imports);
3106
- })(),
766
+ contents: renderMarkdownTemplateModule(await readFile(args.path, "utf8")),
3107
767
  loader: "js",
3108
768
  resolveDir: dirname(args.path)
3109
769
  }));
@@ -3118,19 +778,48 @@ function createFileUrlPlugin() {
3118
778
  }
3119
779
  };
3120
780
  }
781
+ /**
782
+ * Copies a `.wasm?module` import next to the bundle and keeps it as a relative `.wasm` import. Wrangler and Nitro load
783
+ * such an import as a compiled WebAssembly module, which Workers need because they can't compile WebAssembly bytes.
784
+ */
785
+ function createWasmModulePlugin(outdir) {
786
+ return {
787
+ name: "vitehub-wasm-module",
788
+ setup(build) {
789
+ build.onResolve({ filter: /\.wasm\?module$/ }, async (args) => {
790
+ const resolved = await build.resolve(args.path.slice(0, -7), {
791
+ importer: args.importer,
792
+ kind: args.kind,
793
+ resolveDir: args.resolveDir
794
+ });
795
+ if (resolved.errors.length) return { errors: resolved.errors };
796
+ const bytes = await readFile(resolved.path);
797
+ const name = `${basename(resolved.path, ".wasm")}-${createHash("sha256").update(bytes).digest("hex").slice(0, 8)}.wasm`;
798
+ await mkdir(outdir, { recursive: true });
799
+ await copyFile(resolved.path, join(outdir, name));
800
+ return {
801
+ external: true,
802
+ path: `./${name}`
803
+ };
804
+ });
805
+ }
806
+ };
807
+ }
3121
808
  async function bundleEsmEntry(entryFile, outfile, options = {}) {
809
+ const { build: bundle } = await import("./main-F3Y22_uV.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1));
3122
810
  options.signal?.throwIfAborted();
3123
811
  const format = options.format || "esm";
3124
812
  const platform = options.platform || "neutral";
3125
813
  const viteAliasPlugin = createViteAliasPlugin(options.alias);
3126
814
  const frameworkRuntime = (Array.isArray(options.alias) ? options.alias.flatMap((alias) => typeof alias.find === "string" ? [alias.find] : []) : Object.keys(options.alias || {})).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
3127
815
  const plugins = [];
3128
- const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd());
816
+ const resolvedAliasPlugin = createResolvedAliasPlugin(Array.isArray(options.alias) ? void 0 : options.alias, options.workingDir ?? options.rootDir ?? process.cwd(), options.resolveEntryPackageAliases);
3129
817
  if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
3130
818
  plugins.push(...options.plugins ?? [], createFileUrlPlugin());
3131
819
  if (viteAliasPlugin) plugins.push(viteAliasPlugin);
3132
820
  plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
3133
- const result = await (0, import_main.build)({
821
+ if (platform !== "node") plugins.unshift(createWasmModulePlugin(dirname(outfile)));
822
+ const result = await bundle({
3134
823
  absWorkingDir: options.workingDir,
3135
824
  banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
3136
825
  "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
@@ -3141,13 +830,17 @@ async function bundleEsmEntry(entryFile, outfile, options = {}) {
3141
830
  ] : []].filter(Boolean).join("\n") } : void 0,
3142
831
  bundle: true,
3143
832
  conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
833
+ define: options.define,
3144
834
  entryPoints: [entryFile],
3145
835
  external: options.external,
3146
836
  format,
837
+ keepNames: options.minifySyntax || options.minifyIdentifiers,
838
+ loader: platform === "node" ? { ".wasm": "binary" } : void 0,
3147
839
  logLevel: "silent",
3148
840
  mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
3149
841
  resolveExtensions: options.extensions,
3150
842
  minifyIdentifiers: options.minifyIdentifiers,
843
+ minifySyntax: options.minifySyntax,
3151
844
  minifyWhitespace: options.minifyWhitespace,
3152
845
  outfile,
3153
846
  packages: options.packages,
@@ -3203,6 +896,7 @@ function createNodeFunctionConfig(extra = {}) {
3203
896
  //#endregion
3204
897
  //#region ../internal/src/build/provider-output-catalog.ts
3205
898
  var ProviderOutputCatalog = class {
899
+ bundleDefines = {};
3206
900
  #appliedCloudflareContributions = /* @__PURE__ */ new Map();
3207
901
  #cloudflareContributions = /* @__PURE__ */ new Map();
3208
902
  #runtimeContributions = /* @__PURE__ */ new Map();
@@ -3253,8 +947,14 @@ var ProviderOutputCatalog = class {
3253
947
  runtimeContributions(generation) {
3254
948
  return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.entries() ?? (/* @__PURE__ */ new Map()).entries();
3255
949
  }
3256
- resetRuntimeContributions() {
3257
- this.#runtimeContributions.clear();
950
+ resetRuntimeContributions(generation, owner) {
951
+ if (generation) {
952
+ if (owner) this.#runtimeContributionsByGeneration.get(generation)?.delete(owner);
953
+ else this.#runtimeContributionsByGeneration.delete(generation);
954
+ return;
955
+ }
956
+ if (owner) this.#runtimeContributions.delete(owner);
957
+ else this.#runtimeContributions.clear();
3258
958
  }
3259
959
  createDeploymentGeneration() {
3260
960
  const generation = { valid: true };
@@ -3417,35 +1117,12 @@ function useProviderOutputCatalog(config) {
3417
1117
  const owner = config;
3418
1118
  let catalog = owner[providerOutputCatalog] ?? providerOutputCatalogs.get(config);
3419
1119
  if (!catalog) catalog = createProviderOutputCatalog();
1120
+ catalog.bundleDefines = resolveViteHubBundleDefines(config);
3420
1121
  owner[providerOutputCatalog] = catalog;
3421
1122
  providerOutputCatalogs.set(config, catalog);
3422
1123
  return catalog;
3423
1124
  }
3424
1125
  //#endregion
3425
- //#region ../internal/src/build/vite.ts
3426
- function createNoExternalMerger(packageName) {
3427
- return (current) => {
3428
- if (current === true) return true;
3429
- if (!current) return [packageName];
3430
- const values = Array.isArray(current) ? current : [current];
3431
- return values.includes(packageName) ? values : [...values, packageName];
3432
- };
3433
- }
3434
- function isServerEnvironment(name, config) {
3435
- return name === "ssr" || config.consumer === "server";
3436
- }
3437
- function includesNitroVitePlugin(value) {
3438
- if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
3439
- if (!value || typeof value !== "object") return false;
3440
- return "name" in value && value.name === "nitro:main";
3441
- }
3442
- function hasNitroConfigContext(config) {
3443
- return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
3444
- }
3445
- function shouldSkipViteProviderBuild(command, mode) {
3446
- return command === "serve" || mode === "e2e";
3447
- }
3448
- //#endregion
3449
1126
  //#region ../internal/src/build/deployment-output.ts
3450
1127
  const providerDeploymentOutputRegistry = globalThis;
3451
1128
  const providerDeploymentOutputWrites = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputWrites ??= /* @__PURE__ */ new Map();
@@ -3457,7 +1134,6 @@ const providerDeploymentOutputOwnerOrder = [
3457
1134
  "database",
3458
1135
  "blob",
3459
1136
  "queue",
3460
- "rate-limit",
3461
1137
  "schedule",
3462
1138
  "workflow",
3463
1139
  "vite-hub",
@@ -3484,13 +1160,13 @@ function createDefaultCloudflareStaticOutputDir(rootDir) {
3484
1160
  return resolve(rootDir, "dist", "client");
3485
1161
  }
3486
1162
  function resolveProviderOutputOwnershipFile(outputRoot, fileName) {
3487
- if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw new TypeError(`Invalid Provider Output ownership file name: ${JSON.stringify(fileName)}`);
1163
+ if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw invariantError(`ViteHub packages pass a plain Provider Output ownership file name (${JSON.stringify(fileName)})`);
3488
1164
  return resolve(outputRoot, fileName);
3489
1165
  }
3490
1166
  async function readProviderOutputOwnershipFile(outputRoot, fileName) {
3491
1167
  try {
3492
1168
  const parsed = JSON.parse(await readFile(resolveProviderOutputOwnershipFile(outputRoot, fileName), "utf8"));
3493
- if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string")) throw new TypeError(`Invalid Provider Output ownership file schema: ${JSON.stringify(fileName)}`);
1169
+ if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string")) throw internalErrorDiagnostics.INTERNAL_B0035({ message: `Invalid Provider Output ownership file schema: ${JSON.stringify(fileName)}` });
3494
1170
  return parsed;
3495
1171
  } catch (error) {
3496
1172
  if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
@@ -3515,7 +1191,7 @@ async function resolvePersistedProviderOutputOwnership(outputRoot, ownership, fi
3515
1191
  const arrays = { ...ownership?.arrays };
3516
1192
  await Promise.all(Object.entries(files).map(async ([field, fileName]) => {
3517
1193
  const current = arrays[field];
3518
- if (!current) throw new TypeError(`Provider Output ownership file for ${JSON.stringify(field)} requires array ownership.`);
1194
+ invariant(current, `ViteHub packages pass a Provider Output ownership file only for a field that they own as an array (${JSON.stringify(field)})`);
3519
1195
  arrays[field] = {
3520
1196
  ...current,
3521
1197
  values: [...await readProviderOutputOwnershipFile(outputRoot, fileName), ...current.values ?? []]
@@ -3544,8 +1220,14 @@ function createDefaultVercelOutputRoot(rootDir) {
3544
1220
  function createDefaultNetlifyOutputRoot(rootDir) {
3545
1221
  return resolve(rootDir, ".netlify", "v1");
3546
1222
  }
1223
+ /** Restore a retained complete publication before generation or transaction snapshots. Call under the output lock. */
1224
+ function recoverNetlifyDeploymentOutput(rootDir) {
1225
+ const outputRoot = createDefaultNetlifyOutputRoot(rootDir);
1226
+ const previousOutputRoot = `${outputRoot}.previous`;
1227
+ if (!existsSync(outputRoot) && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
1228
+ }
3547
1229
  function assertNetlifyFunctionName(functionName) {
3548
- if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
1230
+ if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw invariantError(`ViteHub writes Netlify function names from safe Definition names (${functionName})`);
3549
1231
  }
3550
1232
  function resolveNetlifyFunctionFile(functionsRoot, functionName) {
3551
1233
  assertNetlifyFunctionName(functionName);
@@ -3553,7 +1235,8 @@ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
3553
1235
  }
3554
1236
  async function appendNetlifyFunctionConfig(outfile, config) {
3555
1237
  if (!config) return;
3556
- await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
1238
+ const bundled = await readFile(outfile, "utf8");
1239
+ await writeFile(outfile, `${bundled.trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
3557
1240
  }
3558
1241
  async function writeCloudflareDeploymentOutput(options, signal) {
3559
1242
  signal?.throwIfAborted();
@@ -3563,7 +1246,7 @@ async function writeCloudflareDeploymentOutput(options, signal) {
3563
1246
  const copiesStaticOutput = Boolean(options.bundleEntry && staticIndex && resolve(clientDir) !== resolve(staticOutputDir));
3564
1247
  const files = Object.entries(options.files ?? {});
3565
1248
  const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
3566
- if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${workerOutfile}`);
1249
+ if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw invariantError(`no Cloudflare output file that ViteHub writes has the name of the bundle file (${workerOutfile})`);
3567
1250
  const backupRoot = copiesStaticOutput ? await mkdtemp(resolve(options.rootDir, ".vitehub-cloudflare-output-")) : void 0;
3568
1251
  const previousOutputRoot = backupRoot ? resolve(backupRoot, "output") : `${outputRoot}.previous`;
3569
1252
  const previousStaticOutputDir = backupRoot ? resolve(backupRoot, "static") : `${staticOutputDir}.previous`;
@@ -3605,7 +1288,7 @@ async function writeCloudflareDeploymentOutput(options, signal) {
3605
1288
  wranglerConfigDefaults: options.wranglerConfigDefaults,
3606
1289
  wranglerConfigOwnership
3607
1290
  }),
3608
- options.bundleEntry && staticIndex ? copyClientOutput(clientDir, staticOutputDir) : Promise.resolve(),
1291
+ options.bundleEntry && staticIndex ? copyClientOutput(clientDir, staticOutputDir, [outputRoot]) : Promise.resolve(),
3609
1292
  ...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
3610
1293
  ];
3611
1294
  if (options.bundleEntry && workerOutfile) {
@@ -3618,6 +1301,14 @@ async function writeCloudflareDeploymentOutput(options, signal) {
3618
1301
  });
3619
1302
  await bundleEsmEntry(options.bundleEntry, stagedWorkerOutfile, {
3620
1303
  ...options.bundleOptions,
1304
+ resolveEntryPackageAliases: options.bundleOptions?.resolveEntryPackageAliases ?? false,
1305
+ define: {
1306
+ ...options.bundleDefines,
1307
+ ...options.bundleOptions?.define
1308
+ },
1309
+ minifyIdentifiers: options.bundleOptions?.minifyIdentifiers ?? true,
1310
+ minifySyntax: options.bundleOptions?.minifySyntax ?? true,
1311
+ minifyWhitespace: options.bundleOptions?.minifyWhitespace ?? true,
3621
1312
  rootDir: options.sourceRootDir ?? options.rootDir,
3622
1313
  signal
3623
1314
  });
@@ -3731,6 +1422,14 @@ async function writeVercelDeploymentOutput(options, signal) {
3731
1422
  }
3732
1423
  await bundleEsmEntry(options.bundleEntry, serverEntry, {
3733
1424
  ...options.bundleOptions,
1425
+ resolveEntryPackageAliases: options.bundleOptions?.resolveEntryPackageAliases ?? false,
1426
+ define: {
1427
+ ...options.bundleDefines,
1428
+ ...options.bundleOptions?.define
1429
+ },
1430
+ minifyIdentifiers: options.bundleOptions?.minifyIdentifiers ?? true,
1431
+ minifySyntax: options.bundleOptions?.minifySyntax ?? true,
1432
+ minifyWhitespace: options.bundleOptions?.minifyWhitespace ?? true,
3734
1433
  rootDir: options.sourceRootDir ?? options.rootDir,
3735
1434
  signal
3736
1435
  });
@@ -3838,7 +1537,15 @@ async function writeNetlifyDeploymentOutput(options, signal) {
3838
1537
  await mkdir(dirname(outfile), { recursive: true });
3839
1538
  await bundleEsmEntry(func.bundleEntry, outfile, {
3840
1539
  ...func.bundleOptions,
3841
- minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
1540
+ resolveEntryPackageAliases: func.bundleOptions.resolveEntryPackageAliases ?? false,
1541
+ conditions: func.bundleOptions.conditions ?? ["netlify", "node"],
1542
+ define: {
1543
+ ...options.bundleDefines,
1544
+ ...func.bundleOptions.define
1545
+ },
1546
+ minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers ?? true,
1547
+ minifySyntax: func.bundleOptions.minifySyntax ?? true,
1548
+ minifyWhitespace: func.bundleOptions.minifyWhitespace ?? true,
3842
1549
  rootDir: options.sourceRootDir ?? options.rootDir,
3843
1550
  signal
3844
1551
  });
@@ -3935,19 +1642,22 @@ async function writeProviderDeploymentOutputsNow(options, signal, transaction) {
3935
1642
  ...options.cloudflare,
3936
1643
  clientOutDir: options.clientOutDir,
3937
1644
  rootDir: options.rootDir,
3938
- sourceRootDir: options.sourceRootDir
1645
+ sourceRootDir: options.sourceRootDir,
1646
+ bundleDefines: options.bundleDefines
3939
1647
  }, signal));
3940
1648
  if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
3941
1649
  ...options.netlify,
3942
1650
  clientOutDir: options.clientOutDir,
3943
1651
  rootDir: options.rootDir,
3944
- sourceRootDir: options.sourceRootDir
1652
+ sourceRootDir: options.sourceRootDir,
1653
+ bundleDefines: options.bundleDefines
3945
1654
  }, signal));
3946
1655
  if (options.vercel) writes.push(writeVercelDeploymentOutput({
3947
1656
  ...options.vercel,
3948
1657
  clientOutDir: options.clientOutDir,
3949
1658
  rootDir: options.rootDir,
3950
- sourceRootDir: options.sourceRootDir
1659
+ sourceRootDir: options.sourceRootDir,
1660
+ bundleDefines: options.bundleDefines
3951
1661
  }, signal));
3952
1662
  await settleWrites(writes);
3953
1663
  if (options.cloudflare && transaction) transaction.cloudflareWritten = true;
@@ -4058,6 +1768,7 @@ async function restoreProviderDeploymentOutputSnapshot(snapshot) {
4058
1768
  }
4059
1769
  }
4060
1770
  async function withProviderDeploymentOutputRootTransaction(rootDir, operation, options = {}) {
1771
+ recoverNetlifyDeploymentOutput(rootDir);
4061
1772
  const roots = [
4062
1773
  createDefaultCloudflareOutputRoot(rootDir),
4063
1774
  createDefaultNetlifyOutputRoot(rootDir),
@@ -4067,8 +1778,6 @@ async function withProviderDeploymentOutputRootTransaction(rootDir, operation, o
4067
1778
  resolve(rootDir, ".vitehub/queue/cloudflare-output.json"),
4068
1779
  resolve(rootDir, ".vitehub/queue/registry.mjs"),
4069
1780
  resolve(rootDir, ".vitehub/queue/vercel-output.json"),
4070
- resolve(rootDir, ".vitehub/rate-limit/cloudflare-output.json"),
4071
- resolve(rootDir, ".vitehub/rate-limit/manifest.json"),
4072
1781
  resolve(rootDir, ".vitehub/schedule"),
4073
1782
  resolve(rootDir, ".vitehub/workflow")
4074
1783
  ];
@@ -4245,15 +1954,15 @@ async function resetProviderDeploymentOutputs(catalog, failure, generation) {
4245
1954
  if (!generation) catalog.resetDeploymentContributions();
4246
1955
  if (active && (!generation || active.state.generations.has(generation))) {
4247
1956
  active.state.rollback = true;
4248
- active.controller.abort(/* @__PURE__ */ new Error("Provider Output finalization reset"));
1957
+ active.controller.abort(internalErrorDiagnostics.INTERNAL_B0039({ message: "Provider Output finalization reset" }));
4249
1958
  active.reset = {
4250
- failures: new Set([failure]),
1959
+ failures: /* @__PURE__ */ new Set([failure]),
4251
1960
  promise: active.promise.catch(() => void 0)
4252
1961
  };
4253
1962
  providerDeploymentOutputCompletedResets.set(catalog, active.reset);
4254
1963
  await active.reset.promise;
4255
1964
  } else if (failure !== void 0) providerDeploymentOutputCompletedResets.set(catalog, {
4256
- failures: new Set([failure]),
1965
+ failures: /* @__PURE__ */ new Set([failure]),
4257
1966
  promise: Promise.resolve()
4258
1967
  });
4259
1968
  }
@@ -4277,6 +1986,7 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
4277
1986
  if (catalog.hasDeploymentContributions()) await finalizeProviderDeploymentOutputs(catalog, options);
4278
1987
  return;
4279
1988
  }
1989
+ const bundleDefines = { ...catalog.bundleDefines };
4280
1990
  const controller = new AbortController();
4281
1991
  const state = {
4282
1992
  generations: /* @__PURE__ */ new Set(),
@@ -4338,7 +2048,13 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
4338
2048
  signal: controller.signal,
4339
2049
  write: async (writeOptions) => {
4340
2050
  throwIfProviderOutputAborted(controller.signal);
4341
- await writeProviderDeploymentOutputsNow(writeOptions, controller.signal, transaction);
2051
+ await writeProviderDeploymentOutputsNow({
2052
+ ...writeOptions,
2053
+ bundleDefines: {
2054
+ ...bundleDefines,
2055
+ ...writeOptions.bundleDefines
2056
+ }
2057
+ }, controller.signal, transaction);
4342
2058
  }
4343
2059
  });
4344
2060
  throwIfProviderOutputAborted(controller.signal);
@@ -4402,119 +2118,707 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
4402
2118
  if (providerDeploymentOutputFinalizations.get(catalog) === active) providerDeploymentOutputFinalizations.delete(catalog);
4403
2119
  }
4404
2120
  }
4405
- const VITEHUB_MODES = {
4406
- e2e: "e2e",
4407
- blob: "blob",
4408
- chat: "chat",
4409
- db: "db",
4410
- env: "env",
4411
- kv: "kv",
4412
- queue: "queue",
4413
- schedule: "schedule",
4414
- sandbox: "sandbox",
4415
- workspace: "workspace",
4416
- workflow: "workflow"
4417
- };
4418
- function isViteCli(argv) {
4419
- return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
4420
- }
4421
- function getViteCliMode(argv = process.argv) {
4422
- if (!isViteCli(argv)) return;
4423
- const modes = new Set(Object.values(VITEHUB_MODES));
4424
- for (let index = 0; index < argv.length; index += 1) {
4425
- const arg = argv[index];
4426
- const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
4427
- if (mode && modes.has(mode)) return mode;
2121
+ //#endregion
2122
+ //#region ../internal/src/provision-state.ts
2123
+ const PROVISION_STATE_FILE = ".vitehub/provision.json";
2124
+ function getProvisionStatePath(rootDir) {
2125
+ return resolve$1(rootDir, PROVISION_STATE_FILE);
2126
+ }
2127
+ function readProvisionStateSync(rootDir) {
2128
+ const path = getProvisionStatePath(rootDir);
2129
+ try {
2130
+ return parseProvisionState(readFileSync(path, "utf8"));
2131
+ } catch (cause) {
2132
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return {};
2133
+ throw internalErrorDiagnostics.INTERNAL_R0014({
2134
+ path,
2135
+ cause
2136
+ });
4428
2137
  }
4429
2138
  }
4430
- function getViteMode(env = process.env) {
4431
- return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
2139
+ function readProvisionedId(state, provider, category, key) {
2140
+ if (!Object.hasOwn(state, provider)) return;
2141
+ const categories = state[provider];
2142
+ if (!categories || !Object.hasOwn(categories, category)) return;
2143
+ const ids = categories[category];
2144
+ if (!ids || !Object.hasOwn(ids, key)) return;
2145
+ return ids[key];
2146
+ }
2147
+ function parseProvisionState(raw) {
2148
+ const parsed = JSON.parse(raw);
2149
+ if (!isRecord(parsed)) return {};
2150
+ const state = {};
2151
+ for (const provider of ["cloudflare", "vercel"]) {
2152
+ const categories = parsed[provider];
2153
+ if (!isRecord(categories)) continue;
2154
+ const validCategories = {};
2155
+ for (const [category, ids] of Object.entries(categories)) {
2156
+ if (!isRecord(ids)) continue;
2157
+ const validIds = {};
2158
+ for (const [key, id] of Object.entries(ids)) if (typeof id === "string") setOwn(validIds, key, id);
2159
+ if (Object.keys(validIds).length) setOwn(validCategories, category, validIds);
2160
+ }
2161
+ if (Object.keys(validCategories).length) state[provider] = validCategories;
2162
+ }
2163
+ return state;
2164
+ }
2165
+ function setOwn(target, key, value) {
2166
+ Object.defineProperty(target, key, {
2167
+ configurable: true,
2168
+ enumerable: true,
2169
+ value,
2170
+ writable: true
2171
+ });
4432
2172
  }
4433
2173
  //#endregion
4434
- //#region ../internal/src/arrays.ts
4435
- function pushUnique(arr, item, key = (value) => value) {
4436
- const id = key(item);
4437
- if (arr.some((entry) => key(entry) === id)) return;
4438
- arr.push(item);
2174
+ //#region ../internal/src/vite-stage.ts
2175
+ /**
2176
+ * Vite's `loadEnv(mode, envDir, "")`: every `.env` value of the mode and the whole shell. With `DEBUG=vite:env`, Vite
2177
+ * logs that result to stderr, secrets included. loadEnv is synchronous, so this drops only the writes of this call.
2178
+ */
2179
+ function loadAllEnv(loadEnv, mode, envDir) {
2180
+ const write = process.stderr.write;
2181
+ process.stderr.write = () => true;
2182
+ try {
2183
+ return loadEnv(mode, envDir, "");
2184
+ } finally {
2185
+ process.stderr.write = write;
2186
+ }
4439
2187
  }
4440
- //#endregion
4441
- //#region src/integrations/cloudflare.ts
4442
- function configureCloudflareKV(target, config) {
4443
- for (const store of Object.values(config.stores || { default: config.store })) {
4444
- if (store.driver !== "cloudflare-kv-binding") continue;
4445
- const { binding, namespaceId } = store;
2188
+ function configureCloudflareKV(target, config, provisionState = {}) {
2189
+ for (const [storeName, store] of Object.entries(config.stores || { default: config.store })) {
2190
+ if (store.driver !== "cloudflare") continue;
2191
+ const { binding } = store;
2192
+ const namespaceId = store.namespaceId ?? readProvisionedId(provisionState, "cloudflare", "kv", storeName);
4446
2193
  target.cloudflare ||= {};
4447
2194
  target.cloudflare.wrangler ||= {};
4448
2195
  target.cloudflare.wrangler.kv_namespaces ||= [];
4449
- pushUnique(target.cloudflare.wrangler.kv_namespaces, {
2196
+ const namespaces = target.cloudflare.wrangler.kv_namespaces;
2197
+ const existing = namespaces.find((entry) => entry.binding === binding);
2198
+ if (existing) {
2199
+ if (store.remote || store.localBase) {
2200
+ delete existing.experimental_remote;
2201
+ if (store.remote) existing.remote = true;
2202
+ else delete existing.remote;
2203
+ }
2204
+ } else namespaces.push({
4450
2205
  binding,
4451
- ...namespaceId ? { id: namespaceId } : {}
4452
- }, (entry) => entry.binding);
2206
+ ...namespaceId ? { id: namespaceId } : {},
2207
+ ...store.remote ? { remote: true } : {}
2208
+ });
2209
+ }
2210
+ }
2211
+ //#endregion
2212
+ //#region src/inspect.ts
2213
+ function describeDevelopment(store) {
2214
+ switch (store.driver) {
2215
+ case "upstash": return "Remote. `vite dev` uses the real Upstash database, so writes change real data.";
2216
+ case "cloudflare": return store.localBase ? `Local. \`vite dev\` uses the \`${store.binding}\` binding of the dev runtime, or \`fs-lite\` in \`${store.localBase}\` when the runtime has no binding.` : `Remote. \`vite dev\` uses the real Cloudflare KV namespace through the \`${store.binding}\` binding, so writes change real data.`;
2217
+ case "deno-kv": return "Local. Deno KV.";
2218
+ case "fs-lite": return `Local. \`fs-lite\` in \`${store.base}\`.`;
2219
+ case "redis": return `The Redis server of \`${store.url.startsWith("env:") ? store.url.slice(4) : "url"}\`, the same as in production when it points there.`;
2220
+ case "database": return `The table \`vitehub_kv\` in the Database "${store.database}" of \`vite dev\`.`;
2221
+ }
2222
+ }
2223
+ /** One summary per KV store: the build driver and what `vite dev` uses. */
2224
+ function inspectKVStores(build, dev, file) {
2225
+ const devStores = dev.stores ?? { default: dev.store };
2226
+ return Object.entries(build.stores ?? { default: build.store }).map(([name, store]) => {
2227
+ const devStore = devStores[name];
2228
+ return {
2229
+ fields: [{
2230
+ label: "Driver",
2231
+ value: store.driver
2232
+ }, ...devStore ? [{
2233
+ label: "Development",
2234
+ value: describeDevelopment(devStore)
2235
+ }] : []],
2236
+ file,
2237
+ name,
2238
+ source: "kv"
2239
+ };
2240
+ });
2241
+ }
2242
+ function cloudflareStores(options, env) {
2243
+ const stores = /* @__PURE__ */ new Map();
2244
+ const kv = resolveKVViteConfig(options, { env }).kv;
2245
+ if (!kv) return stores;
2246
+ for (const [name, store] of Object.entries(kv.stores || { default: kv.store })) if (store.driver === "cloudflare") stores.set(name, store);
2247
+ return stores;
2248
+ }
2249
+ /** Lists the Workers KV namespaces that KV Stores bind, with where each id comes from. Reads local config and Provision State only. */
2250
+ function inspectKVResources(options, provisionRoot, env = process.env) {
2251
+ const stores = cloudflareStores(options, env);
2252
+ if (!stores.size) return [];
2253
+ const configured = cloudflareStores(options, {
2254
+ ...env,
2255
+ KV_NAMESPACE_ID: void 0
2256
+ });
2257
+ const provisionState = readProvisionStateSync(provisionRoot);
2258
+ return [...stores].map(([storeName, store]) => {
2259
+ const configuredId = configured.get(storeName)?.namespaceId;
2260
+ const provisionedId = readProvisionedId(provisionState, "cloudflare", "kv", storeName);
2261
+ const id = store.namespaceId ?? provisionedId;
2262
+ return {
2263
+ binding: store.binding,
2264
+ definition: storeName,
2265
+ host: "cloudflare",
2266
+ kind: "cloudflare-kv-namespace",
2267
+ ...store.namespaceName ? { name: store.namespaceName } : {},
2268
+ owner: "kv",
2269
+ ...id ? { id } : {},
2270
+ ...configuredId ? { source: "config" } : store.namespaceId ? {
2271
+ env: "KV_NAMESPACE_ID",
2272
+ source: "env"
2273
+ } : provisionedId ? { source: "provision-state" } : {}
2274
+ };
2275
+ });
2276
+ }
2277
+ //#endregion
2278
+ //#region ../internal/src/host-credentials.ts
2279
+ /** Reads host credentials from environment variables only. Returns undefined when the token is not set. */
2280
+ function readHostCredentialsFromEnv(host, env) {
2281
+ switch (host) {
2282
+ case "cloudflare": {
2283
+ const token = trimmed(env.CLOUDFLARE_API_TOKEN);
2284
+ const accountId = trimmed(env.CLOUDFLARE_ACCOUNT_ID);
2285
+ return token ? {
2286
+ token,
2287
+ ...accountId && { accountId }
2288
+ } : void 0;
2289
+ }
2290
+ case "vercel": {
2291
+ const token = trimmed(env.VERCEL_TOKEN);
2292
+ const teamId = trimmed(env.VERCEL_TEAM_ID) ?? trimmed(env.VERCEL_ORG_ID);
2293
+ return token ? {
2294
+ token,
2295
+ ...teamId && { teamId }
2296
+ } : void 0;
2297
+ }
2298
+ case "netlify": {
2299
+ const token = trimmed(env.NETLIFY_AUTH_TOKEN);
2300
+ return token ? { token } : void 0;
2301
+ }
2302
+ case "deno": {
2303
+ const token = trimmed(env.DENO_DEPLOY_TOKEN);
2304
+ return token ? { token } : void 0;
2305
+ }
2306
+ }
2307
+ }
2308
+ function trimmed(value) {
2309
+ const result = value?.trim();
2310
+ return result ? result : void 0;
2311
+ }
2312
+ //#endregion
2313
+ //#region ../internal/src/provider-failure.ts
2314
+ const cloudflareCodes = {
2315
+ d1: {},
2316
+ kv: { 10014: "conflict" },
2317
+ queues: {
2318
+ 10104: "not-found",
2319
+ 10106: "unauthorized",
2320
+ 10107: "invalid",
2321
+ 10201: "unavailable",
2322
+ 10202: "invalid",
2323
+ 10203: "invalid",
2324
+ 10204: "invalid",
2325
+ 10205: "invalid",
2326
+ 10206: "invalid",
2327
+ 10207: "invalid",
2328
+ 10208: "invalid",
2329
+ 10250: "throttled",
2330
+ 10251: "throttled",
2331
+ 10252: "throttled",
2332
+ 10253: "throttled",
2333
+ 15e3: "unavailable"
2334
+ },
2335
+ r2: {
2336
+ 10001: "unavailable",
2337
+ 10002: "unauthorized",
2338
+ 10003: "unauthorized",
2339
+ 10004: "conflict",
2340
+ 10005: "invalid",
2341
+ 10006: "not-found",
2342
+ 10007: "not-found",
2343
+ 10008: "conflict",
2344
+ 10009: "invalid",
2345
+ 10011: "invalid",
2346
+ 10012: "invalid",
2347
+ 10013: "invalid",
2348
+ 10014: "invalid",
2349
+ 10018: "unauthorized",
2350
+ 10020: "invalid",
2351
+ 10024: "not-found",
2352
+ 10025: "invalid",
2353
+ 10031: "conflict",
2354
+ 10033: "invalid",
2355
+ 10035: "unauthorized",
2356
+ 10037: "invalid",
2357
+ 10039: "invalid",
2358
+ 10042: "unauthorized",
2359
+ 10043: "unavailable",
2360
+ 10048: "invalid",
2361
+ 10054: "unavailable",
2362
+ 10058: "throttled",
2363
+ 10069: "conflict",
2364
+ 10073: "conflict",
2365
+ 100100: "invalid"
2366
+ }
2367
+ };
2368
+ const vercelCodes = {
2369
+ bad_request: "invalid",
2370
+ conflict_aliases: "conflict",
2371
+ forbidden: "unauthorized",
2372
+ internal_server_error: "unavailable",
2373
+ method_unknown: "invalid",
2374
+ not_found: "not-found",
2375
+ not_modified: "conflict",
2376
+ rate_limited: "throttled",
2377
+ service_unavailable: "unavailable"
2378
+ };
2379
+ function kindFromStatus(status) {
2380
+ if (status === 401 || status === 403) return "unauthorized";
2381
+ if (status === 404 || status === 410) return "not-found";
2382
+ if (status === 409 || status === 412) return "conflict";
2383
+ if (status === 429) return "throttled";
2384
+ if (status === 408 || status >= 500) return "unavailable";
2385
+ if (status >= 400) return "invalid";
2386
+ }
2387
+ /**
2388
+ * Classifies a failed provider call. A documented provider code wins over the HTTP status.
2389
+ * Returns `undefined` only when neither a known code nor an error status is present.
2390
+ */
2391
+ function classifyProviderFailure(source, { codes = [], status }) {
2392
+ for (const code of codes) {
2393
+ const kind = source.host === "vercel" ? typeof code === "string" && Object.hasOwn(vercelCodes, code) ? vercelCodes[code] : void 0 : source.host === "cloudflare" && source.product && typeof code === "number" && Object.hasOwn(cloudflareCodes[source.product], code) ? cloudflareCodes[source.product][code] : void 0;
2394
+ if (kind) return kind;
2395
+ }
2396
+ return status === void 0 ? void 0 : kindFromStatus(status);
2397
+ }
2398
+ /** Finds the Cloudflare product of an account API path, such as `/r2/buckets`. */
2399
+ function cloudflareProductOfPath(path) {
2400
+ if (path.startsWith("/r2/")) return "r2";
2401
+ if (path.startsWith("/storage/kv/")) return "kv";
2402
+ if (path.startsWith("/d1/")) return "d1";
2403
+ if (path === "/queues" || path.startsWith("/queues/") || path.startsWith("/queues?")) return "queues";
2404
+ }
2405
+ /**
2406
+ * Reads the error codes of a Cloudflare (`errors[].code`) or Vercel (`error.code`) error body.
2407
+ * Keeps only codes that are safe to print: numbers, and short strings without spaces or line breaks.
2408
+ */
2409
+ function readProviderErrorCodes(body) {
2410
+ if (!body || typeof body !== "object") return [];
2411
+ const error = Reflect.get(body, "error");
2412
+ const errors = Reflect.get(body, "errors");
2413
+ return [error && typeof error === "object" ? Reflect.get(error, "code") : void 0, ...Array.isArray(errors) ? errors.map((entry) => entry && typeof entry === "object" ? Reflect.get(entry, "code") : void 0) : []].filter((code) => typeof code === "number" && Number.isFinite(code) || typeof code === "string" && /^[\w.-]{1,128}$/.test(code));
2414
+ }
2415
+ //#endregion
2416
+ //#region ../internal/src/provision.ts
2417
+ /**
2418
+ * Whether a value from Provision State can appear in a copyable shell command as is.
2419
+ * The file is editable, so a hint shows a command only for plain names and ids.
2420
+ */
2421
+ function isShellSafeProvisionValue(value) {
2422
+ return /^[A-Za-z0-9][\w.-]*$/.test(value);
2423
+ }
2424
+ function resolveCloudflareProvisionConfig(env) {
2425
+ const credentials = readHostCredentialsFromEnv("cloudflare", env);
2426
+ if (!credentials?.accountId) return;
2427
+ return {
2428
+ accountId: credentials.accountId,
2429
+ token: credentials.token
2430
+ };
2431
+ }
2432
+ function ownParser(options) {
2433
+ if (!Object.hasOwn(options, "parse")) return;
2434
+ return options.parse;
2435
+ }
2436
+ function provisionRequestError(method, path, status, codes, kind) {
2437
+ const suffix = codes.length ? ` Provider code${codes.length === 1 ? "" : "s"}: ${codes.join(", ")}.` : "";
2438
+ return Object.assign(internalErrorDiagnostics.INTERNAL_R0013({ message: `Provision request failed: ${method} ${path} (${status}).${suffix}` }), {
2439
+ codes,
2440
+ kind,
2441
+ status
2442
+ });
2443
+ }
2444
+ /** Whether `error` is a failed provider API call of provisioning. */
2445
+ function isProvisionRequestError(error) {
2446
+ return error instanceof Error && Reflect.get(error, "code") === "INTERNAL_R0013";
2447
+ }
2448
+ function createJsonClient(source, baseURL, headers, fetchImpl, baseQuery) {
2449
+ return async function request(path, options = {}) {
2450
+ const url = new URL(`${baseURL}${path}`);
2451
+ const query = Object.hasOwn(options, "query") ? options.query : void 0;
2452
+ for (const [key, value] of Object.entries({
2453
+ ...baseQuery,
2454
+ ...query
2455
+ })) url.searchParams.set(key, value);
2456
+ const method = Object.hasOwn(options, "method") ? options.method : void 0;
2457
+ const body = Object.hasOwn(options, "body") ? options.body : void 0;
2458
+ const requestHeaders = Object.hasOwn(options, "headers") ? options.headers : void 0;
2459
+ const init = {
2460
+ method: method ?? "GET",
2461
+ headers: {
2462
+ ...requestHeaders,
2463
+ ...headers
2464
+ }
2465
+ };
2466
+ if (body !== void 0) {
2467
+ init.headers = {
2468
+ ...init.headers,
2469
+ "content-type": "application/json"
2470
+ };
2471
+ init.body = JSON.stringify(body);
2472
+ }
2473
+ const response = await fetchImpl(url, init);
2474
+ if (!response.ok) {
2475
+ const codes = readProviderErrorCodes(await response.json().catch(() => void 0));
2476
+ const kind = classifyProviderFailure(source(path), {
2477
+ codes,
2478
+ status: response.status
2479
+ }) ?? "unavailable";
2480
+ throw provisionRequestError(method ?? "GET", path, response.status, codes, kind);
2481
+ }
2482
+ const value = await response.json();
2483
+ const parse = ownParser(options);
2484
+ return parse ? parse(value) : value;
2485
+ };
2486
+ }
2487
+ function createCloudflareProvisionClient(config, fetchImpl = globalThis.fetch) {
2488
+ return createCloudflareClient(`https://api.cloudflare.com/client/v4/accounts/${config.accountId}`, config.token, fetchImpl);
2489
+ }
2490
+ function createCloudflareClient(baseURL, token, fetchImpl) {
2491
+ const client = createJsonClient((path) => ({
2492
+ host: "cloudflare",
2493
+ product: cloudflareProductOfPath(path)
2494
+ }), baseURL, { authorization: `Bearer ${token}` }, fetchImpl);
2495
+ return async (path, options = {}) => {
2496
+ const parse = ownParser(options) ?? ((value) => value);
2497
+ return await client(path, {
2498
+ ...options,
2499
+ parse(value) {
2500
+ if (!value || Object(value) !== value) throw internalErrorDiagnostics.INTERNAL_R0010({ message: "Cloudflare provisioning returned an invalid response." });
2501
+ const envelope = value;
2502
+ return {
2503
+ ...envelope,
2504
+ result: envelope.result === void 0 ? void 0 : parse(envelope.result)
2505
+ };
2506
+ }
2507
+ });
2508
+ };
2509
+ }
2510
+ /**
2511
+ * Reads every page of a Cloudflare list that pages with `page` and `result_info`.
2512
+ * R2 bucket lists page with a cursor instead and do not use this helper.
2513
+ */
2514
+ async function listCloudflarePages(request, path, options) {
2515
+ const items = [];
2516
+ for (let page = 1;; page++) {
2517
+ const query = {
2518
+ ...options.query,
2519
+ page: String(page)
2520
+ };
2521
+ if (options.perPage !== void 0) query.per_page = String(options.perPage);
2522
+ const listed = await request(path, {
2523
+ parse: options.parse,
2524
+ query
2525
+ });
2526
+ const pageItems = listed.result ?? [];
2527
+ items.push(...pageItems);
2528
+ const info = listed.result_info;
2529
+ if (info?.page !== void 0 && info.page !== page) throw internalErrorDiagnostics.INTERNAL_R0010({ message: `Cloudflare provisioning returned page ${info.page} of ${path} for page ${page}.` });
2530
+ if (!pageItems.length) return items;
2531
+ if (info?.total_pages !== void 0) {
2532
+ if (page >= info.total_pages) return items;
2533
+ } else if (info?.total_count !== void 0) {
2534
+ if (page * (info.per_page ?? options.perPage ?? pageItems.length) >= info.total_count) return items;
2535
+ } else if (options.perPage === void 0 || pageItems.length < options.perPage) return items;
4453
2536
  }
4454
2537
  }
4455
2538
  //#endregion
2539
+ //#region src/provision.ts
2540
+ const CLOUDFLARE_KV_NAMESPACE_LIST_PER_PAGE = 100;
2541
+ function parseNamespaces(value) {
2542
+ if (!Array.isArray(value)) throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: "Cloudflare returned an invalid KV namespace list." });
2543
+ for (const namespace of value) {
2544
+ if (!namespace || Object(namespace) !== namespace) throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: "Cloudflare returned an invalid KV namespace list." });
2545
+ const id = Reflect.get(namespace, "id");
2546
+ const title = Reflect.get(namespace, "title");
2547
+ if (!Object.hasOwn(namespace, "id") || !Object.hasOwn(namespace, "title") || typeof id !== "string" || typeof title !== "string") throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: "Cloudflare returned an invalid KV namespace list." });
2548
+ }
2549
+ return value;
2550
+ }
2551
+ function parseCreatedNamespace(value) {
2552
+ if (!value || Object(value) !== value) throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: "Cloudflare returned an invalid KV namespace." });
2553
+ const id = Reflect.get(value, "id");
2554
+ if (!Object.hasOwn(value, "id") || typeof id !== "string") throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: "Cloudflare returned an invalid KV namespace." });
2555
+ return { id };
2556
+ }
2557
+ async function listNamespaceIds(request) {
2558
+ const ids = /* @__PURE__ */ new Map();
2559
+ const namespaces = await listCloudflarePages(request, "/storage/kv/namespaces", {
2560
+ parse: parseNamespaces,
2561
+ perPage: CLOUDFLARE_KV_NAMESPACE_LIST_PER_PAGE
2562
+ });
2563
+ for (const namespace of namespaces) if (namespace.id && namespace.title && !ids.has(namespace.title)) ids.set(namespace.title, namespace.id);
2564
+ return ids;
2565
+ }
2566
+ async function createNamespace(request, title) {
2567
+ try {
2568
+ return (await request("/storage/kv/namespaces", {
2569
+ method: "POST",
2570
+ body: { title },
2571
+ parse: parseCreatedNamespace
2572
+ })).result?.id;
2573
+ } catch (error) {
2574
+ if (!isProvisionRequestError(error) || error.kind !== "conflict") throw error;
2575
+ const id = (await listNamespaceIds(request)).get(title);
2576
+ if (!id) throw error;
2577
+ return id;
2578
+ }
2579
+ }
2580
+ function planStoresByNamespace(options, env) {
2581
+ const kv = resolveKVViteConfig(options, {
2582
+ env,
2583
+ hosting: "cloudflare"
2584
+ }).kv;
2585
+ const storesByNamespace = /* @__PURE__ */ new Map();
2586
+ if (!kv) return storesByNamespace;
2587
+ for (const [storeName, store] of Object.entries(kv.stores || { default: kv.store })) {
2588
+ if (store.driver !== "cloudflare" || store.namespaceId || !store.namespaceName) continue;
2589
+ const stores = storesByNamespace.get(store.namespaceName);
2590
+ if (stores) stores.push(storeName);
2591
+ else storesByNamespace.set(store.namespaceName, [storeName]);
2592
+ }
2593
+ return storesByNamespace;
2594
+ }
2595
+ function cloudflareStoreNames(options, env) {
2596
+ const kv = resolveKVViteConfig(options, {
2597
+ env,
2598
+ hosting: "cloudflare"
2599
+ }).kv;
2600
+ if (!kv) return [];
2601
+ return Object.entries(kv.stores || { default: kv.store }).filter(([, store]) => store.driver === "cloudflare").map(([name]) => name);
2602
+ }
2603
+ function createKVCloudflareProvisionStep(resolveOptions) {
2604
+ return {
2605
+ id: "kv:cloudflare-kv",
2606
+ provider: "cloudflare",
2607
+ recordedState(context) {
2608
+ return [{
2609
+ category: "kv",
2610
+ declared: cloudflareStoreNames(resolveOptions(), context.env),
2611
+ deleteHint: ({ id }) => isShellSafeProvisionValue(id) ? `run \`wrangler kv namespace delete --namespace-id ${id}\`` : "delete the KV namespace in the Cloudflare dashboard"
2612
+ }];
2613
+ },
2614
+ async plan(context) {
2615
+ const storesByNamespace = planStoresByNamespace(resolveOptions(), context.env);
2616
+ if (!storesByNamespace.size) return [];
2617
+ const config = resolveCloudflareProvisionConfig(context.env);
2618
+ if (!config) {
2619
+ context.logger.warn("kv: skipping Cloudflare KV, missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN.");
2620
+ context.markPlanUnchecked?.();
2621
+ return [];
2622
+ }
2623
+ const request = createCloudflareProvisionClient(config, context.fetch);
2624
+ const existing = await listNamespaceIds(request);
2625
+ return [...storesByNamespace].map(([namespaceName, stores]) => ({
2626
+ kind: "cloudflare-kv-namespace",
2627
+ name: namespaceName,
2628
+ exists: existing.has(namespaceName),
2629
+ apply: async () => {
2630
+ const id = existing.get(namespaceName) ?? await createNamespace(request, namespaceName);
2631
+ if (!id) throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: `Cloudflare did not return an id for namespace ${JSON.stringify(namespaceName)}.` });
2632
+ return { ids: { cloudflare: { ["kv"]: Object.fromEntries(stores.map((store) => [store, id])) } } };
2633
+ }
2634
+ }));
2635
+ }
2636
+ };
2637
+ }
2638
+ //#endregion
2639
+ //#region src/deployment-env.ts
2640
+ const owners = ["kv"];
2641
+ const maskedRuntimeValue = "********";
2642
+ function entry(names) {
2643
+ return {
2644
+ names,
2645
+ required: true,
2646
+ secret: true,
2647
+ hasDefault: false,
2648
+ owners
2649
+ };
2650
+ }
2651
+ function storeEntries(store) {
2652
+ if (store.driver === "upstash") return [...store.url === maskedRuntimeValue ? [entry(upstashUrlEnvNames)] : [], ...store.token === maskedRuntimeValue ? [entry(upstashTokenEnvNames)] : []];
2653
+ if (store.driver === "redis" && store.url.startsWith("env:")) return [entry([store.url.slice(4)])];
2654
+ return [];
2655
+ }
2656
+ /**
2657
+ * The variables that the KV stores read on the deployed host: the Upstash REST URL and token, and the Redis URL
2658
+ * variable. Cloudflare KV, Database, Deno KV, and `fs-lite` stores read none.
2659
+ */
2660
+ function kvDeploymentEnv(config) {
2661
+ if (!config) return [];
2662
+ return Object.values(config.stores ?? { default: config.store }).flatMap(storeEntries);
2663
+ }
2664
+ //#endregion
4456
2665
  //#region src/vite.ts
2666
+ const operationsModule = ownModule(import.meta.url, "operations");
4457
2667
  const RESOLVED_KV_VIRTUAL_CONFIG_ID = `\0${KV_VIRTUAL_CONFIG_ID}`;
4458
2668
  const RESOLVED_KV_RUNTIME_ID = `\0#vitehub/kv/runtime`;
4459
- const KV_ERRORS_IMPORT_ID = new URL(import.meta.url.endsWith(".ts") ? "./errors.ts" : "./errors.js", import.meta.url).href;
2669
+ const KV_ERRORS_IMPORT_ID = ownModule(import.meta.url, "errors");
4460
2670
  const UPSTASH_DRIVER_IMPORT_ID = "@vite-hub/kv/runtime/upstash-driver";
4461
- const CLOUDFLARE_KV_RUNTIME_IMPORT_ID = import.meta.url.endsWith(".ts") ? "@vite-hub/kv/runtime/cloudflare-kv" : new URL("./runtime/cloudflare-kv.js", import.meta.url).href;
4462
- const mergeNoExternal = createNoExternalMerger("@vite-hub/kv");
2671
+ const REDIS_DRIVER_IMPORT_ID = "@vite-hub/kv/runtime/redis-driver";
2672
+ const DATABASE_VITE_PLUGIN_NAME = "@vite-hub/database/vite";
2673
+ const CLOUDFLARE_KV_RUNTIME_IMPORT_ID = ownModule(import.meta.url, "runtime/cloudflare-kv");
2674
+ const KV_CLOUDFLARE_REQUEST_ENV_MIDDLEWARE = ownModule(import.meta.url, "runtime/cloudflare-request-env");
2675
+ /**
2676
+ * File path of the unstorage driver over a KV store. Options: `store` (default: the default store) and `base` (a key prefix).
2677
+ * ViteHub mounts it at `kv`, `kv-<store>`, and, with `cache: { driver: "kv" }`, at `cache`.
2678
+ */
2679
+ const kvStorageDriver = ownModule(import.meta.url, "runtime/unstorage-driver");
2680
+ const KV_NITRO_PLUGIN = ownModule(import.meta.url, "runtime/nitro-plugin");
2681
+ const mergeNoExternal = createNoExternalAddition("@vite-hub/kv");
4463
2682
  const KV_CLOUDFLARE_BINDINGS_FILE = ".vitehub-kv-bindings.json";
4464
- function hubKvOptionalPeerResolver() {
2683
+ const OPTIONAL_PEER_ID_PATTERN = /^(?:@vite-hub\/kv\/runtime\/(?:redis|upstash)-driver|cloudflare:workers)$/;
2684
+ const RESOLVE_ID_PATTERN = /^(?:@vite-hub\/kv(?:\/runtime\/(?:redis|upstash)-driver)?|cloudflare:workers|#vitehub\/kv\/config)$/;
2685
+ const LOAD_ID_PATTERN = /^\0#vitehub\/kv\/(?:runtime|config)$/;
2686
+ function hubKVOptionalPeerResolver() {
4465
2687
  return {
4466
2688
  name: "@vite-hub/kv/optional-peers",
4467
2689
  enforce: "pre",
4468
- resolveId(id, importer, resolveOptions) {
4469
- if (!resolveOptions?.ssr || !isKVOptionalUpstashImport(id, importer)) return;
4470
- return {
4471
- external: true,
4472
- id
4473
- };
2690
+ resolveId: {
2691
+ filter: { id: OPTIONAL_PEER_ID_PATTERN },
2692
+ handler(id, importer, resolveOptions) {
2693
+ if (!resolveOptions?.ssr) return;
2694
+ if (isKVOptionalDriverImport(UPSTASH_DRIVER_IMPORT_ID, id, importer) || isKVOptionalDriverImport(REDIS_DRIVER_IMPORT_ID, id, importer) || isUnstorageCloudflareWorkersImport(id, importer)) return {
2695
+ external: true,
2696
+ id
2697
+ };
2698
+ }
4474
2699
  }
4475
2700
  };
4476
2701
  }
4477
- function serializeVirtualConfig(config) {
2702
+ function kvStores(kv) {
2703
+ return kv ? Object.values(kv.stores || { default: kv.store }) : [];
2704
+ }
2705
+ /** Redis is selected explicitly at build time. */
2706
+ function hasRedisStore(kv) {
2707
+ return kvStores(kv).some((store) => store.driver === "redis");
2708
+ }
2709
+ function hasDatabaseStore(kv) {
2710
+ return kvStores(kv).some((store) => store.driver === "database");
2711
+ }
2712
+ function findDatabasePlugin(plugins) {
2713
+ return plugins?.find((plugin) => plugin.name === DATABASE_VITE_PLUGIN_NAME);
2714
+ }
2715
+ function serializeVirtualConfig(config, databaseImport, env) {
2716
+ const resolveStore = (store) => env && store.driver === "upstash" ? resolveUpstashRuntimeValues(store, env) : store;
2717
+ const kv = config.kv && env ? {
2718
+ ...config.kv,
2719
+ store: resolveStore(config.kv.store),
2720
+ ...config.kv.stores ? { stores: Object.fromEntries(Object.entries(config.kv.stores).map(([name, store]) => [name, resolveStore(store)])) } : {}
2721
+ } : config.kv;
4478
2722
  return [
4479
2723
  `export const hosting = ${JSON.stringify(config.hosting)};`,
4480
- `export const kv = ${JSON.stringify(config.kv)};`,
2724
+ `export const kv = ${JSON.stringify(kv)};`,
2725
+ hasDatabaseStore(config.kv) ? `export const loadDatabases = () => import(${JSON.stringify(databaseImport)}).then(module => module.databases);` : "export const loadDatabases = undefined;",
4481
2726
  "export default { hosting, kv };"
4482
2727
  ].join("\n");
4483
2728
  }
4484
2729
  function isCloudflareKVConfig(kv) {
4485
2730
  if (!kv) return false;
4486
- return Object.values(kv.stores || { default: kv.store }).every((store) => store.driver === "cloudflare-kv-binding");
2731
+ return Object.values(kv.stores || { default: kv.store }).every((store) => store.driver === "cloudflare");
4487
2732
  }
4488
- function hasUpstashStore(kv) {
2733
+ function hasCloudflareKVStore(kv) {
4489
2734
  if (!kv) return false;
4490
- return Object.values(kv.stores || { default: kv.store }).some((store) => store.driver === "upstash");
2735
+ return Object.values(kv.stores || { default: kv.store }).some((store) => store.driver === "cloudflare");
2736
+ }
2737
+ /**
2738
+ * Registers the KV Nitro plugin for Redis connections and inferred-store boot notices. It prints the driver of each inferred store at boot, and
2739
+ * disposes the stores when the server closes. Without it, the open connection keeps a Node process alive after a stop
2740
+ * signal.
2741
+ */
2742
+ function configureNitroPlugin(nitro, kv) {
2743
+ const plugins = (nitro.plugins ?? []).filter((plugin) => plugin !== KV_NITRO_PLUGIN);
2744
+ if (hasRedisStore(kv) || kvStores(kv).some((store) => "inferred" in store && store.inferred)) plugins.push(KV_NITRO_PLUGIN);
2745
+ if (plugins.length || nitro.plugins) nitro.plugins = plugins;
2746
+ }
2747
+ /** The Nitro storage mount of a store: `kv` for the default store, `kv-<name>` for a named store. */
2748
+ function kvStorageMountName(store) {
2749
+ const segment = store.replace(/[%:/\\?]/g, (character) => encodeURIComponent(character)) || "%";
2750
+ return store === "default" ? "kv" : `kv-${segment}`;
2751
+ }
2752
+ /**
2753
+ * Mounts each KV store in Nitro storage, so `useStorage("kv")` and modules that take a mount name use the store.
2754
+ * A mount that the app set in `kv` or the deprecated `storage` option wins.
2755
+ */
2756
+ function configureNitroStorage(nitro, kv) {
2757
+ if (!kv) return;
2758
+ const names = Object.keys({
2759
+ default: kv.store,
2760
+ ...kv.stores
2761
+ });
2762
+ const mounts = isRecord(nitro.kv) ? nitro.kv : {};
2763
+ const legacy = isRecord(nitro.storage) ? nitro.storage : {};
2764
+ for (const store of names) {
2765
+ const mount = kvStorageMountName(store);
2766
+ if (Object.hasOwn(mounts, mount) || Object.hasOwn(legacy, mount)) continue;
2767
+ mounts[mount] = store === "default" ? { driver: kvStorageDriver } : {
2768
+ driver: kvStorageDriver,
2769
+ store
2770
+ };
2771
+ }
2772
+ if (Object.keys(mounts).length || nitro.kv) nitro.kv = mounts;
2773
+ }
2774
+ /** Registers the middleware that installs the request's Cloudflare env, or removes it when no store uses a binding. */
2775
+ function configureNitroCloudflareRequestEnv(nitro, kv) {
2776
+ const handlers = Array.isArray(nitro.handlers) ? nitro.handlers.filter((handler) => !(isRecord(handler) && handler.handler === KV_CLOUDFLARE_REQUEST_ENV_MIDDLEWARE)) : [];
2777
+ if (hasCloudflareKVStore(kv)) handlers.unshift({
2778
+ handler: KV_CLOUDFLARE_REQUEST_ENV_MIDDLEWARE,
2779
+ middleware: true
2780
+ });
2781
+ if (handlers.length || Array.isArray(nitro.handlers)) nitro.handlers = handlers;
4491
2782
  }
4492
- function isKVOptionalUpstashImport(id, importer) {
4493
- if (id !== UPSTASH_DRIVER_IMPORT_ID || !importer) return false;
2783
+ function hasUpstashStore(kv) {
2784
+ return kvStores(kv).some((store) => store.driver === "upstash");
2785
+ }
2786
+ /** The import of a provider driver from the KV runtime. A build without a store on that provider keeps it external. */
2787
+ function isKVOptionalDriverImport(driver, id, importer) {
2788
+ if (id !== driver || !importer) return false;
4494
2789
  const normalizedImporter = importer.replace(/\\/g, "/").split("?", 1)[0];
4495
2790
  return normalizedImporter.endsWith("/packages/kv/src/runtime/driver.ts") || normalizedImporter.endsWith("/packages/kv/dist/index.js") || normalizedImporter.includes("/@vite-hub/kv/dist/index.js");
4496
2791
  }
4497
- function createCloudflareKVWranglerConfig(kv) {
2792
+ function isUnstorageCloudflareWorkersImport(id, importer) {
2793
+ if (id !== "cloudflare:workers" || !importer) return false;
2794
+ return /[/\\]unstorage[/\\]dist[/\\]/.test(importer);
2795
+ }
2796
+ function createCloudflareKVWranglerConfig(kv, provisionState) {
4498
2797
  if (!kv) return;
4499
2798
  const target = {};
4500
- configureCloudflareKV(target, kv);
2799
+ configureCloudflareKV(target, kv, provisionState);
4501
2800
  return target.cloudflare?.wrangler?.kv_namespaces?.length ? target.cloudflare.wrangler : void 0;
4502
2801
  }
4503
2802
  function serializeCloudflareRuntime(config) {
4504
2803
  return [
4505
2804
  `import { createCloudflareKVStorage } from ${JSON.stringify(CLOUDFLARE_KV_RUNTIME_IMPORT_ID)};`,
4506
- `import { kvResult } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
2805
+ `import { kvInvalidLimitError, kvKeyLimitCodes, kvResult, kvStoreNotFoundError, kvStoreWithMode, kvUnsupportedOperationError, kvWriteLimitCodes } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
4507
2806
  "",
4508
2807
  `const kvConfig = ${JSON.stringify(config, null, 2)}`,
4509
2808
  "const storages = new Map();",
2809
+ "export async function disposeKVStores() { storages.clear(); }",
4510
2810
  "",
4511
2811
  "function resolveStoreConfig(name) {",
4512
2812
  " const stores = kvConfig.stores || { default: kvConfig.store };",
2813
+ " if (!Object.prototype.hasOwnProperty.call(stores, name)) throw kvStoreNotFoundError(name);",
4513
2814
  " const store = stores[name];",
4514
- " if (!store) throw new Error(`[vitehub] Unknown KV store \"${name}\".`);",
4515
2815
  " return store;",
4516
2816
  "}",
4517
2817
  "",
2818
+ "export async function getKVStoreDriver(name = \"default\") {",
2819
+ " return resolveStoreConfig(name).driver;",
2820
+ "}",
2821
+ "",
4518
2822
  "function resolveStorage(name = \"default\") {",
4519
2823
  " const store = resolveStoreConfig(name);",
4520
2824
  " const existing = storages.get(name);",
@@ -4524,23 +2828,29 @@ function serializeCloudflareRuntime(config) {
4524
2828
  " return storage;",
4525
2829
  "}",
4526
2830
  "",
4527
- "async function resolveStorageResult(name, operation) {",
2831
+ "function unsupported(operation, name) {",
4528
2832
  " resolveStoreConfig(name);",
4529
- " return kvResult(operation, name, async () => resolveStorage(name));",
2833
+ " return [kvUnsupportedOperationError(operation, name), undefined];",
4530
2834
  "}",
4531
2835
  "",
2836
+ "// kvResult throws config errors, for example an unknown store, and returns the other errors.",
4532
2837
  "function createKVStorage(name = \"default\") {",
4533
2838
  " return {",
4534
- " async clear(base, options) { const [error, storage] = await resolveStorageResult(name, \"clear\"); return error ? [error, undefined] : kvResult(\"clear\", name, async () => { await storage.clear(base, options); }); },",
4535
- " async del(key, options) { const [error, storage] = await resolveStorageResult(name, \"del\"); return error ? [error, undefined] : kvResult(\"del\", name, async () => { await storage.removeItem(key, options); }); },",
4536
- " async get(key, options) { const [error, storage] = await resolveStorageResult(name, \"get\"); return error ? [error, undefined] : kvResult(\"get\", name, () => storage.getItem(key, options)); },",
4537
- " async getAndDelete() { resolveStoreConfig(name); throw new Error(\"[vitehub] Cloudflare KV does not support atomic operations. Use Upstash.\"); },",
4538
- " async has(key, options) { const [error, storage] = await resolveStorageResult(name, \"has\"); return error ? [error, undefined] : kvResult(\"has\", name, () => storage.hasItem(key, options)); },",
4539
- " async increment() { resolveStoreConfig(name); throw new Error(\"[vitehub] Cloudflare KV does not support atomic operations. Use Upstash.\"); },",
4540
- " async keys(base, options) { const [error, storage] = await resolveStorageResult(name, \"keys\"); return error ? [error, undefined] : kvResult(\"keys\", name, () => storage.getKeys(base, options)); },",
4541
- " async list(options) { if (!Number.isInteger(options.limit) || options.limit <= 0) throw new TypeError(\"`limit` must be a positive integer.\"); const [error, storage] = await resolveStorageResult(name, \"list\"); return error ? [error, undefined] : kvResult(\"list\", name, () => storage.listKeys(options)); },",
4542
- " async set(key, value, options) { const [error, storage] = await resolveStorageResult(name, \"set\"); return error ? [error, undefined] : kvResult(\"set\", name, async () => { await storage.setItem(key, value, options); }); },",
4543
- " store(storeName) { return createKVStorage(storeName); },",
2839
+ " async clear(base, options) { return kvResult(\"clear\", name, async () => { await resolveStorage(name).clear(base, options); }); },",
2840
+ " async delete(key, options) { return kvResult(\"delete\", name, async () => { await resolveStorage(name).removeItem(key, options); }, kvKeyLimitCodes); },",
2841
+ " async deleteIfEquals() { return unsupported(\"deleteIfEquals\", name); },",
2842
+ " async get(key, options) { return kvResult(\"get\", name, () => resolveStorage(name).getItem(key, options), kvKeyLimitCodes); },",
2843
+ " async getAndDelete() { return unsupported(\"getAndDelete\", name); },",
2844
+ " async getMany(keys, options) { return kvResult(\"getMany\", name, () => resolveStorage(name).getMany(keys, options), kvKeyLimitCodes); },",
2845
+ " async has(key, options) { return kvResult(\"has\", name, () => resolveStorage(name).hasItem(key, options), kvKeyLimitCodes); },",
2846
+ " async increment() { return unsupported(\"increment\", name); },",
2847
+ " async keys(base, options) { return kvResult(\"keys\", name, () => resolveStorage(name).getKeys(base, options)); },",
2848
+ " lock() { return { async acquire() { return unsupported(\"lock\", name); }, async run() { return unsupported(\"lock\", name); } }; },",
2849
+ " async list(options) { if (!Number.isInteger(options.limit) || options.limit <= 0) return [kvInvalidLimitError(), undefined]; return kvResult(\"list\", name, () => resolveStorage(name).listKeys(options), [\"KV_INVALID_CURSOR\"]); },",
2850
+ " async set(key, value, options) { return kvResult(\"set\", name, async () => { await resolveStorage(name).setItem(key, value, options); }, kvWriteLimitCodes); },",
2851
+ " async setMany(entries, options) { return kvResult(\"setMany\", name, async () => { await resolveStorage(name).setMany(entries, options); }, kvWriteLimitCodes); },",
2852
+ " async setIfAbsent() { return unsupported(\"setIfAbsent\", name); },",
2853
+ " store(storeName, options) { return kvStoreWithMode(createKVStorage(storeName), options); },",
4544
2854
  " };",
4545
2855
  "}",
4546
2856
  "",
@@ -4549,11 +2859,11 @@ function serializeCloudflareRuntime(config) {
4549
2859
  ].join("\n");
4550
2860
  }
4551
2861
  function getNitroCloudflareKVNamespaces(target) {
4552
- if (!isPlainObject(target)) return [];
2862
+ if (!isRecord(target)) return [];
4553
2863
  const cloudflare = Reflect.get(target, "cloudflare");
4554
- if (!isPlainObject(cloudflare)) return [];
2864
+ if (!isRecord(cloudflare)) return [];
4555
2865
  const wrangler = Reflect.get(cloudflare, "wrangler");
4556
- if (!isPlainObject(wrangler)) return [];
2866
+ if (!isRecord(wrangler)) return [];
4557
2867
  const namespaces = Reflect.get(wrangler, "kv_namespaces");
4558
2868
  if (!Array.isArray(namespaces)) return [];
4559
2869
  return namespaces.flatMap((namespace) => {
@@ -4568,75 +2878,174 @@ function getNitroCloudflareKVNamespaces(target) {
4568
2878
  const id = Reflect.get(normalized, "id");
4569
2879
  const previewId = Reflect.get(normalized, "preview_id");
4570
2880
  const experimentalRemote = Reflect.get(normalized, "experimental_remote");
2881
+ const remote = Reflect.get(normalized, "remote");
4571
2882
  if (typeof binding !== "string") return [];
4572
2883
  if (id !== void 0 && typeof id !== "string") return [];
4573
2884
  if (previewId !== void 0 && typeof previewId !== "string") return [];
4574
2885
  if (experimentalRemote !== void 0 && typeof experimentalRemote !== "boolean") return [];
2886
+ if (remote !== void 0 && typeof remote !== "boolean") return [];
4575
2887
  return [normalized];
4576
2888
  });
4577
2889
  }
4578
2890
  function getResolvedNitroConfig(config) {
4579
2891
  return Reflect.get(config, "nitro");
4580
2892
  }
4581
- function reconcileNitroCloudflareKV(target, kv, ownedNamespaces) {
2893
+ function reconcileNitroCloudflareKV(target, kv, ownedNamespaces, provisionState) {
2894
+ configureNitroCloudflareRequestEnv(target, kv);
2895
+ configureNitroPlugin(target, kv);
2896
+ configureNitroStorage(target, kv);
4582
2897
  const namespaces = target.cloudflare?.wrangler?.kv_namespaces;
4583
2898
  if (namespaces?.length && ownedNamespaces.size) for (const owned of ownedNamespaces) {
4584
2899
  const ownedIndex = namespaces.findIndex((namespace) => namespace.binding === owned.binding && namespace.id === owned.id);
4585
2900
  if (ownedIndex !== -1) namespaces.splice(ownedIndex, 1);
4586
2901
  }
4587
- if (kv) configureCloudflareKV(target, kv);
2902
+ if (kv) configureCloudflareKV(target, kv, provisionState);
4588
2903
  }
4589
- function configureNitroCloudflareKV(config, options, ownedNamespaces) {
4590
- const { nitro } = config;
4591
- if (!isPlainObject(nitro)) return false;
2904
+ function configureNitroCloudflareKV(config, options, input, ownedNamespaces, provisionState) {
2905
+ const nitro = Reflect.get(config, "nitro");
2906
+ if (!isRecord(nitro)) return false;
4592
2907
  const target = nitro;
4593
2908
  const namespaces = target.cloudflare?.wrangler?.kv_namespaces;
4594
2909
  if (namespaces && ownedNamespaces.size) target.cloudflare.wrangler.kv_namespaces = namespaces.filter((namespace) => !ownedNamespaces.has(namespace));
4595
2910
  ownedNamespaces.clear();
4596
- const kv = resolveKVViteConfig(config.kv ?? options).kv;
2911
+ const kv = resolveKVViteConfig(options, input).kv;
2912
+ configureNitroCloudflareRequestEnv(target, kv);
2913
+ configureNitroPlugin(target, kv);
2914
+ configureNitroStorage(target, kv);
4597
2915
  if (kv) {
4598
2916
  const existingNamespaces = new Set(target.cloudflare?.wrangler?.kv_namespaces);
4599
- configureCloudflareKV(target, kv);
2917
+ configureCloudflareKV(target, kv, provisionState);
4600
2918
  for (const namespace of target.cloudflare?.wrangler?.kv_namespaces ?? []) if (!existingNamespaces.has(namespace)) ownedNamespaces.add(namespace);
4601
2919
  }
4602
2920
  return true;
4603
2921
  }
4604
- function hubKv(options) {
2922
+ /** `input.hosting` names the host preset for driver inference, as `vitehub()` passes it. Without it, KV reads the host from env. */
2923
+ function hubKV(options, input = {}) {
2924
+ let command = "build";
2925
+ let mode = "development";
2926
+ let viteEnv;
2927
+ let databasePlugin;
2928
+ const databaseImport = input.databaseImport ?? "@vite-hub/database/runtime/registry";
2929
+ const postgresDatabase = () => databasePlugin?.api?.getConfig?.()?.databases.default?.dialect === "postgresql";
2930
+ const resolutionInput = () => ({
2931
+ dev: command === "serve",
2932
+ env: command === "serve" ? viteEnv : void 0,
2933
+ hosting: input.hosting,
2934
+ postgresDatabase: postgresDatabase()
2935
+ });
4605
2936
  let nitroOwned = false;
2937
+ let redisEnvWarned = false;
4606
2938
  let nitroOptions;
4607
2939
  const ownedNitroNamespaces = /* @__PURE__ */ new Set();
4608
2940
  let resolved;
4609
2941
  let providerOutput;
4610
2942
  let runtimeConfig;
4611
- const getConfig = () => runtimeConfig ??= resolveKVViteConfig(options);
2943
+ let projectRoot = process.cwd();
2944
+ const getConfig = () => runtimeConfig ??= resolveKVViteConfig(options, resolutionInput());
4612
2945
  const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
4613
2946
  return {
4614
2947
  name: KV_VITE_PLUGIN_NAME,
4615
2948
  enforce: "post",
4616
- api: { getConfig },
2949
+ api: {
2950
+ deploymentEnv: () => kvDeploymentEnv(getConfig().kv),
2951
+ getConfig
2952
+ },
4617
2953
  nitro: {
4618
2954
  name: "@vite-hub/kv/cloudflare-bindings",
4619
2955
  setup(nitro) {
4620
2956
  nitroOptions = nitro.options;
4621
- if (runtimeConfig) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces);
2957
+ if (runtimeConfig) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, readProvisionStateSync(projectRoot));
2958
+ }
2959
+ },
2960
+ vitehub: {
2961
+ durability: () => {
2962
+ const kv = getConfig().kv;
2963
+ if (!kv) return [];
2964
+ return [{
2965
+ export: "kvDurability",
2966
+ input: { stores: Object.fromEntries(Object.entries({
2967
+ default: kv.store,
2968
+ ...kv.stores
2969
+ }).map(([name, store]) => {
2970
+ const database = Reflect.get(store, "database");
2971
+ return [name, {
2972
+ driver: store.driver,
2973
+ ..."base" in store && store.base ? { base: store.base } : {},
2974
+ ...typeof database === "string" ? { database } : {}
2975
+ }];
2976
+ })) },
2977
+ module: durabilityModuleFile(import.meta.url),
2978
+ primitive: "kv"
2979
+ }];
2980
+ },
2981
+ inspect: () => {
2982
+ const build = resolveKVViteConfig(options, {
2983
+ hosting: input.hosting,
2984
+ postgresDatabase: postgresDatabase()
2985
+ }).kv;
2986
+ const dev = resolveKVViteConfig(options, {
2987
+ dev: true,
2988
+ env: viteEnv,
2989
+ hosting: input.hosting
2990
+ }).kv;
2991
+ if (!build || !dev) return;
2992
+ const file = resolved?.configFile ? relativeDefinitionFile(projectRoot, resolved.configFile) : "vite.config.ts";
2993
+ return {
2994
+ definitions: [{
2995
+ kind: "kv",
2996
+ label: "KV stores",
2997
+ list: () => inspectKVStores(build, dev, file)
2998
+ }],
2999
+ resources: () => inspectKVResources(options, projectRoot)
3000
+ };
3001
+ },
3002
+ operations: [{
3003
+ export: "kvOperations",
3004
+ load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).kvOperations,
3005
+ module: operationsModule
3006
+ }],
3007
+ cli: async () => {
3008
+ const { createKVCliContributor } = await import(
3009
+ /* @vite-ignore */
3010
+ "./cli.js"
3011
+ );
3012
+ return {
3013
+ ...createKVCliContributor({ projectRoot: () => projectRoot }),
3014
+ provision: [createKVCloudflareProvisionStep(() => options)]
3015
+ };
4622
3016
  }
4623
3017
  },
4624
3018
  config: {
4625
3019
  order: "pre",
4626
- handler(config) {
4627
- nitroOwned = configureNitroCloudflareKV(config, options, ownedNitroNamespaces);
3020
+ async handler(config, env) {
3021
+ command = env?.command ?? "build";
3022
+ mode = env?.mode ?? config.mode ?? (command === "serve" ? "development" : "production");
3023
+ runtimeConfig = void 0;
3024
+ projectRoot = resolveViteHubProjectRoot(config.root || process.cwd());
3025
+ viteEnv = loadAllEnv((await import("vite")).loadEnv, mode, config.envDir === false ? false : resolve(config.root || process.cwd(), config.envDir ?? "."));
3026
+ nitroOwned = configureNitroCloudflareKV(config, options, resolutionInput(), ownedNitroNamespaces, readProvisionStateSync(projectRoot));
3027
+ return installStandaloneOperationRpc(config, env?.command ?? "build", operationsModule);
4628
3028
  }
4629
3029
  },
4630
3030
  configResolved: {
4631
3031
  order: "pre",
4632
- handler(config) {
3032
+ async handler(config) {
4633
3033
  resolved = config;
3034
+ if (config.command) command = config.command;
3035
+ mode = config.mode ?? mode;
3036
+ projectRoot = resolveViteHubProjectRoot(config.root || process.cwd());
3037
+ viteEnv = loadAllEnv((await import("vite")).loadEnv, mode, config.envDir === false ? false : resolve(config.root || process.cwd(), config.envDir ?? "."));
3038
+ databasePlugin = findDatabasePlugin(config.plugins);
4634
3039
  providerOutput = useProviderOutputCatalog(config);
4635
- runtimeConfig = resolveKVViteConfig(config.kv ?? options);
4636
- if (nitroOptions) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces);
4637
- if (hasNitroConfigContext(config) || isPlainObject(getResolvedNitroConfig(config))) nitroOwned = configureNitroCloudflareKV(config, options, ownedNitroNamespaces);
3040
+ runtimeConfig = resolveKVViteConfig(options, resolutionInput());
3041
+ const provisionState = readProvisionStateSync(projectRoot);
3042
+ if (nitroOptions) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, provisionState);
3043
+ if (hasNitroConfigContext(config) || isRecord(getResolvedNitroConfig(config))) nitroOwned = configureNitroCloudflareKV(config, options, resolutionInput(), ownedNitroNamespaces, provisionState);
4638
3044
  }
4639
3045
  },
3046
+ configureServer(server) {
3047
+ publishStandaloneOperationServer(server);
3048
+ },
4640
3049
  configEnvironment: {
4641
3050
  order: "pre",
4642
3051
  handler(name, config) {
@@ -4646,29 +3055,51 @@ function hubKv(options) {
4646
3055
  },
4647
3056
  resolveId: {
4648
3057
  order: "pre",
3058
+ filter: { id: RESOLVE_ID_PATTERN },
4649
3059
  handler(id, importer, resolveOptions) {
4650
- if (id === UPSTASH_DRIVER_IMPORT_ID && resolveOptions?.ssr && !hasUpstashStore(getConfig().kv) && isKVOptionalUpstashImport(id, importer)) return {
3060
+ if (id === UPSTASH_DRIVER_IMPORT_ID && resolveOptions?.ssr && !hasUpstashStore(getConfig().kv) && isKVOptionalDriverImport(UPSTASH_DRIVER_IMPORT_ID, id, importer)) return {
4651
3061
  external: true,
4652
3062
  id
4653
3063
  };
4654
- if (id === "@vite-hub/kv" && isCloudflareKVConfig(getConfig().kv)) return RESOLVED_KV_RUNTIME_ID;
3064
+ if (id === REDIS_DRIVER_IMPORT_ID && resolveOptions?.ssr && !hasRedisStore(getConfig().kv) && isKVOptionalDriverImport(REDIS_DRIVER_IMPORT_ID, id, importer)) return {
3065
+ external: true,
3066
+ id
3067
+ };
3068
+ if (resolveOptions?.ssr && isUnstorageCloudflareWorkersImport(id, importer)) return {
3069
+ external: true,
3070
+ id
3071
+ };
3072
+ if (id === "@vite-hub/kv" && command === "build" && isCloudflareKVConfig(getConfig().kv)) return RESOLVED_KV_RUNTIME_ID;
4655
3073
  if (id === "#vitehub/kv/config") return RESOLVED_KV_VIRTUAL_CONFIG_ID;
4656
3074
  }
4657
3075
  },
4658
3076
  load: {
4659
3077
  order: "pre",
4660
- handler(id) {
3078
+ filter: { id: LOAD_ID_PATTERN },
3079
+ handler(id, options) {
4661
3080
  if (id === RESOLVED_KV_RUNTIME_ID) {
4662
3081
  const kv = getConfig().kv;
4663
- if (isCloudflareKVConfig(kv)) return serializeCloudflareRuntime(kv);
3082
+ if (command === "build" && isCloudflareKVConfig(kv)) return serializeCloudflareRuntime(kv);
4664
3083
  }
4665
- if (id === RESOLVED_KV_VIRTUAL_CONFIG_ID) return serializeVirtualConfig(getConfig());
3084
+ if (id === RESOLVED_KV_VIRTUAL_CONFIG_ID) return serializeVirtualConfig(getConfig(), databaseImport, command === "serve" && options?.ssr ? viteEnv : void 0);
4666
3085
  }
4667
3086
  },
4668
3087
  buildStart: {
4669
3088
  order: "pre",
4670
3089
  handler() {
3090
+ runtimeConfig = void 0;
4671
3091
  providerOutputGenerations.capture(this, providerOutput);
3092
+ if (command !== "build" || redisEnvWarned) return;
3093
+ redisEnvWarned = true;
3094
+ const warning = kvRedisEnvWarning(options, {
3095
+ ...resolutionInput(),
3096
+ env: {
3097
+ ...viteEnv,
3098
+ ...process.env
3099
+ },
3100
+ hosting: getConfig().hosting
3101
+ });
3102
+ if (warning) console.warn(warning);
4672
3103
  }
4673
3104
  },
4674
3105
  buildEnd: {
@@ -4678,10 +3109,10 @@ function hubKv(options) {
4678
3109
  await providerOutputGenerations.reset(this, providerOutput, error);
4679
3110
  return;
4680
3111
  }
4681
- if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
3112
+ if (!resolved || shouldSkipViteProviderBuild(resolved.command)) return;
4682
3113
  const rootDir = resolved.root;
4683
3114
  const clientOutDir = resolved.build.outDir;
4684
- const wranglerConfig = nitroOwned ? void 0 : createCloudflareKVWranglerConfig(getConfig().kv);
3115
+ const wranglerConfig = nitroOwned ? void 0 : createCloudflareKVWranglerConfig(getConfig().kv, readProvisionStateSync(projectRoot));
4685
3116
  const nextBindings = wranglerConfig?.kv_namespaces?.map((binding) => binding.binding) ?? [];
4686
3117
  const wranglerConfigOwnership = { arrays: { kv_namespaces: {
4687
3118
  key: "binding",
@@ -4718,11 +3149,11 @@ function hubKv(options) {
4718
3149
  order: "post",
4719
3150
  sequential: true,
4720
3151
  async handler() {
4721
- if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
3152
+ if (!resolved || shouldSkipViteProviderBuild(resolved.command)) return;
4722
3153
  await finalizeProviderDeploymentOutputs(providerOutput);
4723
3154
  }
4724
3155
  }
4725
3156
  };
4726
3157
  }
4727
3158
  //#endregion
4728
- export { KV_VIRTUAL_CONFIG_ID, KV_VITE_PLUGIN_NAME, hubKv, hubKvOptionalPeerResolver, resolveKVViteConfig };
3159
+ export { KV_VIRTUAL_CONFIG_ID, KV_VITE_PLUGIN_NAME, hubKV, hubKVOptionalPeerResolver, kvStorageDriver, resolveKVViteConfig };