@vite-hub/kv 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +33 -8
  2. package/dist/cli-Cniq99iX.d.ts +85 -0
  3. package/dist/cli.d.ts +15 -0
  4. package/dist/cli.js +448 -0
  5. package/dist/cloudflare-env-C5rM7kUY.js +74 -0
  6. package/dist/{config-aM9Ae7tH.js → config-DR6_5ZwI.js} +36 -22
  7. package/dist/continuations-DPyH_vr1.js +63 -0
  8. package/dist/{dist-DDW1iC5f.js → create-storage-29gMzf41.js} +70 -75
  9. package/dist/cursor-history-dqYDlsaD.js +148 -0
  10. package/dist/deno-kv-CSYGvRx4.js +120 -0
  11. package/dist/{driver-BT9WefKi.d.ts → driver-D9fI27jl.d.ts} +33 -3
  12. package/dist/error-diagnostics-D_cQeZTi.js +82 -0
  13. package/dist/errors-Dc2oiW-Y.js +38 -0
  14. package/dist/errors.d.ts +12 -7
  15. package/dist/errors.js +2 -20
  16. package/dist/fs-lite-CbLKxLut.js +90 -0
  17. package/dist/index.d.ts +5 -4
  18. package/dist/index.js +92 -64
  19. package/dist/object-B1NW521B.js +7 -0
  20. package/dist/operations-ByuDE12r.js +1442 -0
  21. package/dist/operations-pn8_eGob.js +432 -0
  22. package/dist/operations-tNUdj3G4.d.ts +212 -0
  23. package/dist/operations.d.ts +68 -0
  24. package/dist/operations.js +455 -0
  25. package/dist/results-p7nPCnaJ.js +6 -0
  26. package/dist/runtime/cloudflare-kv.d.ts +3 -4
  27. package/dist/runtime/cloudflare-kv.js +84 -8
  28. package/dist/runtime/upstash-driver.d.ts +4 -6
  29. package/dist/runtime/upstash-driver.js +34 -44
  30. package/dist/{types-CO0DRjJa.d.ts → types-CMDvN0Wr.d.ts} +20 -17
  31. package/dist/utils2-Dsb9P4_2.js +28 -0
  32. package/dist/virtual.d.ts +1 -1
  33. package/dist/vite.d.ts +14 -10
  34. package/dist/vite.js +603 -224
  35. package/package.json +56 -16
  36. package/dist/deno-kv-cJx3jU10.js +0 -69
  37. package/dist/fs-lite-BxzdiJSi.js +0 -79
package/dist/vite.js CHANGED
@@ -1,32 +1,17 @@
1
- import { i as trimmed, n as isPlainObject, r as readEnv, t as normalizeKVOptions } from "./config-aM9Ae7tH.js";
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";
2
5
  import { createRequire } from "node:module";
3
- import { existsSync, renameSync, rmSync } from "node:fs";
4
6
  import { cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
5
- import { tmpdir } from "node:os";
6
7
  import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
8
+ import { existsSync, readFileSync, renameSync, rmSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { Diagnostic } from "nostics";
7
11
  import { fileURLToPath } from "node:url";
8
12
  //#region \0rolldown/runtime.js
9
13
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
10
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
11
- //#endregion
12
- //#region src/vite-config.ts
13
- const KV_VITE_PLUGIN_NAME = "@vite-hub/kv/vite";
14
- const KV_VIRTUAL_CONFIG_ID = "#vitehub/kv/config";
15
- function resolveHosting(input) {
16
- const env = input.env || process.env;
17
- return trimmed(input.hosting) ?? readEnv(env, "VITEHUB_HOSTING");
18
- }
19
- function resolveKVViteConfig(kv, input = {}) {
20
- const env = input.env || process.env;
21
- const hosting = resolveHosting(input);
22
- return {
23
- hosting,
24
- kv: normalizeKVOptions(kv, {
25
- env,
26
- hosting
27
- }) ?? false
28
- };
29
- }
14
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
30
15
  //#endregion
31
16
  //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
32
17
  const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
@@ -126,14 +111,169 @@ const dirname$1 = function(p) {
126
111
  return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
127
112
  };
128
113
  //#endregion
114
+ //#region ../internal/src/definition-catalog.ts
115
+ async function writeFileIfChanged(file, contents) {
116
+ if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
117
+ await mkdir(resolve$1(file, ".."), { recursive: true });
118
+ await writeFile(file, contents, "utf8");
119
+ }
120
+ //#endregion
121
+ //#region ../internal/src/nitro-kit.ts
122
+ function cloneArray(value) {
123
+ return Array.isArray(value) ? [...value] : [];
124
+ }
125
+ function isRecord(value) {
126
+ return Object(value) === value && !Array.isArray(value);
127
+ }
128
+ function sameHandler(left, right) {
129
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
130
+ }
131
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
132
+ function createNitroServerKit(value = {}) {
133
+ const config = isRecord(value) ? { ...value } : {};
134
+ const handlers = cloneArray(config.handlers);
135
+ const plugins = cloneArray(config.plugins);
136
+ config.handlers = handlers;
137
+ config.plugins = plugins;
138
+ return {
139
+ config,
140
+ addHandler(handler, position = "end") {
141
+ if (handlers.some((candidate) => isRecord(candidate) && sameHandler(candidate, handler))) return;
142
+ if (position === "start") handlers.unshift({ ...handler });
143
+ else handlers.push({ ...handler });
144
+ },
145
+ addPlugin(plugin, position = "end") {
146
+ if (plugins.includes(plugin)) return;
147
+ if (position === "start") plugins.unshift(plugin);
148
+ else plugins.push(plugin);
149
+ }
150
+ };
151
+ }
152
+ //#endregion
153
+ //#region ../internal/src/contributions.ts
154
+ function isThenable(value) {
155
+ return typeof value.then === "function";
156
+ }
157
+ async function flattenPlugins(value, plugins, seen) {
158
+ if (Array.isArray(value)) {
159
+ for (const item of value) await flattenPlugins(item, plugins, seen);
160
+ return;
161
+ }
162
+ if (!isPlainObject(value) || seen.has(value)) return;
163
+ seen.add(value);
164
+ if (isThenable(value)) {
165
+ await flattenPlugins(await value, plugins, seen);
166
+ return;
167
+ }
168
+ plugins.push(value);
169
+ }
170
+ /**
171
+ * Flattens Vite plugin options as `collectContributions` reads them: nested arrays and promised options become one
172
+ * list of plugin objects, and falsy entries are dropped. A plugin that filters itself out of `context.plugins` must
173
+ * filter this list, because `vitehub()` nests its plugins in an array.
174
+ */
175
+ async function flattenPluginOptions(plugins) {
176
+ const flattened = [];
177
+ await flattenPlugins(plugins ?? [], flattened, /* @__PURE__ */ new Set());
178
+ return flattened;
179
+ }
180
+ //#endregion
181
+ //#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"
187
+ ]);
188
+ const discoveryInstalled = Symbol.for("vitehub.operations.dev.discovery");
189
+ /** Publish only the elected standalone transport; other Console policies retain their own discovery hook. */
190
+ function publishStandaloneOperationServer(server) {
191
+ const http = server.httpServer;
192
+ if (!http || Reflect.get(server, discoveryInstalled)) return;
193
+ const root = resolve(server.config.root);
194
+ const handlers = Reflect.get(Object(Reflect.get(server.config, "nitro")), "handlers");
195
+ if (!Array.isArray(handlers) || !handlers.some((handler) => handler?.handler === resolve(root, ".vitehub/nitro/operations/rpc.mjs"))) return;
196
+ Reflect.set(server, discoveryInstalled, true);
197
+ let ownedUrl;
198
+ const write = () => {
199
+ const address = http.address();
200
+ if (!address || typeof address === "string") return;
201
+ const host = address.address === "::" || address.address === "0.0.0.0" ? "localhost" : address.family === "IPv6" ? `[${address.address}]` : address.address;
202
+ const url = server.resolvedUrls?.local[0] ?? `${server.config.server.https ? "https" : "http"}://${host}:${address.port}${server.config.base}`;
203
+ try {
204
+ writeViteHubDevServerFile(root, {
205
+ root,
206
+ url
207
+ });
208
+ ownedUrl = url;
209
+ } catch {}
210
+ };
211
+ if (http.listening) write();
212
+ else http.once("listening", write);
213
+ http.once("close", () => {
214
+ try {
215
+ if (ownedUrl && readViteHubDevServerFile(root)?.url === ownedUrl) removeViteHubDevServerFile(root);
216
+ } catch {}
217
+ });
218
+ }
219
+ /** Standalone primitives share one local Nitro RPC. The root integration owns its own access policy. */
220
+ async function installStandaloneOperationRpc(config, command, module) {
221
+ if (command !== "serve") return;
222
+ const plugins = await flattenPluginOptions(config.plugins);
223
+ if (plugins.some((plugin) => Reflect.get(plugin, "name") === "vite-hub/dependencies" || Reflect.get(plugin, "name") === "vite-hub/console")) return;
224
+ const contributions = (await collectOperationContributions(plugins)).filter((source) => source.runtime !== false);
225
+ if (contributions.find((source) => owners.has(source.module))?.module !== module) return;
226
+ const root = resolve(config.root ?? process.cwd());
227
+ const handler = resolve(root, ".vitehub/nitro/operations/rpc.mjs");
228
+ await writeFileIfChanged(handler, [
229
+ `import { createStandaloneOperationHandler } from ${JSON.stringify(module)}`,
230
+ ...contributions.map((entry, index) => `import * as source${index} from ${JSON.stringify(entry.module)}`),
231
+ `export default createStandaloneOperationHandler([${contributions.map((entry, index) => `{ operations: source${index}[${JSON.stringify(entry.export)}], plugin: ${JSON.stringify(entry.plugin)} }`).join(", ")}], ${JSON.stringify(root)})`,
232
+ ""
233
+ ].join("\n"));
234
+ const kit = createNitroServerKit(Reflect.get(config, "nitro"));
235
+ kit.addHandler({
236
+ handler,
237
+ route: operationRpcPath
238
+ });
239
+ Reflect.set(config, "nitro", kit.config);
240
+ }
241
+ //#endregion
242
+ //#region src/vite-config.ts
243
+ const KV_VITE_PLUGIN_NAME = "@vite-hub/kv/vite";
244
+ const KV_VIRTUAL_CONFIG_ID = "#vitehub/kv/config";
245
+ function resolveKVViteConfig(kv, input = {}) {
246
+ const env = input.env || process.env;
247
+ const hosting = resolveHostPreset({
248
+ env,
249
+ hosting: input.hosting
250
+ });
251
+ return {
252
+ hosting,
253
+ kv: normalizeKVOptions(kv, {
254
+ env,
255
+ hosting
256
+ }) ?? false
257
+ };
258
+ }
259
+ //#endregion
129
260
  //#region ../internal/src/build/client-output.ts
