@vite-hub/schedule 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +114 -96
  2. package/dist/console-wEhr0LWn.d.ts +330 -0
  3. package/dist/definition.d.ts +6 -2
  4. package/dist/definition.js +47 -1
  5. package/dist/due-BVMRQ93v.js +144 -0
  6. package/dist/durability.d.ts +14 -0
  7. package/dist/durability.js +23 -0
  8. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  9. package/dist/error-diagnostics-Mpeks7J0.js +166 -0
  10. package/dist/index.d.ts +59 -5
  11. package/dist/index.js +27 -2
  12. package/dist/invariant-DolT9EEx.js +22 -0
  13. package/dist/{kv-storage-Bv9ocZT-.d.ts → kv-storage-C0KZZB6v.d.ts} +2 -2
  14. package/dist/{kv-storage-DWinmLLy.js → kv-storage-iJChCS5A.js} +2 -2
  15. package/dist/object-Da1zyPCR.js +11 -0
  16. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  17. package/dist/{operations-gk2qzhYV.js → operations-DwZWFIUX.js} +75 -22
  18. package/dist/operations.d.ts +27 -4
  19. package/dist/operations.js +127 -730
  20. package/dist/os.d.ts +167 -0
  21. package/dist/os.js +1659 -0
  22. package/dist/runtime/console.d.ts +12 -0
  23. package/dist/runtime/console.js +85 -0
  24. package/dist/runtime/kv.d.ts +1 -1
  25. package/dist/runtime/kv.js +1 -1
  26. package/dist/runtime/process.d.ts +32 -5
  27. package/dist/runtime/process.js +401 -413
  28. package/dist/runtime/state.d.ts +2 -9
  29. package/dist/runtime/state.js +2 -2
  30. package/dist/runtime/static.d.ts +28 -2
  31. package/dist/runtime/static.js +2 -2
  32. package/dist/runtime.d.ts +34 -32
  33. package/dist/runtime.js +6 -5
  34. package/dist/started-BuGmnus4.js +201 -0
  35. package/dist/started-Bx7MDbrl.js +146 -0
  36. package/dist/{execute-BJrgNgQ0.js → started-errors-p7cu_rI7.js} +69 -20
  37. package/dist/{state-DSxmHPn3.js → state-B-Fuyfb4.js} +42 -22
  38. package/dist/state-Do2wV4Tx.d.ts +49 -0
  39. package/dist/{static-6g82xguw.js → static-DQwzzvPg.js} +63 -42
  40. package/dist/store-Df0-fzCl.d.ts +53 -0
  41. package/dist/time-zone-SBldrUgt.js +59 -0
  42. package/dist/{types-CHdV9FQU.d.ts → types-Cw5LjPuc.d.ts} +62 -8
  43. package/dist/vite.d.ts +255 -2
  44. package/dist/vite.js +5876 -2
  45. package/dist/{wait-until-BmIqRo4x.js → wait-until-Dy4Bn3ZN.js} +26 -1
  46. package/package.json +19 -24
  47. package/dist/definition-CMiOg1lg.js +0 -111
  48. package/dist/error-diagnostics-A_8Kp-48.js +0 -116
  49. package/dist/error-diagnostics-in7mif5s.js +0 -45
  50. package/dist/nuxt.d.ts +0 -17
  51. package/dist/nuxt.js +0 -27
  52. package/dist/store-QAOd8bxm.d.ts +0 -11
  53. package/dist/vite-BAVyZ8hZ.d.ts +0 -474
  54. package/dist/vite-BJwZkMrn.js +0 -5193
@@ -1,6 +1,8 @@
1
- import { i as createScheduleError, r as validateScheduledAt, t as runWithScheduleWaitUntil } from "./wait-until-BmIqRo4x.js";
2
- import { r as loadScheduleDefinition, t as getScheduleRunStore } from "./state-DSxmHPn3.js";
3
- import { serializeResponse, toResponse } from "@vite-hub/runtime";
1
+ import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
2
+ import { a as validateScheduledAt, i as scheduleIdempotencyKey, o as createScheduleError, r as parseScheduledAt, t as runWithScheduleWaitUntil } from "./wait-until-Dy4Bn3ZN.js";
3
+ import { r as getScheduleRunStore } from "./state-B-Fuyfb4.js";
4
+ import { defineErrors, serializeResponse, toResponse } from "@vite-hub/runtime";
5
+ import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
4
6
  //#region ../internal/src/runtime/random.ts
5
7
  function randomId(prefix) {
6
8
  const body = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
@@ -86,6 +88,7 @@ function toHandlerContext(run, attempt, waitUntil) {
86
88
  return {
87
89
  attemptId: attempt.id,
88
90
  id: run.id,
91
+ idempotencyKey: scheduleIdempotencyKey(run.scheduleId, run.scheduledAt),
89
92
  runId: run.id,
90
93
  scheduleId: run.scheduleId,
91
94
  scheduledAt: run.scheduledAt,
@@ -123,6 +126,22 @@ async function failRun(run, attempt, error, store = getScheduleRunStore()) {
123
126
  updatedAt: now
124
127
  }));
125
128
  }
