@vite-hub/workflow 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +79 -44
  2. package/dist/{app-CmMq8l4t.js → app-2Y7sBAG6.js} +1 -1
  3. package/dist/{client-CU5rELC0.js → client-CgBcDlGn.js} +155 -80
  4. package/dist/{cloudflare-BfFnNWB0.js → cloudflare-Datj_znU.js} +1 -1
  5. package/dist/{config-DCvRDlxA.js → config-z1651xc2.js} +1 -1
  6. package/dist/definition.d.ts +10 -11
  7. package/dist/definition.js +24 -22
  8. package/dist/{delay--ESDybVT.js → delay-CHN4tv3i.js} +6 -42
  9. package/dist/durability.d.ts +1 -1
  10. package/dist/{error-diagnostics-DSkCJC_L.js → error-diagnostics-C0KyI408.js} +10 -2
  11. package/dist/{error-diagnostics-8YNJ37rP.js → error-diagnostics-DMeaFmQD.js} +68 -19
  12. package/dist/{errors-DCqRnZpN.js → errors-BNxEeeCO.js} +0 -4
  13. package/dist/{errors-DVwFb6Fd.d.ts → errors-D-fNDVg0.d.ts} +12 -6
  14. package/dist/index.d.ts +32 -11
  15. package/dist/index.js +13 -6
  16. package/dist/{openworkflow-TEaNk0LV.d.ts → openworkflow-BoaENgh9.d.ts} +8 -7
  17. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-CI2PJGqu.d.ts} +13 -2
  18. package/dist/{operations-B0L8kV5s.js → operations-CYntpf-T.js} +34 -41
  19. package/dist/operations.d.ts +5 -8
  20. package/dist/operations.js +27 -32
  21. package/dist/{out-fRNaVslw.js → out-DxLKolA0.js} +1 -1
  22. package/dist/{rolldown-runtime-CMFfr-1z.js → rolldown-runtime-B4iAMlE-.js} +10 -1
  23. package/dist/{run-error-DBWqiJHH.js → run-error-Ctn50EYz.js} +1 -2
  24. package/dist/run-failed-gVGo1BaF.js +18 -0
  25. package/dist/runtime/cloudflare-runner.d.ts +12 -2
  26. package/dist/runtime/cloudflare-runner.js +28 -9
  27. package/dist/runtime/cloudflare-vite.d.ts +1 -1
  28. package/dist/runtime/cloudflare-vite.js +2 -2
  29. package/dist/runtime/dev-runs.js +1 -0
  30. package/dist/runtime/execute.d.ts +25 -4
  31. package/dist/runtime/execute.js +168 -43
  32. package/dist/runtime/openworkflow-worker.d.ts +2 -2
  33. package/dist/runtime/openworkflow-worker.js +4 -9
  34. package/dist/runtime/openworkflow.d.ts +2 -2
  35. package/dist/runtime/openworkflow.js +60 -49
  36. package/dist/runtime/state.d.ts +1 -1
  37. package/dist/runtime/state.js +4 -6
  38. package/dist/runtime/vercel-vite.d.ts +1 -1
  39. package/dist/runtime/vercel-vite.js +2 -2
  40. package/dist/signals-C1iolifd.js +80 -0
  41. package/dist/{types-CnKVDnEp.d.ts → types-BWPHeugk.d.ts} +99 -28
  42. package/dist/{vercel-BZU_O6ay.js → vercel-BIkBFrQQ.js} +6 -14
  43. package/dist/vite.d.ts +27 -16
  44. package/dist/vite.js +3404 -961
  45. package/package.json +4 -4
