@vite-hub/rate-limit 0.0.3 → 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.
package/dist/vite.js CHANGED
@@ -1,16 +1,189 @@
1
- import { i as rateLimitPolicyKeys, n as declaredRateLimitPolicy, r as normalizeRateLimitPolicy, t as createRateLimiter } from "./limiter-CHaHluMr.js";
2
- import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-BYZQ2tim.js";
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.js";
2
+ import { i as rateLimitPolicyKeys, n as declaredRateLimitPolicy, r as normalizeRateLimitPolicy, t as createRateLimiter } from "./limiter-DBrMI4vi.js";
3
3
  import { memoryRateLimitDriver } from "./drivers/memory.js";
4
+ import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-DUDRACVB.js";
5
+ import { n as relativeDefinitionFile, r as resolve$1 } from "./inspect-D-FzyM_x.js";
6
+ import { S as isPlainObject, _ as shouldSkipViteProviderBuild, b as removeViteHubDevServerFile, c as operationRpcPath, g as resolveViteHubProjectRoot, h as isServerEnvironment, m as createNoExternalAddition, p as internalErrorDiagnostics, r as collectOperationContributions, v as readViteHubDevServerFile, x as writeViteHubDevServerFile } from "./operations-B09NnEjT.js";
4
7
  import { createRequire } from "node:module";
5
- import { cp, mkdir, readFile, readdir, rm, rmdir, stat, writeFile } from "node:fs/promises";
6
- import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
7
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
8
- import { fileURLToPath } from "node:url";
9
- import { isDeepStrictEqual } from "node:util";
10
- import { Visitor, normalizePath, parseSync } from "vite";
8
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
9
+ import { basename, relative, resolve } from "node:path";
10
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
11
+ import { Visitor, parseSync } from "vite";
11
12
  //#region \0rolldown/runtime.js
12
13
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
13
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
14
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
15
+ //#endregion
16
+ //#region ../internal/src/definition-catalog.ts
17
+ const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
18
+ const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
19
+ const ignoredDirs = /* @__PURE__ */ new Set([
20
+ "node_modules",
21
+ "dist",
22
+ ".output",
23
+ ".nuxt",
24
+ ".vercel",
25
+ ".git",
26
+ ".vitehub"
27
+ ]);
28
+ function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
29
+ return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
30
+ }
31
+ function readDirEntries(root) {
32
+ try {
33
+ return readdirSync(root, { withFileTypes: true });
34
+ } catch (error) {
35
+ if (error.code === "ENOENT") return [];
36
+ throw error;
37
+ }
38
+ }
39
+ function isGitRepositoryDirectory(directory) {
40
+ return existsSync(resolve$1(directory, ".git"));
41
+ }
42
+ function listMatchingFiles(root, predicate, options = {}) {
43
+ const files = [];
44
+ for (const entry of readDirEntries(root)) {
45
+ const absolute = resolve$1(root, entry.name);
46
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
47
+ if (isGitRepositoryDirectory(absolute)) continue;
48
+ if (entry.name.startsWith(".")) continue;
49
+ if (ignoredDirs.has(entry.name)) continue;
50
+ files.push(...listMatchingFiles(absolute, predicate, options));
51
+ continue;
52
+ }
53
+ if (entry.name.startsWith(".") && !options.includeHidden) continue;
54
+ if (entry.isFile() && predicate(entry.name)) files.push(absolute);
55
+ }
56
+ return files.sort();
57
+ }
58
+ function listSourceFiles(root, options = {}) {
59
+ return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
60
+ }
61
+ async function writeFileIfChanged(file, contents) {
62
+ if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
63
+ await mkdir(resolve$1(file, ".."), { recursive: true });
64
+ await writeFile(file, contents, "utf8");
65
+ }
66
+ //#endregion
67
+ //#region ../internal/src/nitro-kit.ts
68
+ function cloneArray(value) {
69
+ return Array.isArray(value) ? [...value] : [];
70
+ }
71
+ function isRecord(value) {
72
+ return Object(value) === value && !Array.isArray(value);
73
+ }
74
+ function sameHandler(left, right) {
75
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
76
+ }
77
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
78
+ function createNitroServerKit(value = {}) {
79
+ const config = isRecord(value) ? { ...value } : {};
80
+ const handlers = cloneArray(config.handlers);
81
+ const plugins = cloneArray(config.plugins);
82
+ config.handlers = handlers;
83
+ config.plugins = plugins;
84
+ return {
85
+ config,
86
+ addHandler(handler, position = "end") {
87
+ if (handlers.some((candidate) => isRecord(candidate) && sameHandler(candidate, handler))) return;
88
+ if (position === "start") handlers.unshift({ ...handler });
89
+ else handlers.push({ ...handler });
90
+ },
91
+ addPlugin(plugin, position = "end") {
92
+ if (plugins.includes(plugin)) return;
93
+ if (position === "start") plugins.unshift(plugin);
94
+ else plugins.push(plugin);
95
+ }
96
+ };
97
+ }
98
+ //#endregion
99
+ //#region ../internal/src/contributions.ts
100
+ function isThenable(value) {
101
+ return typeof value.then === "function";
102
+ }
103
+ async function flattenPlugins(value, plugins, seen) {
104
+ if (Array.isArray(value)) {
105
+ for (const item of value) await flattenPlugins(item, plugins, seen);
106
+ return;
107
+ }
108
+ if (!isPlainObject(value) || seen.has(value)) return;
109
+ seen.add(value);
110
+ if (isThenable(value)) {
111
+ await flattenPlugins(await value, plugins, seen);
112
+ return;
113
+ }
114
+ plugins.push(value);
115
+ }
116
+ /**
117
+ * Flattens Vite plugin options as `collectContributions` reads them: nested arrays and promised options become one
118
+ * list of plugin objects, and falsy entries are dropped. A plugin that filters itself out of `context.plugins` must
119
+ * filter this list, because `vitehub()` nests its plugins in an array.
120
+ */
121
+ async function flattenPluginOptions(plugins) {
122
+ const flattened = [];
123
+ await flattenPlugins(plugins ?? [], flattened, /* @__PURE__ */ new Set());
124
+ return flattened;
125
+ }
126
+ //#endregion
127
+ //#region ../internal/src/operations-vite.ts
128
+ const owners = /* @__PURE__ */ new Set([
129
+ "@vite-hub/kv/operations",
130
+ "@vite-hub/blob/operations",
131
+ "@vite-hub/email/operations",
132
+ "@vite-hub/rate-limit/operations"
133
+ ]);
134
+ const discoveryInstalled = Symbol.for("vitehub.operations.dev.discovery");
135
+ /** Publish only the elected standalone transport; other Console policies retain their own discovery hook. */
136
+ function publishStandaloneOperationServer(server) {
137
+ const http = server.httpServer;
138
+ if (!http || Reflect.get(server, discoveryInstalled)) return;
139
+ const root = resolve(server.config.root);
140
+ const handlers = Reflect.get(Object(Reflect.get(server.config, "nitro")), "handlers");
141
+ if (!Array.isArray(handlers) || !handlers.some((handler) => handler?.handler === resolve(root, ".vitehub/nitro/operations/rpc.mjs"))) return;
142
+ Reflect.set(server, discoveryInstalled, true);
143
+ let ownedUrl;
144
+ const write = () => {
145
+ const address = http.address();
146
+ if (!address || typeof address === "string") return;
147
+ const host = address.address === "::" || address.address === "0.0.0.0" ? "localhost" : address.family === "IPv6" ? `[${address.address}]` : address.address;
148
+ const url = server.resolvedUrls?.local[0] ?? `${server.config.server.https ? "https" : "http"}://${host}:${address.port}${server.config.base}`;
149
+ try {
150
+ writeViteHubDevServerFile(root, {
151
+ root,
152
+ url
153
+ });
154
+ ownedUrl = url;
155
+ } catch {}
156
+ };
157
+ if (http.listening) write();
158
+ else http.once("listening", write);
159
+ http.once("close", () => {
160
+ try {
161
+ if (ownedUrl && readViteHubDevServerFile(root)?.url === ownedUrl) removeViteHubDevServerFile(root);
162
+ } catch {}
163
+ });
164
+ }
165
+ /** Standalone primitives share one local Nitro RPC. The root integration owns its own access policy. */
166
+ async function installStandaloneOperationRpc(config, command, module) {
167
+ if (command !== "serve") return;
168
+ const plugins = await flattenPluginOptions(config.plugins);
169
+ if (plugins.some((plugin) => Reflect.get(plugin, "name") === "vite-hub/dependencies" || Reflect.get(plugin, "name") === "vite-hub/console")) return;
170
+ const contributions = (await collectOperationContributions(plugins)).filter((source) => source.runtime !== false);
171
+ if (contributions.find((source) => owners.has(source.module))?.module !== module) return;
172
+ const root = resolve(config.root ?? process.cwd());
173
+ const handler = resolve(root, ".vitehub/nitro/operations/rpc.mjs");
174
+ await writeFileIfChanged(handler, [
175
+ `import { createStandaloneOperationHandler } from ${JSON.stringify(module)}`,
176
+ ...contributions.map((entry, index) => `import * as source${index} from ${JSON.stringify(entry.module)}`),
177
+ `export default createStandaloneOperationHandler([${contributions.map((entry, index) => `{ operations: source${index}[${JSON.stringify(entry.export)}], plugin: ${JSON.stringify(entry.plugin)} }`).join(", ")}], ${JSON.stringify(root)})`,
178
+ ""
179
+ ].join("\n"));
180
+ const kit = createNitroServerKit(Reflect.get(config, "nitro"));
181
+ kit.addHandler({
182
+ handler,
183
+ route: operationRpcPath
184
+ });
185
+ Reflect.set(config, "nitro", kit.config);
186
+ }
14
187
  const VITEHUB_MODES = {
15
188
  e2e: "e2e",
16
189
  blob: "blob",
@@ -40,127 +213,6 @@ function getViteMode(env = process.env) {
40
213
  return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
41
214
  }
42
215
  //#endregion
43
- //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
44
- const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
45
- function normalizeWindowsPath(input = "") {
46
- if (!input) return input;
47
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
48
- }
49
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
50
- const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
51
- const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
52
- function cwd() {
53
- if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
54
- return "/";
55
- }
56
- const resolve$1 = function(...arguments_) {
57
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
58
- let resolvedPath = "";
59
- let resolvedAbsolute = false;
60
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
61
- const path = index >= 0 ? arguments_[index] : cwd();
62
- if (!path || path.length === 0) continue;
63
- resolvedPath = `${path}/${resolvedPath}`;
64
- resolvedAbsolute = isAbsolute$1(path);
65
- }
66
- resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
67
- if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
68
- return resolvedPath.length > 0 ? resolvedPath : ".";
69
- };
70
- function normalizeString(path, allowAboveRoot) {
71
- let res = "";
72
- let lastSegmentLength = 0;
73
- let lastSlash = -1;
74
- let dots = 0;
75
- let char = null;
76
- for (let index = 0; index <= path.length; ++index) {
77
- if (index < path.length) char = path[index];
78
- else if (char === "/") break;
79
- else char = "/";
80
- if (char === "/") {
81
- if (lastSlash === index - 1 || dots === 1);
82
- else if (dots === 2) {
83
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
84
- if (res.length > 2) {
85
- const lastSlashIndex = res.lastIndexOf("/");
86
- if (lastSlashIndex === -1) {
87
- res = "";
88
- lastSegmentLength = 0;
89
- } else {
90
- res = res.slice(0, lastSlashIndex);
91
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
92
- }
93
- lastSlash = index;
94
- dots = 0;
95
- continue;
96
- } else if (res.length > 0) {
97
- res = "";
98
- lastSegmentLength = 0;
99
- lastSlash = index;
100
- dots = 0;
101
- continue;
102
- }
103
- }
104
- if (allowAboveRoot) {
105
- res += res.length > 0 ? "/.." : "..";
106
- lastSegmentLength = 2;
107
- }
108
- } else {
109
- if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
110
- else res = path.slice(lastSlash + 1, index);
111
- lastSegmentLength = index - lastSlash - 1;
112
- }
113
- lastSlash = index;
114
- dots = 0;
115
- } else if (char === "." && dots !== -1) ++dots;
116
- else dots = -1;
117
- }
118
- return res;
119
- }
120
- const isAbsolute$1 = function(p) {
121
- return _IS_ABSOLUTE_RE.test(p);
122
- };
123
- const relative$1 = function(from, to) {
124
- const _from = resolve$1(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
125
- const _to = resolve$1(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
126
- if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
127
- const _fromCopy = [..._from];
128
- for (const segment of _fromCopy) {
129
- if (_to[0] !== segment) break;
130
- _from.shift();
131
- _to.shift();
132
- }
133
- return [..._from.map(() => ".."), ..._to].join("/");
134
- };
135
- const dirname$1 = function(p) {
136
- const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
137
- if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
138
- return segments.join("/") || (isAbsolute$1(p) ? "/" : ".");
139
- };
140
- //#endregion
141
- //#region ../internal/src/build/client-output.ts
142
- function hasStaticIndex(clientDir) {
143
- return existsSync(resolve$1(clientDir, "index.html"));
144
- }
145
- async function copyClientOutput(clientDir, targetDir) {
146
- const resolvedClientDir = resolve$1(clientDir);
147
- const resolvedTargetDir = resolve$1(targetDir);
148
- if (resolvedClientDir === resolvedTargetDir) return;
149
- await rm(resolvedTargetDir, {
150
- force: true,
151
- recursive: true
152
- });
153
- await mkdir(dirname$1(resolvedTargetDir), { recursive: true });
154
- const targetRelativePath = relative$1(resolvedClientDir, resolvedTargetDir);
155
- if (targetRelativePath && !targetRelativePath.startsWith("../")) {
156
- const [targetRootEntry] = targetRelativePath.split("/", 1);
157
- await mkdir(resolvedTargetDir, { recursive: true });
158
- await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), { recursive: true })));
159
- return;
160
- }
161
- await cp(resolvedClientDir, resolvedTargetDir, { recursive: true });
162
- }
163
- //#endregion
164
216
  //#region ../internal/src/build/provider-output-config.ts
