@vite-hub/schedule 0.0.3 → 0.1.0

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 (50) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +199 -65
  3. package/dist/definition-CMiOg1lg.js +111 -0
  4. package/dist/definition.d.ts +4 -6
  5. package/dist/definition.js +2 -42
  6. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  7. package/dist/error-diagnostics-in7mif5s.js +45 -0
  8. package/dist/execute-BJrgNgQ0.js +201 -0
  9. package/dist/index.d.ts +7 -51
  10. package/dist/index.js +2 -7
  11. package/dist/inspect-DTfAo5gS.js +118 -0
  12. package/dist/kv-storage-Bv9ocZT-.d.ts +18 -0
  13. package/dist/nuxt.d.ts +4 -6
  14. package/dist/nuxt.js +3 -1
  15. package/dist/operations-gk2qzhYV.js +131 -0
  16. package/dist/operations-tNUdj3G4.d.ts +212 -0
  17. package/dist/operations.d.ts +61 -0
  18. package/dist/operations.js +921 -0
  19. package/dist/registry-module.d.ts +0 -5
  20. package/dist/runtime/kv.d.ts +4 -0
  21. package/dist/{kv-BJ1I9IlJ.js → runtime/kv.js} +1 -1
  22. package/dist/runtime/process.d.ts +26 -5
  23. package/dist/runtime/process.js +337 -75
  24. package/dist/runtime/state.d.ts +8 -12
  25. package/dist/runtime/state.js +2 -2
  26. package/dist/runtime/static.d.ts +18 -12
  27. package/dist/runtime/static.js +2 -138
  28. package/dist/runtime.d.ts +36 -4
  29. package/dist/runtime.js +5 -3
  30. package/dist/state-DSxmHPn3.js +448 -0
  31. package/dist/static-6g82xguw.js +245 -0
  32. package/dist/store-QAOd8bxm.d.ts +11 -0
  33. package/dist/types-CHdV9FQU.d.ts +113 -0
  34. package/dist/vite-BAVyZ8hZ.d.ts +474 -0
  35. package/dist/vite-BJwZkMrn.js +5193 -0
  36. package/dist/vite.d.ts +2 -38
  37. package/dist/vite.js +2 -2
  38. package/dist/wait-until-BmIqRo4x.js +87 -0
  39. package/package.json +68 -22
  40. package/dist/client-BMFCy0dX.js +0 -233
  41. package/dist/discovery-BZlat3Kc.js +0 -776
  42. package/dist/due-Bbh4yIxq.js +0 -59
  43. package/dist/execute-ClFYvmp9.js +0 -211
  44. package/dist/runtime/driver.d.ts +0 -26
  45. package/dist/runtime/driver.js +0 -334
  46. package/dist/state-By7WU_ks.js +0 -472
  47. package/dist/store-t-74rsM_.d.ts +0 -48
  48. package/dist/types-Bcje4dLV.d.ts +0 -136
  49. package/dist/vite-BX6_KiRw.js +0 -1218
  50. package/dist/wait-until-CR-JjIOb.js +0 -23
