@vite-hub/kv 0.1.0 → 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 (67) hide show
  1. package/README.md +86 -15
  2. package/dist/batch--v0ri69O.js +40 -0
  3. package/dist/cli-DpPhz_Ek.d.ts +163 -0
  4. package/dist/cli.d.ts +4 -2
  5. package/dist/cli.js +98 -77
  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/{create-storage-29gMzf41.js → create-storage-BGsrQKw3.js} +206 -50
  12. package/dist/{cursor-history-dqYDlsaD.js → cursor-history-BqIQePNP.js} +31 -14
  13. package/dist/database-72Jk3VVk.js +250 -0
  14. package/dist/{deno-kv-CSYGvRx4.js → deno-kv-BM9mYdUp.js} +12 -4
  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 +12 -1
  22. package/dist/errors.js +2 -2
  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 +7 -2
  26. package/dist/index.js +302 -75
  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/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  32. package/dist/operations-B-WZ7P1h.js +1351 -0
  33. package/dist/{operations-pn8_eGob.js → operations-Ch-gKaey.js} +67 -58
  34. package/dist/operations.d.ts +15 -8
  35. package/dist/operations.js +55 -192
  36. package/dist/redis-shared-E5mahECF.js +94 -0
  37. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  38. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  39. package/dist/runtime/cloudflare-kv.js +1 -99
  40. package/dist/runtime/cloudflare-request-env.d.ts +7 -0
  41. package/dist/runtime/cloudflare-request-env.js +11 -0
  42. package/dist/runtime/nitro-plugin.d.ts +12 -0
  43. package/dist/runtime/nitro-plugin.js +22 -0
  44. package/dist/runtime/redis-driver.d.ts +11 -0
  45. package/dist/runtime/redis-driver.js +113 -0
  46. package/dist/runtime/unstorage-driver.d.ts +14 -0
  47. package/dist/runtime/unstorage-driver.js +33 -0
  48. package/dist/runtime/upstash-driver.d.ts +2 -2
  49. package/dist/runtime/upstash-driver.js +58 -98
  50. package/dist/{driver-D9fI27jl.d.ts → types-Bj3EQoRg.d.ts} +16 -41
  51. package/dist/types-DEiKew_3.d.ts +312 -0
  52. package/dist/upstash-DDlqTttY.js +40 -0
  53. package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
  54. package/dist/virtual-module.d.ts +2 -0
  55. package/dist/vite.d.ts +152 -11
  56. package/dist/vite.js +888 -2836
  57. package/package.json +30 -21
  58. package/dist/cli-Cniq99iX.d.ts +0 -85
  59. package/dist/cloudflare-env-C5rM7kUY.js +0 -74
  60. package/dist/config-DR6_5ZwI.js +0 -124
  61. package/dist/continuations-DPyH_vr1.js +0 -63
  62. package/dist/error-diagnostics-D_cQeZTi.js +0 -82
  63. package/dist/errors-Dc2oiW-Y.js +0 -38
  64. package/dist/fs-lite-CbLKxLut.js +0 -90
  65. package/dist/object-B1NW521B.js +0 -7
  66. package/dist/operations-ByuDE12r.js +0 -1442
  67. package/dist/types-CMDvN0Wr.d.ts +0 -81
package/dist/vite.js CHANGED
@@ -1,117 +1,49 @@
1
- import { t as isPlainObject } from "./object-B1NW521B.js";
2
- import { S as writeViteHubDevServerFile, _ as resolveViteHubProjectRoot, c as operationRpcPath, g as isServerEnvironment, h as hasNitroConfigContext, m as createNoExternalAddition, p as internalErrorDiagnostics, r as collectOperationContributions, v as shouldSkipViteProviderBuild, x as removeViteHubDevServerFile, y as readViteHubDevServerFile } from "./operations-ByuDE12r.js";
3
- import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
4
- import { i as resolveHostPreset, t as normalizeKVOptions } from "./config-DR6_5ZwI.js";
5
- import { createRequire } from "node:module";
6
- import { cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
7
- import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
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";
8
13
  import { existsSync, readFileSync, renameSync, rmSync } from "node:fs";
9
14
  import { tmpdir } from "node:os";
10
- import { Diagnostic } from "nostics";
11
15
  import { fileURLToPath } from "node:url";
12
- //#region \0rolldown/runtime.js
13
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
14
- var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
15
- //#endregion
16
- //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
17
- const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
18
- function normalizeWindowsPath(input = "") {
19
- if (!input) return input;
20
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
21
- }
22
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
23
- const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
24
- const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
25
- function cwd() {
26
- if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
27
- return "/";
28
- }
29
- const resolve$1 = function(...arguments_) {
30
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
31
- let resolvedPath = "";
32
- let resolvedAbsolute = false;
33
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
34
- const path = index >= 0 ? arguments_[index] : cwd();
35
- if (!path || path.length === 0) continue;
36
- resolvedPath = `${path}/${resolvedPath}`;
37
- resolvedAbsolute = isAbsolute$1(path);
38
- }
39
- resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
40
- if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
41
- return resolvedPath.length > 0 ? resolvedPath : ".";
42
- };
43
- function normalizeString(path, allowAboveRoot) {
44
- let res = "";
45
- let lastSegmentLength = 0;
46
- let lastSlash = -1;
47
- let dots = 0;
48
- let char = null;
49
- for (let index = 0; index <= path.length; ++index) {
50
- if (index < path.length) char = path[index];
51
- else if (char === "/") break;
52
- else char = "/";
53
- if (char === "/") {
54
- if (lastSlash === index - 1 || dots === 1);
55
- else if (dots === 2) {
56
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
57
- if (res.length > 2) {
58
- const lastSlashIndex = res.lastIndexOf("/");
59
- if (lastSlashIndex === -1) {
60
- res = "";
61
- lastSegmentLength = 0;
62
- } else {
63
- res = res.slice(0, lastSlashIndex);
64
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
65
- }
66
- lastSlash = index;
67
- dots = 0;
68
- continue;
69
- } else if (res.length > 0) {
70
- res = "";
71
- lastSegmentLength = 0;
72
- lastSlash = index;
73
- dots = 0;
74
- continue;
75
- }
76
- }
77
- if (allowAboveRoot) {
78
- res += res.length > 0 ? "/.." : "..";
79
- lastSegmentLength = 2;
80
- }
81
- } else {
82
- if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
83
- else res = path.slice(lastSlash + 1, index);
84
- lastSegmentLength = index - lastSlash - 1;
85
- }
86
- lastSlash = index;
87
- dots = 0;
88
- } else if (char === "." && dots !== -1) ++dots;
89
- else dots = -1;
90
- }
91
- return res;
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);
92
43
  }
93
- const isAbsolute$1 = function(p) {
94
- return _IS_ABSOLUTE_RE.test(p);
95
- };
96
- const relative$1 = function(from, to) {
97
- const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
98
- const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
99
- if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
100
- const _fromCopy = [..._from];
101
- for (const segment of _fromCopy) {
102
- if (_to[0] !== segment) break;
103
- _from.shift();
104
- _to.shift();
105
- }
106
- return [..._from.map(() => ".."), ..._to].join("/");
107
- };
108
- const dirname$1 = function(p) {
109
- const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
110
- if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
111
- return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
112
- };
113
44
  //#endregion
114
45
  //#region ../internal/src/definition-catalog.ts