165
217
  function isProviderJsonArray(value, ancestors) {
166
218
  if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
@@ -204,25 +256,12 @@ function isProviderJsonRecord(value) {
204
256
  }
205
257
  }
206
258
  function assertProviderJsonRecord(value) {
207
- if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
208
- }
209
- function isFileNotFoundError(error) {
210
- return error instanceof Error && "code" in error && error.code === "ENOENT";
259
+ if (!isProviderJsonRecord(value)) throw internalErrorDiagnostics.INTERNAL_B0043({ message: "[vitehub] Provider output config must be a JSON object." });
211
260
  }
212
- async function readProviderJsonRecord(file) {
213
- try {
214
- const parsed = JSON.parse(await readFile(file, "utf8"));
215
- assertProviderJsonRecord(parsed);
216
- return parsed;
217
- } catch (error) {
218
- if (isFileNotFoundError(error)) return;
219
- throw error;
220
- }
221
- }
222
- function deleteOwnedFields(value, ownership) {
261
+ function deleteOwnedFields(value, ownership, cleanup = false) {
223
262
  const next = { ...value };
224
263
  for (const key of ownership.keys ?? []) delete next[key];
225
- for (const field of Object.keys(ownership.arrays ?? {})) delete next[field];
264
+ for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) if (!cleanup || !arrayOwnership.preserveOnCleanup) delete next[field];
226
265
  return next;
227
266
  }
228
267
  function getKeyedArrayEntryValue(value, key) {
@@ -237,7 +276,7 @@ function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
237
276
  const key = getKeyedArrayEntryValue(entry, ownership.key);
238
277
  return key === void 0 ? [] : [key];
239
278
  });
240
- const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
279
+ const ownedKeys = /* @__PURE__ */ new Set([...ownership.values ?? [], ...replacementKeys]);
241
280
  return current.filter((entry) => {
242
281
  const key = getKeyedArrayEntryValue(entry, ownership.key);
243
282
  return key === void 0 || !ownedKeys.has(key);
@@ -253,16 +292,6 @@ function mergeOwnedArrays(existing, value, arrays) {
253
292
  }
254
293
  return next;
255
294
  }
256
- async function persistProviderJsonRecord(file, value, removeIfEmpty) {
257
- if (removeIfEmpty && !Object.keys(value).length) {
258
- await rm(file, { force: true });
259
- return;
260
- }
261
- await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
262
- }
263
- async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
264
- await persistProviderJsonRecord(file, mergeProviderOutputConfig(await readProviderJsonRecord(file) ?? {}, value, ownership), options.removeIfEmpty === true);
265
- }
266
295
  function mergeProviderOutputConfig(existing, value, ownership = {}) {
267
296
  assertProviderJsonRecord(existing);
268
297
  assertProviderJsonRecord(value);
@@ -271,49 +300,7 @@ function mergeProviderOutputConfig(existing, value, ownership = {}) {
271
300
  ...mergeOwnedArrays(existing, value, ownership.arrays)
272
301
  };
273
302
  }
274
- function stringifyProviderOutputConfig(value) {
275
- assertProviderJsonRecord(value);
276
- return JSON.stringify(value, null, 2);
277
- }
278
- async function cleanProviderOutputConfig(file, ownership) {
279
- if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
280
- const existing = await readProviderJsonRecord(file);
281
- if (!existing) return;
282
- const next = deleteOwnedFields(existing, ownership);
283
- let changed = (ownership.keys ?? []).some((key) => key in existing);
284
- for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
285
- if (!(field in existing)) continue;
286
- const current = existing[field];
287
- const preserved = preserveUnownedKeyedArrayEntries(current, arrayOwnership);
288
- changed ||= !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
289
- if (preserved.length) next[field] = preserved;
290
- }
291
- if (!changed) return;
292
- await persistProviderJsonRecord(file, next, true);
293
- }
294
- //#endregion
295
- //#region ../internal/src/build/user-entry.ts
296
- function toSafeAppName(rootDir) {
297
- return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
298
- }
299
- //#endregion
300
- //#region ../internal/src/build/cloudflare.ts
301
- function createDefaultCloudflareOutputRoot(rootDir) {
302
- return resolve(rootDir, "dist", toSafeAppName(rootDir));
303
- }
304
- async function writeCloudflareWranglerConfig(options) {
305
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
306
- const configFile = resolve(outputRoot, "wrangler.json");
307
- if (!options.wranglerConfig) {
308
- await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
309
- return;
310
- }
311
- await mkdir(outputRoot, { recursive: true });
312
- await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, { removeIfEmpty: true });
313
- }
314
- //#endregion
315
- //#region ../internal/src/build/vite.ts
316
- var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
303
+ (/* @__PURE__ */ __commonJSMin(((exports, module) => {
317
304
  var __defProp = Object.defineProperty;
318
305
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
319
306
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -423,7 +410,7 @@ var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
423
410
  };
424
411
  }
425
412
  var ByteBuffer = class {
426
- constructor(buf = new Uint8Array(1024)) {
413
+ constructor(buf = /* @__PURE__ */ new Uint8Array(1024)) {
427
414
  this.buf = buf;
428
415
  this.len = 0;
429
416
  this.ptr = 0;
@@ -626,9 +613,7 @@ is not a problem with esbuild. You need to fix your environment instead.
626
613
  value += fromCharCode(code);
627
614
  break;
628
615
  }
629
- default:
630
- throwSyntaxError(bytes, --i);
631
- break;
616
+ default: throwSyntaxError(bytes, --i);
632
617
  }
633
618
  else if (c <= 127) value += fromCharCode(c);
634
619
  else if ((c & 224) === 192) value += fromCharCode((c & 31) << 6 | bytes[i++] & 63);
@@ -693,23 +678,21 @@ is not a problem with esbuild. You need to fix your environment instead.
693
678
  }
694
679
  if (c === 93) continue;
695
680
  break;
696
- case 2:
697
- if (property === null) {
698
- property = value;
699
- if (c === 58) {
700
- i++;
701
- continue;
702
- }
703
- } else {
704
- object[property] = value;
705
- property = null;
706
- if (c === 44) {
707
- i++;
708
- continue;
709
- }
710
- if (c === 125) continue;
681
+ case 2: if (property === null) {
682
+ property = value;
683
+ if (c === 58) {
684
+ i++;
685
+ continue;
711
686
  }
712
- break;
687
+ } else {
688
+ object[property] = value;
689
+ property = null;
690
+ if (c === 44) {
691
+ i++;
692
+ continue;
693
+ }
694
+ if (c === 125) continue;
695
+ }
713
696
  }
714
697
  break;
715
698
  }
@@ -954,19 +937,21 @@ is not a problem with esbuild. You need to fix your environment instead.
954
937
  if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`);
955
938
  flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`);
956
939
  }
957
- if (entryPoints) if (Array.isArray(entryPoints)) for (let i = 0, n = entryPoints.length; i < n; i++) {
958
- let entryPoint = entryPoints[i];
959
- if (typeof entryPoint === "object" && entryPoint !== null) {
960
- let entryPointKeys = /* @__PURE__ */ Object.create(null);
961
- let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
962
- let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
963
- checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
964
- if (input === void 0) throw new Error("Missing property \"in\" for entry point at index " + i);
965
- if (output === void 0) throw new Error("Missing property \"out\" for entry point at index " + i);
966
- entries.push([output, input]);
967
- } else entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
968
- }
969
- else for (let key in entryPoints) entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
940
+ if (entryPoints) {
941
+ if (Array.isArray(entryPoints)) for (let i = 0, n = entryPoints.length; i < n; i++) {
942
+ let entryPoint = entryPoints[i];
943
+ if (typeof entryPoint === "object" && entryPoint !== null) {
944
+ let entryPointKeys = /* @__PURE__ */ Object.create(null);
945
+ let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString);
946
+ let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString);
947
+ checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i);
948
+ if (input === void 0) throw new Error("Missing property \"in\" for entry point at index " + i);
949
+ if (output === void 0) throw new Error("Missing property \"out\" for entry point at index " + i);
950
+ entries.push([output, input]);
951
+ } else entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]);
952
+ }
953
+ else for (let key in entryPoints) entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]);
954
+ }
970
955
  if (stdin) {
971
956
  let stdinKeys = /* @__PURE__ */ Object.create(null);
972
957
  let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array);
@@ -1027,7 +1012,7 @@ is not a problem with esbuild. You need to fix your environment instead.
1027
1012
  let responseCallbacks = {};
1028
1013
  let nextRequestID = 0;
1029
1014
  let nextBuildKey = 0;
1030
- let stdout = new Uint8Array(16 * 1024);
1015
+ let stdout = /* @__PURE__ */ new Uint8Array(16384);
1031
1016
  let stdoutUsed = 0;
1032
1017
  let readFromStdout = (chunk) => {
1033
1018
  let limit = stdoutUsed + chunk.length;
@@ -1221,7 +1206,7 @@ is not a problem with esbuild. You need to fix your environment instead.
1221
1206
  });
1222
1207
  }
1223
1208
  };
1224
- if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) {
1209
+ if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1048576) {
1225
1210
  let next = start;
1226
1211
  start = () => fs3.writeFile(input, next);
1227
1212
  }
@@ -2110,11 +2095,13 @@ ${file}:${line}:${column}: ERROR: ${e.pluginName ? `[plugin: ${e.pluginName}] `
2110
2095
  return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
2111
2096
  }
2112
2097
  function generateBinPath() {
2113
- if (isValidBinaryPath(ESBUILD_BINARY_PATH)) if (!fs.existsSync(ESBUILD_BINARY_PATH)) console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
2114
- else return {
2115
- binPath: ESBUILD_BINARY_PATH,
2116
- isWASM: false
2117
- };
2098
+ if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
2099
+ if (!fs.existsSync(ESBUILD_BINARY_PATH)) console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
2100
+ else return {
2101
+ binPath: ESBUILD_BINARY_PATH,
2102
+ isWASM: false
2103
+ };
2104
+ }
2118
2105
  const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform();
2119
2106
  let binPath;
2120
2107
  try {
@@ -2477,7 +2464,7 @@ More information: The file containing the code for esbuild's JavaScript API (${_
2477
2464
  };
2478
2465
  var runServiceSync = (callback) => {
2479
2466
  let [command, args] = esbuildCommandAndArgs();
2480
- let stdin = new Uint8Array();
2467
+ let stdin = /* @__PURE__ */ new Uint8Array();
2481
2468
  let { readFromStdout, afterClose, service } = createChannel({
2482
2469
  writeToStdin(bytes) {
2483
2470
  if (stdin.length !== 0) throw new Error("Must run at most one command");
@@ -2492,7 +2479,7 @@ More information: The file containing the code for esbuild's JavaScript API (${_
2492
2479
  cwd: defaultWD,
2493
2480
  windowsHide: true,
2494
2481
  input: stdin,
2495
- maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024
2482
+ maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16777216
2496
2483
  }));
2497
2484
  afterClose(null);
2498
2485
  };
