@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/schedule",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "Schedule primitives and definition discovery for ViteHub.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -75,25 +75,25 @@
75
75
  },
76
76
  "dependencies": {
77
77
  "@valibot/to-json-schema": "^1.8.0",
78
- "@vite-hub/runtime": "0.4.1",
79
- "cron-schedule": "^6.0.0",
78
+ "@vite-hub/runtime": "0.5.1",
79
+ "cron-schedule": "^8.0.1",
80
80
  "nostics": "1.4.0",
81
81
  "valibot": "^1.5.0"
82
82
  },
83
83
  "devDependencies": {
84
- "@types/node": "^24.19.1",
84
+ "@types/node": "^24.19.2",
85
85
  "@vite-hub/internal": "0.0.1",
86
- "@vite-hub/kv": "0.4.1",
86
+ "@vite-hub/kv": "0.5.1",
87
87
  "esbuild": "^0.28.2",
88
88
  "postgres": "^3.4.9",
89
89
  "publint": "^0.3.25",
90
90
  "typescript": "^6.0.3",
91
- "vite": "^8.2.2",
92
- "vite-plus": "^0.3.3",
93
- "vitest": "^4.1.11"
91
+ "vite": "^8.3.8",
92
+ "vite-plus": "^1.7.0",
93
+ "vitest": "5.1.0"
94
94
  },
95
95
  "peerDependencies": {
96
- "@vite-hub/kv": "0.4.1",
96
+ "@vite-hub/kv": "0.5.1",
97
97
  "vite": ">=8.0.0"
98
98
  },
