@vite-hub/schedule 0.4.1 → 0.5.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 (53) hide show
  1. package/README.md +12 -7
  2. package/dist/{console-wEhr0LWn.d.ts → console-DFI1QBkP.d.ts} +2 -4
  3. package/dist/cron-BT3ef48f.js +68 -0
  4. package/dist/definition.d.ts +2 -4
  5. package/dist/definition.js +4 -6
  6. package/dist/{due-sOJvF_6Z.js → due-D-0trD1g.js} +23 -9
  7. package/dist/durability.d.ts +3 -5
  8. package/dist/durability.js +6 -7
  9. package/dist/{error-diagnostics-BBtYYl8j.js → error-diagnostics-B1AaIGWP.js} +2 -7
  10. package/dist/{error-diagnostics-CQ4BUqRe.js → error-diagnostics-kKXseq8d.js} +10 -3
  11. package/dist/index.d.ts +3 -13
  12. package/dist/index.js +5 -8
  13. package/dist/{started-name-ruCM1EtQ.js → inspect-CW0qwt9p.js} +3 -9
  14. package/dist/{kv-storage-2kZtP2CC.js → kv-storage-Dsr3TL9c.js} +1 -2
  15. package/dist/{kv-storage-Bm9aYLfZ.d.ts → kv-storage-hI2IOjb5.d.ts} +0 -2
  16. package/dist/{object-Da1zyPCR.js → object-CAK6UYR5.js} +1 -2
  17. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CqZkx1Rm.d.ts} +8 -6
  18. package/dist/{operations-DqwmJ8MN.js → operations-BTUQeba1.js} +7 -11
  19. package/dist/operations.d.ts +2 -6
  20. package/dist/operations.js +11 -16
  21. package/dist/os.d.ts +0 -9
  22. package/dist/os.js +23 -104
  23. package/dist/out-By90R-Bo.js +22706 -0
  24. package/dist/rolldown-runtime-DegdyBIC.js +25 -0
  25. package/dist/runtime/console.d.ts +2 -4
  26. package/dist/runtime/console.js +3 -4
  27. package/dist/runtime/kv.d.ts +2 -4
  28. package/dist/runtime/kv.js +2 -3
  29. package/dist/runtime/process.d.ts +1 -3
  30. package/dist/runtime/process.js +28 -52
  31. package/dist/runtime/state.d.ts +1 -1
  32. package/dist/runtime/state.js +1 -2
  33. package/dist/runtime/static.d.ts +2 -73
  34. package/dist/runtime/static.js +3 -2
  35. package/dist/runtime.d.ts +5 -7
  36. package/dist/runtime.js +5 -5
  37. package/dist/{started-B0pc3JY0.js → started-B1Se_Iwo.js} +6 -8
  38. package/dist/{started-Bk2Icknk.js → started-Bzvr4t5f.js} +26 -9
  39. package/dist/{started-errors-DEmYH-vp.js → started-errors-IG9DlT2A.js} +49 -12
  40. package/dist/started-name-w6n9uDdt.js +4 -0
  41. package/dist/{state-CPd10SXq.d.ts → state-BDEDVlyr.d.ts} +3 -6
  42. package/dist/{state-D4SZH6zk.js → state-BZLy46UJ.js} +73 -122
  43. package/dist/static-Bg7Jj92L.js +603 -0
  44. package/dist/static-DeRvJqcQ.d.ts +92 -0
  45. package/dist/{store-DeMojnXM.d.ts → store-CEv3cScg.d.ts} +4 -12
  46. package/dist/{time-zone-SBldrUgt.js → time-zone-pMp_g8Uu.js} +1 -2
  47. package/dist/{types-Cw5LjPuc.d.ts → types-DTVPVY5O.d.ts} +0 -2
  48. package/dist/vite.d.ts +6 -20
  49. package/dist/vite.js +2943 -297
  50. package/package.json +9 -9
  51. package/dist/invariant-DolT9EEx.js +0 -22
  52. package/dist/static-7JCga3Iu.js +0 -281
  53. package/dist/wait-until-Dy4Bn3ZN.js +0 -112
