@vite-hub/schedule 0.7.0 → 0.8.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.
package/README.md CHANGED
@@ -196,11 +196,11 @@ Its defaults are prefix `vitehub:schedule`, scan interval `60_000` milliseconds,
196
196
 
197
197
  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.
198
198
 
199
- - 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.
200
- - 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.
199
+ - The server that holds the lease renews it every third of `leaseTtlMs`, from the time it gets the lease until the run ends. 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. A server that reads the done marker at or after `catchUpMs` plus `leaseTtlMs` plus two minutes after the scheduled minute does not run the occurrence, because a missing marker no longer proves that it did not run.
200
+ - If the server loses the Database, or its event loop pauses, for two thirds of `leaseTtlMs` or longer, its lease can expire while its handler still runs. A renewal starts a third of `leaseTtlMs` after the previous one, so a renewal that waits for the rest of the TTL comes too late. 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 one and a half times the longest expected pause, and make external effects idempotent.
201
201
  - 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`.
202
202
  - A failed run is final, as on one server. It is not retried.
203
- - 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. A server that found the lease held tries the occurrence again until `catchUpMs` plus `leaseTtlMs` plus one minute after its scheduled minute, also with `catchUpMs: 0`. 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.
203
+ - 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. A server that found the lease held tries the occurrence again until `catchUpMs` plus `leaseTtlMs` plus one minute after its scheduled minute, also with `catchUpMs: 0`. With shared run history, the run gets a new attempt, and the stopped attempt is marked as failed. So a handler that started before the stop runs again: a Schedule occurrence runs at least once, not exactly once, when a server stops after its handler starts and before it saves the end of the run. 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.
204
204
 
205
205
  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, with postgres.js or node-postgres, remote libSQL, and D1. With `VITEHUB_INSTANCES` greater than 1, a Node server with a Postgres or remote libSQL Default Database reports Schedule as `shared` at boot. 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 reports the hint `SCHEDULE_PROCESS_CLAIMS_IN_MEMORY` in its output and in `.vitehub/hints.json`: 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.
206
206
 
@@ -1,5 +1,5 @@
1
1
  import { t as isIanaTimeZone } from "./time-zone-pMp_g8Uu.js";
2
- import { t as isRecord } from "./object-CAK6UYR5.js";
2
+ import { n as isRecord } from "./object-DNOrQSl5.js";
3
3
  import { t as assertScheduleCronFields } from "./cron-D0mqg3ql.js";
4
4
  import { t as scheduleErrorDiagnostics } from "./error-diagnostics-KvK9MX6w.js";
5
5
  // src/definition.ts
@@ -1,6 +1,6 @@
1
- import { C as createScheduleError, S as validateScheduledAt, _ as emitLogEvent, b as parseScheduledAt, c as markLoggedScheduleError, d as normalizeScheduleRuntimeError, g as logScheduleRun, h as runWithScheduleWaitUntil, v as errorCode, x as scheduleIdempotencyKey } from "./static--wi-oIIb.js";
2
- import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
3
- import { i as getScheduleRunStore } from "./state-CcVY3UzB.js";
1
+ import { C as createScheduleError, S as validateScheduledAt, _ as emitLogEvent, b as parseScheduledAt, c as markLoggedScheduleError, d as normalizeScheduleRuntimeError, g as logScheduleRun, h as runWithScheduleWaitUntil, v as errorCode, x as scheduleIdempotencyKey } from "./static-D4nN8HTx.js";
2
+ import { r as isRecordOrFunction } from "./object-DNOrQSl5.js";
3
+ import { i as getScheduleRunStore } from "./state-BoDrff6R.js";
4
4
  import { serializeResponse, toResponse } from "@vite-hub/runtime/internal/response";
5
5
  import { emitRunFailed, toRunFailedError } from "@vite-hub/runtime/internal/run-failed";
6
6
  import { runInRunScopes } from "@vite-hub/runtime/internal/run-scope";
package/dist/index.d.ts CHANGED
@@ -42,6 +42,10 @@ type StartedScheduleErrorCodes = {
42
42
  name: string;
43
43
  }) => string;
44
44
  };
45
+ SCHEDULE_RUNTIME_INSTALL_FAILED: {
46
+ fix: string;
47
+ why: string;
48
+ };
45
49
  SCHEDULE_STORE_FAILED: {
46
50
  fix: string;
47
51
  why: string;
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  import { defineSchedule } from "./definition.js";
2
- import { i as startSchedule, n as getSchedule, o as runSchedule, r as listSchedules, t as cancelSchedule } from "./started-ClJ5XOWH.js";
2
+ import { i as startSchedule, n as getSchedule, o as runSchedule, r as listSchedules, t as cancelSchedule } from "./started-Ck0Wu5Oc.js";
3
3
  export { cancelSchedule, defineSchedule, getSchedule, listSchedules, runSchedule, startSchedule };
@@ -3,8 +3,12 @@
3
3
  function isRecord(value) {
4
4
  return typeof value === "object" && value !== null && !Array.isArray(value);
5
5
  }
6
+ /** A non-null object. Arrays pass. Functions do not. */
7
+ function isObject(value) {
8
+ return typeof value === "object" && value !== null;
9
+ }
6
10
  /** A non-null object or a function that is not an array. */
7
11
  function isRecordOrFunction(value) {
8
12
  return Object(value) === value && !Array.isArray(value);
9
13
  }
10
- export { isRecordOrFunction as n, isRecord as t };
14
+ export { isRecord as n, isRecordOrFunction as r, isObject as t };
@@ -1,9 +1,9 @@
1
1
  import { t as redactInspectionText } from "./inspect-CW0qwt9p.js";
2
2
  import { t as scheduleErrorDiagnostics } from "./error-diagnostics-KvK9MX6w.js";
3
- import { C as createScheduleError } from "./static--wi-oIIb.js";
4
- import { a as loadScheduleRegistry, i as startSchedule, r as listSchedules, t as cancelSchedule } from "./started-ClJ5XOWH.js";
5
- import { a as loadStaticScheduleDefinition, s as runScheduleFrom } from "./execute-DoQC2i_V.js";
6
- import { i as getScheduleRunStore, n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime, t as getHostScheduleInventory } from "./state-CcVY3UzB.js";
3
+ import { C as createScheduleError } from "./static-D4nN8HTx.js";
4
+ import { a as loadScheduleRegistry, i as startSchedule, r as listSchedules, t as cancelSchedule } from "./started-Ck0Wu5Oc.js";
5
+ import { a as loadStaticScheduleDefinition, s as runScheduleFrom } from "./execute-DHApCpbQ.js";
6
+ import { g as waitForProcessScheduleRuntime, i as getScheduleRunStore, n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime, t as getHostScheduleInventory } from "./state-BoDrff6R.js";
7
7
  // src/runtime/operations.ts
8
8
  function isoDate(value) {
9
9
  if (value === void 0) return;
@@ -122,10 +122,14 @@ async function attempt(work) {
122
122
  }
123
123
  }
124
124
  async function runScheduleRuns(input) {
125
- return await attempt(async () => ({ runs: await listScheduleRuns(input.id, { limit: input.limit ?? 100 }) }));
125
+ return await attempt(async () => {
126
+ await waitForProcessScheduleRuntime();
127
+ return { runs: await listScheduleRuns(input.id, { limit: input.limit ?? 100 }) };
128
+ });
126
129
  }
127
130
  async function runScheduleAttempts(input) {
128
131
  return await attempt(async () => {
132
+ await waitForProcessScheduleRuntime();
129
133
  const run = await getScheduleRunStore().getRun(input.id);
130
134
  if (!run) throw scheduleErrorDiagnostics.SCHEDULE_RUN_NOT_FOUND();
131
135
  return {
@@ -141,6 +145,7 @@ const consoleSchedulesKey = Symbol.for("vitehub.console.schedules");
141
145
  */
142
146
  async function runScheduleNow(input, registry = Reflect.get(globalThis, consoleSchedulesKey) ?? {}) {
143
147
  return await attempt(async () => {
148
+ await waitForProcessScheduleRuntime();
144
149
  if (!Object.hasOwn(registry, input.name)) {
145
150
  const definitions = await loadScheduleRegistry().catch((cause) => {
146
151
  throw scheduleErrorDiagnostics.SCHEDULE_DEFINITION_NOT_FOUND({ cause });
@@ -167,6 +172,7 @@ const startedErrorStatus = {
167
172
  SCHEDULE_INVALID_OPTIONS: 400,
168
173
  SCHEDULE_NOT_FOUND: 404,
169
174
  SCHEDULE_NOT_STARTABLE: 404,
175
+ SCHEDULE_RUNTIME_INSTALL_FAILED: 503,
170
176
  SCHEDULE_STORE_FAILED: 503,
171
177
  SCHEDULE_STORE_MISSING: 503
172
178
  };
@@ -189,6 +195,7 @@ async function listStaticSchedules(filter) {
189
195
  * for started Schedules, so it lists only its Definitions.
190
196
  */
191
197
  async function runScheduleList(input) {
198
+ await waitForProcessScheduleRuntime();
192
199
  const definitions = await listStaticSchedules(input.name);
193
200
  if (!getStartedScheduleRuntime()) return {
194
201
  definitions,
@@ -1,4 +1,4 @@
1
- import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
1
+ import { r as isRecordOrFunction } from "./object-DNOrQSl5.js";
2
2
  import { t as internalErrorDiagnostics } from "./error-diagnostics-CsiNo_oI.js";
3
3
  import { toJsonSchema } from "@valibot/to-json-schema";
4
4
  import * as v from "valibot";
@@ -139,7 +139,7 @@ function table(rows) {
139
139
  return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ")).join("\n");
140
140
  }
141
141
  // src/operations.ts
142
- const runtime = () => import("./operations-CEZCefAG.js");
142
+ const runtime = () => import("./operations-Bog78pOZ.js");
143
143
  const id = v.pipe(v.string(), v.minLength(1));
144
144
  function formatRuns({ runs }) {
145
145
  if (runs.length === 0) return "No runs.\n";
package/dist/os.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as isRecord } from "./object-CAK6UYR5.js";
1
+ import { n as isRecord } from "./object-DNOrQSl5.js";
2
2
  import { t as isIanaTimeZone } from "./time-zone-pMp_g8Uu.js";
3
3
  import { a as parseCronFields, c as timesOfDay, i as isWeekdayRestricted, n as isDayRestricted, o as range, r as isMonthRestricted, s as runsEveryDay, t as arithmeticStep, u as invariantError } from "./cron-imqlBgO-.js";
4
4
  import { i as timeZoneOffsetMinutes } from "./due-DXgXKgzg.js";
@@ -1,5 +1,5 @@
1
- import { n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime } from "../state-CcVY3UzB.js";
2
- import { o as resolveManualSchedule } from "../execute-DoQC2i_V.js";
1
+ import { g as waitForProcessScheduleRuntime, n as getProcessScheduleDefinitions, o as getStartedScheduleRuntime } from "../state-BoDrff6R.js";
2
+ import { o as resolveManualSchedule } from "../execute-DHApCpbQ.js";
3
3
  // src/runtime/console.ts
4
4
  const consoleSchedulesKey = Symbol.for("vitehub.console.schedules");
5
5
  /** The Cron column of the Console: the cron, with the time zone when it is not UTC. */
@@ -61,6 +61,7 @@ function startedScheduleRecord(schedule) {
61
61
  * build checked.
62
62
  */
63
63
  async function readScheduleConsoleRecords() {
64
+ await waitForProcessScheduleRuntime();
64
65
  const registry = Reflect.get(globalThis, consoleSchedulesKey) ?? {};
65
66
  const definitions = getProcessScheduleDefinitions();
66
67
  const candidates = await Promise.all(Object.keys(registry).map((name) => resolveManualSchedule(registry, name).then(() => name, () => void 0)));
@@ -1,11 +1,11 @@
1
- import { n as isRecordOrFunction } from "../object-CAK6UYR5.js";
1
+ import { r as isRecordOrFunction } from "../object-DNOrQSl5.js";
2
+ import { C as createScheduleError, _ as emitLogEvent, c as markLoggedScheduleError, x as scheduleIdempotencyKey } from "../static-D4nN8HTx.js";
2
3
  import { n as parseScheduleCronExpression } from "../cron-D0mqg3ql.js";
3
4
  import { n as isScheduleDue } from "../due-DXgXKgzg.js";
4
5
  import { t as scheduleErrorDiagnostics } from "../error-diagnostics-KvK9MX6w.js";
5
- import { C as createScheduleError, c as markLoggedScheduleError, x as scheduleIdempotencyKey } from "../static--wi-oIIb.js";
6
- import { c as toRunId, i as executeStaticSchedule } from "../execute-DoQC2i_V.js";
7
- import { i as runStartedSchedules } from "../started-yb49f37g.js";
8
- import { a as getScheduleRuntimeRegistry, c as registerProcessScheduleDefinitions, d as setScheduleOccurrenceClaims, f as setScheduleRunStore, i as getScheduleRunStore, p as setScheduleRuntimeRegistry, r as getScheduleOccurrenceClaims } from "../state-CcVY3UzB.js";
6
+ import { c as toRunId, i as executeStaticSchedule } from "../execute-DHApCpbQ.js";
7
+ import { i as runStartedSchedules } from "../started-adRbWkWd.js";
8
+ import { a as getScheduleRuntimeRegistry, c as registerProcessScheduleDefinitions, d as setProcessScheduleRuntimeInstallation, f as setScheduleOccurrenceClaims, i as getScheduleRunStore, m as setScheduleRuntimeRegistry, p as setScheduleRunStore, r as getScheduleOccurrenceClaims } from "../state-BoDrff6R.js";
9
9
  import { createMemoryLeaseStore, getInstanceId } from "@vite-hub/runtime";
10
10
  import { onShutdown } from "@vite-hub/runtime/internal/shutdown";
11
11
  // src/internal/process-wake-runtime.ts
@@ -241,26 +241,26 @@ function createOccurrenceClaims(options) {
241
241
  const ttl = options.ttlMs / 1e3;
242
242
  const doneTtl = options.doneTtlMs / 1e3;
243
243
  const owner = options.owner === void 0 ? {} : { owner: options.owner };
244
- return { async run(runId, run) {
244
+ return { async run(runId, run, runOptions) {
245
245
  const [acquireError, lease] = await options.leases.acquire(occurrenceLeaseKey(runId, options.prefix), {
246
246
  ttl,
247
247
  ...owner
248
248
  });
249
249
  if (acquireError) throw acquireError;
250
250
  if (!lease) return "held";
251
+ const stop = keepAlive(lease, options.ttlMs, options.reportError);
251
252
  let release = true;
252
253
  try {
253
254
  const [doneError, done] = await options.leases.get(occurrenceDoneKey(runId, options.prefix));
254
255
  if (doneError) throw doneError;
255
256
  if (done) return "done";
256
- const stop = keepAlive(lease, options.ttlMs, options.reportError);
257
+ if (runOptions?.scheduledAt && (options.now?.() ?? /* @__PURE__ */ new Date()).getTime() >= runOptions.scheduledAt.getTime() + options.doneTtlMs) return "late";
257
258
  let final = false;
258
259
  try {
259
260
  await run(() => {
260
261
  final = true;
261
262
  });
262
263
  } finally {
263
- await stop();
264
264
  if (final) {
265
265
  const [markError, marked] = await options.leases.acquire(occurrenceDoneKey(runId, options.prefix), {
266
266
  ttl: doneTtl,
@@ -268,6 +268,7 @@ function createOccurrenceClaims(options) {
268
268
  });
269
269
  if (markError) {
270
270
  release = false;
271
+ await stop();
271
272
  options.reportError(markError);
272
273
  const [renewError, renewed] = await lease.renew({ ttl: doneTtl });
273
274
  if (renewError) options.reportError(renewError);
@@ -277,6 +278,7 @@ function createOccurrenceClaims(options) {
277
278
  }
278
279
  return "ran";
279
280
  } finally {
281
+ await stop();
280
282
  if (release) {
281
283
  const [releaseError] = await lease.release();
282
284
  if (releaseError) options.reportError(releaseError);
@@ -355,7 +357,25 @@ function resolveLeaseTtlMs(value) {
355
357
  * checked, within `catchUpMs`, for Schedules with a prior cron-triggered run or indeterminate legacy history.
356
358
  * Processes that share `leases` run each occurrence once between them. Call `close()` during host shutdown.
357
359
  */
358
- async function installProcessScheduleRuntime(options) {
360
+ function installProcessScheduleRuntime(options) {
361
+ const startedAt = performance.now();
362
+ const installation = installRuntime(options);
363
+ setProcessScheduleRuntimeInstallation(installation);
364
+ installation.then(() => {
365
+ const ms = Math.round(performance.now() - startedAt);
366
+ if (!emitLogEvent({
367
+ field: "schedule",
368
+ fields: {
369
+ op: "install",
370
+ ms
371
+ },
372
+ level: "info",
373
+ message: "Schedule runtime installed"
374
+ })) console.info(`[vitehub:schedule] runtime installed in ${ms} ms`);
375
+ }, () => {});
376
+ return installation;
377
+ }
378
+ async function installRuntime(options) {
359
379
  const previousRegistry = getScheduleRuntimeRegistry();
360
380
  const previousScheduleRunStore = getScheduleRunStore();
361
381
  const previousClaims = getScheduleOccurrenceClaims();
@@ -365,6 +385,7 @@ async function installProcessScheduleRuntime(options) {
365
385
  const claims = createOccurrenceClaims({
366
386
  doneTtlMs: catchUpMs + leaseTtlMs + 2 * minuteMs,
367
387
  leases: options.leases ?? createMemoryLeaseStore(),
388
+ now: options.now,
368
389
  owner: getInstanceId(),
369
390
  prefix: options.prefix,
370
391
  reportError,
@@ -429,7 +450,7 @@ async function installProcessScheduleRuntime(options) {
429
450
  },
430
451
  scheduledAt: input.scheduledAt,
431
452
  waitUntil
432
- })) === "held") held.set(runId, {
453
+ }), { scheduledAt: input.scheduledAt }) === "held") held.set(runId, {
433
454
  scheduleId: input.scheduleId,
434
455
  scheduledAt: input.scheduledAt,
435
456
  startBy: input.scheduledAt.getTime() + catchUpMs + leaseTtlMs + minuteMs
@@ -1,2 +1,2 @@
1
- import { a as getScheduleRunStore, c as loadScheduleDefinition, d as setHostScheduleInventory, f as setScheduleOccurrenceClaims, h as setStartedScheduleRuntime, i as getScheduleOccurrenceClaims, l as registerProcessScheduleDefinitions, m as setScheduleRuntimeRegistry, n as getHostScheduleInventory, o as getScheduleRuntimeRegistry, p as setScheduleRunStore, r as getProcessScheduleDefinitions, s as getStartedScheduleRuntime, t as StartedScheduleRuntime, u as resetScheduleRuntime } from "../state-LuEgYpwR.js";
2
- export { StartedScheduleRuntime, getHostScheduleInventory, getProcessScheduleDefinitions, getScheduleOccurrenceClaims, getScheduleRunStore, getScheduleRuntimeRegistry, getStartedScheduleRuntime, loadScheduleDefinition, registerProcessScheduleDefinitions, resetScheduleRuntime, setHostScheduleInventory, setScheduleOccurrenceClaims, setScheduleRunStore, setScheduleRuntimeRegistry, setStartedScheduleRuntime };
1
+ import { _ as waitForProcessScheduleRuntime, a as getScheduleRunStore, c as loadScheduleDefinition, d as setHostScheduleInventory, f as setProcessScheduleRuntimeInstallation, g as setStartedScheduleRuntime, h as setScheduleRuntimeRegistry, i as getScheduleOccurrenceClaims, l as registerProcessScheduleDefinitions, m as setScheduleRunStore, n as getHostScheduleInventory, o as getScheduleRuntimeRegistry, p as setScheduleOccurrenceClaims, r as getProcessScheduleDefinitions, s as getStartedScheduleRuntime, t as StartedScheduleRuntime, u as resetScheduleRuntime } from "../state-CRQQfd8h.js";
2
+ export { StartedScheduleRuntime, getHostScheduleInventory, getProcessScheduleDefinitions, getScheduleOccurrenceClaims, getScheduleRunStore, getScheduleRuntimeRegistry, getStartedScheduleRuntime, loadScheduleDefinition, registerProcessScheduleDefinitions, resetScheduleRuntime, setHostScheduleInventory, setProcessScheduleRuntimeInstallation, setScheduleOccurrenceClaims, setScheduleRunStore, setScheduleRuntimeRegistry, setStartedScheduleRuntime, waitForProcessScheduleRuntime };
@@ -1 +1 @@
1
- export { t as getHostScheduleInventory, n as getProcessScheduleDefinitions, r as getScheduleOccurrenceClaims, i as getScheduleRunStore, a as getScheduleRuntimeRegistry, o as getStartedScheduleRuntime, s as loadScheduleDefinition, c as registerProcessScheduleDefinitions, l as resetScheduleRuntime, u as setHostScheduleInventory, d as setScheduleOccurrenceClaims, f as setScheduleRunStore, p as setScheduleRuntimeRegistry, m as setStartedScheduleRuntime } from "../state-CcVY3UzB.js";
1
+ export { t as getHostScheduleInventory, n as getProcessScheduleDefinitions, r as getScheduleOccurrenceClaims, i as getScheduleRunStore, a as getScheduleRuntimeRegistry, o as getStartedScheduleRuntime, s as loadScheduleDefinition, c as registerProcessScheduleDefinitions, l as resetScheduleRuntime, u as setHostScheduleInventory, d as setProcessScheduleRuntimeInstallation, f as setScheduleOccurrenceClaims, p as setScheduleRunStore, m as setScheduleRuntimeRegistry, h as setStartedScheduleRuntime, g as waitForProcessScheduleRuntime } from "../state-BoDrff6R.js";
@@ -1,3 +1,3 @@
1
- import { a as isScheduleCronAuthorized, c as markLoggedScheduleError, d as normalizeScheduleRuntimeError, f as scheduledWakeTime, i as executeStaticSchedule, l as missingScheduleDefinitionError, n as executeCloudflareStaticSchedules, o as isTimeZoneWakeDue, p as unwrapScheduleDefinition, r as executeMatchingStaticSchedules, s as logScheduleRuntimeError, t as createStaticScheduleRun, u as normalizeCron } from "../static--wi-oIIb.js";
1
+ import { a as isScheduleCronAuthorized, c as markLoggedScheduleError, d as normalizeScheduleRuntimeError, f as scheduledWakeTime, i as executeStaticSchedule, l as missingScheduleDefinitionError, n as executeCloudflareStaticSchedules, o as isTimeZoneWakeDue, p as unwrapScheduleDefinition, r as executeMatchingStaticSchedules, s as logScheduleRuntimeError, t as createStaticScheduleRun, u as normalizeCron } from "../static-D4nN8HTx.js";
2
2
  import { t as cronWithWeekdayNames } from "../due-DXgXKgzg.js";
3
3
  export { createStaticScheduleRun, cronWithWeekdayNames, executeCloudflareStaticSchedules, executeMatchingStaticSchedules, executeStaticSchedule, isScheduleCronAuthorized, isTimeZoneWakeDue, logScheduleRuntimeError, markLoggedScheduleError, missingScheduleDefinitionError, normalizeCron, normalizeScheduleRuntimeError, scheduledWakeTime, unwrapScheduleDefinition };
package/dist/runtime.d.ts CHANGED
@@ -3,7 +3,7 @@ import { a as createScheduleRun, c as runScheduleFrom, n as createKVScheduleRunS
3
3
  import { _ as unwrapScheduleDefinition, m as normalizeCron } from "./static-BFV4x94g.js";
4
4
  import { n as ScheduleKVStorage, r as createScheduleKVStorage, t as ScheduleKVSetOptions } from "./kv-storage-CKSSQ6Fk.js";
5
5
  import { E as StartedScheduleStore, _ as ScheduleRunRecord, a as ScheduleDefinitionOptions, b as ScheduleRunStore, f as ScheduleRunAttemptRecord, g as ScheduleRunListOptions, m as ScheduleRunContext, o as ScheduleDefinitionRegistry, r as ScheduleDefinition, s as ScheduleHandler, u as ScheduleRegistryDefinition } from "./types-Wllh0U8N.js";
6
- import { a as getScheduleRunStore, p as setScheduleRunStore, u as resetScheduleRuntime } from "./state-LuEgYpwR.js";
6
+ import { a as getScheduleRunStore, m as setScheduleRunStore, u as resetScheduleRuntime } from "./state-CRQQfd8h.js";
7
7
  interface InstallStartedSchedulesOptions {
8
8
  /**
9
9
  * How far back, in milliseconds, the first tick after a start runs cron minutes that no tick checked. Use it only with
package/dist/runtime.js CHANGED
@@ -1,6 +1,6 @@
1
- import { i as executeStaticSchedule, r as executeSchedule, s as runScheduleFrom, t as createScheduleRun } from "./execute-DoQC2i_V.js";
2
- import { p as unwrapScheduleDefinition, u as normalizeCron } from "./static--wi-oIIb.js";
1
+ import { i as executeStaticSchedule, r as executeSchedule, s as runScheduleFrom, t as createScheduleRun } from "./execute-DHApCpbQ.js";
2
+ import { p as unwrapScheduleDefinition, u as normalizeCron } from "./static-D4nN8HTx.js";
3
3
  import { t as createScheduleKVStorage } from "./kv-storage-CszEkof6.js";
4
- import { _ as createMemoryScheduleRunStore, f as setScheduleRunStore, g as createKVScheduleRunStore, i as getScheduleRunStore, l as resetScheduleRuntime } from "./state-CcVY3UzB.js";
5
- import { i as runStartedSchedules, n as createMemoryStartedScheduleStore, r as installStartedSchedules, t as createKVStartedScheduleStore } from "./started-yb49f37g.js";
4
+ import { i as getScheduleRunStore, l as resetScheduleRuntime, p as setScheduleRunStore, v as createKVScheduleRunStore, y as createMemoryScheduleRunStore } from "./state-BoDrff6R.js";
5
+ import { i as runStartedSchedules, n as createMemoryStartedScheduleStore, r as installStartedSchedules, t as createKVStartedScheduleStore } from "./started-adRbWkWd.js";
6
6
  export { createKVScheduleRunStore, createKVStartedScheduleStore, createMemoryScheduleRunStore, createMemoryStartedScheduleStore, createScheduleKVStorage, createScheduleRun, executeSchedule, executeStaticSchedule, getScheduleRunStore, installStartedSchedules, normalizeCron, resetScheduleRuntime, runScheduleFrom, runStartedSchedules, setScheduleRunStore, unwrapScheduleDefinition };
@@ -1,9 +1,9 @@
1
1
  import { t as isIanaTimeZone } from "./time-zone-pMp_g8Uu.js";
2
- import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
3
- import { C as createScheduleError, b as parseScheduledAt } from "./static--wi-oIIb.js";
4
- import { l as randomId, n as executeManualSchedule, o as resolveManualSchedule } from "./execute-DoQC2i_V.js";
5
- import { o as getStartedScheduleRuntime } from "./state-CcVY3UzB.js";
6
- import { t as startedScheduleErrors } from "./started-errors-DVw5cYHR.js";
2
+ import { r as isRecordOrFunction } from "./object-DNOrQSl5.js";
3
+ import { C as createScheduleError, b as parseScheduledAt } from "./static-D4nN8HTx.js";
4
+ import { l as randomId, n as executeManualSchedule, o as resolveManualSchedule } from "./execute-DHApCpbQ.js";
5
+ import { g as waitForProcessScheduleRuntime, o as getStartedScheduleRuntime } from "./state-BoDrff6R.js";
6
+ import { t as startedScheduleErrors } from "./started-errors-D6CnKMqD.js";
7
7
  import { parseCronExpression } from "cron-schedule";
8
8
  import { defineErrors } from "@vite-hub/runtime";
9
9
  // src/run-errors.ts
@@ -34,6 +34,7 @@ async function loadScheduleRegistry() {
34
34
  }
35
35
  }
36
36
  async function runSchedule(name, options = {}) {
37
+ await waitForProcessScheduleRuntime();
37
38
  const registry = await loadScheduleRegistry();
38
39
  const definition = await resolveManualSchedule(registry, name);
39
40
  let scheduledAt;
@@ -146,6 +147,11 @@ async function fromStore(work) {
146
147
  }
147
148
  }
148
149
  async function startSchedule(name, options) {
150
+ try {
151
+ await waitForProcessScheduleRuntime();
152
+ } catch (cause) {
153
+ return [startedScheduleErrors.SCHEDULE_RUNTIME_INSTALL_FAILED({ cause }), void 0];
154
+ }
149
155
  const [missing, runtime] = requireRuntime();
150
156
  if (missing) return [missing, void 0];
151
157
  if (!isString(name) || !Object.hasOwn(runtime.registry, name)) return [startedScheduleErrors.SCHEDULE_NOT_STARTABLE({ name: String(name) }), void 0];
@@ -1,9 +1,9 @@
1
1
  import { n as isScheduleDue } from "./due-DXgXKgzg.js";
2
- import { c as toRunId, r as executeSchedule } from "./execute-DoQC2i_V.js";
3
- import { m as setStartedScheduleRuntime, o as getStartedScheduleRuntime, r as getScheduleOccurrenceClaims, v as joinKey, y as keySegments } from "./state-CcVY3UzB.js";
4
- import { t as startedScheduleErrors } from "./started-errors-DVw5cYHR.js";
5
- import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
6
- import { v as errorCode, y as logFailure } from "./static--wi-oIIb.js";
2
+ import { c as toRunId, r as executeSchedule } from "./execute-DHApCpbQ.js";
3
+ import { b as joinKey, h as setStartedScheduleRuntime, o as getStartedScheduleRuntime, r as getScheduleOccurrenceClaims, x as keySegments } from "./state-BoDrff6R.js";
4
+ import { t as startedScheduleErrors } from "./started-errors-D6CnKMqD.js";
5
+ import { r as isRecordOrFunction } from "./object-DNOrQSl5.js";
6
+ import { v as errorCode, y as logFailure } from "./static-D4nN8HTx.js";
7
7
  import { normalizeRuntimeDiagnosticError } from "@vite-hub/runtime";
8
8
  // src/runtime/started.ts
9
9
  const minuteMs = 6e4;
@@ -3,10 +3,6 @@ import { defineErrors } from "@vite-hub/runtime";
3
3
  const startedScheduleErrors = /*#__PURE__*/ defineErrors({
4
4
  docs: "https://vitehub.dev/docs/schedule/diagnostics",
5
5
  codes: {
6
- SCHEDULE_NOT_STARTABLE: {
7
- why: ({ name }) => `No Schedule Definition without \`cron\` is named "${name}", so \`startSchedule()\` cannot start it.`,
8
- fix: "Add `server/schedules/<name>.ts` with `export default defineSchedule({ handler })` and no `cron`. A Definition with its own `cron` runs only on that cron."
9
- },
10
6
  SCHEDULE_INVALID_OPTIONS: {
11
7
  why: ({ problem }) => `\`startSchedule()\` options are invalid: ${problem}`,
12
8
  fix: "Pass `{ at }` for one run, or `{ cron, timeZone }` for a repeating Schedule, and a JSON `payload`."
@@ -15,13 +11,21 @@ const startedScheduleErrors = /*#__PURE__*/ defineErrors({
15
11
  why: ({ id }) => `No started Schedule has the id "${id}". It ran its last time, was cancelled, or never existed.`,
16
12
  fix: "List the started Schedules with `listSchedules()` or `vitehub schedule list`."
17
13
  },
18
- SCHEDULE_STORE_MISSING: {
19
- why: "This server has no store for started Schedules.",
20
- fix: "Add a Schedule Definition without `cron` in `server/schedules/`, enable `kv`, and build with Nitro. On Node, also set `schedule: { runtime: { driver: \"process\" } }`."
14
+ SCHEDULE_NOT_STARTABLE: {
15
+ why: ({ name }) => `No Schedule Definition without \`cron\` is named "${name}", so \`startSchedule()\` cannot start it.`,
16
+ fix: "Add `server/schedules/<name>.ts` with `export default defineSchedule({ handler })` and no `cron`. A Definition with its own `cron` runs only on that cron."
17
+ },
18
+ SCHEDULE_RUNTIME_INSTALL_FAILED: {
19
+ why: "The Process Runtime did not install. The server cannot deliver started Schedules.",
20
+ fix: "Read `error.cause` or the server startup log, fix the install error, then restart the server."
21
21
  },
22
22
  SCHEDULE_STORE_FAILED: {
23
23
  why: "The store of started Schedules failed. `error.cause` has the store error.",
24
24
  fix: "Check that KV is enabled and reachable from this server, then try again."
25
+ },
26
+ SCHEDULE_STORE_MISSING: {
27
+ why: "This server has no store for started Schedules.",
28
+ fix: "Add a Schedule Definition without `cron` in `server/schedules/`, enable `kv`, and build with Nitro. On Node, also set `schedule: { runtime: { driver: \"process\" } }`."
25
29
  }
26
30
  }
27
31
  });
