@vite-hub/schedule 0.0.1 → 0.0.3
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 +73 -8
- package/dist/client-BMFCy0dX.js +233 -0
- package/dist/definition.d.ts +7 -0
- package/dist/definition.js +42 -0
- package/dist/discovery-BZlat3Kc.js +776 -0
- package/dist/due-Bbh4yIxq.js +59 -0
- package/dist/execute-ClFYvmp9.js +211 -0
- package/dist/index.d.ts +28 -23
- package/dist/index.js +7 -152
- package/dist/kv-BJ1I9IlJ.js +6 -0
- package/dist/kv-storage-DWinmLLy.js +30 -0
- package/dist/nuxt.d.ts +19 -0
- package/dist/nuxt.js +25 -0
- package/dist/runtime/driver.d.ts +26 -0
- package/dist/runtime/driver.js +334 -0
- package/dist/runtime/process.d.ts +11 -0
- package/dist/runtime/process.js +285 -0
- package/dist/runtime/state.d.ts +2 -2
- package/dist/runtime/state.js +1 -1
- package/dist/runtime/static.d.ts +27 -3
- package/dist/runtime/static.js +126 -3
- package/dist/runtime.d.ts +4 -3
- package/dist/runtime.js +3 -3
- package/dist/{state-DoONzfij.js → state-By7WU_ks.js} +55 -24
- package/dist/store-t-74rsM_.d.ts +48 -0
- package/dist/{types-DOjXDq0s.d.ts → types-Bcje4dLV.d.ts} +34 -9
- package/dist/vite-BX6_KiRw.js +1218 -0
- package/dist/vite.d.ts +35 -6
- package/dist/vite.js +2 -110
- package/dist/wait-until-CR-JjIOb.js +23 -0
- package/package.json +40 -39
- package/dist/client-BJ33CRLg.js +0 -401
- package/dist/discovery-Di9MD-SN.js +0 -574
- package/dist/module-C_j2ahfg.js +0 -1767
- package/dist/nitro.d.ts +0 -6
- package/dist/nitro.js +0 -2
- package/dist/store-CeeSsInC.d.ts +0 -63
|
@@ -0,0 +1,1218 @@
|
|
|
1
|
+
import { a as writeRuntimeRegistryFile, i as createRuntimeRegistryContents, n as findDefaultExportCall, o as createImportPath, r as readObjectProperty, s as ensureGeneratedDir, t as discoverScheduleDefinitions } from "./discovery-BZlat3Kc.js";
|
|
2
|
+
import { readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, isAbsolute, normalize, relative, resolve } from "node:path";
|
|
4
|
+
import { mkdir, readFile, readdir, rm, rmdir, stat, writeFile } from "node:fs/promises";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { build } from "esbuild";
|
|
7
|
+
import { isDeepStrictEqual } from "node:util";
|
|
8
|
+
//#region ../internal/src/build/user-entry.ts
|
|
9
|
+
function toSafeAppName(rootDir) {
|
|
10
|
+
return basename(rootDir).replace(/[^a-z0-9-]+/gi, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").toLowerCase();
|
|
11
|
+
}
|
|
12
|
+
function createDefaultCloudflareOutputRoot(rootDir) {
|
|
13
|
+
return resolve(rootDir, "dist", toSafeAppName(rootDir));
|
|
14
|
+
}
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region ../internal/src/build/vite.ts
|
|
17
|
+
const projectRootDirectoryMarkers = [
|
|
18
|
+
["server", "agents"],
|
|
19
|
+
["server", "browsers"],
|
|
20
|
+
["server", "schedules"],
|
|
21
|
+
["server", "templates"],
|
|
22
|
+
["server", "workspaces"]
|
|
23
|
+
];
|
|
24
|
+
const projectRootDefinitionFileMarkers = [
|
|
25
|
+
".ts",
|
|
26
|
+
".mts",
|
|
27
|
+
".cts",
|
|
28
|
+
".js",
|
|
29
|
+
".mjs",
|
|
30
|
+
".cjs"
|
|
31
|
+
].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
|
|
32
|
+
const projectRootFileMarkers = [["package.json"]];
|
|
33
|
+
function createNoExternalMerger(packageName) {
|
|
34
|
+
return (current) => {
|
|
35
|
+
if (current === true) return true;
|
|
36
|
+
if (!current) return [packageName];
|
|
37
|
+
const values = Array.isArray(current) ? current : [current];
|
|
38
|
+
return values.includes(packageName) ? values : [...values, packageName];
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function isServerEnvironment(name, config) {
|
|
42
|
+
return name === "ssr" || config.consumer === "server";
|
|
43
|
+
}
|
|
44
|
+
function shouldSkipViteProviderBuild(command, mode) {
|
|
45
|
+
return command === "serve" || mode === "e2e";
|
|
46
|
+
}
|
|
47
|
+
function resolveViteHubProjectRoot(root, options = {}) {
|
|
48
|
+
const resolvedRoot = resolve(root);
|
|
49
|
+
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
50
|
+
if (basename(resolvedRoot) === "app") {
|
|
51
|
+
const parent = dirname(resolvedRoot);
|
|
52
|
+
if (hasProjectRootDirectoryMarker(parent) || hasProjectRootDefinitionFileMarker(parent)) return parent;
|
|
53
|
+
}
|
|
54
|
+
let current = resolvedRoot;
|
|
55
|
+
while (true) {
|
|
56
|
+
if (hasProjectRootMarker(current)) return current;
|
|
57
|
+
const parent = dirname(current);
|
|
58
|
+
if (parent === current) return resolvedRoot;
|
|
59
|
+
current = parent;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function hasProjectRootDirectoryMarker(root) {
|
|
63
|
+
for (const marker of projectRootDirectoryMarkers) try {
|
|
64
|
+
if (statSync(resolve(root, ...marker)).isDirectory()) return true;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (error.code !== "ENOENT") throw error;
|
|
67
|
+
}
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
function hasProjectRootMarker(root) {
|
|
71
|
+
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
72
|
+
if (hasProjectRootDefinitionFileMarker(root)) return true;
|
|
73
|
+
for (const marker of projectRootFileMarkers) try {
|
|
74
|
+
if (statSync(resolve(root, ...marker)).isFile()) return true;
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (error.code !== "ENOENT") throw error;
|
|
77
|
+
}
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
function hasProjectRootDefinitionFileMarker(root) {
|
|
81
|
+
for (const marker of projectRootDefinitionFileMarkers) try {
|
|
82
|
+
if (statSync(resolve(root, ...marker)).isFile()) return true;
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (error.code !== "ENOENT") throw error;
|
|
85
|
+
}
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
//#region ../internal/src/build/esbuild.ts
|
|
90
|
+
const viteRawNamespace = "vitehub-vite-raw";
|
|
91
|
+
const viteMarkdownTemplateNamespace = "vitehub-markdown-template";
|
|
92
|
+
const markdownTemplateFileSuffix = ".template.md";
|
|
93
|
+
const markdownTemplateModuleQuery = "markdown-template";
|
|
94
|
+
const markdownTemplateRegistryId = "#vitehub/templates";
|
|
95
|
+
const markdownTemplateRegistryPath = ".vitehub/markdown-template/templates.mjs";
|
|
96
|
+
const skipMarkdownTemplateResolve = "vitehubSkipMarkdownTemplateResolve";
|
|
97
|
+
const markdownTemplateRuntimeSpecifier = "@vite-hub/markdown-template";
|
|
98
|
+
function resolveEsbuildAliases(aliases) {
|
|
99
|
+
if (!aliases) return;
|
|
100
|
+
return Object.fromEntries(Object.entries(aliases).filter(([specifier]) => !specifier.endsWith("/")));
|
|
101
|
+
}
|
|
102
|
+
function stripMarkdownCode(template) {
|
|
103
|
+
let fence;
|
|
104
|
+
let inList = false;
|
|
105
|
+
let previousLineBlank = true;
|
|
106
|
+
return template.split("\n").map((line) => {
|
|
107
|
+
const content = line.replace(/^(?: {0,3}> ?)+/, "");
|
|
108
|
+
if (!fence) {
|
|
109
|
+
const listIndented = inList && /^ {4}(?:`{3,}|~{3,})/.test(content);
|
|
110
|
+
const opening = (listIndented ? content.slice(4) : content).match(/^ {0,3}(`{3,}|~{3,})/);
|
|
111
|
+
if (!opening) {
|
|
112
|
+
if (/^ {0,3}(?:[-+*]|\d+[.)])\s+/.test(content)) inList = true;
|
|
113
|
+
else if (content.trim() && !/^ {2,}/.test(content)) inList = false;
|
|
114
|
+
const indentedCode = !inList && previousLineBlank && /^(?: {4}|\t)/.test(content) || inList && previousLineBlank && /^(?: {8}| {4}\t|\t{2})/.test(content);
|
|
115
|
+
previousLineBlank = content.trim() === "";
|
|
116
|
+
return indentedCode ? "" : line;
|
|
117
|
+
}
|
|
118
|
+
fence = {
|
|
119
|
+
marker: opening[1][0],
|
|
120
|
+
length: opening[1].length,
|
|
121
|
+
listIndented
|
|
122
|
+
};
|
|
123
|
+
previousLineBlank = false;
|
|
124
|
+
return "";
|
|
125
|
+
}
|
|
126
|
+
const closing = (fence.listIndented ? content.replace(/^ {4}/, "") : content).match(/^ {0,3}(`+|~+)\s*$/)?.[1];
|
|
127
|
+
if (closing?.[0] === fence.marker && closing.length >= fence.length) fence = void 0;
|
|
128
|
+
previousLineBlank = false;
|
|
129
|
+
return "";
|
|
130
|
+
}).join("\n");
|
|
131
|
+
}
|
|
132
|
+
function extractMarkdownTemplateImportSpecifiers(template) {
|
|
133
|
+
const visible = stripMarkdownCode(template).replace(/(`+)[\s\S]*?\1/g, "").replace(/(!?\[[^\]]*\])\([^)]*\)/g, "$1").replace(/^ {0,3}\[[^\]]+\]:\s*\S+/gm, "").replace(/<[^>]*>/g, "");
|
|
134
|
+
const specifiers = /* @__PURE__ */ new Set();
|
|
135
|
+
for (const match of visible.matchAll(/@(\.\.?\/[^\s<>{}[\]]+)/g)) {
|
|
136
|
+
const token = match[1];
|
|
137
|
+
const trailing = token.match(/[.,;:!?)]*$/)?.[0] || "";
|
|
138
|
+
specifiers.add(token.slice(0, token.length - trailing.length));
|
|
139
|
+
}
|
|
140
|
+
return [...specifiers];
|
|
141
|
+
}
|
|
142
|
+
function parseMarkdownTemplateRequest(id) {
|
|
143
|
+
const queryIndex = id.indexOf("?");
|
|
144
|
+
const path = id.split(/[?#]/, 1)[0];
|
|
145
|
+
if (queryIndex === -1) return path.endsWith(markdownTemplateFileSuffix) ? { path } : void 0;
|
|
146
|
+
const query = id.slice(queryIndex + 1).split("#", 1)[0];
|
|
147
|
+
if (!new URLSearchParams(query).has(markdownTemplateModuleQuery)) return;
|
|
148
|
+
return { path };
|
|
149
|
+
}
|
|
150
|
+
function renderMarkdownTemplateModule(template, sourceId, imports = {}) {
|
|
151
|
+
return [
|
|
152
|
+
`import { renderMarkdownTemplate as vitehubRenderMarkdownTemplate } from ${JSON.stringify(markdownTemplateRuntimeSpecifier)}`,
|
|
153
|
+
`const vitehubMarkdownTemplate = ${JSON.stringify(template)}`,
|
|
154
|
+
`const vitehubMarkdownTemplateSourceId = ${JSON.stringify(sourceId)}`,
|
|
155
|
+
`const vitehubMarkdownTemplateImports = ${JSON.stringify(imports)}`,
|
|
156
|
+
"export default function render(data = {}) {",
|
|
157
|
+
" return vitehubRenderMarkdownTemplate(vitehubMarkdownTemplate, { data, sourceId: vitehubMarkdownTemplateSourceId, resolveImport: (specifier, importer) => vitehubMarkdownTemplateImports[`${importer}\\0${specifier}`] })",
|
|
158
|
+
"}",
|
|
159
|
+
""
|
|
160
|
+
].join("\n");
|
|
161
|
+
}
|
|
162
|
+
function hasViteRawQuery(path) {
|
|
163
|
+
const queryIndex = path.indexOf("?");
|
|
164
|
+
return queryIndex !== -1 && /(?:^|&)raw(?:&|$)/.test(path.slice(queryIndex + 1));
|
|
165
|
+
}
|
|
166
|
+
async function resolveViteRawSpecifier(path, rootDir) {
|
|
167
|
+
if (path.startsWith("/@fs/")) return path.slice(5);
|
|
168
|
+
if (!rootDir || !path.startsWith("/")) return path;
|
|
169
|
+
const rootRelativePath = path.slice(1);
|
|
170
|
+
const publicPath = resolve(rootDir, "public", rootRelativePath);
|
|
171
|
+
try {
|
|
172
|
+
await stat(publicPath);
|
|
173
|
+
return publicPath;
|
|
174
|
+
} catch (error) {
|
|
175
|
+
if (error.code !== "ENOENT") throw error;
|
|
176
|
+
return resolve(rootDir, rootRelativePath);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function createViteRawPlugin(rootDir, frameworkRuntime) {
|
|
180
|
+
return {
|
|
181
|
+
name: "vitehub-vite-raw",
|
|
182
|
+
setup(build) {
|
|
183
|
+
build.onResolve({
|
|
184
|
+
filter: /^@vite-hub\/markdown-template$/,
|
|
185
|
+
namespace: viteMarkdownTemplateNamespace
|
|
186
|
+
}, async (args) => {
|
|
187
|
+
if (!frameworkRuntime) return { path: fileURLToPath(import.meta.resolve(markdownTemplateRuntimeSpecifier)) };
|
|
188
|
+
return build.resolve("vite-hub/_internal/markdown-template", {
|
|
189
|
+
importer: args.importer,
|
|
190
|
+
kind: args.kind,
|
|
191
|
+
resolveDir: args.resolveDir
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
build.onResolve({ filter: /\?|\.template\.md$/ }, async (args) => {
|
|
195
|
+
if (args.pluginData?.[skipMarkdownTemplateResolve]) return;
|
|
196
|
+
const markdownTemplate = parseMarkdownTemplateRequest(args.path);
|
|
197
|
+
const raw = hasViteRawQuery(args.path);
|
|
198
|
+
if (!markdownTemplate && !raw) return;
|
|
199
|
+
const specifier = await resolveViteRawSpecifier(markdownTemplate?.path ?? args.path.slice(0, args.path.indexOf("?")), rootDir);
|
|
200
|
+
const resolved = await build.resolve(specifier, {
|
|
201
|
+
importer: args.importer,
|
|
202
|
+
kind: args.kind,
|
|
203
|
+
namespace: args.namespace,
|
|
204
|
+
pluginData: markdownTemplate ? {
|
|
205
|
+
...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
|
|
206
|
+
[skipMarkdownTemplateResolve]: true
|
|
207
|
+
} : args.pluginData,
|
|
208
|
+
resolveDir: args.resolveDir,
|
|
209
|
+
with: args.with
|
|
210
|
+
});
|
|
211
|
+
if (resolved.errors.length) return {
|
|
212
|
+
errors: resolved.errors,
|
|
213
|
+
warnings: resolved.warnings
|
|
214
|
+
};
|
|
215
|
+
if (resolved.external) return {
|
|
216
|
+
external: true,
|
|
217
|
+
namespace: resolved.namespace,
|
|
218
|
+
path: resolved.path,
|
|
219
|
+
pluginData: resolved.pluginData,
|
|
220
|
+
sideEffects: resolved.sideEffects,
|
|
221
|
+
suffix: resolved.suffix,
|
|
222
|
+
warnings: resolved.warnings
|
|
223
|
+
};
|
|
224
|
+
if (resolved.namespace !== "file") return {
|
|
225
|
+
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.` }],
|
|
226
|
+
warnings: resolved.warnings
|
|
227
|
+
};
|
|
228
|
+
return {
|
|
229
|
+
namespace: markdownTemplate ? viteMarkdownTemplateNamespace : viteRawNamespace,
|
|
230
|
+
path: resolved.path,
|
|
231
|
+
pluginData: resolved.pluginData,
|
|
232
|
+
sideEffects: resolved.sideEffects,
|
|
233
|
+
suffix: resolved.suffix,
|
|
234
|
+
warnings: resolved.warnings
|
|
235
|
+
};
|
|
236
|
+
});
|
|
237
|
+
build.onLoad({
|
|
238
|
+
filter: /.*/,
|
|
239
|
+
namespace: viteRawNamespace
|
|
240
|
+
}, async (args) => ({
|
|
241
|
+
contents: await readFile(args.path),
|
|
242
|
+
loader: "text"
|
|
243
|
+
}));
|
|
244
|
+
build.onLoad({
|
|
245
|
+
filter: /.*/,
|
|
246
|
+
namespace: viteMarkdownTemplateNamespace
|
|
247
|
+
}, async (args) => ({
|
|
248
|
+
contents: await (async () => {
|
|
249
|
+
const template = await readFile(args.path, "utf8");
|
|
250
|
+
const imports = {};
|
|
251
|
+
const visited = new Set([args.path]);
|
|
252
|
+
const visit = async (source, importer) => {
|
|
253
|
+
for (const specifier of extractMarkdownTemplateImportSpecifiers(source)) {
|
|
254
|
+
const key = `${importer}\0${specifier}`;
|
|
255
|
+
if (imports[key]) continue;
|
|
256
|
+
const resolved = await build.resolve(specifier, {
|
|
257
|
+
importer,
|
|
258
|
+
kind: "import-statement",
|
|
259
|
+
pluginData: {
|
|
260
|
+
...args.pluginData && typeof args.pluginData === "object" ? args.pluginData : {},
|
|
261
|
+
[skipMarkdownTemplateResolve]: true
|
|
262
|
+
},
|
|
263
|
+
resolveDir: dirname(importer)
|
|
264
|
+
});
|
|
265
|
+
if (resolved.errors.length) return Promise.reject(new Error(resolved.errors.map((error) => error.text).join("\n")));
|
|
266
|
+
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.`);
|
|
267
|
+
const imported = {
|
|
268
|
+
id: resolved.path,
|
|
269
|
+
template: await readFile(resolved.path, "utf8")
|
|
270
|
+
};
|
|
271
|
+
imports[key] = imported;
|
|
272
|
+
if (!visited.has(imported.id)) {
|
|
273
|
+
visited.add(imported.id);
|
|
274
|
+
await visit(imported.template, imported.id);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
await visit(template, args.path);
|
|
279
|
+
return renderMarkdownTemplateModule(template, args.path, imports);
|
|
280
|
+
})(),
|
|
281
|
+
loader: "js",
|
|
282
|
+
resolveDir: dirname(args.path)
|
|
283
|
+
}));
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
async function bundleEsmEntry(entryFile, outfile, options = {}) {
|
|
288
|
+
const format = options.format || "esm";
|
|
289
|
+
const platform = options.platform || "neutral";
|
|
290
|
+
const markdownTemplateRoot = options.rootDir && resolveViteHubProjectRoot(options.rootDir);
|
|
291
|
+
const aliases = resolveEsbuildAliases({
|
|
292
|
+
...markdownTemplateRoot ? { [markdownTemplateRegistryId]: resolve(markdownTemplateRoot, markdownTemplateRegistryPath) } : {},
|
|
293
|
+
...options.alias
|
|
294
|
+
});
|
|
295
|
+
const frameworkRuntime = Object.keys(aliases || {}).some((specifier) => specifier === "vite-hub" || specifier.startsWith("vite-hub/"));
|
|
296
|
+
await build({
|
|
297
|
+
alias: aliases,
|
|
298
|
+
banner: options.banner || format === "esm" && platform === "node" ? { js: [options.banner, ...format === "esm" && platform === "node" ? [
|
|
299
|
+
"import { createRequire as __createRequire } from \"node:module\";",
|
|
300
|
+
"import { dirname as __vitehubDirname } from \"node:path\";",
|
|
301
|
+
"import { fileURLToPath as __vitehubFileURLToPath } from \"node:url\";",
|
|
302
|
+
"globalThis.require = __createRequire(import.meta.url);",
|
|
303
|
+
"globalThis.__filename = __vitehubFileURLToPath(import.meta.url);",
|
|
304
|
+
"globalThis.__dirname = __vitehubDirname(globalThis.__filename);"
|
|
305
|
+
] : []].filter(Boolean).join("\n") } : void 0,
|
|
306
|
+
bundle: true,
|
|
307
|
+
conditions: options.conditions ?? (platform === "node" ? ["node"] : void 0),
|
|
308
|
+
entryPoints: [entryFile],
|
|
309
|
+
external: options.external,
|
|
310
|
+
format,
|
|
311
|
+
logLevel: "silent",
|
|
312
|
+
mainFields: options.mainFields ?? (platform === "neutral" ? ["module", "main"] : void 0),
|
|
313
|
+
minifyIdentifiers: options.minifyIdentifiers,
|
|
314
|
+
outfile,
|
|
315
|
+
platform,
|
|
316
|
+
plugins: [...options.plugins ?? [], createViteRawPlugin(options.rootDir, frameworkRuntime)],
|
|
317
|
+
sourcemap: false,
|
|
318
|
+
target: "es2022",
|
|
319
|
+
write: true
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
//#endregion
|
|
323
|
+
//#region ../internal/src/build/vercel-config.ts
|
|
324
|
+
function createVercelConfigJson() {
|
|
325
|
+
return {
|
|
326
|
+
routes: [{ handle: "filesystem" }, {
|
|
327
|
+
src: "/(.*)",
|
|
328
|
+
dest: "/__server"
|
|
329
|
+
}],
|
|
330
|
+
version: 3
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
function createNodeFunctionConfig(extra = {}) {
|
|
334
|
+
return {
|
|
335
|
+
handler: "index.mjs",
|
|
336
|
+
launcherType: "Nodejs",
|
|
337
|
+
runtime: "nodejs22.x",
|
|
338
|
+
shouldAddHelpers: false,
|
|
339
|
+
supportsResponseStreaming: true,
|
|
340
|
+
...extra
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
//#endregion
|
|
344
|
+
//#region ../internal/src/build/deployment-output.ts
|
|
345
|
+
function createDefaultVercelOutputRoot(rootDir) {
|
|
346
|
+
return resolve(rootDir, ".vercel", "output");
|
|
347
|
+
}
|
|
348
|
+
function createDefaultNetlifyOutputRoot(rootDir) {
|
|
349
|
+
return resolve(rootDir, ".netlify", "v1");
|
|
350
|
+
}
|
|
351
|
+
const VITEHUB_MODES = {
|
|
352
|
+
e2e: "e2e",
|
|
353
|
+
blob: "blob",
|
|
354
|
+
chat: "chat",
|
|
355
|
+
db: "db",
|
|
356
|
+
env: "env",
|
|
357
|
+
kv: "kv",
|
|
358
|
+
queue: "queue",
|
|
359
|
+
schedule: "schedule",
|
|
360
|
+
sandbox: "sandbox",
|
|
361
|
+
workspace: "workspace",
|
|
362
|
+
workflow: "workflow"
|
|
363
|
+
};
|
|
364
|
+
function isViteCli(argv) {
|
|
365
|
+
return argv.some((arg) => /(?:^|[/\\])vite(?:\.[cm]?js)?$/.test(arg) || arg === "vite");
|
|
366
|
+
}
|
|
367
|
+
function getViteCliMode(argv = process.argv) {
|
|
368
|
+
if (!isViteCli(argv)) return;
|
|
369
|
+
const modes = new Set(Object.values(VITEHUB_MODES));
|
|
370
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
371
|
+
const arg = argv[index];
|
|
372
|
+
const mode = arg === "--mode" || arg === "-m" ? argv[index + 1] : arg.startsWith("--mode=") ? arg.slice(7) : void 0;
|
|
373
|
+
if (mode && modes.has(mode)) return mode;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
function getViteMode(env = process.env) {
|
|
377
|
+
return env["VITEHUB_VITE_MODE"] ?? getViteCliMode();
|
|
378
|
+
}
|
|
379
|
+
//#endregion
|
|
380
|
+
//#region src/integrations/vercel.ts
|
|
381
|
+
function getVercelSchedulePath(name) {
|
|
382
|
+
return `/api/vitehub/schedules/vercel/${name.replace(/[^a-z0-9/_-]+/gi, "_")}`;
|
|
383
|
+
}
|
|
384
|
+
//#endregion
|
|
385
|
+
//#region src/internal/provider-output.ts
|
|
386
|
+
const schedulePackageName = "@vite-hub/schedule";
|
|
387
|
+
const scheduleStaticRuntimeImport = "@vite-hub/schedule/runtime/static";
|
|
388
|
+
const productName = "schedule";
|
|
389
|
+
const cloudflareOutputStateFileName = "cloudflare-output.json";
|
|
390
|
+
const denoCronFileName = "deno-cron.mjs";
|
|
391
|
+
const generatedRegistryFileName = "registry.mjs";
|
|
392
|
+
function resolveScheduleRuntimeEntry(resolveImport = (specifier) => import.meta.resolve(specifier)) {
|
|
393
|
+
return fileURLToPath(resolveImport(scheduleStaticRuntimeImport));
|
|
394
|
+
}
|
|
395
|
+
function resolveScheduleDefinitionEntry(resolveImport = (specifier) => import.meta.resolve(specifier)) {
|
|
396
|
+
return resolve(dirname(fileURLToPath(resolveImport(`${schedulePackageName}/package.json`))), "dist/definition.js");
|
|
397
|
+
}
|
|
398
|
+
const scheduleRuntimeEntry = resolveScheduleRuntimeEntry();
|
|
399
|
+
const scheduleDefinitionEntry = resolveScheduleDefinitionEntry();
|
|
400
|
+
function staticScheduleDefinitions(definitions) {
|
|
401
|
+
return definitions.filter((definition) => definition.runtimeOnly !== true);
|
|
402
|
+
}
|
|
403
|
+
async function removeEmptyDirectories(directory, rootDir) {
|
|
404
|
+
const root = resolve(rootDir);
|
|
405
|
+
let current = resolve(directory);
|
|
406
|
+
const pathFromRoot = relative(root, current);
|
|
407
|
+
if (!pathFromRoot || pathFromRoot.startsWith("..") || isAbsolute(pathFromRoot)) return;
|
|
408
|
+
while (current !== root) {
|
|
409
|
+
try {
|
|
410
|
+
await rmdir(current);
|
|
411
|
+
} catch (error) {
|
|
412
|
+
const code = error.code;
|
|
413
|
+
if (code === "ENOENT") {
|
|
414
|
+
current = dirname(current);
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
if (code === "ENOTEMPTY" || code === "EEXIST") return;
|
|
418
|
+
throw error;
|
|
419
|
+
}
|
|
420
|
+
current = dirname(current);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
const cronFieldPattern = /^[*,/\-0-9]+$/;
|
|
424
|
+
function validateProviderCron(cron, scheduleName) {
|
|
425
|
+
const fields = cron.trim().split(/\s+/);
|
|
426
|
+
const hasVercelDayConflict = fields[2] !== "*" && fields[4] !== "*";
|
|
427
|
+
if (fields.length !== 5 || !fields.every((field) => cronFieldPattern.test(field)) || hasVercelDayConflict) throw new Error(`Schedule "${scheduleName}" uses cron "${cron}", but provider wake output only supports five-field UTC cron syntax compatible with Cloudflare, Vercel, and Netlify.`);
|
|
428
|
+
}
|
|
429
|
+
function readStaticScheduleCron(file, scheduleName) {
|
|
430
|
+
const definition = findDefaultExportCall(readFileSync(file, "utf8"), ["defineSchedule"]);
|
|
431
|
+
const cron = definition && readStaticString(readObjectProperty(definition.argument, "cron"));
|
|
432
|
+
if (!cron) throw new Error(`Schedule "${scheduleName}" must declare a static cron string for provider wake output.`);
|
|
433
|
+
return cron;
|
|
434
|
+
}
|
|
435
|
+
function readStaticString(source) {
|
|
436
|
+
if (!source || !/^["'`]/.test(source)) return;
|
|
437
|
+
const quote = source[0];
|
|
438
|
+
let value = "";
|
|
439
|
+
for (let index = 1; index < source.length; index++) if (source[index] === "\\") value += source[++index] || "";
|
|
440
|
+
else if (source[index] === quote) return source.slice(index + 1).trim() ? void 0 : value;
|
|
441
|
+
else value += source[index];
|
|
442
|
+
}
|
|
443
|
+
function renderProviderEntry(file, registryFile, provider, scheduleName) {
|
|
444
|
+
const runtimeImport = createImportPath(file, scheduleRuntimeEntry);
|
|
445
|
+
return [
|
|
446
|
+
`import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
|
|
447
|
+
`import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
|
|
448
|
+
"",
|
|
449
|
+
"async function loadScheduleDefinition(name) {",
|
|
450
|
+
" const loader = scheduleRegistry[name]",
|
|
451
|
+
" if (!loader) return undefined",
|
|
452
|
+
" const loaded = await loader()",
|
|
453
|
+
" return loaded?.default ?? loaded",
|
|
454
|
+
"}",
|
|
455
|
+
"",
|
|
456
|
+
"async function runSchedule(name, cron, scheduledAt) {",
|
|
457
|
+
" const definition = await loadScheduleDefinition(name)",
|
|
458
|
+
" if (!definition) {",
|
|
459
|
+
" throw new Error(`Missing schedule definition: ${name}`)",
|
|
460
|
+
" }",
|
|
461
|
+
" return await executeStaticSchedule({ cron, definition, name, scheduledAt })",
|
|
462
|
+
"}",
|
|
463
|
+
"",
|
|
464
|
+
provider === "cloudflare" ? [
|
|
465
|
+
"export default {",
|
|
466
|
+
" async fetch() {",
|
|
467
|
+
" return new Response('ViteHub schedule provider wake endpoint')",
|
|
468
|
+
" },",
|
|
469
|
+
" async scheduled(event, env, ctx) {",
|
|
470
|
+
" const tasks = Object.entries(scheduleRegistry).map(async ([name]) => {",
|
|
471
|
+
" const definition = await loadScheduleDefinition(name)",
|
|
472
|
+
" if (!definition || definition.cron !== event.cron) return",
|
|
473
|
+
" await executeStaticSchedule({ cron: event.cron, definition, name, scheduledAt: new Date(event.scheduledTime), waitUntil: (promise) => ctx.waitUntil(promise) })",
|
|
474
|
+
" })",
|
|
475
|
+
" await Promise.all(tasks)",
|
|
476
|
+
" },",
|
|
477
|
+
"}"
|
|
478
|
+
].join("\n") : [
|
|
479
|
+
"export default async function scheduleHandler(req, res) {",
|
|
480
|
+
" const cronSecret = process.env.CRON_SECRET",
|
|
481
|
+
" const authorization = req.headers?.authorization || req.headers?.Authorization",
|
|
482
|
+
" if (cronSecret && authorization !== `Bearer ${cronSecret}`) {",
|
|
483
|
+
" res.statusCode = 401",
|
|
484
|
+
" res.end('Unauthorized.')",
|
|
485
|
+
" return",
|
|
486
|
+
" }",
|
|
487
|
+
" const url = new URL(req.url || '/', 'https://vitehub.local')",
|
|
488
|
+
" const prefix = '/api/vitehub/schedules/vercel/'",
|
|
489
|
+
scheduleName === void 0 ? " const name = decodeURIComponent(url.pathname.startsWith(prefix) ? url.pathname.slice(prefix.length) : '')" : ` const name = ${JSON.stringify(scheduleName)}`,
|
|
490
|
+
" const definition = await loadScheduleDefinition(name)",
|
|
491
|
+
" if (!definition) {",
|
|
492
|
+
" res.statusCode = 404",
|
|
493
|
+
" res.end('Missing schedule definition.')",
|
|
494
|
+
" return",
|
|
495
|
+
" }",
|
|
496
|
+
" await runSchedule(name, definition.cron, new Date())",
|
|
497
|
+
" res.statusCode = 204",
|
|
498
|
+
" res.end()",
|
|
499
|
+
"}"
|
|
500
|
+
].join("\n"),
|
|
501
|
+
""
|
|
502
|
+
].join("\n");
|
|
503
|
+
}
|
|
504
|
+
function renderNetlifyScheduleFunction(file, registryFile, scheduleName, cron) {
|
|
505
|
+
const runtimeImport = createImportPath(file, scheduleRuntimeEntry);
|
|
506
|
+
return [
|
|
507
|
+
`import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
|
|
508
|
+
`import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
|
|
509
|
+
"",
|
|
510
|
+
`const scheduleName = ${JSON.stringify(scheduleName)}`,
|
|
511
|
+
"",
|
|
512
|
+
"export default async function netlifyScheduleHandler(request) {",
|
|
513
|
+
" const loaded = await scheduleRegistry[scheduleName]?.()",
|
|
514
|
+
" const definition = loaded?.default ?? loaded",
|
|
515
|
+
" if (!definition) return new Response('Missing schedule definition.', { status: 404 })",
|
|
516
|
+
` await executeStaticSchedule({ cron: ${JSON.stringify(cron)}, definition, name: scheduleName, scheduledAt: new Date() })`,
|
|
517
|
+
" return new Response(null, { status: 204 })",
|
|
518
|
+
"}",
|
|
519
|
+
"",
|
|
520
|
+
"export const config = {",
|
|
521
|
+
` schedule: ${JSON.stringify(cron)},`,
|
|
522
|
+
"}",
|
|
523
|
+
""
|
|
524
|
+
].join("\n");
|
|
525
|
+
}
|
|
526
|
+
function sanitizeNetlifyScheduleFunctionName(name) {
|
|
527
|
+
return `vitehub-schedule-${name.toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "schedule"}.mjs`;
|
|
528
|
+
}
|
|
529
|
+
function renderDenoCronEntry(file, registryFile, crons, runtimeImport = scheduleStaticRuntimeImport) {
|
|
530
|
+
const scheduleCrons = Object.fromEntries([...crons.entries()].sort(([left], [right]) => left.localeCompare(right)));
|
|
531
|
+
return [
|
|
532
|
+
`import scheduleRegistry from ${JSON.stringify(createImportPath(file, registryFile))}`,
|
|
533
|
+
`import { executeStaticSchedule } from ${JSON.stringify(runtimeImport)}`,
|
|
534
|
+
"",
|
|
535
|
+
`const scheduleCrons = ${JSON.stringify(scheduleCrons, null, 2)}`,
|
|
536
|
+
"",
|
|
537
|
+
"async function loadScheduleDefinition(name) {",
|
|
538
|
+
" const loader = scheduleRegistry[name]",
|
|
539
|
+
" if (!loader) return undefined",
|
|
540
|
+
" const loaded = await loader()",
|
|
541
|
+
" return loaded?.default ?? loaded",
|
|
542
|
+
"}",
|
|
543
|
+
"",
|
|
544
|
+
"for (const [name, cron] of Object.entries(scheduleCrons)) {",
|
|
545
|
+
" Deno.cron(`vitehub:${name}`, cron, async () => {",
|
|
546
|
+
" const definition = await loadScheduleDefinition(name)",
|
|
547
|
+
" if (!definition) {",
|
|
548
|
+
" throw new Error(`Missing schedule definition: ${name}`)",
|
|
549
|
+
" }",
|
|
550
|
+
" await executeStaticSchedule({ cron, definition, name, scheduledAt: new Date() })",
|
|
551
|
+
" })",
|
|
552
|
+
"}",
|
|
553
|
+
"",
|
|
554
|
+
"export const vitehubScheduleDefinitions = Object.keys(scheduleCrons)",
|
|
555
|
+
""
|
|
556
|
+
].join("\n");
|
|
557
|
+
}
|
|
558
|
+
function createScheduleDefinitionAliasPlugin() {
|
|
559
|
+
return {
|
|
560
|
+
name: "vitehub-schedule-definition-alias",
|
|
561
|
+
setup(build) {
|
|
562
|
+
build.onResolve({ filter: /^@vite-hub\/schedule$/ }, () => ({ path: scheduleDefinitionEntry }));
|
|
563
|
+
}
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
async function writeProviderEntries(rootDir, source, providedDefinitions) {
|
|
567
|
+
const generatedDir = ensureGeneratedDir(rootDir, productName);
|
|
568
|
+
const registryFile = resolve(generatedDir, generatedRegistryFileName);
|
|
569
|
+
const definitions = (providedDefinitions ?? discoverScheduleDefinitions({ rootDir })).filter((definition) => !source || definition.source === source).filter((definition) => definition.runtimeOnly !== true);
|
|
570
|
+
await writeRuntimeRegistryFile(registryFile, definitions);
|
|
571
|
+
const cloudflareWorkerFile = resolve(generatedDir, "cloudflare-worker.mjs");
|
|
572
|
+
const denoCronFile = resolve(generatedDir, denoCronFileName);
|
|
573
|
+
const vercelServerFile = resolve(generatedDir, "vercel-server.mjs");
|
|
574
|
+
await writeFile(cloudflareWorkerFile, renderProviderEntry(cloudflareWorkerFile, registryFile, "cloudflare"), "utf8");
|
|
575
|
+
await writeFile(vercelServerFile, renderProviderEntry(vercelServerFile, registryFile, "vercel"), "utf8");
|
|
576
|
+
return {
|
|
577
|
+
cloudflareWorkerFile,
|
|
578
|
+
denoCronFile,
|
|
579
|
+
definitions,
|
|
580
|
+
generatedDir,
|
|
581
|
+
registryFile,
|
|
582
|
+
vercelServerFile
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
async function readDefinitionCrons(definitions) {
|
|
586
|
+
const crons = /* @__PURE__ */ new Map();
|
|
587
|
+
for (const definition of staticScheduleDefinitions(definitions)) {
|
|
588
|
+
const cron = readStaticScheduleCron(definition.handler, definition.name);
|
|
589
|
+
validateProviderCron(cron, definition.name);
|
|
590
|
+
crons.set(definition.name, cron);
|
|
591
|
+
}
|
|
592
|
+
return crons;
|
|
593
|
+
}
|
|
594
|
+
async function writeVercelScheduleFunctions(options, crons) {
|
|
595
|
+
const definitions = staticScheduleDefinitions(options.definitions);
|
|
596
|
+
const outputRoot = options.outputRoot;
|
|
597
|
+
const functionRoot = resolve(outputRoot, "functions", "api", "vitehub", "schedules", "vercel");
|
|
598
|
+
await rm(functionRoot, {
|
|
599
|
+
force: true,
|
|
600
|
+
recursive: true
|
|
601
|
+
});
|
|
602
|
+
const emittedFunctionNames = /* @__PURE__ */ new Map();
|
|
603
|
+
for (const definition of definitions) {
|
|
604
|
+
const safeName = definition.name.replace(/[^a-z0-9/_-]+/gi, "_").split("/").filter(Boolean).join("/");
|
|
605
|
+
const existingName = emittedFunctionNames.get(safeName);
|
|
606
|
+
if (existingName) throw new Error(`Schedule "${definition.name}" and "${existingName}" both emit the same Vercel function path: ${safeName}`);
|
|
607
|
+
emittedFunctionNames.set(safeName, definition.name);
|
|
608
|
+
const segments = safeName.split("/");
|
|
609
|
+
const functionDir = resolve(functionRoot, ...segments.slice(0, -1), `${segments.at(-1)}.func`);
|
|
610
|
+
const functionFile = resolve(functionDir, "index.mjs");
|
|
611
|
+
const wrapperFile = resolve(functionDir, "index.source.mjs");
|
|
612
|
+
await mkdir(functionDir, { recursive: true });
|
|
613
|
+
await writeFile(wrapperFile, renderProviderEntry(wrapperFile, options.registryFile, "vercel", definition.name), "utf8");
|
|
614
|
+
await bundleEsmEntry(wrapperFile, functionFile, {
|
|
615
|
+
alias: options.bundleAlias,
|
|
616
|
+
format: "esm",
|
|
617
|
+
platform: "node",
|
|
618
|
+
plugins: [createScheduleDefinitionAliasPlugin()],
|
|
619
|
+
rootDir: options.rootDir
|
|
620
|
+
});
|
|
621
|
+
await rm(wrapperFile, { force: true });
|
|
622
|
+
await writeFile(resolve(functionDir, ".vc-config.json"), `${JSON.stringify(createNodeFunctionConfig(), null, 2)}\n`, "utf8");
|
|
623
|
+
}
|
|
624
|
+
const configFile = resolve(outputRoot, "config.json");
|
|
625
|
+
let vercelConfig;
|
|
626
|
+
try {
|
|
627
|
+
vercelConfig = JSON.parse(await readFile(configFile, "utf8"));
|
|
628
|
+
} catch (error) {
|
|
629
|
+
if (error.code !== "ENOENT") throw error;
|
|
630
|
+
if (!definitions.length) {
|
|
631
|
+
await removeEmptyDirectories(functionRoot, options.rootDir);
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
vercelConfig = createVercelConfigJson();
|
|
635
|
+
}
|
|
636
|
+
const schedulePathPrefix = "/api/vitehub/schedules/vercel/";
|
|
637
|
+
const previousCrons = vercelConfig.crons ?? [];
|
|
638
|
+
const existingCrons = previousCrons.filter((cron) => !cron.path.startsWith(schedulePathPrefix));
|
|
639
|
+
if (!definitions.length && existingCrons.length === previousCrons.length) {
|
|
640
|
+
await removeEmptyDirectories(functionRoot, options.rootDir);
|
|
641
|
+
if (previousCrons.length === 0) {
|
|
642
|
+
delete vercelConfig.crons;
|
|
643
|
+
if (isDeepStrictEqual(vercelConfig, createVercelConfigJson())) {
|
|
644
|
+
const outputFiles = await readdir(outputRoot);
|
|
645
|
+
if (outputFiles.length === 1 && outputFiles[0] === "config.json") {
|
|
646
|
+
await rm(configFile, { force: true });
|
|
647
|
+
await removeEmptyDirectories(outputRoot, options.rootDir);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
const nextCrons = [...existingCrons, ...definitions.map((definition) => ({
|
|
654
|
+
path: getVercelSchedulePath(definition.name),
|
|
655
|
+
schedule: crons.get(definition.name)
|
|
656
|
+
}))];
|
|
657
|
+
if (nextCrons.length) vercelConfig.crons = nextCrons;
|
|
658
|
+
else delete vercelConfig.crons;
|
|
659
|
+
if (!definitions.length) {
|
|
660
|
+
await removeEmptyDirectories(functionRoot, options.rootDir);
|
|
661
|
+
const outputFiles = await readdir(outputRoot);
|
|
662
|
+
if (outputFiles.length === 1 && outputFiles[0] === "config.json" && isDeepStrictEqual(vercelConfig, createVercelConfigJson())) {
|
|
663
|
+
await rm(configFile, { force: true });
|
|
664
|
+
await removeEmptyDirectories(outputRoot, options.rootDir);
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
await writeFile(configFile, `${JSON.stringify(vercelConfig, null, 2)}\n`, "utf8");
|
|
669
|
+
}
|
|
670
|
+
async function createNetlifyScheduleFunctionOutputs(options) {
|
|
671
|
+
const definitions = staticScheduleDefinitions(options.definitions);
|
|
672
|
+
const crons = await readDefinitionCrons(definitions);
|
|
673
|
+
const emitted = /* @__PURE__ */ new Map();
|
|
674
|
+
return definitions.map((definition) => {
|
|
675
|
+
const fileName = sanitizeNetlifyScheduleFunctionName(definition.name);
|
|
676
|
+
const existingName = emitted.get(fileName);
|
|
677
|
+
if (existingName) throw new Error(`Schedule "${definition.name}" and "${existingName}" both emit the same Netlify function file: ${fileName}`);
|
|
678
|
+
emitted.set(fileName, definition.name);
|
|
679
|
+
const file = resolve(options.functionRoot, fileName);
|
|
680
|
+
return {
|
|
681
|
+
cron: crons.get(definition.name),
|
|
682
|
+
file,
|
|
683
|
+
name: definition.name,
|
|
684
|
+
source: renderNetlifyScheduleFunction(file, options.registryFile, definition.name, crons.get(definition.name))
|
|
685
|
+
};
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
async function writeNetlifyScheduleFunctions(options) {
|
|
689
|
+
const functionRoot = resolve(options.outputRoot, "functions");
|
|
690
|
+
const existingFiles = await readdir(functionRoot).catch((error) => {
|
|
691
|
+
if (error.code === "ENOENT") return [];
|
|
692
|
+
throw error;
|
|
693
|
+
});
|
|
694
|
+
await Promise.all(existingFiles.filter((file) => /^vitehub-schedule-.+\.mjs$/.test(file)).map((file) => rm(resolve(functionRoot, file), {
|
|
695
|
+
force: true,
|
|
696
|
+
recursive: true
|
|
697
|
+
})));
|
|
698
|
+
const outputs = await createNetlifyScheduleFunctionOutputs({
|
|
699
|
+
definitions: options.definitions,
|
|
700
|
+
functionRoot,
|
|
701
|
+
registryFile: options.registryFile
|
|
702
|
+
});
|
|
703
|
+
if (outputs.length === 0) {
|
|
704
|
+
await removeEmptyDirectories(functionRoot, options.rootDir);
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
await mkdir(functionRoot, { recursive: true });
|
|
708
|
+
await Promise.all(outputs.map(async (output) => writeFile(output.file, output.source, "utf8")));
|
|
709
|
+
}
|
|
710
|
+
async function writeCloudflareScheduleOutput(options) {
|
|
711
|
+
const outputRoot = createDefaultCloudflareOutputRoot(options.rootDir);
|
|
712
|
+
await mkdir(outputRoot, { recursive: true });
|
|
713
|
+
const configFile = resolve(outputRoot, "wrangler.json");
|
|
714
|
+
let wranglerConfig = {};
|
|
715
|
+
try {
|
|
716
|
+
wranglerConfig = JSON.parse(await readFile(configFile, "utf8"));
|
|
717
|
+
} catch (error) {
|
|
718
|
+
if (error.code !== "ENOENT") throw error;
|
|
719
|
+
}
|
|
720
|
+
const existingTriggers = typeof wranglerConfig.triggers === "object" && wranglerConfig.triggers !== null ? wranglerConfig.triggers : {};
|
|
721
|
+
const previousState = await readCloudflareOutputState(options.stateFile);
|
|
722
|
+
const externalCrons = (existingTriggers.crons ?? []).filter((cron) => !previousState?.crons.includes(cron));
|
|
723
|
+
const ownedCrons = options.crons.filter((cron) => !externalCrons.includes(cron));
|
|
724
|
+
const main = typeof wranglerConfig.main === "string" && wranglerConfig.main ? wranglerConfig.main : "index.js";
|
|
725
|
+
wranglerConfig = {
|
|
726
|
+
...wranglerConfig,
|
|
727
|
+
compatibility_date: wranglerConfig.compatibility_date ?? "2026-04-20",
|
|
728
|
+
compatibility_flags: wranglerConfig.compatibility_flags ?? ["nodejs_compat"],
|
|
729
|
+
main,
|
|
730
|
+
observability: wranglerConfig.observability ?? { enabled: true },
|
|
731
|
+
triggers: {
|
|
732
|
+
...existingTriggers,
|
|
733
|
+
crons: [...new Set([...externalCrons, ...options.crons])]
|
|
734
|
+
}
|
|
735
|
+
};
|
|
736
|
+
await Promise.all([
|
|
737
|
+
bundleEsmEntry(options.bundleEntry, resolve(outputRoot, main), {
|
|
738
|
+
alias: options.bundleAlias,
|
|
739
|
+
conditions: [
|
|
740
|
+
"workerd",
|
|
741
|
+
"worker",
|
|
742
|
+
"browser",
|
|
743
|
+
"default"
|
|
744
|
+
],
|
|
745
|
+
format: "esm",
|
|
746
|
+
platform: "neutral",
|
|
747
|
+
plugins: [createScheduleDefinitionAliasPlugin()],
|
|
748
|
+
rootDir: options.rootDir
|
|
749
|
+
}),
|
|
750
|
+
writeFile(configFile, `${JSON.stringify(wranglerConfig, null, 2)}\n`, "utf8"),
|
|
751
|
+
writeFile(options.stateFile, `${JSON.stringify({
|
|
752
|
+
crons: ownedCrons,
|
|
753
|
+
main
|
|
754
|
+
}, null, 2)}\n`, "utf8")
|
|
755
|
+
]);
|
|
756
|
+
}
|
|
757
|
+
async function readCloudflareOutputState(file) {
|
|
758
|
+
let source;
|
|
759
|
+
try {
|
|
760
|
+
source = await readFile(file, "utf8");
|
|
761
|
+
} catch (error) {
|
|
762
|
+
if (error.code === "ENOENT") return;
|
|
763
|
+
throw error;
|
|
764
|
+
}
|
|
765
|
+
try {
|
|
766
|
+
const state = JSON.parse(source);
|
|
767
|
+
if (!Array.isArray(state.crons) || state.crons.some((cron) => typeof cron !== "string") || typeof state.main !== "string" || !state.main) return;
|
|
768
|
+
return {
|
|
769
|
+
crons: state.crons,
|
|
770
|
+
main: state.main
|
|
771
|
+
};
|
|
772
|
+
} catch {
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
async function cleanCloudflareScheduleOutput(rootDir, stateFile) {
|
|
777
|
+
const state = await readCloudflareOutputState(stateFile);
|
|
778
|
+
if (!state) return;
|
|
779
|
+
const outputRoot = createDefaultCloudflareOutputRoot(rootDir);
|
|
780
|
+
const configFile = resolve(outputRoot, "wrangler.json");
|
|
781
|
+
let configSource;
|
|
782
|
+
try {
|
|
783
|
+
configSource = await readFile(configFile, "utf8");
|
|
784
|
+
} catch (error) {
|
|
785
|
+
if (error.code !== "ENOENT") throw error;
|
|
786
|
+
}
|
|
787
|
+
if (configSource !== void 0) {
|
|
788
|
+
const config = JSON.parse(configSource);
|
|
789
|
+
const triggers = typeof config.triggers === "object" && config.triggers !== null ? config.triggers : void 0;
|
|
790
|
+
const crons = Array.isArray(triggers?.crons) ? triggers.crons.filter((cron) => typeof cron === "string" && !state.crons.includes(cron)) : [];
|
|
791
|
+
if (triggers) config.triggers = {
|
|
792
|
+
...triggers,
|
|
793
|
+
crons
|
|
794
|
+
};
|
|
795
|
+
await writeFile(configFile, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
796
|
+
}
|
|
797
|
+
await Promise.all([rm(resolve(outputRoot, state.main), { force: true }), rm(stateFile, { force: true })]);
|
|
798
|
+
}
|
|
799
|
+
async function generateProviderOutputs(options) {
|
|
800
|
+
const cloudflareStateFile = resolve(ensureGeneratedDir(options.rootDir, productName), cloudflareOutputStateFileName);
|
|
801
|
+
const artifacts = await writeProviderEntries(options.rootDir, options.source, options.definitions);
|
|
802
|
+
const crons = await readDefinitionCrons(artifacts.definitions);
|
|
803
|
+
if (artifacts.definitions.length > 0) {
|
|
804
|
+
await writeFile(artifacts.denoCronFile, renderDenoCronEntry(artifacts.denoCronFile, artifacts.registryFile, crons, options.runtimeImport), "utf8");
|
|
805
|
+
await writeCloudflareScheduleOutput({
|
|
806
|
+
bundleAlias: options.bundleAlias,
|
|
807
|
+
bundleEntry: artifacts.cloudflareWorkerFile,
|
|
808
|
+
crons: [...new Set(crons.values())],
|
|
809
|
+
rootDir: options.rootDir,
|
|
810
|
+
stateFile: cloudflareStateFile
|
|
811
|
+
});
|
|
812
|
+
} else await Promise.all([
|
|
813
|
+
rm(artifacts.cloudflareWorkerFile, { force: true }),
|
|
814
|
+
rm(artifacts.denoCronFile, { force: true }),
|
|
815
|
+
rm(artifacts.registryFile, { force: true }),
|
|
816
|
+
rm(artifacts.vercelServerFile, { force: true }),
|
|
817
|
+
cleanCloudflareScheduleOutput(options.rootDir, cloudflareStateFile)
|
|
818
|
+
]);
|
|
819
|
+
await writeVercelScheduleFunctions({
|
|
820
|
+
bundleAlias: options.bundleAlias,
|
|
821
|
+
definitions: artifacts.definitions,
|
|
822
|
+
outputRoot: createDefaultVercelOutputRoot(options.rootDir),
|
|
823
|
+
registryFile: artifacts.registryFile,
|
|
824
|
+
rootDir: options.rootDir
|
|
825
|
+
}, crons);
|
|
826
|
+
await writeNetlifyScheduleFunctions({
|
|
827
|
+
definitions: artifacts.definitions,
|
|
828
|
+
outputRoot: createDefaultNetlifyOutputRoot(options.rootDir),
|
|
829
|
+
registryFile: artifacts.registryFile,
|
|
830
|
+
rootDir: options.rootDir
|
|
831
|
+
});
|
|
832
|
+
return artifacts;
|
|
833
|
+
}
|
|
834
|
+
//#endregion
|
|
835
|
+
//#region src/targets-module.ts
|
|
836
|
+
const SCHEDULE_TARGETS_ID = "#vitehub/schedule/targets";
|
|
837
|
+
function getScheduleTargetNames(definitions) {
|
|
838
|
+
return definitions.filter((definition) => definition.allowRuntimeSchedules).map((definition) => definition.name).sort();
|
|
839
|
+
}
|
|
840
|
+
function createScheduleTargetsContents(definitions, options = {}) {
|
|
841
|
+
const targets = getScheduleTargetNames(definitions);
|
|
842
|
+
const union = targets.length ? targets.map((target) => JSON.stringify(target)).join(" | ") : "never";
|
|
843
|
+
return [
|
|
844
|
+
`export const scheduleTargetNames = ${JSON.stringify(targets)};`,
|
|
845
|
+
options.types ? `export type ScheduleTargetName = ${union};` : "",
|
|
846
|
+
""
|
|
847
|
+
].filter((line) => line !== "").join("\n");
|
|
848
|
+
}
|
|
849
|
+
//#endregion
|
|
850
|
+
//#region src/vite.ts
|
|
851
|
+
const SCHEDULE_VITE_PLUGIN_NAME = "@vite-hub/schedule/vite";
|
|
852
|
+
const SCHEDULE_REGISTRY_ID = "#vitehub/schedule/registry";
|
|
853
|
+
const RESOLVED_SCHEDULE_REGISTRY_ID = "\0#vitehub/schedule/registry";
|
|
854
|
+
const RESOLVED_SCHEDULE_TARGETS_ID = `\0${SCHEDULE_TARGETS_ID}`;
|
|
855
|
+
const registryImportAnchor = ".vitehub/schedule/registry.js";
|
|
856
|
+
const generatedNitroSchedulePlugin = ".vitehub/nitro/schedule/plugin.ts";
|
|
857
|
+
const generatedNitroRuntimeRegistry = ".vitehub/nitro/schedule/runtime-registry.js";
|
|
858
|
+
const generatedNitroStaticRegistry = ".vitehub/nitro/schedule/static-registry.js";
|
|
859
|
+
const generatedNitroCloudflareModule = "./.vitehub/nitro/schedule/module.mjs";
|
|
860
|
+
const mergeNoExternal = createNoExternalMerger(schedulePackageName);
|
|
861
|
+
function resolveSchedulePluginRoots(root, options = {}) {
|
|
862
|
+
const resolvedViteRoot = resolve(root);
|
|
863
|
+
return {
|
|
864
|
+
projectRoot: resolveViteHubProjectRoot(resolvedViteRoot, { projectRoot: options.projectRoot }),
|
|
865
|
+
viteRoot: resolvedViteRoot
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
function isRecord(value) {
|
|
869
|
+
return typeof value === "object" && value !== null;
|
|
870
|
+
}
|
|
871
|
+
function resolveProcessRuntimeOptions(value) {
|
|
872
|
+
if (value === void 0) return;
|
|
873
|
+
if (!isRecord(value) || value.driver !== "process") throw new TypeError("Schedule Process Runtime driver must be \"process\".");
|
|
874
|
+
if (value.prefix !== void 0 && typeof value.prefix !== "string") throw new TypeError("Schedule Process Runtime prefix must be a string.");
|
|
875
|
+
if (value.intervalMs !== void 0 && (typeof value.intervalMs !== "number" || !Number.isFinite(value.intervalMs) || value.intervalMs <= 0 || value.intervalMs > 6e4)) throw new TypeError("Schedule Process Runtime intervalMs must be a positive number no greater than 60000.");
|
|
876
|
+
if (value.concurrency !== void 0 && (typeof value.concurrency !== "number" || !Number.isInteger(value.concurrency) || value.concurrency < 1)) throw new TypeError("Schedule Process Runtime concurrency must be a positive integer.");
|
|
877
|
+
return {
|
|
878
|
+
...value.concurrency !== void 0 ? { concurrency: value.concurrency } : {},
|
|
879
|
+
driver: "process",
|
|
880
|
+
...value.intervalMs !== void 0 ? { intervalMs: value.intervalMs } : {},
|
|
881
|
+
...value.prefix !== void 0 ? { prefix: value.prefix } : {}
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
function resolveStringAliases(config) {
|
|
885
|
+
const aliases = {};
|
|
886
|
+
for (const alias of config.resolve.alias) if (typeof alias.find === "string" && typeof alias.replacement === "string") aliases[alias.find] = alias.replacement;
|
|
887
|
+
return aliases;
|
|
888
|
+
}
|
|
889
|
+
function moduleImportSpecifier(fromFile, targetFile) {
|
|
890
|
+
const specifier = relative(dirname(fromFile), targetFile).replace(/\\/g, "/");
|
|
891
|
+
return specifier.startsWith(".") ? specifier : `./${specifier}`;
|
|
892
|
+
}
|
|
893
|
+
function cloneNitroConfig(value) {
|
|
894
|
+
const nitro = isRecord(value) ? { ...value } : {};
|
|
895
|
+
if (Array.isArray(nitro.plugins)) nitro.plugins = [...nitro.plugins];
|
|
896
|
+
if (isRecord(nitro.cloudflare)) {
|
|
897
|
+
const cloudflare = { ...nitro.cloudflare };
|
|
898
|
+
if (isRecord(cloudflare.wrangler)) {
|
|
899
|
+
const wrangler = { ...cloudflare.wrangler };
|
|
900
|
+
if (isRecord(wrangler.triggers)) {
|
|
901
|
+
const triggers = { ...wrangler.triggers };
|
|
902
|
+
if (Array.isArray(triggers.crons)) triggers.crons = triggers.crons.filter((cron) => typeof cron === "string");
|
|
903
|
+
wrangler.triggers = triggers;
|
|
904
|
+
}
|
|
905
|
+
cloudflare.wrangler = wrangler;
|
|
906
|
+
}
|
|
907
|
+
nitro.cloudflare = cloudflare;
|
|
908
|
+
}
|
|
909
|
+
return nitro;
|
|
910
|
+
}
|
|
911
|
+
function mergeNitroScheduleConfig(value, options) {
|
|
912
|
+
const nitro = cloneNitroConfig(value);
|
|
913
|
+
nitro.plugins = Array.isArray(nitro.plugins) && nitro.plugins.includes(options.plugin) ? nitro.plugins : [...Array.isArray(nitro.plugins) ? nitro.plugins : [], options.plugin];
|
|
914
|
+
if (!options.providerWake) return nitro;
|
|
915
|
+
nitro.modules = Array.isArray(nitro.modules) && nitro.modules.includes(generatedNitroCloudflareModule) ? nitro.modules : [...Array.isArray(nitro.modules) ? nitro.modules : [], generatedNitroCloudflareModule];
|
|
916
|
+
nitro.cloudflare ||= {};
|
|
917
|
+
nitro.cloudflare.wrangler ||= {};
|
|
918
|
+
const wrangler = nitro.cloudflare.wrangler;
|
|
919
|
+
const existingTriggers = isRecord(wrangler.triggers) ? wrangler.triggers : {};
|
|
920
|
+
const existingCrons = Array.isArray(existingTriggers.crons) ? existingTriggers.crons.filter((cron) => typeof cron === "string") : [];
|
|
921
|
+
wrangler.triggers = {
|
|
922
|
+
...existingTriggers,
|
|
923
|
+
crons: [...new Set([...existingCrons, ...options.crons])]
|
|
924
|
+
};
|
|
925
|
+
return nitro;
|
|
926
|
+
}
|
|
927
|
+
function renderNitroSchedulePlugin(options) {
|
|
928
|
+
const importBase = options.importBase ?? "@vite-hub/schedule";
|
|
929
|
+
const providerWake = options.providerDefinitions.length > 0;
|
|
930
|
+
const processRuntime = options.processRuntime;
|
|
931
|
+
const processDriverOptions = processRuntime ? {
|
|
932
|
+
...processRuntime.concurrency !== void 0 ? { concurrency: processRuntime.concurrency } : {},
|
|
933
|
+
...processRuntime.intervalMs !== void 0 ? { intervalMs: processRuntime.intervalMs } : {}
|
|
934
|
+
} : void 0;
|
|
935
|
+
const scheduleStoreOptions = processRuntime?.prefix !== void 0 ? { prefix: processRuntime.prefix } : {};
|
|
936
|
+
return [
|
|
937
|
+
"import { definePlugin } from 'nitro'",
|
|
938
|
+
...providerWake ? [`import scheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.providerRegistryFile))}`, `import { executeCloudflareStaticSchedules } from ${JSON.stringify(options.runtimeImport ?? `${importBase}/runtime/static`)}`] : [],
|
|
939
|
+
...processRuntime ? [
|
|
940
|
+
`import { createKVRuntimeScheduleStore, createKVScheduleRunStore } from ${JSON.stringify(importBase)}`,
|
|
941
|
+
`import { installScheduleRuntime } from ${JSON.stringify(`${importBase}/runtime/driver`)}`,
|
|
942
|
+
`import { createProcessScheduleWakeDriver } from ${JSON.stringify(`${importBase}/runtime/process`)}`,
|
|
943
|
+
`import runtimeScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.runtimeRegistryFile))}`,
|
|
944
|
+
`import staticScheduleRegistry from ${JSON.stringify(moduleImportSpecifier(options.pluginFile, options.staticRegistryFile))}`
|
|
945
|
+
] : [],
|
|
946
|
+
"",
|
|
947
|
+
...processRuntime ? [
|
|
948
|
+
`const processDriverOptions = ${JSON.stringify(processDriverOptions, null, 2)}`,
|
|
949
|
+
`const scheduleStoreOptions = ${JSON.stringify(scheduleStoreOptions, null, 2)}`,
|
|
950
|
+
""
|
|
951
|
+
] : [],
|
|
952
|
+
"export default definePlugin((nitroApp) => {",
|
|
953
|
+
...providerWake ? [
|
|
954
|
+
" nitroApp.hooks.hook('cloudflare:scheduled', async (event) => {",
|
|
955
|
+
" await executeCloudflareStaticSchedules(event, { registry: scheduleRegistry })",
|
|
956
|
+
" })"
|
|
957
|
+
] : [],
|
|
958
|
+
...processRuntime ? [
|
|
959
|
+
" function captureRuntimeError(error: unknown) {",
|
|
960
|
+
" let runtimeError: Error",
|
|
961
|
+
" try {",
|
|
962
|
+
" runtimeError = error instanceof Error ? error : new Error(String(error))",
|
|
963
|
+
" }",
|
|
964
|
+
" catch {",
|
|
965
|
+
" return",
|
|
966
|
+
" }",
|
|
967
|
+
" try {",
|
|
968
|
+
" console.error('[vitehub:schedule]', runtimeError)",
|
|
969
|
+
" }",
|
|
970
|
+
" catch {}",
|
|
971
|
+
" try {",
|
|
972
|
+
" nitroApp.captureError?.(runtimeError, { tags: ['vitehub-schedule'] })",
|
|
973
|
+
" }",
|
|
974
|
+
" catch {}",
|
|
975
|
+
" }",
|
|
976
|
+
" const runtimeInstallation = installScheduleRuntime({",
|
|
977
|
+
" createDriver: createProcessScheduleWakeDriver(processDriverOptions),",
|
|
978
|
+
" onError: captureRuntimeError,",
|
|
979
|
+
" registry: runtimeScheduleRegistry,",
|
|
980
|
+
" runtimeScheduleStore: createKVRuntimeScheduleStore(scheduleStoreOptions),",
|
|
981
|
+
" scheduleRunStore: createKVScheduleRunStore(scheduleStoreOptions),",
|
|
982
|
+
" staticRegistry: staticScheduleRegistry,",
|
|
983
|
+
" }).then(",
|
|
984
|
+
" controller => ({ controller }),",
|
|
985
|
+
" error => {",
|
|
986
|
+
" captureRuntimeError(error)",
|
|
987
|
+
" return { error }",
|
|
988
|
+
" },",
|
|
989
|
+
" )",
|
|
990
|
+
" nitroApp.hooks.hook('request', async () => {",
|
|
991
|
+
" const result = await runtimeInstallation",
|
|
992
|
+
" if ('error' in result) throw result.error",
|
|
993
|
+
" })",
|
|
994
|
+
" nitroApp.hooks.hook('close', async () => {",
|
|
995
|
+
" const result = await runtimeInstallation",
|
|
996
|
+
" if ('controller' in result) await result.controller.close()",
|
|
997
|
+
" })"
|
|
998
|
+
] : [],
|
|
999
|
+
"})",
|
|
1000
|
+
"",
|
|
1001
|
+
`export const vitehubScheduleDefinitions = ${JSON.stringify(options.providerDefinitions.map((definition) => definition.name))}`,
|
|
1002
|
+
""
|
|
1003
|
+
].join("\n");
|
|
1004
|
+
}
|
|
1005
|
+
function renderNitroCloudflareModule(crons) {
|
|
1006
|
+
return [
|
|
1007
|
+
`const crons = ${JSON.stringify(crons)}`,
|
|
1008
|
+
"",
|
|
1009
|
+
"function dedupeCloudflareCrons(nitro) {",
|
|
1010
|
+
" const wrangler = nitro.options.cloudflare?.wrangler",
|
|
1011
|
+
" if (!wrangler?.triggers || !Array.isArray(wrangler.triggers.crons)) return",
|
|
1012
|
+
" wrangler.triggers.crons = [...new Set(wrangler.triggers.crons.filter((cron) => typeof cron === 'string'))]",
|
|
1013
|
+
"}",
|
|
1014
|
+
"",
|
|
1015
|
+
"export default function vitehubScheduleModule(nitro) {",
|
|
1016
|
+
" nitro.options.cloudflare ??= {}",
|
|
1017
|
+
" nitro.options.cloudflare.wrangler ??= {}",
|
|
1018
|
+
" nitro.options.cloudflare.wrangler.triggers ??= {}",
|
|
1019
|
+
" const existingCrons = Array.isArray(nitro.options.cloudflare.wrangler.triggers.crons) ? nitro.options.cloudflare.wrangler.triggers.crons : []",
|
|
1020
|
+
" nitro.options.cloudflare.wrangler.triggers.crons = [...new Set([...existingCrons, ...crons])]",
|
|
1021
|
+
" nitro.hooks.hook('build:before', dedupeCloudflareCrons)",
|
|
1022
|
+
"}",
|
|
1023
|
+
""
|
|
1024
|
+
].join("\n");
|
|
1025
|
+
}
|
|
1026
|
+
function renderScheduleRegistryTypes(importBase = schedulePackageName) {
|
|
1027
|
+
return [
|
|
1028
|
+
`import type { ScheduleRegistryDefinition } from ${JSON.stringify(importBase)}`,
|
|
1029
|
+
"",
|
|
1030
|
+
"declare const registry: Record<string, () => Promise<ScheduleRegistryDefinition | { default?: ScheduleRegistryDefinition }>>",
|
|
1031
|
+
"export default registry",
|
|
1032
|
+
""
|
|
1033
|
+
].join("\n");
|
|
1034
|
+
}
|
|
1035
|
+
async function writeNitroSchedulePlugin(root, options) {
|
|
1036
|
+
const pluginFile = resolve(root, generatedNitroSchedulePlugin);
|
|
1037
|
+
const moduleFile = resolve(root, generatedNitroCloudflareModule);
|
|
1038
|
+
const providerRegistryFile = resolve(root, registryImportAnchor);
|
|
1039
|
+
const runtimeRegistryFile = resolve(root, generatedNitroRuntimeRegistry);
|
|
1040
|
+
const staticRegistryFile = resolve(root, generatedNitroStaticRegistry);
|
|
1041
|
+
await mkdir(dirname(pluginFile), { recursive: true });
|
|
1042
|
+
const writes = [writeFile(pluginFile, renderNitroSchedulePlugin({
|
|
1043
|
+
importBase: options.importBase,
|
|
1044
|
+
pluginFile,
|
|
1045
|
+
processRuntime: options.processRuntime,
|
|
1046
|
+
providerDefinitions: options.providerDefinitions,
|
|
1047
|
+
providerRegistryFile,
|
|
1048
|
+
runtimeRegistryFile,
|
|
1049
|
+
staticRegistryFile,
|
|
1050
|
+
runtimeImport: options.runtimeImport
|
|
1051
|
+
}), "utf8")];
|
|
1052
|
+
if (options.processRuntime) {
|
|
1053
|
+
writes.push(writeFile(runtimeRegistryFile, createRuntimeRegistryContents(runtimeRegistryFile, options.runtimeDefinitions), "utf8"));
|
|
1054
|
+
writes.push(writeFile(runtimeRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase), "utf8"));
|
|
1055
|
+
writes.push(writeFile(staticRegistryFile, createRuntimeRegistryContents(staticRegistryFile, options.staticDefinitions), "utf8"));
|
|
1056
|
+
writes.push(writeFile(staticRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase), "utf8"));
|
|
1057
|
+
}
|
|
1058
|
+
if (options.providerDefinitions.length > 0) {
|
|
1059
|
+
await mkdir(dirname(providerRegistryFile), { recursive: true });
|
|
1060
|
+
writes.push(writeFile(providerRegistryFile, createRuntimeRegistryContents(providerRegistryFile, options.providerDefinitions), "utf8"));
|
|
1061
|
+
writes.push(writeFile(providerRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase), "utf8"));
|
|
1062
|
+
writes.push(writeFile(moduleFile, renderNitroCloudflareModule(options.crons), "utf8"));
|
|
1063
|
+
}
|
|
1064
|
+
await Promise.all(writes);
|
|
1065
|
+
return generatedNitroSchedulePlugin;
|
|
1066
|
+
}
|
|
1067
|
+
function hasServerScheduleDefinitions(definitions) {
|
|
1068
|
+
return definitions.some((definition) => definition.runtimeOnly !== true && definition.source === "server-schedules");
|
|
1069
|
+
}
|
|
1070
|
+
function hasViteSuffixScheduleDefinitions(definitions) {
|
|
1071
|
+
return definitions.some((definition) => definition.runtimeOnly !== true && definition.source === "vite-suffix");
|
|
1072
|
+
}
|
|
1073
|
+
function selectNitroScheduleDefinitions(definitions, options) {
|
|
1074
|
+
if (options.providerOutput === false || options.providerOutput === "standalone") return [];
|
|
1075
|
+
const staticDefinitions = definitions.filter((definition) => definition.runtimeOnly !== true);
|
|
1076
|
+
if (options.providerOutput === "nitro") return staticDefinitions;
|
|
1077
|
+
return staticDefinitions.filter((definition) => definition.source === "server-schedules");
|
|
1078
|
+
}
|
|
1079
|
+
function selectStandaloneProviderSource(definitions, options) {
|
|
1080
|
+
if (options.providerOutput === "auto" || options.providerOutput === void 0) return hasServerScheduleDefinitions(definitions) ? "vite-suffix" : void 0;
|
|
1081
|
+
}
|
|
1082
|
+
function shouldInstallNitroSchedulePlugin(definitions, options) {
|
|
1083
|
+
return selectNitroScheduleDefinitions(definitions, options).length > 0 || options.runtime !== void 0;
|
|
1084
|
+
}
|
|
1085
|
+
function shouldEmitStandaloneProviderOutput(definitions, options) {
|
|
1086
|
+
if (options.providerOutput === false || options.providerOutput === "nitro") return false;
|
|
1087
|
+
if (options.providerOutput === "standalone") return definitions.some((definition) => definition.runtimeOnly !== true);
|
|
1088
|
+
if (hasServerScheduleDefinitions(definitions)) return hasViteSuffixScheduleDefinitions(definitions);
|
|
1089
|
+
return definitions.some((definition) => definition.runtimeOnly !== true);
|
|
1090
|
+
}
|
|
1091
|
+
async function createScheduleNitroConfig(options = {}) {
|
|
1092
|
+
const processRuntime = resolveProcessRuntimeOptions(options.runtime);
|
|
1093
|
+
const roots = resolveSchedulePluginRoots(options.root || process.cwd(), options);
|
|
1094
|
+
const definitions = discoverScheduleDefinitions({
|
|
1095
|
+
rootDir: roots.viteRoot,
|
|
1096
|
+
serverDirs: options.serverDirs,
|
|
1097
|
+
serverRootDir: roots.projectRoot
|
|
1098
|
+
});
|
|
1099
|
+
if (!shouldInstallNitroSchedulePlugin(definitions, options)) return null;
|
|
1100
|
+
const nitroDefinitions = processRuntime && options.providerOutput !== "nitro" ? [] : selectNitroScheduleDefinitions(definitions, options);
|
|
1101
|
+
const crons = options.command === "build" ? [...new Set((await readDefinitionCrons(nitroDefinitions)).values())] : [];
|
|
1102
|
+
const nitroDefinitionNames = new Set(nitroDefinitions.map((definition) => definition.name));
|
|
1103
|
+
const plugin = await writeNitroSchedulePlugin(roots.projectRoot, {
|
|
1104
|
+
crons,
|
|
1105
|
+
importBase: options.importBase,
|
|
1106
|
+
processRuntime,
|
|
1107
|
+
providerDefinitions: nitroDefinitions,
|
|
1108
|
+
runtimeDefinitions: definitions,
|
|
1109
|
+
staticDefinitions: definitions.filter((definition) => definition.runtimeOnly !== true && !nitroDefinitionNames.has(definition.name) && !(processRuntime && options.providerOutput === "standalone")),
|
|
1110
|
+
runtimeImport: options.runtimeImport
|
|
1111
|
+
});
|
|
1112
|
+
return mergeNitroScheduleConfig(options.nitro, {
|
|
1113
|
+
crons,
|
|
1114
|
+
plugin,
|
|
1115
|
+
providerWake: nitroDefinitions.length > 0
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
function hubSchedule(options = {}) {
|
|
1119
|
+
const internalOptions = options;
|
|
1120
|
+
let resolved;
|
|
1121
|
+
let emitStandaloneProviderOutput = true;
|
|
1122
|
+
let projectRoot;
|
|
1123
|
+
let standaloneProviderSource;
|
|
1124
|
+
let serverDirs;
|
|
1125
|
+
let viteRoot;
|
|
1126
|
+
function discoverViteSchedules() {
|
|
1127
|
+
if (!projectRoot || !viteRoot) return [];
|
|
1128
|
+
return discoverScheduleDefinitions({
|
|
1129
|
+
mode: "vite-suffix",
|
|
1130
|
+
rootDir: viteRoot,
|
|
1131
|
+
serverDirs,
|
|
1132
|
+
serverRootDir: projectRoot
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
function discoverRegistrySchedules() {
|
|
1136
|
+
if (!projectRoot || !viteRoot) return [];
|
|
1137
|
+
return discoverScheduleDefinitions({
|
|
1138
|
+
rootDir: viteRoot,
|
|
1139
|
+
serverDirs,
|
|
1140
|
+
serverRootDir: projectRoot
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
function createRegistryContents() {
|
|
1144
|
+
const definitions = discoverRegistrySchedules();
|
|
1145
|
+
return createRuntimeRegistryContents(projectRoot ? resolve(projectRoot, registryImportAnchor) : registryImportAnchor, definitions);
|
|
1146
|
+
}
|
|
1147
|
+
function createTargetsContents() {
|
|
1148
|
+
return createScheduleTargetsContents(discoverViteSchedules(), { types: false });
|
|
1149
|
+
}
|
|
1150
|
+
return {
|
|
1151
|
+
name: SCHEDULE_VITE_PLUGIN_NAME,
|
|
1152
|
+
enforce: "pre",
|
|
1153
|
+
async config(config, env) {
|
|
1154
|
+
serverDirs = config["__vitehubServerDirs"] ?? serverDirs;
|
|
1155
|
+
const roots = resolveSchedulePluginRoots(config.root || process.cwd(), options);
|
|
1156
|
+
const definitions = discoverScheduleDefinitions({
|
|
1157
|
+
rootDir: roots.viteRoot,
|
|
1158
|
+
serverDirs,
|
|
1159
|
+
serverRootDir: roots.projectRoot
|
|
1160
|
+
});
|
|
1161
|
+
emitStandaloneProviderOutput = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options);
|
|
1162
|
+
standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
|
|
1163
|
+
if (!shouldInstallNitroSchedulePlugin(definitions, options)) return null;
|
|
1164
|
+
const nitro = await createScheduleNitroConfig({
|
|
1165
|
+
...options,
|
|
1166
|
+
command: env.command,
|
|
1167
|
+
nitro: config.nitro,
|
|
1168
|
+
root: config.root || process.cwd(),
|
|
1169
|
+
serverDirs
|
|
1170
|
+
});
|
|
1171
|
+
if (!nitro) return null;
|
|
1172
|
+
config.nitro = nitro;
|
|
1173
|
+
},
|
|
1174
|
+
configResolved(config) {
|
|
1175
|
+
resolved = config;
|
|
1176
|
+
const roots = resolveSchedulePluginRoots(config.root, options);
|
|
1177
|
+
projectRoot = roots.projectRoot;
|
|
1178
|
+
viteRoot = roots.viteRoot;
|
|
1179
|
+
},
|
|
1180
|
+
configEnvironment(name, config) {
|
|
1181
|
+
if (!isServerEnvironment(name, config)) return;
|
|
1182
|
+
return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
|
|
1183
|
+
},
|
|
1184
|
+
handleHotUpdate(context) {
|
|
1185
|
+
const file = normalize(context.file).replace(/\\/g, "/");
|
|
1186
|
+
const serverSchedule = (serverDirs ?? [resolve(projectRoot ?? resolved?.root ?? context.server.config.root, "server")]).map((directory) => `${resolve(directory, "schedules").replace(/\\/g, "/")}/`).some((directory) => file.startsWith(directory) && /\.(?:c|m)?[jt]s$/i.test(file.slice(directory.length)));
|
|
1187
|
+
if (!/\.schedule\.(?:c|m)?[jt]s$/i.test(file) && !serverSchedule) return;
|
|
1188
|
+
const registryModule = context.server.moduleGraph.getModuleById(RESOLVED_SCHEDULE_REGISTRY_ID);
|
|
1189
|
+
if (registryModule) context.server.moduleGraph.invalidateModule(registryModule);
|
|
1190
|
+
const targetsModule = context.server.moduleGraph.getModuleById(RESOLVED_SCHEDULE_TARGETS_ID);
|
|
1191
|
+
if (targetsModule) context.server.moduleGraph.invalidateModule(targetsModule);
|
|
1192
|
+
},
|
|
1193
|
+
resolveId(id) {
|
|
1194
|
+
if (id === SCHEDULE_REGISTRY_ID) return RESOLVED_SCHEDULE_REGISTRY_ID;
|
|
1195
|
+
if (id === "#vitehub/schedule/targets") return RESOLVED_SCHEDULE_TARGETS_ID;
|
|
1196
|
+
},
|
|
1197
|
+
load(id) {
|
|
1198
|
+
if (id === RESOLVED_SCHEDULE_REGISTRY_ID) return createRegistryContents();
|
|
1199
|
+
if (id === RESOLVED_SCHEDULE_TARGETS_ID) return createTargetsContents();
|
|
1200
|
+
},
|
|
1201
|
+
async closeBundle() {
|
|
1202
|
+
if (!resolved || shouldSkipViteProviderBuild(resolved.command, getViteMode())) return;
|
|
1203
|
+
await generateProviderOutputs({
|
|
1204
|
+
bundleAlias: {
|
|
1205
|
+
...resolveStringAliases(resolved),
|
|
1206
|
+
...internalOptions.providerImportAliases
|
|
1207
|
+
},
|
|
1208
|
+
clientOutDir: resolved.build.outDir,
|
|
1209
|
+
...!emitStandaloneProviderOutput ? { definitions: [] } : {},
|
|
1210
|
+
rootDir: resolved.root,
|
|
1211
|
+
runtimeImport: internalOptions.runtimeImport,
|
|
1212
|
+
source: standaloneProviderSource
|
|
1213
|
+
});
|
|
1214
|
+
}
|
|
1215
|
+
};
|
|
1216
|
+
}
|
|
1217
|
+
//#endregion
|
|
1218
|
+
export { hubSchedule as n, createScheduleNitroConfig as t };
|