@@ -1,15 +1,14 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
2
- import { n as createWorkflowError } from "../errors-DCqRnZpN.js";
3
- import { i as runWorkflowProviderOperation } from "../run-error-DBWqiJHH.js";
4
- import { describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter } from "./openworkflow.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-DMeaFmQD.js";
2
+ import { n as createWorkflowError } from "../errors-BNxEeeCO.js";
5
3
  import { getWorkflowRuntimeConfig, getWorkflowRuntimeRegistry, loadWorkflowDefinition, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from "./state.js";
4
+ import { i as runWorkflowProviderOperation } from "../run-error-Ctn50EYz.js";
5
+ import { describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter } from "./openworkflow.js";
6
6
  import { ViteHubError } from "@vite-hub/runtime";
7
7
  import { onShutdown } from "@vite-hub/runtime/internal/shutdown";
8
8
  //#region src/runtime/openworkflow-worker.ts
9
9
  function getProcess() {
10
10
  return globalThis.process;
11
11
  }
12
- /** Registers every Workflow Definition of the registry on the OpenWorkflow client, before a worker copies them. */
13
12
  async function prepareOpenWorkflowWorker(options) {
14
13
  const config = options.config ?? getWorkflowRuntimeConfig();
15
14
  if (!config || config.driver !== "openworkflow") throw workflowErrorDiagnostics.WORKFLOW_R0017({ message: "OpenWorkflow worker requires workflow.driver \"openworkflow\"." });
@@ -138,10 +137,6 @@ const bundledOpenWorkflowModules = {
138
137
  "postgres": () => import("postgres")
139
138
  };
140
139
  const openWorkflowStartDelayMs = 500;
141
- /**
142
- * Errors that a new attempt cannot fix, because the configuration must change first. `WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE` is not one: a
143
- * pool that is full with other traffic when the server starts gives a second connection later.
144
- */
145
140
  const permanentSetupErrorCodes = /* @__PURE__ */ new Set(["WORKFLOW_OPENWORKFLOW_DATABASE_URL_MISSING", "WORKFLOW_OPENWORKFLOW_DATABASE_URL_IGNORED"]);
146
141
  function hasPermanentSetupError(error) {
147
142
  for (let current = error, depth = 0; current && typeof current === "object" && depth < 8; depth++) {
@@ -1,2 +1,2 @@
1
- import { a as getOpenWorkflowRun, c as resetOpenWorkflowRuntime, d as setOpenWorkflowImporter, i as detachOpenWorkflowRuntimes, l as runOpenWorkflow, n as cancelOpenWorkflowRun, o as getOpenWorkflowRuntime, r as describeOpenWorkflowStorage, s as registerOpenWorkflowDefinition, t as OpenWorkflowStorageSource, u as setOpenWorkflowDatabaseUrl } from "../openworkflow-TEaNk0LV.js";
2
- export { OpenWorkflowStorageSource, cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
1
+ import { a as getOpenWorkflowRun, c as resetOpenWorkflowRuntime, d as setOpenWorkflowDatabaseUrl, f as setOpenWorkflowImporter, i as detachOpenWorkflowRuntimes, l as resumeOpenWorkflowSignal, n as cancelOpenWorkflowRun, o as getOpenWorkflowRuntime, r as describeOpenWorkflowStorage, s as registerOpenWorkflowDefinition, t as OpenWorkflowStorageSource, u as runOpenWorkflow } from "../openworkflow-BoaENgh9.js";
2
+ export { OpenWorkflowStorageSource, cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, resumeOpenWorkflowSignal, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
@@ -1,10 +1,11 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-DMeaFmQD.js";
2
2
  import { t as resolveOpenWorkflowStorage } from "../openworkflow-storage-Dj9zUAsk.js";
3
- import { n as createWorkflowError } from "../errors-DCqRnZpN.js";
4
- import { readNonRetryableStepResult, runSerializedWorkflowHandler, toNonRetryableStepResult } from "./execute.js";
3
+ import { n as createWorkflowError } from "../errors-BNxEeeCO.js";
4
+ import { readNonRetryableStepResult, resolveWorkflowStepOptions, runSerializedWorkflowHandler, toDurationMilliseconds, toNonRetryableStepResult, withWorkflowStepTimeout } from "./execute.js";
5
+ import { t as emitWorkflowFailed } from "../run-failed-gVGo1BaF.js";
5
6
  import { r as invariantError, t as defaultOpenWorkflowSqlitePath } from "../openworkflow-defaults-DDig2M4s.js";
6
- import { i as runWorkflowProviderOperation, n as getWorkflowProviderStatus, t as toWorkflowRunError } from "../run-error-DBWqiJHH.js";
7
- import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime";
7
+ import { i as runWorkflowProviderOperation, n as getWorkflowProviderStatus, t as toWorkflowRunError } from "../run-error-Ctn50EYz.js";
8
+ import { deserializeResponse, isSerializedResponse } from "@vite-hub/runtime/internal/response";
8
9
  //#region src/runtime/openworkflow.ts
9
10
  const defaultImporter = (specifier) => import(
10
11
  /* @vite-ignore */
@@ -50,7 +51,6 @@ let databaseUrlResolver;
50
51
  function setOpenWorkflowDatabaseUrl(resolve) {
51
52
  databaseUrlResolver = resolve;
52
53
  }
53
- /** The Postgres URL of the Default Database, when the app has a Postgres Default Database. */
54
54
  function readDatabasePostgresUrl() {
55
55
  if (!databaseUrlResolver) return void 0;
56
56
  const url = databaseUrlResolver()?.trim();
@@ -97,14 +97,11 @@ function getOpenWorkflowConfig(config) {
97
97
  source: "default"
98
98
  };
99
99
  }
100
- /** How long a server waits for the setup lock that another server holds, before the worker start tries again. */
101
100
  const postgresSetupWaitMs = 12e4;
102
- /** How long the server that holds the setup lock waits for the second connection that the OpenWorkflow migration needs. */
103
101
  const postgresSecondConnectionTimeoutMs = 1e4;
104
102
  function sleep(ms) {
105
103
  return new Promise((resolve) => setTimeout(resolve, ms).unref?.());
106
104
  }
107
- /** Resolves `true` when `task` settles first, `false` when `ms` passes first. */
108
105
  function settlesWithin(task, ms) {
109
106
  let timer;
110
107
  return Promise.race([task.then(() => true), new Promise((resolve) => {
@@ -112,23 +109,6 @@ function settlesWithin(task, ms) {
112
109
  timer.unref?.();
113
110
  })]).finally(() => clearTimeout(timer));
114
111
  }
115
- /**
116
- * OpenWorkflow creates its Postgres schema without a lock. When servers start together, all but one fail with
117
- * `duplicate key value violates unique constraint`, and OpenWorkflow leaves the failed migration connection open in an
118
- * aborted transaction. So one server at a time sets up the schema, and the others then find it up to date.
119
- *
120
- * OpenWorkflow does not export its migrations, so they cannot run on the connection that holds the lock: they run on a
121
- * connection that `BackendPostgres.connect()` opens.
122
- * - A server tries the lock with `pg_try_advisory_xact_lock` in a short transaction. A server that does not get it
123
- * commits at once and tries again later, so a waiting server holds no connection.
124
- * - The server that gets it first checks that it can open a second connection. A pool of one connection, such as a
125
- * pooler with one server connection, cannot run the migration while the lock holds that connection, so the server
126
- * stops with `WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE` before the setup starts.
127
- * - Then it holds the lock until OpenWorkflow finished the setup.
128
- * A transaction lock also works through a pooler in transaction mode, such as PgBouncer.
129
- * OpenWorkflow 0.11.0 locks its setup with a session lock
130
- * (https://github.com/openworkflowdev/openworkflow/commit/eb544db), which such a pooler does not keep, so this lock stays.
131
- */
132
112
  async function withPostgresSetupLock(postgres, url, schema, setup) {
133
113
  const sql = postgres.default(url, {
134
114
  idle_timeout: 1,
@@ -163,7 +143,20 @@ async function withPostgresSetupLock(postgres, url, schema, setup) {
163
143
  await sql.end({ timeout: 5 });
164
144
  }
165
145
  }
146
+ function reportFailedRuns(backend, definitions) {
147
+ const failWorkflowRun = async (params) => {
148
+ const run = await backend.failWorkflowRun(params);
149
+ if (run.status === "failed") await emitWorkflowFailed(run.workflowName, run.idempotencyKey || run.id, run.error ?? params.error, definitions.get(run.workflowName));
150
+ return run;
151
+ };
152
+ return new Proxy(backend, { get(target, property) {
153
+ if (property === "failWorkflowRun") return failWorkflowRun;
154
+ const value = Reflect.get(target, property);
155
+ return typeof value === "function" ? value.bind(target) : value;
156
+ } });
157
+ }
166
158
  async function createOpenWorkflowRuntime(options, importer) {
159
+ const definitions = /* @__PURE__ */ new Map();
167
160
  const [{ OpenWorkflow }, backendModule] = await Promise.all([importOpenWorkflowModule("openworkflow", importer), options.backend === "sqlite" ? importOpenWorkflowModule("openworkflow/sqlite", importer) : importOpenWorkflowModule("openworkflow/postgres", importer)]);
168
161
  const { backend, client } = await runWorkflowProviderOperation("openworkflow", "connect", async () => {
169
162
  let backend;
@@ -182,12 +175,13 @@ async function createOpenWorkflowRuntime(options, importer) {
182
175
  }
183
176
  return {
184
177
  backend,
185
- client: new OpenWorkflow({ backend })
178
+ client: new OpenWorkflow({ backend: reportFailedRuns(backend, definitions) })
186
179
  };
187
180
  });
188
181
  return {
189
182
  backend,
190
183
  client,
184
+ definitions,
191
185
  findRunId: createRunIdLookup(backend, options),
192
186
  workflows: /* @__PURE__ */ new Map()
193
187
  };
@@ -203,10 +197,6 @@ function readRowId(row) {
203
197
  const id = Reflect.get(row, "id");
204
198
  return typeof id === "string" ? id : void 0;
205
199
  }
206
- /**
207
- * ViteHub starts a run with the caller's id as the OpenWorkflow idempotency key, and OpenWorkflow gives the run its own
208
- * UUID. The OpenWorkflow API reads runs by UUID only, so this lookup reads the key from the backend connection.
209
- */
210
200
  function createRunIdLookup(backend, options) {
211
201
  const connection = Reflect.get(backend, options.backend === "sqlite" ? "db" : "pg");
212
202
  return async (name, key) => {
@@ -250,24 +240,26 @@ async function getOpenWorkflowRuntime(config) {
250
240
  });
251
241
  return resolved;
252
242
  }
253
- function toOpenWorkflowRetryPolicy(options) {
254
- const retries = options.retries;
255
- if (!retries) return;
243
+ function toOpenWorkflowRetryPolicy(name, options) {
244
+ const { backoff, delay, limit } = resolveWorkflowStepOptions(name, options).retries;
245
+ const initial = toDurationMilliseconds(delay);
246
+ const coefficient = backoff === "exponential" ? 2 : 1;
256
247
  return {
257
- ...retries.backoff ? { backoffCoefficient: retries.backoff === "exponential" ? 2 : 1 } : {},
258
- ...retries.delay ? { initialInterval: retries.delay } : {},
259
- ...typeof retries.limit === "number" ? { maximumAttempts: retries.limit } : {}
248
+ backoffCoefficient: coefficient,
249
+ initialInterval: `${initial}ms`,
250
+ maximumAttempts: limit + 1,
251
+ maximumInterval: `${initial * coefficient ** Math.max(limit - 1, 0)}ms`
260
252
  };
261
253
  }
262
- function createOpenWorkflowProviderStep(step) {
254
+ function createOpenWorkflowProviderStep(step, workflow) {
263
255
  return {
264
256
  async do(name, options, run) {
265
257
  const output = await step.run({
266
258
  name,
267
- ...toOpenWorkflowRetryPolicy(options) ? { retryPolicy: toOpenWorkflowRetryPolicy(options) } : {}
259
+ retryPolicy: toOpenWorkflowRetryPolicy(name, options)
268
260
  }, async () => {
269
261
  try {
270
- return await run();
262
+ return await withWorkflowStepTimeout(name, options.timeout, run)();
271
263
  } catch (error) {
272
264
  const result = toNonRetryableStepResult(error);
273
265
  if (result) return result;
@@ -278,13 +270,38 @@ function createOpenWorkflowProviderStep(step) {
278
270
  if (error) throw error;
279
271
  return output;
280
272
  },
281
- sleep: async (name, milliseconds) => await step.sleep(name, `${milliseconds}ms`)
273
+ sleep: async (name, milliseconds) => await step.sleep(name, `${milliseconds}ms`),
274
+ async waitForSignal(name, token) {
275
+ const received = await step.waitForSignal({
276
+ name,
277
+ signal: token
278
+ });
279
+ if (received === null) throw workflowErrorDiagnostics.WORKFLOW_SIGNAL_TIMEOUT({ name: workflow });
280
+ return received.data;
281
+ }
282
282
  };
283
283
  }
284
+ /**
285
+ * Sends `value` to a live run that waits for the signal `token`. OpenWorkflow drops early signals and can match
286
+ * a wait left behind by cancellation, so check the run before sending.
287
+ */
288
+ async function resumeOpenWorkflowSignal(config, workflow, id, token, value) {
289
+ const runtime = await getOpenWorkflowRuntime(config);
290
+ return await runWorkflowProviderOperation("openworkflow", "resume-signal", async () => {
291
+ const run = await runtime.backend.getWorkflowRun({ workflowRunId: await runtime.findRunId(workflow, id) ?? id });
292
+ if (!run || run.workflowName !== workflow || terminalOpenWorkflowStatuses.has(normalizeOpenWorkflowStatus(run.status))) return false;
293
+ const { workflowRunIds } = await runtime.client.sendSignal({
294
+ data: value,
295
+ signal: token
296
+ });
297
+ return workflowRunIds.includes(run.id);
298
+ });
299
+ }
284
300
  async function registerOpenWorkflowDefinition(runtime, name, definition) {
285
301
  const existing = runtime.workflows.get(name);
286
302
  if (existing) return existing;
287
303
  const openWorkflowDefinition = definition;
304
+ runtime.definitions.set(name, definition);
288
305
  const workflow = runtime.client.defineWorkflow({ name }, async ({ input, run, step }) => {
289
306
  const stored = await runtime.backend.getWorkflowRun({ workflowRunId: run.id });
290
307
  return await runSerializedWorkflowHandler({
@@ -292,7 +309,7 @@ async function registerOpenWorkflowDefinition(runtime, name, definition) {
292
309
  name,
293
310
  payload: input,
294
311
  provider: "openworkflow",
295
- step: createOpenWorkflowProviderStep(step)
312
+ step: createOpenWorkflowProviderStep(step, name)
296
313
  }, openWorkflowDefinition);
297
314
  });
298
315
  runtime.workflows.set(name, workflow);
@@ -335,12 +352,10 @@ function serializeOpenWorkflowRun(run, name) {
335
352
  status
336
353
  };
337
354
  }
338
- /** OpenWorkflow stores `name`, `message`, and `stack`. The stack has server paths, so the step keeps the message only. */
339
355
  function toWorkflowRunStepError(error) {
340
356
  const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : void 0;
341
357
  return { message: typeof message === "string" && message ? message : "Workflow step failed." };
342
358
  }
343
- /** OpenWorkflow stores one row per step attempt. A run reports each step once, with its latest attempt. */
344
359
  function toWorkflowRunSteps(attempts) {
345
360
  const steps = /* @__PURE__ */ new Map();
346
361
  for (const attempt of attempts) {
@@ -423,10 +438,6 @@ const terminalOpenWorkflowStatuses = /* @__PURE__ */ new Set([
423
438
  "completed",
424
439
  "failed"
425
440
  ]);
426
- /**
427
- * Cancels a pending or running OpenWorkflow run of this Workflow and returns its state afterwards. A run of another
428
- * Workflow, or an unknown run, reports `unknown` without being cancelled. A finished run keeps and reports its status.
429
- */
430
441
  async function cancelOpenWorkflowRun(config, name, id) {
431
442
  const current = await getOpenWorkflowRun(config, name, id);
432
443
  if (current.status === "unknown" || terminalOpenWorkflowStatuses.has(current.status)) return current;
@@ -468,4 +479,4 @@ function setOpenWorkflowImporter(importer) {
468
479
  openWorkflowImporter = importer;
469
480
  }
470
481
  //#endregion
471
- export { cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
482
+ export { cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, resumeOpenWorkflowSignal, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
@@ -1,4 +1,4 @@
1
- import { f as WorkflowDefinition, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-CnKVDnEp.js";
1
+ import { f as WorkflowDefinition, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-BWPHeugk.js";
2
2
  //#region src/runtime/state.d.ts
3
3
  export interface WorkflowRunState<TResult = unknown> {
4
4
  error?: unknown;
@@ -1,6 +1,6 @@
1
- import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
2
- import { assertWorkflowDefinitionName } from "../definition.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-DMeaFmQD.js";
3
2
  import { n as setWorkflowDevRecorder } from "../dev-recorder-CTN5Fkao.js";
3
+ import { a as resetInlineWorkflowSignals } from "../signals-C1iolifd.js";
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
5
  //#region src/runtime/state.ts
6
6
  const RUNS_LIMIT = 1024;
@@ -153,10 +153,7 @@ async function loadWorkflowDefinition(name) {
153
153
  const registeredInlineDefinition = loadingInlineDefinitions.get(name) ?? (generation === runtimeRegistryGeneration ? consumeInlineWorkflowDefinition(name) : void 0);
154
154
  if (registeredInlineDefinition) consumeInlineWorkflowDefinition(name, registeredInlineDefinition);
155
155
  const definition = "default" in loaded ? loaded.default : loaded;
156
- if (definition && typeof definition.handler === "function") {
157
- assertWorkflowDefinitionName(name, definition);
158
- return definition;
159
- }
156
+ if (definition && typeof definition.handler === "function") return definition;
160
157
  if (registeredInlineDefinition) return registeredInlineDefinition;
161
158
  const exportedInlineDefinition = findExportedInlineWorkflowDefinition(name, loaded, loadingInlineDefinitions);
162
159
  if (!exportedInlineDefinition) return void 0;
@@ -247,6 +244,7 @@ function resetWorkflowRuntime() {
247
244
  inFlightRuns.clear();
248
245
  fallbackRunKeys.clear();
249
246
  completedRuns.clear();
247
+ resetInlineWorkflowSignals();
250
248
  setWorkflowDevRecorder(void 0);
251
249
  }
252
250
  //#endregion
@@ -1,4 +1,4 @@
1
- import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-CnKVDnEp.js";
1
+ import { l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-BWPHeugk.js";
2
2
  import { t as VitehubApp } from "../app-BojnC_yf.js";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  //#region src/runtime/vercel.d.ts
@@ -1,6 +1,6 @@
1
1
  import { runWithWorkflowRuntimeEvent, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry } from "./state.js";
2
- import { i as setVercelWorkflowRuntimeModules } from "../vercel-BZU_O6ay.js";
3
- import { t as resolveAppFetch } from "../app-CmMq8l4t.js";
2
+ import { i as setVercelWorkflowRuntimeModules } from "../vercel-BIkBFrQQ.js";
3
+ import { t as resolveAppFetch } from "../app-2Y7sBAG6.js";
4
4
  import { waitUntil } from "@vercel/functions";
5
5
  import { H3 } from "h3";
6
6
  //#region ../internal/src/runtime/vercel-hosted.ts
@@ -0,0 +1,80 @@
1
+ import { t as workflowErrorDiagnostics } from "./error-diagnostics-DMeaFmQD.js";
2
+ //#region src/runtime/signals.ts
3
+ const tokenPrefix = "vhsig1.";
4
+ const hosts = /* @__PURE__ */ new Set([
5
+ "cloudflare",
6
+ "inline",
7
+ "openworkflow"
8
+ ]);
9
+ function toBase64Url(text) {
10
+ let binary = "";
11
+ for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);
12
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
13
+ }
14
+ function fromBase64Url(value) {
15
+ const binary = atob(value.replaceAll("-", "+").replaceAll("_", "/"));
16
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
17
+ }
18
+ function createWorkflowSignalToken({ host, run, signal, workflow }) {
19
+ return `${tokenPrefix}${toBase64Url(JSON.stringify([
20
+ host,
21
+ workflow,
22
+ run,
23
+ signal
24
+ ]))}`;
25
+ }
26
+ /** The address in a token of `context.createSignal()`, or undefined for any other string. */
27
+ function readWorkflowSignalToken(token) {
28
+ if (!token.startsWith(tokenPrefix)) return void 0;
29
+ let value;
30
+ try {
31
+ value = JSON.parse(fromBase64Url(token.slice(7)));
32
+ } catch {
33
+ return;
34
+ }
35
+ if (!Array.isArray(value) || value.length !== 4 || !value.every((part) => typeof part === "string" && part !== "")) return void 0;
36
+ const [host, workflow, run, signal] = value;
37
+ if (!hosts.has(host)) return void 0;
38
+ return {
39
+ host,
40
+ run,
41
+ signal,
42
+ workflow
43
+ };
44
+ }
45
+ const inlineSignals = /* @__PURE__ */ new Map();
46
+ /** Adds the inline signal of `token`, so a `resumeWorkflow()` call before the wait keeps its value. */
47
+ function openInlineWorkflowSignal(token) {
48
+ if (!inlineSignals.has(token)) inlineSignals.set(token, {});
49
+ }
50
+ /** Forgets the inline signals of a run that ended. A later `resumeWorkflow()` call fails with `WORKFLOW_SIGNAL_NOT_WAITING`. */
51
+ function closeInlineWorkflowSignals(tokens) {
52
+ for (const token of tokens) inlineSignals.delete(token);
53
+ }
54
+ /** Waits in memory for the value of `resumeWorkflow(token, value)`. */
55
+ async function waitForInlineWorkflowSignal(token) {
56
+ const entry = inlineSignals.get(token) ?? {};
57
+ inlineSignals.set(token, entry);
58
+ if (entry.sent) {
59
+ inlineSignals.delete(token);
60
+ return entry.sent.value;
61
+ }
62
+ return await new Promise((resolve) => {
63
+ entry.resolve = (value) => {
64
+ inlineSignals.delete(token);
65
+ resolve(value);
66
+ };
67
+ });
68
+ }
69
+ /** Sends `value` to the inline signal of `token`. Fails when no run of this process has the signal open. */
70
+ function resumeInlineWorkflowSignal(token, address, value) {
71
+ const entry = inlineSignals.get(token);
72
+ if (!entry || entry.sent) throw workflowErrorDiagnostics.WORKFLOW_SIGNAL_NOT_WAITING({ run: address.run });
73
+ if (entry.resolve) entry.resolve(value);
74
+ else entry.sent = { value };
75
+ }
76
+ function resetInlineWorkflowSignals() {
77
+ inlineSignals.clear();
78
+ }
79
+ //#endregion
80
+ export { resetInlineWorkflowSignals as a, readWorkflowSignalToken as i, createWorkflowSignalToken as n, resumeInlineWorkflowSignal as o, openInlineWorkflowSignal as r, waitForInlineWorkflowSignal as s, closeInlineWorkflowSignals as t };
@@ -1,3 +1,4 @@
1
+ import { Duration, Result } from "@vite-hub/runtime";
1
2
  //#region src/types.d.ts
2
3
  type WorkflowDriver = "cloudflare" | "openworkflow" | "vercel";
3
4
  interface CloudflareWorkflowBinding<TPayload = unknown> {
@@ -10,6 +11,11 @@ interface CloudflareWorkflowBinding<TPayload = unknown> {
10
11
  interface CloudflareWorkflowInstance {
11
12
  id: string;
12
13
  status: () => Promise<unknown>;
14
+ /** Sends an event that `step.waitForEvent()` of the instance waits for. */
15
+ sendEvent?: (event: {
16
+ payload: unknown;
17
+ type: string;
18
+ }) => Promise<void>;
13
19
  /** Stops the instance. Cloudflare rejects the call when the instance has already finished. */
14
20
  terminate: () => Promise<void>;
15
21
  }
@@ -113,20 +119,54 @@ interface WorkflowRunStep {
113
119
  startedAt?: Date;
114
120
  status: WorkflowRunStatus;
115
121
  }
122
+ /** How the wait between retries grows: `exponential` doubles it after each retry, `constant` keeps it. */
123
+ type WorkflowStepBackoff = "constant" | "exponential";
124
+ /** When a step runs again after it throws. The defaults are `{ limit: 3, delay: '10 seconds', backoff: 'exponential' }`. */
125
+ interface WorkflowStepRetries {
126
+ backoff?: WorkflowStepBackoff;
127
+ /** How long to wait before the first retry. */
128
+ delay?: WorkflowDuration;
129
+ /** How many times to run the step again after the first attempt fails. `0` runs it once. */
130
+ limit?: number;
131
+ }
132
+ /**
133
+ * The options of one step. A step file exports them as `retries` and `timeout`. `timeout` is the time limit of one
134
+ * attempt: when it passes, the step's `signal` aborts and the attempt fails with `WORKFLOW_STEP_TIMEOUT`.
135
+ */
116
136
  interface WorkflowStepOptions {
117
- retries?: {
118
- backoff?: string;
119
- delay?: string;
120
- limit?: number;
121
- };
137
+ retries?: WorkflowStepRetries;
138
+ timeout?: WorkflowDuration;
139
+ }
140
+ /** The second argument of a step function. */
141
+ interface WorkflowStepContext {
142
+ /** Aborts when the `timeout` of the step passes. Pass it to `fetch()` and other calls that take a signal. */
143
+ signal: AbortSignal;
122
144
  }
123
- type WorkflowStepFunction<TInput = unknown, TResult = unknown> = (input: TInput) => TResult | Promise<TResult>;
145
+ type WorkflowStepFunction<TInput = unknown, TResult = unknown> = (input: TInput, context: WorkflowStepContext) => TResult | Promise<TResult>;
124
146
  interface WorkflowProviderStep {
125
147
  do?: <TResult>(name: string, options: WorkflowStepOptions, run: () => TResult | Promise<TResult>) => Promise<TResult>;
126
148
  /** Sleeps for a number of milliseconds. ViteHub names each sleep by call order. */
127
149
  sleep?: (name: string, milliseconds: number) => Promise<void>;
128
150
  /** Sleeps until a date. Without it, ViteHub sleeps for the time that is left until the date. */
129
151
  sleepUntil?: (name: string, date: Date) => Promise<void>;
152
+ /**
153
+ * Waits durably until `resumeWorkflow(token, value)` sends the signal, and returns the value. ViteHub names each
154
+ * wait by call order (`signal-1`, `signal-2`).
155
+ */
156
+ waitForSignal?: (name: string, token: string) => Promise<unknown>;
157
+ }
158
+ /**
159
+ * A signal of one run, from `context.createSignal()`. Give `token` to the code that will resume the run, such as the
160
+ * webhook URL of an outside service. `wait()` returns the value of `resumeWorkflow(token, value)`.
161
+ */
162
+ interface WorkflowSignal<TValue = unknown> {
163
+ /**
164
+ * The token of this signal. It is the same on each replay of the run. It is not a secret: check the caller, such as
165
+ * a webhook signature, before you pass a token from a request to `resumeWorkflow()`.
166
+ */
167
+ readonly token: string;
168
+ /** Waits until `resumeWorkflow(token, value)` sends the signal, and returns the value. */
169
+ wait: () => Promise<TValue>;
130
170
  }
131
171
  type WorkflowDurationUnit = "second" | "minute" | "hour" | "day" | "week" | "month" | "year";
132
172
  /**
@@ -139,10 +179,30 @@ type WorkflowDuration = number | `${number} ${WorkflowDurationUnit}` | `${number
139
179
  * `.vitehub/workflow.d.ts` from the numbered files in `server/workflows/<name>/`.
140
180
  */
141
181
  interface WorkflowStepRegistry {}
182
+ /**
183
+ * The Workflow Definitions of the app, by name. ViteHub writes it to `.vitehub/workflow.d.ts` from the files in
184
+ * `server/workflows/`, so `startWorkflow()` checks the name and the payload.
185
+ */
186
+ interface WorkflowRegistry {}
187
+ /** A Workflow name from `WorkflowRegistry`. Any string before ViteHub writes the registry. */
188
+ type WorkflowName = [keyof WorkflowRegistry] extends [never] ? string : Extract<keyof WorkflowRegistry, string>;
189
+ /** The payload type of the Workflow `TName`, from the `payload` that its handler reads. */
190
+ type WorkflowPayload<TName extends string> = TName extends keyof WorkflowRegistry ? WorkflowRegistry[TName] extends {
191
+ handler: (context: infer TContext) => unknown;
192
+ } ? TContext extends {
193
+ payload: infer TPayload;
194
+ } ? TPayload : unknown : unknown : unknown;
142
195
  /** A step runs one input through its step file, inside a durable provider step. */
143
196
  type WorkflowStep<TStep> = TStep extends ((...args: infer TArguments) => infer TResult) ? (...input: TArguments extends [] ? [] : TArguments extends [unknown, ...unknown[]] ? [input: TArguments[0]] : [input?: TArguments[0]]) => Promise<Awaited<TResult>> : never;
144
- /** The step functions of the Workflow `TName`. Empty for a Workflow without step files. */
145
- type WorkflowSteps<TName extends string = string> = TName extends keyof WorkflowStepRegistry ? { readonly [TStep in keyof WorkflowStepRegistry[TName]]: WorkflowStep<WorkflowStepRegistry[TName][TStep]>; } : { readonly [TStep in never]: never; };
197
+ type StepsInFolder<TFolder> = TFolder extends unknown ? keyof TFolder : never;
198
+ type StepInFolder<TFolder, TStep> = TFolder extends unknown ? TStep extends keyof TFolder ? WorkflowStep<TFolder[TStep]> : never : never;
199
+ type WorkflowStepFolders = WorkflowStepRegistry[keyof WorkflowStepRegistry];
200
+ /**
201
+ * The step functions of the folder Workflows. A definition does not name its Workflow, so `steps` has the steps of
202
+ * every folder Workflow: a step name that no folder has is a type error. A shared step name accepts only inputs
203
+ * valid for all its implementations and returns any of their results. At runtime, a Workflow gets only its own steps.
204
+ */
205
+ type WorkflowSteps = { readonly [TStep in StepsInFolder<WorkflowStepFolders>]: StepInFolder<WorkflowStepFolders, TStep>; };
146
206
  /** Run data that a provider gives to ViteHub before ViteHub adds the step runner. */
147
207
  interface WorkflowProviderContext<TPayload = unknown> {
148
208
  id?: string;
@@ -151,10 +211,17 @@ interface WorkflowProviderContext<TPayload = unknown> {
151
211
  provider: WorkflowDriver;
152
212
  step?: WorkflowProviderStep;
153
213
  }
154
- interface WorkflowExecutionContext<TPayload = unknown, TName extends string = string> extends Omit<WorkflowProviderContext<TPayload>, "step"> {
155
- name: TName;
156
- /** The provider step runner. Use `context.sleep()` to sleep. */
157
- step?: Omit<WorkflowProviderStep, "sleep" | "sleepUntil">;
214
+ /** The one object that a Workflow handler receives: the `payload` of the run, the run data, `sleep`, and `steps`. */
215
+ interface WorkflowExecutionContext<TPayload = unknown> extends Omit<WorkflowProviderContext<TPayload>, "step"> {
216
+ /**
217
+ * Makes a signal that the run can wait for. `resumeWorkflow(signal.token, value)` ends the wait of
218
+ * `signal.wait()`. Only a folder Workflow's `index.ts` can wait: in a single-file Workflow, `wait()` throws
219
+ * `WORKFLOW_ROOT_STEP_SIGNAL`. The wait is durable on Cloudflare and OpenWorkflow. Inline runs (`vite dev`) wait in
220
+ * memory. Vercel does not support signals yet: `createSignal()` throws `WORKFLOW_SIGNAL_VERCEL_UNSUPPORTED`.
221
+ */
222
+ createSignal: <TValue = unknown>() => WorkflowSignal<TValue>;
223
+ /** The provider step runner. Use `context.sleep()` to sleep and `context.createSignal()` to wait for a signal. */
224
+ step?: Omit<WorkflowProviderStep, "sleep" | "sleepUntil" | "waitForSignal">;
158
225
  /**
159
226
  * Sleeps for a duration such as `'1 day'` or a number of milliseconds, or until a `Date`. Only a folder Workflow's
160
227
  * `index.ts` can sleep. In a single-file Workflow it throws `WORKFLOW_ROOT_STEP_SLEEP`. The sleep is durable on
@@ -162,9 +229,9 @@ interface WorkflowExecutionContext<TPayload = unknown, TName extends string = st
162
229
  */
163
230
  sleep: (until: WorkflowDuration | Date) => Promise<void>;
164
231
  /** Step functions from the numbered files in the Workflow folder. Empty when the Workflow has no step files. */
165
- steps: WorkflowSteps<TName>;
232
+ steps: WorkflowSteps;
166
233
  }
167
- type WorkflowHandler<TPayload = unknown, TResult = unknown, TName extends string = string> = (payload: TPayload, context: WorkflowExecutionContext<TPayload, TName>) => TResult | Promise<TResult>;
234
+ type WorkflowHandler<TPayload = unknown, TResult = unknown> = (context: WorkflowExecutionContext<TPayload>) => TResult | Promise<TResult>;
168
235
  type WorkflowRunIdValue = boolean | null | number | string | undefined | {
169
236
  readonly [key: string]: WorkflowRunIdValue;
170
237
  } | readonly WorkflowRunIdValue[];
@@ -179,34 +246,38 @@ interface WorkflowCreateOptions<TPayload = unknown, TResult = unknown> {
179
246
  name?: string;
180
247
  rootStep?: boolean;
181
248
  }
249
+ /** Options of `defineWorkflow()`, next to `handler`. */
182
250
  interface WorkflowDefinitionOptions<TPayload = unknown, TResult = unknown> {
183
- id?: string;
184
251
  /** Vercel native entry. Vercel calls it with the provider context only, so it gets no step runner. */
185
252
  native?: (context: WorkflowProviderContext<TPayload>) => TResult | Promise<TResult>;
186
253
  rootStep?: boolean;
187
254
  }
188
- interface WorkflowDefinition<TPayload = unknown, TResult = unknown, TName extends string = string> {
255
+ /** A Workflow Definition: `defineWorkflow({ handler, ...options })`. Its file path is its name. */
256
+ interface WorkflowDefinition<TPayload = unknown, TResult = unknown> extends WorkflowDefinitionOptions<TPayload, TResult> {
189
257
  /** @internal Identifies provider-generated Agent invocation recovery definitions. */
190
258
  internalAgentInvocationRecovery?: true;
191
259
  /** @internal Identifies the inline Agent Workflow handler that the Agent package creates for an Agent turn. */
192
260
  internalAgentWorkflow?: true;
193
- handler: WorkflowHandler<TPayload, TResult, TName>;
194
- /** The discovered Workflow name. `defineWorkflow()` sets it; inline and generated definitions may leave it out. */
195
- name?: string;
196
- options?: WorkflowDefinitionOptions<TPayload, TResult>;
261
+ handler: WorkflowHandler<TPayload, TResult>;
197
262
  }
198
263
  /** Omission is valid only when the handler accepts undefined. */
199
264
  type WorkflowStartArguments<TPayload> = undefined extends TPayload ? [payload?: TPayload, options?: WorkflowStartOptions] : [payload: TPayload, options?: WorkflowStartOptions];
265
+ /**
266
+ * Codes that `startWorkflow()`, `getWorkflowRun()`, `cancelWorkflow()`, `resumeWorkflow()`, and the methods of a
267
+ * WorkflowHandle return in the `[error, data]` tuple. Config errors throw instead.
268
+ */
269
+ type WorkflowResultErrorCode = "RUNTIME_DURATION_INVALID" | "WORKFLOW_CLOUDFLARE_RUN_ID_INVALID" | "WORKFLOW_OPERATION_UNSUPPORTED" | "WORKFLOW_PROVIDER_OPERATION_FAILED" | "WORKFLOW_R0014" | "WORKFLOW_RUN_ID_UNSUPPORTED" | "WORKFLOW_SIGNAL_NOT_WAITING" | "WORKFLOW_SIGNAL_TOKEN_INVALID" | "WORKFLOW_START_DELAY_INVALID";
270
+ /** `cancel()`, `getRun()`, and `start()` return `[error, data]`, as `cancelWorkflow()`, `getWorkflowRun()`, and `startWorkflow()` do. */
200
271
  interface WorkflowHandle<TPayload = unknown, TResult = unknown> {
201
- cancel: (id: string) => Promise<WorkflowRun<unknown, unknown>>;
272
+ cancel: (id: string) => Promise<Result<WorkflowRun<unknown, unknown>, WorkflowResultErrorCode>>;
202
273
  /** Starts a run after the response, through `waitUntil`. A failure goes to the log. */
203
274
  defer: (...args: WorkflowStartArguments<TPayload>) => void;
204
- getRun: (id: string) => Promise<WorkflowRun<unknown, unknown>>;
275
+ getRun: (id: string) => Promise<Result<WorkflowRun<unknown, unknown>, WorkflowResultErrorCode>>;
205
276
  name: string;
206
- start: (...args: WorkflowStartArguments<TPayload>) => Promise<WorkflowRun<TPayload, TResult>>;
277
+ start: (...args: WorkflowStartArguments<TPayload>) => Promise<Result<WorkflowRun<TPayload, TResult>, WorkflowResultErrorCode>>;
207
278
  }
208
- /** Milliseconds, a duration such as `"30 minutes"` or `"3 days"`, or a `Date` that the run must not start before. */
209
- type WorkflowStartDelay = number | string | Date;
279
+ /** A duration such as `"30m"` or `"3 days"`, or a `Date` that the run must not start before. */
280
+ type WorkflowStartDelay = Duration | Date;
210
281
  interface WorkflowStartOptions {
211
282
  /** Starts the run later. A `Date` in the past starts it now. */
212
283
  delay?: WorkflowStartDelay;
@@ -223,9 +294,9 @@ interface WorkflowSignalResult {
223
294
  */
224
295
  interface WorkflowDefinitionRegistry {
225
296
  [name: string]: (() => Promise<{
226
- default?: WorkflowDefinition<never, unknown, never>;
297
+ default?: WorkflowDefinition<never, unknown>;
227
298
  [exportName: string]: unknown;
228
- } | WorkflowDefinition<never, unknown, never>>) & {
299
+ } | WorkflowDefinition<never, unknown>>) & {
229
300
  /** @internal Identifies provider-generated Agent invocation recovery definitions without evaluating their modules. */
230
301
  internalAgentInvocationRecovery?: true;
231
302
  };
@@ -238,4 +309,4 @@ interface DiscoveredWorkflowDefinition {
238
309
  steps?: string[];
239
310
  }
240
311
  //#endregion
241
- export { WorkflowRuntimeConfigValue as A, WorkflowOptions as C, WorkflowRunError as D, WorkflowRun as E, WorkflowStep as F, WorkflowStepFunction as I, WorkflowStepOptions as L, WorkflowSignalResult as M, WorkflowStartDelay as N, WorkflowRunStatus as O, WorkflowStartOptions as P, WorkflowStepRegistry as R, WorkflowModuleDriverOptions as S, WorkflowProviderStep as T, WorkflowDuration as _, InferredWorkflowDriverOptions as a, WorkflowHandle as b, OpenWorkflowWorkerOptions as c, WorkflowCreateOptions as d, WorkflowDefinition as f, WorkflowDriverOptions as g, WorkflowDriver as h, DiscoveredWorkflowDefinition as i, WorkflowSharedOptions as j, WorkflowRunStep as k, ResolvedWorkflowOptions as l, WorkflowDefinitionRegistry as m, CloudflareWorkflowDriverOptions as n, OpenWorkflowDriverOptions as o, WorkflowDefinitionOptions as p, CloudflareWorkflowInstance as r, OpenWorkflowPostgresOptions as s, CloudflareWorkflowBinding as t, VercelWorkflowDriverOptions as u, WorkflowDurationUnit as v, WorkflowProviderContext as w, WorkflowHandler as x, WorkflowExecutionContext as y, WorkflowSteps as z };
312
+ export { WorkflowRun as A, WorkflowStartOptions as B, WorkflowName as C, WorkflowProviderStep as D, WorkflowProviderContext as E, WorkflowSharedOptions as F, WorkflowStepOptions as G, WorkflowStepBackoff as H, WorkflowSignal as I, WorkflowSteps as J, WorkflowStepRegistry as K, WorkflowSignalResult as L, WorkflowRunStatus as M, WorkflowRunStep as N, WorkflowRegistry as O, WorkflowRuntimeConfigValue as P, WorkflowStartArguments as R, WorkflowModuleDriverOptions as S, WorkflowPayload as T, WorkflowStepContext as U, WorkflowStep as V, WorkflowStepFunction as W, WorkflowDuration as _, InferredWorkflowDriverOptions as a, WorkflowHandle as b, OpenWorkflowWorkerOptions as c, WorkflowCreateOptions as d, WorkflowDefinition as f, WorkflowDriverOptions as g, WorkflowDriver as h, DiscoveredWorkflowDefinition as i, WorkflowRunError as j, WorkflowResultErrorCode as k, ResolvedWorkflowOptions as l, WorkflowDefinitionRegistry as m, CloudflareWorkflowDriverOptions as n, OpenWorkflowDriverOptions as o, WorkflowDefinitionOptions as p, WorkflowStepRetries as q, CloudflareWorkflowInstance as r, OpenWorkflowPostgresOptions as s, CloudflareWorkflowBinding as t, VercelWorkflowDriverOptions as u, WorkflowDurationUnit as v, WorkflowOptions as w, WorkflowHandler as x, WorkflowExecutionContext as y, WorkflowStartDelay as z };