@vite-hub/schedule 0.0.4 → 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 (62) hide show
  1. package/README.md +139 -58
  2. package/dist/console-wEhr0LWn.d.ts +330 -0
  3. package/dist/definition.d.ts +8 -6
  4. package/dist/definition.js +34 -28
  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 +61 -40
  11. package/dist/index.js +27 -7
  12. package/dist/inspect-DTfAo5gS.js +118 -0
  13. package/dist/invariant-DolT9EEx.js +22 -0
  14. package/dist/kv-storage-C0KZZB6v.d.ts +18 -0
  15. package/dist/{kv-storage-DWinmLLy.js → kv-storage-iJChCS5A.js} +2 -2
  16. package/dist/object-Da1zyPCR.js +11 -0
  17. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  18. package/dist/operations-DwZWFIUX.js +184 -0
  19. package/dist/operations.d.ts +84 -0
  20. package/dist/operations.js +318 -0
  21. package/dist/os.d.ts +167 -0
  22. package/dist/os.js +1659 -0
  23. package/dist/registry-module.d.ts +0 -5
  24. package/dist/runtime/console.d.ts +12 -0
  25. package/dist/runtime/console.js +85 -0
  26. package/dist/runtime/kv.d.ts +4 -0
  27. package/dist/{kv-BJ1I9IlJ.js → runtime/kv.js} +1 -1
  28. package/dist/runtime/process.d.ts +53 -5
  29. package/dist/runtime/process.js +501 -251
  30. package/dist/runtime/state.d.ts +2 -13
  31. package/dist/runtime/state.js +2 -2
  32. package/dist/runtime/static.d.ts +44 -12
  33. package/dist/runtime/static.js +2 -150
  34. package/dist/runtime.d.ts +38 -4
  35. package/dist/runtime.js +6 -3
  36. package/dist/started-BuGmnus4.js +201 -0
  37. package/dist/started-Bx7MDbrl.js +146 -0
  38. package/dist/started-errors-p7cu_rI7.js +250 -0
  39. package/dist/state-B-Fuyfb4.js +468 -0
  40. package/dist/state-Do2wV4Tx.d.ts +49 -0
  41. package/dist/static-DQwzzvPg.js +266 -0
  42. package/dist/store-Df0-fzCl.d.ts +53 -0
  43. package/dist/time-zone-SBldrUgt.js +59 -0
  44. package/dist/types-Cw5LjPuc.d.ts +167 -0
  45. package/dist/vite.d.ts +214 -11
  46. package/dist/vite.js +5876 -3
  47. package/dist/wait-until-Dy4Bn3ZN.js +112 -0
  48. package/package.json +65 -24
  49. package/dist/client-DpCD4YFE.js +0 -233
  50. package/dist/discovery-DkFAN7Wd.d.ts +0 -15
  51. package/dist/discovery-DvU3B6iD.js +0 -753
  52. package/dist/due-Bbh4yIxq.js +0 -59
  53. package/dist/execute-B-pii4wf.js +0 -211
  54. package/dist/nuxt.d.ts +0 -19
  55. package/dist/nuxt.js +0 -26
  56. package/dist/runtime/driver.d.ts +0 -26
  57. package/dist/runtime/driver.js +0 -337
  58. package/dist/state-By7WU_ks.js +0 -472
  59. package/dist/store-t-74rsM_.d.ts +0 -48
  60. package/dist/types-Bcje4dLV.d.ts +0 -136
  61. package/dist/vite-BHs17nWX.js +0 -4166
  62. package/dist/wait-until-BzIwzXw4.js +0 -23