130
261
  function hasStaticIndex(clientDir) {
131
262
  return existsSync(resolve$1(clientDir, "index.html"));
132
263
  }
133
- async function copyClientOutput(clientDir, targetDir) {
264
+ async function copyClientOutput(clientDir, targetDir, excludedDirs = []) {
134
265
  const resolvedClientDir = resolve$1(clientDir);
135
266
  const resolvedTargetDir = resolve$1(targetDir);
136
267
  if (resolvedClientDir === resolvedTargetDir) return;
268
+ const excluded = /* @__PURE__ */ new Set();
269
+ for (const dir of excludedDirs) {
270
+ const resolved = resolve$1(dir);
271
+ if (resolved !== resolvedClientDir && resolved.startsWith(`${resolvedClientDir}/`)) excluded.add(resolved);
272
+ }
273
+ const filter = (source) => {
274
+ const resolved = resolve$1(source);
275
+ return ![...excluded].some((dir) => resolved === dir || resolved.startsWith(`${dir}/`));
276
+ };
137
277
  await rm(resolvedTargetDir, {
138
278
  force: true,
139
279
  recursive: true
@@ -143,10 +283,16 @@ async function copyClientOutput(clientDir, targetDir) {
143
283
  if (targetRelativePath && !targetRelativePath.startsWith("../")) {
144
284
  const [targetRootEntry] = targetRelativePath.split("/", 1);
145
285
  await mkdir(resolvedTargetDir, { recursive: true });
146
- await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), { recursive: true })));
286
+ await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), {
287
+ recursive: true,
288
+ filter
289
+ })));
147
290
  return;
148
291
  }
149
- await cp(resolvedClientDir, resolvedTargetDir, { recursive: true });
292
+ await cp(resolvedClientDir, resolvedTargetDir, {
293
+ recursive: true,
294
+ filter
295
+ });
150
296
  }
151
297
  //#endregion
152
298
  //#region ../internal/src/build/provider-output-config.ts
@@ -192,7 +338,7 @@ function isProviderJsonRecord(value) {
192
338
  }
193
339
  }
194
340
  function assertProviderJsonRecord(value) {
195
- if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
341
+ if (!isProviderJsonRecord(value)) throw internalErrorDiagnostics.INTERNAL_B0043({ message: "[vitehub] Provider output config must be a JSON object." });
196
342
  }
197
343
  function isFileNotFoundError(error) {
198
344
  return error instanceof Error && "code" in error && error.code === "ENOENT";
@@ -225,7 +371,7 @@ function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
225
371
  const key = getKeyedArrayEntryValue(entry, ownership.key);
226
372
  return key === void 0 ? [] : [key];
227
373
  });
228
- const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
374
+ const ownedKeys = /* @__PURE__ */ new Set([...ownership.values ?? [], ...replacementKeys]);
229
375
  return current.filter((entry) => {
230
376
  const key = getKeyedArrayEntryValue(entry, ownership.key);
231
377
  return key === void 0 || !ownedKeys.has(key);
@@ -422,7 +568,7 @@ var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
422
568
  };
423
569
  }
424
570
  var ByteBuffer = class {
425
- constructor(buf = new Uint8Array(1024)) {
571
+ constructor(buf = /* @__PURE__ */ new Uint8Array(1024)) {
426
572
  this.buf = buf;
427
573
  this.len = 0;
428
574
  this.ptr = 0;
@@ -625,9 +771,7 @@ is not a problem with esbuild. You need to fix your environment instead.
625
771
  value += fromCharCode(code);
626
772
  break;
627
773
  }
628
- default:
629
- throwSyntaxError(bytes, --i);
630
- break;
774
+ default: throwSyntaxError(bytes, --i);
631
775
  }
632
776
  else if (c <= 127) value += fromCharCode(c);
633
777
  else if ((c & 224) === 192) value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
@@ -692,23 +836,21 @@ is not a problem with esbuild. You need to fix your environment instead.
692
836
  }
693
837
  if (c === 93) continue;
694
838
  break;
695
- case 2:
696
- if (property === null) {
697
- property = value;
698
- if (c === 58) {
699
- i++;
700
- continue;
701
- }
702
- } else {
703
- object[property] = value;
704
- property = null;
705
- if (c === 44) {
706
- i++;
707
- continue;
708
- }
709
- if (c === 125) continue;
839
+ case 2: if (property === null) {
840
+ property = value;
841
+ if (c === 58) {
842
+ i++;
843
+ continue;
710
844
  }
711
- break;
845
+ } else {
846
+ object[property] = value;
847
+ property = null;
848
+ if (c === 44) {
849
+ i++;
850
+ continue;
851
+ }
852
+ if (c === 125) continue;
853
+ }
712
854
  }
713
855
  break;
714
856
  }
@@ -953,19 +1095,21 @@ is not a problem with esbuild. You need to fix your environment instead.
953
1095
  if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
954
1096
  flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
955
1097
  }
956
- if (entryPoints) if (Array.isArray(entryPoints)) for (let i = 0, n = entryPoints.length; i < n; i++) {
957
- let entryPoint = entryPoints[i];
958
- if (typeof entryPoint === "object" && entryPoint !== null) {
959
- let entryPointKeys = /* @__PURE__ */ Object.create(null);
960
- let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
961
- let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
962
- checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
963
- if (input === void 0) throw new Error("Missing property \"in\" for entry point at index " + i);
964
- if (output === void 0) throw new Error("Missing property \"out\" for entry point at index " + i);
965
- entries.push([output, input]);
966
- } else entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
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)]);
967
1112
  }