@@ -0,0 +1,111 @@
1
+ import { t as scheduleErrorDiagnostics } from "./error-diagnostics-in7mif5s.js";
2
+ //#region ../internal/src/runtime/time-zone.ts
3
+ const slashlessIanaTimeZones = /* @__PURE__ */ new Set([
4
+ "CET",
5
+ "CST6CDT",
6
+ "Cuba",
7
+ "EET",
8
+ "EST",
9
+ "EST5EDT",
10
+ "Egypt",
11
+ "Eire",
12
+ "Factory",
13
+ "GB",
14
+ "GB-Eire",
15
+ "GMT",
16
+ "GMT+0",
17
+ "GMT-0",
18
+ "GMT0",
19
+ "Greenwich",
20
+ "HST",
21
+ "Hongkong",
22
+ "Iceland",
23
+ "Iran",
24
+ "Israel",
25
+ "Jamaica",
26
+ "Japan",
27
+ "Kwajalein",
28
+ "Libya",
29
+ "MET",
30
+ "MST",
31
+ "MST7MDT",
32
+ "NZ",
33
+ "NZ-CHAT",
34
+ "Navajo",
35
+ "PRC",
36
+ "PST8PDT",
37
+ "Poland",
38
+ "Portugal",
39
+ "ROC",
40
+ "ROK",
41
+ "Singapore",
42
+ "Turkey",
43
+ "UCT",
44
+ "UTC",
45
+ "Universal",
46
+ "W-SU",
47
+ "WET",
48
+ "Zulu"
49
+ ]);
50
+ function isIanaTimeZone(timeZone) {
51
+ if (typeof timeZone !== "string" || !timeZone.includes("/") && !slashlessIanaTimeZones.has(timeZone)) return false;
52
+ try {
53
+ new Intl.DateTimeFormat("en-US", { timeZone });
54
+ return true;
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+ //#endregion
60
+ //#region src/definition.ts
61
+ const cronFieldPattern = /^[^\s]+$/;
62
+ const scheduleDefinitionKeys = /* @__PURE__ */ new Set([
63
+ "manual",
64
+ "cron",
65
+ "handler",
66
+ "timeZone"
67
+ ]);
68
+ const scheduleOptionsKeys = /* @__PURE__ */ new Set(["manual", "timeZone"]);
69
+ function isPlainObject(value) {
70
+ return !!value && typeof value === "object" && !Array.isArray(value);
71
+ }
72
+ function isCronString(value) {
73
+ return value !== null && value !== void 0 && String(value) === value;
74
+ }
75
+ function assertOwnDefinitionFields(input, keys, message, diagnostic) {
76
+ const inheritedKey = [...keys].find((key) => key in input && !Object.hasOwn(input, key));
77
+ if (inheritedKey) throw diagnostic({ message: `${message} The "${inheritedKey}" option must be an own property.` });
78
+ }
79
+ function validateCron(cron) {
80
+ if (typeof cron !== "string" || cron.trim() !== cron || cron.length === 0) throw scheduleErrorDiagnostics.SCHEDULE_C0001({ message: "`defineSchedule()` requires a cron string." });
81
+ const fields = cron.split(/\s+/);
82
+ if (fields.length !== 5 || !fields.every((field) => cronFieldPattern.test(field))) throw scheduleErrorDiagnostics.SCHEDULE_C0002({ message: "`defineSchedule()` cron must be a five-field cron expression." });
83
+ }
84
+ function defineSchedule(cronOrInput, handler, options = {}) {
85
+ if (!isPlainObject(options)) throw scheduleErrorDiagnostics.SCHEDULE_C0003({ message: "`defineSchedule()` options must be an object." });
86
+ assertOwnDefinitionFields(options, scheduleOptionsKeys, "`defineSchedule()` does not accept inherited options.", scheduleErrorDiagnostics.SCHEDULE_C0004);
87
+ if (!isCronString(cronOrInput) && !isPlainObject(cronOrInput)) throw scheduleErrorDiagnostics.SCHEDULE_C0003({ message: "`defineSchedule()` expects an object with `cron` and `handler`." });
88
+ const input = isPlainObject(cronOrInput) ? cronOrInput : {
89
+ ...options,
90
+ cron: cronOrInput,
91
+ handler
92
+ };
93
+ if (!isPlainObject(input)) throw scheduleErrorDiagnostics.SCHEDULE_C0003({ message: "`defineSchedule()` expects an object with `cron` and `handler`." });
94
+ if (!Object.hasOwn(input, "cron") || !Object.hasOwn(input, "handler")) throw scheduleErrorDiagnostics.SCHEDULE_C0003({ message: "`defineSchedule()` expects an object with `cron` and `handler`." });
95
+ assertOwnDefinitionFields(input, scheduleDefinitionKeys, "`defineSchedule()` does not accept inherited options.", scheduleErrorDiagnostics.SCHEDULE_C0004);
96
+ const unknownKey = Object.keys(input).find((key) => !scheduleDefinitionKeys.has(key));
97
+ if (unknownKey) throw scheduleErrorDiagnostics.SCHEDULE_C0004({ message: `\`defineSchedule()\` does not support the "${unknownKey}" option.` });
98
+ validateCron(input.cron);
99
+ if (typeof input.handler !== "function") throw scheduleErrorDiagnostics.SCHEDULE_C0005({ message: "`defineSchedule()` requires a schedule handler." });
100
+ if (input.manual !== void 0 && input.manual !== true && input.manual !== false) throw scheduleErrorDiagnostics.SCHEDULE_C0006({ message: "`defineSchedule()` manual must be a boolean." });
101
+ if (input.timeZone !== void 0 && !isIanaTimeZone(input.timeZone)) throw scheduleErrorDiagnostics.SCHEDULE_C0006({ message: "`defineSchedule()` timeZone must be an IANA time zone, such as \"Europe/Madrid\"." });
102
+ const definition = {
103
+ cron: input.cron,
104
+ handler: input.handler
105
+ };
106
+ if (input.timeZone !== void 0) definition.timeZone = input.timeZone;
107
+ if (input.manual !== void 0) definition.options = { manual: input.manual };
108
+ return definition;
109
+ }
110
+ //#endregion
111
+ export { defineSchedule as t };
@@ -1,7 +1,5 @@
1
- import { S as ScheduleTargetDefinitionInput, c as ScheduleDefinition, l as ScheduleDefinitionInput, x as ScheduleTargetDefinition } from "./types-Bcje4dLV.js";
2
-
1
+ import { i as ScheduleDefinitionOptions, n as ScheduleDefinition, o as ScheduleHandler, r as ScheduleDefinitionInput } from "./types-CHdV9FQU.js";
3
2
  //#region src/definition.d.ts
4
- declare function defineSchedule<TResult = unknown>(input: ScheduleDefinitionInput<TResult>): ScheduleDefinition<TResult>;
5
- declare function defineScheduleTarget<TInput = unknown, TResult = unknown>(input: ScheduleTargetDefinitionInput<TInput, TResult>): ScheduleTargetDefinition<TInput, TResult>;
6
- //#endregion
7
- export { defineSchedule, defineScheduleTarget };
3
+ export declare function defineSchedule<TResult = unknown>(cron: string, handler: ScheduleHandler<TResult>, options?: ScheduleDefinitionOptions): ScheduleDefinition<TResult>;
4
+ export declare function defineSchedule<TResult = unknown>(input: ScheduleDefinitionInput<TResult>): ScheduleDefinition<TResult>;
5
+ //#endregion
@@ -1,42 +1,2 @@
1
- //#region src/definition.ts
2
- const cronFieldPattern = /^[^\s]+$/;
3
- const scheduleDefinitionKeys = new Set([
4
- "allowRuntimeSchedules",
5
- "cron",
6
- "handler"
7
- ]);
8
- const scheduleTargetDefinitionKeys = new Set(["handler"]);
9
- function isPlainObject(value) {
10
- return !!value && typeof value === "object" && !Array.isArray(value);
11
- }
12
- function validateCron(cron) {
13
- if (typeof cron !== "string" || cron.trim() !== cron || cron.length === 0) throw new TypeError("`defineSchedule()` requires a cron string.");
14
- const fields = cron.split(/\s+/);
15
- if (fields.length !== 5 || !fields.every((field) => cronFieldPattern.test(field))) throw new TypeError("`defineSchedule()` cron must be a five-field UTC cron expression.");
16
- }
17
- function defineSchedule(input) {
18
- if (!isPlainObject(input)) throw new TypeError("`defineSchedule()` expects an object with `cron` and `handler`.");
19
- const unknownKey = Object.keys(input).find((key) => !scheduleDefinitionKeys.has(key));
20
- if (unknownKey) throw new TypeError(`\`defineSchedule()\` does not support the "${unknownKey}" option.`);
21
- validateCron(input.cron);
22
- if (typeof input.handler !== "function") throw new TypeError("`defineSchedule()` requires a schedule handler.");
23
- if (typeof input.allowRuntimeSchedules !== "undefined" && typeof input.allowRuntimeSchedules !== "boolean") throw new TypeError("`defineSchedule()` allowRuntimeSchedules must be a boolean.");
24
- const definition = {
25
- cron: input.cron,
26
- handler: input.handler
27
- };
28
- if (typeof input.allowRuntimeSchedules !== "undefined") definition.options = { allowRuntimeSchedules: input.allowRuntimeSchedules };
29
- return definition;
30
- }
31
- function defineScheduleTarget(input) {
32
- if (!isPlainObject(input)) throw new TypeError("`defineScheduleTarget()` expects an object with `handler`.");
33
- const unknownKey = Object.keys(input).find((key) => !scheduleTargetDefinitionKeys.has(key));
34
- if (unknownKey) throw new TypeError(`\`defineScheduleTarget()\` does not support the "${unknownKey}" option.`);
35
- if (typeof input.handler !== "function") throw new TypeError("`defineScheduleTarget()` requires a schedule handler.");
36
- return {
37
- handler: input.handler,
38
- options: { allowRuntimeSchedules: true }
39
- };
40
- }
41
- //#endregion
42
- export { defineSchedule, defineScheduleTarget };
1
+ import { t as defineSchedule } from "./definition-CMiOg1lg.js";
2
+ export { defineSchedule };
@@ -0,0 +1,116 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region ../internal/src/error-diagnostics.ts
3
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
+ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
6
+ codes: {
7
+ INTERNAL_R0012: dynamicError,
8
+ INTERNAL_R0013: dynamicError,
9
+ INTERNAL_R0014: {
10
+ why: ({ path }) => `Cannot read Provision State from "${path}".`,
11
+ fix: "Check file access and restore valid JSON while preserving existing resource IDs."
12
+ },
13
+ INTERNAL_R0020: {
14
+ fix: "Give the operation a name like `content.publish`, a description, a section, a kind, an input schema, and a run function.",
15
+ why: ({ message }) => message === void 0 ? "" : String(message)
16
+ },
17
+ INTERNAL_R0021: {
18
+ fix: "Run `vitehub inspect definitions --kind operation` to list the operations of this app.",
19
+ why: ({ message }) => message === void 0 ? "" : String(message)
20
+ },
21
+ INTERNAL_R0022: {
22
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
23
+ why: ({ message }) => message === void 0 ? "" : String(message)
24
+ },
25
+ INTERNAL_R0024: {
26
+ fix: "Start the dev server with `vite dev`, or pass `--url <origin>` of a deployed app with credentials in VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET.",
27
+ why: ({ message }) => message === void 0 ? "" : String(message)
28
+ },
29
+ INTERNAL_R0023: {
30
+ fix: "Ask for access to the section of this operation.",
31
+ why: ({ message }) => message === void 0 ? "" : String(message)
32
+ },
33
+ INTERNAL_B0001: dynamicError,
34
+ INTERNAL_B0002: dynamicError,
35
+ INTERNAL_B0003: dynamicError,
36
+ INTERNAL_B0004: dynamicError,
37
+ INTERNAL_B0005: dynamicError,
38
+ INTERNAL_B0006: dynamicError,
39
+ INTERNAL_B0007: dynamicError,
40
+ INTERNAL_B0008: dynamicError,
41
+ INTERNAL_B0009: dynamicError,
42
+ INTERNAL_B0010: dynamicError,
43
+ INTERNAL_B0011: dynamicError,
44
+ INTERNAL_B0012: dynamicError,
45
+ INTERNAL_B0013: dynamicError,
46
+ INTERNAL_B0014: dynamicError,
47
+ INTERNAL_B0015: dynamicError,
48
+ INTERNAL_B0016: dynamicError,
49
+ INTERNAL_B0017: dynamicError,
50
+ INTERNAL_B0018: dynamicError,
51
+ INTERNAL_B0019: dynamicError,
52
+ INTERNAL_B0020: dynamicError,
53
+ INTERNAL_B0021: dynamicError,
54
+ INTERNAL_B0022: dynamicError,
55
+ INTERNAL_B0023: dynamicError,
56
+ INTERNAL_B0024: dynamicError,
57
+ INTERNAL_B0025: dynamicError,
58
+ INTERNAL_B0026: dynamicError,
59
+ INTERNAL_B0027: dynamicError,
60
+ INTERNAL_B0028: dynamicError,
61
+ INTERNAL_B0029: dynamicError,
62
+ INTERNAL_B0030: dynamicError,
63
+ INTERNAL_B0031: dynamicError,
64
+ INTERNAL_B0032: dynamicError,
65
+ INTERNAL_B0033: dynamicError,
66
+ INTERNAL_B0034: dynamicError,
67
+ INTERNAL_B0035: dynamicError,
68
+ INTERNAL_B0036: dynamicError,
69
+ INTERNAL_B0037: dynamicError,
70
+ INTERNAL_B0038: dynamicError,
71
+ INTERNAL_B0039: dynamicError,
72
+ INTERNAL_B0040: dynamicError,
73
+ INTERNAL_B0041: dynamicError,
74
+ INTERNAL_B0042: dynamicError,
75
+ INTERNAL_B0043: dynamicError,
76
+ INTERNAL_B0044: dynamicError,
77
+ INTERNAL_B0045: dynamicError,
78
+ INTERNAL_B0046: dynamicError,
79
+ INTERNAL_B0047: dynamicError,
80
+ INTERNAL_B0048: {
81
+ fix: "Rename one of the two operations. A name is `<section>.<verb>` and is unique in the app.",
82
+ why: ({ message }) => message === void 0 ? "" : String(message)
83
+ },
84
+ INTERNAL_B0049: {
85
+ fix: "Set `cli: { namespace, command }` on one of the two operations.",
86
+ why: ({ message }) => message === void 0 ? "" : String(message)
87
+ },
88
+ INTERNAL_B0050: {
89
+ fix: "Rename one of the two operations, or set `mcp: false` on it. MCP tool names replace every character outside letters, digits, `_`, and `-` with `_`.",
90
+ why: ({ message }) => message === void 0 ? "" : String(message)
91
+ },
92
+ INTERNAL_R0025: {
93
+ fix: "Start `vite dev` in the project that you run the command from, or pass `--url` of that server.",
94
+ why: ({ message }) => message === void 0 ? "" : String(message)
95
+ },
96
+ INTERNAL_R0026: {
97
+ why: "The server parsed a destructive operation that the CLI did not confirm.",
98
+ fix: "Review the operation, then run it again with --yes to confirm the change."
99
+ },
100
+ INTERNAL_C0001: dynamicError,
101
+ INTERNAL_C0002: dynamicError,
102
+ INTERNAL_R0001: dynamicError,
103
+ INTERNAL_R0002: dynamicError,
104
+ INTERNAL_R0003: dynamicError,
105
+ INTERNAL_R0004: dynamicError,
106
+ INTERNAL_R0005: dynamicError,
107
+ INTERNAL_R0006: dynamicError,
108
+ INTERNAL_R0007: dynamicError,
109
+ INTERNAL_R0008: dynamicError,
110
+ INTERNAL_R0009: dynamicError,
111
+ INTERNAL_R0010: dynamicError,
112
+ INTERNAL_R0011: dynamicError
113
+ }
114
+ });
115
+ //#endregion
116
+ export { internalErrorDiagnostics as t };
@@ -0,0 +1,45 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region src/error-diagnostics.ts
3
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
+ const scheduleErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
6
+ codes: {
7
+ SCHEDULE_C0001: dynamicError,
8
+ SCHEDULE_C0002: dynamicError,
9
+ SCHEDULE_C0003: dynamicError,
10
+ SCHEDULE_C0004: dynamicError,
11
+ SCHEDULE_C0005: dynamicError,
12
+ SCHEDULE_C0006: dynamicError,
13
+ SCHEDULE_R0001: dynamicError,
14
+ SCHEDULE_R0002: dynamicError,
15
+ SCHEDULE_R0003: dynamicError,
16
+ SCHEDULE_R0004: dynamicError,
17
+ SCHEDULE_R0005: dynamicError,
18
+ SCHEDULE_R0006: dynamicError,
19
+ SCHEDULE_R0022: dynamicError,
20
+ SCHEDULE_R0023: dynamicError,
21
+ SCHEDULE_R0024: dynamicError,
22
+ SCHEDULE_R0025: dynamicError,
23
+ SCHEDULE_R0026: dynamicError,
24
+ SCHEDULE_R0027: dynamicError,
25
+ SCHEDULE_R0028: dynamicError,
26
+ SCHEDULE_R0030: dynamicError,
27
+ SCHEDULE_R0031: dynamicError,
28
+ SCHEDULE_R0032: dynamicError,
29
+ SCHEDULE_R0033: dynamicError,
30
+ SCHEDULE_R0034: dynamicError,
31
+ SCHEDULE_R0035: dynamicError,
32
+ SCHEDULE_R0036: dynamicError,
33
+ SCHEDULE_R0037: dynamicError,
34
+ SCHEDULE_R0038: dynamicError,
35
+ SCHEDULE_B0001: dynamicError,
36
+ SCHEDULE_B0002: dynamicError,
37
+ SCHEDULE_B0003: dynamicError,
38
+ SCHEDULE_B0004: dynamicError,
39
+ SCHEDULE_B0005: dynamicError,
40
+ SCHEDULE_B0006: dynamicError,
41
+ SCHEDULE_B0007: dynamicError
42
+ }
43
+ });
44
+ //#endregion
45
+ export { scheduleErrorDiagnostics as t };
@@ -0,0 +1,201 @@
1
+ import { i as createScheduleError, r as validateScheduledAt, t as runWithScheduleWaitUntil } from "./wait-until-BmIqRo4x.js";
2
+ import { r as loadScheduleDefinition, t as getScheduleRunStore } from "./state-DSxmHPn3.js";
3
+ import { serializeResponse, toResponse } from "@vite-hub/runtime";
4
+ //#region ../internal/src/runtime/random.ts
5
+ function randomId(prefix) {
6
+ const body = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
7
+ return prefix ? `${prefix}_${body}` : body;
8
+ }
9
+ //#endregion
10
+ //#region src/runtime/execute.ts
11
+ function normalizeRunSource(source) {
12
+ return source ?? "direct";
13
+ }
14
+ /** Returns the Schedule Run id for one scheduled occurrence, with an optional unique suffix. */
15
+ function toRunId(source, scheduleId, scheduledAt, runIdSuffix) {
16
+ return `srun_${normalizeRunSource(source)}_${encodeURIComponent(scheduleId)}_${scheduledAt.toISOString()}${runIdSuffix ? `_${runIdSuffix}` : ""}`;
17
+ }
18
+ function toRunError(error) {
19
+ try {
20
+ if (error instanceof Error) return {
21
+ message: error.message,
22
+ name: error.name,
23
+ stack: error.stack
24
+ };
25
+ return { message: String(error) };
26
+ } catch {
27
+ return { message: "[unprintable thrown value]" };
28
+ }
29
+ }
30
+ function requireUpdatedRun(run) {
31
+ if (!run) throw createScheduleError("SCHEDULE_RUN_NOT_FOUND");
32
+ return run;
33
+ }
34
+ async function createOrGetRun(options) {
35
+ const store = options.runStore ?? getScheduleRunStore();
36
+ const id = toRunId(options.source, options.scheduleId, options.scheduledAt, options.runIdSuffix);
37
+ const existing = await store.getRun(id);
38
+ if (existing) return {
39
+ created: false,
40
+ run: existing
41
+ };
42
+ const now = /* @__PURE__ */ new Date();
43
+ const runInput = {
44
+ attemptCount: 0,
45
+ createdAt: now,
46
+ id,
47
+ scheduleId: options.scheduleId,
48
+ scheduledAt: options.scheduledAt,
49
+ status: "pending",
50
+ target: options.target,
51
+ updatedAt: now
52
+ };
53
+ try {
54
+ return {
55
+ created: true,
56
+ run: await store.createRun(runInput)
57
+ };
58
+ } catch (error) {
59
+ const run = await store.getRun(id);
60
+ if (run) return {
61
+ created: false,
62
+ run
63
+ };
64
+ throw error;
65
+ }
66
+ }
67
+ async function startAttempt(run, store = getScheduleRunStore()) {
68
+ const now = /* @__PURE__ */ new Date();
69
+ const attempt = await store.createAttempt({
70
+ createdAt: now,
71
+ id: randomId("satt"),
72
+ runId: run.id,
73
+ startedAt: now,
74
+ status: "running",
75
+ updatedAt: now
76
+ });
77
+ await store.updateRun(run.id, {
78
+ attemptCount: run.attemptCount + 1,
79
+ startedAt: run.startedAt ?? now,
80
+ status: "running",
81
+ updatedAt: now
82
+ });
83
+ return attempt;
84
+ }
85
+ function toHandlerContext(run, attempt, waitUntil) {
86
+ return {
87
+ attemptId: attempt.id,
88
+ id: run.id,
89
+ runId: run.id,
90
+ scheduleId: run.scheduleId,
91
+ scheduledAt: run.scheduledAt,
92
+ target: run.target,
93
+ waitUntil
94
+ };
95
+ }
96
+ async function completeRun(run, attempt, response, store = getScheduleRunStore()) {
97
+ const now = /* @__PURE__ */ new Date();
98
+ await store.updateAttempt(attempt.id, {
99
+ completedAt: now,
100
+ status: "succeeded",
101
+ updatedAt: now
102
+ });
103
+ return requireUpdatedRun(await store.updateRun(run.id, {
104
+ completedAt: now,
105
+ response,
106
+ status: "succeeded",
107
+ updatedAt: now
108
+ }));
109
+ }
110
+ async function failRun(run, attempt, error, store = getScheduleRunStore()) {
111
+ const now = /* @__PURE__ */ new Date();
112
+ const serializedError = toRunError(error);
113
+ await store.updateAttempt(attempt.id, {
114
+ completedAt: now,
115
+ error: serializedError,
116
+ status: "failed",
117
+ updatedAt: now
118
+ });
119
+ return requireUpdatedRun(await store.updateRun(run.id, {
120
+ completedAt: now,
121
+ error: serializedError,
122
+ status: "failed",
123
+ updatedAt: now
124
+ }));
125
+ }
126
+ async function createScheduleRun(options) {
127
+ const scheduledAt = validateScheduledAt(options.scheduledAt ?? /* @__PURE__ */ new Date());
128
+ return (await createOrGetRun({
129
+ ...options,
130
+ scheduledAt
131
+ })).run;
132
+ }
133
+ async function executeSchedule(options) {
134
+ const scheduledAt = validateScheduledAt(options.scheduledAt ?? /* @__PURE__ */ new Date());
135
+ const { created, run } = await createOrGetRun({
136
+ ...options,
137
+ scheduledAt
138
+ });
139
+ if (!created) return run;
140
+ const runStore = options.runStore ?? getScheduleRunStore();
141
+ const attempt = await startAttempt(run, runStore);
142
+ try {
143
+ const value = await runWithScheduleWaitUntil((waitUntil) => options.definition.handler(toHandlerContext(run, attempt, waitUntil)), options.waitUntil);
144
+ return await completeRun(run, attempt, await serializeResponse(toResponse(value)), runStore);
145
+ } catch (error) {
146
+ const failed = await failRun(run, attempt, error, runStore);
147
+ if (options.captureHandlerFailure) return failed;
148
+ throw error;
149
+ }
150
+ }
151
+ async function executeStaticSchedule(options) {
152
+ return await executeSchedule({
153
+ definition: options.definition,
154
+ scheduleId: options.name,
155
+ source: "static",
156
+ scheduledAt: options.scheduledAt,
157
+ target: options.name,
158
+ waitUntil: options.waitUntil
159
+ });
160
+ }
161
+ function isObjectRecord(value) {
162
+ return Object(value) === value && !Array.isArray(value);
163
+ }
164
+ function isStaticScheduleDefinition(value) {
165
+ return isObjectRecord(value) && Object.hasOwn(value, "handler") && typeof value.handler === "function" && Object.hasOwn(value, "cron");
166
+ }
167
+ async function loadStaticScheduleDefinition(name, registry) {
168
+ let loaded;
169
+ if (registry) {
170
+ const entry = Object.hasOwn(registry, name) ? registry[name] : void 0;
171
+ loaded = typeof entry === "function" ? await entry() : void 0;
172
+ } else loaded = await loadScheduleDefinition(name);
173
+ const record = isObjectRecord(loaded) ? loaded : void 0;
174
+ return record && isStaticScheduleDefinition(record) ? record : record && Object.hasOwn(record, "default") && isStaticScheduleDefinition(record.default) ? record.default : void 0;
175
+ }
176
+ /** Runs a manually dispatchable static Schedule Definition immediately. */
177
+ async function runSchedule(name, options = {}) {
178
+ const definition = typeof name === "string" && name ? await loadStaticScheduleDefinition(name, options.registry) : void 0;
179
+ if (!definition) throw createScheduleError("SCHEDULE_DEFINITION_NOT_FOUND");
180
+ if (definition.options?.manual !== true) throw createScheduleError("SCHEDULE_MANUAL_RUN_DISABLED");
181
+ const runStore = getScheduleRunStore();
182
+ const scheduledAt = /* @__PURE__ */ new Date();
183
+ const runIdSuffix = randomId("manual");
184
+ try {
185
+ return await executeSchedule({
186
+ definition,
187
+ runIdSuffix,
188
+ runStore,
189
+ scheduleId: name,
190
+ source: "manual",
191
+ scheduledAt,
192
+ target: name
193
+ });
194
+ } catch (error) {
195
+ const run = await runStore.getRun(toRunId("manual", name, scheduledAt, runIdSuffix));
196
+ if (run?.status === "failed") return run;
197
+ throw error;
198
+ }
199
+ }
200
+ //#endregion
201
+ export { runSchedule as i, executeSchedule as n, executeStaticSchedule as r, createScheduleRun as t };
package/dist/index.d.ts CHANGED
@@ -1,56 +1,12 @@
1
1
  /// <reference path="./registry-module.d.ts" />
