@vite-hub/queue 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +41 -23
  2. package/dist/client-CIc3jsj2.js +114 -0
  3. package/dist/cloudflare-client-COzQ8fHk.js +147 -0
  4. package/dist/{cloudflare-resource-name-R8zYQiZb.js → cloudflare-resource-name-CCuLDvSP.js} +3 -2
  5. package/dist/{cloudflare-vite-BlQfDVZD.js → cloudflare-vite-BCuJOXcT.js} +23 -9
  6. package/dist/{cloudflare-vite-nFPor46-.d.ts → cloudflare-vite-CjdP5yBN.d.ts} +9 -4
  7. package/dist/config-BINujLv4.js +74 -0
  8. package/dist/enqueue-CnQ0QR3O.js +22 -0
  9. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  10. package/dist/error-diagnostics-qzRF6IVB.js +109 -0
  11. package/dist/errors-DIFaM9tW.js +42 -0
  12. package/dist/handler-response-CBwIkmTS.js +56 -0
  13. package/dist/index.d.ts +32 -70
  14. package/dist/index.js +9 -8
  15. package/dist/inspect-PeuckaC3.js +30 -0
  16. package/dist/internal/runtime/cloudflare-client.d.ts +3 -5
  17. package/dist/internal/runtime/cloudflare-client.js +1 -1
  18. package/dist/internal/runtime/cloudflare-vite.d.ts +1 -1
  19. package/dist/internal/runtime/cloudflare-vite.js +1 -1
  20. package/dist/internal/runtime/state.d.ts +16 -15
  21. package/dist/internal/runtime/state.js +2 -2
  22. package/dist/internal/runtime/vercel-client.d.ts +3 -5
  23. package/dist/internal/runtime/vercel-client.js +93 -62
  24. package/dist/nuxt.d.ts +27 -7
  25. package/dist/nuxt.js +6 -2
  26. package/dist/object-B1NW521B.js +7 -0
  27. package/dist/operations-Cnjbz8kk.js +63 -0
  28. package/dist/operations-tNUdj3G4.d.ts +212 -0
  29. package/dist/operations.d.ts +32 -0
  30. package/dist/operations.js +1195 -0
  31. package/dist/runtime/hosted.d.ts +4 -6
  32. package/dist/runtime/hosted.js +30 -8
  33. package/dist/state-G9s378-e.js +184 -0
  34. package/dist/{types-CwvoMATy.d.ts → types-1GRMYES1.d.ts} +35 -24
  35. package/dist/vercel-region-cjskrOKl.js +122 -0
  36. package/dist/vite-ChWLzOVu.js +1512 -0
  37. package/dist/vite.d.ts +334 -34
  38. package/dist/vite.js +2 -2
  39. package/package.json +68 -25
  40. package/dist/_app-D29AwUdD.d.ts +0 -11
  41. package/dist/app-BZpq2cwC.js +0 -10
  42. package/dist/client-DG9fweET.js +0 -93
  43. package/dist/cloudflare-client-w5vphoNn.js +0 -99
  44. package/dist/config-CNgAeIND.js +0 -53
  45. package/dist/delivery-error-glgYWC9g.js +0 -45
  46. package/dist/errors-CjuG_qr-.js +0 -108
  47. package/dist/internal/runtime/vercel-vite.d.ts +0 -20
  48. package/dist/internal/runtime/vercel-vite.js +0 -49
  49. package/dist/state-Cno9O7YS.js +0 -110
  50. package/dist/vercel-runtime-package-copy-CEToJtCu.js +0 -116
  51. package/dist/vite-DOuoen0w.js +0 -4414