@@ -1,5 +1,5 @@
1
1
  import { t as scheduleErrorDiagnostics } from "./error-diagnostics-KvK9MX6w.js";
2
- import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
2
+ import { r as isRecordOrFunction } from "./object-DNOrQSl5.js";
3
3
  import { parseDuration } from "@vite-hub/runtime";
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
5
  // src/runtime/store.ts
@@ -468,6 +468,7 @@ const processDefinitions = /* @__PURE__ */ new Set();
468
468
  let runtimeRegistryVersion = 0;
469
469
  let runStore;
470
470
  let startedRuntime;
471
+ let processRuntimeInstallation;
471
472
  let occurrenceClaims;
472
473
  const loadedRegistryEntries = /* @__PURE__ */ new Map();
473
474
  const loadingRegistryEntries = /* @__PURE__ */ new Map();
@@ -494,6 +495,20 @@ function registerProcessScheduleDefinitions(definitions) {
494
495
  function getProcessScheduleDefinitions() {
495
496
  return [...processDefinitions].at(-1);
496
497
  }
498
+ /** Records the installation that `waitForProcessScheduleRuntime()` waits for. */
499
+ function setProcessScheduleRuntimeInstallation(installation) {
500
+ processRuntimeInstallation = installation.then(() => void 0, (error) => ({ error }));
501
+ }
502
+ /**
503
+ * Waits until the first Process Runtime has installed, and throws its failure. Code that reads what the installation
504
+ * publishes calls it. It returns at once when no Process Runtime installs, or when one is ready: a replacement that
505
+ * installs later does not hold it.
506
+ */
507
+ async function waitForProcessScheduleRuntime() {
508
+ if (processDefinitions.size > 0) return;
509
+ const failed = await processRuntimeInstallation;
510
+ if (failed) throw failed.error;
511
+ }
497
512
  function setHostScheduleInventory(inventory) {
498
513
  hostInventory = inventory;
499
514
  }
@@ -563,8 +578,9 @@ function resetScheduleRuntime() {
563
578
  runtimeRegistryVersion++;
564
579
  runStore = void 0;
565
580
  startedRuntime = void 0;
581
+ processRuntimeInstallation = void 0;
566
582
  occurrenceClaims = void 0;
567
583
  loadedRegistryEntries.clear();
568
584
  loadingRegistryEntries.clear();
569
585
  }
570
- export { createMemoryScheduleRunStore as _, getScheduleRuntimeRegistry as a, registerProcessScheduleDefinitions as c, setScheduleOccurrenceClaims as d, setScheduleRunStore as f, createKVScheduleRunStore as g, DEFAULT_SCHEDULE_RETENTION as h, getScheduleRunStore as i, resetScheduleRuntime as l, setStartedScheduleRuntime as m, getProcessScheduleDefinitions as n, getStartedScheduleRuntime as o, setScheduleRuntimeRegistry as p, getScheduleOccurrenceClaims as r, loadScheduleDefinition as s, getHostScheduleInventory as t, setHostScheduleInventory as u, joinKey as v, keySegments as y };
586
+ export { DEFAULT_SCHEDULE_RETENTION as _, getScheduleRuntimeRegistry as a, joinKey as b, registerProcessScheduleDefinitions as c, setProcessScheduleRuntimeInstallation as d, setScheduleOccurrenceClaims as f, waitForProcessScheduleRuntime as g, setStartedScheduleRuntime as h, getScheduleRunStore as i, resetScheduleRuntime as l, setScheduleRuntimeRegistry as m, getProcessScheduleDefinitions as n, getStartedScheduleRuntime as o, setScheduleRunStore as p, getScheduleOccurrenceClaims as r, loadScheduleDefinition as s, getHostScheduleInventory as t, setHostScheduleInventory as u, createKVScheduleRunStore as v, keySegments as x, createMemoryScheduleRunStore as y };
@@ -1,7 +1,18 @@
1
1
  import { E as StartedScheduleStore, b as ScheduleRunStore, o as ScheduleDefinitionRegistry, r as ScheduleDefinition, u as ScheduleRegistryDefinition } from "./types-Wllh0U8N.js";
2
2
  import { LeaseStore } from "@vite-hub/runtime";
3
- /** `held` when another process holds the occurrence now, `done` when a process finished it, `ran` when this call ran it. */
4
- type OccurrenceClaimResult = "done" | "held" | "ran";
3
+ /**
4
+ * `held` when another process holds the occurrence now, `done` when a process finished it, `late` when the call came
5
+ * after the done marker window of `scheduledAt`, and `ran` when this call ran it.
6
+ */
7
+ type OccurrenceClaimResult = "done" | "held" | "late" | "ran";
8
+ interface OccurrenceClaimRunOptions {
9
+ /**
10
+ * The scheduled time of the occurrence. A done marker is written after this time and lasts `doneTtlMs`, so a missing
11
+ * marker proves nothing from `scheduledAt` plus `doneTtlMs` on. A call that finds no marker then returns `late` and
12
+ * does not run.
13
+ */
14
+ scheduledAt?: Date;
15
+ }
5
16
  /** Runs each Schedule occurrence in one process of all the processes that share `leases`. */
6
17
  interface OccurrenceClaims {
7
18
  /**
@@ -9,7 +20,7 @@ interface OccurrenceClaims {
9
20
  * renewed. Call `markFinal` before invoking the handler or when an existing run is final. Then a done marker stays
10
21
  * for `doneTtlMs`, also when the handler throws. Errors before `markFinal` leave the occurrence retryable.
11
22
  */
12
- run(runId: string, run: (markFinal: () => void) => Promise<unknown>): Promise<OccurrenceClaimResult>;
23
+ run(runId: string, run: (markFinal: () => void) => Promise<unknown>, options?: OccurrenceClaimRunOptions): Promise<OccurrenceClaimResult>;
13
24
  }
14
25
  type ProcessScheduleTimingRecord = Pick<ScheduleDefinition, "cron" | "timeZone">;
15
26
  interface HostScheduleInventory {
@@ -41,6 +52,14 @@ declare function getScheduleRuntimeRegistry(): ScheduleDefinitionRegistry | unde
41
52
  /** Publish only ready runtimes, retaining earlier snapshots until their controllers close. */
42
53
  declare function registerProcessScheduleDefinitions(definitions: ReadonlyMap<string, ProcessScheduleTimingRecord>): () => void;
43
54
  declare function getProcessScheduleDefinitions(): ReadonlyMap<string, ProcessScheduleTimingRecord> | undefined;
55
+ /** Records the installation that `waitForProcessScheduleRuntime()` waits for. */
56
+ declare function setProcessScheduleRuntimeInstallation(installation: Promise<unknown>): void;
57
+ /**
58
+ * Waits until the first Process Runtime has installed, and throws its failure. Code that reads what the installation
59
+ * publishes calls it. It returns at once when no Process Runtime installs, or when one is ready: a replacement that
60
+ * installs later does not hold it.
61
+ */
62
+ declare function waitForProcessScheduleRuntime(): Promise<void>;
44
63
  declare function setHostScheduleInventory(inventory: HostScheduleInventory): void;
45
64
  declare function getHostScheduleInventory(): HostScheduleInventory | undefined;
46
65
  declare function setScheduleRunStore(store: ScheduleRunStore | undefined): void;
@@ -52,4 +71,4 @@ declare function setStartedScheduleRuntime(runtime: StartedScheduleRuntime | und
52
71
  declare function getStartedScheduleRuntime(): StartedScheduleRuntime | undefined;
53
72
  declare function loadScheduleDefinition(name: string): Promise<ScheduleRegistryDefinition | undefined>;
54
73
  declare function resetScheduleRuntime(): void;
55
- export { getScheduleRunStore as a, loadScheduleDefinition as c, setHostScheduleInventory as d, setScheduleOccurrenceClaims as f, setStartedScheduleRuntime as h, getScheduleOccurrenceClaims as i, registerProcessScheduleDefinitions as l, setScheduleRuntimeRegistry as m, getHostScheduleInventory as n, getScheduleRuntimeRegistry as o, setScheduleRunStore as p, getProcessScheduleDefinitions as r, getStartedScheduleRuntime as s, StartedScheduleRuntime as t, resetScheduleRuntime as u };
74
+ export { waitForProcessScheduleRuntime as _, getScheduleRunStore as a, loadScheduleDefinition as c, setHostScheduleInventory as d, setProcessScheduleRuntimeInstallation as f, setStartedScheduleRuntime as g, setScheduleRuntimeRegistry as h, getScheduleOccurrenceClaims as i, registerProcessScheduleDefinitions as l, setScheduleRunStore as m, getHostScheduleInventory as n, getScheduleRuntimeRegistry as o, setScheduleOccurrenceClaims as p, getProcessScheduleDefinitions as r, getStartedScheduleRuntime as s, StartedScheduleRuntime as t, resetScheduleRuntime as u };
@@ -1,5 +1,5 @@
1
1
  import { t as scheduleErrorDiagnostics } from "./error-diagnostics-KvK9MX6w.js";
2
- import { n as isRecordOrFunction } from "./object-CAK6UYR5.js";
2
+ import { r as isRecordOrFunction } from "./object-DNOrQSl5.js";
3
3
  import { n as isScheduleDue, r as latestCronMinute, t as cronWithWeekdayNames } from "./due-DXgXKgzg.js";
4
4
  import { ViteHubError, normalizeRuntimeDiagnosticError } from "@vite-hub/runtime";
5
5
  import { emitRunFailed, toRunFailedError } from "@vite-hub/runtime/internal/run-failed";
package/dist/vite.js CHANGED
@@ -2,14 +2,14 @@ import { r as __toESM } from "./rolldown-runtime-DegdyBIC.js";
2
2
  import { a as parseCronFields, l as invariant, u as invariantError } from "./cron-imqlBgO-.js";
3
3
  import { a as relative$1, i as isAbsolute$1, n as relativeDefinitionFile, o as resolve$1, r as dirname$1 } from "./inspect-CW0qwt9p.js";
4
4
  import { t as internalErrorDiagnostics } from "./error-diagnostics-CsiNo_oI.js";
5
- import { n as isRecordOrFunction, t as isRecord$1 } from "./object-CAK6UYR5.js";
5
+ import { n as isRecord, r as isRecordOrFunction, t as isObject } from "./object-DNOrQSl5.js";
6
6
  import { t as scheduleErrorDiagnostics } from "./error-diagnostics-KvK9MX6w.js";
7
7
  import { n as parseScheduleCronExpression, t as assertScheduleCronFields } from "./cron-D0mqg3ql.js";
8
- import { m as startedSchedulesTickName } from "./static--wi-oIIb.js";
8
+ import { m as startedSchedulesTickName } from "./static-D4nN8HTx.js";
9
9
  import { t as isIanaTimeZone } from "./time-zone-pMp_g8Uu.js";
10
10
  import { i as timeZoneOffsetMinutes, t as cronWithWeekdayNames } from "./due-DXgXKgzg.js";
11
11
  import { scheduleConsoleTiming } from "./runtime/console.js";
12
- import "./state-CcVY3UzB.js";
12
+ import "./state-BoDrff6R.js";
13
13
  import { builtinModules, createRequire, isBuiltin } from "node:module";
14
14
  import { formatDiagnostic } from "nostics";
15
15
  import { parseDuration } from "@vite-hub/runtime";
@@ -534,9 +534,9 @@ function isFileResolution(resolved) {
534
534
  }
535
535
  function collectPackageExportCandidates(packageName, exportsValue, packageRelativePath) {
536
536
  if (typeof exportsValue === "string") return normalizePathSeparators(exportsValue).replace(/^\.\//, "") === packageRelativePath ? [packageName] : [];
537
- if (!Array.isArray(exportsValue) && !isRecord$1(exportsValue)) return [];
537
+ if (!Array.isArray(exportsValue) && !isRecord(exportsValue)) return [];
538
538
  const candidates = [];
539
- const exportEntries = isRecord$1(exportsValue) && Object.keys(exportsValue).some((exportKey) => exportKey.startsWith(".")) ? Object.entries(exportsValue) : [[".", exportsValue]];
539
+ const exportEntries = isRecord(exportsValue) && Object.keys(exportsValue).some((exportKey) => exportKey.startsWith(".")) ? Object.entries(exportsValue) : [[".", exportsValue]];
540
540
  for (const [exportKey, target] of exportEntries) {
541
541
  const targets = [target];
542
542
  while (targets.length) {
@@ -553,7 +553,7 @@ function collectPackageExportCandidates(packageName, exportsValue, packageRelati
553
553
  if (wildcard === void 0) continue;
554
554
  candidates.push(`${packageName}${exportKey.slice(1).replace("*", wildcard)}`);
555
555
  } else if (Array.isArray(value)) targets.push(...value);
556
- else if (isRecord$1(value)) targets.push(...Object.values(value));
556
+ else if (isRecord(value)) targets.push(...Object.values(value));
557
557
  }
558
558
  }
559
559
  return candidates;
@@ -659,7 +659,7 @@ function createResolvedAliasPlugin(aliases, aliasResolveDir, workingDir, resolve
659
659
  else if (resolutionScope) {
660
660
  const packageRelativePath = normalizedSpecifier.slice(resolutionScope.length);
661
661
  const parsedPackageJson = JSON.parse(await readFile(resolve(resolutionScope, "package.json"), "utf8"));
662
- if (!isRecord$1(parsedPackageJson)) return;
662
+ if (!isRecord(parsedPackageJson)) return;
663
663
  const packageJson = parsedPackageJson;
664
664
  if (packageJson.exports === void 0 && !alias.prefix) {
665
665
  const resolvedCandidate = await resolveWithContext(alias.specifier);
@@ -3366,6 +3366,150 @@ async function copyRuntimePackageFiles(packageDir, targetDir) {
3366
3366
  await unlessGone(() => copyFile(join(packageDir, path), target));
3367
3367
  }
3368
3368
  }
3369
+ // ../internal/src/source-files.ts
3370
+ const ignoredDirs = /* @__PURE__ */ new Set([
3371
+ "node_modules",
3372
+ "dist",
3373
+ ".output",
3374
+ ".nuxt",
3375
+ ".vercel",
3376
+ ".git",
3377
+ ".vitehub"
3378
+ ]);
3379
+ const racyWindowNs = 2000000000n;
3380
+ const storeKey = Symbol.for("vite-hub.source-files.v1");
3381
+ function store() {
3382
+ const existing = Reflect.get(globalThis, storeKey);
3383
+ if (isStore(existing)) return existing;
3384
+ const created = {
3385
+ derived: /* @__PURE__ */ new Map(),
3386
+ texts: /* @__PURE__ */ new Map(),
3387
+ trees: /* @__PURE__ */ new Map()
3388
+ };
3389
+ Reflect.set(globalThis, storeKey, created);
3390
+ return created;
3391
+ }
3392
+ function isStore(value) {
3393
+ return typeof value === "object" && value !== null && "texts" in value && "trees" in value && "derived" in value;
3394
+ }
3395
+ function errorCode(error) {
3396
+ return typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
3397
+ }
3398
+ function statOrMissing(path) {
3399
+ try {
3400
+ return statSync(path, { bigint: true });
3401
+ } catch (error) {
3402
+ if (errorCode(error) === "ENOENT" || errorCode(error) === "ENOTDIR") return;
3403
+ throw error;
3404
+ }
3405
+ }
3406
+ function signature(stats) {
3407
+ return `${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`;
3408
+ }
3409
+ function isSettled(stats) {
3410
+ const changed = stats.mtimeNs > stats.ctimeNs ? stats.mtimeNs : stats.ctimeNs;
3411
+ return BigInt(Date.now()) * 1000000n - changed > racyWindowNs;
3412
+ }
3413
+ function readDirEntries(root) {
3414
+ try {
3415
+ return readdirSync(root, { withFileTypes: true });
3416
+ } catch (error) {
3417
+ if (errorCode(error) === "ENOENT") return [];
3418
+ throw error;
3419
+ }
3420
+ }
3421
+ function walkTree(root, directories, files, nested = false) {
3422
+ const before = statOrMissing(root);
3423
+ let trusted = before !== void 0 && isSettled(before);
3424
+ if (before) directories.set(root, signature(before));
3425
+ if (nested && existsSync(resolve$1(root, ".git"))) return trusted;
3426
+ for (const entry of readDirEntries(root)) {
3427
+ const path = resolve$1(root, entry.name);
3428
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
3429
+ if (entry.name.startsWith(".") || ignoredDirs.has(entry.name)) continue;
3430
+ if (!walkTree(path, directories, files, true)) trusted = false;
3431
+ continue;
3432
+ }
3433
+ if (entry.isFile()) files.push({
3434
+ hidden: entry.name.startsWith("."),
3435
+ name: entry.name,
3436
+ path
3437
+ });
3438
+ }
3439
+ return trusted;
3440
+ }
3441
+ function isCurrent(tree) {
3442
+ for (const [directory, stored] of tree.directories) {
3443
+ const stats = statOrMissing(directory);
3444
+ if (!stats || signature(stats) !== stored) return false;
3445
+ }
3446
+ return true;
3447
+ }
3448
+ function sourceTree(root) {
3449
+ const trees = store().trees;
3450
+ const cached = trees.get(root);
3451
+ if (cached && isCurrent(cached)) return cached;
3452
+ const directories = /* @__PURE__ */ new Map();
3453
+ const files = [];
3454
+ const trusted = walkTree(root, directories, files);
3455
+ files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
3456
+ const tree = {
3457
+ directories,
3458
+ files
3459
+ };
3460
+ if (trusted) trees.set(root, tree);
3461
+ else trees.delete(root);
3462
+ return tree;
3463
+ }
3464
+ /**
3465
+ * The files below `root` whose name matches `predicate`, sorted by path. The walk skips hidden folders, Git
3466
+ * repositories, and build output folders such as `node_modules`, `dist`, and `.vitehub`. Hidden files need
3467
+ * `includeHidden`. Symbolic links are skipped.
3468
+ */
3469
+ function listSourceTreeFiles(root, predicate, options = {}) {
3470
+ const files = [];
3471
+ for (const file of sourceTree(resolve$1(root)).files) {
3472
+ if (file.hidden && !options.includeHidden) continue;
3473
+ if (predicate(file.name)) files.push(file.path);
3474
+ }
3475
+ return files;
3476
+ }
3477
+ /** The UTF-8 text of a source file. A file that did not change since the last read is not read again. */
3478
+ function readSourceText(file) {
3479
+ const path = resolve$1(file);
3480
+ const texts = store().texts;
3481
+ const stats = statOrMissing(path);
3482
+ if (!stats) return readFileSync(path, "utf8");
3483
+ const current = signature(stats);
3484
+ const cached = texts.get(path);
3485
+ if (cached?.trusted && cached.signature === current) return cached.text;
3486
+ const read = readFileSync(path, "utf8");
3487
+ const text = cached?.text === read ? cached.text : read;
3488
+ texts.set(path, {
3489
+ signature: current,
3490
+ text,
3491
+ trusted: isSettled(stats)
3492
+ });
3493
+ return text;
3494
+ }
3495
+ /**
3496
+ * A value that `compute` derives from the text of a source file, such as its syntax tree. The value is computed again
3497
+ * only when the text changes. `kind` separates the values of different callers for one file. The last two texts of a
3498
+ * file are kept, because some callers read both the file and its transformed code.
3499
+ */
3500
+ function deriveFromSource(kind, file, source, compute) {
3501
+ const derived = store().derived;
3502
+ const key = `${kind}\0${file}`;
3503
+ const entries = derived.get(key) ?? [];
3504
+ const cached = entries.find((entry) => entry.source === source);
3505
+ if (cached) return cached.value;
3506
+ const value = compute();
3507
+ derived.set(key, [{
3508
+ source,
3509
+ value
3510
+ }, ...entries.slice(0, 1)]);
3511
+ return value;
3512
+ }
3369
3513
  // ../internal/src/build/scan-module.ts
3370
3514
  /**
3371
3515
  * Reads facts from JavaScript and TypeScript modules at build and dev time. The scanner parses each module once with
@@ -3389,6 +3533,17 @@ function scanModule(source, file = "module.ts") {
3389
3533
  source
3390
3534
  };
3391
3535
  }
3536
+ /**
3537
+ * Reads and parses a source file once for each change of its text. Callers share the result, so they must not change
3538
+ * the syntax tree.
3539
+ */
3540
+ function scanSourceFile(file) {
3541
+ return scanModuleText(readSourceText(file), file);
3542
+ }
3543
+ /** `scanModule` with a result that is shared while `source` stays the same for `file`. */
3544
+ function scanModuleText(source, file) {
3545
+ return deriveFromSource("scan-module", file, source, () => scanModule(source, file));
3546
+ }
3392
3547
  /** Removes parentheses, `as`, `satisfies`, `!`, and `<T>` assertions around an expression. */
3393
3548
  function unwrapExpression(node) {
3394
3549
  while (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "TSTypeAssertion") node = node.expression;
@@ -6258,15 +6413,6 @@ function durabilityModuleFile(importMetaUrl) {
6258
6413
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
6259
6414
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
6260
6415
  const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
6261
- const ignoredDirs = /* @__PURE__ */ new Set([
6262
- "node_modules",
6263
- "dist",
6264
- ".output",
6265
- ".nuxt",
6266
- ".vercel",
6267
- ".git",
6268
- ".vitehub"
6269
- ]);
6270
6416
  function resolveDefinitionScanRoots(rootDir, scanDirs = []) {
6271
6417
  return [...new Set([rootDir, ...scanDirs].filter(Boolean))];
6272
6418
  }
@@ -6289,32 +6435,8 @@ function createSuffixDefinitionSource(source, roots, pattern, normalizeName, opt
6289
6435
  source
6290
6436
  };
6291
6437
  }
6292
- function readDirEntries(root) {
6293
- try {
6294
- return readdirSync(root, { withFileTypes: true });
6295
- } catch (error) {
6296
- if (error.code === "ENOENT") return [];
6297
- throw error;
6298
- }
6299
- }
6300
- function isGitRepositoryDirectory(directory) {
6301
- return existsSync(resolve$1(directory, ".git"));
6302
- }
6303
6438
  function listMatchingFiles(root, predicate, options = {}) {
6304
- const files = [];
6305
- for (const entry of readDirEntries(root)) {
6306
- const absolute = resolve$1(root, entry.name);
6307
- if (entry.isDirectory() && !entry.isSymbolicLink()) {
6308
- if (isGitRepositoryDirectory(absolute)) continue;
6309
- if (entry.name.startsWith(".")) continue;
6310
- if (ignoredDirs.has(entry.name)) continue;
6311
- files.push(...listMatchingFiles(absolute, predicate, options));
6312
- continue;
6313
- }
6314
- if (entry.name.startsWith(".") && !options.includeHidden) continue;
6315
- if (entry.isFile() && predicate(entry.name)) files.push(absolute);
6316
- }
6317
- return files.sort();
6439
+ return listSourceTreeFiles(root, predicate, options);
6318
6440
  }
6319
6441
  /** A module that a Definitions folder can hold: JavaScript or TypeScript, and not a declaration, test, or spec file. */
6320
6442
  function isDefinitionSourceFile(name) {
@@ -6579,7 +6701,7 @@ async function flattenPlugins(value, plugins, seen) {
6579
6701
  for (const item of value) await flattenPlugins(item, plugins, seen);
6580
6702
  return;
6581
6703
  }
6582
- if (!isRecord$1(value) || seen.has(value)) return;
6704
+ if (!isRecord(value) || seen.has(value)) return;
6583
6705
  seen.add(value);
6584
6706
  if (isThenable(value)) {
6585
6707
  await flattenPlugins(await value, plugins, seen);
@@ -6611,7 +6733,7 @@ async function collectContributions(plugins, options) {
6611
6733
  for (const plugin of candidates) {
6612
6734
  if (!Object.hasOwn(plugin, "vitehub")) continue;
6613
6735
  const metadata = Reflect.get(plugin, "vitehub");
6614
- if (!isRecord$1(metadata) || !Object.hasOwn(metadata, options.key)) continue;
6736
+ if (!isRecord(metadata) || !Object.hasOwn(metadata, options.key)) continue;
6615
6737
  const source = metadata[options.key];
6616
6738
  const pluginName = Reflect.get(plugin, "name");
6617
6739
  const contributor = isNonEmptyString(pluginName) ? pluginName : unnamedPlugin;
@@ -6639,12 +6761,12 @@ async function collectContributions(plugins, options) {
6639
6761
  return [...collected.values()].map(({ contribution }) => contribution).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
6640
6762
  }
6641
6763
  function readContribution(entry, plugin, options, fail) {
6642
- if (!isRecord$1(entry)) return fail("expected { name, definition: { module, export? }, reason? }.");
6764
+ if (!isRecord(entry)) return fail("expected { name, definition: { module, export? }, reason? }.");
6643
6765
  const { definition, name, reason } = entry;
6644
6766
  if (!isNonEmptyString(name) || name.trim() !== name) return fail("`name` must be a non-empty string without surrounding whitespace.");
6645
6767
  const nameProblem = options.checkName?.(name);
6646
6768
  if (nameProblem) return fail(`${options.kind} ${JSON.stringify(name)}: ${nameProblem}`);
6647
- if (!isRecord$1(definition)) return fail(`${options.kind} ${JSON.stringify(name)} needs \`definition: { module, export? }\`.`);
6769
+ if (!isRecord(definition)) return fail(`${options.kind} ${JSON.stringify(name)} needs \`definition: { module, export? }\`.`);
6648
6770
  if (!isNonEmptyString(definition.module)) return fail(`\`definition.module\` of ${options.kind} ${JSON.stringify(name)} must be a non-empty string.`);
6649
6771
  let module;
6650
6772
  try {
@@ -6715,16 +6837,16 @@ function cronLocation(file, source, offset) {
6715
6837
  return `[vitehub] ${file}:${source.slice(0, offset).split("\n").length}: \`defineSchedule()\``;
6716
6838
  }
6717
6839
  function assertStaticScheduleCron(file) {
6718
- const source = readFileSync(file, "utf8");
6719
- const definition = findDefaultExportCall(scanModule(source, file), ["defineSchedule"]);
6840
+ const source = readSourceText(file);
6841
+ const definition = findDefaultExportCall(scanModuleText(source, file), ["defineSchedule"]);
6720
6842
  const property = definition?.options && findProperty(definition.options, "cron");
6721
6843
  if (!property) return;
6722
6844
  const cron = staticString(property.value);
6723
6845
  if (cron !== void 0) parseScheduleCronExpression(cron, cronLocation(file, source, property.node.start));
6724
6846
  }
6725
6847
  function readScheduleDiscoveryMetadata(file, contribution) {
6726
- const source = readFileSync(file, "utf8");
6727
- const module = scanModule(source, file);
6848
+ const source = readSourceText(file);
6849
+ const module = scanModuleText(source, file);
6728
6850
  const definition = findDefaultExportCall(module, ["defineSchedule"]);
6729
6851
  const unsupported = (offset, message) => {
6730
6852
  const line = source.slice(0, offset).split("\n").length;
@@ -6982,7 +7104,7 @@ function readStringArray(value) {
6982
7104
  return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
6983
7105
  }
6984
7106
  function isVercelCron(value) {
6985
- return isRecord$1(value) && typeof value.path === "string" && typeof value.schedule === "string";
7107
+ return isRecord(value) && typeof value.path === "string" && typeof value.schedule === "string";
6986
7108
  }
6987
7109
  function resolveSchedulePublicEntry(resolveImport = (specifier) => import.meta.resolve(specifier)) {
6988
7110
  const packageRoot = dirname(fileURLToPath(resolveImport(`${schedulePackageName}/package.json`)));
@@ -7078,7 +7200,7 @@ function validateDefinitionProviderCron(cron, definition, overrides) {
7078
7200
  }
7079
7201
  /** Reads the `cron` option of a `defineSchedule()` call. Returns `undefined` when it is missing or not a static string. */
7080
7202
  function readStaticScheduleCronOption(file) {
7081
- const definition = findDefaultExportCall(scanModule(readFileSync(file, "utf8"), file), ["defineSchedule"]);
7203
+ const definition = findDefaultExportCall(scanSourceFile(file), ["defineSchedule"]);
7082
7204
  return definition?.options && staticString(findProperty(definition.options, "cron")?.value) || void 0;
7083
7205
  }
7084
7206
  function readStaticScheduleCron(file, scheduleName) {
@@ -7092,7 +7214,7 @@ function readStaticScheduleCron(file, scheduleName) {
7092
7214
  * when it is present but dynamic.
7093
7215
  */
7094
7216
  function readStaticScheduleTimeZone(file) {
7095
- const definition = findDefaultExportCall(scanModule(readFileSync(file, "utf8"), file), ["defineSchedule"]);
7217
+ const definition = findDefaultExportCall(scanSourceFile(file), ["defineSchedule"]);
7096
7218
  const property = definition?.options && findProperty(definition.options, "timeZone");
7097
7219
  if (!property) return void 0;
7098
7220
  return property.value ? staticString(property.value) ?? null : null;
@@ -7103,7 +7225,7 @@ function readStaticScheduleTimeZone(file) {
7103
7225
  */
7104
7226
  function readStaticScheduleTiming(file) {
7105
7227
  if (!existsSync(file)) return void 0;
7106
- const definition = findDefaultExportCall(scanModule(readFileSync(file, "utf8"), file), ["defineSchedule"]);
7228
+ const definition = findDefaultExportCall(scanSourceFile(file), ["defineSchedule"]);
7107
7229
  if (!definition) return void 0;
7108
7230
  const cron = staticString(definition.options && findProperty(definition.options, "cron")?.value);
7109
7231
  const timeZone = definition.options && findProperty(definition.options, "timeZone");
@@ -7677,7 +7799,7 @@ async function writeCloudflareScheduleOutput(options) {
7677
7799
  } catch (error) {
7678
7800
  if (error.code !== "ENOENT") throw error;
7679
7801
  }
7680
- const existingTriggers = isRecord$1(wranglerConfig.triggers) ? wranglerConfig.triggers : {};
7802
+ const existingTriggers = isRecord(wranglerConfig.triggers) ? wranglerConfig.triggers : {};
7681
7803
  const previousState = await readCloudflareOutputState(options.previousStateFile ?? options.stateFile);
7682
7804
  options.signal?.throwIfAborted();
7683
7805
  const externalCrons = readStringArray(existingTriggers.crons).filter((cron) => !previousState?.crons.includes(cron));
@@ -8093,12 +8215,9 @@ function resolveSchedulePluginRoots(root, options = {}) {
8093
8215
  viteRoot: resolvedViteRoot
8094
8216
  };
8095
8217
  }
8096
- function isRecord(value) {
8097
- return typeof value === "object" && value !== null;
8098
- }
8099
8218
  function resolveProcessRuntimeOptions(value) {
8100
8219
  if (value === void 0) return;
8101
- if (!isRecord(value) || value.driver !== "process") throw scheduleErrorDiagnostics.SCHEDULE_B0001({ message: "Schedule Process Runtime driver must be \"process\"." });
8220
+ if (!isObject(value) || value.driver !== "process") throw scheduleErrorDiagnostics.SCHEDULE_B0001({ message: "Schedule Process Runtime driver must be \"process\"." });
8102
8221
  if (value.prefix !== void 0 && typeof value.prefix !== "string") throw scheduleErrorDiagnostics.SCHEDULE_B0002({ message: "Schedule Process Runtime prefix must be a string." });
8103
8222
  if (value.catchUpMs !== void 0 && (typeof value.catchUpMs !== "number" || !Number.isFinite(value.catchUpMs) || value.catchUpMs < 0)) throw scheduleErrorDiagnostics.SCHEDULE_RUNTIME_CATCH_UP_INVALID();
8104
8223
  if (value.intervalMs !== void 0 && (typeof value.intervalMs !== "number" || !Number.isFinite(value.intervalMs) || value.intervalMs <= 0 || value.intervalMs > 6e4)) throw scheduleErrorDiagnostics.SCHEDULE_B0003({ message: "Schedule Process Runtime intervalMs must be a positive number no greater than 60000." });
@@ -8126,11 +8245,11 @@ function resolveScheduleRetention(value, processRuntime) {
8126
8245
  }
8127
8246
  const databaseVitePluginName = "@vite-hub/database/vite";
8128
8247
  function hasVitePlugin(plugins, name) {
8129
- return (plugins ?? []).some((plugin) => Array.isArray(plugin) ? hasVitePlugin(plugin, name) : isRecord(plugin) && plugin.name === name);
8248
+ return (plugins ?? []).some((plugin) => Array.isArray(plugin) ? hasVitePlugin(plugin, name) : isObject(plugin) && plugin.name === name);
8130
8249
  }
8131
8250
  function resolveCronOverrides(value, definitions, options) {
8132
8251
  if (value === void 0) return;
8133
- if (!isRecord(value) || Array.isArray(value)) throw scheduleErrorDiagnostics.SCHEDULE_B0008({ message: "Schedule `cron` must map Schedule names to cron strings, such as `{ cleanup: \"0 0 * * *\" }`." });
8252
+ if (!isObject(value) || Array.isArray(value)) throw scheduleErrorDiagnostics.SCHEDULE_B0008({ message: "Schedule `cron` must map Schedule names to cron strings, such as `{ cleanup: \"0 0 * * *\" }`." });
8134
8253
  const names = definitions && new Set(definitions.map((definition) => definition.name));
8135
8254
  const overrides = {};
8136
8255
  for (const [name, cron] of Object.entries(value)) {
@@ -8149,13 +8268,13 @@ function moduleImportSpecifier(fromFile, targetFile) {
8149
8268
  return specifier.startsWith(".") ? specifier : `./${specifier}`;
8150
8269
  }
8151
8270
  function cloneNitroConfig(value) {
8152
- const nitro = isRecord(value) ? { ...value } : {};
8271
+ const nitro = isObject(value) ? { ...value } : {};
8153
8272
  if (Array.isArray(nitro.plugins)) nitro.plugins = [...nitro.plugins];
8154
- if (isRecord(nitro.cloudflare)) {
8273
+ if (isObject(nitro.cloudflare)) {
8155
8274
  const cloudflare = { ...nitro.cloudflare };
8156
- if (isRecord(cloudflare.wrangler)) {
8275
+ if (isObject(cloudflare.wrangler)) {
8157
8276
  const wrangler = { ...cloudflare.wrangler };
8158
- if (isRecord(wrangler.triggers)) {
8277
+ if (isObject(wrangler.triggers)) {
8159
8278
  const triggers = { ...wrangler.triggers };
8160
8279
  if (Array.isArray(triggers.crons)) triggers.crons = triggers.crons.filter((cron) => typeof cron === "string");
8161
8280
  wrangler.triggers = triggers;
@@ -8181,7 +8300,7 @@ function mergeNitroScheduleConfig(value, options) {
8181
8300
  configured.cloudflare ||= {};
8182
8301
  configured.cloudflare.wrangler ||= {};
8183
8302
  const wrangler = configured.cloudflare.wrangler;
8184
- const existingTriggers = isRecord(wrangler.triggers) ? wrangler.triggers : {};
8303
+ const existingTriggers = isObject(wrangler.triggers) ? wrangler.triggers : {};
8185
8304
  const existingCrons = Array.isArray(existingTriggers.crons) ? existingTriggers.crons.filter((cron) => typeof cron === "string") : [];
8186
8305
  wrangler.triggers = {
8187
8306
  ...existingTriggers,
@@ -8191,10 +8310,10 @@ function mergeNitroScheduleConfig(value, options) {
8191
8310
  }
8192
8311
  function mergeNitroVercelCrons(value, definitions, crons) {
8193
8312
  const nitro = cloneNitroConfig(value);
8194
- const vercel = isRecord(nitro.vercel) ? { ...nitro.vercel } : {};
8195
- const config = isRecord(vercel.config) ? { ...vercel.config } : {};
8313
+ const vercel = isObject(nitro.vercel) ? { ...nitro.vercel } : {};
8314
+ const config = isObject(vercel.config) ? { ...vercel.config } : {};
8196
8315
  const generatedPaths = new Set(definitions.map((definition) => getVercelSchedulePath(definition.name)));
8197
- config.crons = [...Array.isArray(config.crons) ? config.crons.filter((cron) => isRecord(cron) && typeof cron.path === "string" && !generatedPaths.has(cron.path)) : [], ...definitions.map((definition) => ({
8316
+ config.crons = [...Array.isArray(config.crons) ? config.crons.filter((cron) => isObject(cron) && typeof cron.path === "string" && !generatedPaths.has(cron.path)) : [], ...definitions.map((definition) => ({
8198
8317
  path: getVercelSchedulePath(definition.name),
8199
8318
  schedule: crons.get(definition.name)
8200
8319
  }))];
@@ -8309,11 +8428,7 @@ function renderNitroSchedulePlugin(options) {
8309
8428
  " // ViteHub runs this drain on a stop signal, before the server closes HTTP, or when Nitro closes.",
8310
8429
  " onShutdown(nitroApp, 'schedule', () => runtimeInstallation.then(async (result) => {",
8311
8430
  " if ('controller' in result) await result.controller.close()",
8312
- " }).catch(captureRuntimeError))",
8313
- " nitroApp.hooks.hook('request', async () => {",
8314
- " const result = await runtimeInstallation",
8315
- " if ('error' in result) throw result.error",
8316
- " })"
8431
+ " }).catch(captureRuntimeError))"
8317
8432
  ] : [],
8318
8433
  "})",
8319
8434
  "",
@@ -8612,7 +8727,7 @@ function shouldEmitStandaloneProviderOutput(definitions, options) {
8612
8727
  return definitions.length > 0;
8613
8728
  }
8614
8729
  function readNitroPreset(nitro) {
8615
- return isRecord(nitro) && typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOST || "";
8730
+ return isObject(nitro) && typeof nitro.preset === "string" ? nitro.preset : process.env.NITRO_PRESET || process.env.SERVER_PRESET || process.env.VITEHUB_HOST || "";
8616
8731
  }
8617
8732
  function keepsScheduleRunsInWorkerMemory(nitroPreset, processRuntime, schedules) {
8618
8733
  return !processRuntime && schedules > 0 && nitroPreset.startsWith("cloudflare");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/schedule",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Schedule primitives and definition discovery for ViteHub.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -75,7 +75,7 @@
75
75
  },
76
76
  "dependencies": {
77
77
  "@valibot/to-json-schema": "^1.8.0",
78
- "@vite-hub/runtime": "0.7.0",
78
+ "@vite-hub/runtime": "0.8.0",
79
79
  "cron-schedule": "^8.0.1",
80
80
  "magic-string": "^1.4.5",
81
81
  "nostics": "1.4.0",
@@ -84,8 +84,9 @@
84
84
  "devDependencies": {
85
85
  "@types/node": "^24.19.2",
86
86
  "@vite-hub/internal": "0.0.1",
87
- "@vite-hub/kv": "0.7.0",
87
+ "@vite-hub/kv": "0.8.0",
88
88
  "esbuild": "^0.28.2",
89
+ "fast-check": "^4.11.0",
89
90
  "nitro": "^3.0.261103-rc",
90
91
  "postgres": "^3.4.9",
91
92
  "publint": "^0.3.25",
@@ -95,7 +96,7 @@
95
96
  "vitest": "5.1.0"
96
97
  },
97
98
  "peerDependencies": {
98
- "@vite-hub/kv": "0.7.0",
99
+ "@vite-hub/kv": "0.8.0",
99
100
  "nitro": "3.0.261102-rc || ^3.0.261103-rc",
100
101
  "vite": ">=8.0.0"
101
102
  },