2
- import { C as ScheduleTargetName, S as ScheduleTargetDefinitionInput, _ as ScheduleRunError, a as RuntimeScheduleStore, b as ScheduleRunStore, c as ScheduleDefinition, d as ScheduleDefinitionRegistry, f as ScheduleHandler, g as ScheduleRunContext, h as ScheduleRunAttemptStatus, i as RuntimeScheduleRecord, l as ScheduleDefinitionInput, m as ScheduleRunAttemptRecord, n as RuntimeScheduleCreateInput, o as RuntimeScheduleUpdateInput, p as ScheduleRegistryDefinition, r as RuntimeScheduleMetadata, t as DiscoveredScheduleDefinition, v as ScheduleRunRecord, x as ScheduleTargetDefinition, y as ScheduleRunStatus } from "./types-Bcje4dLV.js";
3
- import { defineSchedule, defineScheduleTarget } from "./definition.js";
4
- import { a as createMemoryScheduleRunStore, c as schedules, i as createMemoryRuntimeScheduleStore, l as validateRuntimeScheduleCron, n as createKVRuntimeScheduleStore, o as ScheduleKVStorage, r as createKVScheduleRunStore, s as createScheduleKVStorage, t as KVScheduleStoreOptions } from "./store-t-74rsM_.js";
5
- import { getRuntimeScheduleStore, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, setRuntimeScheduleStore, setScheduleRunStore, setScheduleRuntimeRegistry } from "./runtime/state.js";
2
+ import { a as ScheduleDefinitionRegistry, c as ScheduleRunAttemptRecord, d as ScheduleRunError, f as ScheduleRunListOptions, g as ScheduleRunStore, h as ScheduleRunStatus, l as ScheduleRunAttemptStatus, m as ScheduleRunResponse, n as ScheduleDefinition, o as ScheduleHandler, p as ScheduleRunRecord, r as ScheduleDefinitionInput, s as ScheduleRegistryDefinition, t as DiscoveredScheduleDefinition, u as ScheduleRunContext } from "./types-CHdV9FQU.js";
3
+ import { defineSchedule } from "./definition.js";
4
+ import { t as ScheduleKVStorage } from "./kv-storage-Bv9ocZT-.js";
5
+ import { t as KVScheduleStoreOptions } from "./store-QAOd8bxm.js";
6
6
  import { ViteHubError } from "@vite-hub/runtime";
