@vite-hub/schedule 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +30 -9
  2. package/dist/cron-D0mqg3ql.js +22 -0
  3. package/dist/definition.d.ts +1 -1
  4. package/dist/definition.js +4 -5
  5. package/dist/{due-D-0trD1g.js → due-DXgXKgzg.js} +1 -1
  6. package/dist/{error-diagnostics-kKXseq8d.js → error-diagnostics-CsiNo_oI.js} +3 -3
  7. package/dist/{error-diagnostics-B1AaIGWP.js → error-diagnostics-KvK9MX6w.js} +14 -2
  8. package/dist/{started-errors-IG9DlT2A.js → execute-DHApCpbQ.js} +8 -35
  9. package/dist/index.d.ts +16 -8
  10. package/dist/index.js +1 -51
  11. package/dist/{kv-storage-hI2IOjb5.d.ts → kv-storage-CKSSQ6Fk.d.ts} +7 -3
  12. package/dist/{kv-storage-Dsr3TL9c.js → kv-storage-CszEkof6.js} +2 -2
  13. package/dist/{object-CAK6UYR5.js → object-DNOrQSl5.js} +5 -1
  14. package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-Blwi3jQF.d.ts} +1 -0
  15. package/dist/{operations-BTUQeba1.js → operations-Bog78pOZ.js} +33 -14
  16. package/dist/operations.d.ts +2 -2
  17. package/dist/operations.js +8 -6
  18. package/dist/os.js +3 -3
  19. package/dist/runtime/console.js +25 -11
  20. package/dist/runtime/kv.d.ts +1 -1
  21. package/dist/runtime/kv.js +1 -1
  22. package/dist/runtime/process.d.ts +1 -1
  23. package/dist/runtime/process.js +41 -22
  24. package/dist/runtime/state.d.ts +2 -2
  25. package/dist/runtime/state.js +1 -1
  26. package/dist/runtime/static.d.ts +1 -1
  27. package/dist/runtime/static.js +2 -2
  28. package/dist/runtime.d.ts +6 -6
  29. package/dist/runtime.js +5 -5
  30. package/dist/{started-B1Se_Iwo.js → started-Ck0Wu5Oc.js} +55 -10
  31. package/dist/{started-Bzvr4t5f.js → started-adRbWkWd.js} +7 -5
  32. package/dist/started-errors-D6CnKMqD.js +32 -0
  33. package/dist/state-BoDrff6R.js +586 -0
  34. package/dist/{state-BDEDVlyr.d.ts → state-CRQQfd8h.d.ts} +24 -5
  35. package/dist/{static-DeRvJqcQ.d.ts → static-BFV4x94g.d.ts} +1 -1
  36. package/dist/{static-Bg7Jj92L.js → static-D4nN8HTx.js} +8 -6
  37. package/dist/{store-CEv3cScg.d.ts → store-TOayO0NL.d.ts} +6 -3
  38. package/dist/{types-DTVPVY5O.d.ts → types-Wllh0U8N.d.ts} +35 -4
  39. package/dist/vite.d.ts +4 -2
  40. package/dist/vite.js +561 -187
  41. package/package.json +11 -4
  42. package/dist/started-name-w6n9uDdt.js +0 -4
  43. package/dist/state-BZLy46UJ.js +0 -427
  44. package/dist/{cron-BT3ef48f.js → cron-imqlBgO-.js} +1 -1
package/dist/vite.js CHANGED
@@ -1,22 +1,25 @@
1
1
  import { r as __toESM } from "./rolldown-runtime-DegdyBIC.js";
2
- import { a as parseCronFields, l as invariant, u as invariantError } from "./cron-BT3ef48f.js";
2
+ import { a as parseCronFields, l as invariant, u as invariantError } from "./cron-imqlBgO-.js";
3
3
  import { a as relative$1, i as isAbsolute$1, n as relativeDefinitionFile, o as resolve$1, r as dirname$1 } from "./inspect-CW0qwt9p.js";
4
- import { t as internalErrorDiagnostics } from "./error-diagnostics-kKXseq8d.js";
5
- import { n as isRecordOrFunction, t as isRecord$1 } from "./object-CAK6UYR5.js";
6
- import { t as scheduleErrorDiagnostics } from "./error-diagnostics-B1AaIGWP.js";
7
- import { t as startedSchedulesTickName } from "./started-name-w6n9uDdt.js";
4
+ import { t as internalErrorDiagnostics } from "./error-diagnostics-CsiNo_oI.js";
5
+ import { n as isRecord, r as isRecordOrFunction, t as isObject } from "./object-DNOrQSl5.js";
6
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-KvK9MX6w.js";
7
+ import { n as parseScheduleCronExpression, t as assertScheduleCronFields } from "./cron-D0mqg3ql.js";
8
+ import { m as startedSchedulesTickName } from "./static-D4nN8HTx.js";
8
9
  import { t as isIanaTimeZone } from "./time-zone-pMp_g8Uu.js";
9
- import { i as timeZoneOffsetMinutes, t as cronWithWeekdayNames } from "./due-D-0trD1g.js";
10
+ import { i as timeZoneOffsetMinutes, t as cronWithWeekdayNames } from "./due-DXgXKgzg.js";
10
11
  import { scheduleConsoleTiming } from "./runtime/console.js";
12
+ import "./state-BoDrff6R.js";
11
13
  import { builtinModules, createRequire, isBuiltin } from "node:module";
12
14
  import { formatDiagnostic } from "nostics";
13
- import { parseCronExpression } from "cron-schedule";
15
+ import { parseDuration } from "@vite-hub/runtime";
14
16
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
15
17
  import { tmpdir } from "node:os";
16
18
  import { basename, dirname, extname, isAbsolute, join, normalize, parse, relative, resolve, sep } from "node:path";
17
19
  import { fileURLToPath, pathToFileURL } from "node:url";
18
20
  import { access, chmod, copyFile, cp, lstat, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
19
21
  import { createHash, randomUUID } from "node:crypto";
22
+ import MagicString from "magic-string";
20
23
  import { isDeepStrictEqual } from "node:util";
21
24
  import { parseSync } from "vite";
22
25
  // ../internal/src/build/vite.ts
@@ -318,12 +321,32 @@ function mergeOwnedArrays(existing, value, arrays) {
318
321
  const next = { ...value };
319
322
  for (const [field, ownership] of Object.entries(arrays ?? {})) {
320
323
  const incoming = Array.isArray(value[field]) ? value[field] : [];
321
- const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
324
+ const unowned = preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming);
325
+ const merged = ownership.key !== void 0 && ownership.preserveOrder && Array.isArray(existing[field]) ? mergeOrderedEntries(existing[field], unowned, incoming, ownership.key) : [...unowned, ...incoming];
322
326
  if (merged.length) next[field] = merged;
323
327
  else delete next[field];
324
328
  }
325
329
  return next;
326
330
  }
