@vite-hub/schedule 0.0.4 → 0.3.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 (62) hide show
  1. package/README.md +139 -58
  2. package/dist/console-wEhr0LWn.d.ts +330 -0
  3. package/dist/definition.d.ts +8 -6
  4. package/dist/definition.js +34 -28
  5. package/dist/due-BVMRQ93v.js +144 -0
  6. package/dist/durability.d.ts +14 -0
  7. package/dist/durability.js +23 -0
  8. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  9. package/dist/error-diagnostics-Mpeks7J0.js +166 -0
  10. package/dist/index.d.ts +61 -40
  11. package/dist/index.js +27 -7
  12. package/dist/inspect-DTfAo5gS.js +118 -0
  13. package/dist/invariant-DolT9EEx.js +22 -0
  14. package/dist/kv-storage-C0KZZB6v.d.ts +18 -0
  15. package/dist/{kv-storage-DWinmLLy.js → kv-storage-iJChCS5A.js} +2 -2
  16. package/dist/object-Da1zyPCR.js +11 -0
  17. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  18. package/dist/operations-DwZWFIUX.js +184 -0
  19. package/dist/operations.d.ts +84 -0
  20. package/dist/operations.js +318 -0
  21. package/dist/os.d.ts +167 -0
  22. package/dist/os.js +1659 -0
  23. package/dist/registry-module.d.ts +0 -5
  24. package/dist/runtime/console.d.ts +12 -0
  25. package/dist/runtime/console.js +85 -0
  26. package/dist/runtime/kv.d.ts +4 -0
  27. package/dist/{kv-BJ1I9IlJ.js → runtime/kv.js} +1 -1
  28. package/dist/runtime/process.d.ts +53 -5
  29. package/dist/runtime/process.js +501 -251
  30. package/dist/runtime/state.d.ts +2 -13
  31. package/dist/runtime/state.js +2 -2
  32. package/dist/runtime/static.d.ts +44 -12
  33. package/dist/runtime/static.js +2 -150
  34. package/dist/runtime.d.ts +38 -4
  35. package/dist/runtime.js +6 -3
  36. package/dist/started-BuGmnus4.js +201 -0
  37. package/dist/started-Bx7MDbrl.js +146 -0
  38. package/dist/started-errors-p7cu_rI7.js +250 -0
  39. package/dist/state-B-Fuyfb4.js +468 -0
  40. package/dist/state-Do2wV4Tx.d.ts +49 -0
  41. package/dist/static-DQwzzvPg.js +266 -0
  42. package/dist/store-Df0-fzCl.d.ts +53 -0
  43. package/dist/time-zone-SBldrUgt.js +59 -0
  44. package/dist/types-Cw5LjPuc.d.ts +167 -0
  45. package/dist/vite.d.ts +214 -11
  46. package/dist/vite.js +5876 -3
  47. package/dist/wait-until-Dy4Bn3ZN.js +112 -0
  48. package/package.json +65 -24
  49. package/dist/client-DpCD4YFE.js +0 -233
  50. package/dist/discovery-DkFAN7Wd.d.ts +0 -15
  51. package/dist/discovery-DvU3B6iD.js +0 -753
  52. package/dist/due-Bbh4yIxq.js +0 -59
  53. package/dist/execute-B-pii4wf.js +0 -211
  54. package/dist/nuxt.d.ts +0 -19
  55. package/dist/nuxt.js +0 -26
  56. package/dist/runtime/driver.d.ts +0 -26
  57. package/dist/runtime/driver.js +0 -337
  58. package/dist/state-By7WU_ks.js +0 -472
  59. package/dist/store-t-74rsM_.d.ts +0 -48
  60. package/dist/types-Bcje4dLV.d.ts +0 -136
  61. package/dist/vite-BHs17nWX.js +0 -4166
  62. package/dist/wait-until-BzIwzXw4.js +0 -23
package/README.md CHANGED
@@ -1,13 +1,18 @@
1
1
  # @vite-hub/schedule
2
2
 