46
+ /** `writeFileIfChangedSync` for async callers. */
115
47
  async function writeFileIfChanged(file, contents) {
116
48
  if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
117
49
  await mkdir(resolve$1(file, ".."), { recursive: true });
@@ -122,15 +54,12 @@ async function writeFileIfChanged(file, contents) {
122
54
  function cloneArray(value) {
123
55
  return Array.isArray(value) ? [...value] : [];
124
56
  }
125
- function isRecord(value) {
126
- return Object(value) === value && !Array.isArray(value);
127
- }
128
57
  function sameHandler(left, right) {
129
58
  return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
130
59
  }
131
60
  /** Create a Nitro 3 configuration builder for generated ViteHub output. */
132
61
  function createNitroServerKit(value = {}) {
133
- const config = isRecord(value) ? { ...value } : {};
62
+ const config = isRecordOrFunction(value) ? { ...value } : {};
134
63
  const handlers = cloneArray(config.handlers);
135
64
  const plugins = cloneArray(config.plugins);
136
65
  config.handlers = handlers;
@@ -138,7 +67,7 @@ function createNitroServerKit(value = {}) {
138
67
  return {
139
68
  config,
140
69
  addHandler(handler, position = "end") {
141
- if (handlers.some((candidate) => isRecord(candidate) && sameHandler(candidate, handler))) return;
70
+ if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
142
71
  if (position === "start") handlers.unshift({ ...handler });
143
72
  else handlers.push({ ...handler });
144
73
  },
@@ -159,7 +88,7 @@ async function flattenPlugins(value, plugins, seen) {
159
88
  for (const item of value) await flattenPlugins(item, plugins, seen);
160
89
  return;
161
90
  }
162
- if (!isPlainObject(value) || seen.has(value)) return;
91
+ if (!isRecord(value) || seen.has(value)) return;
163
92
  seen.add(value);
164
93
  if (isThenable(value)) {
165
94
  await flattenPlugins(await value, plugins, seen);
@@ -179,17 +108,19 @@ async function flattenPluginOptions(plugins) {
179
108
  }
180
109
  //#endregion
181
110
  //#region ../internal/src/operations-vite.ts
182
- const owners = /* @__PURE__ */ new Set([
183
- "@vite-hub/kv/operations",
184
- "@vite-hub/blob/operations",
185
- "@vite-hub/email/operations",
186
- "@vite-hub/rate-limit/operations"
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"
187
118
  ]);
188
119
  const discoveryInstalled = Symbol.for("vitehub.operations.dev.discovery");
189
120
  /** Publish only the elected standalone transport; other Console policies retain their own discovery hook. */
190
121
  function publishStandaloneOperationServer(server) {
191
122
  const http = server.httpServer;
192
- if (!http || Reflect.get(server, discoveryInstalled)) return;
123
+ if (!http || server.config.server.middlewareMode || Reflect.get(server, discoveryInstalled)) return;
193
124
  const root = resolve(server.config.root);
194
125
  const handlers = Reflect.get(Object(Reflect.get(server.config, "nitro")), "handlers");
195
126
  if (!Array.isArray(handlers) || !handlers.some((handler) => handler?.handler === resolve(root, ".vitehub/nitro/operations/rpc.mjs"))) return;
@@ -222,11 +153,12 @@ async function installStandaloneOperationRpc(config, command, module) {
222
153
  const plugins = await flattenPluginOptions(config.plugins);
223
154
  if (plugins.some((plugin) => Reflect.get(plugin, "name") === "vite-hub/dependencies" || Reflect.get(plugin, "name") === "vite-hub/console")) return;
224
155
  const contributions = (await collectOperationContributions(plugins)).filter((source) => source.runtime !== false);
225
- if (contributions.find((source) => owners.has(source.module))?.module !== module) return;
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;
226
158
  const root = resolve(config.root ?? process.cwd());
227
159
  const handler = resolve(root, ".vitehub/nitro/operations/rpc.mjs");
228
160
  await writeFileIfChanged(handler, [
229
- `import { createStandaloneOperationHandler } from ${JSON.stringify(module)}`,
161
+ `import { createStandaloneOperationHandler } from ${JSON.stringify(owner.module)}`,
230
162
  ...contributions.map((entry, index) => `import * as source${index} from ${JSON.stringify(entry.module)}`),
231
163
  `export default createStandaloneOperationHandler([${contributions.map((entry, index) => `{ operations: source${index}[${JSON.stringify(entry.export)}], plugin: ${JSON.stringify(entry.plugin)} }`).join(", ")}], ${JSON.stringify(root)})`,
232
164
  ""
@@ -236,9 +168,19 @@ async function installStandaloneOperationRpc(config, command, module) {
236
168
  handler,
237
169
  route: operationRpcPath
238
170
  });
171
+ const devHandlers = kit.config.devHandlers;
172
+ const signed = Array.isArray(devHandlers) ? [...devHandlers] : [];
173
+ addViteHubDevPeerDevHandler(signed);
174
+ kit.config.devHandlers = signed;
239
175
  Reflect.set(config, "nitro", kit.config);
240
176
  }
241
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
+ }
183
+ //#endregion
242
184
  //#region src/vite-config.ts
243
185
  const KV_VITE_PLUGIN_NAME = "@vite-hub/kv/vite";
244
186
  const KV_VIRTUAL_CONFIG_ID = "#vitehub/kv/config";
@@ -251,8 +193,10 @@ function resolveKVViteConfig(kv, input = {}) {
251
193
  return {
252
194
  hosting,
253
195
  kv: normalizeKVOptions(kv, {
196
+ dev: input.dev,
254
197
  env,
255
- hosting
198
+ hosting,
199
+ postgresDatabase: input.postgresDatabase
256
200
  }) ?? false
257
201
  };
258
202
  }
@@ -395,2425 +339,88 @@ async function persistProviderJsonRecord(file, value, removeIfEmpty) {
395
339
  await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
396
340
  }
397
341
  async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
398
- const existing = await readProviderJsonRecord(file) ?? {};
399
- const defaults = options.defaults ?? {};
400
- assertProviderJsonRecord(defaults);
401
- await persistProviderJsonRecord(file, mergeProviderOutputConfig({
402
- ...defaults,
403
- ...existing
404
- }, value, ownership), options.removeIfEmpty === true);
405
- }
406
- function mergeProviderOutputConfig(existing, value, ownership = {}) {
407
- assertProviderJsonRecord(existing);
408
- assertProviderJsonRecord(value);
409
- return {
410
- ...deleteOwnedFields(existing, ownership),
411
- ...mergeOwnedArrays(existing, value, ownership.arrays)
412
- };
413
- }
414
- function stringifyProviderOutputConfig(value) {
415
- assertProviderJsonRecord(value);
416
- return JSON.stringify(value, null, 2);
417
- }
418
- async function cleanProviderOutputConfig(file, ownership) {
419
- if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
420
- const existing = await readProviderJsonRecord(file);
421
- if (!existing) return;
422
- const next = deleteOwnedFields(existing, ownership, true);
423
- let changed = (ownership.keys ?? []).some((key) => key in existing);
424
- for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
425
- if (arrayOwnership.preserveOnCleanup) continue;
426
- if (!(field in existing)) continue;
427
- const current = existing[field];
428
- const retained = arrayOwnership.retainOnCleanup ?? [];
429
- const preserved = [...preserveUnownedKeyedArrayEntries(current, arrayOwnership, retained), ...retained];
430
- changed ||= retained.length > 0 || !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
431
- if (preserved.length) next[field] = preserved;
432
- }
433
- if (!changed) return;
434
- await persistProviderJsonRecord(file, next, true);
435
- }
436
- //#endregion
437
- //#region ../internal/src/build/user-entry.ts
438
- function toSafeAppName(rootDir) {
439
- return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
440
- }
441
- //#endregion
442
- //#region ../internal/src/build/cloudflare.ts
443
- function createDefaultCloudflareOutputRoot(rootDir) {
444
- return resolve(rootDir, "dist", toSafeAppName(rootDir));
445
- }
446
- async function writeCloudflareWranglerConfig(options) {
447
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
448
- const configFile = resolve(outputRoot, "wrangler.json");
449
- if (!options.wranglerConfig) {
450
- await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
451
- return;
452
- }
453
- await mkdir(outputRoot, { recursive: true });
454
- await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, {
455
- defaults: options.wranglerConfigDefaults,
456
- removeIfEmpty: true
457
- });
458
- }
459
- //#endregion
460
- //#region ../internal/src/build/esbuild.ts
461
- var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
462
- var __defProp = Object.defineProperty;
463
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
464
- var __getOwnPropNames = Object.getOwnPropertyNames;
465
- var __hasOwnProp = Object.prototype.hasOwnProperty;
466
- var __export = (target, all) => {
467
- for (var name in all) __defProp(target, name, {
468
- get: all[name],
469
- enumerable: true
470
- });
471
- };
472
- var __copyProps = (to, from, except, desc) => {
473
- if (from && typeof from === "object" || typeof from === "function") {
474
- for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
475
- get: () => from[key],
476
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
477
- });
478
- }
479
- return to;
480
- };
481
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
482
- var node_exports = {};
483
- __export(node_exports, {
484
- analyzeMetafile: () => analyzeMetafile,
485
- analyzeMetafileSync: () => analyzeMetafileSync,
486
- build: () => build,
487
- buildSync: () => buildSync,
488
- context: () => context,
489
- default: () => node_default,
490
- formatMessages: () => formatMessages,
491
- formatMessagesSync: () => formatMessagesSync,
492
- initialize: () => initialize,
493
- stop: () => stop,
494
- transform: () => transform,
495
- transformSync: () => transformSync,
496
- version: () => version
497
- });
498
- module.exports = __toCommonJS(node_exports);
499
- function encodePacket(packet) {
500
- let visit = (value) => {
501
- if (value === null) bb.write8(0);
502
- else if (typeof value === "boolean") {
503
- bb.write8(1);
504
- bb.write8(+value);
505
- } else if (typeof value === "number") {
506
- bb.write8(2);
507
- bb.write32(value | 0);
508
- } else if (typeof value === "string") {
509
- bb.write8(3);
510
- bb.write(encodeUTF8(value));
511
- } else if (value instanceof Uint8Array) {
512
- bb.write8(4);
513
- bb.write(value);
514
- } else if (value instanceof Array) {
515
- bb.write8(5);
516
- bb.write32(value.length);
517
- for (let item of value) visit(item);
518
- } else {
519
- let keys = Object.keys(value);
520
- bb.write8(6);
521
- bb.write32(keys.length);
522
- for (let key of keys) {
523
- bb.write(encodeUTF8(key));
524
- visit(value[key]);
525
- }
526
- }
527
- };
528
- let bb = new ByteBuffer();
529
- bb.write32(0);
530
- bb.write32(packet.id << 1 | +!packet.isRequest);
531
- visit(packet.value);
532
- writeUInt32LE(bb.buf, bb.len - 4, 0);
533
- return bb.buf.subarray(0, bb.len);
534
- }
535
- function decodePacket(bytes) {
536
- let visit = () => {
537
- switch (bb.read8()) {
538
- case 0: return null;
539
- case 1: return !!bb.read8();
540
- case 2: return bb.read32();
541
- case 3: return decodeUTF8(bb.read());
542
- case 4: return bb.read();
543
- case 5: {
544
- let count = bb.read32();
545
- let value2 = [];
546
- for (let i = 0; i < count; i++) value2.push(visit());
547
- return value2;
548
- }
549
- case 6: {
550
- let count = bb.read32();
551
- let value2 = {};
552
- for (let i = 0; i < count; i++) value2[decodeUTF8(bb.read())] = visit();
553
- return value2;
554
- }
555
- default: throw new Error("Invalid packet");
556
- }
557
- };
558
- let bb = new ByteBuffer(bytes);
559
- let id = bb.read32();
560
- let isRequest = (id & 1) === 0;
561
- id >>>= 1;
562
- let value = visit();
563
- if (bb.ptr !== bytes.length) throw new Error("Invalid packet");
564
- return {
565
- id,
566
- isRequest,
567
- value
568
- };
569
- }
570
- var ByteBuffer = class {
571
- constructor(buf = /* @__PURE__ */ new Uint8Array(1024)) {
572
- this.buf = buf;
573
- this.len = 0;
574
- this.ptr = 0;
575
- }
576
- _write(delta) {
577
- if (this.len + delta > this.buf.length) {
578
- let clone = new Uint8Array((this.len + delta) * 2);
579
- clone.set(this.buf);
580
- this.buf = clone;
581
- }
582
- this.len += delta;
583
- return this.len - delta;
584
- }
585
- write8(value) {
586
- let offset = this._write(1);
587
- this.buf[offset] = value;
588
- }
589
- write32(value) {
590
- let offset = this._write(4);
591
- writeUInt32LE(this.buf, value, offset);
592
- }
593
- write(bytes) {
594
- let offset = this._write(4 + bytes.length);
595
- writeUInt32LE(this.buf, bytes.length, offset);
596
- this.buf.set(bytes, offset + 4);
597
- }
598
- _read(delta) {
599
- if (this.ptr + delta > this.buf.length) throw new Error("Invalid packet");
600
- this.ptr += delta;
601
- return this.ptr - delta;
602
- }
603
- read8() {
604
- return this.buf[this._read(1)];
605
- }
606
- read32() {
607
- return readUInt32LE(this.buf, this._read(4));
608
- }
609
- read() {
610
- let length = this.read32();
611
- let bytes = new Uint8Array(length);
612
- let ptr = this._read(bytes.length);
613
- bytes.set(this.buf.subarray(ptr, ptr + length));
614
- return bytes;
615
- }
616
- };
617
- var encodeUTF8;
618
- var decodeUTF8;
619
- var encodeInvariant;
620
- if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") {
621
- let encoder = new TextEncoder();
622
- let decoder = new TextDecoder();
623
- encodeUTF8 = (text) => encoder.encode(text);
624
- decodeUTF8 = (bytes) => decoder.decode(bytes);
625
- encodeInvariant = "new TextEncoder().encode(\"\")";
626
- } else if (typeof Buffer !== "undefined") {
627
- encodeUTF8 = (text) => Buffer.from(text);
628
- decodeUTF8 = (bytes) => {
629
- let { buffer, byteOffset, byteLength } = bytes;
630
- return Buffer.from(buffer, byteOffset, byteLength).toString();
631
- };
632
- encodeInvariant = "Buffer.from(\"\")";
633
- } else throw new Error("No UTF-8 codec found");
634
- if (!(encodeUTF8("") instanceof Uint8Array)) throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false
635
-
636
- This indicates that your JavaScript environment is broken. You cannot use
637
- esbuild in this environment because esbuild relies on this invariant. This
638
- is not a problem with esbuild. You need to fix your environment instead.
639
- `);
640
- function readUInt32LE(buffer, offset) {
641
- return (buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24) >>> 0;
642
- }
643
- function writeUInt32LE(buffer, value, offset) {
644
- buffer[offset++] = value;
645
- buffer[offset++] = value >> 8;
646
- buffer[offset++] = value >> 16;
647
- buffer[offset++] = value >> 24;
648
- }
649
- var fromCharCode = String.fromCharCode;
650
- function throwSyntaxError(bytes, index, message) {
651
- const c = bytes[index];
652
- let line = 1;
653
- let column = 0;
654
- for (let i = 0; i < index; i++) if (bytes[i] === 10) {
655
- line++;
656
- column = 0;
657
- } else column++;
658
- 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})`);
659
- }
660
- function JSON_parse(bytes) {
661
- if (!(bytes instanceof Uint8Array)) throw new Error(`JSON input must be a Uint8Array`);
662
- const propertyStack = [];
663
- const objectStack = [];
664
- const stateStack = [];
665
- const length = bytes.length;
666
- let property = null;
667
- let state = 0;
668
- let object;
669
- let i = 0;
670
- while (i < length) {
671
- let c = bytes[i++];
672
- if (c <= 32) continue;
673
- let value;
674
- if (state === 2 && property === null && c !== 34 && c !== 125) throwSyntaxError(bytes, --i);
675
- switch (c) {
676
- case 116:
677
- if (bytes[i++] !== 114 || bytes[i++] !== 117 || bytes[i++] !== 101) throwSyntaxError(bytes, --i);
678
- value = true;
679
- break;
680
- case 102:
681
- if (bytes[i++] !== 97 || bytes[i++] !== 108 || bytes[i++] !== 115 || bytes[i++] !== 101) throwSyntaxError(bytes, --i);
682
- value = false;
683
- break;
684
- case 110:
685
- if (bytes[i++] !== 117 || bytes[i++] !== 108 || bytes[i++] !== 108) throwSyntaxError(bytes, --i);
686
- value = null;
687
- break;
688
- case 45:
689
- case 46:
690
- case 48:
691
- case 49:
692
- case 50:
693
- case 51:
694
- case 52:
695
- case 53:
696
- case 54:
697
- case 55:
698
- case 56:
699
- case 57: {
700
- let index = i;
701
- value = fromCharCode(c);
702
- c = bytes[i];
703
- while (true) {
704
- switch (c) {
705
- case 43:
706
- case 45:
707
- case 46:
708
- case 48:
709
- case 49:
710
- case 50:
711
- case 51:
712
- case 52:
713
- case 53:
714
- case 54:
715
- case 55:
716
- case 56:
717
- case 57:
718
- case 101:
719
- case 69:
720
- value += fromCharCode(c);
721
- c = bytes[++i];
722
- continue;
723
- }
724
- break;
725
- }
726
- value = +value;
727
- if (isNaN(value)) throwSyntaxError(bytes, --index, "Invalid number");
728
- break;
729
- }
730
- case 34:
731
- value = "";
732
- while (true) {
733
- if (i >= length) throwSyntaxError(bytes, length);
734
- c = bytes[i++];
735
- if (c === 34) break;
736
- else if (c === 92) switch (bytes[i++]) {
737
- case 34:
738
- value += "\"";
739
- break;
740
- case 47:
741
- value += "/";
742
- break;
743
- case 92:
744
- value += "\\";
745
- break;
746
- case 98:
747
- value += "\b";
748
- break;
749
- case 102:
750
- value += "\f";
751
- break;
752
- case 110:
753
- value += "\n";
754
- break;
755
- case 114:
756
- value += "\r";
757
- break;
758
- case 116:
759
- value += " ";
760
- break;
761
- case 117: {
762
- let code = 0;
763
- for (let j = 0; j < 4; j++) {
764
- c = bytes[i++];
765
- code <<= 4;
766
- if (c >= 48 && c <= 57) code |= c - 48;
767
- else if (c >= 97 && c <= 102) code |= c + -87;
768
- else if (c >= 65 && c <= 70) code |= c + -55;
769
- else throwSyntaxError(bytes, --i);
770
- }
771
- value += fromCharCode(code);
772
- break;
773
- }
774
- default: throwSyntaxError(bytes, --i);
775
- }
776
- else if (c <= 127) value += fromCharCode(c);
777
- else if ((c & 224) === 192) value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
778
- else if ((c & 240) === 224) value += fromCharCode((c & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63);
779
- else if ((c & 248) == 240) {
780
- let codePoint = (c & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
781
- if (codePoint > 65535) {
782
- codePoint -= 65536;
783
- value += fromCharCode(codePoint >> 10 & 1023 | 55296);
784
- codePoint = 56320 | codePoint & 1023;
785
- }
786
- value += fromCharCode(codePoint);
787
- }
788
- }
789
- value[0];
790
- break;
791
- case 91:
792
- value = [];
793
- propertyStack.push(property);
794
- objectStack.push(object);
795
- stateStack.push(state);
796
- property = null;
797
- object = value;
798
- state = 1;
799
- continue;
800
- case 123:
801
- value = {};
802
- propertyStack.push(property);
803
- objectStack.push(object);
804
- stateStack.push(state);
805
- property = null;
806
- object = value;
807
- state = 2;
808
- continue;
809
- case 93:
810
- if (state !== 1) throwSyntaxError(bytes, --i);
811
- value = object;
812
- property = propertyStack.pop();
813
- object = objectStack.pop();
814
- state = stateStack.pop();
815
- break;
816
- case 125:
817
- if (state !== 2) throwSyntaxError(bytes, --i);
818
- value = object;
819
- property = propertyStack.pop();
820
- object = objectStack.pop();
821
- state = stateStack.pop();
822
- break;
823
- default: throwSyntaxError(bytes, --i);
824
- }
825
- c = bytes[i];
826
- while (c <= 32) c = bytes[++i];
827
- switch (state) {
828
- case 0:
829
- if (i === length) return value;
830
- break;
831
- case 1:
832
- object.push(value);
833
- if (c === 44) {
834
- i++;
835
- continue;
836
- }
837
- if (c === 93) continue;
838
- break;
839
- case 2: if (property === null) {
840
- property = value;
841
- if (c === 58) {
842
- i++;
843
- continue;
844
- }
845
- } else {
846
- object[property] = value;
847
- property = null;
848
- if (c === 44) {
849
- i++;
850
- continue;
851
- }
852
- if (c === 125) continue;
853
- }
854
- }
855
- break;
856
- }
857
- throwSyntaxError(bytes, i);
858
- }
859
- var quote = JSON.stringify;
860
- var buildLogLevelDefault = "warning";
861
- var transformLogLevelDefault = "silent";
862
- function validateAndJoinStringArray(values, what) {
863
- const toJoin = [];
864
- for (const value of values) {
865
- validateStringValue(value, what);
866
- if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`);
867
- toJoin.push(value);
868
- }
869
- return toJoin.join(",");
870
- }
871
- var canBeAnything = () => null;
872
- var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean";
873
- var mustBeString = (value) => typeof value === "string" ? null : "a string";
874
- var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object";
875
- var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer";
876
- var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number";
877
- var mustBeFunction = (value) => typeof value === "function" ? null : "a function";
878
- var mustBeArray = (value) => Array.isArray(value) ? null : "an array";
879
- var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings";
880
- var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object";
881
- var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object";
882
- var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module";
883
- var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null";
884
- var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean";
885
- var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object";
886
- var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings";
887
- var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array";
888
- var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL";
889
- function getFlag(object, keys, key, mustBeFn) {
890
- let value = object[key];
891
- keys[key + ""] = true;
892
- if (value === void 0) return void 0;
893
- let mustBe = mustBeFn(value);
894
- if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`);
895
- return value;
896
- }
897
- function checkForInvalidFlags(object, keys, where) {
898
- for (let key in object) if (!(key in keys)) throw new Error(`Invalid option ${where}: ${quote(key)}`);
899
- }
900
- function validateInitializeOptions(options) {
901
- let keys = /* @__PURE__ */ Object.create(null);
902
- let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL);
903
- let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule);
904
- let worker = getFlag(options, keys, "worker", mustBeBoolean);
905
- checkForInvalidFlags(options, keys, "in initialize() call");
906
- return {
907
- wasmURL,
908
- wasmModule,
909
- worker
910
- };
911
- }
912
- function validateMangleCache(mangleCache) {
913
- let validated;
914
- if (mangleCache !== void 0) {
915
- validated = /* @__PURE__ */ Object.create(null);
916
- for (let key in mangleCache) {
917
- let value = mangleCache[key];
918
- if (typeof value === "string" || value === false) validated[key] = value;
919
- else throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`);
920
- }
921
- }
922
- return validated;
923
- }
924
- function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) {
925
- let color = getFlag(options, keys, "color", mustBeBoolean);
926
- let logLevel = getFlag(options, keys, "logLevel", mustBeString);
927
- let logLimit = getFlag(options, keys, "logLimit", mustBeInteger);
928
- if (color !== void 0) flags.push(`--color=${color}`);
929
- else if (isTTY2) flags.push(`--color=true`);
930
- flags.push(`--log-level=${logLevel || logLevelDefault}`);
931
- flags.push(`--log-limit=${logLimit || 0}`);
932
- }
933
- function validateStringValue(value, what, key) {
934
- if (typeof value !== "string") throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`);
935
- return value;
936
- }
937
- function pushCommonFlags(flags, options, keys) {
938
- let legalComments = getFlag(options, keys, "legalComments", mustBeString);
939
- let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString);
940
- let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean);
941
- let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings);
942
- let format = getFlag(options, keys, "format", mustBeString);
943
- let globalName = getFlag(options, keys, "globalName", mustBeString);
944
- let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp);
945
- let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp);
946
- let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean);
947
- let minify = getFlag(options, keys, "minify", mustBeBoolean);
948
- let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean);
949
- let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean);
950
- let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean);
951
- let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger);
952
- let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings);
953
- let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings);
954
- let charset = getFlag(options, keys, "charset", mustBeString);
955
- let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean);
956
- let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean);
957
- let jsx = getFlag(options, keys, "jsx", mustBeString);
958
- let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString);
959
- let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString);
960
- let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString);
961
- let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean);
962
- let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean);
963
- let define = getFlag(options, keys, "define", mustBeObject);
964
- let logOverride = getFlag(options, keys, "logOverride", mustBeObject);
965
- let supported = getFlag(options, keys, "supported", mustBeObject);
966
- let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings);
967
- let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean);
968
- let platform = getFlag(options, keys, "platform", mustBeString);
969
- let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject);
970
- let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings);
971
- if (legalComments) flags.push(`--legal-comments=${legalComments}`);
972
- if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`);
973
- if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`);
974
- if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`);
975
- if (format) flags.push(`--format=${format}`);
976
- if (globalName) flags.push(`--global-name=${globalName}`);
977
- if (platform) flags.push(`--platform=${platform}`);
978
- if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`);
979
- if (minify) flags.push("--minify");
980
- if (minifySyntax) flags.push("--minify-syntax");
981
- if (minifyWhitespace) flags.push("--minify-whitespace");
982
- if (minifyIdentifiers) flags.push("--minify-identifiers");
983
- if (lineLimit) flags.push(`--line-limit=${lineLimit}`);
984
- if (charset) flags.push(`--charset=${charset}`);
985
- if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
986
- if (ignoreAnnotations) flags.push(`--ignore-annotations`);
987
- if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`);
988
- if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`);
989
- if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`);
990
- if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`);
991
- if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`);
992
- if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`);
993
- if (jsx) flags.push(`--jsx=${jsx}`);
994
- if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
995
- if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`);
996
- if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`);
997
- if (jsxDev) flags.push(`--jsx-dev`);
998
- if (jsxSideEffects) flags.push(`--jsx-side-effects`);
999
- if (define) for (let key in define) {
1000
- if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`);
1001
- flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`);
1002
- }
1003
- if (logOverride) for (let key in logOverride) {
1004
- if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`);
1005
- flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`);
1006
- }
1007
- if (supported) for (let key in supported) {
1008
- if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`);
1009
- const value = supported[key];
1010
- if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`);
1011
- flags.push(`--supported:${key}=${value}`);
1012
- }
1013
- if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`);
1014
- if (keepNames) flags.push(`--keep-names`);
1015
- }
1016
- function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) {
1017
- var _a2;
1018
- let flags = [];
1019
- let entries = [];
1020
- let keys = /* @__PURE__ */ Object.create(null);
1021
- let stdinContents = null;
1022
- let stdinResolveDir = null;
1023
- pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
1024
- pushCommonFlags(flags, options, keys);
1025
- let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
1026
- let bundle = getFlag(options, keys, "bundle", mustBeBoolean);
1027
- let splitting = getFlag(options, keys, "splitting", mustBeBoolean);
1028
- let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean);
1029
- let metafile = getFlag(options, keys, "metafile", mustBeBoolean);
1030
- let outfile = getFlag(options, keys, "outfile", mustBeString);
1031
- let outdir = getFlag(options, keys, "outdir", mustBeString);
1032
- let outbase = getFlag(options, keys, "outbase", mustBeString);
1033
- let tsconfig = getFlag(options, keys, "tsconfig", mustBeString);
1034
- let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings);
1035
- let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings);
1036
- let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings);
1037
- let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings);
1038
- let external = getFlag(options, keys, "external", mustBeArrayOfStrings);
1039
- let packages = getFlag(options, keys, "packages", mustBeString);
1040
- let alias = getFlag(options, keys, "alias", mustBeObject);
1041
- let loader = getFlag(options, keys, "loader", mustBeObject);
1042
- let outExtension = getFlag(options, keys, "outExtension", mustBeObject);
1043
- let publicPath = getFlag(options, keys, "publicPath", mustBeString);
1044
- let entryNames = getFlag(options, keys, "entryNames", mustBeString);
1045
- let chunkNames = getFlag(options, keys, "chunkNames", mustBeString);
1046
- let assetNames = getFlag(options, keys, "assetNames", mustBeString);
1047
- let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings);
1048
- let banner = getFlag(options, keys, "banner", mustBeObject);
1049
- let footer = getFlag(options, keys, "footer", mustBeObject);
1050
- let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints);
1051
- let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString);
1052
- let stdin = getFlag(options, keys, "stdin", mustBeObject);
1053
- let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault;
1054
- let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean);
1055
- let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
1056
- keys.plugins = true;
1057
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
1058
- if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`);
1059
- if (bundle) flags.push("--bundle");
1060
- if (allowOverwrite) flags.push("--allow-overwrite");
1061
- if (splitting) flags.push("--splitting");
1062
- if (preserveSymlinks) flags.push("--preserve-symlinks");
1063
- if (metafile) flags.push(`--metafile`);
1064
- if (outfile) flags.push(`--outfile=${outfile}`);
1065
- if (outdir) flags.push(`--outdir=${outdir}`);
1066
- if (outbase) flags.push(`--outbase=${outbase}`);
1067
- if (tsconfig) flags.push(`--tsconfig=${tsconfig}`);
1068
- if (packages) flags.push(`--packages=${packages}`);
1069
- if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`);
1070
- if (publicPath) flags.push(`--public-path=${publicPath}`);
1071
- if (entryNames) flags.push(`--entry-names=${entryNames}`);
1072
- if (chunkNames) flags.push(`--chunk-names=${chunkNames}`);
1073
- if (assetNames) flags.push(`--asset-names=${assetNames}`);
1074
- if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`);
1075
- if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`);
1076
- if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`);
1077
- if (alias) for (let old in alias) {
1078
- if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`);
1079
- flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`);
1080
- }
1081
- if (banner) for (let type in banner) {
1082
- if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`);
1083
- flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`);
1084
- }
1085
- if (footer) for (let type in footer) {
1086
- if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`);
1087
- flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`);
1088
- }
1089
- if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`);
1090
- if (loader) for (let ext in loader) {
1091
- if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`);
1092
- flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`);
1093
- }
1094
- if (outExtension) for (let ext in outExtension) {
1095
- if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
1096
- flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
1097
- }
1098
- if (entryPoints) {
1099
- if (Array.isArray(entryPoints)) for (let i = 0, n = entryPoints.length; i < n; i++) {
1100
- let entryPoint = entryPoints[i];
1101
- if (typeof entryPoint === "object" && entryPoint !== null) {
1102
- let entryPointKeys = /* @__PURE__ */ Object.create(null);
1103
- let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
1104
- let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
1105
- checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
1106
- if (input === void 0) throw new Error("Missing property \"in\" for entry point at index " + i);
1107
- if (output === void 0) throw new Error("Missing property \"out\" for entry point at index " + i);
1108
- entries.push([output, input]);
1109
- } else entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
1110
- }
1111
- else for (let key in entryPoints) entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
1112
- }
1113
- if (stdin) {
1114
- let stdinKeys = /* @__PURE__ */ Object.create(null);
1115
- let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
1116
- let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString);
1117
- let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString);
1118
- let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString);
1119
- checkForInvalidFlags(stdin, stdinKeys, "in \"stdin\" object");
1120
- if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
1121
- if (loader2) flags.push(`--loader=${loader2}`);
1122
- if (resolveDir) stdinResolveDir = resolveDir;
1123
- if (typeof contents === "string") stdinContents = encodeUTF8(contents);
1124
- else if (contents instanceof Uint8Array) stdinContents = contents;
1125
- }
1126
- let nodePaths = [];
1127
- if (nodePathsInput) for (let value of nodePathsInput) {
1128
- value += "";
1129
- nodePaths.push(value);
1130
- }
1131
- return {
1132
- entries,
1133
- flags,
1134
- write,
1135
- stdinContents,
1136
- stdinResolveDir,
1137
- absWorkingDir,
1138
- nodePaths,
1139
- mangleCache: validateMangleCache(mangleCache)
1140
- };
1141
- }
1142
- function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) {
1143
- let flags = [];
1144
- let keys = /* @__PURE__ */ Object.create(null);
1145
- pushLogFlags(flags, options, keys, isTTY2, logLevelDefault);
1146
- pushCommonFlags(flags, options, keys);
1147
- let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean);
1148
- let sourcefile = getFlag(options, keys, "sourcefile", mustBeString);
1149
- let loader = getFlag(options, keys, "loader", mustBeString);
1150
- let banner = getFlag(options, keys, "banner", mustBeString);
1151
- let footer = getFlag(options, keys, "footer", mustBeString);
1152
- let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject);
1153
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
1154
- if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`);
1155
- if (sourcefile) flags.push(`--sourcefile=${sourcefile}`);
1156
- if (loader) flags.push(`--loader=${loader}`);
1157
- if (banner) flags.push(`--banner=${banner}`);
1158
- if (footer) flags.push(`--footer=${footer}`);
1159
- return {
1160
- flags,
1161
- mangleCache: validateMangleCache(mangleCache)
1162
- };
1163
- }
1164
- function createChannel(streamIn) {
1165
- const requestCallbacksByKey = {};
1166
- const closeData = {
1167
- didClose: false,
1168
- reason: ""
1169
- };
1170
- let responseCallbacks = {};
1171
- let nextRequestID = 0;
1172
- let nextBuildKey = 0;
1173
- let stdout = /* @__PURE__ */ new Uint8Array(16384);
1174
- let stdoutUsed = 0;
1175
- let readFromStdout = (chunk) => {
1176
- let limit = stdoutUsed + chunk.length;
1177
- if (limit > stdout.length) {
1178
- let swap = new Uint8Array(limit * 2);
1179
- swap.set(stdout);
1180
- stdout = swap;
1181
- }
1182
- stdout.set(chunk, stdoutUsed);
1183
- stdoutUsed += chunk.length;
1184
- let offset = 0;
1185
- while (offset + 4 <= stdoutUsed) {
1186
- let length = readUInt32LE(stdout, offset);
1187
- if (offset + 4 + length > stdoutUsed) break;
1188
- offset += 4;
1189
- handleIncomingPacket(stdout.subarray(offset, offset + length));
1190
- offset += length;
1191
- }
1192
- if (offset > 0) {
1193
- stdout.copyWithin(0, offset, stdoutUsed);
1194
- stdoutUsed -= offset;
1195
- }
1196
- };
1197
- let afterClose = (error) => {
1198
- closeData.didClose = true;
1199
- if (error) closeData.reason = ": " + (error.message || error);
1200
- const text = "The service was stopped" + closeData.reason;
1201
- for (let id in responseCallbacks) responseCallbacks[id](text, null);
1202
- responseCallbacks = {};
1203
- };
1204
- let sendRequest = (refs, value, callback) => {
1205
- if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null);
1206
- let id = nextRequestID++;
1207
- responseCallbacks[id] = (error, response) => {
1208
- try {
1209
- callback(error, response);
1210
- } finally {
1211
- if (refs) refs.unref();
1212
- }
1213
- };
1214
- if (refs) refs.ref();
1215
- streamIn.writeToStdin(encodePacket({
1216
- id,
1217
- isRequest: true,
1218
- value
1219
- }));
1220
- };
1221
- let sendResponse = (id, value) => {
1222
- if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason);
1223
- streamIn.writeToStdin(encodePacket({
1224
- id,
1225
- isRequest: false,
1226
- value
1227
- }));
1228
- };
1229
- let handleRequest = async (id, request) => {
1230
- try {
1231
- if (request.command === "ping") {
1232
- sendResponse(id, {});
1233
- return;
1234
- }
1235
- if (typeof request.key === "number") {
1236
- const requestCallbacks = requestCallbacksByKey[request.key];
1237
- if (!requestCallbacks) return;
1238
- const callback = requestCallbacks[request.command];
1239
- if (callback) {
1240
- await callback(id, request);
1241
- return;
1242
- }
1243
- }
1244
- throw new Error(`Invalid command: ` + request.command);
1245
- } catch (e) {
1246
- const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")];
1247
- try {
1248
- sendResponse(id, { errors });
1249
- } catch {}
1250
- }
1251
- };
1252
- let isFirstPacket = true;
1253
- let handleIncomingPacket = (bytes) => {
1254
- if (isFirstPacket) {
1255
- isFirstPacket = false;
1256
- let binaryVersion = String.fromCharCode(...bytes);
1257
- if (binaryVersion !== "0.27.7") throw new Error(`Cannot start service: Host version "0.27.7" does not match binary version ${quote(binaryVersion)}`);
1258
- return;
1259
- }
1260
- let packet = decodePacket(bytes);
1261
- if (packet.isRequest) handleRequest(packet.id, packet.value);
1262
- else {
1263
- let callback = responseCallbacks[packet.id];
1264
- delete responseCallbacks[packet.id];
1265
- if (packet.value.error) callback(packet.value.error, {});
1266
- else callback(null, packet.value);
1267
- }
1268
- };
1269
- let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => {
1270
- let refCount = 0;
1271
- const buildKey = nextBuildKey++;
1272
- const requestCallbacks = {};
1273
- const buildRefs = {
1274
- ref() {
1275
- if (++refCount === 1) {
1276
- if (refs) refs.ref();
1277
- }
1278
- },
1279
- unref() {
1280
- if (--refCount === 0) {
1281
- delete requestCallbacksByKey[buildKey];
1282
- if (refs) refs.unref();
1283
- }
1284
- }
1285
- };
1286
- requestCallbacksByKey[buildKey] = requestCallbacks;
1287
- buildRefs.ref();
1288
- buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, (err, res) => {
1289
- try {
1290
- callback(err, res);
1291
- } finally {
1292
- buildRefs.unref();
1293
- }
1294
- });
1295
- };
1296
- let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => {
1297
- const details = createObjectStash();
1298
- let start = (inputPath) => {
1299
- try {
1300
- if (typeof input !== "string" && !(input instanceof Uint8Array)) throw new Error("The input to \"transform\" must be a string or a Uint8Array");
1301
- let { flags, mangleCache } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault);
1302
- let request = {
1303
- command: "transform",
1304
- flags,
1305
- inputFS: inputPath !== null,
1306
- input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input
1307
- };
1308
- if (mangleCache) request.mangleCache = mangleCache;
1309
- sendRequest(refs, request, (error, response) => {
1310
- if (error) return callback(new Error(error), null);
1311
- let errors = replaceDetailsInMessages(response.errors, details);
1312
- let warnings = replaceDetailsInMessages(response.warnings, details);
1313
- let outstanding = 1;
1314
- let next = () => {
1315
- if (--outstanding === 0) {
1316
- let result = {
1317
- warnings,
1318
- code: response.code,
1319
- map: response.map,
1320
- mangleCache: void 0,
1321
- legalComments: void 0
1322
- };
1323
- if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments;
1324
- if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache;
1325
- callback(null, result);
1326
- }
1327
- };
1328
- if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null);
1329
- if (response.codeFS) {
1330
- outstanding++;
1331
- fs3.readFile(response.code, (err, contents) => {
1332
- if (err !== null) callback(err, null);
1333
- else {
1334
- response.code = contents;
1335
- next();
1336
- }
1337
- });
1338
- }
1339
- if (response.mapFS) {
1340
- outstanding++;
1341
- fs3.readFile(response.map, (err, contents) => {
1342
- if (err !== null) callback(err, null);
1343
- else {
1344
- response.map = contents;
1345
- next();
1346
- }
1347
- });
1348
- }
1349
- next();
1350
- });
1351
- } catch (e) {
1352
- let flags = [];
1353
- try {
1354
- pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault);
1355
- } catch {}
1356
- const error = extractErrorMessageV8(e, streamIn, details, void 0, "");
1357
- sendRequest(refs, {
1358
- command: "error",
1359
- flags,
1360
- error
1361
- }, () => {
1362
- error.detail = details.load(error.detail);
1363
- callback(failureErrorWithLog("Transform failed", [error], []), null);
1364
- });
1365
- }
1366
- };
1367
- if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1048576) {
1368
- let next = start;
1369
- start = () => fs3.writeFile(input, next);
1370
- }
1371
- start(null);
1372
- };
1373
- let formatMessages2 = ({ callName, refs, messages, options, callback }) => {
1374
- if (!options) throw new Error(`Missing second argument in ${callName}() call`);
1375
- let keys = {};
1376
- let kind = getFlag(options, keys, "kind", mustBeString);
1377
- let color = getFlag(options, keys, "color", mustBeBoolean);
1378
- let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger);
1379
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
1380
- if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`);
1381
- if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`);
1382
- let request = {
1383
- command: "format-msgs",
1384
- messages: sanitizeMessages(messages, "messages", null, "", terminalWidth),
1385
- isWarning: kind === "warning"
1386
- };
1387
- if (color !== void 0) request.color = color;
1388
- if (terminalWidth !== void 0) request.terminalWidth = terminalWidth;
1389
- sendRequest(refs, request, (error, response) => {
1390
- if (error) return callback(new Error(error), null);
1391
- callback(null, response.messages);
1392
- });
1393
- };
1394
- let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => {
1395
- if (options === void 0) options = {};
1396
- let keys = {};
1397
- let color = getFlag(options, keys, "color", mustBeBoolean);
1398
- let verbose = getFlag(options, keys, "verbose", mustBeBoolean);
1399
- checkForInvalidFlags(options, keys, `in ${callName}() call`);
1400
- let request = {
1401
- command: "analyze-metafile",
1402
- metafile
1403
- };
1404
- if (color !== void 0) request.color = color;
1405
- if (verbose !== void 0) request.verbose = verbose;
1406
- sendRequest(refs, request, (error, response) => {
1407
- if (error) return callback(new Error(error), null);
1408
- callback(null, response.result);
1409
- });
1410
- };
1411
- return {
1412
- readFromStdout,
1413
- afterClose,
1414
- service: {
1415
- buildOrContext,
1416
- transform: transform2,
1417
- formatMessages: formatMessages2,
1418
- analyzeMetafile: analyzeMetafile2
1419
- }
1420
- };
1421
- }
1422
- function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) {
1423
- const details = createObjectStash();
1424
- const isContext = callName === "context";
1425
- const handleError = (e, pluginName) => {
1426
- const flags = [];
1427
- try {
1428
- pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault);
1429
- } catch {}
1430
- const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName);
1431
- sendRequest(refs, {
1432
- command: "error",
1433
- flags,
1434
- error: message
1435
- }, () => {
1436
- message.detail = details.load(message.detail);
1437
- callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null);
1438
- });
1439
- };
1440
- let plugins;
1441
- if (typeof options === "object") {
1442
- const value = options.plugins;
1443
- if (value !== void 0) {
1444
- if (!Array.isArray(value)) return handleError(/* @__PURE__ */ new Error(`"plugins" must be an array`), "");
1445
- plugins = value;
1446
- }
1447
- }
1448
- if (plugins && plugins.length > 0) {
1449
- if (streamIn.isSync) return handleError(/* @__PURE__ */ new Error("Cannot use plugins in synchronous API calls"), "");
1450
- handlePlugins(buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, plugins, details).then((result) => {
1451
- if (!result.ok) return handleError(result.error, result.pluginName);
1452
- try {
1453
- buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks);
1454
- } catch (e) {
1455
- handleError(e, "");
1456
- }
1457
- }, (e) => handleError(e, ""));
1458
- return;
1459
- }
1460
- try {
1461
- buildOrContextContinue(null, (result, done) => done([], []), () => {});
1462
- } catch (e) {
1463
- handleError(e, "");
1464
- }
1465
- function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) {
1466
- const writeDefault = streamIn.hasFS;
1467
- const { entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir, nodePaths, mangleCache } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault);
1468
- if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`);
1469
- const request = {
1470
- command: "build",
1471
- key: buildKey,
1472
- entries,
1473
- flags,
1474
- write,
1475
- stdinContents,
1476
- stdinResolveDir,
1477
- absWorkingDir: absWorkingDir || defaultWD2,
1478
- nodePaths,
1479
- context: isContext
1480
- };
1481
- if (requestPlugins) request.plugins = requestPlugins;
1482
- if (mangleCache) request.mangleCache = mangleCache;
1483
- const buildResponseToResult = (response, callback2) => {
1484
- const result = {
1485
- errors: replaceDetailsInMessages(response.errors, details),
1486
- warnings: replaceDetailsInMessages(response.warnings, details),
1487
- outputFiles: void 0,
1488
- metafile: void 0,
1489
- mangleCache: void 0
1490
- };
1491
- const originalErrors = result.errors.slice();
1492
- const originalWarnings = result.warnings.slice();
1493
- if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles);
1494
- if (response.metafile && response.metafile.length) result.metafile = parseJSON(response.metafile);
1495
- if (response.mangleCache) result.mangleCache = response.mangleCache;
1496
- if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, ""));
1497
- runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => {
1498
- if (originalErrors.length > 0 || onEndErrors.length > 0) return callback2(failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)), null, onEndErrors, onEndWarnings);
1499
- callback2(null, result, onEndErrors, onEndWarnings);
1500
- });
1501
- };
1502
- let latestResultPromise;
1503
- let provideLatestResult;
1504
- if (isContext) requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => {
1505
- buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => {
1506
- const response = {
1507
- errors: onEndErrors,
1508
- warnings: onEndWarnings
1509
- };
1510
- if (provideLatestResult) provideLatestResult(err, result);
1511
- latestResultPromise = void 0;
1512
- provideLatestResult = void 0;
1513
- sendResponse(id, response);
1514
- resolve();
1515
- });
1516
- });
1517
- sendRequest(refs, request, (error, response) => {
1518
- if (error) return callback(new Error(error), null);
1519
- if (!isContext) return buildResponseToResult(response, (err, res) => {
1520
- scheduleOnDisposeCallbacks();
1521
- return callback(err, res);
1522
- });
1523
- if (response.errors.length > 0) return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null);
1524
- let didDispose = false;
1525
- const result = {
1526
- rebuild: () => {
1527
- if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => {
1528
- let settlePromise;
1529
- provideLatestResult = (err, result2) => {
1530
- if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2);
1531
- };
1532
- const triggerAnotherBuild = () => {
1533
- sendRequest(refs, {
1534
- command: "rebuild",
1535
- key: buildKey
1536
- }, (error2, response2) => {
1537
- if (error2) reject(new Error(error2));
1538
- else if (settlePromise) settlePromise();
1539
- else triggerAnotherBuild();
1540
- });
1541
- };
1542
- triggerAnotherBuild();
1543
- });
1544
- return latestResultPromise;
1545
- },
1546
- watch: (options2 = {}) => new Promise((resolve, reject) => {
1547
- if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`);
1548
- const keys = {};
1549
- const delay = getFlag(options2, keys, "delay", mustBeInteger);
1550
- checkForInvalidFlags(options2, keys, `in watch() call`);
1551
- const request2 = {
1552
- command: "watch",
1553
- key: buildKey
1554
- };
1555
- if (delay) request2.delay = delay;
1556
- sendRequest(refs, request2, (error2) => {
1557
- if (error2) reject(new Error(error2));
1558
- else resolve(void 0);
1559
- });
1560
- }),
1561
- serve: (options2 = {}) => new Promise((resolve, reject) => {
1562
- if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`);
1563
- const keys = {};
1564
- const port = getFlag(options2, keys, "port", mustBeValidPortNumber);
1565
- const host = getFlag(options2, keys, "host", mustBeString);
1566
- const servedir = getFlag(options2, keys, "servedir", mustBeString);
1567
- const keyfile = getFlag(options2, keys, "keyfile", mustBeString);
1568
- const certfile = getFlag(options2, keys, "certfile", mustBeString);
1569
- const fallback = getFlag(options2, keys, "fallback", mustBeString);
1570
- const cors = getFlag(options2, keys, "cors", mustBeObject);
1571
- const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction);
1572
- checkForInvalidFlags(options2, keys, `in serve() call`);
1573
- const request2 = {
1574
- command: "serve",
1575
- key: buildKey,
1576
- onRequest: !!onRequest
1577
- };
1578
- if (port !== void 0) request2.port = port;
1579
- if (host !== void 0) request2.host = host;
1580
- if (servedir !== void 0) request2.servedir = servedir;
1581
- if (keyfile !== void 0) request2.keyfile = keyfile;
1582
- if (certfile !== void 0) request2.certfile = certfile;
1583
- if (fallback !== void 0) request2.fallback = fallback;
1584
- if (cors) {
1585
- const corsKeys = {};
1586
- const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings);
1587
- checkForInvalidFlags(cors, corsKeys, `on "cors" object`);
1588
- if (Array.isArray(origin)) request2.corsOrigin = origin;
1589
- else if (origin !== void 0) request2.corsOrigin = [origin];
1590
- }
1591
- sendRequest(refs, request2, (error2, response2) => {
1592
- if (error2) return reject(new Error(error2));
1593
- if (onRequest) requestCallbacks["serve-request"] = (id, request3) => {
1594
- onRequest(request3.args);
1595
- sendResponse(id, {});
1596
- };
1597
- resolve(response2);
1598
- });
1599
- }),
1600
- cancel: () => new Promise((resolve) => {
1601
- if (didDispose) return resolve();
1602
- sendRequest(refs, {
1603
- command: "cancel",
1604
- key: buildKey
1605
- }, () => {
1606
- resolve();
1607
- });
1608
- }),
1609
- dispose: () => new Promise((resolve) => {
1610
- if (didDispose) return resolve();
1611
- didDispose = true;
1612
- sendRequest(refs, {
1613
- command: "dispose",
1614
- key: buildKey
1615
- }, () => {
1616
- resolve();
1617
- scheduleOnDisposeCallbacks();
1618
- refs.unref();
1619
- });
1620
- })
1621
- };
1622
- refs.ref();
1623
- callback(null, result);
1624
- });
1625
- }
1626
- }
1627
- var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => {
1628
- let onStartCallbacks = [];
1629
- let onEndCallbacks = [];
1630
- let onResolveCallbacks = {};
1631
- let onLoadCallbacks = {};
1632
- let onDisposeCallbacks = [];
1633
- let nextCallbackID = 0;
1634
- let i = 0;
1635
- let requestPlugins = [];
1636
- let isSetupDone = false;
1637
- plugins = [...plugins];
1638
- for (let item of plugins) {
1639
- let keys = {};
1640
- if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`);
1641
- const name = getFlag(item, keys, "name", mustBeString);
1642
- if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`);
1643
- try {
1644
- let setup = getFlag(item, keys, "setup", mustBeFunction);
1645
- if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`);
1646
- checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`);
1647
- let plugin = {
1648
- name,
1649
- onStart: false,
1650
- onEnd: false,
1651
- onResolve: [],
1652
- onLoad: []
1653
- };
1654
- i++;
1655
- let resolve = (path3, options = {}) => {
1656
- if (!isSetupDone) throw new Error("Cannot call \"resolve\" before plugin setup has completed");
1657
- if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`);
1658
- let keys2 = /* @__PURE__ */ Object.create(null);
1659
- let pluginName = getFlag(options, keys2, "pluginName", mustBeString);
1660
- let importer = getFlag(options, keys2, "importer", mustBeString);
1661
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
1662
- let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString);
1663
- let kind = getFlag(options, keys2, "kind", mustBeString);
1664
- let pluginData = getFlag(options, keys2, "pluginData", canBeAnything);
1665
- let importAttributes = getFlag(options, keys2, "with", mustBeObject);
1666
- checkForInvalidFlags(options, keys2, "in resolve() call");
1667
- return new Promise((resolve2, reject) => {
1668
- const request = {
1669
- command: "resolve",
1670
- path: path3,
1671
- key: buildKey,
1672
- pluginName: name
1673
- };
1674
- if (pluginName != null) request.pluginName = pluginName;
1675
- if (importer != null) request.importer = importer;
1676
- if (namespace != null) request.namespace = namespace;
1677
- if (resolveDir != null) request.resolveDir = resolveDir;
1678
- if (kind != null) request.kind = kind;
1679
- else throw new Error(`Must specify "kind" when calling "resolve"`);
1680
- if (pluginData != null) request.pluginData = details.store(pluginData);
1681
- if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with");
1682
- sendRequest(refs, request, (error, response) => {
1683
- if (error !== null) reject(new Error(error));
1684
- else resolve2({
1685
- errors: replaceDetailsInMessages(response.errors, details),
1686
- warnings: replaceDetailsInMessages(response.warnings, details),
1687
- path: response.path,
1688
- external: response.external,
1689
- sideEffects: response.sideEffects,
1690
- namespace: response.namespace,
1691
- suffix: response.suffix,
1692
- pluginData: details.load(response.pluginData)
1693
- });
1694
- });
1695
- });
1696
- };
1697
- let promise = setup({
1698
- initialOptions,
1699
- resolve,
1700
- onStart(callback) {
1701
- let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onStart" callback registered here:`), streamIn, "onStart");
1702
- onStartCallbacks.push({
1703
- name,
1704
- callback,
1705
- note: registeredNote
1706
- });
1707
- plugin.onStart = true;
1708
- },
1709
- onEnd(callback) {
1710
- let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onEnd" callback registered here:`), streamIn, "onEnd");
1711
- onEndCallbacks.push({
1712
- name,
1713
- callback,
1714
- note: registeredNote
1715
- });
1716
- plugin.onEnd = true;
1717
- },
1718
- onResolve(options, callback) {
1719
- let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onResolve" callback registered here:`), streamIn, "onResolve");
1720
- let keys2 = {};
1721
- let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1722
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
1723
- checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`);
1724
- if (filter == null) throw new Error(`onResolve() call is missing a filter`);
1725
- let id = nextCallbackID++;
1726
- onResolveCallbacks[id] = {
1727
- name,
1728
- callback,
1729
- note: registeredNote
1730
- };
1731
- plugin.onResolve.push({
1732
- id,
1733
- filter: jsRegExpToGoRegExp(filter),
1734
- namespace: namespace || ""
1735
- });
1736
- },
1737
- onLoad(options, callback) {
1738
- let registeredNote = extractCallerV8(/* @__PURE__ */ new Error(`This error came from the "onLoad" callback registered here:`), streamIn, "onLoad");
1739
- let keys2 = {};
1740
- let filter = getFlag(options, keys2, "filter", mustBeRegExp);
1741
- let namespace = getFlag(options, keys2, "namespace", mustBeString);
1742
- checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`);
1743
- if (filter == null) throw new Error(`onLoad() call is missing a filter`);
1744
- let id = nextCallbackID++;
1745
- onLoadCallbacks[id] = {
1746
- name,
1747
- callback,
1748
- note: registeredNote
1749
- };
1750
- plugin.onLoad.push({
1751
- id,
1752
- filter: jsRegExpToGoRegExp(filter),
1753
- namespace: namespace || ""
1754
- });
1755
- },
1756
- onDispose(callback) {
1757
- onDisposeCallbacks.push(callback);
1758
- },
1759
- esbuild: streamIn.esbuild
1760
- });
1761
- if (promise) await promise;
1762
- requestPlugins.push(plugin);
1763
- } catch (e) {
1764
- return {
1765
- ok: false,
1766
- error: e,
1767
- pluginName: name
1768
- };
1769
- }
1770
- }
1771
- requestCallbacks["on-start"] = async (id, request) => {
1772
- details.clear();
1773
- let response = {
1774
- errors: [],
1775
- warnings: []
1776
- };
1777
- await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => {
1778
- try {
1779
- let result = await callback();
1780
- if (result != null) {
1781
- if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`);
1782
- let keys = {};
1783
- let errors = getFlag(result, keys, "errors", mustBeArray);
1784
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
1785
- checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`);
1786
- if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0));
1787
- if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0));
1788
- }
1789
- } catch (e) {
1790
- response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name));
1791
- }
1792
- }));
1793
- sendResponse(id, response);
1794
- };
1795
- requestCallbacks["on-resolve"] = async (id, request) => {
1796
- let response = {}, name = "", callback, note;
1797
- for (let id2 of request.ids) try {
1798
- ({name, callback, note} = onResolveCallbacks[id2]);
1799
- let result = await callback({
1800
- path: request.path,
1801
- importer: request.importer,
1802
- namespace: request.namespace,
1803
- resolveDir: request.resolveDir,
1804
- kind: request.kind,
1805
- pluginData: details.load(request.pluginData),
1806
- with: request.with
1807
- });
1808
- if (result != null) {
1809
- if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`);
1810
- let keys = {};
1811
- let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1812
- let path3 = getFlag(result, keys, "path", mustBeString);
1813
- let namespace = getFlag(result, keys, "namespace", mustBeString);
1814
- let suffix = getFlag(result, keys, "suffix", mustBeString);
1815
- let external = getFlag(result, keys, "external", mustBeBoolean);
1816
- let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean);
1817
- let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1818
- let errors = getFlag(result, keys, "errors", mustBeArray);
1819
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
1820
- let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1821
- let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1822
- checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`);
1823
- response.id = id2;
1824
- if (pluginName != null) response.pluginName = pluginName;
1825
- if (path3 != null) response.path = path3;
1826
- if (namespace != null) response.namespace = namespace;
1827
- if (suffix != null) response.suffix = suffix;
1828
- if (external != null) response.external = external;
1829
- if (sideEffects != null) response.sideEffects = sideEffects;
1830
- if (pluginData != null) response.pluginData = details.store(pluginData);
1831
- if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1832
- if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1833
- if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1834
- if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1835
- break;
1836
- }
1837
- } catch (e) {
1838
- response = {
1839
- id: id2,
1840
- errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
1841
- };
1842
- break;
1843
- }
1844
- sendResponse(id, response);
1845
- };
1846
- requestCallbacks["on-load"] = async (id, request) => {
1847
- let response = {}, name = "", callback, note;
1848
- for (let id2 of request.ids) try {
1849
- ({name, callback, note} = onLoadCallbacks[id2]);
1850
- let result = await callback({
1851
- path: request.path,
1852
- namespace: request.namespace,
1853
- suffix: request.suffix,
1854
- pluginData: details.load(request.pluginData),
1855
- with: request.with
1856
- });
1857
- if (result != null) {
1858
- if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`);
1859
- let keys = {};
1860
- let pluginName = getFlag(result, keys, "pluginName", mustBeString);
1861
- let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array);
1862
- let resolveDir = getFlag(result, keys, "resolveDir", mustBeString);
1863
- let pluginData = getFlag(result, keys, "pluginData", canBeAnything);
1864
- let loader = getFlag(result, keys, "loader", mustBeString);
1865
- let errors = getFlag(result, keys, "errors", mustBeArray);
1866
- let warnings = getFlag(result, keys, "warnings", mustBeArray);
1867
- let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings);
1868
- let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings);
1869
- checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`);
1870
- response.id = id2;
1871
- if (pluginName != null) response.pluginName = pluginName;
1872
- if (contents instanceof Uint8Array) response.contents = contents;
1873
- else if (contents != null) response.contents = encodeUTF8(contents);
1874
- if (resolveDir != null) response.resolveDir = resolveDir;
1875
- if (pluginData != null) response.pluginData = details.store(pluginData);
1876
- if (loader != null) response.loader = loader;
1877
- if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0);
1878
- if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1879
- if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles");
1880
- if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs");
1881
- break;
1882
- }
1883
- } catch (e) {
1884
- response = {
1885
- id: id2,
1886
- errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)]
1887
- };
1888
- break;
1889
- }
1890
- sendResponse(id, response);
1891
- };
1892
- let runOnEndCallbacks = (result, done) => done([], []);
1893
- if (onEndCallbacks.length > 0) runOnEndCallbacks = (result, done) => {
1894
- (async () => {
1895
- const onEndErrors = [];
1896
- const onEndWarnings = [];
1897
- for (const { name, callback, note } of onEndCallbacks) {
1898
- let newErrors;
1899
- let newWarnings;
1900
- try {
1901
- const value = await callback(result);
1902
- if (value != null) {
1903
- if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`);
1904
- let keys = {};
1905
- let errors = getFlag(value, keys, "errors", mustBeArray);
1906
- let warnings = getFlag(value, keys, "warnings", mustBeArray);
1907
- checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`);
1908
- if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0);
1909
- if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0);
1910
- }
1911
- } catch (e) {
1912
- newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)];
1913
- }
1914
- if (newErrors) {
1915
- onEndErrors.push(...newErrors);
1916
- try {
1917
- result.errors.push(...newErrors);
1918
- } catch {}
1919
- }
1920
- if (newWarnings) {
1921
- onEndWarnings.push(...newWarnings);
1922
- try {
1923
- result.warnings.push(...newWarnings);
1924
- } catch {}
1925
- }
1926
- }
1927
- done(onEndErrors, onEndWarnings);
1928
- })();
1929
- };
1930
- let scheduleOnDisposeCallbacks = () => {
1931
- for (const cb of onDisposeCallbacks) setTimeout(() => cb(), 0);
1932
- };
1933
- isSetupDone = true;
1934
- return {
1935
- ok: true,
1936
- requestPlugins,
1937
- runOnEndCallbacks,
1938
- scheduleOnDisposeCallbacks
1939
- };
1940
- };
1941
- function createObjectStash() {
1942
- const map = /* @__PURE__ */ new Map();
1943
- let nextID = 0;
1944
- return {
1945
- clear() {
1946
- map.clear();
1947
- },
1948
- load(id) {
1949
- return map.get(id);
1950
- },
1951
- store(value) {
1952
- if (value === void 0) return -1;
1953
- const id = nextID++;
1954
- map.set(id, value);
1955
- return id;
1956
- }
1957
- };
1958
- }
1959
- function extractCallerV8(e, streamIn, ident) {
1960
- let note;
1961
- let tried = false;
1962
- return () => {
1963
- if (tried) return note;
1964
- tried = true;
1965
- try {
1966
- let lines = (e.stack + "").split("\n");
1967
- lines.splice(1, 1);
1968
- let location = parseStackLinesV8(streamIn, lines, ident);
1969
- if (location) {
1970
- note = {
1971
- text: e.message,
1972
- location
1973
- };
1974
- return note;
1975
- }
1976
- } catch {}
1977
- };
1978
- }
1979
- function extractErrorMessageV8(e, streamIn, stash, note, pluginName) {
1980
- let text = "Internal error";
1981
- let location = null;
1982
- try {
1983
- text = (e && e.message || e) + "";
1984
- } catch {}
1985
- try {
1986
- location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), "");
1987
- } catch {}
1988
- return {
1989
- id: "",
1990
- pluginName,
1991
- text,
1992
- location,
1993
- notes: note ? [note] : [],
1994
- detail: stash ? stash.store(e) : -1
1995
- };
1996
- }
1997
- function parseStackLinesV8(streamIn, lines, ident) {
1998
- let at = " at ";
1999
- if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) for (let i = 1; i < lines.length; i++) {
2000
- let line = lines[i];
2001
- if (!line.startsWith(at)) continue;
2002
- line = line.slice(7);
2003
- while (true) {
2004
- let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line);
2005
- if (match) {
2006
- line = match[1];
2007
- continue;
2008
- }
2009
- match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line);
2010
- if (match) {
2011
- line = match[1];
2012
- continue;
2013
- }
2014
- match = /^(\S+):(\d+):(\d+)$/.exec(line);
2015
- if (match) {
2016
- let contents;
2017
- try {
2018
- contents = streamIn.readFileSync(match[1], "utf8");
2019
- } catch {
2020
- break;
2021
- }
2022
- let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || "";
2023
- let column = +match[3] - 1;
2024
- let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0;
2025
- return {
2026
- file: match[1],
2027
- namespace: "file",
2028
- line: +match[2],
2029
- column: encodeUTF8(lineText.slice(0, column)).length,
2030
- length: encodeUTF8(lineText.slice(column, column + length)).length,
2031
- lineText: lineText + "\n" + lines.slice(1).join("\n"),
2032
- suggestion: ""
2033
- };
2034
- }
2035
- break;
2036
- }
2037
- }
2038
- return null;
2039
- }
2040
- function failureErrorWithLog(text, errors, warnings) {
2041
- let limit = 5;
2042
- text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, 6).map((e, i) => {
2043
- if (i === limit) return "\n...";
2044
- if (!e.location) return `
2045
- error: ${e.text}`;
2046
- let { file, line, column } = e.location;
2047
- return `
2048
- ${file}:${line}:${column}: ERROR: ${e.pluginName ? `[plugin: ${e.pluginName}] ` : ""}${e.text}`;
2049
- }).join("");
2050
- let error = new Error(text);
2051
- for (const [key, value] of [["errors", errors], ["warnings", warnings]]) Object.defineProperty(error, key, {
2052
- configurable: true,
2053
- enumerable: true,
2054
- get: () => value,
2055
- set: (value2) => Object.defineProperty(error, key, {
2056
- configurable: true,
2057
- enumerable: true,
2058
- value: value2
2059
- })
2060
- });
2061
- return error;
2062
- }
2063
- function replaceDetailsInMessages(messages, stash) {
2064
- for (const message of messages) message.detail = stash.load(message.detail);
2065
- return messages;
2066
- }
2067
- function sanitizeLocation(location, where, terminalWidth) {
2068
- if (location == null) return null;
2069
- let keys = {};
2070
- let file = getFlag(location, keys, "file", mustBeString);
2071
- let namespace = getFlag(location, keys, "namespace", mustBeString);
2072
- let line = getFlag(location, keys, "line", mustBeInteger);
2073
- let column = getFlag(location, keys, "column", mustBeInteger);
2074
- let length = getFlag(location, keys, "length", mustBeInteger);
2075
- let lineText = getFlag(location, keys, "lineText", mustBeString);
2076
- let suggestion = getFlag(location, keys, "suggestion", mustBeString);
2077
- checkForInvalidFlags(location, keys, where);
2078
- if (lineText) {
2079
- const relevantASCII = lineText.slice(0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80));
2080
- if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) lineText = relevantASCII;
2081
- }
2082
- return {
2083
- file: file || "",
2084
- namespace: namespace || "",
2085
- line: line || 0,
2086
- column: column || 0,
2087
- length: length || 0,
2088
- lineText: lineText || "",
2089
- suggestion: suggestion || ""
2090
- };
2091
- }
2092
- function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) {
2093
- let messagesClone = [];
2094
- let index = 0;
2095
- for (const message of messages) {
2096
- let keys = {};
2097
- let id = getFlag(message, keys, "id", mustBeString);
2098
- let pluginName = getFlag(message, keys, "pluginName", mustBeString);
2099
- let text = getFlag(message, keys, "text", mustBeString);
2100
- let location = getFlag(message, keys, "location", mustBeObjectOrNull);
2101
- let notes = getFlag(message, keys, "notes", mustBeArray);
2102
- let detail = getFlag(message, keys, "detail", canBeAnything);
2103
- let where = `in element ${index} of "${property}"`;
2104
- checkForInvalidFlags(message, keys, where);
2105
- let notesClone = [];
2106
- if (notes) for (const note of notes) {
2107
- let noteKeys = {};
2108
- let noteText = getFlag(note, noteKeys, "text", mustBeString);
2109
- let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull);
2110
- checkForInvalidFlags(note, noteKeys, where);
2111
- notesClone.push({
2112
- text: noteText || "",
2113
- location: sanitizeLocation(noteLocation, where, terminalWidth)
2114
- });
2115
- }
2116
- messagesClone.push({
2117
- id: id || "",
2118
- pluginName: pluginName || fallbackPluginName,
2119
- text: text || "",
2120
- location: sanitizeLocation(location, where, terminalWidth),
2121
- notes: notesClone,
2122
- detail: stash ? stash.store(detail) : -1
2123
- });
2124
- index++;
2125
- }
2126
- return messagesClone;
2127
- }
2128
- function sanitizeStringArray(values, property) {
2129
- const result = [];
2130
- for (const value of values) {
2131
- if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`);
2132
- result.push(value);
2133
- }
2134
- return result;
2135
- }
2136
- function sanitizeStringMap(map, property) {
2137
- const result = /* @__PURE__ */ Object.create(null);
2138
- for (const key in map) {
2139
- const value = map[key];
2140
- if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`);
2141
- result[key] = value;
2142
- }
2143
- return result;
2144
- }
2145
- function convertOutputFiles({ path: path3, contents, hash }) {
2146
- let text = null;
2147
- return {
2148
- path: path3,
2149
- contents,
2150
- hash,
2151
- get text() {
2152
- const binary = this.contents;
2153
- if (text === null || binary !== contents) {
2154
- contents = binary;
2155
- text = decodeUTF8(binary);
2156
- }
2157
- return text;
2158
- }
2159
- };
2160
- }
2161
- function jsRegExpToGoRegExp(regexp) {
2162
- let result = regexp.source;
2163
- if (regexp.flags) result = `(?${regexp.flags})${result}`;
2164
- return result;
2165
- }
2166
- function parseJSON(bytes) {
2167
- let text;
2168
- try {
2169
- text = decodeUTF8(bytes);
2170
- } catch {
2171
- return JSON_parse(bytes);
2172
- }
2173
- return JSON.parse(text);
2174
- }
2175
- var fs = __require("fs");
2176
- var os = __require("os");
2177
- var path = __require("path");
2178
- var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
2179
- var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
2180
- var packageDarwin_arm64 = "@esbuild/darwin-arm64";
2181
- var packageDarwin_x64 = "@esbuild/darwin-x64";
2182
- var knownWindowsPackages = {
2183
- "win32 arm64 LE": "@esbuild/win32-arm64",
2184
- "win32 ia32 LE": "@esbuild/win32-ia32",
2185
- "win32 x64 LE": "@esbuild/win32-x64"
2186
- };
2187
- var knownUnixlikePackages = {
2188
- "aix ppc64 BE": "@esbuild/aix-ppc64",
2189
- "android arm64 LE": "@esbuild/android-arm64",
2190
- "darwin arm64 LE": "@esbuild/darwin-arm64",
2191
- "darwin x64 LE": "@esbuild/darwin-x64",
2192
- "freebsd arm64 LE": "@esbuild/freebsd-arm64",
2193
- "freebsd x64 LE": "@esbuild/freebsd-x64",
2194
- "linux arm LE": "@esbuild/linux-arm",
2195
- "linux arm64 LE": "@esbuild/linux-arm64",
2196
- "linux ia32 LE": "@esbuild/linux-ia32",
2197
- "linux mips64el LE": "@esbuild/linux-mips64el",
2198
- "linux ppc64 LE": "@esbuild/linux-ppc64",
2199
- "linux riscv64 LE": "@esbuild/linux-riscv64",
2200
- "linux s390x BE": "@esbuild/linux-s390x",
2201
- "linux x64 LE": "@esbuild/linux-x64",
2202
- "linux loong64 LE": "@esbuild/linux-loong64",
2203
- "netbsd arm64 LE": "@esbuild/netbsd-arm64",
2204
- "netbsd x64 LE": "@esbuild/netbsd-x64",
2205
- "openbsd arm64 LE": "@esbuild/openbsd-arm64",
2206
- "openbsd x64 LE": "@esbuild/openbsd-x64",
2207
- "sunos x64 LE": "@esbuild/sunos-x64"
2208
- };
2209
- var knownWebAssemblyFallbackPackages = {
2210
- "android arm LE": "@esbuild/android-arm",
2211
- "android x64 LE": "@esbuild/android-x64",
2212
- "openharmony arm64 LE": "@esbuild/openharmony-arm64"
2213
- };
2214
- function pkgAndSubpathForCurrentPlatform() {
2215
- let pkg;
2216
- let subpath;
2217
- let isWASM = false;
2218
- let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
2219
- if (platformKey in knownWindowsPackages) {
2220
- pkg = knownWindowsPackages[platformKey];
2221
- subpath = "esbuild.exe";
2222
- } else if (platformKey in knownUnixlikePackages) {
2223
- pkg = knownUnixlikePackages[platformKey];
2224
- subpath = "bin/esbuild";
2225
- } else if (platformKey in knownWebAssemblyFallbackPackages) {
2226
- pkg = knownWebAssemblyFallbackPackages[platformKey];
2227
- subpath = "bin/esbuild";
2228
- isWASM = true;
2229
- } else throw new Error(`Unsupported platform: ${platformKey}`);
2230
- return {
2231
- pkg,
2232
- subpath,
2233
- isWASM
2234
- };
2235
- }
2236
- function pkgForSomeOtherPlatform() {
2237
- const libMainJS = __require.resolve("esbuild");
2238
- const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS)));
2239
- if (path.basename(nodeModulesDirectory) === "node_modules") {
2240
- for (const unixKey in knownUnixlikePackages) try {
2241
- const pkg = knownUnixlikePackages[unixKey];
2242
- if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
2243
- } catch {}
2244
- for (const windowsKey in knownWindowsPackages) try {
2245
- const pkg = knownWindowsPackages[windowsKey];
2246
- if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg;
2247
- } catch {}
2248
- }
2249
- return null;
2250
- }
2251
- function downloadedBinPath(pkg, subpath) {
2252
- const esbuildLibDir = path.dirname(__require.resolve("esbuild"));
2253
- return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
2254
- }
2255
- function generateBinPath() {
2256
- if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
2257
- if (!fs.existsSync(ESBUILD_BINARY_PATH)) console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
2258
- else return {
2259
- binPath: ESBUILD_BINARY_PATH,
2260
- isWASM: false
2261
- };
2262
- }
2263
- const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
2264
- let binPath;
2265
- try {
2266
- binPath = __require.resolve(`${pkg}/${subpath}`);
2267
- } catch (e) {
2268
- binPath = downloadedBinPath(pkg, subpath);
2269
- if (!fs.existsSync(binPath)) {
2270
- try {
2271
- __require.resolve(pkg);
2272
- } catch {
2273
- const otherPkg = pkgForSomeOtherPlatform();
2274
- if (otherPkg) {
2275
- let suggestions = `
2276
- Specifically the "${otherPkg}" package is present but this platform
2277
- needs the "${pkg}" package instead. People often get into this
2278
- situation by installing esbuild on Windows or macOS and copying "node_modules"
2279
- into a Docker image that runs Linux, or by copying "node_modules" between
2280
- Windows and WSL environments.
2281
-
2282
- If you are installing with npm, you can try not copying the "node_modules"
2283
- directory when you copy the files over, and running "npm ci" or "npm install"
2284
- on the destination platform after the copy. Or you could consider using yarn
2285
- instead of npm which has built-in support for installing a package on multiple
2286
- platforms simultaneously.
2287
-
2288
- If you are installing with yarn, you can try listing both this platform and the
2289
- other platform in your ".yarnrc.yml" file using the "supportedArchitectures"
2290
- feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
2291
- Keep in mind that this means multiple copies of esbuild will be present.
2292
- `;
2293
- if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) suggestions = `
2294
- Specifically the "${otherPkg}" package is present but this platform
2295
- needs the "${pkg}" package instead. People often get into this
2296
- situation by installing esbuild with npm running inside of Rosetta 2 and then
2297
- trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta
2298
- 2 is Apple's on-the-fly x86_64-to-arm64 translation service).
2299
-
2300
- If you are installing with npm, you can try ensuring that both npm and node are
2301
- not running under Rosetta 2 and then reinstalling esbuild. This likely involves
2302
- changing how you installed npm and/or node. For example, installing node with
2303
- the universal installer here should work: https://nodejs.org/en/download/. Or
2304
- you could consider using yarn instead of npm which has built-in support for
2305
- installing a package on multiple platforms simultaneously.
2306
-
2307
- If you are installing with yarn, you can try listing both "arm64" and "x64"
2308
- in your ".yarnrc.yml" file using the "supportedArchitectures" feature:
2309
- https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures
2310
- Keep in mind that this means multiple copies of esbuild will be present.
2311
- `;
2312
- throw new Error(`
2313
- You installed esbuild for another platform than the one you're currently using.
2314
- This won't work because esbuild is written with native code and needs to
2315
- install a platform-specific binary executable.
2316
- ${suggestions}
2317
- Another alternative is to use the "esbuild-wasm" package instead, which works
2318
- the same way on all platforms. But it comes with a heavy performance cost and
2319
- can sometimes be 10x slower than the "esbuild" package, so you may also not
2320
- want to do that.
2321
- `);
2322
- }
2323
- throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild.
2324
-
2325
- If you are installing esbuild with npm, make sure that you don't specify the
2326
- "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature
2327
- of "package.json" is used by esbuild to install the correct binary executable
2328
- for your current platform.`);
2329
- }
2330
- throw e;
2331
- }
2332
- }
2333
- if (/\.zip\//.test(binPath)) {
2334
- let pnpapi;
2335
- try {
2336
- pnpapi = __require("pnpapi");
2337
- } catch (e) {}
2338
- if (pnpapi) {
2339
- const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation;
2340
- const binTargetPath = path.join(root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-0.27.7-${path.basename(subpath)}`);
2341
- if (!fs.existsSync(binTargetPath)) {
2342
- fs.mkdirSync(path.dirname(binTargetPath), { recursive: true });
2343
- fs.copyFileSync(binPath, binTargetPath);
2344
- fs.chmodSync(binTargetPath, 493);
2345
- }
2346
- return {
2347
- binPath: binTargetPath,
2348
- isWASM
2349
- };
2350
- }
2351
- }
2352
- return {
2353
- binPath,
2354
- isWASM
2355
- };
2356
- }
2357
- var child_process = __require("child_process");
2358
- var crypto = __require("crypto");
2359
- var path2 = __require("path");
2360
- var fs2 = __require("fs");
2361
- var os2 = __require("os");
2362
- var tty = __require("tty");
2363
- var worker_threads;
2364
- if (process.env.ESBUILD_WORKER_THREADS !== "0") {
2365
- try {
2366
- worker_threads = __require("worker_threads");
2367
- } catch {}
2368
- let [major, minor] = process.versions.node.split(".");
2369
- if (+major < 12 || +major === 12 && +minor < 17 || +major === 13 && +minor < 13) worker_threads = void 0;
2370
- }
2371
- var _a;
2372
- var isInternalWorkerThread = ((_a = worker_threads == null ? void 0 : worker_threads.workerData) == null ? void 0 : _a.esbuildVersion) === "0.27.7";
2373
- var esbuildCommandAndArgs = () => {
2374
- 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.
2375
-
2376
- 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.`);
2377
- {
2378
- const { binPath, isWASM } = generateBinPath();
2379
- if (isWASM) return ["node", [binPath]];
2380
- else return [binPath, []];
2381
- }
2382
- };
2383
- var isTTY = () => tty.isatty(2);
2384
- var fsSync = {
2385
- readFile(tempFile, callback) {
2386
- try {
2387
- let contents = fs2.readFileSync(tempFile, "utf8");
2388
- try {
2389
- fs2.unlinkSync(tempFile);
2390
- } catch {}
2391
- callback(null, contents);
2392
- } catch (err) {
2393
- callback(err, null);
2394
- }
2395
- },
2396
- writeFile(contents, callback) {
2397
- try {
2398
- let tempFile = randomFileName();
2399
- fs2.writeFileSync(tempFile, contents);
2400
- callback(tempFile);
2401
- } catch {
2402
- callback(null);
2403
- }
2404
- }
2405
- };
2406
- var fsAsync = {
2407
- readFile(tempFile, callback) {
2408
- try {
2409
- fs2.readFile(tempFile, "utf8", (err, contents) => {
2410
- try {
2411
- fs2.unlink(tempFile, () => callback(err, contents));
2412
- } catch {
2413
- callback(err, contents);
2414
- }
2415
- });
2416
- } catch (err) {
2417
- callback(err, null);
2418
- }
2419
- },
2420
- writeFile(contents, callback) {
2421
- try {
2422
- let tempFile = randomFileName();
2423
- fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile));
2424
- } catch {
2425
- callback(null);
2426
- }
2427
- }
2428
- };
2429
- var version = "0.27.7";
2430
- var build = (options) => ensureServiceIsRunning().build(options);
2431
- var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions);
2432
- var transform = (input, options) => ensureServiceIsRunning().transform(input, options);
2433
- var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options);
2434
- var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options);
2435
- var buildSync = (options) => {
2436
- if (worker_threads && !isInternalWorkerThread) {
2437
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2438
- return workerThreadService.buildSync(options);
2439
- }
2440
- let result;
2441
- runServiceSync((service) => service.buildOrContext({
2442
- callName: "buildSync",
2443
- refs: null,
2444
- options,
2445
- isTTY: isTTY(),
2446
- defaultWD,
2447
- callback: (err, res) => {
2448
- if (err) throw err;
2449
- result = res;
2450
- }
2451
- }));
2452
- return result;
2453
- };
2454
- var transformSync = (input, options) => {
2455
- if (worker_threads && !isInternalWorkerThread) {
2456
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2457
- return workerThreadService.transformSync(input, options);
2458
- }
2459
- let result;
2460
- runServiceSync((service) => service.transform({
2461
- callName: "transformSync",
2462
- refs: null,
2463
- input,
2464
- options: options || {},
2465
- isTTY: isTTY(),
2466
- fs: fsSync,
2467
- callback: (err, res) => {
2468
- if (err) throw err;
2469
- result = res;
2470
- }
2471
- }));
2472
- return result;
2473
- };
2474
- var formatMessagesSync = (messages, options) => {
2475
- if (worker_threads && !isInternalWorkerThread) {
2476
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2477
- return workerThreadService.formatMessagesSync(messages, options);
2478
- }
2479
- let result;
2480
- runServiceSync((service) => service.formatMessages({
2481
- callName: "formatMessagesSync",
2482
- refs: null,
2483
- messages,
2484
- options,
2485
- callback: (err, res) => {
2486
- if (err) throw err;
2487
- result = res;
2488
- }
2489
- }));
2490
- return result;
2491
- };
2492
- var analyzeMetafileSync = (metafile, options) => {
2493
- if (worker_threads && !isInternalWorkerThread) {
2494
- if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads);
2495
- return workerThreadService.analyzeMetafileSync(metafile, options);
2496
- }
2497
- let result;
2498
- runServiceSync((service) => service.analyzeMetafile({
2499
- callName: "analyzeMetafileSync",
2500
- refs: null,
2501
- metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2502
- options,
2503
- callback: (err, res) => {
2504
- if (err) throw err;
2505
- result = res;
2506
- }
2507
- }));
2508
- return result;
2509
- };
2510
- var stop = () => {
2511
- if (stopService) stopService();
2512
- if (workerThreadService) workerThreadService.stop();
2513
- return Promise.resolve();
2514
- };
2515
- var initializeWasCalled = false;
2516
- var initialize = (options) => {
2517
- options = validateInitializeOptions(options || {});
2518
- if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`);
2519
- if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`);
2520
- if (options.worker) throw new Error(`The "worker" option only works in the browser`);
2521
- if (initializeWasCalled) throw new Error("Cannot call \"initialize\" more than once");
2522
- ensureServiceIsRunning();
2523
- initializeWasCalled = true;
2524
- return Promise.resolve();
2525
- };
2526
- var defaultWD = process.cwd();
2527
- var longLivedService;
2528
- var stopService;
2529
- var ensureServiceIsRunning = () => {
2530
- if (longLivedService) return longLivedService;
2531
- let [command, args] = esbuildCommandAndArgs();
2532
- let child = child_process.spawn(command, args.concat(`--service=0.27.7`, "--ping"), {
2533
- windowsHide: true,
2534
- stdio: [
2535
- "pipe",
2536
- "pipe",
2537
- "inherit"
2538
- ],
2539
- cwd: defaultWD
2540
- });
2541
- let { readFromStdout, afterClose, service } = createChannel({
2542
- writeToStdin(bytes) {
2543
- child.stdin.write(bytes, (err) => {
2544
- if (err) afterClose(err);
2545
- });
2546
- },
2547
- readFileSync: fs2.readFileSync,
2548
- isSync: false,
2549
- hasFS: true,
2550
- esbuild: node_exports
2551
- });
2552
- child.stdin.on("error", afterClose);
2553
- child.on("error", afterClose);
2554
- const stdin = child.stdin;
2555
- const stdout = child.stdout;
2556
- stdout.on("data", readFromStdout);
2557
- stdout.on("end", afterClose);
2558
- stopService = () => {
2559
- stdin.destroy();
2560
- stdout.destroy();
2561
- child.kill();
2562
- initializeWasCalled = false;
2563
- longLivedService = void 0;
2564
- stopService = void 0;
2565
- };
2566
- let refCount = 0;
2567
- child.unref();
2568
- if (stdin.unref) stdin.unref();
2569
- if (stdout.unref) stdout.unref();
2570
- const refs = {
2571
- ref() {
2572
- if (++refCount === 1) child.ref();
2573
- },
2574
- unref() {
2575
- if (--refCount === 0) child.unref();
2576
- }
2577
- };
2578
- longLivedService = {
2579
- build: (options) => new Promise((resolve, reject) => {
2580
- service.buildOrContext({
2581
- callName: "build",
2582
- refs,
2583
- options,
2584
- isTTY: isTTY(),
2585
- defaultWD,
2586
- callback: (err, res) => err ? reject(err) : resolve(res)
2587
- });
2588
- }),
2589
- context: (options) => new Promise((resolve, reject) => service.buildOrContext({
2590
- callName: "context",
2591
- refs,
2592
- options,
2593
- isTTY: isTTY(),
2594
- defaultWD,
2595
- callback: (err, res) => err ? reject(err) : resolve(res)
2596
- })),
2597
- transform: (input, options) => new Promise((resolve, reject) => service.transform({
2598
- callName: "transform",
2599
- refs,
2600
- input,
2601
- options: options || {},
2602
- isTTY: isTTY(),
2603
- fs: fsAsync,
2604
- callback: (err, res) => err ? reject(err) : resolve(res)
2605
- })),
2606
- formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({
2607
- callName: "formatMessages",
2608
- refs,
2609
- messages,
2610
- options,
2611
- callback: (err, res) => err ? reject(err) : resolve(res)
2612
- })),
2613
- analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({
2614
- callName: "analyzeMetafile",
2615
- refs,
2616
- metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile),
2617
- options,
2618
- callback: (err, res) => err ? reject(err) : resolve(res)
2619
- }))
2620
- };
2621
- return longLivedService;
2622
- };
2623
- var runServiceSync = (callback) => {
2624
- let [command, args] = esbuildCommandAndArgs();
2625
- let stdin = /* @__PURE__ */ new Uint8Array();
2626
- let { readFromStdout, afterClose, service } = createChannel({
2627
- writeToStdin(bytes) {
2628
- if (stdin.length !== 0) throw new Error("Must run at most one command");
2629
- stdin = bytes;
2630
- },
2631
- isSync: true,
2632
- hasFS: true,
2633
- esbuild: node_exports
2634
- });
2635
- callback(service);
2636
- readFromStdout(child_process.execFileSync(command, args.concat(`--service=0.27.7`), {
2637
- cwd: defaultWD,
2638
- windowsHide: true,
2639
- input: stdin,
2640
- maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16777216
2641
- }));
2642
- afterClose(null);
2643
- };
2644
- var randomFileName = () => {
2645
- return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`);
2646
- };
2647
- var workerThreadService = null;
2648
- var startWorkerThreadService = (worker_threads2) => {
2649
- let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel();
2650
- let worker = new worker_threads2.Worker(__filename, {
2651
- workerData: {
2652
- workerPort,
2653
- defaultWD,
2654
- esbuildVersion: "0.27.7"
2655
- },
2656
- transferList: [workerPort],
2657
- execArgv: []
2658
- });
2659
- let nextID = 0;
2660
- let fakeBuildError = (text) => {
2661
- let error = /* @__PURE__ */ new Error(`Build failed with 1 error:
2662
- error: ${text}`);
2663
- error.errors = [{
2664
- id: "",
2665
- pluginName: "",
2666
- text,
2667
- location: null,
2668
- notes: [],
2669
- detail: void 0
2670
- }];
2671
- error.warnings = [];
2672
- return error;
2673
- };
2674
- let validateBuildSyncOptions = (options) => {
2675
- if (!options) return;
2676
- let plugins = options.plugins;
2677
- if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`);
2678
- };
2679
- let applyProperties = (object, properties) => {
2680
- for (let key in properties) object[key] = properties[key];
2681
- };
2682
- let runCallSync = (command, args) => {
2683
- let id = nextID++;
2684
- let sharedBuffer = new SharedArrayBuffer(8);
2685
- let sharedBufferView = new Int32Array(sharedBuffer);
2686
- let msg = {
2687
- sharedBuffer,
2688
- id,
2689
- command,
2690
- args
2691
- };
2692
- worker.postMessage(msg);
2693
- let status = Atomics.wait(sharedBufferView, 0, 0);
2694
- if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status);
2695
- let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort);
2696
- if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`);
2697
- if (reject) {
2698
- applyProperties(reject, properties);
2699
- throw reject;
2700
- }
2701
- return resolve;
2702
- };
2703
- worker.unref();
2704
- return {
2705
- buildSync(options) {
2706
- validateBuildSyncOptions(options);
2707
- return runCallSync("build", [options]);
2708
- },
2709
- transformSync(input, options) {
2710
- return runCallSync("transform", [input, options]);
2711
- },
2712
- formatMessagesSync(messages, options) {
2713
- return runCallSync("formatMessages", [messages, options]);
2714
- },
2715
- analyzeMetafileSync(metafile, options) {
2716
- return runCallSync("analyzeMetafile", [metafile, options]);
2717
- },
2718
- stop() {
2719
- worker.terminate();
2720
- workerThreadService = null;
2721
- }
2722
- };
2723
- };
2724
- var startSyncServiceWorker = () => {
2725
- let workerPort = worker_threads.workerData.workerPort;
2726
- let parentPort = worker_threads.parentPort;
2727
- let extractProperties = (object) => {
2728
- let properties = {};
2729
- if (object && typeof object === "object") for (let key in object) properties[key] = object[key];
2730
- return properties;
2731
- };
2732
- try {
2733
- let service = ensureServiceIsRunning();
2734
- defaultWD = worker_threads.workerData.defaultWD;
2735
- parentPort.on("message", (msg) => {
2736
- (async () => {
2737
- let { sharedBuffer, id, command, args } = msg;
2738
- let sharedBufferView = new Int32Array(sharedBuffer);
2739
- try {
2740
- switch (command) {
2741
- case "build":
2742
- workerPort.postMessage({
2743
- id,
2744
- resolve: await service.build(args[0])
2745
- });
2746
- break;
2747
- case "transform":
2748
- workerPort.postMessage({
2749
- id,
2750
- resolve: await service.transform(args[0], args[1])
2751
- });
2752
- break;
2753
- case "formatMessages":
2754
- workerPort.postMessage({
2755
- id,
2756
- resolve: await service.formatMessages(args[0], args[1])
2757
- });
2758
- break;
2759
- case "analyzeMetafile":
2760
- workerPort.postMessage({
2761
- id,
2762
- resolve: await service.analyzeMetafile(args[0], args[1])
2763
- });
2764
- break;
2765
- default: throw new Error(`Invalid command: ${command}`);
2766
- }
2767
- } catch (reject) {
2768
- workerPort.postMessage({
2769
- id,
2770
- reject,
2771
- properties: extractProperties(reject)
2772
- });
2773
- }
2774
- Atomics.add(sharedBufferView, 0, 1);
2775
- Atomics.notify(sharedBufferView, 0, Infinity);
2776
- })();
2777
- });
2778
- } catch (reject) {
2779
- parentPort.on("message", (msg) => {
2780
- let { sharedBuffer, id } = msg;
2781
- let sharedBufferView = new Int32Array(sharedBuffer);
2782
- workerPort.postMessage({
2783
- id,
2784
- reject,
2785
- properties: extractProperties(reject)
2786
- });
2787
- Atomics.add(sharedBufferView, 0, 1);
2788
- Atomics.notify(sharedBufferView, 0, Infinity);
2789
- });
2790
- }
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)
2791
356
  };