7
-
8
- //#region src/discovery.d.ts
9
- declare function discoverScheduleDefinitions(options: {
10
- mode?: "vite-suffix";
11
- rootDir: string;
12
- scanDirs?: string[];
13
- serverDirs?: string[];
14
- serverRootDir?: string;
15
- } | {
16
- mode: "server-schedules";
17
- scanDirs: string[];
18
- }): DiscoveredScheduleDefinition[];
19
- //#endregion
20
- //#region src/runtime/execute.d.ts
21
- interface ExecuteScheduleOptions {
22
- definition: ScheduleRegistryDefinition;
23
- input?: unknown;
24
- runStore?: ScheduleRunStore;
25
- scheduleId: string;
26
- source?: "direct" | "runtime" | "static";
27
- scheduledAt?: Date;
28
- target: ScheduleTargetName;
29
- waitUntil?: (promise: PromiseLike<unknown>) => void;
30
- }
31
- interface ExecuteStaticScheduleOptions {
32
- cron: string;
33
- definition: ScheduleDefinition;
34
- name: string;
35
- scheduledAt?: Date;
36
- waitUntil?: (promise: PromiseLike<unknown>) => void;
37
- }
38
- interface ExecuteRuntimeScheduleOptions {
39
- id: string;
40
- requireDue?: boolean;
41
- runtimeScheduleStore?: RuntimeScheduleStore;
42
- scheduledAt?: Date;
43
- scheduleRunStore?: ScheduleRunStore;
44
- waitUntil?: (promise: PromiseLike<unknown>) => void;
45
- }
46
- declare function createScheduleRun(options: Omit<ExecuteScheduleOptions, "definition" | "waitUntil">): Promise<ScheduleRunRecord>;
47
- declare function executeSchedule(options: ExecuteScheduleOptions): Promise<ScheduleRunRecord>;
48
- declare function executeStaticSchedule(options: ExecuteStaticScheduleOptions): Promise<ScheduleRunRecord>;
49
- declare function executeRuntimeSchedule(options: ExecuteRuntimeScheduleOptions | string): Promise<ScheduleRunRecord>;
50
- //#endregion
51
7
  //#region src/errors.d.ts
