@vite-hub/schedule 0.0.0 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,138 @@
1
+ import { t as createLocalWaitUntil } from "../wait-until-CR-JjIOb.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 : typeof scheduledTime === "number" || typeof scheduledTime === "string" ? new Date(scheduledTime) : /* @__PURE__ */ new Date();
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 typeof value === "object" && value !== null && !Array.isArray(value);
98
+ }
99
+ function readCloudflareWaitUntil(event) {
100
+ const context = isRecord(event.context) ? event.context : void 0;
101
+ const cloudflareContext = isRecord(context?.cloudflare) ? context.cloudflare : void 0;
102
+ const platformContext = isRecord(context?._platform) ? context._platform : void 0;
103
+ const platformCloudflareContext = isRecord(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
104
+ const request = isRecord(event.req) ? event.req : void 0;
105
+ const runtime = isRecord(request?.runtime) ? request.runtime : void 0;
106
+ const runtimeCloudflare = isRecord(runtime?.cloudflare) ? runtime.cloudflare : void 0;
107
+ const owners = [
108
+ event,
109
+ context,
110
+ cloudflareContext,
111
+ isRecord(cloudflareContext?.context) ? cloudflareContext.context : void 0,
112
+ platformCloudflareContext,
113
+ isRecord(platformCloudflareContext?.context) ? platformCloudflareContext.context : void 0,
114
+ request,
115
+ runtimeCloudflare,
116
+ isRecord(runtimeCloudflare?.context) ? runtimeCloudflare.context : void 0
117
+ ];
118
+ for (const owner of owners) if (typeof owner?.waitUntil === "function") return owner.waitUntil.bind(owner);
119
+ }
120
+ function readCloudflareEventEnv(event) {
121
+ if (isRecord(event.env)) return event.env;
122
+ const context = isRecord(event.context) ? event.context : void 0;
123
+ const cloudflareContext = isRecord(context?.cloudflare) ? context.cloudflare : void 0;
124
+ if (isRecord(cloudflareContext?.env)) return cloudflareContext.env;
125
+ const platformContext = isRecord(context?._platform) ? context._platform : void 0;
126
+ const platformCloudflareContext = isRecord(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
127
+ if (isRecord(platformCloudflareContext?.env)) return platformCloudflareContext.env;
128
+ const request = isRecord(event.req) ? event.req : void 0;
129
+ const runtime = isRecord(request?.runtime) ? request.runtime : void 0;
130
+ const runtimeCloudflare = isRecord(runtime?.cloudflare) ? runtime.cloudflare : void 0;
131
+ return isRecord(runtimeCloudflare?.env) ? runtimeCloudflare.env : void 0;
132
+ }
133
+ function unwrapScheduleDefinition(loaded) {
134
+ const definition = typeof loaded === "object" && loaded !== null && "default" in loaded ? loaded.default : loaded;
135
+ return definition && "cron" in definition ? definition : void 0;
136
+ }
137
+ //#endregion
138
+ export { createStaticScheduleRun, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule };
@@ -0,0 +1,5 @@
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 { a as createMemoryRuntimeScheduleStore, c as validateRuntimeScheduleCron, s as schedules } from "./store-D2zUgEDc.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 };
@@ -0,0 +1,3 @@
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-BcEhBV8v.js";
2
+ import { n as validateRuntimeScheduleCron, t as schedules } from "./client-B3cyh-BG.js";
3
+ export { createMemoryRuntimeScheduleStore, getRuntimeScheduleStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, schedules, setRuntimeScheduleStore, setScheduleRuntimeRegistry, validateRuntimeScheduleCron };
@@ -0,0 +1,488 @@
1
+ import { ViteHubError } from "@vite-hub/runtime";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ //#region src/errors.ts
4
+ const scheduleErrorMessages = {
5
+ SCHEDULE_ALREADY_EXISTS: "Runtime Schedule already exists.",
6
+ SCHEDULE_DISABLED: "Runtime Schedule is disabled.",
7
+ SCHEDULE_INVALID_CRON: "Runtime Schedule cron is invalid.",
8
+ SCHEDULE_INVALID_ENABLED: "Runtime Schedule enabled value is invalid.",
9
+ SCHEDULE_INVALID_ID: "Runtime Schedule id is invalid.",
10
+ SCHEDULE_INVALID_INPUT: "Runtime Schedule input is invalid.",
11
+ SCHEDULE_INVALID_SCHEDULED_AT: "Runtime Schedule scheduledAt value is invalid.",
12
+ SCHEDULE_INVALID_TARGET: "Runtime Schedule target is invalid.",
13
+ SCHEDULE_INVALID_TIME_ZONE: "Runtime Schedule time zone is invalid.",
14
+ SCHEDULE_NOT_DUE: "Schedule is not due.",
15
+ SCHEDULE_NOT_FOUND: "Runtime Schedule was not found.",
16
+ SCHEDULE_RUN_NOT_FOUND: "Schedule Run was not found.",
17
+ SCHEDULE_TARGET_NOT_ELIGIBLE: "Runtime Schedule target is not eligible.",
18
+ SCHEDULE_TARGET_NOT_FOUND: "Runtime Schedule target was not found."
19
+ };
20
+ function invalidScheduleValueDetails(field, value) {
21
+ let valueType;
22
+ try {
23
+ valueType = value === null ? "null" : Array.isArray(value) ? "array" : value instanceof Date ? "date" : typeof value;
24
+ } catch {
25
+ valueType = "unknown";
26
+ }
27
+ return {
28
+ field,
29
+ valueType
30
+ };
31
+ }
32
+ function createScheduleError(code, options = {}) {
33
+ return new ViteHubError(code, scheduleErrorMessages[code], options);
34
+ }
35
+ function assertRuntimeScheduleId(id) {
36
+ if (typeof id !== "string" || !id.trim()) throw createScheduleError("SCHEDULE_INVALID_ID", { details: invalidScheduleValueDetails("id", id) });
37
+ }
38
+ //#endregion
39
+ //#region src/runtime/store.ts
40
+ function trimPrefix(prefix) {
41
+ return prefix.replace(/^\/+|\/+$/g, "");
42
+ }
43
+ function joinKey(prefix, ...parts) {
44
+ const base = trimPrefix(prefix);
45
+ const suffix = parts.map(encodeURIComponent).join("/");
46
+ return base ? `${base}/${suffix}` : suffix;
47
+ }
48
+ function runtimeScheduleKey(prefix, id) {
49
+ return joinKey(prefix, "runtime-schedules", id);
50
+ }
51
+ function scheduleRunKey(prefix, id) {
52
+ return joinKey(prefix, "schedule-runs", id);
53
+ }
54
+ function scheduleRunAttemptKey(prefix, id) {
55
+ return joinKey(prefix, "schedule-run-attempts", id);
56
+ }
57
+ function runtimeScheduleBase(prefix) {
58
+ return joinKey(prefix, "runtime-schedules");
59
+ }
60
+ function scheduleRunBase(prefix) {
61
+ return joinKey(prefix, "schedule-runs");
62
+ }
63
+ function scheduleRunAttemptBase(prefix) {
64
+ return joinKey(prefix, "schedule-run-attempts");
65
+ }
66
+ async function resolveDefaultKVStore() {
67
+ const module = await import("@vite-hub/kv");
68
+ return {
69
+ async del(key) {
70
+ const [error] = await module.kv.del(key);
71
+ if (error) throw error;
72
+ },
73
+ async get(key) {
74
+ const [error, value] = await module.kv.get(key);
75
+ if (error) throw error;
76
+ return value;
77
+ },
78
+ async has(key) {
79
+ const [error, value] = await module.kv.has(key);
80
+ if (error) throw error;
81
+ return value;
82
+ },
83
+ async keys(base) {
84
+ const [error, value] = await module.kv.keys(base);
85
+ if (error) throw error;
86
+ return value;
87
+ },
88
+ async set(key, value) {
89
+ const [error] = await module.kv.set(key, value);
90
+ if (error) throw error;
91
+ }
92
+ };
93
+ }
94
+ function cloneRuntimeSchedule(record) {
95
+ return {
96
+ ...record,
97
+ createdAt: new Date(record.createdAt),
98
+ ...record.input !== void 0 ? { input: structuredClone(record.input) } : {},
99
+ updatedAt: new Date(record.updatedAt)
100
+ };
101
+ }
102
+ function serializeRuntimeSchedule(record) {
103
+ return {
104
+ ...record,
105
+ createdAt: record.createdAt.toISOString(),
106
+ ...record.input !== void 0 ? { input: structuredClone(record.input) } : {},
107
+ updatedAt: record.updatedAt.toISOString()
108
+ };
109
+ }
110
+ function deserializeRuntimeSchedule(record) {
111
+ return {
112
+ ...record,
113
+ createdAt: new Date(record.createdAt),
114
+ ...record.input !== void 0 ? { input: structuredClone(record.input) } : {},
115
+ updatedAt: new Date(record.updatedAt)
116
+ };
117
+ }
118
+ function omitUndefinedPatch(patch) {
119
+ return {
120
+ ...patch.cron !== void 0 ? { cron: patch.cron } : {},
121
+ ...patch.enabled !== void 0 ? { enabled: patch.enabled } : {},
122
+ ...Object.hasOwn(patch, "input") ? { input: structuredClone(patch.input) } : {},
123
+ ...patch.target !== void 0 ? { target: patch.target } : {},
124
+ ...patch.timeZone !== void 0 ? { timeZone: patch.timeZone } : {}
125
+ };
126
+ }
127
+ const keyLocks = /* @__PURE__ */ new Map();
128
+ async function withKVKeyLock(key, operation) {
129
+ const previous = keyLocks.get(key) ?? Promise.resolve();
130
+ let release;
131
+ const current = new Promise((resolve) => {
132
+ release = resolve;
133
+ });
134
+ const queued = previous.then(() => current, () => current);
135
+ keyLocks.set(key, queued);
136
+ await previous;
137
+ try {
138
+ return await operation();
139
+ } finally {
140
+ release();
141
+ if (keyLocks.get(key) === queued) keyLocks.delete(key);
142
+ }
143
+ }
144
+ function createMemoryRuntimeScheduleStore() {
145
+ const records = /* @__PURE__ */ new Map();
146
+ return {
147
+ create(record) {
148
+ assertRuntimeScheduleId(record.id);
149
+ if (records.has(record.id)) throw createScheduleError("SCHEDULE_ALREADY_EXISTS");
150
+ records.set(record.id, cloneRuntimeSchedule(record));
151
+ return cloneRuntimeSchedule(record);
152
+ },
153
+ delete(id) {
154
+ return records.delete(id);
155
+ },
156
+ get(id) {
157
+ const record = records.get(id);
158
+ return record ? cloneRuntimeSchedule(record) : void 0;
159
+ },
160
+ list() {
161
+ return [...records.values()].map(cloneRuntimeSchedule);
162
+ },
163
+ update(id, patch) {
164
+ const existing = records.get(id);
165
+ if (!existing) return;
166
+ const next = cloneRuntimeSchedule({
167
+ ...existing,
168
+ ...omitUndefinedPatch(patch),
169
+ updatedAt: patch.updatedAt
170
+ });
171
+ records.set(id, next);
172
+ return cloneRuntimeSchedule(next);
173
+ }
174
+ };
175
+ }
176
+ function createKVRuntimeScheduleStore(options = {}) {
177
+ const prefix = options.prefix ?? "vitehub:schedule";
178
+ async function getKVStore() {
179
+ return options.kvStore || await resolveDefaultKVStore();
180
+ }
181
+ return {
182
+ async create(record) {
183
+ assertRuntimeScheduleId(record.id);
184
+ const store = await getKVStore();
185
+ const key = runtimeScheduleKey(prefix, record.id);
186
+ return await withKVKeyLock(key, async () => {
187
+ if (await store.has(key)) throw createScheduleError("SCHEDULE_ALREADY_EXISTS");
188
+ await store.set(key, serializeRuntimeSchedule(record));
189
+ return cloneRuntimeSchedule(record);
190
+ });
191
+ },
192
+ async delete(id) {
193
+ const store = await getKVStore();
194
+ const key = runtimeScheduleKey(prefix, id);
195
+ return await withKVKeyLock(key, async () => {
196
+ if (!await store.has(key)) return false;
197
+ await store.del(key);
198
+ return true;
199
+ });
200
+ },
201
+ async get(id) {
202
+ const record = await (await getKVStore()).get(runtimeScheduleKey(prefix, id));
203
+ return record ? deserializeRuntimeSchedule(record) : void 0;
204
+ },
205
+ async list() {
206
+ const store = await getKVStore();
207
+ const keys = await store.keys(runtimeScheduleBase(prefix));
208
+ return (await Promise.all(keys.map((key) => store.get(key)))).flatMap((record) => record ? [deserializeRuntimeSchedule(record)] : []);
209
+ },
210
+ async update(id, patch) {
211
+ const store = await getKVStore();
212
+ const key = runtimeScheduleKey(prefix, id);
213
+ return await withKVKeyLock(key, async () => {
214
+ const existing = await store.get(key);
215
+ if (!existing) return;
216
+ const next = cloneRuntimeSchedule({
217
+ ...deserializeRuntimeSchedule(existing),
218
+ ...omitUndefinedPatch(patch),
219
+ updatedAt: patch.updatedAt
220
+ });
221
+ await store.set(key, serializeRuntimeSchedule(next));
222
+ return cloneRuntimeSchedule(next);
223
+ });
224
+ }
225
+ };
226
+ }
227
+ function cloneScheduleRun(record) {
228
+ return {
229
+ ...record,
230
+ completedAt: record.completedAt ? new Date(record.completedAt) : void 0,
231
+ createdAt: new Date(record.createdAt),
232
+ scheduledAt: new Date(record.scheduledAt),
233
+ error: record.error ? { ...record.error } : void 0,
234
+ startedAt: record.startedAt ? new Date(record.startedAt) : void 0,
235
+ updatedAt: new Date(record.updatedAt)
236
+ };
237
+ }
238
+ function cloneScheduleRunAttempt(record) {
239
+ return {
240
+ ...record,
241
+ completedAt: record.completedAt ? new Date(record.completedAt) : void 0,
242
+ createdAt: new Date(record.createdAt),
243
+ error: record.error ? { ...record.error } : void 0,
244
+ startedAt: new Date(record.startedAt),
245
+ updatedAt: new Date(record.updatedAt)
246
+ };
247
+ }
248
+ function serializeScheduleRun(record) {
249
+ return {
250
+ ...record,
251
+ completedAt: record.completedAt?.toISOString(),
252
+ createdAt: record.createdAt.toISOString(),
253
+ error: record.error ? { ...record.error } : void 0,
254
+ scheduledAt: record.scheduledAt.toISOString(),
255
+ startedAt: record.startedAt?.toISOString(),
256
+ updatedAt: record.updatedAt.toISOString()
257
+ };
258
+ }
259
+ function deserializeScheduleRun(record) {
260
+ return {
261
+ ...record,
262
+ completedAt: record.completedAt ? new Date(record.completedAt) : void 0,
263
+ createdAt: new Date(record.createdAt),
264
+ error: record.error ? { ...record.error } : void 0,
265
+ scheduledAt: new Date(record.scheduledAt),
266
+ startedAt: record.startedAt ? new Date(record.startedAt) : void 0,
267
+ updatedAt: new Date(record.updatedAt)
268
+ };
269
+ }
270
+ function serializeScheduleRunAttempt(record) {
271
+ return {
272
+ ...record,
273
+ completedAt: record.completedAt?.toISOString(),
274
+ createdAt: record.createdAt.toISOString(),
275
+ error: record.error ? { ...record.error } : void 0,
276
+ startedAt: record.startedAt.toISOString(),
277
+ updatedAt: record.updatedAt.toISOString()
278
+ };
279
+ }
280
+ function deserializeScheduleRunAttempt(record) {
281
+ return {
282
+ ...record,
283
+ completedAt: record.completedAt ? new Date(record.completedAt) : void 0,
284
+ createdAt: new Date(record.createdAt),
285
+ error: record.error ? { ...record.error } : void 0,
286
+ startedAt: new Date(record.startedAt),
287
+ updatedAt: new Date(record.updatedAt)
288
+ };
289
+ }
290
+ function createMemoryScheduleRunStore() {
291
+ const runs = /* @__PURE__ */ new Map();
292
+ const attempts = /* @__PURE__ */ new Map();
293
+ return {
294
+ createAttempt(attempt) {
295
+ if (attempts.has(attempt.id)) throw new Error(`Schedule Run Attempt already exists: ${attempt.id}`);
296
+ attempts.set(attempt.id, cloneScheduleRunAttempt(attempt));
297
+ return cloneScheduleRunAttempt(attempt);
298
+ },
299
+ createRun(run) {
300
+ if (runs.has(run.id)) throw new Error(`Schedule Run already exists: ${run.id}`);
301
+ runs.set(run.id, cloneScheduleRun(run));
302
+ return cloneScheduleRun(run);
303
+ },
304
+ getAttempt(id) {
305
+ const attempt = attempts.get(id);
306
+ return attempt ? cloneScheduleRunAttempt(attempt) : void 0;
307
+ },
308
+ getRun(id) {
309
+ const run = runs.get(id);
310
+ return run ? cloneScheduleRun(run) : void 0;
311
+ },
312
+ listAttempts(runId) {
313
+ return [...attempts.values()].filter((attempt) => attempt.runId === runId).map(cloneScheduleRunAttempt);
314
+ },
315
+ listRuns() {
316
+ return [...runs.values()].map(cloneScheduleRun);
317
+ },
318
+ updateAttempt(id, patch) {
319
+ const existing = attempts.get(id);
320
+ if (!existing) return;
321
+ const next = cloneScheduleRunAttempt({
322
+ ...existing,
323
+ ...patch,
324
+ updatedAt: patch.updatedAt
325
+ });
326
+ attempts.set(id, next);
327
+ return cloneScheduleRunAttempt(next);
328
+ },
329
+ updateRun(id, patch) {
330
+ const existing = runs.get(id);
331
+ if (!existing) return;
332
+ const next = cloneScheduleRun({
333
+ ...existing,
334
+ ...patch,
335
+ updatedAt: patch.updatedAt
336
+ });
337
+ runs.set(id, next);
338
+ return cloneScheduleRun(next);
339
+ }
340
+ };
341
+ }
342
+ function createKVScheduleRunStore(options = {}) {
343
+ const prefix = options.prefix ?? "vitehub:schedule";
344
+ async function getKVStore() {
345
+ return options.kvStore || await resolveDefaultKVStore();
346
+ }
347
+ return {
348
+ async createAttempt(attempt) {
349
+ const store = await getKVStore();
350
+ const key = scheduleRunAttemptKey(prefix, attempt.id);
351
+ return await withKVKeyLock(key, async () => {
352
+ if (await store.has(key)) throw new Error(`Schedule Run Attempt already exists: ${attempt.id}`);
353
+ await store.set(key, serializeScheduleRunAttempt(attempt));
354
+ return cloneScheduleRunAttempt(attempt);
355
+ });
356
+ },
357
+ async createRun(run) {
358
+ const store = await getKVStore();
359
+ const key = scheduleRunKey(prefix, run.id);
360
+ return await withKVKeyLock(key, async () => {
361
+ if (await store.has(key)) throw new Error(`Schedule Run already exists: ${run.id}`);
362
+ await store.set(key, serializeScheduleRun(run));
363
+ return cloneScheduleRun(run);
364
+ });
365
+ },
366
+ async getAttempt(id) {
367
+ const attempt = await (await getKVStore()).get(scheduleRunAttemptKey(prefix, id));
368
+ return attempt ? deserializeScheduleRunAttempt(attempt) : void 0;
369
+ },
370
+ async getRun(id) {
371
+ const run = await (await getKVStore()).get(scheduleRunKey(prefix, id));
372
+ return run ? deserializeScheduleRun(run) : void 0;
373
+ },
374
+ async listAttempts(runId) {
375
+ const store = await getKVStore();
376
+ const keys = await store.keys(scheduleRunAttemptBase(prefix));
377
+ return (await Promise.all(keys.map((key) => store.get(key)))).flatMap((attempt) => attempt && attempt.runId === runId ? [deserializeScheduleRunAttempt(attempt)] : []);
378
+ },
379
+ async listRuns() {
380
+ const store = await getKVStore();
381
+ const keys = await store.keys(scheduleRunBase(prefix));
382
+ return (await Promise.all(keys.map((key) => store.get(key)))).flatMap((run) => run ? [deserializeScheduleRun(run)] : []);
383
+ },
384
+ async updateAttempt(id, patch) {
385
+ const store = await getKVStore();
386
+ const key = scheduleRunAttemptKey(prefix, id);
387
+ const existing = await store.get(key);
388
+ if (!existing) return;
389
+ const next = cloneScheduleRunAttempt({
390
+ ...deserializeScheduleRunAttempt(existing),
391
+ ...patch,
392
+ updatedAt: patch.updatedAt
393
+ });
394
+ await store.set(key, serializeScheduleRunAttempt(next));
395
+ return cloneScheduleRunAttempt(next);
396
+ },
397
+ async updateRun(id, patch) {
398
+ const store = await getKVStore();
399
+ const key = scheduleRunKey(prefix, id);
400
+ const existing = await store.get(key);
401
+ if (!existing) return;
402
+ const next = cloneScheduleRun({
403
+ ...deserializeScheduleRun(existing),
404
+ ...patch,
405
+ updatedAt: patch.updatedAt
406
+ });
407
+ await store.set(key, serializeScheduleRun(next));
408
+ return cloneScheduleRun(next);
409
+ }
410
+ };
411
+ }
412
+ //#endregion
413
+ //#region src/runtime/state.ts
414
+ let runtimeRegistry;
415
+ let runtimeStore;
416
+ let runtimeRegistryVersion = 0;
417
+ let runStore;
418
+ const loadedRegistryEntries = /* @__PURE__ */ new Map();
419
+ const loadingRegistryEntries = /* @__PURE__ */ new Map();
420
+ const loadingRegistryStorage = new AsyncLocalStorage();
421
+ function isScheduleDefinition(value) {
422
+ return Boolean(value) && typeof value === "object" && typeof value.handler === "function";
423
+ }
424
+ function setScheduleRuntimeRegistry(registry) {
425
+ runtimeRegistry = registry;
426
+ runtimeRegistryVersion++;
427
+ loadedRegistryEntries.clear();
428
+ loadingRegistryEntries.clear();
429
+ }
430
+ function getScheduleRuntimeRegistry() {
431
+ return runtimeRegistry;
432
+ }
433
+ function setRuntimeScheduleStore(store) {
434
+ runtimeStore = store;
435
+ }
436
+ function getRuntimeScheduleStore() {
437
+ return runtimeStore ??= createMemoryRuntimeScheduleStore();
438
+ }
439
+ function setScheduleRunStore(store) {
440
+ runStore = store;
441
+ }
442
+ function getScheduleRunStore() {
443
+ return runStore ??= createMemoryScheduleRunStore();
444
+ }
445
+ async function loadScheduleDefinition(name) {
446
+ const entry = runtimeRegistry && Object.hasOwn(runtimeRegistry, name) ? runtimeRegistry[name] : void 0;
447
+ if (typeof entry !== "function") return;
448
+ if (loadedRegistryEntries.has(name)) return loadedRegistryEntries.get(name);
449
+ const activeLoads = loadingRegistryStorage.getStore();
450
+ const inFlightEntry = loadingRegistryEntries.get(name);
451
+ if (inFlightEntry) {
452
+ if (activeLoads?.has(name)) return void 0;
453
+ const loaded = await inFlightEntry.promise;
454
+ return inFlightEntry.version === runtimeRegistryVersion ? loaded : void 0;
455
+ }
456
+ const loadingVersion = runtimeRegistryVersion;
457
+ const nextActiveLoads = new Set(activeLoads);
458
+ nextActiveLoads.add(name);
459
+ const loadingEntry = Promise.resolve().then(() => loadingRegistryStorage.run(nextActiveLoads, async () => {
460
+ const loaded = await entry();
461
+ if (isScheduleDefinition(loaded)) return loaded;
462
+ if (loaded && typeof loaded === "object" && "default" in loaded && isScheduleDefinition(loaded.default)) return loaded.default;
463
+ }));
464
+ loadingRegistryEntries.set(name, {
465
+ promise: loadingEntry,
466
+ version: loadingVersion
467
+ });
468
+ try {
469
+ const loaded = await loadingEntry;
470
+ if (loadingVersion === runtimeRegistryVersion) {
471
+ loadedRegistryEntries.set(name, loaded);
472
+ return loaded;
473
+ }
474
+ return;
475
+ } finally {
476
+ if (loadingRegistryEntries.get(name)?.promise === loadingEntry) loadingRegistryEntries.delete(name);
477
+ }
478
+ }
479
+ function resetScheduleRuntime() {
480
+ runtimeRegistry = void 0;
481
+ runtimeRegistryVersion++;
482
+ runtimeStore = void 0;
483
+ runStore = void 0;
484
+ loadedRegistryEntries.clear();
485
+ loadingRegistryEntries.clear();
486
+ }
487
+ //#endregion
488
+ export { resetScheduleRuntime as a, setScheduleRuntimeRegistry as c, createMemoryRuntimeScheduleStore as d, createMemoryScheduleRunStore as f, invalidScheduleValueDetails as h, loadScheduleDefinition as i, createKVRuntimeScheduleStore as l, createScheduleError as m, getScheduleRunStore as n, setRuntimeScheduleStore as o, assertRuntimeScheduleId as p, getScheduleRuntimeRegistry as r, setScheduleRunStore as s, getRuntimeScheduleStore as t, createKVScheduleRunStore as u };
@@ -0,0 +1,38 @@
1
+ import { C as ScheduleTargetName, a as RuntimeScheduleStore, b as ScheduleRunStore, i as RuntimeScheduleRecord, m as ScheduleRunAttemptRecord, n as RuntimeScheduleCreateInput, o as RuntimeScheduleUpdateInput, v as ScheduleRunRecord } from "./types-Bcje4dLV.js";
2
+
3
+ //#region src/runtime/client.d.ts
4
+ declare function validateRuntimeScheduleCron(cron: unknown): void;
5
+ declare const schedules: {
6
+ create<TTarget extends ScheduleTargetName, TInput = unknown>(input: RuntimeScheduleCreateInput<TTarget, TInput>): Promise<RuntimeScheduleRecord<TInput>>;
7
+ delete(id: string): Promise<boolean>;
8
+ disable(id: string): Promise<RuntimeScheduleRecord>;
9
+ enable(id: string): Promise<RuntimeScheduleRecord>;
10
+ get(id: string): Promise<RuntimeScheduleRecord | undefined>;
11
+ getRun(id: string): Promise<ScheduleRunRecord | undefined>;
12
+ list(): Promise<RuntimeScheduleRecord[]>;
13
+ listAttempts(runId: string): Promise<ScheduleRunAttemptRecord[]>;
14
+ listRuns(): Promise<ScheduleRunRecord[]>;
15
+ run(id: string, options?: {
16
+ scheduledAt?: Date;
17
+ }): Promise<ScheduleRunRecord>;
18
+ update<TTarget extends ScheduleTargetName, TInput = unknown>(id: string, input: RuntimeScheduleUpdateInput<TTarget, TInput>): Promise<RuntimeScheduleRecord<TInput>>;
19
+ };
20
+ //#endregion
21
+ //#region src/runtime/store.d.ts
22
+ interface ScheduleKVStorage {
23
+ del(key: string): boolean | Promise<boolean> | Promise<void> | void;
24
+ get<T = unknown>(key: string): Promise<T | null | undefined> | T | null | undefined;
25
+ has(key: string): boolean | Promise<boolean>;
26
+ keys(base?: string): Promise<string[]> | string[];
27
+ set<T = unknown>(key: string, value: T): Promise<void> | void;
28
+ }
29
+ interface KVScheduleStoreOptions {
30
+ kvStore?: ScheduleKVStorage;
31
+ prefix?: string;
32
+ }
33
+ declare function createMemoryRuntimeScheduleStore(): RuntimeScheduleStore;
34
+ declare function createKVRuntimeScheduleStore(options?: KVScheduleStoreOptions): RuntimeScheduleStore;
35
+ declare function createMemoryScheduleRunStore(): ScheduleRunStore;
36
+ declare function createKVScheduleRunStore(options?: KVScheduleStoreOptions): ScheduleRunStore;
37
+ //#endregion
38
+ export { createMemoryRuntimeScheduleStore as a, validateRuntimeScheduleCron as c, createKVScheduleRunStore as i, ScheduleKVStorage as n, createMemoryScheduleRunStore as o, createKVRuntimeScheduleStore as r, schedules as s, KVScheduleStoreOptions as t };