3
- `@vite-hub/schedule` discovers recurring work, generates cron output for supported hosts, and manages recurring schedules that an application creates while it runs.
3
+ [![npm version](https://comark-ui.onmax.me/badge.svg?source=npm-version&package=%40vite-hub%2Fschedule&icon=npm)](https://npmx.dev/package/@vite-hub/schedule)
4
+ [![npm downloads](https://comark-ui.onmax.me/badge.svg?source=npm-downloads&package=%40vite-hub%2Fschedule&period=month&icon=npm)](https://npmx.dev/package/@vite-hub/schedule)
5
+ [![license](https://comark-ui.onmax.me/badge.svg?label=license&value=Apache-2.0)](https://github.com/vite-hub/vitehub/blob/main/LICENSE)
6
+ [![docs](https://comark-ui.onmax.me/badge.svg?label=docs&value=vitehub.dev)](https://vitehub.dev/docs)
7
+
8
+ `@vite-hub/schedule` discovers recurring work, generates cron output for supported hosts, and can run Static Schedule Definitions in one long-lived process.
4
9
 
5
10
  ## Choose the package
6
11
 
7
- Install `vite-hub` for an application. It includes Schedule and exposes application imports under `vite-hub/schedule`.
12
+ Install `vite-hub` and `@vite-hub/schedule` for an application. `vite-hub` exposes application imports under `vite-hub/schedule` and loads Schedule from the app.
8
13
 
9
14
  ```sh
10
- pnpm add vite-hub
15
+ pnpm add vite-hub @vite-hub/schedule
11
16
  ```
12
17
 
13
18
  Enable Schedule with the framework integration and import application helpers from its feature path:
@@ -18,7 +23,7 @@ import { vitehub } from "vite-hub";
18
23
  import { defineConfig } from "vite";
19
24
 
20
25
  export default defineConfig({
21
- plugins: [vitehub({ preset: "cloudflare", schedule: true })],
26
+ plugins: [vitehub({ host: "cloudflare", schedule: true })],
22
27
  });
23
28
  ```
24
29
 
@@ -32,26 +37,17 @@ Install the owner package directly when a library or custom integration needs Sc
32
37
  pnpm add @vite-hub/schedule
33
38
  ```
34
39
 
35
- Direct integrations use `@vite-hub/schedule`, `@vite-hub/schedule/runtime`, and `@vite-hub/schedule/vite`. Add Vite when the project uses `hubSchedule()`. Add `@vite-hub/kv` when using the default KV-backed stores or the generated Process Runtime. Static Schedule Definitions, memory stores, and custom `ScheduleKVStorage` implementations do not require KV.
36
-
37
- Both packages require Node.js 24.15 or newer.
38
-
39
- ## Choose the schedule kind
40
-
41
- | Kind | Create it with | Use it when |
42
- | -------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
43
- | Static Schedule Definition | `defineSchedule()` in a discovered source file | The cron is part of the deployment and can produce host Provider Output. |
44
- | Schedule Target | `defineScheduleTarget()` in a discovered source file | Runtime Schedules need a named handler with no build-time cron. A target never produces static cron output. |
45
- | Runtime Schedule | `schedules.create()` in server code | The application must create, update, pause, or delete a recurring schedule while it runs. |
40
+ Direct integrations use `@vite-hub/schedule`, `@vite-hub/schedule/runtime`, and `@vite-hub/schedule/vite`. Add Vite when the project uses `hubSchedule()`. Add `@vite-hub/kv` when using the KV Schedule Run store through `@vite-hub/schedule/runtime/kv` or the generated Process Runtime. Static Schedule Definitions, memory stores, and custom `ScheduleKVStorage` implementations do not require KV.
46
41
 
47
- A Runtime Schedule must name a Schedule Target. A Static Schedule Definition can also become a target when it sets `allowRuntimeSchedules: true`.
42
+ Both packages require Node.js 22.18 or newer.
48
43
 
49
44
  ## Run one occurrence
50
45
 
51
- This smoke test uses the direct owner-package import. If the application installed `vite-hub`, import the same names from `vite-hub/schedule`. It defines a Static Schedule and executes one fixed occurrence without a Vite config or hosted scheduler.
46
+ This smoke test uses the direct owner-package import. If the application installed `vite-hub`, use `vite-hub/schedule` and `vite-hub/schedule/runtime`. It defines a Static Schedule and executes one fixed occurrence without a Vite config or hosted scheduler.
52
47
 
53
48
  ```ts
54
- import { defineSchedule, executeStaticSchedule } from "@vite-hub/schedule";
49
+ import { defineSchedule } from "@vite-hub/schedule";
50
+ import { executeStaticSchedule } from "@vite-hub/schedule/runtime";
55
51
 
56
52
  const dailyReport = defineSchedule({
57
53
  cron: "0 8 * * *",
@@ -93,7 +89,7 @@ export default defineConfig({
93
89
 
94
90
  Then export a definition from `server/schedules/<name>.ts` or `src/<name>.schedule.ts`.
95
91
 
96
- ```ts
92
+ ```ts fragment
97
93
  // server/schedules/daily-report.ts
98
94
  import { defineSchedule } from "@vite-hub/schedule";
99
95
 
@@ -106,69 +102,81 @@ export default defineSchedule({
106
102
  });
107
103
  ```
108
104
 
109
- Static Schedule Definitions use five-field UTC cron expressions. They cannot set `timeZone`. The integration can generate host-specific output for Cloudflare Cron Triggers, Vercel Cron Jobs, Netlify Scheduled Functions, standalone `Deno.cron`, and Nitro's Cloudflare schedule hook. Host selection, local execution, deployment proof, limits, and billing still come from the selected host. Check the [runtime and host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix) before deploying.
105
+ Static Schedule Definitions use five-field cron expressions. The cron uses UTC unless the definition sets `timeZone` to an IANA name, such as `Europe/Madrid`. `timeZone` works with the Process Runtime and with every host's cron output.
110
106
 
111
- Applications that use the framework distribution register Schedule through `vitehub({ preset, schedule: true })` and import the definition helper from `vite-hub/schedule`. The Deno framework preset currently rejects Schedule because standalone Deno cron output sits outside its generated Nitro entrypoint. Use the direct Schedule integration for that output.
107
+ The integration can generate host-specific output for Cloudflare Cron Triggers, Vercel Cron Jobs, Netlify Scheduled Functions, standalone `Deno.cron`, Nitro's Cloudflare schedule hook, and Netlify Scheduled Functions that run in Nitro's server bundle. A build writes only the output of its host: Nitro's resolved preset, or else `nitro.preset`, `NITRO_PRESET`, `SERVER_PRESET`, or `VITEHUB_HOST`. It writes the output of every host only when no host is known. Host selection, local execution, deployment proof, limits, and billing still come from the selected host. Check the [runtime and host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix) before deploying.
112
108
 
113
- Direct Nuxt projects can register `@vite-hub/schedule/nuxt` instead of `hubSchedule()`. The module installs the Vite integration and merges Schedule output into Nitro config.
109
+ Applications that use the framework distribution register Schedule through `vitehub({ host, schedule: true })` and import the definition helper from `vite-hub/schedule`. On Deno, the build writes standalone cron output and a `.output/main.ts` entrypoint that loads it before the Nitro server.
114
110
 
115
- ## Create a Runtime Schedule
111
+ Nuxt projects enable Schedule with `vite-hub/nuxt` and `vitehub: { schedule: true }`. The module installs the Vite integration and merges Schedule output into Nitro config.
116
112
 
117
- Define a cronless target for work that runs only through Runtime Schedules.
113
+ ## Start a Schedule from code
114
+
115
+ Leave out `cron` when your users pick the time, such as a reminder. Code then starts the Definition with `startSchedule()`, once at `at` or on a `cron` in a `timeZone`, and the handler gets `payload`.
118
116
 
119
117
  ```ts
120
- // server/schedules/report.ts
121
- import { defineScheduleTarget } from "@vite-hub/schedule";
118
+ // server/schedules/reminder.ts
119
+ import { defineSchedule } from "@vite-hub/schedule";
122
120
 
123
- export default defineScheduleTarget<{ prompt: string }>({
124
- async handler({ input }) {
125
- if (input) await generateReport(input.prompt);
121
+ export default defineSchedule({
122
+ handler({ payload }) {
123
+ console.log("Reminder", payload);
126
124
  },
127
125
  });
128
126
  ```
129
127
 
130
- Before creating the recurring record, install the Schedule runtime so it can load the discovered target registry and reconcile stored schedules. A custom host calls `installScheduleRuntime()` from `@vite-hub/schedule/runtime/driver` with its wake driver. A generated Process Runtime does this during application startup.
131
-
132
- After runtime installation completes, create the recurring record from server code.
133
-
134
128
  ```ts
135
- import { schedules } from "@vite-hub/schedule/runtime";
136
-
137
- const report = await schedules.create({
138
- cron: "30 8 * * 1-5",
139
- id: "weekday-report",
140
- input: { prompt: "Summarize yesterday" },
141
- target: "report",
142
- timeZone: "Europe/Copenhagen",
143
- });
129
+ import { cancelSchedule, listSchedules, startSchedule } from "@vite-hub/schedule";
144
130
 
145
- console.log(report.id);
131
+ const [error, reminder] = await startSchedule("reminder", { at: "2026-11-08T09:00:00Z", payload: { text: "Call Ana" } });
132
+ const [, standUp] = await startSchedule("reminder", { cron: "0 9 * * 1-5", timeZone: "Europe/Madrid", payload: { text: "Stand-up" } });
133
+ const [, started] = await listSchedules({ name: "reminder" });
134
+ await cancelSchedule(standUp!.id);
146
135
  ```
147
136
 
148
- The installed runtime can supply a native wake driver, or one long-lived process can install `createProcessScheduleWakeDriver()` from `@vite-hub/schedule/runtime/process`.
149
-
150
- Static provider cron output does not automatically wake Runtime Schedules. Provider-backed Runtime Schedules need a host-owned wake driver. Request-scoped and serverless hosts must not use the Process Runtime because the process may stop between requests.
137
+ The functions return `[error, data]`. The Schedules are stored in KV, so they survive restarts and deploys. When a Definition has no `cron`, the build adds the Schedule `vitehub/started-schedules` with the cron `* * * * *`: Cloudflare wakes it with a Cron Trigger, and the Process Runtime wakes it on Node. Each wake runs the started Schedules that are due. Started Schedules need KV, and on Node the Process Runtime. `vitehub schedule list`, `start`, and `cancel` and the Console Schedules page show and change them. Read the [server API](https://vitehub.dev/docs/schedule/server-api#start-a-schedule-from-code) for the delivery rules.
151
138
 
152
139
  ## Understand time zones
153
140
 
154
- Static Schedule Definitions and their Provider Output always use UTC. Runtime Schedules use UTC when `timeZone` is absent and accept IANA time-zone names when the cron must follow local clock time.
141
+ The value of `timeZone` must be an IANA name. Abbreviations such as `PST` and numeric offsets such as `+01:00` are rejected. The Process Runtime accepts any expression, such as a shared constant. Host cron output reads `timeZone` from the source file at build time, so write it as a string literal there. A dynamic value fails the build with `SCHEDULE_R0003`.
142
+
143
+ Cloudflare, Vercel, Netlify, and Deno read cron in UTC only. For a Schedule with a `timeZone`, the build writes a UTC cron that covers every offset of the time zone in the next two years, and the runtime checks the local time on each wake. `0 8 * * *` in `Europe/Madrid` becomes `0 6,7 * * *`: the host wakes the Schedule twice a day, and the Schedule runs at the wake that is 08:00 in Madrid. When a local time moves to another UTC day, the UTC cron wakes every day, or on the shifted weekdays, and the runtime checks the local date. A `cron` override in the build config replaces both the cron and the time zone: the host runs the override in UTC. Rebuild when a time zone changes its rules.
155
144
 
156
- Omitting `timeZone` during an update preserves the stored zone. Set it to `UTC` to return to UTC evaluation. Numeric offsets such as `+01:00` are rejected. During a daylight-saving gap, ViteHub skips a local time that does not exist. During an overlap, both distinct instants that share the repeated local time are due.
145
+ On daylight saving time changes, every host and the Process Runtime behave the same:
157
146
 
158
- ## Choose storage and wake ownership
147
+ - A local time that the clock skips runs once, shifted by the length of the gap, as RFC 5545 and `Temporal` read it. `30 2 * * *` in `Europe/Madrid` runs at 03:30 on the spring-forward day.
148
+ - A local time that occurs twice runs once, at its first occurrence, when the cron sets a fixed minute and hour. A cron with `*` in the minute or hour field runs on elapsed time, so it also runs in the repeated hour.
159
149
 
160
- Memory stores are the default for direct calls. They are process-local and lose Runtime Schedules and Schedule Run history on restart. Use `createKVRuntimeScheduleStore()` and `createKVScheduleRunStore()` when those records must survive a restart. The default KV-backed stores require `@vite-hub/kv`; custom stores can implement the public store interfaces instead.
150
+ ## Run a Schedule once per occurrence
161
151
 
162
- The generated Process Runtime creates both stores through the default KV store configured by `hubKv()`. It scans inside the Node.js process and runs discovered Static Schedule Definitions with stored Runtime Schedules. Configure it only for one long-lived replica:
152
+ Each run gets `idempotencyKey`, `schedule:<name>:<scheduledAt ISO>`. Cloudflare supplies the scheduled timestamp, and the Process Runtime records each occurrence. Repeated deliveries of those occurrences keep the same key. Pass the key to Email, a Channel `send()`, or a Queue on Vercel or the local driver to dedupe work with the same key:
153
+
154
+ ```ts fragment
155
+ export default defineSchedule({
156
+ cron: "0 7 * * *",
157
+ timeZone: "Europe/Stockholm",
158
+ async handler({ idempotencyKey }) {
159
+ await email.send({ from, to, subject: "Today's lesson", text, idempotencyKey });
160
+ },
161
+ });
162
+ ```
163
+
164
+ The Process Runtime also stores one run per occurrence, so it does not run a repeated wake again. Host cron output does not store runs.
165
+
166
+ Vercel, Netlify, and Deno do not supply a scheduled timestamp to these entries. They estimate `scheduledAt` as the latest host UTC cron match within the previous day, or the current minute when none matches. A late delivery or retry after another host cron match can get a different key. Time-zone filtering uses that estimate too: a summer Madrid 06:00 wake delivered after the extra 07:00 wake can be skipped. These hosts cannot guarantee occurrence identity or dedupe across that boundary. Use an application business key for side effects that must dedupe across delays and retries.
167
+
168
+ ## Run schedules in the server process
169
+
170
+ The generated Process Runtime runs each Static Schedule Definition on its cron inside the Node.js process. It records Schedule Runs in the default KV store configured by `hubKV()`. Use it on long-lived servers, one or more:
163
171
 
164
172
  ```ts
165
- import { hubKv } from "@vite-hub/kv/vite";
173
+ import { hubKV } from "@vite-hub/kv/vite";
166
174
  import { hubSchedule } from "@vite-hub/schedule/vite";
167
175
  import { defineConfig } from "vite";
168
176
 
169
177
  export default defineConfig({
170
178
  plugins: [
171
- hubKv(),
179
+ hubKV(),
172
180
  hubSchedule({
173
181
  runtime: {
174
182
  driver: "process",
@@ -179,17 +187,90 @@ export default defineConfig({
179
187
  });
180
188
  ```
181
189
 
182
- Its defaults are prefix `vitehub:schedule`, scan interval `60_000` milliseconds, and concurrency `1`. The interval cannot exceed one minute. `concurrency` limits wake delivery only inside that process. The KV run store records occurrences but does not provide distributed leader election or locking, so multiple replicas can execute the same work. A stopped process does not backfill minutes that it missed.
190
+ Its defaults are prefix `vitehub:schedule`, scan interval `60_000` milliseconds, concurrency `1`, catch-up `catchUpMs` of one hour, and `leaseTtlMs` of one minute. The interval cannot exceed one minute. `concurrency` limits runs only inside that process. A queued occurrence can start while its scheduled minute is within `catchUpMs` of the current minute; older queued work is dropped. With `catchUpMs: 0`, it can start only in its scheduled minute. After a restart, the runtime runs the due minutes that no process checked, within `catchUpMs`, for each Schedule that already has a run. Run ids are deterministic, so a minute that already ran does not run again. Request-scoped and serverless hosts must not use the Process Runtime because the process may stop between requests.
191
+
192
+ ### Run on more than one server
193
+
194
+ Every server checks every Schedule. Before a server runs an occurrence, it takes a lease on the key `<prefix>/schedule/<run id>`, such as `vitehub:schedule/schedule/srun_static_daily_2026-11-09T08:00:00.000Z`. The prefix is `runtime.prefix`, which defaults to `vitehub:schedule`. Use a different prefix for each app that shares a Database, and the same prefix on every server of one app. One server gets the lease and runs the occurrence while it holds that lease. The others skip it and try again at their next scan. Started Schedules use the same lease for each occurrence. Manual runs have their own run id, so the server that gets the request runs them once.
195
+
196
+ - The server that holds the lease renews it every third of `leaseTtlMs` while the run works. When the run ends, it writes a done marker (`<prefix>/schedule/<run id>/done`) and frees the lease. The marker lasts for `catchUpMs` plus `leaseTtlMs` plus two minutes, so a server that starts later does not run the occurrence again. If the marker write fails, the server reports the error and tries to extend its claim for the same time, without releasing it. If that also fails, another server can run the occurrence after the claim expires.
197
+ - If the server loses the Database, or its event loop pauses, for longer than `leaseTtlMs`, its lease can expire while its handler still runs. Another server can run the same occurrence at the same time. The runtime reports renewal failures, but cannot stop the handler or undo its effects. Choose a TTL longer than expected pauses and make external effects idempotent.
198
+ - If the lease store fails before a run starts, the server reports the error and retries at its next scan while the occurrence is inside `catchUpMs`.
199
+ - A failed run is final, as on one server. It is not retried.
200
+ - When a server stops during a run, for example after a crash, its lease ends after `leaseTtlMs`. Then another server runs the occurrence, unless it has a done marker. With shared run history, the run gets a new attempt, and the stopped attempt is marked as failed. This also works when every server restarts: at start, a server reads the runs inside `catchUpMs` that are still pending or running, and tries them again.
201
+
202
+ The generated runtime keeps the leases in the `vitehub_leases` table of the Default Database, through `useLeases()` from `@vite-hub/database`. That works on Postgres, remote libSQL, and D1. A local libSQL file is safe for one server process only, because `@libsql/client` can lose writes when several processes write to one file. The server prints a warning at the first lease in that case. Without a Database, the leases stay in memory and the build prints a warning: each server then runs every occurrence, so run one server only. The run history stays in KV. Use a KV store that all servers share, such as Upstash, so catch-up and the Console see the runs of every server.
203
+
204
+ With the Process Runtime, the default `providerOutput: "auto"` emits no host Provider Output, so the process owns Static Schedule wakes. Set `providerOutput: "standalone"` or `"nitro"` to move Static Schedule wakes to that Provider Output. `providerOutput: false` records the same wake ownership as `"auto"` in this configuration.
205
+
206
+ A custom long-running host can call `installProcessScheduleRuntime({ registry, scheduleRunStore, leases, prefix })` from `@vite-hub/schedule/runtime/process`. Pass the same shared `LeaseStore` and prefix to every process of one app. `prefix` defaults to `vitehub:schedule`; use the same prefix for the app's Schedule stores. Without `leases`, it uses `createMemoryLeaseStore()`, which is for one process only. Call and await `controller.close()` during shutdown. It waits for active runs and their `waitUntil()` work, then stops the timer. It does not delete Schedule Definitions or run history. The generated Nitro Process Runtime registers the same close operation with ViteHub shutdown. See [graceful shutdown](../runtime/README.md).
207
+
208
+ ## Install an OS timer
209
+
210
+ A CLI or a desktop tool has no server that stays on. `@vite-hub/schedule/os` installs the cron of a Schedule as a systemd timer on Linux, a launchd job on macOS, or a Task Scheduler task on Windows. The operating system then starts your command at each time.
211
+
212
+ ```ts
213
+ // src/cli.ts
214
+ import { defineSchedule } from "@vite-hub/schedule";
215
+ import { installOsSchedule } from "@vite-hub/schedule/os";
216
+
217
+ const photoSync = defineSchedule({
218
+ cron: "0 * * * *",
219
+ timeZone: "Europe/Madrid",
220
+ handler() {
221
+ console.log("Syncing photos");
222
+ },
223
+ });
224
+
225
+ const [error, unit] = await installOsSchedule("photo-sync", photoSync, {
226
+ command: [process.execPath, process.argv[1], "sync"],
227
+ });
228
+ if (error) throw error;
229
+ console.log(unit.changed ? unit.files : "The timer is up to date.");
230
+ ```
231
+
232
+ `command[0]` must be an absolute path. An install with the same input changes nothing. `unit.status()` and `unit.uninstall()` read and remove the timer. A cron or time zone that the OS cannot run exactly returns a typed error, such as `SCHEDULE_OS_TIME_ZONE_UNSUPPORTED`. Read [OS timers](https://vitehub.dev/docs/schedule/os-timers) for scopes, logs, catch-up, and time zones.
233
+
234
+ ## Choose storage
235
+
236
+ Schedule Runs record manual runs and Process Runtime runs. Provider cron output runs the handler without a run record.
237
+
238
+ The memory store is the default for direct calls. It is process-local and loses Schedule Run history on restart. Use `createKVScheduleRunStore({ kvStore })` when runs must survive a restart. The factory requires an explicit `ScheduleKVStorage`. To use ViteHub KV, install `@vite-hub/kv` and import the adapter explicitly:
239
+
240
+ ```ts
241
+ import { createKVScheduleRunStore } from "@vite-hub/schedule/runtime"
242
+ import { scheduleKVStorage } from "@vite-hub/schedule/runtime/kv"
243
+
244
+ const scheduleRunStore = createKVScheduleRunStore({ kvStore: scheduleKVStorage })
245
+ ```
246
+
247
+ Generated Process Runtime wiring selects this adapter automatically. Applications using the framework can import it from `vite-hub/schedule/runtime/kv`. Use `setScheduleRunStore(store)` to install a custom `ScheduleRunStore`.
248
+
249
+ Custom stores must apply the `listRuns({ scheduleId, idPrefix, limit })` filters before the limit. The Process Runtime requests `idPrefix: "srun_static_"` with `limit: 1` to read its newest cron run without loading manual run history.
250
+
251
+ ## Run and inspect schedules
252
+
253
+ `hubSchedule()` contributes the `schedule.runs`, `schedule.attempts`, `schedule.run`, `schedule.list`, `schedule.start`, and `schedule.cancel` operations. They are the `vitehub schedule runs <id> [--limit <n>]`, `attempts <runId>`, `run <name>`, `list [name]`, `start <name>`, and `cancel <id>` commands, and the Console runs them too. Each command accepts `--json` and `--url`. Without `--url` the command calls the dev server of the project, whose Nitro runtime owns the same stores and registry as the running app.
254
+
255
+ Set `manual: true` on a Static Schedule Definition to allow an on-demand run, then invoke it with `vitehub schedule run <name>`. The name is the discovered schedule file name. Add `--url <app-url>` to run it on a deployment that enables `console.invoke`. The command signs the call with `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>`, so a CI job needs only that secret. `vitehub secret console-key ci` prints a new key pair. Server code can call `runSchedule(name)` from `@vite-hub/schedule`. It reads the generated registry. Each manual run gets a new `srun_manual_` id.
256
+
257
+ Add `--at <ISO date-time>` to run it as if the cron fired at that time, for example `vitehub schedule run close-month --at 2026-01-31T23:59:00Z`. The handler gets the time as `scheduledAt`, and the run records it, so `vitehub schedule runs` lists it under that time. `runSchedule()` takes the same value as `scheduledAt`. The value needs `Z` or an offset. A value without a time zone, a date only, or a day that does not exist fails with `SCHEDULE_INVALID_SCHEDULED_AT` before the handler runs. The time is not checked against the cron. Manual runs do not advance the Process Runtime's catch-up cursor, even when their scheduled time is in the future.
258
+
259
+ Discovery reads `manual` as a literal boolean from directly exported Definitions. Use identifier keys or quoted keys without escape sequences. Spreads, computed keys, escaped keys, and metadata getters or methods fail with the source file and line.
260
+
261
+ The Console Schedules section lists Schedule Definitions with their cron, time zone, and manual state. It reads them at build time. When the server runs the Process Runtime, the cron and time zone come from the loaded Definitions on each request, so they are the values that the runtime uses. `vitehub inspect definitions` reads them from the source file and shows `Not a static string` for a value that it cannot read there. Use `vitehub schedule runs <name>` to list the runs that the runtime recorded. The CLI and the Console redact credentials in error messages.
262
+
263
+ ## Import runtime helpers
183
264
 
184
- With the Process Runtime, the default `providerOutput: "auto"` emits no host Provider Output, so the process owns Static Schedule wakes. Set `providerOutput: "standalone"` or `"nitro"` to move Static Schedule wakes to that Provider Output while the process continues to run Runtime Schedules. `providerOutput: false` explicitly records the same wake ownership as `"auto"` in this configuration.
265
+ The main `@vite-hub/schedule` entry exports `defineSchedule`, `runSchedule`, `startSchedule`, `getSchedule`, `listSchedules`, `cancelSchedule`, and public types. Import execution, storage, and runtime state helpers from `@vite-hub/schedule/runtime`. Import `installProcessScheduleRuntime` from `@vite-hub/schedule/runtime/process`. Import `installOsSchedule`, `osScheduleStatus`, and `uninstallOsSchedule` from `@vite-hub/schedule/os`. Import `discoverScheduleDefinitions` from `@vite-hub/schedule/vite` when writing a build integration. Applications use `vite-hub/schedule` and `vite-hub/schedule/runtime`.
185
266
 
186
- `installScheduleRuntime()` returns only after its driver reconciles the complete stored snapshot, including disabled Runtime Schedules. Later creates, updates, and deletes persist first and reconcile one at a time. If host reconciliation fails, ViteHub restores the previous stored record and rejects the change.
267
+ Static Schedule execution logs each failed handler as `[vitehub:schedule] Schedule "<name>" failed` with the message, stack, status, and cause chain. The other schedules on the same cron still finish. The run rejects with the error, or with an `AggregateError` when several failed.
187
268
 
188
- When a custom host installs a wake driver, call and await `controller.close()` during shutdown. Closing stops new wakes, drains active wakes and `waitUntil()` work, and releases driver resources. It does not delete Schedule Definitions, Runtime Schedules, or run history. The generated Nitro Process Runtime connects the same close operation to Nitro shutdown and process termination signals.
269
+ `executeSchedule()` accepts `captureHandlerFailure: true` to return the persisted failed run after a handler error. Pre-execution guards still throw.
189
270
 
190
271
  ## Documentation and support
191
272
 
192
- - Read the [Schedule guide](https://vitehub.dev/docs/server-primitives/schedule) for every public import, Runtime Helper, store, wake driver, and Vite option.
273
+ - Read the [Schedule guide](https://vitehub.dev/docs/schedule) for every public import, Runtime Helper, store, and Vite option.
193
274
  - Check [Provider Output](https://vitehub.dev/docs/reference/provider-output) for generated files and deployment inspection.
194
275
  - Check [runtime and host support](https://vitehub.dev/docs/frameworks-hosts/support-matrix) for current proof and host qualifications.
195
276
  - Report package problems in the [ViteHub issue tracker](https://github.com/vite-hub/vitehub/issues).
@@ -0,0 +1,330 @@
1
+ //#region ../internal/src/inspect.d.ts
2
+ interface ViteHubDefinitionField {
3
+ label: string;
4
+ value: string;
5
+ }
6
+ /** Serializable summary of one discovered Definition. Files are relative to the project root. */
7
+ interface ViteHubDefinitionSummary {
8
+ fields: readonly ViteHubDefinitionField[];
9
+ file: string;
10
+ name: string;
11
+ source: string;
12
+ }
13
+ /** Lists the Definitions that one owner package discovered for the resolved Vite config. */
14
+ interface ViteHubDefinitionInspector {
15
+ /** Stable singular kind, for example `queue` or `rate-limit`. */
16
+ kind: string;
17
+ label: string;
18
+ list: () => Promise<readonly ViteHubDefinitionSummary[]> | readonly ViteHubDefinitionSummary[];
19
+ }
20
+ /** One generated Provider Output file or directory that an owner package can write. */
21
+ interface ViteHubProviderOutputEntry {
22
+ description: string;
23
+ owner: string;
24
+ /** Absolute path. */
25
+ path: string;
26
+ }
27
+ /**
28
+ * Where an inspected resource id came from. `name` means the host binds the resource by its name and needs no id.
29
+ * The CLI sets `provider-output` when only a generated Wrangler config names the id.
30
+ */
31
+ type ViteHubResourceIdSource = "config" | "env" | "name" | "provider-output" | "provision-state";
32
+ /** One host resource that a Definition or store maps to. Owner packages read only local config and Provision State. */
33
+ interface ViteHubResourceSummary {
34
+ /** Cloudflare binding name, so the CLI can find the id in generated Wrangler config. */
35
+ binding?: string;
36
+ /** Definition or store name. */
37
+ definition: string;
38
+ /** Env variable that supplied the id when `source` is `env`. */
39
+ env?: string;
40
+ host: "cloudflare" | "vercel";
41
+ id?: string;
42
+ /** Same resource kind names as Provision actions, for example `cloudflare-d1`. */
43
+ kind: string;
44
+ /** Resource name on the host, when the config names it. */
45
+ name?: string;
46
+ /** Explains how the host finds the resource when no id or name is known locally. */
47
+ note?: string;
48
+ owner: string;
49
+ /** Absent when no id is known yet. */
50
+ source?: ViteHubResourceIdSource;
51
+ }
52
+ interface ViteHubInspectionContributor {
53
+ definitions?: readonly ViteHubDefinitionInspector[];
54
+ providerOutput?: readonly ViteHubProviderOutputEntry[];
55
+ resources?: () => readonly ViteHubResourceSummary[] | Promise<readonly ViteHubResourceSummary[]>;
56
+ }
57
+ type ViteHubInspectionContributorFactory = () => ViteHubInspectionContributor | undefined | Promise<ViteHubInspectionContributor | undefined>;
58
+ interface ViteHubInspectionPluginMetadata {
59
+ inspect?: ViteHubInspectionContributor | ViteHubInspectionContributorFactory;
60
+ }
61
+ //#endregion
62
+ //#region ../internal/src/console.d.ts
63
+ type MaybePromise<T> = T | Promise<T>;
64
+ /** Lists discovered Definitions in a sidebar and shows the selected Definition's fields. */
65
+ interface ViteHubConsoleDefinitionCatalogView {
66
+ kind: "definition-catalog";
67
+ /** States which runtime data this catalog does not include. */
68
+ notice: string;
69
+ }
70
+ /** Lists Workspace Definitions like a catalog, and browses the refs, revisions, and files of the selected one. */
71
+ interface ViteHubConsoleWorkspaceBrowserView {
72
+ kind: "workspace-browser";
73
+ /** States which runtime data the browser does not include. */
74
+ notice: string;
75
+ }
76
+ interface ViteHubConsoleRecordColumn {
77
+ /** Set it for a column with few values, such as a status. The Console then filters the table by its values. */
78
+ filter?: boolean;
79
+ /** Key in `ViteHubConsoleRecord.cells`. */
80
+ key: string;
81
+ label: string;
82
+ }
83
+ /** Shows records in a table and the selected record's fields in a detail panel. */
84
+ interface ViteHubConsoleRecordTableView {
85
+ columns: readonly ViteHubConsoleRecordColumn[];
86
+ kind: "record-table";
87
+ /** States the source and limits of the records. */
88
+ notice: string;
89
+ }
90
+ /**
91
+ * Lists the collections and documents of an owner runtime and edits them with owner actions: a form generated from each
92
+ * collection's JSON Schema, a Markdown body, save, publish, and revision history.
93
+ */
94
+ interface ViteHubConsoleDocumentEditorView {
95
+ kind: "document-editor";
96
+ /** States where documents are stored and what the editor does not do. */
97
+ notice: string;
98
+ }
99
+ interface ViteHubConsoleOperationColumn {
100
+ /** Dot path into each item of the result, such as `author.name` or `messages.0.body`. */
101
+ key: string;
102
+ label: string;
103
+ /**
104
+ * `datetime` shows a time in milliseconds since the epoch as a relative date, such as `5m ago`. `excerpt` cuts a long
105
+ * text. `status` shows the value as a status with a colored dot, such as `Open`. `tones` picks the color of each value.
106
+ * `switch` shows a boolean as a switch that calls the `switch` operation.
107
+ */
108
+ format?: "datetime" | "excerpt" | "status" | "switch";
109
+ /** The color of each value of a `status` column, such as `{ open: "info", resolved: "success" }`. Other values are neutral. */
110
+ tones?: Readonly<Record<string, "error" | "info" | "neutral" | "success" | "warning">>;
111
+ /**
112
+ * What a `switch` column calls when the user flips it: `operation` with an input that maps each key of `input` to a
113
+ * dot path of the item, and the column `key` to the new value. `{ operation: "skills.set", input: { name: "name" } }`
114
+ * on the column `enabled` calls `skills.set` with `{ name, enabled }`, then loads the list again. A user who may only
115
+ * read the section sees the switch disabled.
116
+ */
117
+ switch?: {
118
+ operation: string;
119
+ input: Readonly<Record<string, string>>;
120
+ };
121
+ }
122
+ /**
123
+ * A button on each row that calls `operation` with the Console user, then loads the list again. `input` maps each input
124
+ * key to a dot path of the item, as a `switch` column does.
125
+ */
126
+ interface ViteHubConsoleOperationAction {
127
+ label: string;
128
+ operation: string;
129
+ input: Readonly<Record<string, string>>;
130
+ /**
131
+ * The result is `{ url }`, such as a one-time link or a provider sign-in: the Console opens it in a new tab, and loads
132
+ * the list again when the person comes back. The URL must be `https:`, or `http:` on a loopback host.
133
+ */
134
+ tab?: true;
135
+ /** Show the button only on rows where each dot path holds one of the listed values. */
136
+ when?: Readonly<Record<string, readonly string[]>>;
137
+ /** Ask this question before the call. `{path}` takes a value from the item. */
138
+ confirm?: string;
139
+ }
140
+ /** A chip above the list. Choosing it merges `input` into the operation input. The first chip is the default. */
141
+ interface ViteHubConsoleOperationFilter {
142
+ id: string;
143
+ label: string;
144
+ input: Readonly<Record<string, unknown>>;
145
+ }
146
+ /**
147
+ * Lists the items that an operation returns, called over the Console RPC with the signed-in Console user. The operation
148
+ * checks the access of that user for each item, so the view shows only what the user may read. `operation` must return an
149
+ * array of objects with an `id`. A failure of the operation, with its `fix`, shows where the list would be.
150
+ */
151
+ interface ViteHubConsoleOperationView {
152
+ /** Buttons on each row. A user who may only read the section does not see them. */
153
+ actions?: readonly ViteHubConsoleOperationAction[];
154
+ columns: readonly ViteHubConsoleOperationColumn[];
155
+ /**
156
+ * Opens the item of a row in a side panel. `comment-thread` shows an item of `comments.list` as a comment thread
157
+ * where the user reads, replies, resolves, reopens, and mentions people. The panel calls the `comments.*` operations
158
+ * with the Console user, and `?thread=<id>` in the URL opens it.
159
+ */
160
+ detail?: {
161
+ kind: "comment-thread";
162
+ };
163
+ filters?: readonly ViteHubConsoleOperationFilter[];
164
+ kind: "operation-view";
165
+ /**
166
+ * Makes each row a link: `{path}` placeholders take values from the item and are URL-encoded, and `{path:path}` takes an
167
+ * app path and encodes each segment (a value that is not an app path, such as `//evil.com/x`, gives no link).
168
+ * `{path:href}` takes an app URL that is already encoded, with its query, as it is. Rows where `when.path` is not
169
+ * `when.equals` get none.
170
+ */
171
+ link?: {
172
+ label?: string;
173
+ template: string;
174
+ when?: {
175
+ equals: string;
176
+ path: string;
177
+ };
178
+ };
179
+ notice: string;
180
+ /** Operation name, such as `comments.list`. */
181
+ operation: string;
182
+ /** Fetch every page with `limit` and a `before` object whose keys read these dot paths from the last item. */
183
+ pagination?: {
184
+ limit: number;
185
+ cursor: Readonly<Record<string, string>>;
186
+ };
187
+ }
188
+ interface ViteHubConsoleAuthView {
189
+ kind: "auth-management";
190
+ notice: string;
191
+ }
192
+ /**
193
+ * The webhooks of the app, their pending debounce timers, and their delivery log. The Console calls the `webhooks.*`
194
+ * operations of `@vite-hub/webhooks` with the Console user to list them, send a test, send a pending delivery now,
195
+ * cancel it, and redeliver. It has no build-time data.
196
+ */
197
+ interface ViteHubConsoleWebhooksView {
198
+ kind: "webhooks";
199
+ notice: string;
200
+ }
201
+ type ViteHubConsoleSectionView = ViteHubConsoleOperationView | ViteHubConsoleAuthView | ViteHubConsoleWebhooksView | ViteHubConsoleDefinitionCatalogView | ViteHubConsoleRecordTableView | ViteHubConsoleDocumentEditorView | ViteHubConsoleWorkspaceBrowserView;
202
+ /**
203
+ * The overview of a document editor section: document counts by state, the changes that wait for a publish, recent
204
+ * activity, and a New button per collection. It reads the owner `overview` action.
205
+ */
206
+ interface ViteHubConsoleDocumentDashboardView {
207
+ kind: "document-dashboard";
208
+ }
209
+ /**
210
+ * The media library of a document editor section: folders, uploads, alt text, focal points, and crops of the Blob Store
211
+ * that `blob.serve` serves. The owner decides who may use it with `mediaAccess`, and finds the documents that use a file
212
+ * with `references`. The page needs the Blob section, so declare it with `requires: ["blob"]`.
213
+ */
214
+ interface ViteHubConsoleMediaLibraryView {
215
+ kind: "media-library";
216
+ }
217
+ /**
218
+ * The singletons of a document editor section, such as site settings: one row per singleton that opens it in the
219
+ * editor. Singletons appear here instead of among the collections, and the Console hides the page when the section has
220
+ * none.
221
+ */
222
+ interface ViteHubConsoleDocumentSettingsView {
223
+ kind: "document-settings";
224
+ }
225
+ /** A view that the Console UI in `vite-hub` renders for a section page. */
226
+ type ViteHubConsoleSectionPageView = ViteHubConsoleDocumentDashboardView | ViteHubConsoleDocumentSettingsView | ViteHubConsoleMediaLibraryView;
227
+ /**
228
+ * A page of a section next to its main view, such as the Content dashboard or media library. The section sidebar lists
229
+ * the pages, and each page has its own URL:
230
+ *
231
+ * - `/_vitehub/<section>` serves the `index` page, or the main view when the section has none.
232
+ * - `/_vitehub/<section>/-/<page>` serves every other page. The `-` segment keeps page URLs apart from the main view's
233
+ * own segments, such as a collection name.
234
+ *
235
+ * Pages share the access of their section: `console.authorize` that allows the section allows every page of it.
236
+ */
237
+ interface ViteHubConsoleSectionPage {
238
+ /** Lowercase route segment, for example `media`. */
239
+ id: string;
240
+ /** Display name, for example `Media`. */
241
+ label: string;
242
+ /** Iconify class name, for example `i-lucide-image`. */
243
+ icon: string;
244
+ view: ViteHubConsoleSectionPageView;
245
+ /**
246
+ * Serve this page at the section root. At most one page sets it, and `/_vitehub/<section>/-/<id>` then redirects to
247
+ * the root.
248
+ */
249
+ index?: boolean;
250
+ /**
251
+ * Sidebar heading, for example `Assets`. Pages without a group lead the sidebar, above the main view's navigation.
252
+ * Grouped pages follow it, in the order their group first appears.
253
+ */
254
+ group?: string;
255
+ /** Section ids that the project must enable, such as `["blob"]`. The Console leaves the page out otherwise. */
256
+ requires?: readonly string[];
257
+ }
258
+ /** One entry of a record's activity, such as a comment in a thread. `at` is an ISO 8601 timestamp. */
259
+ interface ViteHubConsoleRecordActivity {
260
+ author: string;
261
+ at: string;
262
+ text: string;
263
+ }
264
+ /** One serializable record row. Values are display strings. Do not put credentials in records. */
265
+ interface ViteHubConsoleRecord {
266
+ cells: Readonly<Record<string, string>>;
267
+ fields: readonly ViteHubDefinitionField[];
268
+ id: string;
269
+ /** The Console can run this record when it represents a runnable Schedule Definition. */
270
+ runnable?: boolean;
271
+ /**
272
+ * Where the record lives in the app, such as the page of a comment thread. `href` is an app path that starts with one
273
+ * `/`, or an `https:` URL. The Console opens it in a new tab.
274
+ */
275
+ link?: {
276
+ href: string;
277
+ label: string;
278
+ };
279
+ /** Entries in time order, such as the comments of a thread. The Console shows them as a conversation. */
280
+ activity?: readonly ViteHubConsoleRecordActivity[];
281
+ }
282
+ /** Serializable description of a Console section. The Console UI in `vite-hub` renders the view. */
283
+ interface ViteHubConsoleSectionDescriptor<TView extends ViteHubConsoleSectionView = ViteHubConsoleSectionView> {
284
+ description: string;
285
+ /**
286
+ * Iconify class name, for example `i-lucide-inbox`. The Console draws with Lucide; `ph` also resolves. The
287
+ * Console build bundles the icon of every section in the `vite-hub` Console registry and fails if it cannot resolve one.
288
+ */
289
+ icon: string;
290
+ /** Lowercase route segment, for example `queues`. The Console serves the section at `/_vitehub/<id>`. */
291
+ id: string;
292
+ /** Plural display name, for example `Queues`. */
293
+ label: string;
294
+ view: TView;
295
+ /** Pages next to the main view, in sidebar order. Only document editor sections render pages today. */
296
+ pages?: readonly ViteHubConsoleSectionPage[];
297
+ }
298
+ /** A named export of an owner package server module that the host imports in its generated server code. */
299
+ interface ViteHubConsoleServerExport {
300
+ /** Named export of `module`. */
301
+ export: string;
302
+ /**
303
+ * Absolute path of the owner module, such as `ownModule(import.meta.url, "runtime/console")`, or an owner package
304
+ * specifier that the host maps to a module path that the application can import.
305
+ */
306
+ module: string;
307
+ }
308
+ /**
309
+ * Server module export that returns records on each Console request. The export must be a
310
+ * {@link ViteHubConsoleRuntimeRecordReader}.
311
+ */
312
+ interface ViteHubConsoleRuntimeReader extends ViteHubConsoleServerExport {}
313
+ /**
314
+ * A record table that also reads records at request time. The Console shows the build-time records of `read` first,
315
+ * then the records of the `runtime` reader. A runtime record updates the build-time record with the same id: its cells
316
+ * and fields replace the build-time ones with the same key or label.
317
+ */
318
+ interface ViteHubConsoleRuntimeRecordTableSection<TOptions = void> extends ViteHubConsoleSectionDescriptor<ViteHubConsoleRecordTableView> {
319
+ /** Reads build-time records on the server. When omitted, the section has only runtime records. */
320
+ read?: (options: TOptions) => MaybePromise<readonly ViteHubConsoleRecord[]>;
321
+ runtime: ViteHubConsoleRuntimeReader;
322
+ /**
323
+ * Returns the absolute path of the application module that turns the section on, such as `server/comments.ts`, or
324
+ * `undefined` when the project has none. With it, the host shows the section only when the module exists; without
325
+ * it, a Vite option enables the section.
326
+ */
327
+ entry?: (options: TOptions) => MaybePromise<string | undefined>;
328
+ }
329
+ //#endregion
330
+ export { ViteHubInspectionPluginMetadata as i, ViteHubConsoleRuntimeRecordTableSection as n, ViteHubDefinitionSummary as r, ViteHubConsoleRecord as t };