129
+ const stoppedAttemptError = {
130
+ message: "The process that ran this attempt stopped before the attempt finished.",
131
+ name: "ScheduleAttemptStopped"
132
+ };
133
+ async function failStoppedAttempts(run, store) {
134
+ const now = /* @__PURE__ */ new Date();
135
+ for (const attempt of await store.listAttempts(run.id)) {
136
+ if (attempt.status !== "running") continue;
137
+ await store.updateAttempt(attempt.id, {
138
+ completedAt: now,
139
+ error: stoppedAttemptError,
140
+ status: "failed",
141
+ updatedAt: now
142
+ });
143
+ }
144
+ }
126
145
  async function createScheduleRun(options) {
127
146
  const scheduledAt = validateScheduledAt(options.scheduledAt ?? /* @__PURE__ */ new Date());
128
147
  return (await createOrGetRun({
@@ -136,11 +155,18 @@ async function executeSchedule(options) {
136
155
  ...options,
137
156
  scheduledAt
138
157
  });
139
- if (!created) return run;
140
158
  const runStore = options.runStore ?? getScheduleRunStore();
159
+ if (!created) {
160
+ if (!options.claimed || run.status === "succeeded" || run.status === "failed") {
161
+ options.onExecution?.();
162
+ return run;
163
+ }
164
+ await failStoppedAttempts(run, runStore);
165
+ }
141
166
  const attempt = await startAttempt(run, runStore);
167
+ options.onExecution?.();
142
168
  try {
143
- const value = await runWithScheduleWaitUntil((waitUntil) => options.definition.handler(toHandlerContext(run, attempt, waitUntil)), options.waitUntil);
169
+ const value = await runInRunScopes(() => runWithScheduleWaitUntil((waitUntil) => options.definition.handler(toHandlerContext(run, attempt, waitUntil)), options.waitUntil));
144
170
  return await completeRun(run, attempt, await serializeResponse(toResponse(value)), runStore);
145
171
  } catch (error) {
146
172
  const failed = await failRun(run, attempt, error, runStore);
@@ -150,7 +176,9 @@ async function executeSchedule(options) {
150
176
  }
151
177
  async function executeStaticSchedule(options) {
152
178
  return await executeSchedule({
179
+ ...options.claimed ? { claimed: true } : {},
153
180
  definition: options.definition,
181
+ onExecution: options.onExecution,
154
182
  scheduleId: options.name,
155
183
  source: "static",
156
184
  scheduledAt: options.scheduledAt,
@@ -158,28 +186,22 @@ async function executeStaticSchedule(options) {
158
186
  waitUntil: options.waitUntil
159
187
  });
160
188
  }
161
- function isObjectRecord(value) {
162
- return Object(value) === value && !Array.isArray(value);
163
- }
164
189
  function isStaticScheduleDefinition(value) {
165
- return isObjectRecord(value) && Object.hasOwn(value, "handler") && typeof value.handler === "function" && Object.hasOwn(value, "cron");
190
+ return isRecordOrFunction(value) && Object.hasOwn(value, "handler") && typeof value.handler === "function" && Object.hasOwn(value, "cron");
166
191
  }
167
192
  async function loadStaticScheduleDefinition(name, registry) {
168
- let loaded;
169
- if (registry) {
170
- const entry = Object.hasOwn(registry, name) ? registry[name] : void 0;
171
- loaded = typeof entry === "function" ? await entry() : void 0;
172
- } else loaded = await loadScheduleDefinition(name);
173
- const record = isObjectRecord(loaded) ? loaded : void 0;
193
+ const entry = Object.hasOwn(registry, name) ? registry[name] : void 0;
194
+ const loaded = typeof entry === "function" ? await entry() : void 0;
195
+ const record = isRecordOrFunction(loaded) ? loaded : void 0;
174
196
  return record && isStaticScheduleDefinition(record) ? record : record && Object.hasOwn(record, "default") && isStaticScheduleDefinition(record.default) ? record.default : void 0;
175
197
  }
176
- /** Runs a manually dispatchable static Schedule Definition immediately. */
177
- async function runSchedule(name, options = {}) {
178
- const definition = typeof name === "string" && name ? await loadStaticScheduleDefinition(name, options.registry) : void 0;
198
+ /** Runs a manually dispatchable static Schedule Definition of `registry` immediately. */
199
+ async function runScheduleFrom(registry, name, options = {}) {
200
+ const definition = typeof name === "string" && name ? await loadStaticScheduleDefinition(name, registry) : void 0;
179
201
  if (!definition) throw createScheduleError("SCHEDULE_DEFINITION_NOT_FOUND");
180
202
  if (definition.options?.manual !== true) throw createScheduleError("SCHEDULE_MANUAL_RUN_DISABLED");
203
+ const scheduledAt = parseScheduledAt(options.scheduledAt);
181
204
  const runStore = getScheduleRunStore();
182
- const scheduledAt = /* @__PURE__ */ new Date();
183
205
  const runIdSuffix = randomId("manual");
184
206
  try {
185
207
  return await executeSchedule({
@@ -198,4 +220,31 @@ async function runSchedule(name, options = {}) {
198
220
  }
199
221
  }
200
222
  //#endregion
201
- export { runSchedule as i, executeSchedule as n, executeStaticSchedule as r, createScheduleRun as t };
223
+ //#region src/started-errors.ts
224
+ const startedScheduleErrors = /*#__PURE__*/ defineErrors({
225
+ docs: "https://vitehub.dev/docs/schedule/diagnostics",
226
+ codes: {
227
+ SCHEDULE_NOT_STARTABLE: {
228
+ why: ({ name }) => `No Schedule Definition without \`cron\` is named "${name}", so \`startSchedule()\` cannot start it.`,
229
+ fix: "Add `server/schedules/<name>.ts` with `export default defineSchedule({ handler })` and no `cron`. A Definition with its own `cron` runs only on that cron."
230
+ },
231
+ SCHEDULE_INVALID_OPTIONS: {
232
+ why: ({ problem }) => `\`startSchedule()\` options are invalid: ${problem}`,
233
+ fix: "Pass `{ at }` for one run, or `{ cron, timeZone }` for a repeating Schedule, and a JSON `payload`."
234
+ },
235
+ SCHEDULE_NOT_FOUND: {
236
+ why: ({ id }) => `No started Schedule has the id "${id}". It ran its last time, was cancelled, or never existed.`,
237
+ fix: "List the started Schedules with `listSchedules()` or `vitehub schedule list`."
238
+ },
239
+ SCHEDULE_STORE_MISSING: {
240
+ why: "This server has no store for started Schedules.",
241
+ fix: "Add a Schedule Definition without `cron` in `server/schedules/`, enable `kv`, and build with Nitro. On Node, also set `schedule: { runtime: { driver: \"process\" } }`."
242
+ },
243
+ SCHEDULE_STORE_FAILED: {
244
+ why: "The store of started Schedules failed. `error.cause` has the store error.",
245
+ fix: "Check that KV is enabled and reachable from this server, then try again."
246
+ }
247
+ }
248
+ });
249
+ //#endregion
250
+ export { runScheduleFrom as a, executeStaticSchedule as i, createScheduleRun as n, toRunId as o, executeSchedule as r, randomId as s, startedScheduleErrors as t };
@@ -1,19 +1,8 @@
1
- import { t as scheduleErrorDiagnostics } from "./error-diagnostics-in7mif5s.js";
1
+ import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
2
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-Mpeks7J0.js";
2
3
  import { AsyncLocalStorage } from "node:async_hooks";
3
4
  //#region src/runtime/store.ts
4
5
  const maxLegacyHistoryRecords = 1e3;
5
- /** Raised when the metadata index cannot provide a complete history safely. */
6
- var ScheduleHistoryIncompleteError = class extends Error {
7
- recordCount;
8
- maxRecords;
9
- code = "SCHEDULE_HISTORY_INCOMPLETE";
10
- constructor(recordCount, maxRecords) {
11
- super(`Schedule run history is incomplete because ${recordCount} records have no usable metadata index (maximum fallback is ${maxRecords}). Rebuild the schedule run index before listing history.`);
12
- this.recordCount = recordCount;
13
- this.maxRecords = maxRecords;
14
- this.name = "ScheduleHistoryIncompleteError";
15
- }
16
- };
17
6
  function trimPrefix(prefix) {
18
7
  return prefix.replace(/^\/+|\/+$/g, "");
19
8
  }
@@ -155,7 +144,7 @@ function createMemoryScheduleRunStore() {
155
144
  };
156
145
  }
157
146
  function selectRuns(runs, options = {}) {
158
- const selected = runs.filter((run) => options.scheduleId === void 0 || run.scheduleId === options.scheduleId);
147
+ const selected = runs.filter((run) => (options.scheduleId === void 0 || run.scheduleId === options.scheduleId) && (options.idPrefix === void 0 || run.id.startsWith(options.idPrefix)));
159
148
  selected.sort((left, right) => right.scheduledAt.getTime() - left.scheduledAt.getTime());
160
149
  return options.limit === void 0 ? selected : selected.slice(0, options.limit);
161
150
  }
@@ -200,6 +189,7 @@ function createKVScheduleRunStore(options) {
200
189
  const recordsByKey = /* @__PURE__ */ new Map();
201
190
  function groupRun(key, metadata) {
202
191
  const entry = {
192
+ id: metadata.id,
203
193
  key,
204
194
  scheduledAt: metadata.scheduledAt
205
195
  };
@@ -258,11 +248,15 @@ function createKVScheduleRunStore(options) {
258
248
  };
259
249
  }
260
250
  async function listRuns(options, snapshot) {
261
- if (snapshot.unknown.length > maxLegacyHistoryRecords) throw new ScheduleHistoryIncompleteError(snapshot.unknown.length, maxLegacyHistoryRecords);
251
+ if (snapshot.unknown.length > maxLegacyHistoryRecords) throw scheduleErrorDiagnostics.SCHEDULE_HISTORY_INCOMPLETE({
252
+ maxRecords: maxLegacyHistoryRecords,
253
+ recordCount: snapshot.unknown.length
254
+ });
262
255
  const { keys, recordsByKey } = snapshot;
263
256
  const known = options.scheduleId === void 0 ? snapshot.known : snapshot.bySchedule.get(options.scheduleId) ?? [];
257
+ const matching = options.idPrefix === void 0 ? known : known.filter((entry) => entry.id.startsWith(options.idPrefix));
264
258
  const records = [];
265
- const selectedKeys = options.scheduleId === void 0 && options.limit === void 0 ? keys : known.slice(0, options.limit ?? known.length).map((entry) => entry.key);
259
+ const selectedKeys = options.scheduleId === void 0 && options.idPrefix === void 0 && options.limit === void 0 ? keys : matching.slice(0, options.limit ?? matching.length).map((entry) => entry.key);
266
260
  for (let index = 0; index < selectedKeys.length; index += 16) {
267
261
  const batch = await Promise.all(selectedKeys.slice(index, index + 16).map(async (key) => {
268
262
  if (recordsByKey.has(key)) return recordsByKey.get(key);
@@ -374,16 +368,16 @@ function createKVScheduleRunStore(options) {
374
368
  //#endregion
375
369
  //#region src/runtime/state.ts
376
370
  let runtimeRegistry;
371
+ const processDefinitions = /* @__PURE__ */ new Set();
377
372
  let runtimeRegistryVersion = 0;
378
373
  let runStore;
374
+ let startedRuntime;
375
+ let occurrenceClaims;
379
376
  const loadedRegistryEntries = /* @__PURE__ */ new Map();
380
377
  const loadingRegistryEntries = /* @__PURE__ */ new Map();
381
378
  const loadingRegistryStorage = new AsyncLocalStorage();
382
- function isObjectRecord(value) {
383
- return Object(value) === value && !Array.isArray(value);
384
- }
385
379
  function isScheduleDefinition(value) {
386
- return isObjectRecord(value) && Object.hasOwn(value, "handler") && typeof Reflect.get(value, "handler") === "function";
380
+ return isRecordOrFunction(value) && Object.hasOwn(value, "handler") && typeof Reflect.get(value, "handler") === "function";
387
381
  }
388
382
  function setScheduleRuntimeRegistry(registry) {
389
383
  runtimeRegistry = registry;
@@ -394,12 +388,35 @@ function setScheduleRuntimeRegistry(registry) {
394
388
  function getScheduleRuntimeRegistry() {
395
389
  return runtimeRegistry;
396
390
  }
391
+ /** Publish only ready runtimes, retaining earlier snapshots until their controllers close. */
392
+ function registerProcessScheduleDefinitions(definitions) {
393
+ processDefinitions.add(definitions);
394
+ return () => {
395
+ processDefinitions.delete(definitions);
396
+ };
397
+ }
398
+ function getProcessScheduleDefinitions() {
399
+ return [...processDefinitions].at(-1);
400
+ }
397
401
  function setScheduleRunStore(store) {
398
402
  runStore = store;
399
403
  }
400
404
  function getScheduleRunStore() {
401
405
  return runStore ??= createMemoryScheduleRunStore();
402
406
  }
407
+ /** Installs the claims that make each occurrence run in one process only. The Process Runtime installs them. */
408
+ function setScheduleOccurrenceClaims(claims) {
409
+ occurrenceClaims = claims;
410
+ }
411
+ function getScheduleOccurrenceClaims() {
412
+ return occurrenceClaims;
413
+ }
414
+ function setStartedScheduleRuntime(runtime) {
415
+ startedRuntime = runtime;
416
+ }
417
+ function getStartedScheduleRuntime() {
418
+ return startedRuntime;
419
+ }
403
420
  async function loadScheduleDefinition(name) {
404
421
  const entry = runtimeRegistry && Object.hasOwn(runtimeRegistry, name) ? runtimeRegistry[name] : void 0;
405
422
  if (typeof entry !== "function") return;
@@ -417,7 +434,7 @@ async function loadScheduleDefinition(name) {
417
434
  const loadingEntry = Promise.resolve().then(() => loadingRegistryStorage.run(nextActiveLoads, async () => {
418
435
  const loaded = await entry();
419
436
  if (isScheduleDefinition(loaded)) return loaded;
420
- if (isObjectRecord(loaded) && Object.hasOwn(loaded, "default")) {
437
+ if (isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default")) {
421
438
  const definition = Reflect.get(loaded, "default");
422
439
  if (isScheduleDefinition(definition)) return definition;
423
440
  }
@@ -439,10 +456,13 @@ async function loadScheduleDefinition(name) {
439
456
  }
440
457
  function resetScheduleRuntime() {
441
458
  runtimeRegistry = void 0;
459
+ processDefinitions.clear();
442
460
  runtimeRegistryVersion++;
443
461
  runStore = void 0;
462
+ startedRuntime = void 0;
463
+ occurrenceClaims = void 0;
444
464
  loadedRegistryEntries.clear();
445
465
  loadingRegistryEntries.clear();
446
466
  }
447
467
  //#endregion
448
- export { setScheduleRunStore as a, createMemoryScheduleRunStore as c, resetScheduleRuntime as i, getScheduleRuntimeRegistry as n, setScheduleRuntimeRegistry as o, loadScheduleDefinition as r, createKVScheduleRunStore as s, getScheduleRunStore as t };
468
+ export { getStartedScheduleRuntime as a, resetScheduleRuntime as c, setScheduleRuntimeRegistry as d, setStartedScheduleRuntime as f, keySegments as g, joinKey as h, getScheduleRuntimeRegistry as i, setScheduleOccurrenceClaims as l, createMemoryScheduleRunStore as m, getScheduleOccurrenceClaims as n, loadScheduleDefinition as o, createKVScheduleRunStore as p, getScheduleRunStore as r, registerProcessScheduleDefinitions as s, getProcessScheduleDefinitions as t, setScheduleRunStore as u };
@@ -0,0 +1,49 @@
1
+ import { a as ScheduleDefinitionRegistry, b as StartedScheduleStore, g as ScheduleRunStore, n as ScheduleDefinition, s as ScheduleRegistryDefinition } from "./types-Cw5LjPuc.js";
2
+ import { LeaseStore } from "@vite-hub/runtime";
3
+ //#region src/runtime/claims.d.ts
4
+ /** `held` when another process holds the occurrence now, `done` when a process finished it, `ran` when this call ran it. */
5
+ type OccurrenceClaimResult = "done" | "held" | "ran";
6
+ /** Runs each Schedule occurrence in one process of all the processes that share `leases`. */
7
+ interface OccurrenceClaims {
8
+ /**
9
+ * Runs `run` when this process gets the claim on `runId` and no process finished it. While `run` works, the claim is
10
+ * renewed. Call `markFinal` before invoking the handler or when an existing run is final. Then a done marker stays
11
+ * for `doneTtlMs`, also when the handler throws. Errors before `markFinal` leave the occurrence retryable.
12
+ */
13
+ run(runId: string, run: (markFinal: () => void) => Promise<unknown>): Promise<OccurrenceClaimResult>;
14
+ }
15
+ //#endregion
16
+ //#region src/runtime/state.d.ts
17
+ /** The cron and time zone of a Schedule that the Process Runtime runs. */
18
+ type ProcessScheduleTimingRecord = Pick<ScheduleDefinition, "cron" | "timeZone">;
19
+ /** What `startSchedule()` and the started-Schedule tick use. The generated Nitro plugin installs it. */
20
+ interface StartedScheduleRuntime {
21
+ /** How far back the first tick after a start runs cron minutes that no tick checked. */
22
+ catchUpMs: number;
23
+ /** Last minute, in epoch milliseconds, that a tick of this process checked. */
24
+ checkedThrough?: number;
25
+ /** Occurrences that another process held at a tick, by run id. The next tick tries them again. */
26
+ held?: Map<string, {
27
+ scheduledAt: Date;
28
+ scheduleId: string;
29
+ }>;
30
+ /** Schedule Definitions without `cron`, by name. */
31
+ registry: ScheduleDefinitionRegistry;
32
+ store: StartedScheduleStore;
33
+ }
34
+ declare function setScheduleRuntimeRegistry(registry: ScheduleDefinitionRegistry | undefined): void;
35
+ declare function getScheduleRuntimeRegistry(): ScheduleDefinitionRegistry | undefined;
36
+ /** Publish only ready runtimes, retaining earlier snapshots until their controllers close. */
37
+ declare function registerProcessScheduleDefinitions(definitions: ReadonlyMap<string, ProcessScheduleTimingRecord>): () => void;
38
+ declare function getProcessScheduleDefinitions(): ReadonlyMap<string, ProcessScheduleTimingRecord> | undefined;
39
+ declare function setScheduleRunStore(store: ScheduleRunStore | undefined): void;
40
+ declare function getScheduleRunStore(): ScheduleRunStore;
41
+ /** Installs the claims that make each occurrence run in one process only. The Process Runtime installs them. */
42
+ declare function setScheduleOccurrenceClaims(claims: OccurrenceClaims | undefined): void;
43
+ declare function getScheduleOccurrenceClaims(): OccurrenceClaims | undefined;
44
+ declare function setStartedScheduleRuntime(runtime: StartedScheduleRuntime | undefined): void;
45
+ declare function getStartedScheduleRuntime(): StartedScheduleRuntime | undefined;
46
+ declare function loadScheduleDefinition(name: string): Promise<ScheduleRegistryDefinition | undefined>;
47
+ declare function resetScheduleRuntime(): void;
48
+ //#endregion
49
+ export { getScheduleRuntimeRegistry as a, registerProcessScheduleDefinitions as c, setScheduleRunStore as d, setScheduleRuntimeRegistry as f, getScheduleRunStore as i, resetScheduleRuntime as l, getProcessScheduleDefinitions as n, getStartedScheduleRuntime as o, setStartedScheduleRuntime as p, getScheduleOccurrenceClaims as r, loadScheduleDefinition as s, StartedScheduleRuntime as t, setScheduleOccurrenceClaims as u };
@@ -1,7 +1,9 @@
1
- import { t as scheduleErrorDiagnostics } from "./error-diagnostics-in7mif5s.js";
2
- import { a as invalidScheduleValueDetails, i as createScheduleError, n as isScheduleDate, r as validateScheduledAt, t as runWithScheduleWaitUntil } from "./wait-until-BmIqRo4x.js";
1
+ import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
2
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-Mpeks7J0.js";
3
+ import { a as validateScheduledAt, i as scheduleIdempotencyKey, n as isScheduleDate, o as createScheduleError, s as invalidScheduleValueDetails, t as runWithScheduleWaitUntil } from "./wait-until-Dy4Bn3ZN.js";
4
+ import { n as latestCronMinute, t as isScheduleDue } from "./due-BVMRQ93v.js";
3
5
  import { normalizeRuntimeDiagnosticError } from "@vite-hub/runtime";
4
- import { hasRuntimeType } from "@vite-hub/runtime/internal/runtime-type";
6
+ import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
5
7
  //#region ../internal/src/secret.ts
6
8
  const secretEncoder = new TextEncoder();
7
9
  /**
@@ -23,6 +25,7 @@ function isViteHubSecretEqual(actual, expected) {
23
25
  function isViteHubBearerSecretEqual(authorization, expected) {
24
26
  return isViteHubSecretEqual(/^Bearer\s+(.+)$/i.exec(authorization ?? "")?.[1], expected);
25
27
  }
28
+ Object.freeze({ prefix: "sha256=" });
26
29
  //#endregion
27
30
  //#region src/runtime/static.ts
28
31
  const intrinsicErrorIsError = Error.isError;
@@ -88,30 +91,55 @@ function isScheduleRuntimeError(error) {
88
91
  return false;
89
92
  }
90
93
  }
94
+ /**
95
+ * Estimates a wake minute from callback time when the host supplies no scheduled timestamp. This is the newest UTC
96
+ * cron match within one day, or the current minute when none matches. It cannot identify a delayed or retried wake
97
+ * after another cron match; callers must not treat it as the provider's occurrence identity.
98
+ */
99
+ function scheduledWakeTime(cron, now = /* @__PURE__ */ new Date()) {
100
+ return latestCronMinute(normalizeCron(cron), now);
101
+ }
102
+ /**
103
+ * Returns `true` when a host wake at `scheduledAt` is an occurrence of the Definition's cron in its `timeZone`. The host
104
+ * runs a wider UTC cron for a time-zoned Schedule, so the runtime skips the wakes that are not local occurrences.
105
+ */
106
+ function isTimeZoneWakeDue(definition, name, scheduledAt) {
107
+ const minute = /* @__PURE__ */ new Date(Math.floor(scheduledAt.getTime() / 6e4) * 6e4);
108
+ return isScheduleDue({
109
+ cron: definition.cron,
110
+ id: name,
111
+ ...definition.timeZone ? { timeZone: definition.timeZone } : {}
112
+ }, minute);
113
+ }
91
114
  function createStaticScheduleRun(options) {
92
115
  const scheduledAt = validateScheduledAt(options.scheduledAt);
93
116
  return {
94
117
  cron: options.cron,
95
118
  id: `run_${options.name}_${scheduledAt.toISOString()}`,
119
+ idempotencyKey: scheduleIdempotencyKey(options.name, scheduledAt),
96
120
  scheduleId: options.name,
97
121
  scheduledAt,
98
122
  waitUntil: options.waitUntil
99
123
  };
100
124
  }
101
125
  async function executeStaticSchedule(options) {
102
- return await runWithScheduleWaitUntil((waitUntil) => options.definition.handler(createStaticScheduleRun({
126
+ return await runInRunScopes(() => runWithScheduleWaitUntil((waitUntil) => options.definition.handler(createStaticScheduleRun({
103
127
  ...options,
104
128
  waitUntil
105
- })), options.waitUntil);
129
+ })), options.waitUntil));
106
130
  }
107
131
  async function executeMatchingStaticSchedules(options) {
108
- if (!hasRuntimeType(options.cron, "string") || !options.cron.trim()) throw createScheduleError("SCHEDULE_INVALID_CRON", { details: invalidScheduleValueDetails("cron", options.cron) });
132
+ if (typeof options.cron !== "string" || !options.cron.trim()) throw createScheduleError("SCHEDULE_INVALID_CRON", { details: invalidScheduleValueDetails("cron", options.cron) });
109
133
  const cron = normalizeCron(options.cron);
110
134
  const scheduledAt = validateScheduledAt(options.scheduledAt);
111
135
  const runs = [];
112
136
  for (const [name, load] of Object.entries(options.registry)) {
113
137
  const definition = unwrapScheduleDefinition(await load());
114
- if (!definition || normalizeCron(definition.cron) !== cron) continue;
138
+ if (!definition) continue;
139
+ const override = options.cronOverrides && Object.hasOwn(options.cronOverrides, name) ? options.cronOverrides[name] : void 0;
140
+ const timeZoneCron = override === void 0 && options.timeZoneCrons && Object.hasOwn(options.timeZoneCrons, name) ? options.timeZoneCrons[name] : void 0;
141
+ if (normalizeCron(override ?? timeZoneCron ?? definition.cron) !== cron) continue;
142
+ if (timeZoneCron !== void 0 && !isTimeZoneWakeDue(definition, name, scheduledAt)) continue;
115
143
  runs.push({
116
144
  name,
117
145
  run: executeStaticSchedule({
@@ -139,15 +167,17 @@ async function executeCloudflareStaticSchedules(event, options) {
139
167
  return await runWithCloudflareServerEnv(event, async (waitUntil) => {
140
168
  return await executeMatchingStaticSchedules({
141
169
  cron: scheduled.cron,
170
+ cronOverrides: options.cronOverrides,
142
171
  registry: options.registry,
143
172
  scheduledAt: scheduled.scheduledAt,
173
+ timeZoneCrons: options.timeZoneCrons,
144
174
  waitUntil
145
175
  });
146
176
  }, options.waitUntil ?? readCloudflareWaitUntil(event));
147
177
  }
148
178
  function readCloudflareScheduledEvent(event) {
149
179
  const cron = event.controller?.cron ?? event.cron;
150
- if (!hasRuntimeType(cron, "string") || !cron.trim()) throw scheduleErrorDiagnostics.SCHEDULE_R0027({ message: "[vitehub:schedule] Cloudflare scheduled event is missing a cron string." });
180
+ if (typeof cron !== "string" || !cron.trim()) throw scheduleErrorDiagnostics.SCHEDULE_R0027({ message: "[vitehub:schedule] Cloudflare scheduled event is missing a cron string." });
151
181
  const scheduledTime = event.controller?.scheduledTime ?? event.scheduledTime;
152
182
  const scheduledAt = isScheduleDate(scheduledTime) ? new Date(Date.prototype.getTime.call(scheduledTime)) : scheduledTime === void 0 ? /* @__PURE__ */ new Date() : new Date(scheduledTime);
153
183
  if (Number.isNaN(scheduledAt.getTime())) throw scheduleErrorDiagnostics.SCHEDULE_R0028({ message: "[vitehub:schedule] Cloudflare scheduled event has an invalid scheduledTime." });
@@ -185,36 +215,27 @@ function restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv) {
185
215
  if (hadGlobalEnv) globals.__env__ = previousGlobalEnv;
186
216
  else delete globals.__env__;
187
217
  }
188
- function isRecord(value) {
189
- return Object(value) === value && !Array.isArray(value);
190
- }
191
218
  function isCallable(value) {
192
- if (value === null || value === void 0 || Object(value) !== value) return false;
193
- try {
194
- Function.prototype.toString.call(value);
195
- return true;
196
- } catch {
197
- return false;
198
- }
219
+ return typeof value === "function" || typeof value === "undefined" && value !== void 0;
199
220
  }
200
221
  function readCloudflareWaitUntil(event) {
201
- const context = isRecord(event.context) ? event.context : void 0;
202
- const cloudflareContext = isRecord(context?.cloudflare) ? context.cloudflare : void 0;
203
- const platformContext = isRecord(context?._platform) ? context._platform : void 0;
204
- const platformCloudflareContext = isRecord(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
205
- const request = isRecord(event.req) ? event.req : void 0;
206
- const runtime = isRecord(request?.runtime) ? request.runtime : void 0;
207
- const runtimeCloudflare = isRecord(runtime?.cloudflare) ? runtime.cloudflare : void 0;
222
+ const context = isRecordOrFunction(event.context) ? event.context : void 0;
223
+ const cloudflareContext = isRecordOrFunction(context?.cloudflare) ? context.cloudflare : void 0;
224
+ const platformContext = isRecordOrFunction(context?._platform) ? context._platform : void 0;
225
+ const platformCloudflareContext = isRecordOrFunction(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
226
+ const request = isRecordOrFunction(event.req) ? event.req : void 0;
227
+ const runtime = isRecordOrFunction(request?.runtime) ? request.runtime : void 0;
228
+ const runtimeCloudflare = isRecordOrFunction(runtime?.cloudflare) ? runtime.cloudflare : void 0;
208
229
  const owners = [
209
230
  event,
210
231
  context,
211
232
  cloudflareContext,
212
- isRecord(cloudflareContext?.context) ? cloudflareContext.context : void 0,
233
+ isRecordOrFunction(cloudflareContext?.context) ? cloudflareContext.context : void 0,
213
234
  platformCloudflareContext,
214
- isRecord(platformCloudflareContext?.context) ? platformCloudflareContext.context : void 0,
235
+ isRecordOrFunction(platformCloudflareContext?.context) ? platformCloudflareContext.context : void 0,
215
236
  request,
216
237
  runtimeCloudflare,
217
- isRecord(runtimeCloudflare?.context) ? runtimeCloudflare.context : void 0
238
+ isRecordOrFunction(runtimeCloudflare?.context) ? runtimeCloudflare.context : void 0
218
239
  ];
219
240
  for (const owner of owners) {
220
241
  const waitUntil = owner?.waitUntil;
@@ -222,24 +243,24 @@ function readCloudflareWaitUntil(event) {
222
243
  }
223
244
  }
224
245
  function readCloudflareEventEnv(event) {
225
- if (isRecord(event.env)) return event.env;
226
- const context = isRecord(event.context) ? event.context : void 0;
227
- const cloudflareContext = isRecord(context?.cloudflare) ? context.cloudflare : void 0;
228
- if (isRecord(cloudflareContext?.env)) return cloudflareContext.env;
229
- const platformContext = isRecord(context?._platform) ? context._platform : void 0;
230
- const platformCloudflareContext = isRecord(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
231
- if (isRecord(platformCloudflareContext?.env)) return platformCloudflareContext.env;
232
- const request = isRecord(event.req) ? event.req : void 0;
233
- const runtime = isRecord(request?.runtime) ? request.runtime : void 0;
234
- const runtimeCloudflare = isRecord(runtime?.cloudflare) ? runtime.cloudflare : void 0;
235
- return isRecord(runtimeCloudflare?.env) ? runtimeCloudflare.env : void 0;
246
+ if (isRecordOrFunction(event.env)) return event.env;
247
+ const context = isRecordOrFunction(event.context) ? event.context : void 0;
248
+ const cloudflareContext = isRecordOrFunction(context?.cloudflare) ? context.cloudflare : void 0;
249
+ if (isRecordOrFunction(cloudflareContext?.env)) return cloudflareContext.env;
250
+ const platformContext = isRecordOrFunction(context?._platform) ? context._platform : void 0;
251
+ const platformCloudflareContext = isRecordOrFunction(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
252
+ if (isRecordOrFunction(platformCloudflareContext?.env)) return platformCloudflareContext.env;
253
+ const request = isRecordOrFunction(event.req) ? event.req : void 0;
254
+ const runtime = isRecordOrFunction(request?.runtime) ? request.runtime : void 0;
255
+ const runtimeCloudflare = isRecordOrFunction(runtime?.cloudflare) ? runtime.cloudflare : void 0;
256
+ return isRecordOrFunction(runtimeCloudflare?.env) ? runtimeCloudflare.env : void 0;
236
257
  }
237
258
  function isStaticScheduleDefinition(value) {
238
- return isRecord(value) && Object.hasOwn(value, "cron") && hasRuntimeType(value.cron, "string") && Object.hasOwn(value, "handler") && typeof value.handler === "function";
259
+ return isRecordOrFunction(value) && Object.hasOwn(value, "cron") && typeof value.cron === "string" && Object.hasOwn(value, "handler") && typeof value.handler === "function";
239
260
  }
240
261
  function unwrapScheduleDefinition(loaded) {
241
- const candidate = isRecord(loaded) && Object.hasOwn(loaded, "default") ? loaded.default : loaded;
262
+ const candidate = isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default") ? loaded.default : loaded;
242
263
  return isStaticScheduleDefinition(candidate) ? candidate : void 0;
243
264
  }
244
265
  //#endregion
245
- export { isScheduleCronAuthorized as a, normalizeScheduleRuntimeError as c, executeStaticSchedule as i, unwrapScheduleDefinition as l, executeCloudflareStaticSchedules as n, missingScheduleDefinitionError as o, executeMatchingStaticSchedules as r, normalizeCron as s, createStaticScheduleRun as t };
266
+ export { isScheduleCronAuthorized as a, normalizeCron as c, unwrapScheduleDefinition as d, executeStaticSchedule as i, normalizeScheduleRuntimeError as l, executeCloudflareStaticSchedules as n, isTimeZoneWakeDue as o, executeMatchingStaticSchedules as r, missingScheduleDefinitionError as s, createStaticScheduleRun as t, scheduledWakeTime as u };
@@ -0,0 +1,53 @@
1
+ import { a as ScheduleDefinitionRegistry, g as ScheduleRunStore, n as ScheduleDefinition, p as ScheduleRunRecord } from "./types-Cw5LjPuc.js";
2
+ import { t as ScheduleKVStorage } from "./kv-storage-C0KZZB6v.js";
3
+ //#region src/runtime/execute.d.ts
4
+ interface ExecuteScheduleOptions {
5
+ /** Return the persisted failed run when the handler throws. Guards still throw. */
6
+ captureHandlerFailure?: boolean;
7
+ /**
8
+ * The caller holds the claim on this occurrence, so a run that is still pending or running belongs to a process that
9
+ * stopped. Such a run gets a new attempt, and its unfinished attempts are marked as failed.
10
+ */
11
+ claimed?: boolean;
12
+ definition: ScheduleDefinition;
13
+ /** Signals that the handler can start, or an existing run already consumed this occurrence. */
14
+ onExecution?: () => void;
15
+ runStore?: ScheduleRunStore;
16
+ runIdSuffix?: string;
17
+ scheduleId: string;
18
+ source?: "direct" | "manual" | "started" | "static";
19
+ scheduledAt?: Date;
20
+ target: string;
21
+ waitUntil?: (promise: PromiseLike<unknown>) => void;
22
+ }
23
+ interface ExecuteStaticScheduleOptions {
24
+ claimed?: boolean;
25
+ cron: string;
26
+ definition: ScheduleDefinition;
27
+ name: string;
28
+ onExecution?: () => void;
29
+ scheduledAt?: Date;
30
+ waitUntil?: (promise: PromiseLike<unknown>) => void;
31
+ }
32
+ interface RunScheduleOptions {
33
+ /**
34
+ * The time the handler receives as `scheduledAt`, as if the cron fired then. A string is an ISO 8601 date-time with a
35
+ * time zone, such as `"2026-01-31T23:59:00Z"`. Defaults to now. The run records this time.
36
+ */
37
+ scheduledAt?: Date | string;
38
+ }
39
+ declare function createScheduleRun(options: Omit<ExecuteScheduleOptions, "definition" | "waitUntil">): Promise<ScheduleRunRecord>;
40
+ declare function executeSchedule(options: ExecuteScheduleOptions): Promise<ScheduleRunRecord>;
41
+ declare function executeStaticSchedule(options: ExecuteStaticScheduleOptions): Promise<ScheduleRunRecord>;
42
+ /** Runs a manually dispatchable static Schedule Definition of `registry` immediately. */
43
+ declare function runScheduleFrom(registry: ScheduleDefinitionRegistry, name: string, options?: RunScheduleOptions): Promise<ScheduleRunRecord>;
44
+ //#endregion
45
+ //#region src/runtime/store.d.ts
46
+ interface KVScheduleStoreOptions {
47
+ kvStore: ScheduleKVStorage;
48
+ prefix?: string;
49
+ }
50
+ declare function createMemoryScheduleRunStore(): ScheduleRunStore;
51
+ declare function createKVScheduleRunStore(options: KVScheduleStoreOptions): ScheduleRunStore;
52
+ //#endregion
53
+ export { createScheduleRun as a, runScheduleFrom as c, RunScheduleOptions as i, createKVScheduleRunStore as n, executeSchedule as o, createMemoryScheduleRunStore as r, executeStaticSchedule as s, KVScheduleStoreOptions as t };
@@ -0,0 +1,59 @@
1
+ //#region ../internal/src/runtime/time-zone.ts
2
+ const slashlessIanaTimeZones = /* @__PURE__ */ new Set([
3
+ "CET",
4
+ "CST6CDT",
5
+ "Cuba",
6
+ "EET",
7
+ "EST",
8
+ "EST5EDT",
9
+ "Egypt",
10
+ "Eire",
11
+ "Factory",
12
+ "GB",
13
+ "GB-Eire",
14
+ "GMT",
15
+ "GMT+0",
16
+ "GMT-0",
17
+ "GMT0",
18
+ "Greenwich",
19
+ "HST",
20
+ "Hongkong",
21
+ "Iceland",
22
+ "Iran",
23
+ "Israel",
24
+ "Jamaica",
25
+ "Japan",
26
+ "Kwajalein",
27
+ "Libya",
28
+ "MET",
29
+ "MST",
30
+ "MST7MDT",
31
+ "NZ",
32
+ "NZ-CHAT",
33
+ "Navajo",
34
+ "PRC",
35
+ "PST8PDT",
36
+ "Poland",
37
+ "Portugal",
38
+ "ROC",
39
+ "ROK",
40
+ "Singapore",
41
+ "Turkey",
42
+ "UCT",
43
+ "UTC",
44
+ "Universal",
45
+ "W-SU",
46
+ "WET",
47
+ "Zulu"
48
+ ]);
49
+ function isIanaTimeZone(timeZone) {
50
+ if (typeof timeZone !== "string" || !timeZone.includes("/") && !slashlessIanaTimeZones.has(timeZone)) return false;
51
+ try {
52
+ new Intl.DateTimeFormat("en-US", { timeZone });
53
+ return true;
54
+ } catch {
55
+ return false;
56
+ }
57
+ }
58
+ //#endregion
59
+ export { isIanaTimeZone as t };