331
+ function mergeOrderedEntries(current, unowned, incoming, key) {
332
+ const preserved = new Set(unowned);
333
+ const replacements = new Map(incoming.flatMap((entry) => {
334
+ const identity = getKeyedArrayEntryValue(entry, key);
335
+ return identity === void 0 ? [] : [[identity, entry]];
336
+ }));
337
+ return [...current.flatMap((entry) => {
338
+ if (preserved.has(entry)) return [entry];
339
+ const identity = getKeyedArrayEntryValue(entry, key);
340
+ if (identity === void 0) return [];
341
+ const replacement = replacements.get(identity);
342
+ if (replacement === void 0) return [];
343
+ replacements.delete(identity);
344
+ return [replacement];
345
+ }), ...incoming.filter((entry) => {
346
+ const identity = getKeyedArrayEntryValue(entry, key);
347
+ return identity === void 0 || replacements.has(identity);
348
+ })];
349
+ }
327
350
  async function persistProviderJsonRecord(file, value, removeIfEmpty) {
328
351
  if (removeIfEmpty && !Object.keys(value).length) {
329
352
  await rm(file, { force: true });
@@ -343,19 +366,31 @@ async function writeProviderOutputConfig(file, value, ownership = {}, options =
343
366
  function mergeProviderOutputConfig(existing, value, ownership = {}) {
344
367
  assertProviderJsonRecord(existing);
345
368
  assertProviderJsonRecord(value);
346
- return {
369
+ const next = {
347
370
  ...deleteOwnedFields(existing, ownership),
348
371
  ...mergeOwnedArrays(existing, value, ownership.arrays)
349
372
  };
373
+ for (const [field, childOwnership] of Object.entries(ownership.objects ?? {})) {
374
+ const current = existing[field];
375
+ const incoming = value[field];
376
+ const merged = mergeProviderOutputConfig(isProviderJsonRecord(current) ? current : {}, isProviderJsonRecord(incoming) ? incoming : {}, childOwnership);
377
+ if (Object.keys(merged).length) next[field] = merged;
378
+ else delete next[field];
379
+ }
380
+ return next;
350
381
  }
351
382
  function stringifyProviderOutputConfig(value) {
352
383
  assertProviderJsonRecord(value);
353
384
  return JSON.stringify(value, null, 2);
354
385
  }
355
386
  async function cleanProviderOutputConfig(file, ownership) {
356
- if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
387
+ if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length && !Object.keys(ownership.objects ?? {}).length) return;
357
388
  const existing = await readProviderJsonRecord(file);
358
389
  if (!existing) return;
390
+ const next = cleanOwnedFields(existing, ownership);
391
+ if (next) await persistProviderJsonRecord(file, next, true);
392
+ }
393
+ function cleanOwnedFields(existing, ownership) {
359
394
  const next = deleteOwnedFields(existing, ownership, true);
360
395
  let changed = (ownership.keys ?? []).some((key) => key in existing);
361
396
  for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
@@ -367,8 +402,16 @@ async function cleanProviderOutputConfig(file, ownership) {
367
402
  changed ||= retained.length > 0 || !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
368
403
  if (preserved.length) next[field] = preserved;
369
404
  }
370
- if (!changed) return;
371
- await persistProviderJsonRecord(file, next, true);
405
+ for (const [field, childOwnership] of Object.entries(ownership.objects ?? {})) {
406
+ const current = existing[field];
407
+ if (!isProviderJsonRecord(current)) continue;
408
+ const cleaned = cleanOwnedFields(current, childOwnership);
409
+ if (!cleaned) continue;
410
+ changed = true;
411
+ if (Object.keys(cleaned).length) next[field] = cleaned;
412
+ else delete next[field];
413
+ }
414
+ if (changed) return next;
372
415
  }
373
416
  // ../internal/src/build/user-entry.ts
374
417
  function toSafeAppName(rootDir) {
@@ -491,9 +534,9 @@ function isFileResolution(resolved) {
491
534
  }
492
535
  function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
493
536
  if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
494
- if (!Array.isArray(exportsValue) && !isRecord$1(exportsValue)) return [];
537
+ if (!Array.isArray(exportsValue) && !isRecord(exportsValue)) return [];
495
538
  const candidates = [];
496
- const exportEntries = isRecord$1(exportsValue) && Object.keys(exportsValue).some((exportKey) => exportKey.startsWith(".")) ? Object.entries(exportsValue) : [[".", exportsValue]];
539
+ const exportEntries = isRecord(exportsValue) && Object.keys(exportsValue).some((exportKey) => exportKey.startsWith(".")) ? Object.entries(exportsValue) : [[".", exportsValue]];
497
540
  for (const [exportKey, target] of exportEntries) {
498
541
  const targets = [target];
499
542
  while (targets.length) {
@@ -510,7 +553,7 @@ function collectPackageExportCandidates(packageName, exportsValue, packageRelati
510
553
  if (wildcard === void 0) continue;
511
554
  candidates.push(`${packageName}${exportKey.slice(1).replace("*", wildcard)}`);
512
555
  } else if (Array.isArray(value)) targets.push(...value);
513
- else if (isRecord$1(value)) targets.push(...Object.values(value));
556
+ else if (isRecord(value)) targets.push(...Object.values(value));
514
557
  }
515
558
  }
516
559
  return candidates;
@@ -616,7 +659,7 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir, workingDir, resolve
616
659
  else if (resolutionScope) {
617
660
  const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
618
661
  const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
619
- if (!isRecord$1(parsedPackageJson)) return;
662
+ if (!isRecord(parsedPackageJson)) return;
620
663
  const packageJson = parsedPackageJson;
621
664
  if (packageJson.exports === void 0 && !alias.prefix) {
622
665
  const resolvedCandidate = await resolveWithContext(alias.specifier);
@@ -3323,6 +3366,150 @@ async function copyRuntimePackageFiles(packageDir, targetDir) {
3323
3366
  await unlessGone(() => copyFile(join(packageDir, path), target));
3324
3367
  }
3325
3368
  }
3369
+ // ../internal/src/source-files.ts
3370
+ const ignoredDirs = /* @__PURE__ */ new Set([
3371
+ "node_modules",
3372
+ "dist",
3373
+ ".output",
3374
+ ".nuxt",
3375
+ ".vercel",
3376
+ ".git",
3377
+ ".vitehub"
3378
+ ]);
3379
+ const racyWindowNs = 2000000000n;
3380
+ const storeKey = Symbol.for("vite-hub.source-files.v1");
3381
+ function store() {
3382
+ const existing = Reflect.get(globalThis, storeKey);
3383
+ if (isStore(existing)) return existing;
3384
+ const created = {
3385
+ derived: /* @__PURE__ */ new Map(),
3386
+ texts: /* @__PURE__ */ new Map(),
3387
+ trees: /* @__PURE__ */ new Map()
3388
+ };
3389
+ Reflect.set(globalThis, storeKey, created);
3390
+ return created;
3391
+ }
3392
+ function isStore(value) {
3393
+ return typeof value === "object" && value !== null && "texts" in value && "trees" in value && "derived" in value;
3394
+ }
3395
+ function errorCode(error) {
3396
+ return typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
3397
+ }
3398
+ function statOrMissing(path) {
3399
+ try {
3400
+ return statSync(path, { bigint: true });
3401
+ } catch (error) {
3402
+ if (errorCode(error) === "ENOENT" || errorCode(error) === "ENOTDIR") return;
3403
+ throw error;
3404
+ }
3405
+ }
3406
+ function signature(stats) {
3407
+ return `${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
3408
+ }
3409
+ function isSettled(stats) {
3410
+ const changed = stats.mtimeNs > stats.ctimeNs ? stats.mtimeNs : stats.ctimeNs;
3411
+ return BigInt(Date.now()) * 1000000n - changed > racyWindowNs;
3412
+ }
3413
+ function readDirEntries(root) {
3414
+ try {
3415
+ return readdirSync(root, { withFileTypes: true });
3416
+ } catch (error) {
3417
+ if (errorCode(error) === "ENOENT") return [];
3418
+ throw error;
3419
+ }
3420
+ }
3421
+ function walkTree(root, directories, files, nested = false) {
3422
+ const before = statOrMissing(root);
3423
+ let trusted = before !== void 0 && isSettled(before);
3424
+ if (before) directories.set(root, signature(before));
3425
+ if (nested && existsSync(resolve$1(root, ".git"))) return trusted;
3426
+ for (const entry of readDirEntries(root)) {
3427
+ const path = resolve$1(root, entry.name);
3428
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
3429
+ if (entry.name.startsWith(".") || ignoredDirs.has(entry.name)) continue;
3430
+ if (!walkTree(path, directories, files, true)) trusted = false;
3431
+ continue;
3432
+ }
3433
+ if (entry.isFile()) files.push({
3434
+ hidden: entry.name.startsWith("."),
3435
+ name: entry.name,
3436
+ path
3437
+ });
3438
+ }
3439
+ return trusted;
3440
+ }
3441
+ function isCurrent(tree) {
3442
+ for (const [directory, stored] of tree.directories) {
3443
+ const stats = statOrMissing(directory);
3444
+ if (!stats || signature(stats) !== stored) return false;
3445
+ }
3446
+ return true;
3447
+ }
3448
+ function sourceTree(root) {
3449
+ const trees = store().trees;
3450
+ const cached = trees.get(root);
3451
+ if (cached && isCurrent(cached)) return cached;
3452
+ const directories = /* @__PURE__ */ new Map();
3453
+ const files = [];
3454
+ const trusted = walkTree(root, directories, files);
3455
+ files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
3456
+ const tree = {
3457
+ directories,
3458
+ files
3459
+ };
3460
+ if (trusted) trees.set(root, tree);
3461
+ else trees.delete(root);
3462
+ return tree;
3463
+ }
3464
+ /**
3465
+ * The files below `root` whose name matches `predicate`, sorted by path. The walk skips hidden folders, Git
3466
+ * repositories, and build output folders such as `node_modules`, `dist`, and `.vitehub`. Hidden files need
3467
+ * `includeHidden`. Symbolic links are skipped.
3468
+ */
3469
+ function listSourceTreeFiles(root, predicate, options = {}) {
3470
+ const files = [];
3471
+ for (const file of sourceTree(resolve$1(root)).files) {
3472
+ if (file.hidden && !options.includeHidden) continue;
3473
+ if (predicate(file.name)) files.push(file.path);
3474
+ }
3475
+ return files;
3476
+ }
3477
+ /** The UTF-8 text of a source file. A file that did not change since the last read is not read again. */
3478
+ function readSourceText(file) {
3479
+ const path = resolve$1(file);
3480
+ const texts = store().texts;
3481
+ const stats = statOrMissing(path);
3482
+ if (!stats) return readFileSync(path, "utf8");
3483
+ const current = signature(stats);
3484
+ const cached = texts.get(path);
3485
+ if (cached?.trusted && cached.signature === current) return cached.text;
3486
+ const read = readFileSync(path, "utf8");
3487
+ const text = cached?.text === read ? cached.text : read;
3488
+ texts.set(path, {
3489
+ signature: current,
3490
+ text,
3491
+ trusted: isSettled(stats)
3492
+ });
3493
+ return text;
3494
+ }
3495
+ /**
3496
+ * A value that `compute` derives from the text of a source file, such as its syntax tree. The value is computed again
3497
+ * only when the text changes. `kind` separates the values of different callers for one file. The last two texts of a
3498
+ * file are kept, because some callers read both the file and its transformed code.
3499
+ */
3500
+ function deriveFromSource(kind, file, source, compute) {
3501
+ const derived = store().derived;
3502
+ const key = `${kind}\0${file}`;
3503
+ const entries = derived.get(key) ?? [];
3504
+ const cached = entries.find((entry) => entry.source === source);
3505
+ if (cached) return cached.value;
3506
+ const value = compute();
3507
+ derived.set(key, [{
3508
+ source,
3509
+ value
3510
+ }, ...entries.slice(0, 1)]);
3511
+ return value;
3512
+ }
3326
3513
  // ../internal/src/build/scan-module.ts
3327
3514
  /**
3328
3515
  * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
@@ -3346,6 +3533,17 @@ function scanModule(source, file = "module.ts") {
3346
3533
  source
3347
3534
  };
3348
3535
  }
3536
+ /**
3537
+ * Reads and parses a source file once for each change of its text. Callers share the result, so they must not change
3538
+ * the syntax tree.
3539
+ */
3540
+ function scanSourceFile(file) {
3541
+ return scanModuleText(readSourceText(file), file);
3542
+ }
3543
+ /** `scanModule` with a result that is shared while `source` stays the same for `file`. */
3544
+ function scanModuleText(source, file) {
3545
+ return deriveFromSource("scan-module", file, source, () => scanModule(source, file));
3546
+ }
3349
3547
  /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
3350
3548
  function unwrapExpression(node) {
3351
3549
  while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
@@ -3718,6 +3916,9 @@ const ignoredSourceDirectories = /* @__PURE__ */ new Set([
3718
3916
  "node_modules"
3719
3917
  ]);
3720
3918
  const ignoredGeneratedDirectories = /* @__PURE__ */ new Set([".vitehub", ".vitest-tmp"]);
3919
+ function crossesIgnoredDirectory(parent, child) {
3920
+ return relative(parent, child).split(sep).some((segment) => ignoredSourceDirectories.has(segment) || ignoredGeneratedDirectories.has(segment));
3921
+ }
3721
3922
  function isTransientSourceDirectory(path) {
3722
3923
  return basename(path).startsWith(".drizzle-generate-");
3723
3924
  }
@@ -3813,8 +4014,26 @@ async function linkDependencies(source, target, resolveLinkTarget = (source) =>
3813
4014
  await symlink(resolveLinkTarget(resolvedSourceEntry), targetEntry, process.platform === "win32" ? "junction" : "dir");
3814
4015
  }
3815
4016
  }
3816
- /** Removes retained provider output after readers release it, tolerating transient filesystem contention. */
3817
- async function removeProviderOutputArtifactDir(path) {
4017
+ const keptFailedProviderOutputArtifactDirs = /* @__PURE__ */ new Set();
4018
+ function failureText(failure) {
4019
+ return failure instanceof Error ? `${failure.message}\n${failure.stack ?? ""}` : String(failure);
4020
+ }
4021
+ /**
4022
+ * Removes retained provider output after readers release it, tolerating transient filesystem contention. Pass the
4023
+ * build failure when a failed build discards its generation: with `VITEHUB_KEEP_FAILED_BUILD=1` the folder stays
4024
+ * for inspection.
4025
+ */
4026
+ async function removeProviderOutputArtifactDir(path, failure) {
4027
+ if (failure !== void 0) {
4028
+ const shown = relative(process.cwd(), path) || path;
4029
+ if (/^(?:1|true)$/i.test(process.env.VITEHUB_KEEP_FAILED_BUILD ?? "")) {
4030
+ if (!existsSync(path)) return;
4031
+ if (!keptFailedProviderOutputArtifactDirs.has(path)) console.warn(`[vitehub] The build failed. ViteHub kept its provider sources in ${shown} so you can inspect them. Remove the folder when you are done.`);
4032
+ keptFailedProviderOutputArtifactDirs.add(path);
4033
+ return;
4034
+ }
4035
+ if (failureText(failure).includes(basename(path))) console.warn(`[vitehub] The build error names files in ${shown}, which ViteHub removes after a failed build. Set VITEHUB_KEEP_FAILED_BUILD=1 to keep them.`);
4036
+ }
3818
4037
  await rm(path, {
3819
4038
  force: true,
3820
4039
  maxRetries: 5,
@@ -4071,7 +4290,7 @@ function traceComputedModuleSources(file, source, onRuntimePackageRequest) {
4071
4290
  }
4072
4291
  return paths;
4073
4292
  }
4074
- async function traceImportedSources(paths, root, configuredRoots) {
4293
+ async function traceImportedSources(paths, root, configuredRoots, aliases) {
4075
4294
  const entries = paths.filter((path) => traceableSourceExtensions.has(extname(path)));
4076
4295
  if (!entries.length) return /* @__PURE__ */ new Set();
4077
4296
  const { rolldown } = await importRolldown();
@@ -4212,7 +4431,7 @@ async function traceImportedSources(paths, root, configuredRoots) {
4212
4431
  if (log.code === "UNRESOLVED_IMPORT") throw Object.assign(new Error(log.message), { code: log.code });
4213
4432
  },
4214
4433
  platform: variant.platform,
4215
- plugins: [tracePlugin],
4434
+ plugins: [createResolvedAliasPlugin(aliases, configuredRoots[0] ?? root, root, false), tracePlugin],
4216
4435
  resolve: { conditionNames: variant.conditions }
4217
4436
  });
4218
4437
  try {
@@ -4358,6 +4577,11 @@ function resolveTsconfigReference(config, reference) {
4358
4577
  if (existsSync(resolved)) return resolved;
4359
4578
  } catch {}
4360
4579
  }
4580
+ function resolveTsconfigProjectReference(config, reference) {
4581
+ const path = resolve(dirname(config), reference);
4582
+ const file = existsSync(path) && statSync(path).isDirectory() ? resolve(path, "tsconfig.json") : path;
4583
+ return existsSync(file) && statSync(file).isFile() ? file : void 0;
4584
+ }
4361
4585
  async function tsconfigSourcesForPaths(root, paths) {
4362
4586
  const pending = [];
4363
4587
  for (const path of paths) {
@@ -4379,11 +4603,9 @@ async function tsconfigSourcesForPaths(root, paths) {
4379
4603
  sources.add(config);
4380
4604
  try {
4381
4605
  const parsed = parseJsonWithComments(await readFile(config, "utf8"));
4382
- const references = Array.isArray(parsed.extends) ? parsed.extends : parsed.extends ? [parsed.extends] : [];
4383
- for (const reference of references) {
4384
- const resolved = resolveTsconfigReference(config, reference);
4385
- if (resolved && !sources.has(resolved)) pending.push(resolved);
4386
- }
4606
+ const extended = (Array.isArray(parsed.extends) ? parsed.extends : parsed.extends ? [parsed.extends] : []).map((reference) => resolveTsconfigReference(config, reference));
4607
+ const projects = (Array.isArray(parsed.references) ? parsed.references : []).map((reference) => typeof reference?.path === "string" ? resolveTsconfigProjectReference(config, reference.path) : void 0);
4608
+ for (const resolved of [...extended, ...projects]) if (resolved && !sources.has(resolved)) pending.push(resolved);
4387
4609
  } catch {}
4388
4610
  }
4389
4611
  return [...sources];
@@ -4419,7 +4641,7 @@ async function retainProviderOutputSources(options) {
4419
4641
  const [index, root] = next.value;
4420
4642
  const requested = paths.filter((path) => path !== root && pathContains$1(root, path));
4421
4643
  const nestedConfiguredRoots = configuredRoots.filter((path) => pathContains$1(root, path));
4422
- const importedSources = await traceImportedSources(requested, root, nestedConfiguredRoots);
4644
+ const importedSources = await traceImportedSources(requested, root, nestedConfiguredRoots, options.aliases);
4423
4645
  const materializedSourcePaths = [...requested, ...importedSources];
4424
4646
  const tsconfigSources = await tsconfigSourcesForPaths(root, materializedSourcePaths);
4425
4647
  materializedSourcePaths.push(...tsconfigSources);
@@ -4507,7 +4729,7 @@ async function retainProviderOutputSources(options) {
4507
4729
  const nestedGeneratedOutput = scopedSegments.some((segment) => ignoredGeneratedDirectories.has(segment));
4508
4730
  const ignoredIndex = scopedSegments.findIndex((segment) => ignoredSourceDirectories.has(segment));
4509
4731
  const packageOutput = scopedSegments[ignoredIndex] === "dist" && !containingConfiguredRoot && (ignoredIndex === 0 ? packageRoots.has(root) : referencedPackages.has(resolve(root, ...scopedSegments.slice(0, ignoredIndex))));
4510
- if (nestedGeneratedOutput || ignoredIndex !== -1 && !packageOutput) return requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || [...importedSources].some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || requestedOutputRoots.some((outputRoot) => pathContains$1(outputRoot, resolvedSource)) || configuredOutputClosures.some((outputRoot) => pathContains$1(outputRoot, resolvedSource) && !relative(outputRoot, resolvedSource).split(sep).some((segment) => ignoredSourceDirectories.has(segment))) && !nestedConfiguredRoots.some((configuredRoot) => pathContains$1(configuredRoot, resolvedSource)) || nestedConfiguredRoots.some((configuredRoot) => pathContains$1(resolvedSource, configuredRoot));
4732
+ if (nestedGeneratedOutput || ignoredIndex !== -1 && !packageOutput) return requested.some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource) && !crossesIgnoredDirectory(path, resolvedSource)) || [...importedSources].some((path) => pathContains$1(resolvedSource, path) || pathContains$1(path, resolvedSource)) || requestedOutputRoots.some((outputRoot) => pathContains$1(outputRoot, resolvedSource)) || configuredOutputClosures.some((outputRoot) => pathContains$1(outputRoot, resolvedSource) && !relative(outputRoot, resolvedSource).split(sep).some((segment) => ignoredSourceDirectories.has(segment))) && !nestedConfiguredRoots.some((configuredRoot) => pathContains$1(configuredRoot, resolvedSource)) || nestedConfiguredRoots.some((configuredRoot) => pathContains$1(resolvedSource, configuredRoot));
4511
4733
  return true;
4512
4734
  };
4513
4735
  await copyRetainedSourceTree(root, stagedRoot, (source) => shouldCopySource(resolve(source)));
@@ -5021,17 +5243,17 @@ var ProviderOutputCatalog = class {
5021
5243
  }
5022
5244
  this.#restoreDeploymentContribution(entry);
5023
5245
  }
5024
- resetDeploymentContributions(generation) {
5246
+ resetDeploymentContributions(generation, failure) {
5025
5247
  if (!generation) {
5026
5248
  for (const reference of this.#deploymentGenerations) {
5027
5249
  const current = reference.deref();
5028
5250
  if (current) current.valid = false;
5029
5251
  }
5030
5252
  this.#deploymentGenerations.clear();
5031
- for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
5253
+ for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry, failure);
5032
5254
  for (const taken of this.#takenDeploymentContributions.values()) {
5033
- if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
5034
- for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
5255
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry, failure);
5256
+ for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback, failure);
5035
5257
  }
5036
5258
  this.#deploymentContributions.clear();
5037
5259
  this.#takenDeploymentContributions.clear();
@@ -5040,7 +5262,7 @@ var ProviderOutputCatalog = class {
5040
5262
  generation.valid = false;
5041
5263
  this.#deleteDeploymentGeneration(generation);
5042
5264
  for (const [owner, entries] of this.#deploymentContributions) {
5043
- for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
5265
+ for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry, failure);
5044
5266
  const remaining = entries.filter((entry) => entry.generation !== generation);
5045
5267
  if (remaining.length) this.#deploymentContributions.set(owner, remaining);
5046
5268
  else this.#deploymentContributions.delete(owner);
@@ -5048,10 +5270,10 @@ var ProviderOutputCatalog = class {
5048
5270
  for (const [contribution, taken] of this.#takenDeploymentContributions) {
5049
5271
  const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
5050
5272
  taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
5051
- for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
5273
+ for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback, failure);
5052
5274
  if (taken.entry.generation !== generation) continue;
5053
5275
  this.#takenDeploymentContributions.delete(contribution);
5054
- if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
5276
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry, failure);
5055
5277
  for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
5056
5278
  else this.#restoreDeploymentContribution(fallback);
5057
5279
  }
@@ -5094,7 +5316,7 @@ var ProviderOutputCatalog = class {
5094
5316
  const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
5095
5317
  if (failure) throw failure.reason;
5096
5318
  }
5097
- async completeDeploymentContributions(contributions) {
5319
+ async completeDeploymentContributions(contributions, buildFailure) {
5098
5320
  const discarded = this.#pendingDeploymentDiscards.splice(0);
5099
5321
  const completedGenerations = /* @__PURE__ */ new Set();
5100
5322
  for (const contribution of contributions) {
@@ -5104,7 +5326,7 @@ var ProviderOutputCatalog = class {
5104
5326
  const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
5105
5327
  for (const entry of entries) {
5106
5328
  if (entry.generation) completedGenerations.add(entry.generation);
5107
- if (entry.contribution.discard) discarded.push(entry.contribution.discard());
5329
+ if (entry.contribution.discard) discarded.push(entry.contribution.discard(entry === taken.entry ? buildFailure : void 0));
5108
5330
  }
5109
5331
  }
5110
5332
  for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
@@ -5148,9 +5370,9 @@ var ProviderOutputCatalog = class {
5148
5370
  if (reference) this.#deploymentGenerations.delete(reference);
5149
5371
  this.#deploymentGenerationRefs.delete(generation);
5150
5372
  }
5151
- #queueDeploymentDiscard(entry) {
5373
+ #queueDeploymentDiscard(entry, failure) {
5152
5374
  if (!entry.contribution.discard) return;
5153
- const discard = Promise.resolve().then(entry.contribution.discard);
5375
+ const discard = Promise.resolve().then(async () => await entry.contribution.discard?.(failure));
5154
5376
  discard.catch(() => {});
5155
5377
  this.#pendingDeploymentDiscards.push(discard);
5156
5378
  }
@@ -5995,23 +6217,23 @@ async function resetProviderDeploymentOutputs(catalog, failure, generation) {
5995
6217
  if (!catalog) return;
5996
6218
  const completedReset = providerDeploymentOutputCompletedResets.get(catalog);
5997
6219
  if (completedReset && failure !== void 0 && completedReset.failures.has(failure)) {
5998
- if (generation) catalog.resetDeploymentContributions(generation);
6220
+ if (generation) catalog.resetDeploymentContributions(generation, failure);
5999
6221
  await completedReset.promise;
6000
6222
  return;
6001
6223
  }
6002
6224
  if (completedReset) providerDeploymentOutputCompletedResets.delete(catalog);
6003
- if (generation) catalog.resetDeploymentContributions(generation);
6225
+ if (generation) catalog.resetDeploymentContributions(generation, failure);
6004
6226
  const active = providerDeploymentOutputFinalizations.get(catalog);
6005
6227
  if (active?.reset) {
6006
6228
  if (failure !== void 0 && !active.reset.failures.has(failure)) {
6007
6229
  active.reset.failures.add(failure);
6008
- if (!generation) catalog.resetDeploymentContributions();
6230
+ if (!generation) catalog.resetDeploymentContributions(void 0, failure);
6009
6231
  }
6010
6232
  providerDeploymentOutputCompletedResets.set(catalog, active.reset);
6011
6233
  await active.reset.promise;
6012
6234
  return;
6013
6235
  }
6014
- if (!generation) catalog.resetDeploymentContributions();
6236
+ if (!generation) catalog.resetDeploymentContributions(void 0, failure);
6015
6237
  if (active && (!generation || active.state.generations.has(generation))) {
6016
6238
  active.state.rollback = true;
6017
6239
  active.controller.abort(internalErrorDiagnostics.INTERNAL_B0039({ message: "Provider Output finalization reset" }));
@@ -6160,7 +6382,7 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
6160
6382
  await catalog.completeDeploymentContributions(contributions);
6161
6383
  } catch (error) {
6162
6384
  if (state.rollback) catalog.rollbackDeploymentContributions(contributions);
6163
- else await catalog.completeDeploymentContributions(contributions);
6385
+ else await catalog.completeDeploymentContributions(contributions, error);
6164
6386
  throw error;
6165
6387
  } finally {
6166
6388
  state.generations.clear();
@@ -6191,15 +6413,6 @@ function durabilityModuleFile(importMetaUrl) {
6191
6413
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
6192
6414
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
6193
6415
  const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
6194
- const ignoredDirs = /* @__PURE__ */ new Set([
6195
- "node_modules",
6196
- "dist",
6197
- ".output",
6198
- ".nuxt",
6199
- ".vercel",
6200
- ".git",
6201
- ".vitehub"
6202
- ]);
6203
6416
  function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
6204
6417
  return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
6205
6418
  }
@@ -6222,32 +6435,8 @@ function createSuffixDefinitionSource(source, roots, pattern, normalizeName, opt
6222
6435
  source
6223
6436
  };
6224
6437
  }
6225
- function readDirEntries(root) {
6226
- try {
6227
- return readdirSync(root, { withFileTypes: true });
6228
- } catch (error) {
6229
- if (error.code === "ENOENT") return [];
6230
- throw error;
6231
- }
6232
- }
6233
- function isGitRepositoryDirectory(directory) {
6234
- return existsSync(resolve$1(directory, ".git"));
6235
- }
6236
6438
  function listMatchingFiles(root, predicate, options = {}) {
6237
- const files = [];
6238
- for (const entry of readDirEntries(root)) {
6239
- const absolute = resolve$1(root, entry.name);
6240
- if (entry.isDirectory() && !entry.isSymbolicLink()) {
6241
- if (isGitRepositoryDirectory(absolute)) continue;
6242
- if (entry.name.startsWith(".")) continue;
6243
- if (ignoredDirs.has(entry.name)) continue;
6244
- files.push(...listMatchingFiles(absolute, predicate, options));
6245
- continue;
6246
- }
6247
- if (entry.name.startsWith(".") && !options.includeHidden) continue;
6248
- if (entry.isFile() && predicate(entry.name)) files.push(absolute);
6249
- }
6250
- return files.sort();
6439
+ return listSourceTreeFiles(root, predicate, options);
6251
6440
  }
6252
6441
  /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
6253
6442
  function isDefinitionSourceFile(name) {
@@ -6512,7 +6701,7 @@ async function flattenPlugins(value, plugins, seen) {
6512
6701
  for (const item of value) await flattenPlugins(item, plugins, seen);
6513
6702
  return;
6514
6703
  }
6515
- if (!isRecord$1(value) || seen.has(value)) return;
6704
+ if (!isRecord(value) || seen.has(value)) return;
6516
6705
  seen.add(value);
6517
6706
  if (isThenable(value)) {
6518
6707
  await flattenPlugins(await value, plugins, seen);
@@ -6544,7 +6733,7 @@ async function collectContributions(plugins, options) {
6544
6733
  for (const plugin of candidates) {
6545
6734
  if (!Object.hasOwn(plugin, "vitehub")) continue;
6546
6735
  const metadata = Reflect.get(plugin, "vitehub");
6547
- if (!isRecord$1(metadata) || !Object.hasOwn(metadata, options.key)) continue;
6736
+ if (!isRecord(metadata) || !Object.hasOwn(metadata, options.key)) continue;
6548
6737
  const source = metadata[options.key];
6549
6738
  const pluginName = Reflect.get(plugin, "name");
6550
6739
  const contributor = isNonEmptyString(pluginName) ? pluginName : unnamedPlugin;
@@ -6572,12 +6761,12 @@ async function collectContributions(plugins, options) {
6572
6761
  return [...collected.values()].map(({ contribution }) => contribution).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
6573
6762
  }
6574
6763
  function readContribution(entry, plugin, options, fail) {
6575
- if (!isRecord$1(entry)) return fail("expected { name, definition: { module, export? }, reason? }.");
6764
+ if (!isRecord(entry)) return fail("expected { name, definition: { module, export? }, reason? }.");
6576
6765
  const { definition, name, reason } = entry;
6577
6766
  if (!isNonEmptyString(name) || name.trim() !== name) return fail("`name` must be a non-empty string without surrounding whitespace.");
6578
6767
  const nameProblem = options.checkName?.(name);
6579
6768
  if (nameProblem) return fail(`${options.kind} ${JSON.stringify(name)}: ${nameProblem}`);
6580
- if (!isRecord$1(definition)) return fail(`${options.kind} ${JSON.stringify(name)} needs \`definition: { module, export? }\`.`);
6769
+ if (!isRecord(definition)) return fail(`${options.kind} ${JSON.stringify(name)} needs \`definition: { module, export? }\`.`);
6581
6770
  if (!isNonEmptyString(definition.module)) return fail(`\`definition.module\` of ${options.kind} ${JSON.stringify(name)} must be a non-empty string.`);
6582
6771
  let module;
6583
6772
  try {
@@ -6644,9 +6833,20 @@ function isServerScheduleDefinition(definition) {
6644
6833
  return definition.source === "server-schedules" || definition.source === "vite-plugin-contribution";
6645
6834
  }
6646
6835
  const scheduleSuffixPattern = /\.schedule\.(?:c|m)?[jt]s$/i;
6836
+ function cronLocation(file, source, offset) {
6837
+ return `[vitehub] ${file}:${source.slice(0, offset).split("\n").length}: \`defineSchedule()\``;
6838
+ }
6839
+ function assertStaticScheduleCron(file) {
6840
+ const source = readSourceText(file);
6841
+ const definition = findDefaultExportCall(scanModuleText(source, file), ["defineSchedule"]);
6842
+ const property = definition?.options && findProperty(definition.options, "cron");
6843
+ if (!property) return;
6844
+ const cron = staticString(property.value);
6845
+ if (cron !== void 0) parseScheduleCronExpression(cron, cronLocation(file, source, property.node.start));
6846
+ }
6647
6847
  function readScheduleDiscoveryMetadata(file, contribution) {
6648
- const source = readFileSync(file, "utf8");
6649
- const module = scanModule(source, file);
6848
+ const source = readSourceText(file);
6849
+ const module = scanModuleText(source, file);
6650
6850
  const definition = findDefaultExportCall(module, ["defineSchedule"]);
6651
6851
  const unsupported = (offset, message) => {
6652
6852
  const line = source.slice(0, offset).split("\n").length;
@@ -6665,20 +6865,22 @@ function readScheduleDiscoveryMetadata(file, contribution) {
6665
6865
  return {};
6666
6866
  }
6667
6867
  const start = definition.call.start;
6668
- let manual = false;
6669
- let startable = true;
6868
+ const cronProperty = definition.options && findProperty(definition.options, "cron");
6869
+ const cron = staticString(cronProperty?.value);
6870
+ let manual;
6670
6871
  for (const property of definition.options ? objectProperties(definition.options) : []) {
6671
6872
  if (property.key === void 0 || property.computed) unsupported(start, "Schedule discovery cannot resolve spread, computed, or escaped option keys. Declare manual with an unescaped literal key and a literal true or false value.");
6672
- if (property.key === "cron") startable = false;
6673
6873
  if (property.key !== "manual") continue;
6674
6874
  const value = property.node.type === "Property" && property.node.kind === "init" && !property.node.method && property.value?.type === "Literal" && typeof property.value.value === "boolean" ? property.value.value : void 0;
6675
6875
  if (value === void 0) unsupported(start, "Schedule discovery requires manual to be a literal true or false; it cannot evaluate this expression.");
6676
6876
  manual = value === true;
6677
6877
  }
6678
- return startable ? {
6679
- manual,
6680
- startable
6681
- } : { manual };
6878
+ if (!cronProperty) return {
6879
+ manual: false,
6880
+ startable: true
6881
+ };
6882
+ if (cron !== void 0) assertScheduleCronFields(cron, cronLocation(file, source, cronProperty.node.start));
6883
+ return { manual: manual ?? true };
6682
6884
  }
6683
6885
  function createDiscoveredScheduleDefinition(source) {
6684
6886
  return (context) => {
@@ -6756,7 +6958,7 @@ function startedTickSource() {
6756
6958
  `import { defineSchedule } from ${resolveEntry("@vite-hub/schedule")}`,
6757
6959
  `import { runStartedSchedules } from ${resolveEntry("@vite-hub/schedule/runtime")}`,
6758
6960
  "",
6759
- "export default defineSchedule({ cron: \"* * * * *\", handler: runStartedSchedules, manual: true })",
6961
+ "export default defineSchedule({ cron: \"* * * * *\", handler: runStartedSchedules })",
6760
6962
  ""
6761
6963
  ].join("\n");
6762
6964
  }
@@ -6797,6 +6999,33 @@ function discoverScheduleDefinitions(options) {
6797
6999
  function discoverStartableScheduleDefinitions(options) {
6798
7000
  return discoverAllScheduleDefinitions(options).filter((definition) => definition.startable);
6799
7001
  }
7002
+ // src/registry-types.ts
7003
+ const scheduleTypesFile = ".vitehub/schedule.d.ts";
7004
+ function registryEntries(definitions) {
7005
+ return [...new Set(definitions.map((definition) => definition.name))].sort().map((name) => ` ${JSON.stringify(name)}: true`);
7006
+ }
7007
+ /** Types the names that `runSchedule()` (`ScheduleRegistry`) and `startSchedule()` (`StartableScheduleRegistry`) accept. */
7008
+ function createScheduleTypes(definitions, startableDefinitions, importBase = "@vite-hub/schedule") {
7009
+ return [
7010
+ `import ${JSON.stringify(importBase)}`,
7011
+ `declare module ${JSON.stringify(importBase)} {`,
7012
+ " interface ScheduleRegistryState {",
7013
+ " generated: true",
7014
+ " }",
7015
+ " interface ScheduleRegistry {",
7016
+ ...registryEntries(definitions),
7017
+ " }",
7018
+ " interface StartableScheduleRegistry {",
7019
+ ...registryEntries(startableDefinitions),
7020
+ " }",
7021
+ "}",
7022
+ ""
7023
+ ].join("\n");
7024
+ }
7025
+ /** Writes `.vitehub/schedule.d.ts` when its contents change. */
7026
+ async function writeScheduleTypes(root, definitions, startableDefinitions, importBase = "@vite-hub/schedule") {
7027
+ await writeFileIfChanged(resolve(root, scheduleTypesFile), createScheduleTypes(definitions, startableDefinitions, importBase));
7028
+ }
6800
7029
  // src/integrations/vercel.ts
6801
7030
  function getVercelSchedulePath(name) {
6802
7031
  return `/api/vitehub/schedules/vercel/${name.replace(/[^a-z0-9/_-]+/gi, "_")}`;
@@ -6830,12 +7059,12 @@ function utcCronForTimeZone(cron, timeZone, from = /* @__PURE__ */ new Date()) {
6830
7059
  const key = `${cron}\n${timeZone}\n${from.toISOString().slice(0, 10)}`;
6831
7060
  if (utcCronCache.has(key)) return utcCronCache.get(key);
6832
7061
  const offsets = timeZoneOffsets(timeZone, from);
6833
- const utcCron = offsets.length === 1 && offsets[0] === 0 ? void 0 : expandCron(cron, offsets);
7062
+ const utcCron = offsets.length === 1 && offsets[0] === 0 ? void 0 : expandCron(cron, offsets, timeZone);
6834
7063
  utcCronCache.set(key, utcCron);
6835
7064
  return utcCron;
6836
7065
  }
6837
- function expandCron(cron, offsets) {
6838
- const parsed = parseCronExpression(cron);
7066
+ function expandCron(cron, offsets, timeZone) {
7067
+ const parsed = parseScheduleCronExpression(cron, `Schedule with time zone "${timeZone}"`);
6839
7068
  const [minuteField, hourField, dayField, monthField, weekdayField] = cron.trim().split(/\s+/);
6840
7069
  const minutes = /* @__PURE__ */ new Set();
6841
7070
  const hours = /* @__PURE__ */ new Set();
@@ -6875,7 +7104,7 @@ function readStringArray(value) {
6875
7104
  return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
6876
7105
  }
6877
7106
  function isVercelCron(value) {
6878
- return isRecord$1(value) && typeof value.path === "string" && typeof value.schedule === "string";
7107
+ return isRecord(value) && typeof value.path === "string" && typeof value.schedule === "string";
6879
7108
  }
6880
7109
  function resolveSchedulePublicEntry(resolveImport = (specifier) => import.meta.resolve(specifier)) {
6881
7110
  const packageRoot = dirname(fileURLToPath(resolveImport(`${schedulePackageName}/package.json`)));
@@ -6965,9 +7194,13 @@ function isProviderCron(cron) {
6965
7194
  function validateProviderCron(cron, scheduleName) {
6966
7195
  if (!isProviderCron(cron)) throw scheduleErrorDiagnostics.SCHEDULE_R0003({ message: `Schedule "${scheduleName}" uses cron "${cron}", but provider wake output only supports five-field UTC cron syntax compatible with Cloudflare, Vercel, and Netlify.` });
6967
7196
  }
7197
+ function validateDefinitionProviderCron(cron, definition, overrides) {
7198
+ if (!isProviderCron(cron) && !(overrides && Object.hasOwn(overrides, definition.name))) assertStaticScheduleCron(definition.handler);
7199
+ validateProviderCron(cron, definition.name);
7200
+ }
6968
7201
  /** Reads the `cron` option of a `defineSchedule()` call. Returns `undefined` when it is missing or not a static string. */
6969
7202
  function readStaticScheduleCronOption(file) {
6970
- const definition = findDefaultExportCall(scanModule(readFileSync(file, "utf8"), file), ["defineSchedule"]);
7203
+ const definition = findDefaultExportCall(scanSourceFile(file), ["defineSchedule"]);
6971
7204
  return definition?.options && staticString(findProperty(definition.options, "cron")?.value) || void 0;
6972
7205
  }
6973
7206
  function readStaticScheduleCron(file, scheduleName) {
@@ -6981,7 +7214,7 @@ function readStaticScheduleCron(file, scheduleName) {
6981
7214
  * when it is present but dynamic.
6982
7215
  */
6983
7216
  function readStaticScheduleTimeZone(file) {
6984
- const definition = findDefaultExportCall(scanModule(readFileSync(file, "utf8"), file), ["defineSchedule"]);
7217
+ const definition = findDefaultExportCall(scanSourceFile(file), ["defineSchedule"]);
6985
7218
  const property = definition?.options && findProperty(definition.options, "timeZone");
6986
7219
  if (!property) return void 0;
6987
7220
  return property.value ? staticString(property.value) ?? null : null;
@@ -6992,7 +7225,7 @@ function readStaticScheduleTimeZone(file) {
6992
7225
  */
6993
7226
  function readStaticScheduleTiming(file) {
6994
7227
  if (!existsSync(file)) return void 0;
6995
- const definition = findDefaultExportCall(scanModule(readFileSync(file, "utf8"), file), ["defineSchedule"]);
7228
+ const definition = findDefaultExportCall(scanSourceFile(file), ["defineSchedule"]);
6996
7229
  if (!definition) return void 0;
6997
7230
  const cron = staticString(definition.options && findProperty(definition.options, "cron")?.value);
6998
7231
  const timeZone = definition.options && findProperty(definition.options, "timeZone");
@@ -7016,7 +7249,7 @@ function readTimeZoneCrons(definitions, overrides) {
7016
7249
  if (timeZone === null) throw scheduleErrorDiagnostics.SCHEDULE_R0003({ message: `Schedule "${definition.name}" declares timeZone with a value that is not a static string. Host cron output reads timeZone at build time, so write it as a string literal, such as \`timeZone: "Europe/Madrid"\`.` });
7017
7250
  if (!isIanaTimeZone(timeZone)) throw scheduleErrorDiagnostics.SCHEDULE_R0003({ message: `Schedule "${definition.name}" declares timeZone ${JSON.stringify(timeZone)}, which is not an IANA time zone, such as "Europe/Madrid".` });
7018
7251
  const cron = readStaticScheduleCron(definition.handler, definition.name);
7019
- validateProviderCron(cron, definition.name);
7252
+ validateDefinitionProviderCron(cron, definition);
7020
7253
  const utcCron = utcCronForTimeZone(cron, timeZone);
7021
7254
  if (utcCron !== void 0) crons[definition.name] = utcCron;
7022
7255
  }
@@ -7248,7 +7481,7 @@ async function readDefinitionCrons(definitions, overrides) {
7248
7481
  const crons = await readRuntimeDefinitionCrons(definitions);
7249
7482
  for (const [name, cron] of Object.entries(readTimeZoneCrons(definitions, overrides))) crons.set(name, cron);
7250
7483
  for (const [name, cron] of Object.entries(overrides ?? {})) if (crons.has(name)) crons.set(name, cron);
7251
- for (const [name, cron] of crons) validateProviderCron(cron, name);
7484
+ for (const definition of definitions) validateDefinitionProviderCron(crons.get(definition.name), definition, overrides);
7252
7485
  return crons;
7253
7486
  }
7254
7487
  async function readRuntimeDefinitionCrons(definitions) {
@@ -7566,7 +7799,7 @@ async function writeCloudflareScheduleOutput(options) {
7566
7799
  } catch (error) {
7567
7800
  if (error.code !== "ENOENT") throw error;
7568
7801
  }
7569
- const existingTriggers = isRecord$1(wranglerConfig.triggers) ? wranglerConfig.triggers : {};
7802
+ const existingTriggers = isRecord(wranglerConfig.triggers) ? wranglerConfig.triggers : {};
7570
7803
  const previousState = await readCloudflareOutputState(options.previousStateFile ?? options.stateFile);
7571
7804
  options.signal?.throwIfAborted();
7572
7805
  const externalCrons = readStringArray(existingTriggers.crons).filter((cron) => !previousState?.crons.includes(cron));
@@ -7935,7 +8168,7 @@ const scheduleConsoleSection = {
7935
8168
  }
7936
8169
  ],
7937
8170
  kind: "record-table",
7938
- notice: "The host runs each Schedule on its cron, in its time zone (UTC by default). A Definition without cron runs when code starts it with `startSchedule()`; each started Schedule has its own row. Static Definitions with `manual: true` can also run from the Console or `vitehub schedule run`."
8171
+ notice: "The host runs each Schedule on its cron, in its time zone (UTC by default). A Definition without cron runs when code starts it with `startSchedule()`; each started Schedule has its own row. Static Definitions can also run from the Console or `vitehub schedule run`, unless they set `manual: false`. A development server allows this. A deployed app allows it only when you set `console: { invoke: true }`."
7939
8172
  }
7940
8173
  };
7941
8174
  // src/internal/registry-module.ts
@@ -7962,6 +8195,7 @@ async function readScheduleDefinitionCrons(definitions) {
7962
8195
  const SCHEDULE_VITE_PLUGIN_NAME = "@vite-hub/schedule/vite";
7963
8196
  const SCHEDULE_REGISTRY_ID = "#vitehub/schedule/registry";
7964
8197
  const RESOLVED_SCHEDULE_REGISTRY_ID = "\0#vitehub/schedule/registry";
8198
+ const scheduleRegistryImport = /\/\* @vite-ignore \*\/\s*\/\* @vitehub-schedule-registry \*\/\s*[\w$]+/g;
7965
8199
  const generatedNitroSchedulePlugin = ".vitehub/nitro/schedule/plugin.ts";
7966
8200
  const generatedNitroProviderRegistry = ".vitehub/nitro/schedule/provider-registry.js";
7967
8201
  const generatedNitroStaticRegistry = ".vitehub/nitro/schedule/static-registry.js";
@@ -7970,17 +8204,10 @@ const generatedNitroInventoryRegistry = ".vitehub/nitro/schedule/inventory-regis
7970
8204
  const defaultCatchUpMs = 36e5;
7971
8205
  const generatedNitroScheduleModule = "./.vitehub/nitro/schedule/module.mjs";
7972
8206
  const generatedNitroNetlifyEntry = ".vitehub/nitro/schedule/netlify-entry.mjs";
8207
+ const generatedNitroScheduleRunner = ".vitehub/nitro/schedule/runner.mjs";
8208
+ const generatedNitroVercelHandler = ".vitehub/nitro/schedule/vercel-handler.mjs";
8209
+ const generatedNitroVercelRoutes = ".vitehub/nitro/schedule/vercel";
7973
8210
  const mergeNoExternal = createNoExternalMerger(schedulePackageName);
7974
- function invalidateScheduleRegistry(server) {
7975
- const registry = server.moduleGraph.getModuleById(RESOLVED_SCHEDULE_REGISTRY_ID);
7976
- if (registry) server.moduleGraph.invalidateModule(registry);
7977
- for (const environment of Object.values(server.environments ?? {})) {
7978
- const module = environment.moduleGraph.getModuleById(RESOLVED_SCHEDULE_REGISTRY_ID);
7979
- if (!module) continue;
7980
- environment.moduleGraph.invalidateModule(module);
7981
- if (environment.config.consumer === "server") environment.hot.send({ type: "full-reload" });
7982
- }
7983
- }
7984
8211
  function resolveSchedulePluginRoots(root, options = {}) {
7985
8212
  const resolvedViteRoot = resolve(root);
7986
8213
  return {
@@ -7988,12 +8215,9 @@ function resolveSchedulePluginRoots(root, options = {}) {
7988
8215
  viteRoot: resolvedViteRoot
7989
8216
  };
7990
8217
  }
7991
- function isRecord(value) {
7992
- return typeof value === "object" && value !== null;
7993
- }
7994
8218
  function resolveProcessRuntimeOptions(value) {
7995
8219
  if (value === void 0) return;
7996
- if (!isRecord(value) || value.driver !== "process") throw scheduleErrorDiagnostics.SCHEDULE_B0001({ message: "Schedule Process Runtime driver must be \"process\"." });
8220
+ if (!isObject(value) || value.driver !== "process") throw scheduleErrorDiagnostics.SCHEDULE_B0001({ message: "Schedule Process Runtime driver must be \"process\"." });
7997
8221
  if (value.prefix !== void 0 && typeof value.prefix !== "string") throw scheduleErrorDiagnostics.SCHEDULE_B0002({ message: "Schedule Process Runtime prefix must be a string." });
7998
8222
  if (value.catchUpMs !== void 0 && (typeof value.catchUpMs !== "number" || !Number.isFinite(value.catchUpMs) || value.catchUpMs < 0)) throw scheduleErrorDiagnostics.SCHEDULE_RUNTIME_CATCH_UP_INVALID();
7999
8223
  if (value.intervalMs !== void 0 && (typeof value.intervalMs !== "number" || !Number.isFinite(value.intervalMs) || value.intervalMs <= 0 || value.intervalMs > 6e4)) throw scheduleErrorDiagnostics.SCHEDULE_B0003({ message: "Schedule Process Runtime intervalMs must be a positive number no greater than 60000." });
@@ -8008,13 +8232,24 @@ function resolveProcessRuntimeOptions(value) {
8008
8232
  ...value.prefix !== void 0 ? { prefix: value.prefix } : {}
8009
8233
  };
8010
8234
  }
8235
+ function resolveScheduleRetention(value, processRuntime) {
8236
+ const catchUpMs = processRuntime?.catchUpMs ?? defaultCatchUpMs;
8237
+ if (value === void 0) return catchUpMs > parseDuration("30 days") ? `${catchUpMs}ms` : void 0;
8238
+ const retention = value;
8239
+ const milliseconds = parseDuration(retention, "retention");
8240
+ if (milliseconds <= 0 || processRuntime && milliseconds < catchUpMs) throw scheduleErrorDiagnostics.SCHEDULE_RETENTION_TOO_SHORT({
8241
+ catchUpMs,
8242
+ retention: JSON.stringify(retention)
8243
+ });
8244
+ return retention;
8245
+ }
8011
8246
  const databaseVitePluginName = "@vite-hub/database/vite";
8012
8247
  function hasVitePlugin(plugins, name) {
8013
- return (plugins ?? []).some((plugin) => Array.isArray(plugin) ? hasVitePlugin(plugin, name) : isRecord(plugin) && plugin.name === name);
8248
+ return (plugins ?? []).some((plugin) => Array.isArray(plugin) ? hasVitePlugin(plugin, name) : isObject(plugin) && plugin.name === name);
8014
8249
  }
8015
8250
  function resolveCronOverrides(value, definitions, options) {
8016
8251
  if (value === void 0) return;
8017
- if (!isRecord(value) || Array.isArray(value)) throw scheduleErrorDiagnostics.SCHEDULE_B0008({ message: "Schedule `cron` must map Schedule names to cron strings, such as `{ cleanup: \"0 0 * * *\" }`." });
8252
+ if (!isObject(value) || Array.isArray(value)) throw scheduleErrorDiagnostics.SCHEDULE_B0008({ message: "Schedule `cron` must map Schedule names to cron strings, such as `{ cleanup: \"0 0 * * *\" }`." });
8018
8253
  const names = definitions && new Set(definitions.map((definition) => definition.name));
8019
8254
  const overrides = {};
8020
8255
  for (const [name, cron] of Object.entries(value)) {
@@ -8033,13 +8268,13 @@ function moduleImportSpecifier(fromFile, targetFile) {
8033
8268
  return specifier.startsWith(".") ? specifier : `./${specifier}`;
8034
8269
  }
8035
8270
  function cloneNitroConfig(value) {
8036
- const nitro = isRecord(value) ? { ...value } : {};
8271
+ const nitro = isObject(value) ? { ...value } : {};
8037
8272
  if (Array.isArray(nitro.plugins)) nitro.plugins = [...nitro.plugins];
8038
- if (isRecord(nitro.cloudflare)) {
8273
+ if (isObject(nitro.cloudflare)) {
8039
8274
  const cloudflare = { ...nitro.cloudflare };
8040
- if (isRecord(cloudflare.wrangler)) {
8275
+ if (isObject(cloudflare.wrangler)) {
8041
8276
  const wrangler = { ...cloudflare.wrangler };
8042
- if (isRecord(wrangler.triggers)) {
8277
+ if (isObject(wrangler.triggers)) {
8043
8278
  const triggers = { ...wrangler.triggers };
8044
8279
  if (Array.isArray(triggers.crons)) triggers.crons = triggers.crons.filter((cron) => typeof cron === "string");
8045
8280
  wrangler.triggers = triggers;
@@ -8065,7 +8300,7 @@ function mergeNitroScheduleConfig(value, options) {
8065
8300
  configured.cloudflare ||= {};
8066
8301
  configured.cloudflare.wrangler ||= {};
8067
8302
  const wrangler = configured.cloudflare.wrangler;
8068
- const existingTriggers = isRecord(wrangler.triggers) ? wrangler.triggers : {};
8303
+ const existingTriggers = isObject(wrangler.triggers) ? wrangler.triggers : {};
8069
8304
  const existingCrons = Array.isArray(existingTriggers.crons) ? existingTriggers.crons.filter((cron) => typeof cron === "string") : [];
8070
8305
  wrangler.triggers = {
8071
8306
  ...existingTriggers,
@@ -8075,10 +8310,10 @@ function mergeNitroScheduleConfig(value, options) {
8075
8310
  }
8076
8311
  function mergeNitroVercelCrons(value, definitions, crons) {
8077
8312
  const nitro = cloneNitroConfig(value);
8078
- const vercel = isRecord(nitro.vercel) ? { ...nitro.vercel } : {};
8079
- const config = isRecord(vercel.config) ? { ...vercel.config } : {};
8313
+ const vercel = isObject(nitro.vercel) ? { ...nitro.vercel } : {};
8314
+ const config = isObject(vercel.config) ? { ...vercel.config } : {};
8080
8315
  const generatedPaths = new Set(definitions.map((definition) => getVercelSchedulePath(definition.name)));
8081
- config.crons = [...Array.isArray(config.crons) ? config.crons.filter((cron) => isRecord(cron) && typeof cron.path === "string" && !generatedPaths.has(cron.path)) : [], ...definitions.map((definition) => ({
8316
+ config.crons = [...Array.isArray(config.crons) ? config.crons.filter((cron) => isObject(cron) && typeof cron.path === "string" && !generatedPaths.has(cron.path)) : [], ...definitions.map((definition) => ({
8082
8317
  path: getVercelSchedulePath(definition.name),
8083
8318
  schedule: crons.get(definition.name)
8084
8319
  }))];
@@ -8125,7 +8360,10 @@ function renderNitroSchedulePlugin(options) {
8125
8360
  "",
8126
8361
  ...processRuntime ? [
8127
8362
  `const processRuntimeOptions = ${JSON.stringify(processRuntimeOptions, null, 2)}`,
8128
- ...memoryStores ? [] : [`const scheduleStoreOptions = { ...${JSON.stringify(scheduleStoreOptions, null, 2)}, kvStore: scheduleKVStorage }`],
8363
+ ...memoryStores ? [] : [`const scheduleStoreOptions = { ...${JSON.stringify({
8364
+ ...scheduleStoreOptions,
8365
+ ...options.retention ? { retention: options.retention } : {}
8366
+ }, null, 2)}, kvStore: scheduleKVStorage }`],
8129
8367
  ""
8130
8368
  ] : [],
8131
8369
  "export default definePlugin((nitroApp) => {",
@@ -8190,11 +8428,7 @@ function renderNitroSchedulePlugin(options) {
8190
8428
  " // ViteHub runs this drain on a stop signal, before the server closes HTTP, or when Nitro closes.",
8191
8429
  " onShutdown(nitroApp, 'schedule', () => runtimeInstallation.then(async (result) => {",
8192
8430
  " if ('controller' in result) await result.controller.close()",
8193
- " }).catch(captureRuntimeError))",
8194
- " nitroApp.hooks.hook('request', async () => {",
8195
- " const result = await runtimeInstallation",
8196
- " if ('error' in result) throw result.error",
8197
- " })"
8431
+ " }).catch(captureRuntimeError))"
8198
8432
  ] : [],
8199
8433
  "})",
8200
8434
  "",
@@ -8202,36 +8436,43 @@ function renderNitroSchedulePlugin(options) {
8202
8436
  ""
8203
8437
  ].join("\n");
8204
8438
  }
8205
- function renderNitroScheduleModule(options) {
8206
- const { netlify } = options;
8207
- let netlifyFunctionNames = /* @__PURE__ */ new Map();
8208
- let netlifyNameError;
8209
- try {
8210
- netlifyFunctionNames = netlifyScheduleFunctionNames(netlify.schedules);
8211
- } catch (error) {
8212
- if (!scheduleErrorDiagnostics.SCHEDULE_R0006.is(error)) throw error;
8213
- netlifyNameError = {
8214
- ...error,
8215
- code: error.code,
8216
- message: error.message,
8217
- name: error.name
8439
+ function serializeScheduleError(error) {
8440
+ return {
8441
+ ...error,
8442
+ code: error.code,
8443
+ message: error.message,
8444
+ name: error.name
8445
+ };
8446
+ }
8447
+ function resolveNitroVercelScheduleRoutes(root, schedules, standaloneNames) {
8448
+ const paths = /* @__PURE__ */ new Map();
8449
+ for (const name of [...schedules.map((schedule) => schedule.name), ...standaloneNames]) {
8450
+ const path = getVercelSchedulePath(name);
8451
+ const existing = paths.get(path);
8452
+ if (existing !== void 0) return {
8453
+ error: serializeScheduleError(scheduleErrorDiagnostics.SCHEDULE_R0005({ message: `Schedule "${name}" and "${existing}" both use the same Vercel cron path: ${path}` })),
8454
+ routes: []
8218
8455
  };
8456
+ paths.set(path, name);
8219
8457
  }
8220
- const netlifySchedules = netlify.schedules.map((schedule) => ({
8221
- ...schedule,
8222
- functionName: netlifyFunctionNames.get(schedule.name)
8223
- }));
8224
- const crons = Object.fromEntries(netlify.schedules.map((schedule) => [schedule.name, schedule.cron]));
8225
- const timeZoneNames = netlify.schedules.filter((schedule) => schedule.inTimeZone).map((schedule) => schedule.name);
8226
- const netlifyEntryRuntime = [
8458
+ return { routes: schedules.map(({ name }, index) => ({
8459
+ handler: resolve(root, generatedNitroVercelRoutes, `${index}.mjs`),
8460
+ name,
8461
+ route: getVercelSchedulePath(name)
8462
+ })) };
8463
+ }
8464
+ function renderNitroScheduleRunner(options) {
8465
+ const crons = Object.fromEntries(options.schedules.map((schedule) => [schedule.name, schedule.cron]));
8466
+ const timeZoneNames = options.schedules.filter((schedule) => schedule.inTimeZone).map((schedule) => schedule.name);
8467
+ return [
8227
8468
  "import { useNitroApp } from \"nitro/app\"",
8228
- `import scheduleRegistry from ${JSON.stringify(netlify.registryFile)}`,
8229
- `import { executeStaticSchedule, isTimeZoneWakeDue, missingScheduleDefinitionError, scheduledWakeTime, unwrapScheduleDefinition } from ${JSON.stringify(netlify.runtimeImport)}`,
8469
+ `import scheduleRegistry from ${JSON.stringify(options.registryFile)}`,
8470
+ `import { executeStaticSchedule, isTimeZoneWakeDue, missingScheduleDefinitionError, scheduledWakeTime, unwrapScheduleDefinition } from ${JSON.stringify(options.runtimeImport)}`,
8230
8471
  "",
8231
8472
  `const crons = ${JSON.stringify(crons)}`,
8232
8473
  `const timeZoneNames = new Set(${JSON.stringify(timeZoneNames)})`,
8233
8474
  "",
8234
- "export async function runViteHubNetlifySchedule(name) {",
8475
+ "export async function runViteHubSchedule(name) {",
8235
8476
  " const scheduledAt = scheduledWakeTime(crons[name])",
8236
8477
  " await useNitroApp().ready",
8237
8478
  " const loader = scheduleRegistry[name]",
@@ -8242,6 +8483,52 @@ function renderNitroScheduleModule(options) {
8242
8483
  "}",
8243
8484
  ""
8244
8485
  ].join("\n");
8486
+ }
8487
+ function renderNitroVercelScheduleHandler(options) {
8488
+ return [
8489
+ "import { defineHandler } from \"nitro/h3\"",
8490
+ `import { isScheduleCronAuthorized } from ${JSON.stringify(options.runtimeImport)}`,
8491
+ `import { runViteHubSchedule } from ${JSON.stringify(options.runnerFile)}`,
8492
+ "",
8493
+ "export function defineVercelScheduleHandler(name) {",
8494
+ " return defineHandler(async (event) => {",
8495
+ " const cronSecret = process.env.CRON_SECRET",
8496
+ " if (!cronSecret) return new Response('Unauthorized. Set CRON_SECRET in the Vercel project to run Schedules.', { status: 401 })",
8497
+ " if (!isScheduleCronAuthorized(event.req.headers.get('authorization'), cronSecret)) return new Response('Unauthorized.', { status: 401 })",
8498
+ " await runViteHubSchedule(name)",
8499
+ " return new Response(null, { status: 204 })",
8500
+ " })",
8501
+ "}",
8502
+ ""
8503
+ ].join("\n");
8504
+ }
8505
+ function renderNitroVercelScheduleRoute(handlerFile, name) {
8506
+ return [
8507
+ `import { defineVercelScheduleHandler } from ${JSON.stringify(handlerFile)}`,
8508
+ "",
8509
+ `export default defineVercelScheduleHandler(${JSON.stringify(name)})`,
8510
+ ""
8511
+ ].join("\n");
8512
+ }
8513
+ function renderNitroScheduleModule(options) {
8514
+ let netlifyFunctionNames = /* @__PURE__ */ new Map();
8515
+ let netlifyNameError;
8516
+ try {
8517
+ netlifyFunctionNames = netlifyScheduleFunctionNames(options.schedules);
8518
+ } catch (error) {
8519
+ if (!scheduleErrorDiagnostics.SCHEDULE_R0006.is(error)) throw error;
8520
+ netlifyNameError = serializeScheduleError(error);
8521
+ }
8522
+ const netlifySchedules = options.schedules.map((schedule) => ({
8523
+ ...schedule,
8524
+ functionName: netlifyFunctionNames.get(schedule.name)
8525
+ }));
8526
+ const crons = Object.fromEntries(options.schedules.map((schedule) => [schedule.name, schedule.cron]));
8527
+ const vercelRoutes = options.vercel.routes.map(({ handler, name, route }) => ({
8528
+ handler,
8529
+ route,
8530
+ schedule: crons[name]
8531
+ }));
8245
8532
  return [
8246
8533
  "import { cp, rm, writeFile } from 'node:fs/promises'",
8247
8534
  "import { join } from 'node:path'",
@@ -8249,8 +8536,10 @@ function renderNitroScheduleModule(options) {
8249
8536
  `const crons = ${JSON.stringify(options.crons)}`,
8250
8537
  `const netlifySchedules = ${JSON.stringify(netlifySchedules)}`,
8251
8538
  `const netlifyNameError = ${JSON.stringify(netlifyNameError ?? null)}`,
8252
- `const netlifyEntryFile = ${JSON.stringify(netlify.entryFile)}`,
8253
- `const netlifyEntryRuntime = ${JSON.stringify(netlifyEntryRuntime)}`,
8539
+ `const netlifyEntryFile = ${JSON.stringify(options.netlifyEntryFile)}`,
8540
+ `const runnerFile = ${JSON.stringify(options.runnerFile)}`,
8541
+ `const vercelRoutes = ${JSON.stringify(vercelRoutes)}`,
8542
+ `const vercelPathError = ${JSON.stringify(options.vercel.error ?? null)}`,
8254
8543
  "",
8255
8544
  "function dedupeCloudflareCrons(nitro) {",
8256
8545
  " const wrangler = nitro.options.cloudflare?.wrangler",
@@ -8268,10 +8557,10 @@ function renderNitroScheduleModule(options) {
8268
8557
  " // Netlify deploys each function directory alone, so each one gets its own copy of the server bundle.",
8269
8558
  " await cp(serverDir, functionDir, { filter: source => source !== join(serverDir, 'server.mjs'), recursive: true })",
8270
8559
  " await writeFile(join(functionDir, `${functionName}.mjs`), [",
8271
- " \"import { runViteHubNetlifySchedule } from './main.mjs'\",",
8560
+ " \"import { runViteHubSchedule } from './main.mjs'\",",
8272
8561
  " '',",
8273
8562
  " 'export default async function vitehubNetlifySchedule() {',",
8274
- " ` await runViteHubNetlifySchedule(${JSON.stringify(name)})`,",
8563
+ " ` await runViteHubSchedule(${JSON.stringify(name)})`,",
8275
8564
  " ' return new Response(null, { status: 204 })',",
8276
8565
  " '}',",
8277
8566
  " '',",
@@ -8281,24 +8570,44 @@ function renderNitroScheduleModule(options) {
8281
8570
  " }",
8282
8571
  "}",
8283
8572
  "",
8284
- "export default async function vitehubScheduleModule(nitro) {",
8285
- " nitro.options.cloudflare ??= {}",
8286
- " nitro.options.cloudflare.wrangler ??= {}",
8287
- " nitro.options.cloudflare.wrangler.triggers ??= {}",
8288
- " const existingCrons = Array.isArray(nitro.options.cloudflare.wrangler.triggers.crons) ? nitro.options.cloudflare.wrangler.triggers.crons : []",
8289
- " nitro.options.cloudflare.wrangler.triggers.crons = [...new Set([...existingCrons, ...crons])]",
8290
- " nitro.hooks.hook('build:before', dedupeCloudflareCrons)",
8291
- " if (nitro.options.preset !== 'netlify') return",
8573
+ "async function setupNetlifySchedules(nitro) {",
8292
8574
  " if (netlifyNameError) throw Object.assign(new Error(netlifyNameError.message), netlifyNameError)",
8293
8575
  " if (!netlifySchedules.length) return",
8294
8576
  " // The server bundle keeps Nitro's entry and also exports the Schedule runner for the scheduled functions.",
8295
- " await writeFile(netlifyEntryFile, `export { default } from ${JSON.stringify(nitro.options.entry)}\\n${netlifyEntryRuntime}`)",
8577
+ " await writeFile(netlifyEntryFile, `export { default } from ${JSON.stringify(nitro.options.entry)}\\nexport { runViteHubSchedule } from ${JSON.stringify(runnerFile)}\\n`)",
8296
8578
  " nitro.options.entry = netlifyEntryFile",
8297
8579
  " // Register after all modules have installed their compiled writers, including Database migrations.",
8298
8580
  " nitro.hooks.hookOnce('build:before', () => {",
8299
8581
  " nitro.hooks.hook('compiled', writeNetlifyScheduleFunctions)",
8300
8582
  " })",
8301
8583
  "}",
8584
+ "",
8585
+ "function setupVercelSchedules(nitro) {",
8586
+ " if (vercelPathError) throw Object.assign(new Error(vercelPathError.message), vercelPathError)",
8587
+ " if (!vercelRoutes.length) return",
8588
+ " for (const { handler, route } of vercelRoutes) {",
8589
+ " nitro.options.handlers.push({ route, lazy: true, handler })",
8590
+ " nitro.options.routeRules[route] = { ...nitro.options.routeRules[route], cache: false, isr: false }",
8591
+ " }",
8592
+ " const base = nitro.options.baseURL.replace(/\\/$/, '')",
8593
+ " const vercelCrons = vercelRoutes.map(({ route, schedule }) => ({ path: `${base}${route}`, schedule }))",
8594
+ " nitro.options.vercel ??= {}",
8595
+ " nitro.options.vercel.config ??= {}",
8596
+ " const paths = new Set(vercelCrons.map(cron => cron.path))",
8597
+ " const existing = Array.isArray(nitro.options.vercel.config.crons) ? nitro.options.vercel.config.crons.filter(cron => !paths.has(cron?.path)) : []",
8598
+ " nitro.options.vercel.config.crons = [...existing, ...vercelCrons]",
8599
+ "}",
8600
+ "",
8601
+ "export default async function vitehubScheduleModule(nitro) {",
8602
+ " nitro.options.cloudflare ??= {}",
8603
+ " nitro.options.cloudflare.wrangler ??= {}",
8604
+ " nitro.options.cloudflare.wrangler.triggers ??= {}",
8605
+ " const existingCrons = Array.isArray(nitro.options.cloudflare.wrangler.triggers.crons) ? nitro.options.cloudflare.wrangler.triggers.crons : []",
8606
+ " nitro.options.cloudflare.wrangler.triggers.crons = [...new Set([...existingCrons, ...crons])]",
8607
+ " nitro.hooks.hook('build:before', dedupeCloudflareCrons)",
8608
+ " if (nitro.options.preset === 'netlify') await setupNetlifySchedules(nitro)",
8609
+ " if (nitro.options.preset === 'vercel') setupVercelSchedules(nitro)",
8610
+ "}",
8302
8611
  ""
8303
8612
  ].join("\n");
8304
8613
  }
@@ -8332,6 +8641,7 @@ async function writeNitroSchedulePlugin(root, options) {
8332
8641
  ...options.processTimings ? { processTimings: options.processTimings } : {},
8333
8642
  providerDefinitions: options.providerDefinitions,
8334
8643
  providerRegistryFile,
8644
+ ...options.retention ? { retention: options.retention } : {},
8335
8645
  staticRegistryFile,
8336
8646
  runtimeImport: options.runtimeImport
8337
8647
  }))];
@@ -8350,14 +8660,26 @@ async function writeNitroSchedulePlugin(root, options) {
8350
8660
  if (options.providerDefinitions.length > 0) {
8351
8661
  writes.push(writeFileIfChanged(providerRegistryFile, createRuntimeRegistryContents(providerRegistryFile, options.providerDefinitions)));
8352
8662
  writes.push(writeFileIfChanged(providerRegistryFile.replace(/\.js$/, ".d.ts"), renderScheduleRegistryTypes(options.importBase)));
8663
+ const runnerFile = resolve(root, generatedNitroScheduleRunner);
8664
+ const vercelHandlerFile = resolve(root, generatedNitroVercelHandler);
8665
+ const runtimeImport = options.runtimeImport ?? scheduleStaticRuntimeModule;
8666
+ writes.push(writeFileIfChanged(runnerFile, renderNitroScheduleRunner({
8667
+ registryFile: providerRegistryFile,
8668
+ runtimeImport,
8669
+ schedules: options.hostSchedules
8670
+ })));
8671
+ writes.push(writeFileIfChanged(vercelHandlerFile, renderNitroVercelScheduleHandler({
8672
+ runnerFile,
8673
+ runtimeImport
8674
+ })));
8675
+ const vercel = resolveNitroVercelScheduleRoutes(root, options.hostSchedules, options.standaloneScheduleNames);
8676
+ for (const { handler, name } of vercel.routes) writes.push(writeFileIfChanged(handler, renderNitroVercelScheduleRoute(vercelHandlerFile, name)));
8353
8677
  writes.push(writeFileIfChanged(moduleFile, renderNitroScheduleModule({
8354
8678
  crons: options.crons,
8355
- netlify: {
8356
- entryFile: resolve(root, generatedNitroNetlifyEntry),
8357
- registryFile: providerRegistryFile,
8358
- runtimeImport: options.runtimeImport ?? scheduleStaticRuntimeModule,
8359
- schedules: options.netlifySchedules
8360
- }
8679
+ netlifyEntryFile: resolve(root, generatedNitroNetlifyEntry),
8680
+ runnerFile,
8681
+ schedules: options.hostSchedules,
8682
+ vercel
8361
8683
  })));
8362
8684
  }
8363
8685
  await Promise.all(writes);
@@ -8404,8 +8726,15 @@ function shouldEmitStandaloneProviderOutput(definitions, options) {
8404
8726
  if (hasServerScheduleDefinitions(definitions)) return hasViteSuffixScheduleDefinitions(definitions);
8405
8727
  return definitions.length > 0;
8406
8728
  }
8729
+ function readNitroPreset(nitro) {
8730
+ return isObject(nitro) && typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOST || "";
8731
+ }
8732
+ function keepsScheduleRunsInWorkerMemory(nitroPreset, processRuntime, schedules) {
8733
+ return !processRuntime && schedules > 0 && nitroPreset.startsWith("cloudflare");
8734
+ }
8407
8735
  async function createScheduleNitroConfig(options = {}) {
8408
8736
  const processRuntime = resolveProcessRuntimeOptions(options.runtime);
8737
+ const retention = resolveScheduleRetention(options.retention, processRuntime);
8409
8738
  const roots = resolveSchedulePluginRoots(options.root || process.cwd(), options);
8410
8739
  const internal = options;
8411
8740
  const hints = internal.hints ?? {
@@ -8432,9 +8761,11 @@ async function createScheduleNitroConfig(options = {}) {
8432
8761
  });
8433
8762
  const cronOverrides = resolveCronOverrides(options.cron, options.preliminary ? void 0 : definitions, options);
8434
8763
  const installNitroPlugin = shouldInstallNitroSchedulePlugin(definitions, options, startableDefinitions.length);
8435
- const nitroPreset = isRecord(options.nitro) && typeof options.nitro.preset === "string" ? options.nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOST || "";
8764
+ const nitroPreset = readNitroPreset(options.nitro);
8765
+ if (options.command === "build" && !internal.preliminary && keepsScheduleRunsInWorkerMemory(internal.resolvedNitroPreset ?? nitroPreset, Boolean(processRuntime), definitions.length + startableDefinitions.length)) reportViteHubHint(hints, scheduleErrorDiagnostics.SCHEDULE_RUNS_IN_WORKER_MEMORY());
8436
8766
  const standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
8437
- const vercelDefinitions = options.command === "build" && nitroPreset.startsWith("vercel") && (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options) ? definitions.filter((definition) => standaloneProviderSource === void 0 || definition.source === standaloneProviderSource) : [];
8767
+ const standaloneDefinitions = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options) ? definitions.filter((definition) => standaloneProviderSource === void 0 || definition.source === standaloneProviderSource) : [];
8768
+ const vercelDefinitions = options.command === "build" && nitroPreset.startsWith("vercel") ? standaloneDefinitions : [];
8438
8769
  if (!installNitroPlugin && !vercelDefinitions.length) return null;
8439
8770
  let nitro = options.nitro;
8440
8771
  if (vercelDefinitions.length) nitro = mergeNitroVercelCrons(nitro, vercelDefinitions, await readDefinitionCrons(vercelDefinitions, cronOverrides));
@@ -8445,13 +8776,14 @@ async function createScheduleNitroConfig(options = {}) {
8445
8776
  const timeZoneCrons = options.command === "build" ? readTimeZoneCrons(nitroDefinitions, cronOverrides) : {};
8446
8777
  const triggerCrons = Object.fromEntries([...nitroCrons].map(([name, cron]) => [name, cronWithWeekdayNames(cron)]));
8447
8778
  const crons = [...new Set(Object.values(triggerCrons))];
8448
- const netlifySchedules = [...nitroCrons].map(([name, cron]) => ({
8779
+ const hostSchedules = [...nitroCrons].map(([name, cron]) => ({
8449
8780
  cron,
8450
8781
  ...Object.hasOwn(timeZoneCrons, name) ? { inTimeZone: true } : {},
8451
8782
  name
8452
8783
  }));
8453
8784
  const nitroDefinitionNames = new Set(nitroDefinitions.map((definition) => definition.name));
8454
8785
  const staticDefinitions = definitions.filter((definition) => !nitroDefinitionNames.has(definition.name) && !(processRuntime && options.providerOutput === "standalone"));
8786
+ if (processRuntime) for (const definition of staticDefinitions) assertStaticScheduleCron(definition.handler);
8455
8787
  const processTimings = processRuntime && options.command === "build" ? Object.fromEntries(staticDefinitions.flatMap((definition) => {
8456
8788
  const timing = readStaticScheduleTiming(definition.handler);
8457
8789
  return timing ? [[definition.name, timing]] : [];
@@ -8478,11 +8810,13 @@ async function createScheduleNitroConfig(options = {}) {
8478
8810
  importBase: options.importBase,
8479
8811
  leaseDatabaseImport: internal.leaseDatabaseImport,
8480
8812
  memoryProcessStores: internal.memoryProcessStores,
8481
- netlifySchedules,
8813
+ hostSchedules,
8482
8814
  timeZoneCrons,
8483
8815
  processRuntime,
8484
8816
  ...processTimings ? { processTimings } : {},
8485
8817
  providerDefinitions: nitroDefinitions,
8818
+ ...retention ? { retention } : {},
8819
+ standaloneScheduleNames: standaloneDefinitions.map((definition) => definition.name),
8486
8820
  startableDefinitions,
8487
8821
  staticDefinitions,
8488
8822
  runtimeImport: options.runtimeImport
@@ -8535,6 +8869,15 @@ function hubSchedule(options = {}) {
8535
8869
  function createRegistryContents() {
8536
8870
  return renderScheduleRegistryModule(discoverRegistrySchedules());
8537
8871
  }
8872
+ async function writeRegistryTypes(roots, definitions) {
8873
+ const startable = discoverStartableScheduleDefinitions({
8874
+ contributions,
8875
+ rootDir: roots.viteRoot,
8876
+ serverDirs,
8877
+ serverRootDir: roots.projectRoot
8878
+ });
8879
+ await writeScheduleTypes(roots.projectRoot, definitions, startable, internalOptions.importBase);
8880
+ }
8538
8881
  const inspectable = {
8539
8882
  name: SCHEDULE_VITE_PLUGIN_NAME,
8540
8883
  enforce: "pre",
@@ -8549,6 +8892,7 @@ function hubSchedule(options = {}) {
8549
8892
  serverDirs,
8550
8893
  serverRootDir: roots.projectRoot
8551
8894
  });
8895
+ await writeRegistryTypes(roots, definitions);
8552
8896
  emitStandaloneProviderOutput = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options);
8553
8897
  standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
8554
8898
  const nitro = await createScheduleNitroConfig({
@@ -8574,6 +8918,7 @@ function hubSchedule(options = {}) {
8574
8918
  viteRoot = roots.viteRoot;
8575
8919
  contributions = await collectPluginScheduleContributions(config.plugins, roots);
8576
8920
  const definitions = discoverRegistrySchedules();
8921
+ await writeRegistryTypes(roots, definitions);
8577
8922
  emitStandaloneProviderOutput = (options.runtime === void 0 || options.providerOutput === "standalone") && shouldEmitStandaloneProviderOutput(definitions, options);
8578
8923
  standaloneProviderSource = selectStandaloneProviderSource(definitions, options);
8579
8924
  const storage = processStorageOptions((name) => hasVitePlugin(config.plugins, name));
@@ -8586,6 +8931,7 @@ function hubSchedule(options = {}) {
8586
8931
  nitroOwnsPaths: hasNitroConfigContext(config),
8587
8932
  ...storage,
8588
8933
  hints: config,
8934
+ resolvedNitroPreset: nitroPreset,
8589
8935
  root: config.root,
8590
8936
  serverDirs
8591
8937
  });
@@ -8593,21 +8939,42 @@ function hubSchedule(options = {}) {
8593
8939
  const configWithNitro = config;
8594
8940
  configWithNitro.nitro = nitro;
8595
8941
  }
8596
- } else if (command === "build" && typeof Reflect.get(config, "__vitehubNuxtHints") === "function" && options.runtime && !storage.leaseDatabaseImport) reportViteHubHint({
8597
- ...config,
8598
- command
8599
- }, scheduleErrorDiagnostics.SCHEDULE_PROCESS_CLAIMS_IN_MEMORY());
8942
+ } else if (command === "build" && typeof Reflect.get(config, "__vitehubNuxtHints") === "function") {
8943
+ if (options.runtime && !storage.leaseDatabaseImport) reportViteHubHint({
8944
+ ...config,
8945
+ command
8946
+ }, scheduleErrorDiagnostics.SCHEDULE_PROCESS_CLAIMS_IN_MEMORY());
8947
+ const startable = discoverStartableScheduleDefinitions({
8948
+ contributions,
8949
+ rootDir: roots.viteRoot,
8950
+ serverDirs,
8951
+ serverRootDir: roots.projectRoot
8952
+ });
8953
+ if (keepsScheduleRunsInWorkerMemory(readNitroPreset(config.nitro), Boolean(resolveProcessRuntimeOptions(options.runtime)), definitions.length + startable.length)) reportViteHubHint({
8954
+ ...config,
8955
+ command
8956
+ }, scheduleErrorDiagnostics.SCHEDULE_RUNS_IN_WORKER_MEMORY());
8957
+ }
8600
8958
  },
8601
8959
  configEnvironment(name, config) {
8602
8960
  if (!isServerEnvironment(name, config)) return;
8603
8961
  return { resolve: { noExternal: mergeNoExternal(config.resolve?.noExternal) } };
8604
8962
  },
8605
- async handleHotUpdate(context) {
8963
+ hotUpdate(context) {
8606
8964
  const file = normalize(context.file).replace(/\\/g, "/");
8607
8965
  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)));
8608
8966
  const contributedSchedule = contributions.some((contribution) => normalize(contribution.definition.module).replace(/\\/g, "/") === file);
8609
8967
  if (!/\.schedule\.(?:c|m)?[jt]s$/i.test(file) && !serverSchedule && !contributedSchedule) return;
8610
- invalidateScheduleRegistry(context.server);
8968
+ const environment = this.environment;
8969
+ const registry = environment.moduleGraph.getModuleById(RESOLVED_SCHEDULE_REGISTRY_ID);
8970
+ if (registry) {
8971
+ environment.moduleGraph.invalidateModule(registry);
8972
+ if (environment.config.consumer === "server") environment.hot.send({ type: "full-reload" });
8973
+ }
8974
+ if (projectRoot && viteRoot) return writeRegistryTypes({
8975
+ projectRoot,
8976
+ viteRoot
8977
+ }, discoverRegistrySchedules());
8611
8978
  },
8612
8979
  resolveId: {
8613
8980
  filter: { id: /^#vitehub\/schedule\/registry$/ },
@@ -8618,7 +8985,13 @@ function hubSchedule(options = {}) {
8618
8985
  transform: {
8619
8986
  filter: { code: /\/\* @vitehub-schedule-registry \*\// },
8620
8987
  handler(code) {
8621
- return code.replace(/\/\* @vite-ignore \*\/\s*\/\* @vitehub-schedule-registry \*\/\s*[\w$]+/g, JSON.stringify(SCHEDULE_REGISTRY_ID));
8988
+ const output = new MagicString(code);
8989
+ for (const match of code.matchAll(scheduleRegistryImport)) output.overwrite(match.index, match.index + match[0].length, JSON.stringify(SCHEDULE_REGISTRY_ID));
8990
+ if (!output.hasChanged()) return;
8991
+ return {
8992
+ code: output.toString(),
8993
+ map: output.generateMap({ hires: "boundary" })
8994
+ };
8622
8995
  }
8623
8996
  },
8624
8997
  load: {
@@ -8660,6 +9033,7 @@ function hubSchedule(options = {}) {
8660
9033
  ...workflow?.bundleAlias
8661
9034
  };
8662
9035
  const retainedSources = bundles ? await retainProviderOutputSources({
9036
+ aliases,
8663
9037
  artifactDir: resolve(contributionArtifactDir, "sources"),
8664
9038
  paths: [...definitions.map((definition) => definition.handler), ...providerOutputAliasSources(aliases, [rootDir])],
8665
9039
  roots: [rootDir]
@@ -8676,7 +9050,7 @@ function hubSchedule(options = {}) {
8676
9050
  "@vitejs/devtools-rolldown"
8677
9051
  ] : void 0;
8678
9052
  contributeProviderDeploymentOutput(providerOutput, {
8679
- discard: async () => await removeProviderOutputArtifactDir(contributionArtifactDir),
9053
+ discard: async (failure) => await removeProviderOutputArtifactDir(contributionArtifactDir, failure),
8680
9054
  owner: "schedule",
8681
9055
  rootDir,
8682
9056
  write: async ({ signal }) => {
@@ -8703,7 +9077,7 @@ function hubSchedule(options = {}) {
8703
9077
  }
8704
9078
  }, providerOutputGenerations.get(this));
8705
9079
  } catch (error) {
8706
- if (artifactDir) await removeProviderOutputArtifactDir(artifactDir);
9080
+ if (artifactDir) await removeProviderOutputArtifactDir(artifactDir, error);
8707
9081
  await providerOutputGenerations.reset(this, providerOutput, error);
8708
9082
  throw error;
8709
9083
  }