2792
- if (isInternalWorkerThread) startSyncServiceWorker();
2793
- var node_default = node_exports;
2794
- 0 && (module.exports = {
2795
- analyzeMetafile,
2796
- analyzeMetafileSync,
2797
- build,
2798
- buildSync,
2799
- context,
2800
- formatMessages,
2801
- formatMessagesSync,
2802
- initialize,
2803
- stop,
2804
- transform,
2805
- transformSync,
2806
- 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
2807
401
  });
2808
- })))();
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
2809
418
  const viteRawNamespace = "vitehub-vite-raw";
2810
419
  const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
2811
420
  const markdownTemplateFileSuffix = ".template.md";
2812
421
  const markdownTemplateModuleQuery = "markdown-template";
2813
422
  const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
2814
423
  const skipResolvedAlias = "vitehubSkipResolvedAlias";
2815
- const encodedAliasPrefixMarker = "\0vitehub-prefix:";
2816
- const encodedAliasExactMarker = "\0vitehub-exact:";
2817
424
  const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
2818
425
  function normalizePathSeparators(path) {
2819
426
  return path.replaceAll("\\", "/");
@@ -2823,9 +430,9 @@ function escapeRegExp(value) {
2823
430
  }
2824
431
  function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
2825
432
  if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
2826
- if (!Array.isArray(exportsValue) && !isPlainObject(exportsValue)) return [];
433
+ if (!Array.isArray(exportsValue) && !isRecord(exportsValue)) return [];
2827
434
  const candidates = [];
2828
- 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]];
2829
436
  for (const [exportKey, target] of exportEntries) {
2830
437
  const targets = [target];
2831
438
  while (targets.length) {
@@ -2842,12 +449,12 @@ function collectPackageExportCandidates(packageName, exportsValue, packageRelati
2842
449
  if (wildcard === void 0) continue;
2843
450
  candidates.push(`${packageName}${exportKey.slice(1).replace("*", wildcard)}`);
2844
451
  } else if (Array.isArray(value)) targets.push(...value);
2845
- else if (isPlainObject(value)) targets.push(...Object.values(value));
452
+ else if (isRecord(value)) targets.push(...Object.values(value));
2846
453
  }
2847
454
  }