52
- declare const scheduleErrorCodes: readonly ["SCHEDULE_ALREADY_EXISTS", "SCHEDULE_DISABLED", "SCHEDULE_INVALID_CRON", "SCHEDULE_INVALID_ENABLED", "SCHEDULE_INVALID_ID", "SCHEDULE_INVALID_INPUT", "SCHEDULE_INVALID_SCHEDULED_AT", "SCHEDULE_INVALID_TARGET", "SCHEDULE_INVALID_TIME_ZONE", "SCHEDULE_NOT_DUE", "SCHEDULE_NOT_FOUND", "SCHEDULE_RUN_NOT_FOUND", "SCHEDULE_TARGET_NOT_ELIGIBLE", "SCHEDULE_TARGET_NOT_FOUND"];
53
- declare const scheduleErrorFields: readonly ["cron", "enabled", "id", "input", "options", "scheduledAt", "target", "timeZone"];
8
+ declare const scheduleErrorCodes: readonly ["SCHEDULE_DEFINITION_NOT_FOUND", "SCHEDULE_INVALID_CRON", "SCHEDULE_INVALID_SCHEDULED_AT", "SCHEDULE_MANUAL_RUN_DISABLED", "SCHEDULE_NOT_DUE", "SCHEDULE_RUN_NOT_FOUND"];
9
+ declare const scheduleErrorFields: readonly ["cron", "scheduledAt"];
54
10
  declare const scheduleErrorValueTypes: readonly ["array", "bigint", "boolean", "date", "function", "null", "number", "object", "string", "symbol", "undefined", "unknown"];
