@vite-hub/schedule 0.0.0 → 0.0.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.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
1
  # @vite-hub/schedule
2
2
 
3
- Reserved package name for ViteHub.
3
+ <p>
4
+ <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
+ <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
+ <img alt="Vite" src="https://img.shields.io/badge/Vite-discovery-646cff?style=flat-square">
7
+ <img alt="Schedule" src="https://img.shields.io/badge/Schedule-cron%20runtime-0284c7?style=flat-square">
8
+ </p>
9
+
10
+ `@vite-hub/schedule` keeps cron definitions and runtime schedules behind one schedule registry.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pnpm add @vite-hub/schedule
16
+ ```
17
+
18
+ Add `@vite-hub/kv` when runtime schedules should persist outside memory.
19
+
20
+ ## Minimal API
21
+
22
+ ```ts
23
+ // server/schedules/daily-report.ts
24
+ import { defineSchedule } from "@vite-hub/schedule"
25
+
26
+ export default defineSchedule({
27
+ cron: "0 8 * * *",
28
+ allowRuntimeSchedules: true,
29
+ handler: async ({ scheduledAt }) => {
30
+ console.log(`Generating daily report for ${scheduledAt.toISOString()}`)
31
+ },
32
+ })
33
+ ```
34
+
35
+ ```ts
36
+ // server/api/schedules.post.ts
37
+ import { schedules } from "@vite-hub/schedule/runtime"
38
+ import { defineEventHandler } from "h3"
39
+
40
+ export default defineEventHandler(() => {
41
+ return schedules.create({
42
+ cron: "30 3 * * 1",
43
+ target: "daily-report",
44
+ })
45
+ })
46
+ ```
47
+
48
+ ```ts
49
+ // nitro.config.ts
50
+ import { defineNitroConfig } from "nitro/config"
51
+
52
+ export default defineNitroConfig({
53
+ modules: ["@vite-hub/schedule/nitro"],
54
+ })
55
+ ```
56
+
57
+ ## Vite and Nitro
58
+
59
+ Nitro discovers `server/schedules/<name>.ts`; Vite supports `src/<name>.schedule.ts` through `hubSchedule()`. Static schedules can produce provider cron output, including [Vercel Cron Jobs](https://vercel.com/docs/cron-jobs/). Cron parsing uses [`cron-schedule`](https://github.com/P4sca1/cron-schedule).
60
+
61
+ Learn more at [vitehub.dev](https://vitehub.dev).
@@ -0,0 +1,401 @@
1
+ import { i as loadScheduleDefinition, n as getScheduleRunStore, p as ScheduleError, t as getRuntimeScheduleStore } from "./state-DoONzfij.js";
2
+ //#region ../internal/src/runtime/random.ts
3
+ function randomId(prefix) {
4
+ const body = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
5
+ return prefix ? `${prefix}_${body}` : body;
6
+ }
7
+ //#endregion
8
+ //#region src/runtime/execute.ts
9
+ function assertRuntimeExecuteOptionsObject(options) {
10
+ if (typeof options !== "object" || options === null || Array.isArray(options)) throw new ScheduleError("Runtime Schedule execute options must be a schedule id or options object.", {
11
+ code: "SCHEDULE_INVALID_INPUT",
12
+ details: { options },
13
+ httpStatus: 400
14
+ });
15
+ }
16
+ function normalizeRunSource(source) {
17
+ return source ?? "direct";
18
+ }
19
+ function toRunId(source, scheduleId, scheduledAt) {
20
+ return `srun_${normalizeRunSource(source)}_${encodeURIComponent(scheduleId)}_${scheduledAt.toISOString()}`;
21
+ }
22
+ function validateScheduledAt(scheduledAt) {
23
+ if (!(scheduledAt instanceof Date) || Number.isNaN(scheduledAt.getTime())) throw new ScheduleError("Schedule Run scheduledAt must be a valid Date.", {
24
+ code: "SCHEDULE_INVALID_SCHEDULED_AT",
25
+ details: { scheduledAt },
26
+ httpStatus: 400
27
+ });
28
+ return scheduledAt;
29
+ }
30
+ function toRunError(error) {
31
+ if (error instanceof Error) return {
32
+ message: error.message,
33
+ name: error.name,
34
+ stack: error.stack
35
+ };
36
+ return { message: String(error) };
37
+ }
38
+ function requireUpdatedRun(run) {
39
+ if (!run) throw new ScheduleError("Schedule Run bookkeeping update failed.", {
40
+ code: "SCHEDULE_RUN_NOT_FOUND",
41
+ httpStatus: 500
42
+ });
43
+ return run;
44
+ }
45
+ async function createOrGetRun(options) {
46
+ const store = options.runStore ?? getScheduleRunStore();
47
+ const id = toRunId(options.source, options.scheduleId, options.scheduledAt);
48
+ const existing = await store.getRun(id);
49
+ if (existing) return {
50
+ created: false,
51
+ run: existing
52
+ };
53
+ const now = /* @__PURE__ */ new Date();
54
+ const runInput = {
55
+ attemptCount: 0,
56
+ createdAt: now,
57
+ id,
58
+ scheduleId: options.scheduleId,
59
+ scheduledAt: options.scheduledAt,
60
+ status: "pending",
61
+ target: options.target,
62
+ updatedAt: now
63
+ };
64
+ try {
65
+ return {
66
+ created: true,
67
+ run: await store.createRun(runInput)
68
+ };
69
+ } catch (error) {
70
+ const run = await store.getRun(id);
71
+ if (run) return {
72
+ created: false,
73
+ run
74
+ };
75
+ throw error;
76
+ }
77
+ }
78
+ async function startAttempt(run, store = getScheduleRunStore()) {
79
+ const now = /* @__PURE__ */ new Date();
80
+ const attempt = await store.createAttempt({
81
+ createdAt: now,
82
+ id: randomId("satt"),
83
+ runId: run.id,
84
+ startedAt: now,
85
+ status: "running",
86
+ updatedAt: now
87
+ });
88
+ await store.updateRun(run.id, {
89
+ attemptCount: run.attemptCount + 1,
90
+ startedAt: run.startedAt ?? now,
91
+ status: "running",
92
+ updatedAt: now
93
+ });
94
+ return attempt;
95
+ }
96
+ function toHandlerContext(run, attempt) {
97
+ return {
98
+ attemptId: attempt.id,
99
+ id: run.id,
100
+ runId: run.id,
101
+ scheduleId: run.scheduleId,
102
+ scheduledAt: run.scheduledAt,
103
+ target: run.target
104
+ };
105
+ }
106
+ async function completeRun(run, attempt, store = getScheduleRunStore()) {
107
+ const now = /* @__PURE__ */ new Date();
108
+ await store.updateAttempt(attempt.id, {
109
+ completedAt: now,
110
+ status: "succeeded",
111
+ updatedAt: now
112
+ });
113
+ return requireUpdatedRun(await store.updateRun(run.id, {
114
+ completedAt: now,
115
+ status: "succeeded",
116
+ updatedAt: now
117
+ }));
118
+ }
119
+ async function failRun(run, attempt, error, store = getScheduleRunStore()) {
120
+ const now = /* @__PURE__ */ new Date();
121
+ const serializedError = toRunError(error);
122
+ await store.updateAttempt(attempt.id, {
123
+ completedAt: now,
124
+ error: serializedError,
125
+ status: "failed",
126
+ updatedAt: now
127
+ });
128
+ return requireUpdatedRun(await store.updateRun(run.id, {
129
+ completedAt: now,
130
+ error: serializedError,
131
+ status: "failed",
132
+ updatedAt: now
133
+ }));
134
+ }
135
+ async function createScheduleRun(options) {
136
+ const scheduledAt = validateScheduledAt(options.scheduledAt ?? /* @__PURE__ */ new Date());
137
+ return (await createOrGetRun({
138
+ ...options,
139
+ scheduledAt
140
+ })).run;
141
+ }
142
+ async function executeSchedule(options) {
143
+ const scheduledAt = validateScheduledAt(options.scheduledAt ?? /* @__PURE__ */ new Date());
144
+ const { created, run } = await createOrGetRun({
145
+ ...options,
146
+ scheduledAt
147
+ });
148
+ if (!created) return run;
149
+ const runStore = options.runStore ?? getScheduleRunStore();
150
+ const attempt = await startAttempt(run, runStore);
151
+ try {
152
+ await options.definition.handler(toHandlerContext(run, attempt));
153
+ return await completeRun(run, attempt, runStore);
154
+ } catch (error) {
155
+ await failRun(run, attempt, error, runStore);
156
+ throw error;
157
+ }
158
+ }
159
+ async function executeStaticSchedule(options) {
160
+ return await executeSchedule({
161
+ definition: options.definition,
162
+ scheduleId: options.name,
163
+ source: "static",
164
+ scheduledAt: options.scheduledAt,
165
+ target: options.name
166
+ });
167
+ }
168
+ async function loadRequiredRuntimeSchedule(id, store = getRuntimeScheduleStore()) {
169
+ const schedule = await store.get(id);
170
+ if (!schedule) throw new ScheduleError(`Runtime Schedule not found: ${id}`, {
171
+ code: "SCHEDULE_NOT_FOUND",
172
+ details: { id },
173
+ httpStatus: 404
174
+ });
175
+ return schedule;
176
+ }
177
+ async function executeRuntimeSchedule(options) {
178
+ const runtimeOptions = typeof options === "string" ? { id: options } : options;
179
+ assertRuntimeExecuteOptionsObject(runtimeOptions);
180
+ const id = runtimeOptions.id;
181
+ const scheduledAt = validateScheduledAt(runtimeOptions.scheduledAt ?? /* @__PURE__ */ new Date());
182
+ const runtimeScheduleStore = runtimeOptions.runtimeScheduleStore;
183
+ const scheduleRunStore = runtimeOptions.scheduleRunStore;
184
+ const existingRun = await (scheduleRunStore ?? getScheduleRunStore()).getRun(toRunId("runtime", id, scheduledAt));
185
+ if (existingRun) return existingRun;
186
+ const schedule = await loadRequiredRuntimeSchedule(id, runtimeScheduleStore);
187
+ if (!schedule.enabled) throw new ScheduleError(`Runtime Schedule is disabled: ${id}`, {
188
+ code: "SCHEDULE_DISABLED",
189
+ details: { id },
190
+ httpStatus: 409
191
+ });
192
+ const definition = await loadScheduleDefinition(schedule.target);
193
+ if (!definition) throw new ScheduleError(`Unknown Runtime Schedule target: ${schedule.target}`, {
194
+ code: "SCHEDULE_TARGET_NOT_FOUND",
195
+ details: { target: schedule.target },
196
+ httpStatus: 404
197
+ });
198
+ if (definition.options?.allowRuntimeSchedules !== true) throw new ScheduleError(`Runtime Schedule target is not eligible: ${schedule.target}`, {
199
+ code: "SCHEDULE_TARGET_NOT_ELIGIBLE",
200
+ details: { target: schedule.target },
201
+ httpStatus: 400
202
+ });
203
+ return await executeSchedule({
204
+ definition,
205
+ runStore: scheduleRunStore,
206
+ scheduleId: schedule.id,
207
+ source: "runtime",
208
+ scheduledAt,
209
+ target: schedule.target
210
+ });
211
+ }
212
+ //#endregion
213
+ //#region src/runtime/client.ts
214
+ const cronRange = {
215
+ dayOfMonth: {
216
+ max: 31,
217
+ min: 1
218
+ },
219
+ dayOfWeek: {
220
+ max: 7,
221
+ min: 0
222
+ },
223
+ hour: {
224
+ max: 23,
225
+ min: 0
226
+ },
227
+ minute: {
228
+ max: 59,
229
+ min: 0
230
+ },
231
+ month: {
232
+ max: 12,
233
+ min: 1
234
+ }
235
+ };
236
+ const cronFieldRanges = [
237
+ cronRange.minute,
238
+ cronRange.hour,
239
+ cronRange.dayOfMonth,
240
+ cronRange.month,
241
+ cronRange.dayOfWeek
242
+ ];
243
+ function parseCronNumber(value, range) {
244
+ if (!/^\d+$/.test(value)) throw new Error("not a number");
245
+ const parsed = Number(value);
246
+ if (!Number.isInteger(parsed) || parsed < range.min || parsed > range.max) throw new Error("out of range");
247
+ return parsed;
248
+ }
249
+ function validateCronPart(part, range) {
250
+ const [value, step, extra] = part.split("/");
251
+ if (extra !== void 0 || value === void 0 || value.length === 0) throw new Error("invalid step");
252
+ if (step !== void 0) {
253
+ if (parseCronNumber(step, {
254
+ max: range.max,
255
+ min: 1
256
+ }) < 1) throw new Error("invalid step");
257
+ }
258
+ if (value === "*") return;
259
+ const [start, end, extraRange] = value.split("-");
260
+ if (extraRange !== void 0 || start === void 0 || start.length === 0) throw new Error("invalid range");
261
+ const parsedStart = parseCronNumber(start, range);
262
+ if (end === void 0) return;
263
+ if (parseCronNumber(end, range) < parsedStart) throw new Error("invalid range");
264
+ }
265
+ function validateRuntimeScheduleCron(cron) {
266
+ if (typeof cron !== "string" || cron.trim() !== cron || cron.length === 0) throw new ScheduleError("Runtime Schedule cron must be a five-field UTC cron expression.", {
267
+ code: "SCHEDULE_INVALID_CRON",
268
+ details: { cron },
269
+ httpStatus: 400
270
+ });
271
+ const fields = cron.split(/\s+/);
272
+ if (fields.length !== 5) throw new ScheduleError("Runtime Schedule cron must be a five-field UTC cron expression.", {
273
+ code: "SCHEDULE_INVALID_CRON",
274
+ details: { cron },
275
+ httpStatus: 400
276
+ });
277
+ try {
278
+ fields.forEach((field, index) => {
279
+ if (field.length === 0) throw new Error("empty field");
280
+ for (const part of field.split(",")) validateCronPart(part, cronFieldRanges[index]);
281
+ });
282
+ } catch {
283
+ throw new ScheduleError(`Invalid Runtime Schedule cron expression: ${cron}`, {
284
+ code: "SCHEDULE_INVALID_CRON",
285
+ details: { cron },
286
+ httpStatus: 400
287
+ });
288
+ }
289
+ }
290
+ async function assertRuntimeTarget(target) {
291
+ if (typeof target !== "string" || !target.trim()) throw new ScheduleError("Runtime Schedule target must be a non-empty string.", {
292
+ code: "SCHEDULE_INVALID_TARGET",
293
+ details: { target },
294
+ httpStatus: 400
295
+ });
296
+ const definition = await loadScheduleDefinition(target);
297
+ if (!definition) throw new ScheduleError(`Unknown Runtime Schedule target: ${target}`, {
298
+ code: "SCHEDULE_TARGET_NOT_FOUND",
299
+ details: { target },
300
+ httpStatus: 404
301
+ });
302
+ if (definition.options?.allowRuntimeSchedules !== true) throw new ScheduleError(`Schedule target is not runtime-schedule eligible: ${target}`, {
303
+ code: "SCHEDULE_TARGET_NOT_ELIGIBLE",
304
+ details: { target },
305
+ httpStatus: 400
306
+ });
307
+ }
308
+ function assertRuntimeScheduleInputObject(input, operation) {
309
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw new ScheduleError(`Runtime Schedule ${operation} input must be an object.`, {
310
+ code: "SCHEDULE_INVALID_INPUT",
311
+ details: { input },
312
+ httpStatus: 400
313
+ });
314
+ }
315
+ async function validateCreateInput(input) {
316
+ assertRuntimeScheduleInputObject(input, "create");
317
+ await assertRuntimeTarget(input.target);
318
+ validateRuntimeScheduleCron(input.cron);
319
+ if (input.id !== void 0 && (typeof input.id !== "string" || !input.id.trim())) throw new ScheduleError("Runtime Schedule id must be a non-empty string when provided.", {
320
+ code: "SCHEDULE_INVALID_ID",
321
+ details: { id: input.id },
322
+ httpStatus: 400
323
+ });
324
+ if (input.enabled !== void 0 && typeof input.enabled !== "boolean") throw new ScheduleError("Runtime Schedule enabled must be a boolean when provided.", {
325
+ code: "SCHEDULE_INVALID_ENABLED",
326
+ details: { enabled: input.enabled },
327
+ httpStatus: 400
328
+ });
329
+ }
330
+ async function validateUpdateInput(input) {
331
+ assertRuntimeScheduleInputObject(input, "update");
332
+ if (input.target !== void 0) await assertRuntimeTarget(input.target);
333
+ if (input.cron !== void 0) validateRuntimeScheduleCron(input.cron);
334
+ if (input.enabled !== void 0 && typeof input.enabled !== "boolean") throw new ScheduleError("Runtime Schedule enabled must be a boolean when provided.", {
335
+ code: "SCHEDULE_INVALID_ENABLED",
336
+ details: { enabled: input.enabled },
337
+ httpStatus: 400
338
+ });
339
+ }
340
+ async function updateRuntimeSchedule(id, input) {
341
+ await validateUpdateInput(input);
342
+ const updated = await getRuntimeScheduleStore().update(id, {
343
+ ...input,
344
+ updatedAt: /* @__PURE__ */ new Date()
345
+ });
346
+ if (!updated) throw new ScheduleError(`Runtime Schedule not found: ${id}`, {
347
+ code: "SCHEDULE_NOT_FOUND",
348
+ details: { id },
349
+ httpStatus: 404
350
+ });
351
+ return updated;
352
+ }
353
+ const schedules = {
354
+ async create(input) {
355
+ await validateCreateInput(input);
356
+ const now = /* @__PURE__ */ new Date();
357
+ return await getRuntimeScheduleStore().create({
358
+ createdAt: now,
359
+ cron: input.cron,
360
+ enabled: input.enabled ?? true,
361
+ id: input.id ?? randomId("sched"),
362
+ target: input.target,
363
+ updatedAt: now
364
+ });
365
+ },
366
+ async delete(id) {
367
+ return await getRuntimeScheduleStore().delete(id);
368
+ },
369
+ async disable(id) {
370
+ return await updateRuntimeSchedule(id, { enabled: false });
371
+ },
372
+ async enable(id) {
373
+ return await updateRuntimeSchedule(id, { enabled: true });
374
+ },
375
+ async get(id) {
376
+ return await getRuntimeScheduleStore().get(id);
377
+ },
378
+ async getRun(id) {
379
+ return await getScheduleRunStore().getRun(id);
380
+ },
381
+ async list() {
382
+ return await getRuntimeScheduleStore().list();
383
+ },
384
+ async listAttempts(runId) {
385
+ return await getScheduleRunStore().listAttempts(runId);
386
+ },
387
+ async listRuns() {
388
+ return await getScheduleRunStore().listRuns();
389
+ },
390
+ async run(id, options = {}) {
391
+ return await executeRuntimeSchedule({
392
+ id,
393
+ scheduledAt: options.scheduledAt
394
+ });
395
+ },
396
+ async update(id, input) {
397
+ return await updateRuntimeSchedule(id, input);
398
+ }
399
+ };
400
+ //#endregion
401
+ export { executeSchedule as a, executeRuntimeSchedule as i, validateRuntimeScheduleCron as n, executeStaticSchedule as o, createScheduleRun as r, schedules as t };