99
99
  "peerDependenciesMeta": {
@@ -1,22 +0,0 @@
1
- import { defineDiagnostics } from "nostics";
2
- //#region ../internal/src/invariant.ts
3
- const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
4
- docsBase: "https://vitehub.dev/docs/development/diagnostics",
5
- codes: { INTERNAL_INVARIANT_FAILED: {
6
- why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
7
- fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
8
- } }
9
- });
10
- /**
11
- * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
12
- * Use a code from the package catalog when a developer can cause the error or fix it.
13
- */
14
- function invariantError(what) {
15
- return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
16
- }
17
- /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
18
- function invariant(condition, what) {
19
- if (!condition) throw invariantError(what);
20
- }
21
- //#endregion
22
- export { invariantError as n, invariant as t };
@@ -1,281 +0,0 @@
1
- import { n as isRecordOrFunction } from "./object-Da1zyPCR.js";
2
- import { t as scheduleErrorDiagnostics } from "./error-diagnostics-BBtYYl8j.js";
3
- import { a as validateScheduledAt, i as scheduleIdempotencyKey, n as isScheduleDate, o as createScheduleError, s as invalidScheduleValueDetails, t as runWithScheduleWaitUntil } from "./wait-until-Dy4Bn3ZN.js";
4
- import { n as latestCronMinute, t as isScheduleDue } from "./due-sOJvF_6Z.js";
5
- import { 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
- //#region ../internal/src/secret.ts
9
- const secretEncoder = new TextEncoder();
10
- /**
11
- * Compares a request value with an expected secret in constant time for the length of `expected`. Returns `false`
12
- * when either value is missing or empty. It uses no Node API, so it also runs in Worker runtimes.
13
- */
14
- function isViteHubSecretEqual(actual, expected) {
15
- if (!actual || !expected) return false;
16
- const left = secretEncoder.encode(actual);
17
- const right = secretEncoder.encode(expected);
18
- let difference = left.length ^ right.length;
19
- for (let index = 0; index < right.length; index += 1) difference |= (left[index] ?? 0) ^ right[index];
20
- return difference === 0;
21
- }
22
- /**
23
- * Compares the token of a `Bearer` `Authorization` header with an expected secret in constant time. The scheme is
24
- * case-insensitive. Returns `false` for another scheme or a missing value.
25
- */
26
- function isViteHubBearerSecretEqual(authorization, expected) {
27
- return isViteHubSecretEqual(/^Bearer\s+(.+)$/i.exec(authorization ?? "")?.[1], expected);
28
- }
29
- Object.freeze({ prefix: "sha256=" });
30
- //#endregion
31
- //#region src/runtime/static.ts
32
- const intrinsicErrorIsError = Error.isError;
33
- const intrinsicNativeErrorIsError = (() => {
34
- try {
35
- const process = globalThis.process;
36
- const getBuiltinModule = process?.getBuiltinModule;
37
- if (typeof getBuiltinModule !== "function") return void 0;
38
- const util = getBuiltinModule.call(process, "util");
39
- return typeof util?.types?.isNativeError === "function" ? util.types.isNativeError : void 0;
40
- } catch {
41
- return;
42
- }
43
- })();
44
- function missingScheduleDefinitionError(name) {
45
- return scheduleErrorDiagnostics.SCHEDULE_R0034({ message: `Missing schedule definition: ${name}` });
46
- }
47
- /**
48
- * Checks the `Authorization` header of a Vercel Cron request against `CRON_SECRET` in constant time.
49
- */
50
- function isScheduleCronAuthorized(authorization, cronSecret) {
51
- return isViteHubBearerSecretEqual(authorization, cronSecret);
52
- }
53
- function normalizeCron(cron) {
54
- return cron.trim().split(/\s+/).join(" ");
55
- }
56
- function normalizeScheduleRuntimeError(error) {
57
- if (isScheduleRuntimeError(error)) return error;
58
- let message;
59
- try {
60
- message = String(error);
61
- } catch {
62
- message = "[unprintable thrown value]";
63
- }
64
- try {
65
- return scheduleErrorDiagnostics.SCHEDULE_R0035({
66
- cause: error,
67
- message
68
- });
69
- } catch {
70
- const fallback = new Error(message);
71
- Object.defineProperty(fallback, "code", {
72
- value: "SCHEDULE_R0035",
73
- enumerable: true
74
- });
75
- Object.defineProperty(fallback, "cause", { value: error });
76
- return fallback;
77
- }
78
- }
79
- function isScheduleRuntimeError(error) {
80
- try {
81
- if (error instanceof Error) return true;
82
- } catch {
83
- return false;
84
- }
85
- if (error === null || typeof error !== "object") return false;
86
- if (typeof intrinsicNativeErrorIsError === "function") try {
87
- return intrinsicNativeErrorIsError(error);
88
- } catch {}
89
- try {
90
- return typeof intrinsicErrorIsError === "function" && intrinsicErrorIsError(error) === true;
91
- } catch {
92
- return false;
93
- }
94
- }
95
- /**
96
- * Estimates a wake minute from callback time when the host supplies no scheduled timestamp. This is the newest UTC
97
- * cron match within one day, or the current minute when none matches. It cannot identify a delayed or retried wake
98
- * after another cron match; callers must not treat it as the provider's occurrence identity.
99
- */
100
- function scheduledWakeTime(cron, now = /* @__PURE__ */ new Date()) {
101
- return latestCronMinute(normalizeCron(cron), now);
102
- }
103
- /**
104
- * Returns `true` when a host wake at `scheduledAt` is an occurrence of the Definition's cron in its `timeZone`. The host
105
- * runs a wider UTC cron for a time-zoned Schedule, so the runtime skips the wakes that are not local occurrences.
106
- */
107
- function isTimeZoneWakeDue(definition, name, scheduledAt) {
108
- const minute = /* @__PURE__ */ new Date(Math.floor(scheduledAt.getTime() / 6e4) * 6e4);
109
- return isScheduleDue({
110
- cron: definition.cron,
111
- id: name,
112
- ...definition.timeZone ? { timeZone: definition.timeZone } : {}
113
- }, minute);
114
- }
115
- function createStaticScheduleRun(options) {
116
- const scheduledAt = validateScheduledAt(options.scheduledAt);
117
- return {
118
- cron: options.cron,
119
- id: `run_${options.name}_${scheduledAt.toISOString()}`,
120
- idempotencyKey: scheduleIdempotencyKey(options.name, scheduledAt),
121
- scheduleId: options.name,
122
- scheduledAt,
123
- waitUntil: options.waitUntil
124
- };
125
- }
126
- async function executeStaticSchedule(options) {
127
- return await runInRunScopes(() => runWithScheduleWaitUntil(async (waitUntil) => {
128
- const run = createStaticScheduleRun({
129
- ...options,
130
- waitUntil
131
- });
132
- try {
133
- return await options.definition.handler(run);
134
- } catch (error) {
135
- await emitRunFailed({
136
- event: "schedule.failed",
137
- schedule: run.scheduleId,
138
- runId: run.id,
139
- error: toRunFailedError(error),
140
- failedAt: (/* @__PURE__ */ new Date()).toISOString()
141
- });
142
- throw error;
143
- }
144
- }, options.waitUntil));
145
- }
146
- async function executeMatchingStaticSchedules(options) {
147
- if (typeof options.cron !== "string" || !options.cron.trim()) throw createScheduleError("SCHEDULE_INVALID_CRON", { details: invalidScheduleValueDetails("cron", options.cron) });
148
- const cron = normalizeCron(options.cron);
149
- const scheduledAt = validateScheduledAt(options.scheduledAt);
150
- const runs = [];
151
- for (const [name, load] of Object.entries(options.registry)) {
152
- const definition = unwrapScheduleDefinition(await load());
153
- if (!definition) continue;
154
- const override = options.cronOverrides && Object.hasOwn(options.cronOverrides, name) ? options.cronOverrides[name] : void 0;
155
- const timeZoneCron = override === void 0 && options.timeZoneCrons && Object.hasOwn(options.timeZoneCrons, name) ? options.timeZoneCrons[name] : void 0;
156
- if (normalizeCron(override ?? timeZoneCron ?? definition.cron) !== cron) continue;
157
- if (timeZoneCron !== void 0 && !isTimeZoneWakeDue(definition, name, scheduledAt)) continue;
158
- runs.push({
159
- name,
160
- run: executeStaticSchedule({
161
- cron: options.cron,
162
- definition,
163
- name,
164
- scheduledAt,
165
- waitUntil: options.waitUntil
166
- })
167
- });
168
- }
169
- const results = await Promise.allSettled(runs.map(({ run }) => run));
170
- const failures = [];
171
- results.forEach((result, index) => {
172
- if (result.status === "fulfilled") return;
173
- failures.push(result.reason);
174
- console.error(`[vitehub:schedule] Schedule "${runs[index].name}" failed (cron "${options.cron}").`, normalizeRuntimeDiagnosticError(result.reason, { includeStack: true }));
175
- });
176
- if (failures.length === 1) throw failures[0];
177
- if (failures.length) throw new AggregateError(failures, `[vitehub:schedule] ${failures.length} schedules failed for cron "${options.cron}".`);
178
- return results.map((result) => result.status === "fulfilled" ? result.value : void 0);
179
- }
180
- async function executeCloudflareStaticSchedules(event, options) {
181
- const scheduled = readCloudflareScheduledEvent(event);
182
- return await runWithCloudflareServerEnv(event, async (waitUntil) => {
183
- return await executeMatchingStaticSchedules({
184
- cron: scheduled.cron,
185
- cronOverrides: options.cronOverrides,
186
- registry: options.registry,
187
- scheduledAt: scheduled.scheduledAt,
188
- timeZoneCrons: options.timeZoneCrons,
189
- waitUntil
190
- });
191
- }, options.waitUntil ?? readCloudflareWaitUntil(event));
192
- }
193
- function readCloudflareScheduledEvent(event) {
194
- const cron = event.controller?.cron ?? event.cron;
195
- if (typeof cron !== "string" || !cron.trim()) throw scheduleErrorDiagnostics.SCHEDULE_R0027({ message: "[vitehub:schedule] Cloudflare scheduled event is missing a cron string." });
196
- const scheduledTime = event.controller?.scheduledTime ?? event.scheduledTime;
197
- const scheduledAt = isScheduleDate(scheduledTime) ? new Date(Date.prototype.getTime.call(scheduledTime)) : scheduledTime === void 0 ? /* @__PURE__ */ new Date() : new Date(scheduledTime);
198
- if (Number.isNaN(scheduledAt.getTime())) throw scheduleErrorDiagnostics.SCHEDULE_R0028({ message: "[vitehub:schedule] Cloudflare scheduled event has an invalid scheduledTime." });
199
- return {
200
- cron,
201
- scheduledAt
202
- };
203
- }
204
- async function runWithCloudflareServerEnv(event, callback, hostWaitUntil) {
205
- const globals = globalThis;
206
- const hadGlobalEnv = Object.prototype.hasOwnProperty.call(globals, "__env__");
207
- const previousGlobalEnv = globals.__env__;
208
- const env = readCloudflareEventEnv(event);
209
- if (env) globals.__env__ = env;
210
- const pending = /* @__PURE__ */ new Set();
211
- const waitUntil = hostWaitUntil ? (value) => {
212
- const promise = Promise.resolve(value);
213
- pending.add(promise);
214
- promise.then(() => pending.delete(promise), () => pending.delete(promise));
215
- hostWaitUntil(promise);
216
- } : void 0;
217
- try {
218
- return await callback(waitUntil);
219
- } finally {
220
- if (pending.size === 0) restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv);
221
- else hostWaitUntil(flushPendingWork(pending).finally(() => {
222
- restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv);
223
- }));
224
- }
225
- }
226
- async function flushPendingWork(pending) {
227
- while (pending.size > 0) await Promise.allSettled(pending);
228
- }
229
- function restoreGlobalEnv(globals, hadGlobalEnv, previousGlobalEnv) {
230
- if (hadGlobalEnv) globals.__env__ = previousGlobalEnv;
231
- else delete globals.__env__;
232
- }
233
- function isCallable(value) {
234
- return typeof value === "function" || typeof value === "undefined" && value !== void 0;
235
- }
236
- function readCloudflareWaitUntil(event) {
237
- const context = isRecordOrFunction(event.context) ? event.context : void 0;
238
- const cloudflareContext = isRecordOrFunction(context?.cloudflare) ? context.cloudflare : void 0;
239
- const platformContext = isRecordOrFunction(context?._platform) ? context._platform : void 0;
240
- const platformCloudflareContext = isRecordOrFunction(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
241
- const request = isRecordOrFunction(event.req) ? event.req : void 0;
242
- const runtime = isRecordOrFunction(request?.runtime) ? request.runtime : void 0;
243
- const runtimeCloudflare = isRecordOrFunction(runtime?.cloudflare) ? runtime.cloudflare : void 0;
244
- const owners = [
245
- event,
246
- context,
247
- cloudflareContext,
248
- isRecordOrFunction(cloudflareContext?.context) ? cloudflareContext.context : void 0,
249
- platformCloudflareContext,
250
- isRecordOrFunction(platformCloudflareContext?.context) ? platformCloudflareContext.context : void 0,
251
- request,
252
- runtimeCloudflare,
253
- isRecordOrFunction(runtimeCloudflare?.context) ? runtimeCloudflare.context : void 0
254
- ];
255
- for (const owner of owners) {
256
- const waitUntil = owner?.waitUntil;
257
- if (isCallable(waitUntil)) return (promise) => Reflect.apply(waitUntil, owner, [promise]);
258
- }
259
- }
260
- function readCloudflareEventEnv(event) {
261
- if (isRecordOrFunction(event.env)) return event.env;
262
- const context = isRecordOrFunction(event.context) ? event.context : void 0;
263
- const cloudflareContext = isRecordOrFunction(context?.cloudflare) ? context.cloudflare : void 0;
264
- if (isRecordOrFunction(cloudflareContext?.env)) return cloudflareContext.env;
265
- const platformContext = isRecordOrFunction(context?._platform) ? context._platform : void 0;
266
- const platformCloudflareContext = isRecordOrFunction(platformContext?.cloudflare) ? platformContext.cloudflare : void 0;
267
- if (isRecordOrFunction(platformCloudflareContext?.env)) return platformCloudflareContext.env;
268
- const request = isRecordOrFunction(event.req) ? event.req : void 0;
269
- const runtime = isRecordOrFunction(request?.runtime) ? request.runtime : void 0;
270
- const runtimeCloudflare = isRecordOrFunction(runtime?.cloudflare) ? runtime.cloudflare : void 0;
271
- return isRecordOrFunction(runtimeCloudflare?.env) ? runtimeCloudflare.env : void 0;
272
- }
273
- function isStaticScheduleDefinition(value) {
274
- return isRecordOrFunction(value) && Object.hasOwn(value, "cron") && typeof value.cron === "string" && Object.hasOwn(value, "handler") && typeof value.handler === "function";
275
- }
276
- function unwrapScheduleDefinition(loaded) {
277
- const candidate = isRecordOrFunction(loaded) && Object.hasOwn(loaded, "default") ? loaded.default : loaded;
278
- return isStaticScheduleDefinition(candidate) ? candidate : void 0;
279
- }
280
- //#endregion
281
- export { isScheduleCronAuthorized as a, normalizeCron as c, unwrapScheduleDefinition as d, executeStaticSchedule as i, normalizeScheduleRuntimeError as l, executeCloudflareStaticSchedules as n, isTimeZoneWakeDue as o, executeMatchingStaticSchedules as r, missingScheduleDefinitionError as s, createStaticScheduleRun as t, scheduledWakeTime as u };
@@ -1,112 +0,0 @@
1
- import { ViteHubError } from "@vite-hub/runtime";
2
- //#region src/errors.ts
3
- const scheduleErrorMessages = {
4
- SCHEDULE_DEFINITION_NOT_FOUND: "Static Schedule Definition was not found.",
5
- SCHEDULE_INVALID_CRON: "Schedule cron is invalid.",
6
- SCHEDULE_INVALID_SCHEDULED_AT: "Schedule scheduledAt value is invalid.",
7
- SCHEDULE_MANUAL_RUN_DISABLED: "Schedule Definition does not allow manual runs. Set manual: true to allow them.",
8
- SCHEDULE_NOT_DUE: "Schedule is not due.",
9
- SCHEDULE_RUN_NOT_FOUND: "Schedule Run was not found."
10
- };
11
- function isDateValue(value) {
12
- if (value instanceof Date) return true;
13
- try {
14
- Date.prototype.getTime.call(value);
15
- return true;
16
- } catch {
17
- return false;
18
- }
19
- }
20
- function invalidScheduleValueDetails(field, value) {
21
- let valueType;
22
- try {
23
- valueType = value === null ? "null" : Array.isArray(value) ? "array" : isDateValue(value) ? "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
- //#endregion
36
- //#region src/runtime/date.ts
37
- /** The idempotency key of one Schedule occurrence. Two runs of the same Schedule for the same time share it. */
38
- function scheduleIdempotencyKey(name, scheduledAt) {
39
- return `schedule:${name}:${scheduledAt.toISOString()}`;
40
- }
41
- function isScheduleDate(value) {
42
- try {
43
- return !Number.isNaN(Date.prototype.getTime.call(value));
44
- } catch {
45
- return false;
46
- }
47
- }
48
- const scheduledAtText = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/i;
49
- function parseScheduledAtText(value) {
50
- const match = scheduledAtText.exec(value);
51
- if (!match) return;
52
- const [, year, month, day, hour] = match.map(Number);
53
- const calendarDay = /* @__PURE__ */ new Date(0);
54
- calendarDay.setUTCFullYear(year, month - 1, day);
55
- if (hour > 23 || calendarDay.getUTCMonth() !== month - 1 || calendarDay.getUTCDate() !== day) return;
56
- const date = new Date(value);
57
- return Number.isNaN(date.getTime()) ? void 0 : date;
58
- }
59
- function validateScheduledAt(scheduledAt) {
60
- const value = scheduledAt ?? /* @__PURE__ */ new Date();
61
- if (!isScheduleDate(value)) throw createScheduleError("SCHEDULE_INVALID_SCHEDULED_AT", { details: invalidScheduleValueDetails("scheduledAt", value) });
62
- return new Date(Date.prototype.getTime.call(value));
63
- }
64
- /**
65
- * 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
66
- * as `2026-01-31T23:59:00Z`. Anything else fails with `SCHEDULE_INVALID_SCHEDULED_AT`. Absent means now.
67
- */
68
- function parseScheduledAt(scheduledAt) {
69
- if (typeof scheduledAt !== "string") return validateScheduledAt(scheduledAt);
70
- const parsed = parseScheduledAtText(scheduledAt);
71
- if (parsed) return parsed;
72
- throw createScheduleError("SCHEDULE_INVALID_SCHEDULED_AT", { details: invalidScheduleValueDetails("scheduledAt", scheduledAt) });
73
- }
74
- //#endregion
75
- //#region src/runtime/wait-until.ts
76
- function createLocalWaitUntil() {
77
- const pending = /* @__PURE__ */ new Set();
78
- let error;
79
- let failed = false;
80
- return {
81
- async flush() {
82
- while (pending.size > 0) await Promise.allSettled(pending);
83
- if (failed) throw error;
84
- },
85
- waitUntil(value) {
86
- const promise = Promise.resolve(value);
87
- pending.add(promise);
88
- promise.then(() => pending.delete(promise), (reason) => {
89
- pending.delete(promise);
90
- if (!failed) error = reason;
91
- failed = true;
92
- });
93
- }
94
- };
95
- }
96
- /** Complete local deferred work while preserving a handler's failure over a deferred failure. */
97
- async function runWithScheduleWaitUntil(run, hostWaitUntil) {
98
- if (hostWaitUntil) return await run(hostWaitUntil);
99
- const local = createLocalWaitUntil();
100
- try {
101
- const result = await run(local.waitUntil);
102
- await local.flush();
103
- return result;
104
- } catch (error) {
105
- try {
106
- await local.flush();
107
- } catch {}
108
- throw error;
109
- }
110
- }
111
- //#endregion
112
- export { validateScheduledAt as a, scheduleIdempotencyKey as i, isScheduleDate as n, createScheduleError as o, parseScheduledAt as r, invalidScheduleValueDetails as s, runWithScheduleWaitUntil as t };