@vite-hub/queue 0.0.0 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -1
- package/dist/_app-D29AwUdD.d.ts +11 -0
- package/dist/app-BZpq2cwC.js +10 -0
- package/dist/client-CBDT9GL9.js +93 -0
- package/dist/cloudflare-GosJefIK.js +26 -0
- package/dist/cloudflare-client-w5vphoNn.js +99 -0
- package/dist/cloudflare-resource-name-R8zYQiZb.js +34 -0
- package/dist/cloudflare-vite-BNBVtEwG.js +92 -0
- package/dist/cloudflare-vite-krY8T3zM.d.ts +24 -0
- package/dist/config-B7xkD1v0.js +47 -0
- package/dist/delivery-error-glgYWC9g.js +45 -0
- package/dist/errors-CjuG_qr-.js +108 -0
- package/dist/index.d.ts +91 -0
- package/dist/index.js +28 -0
- package/dist/internal/runtime/cloudflare-client.d.ts +6 -0
- package/dist/internal/runtime/cloudflare-client.js +2 -0
- package/dist/internal/runtime/vercel-client.d.ts +6 -0
- package/dist/internal/runtime/vercel-client.js +114 -0
- package/dist/nuxt.d.ts +19 -0
- package/dist/nuxt.js +29 -0
- package/dist/runtime/cloudflare-vite.d.ts +2 -0
- package/dist/runtime/cloudflare-vite.js +2 -0
- package/dist/runtime/hosted.d.ts +11 -0
- package/dist/runtime/hosted.js +53 -0
- package/dist/runtime/state.d.ts +16 -0
- package/dist/runtime/state.js +2 -0
- package/dist/runtime/vercel-vite.d.ts +20 -0
- package/dist/runtime/vercel-vite.js +49 -0
- package/dist/state-BfUFGeC2.js +105 -0
- package/dist/types-CwvoMATy.d.ts +169 -0
- package/dist/vercel-C_4vqxcl.js +8 -0
- package/dist/vercel-runtime-package-copy-B8AEFWXT.js +66 -0
- package/dist/virtual.d.ts +4 -0
- package/dist/vite-C6yK76Sw.js +1823 -0
- package/dist/vite.d.ts +129 -0
- package/dist/vite.js +2 -0
- package/package.json +73 -5
|
@@ -0,0 +1,1823 @@
|
|
|
1
|
+
import { n as getHostingProvider, t as normalizeQueueOptions } from "./config-B7xkD1v0.js";
|
|
2
|
+
import { t as getCloudflareQueueBindingName } from "./cloudflare-GosJefIK.js";
|
|
3
|
+
import { t as getCloudflareQueueName } from "./cloudflare-resource-name-R8zYQiZb.js";
|
|
4
|
+
import { t as getVercelQueueTopicName } from "./vercel-C_4vqxcl.js";
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
import { cp, mkdir, readFile, readdir, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
7
|
+
import { basename, dirname, relative, resolve } from "node:path";
|
|
8
|
+
import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
9
|
+
import { basename as basename$1, dirname as dirname$1, relative as relative$1, resolve as resolve$1 } from "pathe";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { build } from "esbuild";
|
|
12
|
+
import { isDeepStrictEqual } from "node:util";
|
|
13
|
+
import { hash } from "node:crypto";
|
|
14
|
+
const VITEHUB_MODES = {
|
|
15
|
+
e2e: "e2e",
|
|
16
|
+
blob: "blob",
|
|
17
|
+
chat: "chat",
|
|
18
|
+
db: "db",
|
|
19
|
+
env: "env",
|
|
20
|
+
kv: "kv",
|
|
21
|
+
queue: "queue",
|
|
22
|
+
schedule: "schedule",
|
|
23
|
+
sandbox: "sandbox",
|
|
24
|
+
workspace: "workspace",
|
|
25
|
+
workflow: "workflow"
|
|
26
|
+
};
|
|
27
|
+
function isViteCli(argv) {
|
|
28
|
+
return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
|
|
29
|
+
}
|
|
30
|
+
function getViteCliMode(argv = process.argv) {
|
|
31
|
+
if (!isViteCli(argv)) return;
|
|
32
|
+
const modes = new Set(Object.values(VITEHUB_MODES));
|
|
33
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
34
|
+
const arg = argv[index];
|
|
35
|
+
const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
|
|
36
|
+
if (mode && modes.has(mode)) return mode;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function getViteMode(env = process.env) {
|
|
40
|
+
return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region ../internal/src/build/client-output.ts
|
|
44
|
+
function hasStaticIndex(clientDir) {
|
|
45
|
+
return existsSync(resolve$1(clientDir, "index.html"));
|
|
46
|
+
}
|
|
47
|
+
async function copyClientOutput(clientDir, targetDir) {
|
|
48
|
+
const resolvedClientDir = resolve$1(clientDir);
|
|
49
|
+
const resolvedTargetDir = resolve$1(targetDir);
|
|
50
|
+
if (resolvedClientDir === resolvedTargetDir) return;
|
|
51
|
+
await rm(resolvedTargetDir, {
|
|
52
|
+
force: true,
|
|
53
|
+
recursive: true
|
|
54
|
+
});
|
|
55
|
+
await mkdir(dirname$1(resolvedTargetDir), { recursive: true });
|
|
56
|
+
const targetRelativePath = relative$1(resolvedClientDir, resolvedTargetDir);
|
|
57
|
+
if (targetRelativePath && !targetRelativePath.startsWith("../")) {
|
|
58
|
+
const [targetRootEntry] = targetRelativePath.split("/", 1);
|
|
59
|
+
await mkdir(resolvedTargetDir, { recursive: true });
|
|
60
|
+
await Promise.all((await readdir(resolvedClientDir)).filter((entry) => entry !== targetRootEntry).map((entry) => cp(resolve$1(resolvedClientDir, entry), resolve$1(resolvedTargetDir, entry), { recursive: true })));
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
await cp(resolvedClientDir, resolvedTargetDir, { recursive: true });
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
//#region ../internal/src/build/provider-output-config.ts
|
|
67
|
+
function isProviderJsonArray(value, ancestors) {
|
|
68
|
+
if (Object.getPrototypeOf(value) !== Array.prototype || ancestors.has(value)) return false;
|
|
69
|
+
if (Reflect.ownKeys(value).length !== value.length + 1) return false;
|
|
70
|
+
ancestors.add(value);
|
|
71
|
+
try {
|
|
72
|
+
for (let index = 0; index < value.length; index++) {
|
|
73
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
|
|
74
|
+
if (!descriptor?.enumerable || !("value" in descriptor) || !isProviderJsonValue(descriptor.value, ancestors)) return false;
|
|
75
|
+
}
|
|
76
|
+
return true;
|
|
77
|
+
} finally {
|
|
78
|
+
ancestors.delete(value);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function isProviderJsonRecordValue(value, ancestors) {
|
|
82
|
+
const prototype = Object.getPrototypeOf(value);
|
|
83
|
+
if (prototype !== Object.prototype && prototype !== null || ancestors.has(value)) return false;
|
|
84
|
+
ancestors.add(value);
|
|
85
|
+
try {
|
|
86
|
+
return Reflect.ownKeys(value).every((key) => {
|
|
87
|
+
if (typeof key !== "string") return false;
|
|
88
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
89
|
+
return descriptor?.enumerable === true && "value" in descriptor && isProviderJsonValue(descriptor.value, ancestors);
|
|
90
|
+
});
|
|
91
|
+
} finally {
|
|
92
|
+
ancestors.delete(value);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function isProviderJsonValue(value, ancestors) {
|
|
96
|
+
if (value === null || typeof value === "boolean" || typeof value === "string") return true;
|
|
97
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
98
|
+
if (Array.isArray(value)) return isProviderJsonArray(value, ancestors);
|
|
99
|
+
return typeof value === "object" && isProviderJsonRecordValue(value, ancestors);
|
|
100
|
+
}
|
|
101
|
+
function isProviderJsonRecord(value) {
|
|
102
|
+
try {
|
|
103
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && isProviderJsonRecordValue(value, /* @__PURE__ */ new Set());
|
|
104
|
+
} catch {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function assertProviderJsonRecord(value) {
|
|
109
|
+
if (!isProviderJsonRecord(value)) throw new TypeError("[vitehub] Provider output config must be a JSON object.");
|
|
110
|
+
}
|
|
111
|
+
function isFileNotFoundError(error) {
|
|
112
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
113
|
+
}
|
|
114
|
+
async function readProviderJsonRecord(file) {
|
|
115
|
+
try {
|
|
116
|
+
const parsed = JSON.parse(await readFile(file, "utf8"));
|
|
117
|
+
assertProviderJsonRecord(parsed);
|
|
118
|
+
return parsed;
|
|
119
|
+
} catch (error) {
|
|
120
|
+
if (isFileNotFoundError(error)) return;
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function deleteOwnedFields(value, ownership) {
|
|
125
|
+
const next = { ...value };
|
|
126
|
+
for (const key of ownership.keys ?? []) delete next[key];
|
|
127
|
+
for (const field of Object.keys(ownership.arrays ?? {})) delete next[field];
|
|
128
|
+
return next;
|
|
129
|
+
}
|
|
130
|
+
function getKeyedArrayEntryValue(value, key) {
|
|
131
|
+
if (!isProviderJsonRecord(value)) return;
|
|
132
|
+
const entryValue = value[key];
|
|
133
|
+
return entryValue === null || typeof entryValue === "boolean" || typeof entryValue === "number" || typeof entryValue === "string" ? entryValue : void 0;
|
|
134
|
+
}
|
|
135
|
+
function preserveUnownedKeyedArrayEntries(value, ownership, replacements = []) {
|
|
136
|
+
const current = Array.isArray(value) ? value : [];
|
|
137
|
+
const replacementKeys = replacements.flatMap((entry) => {
|
|
138
|
+
const key = getKeyedArrayEntryValue(entry, ownership.key);
|
|
139
|
+
return key === void 0 ? [] : [key];
|
|
140
|
+
});
|
|
141
|
+
const ownedKeys = new Set([...ownership.values ?? [], ...replacementKeys]);
|
|
142
|
+
return current.filter((entry) => {
|
|
143
|
+
const key = getKeyedArrayEntryValue(entry, ownership.key);
|
|
144
|
+
return key === void 0 || !ownedKeys.has(key);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
function mergeOwnedArrays(existing, value, arrays) {
|
|
148
|
+
const next = { ...value };
|
|
149
|
+
for (const [field, ownership] of Object.entries(arrays ?? {})) {
|
|
150
|
+
const incoming = Array.isArray(value[field]) ? value[field] : [];
|
|
151
|
+
const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
|
|
152
|
+
if (merged.length) next[field] = merged;
|
|
153
|
+
else delete next[field];
|
|
154
|
+
}
|
|
155
|
+
return next;
|
|
156
|
+
}
|
|
157
|
+
async function persistProviderJsonRecord(file, value, removeIfEmpty) {
|
|
158
|
+
if (removeIfEmpty && !Object.keys(value).length) {
|
|
159
|
+
await rm(file, { force: true });
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
163
|
+
}
|
|
164
|
+
async function writeProviderOutputConfig(file, value, ownership = {}, options = {}) {
|
|
165
|
+
await persistProviderJsonRecord(file, mergeProviderOutputConfig(await readProviderJsonRecord(file) ?? {}, value, ownership), options.removeIfEmpty === true);
|
|
166
|
+
}
|
|
167
|
+
function mergeProviderOutputConfig(existing, value, ownership = {}) {
|
|
168
|
+
assertProviderJsonRecord(existing);
|
|
169
|
+
assertProviderJsonRecord(value);
|
|
170
|
+
return {
|
|
171
|
+
...deleteOwnedFields(existing, ownership),
|
|
172
|
+
...mergeOwnedArrays(existing, value, ownership.arrays)
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
function stringifyProviderOutputConfig(value) {
|
|
176
|
+
assertProviderJsonRecord(value);
|
|
177
|
+
return JSON.stringify(value, null, 2);
|
|
178
|
+
}
|
|
179
|
+
async function cleanProviderOutputConfig(file, ownership) {
|
|
180
|
+
if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
|
|
181
|
+
const existing = await readProviderJsonRecord(file);
|
|
182
|
+
if (!existing) return;
|
|
183
|
+
const next = deleteOwnedFields(existing, ownership);
|
|
184
|
+
let changed = (ownership.keys ?? []).some((key) => key in existing);
|
|
185
|
+
for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
|
|
186
|
+
if (!(field in existing)) continue;
|
|
187
|
+
const current = existing[field];
|
|
188
|
+
const preserved = preserveUnownedKeyedArrayEntries(current, arrayOwnership);
|
|
189
|
+
changed ||= !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
|
|
190
|
+
if (preserved.length) next[field] = preserved;
|
|
191
|
+
}
|
|
192
|
+
if (!changed) return;
|
|
193
|
+
await persistProviderJsonRecord(file, next, true);
|
|
194
|
+
}
|
|
195
|
+
//#endregion
|
|
196
|
+
//#region ../internal/src/build/user-entry.ts
|
|
197
|
+
function toSafeAppName(rootDir) {
|
|
198
|
+
return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
|
|
199
|
+
}
|
|
200
|
+
const DEFAULT_ENTRY_NAMES = [
|
|
201
|
+
"server.ts",
|
|
202
|
+
"server.mts",
|
|
203
|
+
"server.js",
|
|
204
|
+
"server.mjs",
|
|
205
|
+
"worker.ts",
|
|
206
|
+
"worker.mts",
|
|
207
|
+
"worker.js",
|
|
208
|
+
"worker.mjs"
|
|
209
|
+
];
|
|
210
|
+
function resolveUserAppEntry(rootDir, options = {}) {
|
|
211
|
+
const names = options.names ?? DEFAULT_ENTRY_NAMES;
|
|
212
|
+
const srcSubdir = options.srcSubdir ?? "src";
|
|
213
|
+
return names.map((name) => resolve(rootDir, srcSubdir, name)).find(existsSync);
|
|
214
|
+
}
|
|
215
|
+
//#endregion
|
|
216
|
+
//#region ../internal/src/build/cloudflare.ts
|
|
217
|
+
const defaultCloudflareCompatibilityDate = "2026-04-20";
|
|
218
|
+
function createDefaultCloudflareOutputRoot(rootDir) {
|
|
219
|
+
return resolve(rootDir, "dist", toSafeAppName(rootDir));
|
|
220
|
+
}
|
|
221
|
+
async function writeCloudflareWranglerConfig(options) {
|
|
222
|
+
const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
|
|
223
|
+
const configFile = resolve(outputRoot, "wrangler.json");
|
|
224
|
+
if (!options.wranglerConfig) {
|
|
225
|
+
await cleanProviderOutputConfig(configFile, options.wranglerConfigOwnership ?? {});
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
await mkdir(outputRoot, { recursive: true });
|
|
229
|
+
await writeProviderOutputConfig(configFile, options.wranglerConfig, options.wranglerConfigOwnership, { removeIfEmpty: true });
|
|
230
|
+
}
|
|
231
|
+
//#endregion
|
|
232
|
+
//#region ../internal/src/build/vite.ts
|
|
233
|
+
const projectRootDirectoryMarkers = [
|
|
234
|
+
["server", "agents"],
|
|
235
|
+
["server", "schedules"],
|
|
236
|
+
["server", "templates"],
|
|
237
|
+
["server", "workspaces"]
|
|
238
|
+
];
|
|
239
|
+
const projectRootDefinitionFileMarkers = [
|
|
240
|
+
".ts",
|
|
241
|
+
".mts",
|
|
242
|
+
".cts",
|
|
243
|
+
".js",
|
|
244
|
+
".mjs",
|
|
245
|
+
".cjs"
|
|
246
|
+
].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
|
|
247
|
+
const projectRootFileMarkers = [["package.json"]];
|
|
248
|
+
function createNoExternalMerger(packageName) {
|
|
249
|
+
return (current) => {
|
|
250
|
+
if (current === true) return true;
|
|
251
|
+
if (!current) return [packageName];
|
|
252
|
+
const values = Array.isArray(current) ? current : [current];
|
|
253
|
+
return values.includes(packageName) ? values : [...values, packageName];
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
function isServerEnvironment(name, config) {
|
|
257
|
+
return name === "ssr" || config.consumer === "server";
|
|
258
|
+
}
|
|
259
|
+
function includesNitroVitePlugin(value) {
|
|
260
|
+
if (Array.isArray(value)) return value.some(includesNitroVitePlugin);
|
|
261
|
+
if (!value || typeof value !== "object") return false;
|
|
262
|
+
return "name" in value && value.name === "nitro:main";
|
|
263
|
+
}
|
|
264
|
+
function hasNitroVitePlugin(config) {
|
|
265
|
+
return includesNitroVitePlugin(config.plugins);
|
|
266
|
+
}
|
|
267
|
+
function resolveNitroVercelFunctionName(config, product, env = process.env) {
|
|
268
|
+
const preset = config.nitro?.preset || env.NITRO_PRESET || env.SERVER_PRESET;
|
|
269
|
+
const nitro = Boolean(preset) || hasNitroVitePlugin(config);
|
|
270
|
+
const clientOutDir = config.environments?.client?.build?.outDir;
|
|
271
|
+
const vercel = preset ? preset.startsWith("vercel") : env.VITEHUB_HOSTING === "vercel" || Boolean(env.VERCEL) || Boolean(clientOutDir && /(^|[/\\])\.vercel[/\\]output([/\\]|$)/.test(clientOutDir));
|
|
272
|
+
return nitro && vercel ? `__${product}.func` : void 0;
|
|
273
|
+
}
|
|
274
|
+
function shouldSkipViteProviderBuild(command, mode) {
|
|
275
|
+
return command === "serve" || mode === "e2e";
|
|
276
|
+
}
|
|
277
|
+
function resolveViteHubProjectRoot(root, options = {}) {
|
|
278
|
+
const resolvedRoot = resolve(root);
|
|
279
|
+
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
280
|
+
if (basename(resolvedRoot) === "app") {
|
|
281
|
+
const parent = dirname(resolvedRoot);
|
|
282
|
+
if (hasProjectRootDirectoryMarker(parent) || hasProjectRootDefinitionFileMarker(parent)) return parent;
|
|
283
|
+
}
|
|
284
|
+
let current = resolvedRoot;
|
|
285
|
+
while (true) {
|
|
286
|
+
if (hasProjectRootMarker(current)) return current;
|
|
287
|
+
const parent = dirname(current);
|
|
288
|
+
if (parent === current) return resolvedRoot;
|
|
289
|
+
current = parent;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
function hasProjectRootDirectoryMarker(root) {
|
|
293
|
+
for (const marker of projectRootDirectoryMarkers) try {
|
|
294
|
+
if (statSync(resolve(root, ...marker)).isDirectory()) return true;
|
|
295
|
+
} catch (error) {
|
|
296
|
+
if (error.code !== "ENOENT") throw error;
|
|
297
|
+
}
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
function hasProjectRootMarker(root) {
|
|
301
|
+
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
302
|
+
if (hasProjectRootDefinitionFileMarker(root)) return true;
|
|
303
|
+
for (const marker of projectRootFileMarkers) try {
|
|
304
|
+
if (statSync(resolve(root, ...marker)).isFile()) return true;
|
|
305
|
+
} catch (error) {
|
|
306
|
+
if (error.code !== "ENOENT") throw error;
|
|
307
|
+
}
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
function hasProjectRootDefinitionFileMarker(root) {
|
|
311
|
+
for (const marker of projectRootDefinitionFileMarkers) try {
|
|
312
|
+
if (statSync(resolve(root, ...marker)).isFile()) return true;
|
|
313
|
+
} catch (error) {
|
|
314
|
+
if (error.code !== "ENOENT") throw error;
|
|
315
|
+
}
|
|
316
|
+
return false;
|
|
317
|
+
}
|
|
318
|
+
//#endregion
|
|
319
|
+
//#region ../internal/src/build/esbuild.ts
|
|
320
|
+
const viteRawNamespace = "vitehub-vite-raw";
|
|
321
|
+
const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
|
|
322
|
+
const markdownTemplateFileSuffix = ".template.md";
|
|
323
|
+
const markdownTemplateModuleQuery = "markdown-template";
|
|
324
|
+
const markdownTemplateRegistryId = "#vitehub/templates";
|
|
325
|
+
const markdownTemplateRegistryPath = ".vitehub/markdown-template/templates.mjs";
|
|
326
|
+
const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
|
|
327
|
+
const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
|
|
328
|
+
function resolveEsbuildAliases(aliases) {
|
|
329
|
+
if (!aliases) return;
|
|
330
|
+
return Object.fromEntries(Object.entries(aliases).filter(([specifier]) => !specifier.endsWith("/")));
|
|
331
|
+
}
|
|
332
|
+
function stripMarkdownCode(template) {
|
|
333
|
+
let fence;
|
|
334
|
+
let inList = false;
|
|
335
|
+
let previousLineBlank = true;
|
|
336
|
+
return template.split("\n").map((line) => {
|
|
337
|
+
const content = line.replace(/^(?: {0,3}> ?)+/, "");
|
|
338
|
+
if (!fence) {
|
|
339
|
+
const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
|
|
340
|
+
const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
|
|
341
|
+
if (!opening) {
|
|
342
|
+
if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
|
|
343
|
+
else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
|
|
344
|
+
const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
|
|
345
|
+
previousLineBlank = content.trim() === "";
|
|
346
|
+
return indentedCode ? "" : line;
|
|
347
|
+
}
|
|
348
|
+
fence = {
|
|
349
|
+
marker: opening[1][0],
|
|
350
|
+
length: opening[1].length,
|
|
351
|
+
listIndented
|
|
352
|
+
};
|
|
353
|
+
previousLineBlank = false;
|
|
354
|
+
return "";
|
|
355
|
+
}
|
|
356
|
+
const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
|
|
357
|
+
if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
|
|
358
|
+
previousLineBlank = false;
|
|
359
|
+
return "";
|
|
360
|
+
}).join("\n");
|
|
361
|
+
}
|
|
362
|
+
function extractMarkdownTemplateImportSpecifiers(template) {
|
|
363
|
+
const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
|
|
364
|
+
const specifiers = /* @__PURE__ */ new Set();
|
|
365
|
+
for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
|
|
366
|
+
const token = match[1];
|
|
367
|
+
const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
|
|
368
|
+
specifiers.add(token.slice(0, token.length - trailing.length));
|
|
369
|
+
}
|
|
370
|
+
return [...specifiers];
|
|
371
|
+
}
|
|
372
|
+
function parseMarkdownTemplateRequest(id) {
|
|
373
|
+
const queryIndex = id.indexOf("?");
|
|
374
|
+
const path = id.split(/[?#]/, 1)[0];
|
|
375
|
+
if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
|
|
376
|
+
const query = id.slice(queryIndex + 1).split("#", 1)[0];
|
|
377
|
+
if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
|
|
378
|
+
return { path };
|
|
379
|
+
}
|
|
380
|
+
function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
|
|
381
|
+
return [
|
|
382
|
+
`import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
|
|
383
|
+
`const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
|
|
384
|
+
`const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
|
|
385
|
+
`const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
|
|
386
|
+
"export default function render(data = {}) {",
|
|
387
|
+
" return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
|
|
388
|
+
"}",
|
|
389
|
+
""
|
|
390
|
+
].join("\n");
|
|
391
|
+
}
|
|
392
|
+
function hasViteRawQuery(path) {
|
|
393
|
+
const queryIndex = path.indexOf("?");
|
|
394
|
+
return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
|
|
395
|
+
}
|
|
396
|
+
async function resolveViteRawSpecifier(path, rootDir) {
|
|
397
|
+
if (path.startsWith("/@fs/")) return path.slice(5);
|
|
398
|
+
if (!rootDir || !path.startsWith("/")) return path;
|
|
399
|
+
const rootRelativePath = path.slice(1);
|
|
400
|
+
const publicPath = resolve(rootDir, "public", rootRelativePath);
|
|
401
|
+
try {
|
|
402
|
+
await stat(publicPath);
|
|
403
|
+
return publicPath;
|
|
404
|
+
} catch (error) {
|
|
405
|
+
if (error.code !== "ENOENT") throw error;
|
|
406
|
+
return resolve(rootDir, rootRelativePath);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
function createViteRawPlugin(rootDir, frameworkRuntime) {
|
|
410
|
+
return {
|
|
411
|
+
name: "vitehub-vite-raw",
|
|
412
|
+
setup(build) {
|
|
413
|
+
build.onResolve({
|
|
414
|
+
filter: /^@vite-hub\/markdown-template$/,
|
|
415
|
+
namespace: viteMarkdownTemplateNamespace
|
|
416
|
+
}, async (args) => {
|
|
417
|
+
if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
|
|
418
|
+
return build.resolve("vite-hub/_internal/markdown-template", {
|
|
419
|
+
importer: args.importer,
|
|
420
|
+
kind: args.kind,
|
|
421
|
+
resolveDir: args.resolveDir
|
|
422
|
+
});
|
|
423
|
+
});
|
|
424
|
+
build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
|
|
425
|
+
if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
|
|
426
|
+
const markdownTemplate = parseMarkdownTemplateRequest(args.path);
|
|
427
|
+
const raw = hasViteRawQuery(args.path);
|
|
428
|
+
if (!markdownTemplate && !raw) return;
|
|
429
|
+
const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
|
|
430
|
+
const resolved = await build.resolve(specifier, {
|
|
431
|
+
importer: args.importer,
|
|
432
|
+
kind: args.kind,
|
|
433
|
+
namespace: args.namespace,
|
|
434
|
+
pluginData: markdownTemplate ? {
|
|
435
|
+
...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
|
|
436
|
+
[skipMarkdownTemplateResolve]: true
|
|
437
|
+
} : args.pluginData,
|
|
438
|
+
resolveDir: args.resolveDir,
|
|
439
|
+
with: args.with
|
|
440
|
+
});
|
|
441
|
+
if (resolved.errors.length) return {
|
|
442
|
+
errors: resolved.errors,
|
|
443
|
+
warnings: resolved.warnings
|
|
444
|
+
};
|
|
445
|
+
if (resolved.external) return {
|
|
446
|
+
external: true,
|
|
447
|
+
namespace: resolved.namespace,
|
|
448
|
+
path: resolved.path,
|
|
449
|
+
pluginData: resolved.pluginData,
|
|
450
|
+
sideEffects: resolved.sideEffects,
|
|
451
|
+
suffix: resolved.suffix,
|
|
452
|
+
warnings: resolved.warnings
|
|
453
|
+
};
|
|
454
|
+
if (resolved.namespace !== "file") return {
|
|
455
|
+
errors: [{ text: markdownTemplate ? `[vitehub] Markdown template fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this template import in a caller plugin.` : `[vitehub] Vite raw fallback cannot load ${JSON.stringify(args.path)} from the ${JSON.stringify(resolved.namespace)} namespace. Handle this raw import in a caller plugin.` }],
|
|
456
|
+
warnings: resolved.warnings
|
|
457
|
+
};
|
|
458
|
+
return {
|
|
459
|
+
namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
|
|
460
|
+
path: resolved.path,
|
|
461
|
+
pluginData: resolved.pluginData,
|
|
462
|
+
sideEffects: resolved.sideEffects,
|
|
463
|
+
suffix: resolved.suffix,
|
|
464
|
+
warnings: resolved.warnings
|
|
465
|
+
};
|
|
466
|
+
});
|
|
467
|
+
build.onLoad({
|
|
468
|
+
filter: /.*/,
|
|
469
|
+
namespace: viteRawNamespace
|
|
470
|
+
}, async (args) => ({
|
|
471
|
+
contents: await readFile(args.path),
|
|
472
|
+
loader: "text"
|
|
473
|
+
}));
|
|
474
|
+
build.onLoad({
|
|
475
|
+
filter: /.*/,
|
|
476
|
+
namespace: viteMarkdownTemplateNamespace
|
|
477
|
+
}, async (args) => ({
|
|
478
|
+
contents: await (async () => {
|
|
479
|
+
const template = await readFile(args.path, "utf8");
|
|
480
|
+
const imports = {};
|
|
481
|
+
const visited = new Set([args.path]);
|
|
482
|
+
const visit = async (source, importer) => {
|
|
483
|
+
for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
|
|
484
|
+
const key = `${importer}\0${specifier}`;
|
|
485
|
+
if (imports[key]) continue;
|
|
486
|
+
const resolved = await build.resolve(specifier, {
|
|
487
|
+
importer,
|
|
488
|
+
kind: "import-statement",
|
|
489
|
+
pluginData: {
|
|
490
|
+
...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
|
|
491
|
+
[skipMarkdownTemplateResolve]: true
|
|
492
|
+
},
|
|
493
|
+
resolveDir: dirname(importer)
|
|
494
|
+
});
|
|
495
|
+
if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
|
|
496
|
+
if (resolved.external || resolved.namespace !== "file") throw new Error(`[vitehub] Could not resolve Markdown template import ${JSON.stringify(specifier)} from ${JSON.stringify(importer)} to a file.`);
|
|
497
|
+
const imported = {
|
|
498
|
+
id: resolved.path,
|
|
499
|
+
template: await readFile(resolved.path, "utf8")
|
|
500
|
+
};
|
|
501
|
+
imports[key] = imported;
|
|
502
|
+
if (!visited.has(imported.id)) {
|
|
503
|
+
visited.add(imported.id);
|
|
504
|
+
await visit(imported.template, imported.id);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
await visit(template, args.path);
|
|
509
|
+
return renderMarkdownTemplateModule(template, args.path, imports);
|
|
510
|
+
})(),
|
|
511
|
+
loader: "js",
|
|
512
|
+
resolveDir: dirname(args.path)
|
|
513
|
+
}));
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
async function bundleEsmEntry(entryFile, outfile, options = {}) {
|
|
518
|
+
const format = options.format || "esm";
|
|
519
|
+
const platform = options.platform || "neutral";
|
|
520
|
+
const markdownTemplateRoot = options.rootDir && resolveViteHubProjectRoot(options.rootDir);
|
|
521
|
+
const aliases = resolveEsbuildAliases({
|
|
522
|
+
...markdownTemplateRoot ? { [markdownTemplateRegistryId]: resolve(markdownTemplateRoot, markdownTemplateRegistryPath) } : {},
|
|
523
|
+
...options.alias
|
|
524
|
+
});
|
|
525
|
+
const frameworkRuntime = Object.keys(aliases || {}).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
|
|
526
|
+
await build({
|
|
527
|
+
alias: aliases,
|
|
528
|
+
banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
|
|
529
|
+
"import { createRequire as __createRequire } from \"node:module\";",
|
|
530
|
+
"import { dirname as __vitehubDirname } from \"node:path\";",
|
|
531
|
+
"import { fileURLToPath as __vitehubFileURLToPath } from \"node:url\";",
|
|
532
|
+
"globalThis.require = __createRequire(import.meta.url);",
|
|
533
|
+
"globalThis.__filename = __vitehubFileURLToPath(import.meta.url);",
|
|
534
|
+
"globalThis.__dirname = __vitehubDirname(globalThis.__filename);"
|
|
535
|
+
] : []].filter(Boolean).join("\n") } : void 0,
|
|
536
|
+
bundle: true,
|
|
537
|
+
conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
|
|
538
|
+
entryPoints: [entryFile],
|
|
539
|
+
external: options.external,
|
|
540
|
+
format,
|
|
541
|
+
logLevel: "silent",
|
|
542
|
+
mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
|
|
543
|
+
minifyIdentifiers: options.minifyIdentifiers,
|
|
544
|
+
outfile,
|
|
545
|
+
platform,
|
|
546
|
+
plugins: [...options.plugins ?? [], createViteRawPlugin(options.rootDir, frameworkRuntime)],
|
|
547
|
+
sourcemap: false,
|
|
548
|
+
target: "es2022",
|
|
549
|
+
write: true
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
//#endregion
|
|
553
|
+
//#region ../internal/src/build/vercel-config.ts
|
|
554
|
+
function createVercelConfigJson() {
|
|
555
|
+
return {
|
|
556
|
+
routes: [{ handle: "filesystem" }, {
|
|
557
|
+
src: "/(.*)",
|
|
558
|
+
dest: "/__server"
|
|
559
|
+
}],
|
|
560
|
+
version: 3
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
function createNodeFunctionConfig(extra = {}) {
|
|
564
|
+
return {
|
|
565
|
+
handler: "index.mjs",
|
|
566
|
+
launcherType: "Nodejs",
|
|
567
|
+
runtime: "nodejs22.x",
|
|
568
|
+
shouldAddHelpers: false,
|
|
569
|
+
supportsResponseStreaming: true,
|
|
570
|
+
...extra
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
//#endregion
|
|
574
|
+
//#region ../internal/src/build/cloudflare-provider-output.ts
|
|
575
|
+
const cloudflareProviderOutputKey = Symbol.for("vitehub.cloudflareProviderOutput");
|
|
576
|
+
const cloudflareProviderOutputByNitro = /* @__PURE__ */ new WeakMap();
|
|
577
|
+
function cloneRecord(value) {
|
|
578
|
+
return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
|
|
579
|
+
}
|
|
580
|
+
function cloneProviderRecord(value) {
|
|
581
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
582
|
+
return Object.fromEntries(Object.entries(value).flatMap(([key, entry]) => typeof entry === "undefined" ? [] : [[key, cloneProviderValue(entry)]]));
|
|
583
|
+
}
|
|
584
|
+
function cloneProviderValue(value) {
|
|
585
|
+
if (Array.isArray(value)) return value.map((entry) => typeof entry === "undefined" ? null : cloneProviderValue(entry));
|
|
586
|
+
if (value && typeof value === "object") return cloneProviderRecord(value);
|
|
587
|
+
return value;
|
|
588
|
+
}
|
|
589
|
+
function useCloudflareProviderOutput(config) {
|
|
590
|
+
const owner = config;
|
|
591
|
+
return owner[cloudflareProviderOutputKey] ??= {
|
|
592
|
+
appliedByOwner: /* @__PURE__ */ new Map(),
|
|
593
|
+
contributionsByOwner: /* @__PURE__ */ new Map()
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
function registerCloudflareProviderOutput(config, owner, contribution) {
|
|
597
|
+
useCloudflareProviderOutput(config).contributionsByOwner.set(owner, contribution);
|
|
598
|
+
}
|
|
599
|
+
function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner) {
|
|
600
|
+
const current = Array.isArray(existing) ? existing.map(cloneProviderRecord) : [];
|
|
601
|
+
return (incoming ?? []).filter((entry) => {
|
|
602
|
+
const identity = entry[identityKey];
|
|
603
|
+
const match = current.find((candidate) => candidate[identityKey] === identity);
|
|
604
|
+
if (!match) {
|
|
605
|
+
current.push(entry);
|
|
606
|
+
return true;
|
|
607
|
+
}
|
|
608
|
+
if (conflictKeys.some((key) => !isDeepStrictEqual(match[key], entry[key]))) throw new Error(`[vitehub] Cloudflare ${identityKey} ${JSON.stringify(identity)} from ${owner} is already assigned to an incompatible resource.`);
|
|
609
|
+
return false;
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
function removeEntries(existing, entries) {
|
|
613
|
+
if (!Array.isArray(existing) || !entries?.length) return Array.isArray(existing) ? existing : [];
|
|
614
|
+
return existing.filter((entry) => !entries.some((previous) => isDeepStrictEqual(entry, previous)));
|
|
615
|
+
}
|
|
616
|
+
function removeContribution(wrangler, contribution) {
|
|
617
|
+
const queues = cloneProviderRecord(wrangler.queues);
|
|
618
|
+
const hasQueues = Boolean(contribution.queues?.consumers?.length || contribution.queues?.producers?.length);
|
|
619
|
+
if (contribution.queues?.consumers?.length) {
|
|
620
|
+
const consumers = removeEntries(queues.consumers, contribution.queues.consumers);
|
|
621
|
+
if (consumers.length) queues.consumers = consumers;
|
|
622
|
+
else delete queues.consumers;
|
|
623
|
+
}
|
|
624
|
+
if (contribution.queues?.producers?.length) {
|
|
625
|
+
const producers = removeEntries(queues.producers, contribution.queues.producers);
|
|
626
|
+
if (producers.length) queues.producers = producers;
|
|
627
|
+
else delete queues.producers;
|
|
628
|
+
}
|
|
629
|
+
const { queues: _queues, ...withoutQueues } = wrangler;
|
|
630
|
+
return {
|
|
631
|
+
...hasQueues ? withoutQueues : wrangler,
|
|
632
|
+
...hasQueues && Object.keys(queues).length ? { queues } : {},
|
|
633
|
+
...contribution.r2Buckets?.length ? { r2_buckets: removeEntries(wrangler.r2_buckets, contribution.r2Buckets) } : {},
|
|
634
|
+
...contribution.rateLimits?.length ? { ratelimits: removeEntries(wrangler.ratelimits, contribution.rateLimits) } : {}
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
function mergeContribution(wrangler, owner, contribution) {
|
|
638
|
+
const queues = cloneProviderRecord(wrangler.queues);
|
|
639
|
+
const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner);
|
|
640
|
+
const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
|
|
641
|
+
const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name"], owner);
|
|
642
|
+
const rateLimits = compatibleEntries(wrangler.ratelimits, contribution.rateLimits, "name", ["namespace_id", "simple"], owner);
|
|
643
|
+
const nextQueues = mergeProviderOutputConfig(queues, {
|
|
644
|
+
...consumers.length ? { consumers } : {},
|
|
645
|
+
...producers.length ? { producers } : {}
|
|
646
|
+
}, { arrays: {
|
|
647
|
+
consumers: { key: "queue" },
|
|
648
|
+
producers: { key: "binding" }
|
|
649
|
+
} });
|
|
650
|
+
return [mergeProviderOutputConfig(wrangler, {
|
|
651
|
+
...Object.keys(nextQueues).length ? { queues: nextQueues } : {},
|
|
652
|
+
...r2Buckets.length ? { r2_buckets: r2Buckets } : {},
|
|
653
|
+
...rateLimits.length ? { ratelimits: rateLimits } : {}
|
|
654
|
+
}, { arrays: {
|
|
655
|
+
r2_buckets: { key: "binding" },
|
|
656
|
+
ratelimits: { key: "name" }
|
|
657
|
+
} }), {
|
|
658
|
+
queues: {
|
|
659
|
+
consumers,
|
|
660
|
+
producers
|
|
661
|
+
},
|
|
662
|
+
r2Buckets,
|
|
663
|
+
rateLimits
|
|
664
|
+
}];
|
|
665
|
+
}
|
|
666
|
+
function composeNitroCloudflareProviderOutput(config, value) {
|
|
667
|
+
const nitro = cloneRecord(value);
|
|
668
|
+
const cloudflare = cloneRecord(nitro.cloudflare);
|
|
669
|
+
const catalog = useCloudflareProviderOutput(config);
|
|
670
|
+
const inherited = value && typeof value === "object" ? value[cloudflareProviderOutputKey] ?? cloudflareProviderOutputByNitro.get(value) : void 0;
|
|
671
|
+
if (inherited && inherited !== catalog) {
|
|
672
|
+
for (const [owner, contribution] of inherited.appliedByOwner) catalog.appliedByOwner.set(owner, contribution);
|
|
673
|
+
catalog.contributionsByOwner = new Map([...inherited.contributionsByOwner, ...catalog.contributionsByOwner]);
|
|
674
|
+
}
|
|
675
|
+
let wrangler = cloneProviderRecord(cloudflare.wrangler);
|
|
676
|
+
for (const contribution of catalog.appliedByOwner.values()) wrangler = removeContribution(wrangler, contribution);
|
|
677
|
+
catalog.appliedByOwner.clear();
|
|
678
|
+
for (const [owner, contribution] of catalog.contributionsByOwner) {
|
|
679
|
+
const [merged, applied] = mergeContribution(wrangler, owner, contribution);
|
|
680
|
+
wrangler = merged;
|
|
681
|
+
catalog.appliedByOwner.set(owner, applied);
|
|
682
|
+
}
|
|
683
|
+
const output = !Object.keys(cloudflare).length && !Object.keys(wrangler).length ? nitro : {
|
|
684
|
+
...nitro,
|
|
685
|
+
cloudflare: {
|
|
686
|
+
...cloudflare,
|
|
687
|
+
wrangler
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
Object.defineProperty(output, cloudflareProviderOutputKey, {
|
|
691
|
+
enumerable: true,
|
|
692
|
+
value: catalog
|
|
693
|
+
});
|
|
694
|
+
cloudflareProviderOutputByNitro.set(output, catalog);
|
|
695
|
+
return output;
|
|
696
|
+
}
|
|
697
|
+
//#endregion
|
|
698
|
+
//#region ../internal/src/build/deployment-output.ts
|
|
699
|
+
const composedProviderOutputKey = Symbol.for("vitehub.composedProviderOutput");
|
|
700
|
+
const providerDeploymentOutputWrites = /* @__PURE__ */ new Map();
|
|
701
|
+
function useComposedProviderOutput(config) {
|
|
702
|
+
const owner = config;
|
|
703
|
+
return owner[composedProviderOutputKey] ??= {
|
|
704
|
+
runtimeModuleFilesByProduct: {},
|
|
705
|
+
vercelRuntimePackagesByProduct: {}
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
function getProviderRuntimeModule(composed, product, provider) {
|
|
709
|
+
return composed?.runtimeModuleFilesByProduct[product]?.[provider];
|
|
710
|
+
}
|
|
711
|
+
function getVercelRuntimePackages(composed, product) {
|
|
712
|
+
return composed?.vercelRuntimePackagesByProduct?.[product] ?? [];
|
|
713
|
+
}
|
|
714
|
+
function resolveClientOutput(rootDir, clientOutDir) {
|
|
715
|
+
const clientDir = resolve(rootDir, clientOutDir);
|
|
716
|
+
return {
|
|
717
|
+
clientDir,
|
|
718
|
+
staticIndex: hasStaticIndex(clientDir)
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
function createDefaultCloudflareStaticOutputDir(rootDir) {
|
|
722
|
+
return resolve(rootDir, "dist", "client");
|
|
723
|
+
}
|
|
724
|
+
function createDefaultVercelOutputRoot(rootDir) {
|
|
725
|
+
return resolve(rootDir, ".vercel", "output");
|
|
726
|
+
}
|
|
727
|
+
function createDefaultNetlifyOutputRoot(rootDir) {
|
|
728
|
+
return resolve(rootDir, ".netlify", "v1");
|
|
729
|
+
}
|
|
730
|
+
function assertNetlifyFunctionName(functionName) {
|
|
731
|
+
if (!functionName || functionName.includes("\\") || functionName.split("/").some((part) => !part || part === "." || part === "..")) throw new Error(`Invalid Netlify function name: ${functionName}`);
|
|
732
|
+
}
|
|
733
|
+
function resolveNetlifyFunctionFile(functionsRoot, functionName) {
|
|
734
|
+
assertNetlifyFunctionName(functionName);
|
|
735
|
+
return resolve(functionsRoot, `${functionName}.mjs`);
|
|
736
|
+
}
|
|
737
|
+
async function appendNetlifyFunctionConfig(outfile, config) {
|
|
738
|
+
if (!config) return;
|
|
739
|
+
await writeFile(outfile, `${(await readFile(outfile, "utf8")).trimEnd()}\n\nexport const config = ${stringifyProviderOutputConfig(config)}\n`, "utf8");
|
|
740
|
+
}
|
|
741
|
+
async function writeCloudflareDeploymentOutput(options) {
|
|
742
|
+
const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
|
|
743
|
+
const outputRoot = options.outputRoot ?? createDefaultCloudflareOutputRoot(options.rootDir);
|
|
744
|
+
const files = Object.entries(options.files ?? {});
|
|
745
|
+
const workerOutfile = options.bundleEntry ? resolve(outputRoot, options.bundleOutfileName ?? "index.js") : void 0;
|
|
746
|
+
if (workerOutfile && files.some(([fileName]) => resolve(outputRoot, fileName) === workerOutfile)) throw new Error(`Cloudflare output file conflicts with bundle outfile: ${workerOutfile}`);
|
|
747
|
+
await mkdir(outputRoot, { recursive: true });
|
|
748
|
+
const writes = [
|
|
749
|
+
writeCloudflareWranglerConfig({
|
|
750
|
+
outputRoot,
|
|
751
|
+
rootDir: options.rootDir,
|
|
752
|
+
wranglerConfig: options.wranglerConfig,
|
|
753
|
+
wranglerConfigOwnership: options.wranglerConfigOwnership ?? { keys: options.wranglerConfigKeys }
|
|
754
|
+
}),
|
|
755
|
+
options.bundleEntry && staticIndex ? copyClientOutput(clientDir, options.staticOutputDir ?? createDefaultCloudflareStaticOutputDir(options.rootDir)) : Promise.resolve(),
|
|
756
|
+
...files.map(([fileName, contents]) => writeFile(resolve(outputRoot, fileName), contents, "utf8"))
|
|
757
|
+
];
|
|
758
|
+
if (options.bundleEntry && workerOutfile) {
|
|
759
|
+
await rm(workerOutfile, {
|
|
760
|
+
force: true,
|
|
761
|
+
recursive: true
|
|
762
|
+
});
|
|
763
|
+
writes.push(bundleEsmEntry(options.bundleEntry, workerOutfile, {
|
|
764
|
+
...options.bundleOptions,
|
|
765
|
+
rootDir: options.rootDir
|
|
766
|
+
}));
|
|
767
|
+
}
|
|
768
|
+
await Promise.all(writes);
|
|
769
|
+
}
|
|
770
|
+
async function writeVercelDeploymentOutput(options) {
|
|
771
|
+
const { clientDir, staticIndex } = resolveClientOutput(options.rootDir, options.clientOutDir);
|
|
772
|
+
const outputRoot = options.outputRoot ?? createDefaultVercelOutputRoot(options.rootDir);
|
|
773
|
+
const functionOutput = options.function ?? { kind: "root" };
|
|
774
|
+
const serverFunctionName = functionOutput.kind === "root" ? "__server.func" : functionOutput.name;
|
|
775
|
+
const config = options.config ?? (functionOutput.kind === "root" ? createVercelConfigJson() : {});
|
|
776
|
+
const serverDir = resolve(outputRoot, "functions", serverFunctionName);
|
|
777
|
+
const serverEntry = resolve(serverDir, "index.mjs");
|
|
778
|
+
await mkdir(serverDir, { recursive: true });
|
|
779
|
+
const staleFiles = (await readdir(serverDir)).filter((file) => file !== "node_modules");
|
|
780
|
+
await Promise.all(staleFiles.map((file) => rm(resolve(serverDir, file), {
|
|
781
|
+
force: true,
|
|
782
|
+
recursive: true
|
|
783
|
+
})));
|
|
784
|
+
await Promise.all([
|
|
785
|
+
bundleEsmEntry(options.bundleEntry, serverEntry, {
|
|
786
|
+
...options.bundleOptions,
|
|
787
|
+
rootDir: options.rootDir
|
|
788
|
+
}),
|
|
789
|
+
writeFile(resolve(serverDir, ".vc-config.json"), `${stringifyProviderOutputConfig(options.functionConfig ?? createNodeFunctionConfig())}\n`, "utf8"),
|
|
790
|
+
writeProviderOutputConfig(resolve(outputRoot, "config.json"), config, { keys: options.configKeys }),
|
|
791
|
+
staticIndex ? copyClientOutput(clientDir, options.staticOutputDir ?? resolve(outputRoot, "static")) : Promise.resolve()
|
|
792
|
+
]);
|
|
793
|
+
}
|
|
794
|
+
async function writeNetlifyDeploymentOutput(options) {
|
|
795
|
+
const outputRoot = options.outputRoot ?? createDefaultNetlifyOutputRoot(options.rootDir);
|
|
796
|
+
const functionsRoot = resolve(outputRoot, "functions");
|
|
797
|
+
const functionWrites = (options.functions ?? []).map(async (func) => {
|
|
798
|
+
const outfile = resolveNetlifyFunctionFile(functionsRoot, func.functionName);
|
|
799
|
+
await rm(outfile, {
|
|
800
|
+
force: true,
|
|
801
|
+
recursive: true
|
|
802
|
+
});
|
|
803
|
+
await mkdir(dirname(outfile), { recursive: true });
|
|
804
|
+
await bundleEsmEntry(func.bundleEntry, outfile, {
|
|
805
|
+
...func.bundleOptions,
|
|
806
|
+
minifyIdentifiers: func.config ? true : func.bundleOptions.minifyIdentifiers,
|
|
807
|
+
rootDir: options.rootDir
|
|
808
|
+
});
|
|
809
|
+
await appendNetlifyFunctionConfig(outfile, func.config);
|
|
810
|
+
});
|
|
811
|
+
await mkdir(outputRoot, { recursive: true });
|
|
812
|
+
await Promise.all([writeProviderOutputConfig(resolve(outputRoot, "config.json"), options.config ?? {}, { keys: options.configKeys }), ...functionWrites]);
|
|
813
|
+
}
|
|
814
|
+
async function cleanupCloudflareDeploymentOutput(rootDir, cleanupInput) {
|
|
815
|
+
const cleanup = typeof cleanupInput === "function" ? await cleanupInput() : cleanupInput;
|
|
816
|
+
const outputRoot = cleanup.outputRoot ?? createDefaultCloudflareOutputRoot(rootDir);
|
|
817
|
+
const writes = (cleanup.fileNames ?? []).map((fileName) => rm(resolve(outputRoot, fileName), {
|
|
818
|
+
force: true,
|
|
819
|
+
recursive: true
|
|
820
|
+
}));
|
|
821
|
+
writes.push(writeCloudflareWranglerConfig({
|
|
822
|
+
outputRoot,
|
|
823
|
+
rootDir,
|
|
824
|
+
wranglerConfigOwnership: cleanup.wranglerConfigOwnership
|
|
825
|
+
}));
|
|
826
|
+
await Promise.all(writes);
|
|
827
|
+
try {
|
|
828
|
+
await rmdir(outputRoot);
|
|
829
|
+
} catch (error) {
|
|
830
|
+
const code = error.code;
|
|
831
|
+
if (code !== "ENOENT" && code !== "ENOTEMPTY") throw error;
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
async function cleanupVercelDeploymentOutput(rootDir, cleanup) {
|
|
835
|
+
const outputRoot = cleanup.outputRoot ?? createDefaultVercelOutputRoot(rootDir);
|
|
836
|
+
const writes = [];
|
|
837
|
+
if (cleanup.serverFunctionName) writes.push(rm(resolve(outputRoot, "functions", cleanup.serverFunctionName), {
|
|
838
|
+
force: true,
|
|
839
|
+
recursive: true
|
|
840
|
+
}));
|
|
841
|
+
writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
|
|
842
|
+
await Promise.all(writes);
|
|
843
|
+
}
|
|
844
|
+
async function cleanupVercelDeploymentOutputs(rootDir, cleanup) {
|
|
845
|
+
await Promise.all((Array.isArray(cleanup) ? cleanup : [cleanup]).map((item) => cleanupVercelDeploymentOutput(rootDir, item)));
|
|
846
|
+
}
|
|
847
|
+
async function cleanupNetlifyDeploymentOutput(rootDir, cleanup) {
|
|
848
|
+
const outputRoot = cleanup.outputRoot ?? createDefaultNetlifyOutputRoot(rootDir);
|
|
849
|
+
const functionsRoot = resolve(outputRoot, "functions");
|
|
850
|
+
const writes = (cleanup.functionNames ?? []).map((functionName) => rm(resolveNetlifyFunctionFile(functionsRoot, functionName), {
|
|
851
|
+
force: true,
|
|
852
|
+
recursive: true
|
|
853
|
+
}));
|
|
854
|
+
writes.push(cleanProviderOutputConfig(resolve(outputRoot, "config.json"), { keys: cleanup.configKeys }));
|
|
855
|
+
await Promise.all(writes);
|
|
856
|
+
}
|
|
857
|
+
async function writeProviderDeploymentOutputsNow(options) {
|
|
858
|
+
const writes = [];
|
|
859
|
+
if (options.cloudflare) writes.push(writeCloudflareDeploymentOutput({
|
|
860
|
+
...options.cloudflare,
|
|
861
|
+
clientOutDir: options.clientOutDir,
|
|
862
|
+
rootDir: options.rootDir
|
|
863
|
+
}));
|
|
864
|
+
else if (options.cleanup?.cloudflare) writes.push(cleanupCloudflareDeploymentOutput(options.rootDir, options.cleanup.cloudflare));
|
|
865
|
+
if (options.netlify) writes.push(writeNetlifyDeploymentOutput({
|
|
866
|
+
...options.netlify,
|
|
867
|
+
clientOutDir: options.clientOutDir,
|
|
868
|
+
rootDir: options.rootDir
|
|
869
|
+
}));
|
|
870
|
+
else if (options.cleanup?.netlify) writes.push(cleanupNetlifyDeploymentOutput(options.rootDir, options.cleanup.netlify));
|
|
871
|
+
if (options.vercel) writes.push(writeVercelDeploymentOutput({
|
|
872
|
+
...options.vercel,
|
|
873
|
+
clientOutDir: options.clientOutDir,
|
|
874
|
+
rootDir: options.rootDir
|
|
875
|
+
}));
|
|
876
|
+
else if (options.cleanup?.vercel) {
|
|
877
|
+
const cleanup = typeof options.cleanup.vercel === "function" ? await options.cleanup.vercel() : options.cleanup.vercel;
|
|
878
|
+
if (cleanup) writes.push(cleanupVercelDeploymentOutputs(options.rootDir, cleanup));
|
|
879
|
+
}
|
|
880
|
+
await Promise.all(writes);
|
|
881
|
+
await options.afterWrite?.();
|
|
882
|
+
}
|
|
883
|
+
async function writeProviderDeploymentOutputs(options) {
|
|
884
|
+
const key = resolve(options.rootDir);
|
|
885
|
+
const write = (providerDeploymentOutputWrites.get(key) ?? Promise.resolve()).catch(() => void 0).then(() => writeProviderDeploymentOutputsNow(options));
|
|
886
|
+
providerDeploymentOutputWrites.set(key, write);
|
|
887
|
+
try {
|
|
888
|
+
await write;
|
|
889
|
+
} finally {
|
|
890
|
+
if (providerDeploymentOutputWrites.get(key) === write) providerDeploymentOutputWrites.delete(key);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
//#endregion
|
|
894
|
+
//#region ../internal/src/build/paths.ts
|
|
895
|
+
function generatedDirSegments(productName) {
|
|
896
|
+
return [".vitehub", productName];
|
|
897
|
+
}
|
|
898
|
+
function ensureGeneratedDir(rootDir, productName) {
|
|
899
|
+
return resolve$1(rootDir, ...generatedDirSegments(productName));
|
|
900
|
+
}
|
|
901
|
+
function toGeneratedPath(rootDir, productName, filename) {
|
|
902
|
+
return relative$1(rootDir, resolve$1(rootDir, ...generatedDirSegments(productName), filename));
|
|
903
|
+
}
|
|
904
|
+
function computePackageDir(importMetaUrl) {
|
|
905
|
+
const currentFileDir = dirname$1(fileURLToPath(importMetaUrl));
|
|
906
|
+
return resolve$1(currentFileDir, basename$1(currentFileDir) === "internal" ? "../.." : "..");
|
|
907
|
+
}
|
|
908
|
+
function resolveRuntimeModule$1(packageDir, modulePath) {
|
|
909
|
+
const distFile = resolve$1(packageDir, "dist", `${modulePath}.js`);
|
|
910
|
+
return existsSync(distFile) ? distFile : resolve$1(packageDir, "src", `${modulePath}.ts`);
|
|
911
|
+
}
|
|
912
|
+
function createImportPath(fromFile, targetFile) {
|
|
913
|
+
const importPath = relative$1(realpathIfExists(dirname$1(fromFile)), realpathIfExists(targetFile));
|
|
914
|
+
return importPath.startsWith(".") ? importPath : `./${importPath}`;
|
|
915
|
+
}
|
|
916
|
+
function realpathIfExists(path) {
|
|
917
|
+
try {
|
|
918
|
+
return realpathSync.native(path);
|
|
919
|
+
} catch {
|
|
920
|
+
return resolve$1(path);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
//#endregion
|
|
924
|
+
//#region ../internal/src/definition-catalog.ts
|
|
925
|
+
const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
|
|
926
|
+
const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
|
|
927
|
+
const ignoredDirs = new Set([
|
|
928
|
+
"node_modules",
|
|
929
|
+
"dist",
|
|
930
|
+
".output",
|
|
931
|
+
".nuxt",
|
|
932
|
+
".vercel",
|
|
933
|
+
".git",
|
|
934
|
+
".vitehub"
|
|
935
|
+
]);
|
|
936
|
+
function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
|
|
937
|
+
return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
|
|
938
|
+
}
|
|
939
|
+
function createDirectoryDefinitionSource(source, scanDirs, subdir, options = {}) {
|
|
940
|
+
return {
|
|
941
|
+
...options,
|
|
942
|
+
kind: "directory",
|
|
943
|
+
scanDirs,
|
|
944
|
+
source,
|
|
945
|
+
subdir
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
function createSuffixDefinitionSource(source, roots, pattern, normalizeName, options = {}) {
|
|
949
|
+
return {
|
|
950
|
+
...options,
|
|
951
|
+
kind: "suffix",
|
|
952
|
+
normalizeName,
|
|
953
|
+
pattern,
|
|
954
|
+
roots,
|
|
955
|
+
source
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
function readDirEntries(root) {
|
|
959
|
+
try {
|
|
960
|
+
return readdirSync(root, { withFileTypes: true });
|
|
961
|
+
} catch (error) {
|
|
962
|
+
if (error.code === "ENOENT") return [];
|
|
963
|
+
throw error;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
function listMatchingFiles(root, predicate, options = {}) {
|
|
967
|
+
const files = [];
|
|
968
|
+
for (const entry of readDirEntries(root)) {
|
|
969
|
+
const absolute = resolve$1(root, entry.name);
|
|
970
|
+
if (entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
971
|
+
if (entry.name.startsWith(".")) continue;
|
|
972
|
+
if (ignoredDirs.has(entry.name)) continue;
|
|
973
|
+
files.push(...listMatchingFiles(absolute, predicate, options));
|
|
974
|
+
continue;
|
|
975
|
+
}
|
|
976
|
+
if (entry.name.startsWith(".") && !options.includeHidden) continue;
|
|
977
|
+
if (entry.isFile() && predicate(entry.name)) files.push(absolute);
|
|
978
|
+
}
|
|
979
|
+
return files.sort();
|
|
980
|
+
}
|
|
981
|
+
function listSourceFiles(root, options = {}) {
|
|
982
|
+
return listMatchingFiles(root, (name) => sourceFilePattern.test(name) && !declarationFilePattern.test(name), options);
|
|
983
|
+
}
|
|
984
|
+
function normalizePathDefinitionName(rootDir, file) {
|
|
985
|
+
return relative$1(rootDir, file).replace(sourceFilePattern, "").replace(/\/index$/i, "");
|
|
986
|
+
}
|
|
987
|
+
function normalizeSuffixDefinitionName(rootDir, file, pattern, options = {}) {
|
|
988
|
+
const normalized = relative$1(rootDir, file).replace(pattern, "");
|
|
989
|
+
if (options.stripPrefix && normalized.startsWith(options.stripPrefix)) return normalized.slice(options.stripPrefix.length);
|
|
990
|
+
return normalized;
|
|
991
|
+
}
|
|
992
|
+
function sortDefinitions(definitions) {
|
|
993
|
+
return [...definitions.values()].sort((left, right) => left.name.localeCompare(right.name));
|
|
994
|
+
}
|
|
995
|
+
function registerDefinition(definitions, definition, sourceLabel) {
|
|
996
|
+
const existing = definitions.get(definition.name);
|
|
997
|
+
if (existing) throw new Error(`Duplicate ${sourceLabel} name "${definition.name}":\n - ${existing.handler}\n - ${definition.handler}`);
|
|
998
|
+
definitions.set(definition.name, definition);
|
|
999
|
+
}
|
|
1000
|
+
function mergeDefinitions(feature, ...sources) {
|
|
1001
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
1002
|
+
for (const source of sources) {
|
|
1003
|
+
if (!source) continue;
|
|
1004
|
+
for (const definition of source) {
|
|
1005
|
+
const existing = definitions.get(definition.name);
|
|
1006
|
+
if (existing && existing.handler !== definition.handler) throw new Error(`Duplicate ${feature} name "${definition.name}" from multiple discovery sources:\n - ${existing.handler} (${existing.source ?? "unknown"})\n - ${definition.handler} (${definition.source ?? "unknown"})`);
|
|
1007
|
+
if (!existing) definitions.set(definition.name, definition);
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
return sortDefinitions(definitions);
|
|
1011
|
+
}
|
|
1012
|
+
function createDefinition(source, file, name) {
|
|
1013
|
+
if (source.createDefinition) return source.createDefinition({
|
|
1014
|
+
file,
|
|
1015
|
+
name
|
|
1016
|
+
});
|
|
1017
|
+
return {
|
|
1018
|
+
handler: file,
|
|
1019
|
+
name,
|
|
1020
|
+
source: source.source
|
|
1021
|
+
};
|
|
1022
|
+
}
|
|
1023
|
+
function scanSuffixDefinitions(feature, source) {
|
|
1024
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
1025
|
+
for (const root of source.roots) for (const file of listMatchingFiles(root, (name) => source.pattern.test(name), { includeHidden: source.includeHidden })) {
|
|
1026
|
+
const name = source.normalizeName(root, file);
|
|
1027
|
+
if (!name) continue;
|
|
1028
|
+
registerDefinition(definitions, createDefinition(source, file, name), feature);
|
|
1029
|
+
}
|
|
1030
|
+
return sortDefinitions(definitions);
|
|
1031
|
+
}
|
|
1032
|
+
function scanDirectoryDefinitions(feature, source) {
|
|
1033
|
+
const definitions = /* @__PURE__ */ new Map();
|
|
1034
|
+
for (const scanDir of source.scanDirs) {
|
|
1035
|
+
const directory = resolve$1(scanDir, source.subdir);
|
|
1036
|
+
for (const file of listSourceFiles(directory, { includeHidden: source.includeHidden })) {
|
|
1037
|
+
const name = source.normalizeName ? source.normalizeName(directory, file) : normalizePathDefinitionName(directory, file);
|
|
1038
|
+
if (!name) continue;
|
|
1039
|
+
registerDefinition(definitions, createDefinition(source, file, name), feature);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
return sortDefinitions(definitions);
|
|
1043
|
+
}
|
|
1044
|
+
function discoverDefinitions(feature, sources) {
|
|
1045
|
+
return mergeDefinitions(feature, ...sources.map((source) => source.kind === "suffix" ? scanSuffixDefinitions(feature, source) : scanDirectoryDefinitions(feature, source)));
|
|
1046
|
+
}
|
|
1047
|
+
function createImportExpression(registryFile, file) {
|
|
1048
|
+
const importPath = relative$1(resolve$1(registryFile, ".."), file);
|
|
1049
|
+
return `import(${JSON.stringify(importPath.startsWith(".") ? importPath : `./${importPath}`)})`;
|
|
1050
|
+
}
|
|
1051
|
+
function createRuntimeRegistryContents(registryFile, definitions) {
|
|
1052
|
+
const needsWorkflowRuntime = definitions.some((definition) => definition.steps?.length);
|
|
1053
|
+
const runtimeImport = needsWorkflowRuntime ? [`import { createWorkflowSteps } from "@vite-hub/workflow/runtime/execute"`, `import { takeInlineWorkflowDefinitionForModule } from "@vite-hub/workflow/runtime/state"`] : [];
|
|
1054
|
+
const imports = definitions.map((definition) => {
|
|
1055
|
+
if (!definition.steps?.length) return ` ${JSON.stringify(definition.name)}: async () => ${createImportExpression(registryFile, definition.handler)},`;
|
|
1056
|
+
const workflowDirectory = /\.(?:c|m)?[jt]s$/i.test(definition.handler) ? dirname$1(definition.handler) : definition.handler;
|
|
1057
|
+
const stepImports = definition.steps.map((step) => {
|
|
1058
|
+
const stepName = relative$1(workflowDirectory, step);
|
|
1059
|
+
return `{ name: ${JSON.stringify(stepName)}, run: (await ${createImportExpression(registryFile, step)}).default }`;
|
|
1060
|
+
});
|
|
1061
|
+
const hasIndex = /\.(?:c|m)?[jt]s$/i.test(definition.handler);
|
|
1062
|
+
const indexImport = hasIndex ? `const index = await ${createImportExpression(registryFile, definition.handler)}` : "";
|
|
1063
|
+
const handler = hasIndex ? `index.default?.handler ? index.default : takeInlineWorkflowDefinitionForModule(${JSON.stringify(definition.name)}, index) || { handler: index.default }` : "{ handler: async (context) => { let value = context.payload; for (const step of Object.values(context.steps || {})) value = await step(value); return value } }";
|
|
1064
|
+
return [
|
|
1065
|
+
` ${JSON.stringify(definition.name)}: async () => {`,
|
|
1066
|
+
` const cached = registryEntryCache.get(${JSON.stringify(definition.name)})`,
|
|
1067
|
+
" if (cached) return cached",
|
|
1068
|
+
indexImport ? ` ${indexImport}` : "",
|
|
1069
|
+
` const steps = [${stepImports.join(", ")}]`,
|
|
1070
|
+
` const definition = ${handler}`,
|
|
1071
|
+
" const entry = {",
|
|
1072
|
+
" ...definition,",
|
|
1073
|
+
" options: { ...definition.options, rootStep: false },",
|
|
1074
|
+
" handler: async (context) => {",
|
|
1075
|
+
" const workflowSteps = createWorkflowSteps(context, steps)",
|
|
1076
|
+
" return await definition.handler({ ...context, steps: workflowSteps })",
|
|
1077
|
+
" },",
|
|
1078
|
+
" }",
|
|
1079
|
+
` registryEntryCache.set(${JSON.stringify(definition.name)}, entry)`,
|
|
1080
|
+
" return entry",
|
|
1081
|
+
" },"
|
|
1082
|
+
].filter(Boolean).join("\n");
|
|
1083
|
+
});
|
|
1084
|
+
return [
|
|
1085
|
+
...runtimeImport,
|
|
1086
|
+
runtimeImport.length ? "" : "",
|
|
1087
|
+
...needsWorkflowRuntime ? ["const registryEntryCache = new Map()", ""] : [],
|
|
1088
|
+
"const registry = {",
|
|
1089
|
+
...imports,
|
|
1090
|
+
"}",
|
|
1091
|
+
"",
|
|
1092
|
+
"export default registry",
|
|
1093
|
+
""
|
|
1094
|
+
].join("\n");
|
|
1095
|
+
}
|
|
1096
|
+
//#endregion
|
|
1097
|
+
//#region src/discovery.ts
|
|
1098
|
+
const queueSuffixPattern = /\.queue\.(?:c|m)?[jt]s$/i;
|
|
1099
|
+
function normalizeSuffixQueueName(rootDir, file) {
|
|
1100
|
+
return normalizeSuffixDefinitionName(rootDir, file, queueSuffixPattern, { stripPrefix: "src/" });
|
|
1101
|
+
}
|
|
1102
|
+
function discoverQueueDefinitions(options) {
|
|
1103
|
+
if (options.mode === "server-queues") return discoverDefinitions("queue", [createDirectoryDefinitionSource("server-queues", options.scanDirs, "queues")]);
|
|
1104
|
+
const roots = resolveDefinitionScanRoots(options.rootDir, options.scanDirs);
|
|
1105
|
+
const serverScanDirs = options.serverDirs || [...new Set(options.serverRootDirs || roots)].map((root) => resolve$1(root, "server"));
|
|
1106
|
+
return mergeDefinitions("queue", discoverDefinitions("queue", [createSuffixDefinitionSource("vite-suffix", roots, queueSuffixPattern, normalizeSuffixQueueName)]), discoverDefinitions("queue", [createDirectoryDefinitionSource("server-queues", serverScanDirs, "queues")]));
|
|
1107
|
+
}
|
|
1108
|
+
//#endregion
|
|
1109
|
+
//#region src/internal/vite-build.ts
|
|
1110
|
+
const queuePackageName = "@vite-hub/queue";
|
|
1111
|
+
const cloudflareQueueWorkerMarker = "vitehub-queue-worker";
|
|
1112
|
+
const cloudflareQueueOutputState = ".vitehub/queue/cloudflare-output.json";
|
|
1113
|
+
const vercelQueueOutputState = ".vitehub/queue/vercel-output.json";
|
|
1114
|
+
const vercelQueueFunctionMarker = ".vitehub-queue-output.json";
|
|
1115
|
+
const productName = "queue";
|
|
1116
|
+
const generatedRegistryFileName = "registry.mjs";
|
|
1117
|
+
const generatedQueueNitroPlugin = ".vitehub/nitro/queue/plugin.ts";
|
|
1118
|
+
const generatedQueueNitroMiddleware = ".vitehub/nitro/queue/middleware.ts";
|
|
1119
|
+
const packageDir = computePackageDir(import.meta.url);
|
|
1120
|
+
const packageRequire = createRequire(resolve(packageDir, "package.json"));
|
|
1121
|
+
const resolvePackageDependency = (specifier) => packageRequire.resolve(specifier);
|
|
1122
|
+
const resolveRuntimeModule = (modulePath) => resolveRuntimeModule$1(packageDir, modulePath);
|
|
1123
|
+
const providerEntrySpecs = [{
|
|
1124
|
+
name: "cloudflare",
|
|
1125
|
+
entryFile: "cloudflare-worker.mjs",
|
|
1126
|
+
runtimeModule: "runtime/cloudflare-vite",
|
|
1127
|
+
factory: "createQueueCloudflareWorker",
|
|
1128
|
+
hosting: "cloudflare"
|
|
1129
|
+
}, {
|
|
1130
|
+
name: "vercel",
|
|
1131
|
+
entryFile: "vercel-server.mjs",
|
|
1132
|
+
runtimeModule: "runtime/vercel-vite",
|
|
1133
|
+
factory: "createQueueVercelServer",
|
|
1134
|
+
hosting: "vercel"
|
|
1135
|
+
}];
|
|
1136
|
+
function isVercelQueueEnabled(queueConfig) {
|
|
1137
|
+
return queueConfig !== false && queueConfig.provider === "vercel";
|
|
1138
|
+
}
|
|
1139
|
+
function resolveOutputQueueConfig(queue, hosting) {
|
|
1140
|
+
if (typeof queue === "undefined") return false;
|
|
1141
|
+
return normalizeQueueOptions(queue, { hosting }) || false;
|
|
1142
|
+
}
|
|
1143
|
+
function shouldWriteProviderEntry(spec, queue) {
|
|
1144
|
+
const queueConfig = resolveOutputQueueConfig(queue, spec.hosting);
|
|
1145
|
+
return queueConfig === false ? spec.name === "vercel" : queueConfig.provider === spec.name;
|
|
1146
|
+
}
|
|
1147
|
+
function shouldCreateVercelOutput(queue) {
|
|
1148
|
+
const queueConfig = resolveOutputQueueConfig(queue, "vercel");
|
|
1149
|
+
return queueConfig === false || queueConfig.provider === "vercel";
|
|
1150
|
+
}
|
|
1151
|
+
function renderProviderEntry(spec, entryFile, registryFile, userAppEntry, queueConfig, preloadVercelQueue = false, queueDefinitions) {
|
|
1152
|
+
const vercelRuntime = spec.name === "vercel" && queueConfig !== false && queueConfig.provider === "vercel";
|
|
1153
|
+
const imports = [`import { ${spec.factory} } from ${JSON.stringify(createImportPath(entryFile, resolveRuntimeModule(spec.runtimeModule)))}`, `import queueRegistry from ${JSON.stringify(`./${generatedRegistryFileName}`)}`];
|
|
1154
|
+
if (vercelRuntime) imports.push(`import { createVercelQueueRuntimeClient } from ${JSON.stringify(createImportPath(entryFile, resolveRuntimeModule("internal/runtime/vercel-client")))}`);
|
|
1155
|
+
if (preloadVercelQueue) imports.unshift(`import * as __vitehubVercelQueue from ${JSON.stringify(createImportPath(entryFile, resolvePackageDependency("@vercel/queue")))}`);
|
|
1156
|
+
if (userAppEntry) imports.push(`import queueApp from ${JSON.stringify(createImportPath(entryFile, userAppEntry))}`);
|
|
1157
|
+
return [
|
|
1158
|
+
...imports,
|
|
1159
|
+
preloadVercelQueue ? "globalThis.__vitehubVercelQueue = __vitehubVercelQueue" : "",
|
|
1160
|
+
"",
|
|
1161
|
+
`const queueConfig = ${JSON.stringify(queueConfig, null, 2)}`,
|
|
1162
|
+
queueDefinitions ? `const queueDefinitions = ${JSON.stringify(queueDefinitions, null, 2)}` : "",
|
|
1163
|
+
"",
|
|
1164
|
+
`export default ${spec.factory}({`,
|
|
1165
|
+
userAppEntry ? " app: queueApp," : "",
|
|
1166
|
+
vercelRuntime ? " createClient: createVercelQueueRuntimeClient," : "",
|
|
1167
|
+
queueDefinitions ? " definitions: queueDefinitions," : "",
|
|
1168
|
+
" queue: queueConfig,",
|
|
1169
|
+
" registry: queueRegistry,",
|
|
1170
|
+
"})",
|
|
1171
|
+
""
|
|
1172
|
+
].filter(Boolean).join("\n");
|
|
1173
|
+
}
|
|
1174
|
+
async function writeProviderEntries(rootDir, queue, definitions = discoverQueueDefinitions({ rootDir })) {
|
|
1175
|
+
const generatedDir = ensureGeneratedDir(rootDir, productName);
|
|
1176
|
+
await mkdir(generatedDir, { recursive: true });
|
|
1177
|
+
const registryFile = resolve(generatedDir, generatedRegistryFileName);
|
|
1178
|
+
const userAppEntry = resolveUserAppEntry(rootDir);
|
|
1179
|
+
await writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions), "utf8");
|
|
1180
|
+
const entryFiles = {
|
|
1181
|
+
cloudflare: "",
|
|
1182
|
+
vercel: ""
|
|
1183
|
+
};
|
|
1184
|
+
for (const spec of providerEntrySpecs) {
|
|
1185
|
+
if (!shouldWriteProviderEntry(spec, queue)) continue;
|
|
1186
|
+
const entryFile = resolve(generatedDir, spec.entryFile);
|
|
1187
|
+
const queueConfig = resolveOutputQueueConfig(queue, spec.hosting);
|
|
1188
|
+
await writeFile(entryFile, renderProviderEntry(spec, entryFile, registryFile, userAppEntry, queueConfig, spec.name === "vercel" && isVercelQueueEnabled(queueConfig), spec.name === "cloudflare" ? createCloudflareQueueDefinitionNames(definitions, queueConfig !== false && queueConfig.provider === "cloudflare" ? queueConfig.namePrefix : void 0) : void 0), "utf8");
|
|
1189
|
+
entryFiles[spec.name] = entryFile;
|
|
1190
|
+
}
|
|
1191
|
+
return {
|
|
1192
|
+
cloudflareWorkerFile: entryFiles.cloudflare,
|
|
1193
|
+
definitions,
|
|
1194
|
+
generatedDir,
|
|
1195
|
+
registryFile,
|
|
1196
|
+
vercelServerFile: entryFiles.vercel
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
function createCloudflareQueueDefinitionNames(definitions, namePrefix = "") {
|
|
1200
|
+
const names = /* @__PURE__ */ new Map();
|
|
1201
|
+
for (const definition of definitions) {
|
|
1202
|
+
const physicalName = getCloudflareQueueName(definition.name, namePrefix);
|
|
1203
|
+
const existing = names.get(physicalName);
|
|
1204
|
+
if (existing) throw new Error(`Queue names ${JSON.stringify(existing.name)} and ${JSON.stringify(definition.name)} collide after Cloudflare resource name derivation:\n - ${existing.handler}\n - ${definition.handler}\nResolved Queue name: ${physicalName}`);
|
|
1205
|
+
names.set(physicalName, definition);
|
|
1206
|
+
}
|
|
1207
|
+
return Object.fromEntries([...names].map(([physicalName, definition]) => [physicalName, definition.name]));
|
|
1208
|
+
}
|
|
1209
|
+
function createCloudflareQueueBindings(definitions, namePrefix = "") {
|
|
1210
|
+
if (!definitions.length) return;
|
|
1211
|
+
const names = createCloudflareQueueDefinitionNames(definitions, namePrefix);
|
|
1212
|
+
return {
|
|
1213
|
+
consumers: Object.keys(names).map((queue) => ({ queue })),
|
|
1214
|
+
producers: definitions.map((definition) => ({
|
|
1215
|
+
binding: getCloudflareQueueBindingName(definition.name),
|
|
1216
|
+
queue: getCloudflareQueueName(definition.name, namePrefix)
|
|
1217
|
+
}))
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
function renderNitroPlugin(pluginFile, registryFile, queueConfig, cloudflareQueues, queueDefinitions) {
|
|
1221
|
+
const cloudflareRuntime = queueConfig !== false && queueConfig.provider === "cloudflare";
|
|
1222
|
+
const vercelRuntime = queueConfig !== false && queueConfig.provider === "vercel";
|
|
1223
|
+
const cloudflare = cloudflareQueues && cloudflareRuntime;
|
|
1224
|
+
const runtimeClientFactory = cloudflareRuntime ? "createCloudflareQueueRuntimeClient" : vercelRuntime ? "createVercelQueueRuntimeClient" : void 0;
|
|
1225
|
+
return [
|
|
1226
|
+
"import { definePlugin } from 'nitro'",
|
|
1227
|
+
...vercelRuntime ? [`import * as __vitehubVercelQueue from ${JSON.stringify(createImportPath(pluginFile, resolvePackageDependency("@vercel/queue")))}`] : [],
|
|
1228
|
+
...cloudflareRuntime ? ["import { env as vitehubEnv, waitUntil as vitehubWaitUntil } from 'cloudflare:workers'"] : [],
|
|
1229
|
+
...cloudflare ? [`import { createQueueCloudflareWorker } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("runtime/cloudflare-vite")))}`] : [],
|
|
1230
|
+
...cloudflareRuntime ? [`import { createCloudflareQueueRuntimeClient } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/cloudflare-client")))}`] : [],
|
|
1231
|
+
...vercelRuntime ? [`import { createVercelQueueRuntimeClient } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("internal/runtime/vercel-client")))}`] : [],
|
|
1232
|
+
`import { setQueueRuntimeConfig, setQueueRuntimeEventDefaults, setQueueRuntimeRegistry } from ${JSON.stringify(createImportPath(pluginFile, resolveRuntimeModule("runtime/state")))}`,
|
|
1233
|
+
`import queueRegistry from ${JSON.stringify(createImportPath(pluginFile, registryFile))}`,
|
|
1234
|
+
"",
|
|
1235
|
+
...vercelRuntime ? ["globalThis.__vitehubVercelQueue = __vitehubVercelQueue", ""] : [],
|
|
1236
|
+
`const queueConfig = ${JSON.stringify(queueConfig, null, 2)}`,
|
|
1237
|
+
...cloudflare ? [`const queueDefinitions = ${JSON.stringify(queueDefinitions, null, 2)}`, "const queueWorker = createQueueCloudflareWorker({ definitions: queueDefinitions, queue: queueConfig, registry: queueRegistry })"] : [],
|
|
1238
|
+
"",
|
|
1239
|
+
`export default definePlugin((${cloudflare ? "nitro" : ""}) => {`,
|
|
1240
|
+
` setQueueRuntimeConfig(queueConfig${runtimeClientFactory ? `, ${runtimeClientFactory}` : ""})`,
|
|
1241
|
+
" setQueueRuntimeRegistry(queueRegistry)",
|
|
1242
|
+
...cloudflareRuntime ? [" setQueueRuntimeEventDefaults({ env: vitehubEnv, waitUntil: vitehubWaitUntil })"] : [],
|
|
1243
|
+
...cloudflare ? [" nitro.hooks.hook('cloudflare:queue', ({ batch, context, env }) => queueWorker.queue(batch, env, context))"] : [],
|
|
1244
|
+
"})",
|
|
1245
|
+
""
|
|
1246
|
+
].join("\n");
|
|
1247
|
+
}
|
|
1248
|
+
function renderNitroMiddleware(middlewareFile, queueConfig, hasDefinitions) {
|
|
1249
|
+
const cloudflare = queueConfig !== false && queueConfig.provider === "cloudflare";
|
|
1250
|
+
const vercel = hasDefinitions && queueConfig !== false && queueConfig.provider === "vercel";
|
|
1251
|
+
return [
|
|
1252
|
+
"import { defineMiddleware } from 'nitro'",
|
|
1253
|
+
...vercel ? [`import { waitUntil as vitehubWaitUntil } from ${JSON.stringify(createImportPath(middlewareFile, resolvePackageDependency("@vercel/functions")))}`] : [],
|
|
1254
|
+
...cloudflare ? ["import { env as vitehubEnv, waitUntil as vitehubWaitUntil } from 'cloudflare:workers'"] : [],
|
|
1255
|
+
`import { enterQueueRuntimeEvent } from ${JSON.stringify(createImportPath(middlewareFile, resolveRuntimeModule("runtime/state")))}`,
|
|
1256
|
+
"",
|
|
1257
|
+
"export default defineMiddleware((event) => {",
|
|
1258
|
+
...cloudflare ? [" const runtimeEvent = event as any"] : [],
|
|
1259
|
+
...vercel ? [" Object.assign(event, { waitUntil: vitehubWaitUntil })"] : [],
|
|
1260
|
+
...cloudflare ? [" Object.assign(event, { env: runtimeEvent.env ?? runtimeEvent.context?.cloudflare?.env ?? runtimeEvent.context?._platform?.cloudflare?.env ?? runtimeEvent.req?.runtime?.cloudflare?.env ?? runtimeEvent.node?.req?.runtime?.cloudflare?.env ?? vitehubEnv, waitUntil: vitehubWaitUntil })"] : [],
|
|
1261
|
+
" enterQueueRuntimeEvent(event)",
|
|
1262
|
+
"})",
|
|
1263
|
+
""
|
|
1264
|
+
].join("\n");
|
|
1265
|
+
}
|
|
1266
|
+
async function writeQueueNitroIntegration(rootDir, queue, hosting, cloudflareQueues = true, definitions = discoverQueueDefinitions({ rootDir })) {
|
|
1267
|
+
const generatedDir = ensureGeneratedDir(rootDir, productName);
|
|
1268
|
+
const registryFile = resolve(generatedDir, generatedRegistryFileName);
|
|
1269
|
+
const pluginFile = resolve(rootDir, generatedQueueNitroPlugin);
|
|
1270
|
+
const middlewareFile = resolve(rootDir, generatedQueueNitroMiddleware);
|
|
1271
|
+
const queueConfig = resolveOutputQueueConfig(typeof queue === "undefined" ? {} : queue, hosting);
|
|
1272
|
+
const queueDefinitions = cloudflareQueues && queueConfig !== false && queueConfig.provider === "cloudflare" ? createCloudflareQueueDefinitionNames(definitions, queueConfig.namePrefix) : {};
|
|
1273
|
+
await Promise.all([mkdir(dirname(pluginFile), { recursive: true }), mkdir(generatedDir, { recursive: true })]);
|
|
1274
|
+
await Promise.all([
|
|
1275
|
+
writeFile(registryFile, createRuntimeRegistryContents(registryFile, definitions), "utf8"),
|
|
1276
|
+
writeFile(pluginFile, renderNitroPlugin(pluginFile, registryFile, queueConfig, cloudflareQueues, queueDefinitions), "utf8"),
|
|
1277
|
+
writeFile(middlewareFile, renderNitroMiddleware(middlewareFile, queueConfig, definitions.length > 0), "utf8")
|
|
1278
|
+
]);
|
|
1279
|
+
}
|
|
1280
|
+
async function createCloudflareQueueConfig(options = {}) {
|
|
1281
|
+
const rootDir = resolve(process.cwd(), options.rootDir || ".");
|
|
1282
|
+
const queues = createCloudflareQueueBindings((await writeProviderEntries(rootDir, { provider: "cloudflare" })).definitions);
|
|
1283
|
+
return {
|
|
1284
|
+
assets: { run_worker_first: ["/api/*"] },
|
|
1285
|
+
compatibility_date: options.compatibilityDate || "2026-04-20",
|
|
1286
|
+
compatibility_flags: ["nodejs_compat"],
|
|
1287
|
+
main: toGeneratedPath(rootDir, productName, providerEntrySpecs[0].entryFile),
|
|
1288
|
+
observability: { enabled: true },
|
|
1289
|
+
...queues ? { queues } : {}
|
|
1290
|
+
};
|
|
1291
|
+
}
|
|
1292
|
+
function createProviderRuntimeAliases(providerOutput, provider, providerImportAliases = {}) {
|
|
1293
|
+
const blobRuntime = getProviderRuntimeModule(providerOutput, "blob", provider);
|
|
1294
|
+
return {
|
|
1295
|
+
...providerImportAliases,
|
|
1296
|
+
...blobRuntime ? { "@vite-hub/blob": blobRuntime } : {}
|
|
1297
|
+
};
|
|
1298
|
+
}
|
|
1299
|
+
async function copyVercelRuntimePackages(options) {
|
|
1300
|
+
const { copyVercelFunctionRuntimePackageDirectories } = await import("./vercel-runtime-package-copy-B8AEFWXT.js");
|
|
1301
|
+
await copyVercelFunctionRuntimePackageDirectories(options);
|
|
1302
|
+
}
|
|
1303
|
+
function createCloudflareOutput(artifacts, providerOutput, providerImportAliases, namePrefix = "") {
|
|
1304
|
+
const queues = createCloudflareQueueBindings(artifacts.definitions, namePrefix);
|
|
1305
|
+
const wranglerConfig = {
|
|
1306
|
+
compatibility_date: defaultCloudflareCompatibilityDate,
|
|
1307
|
+
compatibility_flags: ["nodejs_compat"],
|
|
1308
|
+
main: "index.js",
|
|
1309
|
+
observability: { enabled: true },
|
|
1310
|
+
...queues ? { queues } : {}
|
|
1311
|
+
};
|
|
1312
|
+
return {
|
|
1313
|
+
bundleEntry: artifacts.cloudflareWorkerFile,
|
|
1314
|
+
bundleOptions: {
|
|
1315
|
+
alias: createProviderRuntimeAliases(providerOutput, "cloudflare", providerImportAliases),
|
|
1316
|
+
banner: `// ${cloudflareQueueWorkerMarker}`,
|
|
1317
|
+
conditions: [
|
|
1318
|
+
"workerd",
|
|
1319
|
+
"worker",
|
|
1320
|
+
"browser",
|
|
1321
|
+
"default"
|
|
1322
|
+
],
|
|
1323
|
+
external: [
|
|
1324
|
+
"@vercel/queue",
|
|
1325
|
+
"cloudflare:workers",
|
|
1326
|
+
"node:async_hooks",
|
|
1327
|
+
"node:fs",
|
|
1328
|
+
"node:fs/promises",
|
|
1329
|
+
"node:path",
|
|
1330
|
+
"node:url"
|
|
1331
|
+
],
|
|
1332
|
+
format: "esm",
|
|
1333
|
+
platform: "neutral"
|
|
1334
|
+
},
|
|
1335
|
+
wranglerConfigKeys: ["queues"],
|
|
1336
|
+
wranglerConfig
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
function isLegacyCloudflareQueueWorker(contents, wrangler) {
|
|
1340
|
+
if (!contents.includes("createQueueCloudflareWorker({") || !contents.includes("getCloudflareQueueDefinitionName(batch.queue)") || !contents.includes("label: \"queue\"") || contents.includes("cloudflare:queue")) return false;
|
|
1341
|
+
if (!wrangler || typeof wrangler !== "object" || Array.isArray(wrangler)) return false;
|
|
1342
|
+
const config = wrangler;
|
|
1343
|
+
const observability = config.observability;
|
|
1344
|
+
return config.main === "index.js" && Array.isArray(config.compatibility_flags) && config.compatibility_flags.includes("nodejs_compat") && Boolean(observability) && typeof observability === "object" && !Array.isArray(observability) && observability.enabled === true;
|
|
1345
|
+
}
|
|
1346
|
+
async function createNitroCloudflareCleanup(rootDir, hasCurrentContribution) {
|
|
1347
|
+
const outputRoot = createDefaultCloudflareOutputRoot(rootDir);
|
|
1348
|
+
let ownsWorker = false;
|
|
1349
|
+
let ownsQueues = false;
|
|
1350
|
+
try {
|
|
1351
|
+
const contents = await readFile(resolve(outputRoot, "index.js"), "utf8");
|
|
1352
|
+
if (contents.includes(cloudflareQueueWorkerMarker)) ownsWorker = true;
|
|
1353
|
+
else ownsWorker = isLegacyCloudflareQueueWorker(contents, JSON.parse(await readFile(resolve(outputRoot, "wrangler.json"), "utf8")));
|
|
1354
|
+
} catch (error) {
|
|
1355
|
+
if (error.code !== "ENOENT") throw error;
|
|
1356
|
+
}
|
|
1357
|
+
try {
|
|
1358
|
+
const [state, wrangler] = await Promise.all([readFile(resolve(rootDir, cloudflareQueueOutputState), "utf8").then((value) => JSON.parse(value)), readFile(resolve(outputRoot, "wrangler.json"), "utf8").then((value) => JSON.parse(value))]);
|
|
1359
|
+
ownsQueues = JSON.stringify(state.queues) === JSON.stringify(wrangler.queues);
|
|
1360
|
+
await rm(resolve(rootDir, cloudflareQueueOutputState), { force: true });
|
|
1361
|
+
} catch (error) {
|
|
1362
|
+
if (error.code !== "ENOENT") throw error;
|
|
1363
|
+
}
|
|
1364
|
+
return {
|
|
1365
|
+
fileNames: ownsWorker ? ["index.js"] : [],
|
|
1366
|
+
outputRoot,
|
|
1367
|
+
wranglerConfigOwnership: { keys: [...ownsWorker ? [
|
|
1368
|
+
"compatibility_date",
|
|
1369
|
+
"compatibility_flags",
|
|
1370
|
+
"main",
|
|
1371
|
+
"observability"
|
|
1372
|
+
] : [], ...ownsWorker || ownsQueues && !hasCurrentContribution ? ["queues"] : []] }
|
|
1373
|
+
};
|
|
1374
|
+
}
|
|
1375
|
+
function sanitizeVercelConsumerName(functionPath) {
|
|
1376
|
+
let result = "";
|
|
1377
|
+
for (const char of functionPath) if (char === "_") result += "__";
|
|
1378
|
+
else if (char === "/") result += "_S";
|
|
1379
|
+
else if (char === ".") result += "_D";
|
|
1380
|
+
else if (/[A-Za-z0-9-]/.test(char)) result += char;
|
|
1381
|
+
else result += `_${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;
|
|
1382
|
+
return result;
|
|
1383
|
+
}
|
|
1384
|
+
function createVercelQueueWrapperContents(file, registryFile, name, queueConfig) {
|
|
1385
|
+
return [
|
|
1386
|
+
`import * as __vitehubVercelQueue from ${JSON.stringify(createImportPath(file, resolvePackageDependency("@vercel/queue")))}`,
|
|
1387
|
+
`import { H3 } from ${JSON.stringify(createImportPath(file, resolvePackageDependency("h3")))}`,
|
|
1388
|
+
`import { toNodeHandler } from ${JSON.stringify(createImportPath(file, resolvePackageDependency("h3/node")))}`,
|
|
1389
|
+
`import { createVercelQueueRuntimeClient } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("internal/runtime/vercel-client")))}`,
|
|
1390
|
+
`import { handleHostedVercelQueueCallback, hostedVercelWaitUntil } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("runtime/hosted")))}`,
|
|
1391
|
+
`import { loadQueueDefinition, runWithQueueRuntimeEvent, setQueueRuntimeConfig, setQueueRuntimeRegistry } from ${JSON.stringify(createImportPath(file, resolveRuntimeModule("runtime/state")))}`,
|
|
1392
|
+
`import queueRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
|
|
1393
|
+
"",
|
|
1394
|
+
"globalThis.__vitehubVercelQueue = __vitehubVercelQueue",
|
|
1395
|
+
"",
|
|
1396
|
+
`setQueueRuntimeConfig(${JSON.stringify(queueConfig, null, 2)}, createVercelQueueRuntimeClient)`,
|
|
1397
|
+
"setQueueRuntimeRegistry(queueRegistry)",
|
|
1398
|
+
"",
|
|
1399
|
+
"const app = new H3()",
|
|
1400
|
+
"app.use(async (event) => {",
|
|
1401
|
+
` const definition = await loadQueueDefinition(${JSON.stringify(name)})`,
|
|
1402
|
+
" if (!definition) {",
|
|
1403
|
+
" throw new Error('Missing queue definition.')",
|
|
1404
|
+
" }",
|
|
1405
|
+
` return await handleHostedVercelQueueCallback(event, ${JSON.stringify(name)}, definition)`,
|
|
1406
|
+
"})",
|
|
1407
|
+
"",
|
|
1408
|
+
"const handler = toNodeHandler(app)",
|
|
1409
|
+
"export default function queueHandler(req, res) {",
|
|
1410
|
+
" return runWithQueueRuntimeEvent({ req, res, waitUntil: hostedVercelWaitUntil }, () => handler(req, res))",
|
|
1411
|
+
"}",
|
|
1412
|
+
""
|
|
1413
|
+
].join("\n");
|
|
1414
|
+
}
|
|
1415
|
+
function createVercelOutput(artifacts, providerOutput, providerImportAliases, serverFunctionName) {
|
|
1416
|
+
return {
|
|
1417
|
+
bundleEntry: artifacts.vercelServerFile,
|
|
1418
|
+
bundleOptions: {
|
|
1419
|
+
alias: createProviderRuntimeAliases(providerOutput, "vercel", providerImportAliases),
|
|
1420
|
+
format: "esm",
|
|
1421
|
+
platform: "node"
|
|
1422
|
+
},
|
|
1423
|
+
...serverFunctionName ? { function: {
|
|
1424
|
+
kind: "isolated",
|
|
1425
|
+
name: serverFunctionName
|
|
1426
|
+
} } : {}
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
async function readVercelQueueOutputState(rootDir) {
|
|
1430
|
+
try {
|
|
1431
|
+
const state = JSON.parse(await readFile(resolve(rootDir, vercelQueueOutputState), "utf8"));
|
|
1432
|
+
return typeof state.serverFunctionName === "string" && /^[^/\\]+\.func$/.test(state.serverFunctionName) && typeof state.digest === "string" && /^[0-9a-f]{64}$/.test(state.digest) ? {
|
|
1433
|
+
digest: state.digest,
|
|
1434
|
+
serverFunctionName: state.serverFunctionName
|
|
1435
|
+
} : void 0;
|
|
1436
|
+
} catch (error) {
|
|
1437
|
+
if (error.code === "ENOENT") return void 0;
|
|
1438
|
+
throw error;
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
async function isVercelQueueFunctionOwned(rootDir, serverFunctionName, state) {
|
|
1442
|
+
try {
|
|
1443
|
+
const functionRoot = resolve(createDefaultVercelOutputRoot(rootDir), "functions", serverFunctionName);
|
|
1444
|
+
const digest = hash("sha256", await readFile(resolve(functionRoot, "index.mjs")), "hex");
|
|
1445
|
+
if (state?.serverFunctionName === serverFunctionName && state.digest === digest) return true;
|
|
1446
|
+
return JSON.parse(await readFile(resolve(functionRoot, vercelQueueFunctionMarker), "utf8")).digest === digest;
|
|
1447
|
+
} catch (error) {
|
|
1448
|
+
if (error.code === "ENOENT") return false;
|
|
1449
|
+
throw error;
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
async function writeVercelQueueFunctions(rootDir, queue, artifacts, providerOutput, providerImportAliases) {
|
|
1453
|
+
const outputRoot = createDefaultVercelOutputRoot(rootDir);
|
|
1454
|
+
const queueRoot = resolve(outputRoot, "functions", "api", "vitehub", "queues", "vercel");
|
|
1455
|
+
const queueConfig = resolveOutputQueueConfig(queue, "vercel");
|
|
1456
|
+
await rm(queueRoot, {
|
|
1457
|
+
force: true,
|
|
1458
|
+
recursive: true
|
|
1459
|
+
});
|
|
1460
|
+
if (!isVercelQueueEnabled(queueConfig)) return;
|
|
1461
|
+
const functionDirs = /* @__PURE__ */ new Map();
|
|
1462
|
+
for (const definition of artifacts.definitions) {
|
|
1463
|
+
const segments = definition.name.replace(/[^a-z0-9/_-]+/gi, "_").split("/");
|
|
1464
|
+
const functionDirKey = [...segments, `${segments.at(-1)}.func`].join("/");
|
|
1465
|
+
const existing = functionDirs.get(functionDirKey);
|
|
1466
|
+
if (existing) throw new Error(`Queue names "${existing.name}" and "${definition.name}" collide after Vercel output sanitization:\n - ${existing.handler}\n - ${definition.handler}\nResolved output path: ${functionDirKey}`);
|
|
1467
|
+
functionDirs.set(functionDirKey, definition);
|
|
1468
|
+
const functionDir = resolve(queueRoot, ...segments, `${segments.at(-1)}.func`);
|
|
1469
|
+
const functionFile = resolve(functionDir, "index.mjs");
|
|
1470
|
+
const wrapperFile = resolve(functionDir, "index.source.mjs");
|
|
1471
|
+
const functionPath = relative(resolve(outputRoot, "functions"), functionDir).replace(/\\/g, "/");
|
|
1472
|
+
const consumer = sanitizeVercelConsumerName(functionPath);
|
|
1473
|
+
await mkdir(functionDir, { recursive: true });
|
|
1474
|
+
await writeFile(wrapperFile, createVercelQueueWrapperContents(wrapperFile, artifacts.registryFile, definition.name, queueConfig), "utf8");
|
|
1475
|
+
await bundleEsmEntry(wrapperFile, functionFile, {
|
|
1476
|
+
alias: createProviderRuntimeAliases(providerOutput, "vercel", providerImportAliases),
|
|
1477
|
+
format: "esm",
|
|
1478
|
+
platform: "node",
|
|
1479
|
+
rootDir
|
|
1480
|
+
});
|
|
1481
|
+
await copyVercelRuntimePackages({
|
|
1482
|
+
outputRoot,
|
|
1483
|
+
packages: getVercelRuntimePackages(providerOutput, "blob"),
|
|
1484
|
+
rootDir,
|
|
1485
|
+
serverFunctionName: functionPath
|
|
1486
|
+
});
|
|
1487
|
+
await rm(wrapperFile, { force: true });
|
|
1488
|
+
await writeFile(resolve(functionDir, ".vc-config.json"), `${JSON.stringify(createNodeFunctionConfig({ experimentalTriggers: [{
|
|
1489
|
+
consumer,
|
|
1490
|
+
topic: getVercelQueueTopicName(definition.name),
|
|
1491
|
+
type: "queue/v2beta"
|
|
1492
|
+
}] }), null, 2)}\n`, "utf8");
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
async function generateProviderOutputs(options) {
|
|
1496
|
+
const artifacts = await writeProviderEntries(options.rootDir, options.queue, options.definitions);
|
|
1497
|
+
const cloudflareQueueConfig = resolveOutputQueueConfig(options.queue, "cloudflare");
|
|
1498
|
+
const usesCloudflare = cloudflareQueueConfig !== false && cloudflareQueueConfig.provider === "cloudflare";
|
|
1499
|
+
const cloudflareNamePrefix = cloudflareQueueConfig !== false && cloudflareQueueConfig.provider === "cloudflare" ? cloudflareQueueConfig.namePrefix : void 0;
|
|
1500
|
+
const createCloudflare = !options.cloudflareOwnedByNitro && usesCloudflare;
|
|
1501
|
+
const createVercel = shouldCreateVercelOutput(options.queue);
|
|
1502
|
+
const vercelFunctionName = options.serverFunctionName ?? "__server.func";
|
|
1503
|
+
if (!createCloudflare) await writeProviderDeploymentOutputs({
|
|
1504
|
+
clientOutDir: options.clientOutDir,
|
|
1505
|
+
cleanup: { cloudflare: options.cloudflareOwnedByNitro ? () => createNitroCloudflareCleanup(options.rootDir, usesCloudflare && artifacts.definitions.length > 0) : { wranglerConfigOwnership: { keys: ["queues"] } } },
|
|
1506
|
+
rootDir: options.rootDir
|
|
1507
|
+
});
|
|
1508
|
+
await writeProviderDeploymentOutputs({
|
|
1509
|
+
afterWrite: async () => {
|
|
1510
|
+
const previousVercelOutput = await readVercelQueueOutputState(options.rootDir);
|
|
1511
|
+
const vercelFunctionCandidates = new Set(["__server.func", "__queue.func"]);
|
|
1512
|
+
if (previousVercelOutput) vercelFunctionCandidates.add(previousVercelOutput.serverFunctionName);
|
|
1513
|
+
const ownedVercelFunctions = [];
|
|
1514
|
+
for (const serverFunctionName of vercelFunctionCandidates) if (await isVercelQueueFunctionOwned(options.rootDir, serverFunctionName, previousVercelOutput)) ownedVercelFunctions.push(serverFunctionName);
|
|
1515
|
+
await Promise.all(ownedVercelFunctions.filter((serverFunctionName) => !createVercel || serverFunctionName !== vercelFunctionName).map((serverFunctionName) => rm(resolve(createDefaultVercelOutputRoot(options.rootDir), "functions", serverFunctionName), {
|
|
1516
|
+
force: true,
|
|
1517
|
+
recursive: true
|
|
1518
|
+
})));
|
|
1519
|
+
if (createVercel) {
|
|
1520
|
+
const functionRoot = resolve(createDefaultVercelOutputRoot(options.rootDir), "functions", vercelFunctionName);
|
|
1521
|
+
await copyVercelRuntimePackages({
|
|
1522
|
+
packages: getVercelRuntimePackages(options.providerOutput, "blob"),
|
|
1523
|
+
rootDir: options.rootDir,
|
|
1524
|
+
serverFunctionName: vercelFunctionName
|
|
1525
|
+
});
|
|
1526
|
+
const digest = hash("sha256", await readFile(resolve(functionRoot, "index.mjs")), "hex");
|
|
1527
|
+
await writeFile(resolve(functionRoot, vercelQueueFunctionMarker), `${JSON.stringify({ digest }, null, 2)}\n`, "utf8");
|
|
1528
|
+
await mkdir(dirname(resolve(options.rootDir, vercelQueueOutputState)), { recursive: true });
|
|
1529
|
+
await writeFile(resolve(options.rootDir, vercelQueueOutputState), `${JSON.stringify({
|
|
1530
|
+
digest,
|
|
1531
|
+
serverFunctionName: vercelFunctionName
|
|
1532
|
+
}, null, 2)}\n`, "utf8");
|
|
1533
|
+
} else await rm(resolve(options.rootDir, vercelQueueOutputState), { force: true });
|
|
1534
|
+
},
|
|
1535
|
+
clientOutDir: options.clientOutDir,
|
|
1536
|
+
cloudflare: createCloudflare ? createCloudflareOutput(artifacts, options.providerOutput, options.providerImportAliases, cloudflareNamePrefix) : void 0,
|
|
1537
|
+
rootDir: options.rootDir,
|
|
1538
|
+
vercel: createVercel ? createVercelOutput(artifacts, options.providerOutput, options.providerImportAliases, options.serverFunctionName) : void 0
|
|
1539
|
+
});
|
|
1540
|
+
if (createCloudflare) {
|
|
1541
|
+
const queues = createCloudflareQueueBindings(artifacts.definitions, cloudflareNamePrefix);
|
|
1542
|
+
await mkdir(dirname(resolve(options.rootDir, cloudflareQueueOutputState)), { recursive: true });
|
|
1543
|
+
await writeFile(resolve(options.rootDir, cloudflareQueueOutputState), `${JSON.stringify({ queues }, null, 2)}\n`, "utf8");
|
|
1544
|
+
} else await rm(resolve(options.rootDir, cloudflareQueueOutputState), { force: true });
|
|
1545
|
+
await writeVercelQueueFunctions(options.rootDir, options.queue, artifacts, options.providerOutput, options.providerImportAliases);
|
|
1546
|
+
return artifacts;
|
|
1547
|
+
}
|
|
1548
|
+
//#endregion
|
|
1549
|
+
//#region ../internal/src/provision.ts
|
|
1550
|
+
function resolveCloudflareProvisionConfig(env) {
|
|
1551
|
+
const accountId = trimmedEnv(env.CLOUDFLARE_ACCOUNT_ID);
|
|
1552
|
+
const token = trimmedEnv(env.CLOUDFLARE_API_TOKEN);
|
|
1553
|
+
if (!accountId || !token) return;
|
|
1554
|
+
return {
|
|
1555
|
+
accountId,
|
|
1556
|
+
token
|
|
1557
|
+
};
|
|
1558
|
+
}
|
|
1559
|
+
function createJsonClient(baseURL, headers, fetchImpl, baseQuery) {
|
|
1560
|
+
return async function request(path, options = {}) {
|
|
1561
|
+
const url = new URL(`${baseURL}${path}`);
|
|
1562
|
+
for (const [key, value] of Object.entries({
|
|
1563
|
+
...baseQuery,
|
|
1564
|
+
...options.query
|
|
1565
|
+
})) url.searchParams.set(key, value);
|
|
1566
|
+
const init = {
|
|
1567
|
+
method: options.method ?? "GET",
|
|
1568
|
+
headers: { ...headers }
|
|
1569
|
+
};
|
|
1570
|
+
if (typeof options.body !== "undefined") {
|
|
1571
|
+
init.headers["content-type"] = "application/json";
|
|
1572
|
+
init.body = JSON.stringify(options.body);
|
|
1573
|
+
}
|
|
1574
|
+
const response = await fetchImpl(url, init);
|
|
1575
|
+
if (!response.ok) throw new Error(`Provision request failed: ${options.method ?? "GET"} ${path} (${response.status}).`);
|
|
1576
|
+
return await response.json();
|
|
1577
|
+
};
|
|
1578
|
+
}
|
|
1579
|
+
function createCloudflareProvisionClient(config, fetchImpl = globalThis.fetch) {
|
|
1580
|
+
const client = createJsonClient(`https://api.cloudflare.com/client/v4/accounts/${config.accountId}`, { authorization: `Bearer ${config.token}` }, fetchImpl);
|
|
1581
|
+
return (path, options) => client(path, options);
|
|
1582
|
+
}
|
|
1583
|
+
function trimmedEnv(value) {
|
|
1584
|
+
const trimmed = value?.trim();
|
|
1585
|
+
return trimmed ? trimmed : void 0;
|
|
1586
|
+
}
|
|
1587
|
+
//#endregion
|
|
1588
|
+
//#region src/provision.ts
|
|
1589
|
+
function createQueueProvisionStep(resolveRootDir, resolveNamePrefix = () => void 0) {
|
|
1590
|
+
return {
|
|
1591
|
+
id: "queue:cloudflare-queues",
|
|
1592
|
+
provider: "cloudflare",
|
|
1593
|
+
async plan(context) {
|
|
1594
|
+
const config = resolveCloudflareProvisionConfig(context.env);
|
|
1595
|
+
if (!config) {
|
|
1596
|
+
context.logger.warn("queue: skipping Cloudflare queues, missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN.");
|
|
1597
|
+
return [];
|
|
1598
|
+
}
|
|
1599
|
+
const request = createCloudflareProvisionClient(config, context.fetch);
|
|
1600
|
+
const namePrefix = resolveNamePrefix();
|
|
1601
|
+
const names = discoverQueueDefinitions({ rootDir: resolveRootDir() }).map((definition) => getCloudflareQueueName(definition.name, namePrefix));
|
|
1602
|
+
if (!names.length) return [];
|
|
1603
|
+
const listed = await request("/queues");
|
|
1604
|
+
const existing = new Set((listed.result ?? []).map((queue) => queue.queue_name).filter((name) => Boolean(name)));
|
|
1605
|
+
return names.map((name) => ({
|
|
1606
|
+
kind: "cloudflare-queue",
|
|
1607
|
+
name,
|
|
1608
|
+
exists: existing.has(name),
|
|
1609
|
+
apply: async () => {
|
|
1610
|
+
if (!existing.has(name)) await request("/queues", {
|
|
1611
|
+
method: "POST",
|
|
1612
|
+
body: { queue_name: name }
|
|
1613
|
+
});
|
|
1614
|
+
return {};
|
|
1615
|
+
}
|
|
1616
|
+
}));
|
|
1617
|
+
}
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
//#endregion
|
|
1621
|
+
//#region src/vite.ts
|
|
1622
|
+
const mergeNoExternal = createNoExternalMerger(queuePackageName);
|
|
1623
|
+
async function createQueueNitroConfig(plugin, options) {
|
|
1624
|
+
const createNitroConfig = plugin.vitehub?.queue?.createNitroConfig;
|
|
1625
|
+
if (!createNitroConfig) throw new Error("The existing @vite-hub/queue/vite plugin does not expose Queue Nitro configuration.");
|
|
1626
|
+
return createNitroConfig(options);
|
|
1627
|
+
}
|
|
1628
|
+
function resolveStableQueueDefinitions(resolveDefinitions, snapshot, context) {
|
|
1629
|
+
const definitions = resolveDefinitions();
|
|
1630
|
+
if (JSON.stringify(definitions) !== JSON.stringify(snapshot)) throw new Error(`[vitehub] ${context} Queue Definitions changed after config resolution. Generate Queue Definition source files before Vite config resolves.`);
|
|
1631
|
+
return definitions;
|
|
1632
|
+
}
|
|
1633
|
+
function cloneNitroConfig(value) {
|
|
1634
|
+
return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
|
|
1635
|
+
}
|
|
1636
|
+
function mergeNitroExternal(value, addition) {
|
|
1637
|
+
if (typeof value === "undefined") return [addition];
|
|
1638
|
+
if (Array.isArray(value)) return value.includes(addition) ? [...value] : [...value, addition];
|
|
1639
|
+
if (typeof value === "string" || value instanceof RegExp) return [value, addition];
|
|
1640
|
+
if (typeof value === "function") return (source, importer, isResolved) => source === addition || Boolean(value(source, importer, isResolved));
|
|
1641
|
+
return value;
|
|
1642
|
+
}
|
|
1643
|
+
function resolveQueueHosting(queue, nitro) {
|
|
1644
|
+
return getHostingProvider(typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING) || queue !== false && queue?.provider || "vercel";
|
|
1645
|
+
}
|
|
1646
|
+
function resolveNitroHosting(nitro) {
|
|
1647
|
+
return getHostingProvider(typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING);
|
|
1648
|
+
}
|
|
1649
|
+
function supportsCloudflareQueues(nitro) {
|
|
1650
|
+
return !(typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOSTING || "").replaceAll("-", "_").includes("cloudflare_pages");
|
|
1651
|
+
}
|
|
1652
|
+
function mergeNitroConfig(config, value, queue, root, definitions = discoverQueueDefinitions({ rootDir: root })) {
|
|
1653
|
+
const nitro = cloneNitroConfig(value);
|
|
1654
|
+
const nitroHosting = resolveNitroHosting(nitro);
|
|
1655
|
+
const providerMismatch = queue !== false && queue?.provider && nitroHosting && queue.provider !== nitroHosting;
|
|
1656
|
+
const runtimeEnabled = queue !== false && !providerMismatch;
|
|
1657
|
+
const plugins = Array.isArray(nitro.plugins) ? nitro.plugins.filter((plugin) => runtimeEnabled || plugin !== ".vitehub/nitro/queue/plugin.ts") : [];
|
|
1658
|
+
const handlers = Array.isArray(nitro.handlers) ? nitro.handlers.filter((handler) => handler?.handler !== generatedQueueNitroMiddleware) : [];
|
|
1659
|
+
if (!runtimeEnabled) {
|
|
1660
|
+
registerCloudflareProviderOutput(config, "queue", {});
|
|
1661
|
+
return composeNitroCloudflareProviderOutput(config, {
|
|
1662
|
+
...nitro,
|
|
1663
|
+
handlers,
|
|
1664
|
+
plugins
|
|
1665
|
+
});
|
|
1666
|
+
}
|
|
1667
|
+
if (!plugins.includes(".vitehub/nitro/queue/plugin.ts")) plugins.unshift(generatedQueueNitroPlugin);
|
|
1668
|
+
handlers.unshift({
|
|
1669
|
+
handler: generatedQueueNitroMiddleware,
|
|
1670
|
+
middleware: true,
|
|
1671
|
+
route: "/**"
|
|
1672
|
+
});
|
|
1673
|
+
const queueHosting = resolveQueueHosting(queue, nitro);
|
|
1674
|
+
if (queueHosting !== "cloudflare") {
|
|
1675
|
+
registerCloudflareProviderOutput(config, "queue", {});
|
|
1676
|
+
return composeNitroCloudflareProviderOutput(config, {
|
|
1677
|
+
...nitro,
|
|
1678
|
+
handlers,
|
|
1679
|
+
plugins
|
|
1680
|
+
});
|
|
1681
|
+
}
|
|
1682
|
+
const cloudflare = cloneNitroConfig(nitro.cloudflare);
|
|
1683
|
+
const wrangler = cloneNitroConfig(cloudflare.wrangler);
|
|
1684
|
+
const compatibilityFlags = Array.isArray(wrangler.compatibility_flags) ? [...wrangler.compatibility_flags] : [];
|
|
1685
|
+
if (!compatibilityFlags.includes("nodejs_compat")) compatibilityFlags.push("nodejs_compat");
|
|
1686
|
+
const cloudflareQueues = supportsCloudflareQueues(nitro);
|
|
1687
|
+
const rollupConfig = cloneNitroConfig(nitro.rollupConfig);
|
|
1688
|
+
const resolvedQueue = normalizeQueueOptions(queue, { hosting: queueHosting });
|
|
1689
|
+
const generated = createCloudflareQueueBindings(definitions, resolvedQueue?.provider === "cloudflare" ? resolvedQueue.namePrefix : void 0);
|
|
1690
|
+
const baseNitro = {
|
|
1691
|
+
...nitro,
|
|
1692
|
+
...cloudflareQueues ? { rollupConfig: {
|
|
1693
|
+
...rollupConfig,
|
|
1694
|
+
external: mergeNitroExternal(rollupConfig.external, "cloudflare:workers")
|
|
1695
|
+
} } : {},
|
|
1696
|
+
cloudflare: {
|
|
1697
|
+
...cloudflare,
|
|
1698
|
+
wrangler: {
|
|
1699
|
+
...wrangler,
|
|
1700
|
+
compatibility_flags: compatibilityFlags
|
|
1701
|
+
}
|
|
1702
|
+
},
|
|
1703
|
+
handlers,
|
|
1704
|
+
plugins
|
|
1705
|
+
};
|
|
1706
|
+
if (!generated) {
|
|
1707
|
+
registerCloudflareProviderOutput(config, "queue", {});
|
|
1708
|
+
return composeNitroCloudflareProviderOutput(config, baseNitro);
|
|
1709
|
+
}
|
|
1710
|
+
const binding = resolvedQueue?.provider === "cloudflare" && typeof resolvedQueue.binding === "string" ? resolvedQueue.binding : void 0;
|
|
1711
|
+
if (binding && generated.producers.length > 1) throw new Error("A custom Cloudflare queue binding can only be used with one Queue Definition.");
|
|
1712
|
+
const generatedProducers = binding ? generated.producers.map((producer) => ({
|
|
1713
|
+
...producer,
|
|
1714
|
+
binding
|
|
1715
|
+
})) : generated.producers;
|
|
1716
|
+
registerCloudflareProviderOutput(config, "queue", { queues: {
|
|
1717
|
+
...cloudflareQueues ? { consumers: generated.consumers } : {},
|
|
1718
|
+
producers: generatedProducers
|
|
1719
|
+
} });
|
|
1720
|
+
return composeNitroCloudflareProviderOutput(config, baseNitro);
|
|
1721
|
+
}
|
|
1722
|
+
function hubQueue(options) {
|
|
1723
|
+
const internalOptions = options;
|
|
1724
|
+
let resolved;
|
|
1725
|
+
let queue = options;
|
|
1726
|
+
let hosting = "vercel";
|
|
1727
|
+
let cloudflareQueues = true;
|
|
1728
|
+
let configuredDefinitions = [];
|
|
1729
|
+
let nitroOwnsCloudflareWorker = false;
|
|
1730
|
+
let nitroQueue = queue;
|
|
1731
|
+
let nuxtConfiguredDefinitions;
|
|
1732
|
+
let nuxtProjectRoot;
|
|
1733
|
+
let resolveNuxtDefinitions;
|
|
1734
|
+
let nuxtServerQueueDirs = [];
|
|
1735
|
+
let nuxtOwnsCloudflareWorker = false;
|
|
1736
|
+
let providerOutput;
|
|
1737
|
+
let validatesNitroDefinitions = false;
|
|
1738
|
+
return {
|
|
1739
|
+
name: "@vite-hub/queue/vite",
|
|
1740
|
+
vitehub: {
|
|
1741
|
+
cli: async () => {
|
|
1742
|
+
return {
|
|
1743
|
+
namespaces: [],
|
|
1744
|
+
provision: [createQueueProvisionStep(() => resolved?.root ?? process.cwd(), () => {
|
|
1745
|
+
const resolvedQueue = normalizeQueueOptions(queue, { hosting: "cloudflare" });
|
|
1746
|
+
return resolvedQueue?.provider === "cloudflare" ? resolvedQueue.namePrefix : void 0;
|
|
1747
|
+
})]
|
|
1748
|
+
};
|
|
1749
|
+
},
|
|
1750
|
+
queue: { async createNitroConfig({ nitro, projectRoot, root, serverDirs }) {
|
|
1751
|
+
const config = { nitro };
|
|
1752
|
+
nuxtProjectRoot = projectRoot;
|
|
1753
|
+
nuxtServerQueueDirs = [...new Set(serverDirs || [resolve$1(projectRoot, "server"), resolve$1(root, "server")])].map((dir) => `${resolve$1(dir, "queues").replace(/\\/g, "/")}/`);
|
|
1754
|
+
resolveNuxtDefinitions = () => discoverQueueDefinitions({
|
|
1755
|
+
rootDir: root,
|
|
1756
|
+
serverDirs,
|
|
1757
|
+
serverRootDirs: [projectRoot, root]
|
|
1758
|
+
});
|
|
1759
|
+
const definitions = resolveNuxtDefinitions();
|
|
1760
|
+
nuxtConfiguredDefinitions = definitions;
|
|
1761
|
+
const configuredNitro = mergeNitroConfig(config, nitro, queue, projectRoot, definitions);
|
|
1762
|
+
hosting = resolveQueueHosting(queue, configuredNitro);
|
|
1763
|
+
const nitroHosting = resolveNitroHosting(configuredNitro);
|
|
1764
|
+
nitroQueue = queue !== false && queue?.provider && nitroHosting && queue.provider !== nitroHosting ? false : queue;
|
|
1765
|
+
cloudflareQueues = supportsCloudflareQueues(configuredNitro);
|
|
1766
|
+
nuxtOwnsCloudflareWorker = nitroQueue !== false && nitroHosting === "cloudflare" && cloudflareQueues;
|
|
1767
|
+
await writeQueueNitroIntegration(projectRoot, nitroQueue, hosting, cloudflareQueues, definitions);
|
|
1768
|
+
return configuredNitro;
|
|
1769
|
+
} }
|
|
1770
|
+
},
|
|
1771
|
+
config(config) {
|
|
1772
|
+
queue = config.queue ?? queue;
|
|
1773
|
+
const nitro = config.nitro;
|
|
1774
|
+
config.nitro = mergeNitroConfig(config, nitro, queue, config.root || process.cwd());
|
|
1775
|
+
},
|
|
1776
|
+
async configResolved(config) {
|
|
1777
|
+
resolved = config;
|
|
1778
|
+
queue = config.queue ?? queue;
|
|
1779
|
+
const configuredNitro = config.nitro;
|
|
1780
|
+
const configuredNitroConfig = cloneNitroConfig(configuredNitro);
|
|
1781
|
+
nitroOwnsCloudflareWorker = hasNitroVitePlugin(config) && resolveNitroHosting(configuredNitroConfig) === "cloudflare" && supportsCloudflareQueues(configuredNitroConfig);
|
|
1782
|
+
configuredDefinitions = discoverQueueDefinitions({ rootDir: config.root });
|
|
1783
|
+
const nitro = mergeNitroConfig(config, configuredNitro, queue, config.root, configuredDefinitions);
|
|
1784
|
+
config.nitro = nitro;
|
|
1785
|
+
providerOutput = useComposedProviderOutput(config);
|
|
1786
|
+
hosting = resolveQueueHosting(queue, nitro);
|
|
1787
|
+
cloudflareQueues = supportsCloudflareQueues(nitro);
|
|
1788
|
+
const nitroHosting = resolveNitroHosting(nitro);
|
|
1789
|
+
nitroQueue = queue !== false && queue?.provider && nitroHosting && queue.provider !== nitroHosting ? false : queue;
|
|
1790
|
+
validatesNitroDefinitions = hasNitroVitePlugin(config) && nitroQueue !== false;
|
|
1791
|
+
await writeQueueNitroIntegration(config.root, nitroQueue, hosting, cloudflareQueues, configuredDefinitions);
|
|
1792
|
+
},
|
|
1793
|
+
configEnvironment(name, config) {
|
|
1794
|
+
if (!isServerEnvironment(name, config)) return;
|
|
1795
|
+
return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
|
|
1796
|
+
},
|
|
1797
|
+
async handleHotUpdate(context) {
|
|
1798
|
+
const file = context.file.replace(/\\/g, "/");
|
|
1799
|
+
const isDirectoryDefinition = /\.(?:c|m)?[jt]s$/i.test(file) && (/\/server\/queues\//.test(file) || nuxtServerQueueDirs.some((dir) => file.startsWith(dir)));
|
|
1800
|
+
if (!/\.queue\.(?:c|m)?[jt]s$/i.test(file) && !isDirectoryDefinition) return;
|
|
1801
|
+
resolved = context.server.config;
|
|
1802
|
+
await writeQueueNitroIntegration(nuxtProjectRoot || resolved.root, nitroQueue, hosting, cloudflareQueues, resolveNuxtDefinitions?.());
|
|
1803
|
+
},
|
|
1804
|
+
async closeBundle() {
|
|
1805
|
+
if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
|
|
1806
|
+
let definitions;
|
|
1807
|
+
if (resolveNuxtDefinitions && nuxtConfiguredDefinitions) definitions = resolveStableQueueDefinitions(resolveNuxtDefinitions, nuxtConfiguredDefinitions, "Nuxt");
|
|
1808
|
+
else if (validatesNitroDefinitions) definitions = resolveStableQueueDefinitions(() => discoverQueueDefinitions({ rootDir: resolved.root }), configuredDefinitions, "Nitro Cloudflare");
|
|
1809
|
+
await generateProviderOutputs({
|
|
1810
|
+
clientOutDir: resolved.build.outDir,
|
|
1811
|
+
cloudflareOwnedByNitro: nitroOwnsCloudflareWorker || nuxtOwnsCloudflareWorker,
|
|
1812
|
+
definitions,
|
|
1813
|
+
providerImportAliases: internalOptions?.providerImportAliases,
|
|
1814
|
+
providerOutput,
|
|
1815
|
+
queue: queue ?? (resolveNitroHosting(cloneNitroConfig(resolved.nitro)) ? { provider: hosting === "cloudflare" ? "cloudflare" : "vercel" } : void 0),
|
|
1816
|
+
rootDir: nuxtProjectRoot || resolved.root,
|
|
1817
|
+
serverFunctionName: resolveNitroVercelFunctionName(resolved, "queue")
|
|
1818
|
+
});
|
|
1819
|
+
}
|
|
1820
|
+
};
|
|
1821
|
+
}
|
|
1822
|
+
//#endregion
|
|
1823
|
+
export { createDefaultVercelOutputRoot as i, hubQueue as n, createCloudflareQueueConfig as r, createQueueNitroConfig as t };
|