@@ -1,13 +1,2 @@
1
- import { a as RuntimeScheduleStore, b as ScheduleRunStore, d as ScheduleDefinitionRegistry, p as ScheduleRegistryDefinition } from "../types-Bcje4dLV.js";
2
-
3
- //#region src/runtime/state.d.ts
4
- declare function setScheduleRuntimeRegistry(registry: ScheduleDefinitionRegistry | undefined): void;
5
- declare function getScheduleRuntimeRegistry(): ScheduleDefinitionRegistry | undefined;
6
- declare function setRuntimeScheduleStore(store: RuntimeScheduleStore | undefined): void;
7
- declare function getRuntimeScheduleStore(): RuntimeScheduleStore;
8
- declare function setScheduleRunStore(store: ScheduleRunStore | undefined): void;
9
- declare function getScheduleRunStore(): ScheduleRunStore;
10
- declare function loadScheduleDefinition(name: string): Promise<ScheduleRegistryDefinition | undefined>;
11
- declare function resetScheduleRuntime(): void;
12
- //#endregion
13
- export { getRuntimeScheduleStore, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, setRuntimeScheduleStore, setScheduleRunStore, setScheduleRuntimeRegistry };
1
+ import { a as getScheduleRuntimeRegistry, c as registerProcessScheduleDefinitions, d as setScheduleRunStore, f as setScheduleRuntimeRegistry, i as getScheduleRunStore, l as resetScheduleRuntime, n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime, p as setStartedScheduleRuntime, r as getScheduleOccurrenceClaims, s as loadScheduleDefinition, t as StartedScheduleRuntime, u as setScheduleOccurrenceClaims } from "../state-Do2wV4Tx.js";
2
+ export { StartedScheduleRuntime, getProcessScheduleDefinitions, getScheduleOccurrenceClaims, getScheduleRunStore, getScheduleRuntimeRegistry, getStartedScheduleRuntime, loadScheduleDefinition, registerProcessScheduleDefinitions, resetScheduleRuntime, setScheduleOccurrenceClaims, setScheduleRunStore, setScheduleRuntimeRegistry, setStartedScheduleRuntime };
@@ -1,2 +1,2 @@
1
- import { a as resetScheduleRuntime, c as setScheduleRuntimeRegistry, i as loadScheduleDefinition, n as getScheduleRunStore, o as setRuntimeScheduleStore, r as getScheduleRuntimeRegistry, s as setScheduleRunStore, t as getRuntimeScheduleStore } from "../state-By7WU_ks.js";
2
- export { getRuntimeScheduleStore, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, setRuntimeScheduleStore, setScheduleRunStore, setScheduleRuntimeRegistry };
1
+ import { a as getStartedScheduleRuntime, c as resetScheduleRuntime, d as setScheduleRuntimeRegistry, f as setStartedScheduleRuntime, i as getScheduleRuntimeRegistry, l as setScheduleOccurrenceClaims, n as getScheduleOccurrenceClaims, o as loadScheduleDefinition, r as getScheduleRunStore, s as registerProcessScheduleDefinitions, t as getProcessScheduleDefinitions, u as setScheduleRunStore } from "../state-B-Fuyfb4.js";
2
+ export { getProcessScheduleDefinitions, getScheduleOccurrenceClaims, getScheduleRunStore, getScheduleRuntimeRegistry, getStartedScheduleRuntime, loadScheduleDefinition, registerProcessScheduleDefinitions, resetScheduleRuntime, setScheduleOccurrenceClaims, setScheduleRunStore, setScheduleRuntimeRegistry, setStartedScheduleRuntime };
@@ -1,21 +1,31 @@
1
- import { c as ScheduleDefinition, d as ScheduleDefinitionRegistry, g as ScheduleRunContext } from "../types-Bcje4dLV.js";
2
-
1
+ import { a as ScheduleDefinitionRegistry, n as ScheduleDefinition, u as ScheduleRunContext } from "../types-Cw5LjPuc.js";
3
2
  //#region src/runtime/static.d.ts