@@ -0,0 +1,1512 @@
1
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-A_8Kp-48.js";
2
+ import { i as resolveHostPreset, n as getHostingProvider, r as resolveHost, t as normalizeQueueOptions } from "./config-BINujLv4.js";
3
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-qzRF6IVB.js";
4
+ import { t as getCloudflareQueueBindingName } from "./cloudflare-GosJefIK.js";
5
+ import { t as getCloudflareQueueName } from "./cloudflare-resource-name-CCuLDvSP.js";
6
+ import { t as getVercelQueueTopicName } from "./vercel-C_4vqxcl.js";
7
+ import { n as summarizeDefinitions } from "./inspect-PeuckaC3.js";
8
+ import { createRequire } from "node:module";
9
+ import { Diagnostic } from "nostics";
10
+ import { basename, dirname, parse, resolve } from "node:path";
11
+ import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { mkdir, rm, writeFile } from "node:fs/promises";
14
+ import { basename as basename$1, dirname as dirname$1, relative, resolve as resolve$1 } from "pathe";
15
+ import { fileURLToPath } from "node:url";
16
+ import "esbuild";
17
+ //#region ../internal/src/build/vite.ts
18
+ const projectRootDirectoryMarkers = [
19
+ ["server", "agents"],
20
+ ["server", "channels"],
21
+ ["server", "connections"],
22
+ ["server", "browsers"],
23
+ ["server", "emails"],
24
+ ["server", "schedules"],
25
+ ["server", "workspaces"]
26
+ ];
27
+ const projectRootFileMarkers = [
28
+ ["package.json"],
29
+ ["nuxt.config.ts"],
30
+ ["nuxt.config.mts"],
31
+ ["nuxt.config.js"],
32
+ ["nuxt.config.mjs"]
33
+ ];
34
+ function createNoExternalAddition(...packageNames) {
35
+ return (current) => {
36
+ if (current === true) return;
37
+ const values = Array.isArray(current) ? current : [current];
38
+ const missing = packageNames.filter((packageName) => !values.includes(packageName));
39
+ return missing.length ? missing : void 0;
40
+ };
41
+ }
42
+ function isServerEnvironment(name, config) {
43
+ return name === "ssr" || config.consumer === "server";
44
+ }
45
+ /**
46
+ * Lists the server directory of the application and of each Nuxt layer it extends.
47
+ * The application comes first. Layers follow in Nuxt priority order, like Nuxt's own Nitro scan directories.
48
+ */
49
+ function resolveNuxtServerDirs(options) {
50
+ const appRoot = options.rootDir ? resolve(options.rootDir) : void 0;
51
+ let appDirectory = options.serverDir ? resolve(options.serverDir) : void 0;
52
+ const layerDirectories = [];
53
+ for (const layer of options._layers ?? []) {
54
+ const root = layer.config?.rootDir ?? layer.cwd;
55
+ const isApp = Boolean(root && appRoot && resolve(root) === appRoot);
56
+ if (isApp && appDirectory) continue;
57
+ const config = isApp ? options : layer.config ?? {};
58
+ const sourceDir = config.srcDir ?? layer.cwd ?? root;
59
+ if (!sourceDir) continue;
60
+ const directory = resolve(sourceDir, config.serverDir ?? "server");
61
+ if (isApp) appDirectory = directory;
62
+ else layerDirectories.push(directory);
63
+ }
64
+ if (!appDirectory && layerDirectories.length && appRoot) appDirectory = resolve(appRoot, "server");
65
+ const directories = [.../* @__PURE__ */ new Set([...appDirectory ? [appDirectory] : [], ...layerDirectories])];
66
+ return directories.length ? directories : void 0;
67
+ }
68
+ function includesNitroVitePlugin(value) {
69
+ if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
70
+ if (!value || typeof value !== "object") return false;
71
+ return "name" in value && value.name === "nitro:main";
72
+ }
73
+ function hasNitroConfigContext(config) {
74
+ return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
75
+ }
76
+ function shouldSkipViteProviderBuild(command, mode) {
77
+ return command === "serve" || mode === "e2e";
78
+ }
79
+ function resolveViteHubProjectRoot(root, options = {}) {
80
+ const resolvedRoot = resolve(root);
81
+ const temporaryRoot = resolve(tmpdir());
82
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
83
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
84
+ if (basename(resolvedRoot) === "app") {
85
+ const parent = dirname(resolvedRoot);
86
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
87
+ "nuxt.config.ts",
88
+ "nuxt.config.mts",
89
+ "nuxt.config.js",
90
+ "nuxt.config.mjs"
91
+ ]))) return parent;
92
+ }
93
+ let current = resolvedRoot;
94
+ while (true) {
95
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
96
+ if (hasProjectRootMarker(current)) return current;
97
+ const parent = dirname(current);
98
+ if (parent === current) return resolvedRoot;
99
+ current = parent;
100
+ }
101
+ }
102
+ function hasProjectRootDirectoryMarker(root) {
103
+ for (const marker of projectRootDirectoryMarkers) try {
104
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
105
+ } catch (error) {
106
+ if (error.code !== "ENOENT") throw error;
107
+ }
108
+ return false;
109
+ }
110
+ function hasProjectRootMarker(root) {
111
+ if (hasProjectRootDirectoryMarker(root)) return true;
112
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
113
+ }
114
+ function hasProjectRootFileMarker(root, markers) {
115
+ for (const marker of markers) {
116
+ const path = Array.isArray(marker) ? marker : [marker];
117
+ try {
118
+ if (statSync(resolve(root, ...path)).isFile()) return true;
119
+ } catch (error) {
120
+ if (error.code !== "ENOENT") throw error;
121
+ }
122
+ }
123
+ return false;
124
+ }
125
+ const VITEHUB_MODES = {
126
+ e2e: "e2e",
127
+ blob: "blob",
128
+ chat: "chat",
129
+ db: "db",
130
+ env: "env",
131
+ kv: "kv",
132
+ queue: "queue",
133
+ schedule: "schedule",
134
+ sandbox: "sandbox",
135
+ workspace: "workspace",
136
+ workflow: "workflow"
137
+ };
138
+ function isViteCli(argv) {
139
+ return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
140
+ }
141
+ function getViteCliMode(argv = process.argv) {
142
+ if (!isViteCli(argv)) return;
143
+ const modes = new Set(Object.values(VITEHUB_MODES));
144
+ for (let index = 0; index < argv.length; index += 1) {
145
+ const arg = argv[index];
146
+ const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
147
+ if (mode && modes.has(mode)) return mode;
148
+ }
149
+ }
150
+ function getViteMode(env = process.env) {
151
+ return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
152
+ }
153
+ //#endregion
154
+ //#region ../internal/src/build/provider-output-config.ts
155
+ function isProviderJsonArray(value, ancestors) {
156
+ if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
157
+ if (Reflect.ownKeys(value).length !== value.length + 1) return false;
158
+ ancestors.add(value);
159
+ try {
160
+ for (let index = 0; index < value.length; index++) {
161
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
162
+ if (!descriptor?.enumerable || !("value" in descriptor) || !isProviderJsonValue(descriptor.value, ancestors)) return false;
163
+ }
164
+ return true;
165
+ } finally {
166
+ ancestors.delete(value);
167
+ }
168
+ }
169
+ function isProviderJsonRecordValue(value, ancestors) {
170
+ const prototype = Object.getPrototypeOf(value);
171
+ if (prototype !== Object.prototype && prototype !== null || ancestors.has(value)) return false;
172
+ ancestors.add(value);
173
+ try {
174
+ return Reflect.ownKeys(value).every((key) => {
175
+ if (typeof key !== "string") return false;
176
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
177
+ return descriptor?.enumerable === true && "value" in descriptor && isProviderJsonValue(descriptor.value, ancestors);
178
+ });
179
+ } finally {
180
+ ancestors.delete(value);
181
+ }
182
+ }
183
+ function isProviderJsonValue(value, ancestors) {
184
+ if (value === null || typeof value === "boolean" || typeof value === "string") return true;
185
+ if (typeof value === "number") return Number.isFinite(value);
186
+ if (Array.isArray(value)) return isProviderJsonArray(value, ancestors);
187
+ return typeof value === "object" && isProviderJsonRecordValue(value, ancestors);
188
+ }
189
+ function isProviderJsonRecord(value) {
190
+ try {
191
+ return typeof value === "object" && value !== null && !Array.isArray(value) && isProviderJsonRecordValue(value, /* @__PURE__ */ new Set());
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+ function assertProviderJsonRecord(value) {
197
+ if (!isProviderJsonRecord(value)) throw internalErrorDiagnostics.INTERNAL_B0043({ message: "[vitehub] Provider output config must be a JSON object." });
198
+ }
199
+ function deleteOwnedFields(value, ownership, cleanup = false) {
200
+ const next = { ...value };
201
+ for (const key of ownership.keys ?? []) delete next[key];
202
+ for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) if (!cleanup || !arrayOwnership.preserveOnCleanup) delete next[field];
203
+ return next;
204
+ }
205
+ function getKeyedArrayEntryValue(value, key) {
206
+ if (key === void 0) return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string" ? value : void 0;
207
+ if (!isProviderJsonRecord(value)) return;
208
+ const entryValue = value[key];
209
+ return entryValue === null || typeof entryValue === "boolean" || typeof entryValue === "number" || typeof entryValue === "string" ? entryValue : void 0;
210
+ }
211
+ function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
212
+ const current = Array.isArray(value) ? value : [];
213
+ const replacementKeys = replacements.flatMap((entry) => {
214
+ const key = getKeyedArrayEntryValue(entry, ownership.key);
215
+ return key === void 0 ? [] : [key];
216
+ });
217
+ const ownedKeys = /* @__PURE__ */ new Set([...ownership.values ?? [], ...replacementKeys]);
218
+ return current.filter((entry) => {
219
+ const key = getKeyedArrayEntryValue(entry, ownership.key);
220
+ return key === void 0 || !ownedKeys.has(key);
221
+ });
222
+ }
223
+ function mergeOwnedArrays(existing, value, arrays) {
224
+ const next = { ...value };
225
+ for (const [field, ownership] of Object.entries(arrays ?? {})) {
226
+ const incoming = Array.isArray(value[field]) ? value[field] : [];
227
+ const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
228
+ if (merged.length) next[field] = merged;
229
+ else delete next[field];
230
+ }
231
+ return next;
232
+ }
233
+ function mergeProviderOutputConfig(existing, value, ownership = {}) {
234
+ assertProviderJsonRecord(existing);
235
+ assertProviderJsonRecord(value);
236
+ return {
237
+ ...deleteOwnedFields(existing, ownership),
238
+ ...mergeOwnedArrays(existing, value, ownership.arrays)
239
+ };
240
+ }
241
+ //#endregion
242
+ //#region ../internal/src/build/esbuild.ts
243
+ /** Select the runtime constants from one resolved Vite configuration. */
244
+ function resolveViteHubBundleDefines(config) {
245
+ const defines = {};
246
+ for (const name of ["__VITEHUB_PUBLIC_URL__", "__VITEHUB_APP_BASE_URL__"]) {
247
+ const value = config.define?.[name];
248
+ if (typeof value === "string") defines[name] = value;
249
+ }
250
+ return defines;
251
+ }
252
+ //#endregion
253
+ //#region ../internal/src/build/paths.ts
254
+ function generatedDirSegments(productName) {
255
+ return [".vitehub", productName];
256
+ }
257
+ function ensureGeneratedDir(rootDir, productName) {
258
+ return resolve$1(rootDir, ...generatedDirSegments(productName));
259
+ }
260
+ function computePackageDir(importMetaUrl) {
261
+ const currentFileDir = dirname$1(fileURLToPath(importMetaUrl));
262
+ return resolve$1(currentFileDir, basename$1(currentFileDir) === "internal" ? "../.." : "..");
263
+ }
264
+ function resolveRuntimeModule$1(packageDir, modulePath) {
265
+ const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
266
+ return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
267
+ }
268
+ function createImportPath(fromFile, targetFile) {
269
+ const fromDir = realpathIfExists(dirname$1(fromFile));
270
+ const target = realpathIfExists(targetFile);
271
+ const importPath = relative(fromDir, target);
272
+ return importPath.startsWith(".") ? importPath : `./${importPath}`;
273
+ }
274
+ function realpathIfExists(path) {
275
+ try {
276
+ return realpathSync.native(path);
277
+ } catch {
278
+ return resolve$1(path);
279
+ }
280
+ }
281
+ //#endregion
282
+ //#region ../internal/src/build/cloudflare-provider-output.ts
283
+ function isDeepStrictEqual(left, right) {
284
+ if (Object.is(left, right)) return true;
285
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
286
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
287
+ if (Array.isArray(left)) return left.length === right.length && left.every((value, index) => isDeepStrictEqual(value, right[index]));
288
+ const leftRecord = left;
289
+ const rightRecord = right;
290
+ const leftKeys = Object.keys(leftRecord);
291
+ const rightKeys = Object.keys(rightRecord);
292
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.hasOwn(rightRecord, key) && isDeepStrictEqual(leftRecord[key], rightRecord[key]));
293
+ }
294
+ const providerOutputCatalogRegistry$1 = globalThis;
295
+ const providerOutputCatalogByNitroValue = providerOutputCatalogRegistry$1.__vitehubProviderOutputCatalogsByNitroValue ??= /* @__PURE__ */ new WeakMap();
296
+ function cloneRecord(value) {
297
+ return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
298
+ }
299
+ function cloneProviderRecord(value) {
300
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
301
+ return Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => typeof entry === "undefined" ? [] : [[key, cloneProviderValue(entry)]]));
302
+ }
303
+ function cloneProviderValue(value) {
304
+ if (Array.isArray(value)) return value.map((entry) => typeof entry === "undefined" ? null : cloneProviderValue(entry));
305
+ if (value && typeof value === "object") return cloneProviderRecord(value);
306
+ return value;
307
+ }
308
+ function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner) {
309
+ const current = Array.isArray(existing) ? existing.map(cloneProviderRecord) : [];
310
+ return (incoming ?? []).filter((entry) => {
311
+ const identity = entry[identityKey];
312
+ const match = current.find((candidate) => candidate[identityKey] === identity);
313
+ if (!match) {
314
+ current.push(entry);
315
+ return true;
316
+ }
317
+ 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.` });
318
+ return false;
319
+ });
320
+ }
321
+ function removeEntries(existing, entries) {
322
+ if (!Array.isArray(existing) || !entries?.length) return Array.isArray(existing) ? existing : [];
323
+ return existing.filter((entry) => !entries.some((previous) => isDeepStrictEqual(entry, previous)));
324
+ }
325
+ function removeContribution(wrangler, contribution) {
326
+ const queues = cloneProviderRecord(wrangler.queues);
327
+ const secrets = cloneProviderRecord(wrangler.secrets);
328
+ const environments = cloneProviderRecord(wrangler.env);
329
+ const hasQueues = Boolean(contribution.queues?.consumers?.length || contribution.queues?.producers?.length);
330
+ const hasSecrets = Boolean(contribution.requiredSecrets?.length || Object.keys(contribution.requiredSecretsByEnvironment ?? {}).length);
331
+ if (contribution.queues?.consumers?.length) {
332
+ const consumers = removeEntries(queues.consumers, contribution.queues.consumers);
333
+ if (consumers.length) queues.consumers = consumers;
334
+ else delete queues.consumers;
335
+ }
336
+ if (contribution.queues?.producers?.length) {
337
+ const producers = removeEntries(queues.producers, contribution.queues.producers);
338
+ if (producers.length) queues.producers = producers;
339
+ else delete queues.producers;
340
+ }
341
+ if (contribution.requiredSecrets?.length) {
342
+ const required = removeEntries(secrets.required, contribution.requiredSecrets);
343
+ if (required.length) secrets.required = required;
344
+ else delete secrets.required;
345
+ }
346
+ for (const [name, requiredSecrets] of Object.entries(contribution.requiredSecretsByEnvironment ?? {})) {
347
+ if (!Object.hasOwn(environments, name)) continue;
348
+ const environment = cloneProviderRecord(environments[name]);
349
+ const environmentSecrets = cloneProviderRecord(environment.secrets);
350
+ const required = removeEntries(environmentSecrets.required, requiredSecrets);
351
+ if (required.length) environmentSecrets.required = required;
352
+ else delete environmentSecrets.required;
353
+ if (Object.keys(environmentSecrets).length) environment.secrets = environmentSecrets;
354
+ else delete environment.secrets;
355
+ environments[name] = environment;
356
+ }
357
+ const withoutOwned = { ...wrangler };
358
+ if (hasQueues) delete withoutOwned.queues;
359
+ if (hasSecrets) delete withoutOwned.secrets;
360
+ if (hasSecrets) delete withoutOwned.env;
361
+ return {
362
+ ...withoutOwned,
363
+ ...hasQueues && Object.keys(queues).length ? { queues } : {},
364
+ ...hasSecrets && Object.keys(secrets).length ? { secrets } : {},
365
+ ...hasSecrets && Object.keys(environments).length ? { env: environments } : {},
366
+ ...contribution.r2Buckets?.length ? { r2_buckets: removeEntries(wrangler.r2_buckets, contribution.r2Buckets) } : {},
367
+ ...contribution.rateLimits?.length ? { ratelimits: removeEntries(wrangler.ratelimits, contribution.rateLimits) } : {}
368
+ };
369
+ }
370
+ function mergeContribution(wrangler, owner, contribution) {
371
+ const queues = cloneProviderRecord(wrangler.queues);
372
+ const secrets = cloneProviderRecord(wrangler.secrets);
373
+ const environments = cloneProviderRecord(wrangler.env);
374
+ const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner);
375
+ const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
376
+ const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name", "jurisdiction"], owner);
377
+ const rateLimits = compatibleEntries(wrangler.ratelimits, contribution.rateLimits, "name", ["namespace_id", "simple"], owner);
378
+ const currentRequiredSecrets = Array.isArray(secrets.required) ? secrets.required : [];
379
+ const requiredSecrets = (contribution.requiredSecrets ?? []).filter((name) => !currentRequiredSecrets.includes(name));
380
+ if (requiredSecrets.length) secrets.required = [...currentRequiredSecrets, ...requiredSecrets];
381
+ const requiredSecretsByEnvironment = {};
382
+ for (const [name, value] of Object.entries(environments)) {
383
+ const environment = cloneProviderRecord(value);
384
+ const environmentSecrets = cloneProviderRecord(environment.secrets);
385
+ const current = Array.isArray(environmentSecrets.required) ? environmentSecrets.required : [];
386
+ const required = (contribution.requiredSecrets ?? []).filter((secret) => !current.includes(secret));
387
+ if (required.length) {
388
+ environmentSecrets.required = [...current, ...required];
389
+ environment.secrets = environmentSecrets;
390
+ environments[name] = environment;
391
+ requiredSecretsByEnvironment[name] = required;
392
+ }
393
+ }
394
+ const nextQueues = mergeProviderOutputConfig(queues, {
395
+ ...consumers.length ? { consumers } : {},
396
+ ...producers.length ? { producers } : {}
397
+ }, { arrays: {
398
+ consumers: { key: "queue" },
399
+ producers: { key: "binding" }
400
+ } });
401
+ return [mergeProviderOutputConfig(wrangler, {
402
+ ...Object.keys(nextQueues).length ? { queues: nextQueues } : {},
403
+ ...r2Buckets.length ? { r2_buckets: r2Buckets } : {},
404
+ ...rateLimits.length ? { ratelimits: rateLimits } : {},
405
+ ...Object.keys(secrets).length ? { secrets } : {},
406
+ ...Object.keys(environments).length ? { env: environments } : {}
407
+ }, { arrays: {
408
+ r2_buckets: { key: "binding" },
409
+ ratelimits: { key: "name" }
410
+ } }), {
411
+ queues: {
412
+ consumers,
413
+ producers
414
+ },
415
+ r2Buckets,
416
+ rateLimits,
417
+ requiredSecrets,
418
+ requiredSecretsByEnvironment
419
+ }];
420
+ }
421
+ function inheritedProviderOutputCatalog(value) {
422
+ if (!value || typeof value !== "object") return;
423
+ const cloudflare = value.cloudflare;
424
+ const wrangler = cloudflare && typeof cloudflare === "object" ? cloudflare.wrangler : void 0;
425
+ return providerOutputCatalogByNitroValue.get(value) ?? (cloudflare && typeof cloudflare === "object" ? providerOutputCatalogByNitroValue.get(cloudflare) : void 0) ?? (wrangler && typeof wrangler === "object" ? providerOutputCatalogByNitroValue.get(wrangler) : void 0);
426
+ }
427
+ function associateProviderOutputCatalog(output, catalog) {
428
+ providerOutputCatalogByNitroValue.set(output, catalog);
429
+ const cloudflare = output.cloudflare;
430
+ if (!cloudflare || typeof cloudflare !== "object") return;
431
+ providerOutputCatalogByNitroValue.set(cloudflare, catalog);
432
+ const wrangler = cloudflare.wrangler;
433
+ if (wrangler && typeof wrangler === "object") providerOutputCatalogByNitroValue.set(wrangler, catalog);
434
+ }
435
+ function composeNitroCloudflareProviderOutput(catalog, value, inheritedValue = value) {
436
+ const nitro = cloneRecord(value);
437
+ const cloudflare = cloneRecord(nitro.cloudflare);
438
+ const inherited = inheritedProviderOutputCatalog(inheritedValue) ?? inheritedProviderOutputCatalog(value);
439
+ if (inherited && inherited !== catalog) catalog.inheritCloudflareContributions(inherited);
440
+ let wrangler = cloneProviderRecord(cloudflare.wrangler);
441
+ for (const contribution of catalog.appliedCloudflareContributions()) wrangler = removeContribution(wrangler, contribution);
442
+ catalog.clearAppliedCloudflareContributions();
443
+ for (const [owner, contribution] of catalog.cloudflareContributions()) {
444
+ const [merged, applied] = mergeContribution(wrangler, owner, contribution);
445
+ wrangler = merged;
446
+ catalog.replaceAppliedCloudflareContribution(owner, applied);
447
+ }
448
+ const output = !Object.keys(cloudflare).length && !Object.keys(wrangler).length ? nitro : {
449
+ ...nitro,
450
+ cloudflare: {
451
+ ...cloudflare,
452
+ wrangler
453
+ }
454
+ };
455
+ associateProviderOutputCatalog(output, catalog);
456
+ return output;
457
+ }
458
+ //#endregion
459
+ //#region ../internal/src/build/provider-output-catalog.ts
460
+ var ProviderOutputCatalog = class {
461
+ bundleDefines = {};
462
+ #appliedCloudflareContributions = /* @__PURE__ */ new Map();
463
+ #cloudflareContributions = /* @__PURE__ */ new Map();
464
+ #runtimeContributions = /* @__PURE__ */ new Map();
465
+ #runtimeContributionsByGeneration = /* @__PURE__ */ new WeakMap();
466
+ #deploymentContributionSequence = 0;
467
+ #deploymentContributions = /* @__PURE__ */ new Map();
468
+ #deploymentGenerationRefs = /* @__PURE__ */ new WeakMap();
469
+ #deploymentGenerations = /* @__PURE__ */ new Set();
470
+ #pendingDeploymentDiscards = [];
471
+ #takenDeploymentContributions = /* @__PURE__ */ new Map();
472
+ appliedCloudflareContributions() {
473
+ return this.#appliedCloudflareContributions.values();
474
+ }
475
+ appliedCloudflareContributionEntries() {
476
+ return this.#appliedCloudflareContributions.entries();
477
+ }
478
+ clearAppliedCloudflareContributions() {
479
+ this.#appliedCloudflareContributions.clear();
480
+ }
481
+ cloudflareContributions() {
482
+ return this.#cloudflareContributions.entries();
483
+ }
484
+ inheritCloudflareContributions(catalog) {
485
+ for (const [owner, contribution] of catalog.appliedCloudflareContributionEntries()) this.#appliedCloudflareContributions.set(owner, contribution);
486
+ for (const [owner, contribution] of [...catalog.cloudflareContributions(), ...this.#cloudflareContributions]) this.#cloudflareContributions.set(owner, contribution);
487
+ }
488
+ replaceAppliedCloudflareContribution(owner, contribution) {
489
+ this.#appliedCloudflareContributions.set(owner, contribution);
490
+ }
491
+ replaceCloudflareContribution(owner, contribution) {
492
+ this.#cloudflareContributions.set(owner, contribution);
493
+ }
494
+ replaceRuntimeContribution(contribution, generation) {
495
+ if (!generation) {
496
+ this.#runtimeContributions.set(contribution.owner, contribution);
497
+ return;
498
+ }
499
+ let contributions = this.#runtimeContributionsByGeneration.get(generation);
500
+ if (!contributions) {
501
+ contributions = /* @__PURE__ */ new Map();
502
+ this.#runtimeContributionsByGeneration.set(generation, contributions);
503
+ }
504
+ contributions.set(contribution.owner, contribution);
505
+ }
506
+ runtimeContribution(product, generation) {
507
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.get(product);
508
+ }
509
+ runtimeContributions(generation) {
510
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.entries() ?? (/* @__PURE__ */ new Map()).entries();
511
+ }
512
+ resetRuntimeContributions(generation, owner) {
513
+ if (generation) {
514
+ if (owner) this.#runtimeContributionsByGeneration.get(generation)?.delete(owner);
515
+ else this.#runtimeContributionsByGeneration.delete(generation);
516
+ return;
517
+ }
518
+ if (owner) this.#runtimeContributions.delete(owner);
519
+ else this.#runtimeContributions.clear();
520
+ }
521
+ resetRuntimeContribution(product, generation) {
522
+ if (!generation) {
523
+ this.#runtimeContributions.delete(product);
524
+ return;
525
+ }
526
+ this.#runtimeContributionsByGeneration.get(generation)?.delete(product);
527
+ }
528
+ createDeploymentGeneration() {
529
+ const generation = { valid: true };
530
+ this.#trackDeploymentGeneration(generation);
531
+ return generation;
532
+ }
533
+ replaceDeploymentContribution(contribution, generation) {
534
+ const entry = {
535
+ contribution,
536
+ generation,
537
+ sequence: this.#deploymentContributionSequence++
538
+ };
539
+ if (generation && !generation.valid) {
540
+ this.#queueDeploymentDiscard(entry);
541
+ return;
542
+ }
543
+ this.#restoreDeploymentContribution(entry);
544
+ }
545
+ resetDeploymentContributions(generation) {
546
+ if (!generation) {
547
+ for (const reference of this.#deploymentGenerations) {
548
+ const current = reference.deref();
549
+ if (current) current.valid = false;
550
+ }
551
+ this.#deploymentGenerations.clear();
552
+ for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
553
+ for (const taken of this.#takenDeploymentContributions.values()) {
554
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
555
+ for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
556
+ }
557
+ this.#deploymentContributions.clear();
558
+ this.#takenDeploymentContributions.clear();
559
+ return;
560
+ }
561
+ generation.valid = false;
562
+ this.#deleteDeploymentGeneration(generation);
563
+ for (const [owner, entries] of this.#deploymentContributions) {
564
+ for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
565
+ const remaining = entries.filter((entry) => entry.generation !== generation);
566
+ if (remaining.length) this.#deploymentContributions.set(owner, remaining);
567
+ else this.#deploymentContributions.delete(owner);
568
+ }
569
+ for (const [contribution, taken] of this.#takenDeploymentContributions) {
570
+ const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
571
+ taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
572
+ for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
573
+ if (taken.entry.generation !== generation) continue;
574
+ this.#takenDeploymentContributions.delete(contribution);
575
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
576
+ for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
577
+ else this.#restoreDeploymentContribution(fallback);
578
+ }
579
+ }
580
+ hasDeploymentContributions() {
581
+ return this.#deploymentContributions.size > 0;
582
+ }
583
+ takeDeploymentContributions() {
584
+ const contributions = [];
585
+ for (const [owner, entries] of this.#deploymentContributions) {
586
+ const entry = entries.at(-1);
587
+ contributions.push(entry.contribution);
588
+ this.#takenDeploymentContributions.set(entry.contribution, {
589
+ committed: false,
590
+ entry,
591
+ entryDiscarded: false,
592
+ fallbacks: entries.slice(0, -1)
593
+ });
594
+ this.#deploymentContributions.delete(owner);
595
+ }
596
+ return contributions;
597
+ }
598
+ deploymentContributionGeneration(contribution) {
599
+ return this.#takenDeploymentContributions.get(contribution)?.entry.generation;
600
+ }
601
+ commitDeploymentContributions(contributions) {
602
+ for (const contribution of contributions) {
603
+ const taken = this.#takenDeploymentContributions.get(contribution);
604
+ if (taken) taken.committed = true;
605
+ }
606
+ }
607
+ async prepareDeploymentContributions(contributions) {
608
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
609
+ for (const contribution of contributions) {
610
+ const taken = this.#takenDeploymentContributions.get(contribution);
611
+ if (!taken || taken.entryDiscarded || !taken.entry.contribution.discard) continue;
612
+ taken.entryDiscarded = true;
613
+ discarded.push(Promise.resolve().then(taken.entry.contribution.discard));
614
+ }
615
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
616
+ if (failure) throw failure.reason;
617
+ }
618
+ async completeDeploymentContributions(contributions) {
619
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
620
+ const completedGenerations = /* @__PURE__ */ new Set();
621
+ for (const contribution of contributions) {
622
+ const taken = this.#takenDeploymentContributions.get(contribution);
623
+ if (!taken) continue;
624
+ this.#takenDeploymentContributions.delete(contribution);
625
+ const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
626
+ for (const entry of entries) {
627
+ if (entry.generation) completedGenerations.add(entry.generation);
628
+ if (entry.contribution.discard) discarded.push(entry.contribution.discard());
629
+ }
630
+ }
631
+ for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
632
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
633
+ if (failure) throw failure.reason;
634
+ }
635
+ rollbackDeploymentContributions(contributions) {
636
+ for (const contribution of contributions) {
637
+ const taken = this.#takenDeploymentContributions.get(contribution);
638
+ if (!taken) continue;
639
+ this.#takenDeploymentContributions.delete(contribution);
640
+ for (const entry of [...taken.fallbacks, taken.entry]) this.#restoreDeploymentContribution(entry);
641
+ }
642
+ }
643
+ #restoreDeploymentContribution(entry) {
644
+ if (entry.generation && !entry.generation.valid) return;
645
+ if (entry.generation) this.#trackDeploymentGeneration(entry.generation);
646
+ const entries = this.#deploymentContributions.get(entry.contribution.owner) ?? [];
647
+ const replaced = entries.findIndex((candidate) => candidate.generation === entry.generation);
648
+ if (replaced >= 0) {
649
+ if (entries[replaced].sequence > entry.sequence) return;
650
+ entries.splice(replaced, 1);
651
+ }
652
+ entries.push(entry);
653
+ entries.sort((left, right) => left.sequence - right.sequence);
654
+ this.#deploymentContributions.set(entry.contribution.owner, entries);
655
+ }
656
+ #retireDeploymentGeneration(generation) {
657
+ const pending = [...this.#deploymentContributions.values()].some((entries) => entries.some((entry) => entry.generation === generation));
658
+ const taken = [...this.#takenDeploymentContributions.values()].some((entry) => entry.entry.generation === generation || entry.fallbacks.some((fallback) => fallback.generation === generation));
659
+ if (!pending && !taken) this.#deleteDeploymentGeneration(generation);
660
+ }
661
+ #trackDeploymentGeneration(generation) {
662
+ if (this.#deploymentGenerationRefs.has(generation)) return;
663
+ const reference = new WeakRef(generation);
664
+ this.#deploymentGenerationRefs.set(generation, reference);
665
+ this.#deploymentGenerations.add(reference);
666
+ }
667
+ #deleteDeploymentGeneration(generation) {
668
+ const reference = this.#deploymentGenerationRefs.get(generation);
669
+ if (reference) this.#deploymentGenerations.delete(reference);
670
+ this.#deploymentGenerationRefs.delete(generation);
671
+ }
672
+ #queueDeploymentDiscard(entry) {
673
+ if (!entry.contribution.discard) return;
674
+ const discard = Promise.resolve().then(entry.contribution.discard);
675
+ discard.catch(() => {});
676
+ this.#pendingDeploymentDiscards.push(discard);
677
+ }
678
+ };
679
+ const providerOutputCatalogRegistry = globalThis;
680
+ const providerOutputCatalogs = providerOutputCatalogRegistry.__vitehubProviderOutputCatalogs ??= /* @__PURE__ */ new WeakMap();
681
+ const providerOutputCatalog = Symbol.for("vitehub.provider-output-catalog");
682
+ function createProviderOutputCatalog() {
683
+ return new ProviderOutputCatalog();
684
+ }
685
+ function useProviderOutputCatalog(config) {
686
+ const owner = config;
687
+ let catalog = owner[providerOutputCatalog] ?? providerOutputCatalogs.get(config);
688
+ if (!catalog) catalog = createProviderOutputCatalog();
689
+ catalog.bundleDefines = resolveViteHubBundleDefines(config);
690
+ owner[providerOutputCatalog] = catalog;
691
+ providerOutputCatalogs.set(config, catalog);
692
+ return catalog;
693
+ }
694
+ function contributeCloudflareProviderOutput(catalog, contribution) {
695
+ const { owner, ...value } = contribution;
696
+ catalog.replaceCloudflareContribution(owner, value);
697
+ }
698
+ //#endregion
699
+ //#region ../internal/src/nitro-kit.ts
700
+ function cloneArray(value) {
701
+ return Array.isArray(value) ? [...value] : [];
702
+ }
703
+ function isRecord(value) {
704
+ return Object(value) === value && !Array.isArray(value);
705
+ }
706
+ function sameHandler(left, right) {
707
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
708
+ }
709
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
710
+ function createNitroServerKit(value = {}) {
711
+ const config = isRecord(value) ? { ...value } : {};
712
+ const handlers = cloneArray(config.handlers);
713
+ const plugins = cloneArray(config.plugins);
714
+ config.handlers = handlers;
715
+ config.plugins = plugins;
716
+ return {
717
+ config,
718
+ addHandler(handler, position = "end") {
719
+ if (handlers.some((candidate) => isRecord(candidate) && sameHandler(candidate, handler))) return;
720
+ if (position === "start") handlers.unshift({ ...handler });
721
+ else handlers.push({ ...handler });
722
+ },
723
+ addPlugin(plugin, position = "end") {
724
+ if (plugins.includes(plugin)) return;
725
+ if (position === "start") plugins.unshift(plugin);
726
+ else plugins.push(plugin);
727
+ }
728
+ };
729
+ }
730
+ //#endregion
731
+ //#region ../internal/src/definition-catalog.ts
732
+ const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
733
+ const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
734
+ const ignoredDirs = /* @__PURE__ */ new Set([
735
+ "node_modules",
736
+ "dist",
737
+ ".output",
738
+ ".nuxt",
739
+ ".vercel",
740
+ ".git",
741
+ ".vitehub"
742
+ ]);
743
+ function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
744
+ return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
745
+ }
746
+ function createDirectoryDefinitionSource(source, scanDirs, subdir, options = {}) {
747
+ return {
748
+ ...options,
749
+ kind: "directory",
750
+ scanDirs,
751
+ source,
752
+ subdir
753
+ };
754
+ }
755
+ function createSuffixDefinitionSource(source, roots, pattern, normalizeName, options = {}) {
756
+ return {
757
+ ...options,
758
+ kind: "suffix",
759
+ normalizeName,
760
+ pattern,
761
+ roots,
762
+ source
763
+ };
764
+ }
765
+ function readDirEntries(root) {
766
+ try {
767
+ return readdirSync(root, { withFileTypes: true });
768
+ } catch (error) {
769
+ if (error.code === "ENOENT") return [];
770
+ throw error;
771
+ }
772
+ }
773
+ function isGitRepositoryDirectory(directory) {
774
+ return existsSync(resolve$1(directory, ".git"));
775
+ }
776
+ function listMatchingFiles(root, predicate, options = {}) {
777
+ const files = [];
778
+ for (const entry of readDirEntries(root)) {
779
+ const absolute = resolve$1(root, entry.name);
780
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
781
+ if (isGitRepositoryDirectory(absolute)) continue;
782
+ if (entry.name.startsWith(".")) continue;
783
+ if (ignoredDirs.has(entry.name)) continue;
784
+ files.push(...listMatchingFiles(absolute, predicate, options));
785
+ continue;
786
+ }
787
+ if (entry.name.startsWith(".") && !options.includeHidden) continue;
788
+ if (entry.isFile() && predicate(entry.name)) files.push(absolute);
789
+ }
790
+ return files.sort();
791
+ }
792
+ function listSourceFiles(root, options = {}) {
793
+ return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
794
+ }
795
+ function normalizePathDefinitionName(rootDir, file) {
796
+ return relative(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
797
+ }
798
+ function normalizeSuffixDefinitionName(rootDir, file, pattern, options = {}) {
799
+ const normalized = relative(rootDir, file).replace(pattern, "");
800
+ if (options.stripPrefix && normalized.startsWith(options.stripPrefix)) return normalized.slice(options.stripPrefix.length);
801
+ return normalized;
802
+ }
803
+ function sortDefinitions(definitions) {
804
+ return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
805
+ }
806
+ function registerDefinition(definitions, definition, sourceLabel) {
807
+ const existing = definitions.get(definition.name);
808
+ if (existing) throw internalErrorDiagnostics.INTERNAL_C0001({ message: `Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}` });
809
+ definitions.set(definition.name, definition);
810
+ }
811
+ function mergeDefinitions(feature, ...sources) {
812
+ const definitions = /* @__PURE__ */ new Map();
813
+ for (const source of sources) {
814
+ if (!source) continue;
815
+ for (const definition of source) {
816
+ const existing = definitions.get(definition.name);
817
+ if (existing && existing.handler !== definition.handler) throw internalErrorDiagnostics.INTERNAL_C0002({ message: `Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})` });
818
+ if (!existing) definitions.set(definition.name, definition);
819
+ }
820
+ }
821
+ return sortDefinitions(definitions);
822
+ }
823
+ function createDefinition(source, file, name) {
824
+ if (source.createDefinition) return source.createDefinition({
825
+ file,
826
+ name
827
+ });
828
+ return {
829
+ handler: file,
830
+ name,
831
+ source: source.source
832
+ };
833
+ }
834
+ function scanSuffixDefinitions(feature, source) {
835
+ const definitions = /* @__PURE__ */ new Map();
836
+ for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => {
837
+ source.pattern.lastIndex = 0;
838
+ return source.pattern.test(name);
839
+ }, { includeHidden: source.includeHidden })) {
840
+ const name = source.normalizeName(root, file);
841
+ if (!name) continue;
842
+ registerDefinition(definitions, createDefinition(source, file, name), feature);
843
+ }
844
+ return sortDefinitions(definitions);
845
+ }
846
+ function scanDirectoryDefinitions(feature, source) {
847
+ const definitions = /* @__PURE__ */ new Map();
848
+ for (const scanDir of source.scanDirs) {
849
+ const directory = resolve$1(scanDir, source.subdir);
850
+ for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
851
+ const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
852
+ if (!name) continue;
853
+ registerDefinition(definitions, createDefinition(source, file, name), feature);
854
+ }
855
+ }
856
+ return sortDefinitions(definitions);
857
+ }
858
+ function discoverDefinitions(feature, sources) {
859
+ return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
860
+ }
861
+ function createImportExpression(registryFile, file) {
862
+ const importPath = relative(resolve$1(registryFile, ".."), file);
863
+ return `import(${JSON.stringify(importPath.startsWith(".") ? importPath : `./${importPath}`)})`;
864
+ }
865
+ function createRuntimeRegistryContents(registryFile, definitions) {
866
+ return [
867
+ "",
868
+ "const registry = {",
869
+ ...definitions.map((definition) => ` [${JSON.stringify(definition.name)}]: async () => ${createImportExpression(registryFile, definition.handler)},`),
870
+ "}",
871
+ "",
872
+ "export default registry",
873
+ ""
874
+ ].join("\n");
875
+ }
876
+ //#endregion
877
+ //#region src/discovery.ts
878
+ const queueSuffixPattern = /\.queue\.(?:c|m)?[jt]s$/i;
879
+ function normalizeSuffixQueueName(rootDir, file) {
880
+ return normalizeSuffixDefinitionName(rootDir, file, queueSuffixPattern, { stripPrefix: "src/" });
881
+ }
882
+ function discoverQueueDefinitions(options) {
883
+ if (options.mode === "server-queues") return discoverDefinitions("queue", [createDirectoryDefinitionSource("server-queues", options.scanDirs, "queues")]);
884
+ const roots = resolveDefinitionScanRoots(options.rootDir, options.scanDirs);
885
+ const serverScanDirs = options.serverDirs || [...new Set(options.serverRootDirs || roots)].map((root) => resolve$1(root, "server"));
886
+ return discoverDefinitions("queue", [createSuffixDefinitionSource("vite-suffix", roots, queueSuffixPattern, normalizeSuffixQueueName), createDirectoryDefinitionSource("server-queues", serverScanDirs, "queues")]);
887
+ }
888
+ //#endregion
889
+ //#region src/registry-types.ts
890
+ function createQueueTypes(file, definitions, importBase = "@vite-hub/queue") {
891
+ const entries = definitions.map((definition) => {
892
+ const path = relative(dirname$1(file), definition.handler);
893
+ const specifier = path.startsWith(".") ? path : `./${path}`;
894
+ return ` ${JSON.stringify(definition.name)}: typeof import(${JSON.stringify(specifier)}).default`;
895
+ });
896
+ return [
897
+ `import ${JSON.stringify(importBase)}`,
898
+ `declare module ${JSON.stringify(importBase)} {`,
899
+ " interface QueueRegistry {",
900
+ ...entries,
901
+ " }",
902
+ "}",
903
+ ""
904
+ ].join("\n");
905
+ }
906
+ async function writeQueueTypes(root, definitions, importBase = "@vite-hub/queue") {
907
+ const file = resolve$1(root, ".vitehub/queue.d.ts");
908
+ await mkdir(dirname$1(file), { recursive: true });
909
+ await writeFile(file, createQueueTypes(file, definitions, importBase), "utf8");
910
+ }
911
+ //#endregion
912
+ //#region src/internal/vite-build.ts
913
+ const queuePackageName = "@vite-hub/queue";
914
+ const productName = "queue";
915
+ const generatedRegistryFileName = "registry.mjs";
916
+ const generatedQueueNitroPlugin = ".vitehub/nitro/queue/plugin.ts";
917
+ const generatedQueueNitroMiddleware = ".vitehub/nitro/queue/middleware.ts";
918
+ const generatedQueueNitroVercelConsumerDir = ".vitehub/nitro/queue/vercel";
919
+ const vercelQueueConsumerRoutePrefix = "/api/vitehub/queues/vercel";
920
+ const packageDir = computePackageDir(import.meta.url);
921
+ const packageRequire = createRequire(resolve(packageDir, "package.json"));
922
+ const resolvePackageDependency = (specifier) => packageRequire.resolve(specifier);
923
+ const resolveRuntimeModule = (modulePath) => resolveRuntimeModule$1(packageDir, modulePath);
924
+ function resolveOutputQueueConfig(queue, hosting) {
925
+ if (typeof queue === "undefined") return false;
926
+ return normalizeQueueOptions(queue, { hosting }) || false;
927
+ }
928
+ function createCloudflareQueueDefinitionNames(definitions, namePrefix = "") {
929
+ const names = /* @__PURE__ */ new Map();
930
+ for (const definition of definitions) {
931
+ const physicalName = getCloudflareQueueName(definition.name, namePrefix);
932
+ const existing = names.get(physicalName);
933
+ if (existing) throw queueErrorDiagnostics.QUEUE_NAME_COLLISION({
934
+ first: existing.name,
935
+ resolved: physicalName,
936
+ second: definition.name
937
+ });
938
+ names.set(physicalName, definition);
939
+ }
940
+ return Object.fromEntries([...names].map(([physicalName, definition]) => [physicalName, definition.name]));
941
+ }
942
+ function createCloudflareQueueBindings(definitions, namePrefix = "") {
943
+ if (!definitions.length) return;
944
+ const names = createCloudflareQueueDefinitionNames(definitions, namePrefix);
945
+ return {
946
+ consumers: Object.keys(names).map((queue) => ({ queue })),
947
+ producers: definitions.map((definition) => ({
948
+ binding: getCloudflareQueueBindingName(definition.name),
949
+ queue: getCloudflareQueueName(definition.name, namePrefix)
950
+ }))
951
+ };
952
+ }
953
+ function renderNitroPlugin(pluginFile, registryFile, queueConfig, cloudflareQueues, queueDefinitions, development) {
954
+ const cloudflareRuntime = queueConfig !== false && queueConfig.provider === "cloudflare";
955
+ const vercelRuntime = queueConfig !== false && queueConfig.provider === "vercel";
956
+ const cloudflare = cloudflareQueues && cloudflareRuntime;
957
+ const cloudflareGlobals = cloudflareRuntime && !development;
958
+ const runtimeClientFactory = cloudflareRuntime ? "createCloudflareQueueRuntimeClient" : vercelRuntime ? "createVercelQueueRuntimeClient" : void 0;
959
+ return [
960
+ "import { definePlugin } from 'nitro'",
961
+ ...vercelRuntime ? [`import * as __vitehubVercelQueue from ${JSON.stringify(createImportPath(pluginFile, resolvePackageDependency("@vercel/queue")))}`] : [],
962
+ ...cloudflareGlobals ? ["import * as vitehubCloudflareWorkers from 'cloudflare:workers'"] : [],
963
+ ...cloudflare ? [`import { createQueueCloudflareWorker } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/cloudflare-vite")))}`] : [],
964
+ ...cloudflareRuntime ? [`import { createCloudflareQueueRuntimeClient } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/cloudflare-client")))}`] : [],
965
+ ...vercelRuntime ? [`import { createVercelQueueRuntimeClient } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/vercel-client")))}`] : [],
966
+ `import { setQueueRuntimeConfig, setQueueRuntimeEventDefaults, setQueueRuntimeRegistry } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/state")))}`,
967
+ `import queueRegistry from ${JSON.stringify(createImportPath(pluginFile, registryFile))}`,
968
+ "",
969
+ ...cloudflareGlobals ? ["const { env: vitehubEnv, waitUntil: vitehubWaitUntil } = vitehubCloudflareWorkers as unknown as { env: Record<string, unknown>, waitUntil(promise: Promise<unknown>): void }", ""] : [],
970
+ ...vercelRuntime ? ["globalThis.__vitehubVercelQueue = __vitehubVercelQueue", ""] : [],
971
+ `const queueConfig = ${JSON.stringify(queueConfig, null, 2)}`,
972
+ ...cloudflare ? [`const queueDefinitions = ${JSON.stringify(queueDefinitions, null, 2)}`, "const queueWorker = createQueueCloudflareWorker({ definitions: queueDefinitions, queue: queueConfig, registry: queueRegistry })"] : [],
973
+ "",
974
+ `export default definePlugin((${cloudflare ? "nitro" : ""}) => {`,
975
+ ` setQueueRuntimeConfig(queueConfig${runtimeClientFactory ? `, ${runtimeClientFactory}` : ""})`,
976
+ " setQueueRuntimeRegistry(queueRegistry)",
977
+ ...cloudflareGlobals ? [" setQueueRuntimeEventDefaults({ env: vitehubEnv, waitUntil: vitehubWaitUntil })"] : [],
978
+ ...cloudflare ? [" nitro.hooks.hook('cloudflare:queue', ({ batch, context, env }) => queueWorker.queue(batch, env, context))"] : [],
979
+ "})",
980
+ ""
981
+ ].join("\n");
982
+ }
983
+ function renderNitroMiddleware(middlewareFile, queueConfig, hasDefinitions, development) {
984
+ const cloudflare = queueConfig !== false && queueConfig.provider === "cloudflare";
985
+ const cloudflareGlobals = cloudflare && !development;
986
+ const vercel = hasDefinitions && queueConfig !== false && queueConfig.provider === "vercel";
987
+ return [
988
+ "import { defineMiddleware } from 'nitro'",
989
+ ...vercel ? [`import { waitUntil as vitehubWaitUntil } from ${JSON.stringify(createImportPath(middlewareFile, resolvePackageDependency("@vercel/functions")))}`] : [],
990
+ ...cloudflareGlobals ? ["import * as vitehubCloudflareWorkers from 'cloudflare:workers'"] : [],
991
+ `import { enterQueueRuntimeEvent } from ${JSON.stringify(createImportPath(middlewareFile, resolveRuntimeModule("internal/runtime/state")))}`,
992
+ "",
993
+ ...cloudflareGlobals ? ["const { env: vitehubEnv, waitUntil: vitehubWaitUntil } = vitehubCloudflareWorkers as unknown as { env: Record<string, unknown>, waitUntil(promise: Promise<unknown>): void }", ""] : [],
994
+ "export default defineMiddleware((event) => {",
995
+ ...cloudflare ? [" const runtimeEvent = event as any"] : [],
996
+ ...vercel ? [" Object.assign(event, { waitUntil: vitehubWaitUntil })"] : [],
997
+ ...cloudflare ? [` Object.assign(event, { env: runtimeEvent.env ?? runtimeEvent.context?.cloudflare?.env ?? runtimeEvent.context?._platform?.cloudflare?.env ?? runtimeEvent.req?.runtime?.cloudflare?.env ?? runtimeEvent.node?.req?.runtime?.cloudflare?.env${cloudflareGlobals ? " ?? vitehubEnv, waitUntil: vitehubWaitUntil" : ""} })`] : [],
998
+ " enterQueueRuntimeEvent(event)",
999
+ "})",
1000
+ ""
1001
+ ].join("\n");
1002
+ }
1003
+ async function writeQueueNitroIntegration(rootDir, queue, hosting, cloudflareQueues = true, definitions = discoverQueueDefinitions({ rootDir }), development = false, importBase = queuePackageName) {
1004
+ await writeQueueTypes(rootDir, definitions, importBase);
1005
+ const generatedDir = ensureGeneratedDir(rootDir, productName);
1006
+ const registryFile = resolve(generatedDir, generatedRegistryFileName);
1007
+ const pluginFile = resolve(rootDir, generatedQueueNitroPlugin);
1008
+ const middlewareFile = resolve(rootDir, generatedQueueNitroMiddleware);
1009
+ const queueConfig = resolveOutputQueueConfig(typeof queue === "undefined" ? {} : queue, hosting);
1010
+ const queueDefinitions = cloudflareQueues && queueConfig !== false && queueConfig.provider === "cloudflare" ? createCloudflareQueueDefinitionNames(definitions, queueConfig.namePrefix) : {};
1011
+ await Promise.all([mkdir(dirname(pluginFile), { recursive: true }), mkdir(generatedDir, { recursive: true })]);
1012
+ const vercelConsumerDir = resolve(rootDir, generatedQueueNitroVercelConsumerDir);
1013
+ const vercelConsumers = queueConfig !== false && queueConfig.provider === "vercel" ? createVercelQueueConsumerRoutes(definitions) : [];
1014
+ await rm(vercelConsumerDir, {
1015
+ force: true,
1016
+ recursive: true
1017
+ });
1018
+ if (vercelConsumers.length) await mkdir(vercelConsumerDir, { recursive: true });
1019
+ await Promise.all([
1020
+ writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions), "utf8"),
1021
+ writeFile(pluginFile, renderNitroPlugin(pluginFile, registryFile, queueConfig, cloudflareQueues, queueDefinitions, development), "utf8"),
1022
+ writeFile(middlewareFile, renderNitroMiddleware(middlewareFile, queueConfig, definitions.length > 0, development), "utf8"),
1023
+ ...vercelConsumers.map(async (consumer) => {
1024
+ const file = resolve(rootDir, consumer.handler);
1025
+ await writeFile(file, renderVercelQueueConsumerHandler(file, consumer.name), "utf8");
1026
+ })
1027
+ ]);
1028
+ }
1029
+ function sanitizeVercelConsumerName(functionPath) {
1030
+ let result = "";
1031
+ for (const char of functionPath) if (char === "_") result += "__";
1032
+ else if (char === "/") result += "_S";
1033
+ else if (char === ".") result += "_D";
1034
+ else if (/[A-Za-z0-9-]/.test(char)) result += char;
1035
+ else result += `_${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;
1036
+ return result;
1037
+ }
1038
+ /**
1039
+ * Maps each Queue Definition to a Nitro route with a Vercel queue trigger.
1040
+ * The consumer name keeps the function path of earlier ViteHub releases, so a redeploy keeps the Vercel consumer group.
1041
+ */
1042
+ function createVercelQueueConsumerRoutes(definitions) {
1043
+ const routes = /* @__PURE__ */ new Map();
1044
+ return definitions.map((definition) => {
1045
+ const segments = definition.name.replace(/[^a-z0-9/_-]+/gi, "_").split("/");
1046
+ const route = `${vercelQueueConsumerRoutePrefix}/${segments.join("/")}`;
1047
+ const existing = routes.get(route);
1048
+ if (existing) throw queueErrorDiagnostics.QUEUE_NAME_COLLISION({
1049
+ first: existing.name,
1050
+ resolved: route,
1051
+ second: definition.name
1052
+ });
1053
+ routes.set(route, definition);
1054
+ const consumer = sanitizeVercelConsumerName(`${route.slice(1)}.func`);
1055
+ return {
1056
+ consumer,
1057
+ handler: `${generatedQueueNitroVercelConsumerDir}/${consumer}.mjs`,
1058
+ name: definition.name,
1059
+ route,
1060
+ topic: getVercelQueueTopicName(definition.name)
1061
+ };
1062
+ });
1063
+ }
1064
+ function renderVercelQueueConsumerHandler(file, name) {
1065
+ return [
1066
+ `import { defineHandler } from ${JSON.stringify(createImportPath(file, resolvePackageDependency("h3")))}`,
1067
+ `import { handleHostedVercelQueueCallback } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("runtime/hosted")))}`,
1068
+ `import { loadQueueDefinition, missingQueueDefinitionError } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("internal/runtime/state")))}`,
1069
+ "",
1070
+ `const name = ${JSON.stringify(name)}`,
1071
+ "",
1072
+ "export default defineHandler(async (event) => {",
1073
+ " const definition = await loadQueueDefinition(name)",
1074
+ " if (!definition) throw missingQueueDefinitionError(name)",
1075
+ " return await handleHostedVercelQueueCallback(event, name, definition)",
1076
+ "})",
1077
+ ""
1078
+ ].join("\n");
1079
+ }
1080
+ //#endregion
1081
+ //#region src/inspect.ts
1082
+ /** Summarizes discovered Queue Definitions for the CLI and Console. */
1083
+ function inspectQueueDefinitions(options) {
1084
+ return summarizeDefinitions(options.projectRoot, discoverQueueDefinitions({
1085
+ rootDir: options.rootDir,
1086
+ serverDirs: options.serverDirs
1087
+ }), "queue");
1088
+ }
1089
+ /** Console section that lists discovered Queue Definitions. `vitehub inspect definitions` reads the same data. */
1090
+ const queueConsoleSection = {
1091
+ description: "Inspect discovered Queue Definitions and their source metadata.",
1092
+ icon: "i-lucide-inbox",
1093
+ id: "queues",
1094
+ label: "Queues",
1095
+ read: inspectQueueDefinitions,
1096
+ view: {
1097
+ kind: "definition-catalog",
1098
+ notice: "Queue backlog, message, and delivery history are not exposed by ViteHub's provider-independent Queue contract yet."
1099
+ }
1100
+ };
1101
+ //#endregion
1102
+ //#region ../internal/src/provision.ts
1103
+ function resolveCloudflareProvisionConfig(env) {
1104
+ const accountId = trimmedEnv(env.CLOUDFLARE_ACCOUNT_ID);
1105
+ const token = trimmedEnv(env.CLOUDFLARE_API_TOKEN);
1106
+ if (!accountId || !token) return;
1107
+ return {
1108
+ accountId,
1109
+ token
1110
+ };
1111
+ }
1112
+ function ownParser(options) {
1113
+ if (!Object.hasOwn(options, "parse")) return;
1114
+ return options.parse;
1115
+ }
1116
+ var ProvisionRequestError = class ProvisionRequestError extends Diagnostic {
1117
+ codes;
1118
+ status;
1119
+ constructor(method, path, status, codes = []) {
1120
+ const suffix = codes.length ? ` Provider code${codes.length === 1 ? "" : "s"}: ${codes.join(", ")}.` : "";
1121
+ super({
1122
+ code: "INTERNAL_R0013",
1123
+ docs: "https://vitehub.dev/docs/reference/diagnostics",
1124
+ why: `Provision request failed: ${method} ${path} (${status}).${suffix}`
1125
+ }, ProvisionRequestError);
1126
+ this.name = "ProvisionRequestError";
1127
+ this.codes = codes;
1128
+ this.status = status;
1129
+ }
1130
+ };
1131
+ function createJsonClient(baseURL, headers, fetchImpl, baseQuery) {
1132
+ return async function request(path, options = {}) {
1133
+ const url = new URL(`${baseURL}${path}`);
1134
+ const query = Object.hasOwn(options, "query") ? options.query : void 0;
1135
+ for (const [key, value] of Object.entries({
1136
+ ...baseQuery,
1137
+ ...query
1138
+ })) url.searchParams.set(key, value);
1139
+ const method = Object.hasOwn(options, "method") ? options.method : void 0;
1140
+ const body = Object.hasOwn(options, "body") ? options.body : void 0;
1141
+ const requestHeaders = Object.hasOwn(options, "headers") ? options.headers : void 0;
1142
+ const init = {
1143
+ method: method ?? "GET",
1144
+ headers: {
1145
+ ...requestHeaders,
1146
+ ...headers
1147
+ }
1148
+ };
1149
+ if (body !== void 0) {
1150
+ init.headers = {
1151
+ ...init.headers,
1152
+ "content-type": "application/json"
1153
+ };
1154
+ init.body = JSON.stringify(body);
1155
+ }
1156
+ const response = await fetchImpl(url, init);
1157
+ if (!response.ok) {
1158
+ const body = await response.json().catch(() => void 0);
1159
+ const codes = [body?.error?.code, ...body?.errors?.map((error) => error.code) ?? []].filter((code) => typeof code === "number" || typeof code === "string" && /^[\w.-]{1,128}$/.test(code));
1160
+ throw new ProvisionRequestError(method ?? "GET", path, response.status, codes);
1161
+ }
1162
+ const value = await response.json();
1163
+ const parse = ownParser(options);
1164
+ return parse ? parse(value) : value;
1165
+ };
1166
+ }
1167
+ function createCloudflareProvisionClient(config, fetchImpl = globalThis.fetch) {
1168
+ const client = createJsonClient(`https://api.cloudflare.com/client/v4/accounts/${config.accountId}`, { authorization: `Bearer ${config.token}` }, fetchImpl);
1169
+ return async (path, options = {}) => {
1170
+ const parse = ownParser(options) ?? ((value) => value);
1171
+ return await client(path, {
1172
+ ...options,
1173
+ parse(value) {
1174
+ if (!value || Object(value) !== value) throw internalErrorDiagnostics.INTERNAL_R0010({ message: "Cloudflare provisioning returned an invalid response." });
1175
+ const envelope = value;
1176
+ return {
1177
+ ...envelope,
1178
+ result: envelope.result === void 0 ? void 0 : parse(envelope.result)
1179
+ };
1180
+ }
1181
+ });
1182
+ };
1183
+ }
1184
+ function trimmedEnv(value) {
1185
+ const trimmed = value?.trim();
1186
+ return trimmed ? trimmed : void 0;
1187
+ }
1188
+ //#endregion
1189
+ //#region src/provision.ts
1190
+ function parseQueues(value) {
1191
+ if (!Array.isArray(value) || Array.from(value).some((queue, index) => !(index in value) || queue === null || typeof queue !== "object" || Array.isArray(queue))) throw queueErrorDiagnostics.QUEUE_PROVISION_FAILED();
1192
+ return value;
1193
+ }
1194
+ function createQueueProvisionStep(resolveRootDir, resolveNamePrefix = () => void 0) {
1195
+ return {
1196
+ id: "queue:cloudflare-queues",
1197
+ provider: "cloudflare",
1198
+ async plan(context) {
1199
+ const config = resolveCloudflareProvisionConfig(context.env);
1200
+ if (!config) {
1201
+ context.logger.warn("queue: skipping Cloudflare queues, missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN.");
1202
+ context.markPlanUnchecked?.();
1203
+ return [];
1204
+ }
1205
+ const request = createCloudflareProvisionClient(config, context.fetch);
1206
+ const namePrefix = resolveNamePrefix();
1207
+ const names = discoverQueueDefinitions({ rootDir: resolveRootDir() }).map((definition) => getCloudflareQueueName(definition.name, namePrefix));
1208
+ if (!names.length) return [];
1209
+ const listed = await request("/queues", { parse: parseQueues });
1210
+ const existing = new Set((listed.result ?? []).map((queue) => queue.queue_name).filter((name) => Boolean(name)));
1211
+ return names.map((name) => ({
1212
+ kind: "cloudflare-queue",
1213
+ name,
1214
+ exists: existing.has(name),
1215
+ apply: async () => {
1216
+ if (!existing.has(name)) await request("/queues", {
1217
+ method: "POST",
1218
+ body: { queue_name: name }
1219
+ });
1220
+ return {};
1221
+ }
1222
+ }));
1223
+ }
1224
+ };
1225
+ }
1226
+ //#endregion
1227
+ //#region src/vite.ts
1228
+ const mergeNoExternal = createNoExternalAddition(queuePackageName);
1229
+ async function createQueueNitroConfig(plugin, options) {
1230
+ const createNitroConfig = plugin.vitehub?.queue?.createNitroConfig;
1231
+ if (!createNitroConfig) throw queueErrorDiagnostics.QUEUE_PLUGIN_INCOMPATIBLE();
1232
+ return createNitroConfig(options);
1233
+ }
1234
+ function resolveStableQueueDefinitions(resolveDefinitions, snapshot, context) {
1235
+ const definitions = resolveDefinitions();
1236
+ if (JSON.stringify(definitions) !== JSON.stringify(snapshot)) throw queueErrorDiagnostics.QUEUE_DEFINITIONS_CHANGED({ context });
1237
+ return definitions;
1238
+ }
1239
+ function cloneNitroConfig(value) {
1240
+ return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
1241
+ }
1242
+ function mergeNitroExternal(value, addition) {
1243
+ if (typeof value === "undefined") return [addition];
1244
+ if (Array.isArray(value)) return value.includes(addition) ? [...value] : [...value, addition];
1245
+ if (typeof value === "string" || value instanceof RegExp) return [value, addition];
1246
+ if (typeof value === "function") return (source, importer, isResolved) => source === addition || Boolean(value(source, importer, isResolved));
1247
+ return value;
1248
+ }
1249
+ function normalizeQueueForHosting(queue, hosting) {
1250
+ if (queue && typeof queue === "object" && Object.hasOwn(queue, "provider")) {
1251
+ const provider = queue.provider;
1252
+ const providerOnly = normalizeQueueOptions({ provider }, { hosting });
1253
+ if (providerOnly?.provider && hosting && providerOnly.provider !== hosting) return void 0;
1254
+ }
1255
+ return normalizeQueueOptions(queue, { hosting });
1256
+ }
1257
+ function resolveQueueHosting(queue, nitro) {
1258
+ const hosting = getHostingProvider(resolveHost({ nitro }));
1259
+ return hosting || normalizeQueueForHosting(queue, hosting)?.provider || "vercel";
1260
+ }
1261
+ function supportsCloudflareQueues(nitro) {
1262
+ return !(resolveHostPreset({ nitro }) ?? "").replaceAll("-", "_").includes("cloudflare_pages");
1263
+ }
1264
+ function isGeneratedNitroRegistration(value, generatedPath) {
1265
+ return typeof value === "string" && (value === generatedPath || value.replaceAll("\\", "/").endsWith(`/${generatedPath}`));
1266
+ }
1267
+ function isGeneratedVercelConsumer(value) {
1268
+ return typeof value === "string" && value.replaceAll("\\", "/").includes(`.vitehub/nitro/queue/vercel/`);
1269
+ }
1270
+ /** Vercel delivers Queue messages to Nitro routes that have a queue trigger in `vercel.functionRules`. */
1271
+ function hostsVercelQueueConsumers(nitro) {
1272
+ const hosting = getHostingProvider(resolveHost({ nitro }));
1273
+ return hosting === "vercel" || hosting === void 0 && Boolean(process.env.VERCEL);
1274
+ }
1275
+ function addVercelQueueConsumers(kit, definitions, root) {
1276
+ const vercel = cloneNitroConfig(kit.config.vercel);
1277
+ const functionRules = cloneNitroConfig(vercel.functionRules);
1278
+ for (const consumer of createVercelQueueConsumerRoutes(definitions)) {
1279
+ kit.addHandler({
1280
+ handler: root ? resolve$1(root, consumer.handler) : consumer.handler,
1281
+ route: consumer.route
1282
+ });
1283
+ functionRules[consumer.route] = {
1284
+ ...cloneNitroConfig(functionRules[consumer.route]),
1285
+ experimentalTriggers: [{
1286
+ consumer: consumer.consumer,
1287
+ topic: consumer.topic,
1288
+ type: "queue/v2beta"
1289
+ }]
1290
+ };
1291
+ }
1292
+ kit.config.vercel = {
1293
+ ...vercel,
1294
+ functionRules
1295
+ };
1296
+ }
1297
+ function mergeNitroConfig(config, value, queue, root, definitions = discoverQueueDefinitions({ rootDir: root })) {
1298
+ const providerOutput = useProviderOutputCatalog(config);
1299
+ const nitro = cloneNitroConfig(value);
1300
+ const nitroHosting = getHostingProvider(resolveHost({ nitro }));
1301
+ const normalizedQueue = normalizeQueueForHosting(queue, nitroHosting);
1302
+ const runtimeEnabled = queue !== false && !(queue !== false && nitroHosting && queue && normalizedQueue === void 0);
1303
+ const nitroOwnsPaths = hasNitroConfigContext(config);
1304
+ const plugin = nitroOwnsPaths ? resolve$1(root, generatedQueueNitroPlugin) : generatedQueueNitroPlugin;
1305
+ const middleware = nitroOwnsPaths ? resolve$1(root, generatedQueueNitroMiddleware) : generatedQueueNitroMiddleware;
1306
+ nitro.plugins = Array.isArray(nitro.plugins) ? nitro.plugins.filter((entry) => !isGeneratedNitroRegistration(entry, generatedQueueNitroPlugin)) : [];
1307
+ nitro.handlers = Array.isArray(nitro.handlers) ? nitro.handlers.filter((handler) => !isGeneratedNitroRegistration(handler?.handler, ".vitehub/nitro/queue/middleware.ts") && !isGeneratedVercelConsumer(handler?.handler)) : [];
1308
+ const kit = createNitroServerKit(nitro);
1309
+ if (!runtimeEnabled) {
1310
+ contributeCloudflareProviderOutput(providerOutput, { owner: "queue" });
1311
+ return composeNitroCloudflareProviderOutput(providerOutput, kit.config, value);
1312
+ }
1313
+ kit.addPlugin(plugin, "start");
1314
+ kit.addHandler({
1315
+ handler: middleware,
1316
+ middleware: true,
1317
+ route: "/**"
1318
+ }, "start");
1319
+ const queueHosting = resolveQueueHosting(queue, nitro);
1320
+ const resolvedVercelQueue = queueHosting === "vercel" ? normalizeQueueOptions(queue, { hosting: queueHosting }) : void 0;
1321
+ if (resolvedVercelQueue && resolvedVercelQueue.provider === "vercel" && hostsVercelQueueConsumers(nitro)) addVercelQueueConsumers(kit, definitions, nitroOwnsPaths ? root : void 0);
1322
+ if (queueHosting !== "cloudflare") {
1323
+ contributeCloudflareProviderOutput(providerOutput, { owner: "queue" });
1324
+ return composeNitroCloudflareProviderOutput(providerOutput, kit.config, value);
1325
+ }
1326
+ const cloudflare = cloneNitroConfig(nitro.cloudflare);
1327
+ const wrangler = cloneNitroConfig(cloudflare.wrangler);
1328
+ const compatibilityFlags = Array.isArray(wrangler.compatibility_flags) ? [...wrangler.compatibility_flags] : [];
1329
+ if (!compatibilityFlags.includes("nodejs_compat")) compatibilityFlags.push("nodejs_compat");
1330
+ const cloudflareQueues = supportsCloudflareQueues(nitro);
1331
+ const rollupConfig = cloneNitroConfig(nitro.rollupConfig);
1332
+ const resolvedQueue = normalizeQueueOptions(queue, { hosting: queueHosting });
1333
+ const generated = createCloudflareQueueBindings(definitions, resolvedQueue?.provider === "cloudflare" ? resolvedQueue.namePrefix : void 0);
1334
+ const baseNitro = {
1335
+ ...nitro,
1336
+ ...cloudflareQueues ? { rollupConfig: {
1337
+ ...rollupConfig,
1338
+ external: mergeNitroExternal(rollupConfig.external, "cloudflare:workers")
1339
+ } } : {},
1340
+ cloudflare: {
1341
+ ...cloudflare,
1342
+ wrangler: {
1343
+ ...wrangler,
1344
+ compatibility_flags: compatibilityFlags
1345
+ }
1346
+ },
1347
+ handlers: kit.config.handlers,
1348
+ plugins: kit.config.plugins
1349
+ };
1350
+ if (!generated) {
1351
+ contributeCloudflareProviderOutput(providerOutput, { owner: "queue" });
1352
+ return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
1353
+ }
1354
+ const binding = resolvedQueue?.provider === "cloudflare" && typeof resolvedQueue.binding === "string" ? resolvedQueue.binding : void 0;
1355
+ if (binding && generated.producers.length > 1) throw queueErrorDiagnostics.QUEUE_BINDING_CONFLICT();
1356
+ const generatedProducers = binding ? generated.producers.map((producer) => ({
1357
+ ...producer,
1358
+ binding
1359
+ })) : generated.producers;
1360
+ contributeCloudflareProviderOutput(providerOutput, {
1361
+ owner: "queue",
1362
+ queues: {
1363
+ ...cloudflareQueues ? { consumers: generated.consumers } : {},
1364
+ producers: generatedProducers
1365
+ }
1366
+ });
1367
+ return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
1368
+ }
1369
+ function hubQueue(options, internalOptions = {}) {
1370
+ let resolved;
1371
+ let queue = options;
1372
+ let hosting = "vercel";
1373
+ let cloudflareQueues = true;
1374
+ let configuredDefinitions = [];
1375
+ let localDevelopment = false;
1376
+ let nitroQueue = queue;
1377
+ let nuxtConfiguredDefinitions;
1378
+ let nuxtProjectRoot;
1379
+ let resolveNuxtDefinitions;
1380
+ let nuxtServerQueueDirs = [];
1381
+ const resolvedConfigs = /* @__PURE__ */ new Map();
1382
+ const queueOptions = /* @__PURE__ */ new Map();
1383
+ const nuxtStates = /* @__PURE__ */ new Map();
1384
+ const buildStates = /* @__PURE__ */ new WeakMap();
1385
+ let validatesNitroDefinitions = false;
1386
+ let serverDirs;
1387
+ return {
1388
+ name: "@vite-hub/queue/vite",
1389
+ vitehub: {
1390
+ operations: [{
1391
+ export: "queueOperations",
1392
+ load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).queueOperations,
1393
+ module: "@vite-hub/queue/operations"
1394
+ }],
1395
+ inspect: () => {
1396
+ if (!normalizeQueueOptions(queue, { hosting })?.provider) return;
1397
+ return { definitions: [{
1398
+ kind: "queue",
1399
+ label: "Queues",
1400
+ list: () => {
1401
+ const rootDir = resolved?.root ?? process.cwd();
1402
+ return inspectQueueDefinitions({
1403
+ projectRoot: resolveViteHubProjectRoot(rootDir),
1404
+ rootDir,
1405
+ serverDirs
1406
+ });
1407
+ }
1408
+ }] };
1409
+ },
1410
+ cli: async () => {
1411
+ return {
1412
+ namespaces: [],
1413
+ provision: [createQueueProvisionStep(() => resolved?.root ?? process.cwd(), () => {
1414
+ const resolvedQueue = normalizeQueueOptions(queue, { hosting: "cloudflare" });
1415
+ return resolvedQueue?.provider === "cloudflare" ? resolvedQueue.namePrefix : void 0;
1416
+ })]
1417
+ };
1418
+ },
1419
+ queue: { async createNitroConfig({ development = false, nitro, projectRoot, root, serverDirs, viteConfig }) {
1420
+ const config = viteConfig ?? {
1421
+ ["__vitehubNitroConfigContext"]: true,
1422
+ nitro
1423
+ };
1424
+ const resolvedConfig = resolvedConfigs.get(root);
1425
+ const state = resolvedConfig ? buildStates.get(resolvedConfig) : void 0;
1426
+ const projectQueue = viteConfig ? viteConfig.queue ?? options : state ? state.queue : queueOptions.has(root) ? queueOptions.get(root) : options;
1427
+ nuxtProjectRoot = projectRoot;
1428
+ nuxtServerQueueDirs = [...new Set(serverDirs || [resolve$1(projectRoot, "server"), resolve$1(root, "server")])].map((dir) => `${resolve$1(dir, "queues").replace(/\\/g, "/")}/`);
1429
+ resolveNuxtDefinitions = () => discoverQueueDefinitions({
1430
+ rootDir: root,
1431
+ serverDirs,
1432
+ serverRootDirs: [projectRoot, root]
1433
+ });
1434
+ const definitions = resolveNuxtDefinitions();
1435
+ nuxtConfiguredDefinitions = definitions;
1436
+ const configuredNitro = mergeNitroConfig(config, nitro, projectQueue, projectRoot, definitions);
1437
+ hosting = resolveQueueHosting(projectQueue, configuredNitro);
1438
+ const nitroHosting = getHostingProvider(resolveHost({ nitro: configuredNitro }));
1439
+ const resolvedQueue = normalizeQueueOptions(projectQueue, { hosting: nitroHosting });
1440
+ nitroQueue = resolvedQueue?.provider && nitroHosting && resolvedQueue.provider !== nitroHosting ? false : projectQueue;
1441
+ cloudflareQueues = supportsCloudflareQueues(configuredNitro);
1442
+ localDevelopment = development;
1443
+ const nuxtState = {
1444
+ nuxtConfiguredDefinitions,
1445
+ nuxtProjectRoot,
1446
+ resolveNuxtDefinitions
1447
+ };
1448
+ nuxtStates.set(root, nuxtState);
1449
+ if (state) Object.assign(state, nuxtState);
1450
+ await writeQueueNitroIntegration(projectRoot, nitroQueue, hosting, cloudflareQueues, definitions, localDevelopment, internalOptions.importBase);
1451
+ return configuredNitro;
1452
+ } }
1453
+ },
1454
+ config(config) {
1455
+ queue = config.queue ?? options;
1456
+ queueOptions.set(resolve$1(config.root || process.cwd()), queue);
1457
+ serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
1458
+ const nitro = config.nitro;
1459
+ config.nitro = mergeNitroConfig(config, nitro, queue, config.root || process.cwd());
1460
+ },
1461
+ async configResolved(config) {
1462
+ resolved = config;
1463
+ resolvedConfigs.set(config.root, config);
1464
+ const nuxtState = nuxtStates.get(config.root);
1465
+ nuxtConfiguredDefinitions = nuxtState?.nuxtConfiguredDefinitions;
1466
+ nuxtProjectRoot = nuxtState?.nuxtProjectRoot;
1467
+ resolveNuxtDefinitions = nuxtState?.resolveNuxtDefinitions;
1468
+ queue = config.queue ?? options;
1469
+ queueOptions.set(config.root, queue);
1470
+ const configuredNitro = config.nitro;
1471
+ configuredDefinitions = discoverQueueDefinitions({ rootDir: config.root });
1472
+ const nitro = mergeNitroConfig(config, configuredNitro, queue, config.root, configuredDefinitions);
1473
+ config.nitro = nitro;
1474
+ hosting = resolveQueueHosting(queue, nitro);
1475
+ cloudflareQueues = supportsCloudflareQueues(nitro);
1476
+ const nitroHosting = getHostingProvider(resolveHost({ nitro }));
1477
+ const resolvedQueue = normalizeQueueOptions(queue, { hosting: nitroHosting });
1478
+ nitroQueue = resolvedQueue?.provider && nitroHosting && resolvedQueue.provider !== nitroHosting ? false : queue;
1479
+ validatesNitroDefinitions = hasNitroConfigContext(config) && nitroQueue !== false;
1480
+ localDevelopment = config.command === "serve";
1481
+ await writeQueueNitroIntegration(config.root, nitroQueue, hosting, cloudflareQueues, configuredDefinitions, localDevelopment, internalOptions.importBase);
1482
+ buildStates.set(config, {
1483
+ configuredDefinitions,
1484
+ nuxtConfiguredDefinitions,
1485
+ queue,
1486
+ resolveNuxtDefinitions,
1487
+ resolved: config,
1488
+ validatesNitroDefinitions
1489
+ });
1490
+ },
1491
+ configEnvironment(name, config) {
1492
+ if (!isServerEnvironment(name, config)) return;
1493
+ return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
1494
+ },
1495
+ async handleHotUpdate(context) {
1496
+ const file = context.file.replace(/\\/g, "/");
1497
+ const isDirectoryDefinition = /\.(?:c|m)?[jt]s$/i.test(file) && (/\/server\/queues\//.test(file) || nuxtServerQueueDirs.some((dir) => file.startsWith(dir)));
1498
+ if (!/\.queue\.(?:c|m)?[jt]s$/i.test(file) && !isDirectoryDefinition) return;
1499
+ resolved = context.server.config;
1500
+ await writeQueueNitroIntegration(nuxtProjectRoot || resolved.root, nitroQueue, hosting, cloudflareQueues, resolveNuxtDefinitions?.(), localDevelopment, internalOptions.importBase);
1501
+ },
1502
+ buildEnd(error) {
1503
+ const config = this.environment?.config ?? resolved;
1504
+ const state = config ? buildStates.get(config) : void 0;
1505
+ if (error || !state || shouldSkipViteProviderBuild(state.resolved.command, getViteMode())) return;
1506
+ if (state.resolveNuxtDefinitions && state.nuxtConfiguredDefinitions) resolveStableQueueDefinitions(state.resolveNuxtDefinitions, state.nuxtConfiguredDefinitions, "Nuxt");
1507
+ else if (state.validatesNitroDefinitions) resolveStableQueueDefinitions(() => discoverQueueDefinitions({ rootDir: state.resolved.root }), state.configuredDefinitions, "Nitro");
1508
+ }
1509
+ };
1510
+ }
1511
+ //#endregion
1512
+ export { discoverQueueDefinitions as a, queueConsoleSection as i, hubQueue as n, resolveNuxtServerDirs as o, inspectQueueDefinitions as r, createQueueNitroConfig as t };