968
- else for (let key in entryPoints) entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
969
1113
  if (stdin) {
970
1114
  let stdinKeys = /* @__PURE__ */ Object.create(null);
971
1115
  let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
@@ -1026,7 +1170,7 @@ is not a problem with esbuild. You need to fix your environment instead.
1026
1170
  let responseCallbacks = {};
1027
1171
  let nextRequestID = 0;
1028
1172
  let nextBuildKey = 0;
1029
- let stdout = new Uint8Array(16 * 1024);
1173
+ let stdout = /* @__PURE__ */ new Uint8Array(16384);
1030
1174
  let stdoutUsed = 0;
1031
1175
  let readFromStdout = (chunk) => {
1032
1176
  let limit = stdoutUsed + chunk.length;
@@ -1220,7 +1364,7 @@ is not a problem with esbuild. You need to fix your environment instead.
1220
1364
  });
1221
1365
  }
1222
1366
  };
1223
- if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
1367
+ if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1048576) {
1224
1368
  let next = start;
1225
1369
  start = () => fs3.writeFile(input, next);
1226
1370
  }
@@ -2109,11 +2253,13 @@ ${file}:${line}:${column}: ERROR: ${e.pluginName ? `[plugin: ${e.pluginName}] `
2109
2253
  return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
2110
2254
  }
2111
2255
  function generateBinPath() {
2112
- if (isValidBinaryPath(ESBUILD_BINARY_PATH)) if (!fs.existsSync(ESBUILD_BINARY_PATH)) console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
2113
- else return {
2114
- binPath: ESBUILD_BINARY_PATH,
2115
- isWASM: false
2116
- };
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
+ }
2117
2263
  const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
2118
2264
  let binPath;
2119
2265
  try {
@@ -2476,7 +2622,7 @@ More information: The file containing the code for esbuild's JavaScript API (${_
2476
2622
  };
2477
2623
  var runServiceSync = (callback) => {
2478
2624
  let [command, args] = esbuildCommandAndArgs();
2479
- let stdin = new Uint8Array();
2625
+ let stdin = /* @__PURE__ */ new Uint8Array();
2480
2626
  let { readFromStdout, afterClose, service } = createChannel({
2481
2627
  writeToStdin(bytes) {
2482
2628
  if (stdin.length !== 0) throw new Error("Must run at most one command");
@@ -2491,7 +2637,7 @@ More information: The file containing the code for esbuild's JavaScript API (${_
2491
2637
  cwd: defaultWD,
2492
2638
  windowsHide: true,
2493
2639
  input: stdin,
2494
- maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2640
+ maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16777216
2495
2641
  }));
2496
2642
  afterClose(null);
2497
2643
  };
@@ -2923,62 +3069,20 @@ function createViteAliasPlugin(aliases) {
2923
3069
  }
2924
3070
  };
2925
3071
  }
2926
- function stripMarkdownCode(template) {
2927
- let fence;
2928
- let inList = false;
2929
- let previousLineBlank = true;
2930
- return template.split("\n").map((line) => {
2931
- const content = line.replace(/^(?: {0,3}> ?)+/, "");
2932
- if (!fence) {
2933
- const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
2934
- const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
2935
- if (!opening) {
2936
- if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
2937
- else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
2938
- const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
2939
- previousLineBlank = content.trim() === "";
2940
- return indentedCode ? "" : line;
2941
- }
2942
- fence = {
2943
- marker: opening[1][0],
2944
- length: opening[1].length,
2945
- listIndented
2946
- };
2947
- previousLineBlank = false;
2948
- return "";
2949
- }
2950
- const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
2951
- if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
2952
- previousLineBlank = false;
2953
- return "";
2954
- }).join("\n");
2955
- }
2956
- function extractMarkdownTemplateImportSpecifiers(template) {
2957
- const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
2958
- const specifiers = /* @__PURE__ */ new Set();
2959
- for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
2960
- const token = match[1];
2961
- const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
2962
- specifiers.add(token.slice(0, token.length - trailing.length));
2963
- }
2964
- return [...specifiers];
2965
- }
2966
3072
  function parseMarkdownTemplateRequest(id) {
3073
+ if (id.includes("#")) return;
2967
3074
  const queryIndex = id.indexOf("?");
2968
- const path = id.split(/[?#]/, 1)[0];
3075
+ const path = id.split("?", 1)[0];
2969
3076
  if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
2970
- const query = id.slice(queryIndex + 1).split("#", 1)[0];
2971
- if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
3077
+ if (id.slice(queryIndex + 1) !== markdownTemplateModuleQuery) return;
2972
3078
  return { path };
2973
3079
  }
2974
- function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
3080
+ function renderMarkdownTemplateModule(template) {
2975
3081
  return [
2976
3082
  `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
2977
3083
  `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
2978
- `const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
2979
- `const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
2980
3084
  "export default function render(data = {}) {",
2981
- " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
3085
+ " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data })",
2982
3086
  "}",
2983
3087
  ""
2984
3088
  ].join("\n");
@@ -3071,45 +3175,22 @@ function createViteRawPlugin(rootDir, frameworkRuntime) {
3071
3175
  filter: /.*/,
3072
3176
  namespace: viteMarkdownTemplateNamespace
3073
3177
  }, async (args) => ({
3074
- contents: await (async () => {
3075
- const template = await readFile(args.path, "utf8");
3076
- const imports = {};
3077
- const visited = new Set([args.path]);
3078
- const visit = async (source, importer) => {
3079
- for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
3080
- const key = `${importer}\0${specifier}`;
3081
- if (imports[key]) continue;
3082
- const resolved = await build.resolve(specifier, {
3083
- importer,
3084
- kind: "import-statement",
3085
- pluginData: {
3086
- ...args.pluginData,
3087
- [skipMarkdownTemplateResolve]: true
3088
- },
3089
- resolveDir: dirname(importer)
3090
- });
3091
- if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
3092
- if (resolved.external || resolved.namespace !== "file") throw new Error(`[vitehub] Could not resolve Markdown template import ${JSON.stringify(specifier)} from ${JSON.stringify(importer)} to a file.`);
3093
- const imported = {
3094
- id: resolved.path,
3095
- template: await readFile(resolved.path, "utf8")
3096
- };
3097
- imports[key] = imported;
3098
- if (!visited.has(imported.id)) {
3099
- visited.add(imported.id);
3100
- await visit(imported.template, imported.id);
3101
- }
3102
- }
3103
- };
3104
- await visit(template, args.path);
3105
- return renderMarkdownTemplateModule(template, args.path, imports);
3106
- })(),
3178
+ contents: renderMarkdownTemplateModule(await readFile(args.path, "utf8")),
3107
3179
  loader: "js",
3108
3180
  resolveDir: dirname(args.path)
3109
3181
  }));
3110
3182
  }
3111
3183
  };
3112
3184
  }
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
+ }
3113
3194
  function createFileUrlPlugin() {
3114
3195
  return {
3115
3196
  name: "vitehub-file-url",
@@ -3141,13 +3222,16 @@ async function bundleEsmEntry(entryFile, outfile, options = {}) {
3141
3222
  ] : []].filter(Boolean).join("\n") } : void 0,
3142
3223
  bundle: true,
3143
3224
  conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
3225
+ define: options.define,
3144
3226
  entryPoints: [entryFile],
3145
3227
  external: options.external,
3146
3228
  format,
3229
+ keepNames: options.minifySyntax || options.minifyIdentifiers,
3147
3230
  logLevel: "silent",
3148
3231
  mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
3149
3232
  resolveExtensions: options.extensions,
3150
3233
  minifyIdentifiers: options.minifyIdentifiers,
3234
+ minifySyntax: options.minifySyntax,
3151
3235
  minifyWhitespace: options.minifyWhitespace,