2848
455
  return candidates;
2849
456
  }
2850
- function createResolvedAliasPlugin(aliases, aliasResolveDir) {
457
+ function createResolvedAliasPlugin(aliases, aliasResolveDir, resolveEntryPackageAliases = true) {
2851
458
  const entries = Object.entries(aliases || {});
2852
459
  if (!entries.length) return;
2853
460
  const resolvedEntries = Promise.all(entries.map(async ([encodedSpecifier, replacement]) => {
@@ -2873,6 +480,17 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
2873
480
  const resolvedBareAliasPaths = /* @__PURE__ */ new Map();
2874
481
  build.onResolve({ filter: /.*/ }, async (args) => {
2875
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
+ });
2876
494
  const aliases = await resolvedEntries;
2877
495
  let match = aliases.find(({ prefix, specifier }) => /^\.\.?[\\/]/.test(specifier) && (prefix ? args.path.startsWith(specifier) : args.path === specifier));
2878
496
  let matchedAlias = match?.specifier;
@@ -2889,128 +507,109 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
2889
507
  await canonicalizeSpecifier();
2890
508
  match = aliases.find(({ canonicalSpecifier: canonicalAlias, prefix }) => prefix ? canonicalSpecifier.startsWith(canonicalAlias) : canonicalSpecifier === canonicalAlias);
2891
509
  }
2892
- if (!match && isAbsolute(args.path)) for (const alias of aliases) {
2893
- if (isAbsolute(alias.specifier)) continue;
2894
- const packageAlias = alias.prefix ? alias.specifier.replace(/\/$/, "") : alias.specifier;
2895
- const aliasSegments = packageAlias.split("/");
2896
- if (!alias.prefix && aliasSegments.length === 1 && packageAlias.startsWith("@")) continue;
2897
- let packageName = packageAlias.startsWith("@") ? aliasSegments.slice(0, 2).join("/") : aliasSegments[0];
2898
- if (alias.prefix && aliasSegments.length === 1 && alias.specifier.startsWith("@")) {
2899
- const scopeMarker = `/node_modules/${packageAlias}/`;
2900
- const scopeMarkerIndex = normalizedSpecifier.lastIndexOf(scopeMarker);
2901
- const scopedPackage = scopeMarkerIndex === -1 ? void 0 : normalizedSpecifier.slice(scopeMarkerIndex + scopeMarker.length).split("/")[0];
2902
- if (scopedPackage) packageName = `${packageAlias}/${scopedPackage}`;
2903
- }
2904
- const packageMarker = `/node_modules/${packageName}/`;
2905
- const packageMarkerIndex = normalizedSpecifier.lastIndexOf(packageMarker);
2906
- const resolutionScope = packageMarkerIndex === -1 ? "" : normalizedSpecifier.slice(0, packageMarkerIndex + packageMarker.length);
2907
- const cacheKey = [
2908
- alias.specifier,
2909
- alias.prefix,
2910
- resolutionScope,
2911
- args.importer,
2912
- args.resolveDir,
2913
- args.kind,
2914
- args.namespace,
2915
- JSON.stringify(args.with)
2916
- ].join("\0");
2917
- let resolution = args.pluginData ? void 0 : resolvedBareAliasPaths.get(cacheKey);
2918
- if (!resolution) {
2919
- resolution = (async () => {
2920
- let resolvedAliasPath;
2921
- if (alias.prefix && /^\.\.?[\\/]/.test(alias.specifier)) resolvedAliasPath = normalizePathSeparators(resolve(aliasResolveDir, alias.specifier));
2922
- else if (resolutionScope) {
2923
- const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
2924
- const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
2925
- if (!isPlainObject(parsedPackageJson)) return;
2926
- const packageJson = parsedPackageJson;
2927
- if (packageJson.exports === void 0 && !alias.prefix) {
2928
- const resolvedCandidate = await build.resolve(alias.specifier, {
2929
- importer: args.importer,
2930
- kind: args.kind,
2931
- namespace: args.namespace,
2932
- pluginData: {
2933
- ...args.pluginData,
2934
- [skipResolvedAlias]: true
2935
- },
2936
- resolveDir: args.resolveDir,
2937
- with: args.with
2938
- });
2939
- if (!resolvedCandidate.errors.length && !resolvedCandidate.external && resolvedCandidate.namespace === "file" && normalizePathSeparators(resolve(resolvedCandidate.path)) === normalizedSpecifier) return {
2940
- canonical: alias.specifier,
2941
- normalized: alias.specifier,
2942
- publicSpecifier: alias.specifier
2943
- };
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
+ }
2944
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));
2945
577
  }
2946
- const matchingPublicSpecifiers = /* @__PURE__ */ new Set();
2947
- for (const publicSpecifier of collectPackageExportCandidates(packageName, packageJson.exports, packageRelativePath)) {
2948
- const resolvedCandidate = await build.resolve(publicSpecifier, {
2949
- importer: args.importer,
2950
- kind: args.kind,
2951
- namespace: args.namespace,
2952
- pluginData: {
2953
- ...args.pluginData,
2954
- [skipResolvedAlias]: true
2955
- },
2956
- resolveDir: args.resolveDir,
2957
- with: args.with
2958
- });
2959
- if (resolvedCandidate.errors.length || resolvedCandidate.external || resolvedCandidate.namespace !== "file") continue;
2960
- if (normalizePathSeparators(resolve(resolvedCandidate.path)) !== normalizedSpecifier) continue;
2961
- matchingPublicSpecifiers.add(publicSpecifier);
2962
- }
2963
- if (matchingPublicSpecifiers.size === 1) {
2964
- const publicSpecifier = [...matchingPublicSpecifiers][0];
2965
- if (alias.prefix ? publicSpecifier.startsWith(alias.specifier) : publicSpecifier === alias.specifier) return {
2966
- canonical: publicSpecifier,
2967
- normalized: publicSpecifier,
2968
- publicSpecifier
2969
- };
2970
- }
2971
- return;
2972
- } else {
2973
- const resolvedAlias = await build.resolve(alias.specifier, {
2974
- importer: args.importer,
2975
- kind: args.kind,
2976
- namespace: args.namespace,
2977
- pluginData: {
2978
- ...args.pluginData,
2979
- [skipResolvedAlias]: true
2980
- },
2981
- resolveDir: args.resolveDir,
2982
- with: args.with
2983
- });
2984
- if (resolvedAlias.errors.length || resolvedAlias.external || resolvedAlias.namespace !== "file") return;
2985
- resolvedAliasPath = normalizePathSeparators(resolve(resolvedAlias.path));
2986
- }
2987
- const canonicalAliasPath = normalizePathSeparators(await realpath(resolvedAliasPath).catch(() => resolvedAliasPath));
2988
- return {
2989
- canonical: `${canonicalAliasPath}${alias.prefix && !canonicalAliasPath.endsWith("/") ? "/" : ""}`,
2990
- normalized: `${resolvedAliasPath}${alias.prefix && !resolvedAliasPath.endsWith("/") ? "/" : ""}`
2991
- };
2992
- })();
2993
- if (!args.pluginData) resolvedBareAliasPaths.set(cacheKey, resolution);
2994
- }
2995
- const paths = await resolution;
2996
- if (!paths) continue;
2997
- if (paths.publicSpecifier) {
2998
- match = alias;
2999
- matchedAlias = alias.specifier;
3000
- matchedSpecifier = paths.publicSpecifier;
3001
- break;
3002
- }
3003
- const normalizedMatch = alias.prefix ? normalizedSpecifier.startsWith(paths.normalized) : normalizedSpecifier === paths.normalized;
3004
- let canonicalMatch = false;
3005
- if (!normalizedMatch && paths.canonical !== paths.normalized) {
3006
- await canonicalizeSpecifier();
3007
- 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
+ });
3008
590
  }
