@vite-hub/queue 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +141 -20
  2. package/dist/client-Cj50hQYp.js +180 -0
  3. package/dist/{cloudflare-client-COzQ8fHk.js → cloudflare-client-DYsAjM8B.js} +9 -16
  4. package/dist/{cloudflare-resource-name-CCuLDvSP.js → cloudflare-resource-name-BJHYRCMQ.js} +1 -1
  5. package/dist/config-BcTDeQIP.js +105 -0
  6. package/dist/durability.d.ts +13 -0
  7. package/dist/durability.js +47 -0
  8. package/dist/error-diagnostics-BRartC1z.js +181 -0
  9. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  10. package/dist/errors-DL3pcNO4.js +77 -0
  11. package/dist/{handler-response-CBwIkmTS.js → handler-response-By0Fpspv.js} +9 -4
  12. package/dist/index.d.ts +15 -31
  13. package/dist/index.js +23 -11
  14. package/dist/internal/runtime/cloudflare-client.d.ts +2 -2
  15. package/dist/internal/runtime/cloudflare-client.js +1 -1
  16. package/dist/internal/runtime/cloudflare-vite.d.ts +30 -2
  17. package/dist/internal/runtime/cloudflare-vite.js +111 -1
  18. package/dist/internal/runtime/local-client.d.ts +17 -0
  19. package/dist/internal/runtime/local-client.js +71 -0
  20. package/dist/internal/runtime/postgres-client.d.ts +46 -0
  21. package/dist/internal/runtime/postgres-client.js +560 -0
  22. package/dist/internal/runtime/state.d.ts +11 -4
  23. package/dist/internal/runtime/state.js +2 -2
  24. package/dist/internal/runtime/vercel-client.d.ts +2 -2
  25. package/dist/internal/runtime/vercel-client.js +52 -26
  26. package/dist/internal/runtime/worker-client.d.ts +6 -0
  27. package/dist/internal/runtime/worker-client.js +11 -0
  28. package/dist/invariant-D8_xBqmZ.js +22 -0
  29. package/dist/local-CGckW5nr.js +540 -0
  30. package/dist/local-CVVRVWeR.d.ts +22 -0
  31. package/dist/object-D8pRdprI.js +15 -0
  32. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  33. package/dist/operations-Crwjca91.js +124 -0
  34. package/dist/operations.d.ts +45 -8
  35. package/dist/operations.js +173 -24
  36. package/dist/runtime/hosted.d.ts +3 -5
  37. package/dist/runtime/hosted.js +21 -45
  38. package/dist/{state-G9s378-e.js → state-mVA2X_wa.js} +59 -47
  39. package/dist/types-BD-8U9zS.d.ts +420 -0
  40. package/dist/types-DS_rqu9l.d.ts +10 -0
  41. package/dist/vercel-region-D1CivgdA.js +26 -0
  42. package/dist/virtual.d.ts +4 -0
  43. package/dist/vite.d.ts +364 -49
  44. package/dist/vite.js +2071 -2
  45. package/package.json +39 -46
  46. package/dist/client-CIc3jsj2.js +0 -114
  47. package/dist/cloudflare-vite-BCuJOXcT.js +0 -111
  48. package/dist/cloudflare-vite-CjdP5yBN.d.ts +0 -29
  49. package/dist/config-BINujLv4.js +0 -74
  50. package/dist/enqueue-CnQ0QR3O.js +0 -22
  51. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  52. package/dist/error-diagnostics-qzRF6IVB.js +0 -109
  53. package/dist/errors-DIFaM9tW.js +0 -42
  54. package/dist/nuxt.d.ts +0 -39
  55. package/dist/nuxt.js +0 -34
  56. package/dist/object-B1NW521B.js +0 -7
  57. package/dist/operations-Cnjbz8kk.js +0 -63
  58. package/dist/types-1GRMYES1.d.ts +0 -180
  59. package/dist/vercel-region-cjskrOKl.js +0 -122
  60. package/dist/vite-ChWLzOVu.js +0 -1512