4
- interface ExecuteStaticScheduleOptions {
3
+ export interface ExecuteStaticScheduleOptions {
5
4
  cron: string;
6
5
  definition: ScheduleDefinition;
7
6
  name: string;
8
7
  scheduledAt?: Date;
9
8
  waitUntil?: (promise: PromiseLike<unknown>) => void;
10
9
  }
11
- interface ExecuteMatchingStaticSchedulesOptions {
10
+ export interface ExecuteMatchingStaticSchedulesOptions {
12
11
  cron: string;
12
+ /** Cron per Schedule name that the host registered in place of the Definition's cron. */
13
+ cronOverrides?: Readonly<Record<string, string>>;
13
14
  registry: ScheduleDefinitionRegistry;
14
15
  scheduledAt?: Date;
16
+ /**
17
+ * UTC cron that the host registered for each Schedule with a `timeZone`. A wake runs such a Schedule only when its
18
+ * own cron is due in its time zone at that minute. `cronOverrides` wins over this map.
19
+ */
20
+ timeZoneCrons?: Readonly<Record<string, string>>;
15
21
  waitUntil?: (promise: PromiseLike<unknown>) => void;
16
22
  }
17
- interface ExecuteCloudflareStaticSchedulesOptions {
23
+ export interface ExecuteCloudflareStaticSchedulesOptions {
24
+ /** Cron per Schedule name that the host registered in place of the Definition's cron. */
25
+ cronOverrides?: Readonly<Record<string, string>>;
18
26
  registry: ScheduleDefinitionRegistry;
27
+ /** UTC cron that the host registered for each Schedule with a `timeZone`. */
28
+ timeZoneCrons?: Readonly<Record<string, string>>;
19
29
  waitUntil?: (promise: PromiseLike<unknown>) => void;
20
30
  }
21
31
  interface CloudflareScheduledEventLike {
@@ -27,15 +37,37 @@ interface CloudflareScheduledEventLike {
27
37
  cron?: string;
28
38
  scheduledTime?: number | string | Date;
29
39
  }
30
- interface StaticScheduleRun extends ScheduleRunContext {
40
+ export interface StaticScheduleRun extends ScheduleRunContext {
31
41
  cron: string;
32
42
  scheduleId: string;
33
43
  }
34
- declare function createStaticScheduleRun(options: Omit<ExecuteStaticScheduleOptions, "definition" | "waitUntil"> & {
44
+ export declare function missingScheduleDefinitionError(name: string): Error;
45
+ /**
46
+ * Checks the `Authorization` header of a Vercel Cron request against `CRON_SECRET` in constant time.
47
+ */
48
+ export declare function isScheduleCronAuthorized(authorization: string | null | undefined, cronSecret: string): boolean;
49
+ export declare function normalizeCron(cron: string): string;
50
+ export declare function normalizeScheduleRuntimeError(error: unknown): Error;
51
+ /**
52
+ * Estimates a wake minute from callback time when the host supplies no scheduled timestamp. This is the newest UTC
53
+ * cron match within one day, or the current minute when none matches. It cannot identify a delayed or retried wake
54
+ * after another cron match; callers must not treat it as the provider's occurrence identity.
55
+ */
56
+ export declare function scheduledWakeTime(cron: string, now?: Date): Date;
57
+ /**
58
+ * Returns `true` when a host wake at `scheduledAt` is an occurrence of the Definition's cron in its `timeZone`. The host
59
+ * runs a wider UTC cron for a time-zoned Schedule, so the runtime skips the wakes that are not local occurrences.
60
+ */
61
+ export declare function isTimeZoneWakeDue(definition: ScheduleDefinition & {
62
+ cron: string;
63
+ }, name: string, scheduledAt: Date): boolean;
64
+ export declare function createStaticScheduleRun(options: Omit<ExecuteStaticScheduleOptions, "definition" | "waitUntil"> & {
35
65
  waitUntil: NonNullable<ExecuteStaticScheduleOptions["waitUntil"]>;
36
66
  }): StaticScheduleRun;
37
- declare function executeStaticSchedule(options: ExecuteStaticScheduleOptions): Promise<unknown>;
38
- declare function executeMatchingStaticSchedules(options: ExecuteMatchingStaticSchedulesOptions): Promise<unknown[]>;
39
- declare function executeCloudflareStaticSchedules(event: CloudflareScheduledEventLike, options: ExecuteCloudflareStaticSchedulesOptions): Promise<unknown[]>;
40
- //#endregion
41
- export { ExecuteCloudflareStaticSchedulesOptions, ExecuteMatchingStaticSchedulesOptions, ExecuteStaticScheduleOptions, StaticScheduleRun, createStaticScheduleRun, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule };
67
+ export declare function executeStaticSchedule(options: ExecuteStaticScheduleOptions): Promise<unknown>;
68
+ export declare function executeMatchingStaticSchedules(options: ExecuteMatchingStaticSchedulesOptions): Promise<unknown[]>;
69
+ export declare function executeCloudflareStaticSchedules(event: CloudflareScheduledEventLike, options: ExecuteCloudflareStaticSchedulesOptions): Promise<unknown[]>;
70
+ export declare function unwrapScheduleDefinition(loaded: unknown): (ScheduleDefinition & {
71
+ cron: string;
72
+ }) | undefined;
73
+ //#endregion
@@ -1,150 +1,2 @@
1
- import { t as createLocalWaitUntil } from "../wait-until-BzIwzXw4.js";
2
- //#region src/runtime/static.ts
3
- function createStaticScheduleRun(options) {
4
- const scheduledAt = options.scheduledAt ?? /* @__PURE__ */ new Date();
5
- return {
6
- cron: options.cron,
7
- id: `run_${options.name}_${scheduledAt.toISOString()}`,
8
- scheduleId: options.name,
9
- scheduledAt,
10
- waitUntil: options.waitUntil
11
- };
12
- }
13
- async function executeStaticSchedule(options) {
14
- const localWaitUntil = createLocalWaitUntil();
15
- try {
16
- const result = await options.definition.handler(createStaticScheduleRun({
17
- ...options,
18
- waitUntil: options.waitUntil ?? localWaitUntil.waitUntil
19
- }));
20
- if (!options.waitUntil) await localWaitUntil.flush();
21
- return result;
22
- } catch (error) {
23
- if (!options.waitUntil) try {
24
- await localWaitUntil.flush();
25
- } catch {}
26
- throw error;
27
- }
28
- }
29
- async function executeMatchingStaticSchedules(options) {
30
- const scheduledAt = options.scheduledAt ?? /* @__PURE__ */ new Date();
31
- const runs = [];
32
- for (const [name, load] of Object.entries(options.registry)) {
33
- const definition = unwrapScheduleDefinition(await load());
34
- if (!definition || definition.cron !== options.cron) continue;
35
- runs.push(executeStaticSchedule({
36
- cron: options.cron,
37
- definition,
38
- name,
39
- scheduledAt,
40
- waitUntil: options.waitUntil
41
- }));
42
- }
43
- return await Promise.all(runs);
44
- }
45
- async function executeCloudflareStaticSchedules(event, options) {
46
- const scheduled = readCloudflareScheduledEvent(event);
47
- return await runWithCloudflareServerEnv(event, async (waitUntil) => {
48
- return await executeMatchingStaticSchedules({
49
- cron: scheduled.cron,
50
- registry: options.registry,
51
- scheduledAt: scheduled.scheduledAt,
52
- waitUntil
53
- });
54
- }, options.waitUntil ?? readCloudflareWaitUntil(event));
55
- }
56
- function readCloudflareScheduledEvent(event) {
57
- const cron = event.controller?.cron ?? event.cron;
58
- if (!cron) throw new TypeError("[vitehub:schedule] Cloudflare scheduled event is missing a cron string.");
59
- const scheduledTime = event.controller?.scheduledTime ?? event.scheduledTime;
60
- const scheduledAt = scheduledTime instanceof Date ? scheduledTime : scheduledTime === void 0 ? /* @__PURE__ */ new Date() : new Date(scheduledTime);
61
- if (Number.isNaN(scheduledAt.getTime())) throw new TypeError("[vitehub:schedule] Cloudflare scheduled event has an invalid scheduledTime.");
62
- return {
63
- cron,
64
- scheduledAt
65
- };
66
- }
67
- async function runWithCloudflareServerEnv(event, callback, hostWaitUntil) {
68
- const globals = globalThis;
69
- const hadGlobalEnv = Object.prototype.hasOwnProperty.call(globals, "__env__");
70
- const previousGlobalEnv = globals.__env__;
71
- const env = readCloudflareEventEnv(event);
72
- if (env) globals.__env__ = env;
73
- const pending = /* @__PURE__ */ new Set();
74
- const waitUntil = hostWaitUntil ? (value) => {
75
- const promise = Promise.resolve(value);
76
- pending.add(promise);
77
- promise.then(() => pending.delete(promise), () => pending.delete(promise));
78
- hostWaitUntil(promise);
79
- } : void 0;
80
- try {
81
- return await callback(waitUntil);
82
- } finally {
83
- if (pending.size === 0) restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv);
84
- else hostWaitUntil(flushPendingWork(pending).finally(() => {
85
- restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv);
86
- }));
87
- }
88
- }
89
- async function flushPendingWork(pending) {
90
- while (pending.size > 0) await Promise.allSettled(pending);
91
- }
92
- function restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv) {
93
- if (hadGlobalEnv) globals.__env__ = previousGlobalEnv;
94
- else delete globals.__env__;
95
- }
96
- function isRecord(value) {
97
- return Object(value) === value && !Array.isArray(value);
98
- }
99
- function isCallable(value) {
100
- if (value === null || value === void 0 || Object(value) !== value) return false;
101
- try {
102
- Function.prototype.toString.call(value);
103
- return true;
104
- } catch {
105
- return false;
106
- }
107
- }
108
- function readCloudflareWaitUntil(event) {
109
- const context = isRecord(event.context) ? event.context : void 0;
110
- const cloudflareContext = isRecord(context?.cloudflare) ? context.cloudflare : void 0;
111
- const platformContext = isRecord(context?._platform) ? context._platform : void 0;
112
- const platformCloudflareContext = isRecord(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
113
- const request = isRecord(event.req) ? event.req : void 0;
114
- const runtime = isRecord(request?.runtime) ? request.runtime : void 0;
115
- const runtimeCloudflare = isRecord(runtime?.cloudflare) ? runtime.cloudflare : void 0;
116
- const owners = [
117
- event,
118
- context,
119
- cloudflareContext,
120
- isRecord(cloudflareContext?.context) ? cloudflareContext.context : void 0,
121
- platformCloudflareContext,
122
- isRecord(platformCloudflareContext?.context) ? platformCloudflareContext.context : void 0,
123
- request,
124
- runtimeCloudflare,
125
- isRecord(runtimeCloudflare?.context) ? runtimeCloudflare.context : void 0
126
- ];
127
- for (const owner of owners) {
128
- const waitUntil = owner?.waitUntil;
129
- if (isCallable(waitUntil)) return (promise) => Reflect.apply(waitUntil, owner, [promise]);
130
- }
131
- }
132
- function readCloudflareEventEnv(event) {
133
- if (isRecord(event.env)) return event.env;
134
- const context = isRecord(event.context) ? event.context : void 0;
135
- const cloudflareContext = isRecord(context?.cloudflare) ? context.cloudflare : void 0;
136
- if (isRecord(cloudflareContext?.env)) return cloudflareContext.env;
137
- const platformContext = isRecord(context?._platform) ? context._platform : void 0;
138
- const platformCloudflareContext = isRecord(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
139
- if (isRecord(platformCloudflareContext?.env)) return platformCloudflareContext.env;
140
- const request = isRecord(event.req) ? event.req : void 0;
141
- const runtime = isRecord(request?.runtime) ? request.runtime : void 0;
142
- const runtimeCloudflare = isRecord(runtime?.cloudflare) ? runtime.cloudflare : void 0;
143
- return isRecord(runtimeCloudflare?.env) ? runtimeCloudflare.env : void 0;
144
- }
145
- function unwrapScheduleDefinition(loaded) {
146
- const definition = "default" in loaded ? loaded.default : loaded;
147
- return definition && "cron" in definition ? definition : void 0;
148
- }
149
- //#endregion
150
- export { createStaticScheduleRun, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule };
1
+ import { a as isScheduleCronAuthorized, c as normalizeCron, d as unwrapScheduleDefinition, i as executeStaticSchedule, l as normalizeScheduleRuntimeError, n as executeCloudflareStaticSchedules, o as isTimeZoneWakeDue, r as executeMatchingStaticSchedules, s as missingScheduleDefinitionError, t as createStaticScheduleRun, u as scheduledWakeTime } from "../static-DQwzzvPg.js";
2
+ export { createStaticScheduleRun, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule, isScheduleCronAuthorized, isTimeZoneWakeDue, missingScheduleDefinitionError, normalizeCron, normalizeScheduleRuntimeError, scheduledWakeTime, unwrapScheduleDefinition };
package/dist/runtime.d.ts CHANGED
@@ -1,5 +1,39 @@
1
1
  /// <reference path="./registry-module.d.ts" />
2
- import { C as ScheduleTargetName, S as ScheduleTargetDefinitionInput, a as RuntimeScheduleStore, c as ScheduleDefinition, d as ScheduleDefinitionRegistry, f as ScheduleHandler, g as ScheduleRunContext, i as RuntimeScheduleRecord, n as RuntimeScheduleCreateInput, o as RuntimeScheduleUpdateInput, p as ScheduleRegistryDefinition, r as RuntimeScheduleMetadata, u as ScheduleDefinitionOptions, x as ScheduleTargetDefinition } from "./types-Bcje4dLV.js";
3
- import { c as schedules, i as createMemoryRuntimeScheduleStore, l as validateRuntimeScheduleCron } from "./store-t-74rsM_.js";
4
- import { getRuntimeScheduleStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, setRuntimeScheduleStore, setScheduleRuntimeRegistry } from "./runtime/state.js";
5
- export { type RuntimeScheduleCreateInput, type RuntimeScheduleMetadata, type RuntimeScheduleRecord, type RuntimeScheduleStore, type RuntimeScheduleUpdateInput, type ScheduleDefinition, type ScheduleDefinitionOptions, type ScheduleDefinitionRegistry, type ScheduleHandler, type ScheduleRegistryDefinition, type ScheduleRunContext, type ScheduleTargetDefinition, type ScheduleTargetDefinitionInput, type ScheduleTargetName, createMemoryRuntimeScheduleStore, getRuntimeScheduleStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, schedules, setRuntimeScheduleStore, setScheduleRuntimeRegistry, validateRuntimeScheduleCron };
2
+ import { a as ScheduleDefinitionRegistry, b as StartedScheduleStore, c as ScheduleRunAttemptRecord, f as ScheduleRunListOptions, g as ScheduleRunStore, i as ScheduleDefinitionOptions, n as ScheduleDefinition, o as ScheduleHandler, p as ScheduleRunRecord, s as ScheduleRegistryDefinition, u as ScheduleRunContext } from "./types-Cw5LjPuc.js";
3
+ import { a as createScheduleRun, c as runScheduleFrom, n as createKVScheduleRunStore, o as executeSchedule, r as createMemoryScheduleRunStore, s as executeStaticSchedule, t as KVScheduleStoreOptions } from "./store-Df0-fzCl.js";
4
+ import { n as createScheduleKVStorage, t as ScheduleKVStorage } from "./kv-storage-C0KZZB6v.js";
5
+ import { normalizeCron, unwrapScheduleDefinition } from "./runtime/static.js";
6
+ import { d as setScheduleRunStore, i as getScheduleRunStore, l as resetScheduleRuntime } from "./state-Do2wV4Tx.js";
7
+ //#region src/runtime/started.d.ts
8
+ interface InstallStartedSchedulesOptions {
9
+ /**
10
+ * How far back, in milliseconds, the first tick after a start runs cron minutes that no tick checked. Use it only with
11
+ * a run store that survives restarts, because the run ids dedupe minutes that already ran. Defaults to `0`.
12
+ */
13
+ catchUpMs?: number;
14
+ /** Schedule Definitions without `cron`, by name. */
15
+ registry: ScheduleDefinitionRegistry;
16
+ store: StartedScheduleStore;
17
+ }
18
+ /** Installs the store and the Definitions that `startSchedule()` and the tick use. The generated Nitro plugin calls it. */
19
+ export declare function installStartedSchedules(options: InstallStartedSchedulesOptions): void;
20
+ /** Keeps started Schedules in this process only. They are lost on restart. Use it in tests. */
21
+ export declare function createMemoryStartedScheduleStore(): StartedScheduleStore;
22
+ interface KVStartedScheduleStoreOptions {
23
+ kvStore: ScheduleKVStorage;
24
+ /** Key prefix. Defaults to `vitehub:schedule`, the prefix of the KV Schedule Run store. */
25
+ prefix?: string;
26
+ }
27
+ /**
28
+ * Keeps started Schedules in KV, one key for each Schedule, so they survive restarts and deploys. A record never changes
29
+ * after `put()`, so `list()` reads each key once per process and then only lists the keys.
30
+ */
31
+ export declare function createKVStartedScheduleStore(options: KVStartedScheduleStoreOptions): StartedScheduleStore;
32
+ /**
33
+ * Runs the started Schedules that are due at the minute of `context.scheduledAt`. It is the handler of the
34
+ * `vitehub/started-schedules` Schedule, which the host wakes each minute. A handler failure is recorded in the run of
35
+ * that started Schedule and logged; it does not fail the tick.
36
+ */
37
+ export declare function runStartedSchedules(context: ScheduleRunContext): Promise<void>;
38
+ //#endregion
39
+ export { type InstallStartedSchedulesOptions, type KVScheduleStoreOptions, type KVStartedScheduleStoreOptions, type ScheduleDefinition, type ScheduleDefinitionOptions, type ScheduleDefinitionRegistry, type ScheduleHandler, type ScheduleKVStorage, type ScheduleRegistryDefinition, type ScheduleRunAttemptRecord, type ScheduleRunContext, type ScheduleRunListOptions, type ScheduleRunRecord, type ScheduleRunStore, createKVScheduleRunStore, createMemoryScheduleRunStore, createScheduleKVStorage, createScheduleRun, executeSchedule, executeStaticSchedule, getScheduleRunStore, normalizeCron, resetScheduleRuntime, runScheduleFrom, setScheduleRunStore, unwrapScheduleDefinition };
package/dist/runtime.js CHANGED
@@ -1,3 +1,6 @@
1
- import { a as resetScheduleRuntime, c as setScheduleRuntimeRegistry, d as createMemoryRuntimeScheduleStore, i as loadScheduleDefinition, o as setRuntimeScheduleStore, r as getScheduleRuntimeRegistry, t as getRuntimeScheduleStore } from "./state-By7WU_ks.js";
2
- import { n as validateRuntimeScheduleCron, t as schedules } from "./client-DpCD4YFE.js";
3
- export { createMemoryRuntimeScheduleStore, getRuntimeScheduleStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, schedules, setRuntimeScheduleStore, setScheduleRuntimeRegistry, validateRuntimeScheduleCron };
1
+ import { a as runScheduleFrom, i as executeStaticSchedule, n as createScheduleRun, r as executeSchedule } from "./started-errors-p7cu_rI7.js";
2
+ import { c as resetScheduleRuntime, m as createMemoryScheduleRunStore, p as createKVScheduleRunStore, r as getScheduleRunStore, u as setScheduleRunStore } from "./state-B-Fuyfb4.js";
3
+ import { c as normalizeCron, d as unwrapScheduleDefinition } from "./static-DQwzzvPg.js";
4
+ import { t as createScheduleKVStorage } from "./kv-storage-iJChCS5A.js";
5
+ import { i as runStartedSchedules, n as createMemoryStartedScheduleStore, r as installStartedSchedules, t as createKVStartedScheduleStore } from "./started-BuGmnus4.js";
6
+ export { createKVScheduleRunStore, createKVStartedScheduleStore, createMemoryScheduleRunStore, createMemoryStartedScheduleStore, createScheduleKVStorage, createScheduleRun, executeSchedule, executeStaticSchedule, getScheduleRunStore, installStartedSchedules, normalizeCron, resetScheduleRuntime, runScheduleFrom, runStartedSchedules, setScheduleRunStore, unwrapScheduleDefinition };
@@ -0,0 +1,201 @@
1
+ import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
2
+ import { o as toRunId, r as executeSchedule, t as startedScheduleErrors } from "./started-errors-p7cu_rI7.js";
3
+ import { a as getStartedScheduleRuntime, f as setStartedScheduleRuntime, g as keySegments, h as joinKey, n as getScheduleOccurrenceClaims } from "./state-B-Fuyfb4.js";
4
+ import { t as isScheduleDue } from "./due-BVMRQ93v.js";
5
+ import { normalizeRuntimeDiagnosticError } from "@vite-hub/runtime";
6
+ //#region src/runtime/started.ts
7
+ const minuteMs = 6e4;
8
+ /** Installs the store and the Definitions that `startSchedule()` and the tick use. The generated Nitro plugin calls it. */
9
+ function installStartedSchedules(options) {
10
+ setStartedScheduleRuntime({
11
+ catchUpMs: options.catchUpMs ?? 0,
12
+ registry: options.registry,
13
+ store: options.store
14
+ });
15
+ }
16
+ function serialize(schedule) {
17
+ return {
18
+ ...schedule.at ? { at: schedule.at.toISOString() } : {},
19
+ createdAt: schedule.createdAt.toISOString(),
20
+ ...schedule.cron === void 0 ? {} : { cron: schedule.cron },
21
+ id: schedule.id,
22
+ ...schedule.payload === void 0 ? {} : { payload: schedule.payload },
23
+ name: schedule.name,
24
+ ...schedule.timeZone === void 0 ? {} : { timeZone: schedule.timeZone }
25
+ };
26
+ }
27
+ function deserialize(stored) {
28
+ return {
29
+ ...stored.at ? { at: new Date(stored.at) } : {},
30
+ createdAt: new Date(stored.createdAt),
31
+ ...stored.cron === void 0 ? {} : { cron: stored.cron },
32
+ id: stored.id,
33
+ ...stored.payload === void 0 ? {} : { payload: stored.payload },
34
+ name: stored.name,
35
+ ...stored.timeZone === void 0 ? {} : { timeZone: stored.timeZone }
36
+ };
37
+ }
38
+ /** Keeps started Schedules in this process only. They are lost on restart. Use it in tests. */
39
+ function createMemoryStartedScheduleStore() {
40
+ const schedules = /* @__PURE__ */ new Map();
41
+ return {
42
+ async delete(id) {
43
+ return schedules.delete(id);
44
+ },
45
+ async get(id) {
46
+ const stored = schedules.get(id);
47
+ return stored ? deserialize(stored) : void 0;
48
+ },
49
+ async list() {
50
+ return [...schedules.values()].map(deserialize);
51
+ },
52
+ async put(schedule) {
53
+ schedules.set(schedule.id, serialize(schedule));
54
+ }
55
+ };
56
+ }
57
+ /**
58
+ * Keeps started Schedules in KV, one key for each Schedule, so they survive restarts and deploys. A record never changes
59
+ * after `put()`, so `list()` reads each key once per process and then only lists the keys.
60
+ */
61
+ function createKVStartedScheduleStore(options) {
62
+ const prefix = options.prefix ?? "vitehub:schedule";
63
+ const kv = options.kvStore;
64
+ const key = (id) => joinKey(prefix, "started-schedules", id);
65
+ const read = /* @__PURE__ */ new Map();
66
+ return {
67
+ async delete(id) {
68
+ read.delete(id);
69
+ if (!await kv.has(key(id))) return false;
70
+ await kv.delete(key(id));
71
+ return true;
72
+ },
73
+ async get(id) {
74
+ const stored = await kv.get(key(id));
75
+ return stored ? deserialize(stored) : void 0;
76
+ },
77
+ async list() {
78
+ const ids = new Set((await kv.keys(`${joinKey(prefix, "started-schedules")}/`)).map((entry) => keySegments(entry, 1)[0]));
79
+ for (const id of read.keys()) if (!ids.has(id)) read.delete(id);
80
+ const schedules = [];
81
+ for (const id of ids) {
82
+ let schedule = read.get(id);
83
+ if (!schedule) {
84
+ const stored = await kv.get(key(id));
85
+ if (!stored) continue;
86
+ schedule = deserialize(stored);
87
+ read.set(id, schedule);
88
+ }
89
+ schedules.push(schedule);
90
+ }
91
+ return schedules;
92
+ },
93
+ async put(schedule) {
94
+ await kv.set(key(schedule.id), serialize(schedule));
95
+ }
96
+ };
97
+ }
98
+ function unwrapStartableDefinition(loaded) {
99
+ const candidate = isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default") ? loaded.default : loaded;
100
+ return isRecordOrFunction(candidate) && typeof candidate.handler === "function" && !Object.hasOwn(candidate, "cron") ? candidate : void 0;
101
+ }
102
+ /** The minutes in `[first, last]` when `schedule` is due, after it was created. A one-time Schedule is due once `at` passed. */
103
+ function dueMinutes(schedule, first, last) {
104
+ if (schedule.at) return schedule.at.getTime() <= last ? [schedule.at] : [];
105
+ const due = [];
106
+ const start = Math.max(first, Math.floor(schedule.createdAt.getTime() / minuteMs) * minuteMs + minuteMs);
107
+ for (let minute = start; minute <= last; minute += minuteMs) {
108
+ const scheduledAt = new Date(minute);
109
+ if (isScheduleDue({
110
+ cron: schedule.cron,
111
+ id: schedule.id,
112
+ timeZone: schedule.timeZone
113
+ }, scheduledAt)) due.push(scheduledAt);
114
+ }
115
+ return due;
116
+ }
117
+ /** Runs one occurrence of a started Schedule. Resolves `false` when another process holds it, so a later tick tries again. */
118
+ async function runOccurrence(runtime, schedule, scheduledAt, waitUntil) {
119
+ const definition = unwrapStartableDefinition(await (Object.hasOwn(runtime.registry, schedule.name) ? runtime.registry[schedule.name] : void 0)?.());
120
+ if (!definition) {
121
+ if (schedule.at) await runtime.store.delete(schedule.id);
122
+ throw startedScheduleErrors.SCHEDULE_NOT_STARTABLE({ name: schedule.name });
123
+ }
124
+ const claims = getScheduleOccurrenceClaims();
125
+ const run = async (markFinal) => {
126
+ let final = false;
127
+ try {
128
+ await executeSchedule({
129
+ captureHandlerFailure: true,
130
+ ...claims ? { claimed: true } : {},
131
+ definition: { handler: (context) => definition.handler({
132
+ ...context,
133
+ payload: schedule.payload
134
+ }) },
135
+ onExecution() {
136
+ final = true;
137
+ markFinal?.();
138
+ },
139
+ scheduleId: schedule.id,
140
+ scheduledAt,
141
+ source: "started",
142
+ target: schedule.name,
143
+ waitUntil
144
+ });
145
+ } finally {
146
+ if (schedule.at && final) await runtime.store.delete(schedule.id);
147
+ }
148
+ };
149
+ if (!claims) {
150
+ await run();
151
+ return true;
152
+ }
153
+ return await claims.run(toRunId("started", schedule.id, scheduledAt), run) !== "held";
154
+ }
155
+ /**
156
+ * Runs the started Schedules that are due at the minute of `context.scheduledAt`. It is the handler of the
157
+ * `vitehub/started-schedules` Schedule, which the host wakes each minute. A handler failure is recorded in the run of
158
+ * that started Schedule and logged; it does not fail the tick.
159
+ */
160
+ async function runStartedSchedules(context) {
161
+ const runtime = getStartedScheduleRuntime();
162
+ if (!runtime) throw startedScheduleErrors.SCHEDULE_STORE_MISSING();
163
+ const minute = Math.floor(context.scheduledAt.getTime() / minuteMs) * minuteMs;
164
+ const first = runtime.checkedThrough === void 0 ? minute - runtime.catchUpMs : Math.min(minute, runtime.checkedThrough + minuteMs);
165
+ const schedules = await runtime.store.list();
166
+ const occurrences = schedules.flatMap((schedule) => dueMinutes(schedule, first, minute).map((scheduledAt) => ({
167
+ schedule,
168
+ scheduledAt
169
+ })));
170
+ const held = runtime.held ??= /* @__PURE__ */ new Map();
171
+ const byId = new Map(schedules.map((schedule) => [schedule.id, schedule]));
172
+ for (const [runId, entry] of held) {
173
+ const schedule = byId.get(entry.scheduleId);
174
+ if (!schedule) held.delete(runId);
175
+ else if (!occurrences.some((occurrence) => occurrence.schedule.id === schedule.id && occurrence.scheduledAt.getTime() === entry.scheduledAt.getTime())) occurrences.push({
176
+ schedule,
177
+ scheduledAt: entry.scheduledAt
178
+ });
179
+ }
180
+ const results = await Promise.allSettled(occurrences.map(({ schedule, scheduledAt }) => runOccurrence(runtime, schedule, scheduledAt, context.waitUntil)));
181
+ results.forEach((result, index) => {
182
+ const { schedule, scheduledAt } = occurrences[index];
183
+ const runId = toRunId("started", schedule.id, scheduledAt);
184
+ if (result.status === "fulfilled") {
185
+ if (result.value) held.delete(runId);
186
+ else held.set(runId, {
187
+ scheduleId: schedule.id,
188
+ scheduledAt
189
+ });
190
+ return;
191
+ }
192
+ held.set(runId, {
193
+ scheduleId: schedule.id,
194
+ scheduledAt
195
+ });
196
+ console.error(`[vitehub:schedule] Started Schedule "${schedule.id}" of "${schedule.name}" failed.`, normalizeRuntimeDiagnosticError(result.reason, { includeStack: true }));
197
+ });
198
+ if (results.every((result) => result.status === "fulfilled")) runtime.checkedThrough = Math.max(runtime.checkedThrough ?? minute, minute);
199
+ }
200
+ //#endregion
201
+ export { runStartedSchedules as i, createMemoryStartedScheduleStore as n, installStartedSchedules as r, createKVStartedScheduleStore as t };