3152
3236
  outfile,
3153
3237
  packages: options.packages,
@@ -3203,6 +3287,7 @@ function createNodeFunctionConfig(extra = {}) {
3203
3287
  //#endregion
3204
3288
  //#region ../internal/src/build/provider-output-catalog.ts
3205
3289
  var ProviderOutputCatalog = class {
3290
+ bundleDefines = {};
3206
3291
  #appliedCloudflareContributions = /* @__PURE__ */ new Map();
3207
3292
  #cloudflareContributions = /* @__PURE__ */ new Map();
3208
3293
  #runtimeContributions = /* @__PURE__ */ new Map();
@@ -3253,8 +3338,21 @@ var ProviderOutputCatalog = class {
3253
3338
  runtimeContributions(generation) {
3254
3339
  return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.entries() ?? (/* @__PURE__ */ new Map()).entries();
3255
3340
  }
3256
- resetRuntimeContributions() {
3257
- this.#runtimeContributions.clear();
3341
+ resetRuntimeContributions(generation, owner) {
3342
+ if (generation) {
3343
+ if (owner) this.#runtimeContributionsByGeneration.get(generation)?.delete(owner);
3344
+ else this.#runtimeContributionsByGeneration.delete(generation);
3345
+ return;
3346
+ }
3347
+ if (owner) this.#runtimeContributions.delete(owner);
3348
+ else this.#runtimeContributions.clear();
3349
+ }
3350
+ resetRuntimeContribution(product, generation) {
3351
+ if (!generation) {
3352
+ this.#runtimeContributions.delete(product);
3353
+ return;
3354
+ }
3355
+ this.#runtimeContributionsByGeneration.get(generation)?.delete(product);
3258
3356
  }
3259
3357
  createDeploymentGeneration() {
3260
3358
  const generation = { valid: true };
@@ -3417,35 +3515,12 @@ function useProviderOutputCatalog(config) {
3417
3515
  const owner = config;
3418
3516
  let catalog = owner[providerOutputCatalog] ?? providerOutputCatalogs.get(config);
3419
3517
  if (!catalog) catalog = createProviderOutputCatalog();
3518
+ catalog.bundleDefines = resolveViteHubBundleDefines(config);
3420
3519
  owner[providerOutputCatalog] = catalog;
3421
3520
  providerOutputCatalogs.set(config, catalog);
3422
3521
  return catalog;
3423
3522
  }
3424
3523
  //#endregion
3425
- //#region ../internal/src/build/vite.ts
3426
- function createNoExternalMerger(packageName) {
3427
- return (current) => {
3428
- if (current === true) return true;
3429
- if (!current) return [packageName];
3430
- const values = Array.isArray(current) ? current : [current];
3431
- return values.includes(packageName) ? values : [...values, packageName];
3432
- };
3433
- }
3434
- function isServerEnvironment(name, config) {
3435
- return name === "ssr" || config.consumer === "server";
3436
- }
3437
- function includesNitroVitePlugin(value) {
3438
- if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
3439
- if (!value || typeof value !== "object") return false;
3440
- return "name" in value && value.name === "nitro:main";
3441
- }
3442
- function hasNitroConfigContext(config) {
3443
- return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
3444
- }
3445
- function shouldSkipViteProviderBuild(command, mode) {
3446
- return command === "serve" || mode === "e2e";
3447
- }
3448
- //#endregion
3449
3524
  //#region ../internal/src/build/deployment-output.ts
3450
3525
  const providerDeploymentOutputRegistry = globalThis;
3451
3526
  const providerDeploymentOutputWrites = providerDeploymentOutputRegistry.__vitehubProviderDeploymentOutputWrites ??= /* @__PURE__ */ new Map();
@@ -3457,7 +3532,6 @@ const providerDeploymentOutputOwnerOrder = [
3457
3532
  "database",
3458
3533
  "blob",
3459
3534
  "queue",
3460
- "rate-limit",
3461
3535
  "schedule",
3462
3536
  "workflow",
3463
3537
  "vite-hub",
@@ -3484,13 +3558,13 @@ function createDefaultCloudflareStaticOutputDir(rootDir) {
3484
3558
  return resolve(rootDir, "dist", "client");
3485
3559
  }
3486
3560
  function resolveProviderOutputOwnershipFile(outputRoot, fileName) {
3487
- if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw new TypeError(`Invalid Provider Output ownership file name: ${JSON.stringify(fileName)}`);
3561
+ if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") throw internalErrorDiagnostics.INTERNAL_B0034({ message: `Invalid Provider Output ownership file name: ${JSON.stringify(fileName)}` });
3488
3562
  return resolve(outputRoot, fileName);
3489
3563
  }
3490
3564
  async function readProviderOutputOwnershipFile(outputRoot, fileName) {
3491
3565
  try {
3492
3566
  const parsed = JSON.parse(await readFile(resolveProviderOutputOwnershipFile(outputRoot, fileName), "utf8"));
3493
- if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string")) throw new TypeError(`Invalid Provider Output ownership file schema: ${JSON.stringify(fileName)}`);
3567
+ if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string")) throw internalErrorDiagnostics.INTERNAL_B0035({ message: `Invalid Provider Output ownership file schema: ${JSON.stringify(fileName)}` });
3494
3568
  return parsed;
3495
3569
  } catch (error) {
3496
3570
  if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
@@ -3515,7 +3589,7 @@ async function resolvePersistedProviderOutputOwnership(outputRoot, ownership, fi
3515
3589
  const arrays = { ...ownership?.arrays };
3516
3590
  await Promise.all(Object.entries(files).map(async ([field, fileName]) => {
3517
3591
  const current = arrays[field];
3518
- if (!current) throw new TypeError(`Provider Output ownership file for ${JSON.stringify(field)} requires array ownership.`);
3592
+ if (!current) throw internalErrorDiagnostics.INTERNAL_B0036({ message: `Provider Output ownership file for ${JSON.stringify(field)} requires array ownership.` });
3519
3593
  arrays[field] = {
3520
3594
  ...current,
3521
3595
  values: [...await readProviderOutputOwnershipFile(outputRoot, fileName), ...current.values ?? []]
@@ -3544,8 +3618,14 @@ function createDefaultVercelOutputRoot(rootDir) {
3544
3618
  function createDefaultNetlifyOutputRoot(rootDir) {
3545
3619
  return resolve(rootDir, ".netlify", "v1");
3546
3620
  }
3621
+ /** Restore a retained complete publication before generation or transaction snapshots. Call under the output lock. */
3622
+ function recoverNetlifyDeploymentOutput(rootDir) {
3623
+ const outputRoot = createDefaultNetlifyOutputRoot(rootDir);
3624
+ const previousOutputRoot = `${outputRoot}.previous`;
3625
+ if (!existsSync(outputRoot) && existsSync(previousOutputRoot)) renameSync(previousOutputRoot, outputRoot);
3626
+ }
3547
3627
  function assertNetlifyFunctionName(functionName) {
3548
- if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
3628
+ if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw internalErrorDiagnostics.INTERNAL_B0037({ message: `Invalid Netlify function name: ${functionName}` });
3549
3629
  }
3550
3630
  function resolveNetlifyFunctionFile(functionsRoot, functionName) {
3551
3631
  assertNetlifyFunctionName(functionName);
@@ -3553,7 +3633,8 @@ function resolveNetlifyFunctionFile(functionsRoot, functionName) {
3553
3633
  }
3554
3634
  async function appendNetlifyFunctionConfig(outfile, config) {
3555
3635
  if (!config) return;
3556
- await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
3636
+ const bundled = await readFile(outfile, "utf8");
3637
+ await writeFile(outfile, `${bundled.trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
3557
3638
  }
3558
3639
  async function writeCloudflareDeploymentOutput(options, signal) {
3559
3640
  signal?.throwIfAborted();
@@ -3563,7 +3644,7 @@ async function writeCloudflareDeploymentOutput(options, signal) {
3563
3644
  const copiesStaticOutput = Boolean(options.bundleEntry && staticIndex && resolve(clientDir) !== resolve(staticOutputDir));
3564
3645
  const files = Object.entries(options.files ?? {});
3565
3646
  const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
3566
- if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${workerOutfile}`);
3647
+ if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw internalErrorDiagnostics.INTERNAL_B0038({ message: `Cloudflare output file conflicts with bundle outfile: ${workerOutfile}` });
3567
3648
  const backupRoot = copiesStaticOutput ? await mkdtemp(resolve(options.rootDir, ".vitehub-cloudflare-output-")) : void 0;
3568
3649
  const previousOutputRoot = backupRoot ? resolve(backupRoot, "output") : `${outputRoot}.previous`;
3569
3650
  const previousStaticOutputDir = backupRoot ? resolve(backupRoot, "static") : `${staticOutputDir}.previous`;
@@ -3605,7 +3686,7 @@ async function writeCloudflareDeploymentOutput(options, signal) {
3605
3686
  wranglerConfigDefaults: options.wranglerConfigDefaults,
3606
3687
  wranglerConfigOwnership
3607
3688
  }),
3608
- options.bundleEntry && staticIndex ? copyClientOutput(clientDir, staticOutputDir) : Promise.resolve(),
3689
+ options.bundleEntry && staticIndex ? copyClientOutput(clientDir, staticOutputDir, [outputRoot]) : Promise.resolve(),
3609
3690
  ...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
3610
3691
  ];
3611
3692
  if (options.bundleEntry && workerOutfile) {
@@ -3618,6 +3699,13 @@ async function writeCloudflareDeploymentOutput(options, signal) {
3618
3699
  });
3619
3700
  await bundleEsmEntry(options.bundleEntry, stagedWorkerOutfile, {
3620
3701
  ...options.bundleOptions,
3702
+ define: {
3703
+ ...options.bundleDefines,
3704
+ ...options.bundleOptions?.define
3705
+ },
3706
+ minifyIdentifiers: options.bundleOptions?.minifyIdentifiers ?? true,
3707
+ minifySyntax: options.bundleOptions?.minifySyntax ?? true,
3708
+ minifyWhitespace: options.bundleOptions?.minifyWhitespace ?? true,
3621
3709
  rootDir: options.sourceRootDir ?? options.rootDir,
3622
3710
  signal
3623
3711
  });
@@ -3731,6 +3819,13 @@ async function writeVercelDeploymentOutput(options, signal) {
3731
3819
  }
3732
3820
  await bundleEsmEntry(options.bundleEntry, serverEntry, {
3733
3821
  ...options.bundleOptions,
3822
+ define: {
3823
+ ...options.bundleDefines,
3824
+ ...options.bundleOptions?.define
3825
+ },
3826
+ minifyIdentifiers: options.bundleOptions?.minifyIdentifiers ?? true,
3827
+ minifySyntax: options.bundleOptions?.minifySyntax ?? true,
3828
+ minifyWhitespace: options.bundleOptions?.minifyWhitespace ?? true,
3734
3829
  rootDir: options.sourceRootDir ?? options.rootDir,
3735
3830
  signal
3736
3831
  });
@@ -3838,7 +3933,14 @@ async function writeNetlifyDeploymentOutput(options, signal) {
3838
3933
  await mkdir(dirname(outfile), { recursive: true });
3839
3934
  await bundleEsmEntry(func.bundleEntry, outfile, {
3840
3935
  ...func.bundleOptions,
3841
- minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
3936
+ conditions: func.bundleOptions.conditions ?? ["netlify", "node"],
3937
+ define: {
3938
+ ...options.bundleDefines,
3939
+ ...func.bundleOptions.define
3940
+ },
3941
+ minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers ?? true,
3942
+ minifySyntax: func.bundleOptions.minifySyntax ?? true,
3943
+ minifyWhitespace: func.bundleOptions.minifyWhitespace ?? true,
3842
3944
  rootDir: options.sourceRootDir ?? options.rootDir,
3843
3945
  signal
3844
3946
  });
@@ -3935,19 +4037,22 @@ async function writeProviderDeploymentOutputsNow(options, signal, transaction) {
3935
4037
  ...options.cloudflare,
3936
4038
  clientOutDir: options.clientOutDir,
3937
4039
  rootDir: options.rootDir,
3938
- sourceRootDir: options.sourceRootDir
4040
+ sourceRootDir: options.sourceRootDir,
4041
+ bundleDefines: options.bundleDefines
3939
4042
  }, signal));
3940
4043
  if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
3941
4044
  ...options.netlify,
3942
4045
  clientOutDir: options.clientOutDir,
3943
4046
  rootDir: options.rootDir,
3944
- sourceRootDir: options.sourceRootDir
4047
+ sourceRootDir: options.sourceRootDir,
4048
+ bundleDefines: options.bundleDefines
3945
4049
  }, signal));
3946
4050
  if (options.vercel) writes.push(writeVercelDeploymentOutput({
3947
4051
  ...options.vercel,
3948
4052
  clientOutDir: options.clientOutDir,
3949
4053
  rootDir: options.rootDir,
3950
- sourceRootDir: options.sourceRootDir
4054
+ sourceRootDir: options.sourceRootDir,
4055
+ bundleDefines: options.bundleDefines
3951
4056
  }, signal));
3952
4057
  await settleWrites(writes);
3953
4058
  if (options.cloudflare && transaction) transaction.cloudflareWritten = true;
@@ -4058,6 +4163,7 @@ async function restoreProviderDeploymentOutputSnapshot(snapshot) {
4058
4163
  }
4059
4164
  }
4060
4165
  async function withProviderDeploymentOutputRootTransaction(rootDir, operation, options = {}) {
4166
+ recoverNetlifyDeploymentOutput(rootDir);
4061
4167
  const roots = [
4062
4168
  createDefaultCloudflareOutputRoot(rootDir),
4063
4169
  createDefaultNetlifyOutputRoot(rootDir),
@@ -4067,8 +4173,6 @@ async function withProviderDeploymentOutputRootTransaction(rootDir, operation, o
4067
4173
  resolve(rootDir, ".vitehub/queue/cloudflare-output.json"),
4068
4174
  resolve(rootDir, ".vitehub/queue/registry.mjs"),
4069
4175
  resolve(rootDir, ".vitehub/queue/vercel-output.json"),
4070
- resolve(rootDir, ".vitehub/rate-limit/cloudflare-output.json"),
4071
- resolve(rootDir, ".vitehub/rate-limit/manifest.json"),
4072
4176
  resolve(rootDir, ".vitehub/schedule"),
4073
4177
  resolve(rootDir, ".vitehub/workflow")
4074
4178
  ];
@@ -4245,15 +4349,15 @@ async function resetProviderDeploymentOutputs(catalog, failure, generation) {
4245
4349
  if (!generation) catalog.resetDeploymentContributions();
4246
4350
  if (active && (!generation || active.state.generations.has(generation))) {
4247
4351
  active.state.rollback = true;
4248
- active.controller.abort(/* @__PURE__ */ new Error("Provider Output finalization reset"));
4352
+ active.controller.abort(internalErrorDiagnostics.INTERNAL_B0039({ message: "Provider Output finalization reset" }));
4249
4353
  active.reset = {
4250
- failures: new Set([failure]),
4354
+ failures: /* @__PURE__ */ new Set([failure]),
4251
4355
  promise: active.promise.catch(() => void 0)
4252
4356
  };
4253
4357
  providerDeploymentOutputCompletedResets.set(catalog, active.reset);
4254
4358
  await active.reset.promise;
4255
4359
  } else if (failure !== void 0) providerDeploymentOutputCompletedResets.set(catalog, {
4256
- failures: new Set([failure]),
4360
+ failures: /* @__PURE__ */ new Set([failure]),
4257
4361
  promise: Promise.resolve()
4258
4362
  });
4259
4363
  }
@@ -4277,6 +4381,7 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
4277
4381
  if (catalog.hasDeploymentContributions()) await finalizeProviderDeploymentOutputs(catalog, options);
4278
4382
  return;
4279
4383
  }
4384
+ const bundleDefines = { ...catalog.bundleDefines };
4280
4385
  const controller = new AbortController();
4281
4386
  const state = {
4282
4387
  generations: /* @__PURE__ */ new Set(),
@@ -4338,7 +4443,13 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
4338
4443
  signal: controller.signal,
4339
4444
  write: async (writeOptions) => {
4340
4445
  throwIfProviderOutputAborted(controller.signal);
4341
- await writeProviderDeploymentOutputsNow(writeOptions, controller.signal, transaction);
4446
+ await writeProviderDeploymentOutputsNow({
4447
+ ...writeOptions,
4448
+ bundleDefines: {
4449
+ ...bundleDefines,
4450
+ ...writeOptions.bundleDefines
4451
+ }
4452
+ }, controller.signal, transaction);
4342
4453
  }
4343
4454
  });
4344
4455
  throwIfProviderOutputAborted(controller.signal);
@@ -4431,18 +4542,69 @@ function getViteMode(env = process.env) {
4431
4542
  return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
4432
4543
  }
4433
4544
  //#endregion
4545
+ //#region ../internal/src/provision-state.ts
4546
+ const PROVISION_STATE_FILE = ".vitehub/provision.json";
4547
+ function getProvisionStatePath(rootDir) {
4548
+ return resolve$1(rootDir, PROVISION_STATE_FILE);
4549
+ }
4550
+ function readProvisionStateSync(rootDir) {
4551
+ const path = getProvisionStatePath(rootDir);
4552
+ try {
4553
+ return parseProvisionState(readFileSync(path, "utf8"));
4554
+ } catch (cause) {
4555
+ if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return {};
4556
+ throw internalErrorDiagnostics.INTERNAL_R0014({
4557
+ path,
4558
+ cause
4559
+ });
4560
+ }
4561
+ }
4562
+ function readProvisionedId(state, provider, category, key) {
4563
+ if (!Object.hasOwn(state, provider)) return;
4564
+ const categories = state[provider];
4565
+ if (!categories || !Object.hasOwn(categories, category)) return;
4566
+ const ids = categories[category];
4567
+ if (!ids || !Object.hasOwn(ids, key)) return;
4568
+ return ids[key];
4569
+ }
4570
+ function parseProvisionState(raw) {
4571
+ const parsed = JSON.parse(raw);
4572
+ if (!isPlainObject(parsed)) return {};
4573
+ const state = {};
4574
+ for (const provider of ["cloudflare", "vercel"]) {
4575
+ const categories = parsed[provider];
4576
+ if (!isPlainObject(categories)) continue;
4577
+ const validCategories = {};
4578
+ for (const [category, ids] of Object.entries(categories)) {
4579
+ if (!isPlainObject(ids)) continue;
4580
+ const validIds = {};
4581
+ for (const [key, id] of Object.entries(ids)) if (typeof id === "string") setOwn(validIds, key, id);
4582
+ if (Object.keys(validIds).length) setOwn(validCategories, category, validIds);
4583
+ }
4584
+ if (Object.keys(validCategories).length) state[provider] = validCategories;
4585
+ }
4586
+ return state;
4587
+ }
4588
+ function setOwn(target, key, value) {
4589
+ Object.defineProperty(target, key, {
4590
+ configurable: true,
4591
+ enumerable: true,
4592
+ value,
4593
+ writable: true
4594
+ });
4595
+ }
4596
+ //#endregion
4434
4597
  //#region ../internal/src/arrays.ts
4435
4598
  function pushUnique(arr, item, key = (value) => value) {
4436
4599
  const id = key(item);
4437
4600
  if (arr.some((entry) => key(entry) === id)) return;
4438
4601
  arr.push(item);
4439
4602
  }
4440
- //#endregion
4441
- //#region src/integrations/cloudflare.ts
4442
- function configureCloudflareKV(target, config) {
4443
- for (const store of Object.values(config.stores || { default: config.store })) {
4603
+ function configureCloudflareKV(target, config, provisionState = {}) {
4604
+ for (const [storeName, store] of Object.entries(config.stores || { default: config.store })) {
4444
4605
  if (store.driver !== "cloudflare-kv-binding") continue;
4445
- const { binding, namespaceId } = store;
4606
+ const { binding } = store;
4607
+ const namespaceId = store.namespaceId ?? readProvisionedId(provisionState, "cloudflare", "kv", storeName);
4446
4608
  target.cloudflare ||= {};
4447
4609
  target.cloudflare.wrangler ||= {};
4448
4610
  target.cloudflare.wrangler.kv_namespaces ||= [];
@@ -4453,13 +4615,200 @@ function configureCloudflareKV(target, config) {
4453
4615
  }
4454
4616
  }
4455
4617
  //#endregion
4618
+ //#region ../internal/src/provision.ts
4619
+ function resolveCloudflareProvisionConfig(env) {
4620
+ const accountId = trimmedEnv(env.CLOUDFLARE_ACCOUNT_ID);
4621
+ const token = trimmedEnv(env.CLOUDFLARE_API_TOKEN);
4622
+ if (!accountId || !token) return;
4623
+ return {
4624
+ accountId,
4625
+ token
4626
+ };
4627
+ }
4628
+ function ownParser(options) {
4629
+ if (!Object.hasOwn(options, "parse")) return;
4630
+ return options.parse;
4631
+ }
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) {
4648
+ return async function request(path, options = {}) {
4649
+ const url = new URL(`${baseURL}${path}`);
4650
+ const query = Object.hasOwn(options, "query") ? options.query : void 0;
4651
+ for (const [key, value] of Object.entries({
4652
+ ...baseQuery,
4653
+ ...query
4654
+ })) url.searchParams.set(key, value);
4655
+ const method = Object.hasOwn(options, "method") ? options.method : void 0;
4656
+ const body = Object.hasOwn(options, "body") ? options.body : void 0;
4657
+ const requestHeaders = Object.hasOwn(options, "headers") ? options.headers : void 0;
4658
+ const init = {
4659
+ method: method ?? "GET",
4660
+ headers: {
4661
+ ...requestHeaders,
4662
+ ...headers
4663
+ }
4664
+ };
4665
+ if (body !== void 0) {
4666
+ init.headers = {
4667
+ ...init.headers,
4668
+ "content-type": "application/json"
4669
+ };
4670
+ init.body = JSON.stringify(body);
4671
+ }
4672
+ const response = await fetchImpl(url, init);
4673
+ 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);
4677
+ }
4678
+ const value = await response.json();
4679
+ const parse = ownParser(options);
4680
+ return parse ? parse(value) : value;
4681
+ };
4682
+ }
4683
+ function createCloudflareProvisionClient(config, fetchImpl = globalThis.fetch) {
4684
+ const client = createJsonClient(`https://api.cloudflare.com/client/v4/accounts/${config.accountId}`, { authorization: `Bearer ${config.token}` }, fetchImpl);
4685
+ return async (path, options = {}) => {
4686
+ const parse = ownParser(options) ?? ((value) => value);
4687
+ return await client(path, {
4688
+ ...options,
4689
+ parse(value) {
4690
+ if (!value || Object(value) !== value) throw internalErrorDiagnostics.INTERNAL_R0010({ message: "Cloudflare provisioning returned an invalid response." });
4691
+ const envelope = value;
4692
+ return {
4693
+ ...envelope,
4694
+ result: envelope.result === void 0 ? void 0 : parse(envelope.result)
4695
+ };
4696
+ }
4697
+ });
4698
+ };
4699
+ }
4700
+ function trimmedEnv(value) {
4701
+ const trimmed = value?.trim();
4702
+ return trimmed ? trimmed : void 0;
4703
+ }
4704
+ //#endregion
4705
+ //#region src/provision.ts
4706
+ const CLOUDFLARE_KV_NAMESPACE_LIST_PER_PAGE = 100;
4707
+ const CLOUDFLARE_KV_DUPLICATE_TITLE_CODE = 10014;
4708
+ function parseNamespaces(value) {
4709
+ if (!Array.isArray(value)) throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: "Cloudflare returned an invalid KV namespace list." });
4710
+ for (const namespace of value) {
4711
+ if (!namespace || Object(namespace) !== namespace) throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: "Cloudflare returned an invalid KV namespace list." });
4712
+ const id = Reflect.get(namespace, "id");
4713
+ const title = Reflect.get(namespace, "title");
4714
+ if (!Object.hasOwn(namespace, "id") || !Object.hasOwn(namespace, "title") || typeof id !== "string" || typeof title !== "string") throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: "Cloudflare returned an invalid KV namespace list." });
4715
+ }
4716
+ return value;
4717
+ }
4718
+ function parseCreatedNamespace(value) {
4719
+ if (!value || Object(value) !== value) throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: "Cloudflare returned an invalid KV namespace." });
4720
+ const id = Reflect.get(value, "id");
4721
+ if (!Object.hasOwn(value, "id") || typeof id !== "string") throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: "Cloudflare returned an invalid KV namespace." });
4722
+ return { id };
4723
+ }
4724
+ async function listNamespaceIds(request) {
4725
+ 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
+ }
4747
+ }
4748
+ async function createNamespace(request, title) {
4749
+ try {
4750
+ return (await request("/storage/kv/namespaces", {
4751
+ method: "POST",
4752
+ body: { title },
4753
+ parse: parseCreatedNamespace
4754
+ })).result?.id;
4755
+ } catch (error) {
4756
+ if (!(error instanceof ProvisionRequestError && (error.status === 400 || error.status === 409 || error.codes.includes(CLOUDFLARE_KV_DUPLICATE_TITLE_CODE)))) throw error;
4757
+ const id = (await listNamespaceIds(request)).get(title);
4758
+ if (!id) throw error;
4759
+ return id;
4760
+ }
4761
+ }
4762
+ function planStoresByNamespace(options, env) {
4763
+ const kv = resolveKVViteConfig(options, {
4764
+ env,
4765
+ hosting: "cloudflare"
4766
+ }).kv;
4767
+ const storesByNamespace = /* @__PURE__ */ new Map();
4768
+ if (!kv) return storesByNamespace;
4769
+ for (const [storeName, store] of Object.entries(kv.stores || { default: kv.store })) {
4770
+ if (store.driver !== "cloudflare-kv-binding" || store.namespaceId || !store.namespaceName) continue;
4771
+ const stores = storesByNamespace.get(store.namespaceName);
4772
+ if (stores) stores.push(storeName);
4773
+ else storesByNamespace.set(store.namespaceName, [storeName]);
4774
+ }
4775
+ return storesByNamespace;
4776
+ }
4777
+ function createKVCloudflareProvisionStep(resolveOptions) {
4778
+ return {
4779
+ id: "kv:cloudflare-kv",
4780
+ provider: "cloudflare",
4781
+ async plan(context) {
4782
+ const storesByNamespace = planStoresByNamespace(resolveOptions(), context.env);
4783
+ if (!storesByNamespace.size) return [];
4784
+ const config = resolveCloudflareProvisionConfig(context.env);
4785
+ if (!config) {
4786
+ context.logger.warn("kv: skipping Cloudflare KV, missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN.");
4787
+ return [];
4788
+ }
4789
+ const request = createCloudflareProvisionClient(config, context.fetch);
4790
+ const existing = await listNamespaceIds(request);
4791
+ return [...storesByNamespace].map(([namespaceName, stores]) => ({
4792
+ kind: "cloudflare-kv-namespace",
4793
+ name: namespaceName,
4794
+ exists: existing.has(namespaceName),
4795
+ apply: async () => {
4796
+ const id = existing.get(namespaceName) ?? await createNamespace(request, namespaceName);
4797
+ if (!id) throw kvErrorDiagnostics.KV_PROVISION_FAILED({ problem: `Cloudflare did not return an id for namespace ${JSON.stringify(namespaceName)}.` });
4798
+ return { ids: { cloudflare: { ["kv"]: Object.fromEntries(stores.map((store) => [store, id])) } } };
4799
+ }
4800
+ }));
4801
+ }
4802
+ };
4803
+ }
4804
+ //#endregion
4456
4805
  //#region src/vite.ts