@@ -2661,344 +2648,30 @@ error: ${text}`);
2661
2648
  version
2662
2649
  });
2663
2650
  })))();
2664
- const projectRootDirectoryMarkers = [
2665
- ["server", "agents"],
2666
- ["server", "browsers"],
2667
- ["server", "schedules"],
2668
- ["server", "templates"],
2669
- ["server", "workspaces"]
2670
- ];
2671
- const projectRootDefinitionFileMarkers = [
2672
- ".ts",
2673
- ".mts",
2674
- ".cts",
2675
- ".js",
2676
- ".mjs",
2677
- ".cjs"
2678
- ].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
2679
- const projectRootFileMarkers = [["package.json"]];
2680
- function createNoExternalMerger(packageName) {
2681
- return (current) => {
2682
- if (current === true) return true;
2683
- if (!current) return [packageName];
2684
- const values = Array.isArray(current) ? current : [current];
2685
- return values.includes(packageName) ? values : [...values, packageName];
2686
- };
2687
- }
2688
- function isServerEnvironment(name, config) {
2689
- return name === "ssr" || config.consumer === "server";
2690
- }
2691
- function includesNitroVitePlugin(value) {
2692
- if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
2693
- if (!value || typeof value !== "object") return false;
2694
- return "name" in value && value.name === "nitro:main";
2695
- }
2696
- function hasNitroConfigContext(config) {
2697
- return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
2698
- }
2699
- function shouldSkipViteProviderBuild(command, mode) {
2700
- return command === "serve" || mode === "e2e";
2701
- }
2702
- function resolveViteHubProjectRoot(root, options = {}) {
2703
- const resolvedRoot = resolve(root);
2704
- if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
2705
- if (basename(resolvedRoot) === "app") {
2706
- const parent = dirname(resolvedRoot);
2707
- if (hasProjectRootDirectoryMarker(parent) || hasProjectRootDefinitionFileMarker(parent)) return parent;
2708
- }
2709
- let current = resolvedRoot;
2710
- while (true) {
2711
- if (hasProjectRootMarker(current)) return current;
2712
- const parent = dirname(current);
2713
- if (parent === current) return resolvedRoot;
2714
- current = parent;
2715
- }
2716
- }
2717
- function hasProjectRootDirectoryMarker(root) {
2718
- for (const marker of projectRootDirectoryMarkers) try {
2719
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
2720
- } catch (error) {
2721
- if (error.code !== "ENOENT") throw error;
2722
- }
2723
- return false;
2724
- }
2725
- function hasProjectRootMarker(root) {
2726
- if (hasProjectRootDirectoryMarker(root)) return true;
2727
- if (hasProjectRootDefinitionFileMarker(root)) return true;
2728
- for (const marker of projectRootFileMarkers) try {
2729
- if (statSync(resolve(root, ...marker)).isFile()) return true;
2730
- } catch (error) {
2731
- if (error.code !== "ENOENT") throw error;
2732
- }
2733
- return false;
2734
- }
2735
- function hasProjectRootDefinitionFileMarker(root) {
2736
- for (const marker of projectRootDefinitionFileMarkers) try {
2737
- if (statSync(resolve(root, ...marker)).isFile()) return true;
2738
- } catch (error) {
2739
- if (error.code !== "ENOENT") throw error;
2740
- }
2741
- return false;
2742
- }
2743
- //#endregion
2744
- //#region ../internal/src/build/esbuild.ts
2745
- const viteRawNamespace = "vitehub-vite-raw";
2746
- const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
2747
- const markdownTemplateFileSuffix = ".template.md";
2748
- const markdownTemplateModuleQuery = "markdown-template";
2749
- const markdownTemplateRegistryId = "#vitehub/templates";
2750
- const markdownTemplateRegistryPath = ".vitehub/markdown-template/templates.mjs";
2751
- const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
2752
- const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
2753
- function resolveEsbuildAliases(aliases) {
2754
- if (!aliases) return;
2755
- return Object.fromEntries(Object.entries(aliases).filter(([specifier]) => !specifier.endsWith("/")));
2756
- }
2757
- function stripMarkdownCode(template) {
2758
- let fence;
2759
- let inList = false;
2760
- let previousLineBlank = true;
2761
- return template.split("\n").map((line) => {
2762
- const content = line.replace(/^(?: {0,3}> ?)+/, "");
2763
- if (!fence) {
2764
- const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
2765
- const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
2766
- if (!opening) {
2767
- if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
2768
- else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
2769
- const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
2770
- previousLineBlank = content.trim() === "";
2771
- return indentedCode ? "" : line;
2772
- }
2773
- fence = {
2774
- marker: opening[1][0],
2775
- length: opening[1].length,
2776
- listIndented
2777
- };
2778
- previousLineBlank = false;
2779
- return "";
2780
- }
2781
- const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
2782
- if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
2783
- previousLineBlank = false;
2784
- return "";
2785
- }).join("\n");
2786
- }
2787
- function extractMarkdownTemplateImportSpecifiers(template) {
2788
- const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
2789
- const specifiers = /* @__PURE__ */ new Set();
2790
- for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
2791
- const token = match[1];
2792
- const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
2793
- specifiers.add(token.slice(0, token.length - trailing.length));
2794
- }
2795
- return [...specifiers];
2796
- }
2797
- function parseMarkdownTemplateRequest(id) {
2798
- const queryIndex = id.indexOf("?");
2799
- const path = id.split(/[?#]/, 1)[0];
2800
- if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
2801
- const query = id.slice(queryIndex + 1).split("#", 1)[0];
2802
- if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
2803
- return { path };
2804
- }
2805
- function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
2806
- return [
2807
- `import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
2808
- `const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
2809
- `const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
2810
- `const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
2811
- "export default function render(data = {}) {",
2812
- " return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
2813
- "}",
2814
- ""
2815
- ].join("\n");
2816
- }
2817
- function hasViteRawQuery(path) {
2818
- const queryIndex = path.indexOf("?");
2819
- return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
2820
- }
2821
- async function resolveViteRawSpecifier(path, rootDir) {
2822
- if (path.startsWith("/@fs/")) return path.slice(5);
2823
- if (!rootDir || !path.startsWith("/")) return path;
2824
- const rootRelativePath = path.slice(1);
2825
- const publicPath = resolve(rootDir, "public", rootRelativePath);
2826
- try {
2827
- await stat(publicPath);
2828
- return publicPath;
2829
- } catch (error) {
2830
- if (error.code !== "ENOENT") throw error;
2831
- return resolve(rootDir, rootRelativePath);
2651
+ /** Select the runtime constants from one resolved Vite configuration. */
2652
+ function resolveViteHubBundleDefines(config) {
2653
+ const defines = {};
2654
+ for (const name of ["__VITEHUB_PUBLIC_URL__", "__VITEHUB_APP_BASE_URL__"]) {
2655
+ const value = config.define?.[name];
2656
+ if (typeof value === "string") defines[name] = value;
2832
2657
  }
2833
- }
2834
- function createViteRawPlugin(rootDir, frameworkRuntime) {
2835
- return {
2836
- name: "vitehub-vite-raw",
2837
- setup(build) {
2838
- build.onResolve({
2839
- filter: /^@vite-hub\/markdown-template$/,
2840
- namespace: viteMarkdownTemplateNamespace
2841
- }, async (args) => {
2842
- if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
2843
- return build.resolve("vite-hub/_internal/markdown-template", {
2844
- importer: args.importer,
2845
- kind: args.kind,
2846
- resolveDir: args.resolveDir
2847
- });
2848
- });
2849
- build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
2850
- if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
2851
- const markdownTemplate = parseMarkdownTemplateRequest(args.path);
2852
- const raw = hasViteRawQuery(args.path);
2853
- if (!markdownTemplate && !raw) return;
2854
- const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
2855
- const resolved = await build.resolve(specifier, {
2856
- importer: args.importer,
2857
- kind: args.kind,
2858
- namespace: args.namespace,
2859
- pluginData: markdownTemplate ? {
2860
- ...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
2861
- [skipMarkdownTemplateResolve]: true
2862
- } : args.pluginData,
2863
- resolveDir: args.resolveDir,
2864
- with: args.with
2865
- });
2866
- if (resolved.errors.length) return {
2867
- errors: resolved.errors,
2868
- warnings: resolved.warnings
2869
- };
2870
- if (resolved.external) return {
2871
- external: true,
2872
- namespace: resolved.namespace,
2873
- path: resolved.path,
2874
- pluginData: resolved.pluginData,
2875
- sideEffects: resolved.sideEffects,
2876
- suffix: resolved.suffix,
2877
- warnings: resolved.warnings
2878
- };
2879
- if (resolved.namespace !== "file") return {
2880
- errors: [{ text: markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this raw import in a caller plugin.` }],
2881
- warnings: resolved.warnings
2882
- };
2883
- return {
2884
- namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
2885
- path: resolved.path,
2886
- pluginData: resolved.pluginData,
2887
- sideEffects: resolved.sideEffects,
2888
- suffix: resolved.suffix,
2889
- warnings: resolved.warnings
2890
- };
2891
- });
2892
- build.onLoad({
2893
- filter: /.*/,
2894
- namespace: viteRawNamespace
2895
- }, async (args) => ({
2896
- contents: await readFile(args.path),
2897
- loader: "text"
2898
- }));
2899
- build.onLoad({
2900
- filter: /.*/,
2901
- namespace: viteMarkdownTemplateNamespace
2902
- }, async (args) => ({
2903
- contents: await (async () => {
2904
- const template = await readFile(args.path, "utf8");
2905
- const imports = {};
2906
- const visited = new Set([args.path]);
2907
- const visit = async (source, importer) => {
2908
- for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
2909
- const key = `${importer}\0${specifier}`;
2910
- if (imports[key]) continue;
2911
- const resolved = await build.resolve(specifier, {
2912
- importer,
2913
- kind: "import-statement",
2914
- pluginData: {
2915
- ...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
2916
- [skipMarkdownTemplateResolve]: true
2917
- },
2918
- resolveDir: dirname(importer)
2919
- });
2920
- if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
2921
- 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.`);
2922
- const imported = {
2923
- id: resolved.path,
2924
- template: await readFile(resolved.path, "utf8")
2925
- };
2926
- imports[key] = imported;
2927
- if (!visited.has(imported.id)) {
2928
- visited.add(imported.id);
2929
- await visit(imported.template, imported.id);
2930
- }
2931
- }
2932
- };
2933
- await visit(template, args.path);
2934
- return renderMarkdownTemplateModule(template, args.path, imports);
2935
- })(),
2936
- loader: "js",
2937
- resolveDir: dirname(args.path)
2938
- }));
2939
- }
2940
- };
2941
- }
2942
- async function bundleEsmEntry(entryFile, outfile, options = {}) {
2943
- const format = options.format || "esm";
2944
- const platform = options.platform || "neutral";
2945
- const markdownTemplateRoot = options.rootDir && resolveViteHubProjectRoot(options.rootDir);
2946
- const aliases = resolveEsbuildAliases({
2947
- ...markdownTemplateRoot ? { [markdownTemplateRegistryId]: resolve(markdownTemplateRoot, markdownTemplateRegistryPath) } : {},
2948
- ...options.alias
2949
- });
2950
- const frameworkRuntime = Object.keys(aliases || {}).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
2951
- await (0, import_main.build)({
2952
- alias: aliases,
2953
- banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
2954
- "import { createRequire as __createRequire } from \"node:module\";",
2955
- "import { dirname as __vitehubDirname } from \"node:path\";",
2956
- "import { fileURLToPath as __vitehubFileURLToPath } from \"node:url\";",
2957
- "globalThis.require = __createRequire(import.meta.url);",
2958
- "globalThis.__filename = __vitehubFileURLToPath(import.meta.url);",
2959
- "globalThis.__dirname = __vitehubDirname(globalThis.__filename);"
2960
- ] : []].filter(Boolean).join("\n") } : void 0,
2961
- bundle: true,
2962
- conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
2963
- entryPoints: [entryFile],
2964
- external: options.external,
2965
- format,
2966
- logLevel: "silent",
2967
- mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
2968
- minifyIdentifiers: options.minifyIdentifiers,
2969
- outfile,
2970
- platform,
2971
- plugins: [...options.plugins ?? [], createViteRawPlugin(options.rootDir, frameworkRuntime)],
2972
- sourcemap: false,
2973
- target: "es2022",
2974
- write: true
2975
- });
2976
- }
2977
- //#endregion
2978
- //#region ../internal/src/build/vercel-config.ts
2979
- function createVercelConfigJson() {
2980
- return {
2981
- routes: [{ handle: "filesystem" }, {
2982
- src: "/(.*)",
2983
- dest: "/__server"
2984
- }],
2985
- version: 3
2986
- };
2987
- }
2988
- function createNodeFunctionConfig(extra = {}) {
2989
- return {
2990
- handler: "index.mjs",
2991
- launcherType: "Nodejs",
2992
- runtime: "nodejs22.x",
2993
- shouldAddHelpers: false,
2994
- supportsResponseStreaming: true,
2995
- ...extra
2996
- };
2658
+ return defines;
2997
2659
  }
2998
2660
  //#endregion
2999
2661
  //#region ../internal/src/build/cloudflare-provider-output.ts
3000
- const cloudflareProviderOutputKey = Symbol.for("vitehub.cloudflareProviderOutput");
3001
- const cloudflareProviderOutputByNitro = /* @__PURE__ */ new WeakMap();
2662
+ function isDeepStrictEqual(left, right) {
2663
+ if (Object.is(left, right)) return true;
2664
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
2665
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
2666
+ if (Array.isArray(left)) return left.length === right.length && left.every((value, index) => isDeepStrictEqual(value, right[index]));
2667
+ const leftRecord = left;
2668
+ const rightRecord = right;
2669
+ const leftKeys = Object.keys(leftRecord);
2670
+ const rightKeys = Object.keys(rightRecord);
2671
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.hasOwn(rightRecord, key) && isDeepStrictEqual(leftRecord[key], rightRecord[key]));
2672
+ }
2673
+ const providerOutputCatalogRegistry$1 = globalThis;
2674
+ const providerOutputCatalogByNitroValue = providerOutputCatalogRegistry$1.__vitehubProviderOutputCatalogsByNitroValue ??= /* @__PURE__ */ new WeakMap();
3002
2675
  function cloneRecord(value) {
3003
2676
  return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
3004
2677
  }
@@ -3011,16 +2684,6 @@ function cloneProviderValue(value) {
3011
2684
  if (value && typeof value === "object") return cloneProviderRecord(value);
3012
2685
  return value;
3013
2686
  }
3014
- function useCloudflareProviderOutput(config) {
3015
- const owner = config;
3016
- return owner[cloudflareProviderOutputKey] ??= {
3017
- appliedByOwner: /* @__PURE__ */ new Map(),
3018
- contributionsByOwner: /* @__PURE__ */ new Map()
3019
- };
3020
- }
3021
- function registerCloudflareProviderOutput(config, owner, contribution) {
3022
- useCloudflareProviderOutput(config).contributionsByOwner.set(owner, contribution);
3023
- }
3024
2687
  function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner) {
3025
2688
  const current = Array.isArray(existing) ? existing.map(cloneProviderRecord) : [];
3026
2689
  return (incoming ?? []).filter((entry) => {
@@ -3030,7 +2693,7 @@ function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner)
3030
2693
  current.push(entry);
3031
2694
  return true;
3032
2695
  }
3033
- if (conflictKeys.some((key) => !isDeepStrictEqual(match[key], entry[key]))) throw new Error(`[vitehub] Cloudflare ${identityKey} ${JSON.stringify(identity)} from ${owner} is already assigned to an incompatible resource.`);
2696
+ if (conflictKeys.some((key) => !isDeepStrictEqual(match[key], entry[key]))) throw internalErrorDiagnostics.INTERNAL_B0001({ message: `[vitehub] Cloudflare ${identityKey} ${JSON.stringify(identity)} from ${owner} is already assigned to an incompatible resource.` });
3034
2697
  return false;
3035
2698
  });
3036
2699
  }
@@ -3040,7 +2703,10 @@ function removeEntries(existing, entries) {
3040
2703
  }
3041
2704
  function removeContribution(wrangler, contribution) {
3042
2705
  const queues = cloneProviderRecord(wrangler.queues);
2706
+ const secrets = cloneProviderRecord(wrangler.secrets);
2707
+ const environments = cloneProviderRecord(wrangler.env);
3043
2708
  const hasQueues = Boolean(contribution.queues?.consumers?.length || contribution.queues?.producers?.length);
2709
+ const hasSecrets = Boolean(contribution.requiredSecrets?.length || Object.keys(contribution.requiredSecretsByEnvironment ?? {}).length);
3044
2710
  if (contribution.queues?.consumers?.length) {
3045
2711
  const consumers = removeEntries(queues.consumers, contribution.queues.consumers);
3046
2712
  if (consumers.length) queues.consumers = consumers;
@@ -3051,20 +2717,59 @@ function removeContribution(wrangler, contribution) {
3051
2717
  if (producers.length) queues.producers = producers;
3052
2718
  else delete queues.producers;
3053
2719
  }
3054
- const { queues: _queues, ...withoutQueues } = wrangler;
2720
+ if (contribution.requiredSecrets?.length) {
2721
+ const required = removeEntries(secrets.required, contribution.requiredSecrets);
2722
+ if (required.length) secrets.required = required;
2723
+ else delete secrets.required;
2724
+ }
2725
+ for (const [name, requiredSecrets] of Object.entries(contribution.requiredSecretsByEnvironment ?? {})) {
2726
+ if (!Object.hasOwn(environments, name)) continue;
2727
+ const environment = cloneProviderRecord(environments[name]);
2728
+ const environmentSecrets = cloneProviderRecord(environment.secrets);
2729
+ const required = removeEntries(environmentSecrets.required, requiredSecrets);
2730
+ if (required.length) environmentSecrets.required = required;
2731
+ else delete environmentSecrets.required;
2732
+ if (Object.keys(environmentSecrets).length) environment.secrets = environmentSecrets;
2733
+ else delete environment.secrets;
2734
+ environments[name] = environment;
2735
+ }
2736
+ const withoutOwned = { ...wrangler };
2737
+ if (hasQueues) delete withoutOwned.queues;
2738
+ if (hasSecrets) delete withoutOwned.secrets;
2739
+ if (hasSecrets) delete withoutOwned.env;
3055
2740
  return {
3056
- ...hasQueues ? withoutQueues : wrangler,
2741
+ ...withoutOwned,
3057
2742
  ...hasQueues && Object.keys(queues).length ? { queues } : {},
2743
+ ...hasSecrets && Object.keys(secrets).length ? { secrets } : {},
2744
+ ...hasSecrets && Object.keys(environments).length ? { env: environments } : {},
3058
2745
  ...contribution.r2Buckets?.length ? { r2_buckets: removeEntries(wrangler.r2_buckets, contribution.r2Buckets) } : {},
3059
2746
  ...contribution.rateLimits?.length ? { ratelimits: removeEntries(wrangler.ratelimits, contribution.rateLimits) } : {}
3060
2747
  };
3061
2748
  }
3062
2749
  function mergeContribution(wrangler, owner, contribution) {
3063
2750
  const queues = cloneProviderRecord(wrangler.queues);
2751
+ const secrets = cloneProviderRecord(wrangler.secrets);
2752
+ const environments = cloneProviderRecord(wrangler.env);
3064
2753
  const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner);
3065
2754
  const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
3066
- const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name"], owner);
2755
+ const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name", "jurisdiction"], owner);
3067
2756
  const rateLimits = compatibleEntries(wrangler.ratelimits, contribution.rateLimits, "name", ["namespace_id", "simple"], owner);
2757
+ const currentRequiredSecrets = Array.isArray(secrets.required) ? secrets.required : [];
2758
+ const requiredSecrets = (contribution.requiredSecrets ?? []).filter((name) => !currentRequiredSecrets.includes(name));
2759
+ if (requiredSecrets.length) secrets.required = [...currentRequiredSecrets, ...requiredSecrets];
2760
+ const requiredSecretsByEnvironment = {};
2761
+ for (const [name, value] of Object.entries(environments)) {
2762
+ const environment = cloneProviderRecord(value);
2763
+ const environmentSecrets = cloneProviderRecord(environment.secrets);
2764
+ const current = Array.isArray(environmentSecrets.required) ? environmentSecrets.required : [];
2765
+ const required = (contribution.requiredSecrets ?? []).filter((secret) => !current.includes(secret));
2766
+ if (required.length) {
2767
+ environmentSecrets.required = [...current, ...required];
2768
+ environment.secrets = environmentSecrets;
2769
+ environments[name] = environment;
2770
+ requiredSecretsByEnvironment[name] = required;
2771
+ }
2772
+ }
3068
2773
  const nextQueues = mergeProviderOutputConfig(queues, {
3069
2774
  ...consumers.length ? { consumers } : {},
3070
2775
  ...producers.length ? { producers } : {}
@@ -3075,7 +2780,9 @@ function mergeContribution(wrangler, owner, contribution) {
3075
2780
  return [mergeProviderOutputConfig(wrangler, {
3076
2781
  ...Object.keys(nextQueues).length ? { queues: nextQueues } : {},
3077
2782
  ...r2Buckets.length ? { r2_buckets: r2Buckets } : {},
3078
- ...rateLimits.length ? { ratelimits: rateLimits } : {}
2783
+ ...rateLimits.length ? { ratelimits: rateLimits } : {},
2784
+ ...Object.keys(secrets).length ? { secrets } : {},
2785
+ ...Object.keys(environments).length ? { env: environments } : {}
3079
2786
  }, { arrays: {
3080
2787
  r2_buckets: { key: "binding" },
3081
2788
  ratelimits: { key: "name" }
@@ -3085,25 +2792,37 @@ function mergeContribution(wrangler, owner, contribution) {
3085
2792
  producers
3086
2793
  },
3087
2794
  r2Buckets,
3088
- rateLimits
2795
+ rateLimits,
2796
+ requiredSecrets,
2797
+ requiredSecretsByEnvironment
3089
2798
  }];
3090
2799
  }
3091
- function composeNitroCloudflareProviderOutput(config, value) {
2800
+ function inheritedProviderOutputCatalog(value) {
2801
+ if (!value || typeof value !== "object") return;
2802
+ const cloudflare = value.cloudflare;
2803
+ const wrangler = cloudflare && typeof cloudflare === "object" ? cloudflare.wrangler : void 0;
2804
+ return providerOutputCatalogByNitroValue.get(value) ?? (cloudflare && typeof cloudflare === "object" ? providerOutputCatalogByNitroValue.get(cloudflare) : void 0) ?? (wrangler && typeof wrangler === "object" ? providerOutputCatalogByNitroValue.get(wrangler) : void 0);
2805
+ }
2806
+ function associateProviderOutputCatalog(output, catalog) {
2807
+ providerOutputCatalogByNitroValue.set(output, catalog);
2808
+ const cloudflare = output.cloudflare;
2809
+ if (!cloudflare || typeof cloudflare !== "object") return;
2810
+ providerOutputCatalogByNitroValue.set(cloudflare, catalog);
2811
+ const wrangler = cloudflare.wrangler;
2812
+ if (wrangler && typeof wrangler === "object") providerOutputCatalogByNitroValue.set(wrangler, catalog);
2813
+ }
2814
+ function composeNitroCloudflareProviderOutput(catalog, value, inheritedValue = value) {
3092
2815
  const nitro = cloneRecord(value);
3093
2816
  const cloudflare = cloneRecord(nitro.cloudflare);
3094
- const catalog = useCloudflareProviderOutput(config);
3095
- const inherited = value && typeof value === "object" ? value[cloudflareProviderOutputKey] ?? cloudflareProviderOutputByNitro.get(value) : void 0;
3096
- if (inherited && inherited !== catalog) {
3097
- for (const [owner, contribution] of inherited.appliedByOwner) catalog.appliedByOwner.set(owner, contribution);
3098
- catalog.contributionsByOwner = new Map([...inherited.contributionsByOwner, ...catalog.contributionsByOwner]);
3099
- }
2817
+ const inherited = inheritedProviderOutputCatalog(inheritedValue) ?? inheritedProviderOutputCatalog(value);
2818
+ if (inherited && inherited !== catalog) catalog.inheritCloudflareContributions(inherited);
3100
2819
  let wrangler = cloneProviderRecord(cloudflare.wrangler);
3101
- for (const contribution of catalog.appliedByOwner.values()) wrangler = removeContribution(wrangler, contribution);
3102
- catalog.appliedByOwner.clear();
3103
- for (const [owner, contribution] of catalog.contributionsByOwner) {
2820
+ for (const contribution of catalog.appliedCloudflareContributions()) wrangler = removeContribution(wrangler, contribution);
2821
+ catalog.clearAppliedCloudflareContributions();
2822
+ for (const [owner, contribution] of catalog.cloudflareContributions()) {
3104
2823
  const [merged, applied] = mergeContribution(wrangler, owner, contribution);
3105
2824
  wrangler = merged;
3106
- catalog.appliedByOwner.set(owner, applied);
2825
+ catalog.replaceAppliedCloudflareContribution(owner, applied);
3107
2826
  }
3108
2827
  const output = !Object.keys(cloudflare).length && !Object.keys(wrangler).length ? nitro : {
3109
2828
  ...nitro,
@@ -3112,269 +2831,248 @@ function composeNitroCloudflareProviderOutput(config, value) {
3112
2831
  wrangler
3113
2832
  }
3114
2833
  };
3115
- Object.defineProperty(output, cloudflareProviderOutputKey, {
3116
- enumerable: true,
3117
- value: catalog
3118
- });
3119
- cloudflareProviderOutputByNitro.set(output, catalog);
2834
+ associateProviderOutputCatalog(output, catalog);
3120
2835
  return output;
3121
2836
  }
3122
2837
  //#endregion
3123
- //#region ../internal/src/build/deployment-output.ts
3124
- const composedProviderOutputKey = Symbol.for("vitehub.composedProviderOutput");
3125
- const providerDeploymentOutputWrites = /* @__PURE__ */ new Map();
3126
- function useComposedProviderOutput(config) {
3127
- const owner = config;
3128
- return owner[composedProviderOutputKey] ??= {
3129
- runtimeModuleFilesByProduct: {},
3130
- vercelRuntimePackagesByProduct: {}
3131
- };
3132
- }
3133
- function registerProviderRuntimeModules(composed, product, runtimeModuleFiles) {
3134
- if (composed) composed.runtimeModuleFilesByProduct[product] = runtimeModuleFiles;
3135
- }
3136
- function resolveClientOutput(rootDir, clientOutDir) {
3137
- const clientDir = resolve(rootDir, clientOutDir);
3138
- return {
3139
- clientDir,
3140
- staticIndex: hasStaticIndex(clientDir)
3141
- };
3142
- }
3143
- function createDefaultCloudflareStaticOutputDir(rootDir) {
3144
- return resolve(rootDir, "dist", "client");
3145
- }
3146
- function createDefaultVercelOutputRoot(rootDir) {
3147
- return resolve(rootDir, ".vercel", "output");
3148
- }
3149
- function createDefaultNetlifyOutputRoot(rootDir) {
3150
- return resolve(rootDir, ".netlify", "v1");
3151
- }
3152
- function assertNetlifyFunctionName(functionName) {
3153
- if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
3154
- }
3155
- function resolveNetlifyFunctionFile(functionsRoot, functionName) {
3156
- assertNetlifyFunctionName(functionName);
3157
- return resolve(functionsRoot, `${functionName}.mjs`);
3158
- }
3159
- async function appendNetlifyFunctionConfig(outfile, config) {
3160
- if (!config) return;
3161
- await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
3162
- }
3163
- async function writeCloudflareDeploymentOutput(options) {
3164
- const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
3165
- const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
3166
- const files = Object.entries(options.files ?? {});
3167
- const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
3168
- if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${workerOutfile}`);
3169
- await mkdir(outputRoot, { recursive: true });
3170
- const writes = [
3171
- writeCloudflareWranglerConfig({
3172
- outputRoot,
3173
- rootDir: options.rootDir,
3174
- wranglerConfig: options.wranglerConfig,
3175
- wranglerConfigOwnership: options.wranglerConfigOwnership ?? { keys: options.wranglerConfigKeys }
3176
- }),
3177
- options.bundleEntry && staticIndex ? copyClientOutput(clientDir, options.staticOutputDir ?? createDefaultCloudflareStaticOutputDir(options.rootDir)) : Promise.resolve(),
3178
- ...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
3179
- ];
3180
- if (options.bundleEntry && workerOutfile) {
3181
- await rm(workerOutfile, {
3182
- force: true,
3183
- recursive: true
3184
- });
3185
- writes.push(bundleEsmEntry(options.bundleEntry, workerOutfile, {
3186
- ...options.bundleOptions,
3187
- rootDir: options.rootDir
3188
- }));
2838
+ //#region ../internal/src/build/provider-output-catalog.ts
2839
+ var ProviderOutputCatalog = class {
2840
+ bundleDefines = {};
2841
+ #appliedCloudflareContributions = /* @__PURE__ */ new Map();
2842
+ #cloudflareContributions = /* @__PURE__ */ new Map();
2843
+ #runtimeContributions = /* @__PURE__ */ new Map();
2844
+ #runtimeContributionsByGeneration = /* @__PURE__ */ new WeakMap();
2845
+ #deploymentContributionSequence = 0;
2846
+ #deploymentContributions = /* @__PURE__ */ new Map();
2847
+ #deploymentGenerationRefs = /* @__PURE__ */ new WeakMap();
2848
+ #deploymentGenerations = /* @__PURE__ */ new Set();
2849
+ #pendingDeploymentDiscards = [];
2850
+ #takenDeploymentContributions = /* @__PURE__ */ new Map();
2851
+ appliedCloudflareContributions() {
2852
+ return this.#appliedCloudflareContributions.values();
2853
+ }
2854
+ appliedCloudflareContributionEntries() {
2855
+ return this.#appliedCloudflareContributions.entries();
2856
+ }
2857
+ clearAppliedCloudflareContributions() {
2858
+ this.#appliedCloudflareContributions.clear();
2859
+ }
2860
+ cloudflareContributions() {
2861
+ return this.#cloudflareContributions.entries();
2862
+ }
2863
+ inheritCloudflareContributions(catalog) {
2864
+ for (const [owner, contribution] of catalog.appliedCloudflareContributionEntries()) this.#appliedCloudflareContributions.set(owner, contribution);
2865
+ for (const [owner, contribution] of [...catalog.cloudflareContributions(), ...this.#cloudflareContributions]) this.#cloudflareContributions.set(owner, contribution);
2866
+ }
2867
+ replaceAppliedCloudflareContribution(owner, contribution) {
2868
+ this.#appliedCloudflareContributions.set(owner, contribution);
2869
+ }
2870
+ replaceCloudflareContribution(owner, contribution) {
2871
+ this.#cloudflareContributions.set(owner, contribution);
2872
+ }
2873
+ replaceRuntimeContribution(contribution, generation) {
2874
+ if (!generation) {
2875
+ this.#runtimeContributions.set(contribution.owner, contribution);
2876
+ return;
2877
+ }
2878
+ let contributions = this.#runtimeContributionsByGeneration.get(generation);
2879
+ if (!contributions) {
2880
+ contributions = /* @__PURE__ */ new Map();
2881
+ this.#runtimeContributionsByGeneration.set(generation, contributions);
2882
+ }
2883
+ contributions.set(contribution.owner, contribution);
3189
2884
  }
3190
- await Promise.all(writes);
3191
- }
3192
- async function copyVercelClientOutput(rootDir, clientDir, staticOutputDir) {
3193
- const cloudflareOutputRoot = createDefaultCloudflareOutputRoot(rootDir);
3194
- const outputRelativePath = relative(clientDir, cloudflareOutputRoot);
3195
- const excludesCloudflareOutput = outputRelativePath && outputRelativePath !== ".." && !outputRelativePath.startsWith(`..${sep}`) && !isAbsolute(outputRelativePath);
3196
- await copyClientOutput(clientDir, staticOutputDir);
3197
- if (resolve(clientDir) === resolve(staticOutputDir) || !excludesCloudflareOutput) return;
3198
- try {
3199
- await readFile(resolve(cloudflareOutputRoot, "wrangler.json"));
3200
- } catch (error) {
3201
- if (error.code === "ENOENT") return;
3202
- throw error;
2885
+ runtimeContribution(product, generation) {
2886
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.get(product);
3203
2887
  }
3204
- await rm(resolve(staticOutputDir, outputRelativePath), {
3205
- force: true,
3206
- recursive: true
3207
- });
3208
- }
3209
- async function writeVercelDeploymentOutput(options) {
3210
- const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
3211
- const outputRoot = options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir);
3212
- const functionOutput = options.function ?? { kind: "root" };
3213
- const serverFunctionName = functionOutput.kind === "root" ? "__server.func" : functionOutput.name;
3214
- const config = options.config ?? (functionOutput.kind === "root" ? createVercelConfigJson() : {});
3215
- const serverDir = resolve(outputRoot, "functions", serverFunctionName);
3216
- const serverEntry = resolve(serverDir, "index.mjs");
3217
- await mkdir(serverDir, { recursive: true });
3218
- const staleFiles = (await readdir(serverDir)).filter((file) => file !== "node_modules");
3219
- await Promise.all(staleFiles.map((file) => rm(resolve(serverDir, file), {
3220
- force: true,
3221
- recursive: true
3222
- })));
3223
- await Promise.all([
3224
- bundleEsmEntry(options.bundleEntry, serverEntry, {
3225
- ...options.bundleOptions,
3226
- rootDir: options.rootDir
3227
- }),
3228
- writeFile(resolve(serverDir, ".vc-config.json"), `${stringifyProviderOutputConfig(options.functionConfig ?? createNodeFunctionConfig())}\n`, "utf8"),
3229
- writeProviderOutputConfig(resolve(outputRoot, "config.json"), config, { keys: options.configKeys }),
3230
- staticIndex ? copyVercelClientOutput(options.rootDir, clientDir, options.staticOutputDir ?? resolve(outputRoot, "static")) : Promise.resolve()
3231
- ]);
3232
- }
3233
- async function writeNetlifyDeploymentOutput(options) {
3234
- const outputRoot = options.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir);
3235
- const functionsRoot = resolve(outputRoot, "functions");
3236
- const functionWrites = (options.functions ?? []).map(async (func) => {
3237
- const outfile = resolveNetlifyFunctionFile(functionsRoot, func.functionName);
3238
- await rm(outfile, {
3239
- force: true,
3240
- recursive: true
3241
- });
3242
- await mkdir(dirname(outfile), { recursive: true });
3243
- await bundleEsmEntry(func.bundleEntry, outfile, {
3244
- ...func.bundleOptions,
3245
- minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
3246
- rootDir: options.rootDir
3247
- });
3248
- await appendNetlifyFunctionConfig(outfile, func.config);
3249
- });
3250
- await mkdir(outputRoot, { recursive: true });
3251
- await Promise.all([writeProviderOutputConfig(resolve(outputRoot, "config.json"), options.config ?? {}, { keys: options.configKeys }), ...functionWrites]);
3252
- }
3253
- async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput) {
3254
- const cleanup = typeof cleanupInput === "function" ? await cleanupInput() : cleanupInput;
3255
- const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
3256
- const writes = (cleanup.fileNames ?? []).map((fileName) => rm(resolve(outputRoot, fileName), {
3257
- force: true,
3258
- recursive: true
3259
- }));
3260
- writes.push(writeCloudflareWranglerConfig({
3261
- outputRoot,
3262
- rootDir,
3263
- wranglerConfigOwnership: cleanup.wranglerConfigOwnership
3264
- }));
3265
- await Promise.all(writes);
3266
- try {
3267
- await rmdir(outputRoot);
3268
- } catch (error) {
3269
- const code = error.code;
3270
- if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error;
3271
- }
3272
- }
3273
- async function cleanupVercelDeploymentOutput(rootDir, cleanup) {
3274
- const outputRoot = cleanup.outputRoot ?? createDefaultVercelOutputRoot(rootDir);
3275
- const writes = [];
3276
- if (cleanup.serverFunctionName) writes.push(rm(resolve(outputRoot, "functions", cleanup.serverFunctionName), {
3277
- force: true,
3278
- recursive: true
3279
- }));
3280
- writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
3281
- await Promise.all(writes);
3282
- }
3283
- async function cleanupVercelDeploymentOutputs(rootDir, cleanup) {
3284
- await Promise.all((Array.isArray(cleanup) ? cleanup : [cleanup]).map((item) => cleanupVercelDeploymentOutput(rootDir, item)));
3285
- }
3286
- async function cleanupNetlifyDeploymentOutput(rootDir, cleanup) {
3287
- const outputRoot = cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(rootDir);
3288
- const functionsRoot = resolve(outputRoot, "functions");
3289
- const writes = (cleanup.functionNames ?? []).map((functionName) => rm(resolveNetlifyFunctionFile(functionsRoot, functionName), {
3290
- force: true,
3291
- recursive: true
3292
- }));
3293
- writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
3294
- await Promise.all(writes);
3295
- }
3296
- async function writeProviderDeploymentOutputsNow(options) {
3297
- const writes = [];
3298
- if (options.cloudflare) writes.push(writeCloudflareDeploymentOutput({
3299
- ...options.cloudflare,
3300
- clientOutDir: options.clientOutDir,
3301
- rootDir: options.rootDir
3302
- }));
3303
- else if (options.cleanup?.cloudflare) writes.push(cleanupCloudflareDeploymentOutput(options.rootDir, options.cleanup.cloudflare));
3304
- if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
3305
- ...options.netlify,
3306
- clientOutDir: options.clientOutDir,
3307
- rootDir: options.rootDir
3308
- }));
3309
- else if (options.cleanup?.netlify) writes.push(cleanupNetlifyDeploymentOutput(options.rootDir, options.cleanup.netlify));
3310
- if (options.vercel) writes.push(writeVercelDeploymentOutput({
3311
- ...options.vercel,
3312
- clientOutDir: options.clientOutDir,
3313
- rootDir: options.rootDir
3314
- }));
3315
- else if (options.cleanup?.vercel) {
3316
- const cleanup = typeof options.cleanup.vercel === "function" ? await options.cleanup.vercel() : options.cleanup.vercel;
3317
- if (cleanup) writes.push(cleanupVercelDeploymentOutputs(options.rootDir, cleanup));
3318
- }
3319
- await Promise.all(writes);
3320
- await options.afterWrite?.();
3321
- }
3322
- async function writeProviderDeploymentOutputs(options) {
3323
- const key = resolve(options.rootDir);
3324
- const write = (providerDeploymentOutputWrites.get(key) ?? Promise.resolve()).catch(() => void 0).then(() => writeProviderDeploymentOutputsNow(options));
3325
- providerDeploymentOutputWrites.set(key, write);
3326
- try {
3327
- await write;
3328
- } finally {
3329
- if (providerDeploymentOutputWrites.get(key) === write) providerDeploymentOutputWrites.delete(key);
2888
+ runtimeContributions(generation) {
2889
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.entries() ?? (/* @__PURE__ */ new Map()).entries();
3330
2890
  }
3331
- }
3332
- //#endregion
3333
- //#region ../internal/src/definition-catalog.ts
3334
- const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
3335
- const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
3336
- const ignoredDirs = new Set([
3337
- "node_modules",
3338
- "dist",
3339
- ".output",
3340
- ".nuxt",
3341
- ".vercel",
3342
- ".git",
3343
- ".vitehub"
3344
- ]);
3345
- function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
3346
- return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
3347
- }
3348
- function readDirEntries(root) {
3349
- try {
3350
- return readdirSync(root, { withFileTypes: true });
3351
- } catch (error) {
3352
- if (error.code === "ENOENT") return [];
3353
- throw error;
2891
+ resetRuntimeContributions(generation, owner) {
2892
+ if (generation) {
2893
+ if (owner) this.#runtimeContributionsByGeneration.get(generation)?.delete(owner);
2894
+ else this.#runtimeContributionsByGeneration.delete(generation);
2895
+ return;
2896
+ }
2897
+ if (owner) this.#runtimeContributions.delete(owner);
2898
+ else this.#runtimeContributions.clear();
3354
2899
  }
3355
- }
3356
- function listMatchingFiles(root, predicate, options = {}) {
3357
- const files = [];
3358
- for (const entry of readDirEntries(root)) {
3359
- const absolute = resolve$1(root, entry.name);
3360
- if (entry.isDirectory() && !entry.isSymbolicLink()) {
3361
- if (entry.name.startsWith(".")) continue;
3362
- if (ignoredDirs.has(entry.name)) continue;
3363
- files.push(...listMatchingFiles(absolute, predicate, options));
3364
- continue;
2900
+ resetRuntimeContribution(product, generation) {
2901
+ if (!generation) {
2902
+ this.#runtimeContributions.delete(product);
2903
+ return;
3365
2904
  }
3366
- if (entry.name.startsWith(".") && !options.includeHidden) continue;
3367
- if (entry.isFile() && predicate(entry.name)) files.push(absolute);
2905
+ this.#runtimeContributionsByGeneration.get(generation)?.delete(product);
2906
+ }
2907
+ createDeploymentGeneration() {
2908
+ const generation = { valid: true };
2909
+ this.#trackDeploymentGeneration(generation);
2910
+ return generation;
2911
+ }
2912
+ replaceDeploymentContribution(contribution, generation) {
2913
+ const entry = {
2914
+ contribution,
2915
+ generation,
2916
+ sequence: this.#deploymentContributionSequence++
2917
+ };
2918
+ if (generation && !generation.valid) {
2919
+ this.#queueDeploymentDiscard(entry);
2920
+ return;
2921
+ }
2922
+ this.#restoreDeploymentContribution(entry);
3368
2923
  }
3369
- return files.sort();
2924
+ resetDeploymentContributions(generation) {
2925
+ if (!generation) {
2926
+ for (const reference of this.#deploymentGenerations) {
2927
+ const current = reference.deref();
2928
+ if (current) current.valid = false;
2929
+ }
2930
+ this.#deploymentGenerations.clear();
2931
+ for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
2932
+ for (const taken of this.#takenDeploymentContributions.values()) {
2933
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
2934
+ for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
2935
+ }
2936
+ this.#deploymentContributions.clear();
2937
+ this.#takenDeploymentContributions.clear();
2938
+ return;
2939
+ }
2940
+ generation.valid = false;
2941
+ this.#deleteDeploymentGeneration(generation);
2942
+ for (const [owner, entries] of this.#deploymentContributions) {
2943
+ for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
2944
+ const remaining = entries.filter((entry) => entry.generation !== generation);
2945
+ if (remaining.length) this.#deploymentContributions.set(owner, remaining);
2946
+ else this.#deploymentContributions.delete(owner);
2947
+ }
2948
+ for (const [contribution, taken] of this.#takenDeploymentContributions) {
2949
+ const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
2950
+ taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
2951
+ for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
2952
+ if (taken.entry.generation !== generation) continue;
2953
+ this.#takenDeploymentContributions.delete(contribution);
2954
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
2955
+ for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
2956
+ else this.#restoreDeploymentContribution(fallback);
2957
+ }
2958
+ }
2959
+ hasDeploymentContributions() {
2960
+ return this.#deploymentContributions.size > 0;
2961
+ }
2962
+ takeDeploymentContributions() {
2963
+ const contributions = [];
2964
+ for (const [owner, entries] of this.#deploymentContributions) {
2965
+ const entry = entries.at(-1);
2966
+ contributions.push(entry.contribution);
2967
+ this.#takenDeploymentContributions.set(entry.contribution, {
2968
+ committed: false,
2969
+ entry,
2970
+ entryDiscarded: false,
2971
+ fallbacks: entries.slice(0, -1)
2972
+ });
2973
+ this.#deploymentContributions.delete(owner);
2974
+ }
2975
+ return contributions;
2976
+ }
2977
+ deploymentContributionGeneration(contribution) {
2978
+ return this.#takenDeploymentContributions.get(contribution)?.entry.generation;
2979
+ }
2980
+ commitDeploymentContributions(contributions) {
2981
+ for (const contribution of contributions) {
2982
+ const taken = this.#takenDeploymentContributions.get(contribution);
2983
+ if (taken) taken.committed = true;
2984
+ }
2985
+ }
2986
+ async prepareDeploymentContributions(contributions) {
2987
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
2988
+ for (const contribution of contributions) {
2989
+ const taken = this.#takenDeploymentContributions.get(contribution);
2990
+ if (!taken || taken.entryDiscarded || !taken.entry.contribution.discard) continue;
2991
+ taken.entryDiscarded = true;
2992
+ discarded.push(Promise.resolve().then(taken.entry.contribution.discard));
2993
+ }
2994
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
2995
+ if (failure) throw failure.reason;
2996
+ }
2997
+ async completeDeploymentContributions(contributions) {
2998
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
2999
+ const completedGenerations = /* @__PURE__ */ new Set();
3000
+ for (const contribution of contributions) {
3001
+ const taken = this.#takenDeploymentContributions.get(contribution);
3002
+ if (!taken) continue;
3003
+ this.#takenDeploymentContributions.delete(contribution);
3004
+ const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
3005
+ for (const entry of entries) {
3006
+ if (entry.generation) completedGenerations.add(entry.generation);
3007
+ if (entry.contribution.discard) discarded.push(entry.contribution.discard());
3008
+ }
3009
+ }
3010
+ for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
3011
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
3012
+ if (failure) throw failure.reason;
3013
+ }
3014
+ rollbackDeploymentContributions(contributions) {
3015
+ for (const contribution of contributions) {
3016
+ const taken = this.#takenDeploymentContributions.get(contribution);
3017
+ if (!taken) continue;
3018
+ this.#takenDeploymentContributions.delete(contribution);
3019
+ for (const entry of [...taken.fallbacks, taken.entry]) this.#restoreDeploymentContribution(entry);
3020
+ }
3021
+ }
3022
+ #restoreDeploymentContribution(entry) {
3023
+ if (entry.generation && !entry.generation.valid) return;
3024
+ if (entry.generation) this.#trackDeploymentGeneration(entry.generation);
3025
+ const entries = this.#deploymentContributions.get(entry.contribution.owner) ?? [];
3026
+ const replaced = entries.findIndex((candidate) => candidate.generation === entry.generation);
3027
+ if (replaced >= 0) {
3028
+ if (entries[replaced].sequence > entry.sequence) return;
3029
+ entries.splice(replaced, 1);
3030
+ }
3031
+ entries.push(entry);
3032
+ entries.sort((left, right) => left.sequence - right.sequence);
3033
+ this.#deploymentContributions.set(entry.contribution.owner, entries);
3034
+ }
3035
+ #retireDeploymentGeneration(generation) {
3036
+ const pending = [...this.#deploymentContributions.values()].some((entries) => entries.some((entry) => entry.generation === generation));
3037
+ const taken = [...this.#takenDeploymentContributions.values()].some((entry) => entry.entry.generation === generation || entry.fallbacks.some((fallback) => fallback.generation === generation));
3038
+ if (!pending && !taken) this.#deleteDeploymentGeneration(generation);
3039
+ }
3040
+ #trackDeploymentGeneration(generation) {
3041
+ if (this.#deploymentGenerationRefs.has(generation)) return;
3042
+ const reference = new WeakRef(generation);
3043
+ this.#deploymentGenerationRefs.set(generation, reference);
3044
+ this.#deploymentGenerations.add(reference);
3045
+ }
3046
+ #deleteDeploymentGeneration(generation) {
3047
+ const reference = this.#deploymentGenerationRefs.get(generation);
3048
+ if (reference) this.#deploymentGenerations.delete(reference);
3049
+ this.#deploymentGenerationRefs.delete(generation);
3050
+ }
3051
+ #queueDeploymentDiscard(entry) {
3052
+ if (!entry.contribution.discard) return;
3053
+ const discard = Promise.resolve().then(entry.contribution.discard);
3054
+ discard.catch(() => {});
3055
+ this.#pendingDeploymentDiscards.push(discard);
3056
+ }
3057
+ };
3058
+ const providerOutputCatalogRegistry = globalThis;
3059
+ const providerOutputCatalogs = providerOutputCatalogRegistry.__vitehubProviderOutputCatalogs ??= /* @__PURE__ */ new WeakMap();
3060
+ const providerOutputCatalog = Symbol.for("vitehub.provider-output-catalog");
3061
+ function createProviderOutputCatalog() {
3062
+ return new ProviderOutputCatalog();
3370
3063
  }
3371
- function listSourceFiles(root, options = {}) {
3372
- return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
3064
+ function useProviderOutputCatalog(config) {
3065
+ const owner = config;
3066
+ let catalog = owner[providerOutputCatalog] ?? providerOutputCatalogs.get(config);
3067
+ if (!catalog) catalog = createProviderOutputCatalog();
3068
+ catalog.bundleDefines = resolveViteHubBundleDefines(config);
3069
+ owner[providerOutputCatalog] = catalog;
3070
+ providerOutputCatalogs.set(config, catalog);
3071
+ return catalog;
3373
3072
  }
3374
- async function writeFileIfChanged(file, contents) {
3375
- if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
3376
- await mkdir(resolve$1(file, ".."), { recursive: true });
3377
- await writeFile(file, contents, "utf8");
3073
+ function contributeCloudflareProviderOutput(catalog, contribution) {
3074
+ const { owner, ...value } = contribution;
3075
+ catalog.replaceCloudflareContribution(owner, value);
3378
3076
  }
3379
3077
  function deploymentPresetFromNitro(value) {
3380
3078
  const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
@@ -3387,19 +3085,45 @@ function deploymentPresetFromNitro(value) {
3387
3085
  }
3388
3086
  //#endregion
3389
3087
  //#region ../internal/src/hosting.ts
3088
+ /**
3089
+ * Returns the Nitro preset name that this build targets, as the developer wrote it.
3090
+ * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOSTING`.
3091
+ * Empty values are skipped.
3092
+ */
3093
+ function resolveHostPreset(input = {}) {
3094
+ const env = input.env ?? (typeof process === "undefined" ? {} : process.env);
3095
+ const nitroPreset = input.nitro && typeof input.nitro === "object" ? Reflect.get(input.nitro, "preset") : void 0;
3096
+ for (const value of [
3097
+ nitroPreset,
3098
+ input.hosting,
3099
+ env.NITRO_PRESET,
3100
+ env.SERVER_PRESET,
3101
+ env.VITEHUB_HOSTING
3102
+ ]) if (typeof value === "string" && value.trim()) return value.trim();
3103
+ }
3104
+ /** Returns the host that this build targets: `cloudflare`, `deno`, `netlify`, `node`, or `vercel`. */
3105
+ function resolveHost(input = {}) {
3106
+ return deploymentPresetFromNitro(resolveHostPreset(input));
3107
+ }
3108
+ /** Narrows a preset or host name to the hosts that have a native provider: Cloudflare, Netlify, or Vercel. */
3390
3109
  function getHostingProvider(hosting) {
3391
3110
  const preset = deploymentPresetFromNitro(hosting);
3392
3111
  if (preset === "cloudflare" || preset === "netlify" || preset === "vercel") return preset;
3393
3112
  }
3394
3113
  //#endregion
3395
3114
  //#region src/discovery.ts
3396
- const rateLimitImports = new Set(["@vite-hub/rate-limit", "vite-hub/rate-limit"]);
3397
- const ignoredSourceDirectories = new Set([
3115
+ const rateLimitImports = /* @__PURE__ */ new Set(["@vite-hub/rate-limit", "vite-hub/rate-limit"]);
3116
+ /** Functions whose calls declare a managed Rate Limit. Both consume the same counters. */
3117
+ const rateLimitGuards = ["checkRateLimit", "requireRateLimit"];
3118
+ function isRateLimitGuard(name) {
3119
+ return rateLimitGuards.some((guard) => guard === name);
3120
+ }
3121
+ const ignoredSourceDirectories = /* @__PURE__ */ new Set([
3398
3122
  "__tests__",
3399
3123
  "test",
3400
3124
  "tests"
3401
3125
  ]);
3402
- const nestedIgnoredSourceDirectories = new Set(["__tests__", "tests"]);
3126
+ const nestedIgnoredSourceDirectories = /* @__PURE__ */ new Set(["__tests__", "tests"]);
3403
3127
  function isApplicationSource(root, file) {
3404
3128
  const segments = relative(root, file).split(/[\\/]/);
3405
3129
  if (segments.length > 1 && ignoredSourceDirectories.has(segments[0])) return false;
@@ -3415,34 +3139,44 @@ function location(source, offset) {
3415
3139
  }
3416
3140
  function declarationError(file, source, node, message) {
3417
3141
  const { column, line } = location(source, node.start);
3418
- return /* @__PURE__ */ new Error(`[vitehub] ${message}\n at ${file}:${line}:${column}`);
3142
+ return rateLimitErrorDiagnostics.RATE_LIMIT_R0001({ message: `[vitehub] ${message}\n at ${file}:${line}:${column}` });
3419
3143
  }
3420
- function requireRateLimitBindings(program) {
3144
+ function rateLimitImportBindings(program) {
3421
3145
  const bindings = {
3422
- direct: /* @__PURE__ */ new Set(),
3146
+ direct: /* @__PURE__ */ new Map(),
3423
3147
  namespaces: /* @__PURE__ */ new Set()
3424
3148
  };
3425
3149
  for (const statement of program.body) {
3426
3150
  if (statement.type !== "ImportDeclaration" || statement.importKind === "type" || !rateLimitImports.has(statement.source.value)) continue;
3427
3151
  for (const specifier of statement.specifiers) {
3428
- if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && specifier.imported.type === "Identifier" && specifier.imported.name === "requireRateLimit") bindings.direct.add(specifier.local.name);
3152
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && specifier.imported.type === "Identifier" && isRateLimitGuard(specifier.imported.name)) bindings.direct.set(specifier.local.name, specifier.imported.name);
3429
3153
  if (specifier.type === "ImportNamespaceSpecifier") bindings.namespaces.add(specifier.local.name);
3430
3154
  }
3431
3155
  }
3432
3156
  return bindings;
3433
3157
  }
3434
- function resolveRateLimitBinding(name, kind, scopes) {
3158
+ function resolveDirectGuard(name, scopes) {
3435
3159
  for (let index = scopes.length - 1; index >= 0; index -= 1) {
3436
3160
  const scope = scopes[index];
3437
- if (scope[kind].has(name)) return true;
3161
+ const guard = scope.direct.get(name);
3162
+ if (guard) return guard;
3163
+ if (scope.shadows.has(name)) return void 0;
3164
+ }
3165
+ }
3166
+ function resolveNamespace(name, scopes) {
3167
+ for (let index = scopes.length - 1; index >= 0; index -= 1) {
3168
+ const scope = scopes[index];
3169
+ if (scope.namespaces.has(name)) return true;
3438
3170
  if (scope.shadows.has(name)) return false;
3439
3171
  }
3440
3172
  return false;
3441
3173
  }
3442
- function rateLimitBindingName(callee, scopes) {
3443
- if (callee.type === "Identifier" && resolveRateLimitBinding(callee.name, "direct", scopes)) return callee.name;
3444
- if (callee.type !== "MemberExpression" || callee.object.type !== "Identifier" || !resolveRateLimitBinding(callee.object.name, "namespaces", scopes)) return;
3445
- return (callee.computed ? callee.property.type === "Literal" ? callee.property.value : void 0 : callee.property.type === "Identifier" ? callee.property.name : void 0) === "requireRateLimit" ? callee.object.name : void 0;
3174
+ /** The guard that a call invokes, or `undefined` when the callee is not a Rate Limit guard. */
3175
+ function rateLimitGuardOf(callee, scopes) {
3176
+ if (callee.type === "Identifier") return resolveDirectGuard(callee.name, scopes);
3177
+ if (callee.type !== "MemberExpression" || callee.object.type !== "Identifier" || !resolveNamespace(callee.object.name, scopes)) return;
3178
+ const property = callee.computed ? callee.property.type === "Literal" ? callee.property.value : void 0 : callee.property.type === "Identifier" ? callee.property.name : void 0;
3179
+ return isRateLimitGuard(property) ? property : void 0;
3446
3180
  }
3447
3181
  function rateLimitDynamicImport(expression) {
3448
3182
  if (!expression) return false;
@@ -3463,10 +3197,11 @@ function addDynamicRateLimitBindings(declaration, scope) {
3463
3197
  if (declarator.id.type !== "ObjectPattern") continue;
3464
3198
  for (const property of declarator.id.properties) {
3465
3199
  if (property.type !== "Property") continue;
3466
- if ((property.computed ? property.key.type === "Literal" ? property.key.value : void 0 : property.key.type === "Identifier" ? property.key.name : void 0) !== "requireRateLimit") continue;
3200
+ const name = property.computed ? property.key.type === "Literal" ? property.key.value : void 0 : property.key.type === "Identifier" ? property.key.name : void 0;
3201
+ if (!isRateLimitGuard(name)) continue;
3467
3202
  const value = property.value.type === "AssignmentPattern" ? property.value.left : property.value;
3468
3203
  if (value.type !== "Identifier") continue;
3469
- scope.direct.add(value.name);
3204
+ scope.direct.set(value.name, name);
3470
3205
  }
3471
3206
  }
3472
3207
  }
@@ -3620,19 +3355,19 @@ function staticString(expression) {
3620
3355
  if (value.type === "Literal" && typeof value.value === "string") return value.value;
3621
3356
  if (value.type === "TemplateLiteral" && value.expressions.length === 0) return value.quasis[0]?.value.cooked ?? value.quasis[0]?.value.raw;
3622
3357
  }
3623
- function staticPolicy(call, file, source) {
3358
+ function staticPolicy(call, guard, file, source) {
3624
3359
  const policyArgument = call.arguments[2];
3625
3360
  const policyNode = policyArgument?.type === "SpreadElement" ? policyArgument : policyArgument && unwrapStaticExpression(policyArgument);
3626
- if (!policyNode || policyNode.type !== "ObjectExpression") throw declarationError(file, source, call, "`requireRateLimit()` requires a static options object as its third argument.");
3361
+ if (!policyNode || policyNode.type !== "ObjectExpression") throw declarationError(file, source, call, `\`${guard}()\` requires a static options object as its third argument.`);
3627
3362
  const values = /* @__PURE__ */ new Map();
3628
3363
  for (const property of policyNode.properties) {
3629
- if (property.type !== "Property") throw declarationError(file, source, property, "`requireRateLimit()` options cannot use object spreads.");
3364
+ if (property.type !== "Property") throw declarationError(file, source, property, `\`${guard}()\` options cannot use object spreads.`);
3630
3365
  const name = staticPropertyName(property);
3631
3366
  if (name === "key") continue;
3632
- if (!name || !rateLimitPolicyKeys.has(name)) throw declarationError(file, source, property, `\`requireRateLimit()\` does not support the ${name ? `"${name}"` : "dynamic"} option.`);
3367
+ if (!name || !rateLimitPolicyKeys.has(name)) throw declarationError(file, source, property, `\`${guard}()\` does not support the ${name ? `"${name}"` : "dynamic"} option.`);
3633
3368
  const value = unwrapStaticExpression(property.value);
3634
3369
  const literal = value.type === "Literal" && typeof value.value === "number" ? value.value : staticString(value);
3635
- if (literal === void 0) throw declarationError(file, source, property.value, `\`requireRateLimit()\` policy option "${name}" must be a static literal.`);
3370
+ if (literal === void 0) throw declarationError(file, source, property.value, `\`${guard}()\` policy option "${name}" must be a static literal.`);
3636
3371
  values.set(name, literal);
3637
3372
  }
3638
3373
  const policy = {
@@ -3648,12 +3383,12 @@ function staticPolicy(call, file, source) {
3648
3383
  }
3649
3384
  }
3650
3385
  function extractRateLimitDeclarations(file, source) {
3651
- if (!source.includes("requireRateLimit")) return [];
3386
+ if (!rateLimitGuards.some((guard) => source.includes(guard))) return [];
3652
3387
  const parsed = parseSync(file, source);
3653
- if (parsed.errors.length > 0) throw new Error(`[vitehub] Could not parse ${file} while collecting Rate Limits: ${parsed.errors[0]?.message}`);
3388
+ if (parsed.errors.length > 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0002({ message: `[vitehub] Could not parse ${file} while collecting Rate Limits: ${parsed.errors[0]?.message}` });
3654
3389
  const rootShadows = programBindings(parsed.program);
3655
- const bindings = requireRateLimitBindings(parsed.program);
3656
- if (!rootShadows.has("requireRateLimit")) bindings.direct.add("requireRateLimit");
3390
+ const bindings = rateLimitImportBindings(parsed.program);
3391
+ for (const guard of rateLimitGuards) if (!rootShadows.has(guard) && !bindings.direct.has(guard)) bindings.direct.set(guard, guard);
3657
3392
  const declarations = [];
3658
3393
  const scopes = [{
3659
3394
  ...bindings,
@@ -3663,7 +3398,7 @@ function extractRateLimitDeclarations(file, source) {
3663
3398
  addDynamicRateLimitBindingsFromStatements(parsed.program.body, scopes[0]);
3664
3399
  const enterScope = (shadows) => {
3665
3400
  scopes.push({
3666
- direct: /* @__PURE__ */ new Set(),
3401
+ direct: /* @__PURE__ */ new Map(),
3667
3402
  namespaces: /* @__PURE__ */ new Set(),
3668
3403
  shadows
3669
3404
  });
@@ -3694,16 +3429,17 @@ function extractRateLimitDeclarations(file, source) {
3694
3429
  },
3695
3430
  "ClassExpression:exit": exitScope,
3696
3431
  CallExpression(call) {
3697
- if (!rateLimitBindingName(call.callee, scopes)) return;
3698
- if (call.arguments.length !== 3) throw declarationError(file, source, call, "`requireRateLimit()` requires an event, a stable ID, and a static options object.");
3432
+ const guard = rateLimitGuardOf(call.callee, scopes);
3433
+ if (!guard) return;
3434
+ if (call.arguments.length !== 3) throw declarationError(file, source, call, `\`${guard}()\` requires an event, a stable ID, and a static options object.`);
3699
3435
  const idNode = call.arguments[1];
3700
3436
  const staticId = idNode?.type === "SpreadElement" ? void 0 : idNode && staticString(idNode);
3701
- if (!staticId?.trim()) throw declarationError(file, source, idNode ?? call, "`requireRateLimit()` requires a non-empty static string ID.");
3437
+ if (!staticId?.trim()) throw declarationError(file, source, idNode ?? call, `\`${guard}()\` requires a non-empty static string ID.`);
3702
3438
  const id = staticId.trim();
3703
3439
  const sourceLocation = location(source, call.start);
3704
3440
  declarations.push({
3705
3441
  name: id,
3706
- policy: staticPolicy(call, file, source),
3442
+ policy: staticPolicy(call, guard, file, source),
3707
3443
  source: {
3708
3444
  file,
3709
3445
  ...sourceLocation
@@ -3753,11 +3489,11 @@ function discoverRateLimitCatalog(options) {
3753
3489
  if (extracted.length > 0) declarationFiles.add(file);
3754
3490
  for (const declaration of extracted) {
3755
3491
  const existing = declarations.get(declaration.name);
3756
- if (existing && JSON.stringify(existing.policy) !== JSON.stringify(declaration.policy)) throw new Error([
3492
+ if (existing && JSON.stringify(existing.policy) !== JSON.stringify(declaration.policy)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0003({ message: [
3757
3493
  `[vitehub] Conflicting Rate Limit policies for ID "${declaration.name}":`,
3758
3494
  ` - ${existing.source.file}:${existing.source.line}:${existing.source.column} ${JSON.stringify(existing.policy)}`,
3759
3495
  ` - ${declaration.source.file}:${declaration.source.line}:${declaration.source.column} ${JSON.stringify(declaration.policy)}`
3760
- ].join("\n"));
3496
+ ].join("\n") });
3761
3497
  if (!existing) declarations.set(declaration.name, declaration);
3762
3498
  }
3763
3499
  }
@@ -3766,12 +3502,66 @@ function discoverRateLimitCatalog(options) {
3766
3502
  declarations: [...declarations.values()].sort((left, right) => left.name.localeCompare(right.name))
3767
3503
  };
3768
3504
  }
3505
+ function discoverRateLimitDeclarations(options) {
3506
+ return discoverRateLimitCatalog(options).declarations;
3507
+ }
3508
+ //#endregion
3509
+ //#region src/inspect.ts
3510
+ function summarizeRateLimitDeclaration(projectRoot, declaration) {
3511
+ return {
3512
+ fields: [
3513
+ {
3514
+ label: "Limit",
3515
+ value: String(declaration.policy.limit)
3516
+ },
3517
+ {
3518
+ label: "Window",
3519
+ value: declaration.policy.window
3520
+ },
3521
+ {
3522
+ label: "Enforcement",
3523
+ value: declaration.policy.enforcement === "strict" ? "Strict" : "Best effort"
3524
+ },
3525
+ {
3526
+ label: "Provider failure",
3527
+ value: declaration.policy.failure === "allow" ? "Allow" : "Deny"
3528
+ },
3529
+ {
3530
+ label: "Source location",
3531
+ value: `${declaration.source.line}:${declaration.source.column}`
3532
+ }
3533
+ ],
3534
+ file: relativeDefinitionFile(projectRoot, declaration.source.file),
3535
+ name: declaration.name,
3536
+ source: "require-rate-limit"
3537
+ };
3538
+ }
3539
+ /** Lists `requireRateLimit()` declarations as serializable inspection summaries. */
3540
+ function inspectRateLimitDefinitions(options) {
3541
+ return discoverRateLimitDeclarations({
3542
+ rootDir: options.rootDir,
3543
+ scanDirs: options.scanDirs
3544
+ }).map((declaration) => summarizeRateLimitDeclaration(options.projectRoot, declaration));
3545
+ }
3546
+ /** Console section that lists discovered Rate Limit Definitions. `vitehub inspect definitions` reads the same data. */
3547
+ const rateLimitConsoleSection = {
3548
+ description: "Inspect discovered Rate Limit policies and their source locations.",
3549
+ icon: "i-lucide-gauge",
3550
+ id: "rate-limits",
3551
+ label: "Rate Limits",
3552
+ read: inspectRateLimitDefinitions,
3553
+ view: {
3554
+ kind: "definition-catalog",
3555
+ notice: "The page lists the policies. Enter a key to read its live counter or to reset it. Counters depend on the provider: a Cloudflare binding cannot be read or reset, and a memory counter exists only in this server process."
3556
+ }
3557
+ };
3769
3558
  //#endregion
3770
3559
  //#region src/internal/manifest.ts
3771
3560
  const rateLimitManifestPath = ".vitehub/rate-limit/manifest.json";
3772
3561
  function resolveProviderCapabilities(provider) {
3562
+ const driver = provider === "cloudflare" ? cloudflareRateLimitDriver({ binding: { limit: async () => ({ success: true }) } }) : memoryRateLimitDriver();
3773
3563
  return createRateLimiter({
3774
- driver: provider === "cloudflare" ? cloudflareRateLimitDriver({ binding: { limit: async () => ({ success: true }) } }) : memoryRateLimitDriver(),
3564
+ driver,
3775
3565
  limit: 1,
3776
3566
  window: "1m"
3777
3567
  }).capabilities;
@@ -3792,37 +3582,7 @@ async function writeRateLimitManifest(rootDir, declarations, provider) {
3792
3582
  await writeFileIfChanged(resolve(rootDir, rateLimitManifestPath), `${JSON.stringify(manifest, null, 2)}\n`);
3793
3583
  }
3794
3584
  //#endregion
3795
- //#region src/internal/provider-output.ts
3796
- function outputStateFile(rootDir) {
3797
- return resolve(rootDir, ".vitehub", "rate-limit", "cloudflare-output.json");
3798
- }
3799
- async function readOutputState(rootDir) {
3800
- try {
3801
- const parsed = JSON.parse(await readFile(outputStateFile(rootDir), "utf8"));
3802
- return {
3803
- bindings: Array.isArray(parsed.bindings) ? parsed.bindings.filter((value) => typeof value === "string") : [],
3804
- standalone: parsed.standalone !== false && Array.isArray(parsed.bindings) && parsed.bindings.length > 0
3805
- };
3806
- } catch (error) {
3807
- if (error.code === "ENOENT") return {
3808
- bindings: [],
3809
- standalone: false
3810
- };
3811
- throw error;
3812
- }
3813
- }
3814
- async function writeOutputState(rootDir, bindings, standalone = false) {
3815
- const file = outputStateFile(rootDir);
3816
- if (bindings.length === 0) {
3817
- await rm(file, { force: true });
3818
- return;
3819
- }
3820
- await mkdir(dirname(file), { recursive: true });
3821
- await writeFile(file, `${JSON.stringify({
3822
- bindings,
3823
- standalone
3824
- }, null, 2)}\n`, "utf8");
3825
- }
3585
+ //#region src/internal/cloudflare-bindings.ts
3826
3586
  function namespaceId(namespace, rateLimitId) {
3827
3587
  let hash = 2166136261;
3828
3588
  for (const character of `${namespace}:${rateLimitId}`) {
@@ -3834,9 +3594,9 @@ function namespaceId(namespace, rateLimitId) {
3834
3594
  function createCloudflareRateLimitBindings(declarations, namespace) {
3835
3595
  return declarations.map((declaration) => {
3836
3596
  const policy = normalizeRateLimitPolicy(declaration.policy);
3837
- if (policy.enforcement === "strict") throw new Error(`Rate Limit "${declaration.name}" requires strict enforcement, but Cloudflare's native Rate Limiting binding is best-effort.`);
3597
+ if (policy.enforcement === "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0015({ message: `Rate Limit "${declaration.name}" requires strict enforcement, but Cloudflare's native Rate Limiting binding is best-effort.` });
3838
3598
  const period = policy.windowMs / 1e3;
3839
- if (period !== 10 && period !== 60) throw new Error(`Rate Limit "${declaration.name}" uses ${policy.window}, but Cloudflare Rate Limiting supports only 10s and 1m windows.`);
3599
+ if (period !== 10 && period !== 60) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0016({ message: `Rate Limit "${declaration.name}" uses ${policy.window}, but Cloudflare Rate Limiting supports only 10s and 1m windows.` });
3840
3600
  return {
3841
3601
  name: getCloudflareRateLimitBindingName(declaration.name),
3842
3602
  namespace_id: namespaceId(namespace, declaration.name),
@@ -3847,178 +3607,137 @@ function createCloudflareRateLimitBindings(declarations, namespace) {
3847
3607
  };
3848
3608
  });
3849
3609
  }
3850
- function resolveRateLimitNamespace(configured) {
3851
- return configured?.trim() || void 0;
3852
- }
3853
- async function writeRateLimitProviderOutput(options) {
3854
- const state = await readOutputState(options.rootDir);
3855
- const currentBindings = options.declarations.map((declaration) => getCloudflareRateLimitBindingName(declaration.name));
3856
- const previousBindings = options.previousDeclarations?.map((declaration) => getCloudflareRateLimitBindingName(declaration.name)) ?? [];
3857
- const ownership = { arrays: { ratelimits: {
3858
- key: "name",
3859
- values: [...new Set([
3860
- ...state.bindings,
3861
- ...previousBindings,
3862
- ...currentBindings
3863
- ])]
3864
- } } };
3865
- if (options.cloudflareOwnedByNitro) {
3866
- if (options.provider === "cloudflare" && options.declarations.length > 0 && !options.namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
3867
- if (state.standalone && state.bindings.length > 0) await writeProviderDeploymentOutputs({
3868
- clientOutDir: options.clientOutDir,
3869
- cleanup: { cloudflare: {
3870
- outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
3871
- wranglerConfigOwnership: { arrays: { ratelimits: {
3872
- key: "name",
3873
- values: state.bindings
3874
- } } }
3875
- } },
3876
- rootDir: options.rootDir
3877
- });
3878
- await writeOutputState(options.rootDir, []);
3879
- await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
3880
- return;
3881
- }
3882
- if (options.provider === "cloudflare" && options.declarations.length > 0) {
3883
- if (!options.namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
3884
- await writeProviderDeploymentOutputs({
3885
- clientOutDir: options.clientOutDir,
3886
- cloudflare: {
3887
- outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
3888
- wranglerConfig: { ratelimits: createCloudflareRateLimitBindings(options.declarations, options.namespace) },
3889
- wranglerConfigOwnership: ownership
3890
- },
3891
- rootDir: options.rootDir
3892
- });
3893
- await writeOutputState(options.rootDir, currentBindings, true);
3894
- await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
3895
- return;
3896
- }
3897
- await writeProviderDeploymentOutputs({
3898
- clientOutDir: options.clientOutDir,
3899
- cleanup: { cloudflare: {
3900
- outputRoot: createDefaultCloudflareOutputRoot(options.rootDir),
3901
- wranglerConfigOwnership: ownership
3902
- } },
3903
- rootDir: options.rootDir
3904
- });
3905
- await writeOutputState(options.rootDir, []);
3906
- await writeRateLimitManifest(options.rootDir, options.declarations, options.provider);
3907
- }
3908
3610
  //#endregion
3909
3611
  //#region src/vite.ts
3910
3612
  const packageName = "@vite-hub/rate-limit";
3911
3613
  const pluginName = "@vite-hub/rate-limit/vite";
3912
3614
  const generatedNitroPlugin = ".vitehub/nitro/rate-limit/plugin.ts";
3913
- const legacyGeneratedNitroMiddleware = ".vitehub/nitro/rate-limit/middleware.ts";
3914
- const generatedRuntimeModule = ".vitehub/rate-limit/cloudflare-runtime.mjs";
3915
- const legacyGeneratedRegistry = ".vitehub/nitro/rate-limit/registry.mjs";
3916
- const mergeNoExternal = createNoExternalMerger(packageName);
3615
+ const mergeNoExternal = createNoExternalAddition(packageName);
3917
3616
  function cloneNitroConfig(value) {
3918
3617
  return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
3919
3618
  }
3920
- function mergeNitroConfig(config, value, declarations, namespace, provider, nitroCloudflare) {
3921
- const nitro = cloneNitroConfig(value);
3922
- const plugins = Array.isArray(nitro.plugins) ? [...nitro.plugins] : [];
3923
- if (!plugins.includes(generatedNitroPlugin)) plugins.unshift(generatedNitroPlugin);
3924
- const baseNitro = {
3925
- ...nitro,
3926
- plugins
3927
- };
3619
+ function mergeNitroConfig(config, value, declarations, namespace, provider, nitroCloudflare, projectRoot) {
3620
+ const providerOutput = useProviderOutputCatalog(config);
3621
+ const kit = createNitroServerKit(cloneNitroConfig(value));
3622
+ kit.addPlugin(resolve(projectRoot, generatedNitroPlugin), "start");
3623
+ const baseNitro = kit.config;
3928
3624
  if (!nitroCloudflare || provider !== "cloudflare" || declarations.length === 0) {
3929
- registerCloudflareProviderOutput(config, "rate-limit", {});
3930
- return composeNitroCloudflareProviderOutput(config, baseNitro);
3625
+ contributeCloudflareProviderOutput(providerOutput, { owner: "rate-limit" });
3626
+ return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
3931
3627
  }
3932
- if (!namespace) throw new Error("[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments.");
3933
- registerCloudflareProviderOutput(config, "rate-limit", { rateLimits: createCloudflareRateLimitBindings(declarations, namespace) });
3934
- return composeNitroCloudflareProviderOutput(config, baseNitro);
3628
+ if (!namespace) throw rateLimitErrorDiagnostics.RATE_LIMIT_B0001({ message: "[vitehub] Cloudflare Rate Limit requires rateLimit.namespace to isolate counters between deployments." });
3629
+ contributeCloudflareProviderOutput(providerOutput, {
3630
+ owner: "rate-limit",
3631
+ rateLimits: createCloudflareRateLimitBindings(declarations, namespace)
3632
+ });
3633
+ return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
3935
3634
  }
3936
- function renderRuntimeInstaller(runtimeConfig, importBase, nitro) {
3635
+ function renderRuntimeInstaller(runtimeConfig, importBase) {
3937
3636
  return [
3938
- ...nitro ? ["import { definePlugin } from 'nitro'"] : [],
3637
+ "import { definePlugin } from 'nitro'",
3939
3638
  `import { setRateLimitRuntimeConfig } from ${JSON.stringify(`${importBase}/runtime`)}`,
3940
3639
  "",
3941
3640
  `const config = ${JSON.stringify(runtimeConfig)}`,
3942
- ...nitro ? [
3943
- "export default definePlugin(() => {",
3944
- " setRateLimitRuntimeConfig(config)",
3945
- "})"
3946
- ] : ["setRateLimitRuntimeConfig(config)", "export default config"],
3641
+ "export default definePlugin(() => {",
3642
+ " setRateLimitRuntimeConfig(config)",
3643
+ "})",
3947
3644
  ""
3948
3645
  ].join("\n");
3949
3646
  }
3647
+ function resolveRateLimitNamespace(configured) {
3648
+ return configured?.trim() || void 0;
3649
+ }
3950
3650
  function resolveProvider(options, command, nitro, deferUnknown = false) {
3951
3651
  if (options.provider && options.provider !== "auto") return options.provider;
3952
3652
  if (command === "serve") return "memory";
3953
- const hosting = resolveNitroHosting(nitro);
3653
+ const hosting = getHostingProvider(resolveHost({ nitro }));
3954
3654
  if (hosting === "cloudflare") return "cloudflare";
3955
- if (hosting) throw new Error(`[vitehub] Rate Limit has no native ${hosting} driver. Configure a custom Rate Limiter instead of falling back to per-instance memory.`);
3655
+ if (hosting) throw rateLimitErrorDiagnostics.RATE_LIMIT_B0002({ message: `[vitehub] Rate Limit has no native ${hosting} driver. Configure a custom Rate Limiter instead of falling back to per-instance memory.` });
3956
3656
  if (deferUnknown) return;
3957
- throw new Error("[vitehub] Rate Limit provider cannot be inferred for a production build. Set rateLimit.provider to \"cloudflare\" or explicitly choose \"memory\" for a known single-process deployment.");
3958
- }
3959
- function resolveNitroHosting(nitro) {
3960
- const preset = cloneNitroConfig(nitro).preset;
3961
- return getHostingProvider(typeof preset === "string" ? preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING);
3657
+ throw rateLimitErrorDiagnostics.RATE_LIMIT_B0003({ message: "[vitehub] Rate Limit provider cannot be inferred for a production build. Set rateLimit.provider to \"cloudflare\" or explicitly choose \"memory\" for a known single-process deployment." });
3962
3658
  }
3963
3659
  function hubRateLimit(options = {}) {
3964
3660
  const importBase = options.importBase ?? packageName;
3965
3661
  let rateLimit = options;
3966
- let composedOutput;
3967
3662
  let declarations = [];
3968
- let declarationFiles = /* @__PURE__ */ new Set();
3969
- let cloudflareOwnedByNitro = false;
3970
- let previousDeclarations = [];
3663
+ let cloudflareBindings = false;
3971
3664
  let provider = "memory";
3972
3665
  let projectRoot;
3973
3666
  let resolved;
3974
3667
  const collectDeclarations = () => {
3975
3668
  if (!projectRoot) return;
3976
- const catalog = discoverRateLimitCatalog({
3669
+ declarations = discoverRateLimitCatalog({
3977
3670
  rootDir: projectRoot,
3978
3671
  scanDirs: rateLimit.scanDirs
3979
- });
3980
- declarations = catalog.declarations;
3981
- declarationFiles = catalog.declarationFiles;
3672
+ }).declarations;
3982
3673
  };
3983
3674
  const refreshDeclarations = async () => {
3984
3675
  if (!projectRoot || !resolved) return;
3985
3676
  collectDeclarations();
3986
- await writeRateLimitManifest(resolved.root, declarations, provider);
3677
+ await writeRateLimitManifest(projectRoot, declarations, provider);
3987
3678
  };
3679
+ const inspectionRoot = () => projectRoot ?? resolveViteHubProjectRoot(process.cwd(), { projectRoot: rateLimit.projectRoot });
3988
3680
  return {
3989
3681
  name: pluginName,
3990
- config(config, env) {
3991
- rateLimit = config.rateLimit ?? rateLimit;
3992
- const configuredNitro = config.nitro;
3993
- projectRoot = resolveViteHubProjectRoot(config.root || process.cwd(), { projectRoot: rateLimit.projectRoot });
3994
- const configuredProvider = resolveProvider(rateLimit, env?.command ?? "serve", configuredNitro, true);
3995
- if (configuredProvider) provider = configuredProvider;
3996
- collectDeclarations();
3997
- config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), configuredProvider, resolveNitroHosting(configuredNitro) === "cloudflare");
3682
+ enforce: "pre",
3683
+ vitehub: {
3684
+ operations: [{
3685
+ export: "rateLimitOperations",
3686
+ load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).rateLimitOperations,
3687
+ module: "@vite-hub/rate-limit/operations"
3688
+ }],
3689
+ cli: async () => {
3690
+ const { createRateLimitCliContributor } = await import(
3691
+ /* @vite-ignore */
3692
+ "./cli.js"
3693
+ );
3694
+ return createRateLimitCliContributor();
3695
+ },
3696
+ inspect: () => ({
3697
+ definitions: [{
3698
+ kind: "rate-limit",
3699
+ label: "Rate Limits",
3700
+ list: () => inspectRateLimitDefinitions({
3701
+ projectRoot: inspectionRoot(),
3702
+ rootDir: inspectionRoot(),
3703
+ scanDirs: rateLimit.scanDirs
3704
+ })
3705
+ }],
3706
+ providerOutput: [{
3707
+ description: "Rate Limit manifest with provider and capabilities",
3708
+ owner: "rate-limit",
3709
+ path: resolve(inspectionRoot(), ".vitehub/rate-limit/manifest.json")
3710
+ }]
3711
+ })
3712
+ },
3713
+ config: {
3714
+ order: "pre",
3715
+ handler(config, env) {
3716
+ rateLimit = config.rateLimit ?? rateLimit;
3717
+ const configuredNitro = config.nitro;
3718
+ projectRoot = resolveViteHubProjectRoot(config.root || process.cwd(), { projectRoot: rateLimit.projectRoot });
3719
+ const configuredProvider = resolveProvider(rateLimit, env?.command ?? "serve", configuredNitro, true);
3720
+ if (configuredProvider) provider = configuredProvider;
3721
+ collectDeclarations();
3722
+ config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), configuredProvider, resolveHost({ nitro: configuredNitro }) === "cloudflare", projectRoot);
3723
+ return installStandaloneOperationRpc(config, env?.command ?? "build", "@vite-hub/rate-limit/operations");
3724
+ }
3998
3725
  },
3999
3726
  async configResolved(config) {
4000
3727
  resolved = config;
4001
3728
  rateLimit = config.rateLimit ?? rateLimit;
4002
- composedOutput = useComposedProviderOutput(config);
4003
3729
  projectRoot = resolveViteHubProjectRoot(config.root, { projectRoot: rateLimit.projectRoot });
4004
3730
  const configuredNitro = config.nitro;
4005
- const nitroCloudflare = resolveNitroHosting(configuredNitro) === "cloudflare";
4006
- cloudflareOwnedByNitro = hasNitroConfigContext(config) && nitroCloudflare;
3731
+ const nitroCloudflare = resolveHost({ nitro: configuredNitro }) === "cloudflare";
4007
3732
  provider = resolveProvider(rateLimit, config.command, configuredNitro);
3733
+ cloudflareBindings = nitroCloudflare && provider === "cloudflare";
4008
3734
  collectDeclarations();
4009
- config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), provider, nitroCloudflare);
4010
- await writeRateLimitManifest(config.root, declarations, provider);
4011
- const pluginFile = resolve(config.root, generatedNitroPlugin);
4012
- const middlewareFile = resolve(config.root, legacyGeneratedNitroMiddleware);
4013
- const runtimeFile = resolve(config.root, generatedRuntimeModule);
4014
- const runtimeConfig = { provider };
4015
- await Promise.all([
4016
- rm(resolve(config.root, legacyGeneratedRegistry), { force: true }),
4017
- rm(middlewareFile, { force: true }),
4018
- writeFileIfChanged(pluginFile, renderRuntimeInstaller(runtimeConfig, importBase, true)),
4019
- writeFileIfChanged(runtimeFile, renderRuntimeInstaller(runtimeConfig, importBase, false))
4020
- ]);
4021
- registerProviderRuntimeModules(composedOutput, "rate-limit", { cloudflare: runtimeFile });
3735
+ config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), provider, nitroCloudflare, projectRoot);
3736
+ await writeRateLimitManifest(projectRoot, declarations, provider);
3737
+ await writeFileIfChanged(resolve(projectRoot, generatedNitroPlugin), renderRuntimeInstaller({ provider }, importBase));
3738
+ },
3739
+ configureServer(server) {
3740
+ publishStandaloneOperationServer(server);
4022
3741
  },
4023
3742
  configEnvironment(name, config) {
4024
3743
  if (!isServerEnvironment(name, config)) return;
@@ -4029,31 +3748,13 @@ function hubRateLimit(options = {}) {
4029
3748
  resolved = context.server.config;
4030
3749
  await refreshDeclarations();
4031
3750
  },
4032
- transform(code, id) {
4033
- if (provider !== "cloudflare" || !resolved?.build.ssr || !declarationFiles.has(id.split("?", 1)[0])) return;
4034
- return `import ${JSON.stringify(normalizePath(resolve(resolved.root, generatedRuntimeModule)))}\n${code}`;
4035
- },
4036
- async closeBundle() {
4037
- if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
4038
- if (cloudflareOwnedByNitro && provider === "cloudflare") {
4039
- const configuredDeclarations = declarations;
4040
- collectDeclarations();
4041
- if (JSON.stringify(declarations) !== JSON.stringify(configuredDeclarations)) throw new Error("[vitehub] Nitro Cloudflare Rate Limit declarations changed after config resolution. Generate Rate Limit source files before Vite config resolves.");
4042
- await writeRateLimitManifest(resolved.root, declarations, provider);
4043
- } else await refreshDeclarations();
4044
- const namespace = resolveRateLimitNamespace(rateLimit.namespace);
4045
- await writeRateLimitProviderOutput({
4046
- clientOutDir: resolved.build.outDir,
4047
- cloudflareOwnedByNitro,
4048
- declarations,
4049
- namespace,
4050
- previousDeclarations,
4051
- provider,
4052
- rootDir: resolved.root
4053
- });
4054
- previousDeclarations = declarations;
3751
+ buildEnd(error) {
3752
+ if (error || !cloudflareBindings || !resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
3753
+ const configuredDeclarations = declarations;
3754
+ collectDeclarations();
3755
+ if (JSON.stringify(declarations) !== JSON.stringify(configuredDeclarations)) throw rateLimitErrorDiagnostics.RATE_LIMIT_B0004({ message: "[vitehub] Nitro Cloudflare Rate Limit declarations changed after config resolution. Generate Rate Limit source files before Vite config resolves." });
4055
3756
  }
4056
3757
  };
4057
3758
  }
4058
3759
  //#endregion
4059
- export { hubRateLimit };
3760
+ export { discoverRateLimitDeclarations, hubRateLimit, inspectRateLimitDefinitions, rateLimitConsoleSection };