3009
- if (normalizedMatch || canonicalMatch) {
3010
- match = alias;
3011
- matchedAlias = alias.prefix ? canonicalMatch ? paths.canonical : paths.normalized : alias.specifier;
3012
- matchedSpecifier = alias.prefix ? canonicalMatch ? canonicalSpecifier : normalizedSpecifier : alias.specifier;
3013
- 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
+ }
3014
613
  }
3015
614
  }
3016
615
  matchedAlias ||= match && canonicalSpecifier.startsWith(match.canonicalSpecifier) ? match.canonicalSpecifier : match?.specifier;
@@ -3018,18 +617,7 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir) {
3018
617
  if (!match) return;
3019
618
  const target = match?.prefix ? matchedSpecifier.replace(matchedAlias.slice(0, -1), match.replacement.slice(0, -1)) : matchedSpecifier.replace(matchedAlias, match?.replacement ?? "");
3020
619
  if (!target) return;
3021
- const resolvedTarget = /^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target;
3022
- return build.resolve(resolvedTarget, {
3023
- importer: args.importer,
3024
- kind: args.kind,
3025
- namespace: args.namespace,
3026
- pluginData: {
3027
- ...args.pluginData,
3028
- [skipResolvedAlias]: true
3029
- },
3030
- resolveDir: args.resolveDir,
3031
- with: args.with
3032
- });
620
+ return resolveWithContext(/^\.\.?[\\/]/.test(target) ? resolve(aliasResolveDir, target) : target);
3033
621
  });