4457
4806
  const RESOLVED_KV_VIRTUAL_CONFIG_ID = `\0${KV_VIRTUAL_CONFIG_ID}`;
4458
4807
  const RESOLVED_KV_RUNTIME_ID = `\0#vitehub/kv/runtime`;
4459
4808
  const KV_ERRORS_IMPORT_ID = new URL(import.meta.url.endsWith(".ts") ? "./errors.ts" : "./errors.js", import.meta.url).href;
4460
4809
  const UPSTASH_DRIVER_IMPORT_ID = "@vite-hub/kv/runtime/upstash-driver";
4461
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;
4462
- const mergeNoExternal = createNoExternalMerger("@vite-hub/kv");
4811
+ const mergeNoExternal = createNoExternalAddition("@vite-hub/kv");
4463
4812
  const KV_CLOUDFLARE_BINDINGS_FILE = ".vitehub-kv-bindings.json";
4464
4813
  function hubKvOptionalPeerResolver() {
4465
4814
  return {
@@ -4494,24 +4843,25 @@ function isKVOptionalUpstashImport(id, importer) {
4494
4843
  const normalizedImporter = importer.replace(/\\/g, "/").split("?", 1)[0];
4495
4844
  return normalizedImporter.endsWith("/packages/kv/src/runtime/driver.ts") || normalizedImporter.endsWith("/packages/kv/dist/index.js") || normalizedImporter.includes("/@vite-hub/kv/dist/index.js");
4496
4845
  }
4497
- function createCloudflareKVWranglerConfig(kv) {
4846
+ function createCloudflareKVWranglerConfig(kv, provisionState) {
4498
4847
  if (!kv) return;
4499
4848
  const target = {};
4500
- configureCloudflareKV(target, kv);
4849
+ configureCloudflareKV(target, kv, provisionState);
4501
4850
  return target.cloudflare?.wrangler?.kv_namespaces?.length ? target.cloudflare.wrangler : void 0;
4502
4851
  }
4503
4852
  function serializeCloudflareRuntime(config) {
4504
4853
  return [
4505
4854
  `import { createCloudflareKVStorage } from ${JSON.stringify(CLOUDFLARE_KV_RUNTIME_IMPORT_ID)};`,
4506
- `import { kvResult } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
4855
+ `import { kvInvalidLimitError, kvResult, kvStoreNotFoundError, kvUnsupportedOperationError } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
4507
4856
  "",
4508
4857
  `const kvConfig = ${JSON.stringify(config, null, 2)}`,
4509
4858
  "const storages = new Map();",
4859
+ "export async function disposeKVStores() { storages.clear(); }",
4510
4860
  "",
4511
4861
  "function resolveStoreConfig(name) {",
4512
4862
  " const stores = kvConfig.stores || { default: kvConfig.store };",
4863
+ " if (!Object.prototype.hasOwnProperty.call(stores, name)) throw kvStoreNotFoundError(name);",
4513
4864
  " const store = stores[name];",
4514
- " if (!store) throw new Error(`[vitehub] Unknown KV store \"${name}\".`);",
4515
4865
  " return store;",
4516
4866
  "}",
4517
4867
  "",
@@ -4524,22 +4874,23 @@ function serializeCloudflareRuntime(config) {
4524
4874
  " return storage;",
4525
4875
  "}",
4526
4876
  "",
4527
- "async function resolveStorageResult(name, operation) {",
4877
+ "function unsupported(operation, name) {",
4528
4878
  " resolveStoreConfig(name);",
4529
- " return kvResult(operation, name, async () => resolveStorage(name));",
4879
+ " return [kvUnsupportedOperationError(operation, name), undefined];",
4530
4880
  "}",
4531
4881
  "",
4882
+ "// kvResult throws config errors, for example an unknown store, and returns the other errors.",
4532
4883
  "function createKVStorage(name = \"default\") {",
4533
4884
  " return {",
4534
- " async clear(base, options) { const [error, storage] = await resolveStorageResult(name, \"clear\"); return error ? [error, undefined] : kvResult(\"clear\", name, async () => { await storage.clear(base, options); }); },",
4535
- " async del(key, options) { const [error, storage] = await resolveStorageResult(name, \"del\"); return error ? [error, undefined] : kvResult(\"del\", name, async () => { await storage.removeItem(key, options); }); },",
4536
- " async get(key, options) { const [error, storage] = await resolveStorageResult(name, \"get\"); return error ? [error, undefined] : kvResult(\"get\", name, () => storage.getItem(key, options)); },",
4537
- " async getAndDelete() { resolveStoreConfig(name); throw new Error(\"[vitehub] Cloudflare KV does not support atomic operations. Use Upstash.\"); },",
4538
- " async has(key, options) { const [error, storage] = await resolveStorageResult(name, \"has\"); return error ? [error, undefined] : kvResult(\"has\", name, () => storage.hasItem(key, options)); },",
4539
- " async increment() { resolveStoreConfig(name); throw new Error(\"[vitehub] Cloudflare KV does not support atomic operations. Use Upstash.\"); },",
4540
- " async keys(base, options) { const [error, storage] = await resolveStorageResult(name, \"keys\"); return error ? [error, undefined] : kvResult(\"keys\", name, () => storage.getKeys(base, options)); },",
4541
- " async list(options) { if (!Number.isInteger(options.limit) || options.limit <= 0) throw new TypeError(\"`limit` must be a positive integer.\"); const [error, storage] = await resolveStorageResult(name, \"list\"); return error ? [error, undefined] : kvResult(\"list\", name, () => storage.listKeys(options)); },",
4542
- " async set(key, value, options) { const [error, storage] = await resolveStorageResult(name, \"set\"); return error ? [error, undefined] : kvResult(\"set\", name, async () => { await storage.setItem(key, value, options); }); },",
4885
+ " 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)); },",
4888
+ " async getAndDelete() { return unsupported(\"getAndDelete\", name); },",
4889
+ " async has(key, options) { return kvResult(\"has\", name, () => resolveStorage(name).hasItem(key, options)); },",
4890
+ " async increment() { return unsupported(\"increment\", name); },",
4891
+ " async keys(base, options) { return kvResult(\"keys\", name, () => resolveStorage(name).getKeys(base, options)); },",
4892
+ " 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); }); },",
4543
4894
  " store(storeName) { return createKVStorage(storeName); },",
4544
4895
  " };",
4545
4896
  "}",
@@ -4578,15 +4929,15 @@ function getNitroCloudflareKVNamespaces(target) {
4578
4929
  function getResolvedNitroConfig(config) {
4579
4930
  return Reflect.get(config, "nitro");
4580
4931
  }
4581
- function reconcileNitroCloudflareKV(target, kv, ownedNamespaces) {
4932
+ function reconcileNitroCloudflareKV(target, kv, ownedNamespaces, provisionState) {
4582
4933
  const namespaces = target.cloudflare?.wrangler?.kv_namespaces;
4583
4934
  if (namespaces?.length && ownedNamespaces.size) for (const owned of ownedNamespaces) {
4584
4935
  const ownedIndex = namespaces.findIndex((namespace) => namespace.binding === owned.binding && namespace.id === owned.id);
4585
4936
  if (ownedIndex !== -1) namespaces.splice(ownedIndex, 1);
4586
4937
  }
4587
- if (kv) configureCloudflareKV(target, kv);
4938
+ if (kv) configureCloudflareKV(target, kv, provisionState);
4588
4939
  }
4589
- function configureNitroCloudflareKV(config, options, ownedNamespaces) {
4940
+ function configureNitroCloudflareKV(config, options, ownedNamespaces, provisionState) {
4590
4941
  const { nitro } = config;
4591
4942
  if (!isPlainObject(nitro)) return false;
4592
4943
  const target = nitro;
@@ -4596,7 +4947,7 @@ function configureNitroCloudflareKV(config, options, ownedNamespaces) {
4596
4947
  const kv = resolveKVViteConfig(config.kv ?? options).kv;
4597
4948
  if (kv) {
4598
4949
  const existingNamespaces = new Set(target.cloudflare?.wrangler?.kv_namespaces);
4599
- configureCloudflareKV(target, kv);
4950
+ configureCloudflareKV(target, kv, provisionState);
4600
4951
  for (const namespace of target.cloudflare?.wrangler?.kv_namespaces ?? []) if (!existingNamespaces.has(namespace)) ownedNamespaces.add(namespace);
4601
4952
  }
4602
4953
  return true;
@@ -4608,6 +4959,8 @@ function hubKv(options) {
4608
4959
  let resolved;
4609
4960
  let providerOutput;
4610
4961
  let runtimeConfig;
4962
+ let configuredOptions = options;
4963
+ let projectRoot = process.cwd();
4611
4964
  const getConfig = () => runtimeConfig ??= resolveKVViteConfig(options);
4612
4965
  const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
4613
4966
  return {
@@ -4618,25 +4971,51 @@ function hubKv(options) {
4618
4971
  name: "@vite-hub/kv/cloudflare-bindings",
4619
4972
  setup(nitro) {
4620
4973
  nitroOptions = nitro.options;
4621
- if (runtimeConfig) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces);
4974
+ if (runtimeConfig) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, readProvisionStateSync(projectRoot));
4975
+ }
4976
+ },
4977
+ vitehub: {
4978
+ operations: [{
4979
+ export: "kvOperations",
4980
+ load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).kvOperations,
4981
+ module: "@vite-hub/kv/operations"
4982
+ }],
4983
+ cli: async () => {
4984
+ const { createKVCliContributor } = await import(
4985
+ /* @vite-ignore */
4986
+ "./cli.js"
4987
+ );
4988
+ return {
4989
+ ...createKVCliContributor(),
4990
+ provision: [createKVCloudflareProvisionStep(() => configuredOptions)]
4991
+ };
4622
4992
  }
4623
4993
  },
4624
4994
  config: {
4625
4995
  order: "pre",
4626
- handler(config) {
4627
- nitroOwned = configureNitroCloudflareKV(config, options, ownedNitroNamespaces);
4996
+ handler(config, env) {
4997
+ configuredOptions = config.kv ?? options;
4998
+ 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");
4628
5001
  }
4629
5002
  },
4630
5003
  configResolved: {
4631
5004
  order: "pre",
4632
5005
  handler(config) {
4633
5006
  resolved = config;
5007
+ configuredOptions = config.kv ?? options;
5008
+ projectRoot = resolveViteHubProjectRoot(config.root || process.cwd());
4634
5009
  providerOutput = useProviderOutputCatalog(config);
4635
5010
  runtimeConfig = resolveKVViteConfig(config.kv ?? options);
4636
- if (nitroOptions) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces);
4637
- if (hasNitroConfigContext(config) || isPlainObject(getResolvedNitroConfig(config))) nitroOwned = configureNitroCloudflareKV(config, options, ownedNitroNamespaces);
5011
+ const provisionState = readProvisionStateSync(projectRoot);
5012
+ if (nitroOptions) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, provisionState);
5013
+ if (hasNitroConfigContext(config) || isPlainObject(getResolvedNitroConfig(config))) nitroOwned = configureNitroCloudflareKV(config, options, ownedNitroNamespaces, provisionState);
4638
5014
  }
4639
5015
  },
5016
+ configureServer(server) {
5017
+ publishStandaloneOperationServer(server);
5018
+ },
4640
5019
  configEnvironment: {
4641
5020
  order: "pre",
4642
5021
  handler(name, config) {
@@ -4681,7 +5060,7 @@ function hubKv(options) {
4681
5060
  if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
4682
5061
  const rootDir = resolved.root;
4683
5062
  const clientOutDir = resolved.build.outDir;
4684
- const wranglerConfig = nitroOwned ? void 0 : createCloudflareKVWranglerConfig(getConfig().kv);
5063
+ const wranglerConfig = nitroOwned ? void 0 : createCloudflareKVWranglerConfig(getConfig().kv, readProvisionStateSync(projectRoot));
4685
5064
  const nextBindings = wranglerConfig?.kv_namespaces?.map((binding) => binding.binding) ?? [];
4686
5065
  const wranglerConfigOwnership = { arrays: { kv_namespaces: {
4687
5066
  key: "binding",