@@ -0,0 +1,603 @@
1
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-B1AaIGWP.js";
2
+ import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
3
+ import { n as isScheduleDue, r as latestCronMinute, t as cronWithWeekdayNames } from "./due-D-0trD1g.js";
4
+ import "./started-name-w6n9uDdt.js";
5
+ import { ViteHubError, normalizeRuntimeDiagnosticError } from "@vite-hub/runtime";
6
+ import { emitRunFailed, toRunFailedError } from "@vite-hub/runtime/internal/run-failed";
7
+ import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
8
+ // src/errors.ts
9
+ const scheduleErrorMessages = {
10
+ SCHEDULE_DEFINITION_NOT_FOUND: "Static Schedule Definition was not found.",
11
+ SCHEDULE_INVALID_CRON: "Schedule cron is invalid.",
12
+ SCHEDULE_INVALID_SCHEDULED_AT: "Schedule scheduledAt value is invalid.",
13
+ SCHEDULE_MANUAL_RUN_DISABLED: "Schedule Definition does not allow manual runs. Set manual: true to allow them.",
14
+ SCHEDULE_NOT_DUE: "Schedule is not due.",
15
+ SCHEDULE_RUN_NOT_FOUND: "Schedule Run was not found."
16
+ };
17
+ function isDateValue(value) {
18
+ if (value instanceof Date) return true;
19
+ try {
20
+ Date.prototype.getTime.call(value);
21
+ return true;
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+ function invalidScheduleValueDetails(field, value) {
27
+ let valueType;
28
+ try {
29
+ valueType = value === null ? "null" : Array.isArray(value) ? "array" : isDateValue(value) ? "date" : typeof value;
30
+ } catch {
31
+ valueType = "unknown";
32
+ }
33
+ return {
34
+ field,
35
+ valueType
36
+ };
37
+ }
38
+ function createScheduleError(code, options = {}) {
39
+ return new ViteHubError(code, scheduleErrorMessages[code], options);
40
+ }
41
+ // src/runtime/date.ts
42
+ /** The idempotency key of one Schedule occurrence. Two runs of the same Schedule for the same time share it. */
43
+ function scheduleIdempotencyKey(name, scheduledAt) {
44
+ return `schedule:${name}:${scheduledAt.toISOString()}`;
45
+ }
46
+ function isScheduleDate(value) {
47
+ try {
48
+ return !Number.isNaN(Date.prototype.getTime.call(value));
49
+ } catch {
50
+ return false;
51
+ }
52
+ }
53
+ const scheduledAtText = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/i;
54
+ function parseScheduledAtText(value) {
55
+ const match = scheduledAtText.exec(value);
56
+ if (!match) return;
57
+ const [, year, month, day, hour] = match.map(Number);
58
+ const calendarDay = /* @__PURE__ */ new Date(0);
59
+ calendarDay.setUTCFullYear(year, month - 1, day);
60
+ if (hour > 23 || calendarDay.getUTCMonth() !== month - 1 || calendarDay.getUTCDate() !== day) return;
61
+ const date = new Date(value);
62
+ return Number.isNaN(date.getTime()) ? void 0 : date;
63
+ }
64
+ function validateScheduledAt(scheduledAt) {
65
+ const value = scheduledAt ?? /* @__PURE__ */ new Date();
66
+ if (!isScheduleDate(value)) throw createScheduleError("SCHEDULE_INVALID_SCHEDULED_AT", { details: invalidScheduleValueDetails("scheduledAt", value) });
67
+ return new Date(Date.prototype.getTime.call(value));
68
+ }
69
+ /**
70
+ * Returns the time a manual run treats as its fire time. A string must be an ISO 8601 date-time with a time zone, such
71
+ * as `2026-01-31T23:59:00Z`. Anything else fails with `SCHEDULE_INVALID_SCHEDULED_AT`. Absent means now.
72
+ */
73
+ function parseScheduledAt(scheduledAt) {
74
+ if (typeof scheduledAt !== "string") return validateScheduledAt(scheduledAt);
75
+ const parsed = parseScheduledAtText(scheduledAt);
76
+ if (parsed) return parsed;
77
+ throw createScheduleError("SCHEDULE_INVALID_SCHEDULED_AT", { details: invalidScheduleValueDetails("scheduledAt", scheduledAt) });
78
+ }
79
+ // ../internal/src/runtime/request-log.ts
80
+ function isRequestLog(value) {
81
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "set") === "function" && typeof Reflect.get(value, "warn") === "function" && typeof Reflect.get(value, "error") === "function";
82
+ }
83
+ function contextLog(value) {
84
+ const context = value !== null && typeof value === "object" ? Reflect.get(value, "context") : void 0;
85
+ return context !== null && typeof context === "object" ? Reflect.get(context, "log") : void 0;
86
+ }
87
+ /**
88
+ * The evlog request logger of a request, or `undefined` when the app does not register evlog. Pass a Nitro v3 event
89
+ * (evlog sets `event.req.context.log`) or its `Request` (`request.context.log`).
90
+ */
91
+ function requestLog(input) {
92
+ const log = contextLog(input !== null && typeof input === "object" ? Reflect.get(input, "req") : void 0) ?? contextLog(input);
93
+ return isRequestLog(log) ? log : void 0;
94
+ }
95
+ /**
96
+ * The `Symbol.for()` key of the bridge on `globalThis`. Every bundled copy of this module and the Nitro plugin that
97
+ * `vitehub()` generates use the same key.
98
+ */
99
+ const evlogBridgeKey = "vitehub.evlog";
100
+ function isEvlogBridge(value) {
101
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "createLogger") === "function";
102
+ }
103
+ /** The evlog bridge of this process, or `undefined` when the app does not register evlog. */
104
+ function evlogBridge() {
105
+ const bridge = globalThis[Symbol.for(evlogBridgeKey)];
106
+ return isEvlogBridge(bridge) ? bridge : void 0;
107
+ }
108
+ function activeBridge() {
109
+ const bridge = evlogBridge();
110
+ try {
111
+ return bridge && bridge.isEnabled?.() !== false ? bridge : void 0;
112
+ } catch {
113
+ return;
114
+ }
115
+ }
116
+ /**
117
+ * A short name for the cause of a failure, safe to put in a log field: the string `code` of the error, such as
118
+ * `ENOSPC` or a ViteHub diagnostic code, else its class name. Never the message, which can hold paths or values.
119
+ */
120
+ function errorCode(error) {
121
+ if (error === null || typeof error !== "object") return void 0;
122
+ const code = Reflect.get(error, "code");
123
+ if (typeof code === "string" && code) return code;
124
+ const name = Reflect.get(error, "name");
125
+ return typeof name === "string" && name && name !== "Error" ? name : void 0;
126
+ }
127
+ /**
128
+ * Emits one evlog event of its own, outside a request's wide event. The event also reaches the app's `evlog:drain`
129
+ * hooks. Returns `false` when the app does not register evlog or turned it off, and never throws.
130
+ */
131
+ function emitLogEvent(event) {
132
+ const bridge = activeBridge();
133
+ if (!bridge) return false;
134
+ try {
135
+ const log = bridge.createLogger({
136
+ action: event.field,
137
+ message: event.message,
138
+ [event.field]: event.fields
139
+ }, event.waitUntil ? { waitUntil: event.waitUntil } : void 0);
140
+ if (event.level === "error") log.error(event.withError && event.error instanceof Error ? event.error : event.message);
141
+ else log[event.level](event.message);
142
+ const emitted = log.emit();
143
+ if (emitted && bridge.drain) {
144
+ const drained = Promise.resolve().then(() => bridge.drain?.(emitted)).catch((error) => {
145
+ console.error("[evlog] drain failed:", error);
146
+ });
147
+ event.waitUntil?.(drained);
148
+ }
149
+ return true;
150
+ } catch {
151
+ return false;
152
+ }
153
+ }
154
+ /**
155
+ * Logs a failure that the caller survives, with a fixed message and the `code` of the error. With the evlog request
156
+ * logger of `request`, it replaces `[field]` on the request's wide event and adds a warning. Pass `request` only when the
157
+ * request has not answered yet: evlog drops fields after it emits the wide event. Otherwise it emits an event of its
158
+ * own. Without evlog, or with evlog off, it calls `fallback`, which prints to the server console as before. It never
159
+ * throws.
160
+ */
161
+ function logFailure(failure, fallback) {
162
+ const code = errorCode(failure.error);
163
+ const fields = {
164
+ ...failure.fields,
165
+ ...code ? { code } : {}
166
+ };
167
+ const log = failure.request !== void 0 && activeBridge() ? requestLog(failure.request) : void 0;
168
+ if (log) try {
169
+ log.set({ [failure.field]: false });
170
+ log.warn(failure.message, { [failure.field]: fields });
171
+ return;
172
+ } catch {}
173
+ if (emitLogEvent({
174
+ ...failure,
175
+ fields,
176
+ level: failure.level ?? "warn"
177
+ })) return;
178
+ try {
179
+ fallback();
180
+ } catch {}
181
+ }
182
+ // src/runtime/log.ts
183
+ const loggedKey = Symbol.for("vitehub.schedule.logged-errors");
184
+ const runtimeGlobal = globalThis;
185
+ const logged = runtimeGlobal[loggedKey] ||= /* @__PURE__ */ new WeakSet();
186
+ /**
187
+ * Emits one evlog event for a Schedule run that ran its handler: `{ action: "schedule", schedule }`, at `info` for a
188
+ * success and at `error` with the handler's error for a failure. The handler is the app's own code, so its error goes
189
+ * on the event as a route's error does. Returns whether evlog has the event. Without evlog, it does nothing: the run
190
+ * history keeps the run.
191
+ */
192
+ function logScheduleRun(run, startedAt, outcome, options = {}) {
193
+ const fields = {
194
+ ...run,
195
+ scheduledAt: run.scheduledAt.toISOString(),
196
+ ms: Math.round(performance.now() - startedAt),
197
+ outcome
198
+ };
199
+ const waitUntil = options.waitUntil ? { waitUntil: options.waitUntil } : {};
200
+ return outcome === "failure" ? emitLogEvent({
201
+ field: "schedule",
202
+ fields,
203
+ level: "error",
204
+ message: "Schedule run failed",
205
+ error: options.error,
206
+ withError: true,
207
+ ...waitUntil
208
+ }) : emitLogEvent({
209
+ field: "schedule",
210
+ fields,
211
+ level: "info",
212
+ message: "Schedule run succeeded",
213
+ ...waitUntil
214
+ });
215
+ }
216
+ /** Notes that a log event has this error. An error that is not an object cannot be noted: wrap it first. */
217
+ function rememberLoggedScheduleError(error) {
218
+ logged.add(error);
219
+ }
220
+ /** Whether a log event already has this error. */
221
+ function isLoggedScheduleError(error) {
222
+ return typeof error === "object" && error !== null && logged.has(error);
223
+ }
224
+ // src/runtime/wait-until.ts
225
+ function createLocalWaitUntil() {
226
+ const pending = /* @__PURE__ */ new Set();
227
+ let error;
228
+ let failed = false;
229
+ return {
230
+ async flush() {
231
+ while (pending.size > 0) await Promise.allSettled(pending);
232
+ if (failed) throw error;
233
+ },
234
+ waitUntil(value) {
235
+ const promise = Promise.resolve(value);
236
+ pending.add(promise);
237
+ promise.then(() => pending.delete(promise), (reason) => {
238
+ pending.delete(promise);
239
+ if (!failed) error = reason;
240
+ failed = true;
241
+ });
242
+ }
243
+ };
244
+ }
245
+ /** Complete local deferred work while preserving a handler's failure over a deferred failure. */
246
+ async function runWithScheduleWaitUntil(run, hostWaitUntil) {
247
+ if (hostWaitUntil) return await run(hostWaitUntil);
248
+ const local = createLocalWaitUntil();
249
+ let result;
250
+ try {
251
+ result = await run(local.waitUntil);
252
+ } catch (error) {
253
+ await local.flush().catch(logDeferredFailure);
254
+ throw error;
255
+ }
256
+ await local.flush();
257
+ return result;
258
+ }
259
+ function logDeferredFailure(error) {
260
+ logFailure({
261
+ field: "schedule",
262
+ fields: { op: "wait-until" },
263
+ level: "error",
264
+ message: "Schedule deferred work failed after the handler failed",
265
+ error
266
+ }, () => console.error("[vitehub:schedule] Deferred work failed after the handler failed.", error));
267
+ }
268
+ // ../internal/src/secret.ts
269
+ const secretEncoder = new TextEncoder();
270
+ /**
271
+ * Compares a request value with an expected secret in constant time for the length of `expected`. Returns `false`
272
+ * when either value is missing or empty. It uses no Node API, so it also runs in Worker runtimes.
273
+ */
274
+ function isViteHubSecretEqual(actual, expected) {
275
+ if (!actual || !expected) return false;
276
+ const left = secretEncoder.encode(actual);
277
+ const right = secretEncoder.encode(expected);
278
+ let difference = left.length ^ right.length;
279
+ for (let index = 0; index < right.length; index += 1) difference |= (left[index] ?? 0) ^ right[index];
280
+ return difference === 0;
281
+ }
282
+ /**
283
+ * Compares the token of a `Bearer` `Authorization` header with an expected secret in constant time. The scheme is
284
+ * case-insensitive. Returns `false` for another scheme or a missing value.
285
+ */
286
+ function isViteHubBearerSecretEqual(authorization, expected) {
287
+ return isViteHubSecretEqual(/^Bearer\s+(.+)$/i.exec(authorization ?? "")?.[1], expected);
288
+ }
289
+ Object.freeze({ prefix: "sha256=" });
290
+ // src/runtime/static.ts
291
+ const intrinsicErrorIsError = Error.isError;
292
+ const intrinsicNativeErrorIsError = (() => {
293
+ try {
294
+ const process = globalThis.process;
295
+ const getBuiltinModule = process?.getBuiltinModule;
296
+ if (typeof getBuiltinModule !== "function") return void 0;
297
+ const util = getBuiltinModule.call(process, "util");
298
+ return typeof util?.types?.isNativeError === "function" ? util.types.isNativeError : void 0;
299
+ } catch {
300
+ return;
301
+ }
302
+ })();
303
+ function missingScheduleDefinitionError(name) {
304
+ return scheduleErrorDiagnostics.SCHEDULE_R0034({ message: `Missing schedule definition: ${name}` });
305
+ }
306
+ /**
307
+ * Checks the `Authorization` header of a Vercel Cron request against `CRON_SECRET` in constant time.
308
+ */
309
+ function isScheduleCronAuthorized(authorization, cronSecret) {
310
+ return isViteHubBearerSecretEqual(authorization, cronSecret);
311
+ }
312
+ function normalizeCron(cron) {
313
+ return cron.trim().split(/\s+/).join(" ");
314
+ }
315
+ /**
316
+ * Logs a failure that the Process Runtime reports: as an evlog event `{ schedule: { op: "runtime" } }`, else on the
317
+ * console. A failed run that has its run event is not logged again.
318
+ */
319
+ function logScheduleRuntimeError(error, runtimeError) {
320
+ if (isLoggedScheduleError(error)) return;
321
+ logFailure({
322
+ field: "schedule",
323
+ fields: { op: "runtime" },
324
+ level: "error",
325
+ message: "Schedule runtime failed",
326
+ error: runtimeError
327
+ }, () => console.error("[vitehub:schedule]", runtimeError));
328
+ }
329
+ /**
330
+ * Notes that a log event has `error`, and returns it to throw on. A thrown value that is not an object cannot be
331
+ * noted, so it becomes the Error that `normalizeScheduleRuntimeError()` makes of it anyway.
332
+ */
333
+ function markLoggedScheduleError(error) {
334
+ const marked = typeof error === "object" && error !== null ? error : normalizeScheduleRuntimeError(error);
335
+ rememberLoggedScheduleError(marked);
336
+ return marked;
337
+ }
338
+ function normalizeScheduleRuntimeError(error) {
339
+ if (isScheduleRuntimeError(error)) return error;
340
+ let message;
341
+ try {
342
+ message = String(error);
343
+ } catch {
344
+ message = "[unprintable thrown value]";
345
+ }
346
+ try {
347
+ return scheduleErrorDiagnostics.SCHEDULE_R0035({
348
+ cause: error,
349
+ message
350
+ });
351
+ } catch {
352
+ const fallback = new Error(message);
353
+ Object.defineProperty(fallback, "code", {
354
+ value: "SCHEDULE_R0035",
355
+ enumerable: true
356
+ });
357
+ Object.defineProperty(fallback, "cause", { value: error });
358
+ return fallback;
359
+ }
360
+ }
361
+ function isScheduleRuntimeError(error) {
362
+ try {
363
+ if (error instanceof Error) return true;
364
+ } catch {
365
+ return false;
366
+ }
367
+ if (error === null || typeof error !== "object") return false;
368
+ if (typeof intrinsicNativeErrorIsError === "function") return intrinsicNativeErrorIsError(error);
369
+ try {
370
+ return typeof intrinsicErrorIsError === "function" && intrinsicErrorIsError(error) === true;
371
+ } catch {
372
+ return false;
373
+ }
374
+ }
375
+ /**
376
+ * Estimates a wake minute from callback time when the host supplies no scheduled timestamp. This is the newest UTC
377
+ * cron match within one day, or the current minute when none matches. It cannot identify a delayed or retried wake
378
+ * after another cron match; callers must not treat it as the provider's occurrence identity.
379
+ */
380
+ function scheduledWakeTime(cron, now = /* @__PURE__ */ new Date()) {
381
+ return latestCronMinute(normalizeCron(cron), now);
382
+ }
383
+ /**
384
+ * Returns `true` when a host wake at `scheduledAt` is an occurrence of the Definition's cron in its `timeZone`. The host
385
+ * runs a wider UTC cron for a time-zoned Schedule, so the runtime skips the wakes that are not local occurrences.
386
+ */
387
+ function isTimeZoneWakeDue(definition, name, scheduledAt) {
388
+ const minute = /* @__PURE__ */ new Date(Math.floor(scheduledAt.getTime() / 6e4) * 6e4);
389
+ return isScheduleDue({
390
+ cron: definition.cron,
391
+ id: name,
392
+ ...definition.timeZone ? { timeZone: definition.timeZone } : {}
393
+ }, minute);
394
+ }
395
+ function createStaticScheduleRun(options) {
396
+ const scheduledAt = validateScheduledAt(options.scheduledAt);
397
+ return {
398
+ cron: options.cron,
399
+ id: `run_${options.name}_${scheduledAt.toISOString()}`,
400
+ idempotencyKey: scheduleIdempotencyKey(options.name, scheduledAt),
401
+ scheduleId: options.name,
402
+ scheduledAt,
403
+ waitUntil: options.waitUntil
404
+ };
405
+ }
406
+ async function executeStaticSchedule(options) {
407
+ const scheduledAt = validateScheduledAt(options.scheduledAt);
408
+ const execute = () => runInRunScopes(() => runWithScheduleWaitUntil(async (waitUntil) => {
409
+ const run = createStaticScheduleRun({
410
+ ...options,
411
+ scheduledAt,
412
+ waitUntil
413
+ });
414
+ try {
415
+ return await options.definition.handler(run);
416
+ } catch (error) {
417
+ await emitRunFailed({
418
+ event: "schedule.failed",
419
+ schedule: run.scheduleId,
420
+ runId: run.id,
421
+ error: toRunFailedError(error),
422
+ failedAt: (/* @__PURE__ */ new Date()).toISOString()
423
+ });
424
+ throw error;
425
+ }
426
+ }, options.waitUntil));
427
+ if (options.name === "vitehub/started-schedules") return await execute();
428
+ const run = {
429
+ name: options.name,
430
+ source: "static",
431
+ scheduledAt
432
+ };
433
+ const startedAt = performance.now();
434
+ return await runWithScheduleWaitUntil(async (waitUntil) => {
435
+ try {
436
+ const value = await execute();
437
+ logScheduleRun(run, startedAt, "success", { waitUntil });
438
+ return value;
439
+ } catch (error) {
440
+ if (logScheduleRun(run, startedAt, "failure", {
441
+ error: normalizeScheduleRuntimeError(error),
442
+ waitUntil
443
+ })) options.onRunLogged?.();
444
+ throw error;
445
+ }
446
+ }, options.waitUntil);
447
+ }
448
+ function isHostCronTrigger(hostCron, trigger) {
449
+ try {
450
+ return cronWithWeekdayNames(hostCron) === trigger;
451
+ } catch {
452
+ return false;
453
+ }
454
+ }
455
+ async function executeMatchingStaticSchedules(options) {
456
+ return await matchStaticSchedules(options);
457
+ }
458
+ async function matchStaticSchedules(options, matchesTrigger) {
459
+ if (typeof options.cron !== "string" || !options.cron.trim()) throw createScheduleError("SCHEDULE_INVALID_CRON", { details: invalidScheduleValueDetails("cron", options.cron) });
460
+ const cron = normalizeCron(options.cron);
461
+ const scheduledAt = validateScheduledAt(options.scheduledAt);
462
+ const runs = [];
463
+ for (const [name, load] of Object.entries(options.registry)) {
464
+ const definition = unwrapScheduleDefinition(await load());
465
+ if (!definition) continue;
466
+ const override = options.cronOverrides && Object.hasOwn(options.cronOverrides, name) ? options.cronOverrides[name] : void 0;
467
+ const timeZoneCron = override === void 0 && options.timeZoneCrons && Object.hasOwn(options.timeZoneCrons, name) ? options.timeZoneCrons[name] : void 0;
468
+ const hostCron = normalizeCron(override ?? timeZoneCron ?? definition.cron);
469
+ if (!(matchesTrigger ? matchesTrigger(name, hostCron, cron, override !== void 0) : hostCron === cron)) continue;
470
+ if (timeZoneCron !== void 0 && !isTimeZoneWakeDue(definition, name, scheduledAt)) continue;
471
+ let logged = false;
472
+ const run = executeStaticSchedule({
473
+ cron: matchesTrigger ? hostCron : options.cron,
474
+ definition,
475
+ name,
476
+ onRunLogged: () => {
477
+ logged = true;
478
+ },
479
+ scheduledAt,
480
+ waitUntil: options.waitUntil
481
+ });
482
+ runs.push({
483
+ logged: () => logged,
484
+ name,
485
+ run
486
+ });
487
+ }
488
+ const results = await Promise.allSettled(runs.map(({ run }) => run));
489
+ const failures = [];
490
+ results.forEach((result, index) => {
491
+ if (result.status === "fulfilled") return;
492
+ failures.push(result.reason);
493
+ if (!runs[index].logged()) console.error(`[vitehub:schedule] Schedule "${runs[index].name}" failed (cron "${options.cron}").`, normalizeRuntimeDiagnosticError(result.reason, { includeStack: true }));
494
+ });
495
+ if (failures.length === 1) throw failures[0];
496
+ if (failures.length) throw new AggregateError(failures, `[vitehub:schedule] ${failures.length} schedules failed for cron "${options.cron}".`);
497
+ return results.map((result) => result.status === "fulfilled" ? result.value : void 0);
498
+ }
499
+ async function executeCloudflareStaticSchedules(event, options) {
500
+ const scheduled = readCloudflareScheduledEvent(event);
501
+ return await runWithCloudflareServerEnv(event, async (waitUntil) => {
502
+ return await matchStaticSchedules({
503
+ cron: scheduled.cron,
504
+ cronOverrides: options.cronOverrides,
505
+ registry: options.registry,
506
+ scheduledAt: scheduled.scheduledAt,
507
+ timeZoneCrons: options.timeZoneCrons,
508
+ waitUntil
509
+ }, (name, hostCron, trigger, hasOverride) => {
510
+ const registered = options.triggerCrons && Object.hasOwn(options.triggerCrons, name) ? options.triggerCrons[name] : void 0;
511
+ if (registered !== void 0) return normalizeCron(registered) === trigger;
512
+ return hasOverride ? hostCron === trigger : isHostCronTrigger(hostCron, trigger);
513
+ });
514
+ }, options.waitUntil ?? readCloudflareWaitUntil(event));
515
+ }
516
+ function readCloudflareScheduledEvent(event) {
517
+ const cron = event.controller?.cron ?? event.cron;
518
+ if (typeof cron !== "string" || !cron.trim()) throw scheduleErrorDiagnostics.SCHEDULE_R0027({ message: "[vitehub:schedule] Cloudflare scheduled event is missing a cron string." });
519
+ const scheduledTime = event.controller?.scheduledTime ?? event.scheduledTime;
520
+ const scheduledAt = isScheduleDate(scheduledTime) ? new Date(Date.prototype.getTime.call(scheduledTime)) : scheduledTime === void 0 ? /* @__PURE__ */ new Date() : new Date(scheduledTime);
521
+ if (Number.isNaN(scheduledAt.getTime())) throw scheduleErrorDiagnostics.SCHEDULE_R0028({ message: "[vitehub:schedule] Cloudflare scheduled event has an invalid scheduledTime." });
522
+ return {
523
+ cron,
524
+ scheduledAt
525
+ };
526
+ }
527
+ async function runWithCloudflareServerEnv(event, callback, hostWaitUntil) {
528
+ const globals = globalThis;
529
+ const hadGlobalEnv = Object.prototype.hasOwnProperty.call(globals, "__env__");
530
+ const previousGlobalEnv = globals.__env__;
531
+ const env = readCloudflareEventEnv(event);
532
+ if (env) globals.__env__ = env;
533
+ const pending = /* @__PURE__ */ new Set();
534
+ const waitUntil = hostWaitUntil ? (value) => {
535
+ const promise = Promise.resolve(value);
536
+ pending.add(promise);
537
+ promise.then(() => pending.delete(promise), () => pending.delete(promise));
538
+ hostWaitUntil(promise);
539
+ } : void 0;
540
+ try {
541
+ return await callback(waitUntil);
542
+ } finally {
543
+ if (pending.size === 0) restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv);
544
+ else hostWaitUntil(flushPendingWork(pending).finally(() => {
545
+ restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv);
546
+ }));
547
+ }
548
+ }
549
+ async function flushPendingWork(pending) {
550
+ while (pending.size > 0) await Promise.allSettled(pending);
551
+ }
552
+ function restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv) {
553
+ if (hadGlobalEnv) globals.__env__ = previousGlobalEnv;
554
+ else delete globals.__env__;
555
+ }
556
+ function isCallable(value) {
557
+ return typeof value === "function" || typeof value === "undefined" && value !== void 0;
558
+ }
559
+ function readCloudflareWaitUntil(event) {
560
+ const context = isRecordOrFunction(event.context) ? event.context : void 0;
561
+ const cloudflareContext = isRecordOrFunction(context?.cloudflare) ? context.cloudflare : void 0;
562
+ const platformContext = isRecordOrFunction(context?._platform) ? context._platform : void 0;
563
+ const platformCloudflareContext = isRecordOrFunction(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
564
+ const request = isRecordOrFunction(event.req) ? event.req : void 0;
565
+ const runtime = isRecordOrFunction(request?.runtime) ? request.runtime : void 0;
566
+ const runtimeCloudflare = isRecordOrFunction(runtime?.cloudflare) ? runtime.cloudflare : void 0;
567
+ const owners = [
568
+ event,
569
+ context,
570
+ cloudflareContext,
571
+ isRecordOrFunction(cloudflareContext?.context) ? cloudflareContext.context : void 0,
572
+ platformCloudflareContext,
573
+ isRecordOrFunction(platformCloudflareContext?.context) ? platformCloudflareContext.context : void 0,
574
+ request,
575
+ runtimeCloudflare,
576
+ isRecordOrFunction(runtimeCloudflare?.context) ? runtimeCloudflare.context : void 0
577
+ ];
578
+ for (const owner of owners) {
579
+ const waitUntil = owner?.waitUntil;
580
+ if (isCallable(waitUntil)) return (promise) => Reflect.apply(waitUntil, owner, [promise]);
581
+ }
582
+ }
583
+ function readCloudflareEventEnv(event) {
584
+ if (isRecordOrFunction(event.env)) return event.env;
585
+ const context = isRecordOrFunction(event.context) ? event.context : void 0;
586
+ const cloudflareContext = isRecordOrFunction(context?.cloudflare) ? context.cloudflare : void 0;
587
+ if (isRecordOrFunction(cloudflareContext?.env)) return cloudflareContext.env;
588
+ const platformContext = isRecordOrFunction(context?._platform) ? context._platform : void 0;
589
+ const platformCloudflareContext = isRecordOrFunction(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
590
+ if (isRecordOrFunction(platformCloudflareContext?.env)) return platformCloudflareContext.env;
591
+ const request = isRecordOrFunction(event.req) ? event.req : void 0;
592
+ const runtime = isRecordOrFunction(request?.runtime) ? request.runtime : void 0;
593
+ const runtimeCloudflare = isRecordOrFunction(runtime?.cloudflare) ? runtime.cloudflare : void 0;
594
+ return isRecordOrFunction(runtimeCloudflare?.env) ? runtimeCloudflare.env : void 0;
595
+ }
596
+ function isStaticScheduleDefinition(value) {
597
+ return isRecordOrFunction(value) && Object.hasOwn(value, "cron") && typeof value.cron === "string" && Object.hasOwn(value, "handler") && typeof value.handler === "function";
598
+ }
599
+ function unwrapScheduleDefinition(loaded) {
600
+ const candidate = isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default") ? loaded.default : loaded;
601
+ return isStaticScheduleDefinition(candidate) ? candidate : void 0;
602
+ }
603
+ export { createScheduleError as S, errorCode as _, isScheduleCronAuthorized as a, scheduleIdempotencyKey as b, markLoggedScheduleError as c, normalizeScheduleRuntimeError as d, scheduledWakeTime as f, emitLogEvent as g, logScheduleRun as h, executeStaticSchedule as i, missingScheduleDefinitionError as l, runWithScheduleWaitUntil as m, executeCloudflareStaticSchedules as n, isTimeZoneWakeDue as o, unwrapScheduleDefinition as p, executeMatchingStaticSchedules as r, logScheduleRuntimeError as s, createStaticScheduleRun as t, normalizeCron as u, logFailure as v, validateScheduledAt as x, parseScheduledAt as y };
@@ -0,0 +1,92 @@
1
+ import { a as ScheduleDefinitionRegistry, n as ScheduleDefinition, u as ScheduleRunContext } from "./types-DTVPVY5O.js";
2
+ /**
3
+ * Returns `cron` with its weekday field written as names, such as `0 4 * * MON,FRI`. Cloudflare and Deno number
4
+ * weekdays 1-7 from Sunday, so standard 0-6 numbers fire one day early or fail to deploy. Names have one meaning on
5
+ * every host.
6
+ */
7
+ declare function cronWithWeekdayNames(cron: string): string;
8
+ interface ExecuteStaticScheduleOptions {
9
+ cron: string;
10
+ definition: ScheduleDefinition;
11
+ name: string;
12
+ scheduledAt?: Date;
13
+ waitUntil?: (promise: PromiseLike<unknown>) => void;
14
+ /** Called when the run's evlog event has the failure, so the caller does not log it again. */
15
+ onRunLogged?: () => void;
16
+ }
17
+ interface ExecuteMatchingStaticSchedulesOptions {
18
+ cron: string;
19
+ /** Cron per Schedule name that the host registered in place of the Definition's cron. */
20
+ cronOverrides?: Readonly<Record<string, string>>;
21
+ registry: ScheduleDefinitionRegistry;
22
+ scheduledAt?: Date;
23
+ /**
24
+ * UTC cron that the host registered for each Schedule with a `timeZone`. A wake runs such a Schedule only when its
25
+ * own cron is due in its time zone at that minute. `cronOverrides` wins over this map.
26
+ */
27
+ timeZoneCrons?: Readonly<Record<string, string>>;
28
+ waitUntil?: (promise: PromiseLike<unknown>) => void;
29
+ }
30
+ interface ExecuteCloudflareStaticSchedulesOptions {
31
+ /** Cron per Schedule name that the host registered in place of the Definition's cron. */
32
+ cronOverrides?: Readonly<Record<string, string>>;
33
+ registry: ScheduleDefinitionRegistry;
34
+ /** UTC cron that the host registered for each Schedule with a `timeZone`. */
35
+ timeZoneCrons?: Readonly<Record<string, string>>;
36
+ /** Generated Cloudflare trigger per Schedule name, separate from the standard cron passed to the handler. */
37
+ triggerCrons?: Readonly<Record<string, string>>;
38
+ waitUntil?: (promise: PromiseLike<unknown>) => void;
39
+ }
40
+ interface CloudflareScheduledEventLike {
41
+ [key: string]: unknown;
42
+ controller?: {
43
+ cron?: string;
44
+ scheduledTime?: number | string | Date;
45
+ };
46
+ cron?: string;
47
+ scheduledTime?: number | string | Date;
48
+ }
49
+ interface StaticScheduleRun extends ScheduleRunContext {
50
+ cron: string;
51
+ scheduleId: string;
52
+ }
53
+ declare function missingScheduleDefinitionError(name: string): Error;
54
+ /**
55
+ * Checks the `Authorization` header of a Vercel Cron request against `CRON_SECRET` in constant time.
56
+ */
57
+ declare function isScheduleCronAuthorized(authorization: string | null | undefined, cronSecret: string): boolean;
58
+ declare function normalizeCron(cron: string): string;
59
+ /**
60
+ * Logs a failure that the Process Runtime reports: as an evlog event `{ schedule: { op: "runtime" } }`, else on the
61
+ * console. A failed run that has its run event is not logged again.
62
+ */
63
+ declare function logScheduleRuntimeError(error: unknown, runtimeError: Error): void;
64
+ /**
65
+ * Notes that a log event has `error`, and returns it to throw on. A thrown value that is not an object cannot be
66
+ * noted, so it becomes the Error that `normalizeScheduleRuntimeError()` makes of it anyway.
67
+ */
68
+ declare function markLoggedScheduleError(error: unknown): unknown;
69
+ declare function normalizeScheduleRuntimeError(error: unknown): Error;
70
+ /**
71
+ * Estimates a wake minute from callback time when the host supplies no scheduled timestamp. This is the newest UTC
72
+ * cron match within one day, or the current minute when none matches. It cannot identify a delayed or retried wake
73
+ * after another cron match; callers must not treat it as the provider's occurrence identity.
74
+ */
75
+ declare function scheduledWakeTime(cron: string, now?: Date): Date;
76
+ /**
77
+ * Returns `true` when a host wake at `scheduledAt` is an occurrence of the Definition's cron in its `timeZone`. The host
78
+ * runs a wider UTC cron for a time-zoned Schedule, so the runtime skips the wakes that are not local occurrences.
79
+ */
80
+ declare function isTimeZoneWakeDue(definition: ScheduleDefinition & {
81
+ cron: string;
82
+ }, name: string, scheduledAt: Date): boolean;
83
+ declare function createStaticScheduleRun(options: Omit<ExecuteStaticScheduleOptions, "definition" | "waitUntil"> & {
84
+ waitUntil: NonNullable<ExecuteStaticScheduleOptions["waitUntil"]>;
85
+ }): StaticScheduleRun;
86
+ declare function executeStaticSchedule(options: ExecuteStaticScheduleOptions): Promise<unknown>;
87
+ declare function executeMatchingStaticSchedules(options: ExecuteMatchingStaticSchedulesOptions): Promise<unknown[]>;
88
+ declare function executeCloudflareStaticSchedules(event: CloudflareScheduledEventLike, options: ExecuteCloudflareStaticSchedulesOptions): Promise<unknown[]>;
89
+ declare function unwrapScheduleDefinition(loaded: unknown): (ScheduleDefinition & {
90
+ cron: string;
91
+ }) | undefined;
92
+ export { unwrapScheduleDefinition as _, createStaticScheduleRun as a, executeStaticSchedule as c, logScheduleRuntimeError as d, markLoggedScheduleError as f, scheduledWakeTime as g, normalizeScheduleRuntimeError as h, StaticScheduleRun as i, isScheduleCronAuthorized as l, normalizeCron as m, ExecuteMatchingStaticSchedulesOptions as n, executeCloudflareStaticSchedules as o, missingScheduleDefinitionError as p, ExecuteStaticScheduleOptions as r, executeMatchingStaticSchedules as s, ExecuteCloudflareStaticSchedulesOptions as t, isTimeZoneWakeDue as u, cronWithWeekdayNames as v };