package/dist/vite.js CHANGED
@@ -1,2 +1,2071 @@
1
- import { a as discoverQueueDefinitions, i as queueConsoleSection, n as hubQueue, r as inspectQueueDefinitions, t as createQueueNitroConfig } from "./vite-ChWLzOVu.js";
2
- export { createQueueNitroConfig, discoverQueueDefinitions, hubQueue, inspectQueueDefinitions, queueConsoleSection };
1
+ import { t as queueErrorDiagnostics } from "./error-diagnostics-BRartC1z.js";
2
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-DSkCJC_L.js";
3
+ import { a as resolveHost, i as getHostingProvider, n as normalizeQueueOptions, o as resolveHostPreset, r as postgresQueueUrlVariable, t as defaultLocalQueueBase } from "./config-BcTDeQIP.js";
4
+ import { n as isRecord, r as isRecordOrFunction, t as cloneRecord } from "./object-D8pRdprI.js";
5
+ import { t as getCloudflareQueueBindingName } from "./cloudflare-GosJefIK.js";
6
+ import { t as getVercelQueueTopicName } from "./vercel-C_4vqxcl.js";
7
+ import { n as summarizeDefinitions } from "./inspect-PeuckaC3.js";
8
+ import { t as invariant } from "./invariant-D8_xBqmZ.js";
9
+ import { t as getCloudflareQueueName } from "./cloudflare-resource-name-BJHYRCMQ.js";
10
+ import { createRequire } from "node:module";
11
+ import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { basename, dirname, isAbsolute, parse, resolve } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { mkdir, rm, writeFile } from "node:fs/promises";
16
+ import { basename as basename$1, dirname as dirname$1, isAbsolute as isAbsolute$1, relative, resolve as resolve$1 } from "pathe";
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
+ /** The deployment host that `vitehub()` selected, such as `"cloudflare"`. */
46
+ const VITEHUB_DEPLOYMENT_HOST = "__vitehubDeploymentHost";
47
+ /**
48
+ * Feature options that `vitehub()` and `vite-hub/nuxt` resolve for owner plugins during config hooks, such as the Queue
49
+ * provider of the host. Apps set features only in `vitehub()`, so this key is private.
50
+ */
51
+ const VITEHUB_FEATURES = "__vitehubFeatures";
52
+ /** The options that ViteHub resolved for a feature on this Vite config. The owner plugin names their type. */
53
+ function getResolvedFeatureOptions(config, feature) {
54
+ const features = Reflect.get(config, VITEHUB_FEATURES);
55
+ if (!features || typeof features !== "object") return void 0;
56
+ return Reflect.get(features, feature);
57
+ }
58
+ /** The deployment host that `vitehub()` selected on this Vite config. */
59
+ function getDeploymentHost(config) {
60
+ const host = Reflect.get(config, VITEHUB_DEPLOYMENT_HOST);
61
+ return typeof host === "string" ? host : void 0;
62
+ }
63
+ function includesNitroVitePlugin(value) {
64
+ if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
65
+ if (!value || typeof value !== "object") return false;
66
+ return "name" in value && value.name === "nitro:main";
67
+ }
68
+ function hasNitroConfigContext(config) {
69
+ return config["__vitehubNitroConfigContext"] === true || includesNitroVitePlugin(config.plugins);
70
+ }
71
+ function shouldSkipViteProviderBuild(command) {
72
+ return command === "serve";
73
+ }
74
+ function resolveViteHubProjectRoot(root, options = {}) {
75
+ const resolvedRoot = resolve(root);
76
+ const temporaryRoot = resolve(tmpdir());
77
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
78
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
79
+ if (basename(resolvedRoot) === "app") {
80
+ const parent = dirname(resolvedRoot);
81
+ if (parent !== sharedTemporaryRoot && (hasProjectRootDirectoryMarker(parent) || hasProjectRootFileMarker(parent, [
82
+ "nuxt.config.ts",
83
+ "nuxt.config.mts",
84
+ "nuxt.config.js",
85
+ "nuxt.config.mjs"
86
+ ]))) return parent;
87
+ }
88
+ let current = resolvedRoot;
89
+ while (true) {
90
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
91
+ if (hasProjectRootMarker(current)) return current;
92
+ const parent = dirname(current);
93
+ if (parent === current) return resolvedRoot;
94
+ current = parent;
95
+ }
96
+ }
97
+ function hasProjectRootDirectoryMarker(root) {
98
+ for (const marker of projectRootDirectoryMarkers) try {
99
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
100
+ } catch (error) {
101
+ if (error.code !== "ENOENT") throw error;
102
+ }
103
+ return false;
104
+ }
105
+ function hasProjectRootMarker(root) {
106
+ if (hasProjectRootDirectoryMarker(root)) return true;
107
+ return hasProjectRootFileMarker(root, projectRootFileMarkers.flat());
108
+ }
109
+ function hasProjectRootFileMarker(root, markers) {
110
+ for (const marker of markers) {
111
+ const path = Array.isArray(marker) ? marker : [marker];
112
+ try {
113
+ if (statSync(resolve(root, ...path)).isFile()) return true;
114
+ } catch (error) {
115
+ if (error.code !== "ENOENT") throw error;
116
+ }
117
+ }
118
+ return false;
119
+ }
120
+ //#endregion
121
+ //#region ../internal/src/durability.ts
122
+ /** The `durability` module next to the Vite plugin module at `importMetaUrl`, in source and in `dist`. */
123
+ function durabilityModuleFile(importMetaUrl) {
124
+ return fileURLToPath(new URL(importMetaUrl.endsWith(".ts") ? "./durability.ts" : "./durability.js", importMetaUrl));
125
+ }
126
+ //#endregion
127
+ //#region ../internal/src/build/paths.ts
128
+ function generatedDirSegments(productName) {
129
+ return [".vitehub", productName];
130
+ }
131
+ function ensureGeneratedDir(rootDir, productName) {
132
+ return resolve$1(rootDir, ...generatedDirSegments(productName));
133
+ }
134
+ function computePackageDir(importMetaUrl) {
135
+ const currentFileDir = dirname$1(fileURLToPath(importMetaUrl));
136
+ return resolve$1(currentFileDir, basename$1(currentFileDir) === "internal" ? "../.." : "..");
137
+ }
138
+ function resolveRuntimeModule$1(packageDir, modulePath) {
139
+ const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
140
+ return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
141
+ }
142
+ const packageDirs = /* @__PURE__ */ new Map();
143
+ function findPackageDir(file) {
144
+ const start = dirname$1(file);
145
+ const cached = packageDirs.get(start);
146
+ if (cached) return cached;
147
+ let dir = start;
148
+ while (!existsSync(resolve$1(dir, "package.json"))) {
149
+ const parent = dirname$1(dir);
150
+ invariant(parent !== dir, `a file that a package resolver found has a package.json above it (${file})`);
151
+ dir = parent;
152
+ }
153
+ packageDirs.set(start, dir);
154
+ return dir;
155
+ }
156
+ /**
157
+ * The absolute path of a module that the calling package builds, such as `ownModule(import.meta.url, "runtime/state")`.
158
+ * Owner plugins write this path into generated code, so the module needs no package export, and an app resolves it
159
+ * only when the owner's feature is on. It is the `dist` file, or the `src` file before the package is built.
160
+ */
161
+ function ownModule(importMetaUrl, modulePath) {
162
+ return resolveRuntimeModule$1(findPackageDir(fileURLToPath(importMetaUrl)), modulePath);
163
+ }
164
+ function createImportPath(fromFile, targetFile) {
165
+ const fromDir = realpathIfExists(dirname$1(fromFile));
166
+ const target = realpathIfExists(targetFile);
167
+ const importPath = relative(fromDir, target);
168
+ return importPath.startsWith(".") ? importPath : `./${importPath}`;
169
+ }
170
+ function realpathIfExists(path) {
171
+ try {
172
+ return realpathSync.native(path);
173
+ } catch {
174
+ return resolve$1(path);
175
+ }
176
+ }
177
+ //#endregion
178
+ //#region ../internal/src/build/provider-output-config.ts
179
+ function isProviderJsonArray(value, ancestors) {
180
+ if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
181
+ if (Reflect.ownKeys(value).length !== value.length + 1) return false;
182
+ ancestors.add(value);
183
+ try {
184
+ for (let index = 0; index < value.length; index++) {
185
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
186
+ if (!descriptor?.enumerable || !("value" in descriptor) || !isProviderJsonValue(descriptor.value, ancestors)) return false;
187
+ }
188
+ return true;
189
+ } finally {
190
+ ancestors.delete(value);
191
+ }
192
+ }
193
+ function isProviderJsonRecordValue(value, ancestors) {
194
+ const prototype = Object.getPrototypeOf(value);
195
+ if (prototype !== Object.prototype && prototype !== null || ancestors.has(value)) return false;
196
+ ancestors.add(value);
197
+ try {
198
+ return Reflect.ownKeys(value).every((key) => {
199
+ if (typeof key !== "string") return false;
200
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
201
+ return descriptor?.enumerable === true && "value" in descriptor && isProviderJsonValue(descriptor.value, ancestors);
202
+ });
203
+ } finally {
204
+ ancestors.delete(value);
205
+ }
206
+ }
207
+ function isProviderJsonValue(value, ancestors) {
208
+ if (value === null || typeof value === "boolean" || typeof value === "string") return true;
209
+ if (typeof value === "number") return Number.isFinite(value);
210
+ if (Array.isArray(value)) return isProviderJsonArray(value, ancestors);
211
+ return typeof value === "object" && isProviderJsonRecordValue(value, ancestors);
212
+ }
213
+ function isProviderJsonRecord(value) {
214
+ try {
215
+ return typeof value === "object" && value !== null && !Array.isArray(value) && isProviderJsonRecordValue(value, /* @__PURE__ */ new Set());
216
+ } catch {
217
+ return false;
218
+ }
219
+ }
220
+ function assertProviderJsonRecord(value) {
221
+ if (!isProviderJsonRecord(value)) throw internalErrorDiagnostics.INTERNAL_B0043({ message: "[vitehub] Provider output config must be a JSON object." });
222
+ }
223
+ function deleteOwnedFields(value, ownership, cleanup = false) {
224
+ const next = { ...value };
225
+ for (const key of ownership.keys ?? []) delete next[key];
226
+ for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) if (!cleanup || !arrayOwnership.preserveOnCleanup) delete next[field];
227
+ return next;
228
+ }
229
+ function getKeyedArrayEntryValue(value, key) {
230
+ if (key === void 0) return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string" ? value : void 0;
231
+ if (!isProviderJsonRecord(value)) return;
232
+ const entryValue = value[key];
233
+ return entryValue === null || typeof entryValue === "boolean" || typeof entryValue === "number" || typeof entryValue === "string" ? entryValue : void 0;
234
+ }
235
+ function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
236
+ const current = Array.isArray(value) ? value : [];
237
+ const replacementKeys = replacements.flatMap((entry) => {
238
+ const key = getKeyedArrayEntryValue(entry, ownership.key);
239
+ return key === void 0 ? [] : [key];
240
+ });
241
+ const ownedKeys = /* @__PURE__ */ new Set([...ownership.values ?? [], ...replacementKeys]);
242
+ return current.filter((entry) => {
243
+ const key = getKeyedArrayEntryValue(entry, ownership.key);
244
+ return key === void 0 || !ownedKeys.has(key);
245
+ });
246
+ }
247
+ function mergeOwnedArrays(existing, value, arrays) {
248
+ const next = { ...value };
249
+ for (const [field, ownership] of Object.entries(arrays ?? {})) {
250
+ const incoming = Array.isArray(value[field]) ? value[field] : [];
251
+ const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
252
+ if (merged.length) next[field] = merged;
253
+ else delete next[field];
254
+ }
255
+ return next;
256
+ }
257
+ function mergeProviderOutputConfig(existing, value, ownership = {}) {
258
+ assertProviderJsonRecord(existing);
259
+ assertProviderJsonRecord(value);
260
+ return {
261
+ ...deleteOwnedFields(existing, ownership),
262
+ ...mergeOwnedArrays(existing, value, ownership.arrays)
263
+ };
264
+ }
265
+ //#endregion
266
+ //#region ../internal/src/build/bundle-options.ts
267
+ /** Select the runtime constants from one resolved Vite configuration. */
268
+ function resolveViteHubBundleDefines(config) {
269
+ const defines = {};
270
+ for (const name of ["__VITEHUB_PUBLIC_URL__", "__VITEHUB_APP_BASE_URL__"]) {
271
+ const value = config.define?.[name];
272
+ if (typeof value === "string") defines[name] = value;
273
+ }
274
+ return defines;
275
+ }
276
+ //#endregion
277
+ //#region ../internal/src/build/cloudflare-provider-output.ts
278
+ function isDeepStrictEqual(left, right) {
279
+ if (Object.is(left, right)) return true;
280
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
281
+ if (Array.isArray(left) !== Array.isArray(right)) return false;
282
+ if (Array.isArray(left)) return left.length === right.length && left.every((value, index) => isDeepStrictEqual(value, right[index]));
283
+ const leftRecord = left;
284
+ const rightRecord = right;
285
+ const leftKeys = Object.keys(leftRecord);
286
+ const rightKeys = Object.keys(rightRecord);
287
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.hasOwn(rightRecord, key) && isDeepStrictEqual(leftRecord[key], rightRecord[key]));
288
+ }
289
+ const providerOutputCatalogRegistry$1 = globalThis;
290
+ const providerOutputCatalogByNitroValue = providerOutputCatalogRegistry$1.__vitehubProviderOutputCatalogsByNitroValue ??= /* @__PURE__ */ new WeakMap();
291
+ function cloneProviderRecord(value) {
292
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
293
+ return Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => typeof entry === "undefined" ? [] : [[key, cloneProviderValue(entry)]]));
294
+ }
295
+ function cloneProviderValue(value) {
296
+ if (Array.isArray(value)) return value.map((entry) => typeof entry === "undefined" ? null : cloneProviderValue(entry));
297
+ if (value && typeof value === "object") return cloneProviderRecord(value);
298
+ return value;
299
+ }
300
+ function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner) {
301
+ const current = Array.isArray(existing) ? existing.map(cloneProviderRecord) : [];
302
+ return (incoming ?? []).filter((entry) => {
303
+ const identity = entry[identityKey];
304
+ const match = current.find((candidate) => candidate[identityKey] === identity);
305
+ if (!match) {
306
+ current.push(entry);
307
+ return true;
308
+ }
309
+ 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.` });
310
+ return false;
311
+ });
312
+ }
313
+ function removeEntries(existing, entries) {
314
+ if (!Array.isArray(existing) || !entries?.length) return Array.isArray(existing) ? existing : [];
315
+ return existing.filter((entry) => !entries.some((previous) => isDeepStrictEqual(entry, previous)));
316
+ }
317
+ function removeContribution(wrangler, contribution) {
318
+ const queues = cloneProviderRecord(wrangler.queues);
319
+ const secrets = cloneProviderRecord(wrangler.secrets);
320
+ const environments = cloneProviderRecord(wrangler.env);
321
+ const hasQueues = Boolean(contribution.queues?.consumers?.length || contribution.queues?.producers?.length);
322
+ const hasSecrets = Boolean(contribution.requiredSecrets?.length || Object.keys(contribution.requiredSecretsByEnvironment ?? {}).length);
323
+ if (contribution.queues?.consumers?.length) {
324
+ const consumers = removeEntries(queues.consumers, contribution.queues.consumers);
325
+ if (consumers.length) queues.consumers = consumers;
326
+ else delete queues.consumers;
327
+ }
328
+ if (contribution.queues?.producers?.length) {
329
+ const producers = removeEntries(queues.producers, contribution.queues.producers);
330
+ if (producers.length) queues.producers = producers;
331
+ else delete queues.producers;
332
+ }
333
+ if (contribution.requiredSecrets?.length) {
334
+ const required = removeEntries(secrets.required, contribution.requiredSecrets);
335
+ if (required.length) secrets.required = required;
336
+ else delete secrets.required;
337
+ }
338
+ for (const [name, requiredSecrets] of Object.entries(contribution.requiredSecretsByEnvironment ?? {})) {
339
+ if (!Object.hasOwn(environments, name)) continue;
340
+ const environment = cloneProviderRecord(environments[name]);
341
+ const environmentSecrets = cloneProviderRecord(environment.secrets);
342
+ const required = removeEntries(environmentSecrets.required, requiredSecrets);
343
+ if (required.length) environmentSecrets.required = required;
344
+ else delete environmentSecrets.required;
345
+ if (Object.keys(environmentSecrets).length) environment.secrets = environmentSecrets;
346
+ else delete environment.secrets;
347
+ environments[name] = environment;
348
+ }
349
+ const withoutOwned = { ...wrangler };
350
+ if (hasQueues) delete withoutOwned.queues;
351
+ if (hasSecrets) delete withoutOwned.secrets;
352
+ if (hasSecrets) delete withoutOwned.env;
353
+ return {
354
+ ...withoutOwned,
355
+ ...hasQueues && Object.keys(queues).length ? { queues } : {},
356
+ ...hasSecrets && Object.keys(secrets).length ? { secrets } : {},
357
+ ...hasSecrets && Object.keys(environments).length ? { env: environments } : {},
358
+ ...contribution.r2Buckets?.length ? { r2_buckets: removeEntries(wrangler.r2_buckets, contribution.r2Buckets) } : {},
359
+ ...contribution.rateLimits?.length ? { ratelimits: removeEntries(wrangler.ratelimits, contribution.rateLimits) } : {}
360
+ };
361
+ }
362
+ function mergeContribution(wrangler, owner, contribution) {
363
+ const queues = cloneProviderRecord(wrangler.queues);
364
+ const secrets = cloneProviderRecord(wrangler.secrets);
365
+ const environments = cloneProviderRecord(wrangler.env);
366
+ const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner);
367
+ const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
368
+ const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name", "jurisdiction"], owner);
369
+ const rateLimits = compatibleEntries(wrangler.ratelimits, contribution.rateLimits, "name", ["namespace_id", "simple"], owner);
370
+ const currentRequiredSecrets = Array.isArray(secrets.required) ? secrets.required : [];
371
+ const requiredSecrets = (contribution.requiredSecrets ?? []).filter((name) => !currentRequiredSecrets.includes(name));
372
+ if (requiredSecrets.length) secrets.required = [...currentRequiredSecrets, ...requiredSecrets];
373
+ const requiredSecretsByEnvironment = {};
374
+ for (const [name, value] of Object.entries(environments)) {
375
+ const environment = cloneProviderRecord(value);
376
+ const environmentSecrets = cloneProviderRecord(environment.secrets);
377
+ const current = Array.isArray(environmentSecrets.required) ? environmentSecrets.required : [];
378
+ const required = (contribution.requiredSecrets ?? []).filter((secret) => !current.includes(secret));
379
+ if (required.length) {
380
+ environmentSecrets.required = [...current, ...required];
381
+ environment.secrets = environmentSecrets;
382
+ environments[name] = environment;
383
+ requiredSecretsByEnvironment[name] = required;
384
+ }
385
+ }
386
+ const nextQueues = mergeProviderOutputConfig(queues, {
387
+ ...consumers.length ? { consumers } : {},
388
+ ...producers.length ? { producers } : {}
389
+ }, { arrays: {
390
+ consumers: { key: "queue" },
391
+ producers: { key: "binding" }
392
+ } });
393
+ return [mergeProviderOutputConfig(wrangler, {
394
+ ...Object.keys(nextQueues).length ? { queues: nextQueues } : {},
395
+ ...r2Buckets.length ? { r2_buckets: r2Buckets } : {},
396
+ ...rateLimits.length ? { ratelimits: rateLimits } : {},
397
+ ...Object.keys(secrets).length ? { secrets } : {},
398
+ ...Object.keys(environments).length ? { env: environments } : {}
399
+ }, { arrays: {
400
+ r2_buckets: { key: "binding" },
401
+ ratelimits: { key: "name" }
402
+ } }), {
403
+ queues: {
404
+ consumers,
405
+ producers
406
+ },
407
+ r2Buckets,
408
+ rateLimits,
409
+ requiredSecrets,
410
+ requiredSecretsByEnvironment
411
+ }];
412
+ }
413
+ function inheritedProviderOutputCatalog(value) {
414
+ if (!value || typeof value !== "object") return;
415
+ const cloudflare = value.cloudflare;
416
+ const wrangler = cloudflare && typeof cloudflare === "object" ? cloudflare.wrangler : void 0;
417
+ return providerOutputCatalogByNitroValue.get(value) ?? (cloudflare && typeof cloudflare === "object" ? providerOutputCatalogByNitroValue.get(cloudflare) : void 0) ?? (wrangler && typeof wrangler === "object" ? providerOutputCatalogByNitroValue.get(wrangler) : void 0);
418
+ }
419
+ function associateProviderOutputCatalog(output, catalog) {
420
+ providerOutputCatalogByNitroValue.set(output, catalog);
421
+ const cloudflare = output.cloudflare;
422
+ if (!cloudflare || typeof cloudflare !== "object") return;
423
+ providerOutputCatalogByNitroValue.set(cloudflare, catalog);
424
+ const wrangler = cloudflare.wrangler;
425
+ if (wrangler && typeof wrangler === "object") providerOutputCatalogByNitroValue.set(wrangler, catalog);
426
+ }
427
+ function composeNitroCloudflareProviderOutput(catalog, value, inheritedValue = value) {
428
+ const nitro = cloneRecord(value);
429
+ const cloudflare = cloneRecord(nitro.cloudflare);
430
+ const inherited = inheritedProviderOutputCatalog(inheritedValue) ?? inheritedProviderOutputCatalog(value);
431
+ if (inherited && inherited !== catalog) catalog.inheritCloudflareContributions(inherited);
432
+ let wrangler = cloneProviderRecord(cloudflare.wrangler);
433
+ for (const contribution of catalog.appliedCloudflareContributions()) wrangler = removeContribution(wrangler, contribution);
434
+ catalog.clearAppliedCloudflareContributions();
435
+ for (const [owner, contribution] of catalog.cloudflareContributions()) {
436
+ const [merged, applied] = mergeContribution(wrangler, owner, contribution);
437
+ wrangler = merged;
438
+ catalog.replaceAppliedCloudflareContribution(owner, applied);
439
+ }
440
+ const output = !Object.keys(cloudflare).length && !Object.keys(wrangler).length ? nitro : {
441
+ ...nitro,
442
+ cloudflare: {
443
+ ...cloudflare,
444
+ wrangler
445
+ }
446
+ };
447
+ associateProviderOutputCatalog(output, catalog);
448
+ return output;
449
+ }
450
+ //#endregion
451
+ //#region ../internal/src/build/provider-output-catalog.ts
452
+ var ProviderOutputCatalog = class {
453
+ bundleDefines = {};
454
+ #appliedCloudflareContributions = /* @__PURE__ */ new Map();
455
+ #cloudflareContributions = /* @__PURE__ */ new Map();
456
+ #runtimeContributions = /* @__PURE__ */ new Map();
457
+ #runtimeContributionsByGeneration = /* @__PURE__ */ new WeakMap();
458
+ #deploymentContributionSequence = 0;
459
+ #deploymentContributions = /* @__PURE__ */ new Map();
460
+ #deploymentGenerationRefs = /* @__PURE__ */ new WeakMap();
461
+ #deploymentGenerations = /* @__PURE__ */ new Set();
462
+ #pendingDeploymentDiscards = [];
463
+ #takenDeploymentContributions = /* @__PURE__ */ new Map();
464
+ appliedCloudflareContributions() {
465
+ return this.#appliedCloudflareContributions.values();
466
+ }
467
+ appliedCloudflareContributionEntries() {
468
+ return this.#appliedCloudflareContributions.entries();
469
+ }
470
+ clearAppliedCloudflareContributions() {
471
+ this.#appliedCloudflareContributions.clear();
472
+ }
473
+ cloudflareContributions() {
474
+ return this.#cloudflareContributions.entries();
475
+ }
476
+ inheritCloudflareContributions(catalog) {
477
+ for (const [owner, contribution] of catalog.appliedCloudflareContributionEntries()) this.#appliedCloudflareContributions.set(owner, contribution);
478
+ for (const [owner, contribution] of [...catalog.cloudflareContributions(), ...this.#cloudflareContributions]) this.#cloudflareContributions.set(owner, contribution);
479
+ }
480
+ replaceAppliedCloudflareContribution(owner, contribution) {
481
+ this.#appliedCloudflareContributions.set(owner, contribution);
482
+ }
483
+ replaceCloudflareContribution(owner, contribution) {
484
+ this.#cloudflareContributions.set(owner, contribution);
485
+ }
486
+ replaceRuntimeContribution(contribution, generation) {
487
+ if (!generation) {
488
+ this.#runtimeContributions.set(contribution.owner, contribution);
489
+ return;
490
+ }
491
+ let contributions = this.#runtimeContributionsByGeneration.get(generation);
492
+ if (!contributions) {
493
+ contributions = /* @__PURE__ */ new Map();
494
+ this.#runtimeContributionsByGeneration.set(generation, contributions);
495
+ }
496
+ contributions.set(contribution.owner, contribution);
497
+ }
498
+ runtimeContribution(product, generation) {
499
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.get(product);
500
+ }
501
+ runtimeContributions(generation) {
502
+ return (generation ? this.#runtimeContributionsByGeneration.get(generation) : this.#runtimeContributions)?.entries() ?? (/* @__PURE__ */ new Map()).entries();
503
+ }
504
+ resetRuntimeContributions(generation, owner) {
505
+ if (generation) {
506
+ if (owner) this.#runtimeContributionsByGeneration.get(generation)?.delete(owner);
507
+ else this.#runtimeContributionsByGeneration.delete(generation);
508
+ return;
509
+ }
510
+ if (owner) this.#runtimeContributions.delete(owner);
511
+ else this.#runtimeContributions.clear();
512
+ }
513
+ createDeploymentGeneration() {
514
+ const generation = { valid: true };
515
+ this.#trackDeploymentGeneration(generation);
516
+ return generation;
517
+ }
518
+ replaceDeploymentContribution(contribution, generation) {
519
+ const entry = {
520
+ contribution,
521
+ generation,
522
+ sequence: this.#deploymentContributionSequence++
523
+ };
524
+ if (generation && !generation.valid) {
525
+ this.#queueDeploymentDiscard(entry);
526
+ return;
527
+ }
528
+ this.#restoreDeploymentContribution(entry);
529
+ }
530
+ resetDeploymentContributions(generation) {
531
+ if (!generation) {
532
+ for (const reference of this.#deploymentGenerations) {
533
+ const current = reference.deref();
534
+ if (current) current.valid = false;
535
+ }
536
+ this.#deploymentGenerations.clear();
537
+ for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
538
+ for (const taken of this.#takenDeploymentContributions.values()) {
539
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
540
+ for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
541
+ }
542
+ this.#deploymentContributions.clear();
543
+ this.#takenDeploymentContributions.clear();
544
+ return;
545
+ }
546
+ generation.valid = false;
547
+ this.#deleteDeploymentGeneration(generation);
548
+ for (const [owner, entries] of this.#deploymentContributions) {
549
+ for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
550
+ const remaining = entries.filter((entry) => entry.generation !== generation);
551
+ if (remaining.length) this.#deploymentContributions.set(owner, remaining);
552
+ else this.#deploymentContributions.delete(owner);
553
+ }
554
+ for (const [contribution, taken] of this.#takenDeploymentContributions) {
555
+ const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
556
+ taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
557
+ for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
558
+ if (taken.entry.generation !== generation) continue;
559
+ this.#takenDeploymentContributions.delete(contribution);
560
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
561
+ for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
562
+ else this.#restoreDeploymentContribution(fallback);
563
+ }
564
+ }
565
+ hasDeploymentContributions() {
566
+ return this.#deploymentContributions.size > 0;
567
+ }
568
+ takeDeploymentContributions() {
569
+ const contributions = [];
570
+ for (const [owner, entries] of this.#deploymentContributions) {
571
+ const entry = entries.at(-1);
572
+ contributions.push(entry.contribution);
573
+ this.#takenDeploymentContributions.set(entry.contribution, {
574
+ committed: false,
575
+ entry,
576
+ entryDiscarded: false,
577
+ fallbacks: entries.slice(0, -1)
578
+ });
579
+ this.#deploymentContributions.delete(owner);
580
+ }
581
+ return contributions;
582
+ }
583
+ deploymentContributionGeneration(contribution) {
584
+ return this.#takenDeploymentContributions.get(contribution)?.entry.generation;
585
+ }
586
+ commitDeploymentContributions(contributions) {
587
+ for (const contribution of contributions) {
588
+ const taken = this.#takenDeploymentContributions.get(contribution);
589
+ if (taken) taken.committed = true;
590
+ }
591
+ }
592
+ async prepareDeploymentContributions(contributions) {
593
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
594
+ for (const contribution of contributions) {
595
+ const taken = this.#takenDeploymentContributions.get(contribution);
596
+ if (!taken || taken.entryDiscarded || !taken.entry.contribution.discard) continue;
597
+ taken.entryDiscarded = true;
598
+ discarded.push(Promise.resolve().then(taken.entry.contribution.discard));
599
+ }
600
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
601
+ if (failure) throw failure.reason;
602
+ }
603
+ async completeDeploymentContributions(contributions) {
604
+ const discarded = this.#pendingDeploymentDiscards.splice(0);
605
+ const completedGenerations = /* @__PURE__ */ new Set();
606
+ for (const contribution of contributions) {
607
+ const taken = this.#takenDeploymentContributions.get(contribution);
608
+ if (!taken) continue;
609
+ this.#takenDeploymentContributions.delete(contribution);
610
+ const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
611
+ for (const entry of entries) {
612
+ if (entry.generation) completedGenerations.add(entry.generation);
613
+ if (entry.contribution.discard) discarded.push(entry.contribution.discard());
614
+ }
615
+ }
616
+ for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
617
+ const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
618
+ if (failure) throw failure.reason;
619
+ }
620
+ rollbackDeploymentContributions(contributions) {
621
+ for (const contribution of contributions) {
622
+ const taken = this.#takenDeploymentContributions.get(contribution);
623
+ if (!taken) continue;
624
+ this.#takenDeploymentContributions.delete(contribution);
625
+ for (const entry of [...taken.fallbacks, taken.entry]) this.#restoreDeploymentContribution(entry);
626
+ }
627
+ }
628
+ #restoreDeploymentContribution(entry) {
629
+ if (entry.generation && !entry.generation.valid) return;
630
+ if (entry.generation) this.#trackDeploymentGeneration(entry.generation);
631
+ const entries = this.#deploymentContributions.get(entry.contribution.owner) ?? [];
632
+ const replaced = entries.findIndex((candidate) => candidate.generation === entry.generation);
633
+ if (replaced >= 0) {
634
+ if (entries[replaced].sequence > entry.sequence) return;
635
+ entries.splice(replaced, 1);
636
+ }
637
+ entries.push(entry);
638
+ entries.sort((left, right) => left.sequence - right.sequence);
639
+ this.#deploymentContributions.set(entry.contribution.owner, entries);
640
+ }
641
+ #retireDeploymentGeneration(generation) {
642
+ const pending = [...this.#deploymentContributions.values()].some((entries) => entries.some((entry) => entry.generation === generation));
643
+ const taken = [...this.#takenDeploymentContributions.values()].some((entry) => entry.entry.generation === generation || entry.fallbacks.some((fallback) => fallback.generation === generation));
644
+ if (!pending && !taken) this.#deleteDeploymentGeneration(generation);
645
+ }
646
+ #trackDeploymentGeneration(generation) {
647
+ if (this.#deploymentGenerationRefs.has(generation)) return;
648
+ const reference = new WeakRef(generation);
649
+ this.#deploymentGenerationRefs.set(generation, reference);
650
+ this.#deploymentGenerations.add(reference);
651
+ }
652
+ #deleteDeploymentGeneration(generation) {
653
+ const reference = this.#deploymentGenerationRefs.get(generation);
654
+ if (reference) this.#deploymentGenerations.delete(reference);
655
+ this.#deploymentGenerationRefs.delete(generation);
656
+ }
657
+ #queueDeploymentDiscard(entry) {
658
+ if (!entry.contribution.discard) return;
659
+ const discard = Promise.resolve().then(entry.contribution.discard);
660
+ discard.catch(() => {});
661
+ this.#pendingDeploymentDiscards.push(discard);
662
+ }
663
+ };
664
+ const providerOutputCatalogRegistry = globalThis;
665
+ const providerOutputCatalogs = providerOutputCatalogRegistry.__vitehubProviderOutputCatalogs ??= /* @__PURE__ */ new WeakMap();
666
+ const providerOutputCatalog = Symbol.for("vitehub.provider-output-catalog");
667
+ function createProviderOutputCatalog() {
668
+ return new ProviderOutputCatalog();
669
+ }
670
+ function useProviderOutputCatalog(config) {
671
+ const owner = config;
672
+ let catalog = owner[providerOutputCatalog] ?? providerOutputCatalogs.get(config);
673
+ if (!catalog) catalog = createProviderOutputCatalog();
674
+ catalog.bundleDefines = resolveViteHubBundleDefines(config);
675
+ owner[providerOutputCatalog] = catalog;
676
+ providerOutputCatalogs.set(config, catalog);
677
+ return catalog;
678
+ }
679
+ function contributeCloudflareProviderOutput(catalog, contribution) {
680
+ const { owner, ...value } = contribution;
681
+ catalog.replaceCloudflareContribution(owner, value);
682
+ }
683
+ //#endregion
684
+ //#region ../internal/src/nitro-kit.ts
685
+ function cloneArray(value) {
686
+ return Array.isArray(value) ? [...value] : [];
687
+ }
688
+ function sameHandler(left, right) {
689
+ return left.handler === right.handler && left.route === right.route && left.method === right.method && left.middleware === right.middleware;
690
+ }
691
+ /** Create a Nitro 3 configuration builder for generated ViteHub output. */
692
+ function createNitroServerKit(value = {}) {
693
+ const config = isRecordOrFunction(value) ? { ...value } : {};
694
+ const handlers = cloneArray(config.handlers);
695
+ const plugins = cloneArray(config.plugins);
696
+ config.handlers = handlers;
697
+ config.plugins = plugins;
698
+ return {
699
+ config,
700
+ addHandler(handler, position = "end") {
701
+ if (handlers.some((candidate) => isRecordOrFunction(candidate) && sameHandler(candidate, handler))) return;
702
+ if (position === "start") handlers.unshift({ ...handler });
703
+ else handlers.push({ ...handler });
704
+ },
705
+ addPlugin(plugin, position = "end") {
706
+ if (plugins.includes(plugin)) return;
707
+ if (position === "start") plugins.unshift(plugin);
708
+ else plugins.push(plugin);
709
+ }
710
+ };
711
+ }
712
+ /** Add one module id to a Nitro or Rollup `external` option, in each form that option takes. */
713
+ function mergeNitroExternal(value, addition) {
714
+ if (typeof value === "undefined") return [addition];
715
+ if (Array.isArray(value)) return value.includes(addition) ? [...value] : [...value, addition];
716
+ if (typeof value === "string" || value instanceof RegExp) return [value, addition];
717
+ if (typeof value === "function") return (source, importer, isResolved) => source === addition || Boolean(value(source, importer, isResolved));
718
+ return value;
719
+ }
720
+ //#endregion
721
+ //#region ../internal/src/contributions.ts
722
+ const unnamedPlugin = "unnamed plugin";
723
+ function isNonEmptyString(value) {
724
+ return String(value) === value && value.length > 0;
725
+ }
726
+ function isThenable(value) {
727
+ return typeof value.then === "function";
728
+ }
729
+ async function flattenPlugins(value, plugins, seen) {
730
+ if (Array.isArray(value)) {
731
+ for (const item of value) await flattenPlugins(item, plugins, seen);
732
+ return;
733
+ }
734
+ if (!isRecord(value) || seen.has(value)) return;
735
+ seen.add(value);
736
+ if (isThenable(value)) {
737
+ await flattenPlugins(await value, plugins, seen);
738
+ return;
739
+ }
740
+ plugins.push(value);
741
+ }
742
+ function readModule(value) {
743
+ if (!/^file:/i.test(value)) return value;
744
+ const url = value.slice(5);
745
+ return url.startsWith("/") ? fileURLToPath(`file:${url}`) : void 0;
746
+ }
747
+ function isRelative(module) {
748
+ return !isAbsolute$1(module) && /^\.\.?(?:[\\/]|$)/.test(module);
749
+ }
750
+ /** Describes a contribution as `module#export from plugin "name"` for messages. */
751
+ function describeContribution(contribution) {
752
+ const { export: exportName, module } = contribution.definition;
753
+ return `${exportName === "default" ? module : `${module}#${exportName}`} from plugin ${JSON.stringify(contribution.plugin)}`;
754
+ }
755
+ async function collectContributions(plugins, options) {
756
+ const candidates = [];
757
+ await flattenPlugins(plugins ?? [], candidates, /* @__PURE__ */ new Set());
758
+ const collected = /* @__PURE__ */ new Map();
759
+ for (const plugin of candidates) {
760
+ if (!Object.hasOwn(plugin, "vitehub")) continue;
761
+ const metadata = Reflect.get(plugin, "vitehub");
762
+ if (!isRecord(metadata) || !Object.hasOwn(metadata, options.key)) continue;
763
+ const source = metadata[options.key];
764
+ const pluginName = Reflect.get(plugin, "name");
765
+ const contributor = isNonEmptyString(pluginName) ? pluginName : unnamedPlugin;
766
+ const fail = (reason) => {
767
+ throw options.invalid(`[vitehub] Plugin ${JSON.stringify(contributor)} contributed an invalid ${options.kind}: ${reason}`);
768
+ };
769
+ const callable = typeof source === "function";
770
+ const entries = callable ? await Reflect.apply(source, void 0, [options.context]) : source;
771
+ if (entries === void 0 && callable) continue;
772
+ if (!Array.isArray(entries)) fail(`\`vitehub.${options.key}\` must be an array or a function that returns one.`);
773
+ const list = entries;
774
+ for (const entry of list) {
775
+ const contribution = readContribution(entry, contributor, options, fail);
776
+ const { plugin: _plugin, reason: _reason, ...definitionIdentity } = contribution;
777
+ const identity = JSON.stringify(definitionIdentity);
778
+ const existing = collected.get(contribution.name);
779
+ if (existing?.identity === identity) continue;
780
+ if (existing) throw options.duplicate(`[vitehub] ${options.kind} ${JSON.stringify(contribution.name)} is contributed more than once:\n - ${describeContribution(existing.contribution)}\n - ${describeContribution(contribution)}\nEach ${options.kind} name must have one contribution. Rename or remove one.`);
781
+ collected.set(contribution.name, {
782
+ contribution,
783
+ identity
784
+ });
785
+ }
786
+ }
787
+ return [...collected.values()].map(({ contribution }) => contribution).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
788
+ }
789
+ function readContribution(entry, plugin, options, fail) {
790
+ if (!isRecord(entry)) return fail("expected { name, definition: { module, export? }, reason? }.");
791
+ const { definition, name, reason } = entry;
792
+ if (!isNonEmptyString(name) || name.trim() !== name) return fail("`name` must be a non-empty string without surrounding whitespace.");
793
+ const nameProblem = options.checkName?.(name);
794
+ if (nameProblem) return fail(`${options.kind} ${JSON.stringify(name)}: ${nameProblem}`);
795
+ if (!isRecord(definition)) return fail(`${options.kind} ${JSON.stringify(name)} needs \`definition: { module, export? }\`.`);
796
+ if (!isNonEmptyString(definition.module)) return fail(`\`definition.module\` of ${options.kind} ${JSON.stringify(name)} must be a non-empty string.`);
797
+ let module;
798
+ try {
799
+ module = readModule(definition.module);
800
+ } catch {
801
+ module = void 0;
802
+ }
803
+ if (module === void 0) return fail(`\`definition.module\` of ${options.kind} ${JSON.stringify(name)} must be a valid file URL or module specifier.`);
804
+ if (isRelative(module)) return fail(`\`definition.module\` of ${options.kind} ${JSON.stringify(name)} is relative: ${JSON.stringify(module)}. Use an absolute file path, a file: URL, or a package specifier.`);
805
+ const exportName = definition.export ?? "default";
806
+ if (!isNonEmptyString(exportName)) return fail(`\`definition.export\` of ${options.kind} ${JSON.stringify(name)} must be a non-empty string.`);
807
+ if (reason !== void 0 && !isNonEmptyString(reason)) return fail(`\`reason\` of ${options.kind} ${JSON.stringify(name)} must be a non-empty string.`);
808
+ const base = {
809
+ definition: {
810
+ export: exportName,
811
+ module
812
+ },
813
+ name,
814
+ plugin
815
+ };
816
+ if (reason !== void 0) base.reason = reason;
817
+ return {
818
+ ...options.fields?.(entry, fail),
819
+ ...base
820
+ };
821
+ }
822
+ //#endregion
823
+ //#region src/contributions.ts
824
+ const queueNamePattern = /^[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)*$/i;
825
+ function invalid(message) {
826
+ return queueErrorDiagnostics.QUEUE_CONTRIBUTION_INVALID({ message });
827
+ }
828
+ /**
829
+ * Collects `vitehub.queues` contributions from Vite plugins. Two contributions with one name fail with
830
+ * `QUEUE_DEFINITION_DUPLICATE`. Invalid entries fail with `QUEUE_CONTRIBUTION_INVALID`.
831
+ */
832
+ async function collectQueueContributions(plugins, context) {
833
+ const contributions = await collectContributions(plugins, {
834
+ checkName: (name) => queueNamePattern.test(name) ? void 0 : "`name` must be letters, numbers, dots, underscores, dashes, and slashes, for example \"webhooks/deliver\".",
835
+ context,
836
+ duplicate: (message) => queueErrorDiagnostics.QUEUE_DEFINITION_DUPLICATE({ message }),
837
+ invalid,
838
+ key: "queues",
839
+ kind: "Queue"
840
+ });
841
+ for (const contribution of contributions) {
842
+ const { export: exportName, module } = contribution.definition;
843
+ const prefix = `[vitehub] Plugin ${JSON.stringify(contribution.plugin)} contributed an invalid Queue:`;
844
+ if (!isAbsolute(module)) throw invalid(`${prefix} \`definition.module\` of Queue ${JSON.stringify(contribution.name)} must be an absolute file path or a file: URL.`);
845
+ if (exportName !== "default") throw invalid(`${prefix} Queue ${JSON.stringify(contribution.name)} uses \`definition.export: ${JSON.stringify(exportName)}\`. Queue Definitions must be the default export.`);
846
+ if (!existsSync(module)) throw invalid(`${prefix} the module of Queue ${JSON.stringify(contribution.name)} does not exist: ${module}`);
847
+ }
848
+ return contributions;
849
+ }
850
+ //#endregion
851
+ //#region src/deployment-env.ts
852
+ const owners = ["queue"];
853
+ /**
854
+ * The variables that Queue reads on the deployed host. The `postgres` provider reads `QUEUE_POSTGRES_URL`, which is
855
+ * required unless the build found a Postgres Default Database to borrow. The `vercel` provider reads the optional
856
+ * `QUEUE_REGION`. Cloudflare Queues and the `local` provider read none.
857
+ */
858
+ function queueDeploymentEnv(queue) {
859
+ if (!queue) return [];
860
+ if (queue.driver === "postgres") return [{
861
+ names: [postgresQueueUrlVariable],
862
+ required: !queue.database,
863
+ secret: true,
864
+ hasDefault: Boolean(queue.database),
865
+ owners
866
+ }];
867
+ if (queue.driver === "vercel") return [{
868
+ names: ["QUEUE_REGION"],
869
+ required: false,
870
+ secret: false,
871
+ hasDefault: false,
872
+ owners
873
+ }];
874
+ return [];
875
+ }
876
+ //#endregion
877
+ //#region ../internal/src/definition-catalog.ts
878
+ const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
879
+ const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
880
+ const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
881
+ const ignoredDirs = /* @__PURE__ */ new Set([
882
+ "node_modules",
883
+ "dist",
884
+ ".output",
885
+ ".nuxt",
886
+ ".vercel",
887
+ ".git",
888
+ ".vitehub"
889
+ ]);
890
+ function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
891
+ return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
892
+ }
893
+ function createDirectoryDefinitionSource(source, scanDirs, subdir, options = {}) {
894
+ return {
895
+ ...options,
896
+ kind: "directory",
897
+ scanDirs,
898
+ source,
899
+ subdir
900
+ };
901
+ }
902
+ function createSuffixDefinitionSource(source, roots, pattern, normalizeName, options = {}) {
903
+ return {
904
+ ...options,
905
+ kind: "suffix",
906
+ normalizeName,
907
+ pattern,
908
+ roots,
909
+ source
910
+ };
911
+ }
912
+ function readDirEntries(root) {
913
+ try {
914
+ return readdirSync(root, { withFileTypes: true });
915
+ } catch (error) {
916
+ if (error.code === "ENOENT") return [];
917
+ throw error;
918
+ }
919
+ }
920
+ function isGitRepositoryDirectory(directory) {
921
+ return existsSync(resolve$1(directory, ".git"));
922
+ }
923
+ function listMatchingFiles(root, predicate, options = {}) {
924
+ const files = [];
925
+ for (const entry of readDirEntries(root)) {
926
+ const absolute = resolve$1(root, entry.name);
927
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
928
+ if (isGitRepositoryDirectory(absolute)) continue;
929
+ if (entry.name.startsWith(".")) continue;
930
+ if (ignoredDirs.has(entry.name)) continue;
931
+ files.push(...listMatchingFiles(absolute, predicate, options));
932
+ continue;
933
+ }
934
+ if (entry.name.startsWith(".") && !options.includeHidden) continue;
935
+ if (entry.isFile() && predicate(entry.name)) files.push(absolute);
936
+ }
937
+ return files.sort();
938
+ }
939
+ /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
940
+ function isDefinitionSourceFile(name) {
941
+ return sourceFilePattern.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
942
+ }
943
+ function listSourceFiles(root, options = {}) {
944
+ return listMatchingFiles(root, isDefinitionSourceFile, options);
945
+ }
946
+ function normalizePathDefinitionName(rootDir, file) {
947
+ return relative(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
948
+ }
949
+ function normalizeSuffixDefinitionName(rootDir, file, pattern, options = {}) {
950
+ const normalized = relative(rootDir, file).replace(pattern, "");
951
+ if (options.stripPrefix && normalized.startsWith(options.stripPrefix)) return normalized.slice(options.stripPrefix.length);
952
+ return normalized;
953
+ }
954
+ function sortDefinitions(definitions) {
955
+ return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
956
+ }
957
+ function registerDefinition(definitions, definition, sourceLabel) {
958
+ const existing = definitions.get(definition.name);
959
+ if (existing) throw internalErrorDiagnostics.INTERNAL_C0001({ message: `Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}` });
960
+ definitions.set(definition.name, definition);
961
+ }
962
+ function mergeDefinitions(feature, ...sources) {
963
+ const definitions = /* @__PURE__ */ new Map();
964
+ for (const source of sources) {
965
+ if (!source) continue;
966
+ for (const definition of source) {
967
+ const existing = definitions.get(definition.name);
968
+ 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"})` });
969
+ if (!existing) definitions.set(definition.name, definition);
970
+ }
971
+ }
972
+ return sortDefinitions(definitions);
973
+ }
974
+ function createDefinition(source, file, name) {
975
+ if (source.createDefinition) return source.createDefinition({
976
+ file,
977
+ name
978
+ });
979
+ return {
980
+ handler: file,
981
+ name,
982
+ source: source.source
983
+ };
984
+ }
985
+ function scanSuffixDefinitions(feature, source) {
986
+ const definitions = /* @__PURE__ */ new Map();
987
+ for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => {
988
+ source.pattern.lastIndex = 0;
989
+ return source.pattern.test(name);
990
+ }, { includeHidden: source.includeHidden })) {
991
+ const name = source.normalizeName(root, file);
992
+ if (!name) continue;
993
+ registerDefinition(definitions, createDefinition(source, file, name), feature);
994
+ }
995
+ return sortDefinitions(definitions);
996
+ }
997
+ function scanDirectoryDefinitions(feature, source) {
998
+ const definitions = /* @__PURE__ */ new Map();
999
+ for (const scanDir of source.scanDirs) {
1000
+ const directory = resolve$1(scanDir, source.subdir);
1001
+ for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
1002
+ const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
1003
+ if (!name) continue;
1004
+ registerDefinition(definitions, createDefinition(source, file, name), feature);
1005
+ }
1006
+ }
1007
+ return sortDefinitions(definitions);
1008
+ }
1009
+ function discoverDefinitions(feature, sources) {
1010
+ return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
1011
+ }
1012
+ function createImportExpression(registryFile, file) {
1013
+ const importPath = relative(resolve$1(registryFile, ".."), file);
1014
+ return `import(${JSON.stringify(importPath.startsWith(".") ? importPath : `./${importPath}`)})`;
1015
+ }
1016
+ function createRuntimeRegistryContents(registryFile, definitions) {
1017
+ return [
1018
+ "",
1019
+ "const registry = {",
1020
+ ...definitions.map((definition) => ` [${JSON.stringify(definition.name)}]: async () => ${createImportExpression(registryFile, definition.handler)},`),
1021
+ "}",
1022
+ "",
1023
+ "export default registry",
1024
+ ""
1025
+ ].join("\n");
1026
+ }
1027
+ //#endregion
1028
+ //#region src/discovery.ts
1029
+ const queueSuffixPattern = /\.queue\.(?:c|m)?[jt]s$/i;
1030
+ /** Discovery source of Queue Definitions that Vite plugins contribute through `vitehub.queues`. */
1031
+ const contributedQueueSource = "vite-plugin-contribution";
1032
+ function normalizeSuffixQueueName(rootDir, file) {
1033
+ return normalizeSuffixDefinitionName(rootDir, file, queueSuffixPattern, { stripPrefix: "src/" });
1034
+ }
1035
+ function mergeContributedQueueDefinitions(discovered, contributions) {
1036
+ if (!contributions?.length) return discovered;
1037
+ const definitions = new Map(discovered.map((definition) => [definition.name, definition]));
1038
+ for (const contribution of contributions) {
1039
+ const existing = definitions.get(contribution.name);
1040
+ if (existing) throw queueErrorDiagnostics.QUEUE_DEFINITION_DUPLICATE({ message: `[vitehub] Queue "${contribution.name}" is defined more than once:\n - ${existing.handler}\n - ${describeContribution(contribution)}\nRename or remove one definition. Each Queue name must have one definition.` });
1041
+ const definition = {
1042
+ contributor: contribution.plugin,
1043
+ handler: contribution.definition.module,
1044
+ name: contribution.name,
1045
+ source: contributedQueueSource
1046
+ };
1047
+ if (contribution.reason) definition.reason = contribution.reason;
1048
+ definitions.set(contribution.name, definition);
1049
+ }
1050
+ return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
1051
+ }
1052
+ function discoverQueueDefinitions(options) {
1053
+ if (options.mode === "server-queues") return mergeContributedQueueDefinitions(discoverDefinitions("queue", [createDirectoryDefinitionSource("server-queues", options.scanDirs, "queues")]), options.contributions);
1054
+ const roots = resolveDefinitionScanRoots(options.rootDir, options.scanDirs);
1055
+ const serverScanDirs = options.serverDirs || [...new Set(options.serverRootDirs || roots)].map((root) => resolve$1(root, "server"));
1056
+ return mergeContributedQueueDefinitions(discoverDefinitions("queue", [createSuffixDefinitionSource("vite-suffix", roots, queueSuffixPattern, normalizeSuffixQueueName), createDirectoryDefinitionSource("server-queues", serverScanDirs, "queues")]), options.contributions);
1057
+ }
1058
+ //#endregion
1059
+ //#region src/registry-types.ts
1060
+ function createQueueTypes(file, definitions, importBase = "@vite-hub/queue") {
1061
+ const entries = definitions.map((definition) => {
1062
+ const path = relative(dirname$1(file), definition.handler);
1063
+ const specifier = path.startsWith(".") ? path : `./${path}`;
1064
+ return ` ${JSON.stringify(definition.name)}: typeof import(${JSON.stringify(specifier)}).default`;
1065
+ });
1066
+ return [
1067
+ `import ${JSON.stringify(importBase)}`,
1068
+ `declare module ${JSON.stringify(importBase)} {`,
1069
+ " interface QueueRegistry {",
1070
+ ...entries,
1071
+ " }",
1072
+ "}",
1073
+ ""
1074
+ ].join("\n");
1075
+ }
1076
+ async function writeQueueTypes(root, definitions, importBase = "@vite-hub/queue") {
1077
+ const file = resolve$1(root, ".vitehub/queue.d.ts");
1078
+ await mkdir(dirname$1(file), { recursive: true });
1079
+ await writeFile(file, createQueueTypes(file, definitions, importBase), "utf8");
1080
+ }
1081
+ //#endregion
1082
+ //#region src/internal/vite-build.ts
1083
+ const queuePackageName = "@vite-hub/queue";
1084
+ const productName = "queue";
1085
+ const generatedRegistryFileName = "registry.mjs";
1086
+ const generatedQueueTestSetup = ".vitehub/queue/test-setup.mjs";
1087
+ const generatedQueueNitroPlugin = ".vitehub/nitro/queue/plugin.ts";
1088
+ const generatedQueueNitroMiddleware = ".vitehub/nitro/queue/middleware.ts";
1089
+ const generatedQueueNitroVercelConsumerDir = ".vitehub/nitro/queue/vercel";
1090
+ const vercelQueueConsumerRoutePrefix = "/api/vitehub/queues/vercel";
1091
+ const packageDir = computePackageDir(import.meta.url);
1092
+ const packageRequire = createRequire(resolve(packageDir, "package.json"));
1093
+ /** `@vercel/queue` and `@vercel/functions` are optional peers. A Vercel build needs both in the app. */
1094
+ function resolveVercelDependency(specifier) {
1095
+ try {
1096
+ return packageRequire.resolve(specifier);
1097
+ } catch (cause) {
1098
+ throw queueErrorDiagnostics.QUEUE_VERCEL_SDK_UNAVAILABLE({ cause });
1099
+ }
1100
+ }
1101
+ const resolveRuntimeModule = (modulePath) => resolveRuntimeModule$1(packageDir, modulePath);
1102
+ function resolveOutputQueueConfig(queue, hosting, postgresDatabase) {
1103
+ if (typeof queue === "undefined") return false;
1104
+ return normalizeQueueOptions(queue, {
1105
+ hosting,
1106
+ postgresDatabase
1107
+ }) || false;
1108
+ }
1109
+ /**
1110
+ * The Queue configuration that the generated server installs. `vite dev` runs in Node, where Cloudflare and Vercel
1111
+ * cannot deliver jobs, so it runs them with the local driver and the delivery rules of the driver of the build.
1112
+ * A build keeps the configured driver.
1113
+ */
1114
+ function resolveRuntimeQueueConfig(queueConfig, development, rootDir) {
1115
+ if (!development || queueConfig === false) return queueConfig;
1116
+ if (queueConfig.driver === "local") return {
1117
+ ...queueConfig,
1118
+ development
1119
+ };
1120
+ return {
1121
+ base: resolve(rootDir, defaultLocalQueueBase),
1122
+ ...queueConfig.cache === void 0 ? {} : { cache: queueConfig.cache },
1123
+ development,
1124
+ driver: "local",
1125
+ rules: queueConfig.driver
1126
+ };
1127
+ }
1128
+ function createCloudflareQueueDefinitionNames(definitions, namePrefix = "") {
1129
+ const names = /* @__PURE__ */ new Map();
1130
+ for (const definition of definitions) {
1131
+ const physicalName = getCloudflareQueueName(definition.name, namePrefix);
1132
+ const existing = names.get(physicalName);
1133
+ if (existing) throw queueErrorDiagnostics.QUEUE_NAME_COLLISION({
1134
+ first: existing.name,
1135
+ resolved: physicalName,
1136
+ second: definition.name
1137
+ });
1138
+ names.set(physicalName, definition);
1139
+ }
1140
+ return Object.fromEntries([...names].map(([physicalName, definition]) => [physicalName, definition.name]));
1141
+ }
1142
+ function createCloudflareQueueBindings(definitions, namePrefix = "") {
1143
+ if (!definitions.length) return;
1144
+ const names = createCloudflareQueueDefinitionNames(definitions, namePrefix);
1145
+ return {
1146
+ consumers: Object.keys(names).map((queue) => ({ queue })),
1147
+ producers: definitions.map((definition) => ({
1148
+ binding: getCloudflareQueueBindingName(definition.name),
1149
+ queue: getCloudflareQueueName(definition.name, namePrefix)
1150
+ }))
1151
+ };
1152
+ }
1153
+ function renderNitroPlugin(pluginFile, registryFile, queueConfig, cloudflareQueues, queueDefinitions, development, databaseImport) {
1154
+ const cloudflareRuntime = queueConfig !== false && queueConfig.driver === "cloudflare";
1155
+ const vercelRuntime = queueConfig !== false && queueConfig.driver === "vercel";
1156
+ const localRuntime = queueConfig !== false && queueConfig.driver === "local";
1157
+ const postgresRuntime = queueConfig !== false && queueConfig.driver === "postgres";
1158
+ const postgresDatabase = queueConfig !== false && queueConfig.driver === "postgres" ? queueConfig.database : void 0;
1159
+ const cloudflare = cloudflareQueues && cloudflareRuntime;
1160
+ const cloudflareGlobals = cloudflareRuntime && !development;
1161
+ const runtimeClientFactory = cloudflareRuntime ? "createCloudflareQueueRuntimeClient" : vercelRuntime ? "createVercelQueueRuntimeClient" : localRuntime ? "createLocalQueueRuntimeClient" : postgresRuntime ? "createPostgresQueueRuntimeClient" : void 0;
1162
+ return [
1163
+ "import { definePlugin } from 'nitro'",
1164
+ ...vercelRuntime ? [`import * as __vitehubVercelQueue from ${JSON.stringify(createImportPath(pluginFile, resolveVercelDependency("@vercel/queue")))}`] : [],
1165
+ ...cloudflareGlobals ? ["import * as vitehubCloudflareWorkers from 'cloudflare:workers'"] : [],
1166
+ ...cloudflare ? [`import { createQueueCloudflareWorker } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/cloudflare-vite")))}`] : [],
1167
+ ...cloudflareRuntime ? [`import { createCloudflareQueueRuntimeClient } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/cloudflare-client")))}`] : [],
1168
+ ...localRuntime ? [`import { closeLocalQueues, createLocalQueueRuntimeClient, startLocalQueue } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/local-client")))}`] : [],
1169
+ ...postgresRuntime ? [`import { closePostgresQueues, createPostgresQueueRuntimeClient, startPostgresQueue } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/postgres-client")))}`] : [],
1170
+ ...vercelRuntime ? [`import { createVercelQueueRuntimeClient } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/vercel-client")))}`] : [],
1171
+ `import { setQueueRuntimeConfig, setQueueRuntimeEventDefaults, setQueueRuntimeRegistry } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/state")))}`,
1172
+ `import queueRegistry from ${JSON.stringify(createImportPath(pluginFile, registryFile))}`,
1173
+ "",
1174
+ ...cloudflareGlobals ? ["const { env: vitehubEnv, waitUntil: vitehubWaitUntil } = vitehubCloudflareWorkers as unknown as { env: Record<string, unknown>, waitUntil(promise: Promise<unknown>): void }", ""] : [],
1175
+ ...vercelRuntime ? ["globalThis.__vitehubVercelQueue = __vitehubVercelQueue", ""] : [],
1176
+ `const queueConfig = ${JSON.stringify(queueConfig, null, 2)}`,
1177
+ ...cloudflare ? [`const queueDefinitions = ${JSON.stringify(queueDefinitions, null, 2)}`, "const queueWorker = createQueueCloudflareWorker({ definitions: queueDefinitions, queue: queueConfig, registry: queueRegistry })"] : [],
1178
+ "",
1179
+ `export default definePlugin((${cloudflare || localRuntime || postgresRuntime ? "nitro" : ""}) => {`,
1180
+ ` setQueueRuntimeConfig(queueConfig${runtimeClientFactory ? `, ${runtimeClientFactory}` : ""})`,
1181
+ " setQueueRuntimeRegistry(queueRegistry)",
1182
+ ...cloudflareGlobals ? [" setQueueRuntimeEventDefaults({ env: vitehubEnv, waitUntil: vitehubWaitUntil })"] : [],
1183
+ ...cloudflare ? [" nitro.hooks.hook('cloudflare:queue', ({ batch, context, env }) => queueWorker.queue(batch, env, context))"] : [],
1184
+ ...localRuntime ? [" startLocalQueue(queueConfig)", " nitro.hooks.hook('close', closeLocalQueues)"] : [],
1185
+ ...postgresRuntime ? [postgresDatabase ? ` startPostgresQueue(queueConfig, () => import(${JSON.stringify(databaseImport)}).then(module => module.databases))` : " startPostgresQueue(queueConfig)", " nitro.hooks.hook('close', closePostgresQueues)"] : [],
1186
+ "})",
1187
+ ""
1188
+ ].join("\n");
1189
+ }
1190
+ function renderNitroMiddleware(middlewareFile, queueConfig, hasDefinitions, development) {
1191
+ const cloudflare = queueConfig !== false && queueConfig.driver === "cloudflare";
1192
+ const cloudflareGlobals = cloudflare && !development;
1193
+ const vercel = hasDefinitions && queueConfig !== false && queueConfig.driver === "vercel";
1194
+ return [
1195
+ "import { defineMiddleware } from 'nitro'",
1196
+ ...vercel ? [`import { waitUntil as vitehubWaitUntil } from ${JSON.stringify(createImportPath(middlewareFile, resolveVercelDependency("@vercel/functions")))}`] : [],
1197
+ ...cloudflareGlobals ? ["import * as vitehubCloudflareWorkers from 'cloudflare:workers'"] : [],
1198
+ `import { enterQueueRuntimeEvent } from ${JSON.stringify(createImportPath(middlewareFile, resolveRuntimeModule("internal/runtime/state")))}`,
1199
+ "",
1200
+ ...cloudflareGlobals ? ["const { env: vitehubEnv, waitUntil: vitehubWaitUntil } = vitehubCloudflareWorkers as unknown as { env: Record<string, unknown>, waitUntil(promise: Promise<unknown>): void }", ""] : [],
1201
+ "export default defineMiddleware((event) => {",
1202
+ ...cloudflare ? [" const runtimeEvent = event as any"] : [],
1203
+ ...vercel ? [" Object.assign(event, { waitUntil: vitehubWaitUntil })"] : [],
1204
+ ...cloudflare ? [` Object.assign(event, { env: runtimeEvent.env ?? runtimeEvent.context?.cloudflare?.env ?? runtimeEvent.context?._platform?.cloudflare?.env ?? runtimeEvent.req?.runtime?.cloudflare?.env${cloudflareGlobals ? " ?? vitehubEnv, waitUntil: vitehubWaitUntil" : ""} })`] : [],
1205
+ " enterQueueRuntimeEvent(event)",
1206
+ "})",
1207
+ ""
1208
+ ].join("\n");
1209
+ }
1210
+ /** Writes the generated Queue integration and returns the Queue config that its Nitro plugin uses. */
1211
+ async function writeQueueNitroIntegration(rootDir, queue, hosting, cloudflareQueues = true, definitions = discoverQueueDefinitions({ rootDir }), development = false, importBase = queuePackageName, database = {}) {
1212
+ await writeQueueTypes(rootDir, definitions, importBase);
1213
+ const generatedDir = ensureGeneratedDir(rootDir, productName);
1214
+ const registryFile = resolve(generatedDir, generatedRegistryFileName);
1215
+ const pluginFile = resolve(rootDir, generatedQueueNitroPlugin);
1216
+ const middlewareFile = resolve(rootDir, generatedQueueNitroMiddleware);
1217
+ const queueConfig = resolveOutputQueueConfig(typeof queue === "undefined" ? {} : queue, hosting, database.postgres === true);
1218
+ const queueDefinitions = cloudflareQueues && queueConfig !== false && queueConfig.driver === "cloudflare" ? createCloudflareQueueDefinitionNames(definitions, queueConfig.namePrefix) : {};
1219
+ const runtimeConfig = resolveRuntimeQueueConfig(queueConfig, development, rootDir);
1220
+ await Promise.all([mkdir(dirname(pluginFile), { recursive: true }), mkdir(generatedDir, { recursive: true })]);
1221
+ const vercelConsumerDir = resolve(rootDir, generatedQueueNitroVercelConsumerDir);
1222
+ const vercelConsumers = queueConfig !== false && queueConfig.driver === "vercel" ? createVercelQueueConsumerRoutes(definitions) : [];
1223
+ await rm(vercelConsumerDir, {
1224
+ force: true,
1225
+ recursive: true
1226
+ });
1227
+ if (vercelConsumers.length) await mkdir(vercelConsumerDir, { recursive: true });
1228
+ await Promise.all([
1229
+ writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions), "utf8"),
1230
+ writeFile(pluginFile, renderNitroPlugin(pluginFile, registryFile, runtimeConfig, cloudflareQueues, queueDefinitions, development, database.import ?? "@vite-hub/database/drizzle"), "utf8"),
1231
+ writeFile(middlewareFile, renderNitroMiddleware(middlewareFile, runtimeConfig, definitions.length > 0, development), "utf8"),
1232
+ ...vercelConsumers.map(async (consumer) => {
1233
+ const file = resolve(rootDir, consumer.handler);
1234
+ await writeFile(file, renderVercelQueueConsumerHandler(file, consumer.name), "utf8");
1235
+ }),
1236
+ ...process.env.VITEST ? [writeFile(resolve(rootDir, generatedQueueTestSetup), [
1237
+ `import { setQueueRuntimeConfig, setQueueRuntimeRegistry } from ${JSON.stringify(createImportPath(resolve(rootDir, generatedQueueTestSetup), resolveRuntimeModule("internal/runtime/state")))}`,
1238
+ `import registry from "./${generatedRegistryFileName}"`,
1239
+ `setQueueRuntimeConfig(${JSON.stringify(queueConfig)})`,
1240
+ "setQueueRuntimeRegistry(registry)",
1241
+ ""
1242
+ ].join("\n"), "utf8")] : []
1243
+ ]);
1244
+ return queueConfig;
1245
+ }
1246
+ function sanitizeVercelConsumerName(functionPath) {
1247
+ let result = "";
1248
+ for (const char of functionPath) if (char === "_") result += "__";
1249
+ else if (char === "/") result += "_S";
1250
+ else if (char === ".") result += "_D";
1251
+ else if (/[A-Za-z0-9-]/.test(char)) result += char;
1252
+ else result += `_${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;
1253
+ return result;
1254
+ }
1255
+ /**
1256
+ * Maps each Queue Definition to a Nitro route with a Vercel queue trigger.
1257
+ * The consumer name keeps the function path of earlier ViteHub releases, so a redeploy keeps the Vercel consumer group.
1258
+ */
1259
+ function createVercelQueueConsumerRoutes(definitions) {
1260
+ const routes = /* @__PURE__ */ new Map();
1261
+ return definitions.map((definition) => {
1262
+ const segments = definition.name.replace(/[^a-z0-9/_-]+/gi, "_").split("/");
1263
+ const route = `${vercelQueueConsumerRoutePrefix}/${segments.join("/")}`;
1264
+ const existing = routes.get(route);
1265
+ if (existing) throw queueErrorDiagnostics.QUEUE_NAME_COLLISION({
1266
+ first: existing.name,
1267
+ resolved: route,
1268
+ second: definition.name
1269
+ });
1270
+ routes.set(route, definition);
1271
+ const consumer = sanitizeVercelConsumerName(`${route.slice(1)}.func`);
1272
+ return {
1273
+ consumer,
1274
+ handler: `${generatedQueueNitroVercelConsumerDir}/${consumer}.mjs`,
1275
+ name: definition.name,
1276
+ route,
1277
+ topic: getVercelQueueTopicName(definition.name)
1278
+ };
1279
+ });
1280
+ }
1281
+ function renderVercelQueueConsumerHandler(file, name) {
1282
+ return [
1283
+ `import { handleHostedVercelQueueCallback } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("runtime/hosted")))}`,
1284
+ `import { loadQueueDefinition, missingQueueDefinitionError } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("internal/runtime/state")))}`,
1285
+ "",
1286
+ `const name = ${JSON.stringify(name)}`,
1287
+ "",
1288
+ "export default {",
1289
+ " async fetch(request) {",
1290
+ " const definition = await loadQueueDefinition(name)",
1291
+ " if (!definition) throw missingQueueDefinitionError(name)",
1292
+ " return await handleHostedVercelQueueCallback(request, name, definition)",
1293
+ " },",
1294
+ "}",
1295
+ ""
1296
+ ].join("\n");
1297
+ }
1298
+ //#endregion
1299
+ //#region src/inspect.ts
1300
+ /** Summarizes discovered Queue Definitions for the CLI and Console. */
1301
+ function inspectQueueDefinitions(options) {
1302
+ const definitions = discoverQueueDefinitions({
1303
+ contributions: options.contributions,
1304
+ rootDir: options.rootDir,
1305
+ serverDirs: options.serverDirs
1306
+ });
1307
+ return summarizeDefinitions(options.projectRoot, definitions, "queue").map((summary, index) => {
1308
+ const { contributor, reason } = definitions[index];
1309
+ if (!contributor) return summary;
1310
+ return {
1311
+ ...summary,
1312
+ fields: [{
1313
+ label: "Contributed by",
1314
+ value: contributor
1315
+ }, ...reason ? [{
1316
+ label: "Reason",
1317
+ value: reason
1318
+ }] : []]
1319
+ };
1320
+ });
1321
+ }
1322
+ /** Lists the Cloudflare Queues that Queue Definitions bind by name. Reads local files only. */
1323
+ function inspectQueueResources(options) {
1324
+ return discoverQueueDefinitions({
1325
+ contributions: options.contributions,
1326
+ rootDir: options.rootDir,
1327
+ serverDirs: options.serverDirs
1328
+ }).map((definition) => ({
1329
+ binding: options.binding ?? getCloudflareQueueBindingName(definition.name),
1330
+ definition: definition.name,
1331
+ host: "cloudflare",
1332
+ kind: "cloudflare-queue",
1333
+ name: getCloudflareQueueName(definition.name, options.namePrefix),
1334
+ owner: "queue",
1335
+ source: "name"
1336
+ }));
1337
+ }
1338
+ /** Console section that lists discovered Queue Definitions. `vitehub inspect definitions` reads the same data. */
1339
+ const queueConsoleSection = {
1340
+ description: "Inspect discovered Queue Definitions and their source metadata.",
1341
+ icon: "i-vitehub-queue",
1342
+ id: "queues",
1343
+ label: "Queues",
1344
+ read: inspectQueueDefinitions,
1345
+ view: {
1346
+ kind: "definition-catalog",
1347
+ notice: "Cloudflare and Vercel do not expose Queue backlog or delivery history through ViteHub. The local provider reports its job directory and job counts in `vitehub queue list`."
1348
+ }
1349
+ };
1350
+ //#endregion
1351
+ //#region ../internal/src/host-credentials.ts
1352
+ /** Reads host credentials from environment variables only. Returns undefined when the token is not set. */
1353
+ function readHostCredentialsFromEnv(host, env) {
1354
+ switch (host) {
1355
+ case "cloudflare": {
1356
+ const token = trimmed(env.CLOUDFLARE_API_TOKEN);
1357
+ const accountId = trimmed(env.CLOUDFLARE_ACCOUNT_ID);
1358
+ return token ? {
1359
+ token,
1360
+ ...accountId && { accountId }
1361
+ } : void 0;
1362
+ }
1363
+ case "vercel": {
1364
+ const token = trimmed(env.VERCEL_TOKEN);
1365
+ const teamId = trimmed(env.VERCEL_TEAM_ID) ?? trimmed(env.VERCEL_ORG_ID);
1366
+ return token ? {
1367
+ token,
1368
+ ...teamId && { teamId }
1369
+ } : void 0;
1370
+ }
1371
+ case "netlify": {
1372
+ const token = trimmed(env.NETLIFY_AUTH_TOKEN);
1373
+ return token ? { token } : void 0;
1374
+ }
1375
+ case "deno": {
1376
+ const token = trimmed(env.DENO_DEPLOY_TOKEN);
1377
+ return token ? { token } : void 0;
1378
+ }
1379
+ }
1380
+ }
1381
+ function trimmed(value) {
1382
+ const result = value?.trim();
1383
+ return result ? result : void 0;
1384
+ }
1385
+ //#endregion
1386
+ //#region ../internal/src/provider-failure.ts
1387
+ const cloudflareCodes = {
1388
+ d1: {},
1389
+ kv: { 10014: "conflict" },
1390
+ queues: {
1391
+ 10104: "not-found",
1392
+ 10106: "unauthorized",
1393
+ 10107: "invalid",
1394
+ 10201: "unavailable",
1395
+ 10202: "invalid",
1396
+ 10203: "invalid",
1397
+ 10204: "invalid",
1398
+ 10205: "invalid",
1399
+ 10206: "invalid",
1400
+ 10207: "invalid",
1401
+ 10208: "invalid",
1402
+ 10250: "throttled",
1403
+ 10251: "throttled",
1404
+ 10252: "throttled",
1405
+ 10253: "throttled",
1406
+ 15e3: "unavailable"
1407
+ },
1408
+ r2: {
1409
+ 10001: "unavailable",
1410
+ 10002: "unauthorized",
1411
+ 10003: "unauthorized",
1412
+ 10004: "conflict",
1413
+ 10005: "invalid",
1414
+ 10006: "not-found",
1415
+ 10007: "not-found",
1416
+ 10008: "conflict",
1417
+ 10009: "invalid",
1418
+ 10011: "invalid",
1419
+ 10012: "invalid",
1420
+ 10013: "invalid",
1421
+ 10014: "invalid",
1422
+ 10018: "unauthorized",
1423
+ 10020: "invalid",
1424
+ 10024: "not-found",
1425
+ 10025: "invalid",
1426
+ 10031: "conflict",
1427
+ 10033: "invalid",
1428
+ 10035: "unauthorized",
1429
+ 10037: "invalid",
1430
+ 10039: "invalid",
1431
+ 10042: "unauthorized",
1432
+ 10043: "unavailable",
1433
+ 10048: "invalid",
1434
+ 10054: "unavailable",
1435
+ 10058: "throttled",
1436
+ 10069: "conflict",
1437
+ 10073: "conflict",
1438
+ 100100: "invalid"
1439
+ }
1440
+ };
1441
+ const vercelCodes = {
1442
+ bad_request: "invalid",
1443
+ conflict_aliases: "conflict",
1444
+ forbidden: "unauthorized",
1445
+ internal_server_error: "unavailable",
1446
+ method_unknown: "invalid",
1447
+ not_found: "not-found",
1448
+ not_modified: "conflict",
1449
+ rate_limited: "throttled",
1450
+ service_unavailable: "unavailable"
1451
+ };
1452
+ function kindFromStatus(status) {
1453
+ if (status === 401 || status === 403) return "unauthorized";
1454
+ if (status === 404 || status === 410) return "not-found";
1455
+ if (status === 409 || status === 412) return "conflict";
1456
+ if (status === 429) return "throttled";
1457
+ if (status === 408 || status >= 500) return "unavailable";
1458
+ if (status >= 400) return "invalid";
1459
+ }
1460
+ /**
1461
+ * Classifies a failed provider call. A documented provider code wins over the HTTP status.
1462
+ * Returns `undefined` only when neither a known code nor an error status is present.
1463
+ */
1464
+ function classifyProviderFailure(source, { codes = [], status }) {
1465
+ for (const code of codes) {
1466
+ const kind = source.host === "vercel" ? typeof code === "string" && Object.hasOwn(vercelCodes, code) ? vercelCodes[code] : void 0 : source.host === "cloudflare" && source.product && typeof code === "number" && Object.hasOwn(cloudflareCodes[source.product], code) ? cloudflareCodes[source.product][code] : void 0;
1467
+ if (kind) return kind;
1468
+ }
1469
+ return status === void 0 ? void 0 : kindFromStatus(status);
1470
+ }
1471
+ /** Finds the Cloudflare product of an account API path, such as `/r2/buckets`. */
1472
+ function cloudflareProductOfPath(path) {
1473
+ if (path.startsWith("/r2/")) return "r2";
1474
+ if (path.startsWith("/storage/kv/")) return "kv";
1475
+ if (path.startsWith("/d1/")) return "d1";
1476
+ if (path === "/queues" || path.startsWith("/queues/") || path.startsWith("/queues?")) return "queues";
1477
+ }
1478
+ /**
1479
+ * Reads the error codes of a Cloudflare (`errors[].code`) or Vercel (`error.code`) error body.
1480
+ * Keeps only codes that are safe to print: numbers, and short strings without spaces or line breaks.
1481
+ */
1482
+ function readProviderErrorCodes(body) {
1483
+ if (!body || typeof body !== "object") return [];
1484
+ const error = Reflect.get(body, "error");
1485
+ const errors = Reflect.get(body, "errors");
1486
+ return [error && typeof error === "object" ? Reflect.get(error, "code") : void 0, ...Array.isArray(errors) ? errors.map((entry) => entry && typeof entry === "object" ? Reflect.get(entry, "code") : void 0) : []].filter((code) => typeof code === "number" && Number.isFinite(code) || typeof code === "string" && /^[\w.-]{1,128}$/.test(code));
1487
+ }
1488
+ //#endregion
1489
+ //#region ../internal/src/provision.ts
1490
+ /**
1491
+ * Whether a value from Provision State can appear in a copyable shell command as is.
1492
+ * The file is editable, so a hint shows a command only for plain names and ids.
1493
+ */
1494
+ function isShellSafeProvisionValue(value) {
1495
+ return /^[A-Za-z0-9][\w.-]*$/.test(value);
1496
+ }
1497
+ function resolveCloudflareProvisionConfig(env) {
1498
+ const credentials = readHostCredentialsFromEnv("cloudflare", env);
1499
+ if (!credentials?.accountId) return;
1500
+ return {
1501
+ accountId: credentials.accountId,
1502
+ token: credentials.token
1503
+ };
1504
+ }
1505
+ function ownParser(options) {
1506
+ if (!Object.hasOwn(options, "parse")) return;
1507
+ return options.parse;
1508
+ }
1509
+ function provisionRequestError(method, path, status, codes, kind) {
1510
+ const suffix = codes.length ? ` Provider code${codes.length === 1 ? "" : "s"}: ${codes.join(", ")}.` : "";
1511
+ return Object.assign(internalErrorDiagnostics.INTERNAL_R0013({ message: `Provision request failed: ${method} ${path} (${status}).${suffix}` }), {
1512
+ codes,
1513
+ kind,
1514
+ status
1515
+ });
1516
+ }
1517
+ function createJsonClient(source, baseURL, headers, fetchImpl, baseQuery) {
1518
+ return async function request(path, options = {}) {
1519
+ const url = new URL(`${baseURL}${path}`);
1520
+ const query = Object.hasOwn(options, "query") ? options.query : void 0;
1521
+ for (const [key, value] of Object.entries({
1522
+ ...baseQuery,
1523
+ ...query
1524
+ })) url.searchParams.set(key, value);
1525
+ const method = Object.hasOwn(options, "method") ? options.method : void 0;
1526
+ const body = Object.hasOwn(options, "body") ? options.body : void 0;
1527
+ const requestHeaders = Object.hasOwn(options, "headers") ? options.headers : void 0;
1528
+ const init = {
1529
+ method: method ?? "GET",
1530
+ headers: {
1531
+ ...requestHeaders,
1532
+ ...headers
1533
+ }
1534
+ };
1535
+ if (body !== void 0) {
1536
+ init.headers = {
1537
+ ...init.headers,
1538
+ "content-type": "application/json"
1539
+ };
1540
+ init.body = JSON.stringify(body);
1541
+ }
1542
+ const response = await fetchImpl(url, init);
1543
+ if (!response.ok) {
1544
+ const codes = readProviderErrorCodes(await response.json().catch(() => void 0));
1545
+ const kind = classifyProviderFailure(source(path), {
1546
+ codes,
1547
+ status: response.status
1548
+ }) ?? "unavailable";
1549
+ throw provisionRequestError(method ?? "GET", path, response.status, codes, kind);
1550
+ }
1551
+ const value = await response.json();
1552
+ const parse = ownParser(options);
1553
+ return parse ? parse(value) : value;
1554
+ };
1555
+ }
1556
+ function createCloudflareProvisionClient(config, fetchImpl = globalThis.fetch) {
1557
+ return createCloudflareClient(`https://api.cloudflare.com/client/v4/accounts/${config.accountId}`, config.token, fetchImpl);
1558
+ }
1559
+ function createCloudflareClient(baseURL, token, fetchImpl) {
1560
+ const client = createJsonClient((path) => ({
1561
+ host: "cloudflare",
1562
+ product: cloudflareProductOfPath(path)
1563
+ }), baseURL, { authorization: `Bearer ${token}` }, fetchImpl);
1564
+ return async (path, options = {}) => {
1565
+ const parse = ownParser(options) ?? ((value) => value);
1566
+ return await client(path, {
1567
+ ...options,
1568
+ parse(value) {
1569
+ if (!value || Object(value) !== value) throw internalErrorDiagnostics.INTERNAL_R0010({ message: "Cloudflare provisioning returned an invalid response." });
1570
+ const envelope = value;
1571
+ return {
1572
+ ...envelope,
1573
+ result: envelope.result === void 0 ? void 0 : parse(envelope.result)
1574
+ };
1575
+ }
1576
+ });
1577
+ };
1578
+ }
1579
+ /**
1580
+ * Reads every page of a Cloudflare list that pages with `page` and `result_info`.
1581
+ * R2 bucket lists page with a cursor instead and do not use this helper.
1582
+ */
1583
+ async function listCloudflarePages(request, path, options) {
1584
+ const items = [];
1585
+ for (let page = 1;; page++) {
1586
+ const query = {
1587
+ ...options.query,
1588
+ page: String(page)
1589
+ };
1590
+ if (options.perPage !== void 0) query.per_page = String(options.perPage);
1591
+ const listed = await request(path, {
1592
+ parse: options.parse,
1593
+ query
1594
+ });
1595
+ const pageItems = listed.result ?? [];
1596
+ items.push(...pageItems);
1597
+ const info = listed.result_info;
1598
+ if (info?.page !== void 0 && info.page !== page) throw internalErrorDiagnostics.INTERNAL_R0010({ message: `Cloudflare provisioning returned page ${info.page} of ${path} for page ${page}.` });
1599
+ if (!pageItems.length) return items;
1600
+ if (info?.total_pages !== void 0) {
1601
+ if (page >= info.total_pages) return items;
1602
+ } else if (info?.total_count !== void 0) {
1603
+ if (page * (info.per_page ?? options.perPage ?? pageItems.length) >= info.total_count) return items;
1604
+ } else if (options.perPage === void 0 || pageItems.length < options.perPage) return items;
1605
+ }
1606
+ }
1607
+ //#endregion
1608
+ //#region src/provision.ts
1609
+ /** Provision State category for Cloudflare Queue names, keyed by Queue Definition name. Config never reads it, because Queue names come from Definitions. */
1610
+ const QUEUE_CLOUDFLARE_PROVISION_CATEGORY = "queue";
1611
+ function parseQueues(value) {
1612
+ 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();
1613
+ return value;
1614
+ }
1615
+ function createQueueProvisionStep(resolveRootDir, resolveNamePrefix = () => void 0, resolveContributions = () => []) {
1616
+ return {
1617
+ id: "queue:cloudflare-queues",
1618
+ provider: "cloudflare",
1619
+ recordedState() {
1620
+ const namePrefix = resolveNamePrefix();
1621
+ const queues = new Map(discoverQueueDefinitions({
1622
+ contributions: resolveContributions(),
1623
+ rootDir: resolveRootDir()
1624
+ }).map((definition) => [definition.name, getCloudflareQueueName(definition.name, namePrefix)]));
1625
+ return [{
1626
+ category: QUEUE_CLOUDFLARE_PROVISION_CATEGORY,
1627
+ declared: [...queues.keys()],
1628
+ declaredResourceIdentity: (key) => queues.get(key),
1629
+ deleteHint: ({ id }) => isShellSafeProvisionValue(id) ? `run \`wrangler queues delete ${id}\`` : "delete the Queue in the Cloudflare dashboard"
1630
+ }];
1631
+ },
1632
+ async plan(context) {
1633
+ const config = resolveCloudflareProvisionConfig(context.env);
1634
+ if (!config) {
1635
+ context.logger.warn("queue: skipping Cloudflare queues, missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN.");
1636
+ context.markPlanUnchecked?.();
1637
+ return [];
1638
+ }
1639
+ const request = createCloudflareProvisionClient(config, context.fetch);
1640
+ const namePrefix = resolveNamePrefix();
1641
+ const queues = discoverQueueDefinitions({
1642
+ contributions: resolveContributions(),
1643
+ rootDir: resolveRootDir()
1644
+ }).map((definition) => ({
1645
+ definition: definition.name,
1646
+ name: getCloudflareQueueName(definition.name, namePrefix)
1647
+ }));
1648
+ if (!queues.length) return [];
1649
+ const listed = await listCloudflarePages(request, "/queues", { parse: parseQueues });
1650
+ const existing = new Set(listed.map((queue) => queue.queue_name).filter((name) => Boolean(name)));
1651
+ return queues.map(({ definition, name }) => ({
1652
+ kind: "cloudflare-queue",
1653
+ name,
1654
+ exists: existing.has(name),
1655
+ apply: async () => {
1656
+ if (!existing.has(name)) await request("/queues", {
1657
+ method: "POST",
1658
+ body: { queue_name: name }
1659
+ });
1660
+ return { ids: { cloudflare: { [QUEUE_CLOUDFLARE_PROVISION_CATEGORY]: { [definition]: name } } } };
1661
+ }
1662
+ }));
1663
+ }
1664
+ };
1665
+ }
1666
+ //#endregion
1667
+ //#region src/vite.ts
1668
+ const operationsModule = ownModule(import.meta.url, "operations");
1669
+ const mergeNoExternal = createNoExternalAddition(queuePackageName);
1670
+ const databaseVitePluginName = "@vite-hub/database/vite";
1671
+ function findDatabasePlugin(plugins) {
1672
+ for (const plugin of plugins ?? []) if (Array.isArray(plugin)) {
1673
+ const found = findDatabasePlugin(plugin);
1674
+ if (found) return found;
1675
+ } else if (plugin && typeof plugin === "object" && "name" in plugin && plugin.name === databaseVitePluginName) return plugin;
1676
+ }
1677
+ /**
1678
+ * Whether the Database integration resolved the Default Database on Postgres, with its layers, contributions, and
1679
+ * server directories. A Node server then infers the postgres provider on the connection of that Database.
1680
+ */
1681
+ function hasPostgresDefaultDatabase(plugin) {
1682
+ return plugin?.api?.getConfig?.()?.databases.default?.dialect === "postgresql";
1683
+ }
1684
+ async function createQueueNitroConfig(plugin, options) {
1685
+ const createNitroConfig = plugin.vitehub?.queue?.createNitroConfig;
1686
+ if (!createNitroConfig) throw queueErrorDiagnostics.QUEUE_PLUGIN_INCOMPATIBLE();
1687
+ return createNitroConfig(options);
1688
+ }
1689
+ function resolveStableQueueDefinitions(resolveDefinitions, snapshot, context) {
1690
+ const definitions = resolveDefinitions();
1691
+ if (JSON.stringify(definitions) !== JSON.stringify(snapshot)) throw queueErrorDiagnostics.QUEUE_DEFINITIONS_CHANGED({ context });
1692
+ return definitions;
1693
+ }
1694
+ function normalizeQueueForHosting(queue, hosting) {
1695
+ if (queue && typeof queue === "object" && Object.hasOwn(queue, "driver")) {
1696
+ const driver = queue.driver;
1697
+ const driverOnly = normalizeQueueOptions({ driver }, { hosting });
1698
+ if (driverOnly?.driver && hosting && driverOnly.driver !== hosting) return void 0;
1699
+ }
1700
+ return normalizeQueueOptions(queue, { hosting });
1701
+ }
1702
+ /**
1703
+ * The host of this build: the Nitro preset, else the host that `vitehub()` selected. `vite dev` has no Nitro preset, so
1704
+ * a Node app in dev reads its host from `vitehub()`.
1705
+ */
1706
+ function resolveQueueHost(config, nitro) {
1707
+ return resolveHost({
1708
+ nitro,
1709
+ hosting: getDeploymentHost(config)
1710
+ });
1711
+ }
1712
+ function resolveQueueHosting(queue, host, postgresDatabase = false) {
1713
+ const hosting = getHostingProvider(host);
1714
+ if (hosting) return hosting;
1715
+ if (host === "node") return normalizeQueueOptions(queue, {
1716
+ hosting: "node-server",
1717
+ postgresDatabase
1718
+ })?.driver ?? "local";
1719
+ return normalizeQueueForHosting(queue, hosting)?.driver || "vercel";
1720
+ }
1721
+ function supportsCloudflareQueues(nitro) {
1722
+ return !(resolveHostPreset({ nitro }) ?? "").replaceAll("-", "_").includes("cloudflare_pages");
1723
+ }
1724
+ function isGeneratedNitroRegistration(value, generatedPath) {
1725
+ return typeof value === "string" && (value === generatedPath || value.replaceAll("\\", "/").endsWith(`/${generatedPath}`));
1726
+ }
1727
+ function isGeneratedVercelConsumer(value) {
1728
+ return typeof value === "string" && value.replaceAll("\\", "/").includes(`.vitehub/nitro/queue/vercel/`);
1729
+ }
1730
+ /** Vercel delivers Queue messages to Nitro routes that have a queue trigger in `vercel.functionRules`. */
1731
+ function hostsVercelQueueConsumers(nitro) {
1732
+ const hosting = getHostingProvider(resolveHost({ nitro }));
1733
+ return hosting === "vercel" || hosting === void 0 && Boolean(process.env.VERCEL);
1734
+ }
1735
+ function addVercelQueueConsumers(kit, definitions, root) {
1736
+ const vercel = cloneRecord(kit.config.vercel);
1737
+ const functionRules = cloneRecord(vercel.functionRules);
1738
+ for (const consumer of createVercelQueueConsumerRoutes(definitions)) {
1739
+ kit.addHandler({
1740
+ handler: root ? resolve$1(root, consumer.handler) : consumer.handler,
1741
+ route: consumer.route
1742
+ });
1743
+ functionRules[consumer.route] = {
1744
+ ...cloneRecord(functionRules[consumer.route]),
1745
+ experimentalTriggers: [{
1746
+ consumer: consumer.consumer,
1747
+ topic: consumer.topic,
1748
+ type: "queue/v2beta"
1749
+ }]
1750
+ };
1751
+ }
1752
+ kit.config.vercel = {
1753
+ ...vercel,
1754
+ functionRules
1755
+ };
1756
+ }
1757
+ function mergeNitroConfig(config, value, queue, root, definitions) {
1758
+ const providerOutput = useProviderOutputCatalog(config);
1759
+ const nitro = cloneRecord(value);
1760
+ const nitroHosting = getHostingProvider(resolveHost({ nitro }));
1761
+ const normalizedQueue = normalizeQueueForHosting(queue, nitroHosting);
1762
+ const runtimeEnabled = queue !== false && !(queue !== false && nitroHosting && queue && normalizedQueue === void 0);
1763
+ const nitroOwnsPaths = hasNitroConfigContext(config);
1764
+ const plugin = nitroOwnsPaths ? resolve$1(root, generatedQueueNitroPlugin) : generatedQueueNitroPlugin;
1765
+ const middleware = nitroOwnsPaths ? resolve$1(root, generatedQueueNitroMiddleware) : generatedQueueNitroMiddleware;
1766
+ nitro.plugins = Array.isArray(nitro.plugins) ? nitro.plugins.filter((entry) => !isGeneratedNitroRegistration(entry, generatedQueueNitroPlugin)) : [];
1767
+ nitro.handlers = Array.isArray(nitro.handlers) ? nitro.handlers.filter((handler) => !isGeneratedNitroRegistration(handler?.handler, ".vitehub/nitro/queue/middleware.ts") && !isGeneratedVercelConsumer(handler?.handler)) : [];
1768
+ const kit = createNitroServerKit(nitro);
1769
+ if (!runtimeEnabled) {
1770
+ contributeCloudflareProviderOutput(providerOutput, { owner: "queue" });
1771
+ return composeNitroCloudflareProviderOutput(providerOutput, kit.config, value);
1772
+ }
1773
+ kit.addPlugin(plugin, "start");
1774
+ kit.addHandler({
1775
+ handler: middleware,
1776
+ middleware: true,
1777
+ route: "/**"
1778
+ }, "start");
1779
+ const queueHosting = resolveQueueHosting(queue, resolveQueueHost(config, nitro));
1780
+ const resolvedVercelQueue = queueHosting === "vercel" ? normalizeQueueOptions(queue, { hosting: queueHosting }) : void 0;
1781
+ if (resolvedVercelQueue && resolvedVercelQueue.driver === "vercel" && hostsVercelQueueConsumers(nitro)) addVercelQueueConsumers(kit, definitions, nitroOwnsPaths ? root : void 0);
1782
+ if (queueHosting !== "cloudflare") {
1783
+ contributeCloudflareProviderOutput(providerOutput, { owner: "queue" });
1784
+ return composeNitroCloudflareProviderOutput(providerOutput, kit.config, value);
1785
+ }
1786
+ const cloudflare = cloneRecord(nitro.cloudflare);
1787
+ const wrangler = cloneRecord(cloudflare.wrangler);
1788
+ const compatibilityFlags = Array.isArray(wrangler.compatibility_flags) ? [...wrangler.compatibility_flags] : [];
1789
+ if (!compatibilityFlags.includes("nodejs_compat")) compatibilityFlags.push("nodejs_compat");
1790
+ const cloudflareQueues = supportsCloudflareQueues(nitro);
1791
+ const rollupConfig = cloneRecord(nitro.rollupConfig);
1792
+ const resolvedQueue = normalizeQueueOptions(queue, { hosting: queueHosting });
1793
+ const generated = createCloudflareQueueBindings(definitions, resolvedQueue?.driver === "cloudflare" ? resolvedQueue.namePrefix : void 0);
1794
+ const baseNitro = {
1795
+ ...nitro,
1796
+ ...cloudflareQueues ? { rollupConfig: {
1797
+ ...rollupConfig,
1798
+ external: mergeNitroExternal(rollupConfig.external, "cloudflare:workers")
1799
+ } } : {},
1800
+ cloudflare: {
1801
+ ...cloudflare,
1802
+ wrangler: {
1803
+ ...wrangler,
1804
+ compatibility_flags: compatibilityFlags
1805
+ }
1806
+ },
1807
+ handlers: kit.config.handlers,
1808
+ plugins: kit.config.plugins
1809
+ };
1810
+ if (!generated) {
1811
+ contributeCloudflareProviderOutput(providerOutput, { owner: "queue" });
1812
+ return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
1813
+ }
1814
+ const binding = resolvedQueue?.driver === "cloudflare" && typeof resolvedQueue.binding === "string" ? resolvedQueue.binding : void 0;
1815
+ if (binding && generated.producers.length > 1) throw queueErrorDiagnostics.QUEUE_BINDING_CONFLICT();
1816
+ const generatedProducers = binding ? generated.producers.map((producer) => ({
1817
+ ...producer,
1818
+ binding
1819
+ })) : generated.producers;
1820
+ contributeCloudflareProviderOutput(providerOutput, {
1821
+ owner: "queue",
1822
+ queues: {
1823
+ ...cloudflareQueues ? { consumers: generated.consumers } : {},
1824
+ producers: generatedProducers
1825
+ }
1826
+ });
1827
+ return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
1828
+ }
1829
+ function hubQueue(options, internalOptions = {}) {
1830
+ let resolved;
1831
+ let queue = options;
1832
+ let hosting = "vercel";
1833
+ let cloudflareQueues = true;
1834
+ let configuredDefinitions = [];
1835
+ let contributions = [];
1836
+ let localDevelopment = false;
1837
+ let preview = false;
1838
+ let nitroQueue = queue;
1839
+ let writtenQueue;
1840
+ let nuxtConfiguredDefinitions;
1841
+ let nuxtProjectRoot;
1842
+ let resolveNuxtDefinitions;
1843
+ let nuxtServerQueueDirs = [];
1844
+ const resolvedConfigs = /* @__PURE__ */ new Map();
1845
+ const queueOptions = /* @__PURE__ */ new Map();
1846
+ const nuxtStates = /* @__PURE__ */ new Map();
1847
+ const buildStates = /* @__PURE__ */ new WeakMap();
1848
+ let validatesNitroDefinitions = false;
1849
+ let serverDirs;
1850
+ async function collectPluginQueueContributions(plugins, root, projectRoot = resolveViteHubProjectRoot(root), dirs = serverDirs) {
1851
+ return await collectQueueContributions(plugins, {
1852
+ projectRoot,
1853
+ root,
1854
+ serverDirs: dirs
1855
+ });
1856
+ }
1857
+ let databasePlugin;
1858
+ let postgresDatabase = false;
1859
+ const database = () => ({
1860
+ import: internalOptions.databaseImport,
1861
+ postgres: postgresDatabase
1862
+ });
1863
+ const nodeWrites = /* @__PURE__ */ new Map();
1864
+ function recordNodeWrite(rootDir, queue, host, definitions) {
1865
+ if (host !== "node") return;
1866
+ nodeWrites.set(rootDir, {
1867
+ cloudflareQueues,
1868
+ definitions,
1869
+ development: localDevelopment,
1870
+ nitroQueue,
1871
+ postgres: postgresDatabase,
1872
+ queue
1873
+ });
1874
+ }
1875
+ return {
1876
+ name: "@vite-hub/queue/vite",
1877
+ api: { deploymentEnv: (context) => queueDeploymentEnv(writtenQueue ?? normalizeQueueOptions(nitroQueue === false ? false : queue, {
1878
+ hosting: context.host,
1879
+ postgresDatabase
1880
+ })) },
1881
+ vitehub: {
1882
+ durability: () => {
1883
+ const resolvedQueue = writtenQueue ?? (nitroQueue === false ? void 0 : normalizeQueueOptions(queue, { hosting }));
1884
+ if (!resolvedQueue || !resolvedQueue.driver) return [];
1885
+ const base = Reflect.get(resolvedQueue, "base");
1886
+ const database = Reflect.get(resolvedQueue, "database");
1887
+ return [{
1888
+ export: "queueDurability",
1889
+ input: {
1890
+ driver: resolvedQueue.driver,
1891
+ ...typeof base === "string" ? { base } : {},
1892
+ ...typeof database === "string" ? { database } : {}
1893
+ },
1894
+ module: durabilityModuleFile(import.meta.url),
1895
+ primitive: "queue"
1896
+ }];
1897
+ },
1898
+ operations: [{
1899
+ export: "queueOperations",
1900
+ load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).queueOperations,
1901
+ module: operationsModule
1902
+ }],
1903
+ inspect: () => {
1904
+ const resolvedQueue = normalizeQueueOptions(queue, { hosting });
1905
+ if (!resolvedQueue?.driver) return;
1906
+ const rootDir = resolved?.root ?? process.cwd();
1907
+ return {
1908
+ definitions: [{
1909
+ kind: "queue",
1910
+ label: "Queues",
1911
+ list: () => inspectQueueDefinitions({
1912
+ contributions,
1913
+ projectRoot: resolveViteHubProjectRoot(rootDir),
1914
+ rootDir,
1915
+ serverDirs
1916
+ })
1917
+ }],
1918
+ resources: () => resolvedQueue.driver === "cloudflare" ? inspectQueueResources({
1919
+ binding: resolvedQueue.binding,
1920
+ contributions,
1921
+ namePrefix: resolvedQueue.namePrefix,
1922
+ projectRoot: resolveViteHubProjectRoot(rootDir),
1923
+ rootDir,
1924
+ serverDirs
1925
+ }) : []
1926
+ };
1927
+ },
1928
+ cli: async () => {
1929
+ return {
1930
+ namespaces: [],
1931
+ provision: [createQueueProvisionStep(() => resolved?.root ?? process.cwd(), () => {
1932
+ const resolvedQueue = normalizeQueueOptions(queue, { hosting: "cloudflare" });
1933
+ return resolvedQueue?.driver === "cloudflare" ? resolvedQueue.namePrefix : void 0;
1934
+ }, () => contributions)]
1935
+ };
1936
+ },
1937
+ queue: { async createNitroConfig({ development = false, nitro, projectRoot, root, serverDirs, viteConfig }) {
1938
+ const config = viteConfig ?? {
1939
+ ["__vitehubNitroConfigContext"]: true,
1940
+ nitro
1941
+ };
1942
+ const resolvedConfig = resolvedConfigs.get(root);
1943
+ const state = resolvedConfig ? buildStates.get(resolvedConfig) : void 0;
1944
+ const projectQueue = viteConfig ? getResolvedFeatureOptions(viteConfig, "queue") ?? options : state ? state.queue : queueOptions.has(root) ? queueOptions.get(root) : options;
1945
+ nuxtProjectRoot = projectRoot;
1946
+ if (viteConfig) contributions = await collectPluginQueueContributions(viteConfig.plugins, root, projectRoot, serverDirs);
1947
+ const nuxtContributions = contributions;
1948
+ nuxtServerQueueDirs = [...new Set(serverDirs || [resolve$1(projectRoot, "server"), resolve$1(root, "server")])].map((dir) => `${resolve$1(dir, "queues").replace(/\\/g, "/")}/`);
1949
+ resolveNuxtDefinitions = () => discoverQueueDefinitions({
1950
+ contributions: nuxtContributions,
1951
+ rootDir: root,
1952
+ serverDirs,
1953
+ serverRootDirs: [projectRoot, root]
1954
+ });
1955
+ const definitions = resolveNuxtDefinitions();
1956
+ nuxtConfiguredDefinitions = definitions;
1957
+ const configuredNitro = mergeNitroConfig(config, nitro, projectQueue, projectRoot, definitions);
1958
+ databasePlugin = findDatabasePlugin(viteConfig?.plugins) ?? databasePlugin;
1959
+ const host = resolveQueueHost(config, configuredNitro);
1960
+ postgresDatabase = host === "node" && hasPostgresDefaultDatabase(databasePlugin);
1961
+ hosting = resolveQueueHosting(projectQueue, host, postgresDatabase);
1962
+ const nitroHosting = getHostingProvider(resolveHost({ nitro: configuredNitro }));
1963
+ const resolvedQueue = normalizeQueueOptions(projectQueue, { hosting: nitroHosting });
1964
+ nitroQueue = resolvedQueue?.driver && nitroHosting && resolvedQueue.driver !== nitroHosting ? false : projectQueue;
1965
+ cloudflareQueues = supportsCloudflareQueues(configuredNitro);
1966
+ localDevelopment = development;
1967
+ const nuxtState = {
1968
+ nuxtConfiguredDefinitions,
1969
+ nuxtProjectRoot,
1970
+ resolveNuxtDefinitions
1971
+ };
1972
+ nuxtStates.set(root, nuxtState);
1973
+ if (state) Object.assign(state, nuxtState);
1974
+ writtenQueue = await writeQueueNitroIntegration(projectRoot, nitroQueue, hosting, cloudflareQueues, definitions, localDevelopment, internalOptions.importBase, database());
1975
+ recordNodeWrite(projectRoot, projectQueue, host, definitions);
1976
+ return configuredNitro;
1977
+ } }
1978
+ },
1979
+ async config(config, env) {
1980
+ preview = env?.isPreview === true;
1981
+ queue = getResolvedFeatureOptions(config, "queue") ?? options;
1982
+ queueOptions.set(resolve$1(config.root || process.cwd()), queue);
1983
+ serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
1984
+ const root = config.root || process.cwd();
1985
+ contributions = await collectPluginQueueContributions(config.plugins, root);
1986
+ const nitro = config.nitro;
1987
+ config.nitro = mergeNitroConfig(config, nitro, queue, root, discoverQueueDefinitions({
1988
+ contributions,
1989
+ rootDir: root
1990
+ }));
1991
+ if (process.env.VITEST) return { test: { setupFiles: [resolve$1(root, generatedQueueTestSetup)] } };
1992
+ },
1993
+ async configResolved(config) {
1994
+ resolved = config;
1995
+ resolvedConfigs.set(config.root, config);
1996
+ const nuxtState = nuxtStates.get(config.root);
1997
+ nuxtConfiguredDefinitions = nuxtState?.nuxtConfiguredDefinitions;
1998
+ nuxtProjectRoot = nuxtState?.nuxtProjectRoot;
1999
+ resolveNuxtDefinitions = nuxtState?.resolveNuxtDefinitions;
2000
+ queue = getResolvedFeatureOptions(config, "queue") ?? options;
2001
+ queueOptions.set(config.root, queue);
2002
+ const configuredNitro = config.nitro;
2003
+ contributions = await collectPluginQueueContributions(config.plugins, config.root);
2004
+ configuredDefinitions = discoverQueueDefinitions({
2005
+ contributions,
2006
+ rootDir: config.root
2007
+ });
2008
+ const nitro = mergeNitroConfig(config, configuredNitro, queue, config.root, configuredDefinitions);
2009
+ config.nitro = nitro;
2010
+ databasePlugin = findDatabasePlugin(config.plugins) ?? databasePlugin;
2011
+ const host = resolveQueueHost(config, nitro);
2012
+ postgresDatabase = host === "node" && hasPostgresDefaultDatabase(databasePlugin);
2013
+ hosting = resolveQueueHosting(queue, host, postgresDatabase);
2014
+ cloudflareQueues = supportsCloudflareQueues(nitro);
2015
+ const nitroHosting = getHostingProvider(resolveHost({ nitro }));
2016
+ const resolvedQueue = normalizeQueueOptions(queue, { hosting: nitroHosting });
2017
+ nitroQueue = resolvedQueue?.driver && nitroHosting && resolvedQueue.driver !== nitroHosting ? false : queue;
2018
+ validatesNitroDefinitions = hasNitroConfigContext(config) && nitroQueue !== false;
2019
+ localDevelopment = config.command === "serve" && !preview;
2020
+ writtenQueue = await writeQueueNitroIntegration(config.root, nitroQueue, hosting, cloudflareQueues, configuredDefinitions, localDevelopment, internalOptions.importBase, database());
2021
+ recordNodeWrite(config.root, queue, host, configuredDefinitions);
2022
+ buildStates.set(config, {
2023
+ configuredDefinitions,
2024
+ contributions,
2025
+ nuxtConfiguredDefinitions,
2026
+ queue,
2027
+ resolveNuxtDefinitions,
2028
+ resolved: config,
2029
+ validatesNitroDefinitions
2030
+ });
2031
+ },
2032
+ configEnvironment(name, config) {
2033
+ if (!isServerEnvironment(name, config)) return;
2034
+ return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
2035
+ },
2036
+ async handleHotUpdate(context) {
2037
+ const file = context.file.replace(/\\/g, "/");
2038
+ const isDirectoryDefinition = /\.(?:c|m)?[jt]s$/i.test(file) && (/\/server\/queues\//.test(file) || nuxtServerQueueDirs.some((dir) => file.startsWith(dir)));
2039
+ if (!/\.queue\.(?:c|m)?[jt]s$/i.test(file) && !isDirectoryDefinition) return;
2040
+ resolved = context.server.config;
2041
+ const definitions = resolveNuxtDefinitions?.() ?? discoverQueueDefinitions({
2042
+ contributions,
2043
+ rootDir: resolved.root
2044
+ });
2045
+ writtenQueue = await writeQueueNitroIntegration(nuxtProjectRoot || resolved.root, nitroQueue, hosting, cloudflareQueues, definitions, localDevelopment, internalOptions.importBase, database());
2046
+ },
2047
+ async buildStart() {
2048
+ const databaseConfig = databasePlugin?.api?.getConfig?.();
2049
+ if (!databaseConfig) return;
2050
+ postgresDatabase = databaseConfig.databases.default?.dialect === "postgresql";
2051
+ for (const [rootDir, write] of nodeWrites) {
2052
+ if (write.postgres === postgresDatabase) continue;
2053
+ write.postgres = postgresDatabase;
2054
+ hosting = resolveQueueHosting(write.queue, "node", postgresDatabase);
2055
+ writtenQueue = await writeQueueNitroIntegration(rootDir, write.nitroQueue, hosting, write.cloudflareQueues, write.definitions, write.development, internalOptions.importBase, database());
2056
+ }
2057
+ },
2058
+ buildEnd(error) {
2059
+ const config = this.environment?.config ?? resolved;
2060
+ const state = config ? buildStates.get(config) : void 0;
2061
+ if (error || !state || shouldSkipViteProviderBuild(state.resolved.command)) return;
2062
+ if (state.resolveNuxtDefinitions && state.nuxtConfiguredDefinitions) resolveStableQueueDefinitions(state.resolveNuxtDefinitions, state.nuxtConfiguredDefinitions, "Nuxt");
2063
+ else if (state.validatesNitroDefinitions) resolveStableQueueDefinitions(() => discoverQueueDefinitions({
2064
+ contributions: state.contributions,
2065
+ rootDir: state.resolved.root
2066
+ }), state.configuredDefinitions, "Nitro");
2067
+ }
2068
+ };
2069
+ }
2070
+ //#endregion
2071
+ export { collectQueueContributions, contributedQueueSource, createQueueNitroConfig, discoverQueueDefinitions, hubQueue, inspectQueueDefinitions, queueConsoleSection };