55
11
  type ScheduleErrorCode = typeof scheduleErrorCodes[number];
56
12
  type ScheduleErrorField = typeof scheduleErrorFields[number];
@@ -61,4 +17,4 @@ type ScheduleErrorDetails = {
61
17
  valueType: ScheduleErrorValueType;
62
18
  };
63
19
  //#endregion
64
- export { type DiscoveredScheduleDefinition, type KVScheduleStoreOptions, type RuntimeScheduleCreateInput, type RuntimeScheduleMetadata, type RuntimeScheduleRecord, type RuntimeScheduleStore, type RuntimeScheduleUpdateInput, type ScheduleDefinition, type ScheduleDefinitionInput, type ScheduleDefinitionRegistry, type ScheduleErrorCode, type ScheduleErrorDetails, type ScheduleErrorField, type ScheduleErrorValueType, type ScheduleHandler, type ScheduleKVStorage, type ScheduleRegistryDefinition, type ScheduleRunAttemptRecord, type ScheduleRunAttemptStatus, type ScheduleRunContext, type ScheduleRunError, type ScheduleRunRecord, type ScheduleRunStatus, type ScheduleRunStore, type ScheduleTargetDefinition, type ScheduleTargetDefinitionInput, type ScheduleTargetName, type ScheduleValidationErrorCode, createKVRuntimeScheduleStore, createKVScheduleRunStore, createMemoryRuntimeScheduleStore, createMemoryScheduleRunStore, createScheduleKVStorage, createScheduleRun, defineSchedule, defineScheduleTarget, discoverScheduleDefinitions, executeRuntimeSchedule, executeSchedule, executeStaticSchedule, getRuntimeScheduleStore, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, schedules, setRuntimeScheduleStore, setScheduleRunStore, setScheduleRuntimeRegistry, validateRuntimeScheduleCron };
20
+ export { type DiscoveredScheduleDefinition, type KVScheduleStoreOptions, type ScheduleDefinition, type ScheduleDefinitionInput, type ScheduleDefinitionRegistry, type ScheduleErrorCode, type ScheduleErrorDetails, type ScheduleErrorField, type ScheduleErrorValueType, type ScheduleHandler, type ScheduleKVStorage, type ScheduleRegistryDefinition, type ScheduleRunAttemptRecord, type ScheduleRunAttemptStatus, type ScheduleRunContext, type ScheduleRunError, type ScheduleRunListOptions, type ScheduleRunRecord, type ScheduleRunResponse, type ScheduleRunStatus, type ScheduleRunStore, type ScheduleValidationErrorCode, defineSchedule };
package/dist/index.js CHANGED
@@ -1,7 +1,2 @@
1
- import { defineSchedule, defineScheduleTarget } from "./definition.js";
2
- import { t as discoverScheduleDefinitions } from "./discovery-BZlat3Kc.js";
3
- import { a as executeStaticSchedule, i as executeSchedule, n as executeRuntimeSchedule, t as createScheduleRun } from "./execute-ClFYvmp9.js";
4
- import { a as resetScheduleRuntime, c as setScheduleRuntimeRegistry, d as createMemoryRuntimeScheduleStore, f as createMemoryScheduleRunStore, i as loadScheduleDefinition, l as createKVRuntimeScheduleStore, n as getScheduleRunStore, o as setRuntimeScheduleStore, r as getScheduleRuntimeRegistry, s as setScheduleRunStore, t as getRuntimeScheduleStore, u as createKVScheduleRunStore } from "./state-By7WU_ks.js";
5
- import { n as validateRuntimeScheduleCron, t as schedules } from "./client-BMFCy0dX.js";
6
- import { t as createScheduleKVStorage } from "./kv-storage-DWinmLLy.js";
7
- export { createKVRuntimeScheduleStore, createKVScheduleRunStore, createMemoryRuntimeScheduleStore, createMemoryScheduleRunStore, createScheduleKVStorage, createScheduleRun, defineSchedule, defineScheduleTarget, discoverScheduleDefinitions, executeRuntimeSchedule, executeSchedule, executeStaticSchedule, getRuntimeScheduleStore, getScheduleRunStore, getScheduleRuntimeRegistry, loadScheduleDefinition, resetScheduleRuntime, schedules, setRuntimeScheduleStore, setScheduleRunStore, setScheduleRuntimeRegistry, validateRuntimeScheduleCron };
1
+ import { t as defineSchedule } from "./definition-CMiOg1lg.js";
2
+ export { defineSchedule };