3034
622
  }
3035
623
  };
@@ -3113,7 +701,7 @@ function createViteRawPlugin(rootDir, frameworkRuntime) {
3113
701
  namespace: viteMarkdownTemplateNamespace
3114
702
  }, async (args) => {
3115
703
  if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
3116
- return build.resolve("vite-hub/_internal/markdown-template", {
704
+ return build.resolve("vite-hub/markdown-template", {
3117
705
  importer: args.importer,
3118
706
  kind: args.kind,
3119
707
  resolveDir: args.resolveDir
@@ -3182,15 +770,6 @@ function createViteRawPlugin(rootDir, frameworkRuntime) {
3182
770
  }
3183
771
  };
3184
772
  }
3185
- /** Select the runtime constants from one resolved Vite configuration. */
3186
- function resolveViteHubBundleDefines(config) {
3187
- const defines = {};
3188
- for (const name of ["__VITEHUB_PUBLIC_URL__", "__VITEHUB_APP_BASE_URL__"]) {
3189
- const value = config.define?.[name];
3190
- if (typeof value === "string") defines[name] = value;
3191
- }
3192
- return defines;
3193
- }
3194
773
  function createFileUrlPlugin() {
3195
774
  return {
3196
775
  name: "vitehub-file-url",
@@ -3199,19 +778,48 @@ function createFileUrlPlugin() {
3199
778
  }
3200
779
  };
3201
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
+ }
3202
808
  async function bundleEsmEntry(entryFile, outfile, options = {}) {
809
+ const { build: bundle } = await import("./main-F3Y22_uV.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1));
3203
810
  options.signal?.throwIfAborted();
3204
811
  const format = options.format || "esm";
3205
812
  const platform = options.platform || "neutral";
3206
813
  const viteAliasPlugin = createViteAliasPlugin(options.alias);
3207
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/"));
3208
815
  const plugins = [];
3209
- 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);
3210
817
  if (resolvedAliasPlugin) plugins.push(resolvedAliasPlugin);
3211
818
  plugins.push(...options.plugins ?? [], createFileUrlPlugin());
3212
819
  if (viteAliasPlugin) plugins.push(viteAliasPlugin);
3213
820
  plugins.push(createViteRawPlugin(options.rootDir, frameworkRuntime));
3214
- const result = await (0, import_main.build)({
821
+ if (platform !== "node") plugins.unshift(createWasmModulePlugin(dirname(outfile)));
822
+ const result = await bundle({
3215
823
  absWorkingDir: options.workingDir,
3216
824
  banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
3217
825
  "if (globalThis.process?.getBuiltinModule && import.meta.url) {",
@@ -3227,6 +835,7 @@ async function bundleEsmEntry(entryFile, outfile, options = {}) {
3227
835
  external: options.external,
3228
836
  format,
3229
837
  keepNames: options.minifySyntax || options.minifyIdentifiers,
838
+ loader: platform === "node" ? { ".wasm": "binary" } : void 0,
3230
839
  logLevel: "silent",
3231
840
  mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
3232
841
  resolveExtensions: options.extensions,
@@ -3347,13 +956,6 @@ var ProviderOutputCatalog = class {
3347
956
  if (owner) this.#runtimeContributions.delete(owner);
3348
957
  else this.#runtimeContributions.clear();
3349
958
  }
3350
- resetRuntimeContribution(product, generation) {
3351
- if (!generation) {
3352
- this.#runtimeContributions.delete(product);
3353
- return;
3354
- }
3355
- this.#runtimeContributionsByGeneration.get(generation)?.delete(product);
3356
- }
3357
959
  createDeploymentGeneration() {
3358
960
  const generation = { valid: true };
3359
961
  this.#trackDeploymentGeneration(generation);
@@ -3558,7 +1160,7 @@ function createDefaultCloudflareStaticOutputDir(rootDir) {
3558
1160
  return resolve(rootDir, "dist", "client");
3559
1161
  }
3560
1162
  function resolveProviderOutputOwnershipFile(outputRoot, fileName) {
3561
- if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw internalErrorDiagnostics.INTERNAL_B0034({ message: `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)})`);
3562
1164
  return resolve(outputRoot, fileName);
3563
1165
  }
3564
1166
  async function readProviderOutputOwnershipFile(outputRoot, fileName) {
@@ -3589,7 +1191,7 @@ async function resolvePersistedProviderOutputOwnership(outputRoot, ownership, fi
3589
1191
  const arrays = { ...ownership?.arrays };
3590
1192
  await Promise.all(Object.entries(files).map(async ([field, fileName]) => {
3591
1193
  const current = arrays[field];
3592
- if (!current) throw internalErrorDiagnostics.INTERNAL_B0036({ message: `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)})`);
3593
1195
  arrays[field] = {
3594
1196
  ...current,
3595
1197
  values: [...await readProviderOutputOwnershipFile(outputRoot, fileName), ...current.values ?? []]
@@ -3625,7 +1227,7 @@ function recoverNetlifyDeploymentOutput(rootDir) {
3625
1227
  if (!existsSync(outputRoot) && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
3626
1228
  }
3627
1229
  function assertNetlifyFunctionName(functionName) {
3628
- if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw internalErrorDiagnostics.INTERNAL_B0037({ message: `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})`);
3629
1231
  }
3630
1232
  function resolveNetlifyFunctionFile(functionsRoot, functionName) {
3631
1233
  assertNetlifyFunctionName(functionName);
@@ -3644,7 +1246,7 @@ async function writeCloudflareDeploymentOutput(options, signal) {
3644
1246
  const copiesStaticOutput = Boolean(options.bundleEntry && staticIndex && resolve(clientDir) !== resolve(staticOutputDir));
3645
1247
  const files = Object.entries(options.files ?? {});
3646
1248
  const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
3647
- if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw internalErrorDiagnostics.INTERNAL_B0038({ message: `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})`);
3648
1250
  const backupRoot = copiesStaticOutput ? await mkdtemp(resolve(options.rootDir, ".vitehub-cloudflare-output-")) : void 0;
3649
1251
  const previousOutputRoot = backupRoot ? resolve(backupRoot, "output") : `${outputRoot}.previous`;
3650
1252
  const previousStaticOutputDir = backupRoot ? resolve(backupRoot, "static") : `${staticOutputDir}.previous`;
@@ -3699,6 +1301,7 @@ async function writeCloudflareDeploymentOutput(options, signal) {
3699
1301
  });
3700
1302
  await bundleEsmEntry(options.bundleEntry, stagedWorkerOutfile, {
3701
1303
  ...options.bundleOptions,
1304
+ resolveEntryPackageAliases: options.bundleOptions?.resolveEntryPackageAliases ?? false,
3702
1305
  define: {
3703
1306
  ...options.bundleDefines,
3704
1307
  ...options.bundleOptions?.define
@@ -3819,6 +1422,7 @@ async function writeVercelDeploymentOutput(options, signal) {
3819
1422
  }
3820
1423
  await bundleEsmEntry(options.bundleEntry, serverEntry, {
3821
1424
  ...options.bundleOptions,
1425
+ resolveEntryPackageAliases: options.bundleOptions?.resolveEntryPackageAliases ?? false,
3822
1426
  define: {
3823
1427
  ...options.bundleDefines,
3824
1428
  ...options.bundleOptions?.define
@@ -3933,6 +1537,7 @@ async function writeNetlifyDeploymentOutput(options, signal) {
3933
1537
  await mkdir(dirname(outfile), { recursive: true });
3934
1538
  await bundleEsmEntry(func.bundleEntry, outfile, {
3935
1539
  ...func.bundleOptions,
1540
+ resolveEntryPackageAliases: func.bundleOptions.resolveEntryPackageAliases ?? false,
3936
1541
  conditions: func.bundleOptions.conditions ?? ["netlify", "node"],
3937
1542
  define: {
3938
1543
  ...options.bundleDefines,
@@ -4513,34 +2118,6 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
4513
2118
  if (providerDeploymentOutputFinalizations.get(catalog) === active) providerDeploymentOutputFinalizations.delete(catalog);
4514
2119
  }
4515
2120
  }
4516
- const VITEHUB_MODES = {
4517
- e2e: "e2e",
4518
- blob: "blob",
4519
- chat: "chat",
4520
- db: "db",
4521
- env: "env",
4522
- kv: "kv",
4523
- queue: "queue",
4524
- schedule: "schedule",
4525
- sandbox: "sandbox",
4526
- workspace: "workspace",
4527
- workflow: "workflow"
4528
- };
4529
- function isViteCli(argv) {
4530
- return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
4531
- }
4532
- function getViteCliMode(argv = process.argv) {
4533
- if (!isViteCli(argv)) return;
4534
- const modes = new Set(Object.values(VITEHUB_MODES));
4535
- for (let index = 0; index < argv.length; index += 1) {
4536
- const arg = argv[index];
4537
- const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
4538
- if (mode && modes.has(mode)) return mode;
4539
- }
4540
- }
4541
- function getViteMode(env = process.env) {
4542
- return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
4543
- }
4544
2121
  //#endregion
4545
2122
  //#region ../internal/src/provision-state.ts
4546
2123
  const PROVISION_STATE_FILE = ".vitehub/provision.json";
@@ -4569,14 +2146,14 @@ function readProvisionedId(state, provider, category, key) {
4569
2146
  }
4570
2147
  function parseProvisionState(raw) {
4571
2148
  const parsed = JSON.parse(raw);
4572
- if (!isPlainObject(parsed)) return {};
2149
+ if (!isRecord(parsed)) return {};
4573
2150
  const state = {};
4574
2151
  for (const provider of ["cloudflare", "vercel"]) {
4575
2152
  const categories = parsed[provider];
4576
- if (!isPlainObject(categories)) continue;
2153
+ if (!isRecord(categories)) continue;
4577
2154
  const validCategories = {};
4578
2155
  for (const [category, ids] of Object.entries(categories)) {
4579
- if (!isPlainObject(ids)) continue;
2156
+ if (!isRecord(ids)) continue;
4580
2157
  const validIds = {};
4581
2158
  for (const [key, id] of Object.entries(ids)) if (typeof id === "string") setOwn(validIds, key, id);
4582
2159
  if (Object.keys(validIds).length) setOwn(validCategories, category, validIds);
@@ -4594,57 +2171,281 @@ function setOwn(target, key, value) {
4594
2171
  });
4595
2172
  }
4596
2173
  //#endregion
4597
- //#region ../internal/src/arrays.ts
4598
- function pushUnique(arr, item, key = (value) => value) {
4599
- const id = key(item);
4600
- if (arr.some((entry) => key(entry) === id)) return;
4601
- 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
+ }
4602
2187
  }
4603
2188
  function configureCloudflareKV(target, config, provisionState = {}) {
4604
2189
  for (const [storeName, store] of Object.entries(config.stores || { default: config.store })) {
4605
- if (store.driver !== "cloudflare-kv-binding") continue;
2190
+ if (store.driver !== "cloudflare") continue;
4606
2191
  const { binding } = store;
4607
2192
  const namespaceId = store.namespaceId ?? readProvisionedId(provisionState, "cloudflare", "kv", storeName);
4608
2193
  target.cloudflare ||= {};
4609
2194
  target.cloudflare.wrangler ||= {};
4610
2195
  target.cloudflare.wrangler.kv_namespaces ||= [];
4611
- 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({
4612
2205
  binding,
4613
- ...namespaceId ? { id: namespaceId } : {}
4614
- }, (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;
4615
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));
4616
2414
  }
4617
2415
  //#endregion
4618
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
+ }
4619
2424
  function resolveCloudflareProvisionConfig(env) {
4620
- const accountId = trimmedEnv(env.CLOUDFLARE_ACCOUNT_ID);
4621
- const token = trimmedEnv(env.CLOUDFLARE_API_TOKEN);
4622
- if (!accountId || !token) return;
2425
+ const credentials = readHostCredentialsFromEnv("cloudflare", env);
2426
+ if (!credentials?.accountId) return;
4623
2427
  return {
4624
- accountId,
4625
- token
2428
+ accountId: credentials.accountId,
2429
+ token: credentials.token
4626
2430
  };
4627
2431
  }
4628
2432
  function ownParser(options) {
4629
2433
  if (!Object.hasOwn(options, "parse")) return;
4630
2434
  return options.parse;
4631
2435
  }
4632
- var ProvisionRequestError = class ProvisionRequestError extends Diagnostic {
4633
- codes;
4634
- status;
4635
- constructor(method, path, status, codes = []) {
4636
- const suffix = codes.length ? ` Provider code${codes.length === 1 ? "" : "s"}: ${codes.join(", ")}.` : "";
4637
- super({
4638
- code: "INTERNAL_R0013",
4639
- docs: "https://vitehub.dev/docs/reference/diagnostics",
4640
- why: `Provision request failed: ${method} ${path} (${status}).${suffix}`
4641
- }, ProvisionRequestError);
4642
- this.name = "ProvisionRequestError";
4643
- this.codes = codes;
4644
- this.status = status;
4645
- }
4646
- };
4647
- function createJsonClient(baseURL, headers, fetchImpl, baseQuery) {
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) {
4648
2449
  return async function request(path, options = {}) {
4649
2450
  const url = new URL(`${baseURL}${path}`);
4650
2451
  const query = Object.hasOwn(options, "query") ? options.query : void 0;
@@ -4671,9 +2472,12 @@ function createJsonClient(baseURL, headers, fetchImpl, baseQuery) {
4671
2472
  }
4672
2473
  const response = await fetchImpl(url, init);
4673
2474
  if (!response.ok) {
4674
- const body = await response.json().catch(() => void 0);
4675
- const codes = [body?.error?.code, ...body?.errors?.map((error) => error.code) ?? []].filter((code) => typeof code === "number" || typeof code === "string" && /^[\w.-]{1,128}$/.test(code));
4676
- throw new ProvisionRequestError(method ?? "GET", path, response.status, codes);
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);
4677
2481
  }
4678
2482
  const value = await response.json();
4679
2483
  const parse = ownParser(options);
@@ -4681,7 +2485,13 @@ function createJsonClient(baseURL, headers, fetchImpl, baseQuery) {
4681
2485
  };
4682
2486
  }
4683
2487
  function createCloudflareProvisionClient(config, fetchImpl = globalThis.fetch) {
4684
- const client = createJsonClient(`https://api.cloudflare.com/client/v4/accounts/${config.accountId}`, { authorization: `Bearer ${config.token}` }, fetchImpl);
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);
4685
2495
  return async (path, options = {}) => {
4686
2496
  const parse = ownParser(options) ?? ((value) => value);
4687
2497
  return await client(path, {
@@ -4697,14 +2507,37 @@ function createCloudflareProvisionClient(config, fetchImpl = globalThis.fetch) {
4697
2507
  });
4698
2508
  };
4699
2509
  }
4700
- function trimmedEnv(value) {
4701
- const trimmed = value?.trim();
4702
- return trimmed ? trimmed : void 0;
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;
2536
+ }
4703
2537
  }
4704
2538
  //#endregion
4705
2539
  //#region src/provision.ts
4706
2540
  const CLOUDFLARE_KV_NAMESPACE_LIST_PER_PAGE = 100;
4707
- const CLOUDFLARE_KV_DUPLICATE_TITLE_CODE = 10014;
4708
2541
  function parseNamespaces(value) {
4709
2542
  if (!Array.isArray(value)) throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: "Cloudflare returned an invalid KV namespace list." });
4710
2543
  for (const namespace of value) {
@@ -4723,27 +2556,12 @@ function parseCreatedNamespace(value) {
4723
2556
  }
4724
2557
  async function listNamespaceIds(request) {
4725
2558
  const ids = /* @__PURE__ */ new Map();
4726
- for (let page = 1;; page++) {
4727
- const listed = await request("/storage/kv/namespaces", {
4728
- parse: parseNamespaces,
4729
- query: {
4730
- page: String(page),
4731
- per_page: String(CLOUDFLARE_KV_NAMESPACE_LIST_PER_PAGE)
4732
- }
4733
- });
4734
- const namespaces = listed.result ?? [];
4735
- for (const namespace of namespaces) if (namespace.id && namespace.title && !ids.has(namespace.title)) ids.set(namespace.title, namespace.id);
4736
- const resultInfo = listed.result_info;
4737
- if (resultInfo?.total_pages !== void 0) {
4738
- if (page >= resultInfo.total_pages) return ids;
4739
- continue;
4740
- }
4741
- if (resultInfo?.total_count !== void 0) {
4742
- if ((resultInfo.page ?? page) * (resultInfo.per_page ?? CLOUDFLARE_KV_NAMESPACE_LIST_PER_PAGE) < resultInfo.total_count) continue;
4743
- return ids;
4744
- }
4745
- if (namespaces.length < CLOUDFLARE_KV_NAMESPACE_LIST_PER_PAGE) return ids;
4746
- }
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;
4747
2565
  }
4748
2566
  async function createNamespace(request, title) {
4749
2567
  try {
@@ -4753,7 +2571,7 @@ async function createNamespace(request, title) {
4753
2571
  parse: parseCreatedNamespace
4754
2572
  })).result?.id;
4755
2573
  } catch (error) {
4756
- if (!(error instanceof ProvisionRequestError && (error.status === 400 || error.status === 409 || error.codes.includes(CLOUDFLARE_KV_DUPLICATE_TITLE_CODE)))) throw error;
2574
+ if (!isProvisionRequestError(error) || error.kind !== "conflict") throw error;
4757
2575
  const id = (await listNamespaceIds(request)).get(title);
4758
2576
  if (!id) throw error;
4759
2577
  return id;
@@ -4767,23 +2585,39 @@ function planStoresByNamespace(options, env) {
4767
2585
  const storesByNamespace = /* @__PURE__ */ new Map();
4768
2586
  if (!kv) return storesByNamespace;
4769
2587
  for (const [storeName, store] of Object.entries(kv.stores || { default: kv.store })) {
4770
- if (store.driver !== "cloudflare-kv-binding" || store.namespaceId || !store.namespaceName) continue;
2588
+ if (store.driver !== "cloudflare" || store.namespaceId || !store.namespaceName) continue;
4771
2589
  const stores = storesByNamespace.get(store.namespaceName);
4772
2590
  if (stores) stores.push(storeName);
4773
2591
  else storesByNamespace.set(store.namespaceName, [storeName]);
4774
2592
  }
4775
2593
  return storesByNamespace;
4776
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
+ }
4777
2603
  function createKVCloudflareProvisionStep(resolveOptions) {
4778
2604
  return {
4779
2605
  id: "kv:cloudflare-kv",
4780
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
+ },
4781
2614
  async plan(context) {
4782
2615
  const storesByNamespace = planStoresByNamespace(resolveOptions(), context.env);
4783
2616
  if (!storesByNamespace.size) return [];
4784
2617
  const config = resolveCloudflareProvisionConfig(context.env);
4785
2618
  if (!config) {
4786
2619
  context.logger.warn("kv: skipping Cloudflare KV, missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN.");
2620
+ context.markPlanUnchecked?.();
4787
2621
  return [];
4788
2622
  }
4789
2623
  const request = createCloudflareProvisionClient(config, context.fetch);
@@ -4802,47 +2636,163 @@ function createKVCloudflareProvisionStep(resolveOptions) {
4802
2636
  };
4803
2637
  }
4804
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
4805
2665
  //#region src/vite.ts
2666
+ const operationsModule = ownModule(import.meta.url, "operations");
4806
2667
  const RESOLVED_KV_VIRTUAL_CONFIG_ID = `\0${KV_VIRTUAL_CONFIG_ID}`;
4807
2668
  const RESOLVED_KV_RUNTIME_ID = `\0#vitehub/kv/runtime`;
4808
- 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");
4809
2670
  const UPSTASH_DRIVER_IMPORT_ID = "@vite-hub/kv/runtime/upstash-driver";
4810
- 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;
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");
4811
2681
  const mergeNoExternal = createNoExternalAddition("@vite-hub/kv");
4812
2682
  const KV_CLOUDFLARE_BINDINGS_FILE = ".vitehub-kv-bindings.json";
4813
- 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() {
4814
2687
  return {
4815
2688
  name: "@vite-hub/kv/optional-peers",
4816
2689
  enforce: "pre",
4817
- resolveId(id, importer, resolveOptions) {
4818
- if (!resolveOptions?.ssr || !isKVOptionalUpstashImport(id, importer)) return;
4819
- return {
4820
- external: true,
4821
- id
4822
- };
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
+ }
4823
2699
  }
4824
2700
  };
4825
2701
  }
4826
- 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;
4827
2722
  return [
4828
2723
  `export const hosting = ${JSON.stringify(config.hosting)};`,
4829
- `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;",
4830
2726
  "export default { hosting, kv };"
4831
2727
  ].join("\n");
4832
2728
  }
4833
2729
  function isCloudflareKVConfig(kv) {
4834
2730
  if (!kv) return false;
4835
- 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");
4836
2732
  }
4837
- function hasUpstashStore(kv) {
2733
+ function hasCloudflareKVStore(kv) {
4838
2734
  if (!kv) return false;
4839
- 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");
4840
2736
  }
4841
- function isKVOptionalUpstashImport(id, importer) {
4842
- if (id !== UPSTASH_DRIVER_IMPORT_ID || !importer) return false;
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;
2782
+ }
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;
4843
2789
  const normalizedImporter = importer.replace(/\\/g, "/").split("?", 1)[0];
4844
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");
4845
2791
  }
2792
+ function isUnstorageCloudflareWorkersImport(id, importer) {
2793
+ if (id !== "cloudflare:workers" || !importer) return false;
2794
+ return /[/\\]unstorage[/\\]dist[/\\]/.test(importer);
2795
+ }
4846
2796
  function createCloudflareKVWranglerConfig(kv, provisionState) {
4847
2797
  if (!kv) return;
4848
2798
  const target = {};
@@ -4852,7 +2802,7 @@ function createCloudflareKVWranglerConfig(kv, provisionState) {
4852
2802
  function serializeCloudflareRuntime(config) {
4853
2803
  return [
4854
2804
  `import { createCloudflareKVStorage } from ${JSON.stringify(CLOUDFLARE_KV_RUNTIME_IMPORT_ID)};`,
4855
- `import { kvInvalidLimitError, kvResult, kvStoreNotFoundError, kvUnsupportedOperationError } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
2805
+ `import { kvInvalidLimitError, kvKeyLimitCodes, kvResult, kvStoreNotFoundError, kvStoreWithMode, kvUnsupportedOperationError, kvWriteLimitCodes } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
4856
2806
  "",
4857
2807
  `const kvConfig = ${JSON.stringify(config, null, 2)}`,
4858
2808
  "const storages = new Map();",
@@ -4865,6 +2815,10 @@ function serializeCloudflareRuntime(config) {
4865
2815
  " return store;",
4866
2816
  "}",
4867
2817
  "",
2818
+ "export async function getKVStoreDriver(name = \"default\") {",
2819
+ " return resolveStoreConfig(name).driver;",
2820
+ "}",
2821
+ "",
4868
2822
  "function resolveStorage(name = \"default\") {",
4869
2823
  " const store = resolveStoreConfig(name);",
4870
2824
  " const existing = storages.get(name);",
@@ -4883,15 +2837,20 @@ function serializeCloudflareRuntime(config) {
4883
2837
  "function createKVStorage(name = \"default\") {",
4884
2838
  " return {",
4885
2839
  " async clear(base, options) { return kvResult(\"clear\", name, async () => { await resolveStorage(name).clear(base, options); }); },",
4886
- " async del(key, options) { return kvResult(\"del\", name, async () => { await resolveStorage(name).removeItem(key, options); }); },",
4887
- " async get(key, options) { return kvResult(\"get\", name, () => resolveStorage(name).getItem(key, 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); },",
4888
2843
  " async getAndDelete() { return unsupported(\"getAndDelete\", name); },",
4889
- " async has(key, options) { return kvResult(\"has\", name, () => resolveStorage(name).hasItem(key, options)); },",
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); },",
4890
2846
  " async increment() { return unsupported(\"increment\", name); },",
4891
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); } }; },",
4892
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\"]); },",
4893
- " async set(key, value, options) { return kvResult(\"set\", name, async () => { await resolveStorage(name).setItem(key, value, options); }); },",
4894
- " store(storeName) { return createKVStorage(storeName); },",
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); },",
4895
2854
  " };",
4896
2855
  "}",
4897
2856
  "",
@@ -4900,11 +2859,11 @@ function serializeCloudflareRuntime(config) {
4900
2859
  ].join("\n");
4901
2860
  }
4902
2861
  function getNitroCloudflareKVNamespaces(target) {
4903
- if (!isPlainObject(target)) return [];
2862
+ if (!isRecord(target)) return [];
4904
2863
  const cloudflare = Reflect.get(target, "cloudflare");
4905
- if (!isPlainObject(cloudflare)) return [];
2864
+ if (!isRecord(cloudflare)) return [];
4906
2865
  const wrangler = Reflect.get(cloudflare, "wrangler");
4907
- if (!isPlainObject(wrangler)) return [];
2866
+ if (!isRecord(wrangler)) return [];
4908
2867
  const namespaces = Reflect.get(wrangler, "kv_namespaces");
4909
2868
  if (!Array.isArray(namespaces)) return [];
4910
2869
  return namespaces.flatMap((namespace) => {
@@ -4919,10 +2878,12 @@ function getNitroCloudflareKVNamespaces(target) {
4919
2878
  const id = Reflect.get(normalized, "id");
4920
2879
  const previewId = Reflect.get(normalized, "preview_id");
4921
2880
  const experimentalRemote = Reflect.get(normalized, "experimental_remote");
2881
+ const remote = Reflect.get(normalized, "remote");
4922
2882
  if (typeof binding !== "string") return [];
4923
2883
  if (id !== void 0 && typeof id !== "string") return [];
4924
2884
  if (previewId !== void 0 && typeof previewId !== "string") return [];
4925
2885
  if (experimentalRemote !== void 0 && typeof experimentalRemote !== "boolean") return [];
2886
+ if (remote !== void 0 && typeof remote !== "boolean") return [];
4926
2887
  return [normalized];
4927
2888
  });
4928
2889
  }
@@ -4930,6 +2891,9 @@ function getResolvedNitroConfig(config) {
4930
2891
  return Reflect.get(config, "nitro");
4931
2892
  }
4932
2893
  function reconcileNitroCloudflareKV(target, kv, ownedNamespaces, provisionState) {
2894
+ configureNitroCloudflareRequestEnv(target, kv);
2895
+ configureNitroPlugin(target, kv);
2896
+ configureNitroStorage(target, kv);
4933
2897
  const namespaces = target.cloudflare?.wrangler?.kv_namespaces;
4934
2898
  if (namespaces?.length && ownedNamespaces.size) for (const owned of ownedNamespaces) {
4935
2899
  const ownedIndex = namespaces.findIndex((namespace) => namespace.binding === owned.binding && namespace.id === owned.id);
@@ -4937,14 +2901,17 @@ function reconcileNitroCloudflareKV(target, kv, ownedNamespaces, provisionState)
4937
2901
  }
4938
2902
  if (kv) configureCloudflareKV(target, kv, provisionState);
4939
2903
  }
4940
- function configureNitroCloudflareKV(config, options, ownedNamespaces, provisionState) {
4941
- const { nitro } = config;
4942
- 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;
4943
2907
  const target = nitro;
4944
2908
  const namespaces = target.cloudflare?.wrangler?.kv_namespaces;
4945
2909
  if (namespaces && ownedNamespaces.size) target.cloudflare.wrangler.kv_namespaces = namespaces.filter((namespace) => !ownedNamespaces.has(namespace));
4946
2910
  ownedNamespaces.clear();
4947
- 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);
4948
2915
  if (kv) {
4949
2916
  const existingNamespaces = new Set(target.cloudflare?.wrangler?.kv_namespaces);
4950
2917
  configureCloudflareKV(target, kv, provisionState);
@@ -4952,21 +2919,37 @@ function configureNitroCloudflareKV(config, options, ownedNamespaces, provisionS
4952
2919
  }
4953
2920
  return true;
4954
2921
  }
4955
- 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
+ });
4956
2936
  let nitroOwned = false;
2937
+ let redisEnvWarned = false;
4957
2938
  let nitroOptions;
4958
2939
  const ownedNitroNamespaces = /* @__PURE__ */ new Set();
4959
2940
  let resolved;
4960
2941
  let providerOutput;
4961
2942
  let runtimeConfig;
4962
- let configuredOptions = options;
4963
2943
  let projectRoot = process.cwd();
4964
- const getConfig = () => runtimeConfig ??= resolveKVViteConfig(options);
2944
+ const getConfig = () => runtimeConfig ??= resolveKVViteConfig(options, resolutionInput());
4965
2945
  const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
4966
2946
  return {
4967
2947
  name: KV_VITE_PLUGIN_NAME,
4968
2948
  enforce: "post",
4969
- api: { getConfig },
2949
+ api: {
2950
+ deploymentEnv: () => kvDeploymentEnv(getConfig().kv),
2951
+ getConfig
2952
+ },
4970
2953
  nitro: {
4971
2954
  name: "@vite-hub/kv/cloudflare-bindings",
4972
2955
  setup(nitro) {
@@ -4975,10 +2958,51 @@ function hubKv(options) {
4975
2958
  }
4976
2959
  },
4977
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
+ },
4978
3002
  operations: [{
4979
3003
  export: "kvOperations",
4980
3004
  load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).kvOperations,
4981
- module: "@vite-hub/kv/operations"
3005
+ module: operationsModule
4982
3006
  }],
4983
3007
  cli: async () => {
4984
3008
  const { createKVCliContributor } = await import(
@@ -4986,31 +3010,37 @@ function hubKv(options) {
4986
3010
  "./cli.js"
4987
3011
  );
4988
3012
  return {
4989
- ...createKVCliContributor(),
4990
- provision: [createKVCloudflareProvisionStep(() => configuredOptions)]
3013
+ ...createKVCliContributor({ projectRoot: () => projectRoot }),
3014
+ provision: [createKVCloudflareProvisionStep(() => options)]
4991
3015
  };
4992
3016
  }
4993
3017
  },
4994
3018
  config: {
4995
3019
  order: "pre",
4996
- handler(config, env) {
4997
- configuredOptions = config.kv ?? options;
3020
+ async handler(config, env) {
3021
+ command = env?.command ?? "build";
3022
+ mode = env?.mode ?? config.mode ?? (command === "serve" ? "development" : "production");
3023
+ runtimeConfig = void 0;
4998
3024
  projectRoot = resolveViteHubProjectRoot(config.root || process.cwd());
4999
- nitroOwned = configureNitroCloudflareKV(config, options, ownedNitroNamespaces, readProvisionStateSync(projectRoot));
5000
- return installStandaloneOperationRpc(config, env?.command ?? "build", "@vite-hub/kv/operations");
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);
5001
3028
  }
5002
3029
  },
5003
3030
  configResolved: {
5004
3031
  order: "pre",
5005
- handler(config) {
3032
+ async handler(config) {
5006
3033
  resolved = config;
5007
- configuredOptions = config.kv ?? options;
3034
+ if (config.command) command = config.command;
3035
+ mode = config.mode ?? mode;
5008
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);
5009
3039
  providerOutput = useProviderOutputCatalog(config);
5010
- runtimeConfig = resolveKVViteConfig(config.kv ?? options);
3040
+ runtimeConfig = resolveKVViteConfig(options, resolutionInput());
5011
3041
  const provisionState = readProvisionStateSync(projectRoot);
5012
3042
  if (nitroOptions) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, provisionState);
5013
- if (hasNitroConfigContext(config) || isPlainObject(getResolvedNitroConfig(config))) nitroOwned = configureNitroCloudflareKV(config, options, ownedNitroNamespaces, provisionState);
3043
+ if (hasNitroConfigContext(config) || isRecord(getResolvedNitroConfig(config))) nitroOwned = configureNitroCloudflareKV(config, options, resolutionInput(), ownedNitroNamespaces, provisionState);
5014
3044
  }
5015
3045
  },
5016
3046
  configureServer(server) {
@@ -5025,29 +3055,51 @@ function hubKv(options) {
5025
3055
  },
5026
3056
  resolveId: {
5027
3057
  order: "pre",
3058
+ filter: { id: RESOLVE_ID_PATTERN },
5028
3059
  handler(id, importer, resolveOptions) {
5029
- 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 {
5030
3061
  external: true,
5031
3062
  id
5032
3063
  };
5033
- 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;
5034
3073
  if (id === "#vitehub/kv/config") return RESOLVED_KV_VIRTUAL_CONFIG_ID;
5035
3074
  }
5036
3075
  },
5037
3076
  load: {
5038
3077
  order: "pre",
5039
- handler(id) {
3078
+ filter: { id: LOAD_ID_PATTERN },
3079
+ handler(id, options) {
5040
3080
  if (id === RESOLVED_KV_RUNTIME_ID) {
5041
3081
  const kv = getConfig().kv;
5042
- if (isCloudflareKVConfig(kv)) return serializeCloudflareRuntime(kv);
3082
+ if (command === "build" && isCloudflareKVConfig(kv)) return serializeCloudflareRuntime(kv);
5043
3083
  }
5044
- 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);
5045
3085
  }
5046
3086
  },
5047
3087
  buildStart: {
5048
3088
  order: "pre",
5049
3089
  handler() {
3090
+ runtimeConfig = void 0;
5050
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);
5051
3103
  }
5052
3104
  },
5053
3105
  buildEnd: {
@@ -5057,7 +3109,7 @@ function hubKv(options) {
5057
3109
  await providerOutputGenerations.reset(this, providerOutput, error);
5058
3110
  return;
5059
3111
  }
5060
- if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
3112
+ if (!resolved || shouldSkipViteProviderBuild(resolved.command)) return;
5061
3113
  const rootDir = resolved.root;
5062
3114
  const clientOutDir = resolved.build.outDir;
5063
3115
  const wranglerConfig = nitroOwned ? void 0 : createCloudflareKVWranglerConfig(getConfig().kv, readProvisionStateSync(projectRoot));
@@ -5097,11 +3149,11 @@ function hubKv(options) {
5097
3149
  order: "post",
5098
3150
  sequential: true,
5099
3151
  async handler() {
5100
- if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
3152
+ if (!resolved || shouldSkipViteProviderBuild(resolved.command)) return;
5101
3153
  await finalizeProviderDeploymentOutputs(providerOutput);
5102
3154
  }
5103
3155
  }
5104
3156
  };
5105
3157
  }
5106
3158
  //#endregion
5107
- 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 };