@vite-hub/workflow 0.0.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +168 -47
  2. package/dist/{_app-DgwN4ulW.d.ts → app-BojnC_yf.d.ts} +1 -4
  3. package/dist/{app-BZpq2cwC.js → app-CmMq8l4t.js} +2 -1
  4. package/dist/client-CU5rELC0.js +658 -0
  5. package/dist/{cloudflare-D0Di-QYL.js → cloudflare-BfFnNWB0.js} +20 -4
  6. package/dist/cloudflare-env-CGLx7lUd.js +115 -0
  7. package/dist/cloudflare-env-lookup-CfX6wZKb.d.ts +4 -0
  8. package/dist/{cloudflare-env-CIjdFTv6.d.ts → cloudflare-shared-CTqh_a2s.d.ts} +2 -2
  9. package/dist/config-DCvRDlxA.js +145 -0
  10. package/dist/definition.d.ts +19 -0
  11. package/dist/definition.js +31 -0
  12. package/dist/delay--ESDybVT.js +81 -0
  13. package/dist/dev-recorder-CTN5Fkao.js +10 -0
  14. package/dist/durability.d.ts +23 -0
  15. package/dist/durability.js +62 -0
  16. package/dist/error-diagnostics-8YNJ37rP.js +286 -0
  17. package/dist/error-diagnostics-DSkCJC_L.js +266 -0
  18. package/dist/errors-DCqRnZpN.js +35 -0
  19. package/dist/errors-DVwFb6Fd.d.ts +56 -0
  20. package/dist/index.d.ts +23 -71
  21. package/dist/index.js +23 -378
  22. package/dist/inspect-B72iFyj-.js +70 -0
  23. package/dist/object-Da1zyPCR.js +11 -0
  24. package/dist/openworkflow-TEaNk0LV.d.ts +50 -0
  25. package/dist/openworkflow-defaults-DDig2M4s.js +26 -0
  26. package/dist/openworkflow-storage-Dj9zUAsk.js +28 -0
  27. package/dist/openworkflow.d.ts +2 -0
  28. package/dist/openworkflow.js +2 -0
  29. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  30. package/dist/operations-B0L8kV5s.js +329 -0
  31. package/dist/operations.d.ts +71 -0
  32. package/dist/operations.js +314 -0
  33. package/dist/out-fRNaVslw.js +20357 -0
  34. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  35. package/dist/run-error-DBWqiJHH.js +110 -0
  36. package/dist/runtime/cloudflare-runner.d.ts +7 -19
  37. package/dist/runtime/cloudflare-runner.js +27 -10
  38. package/dist/runtime/cloudflare-shared.d.ts +2 -1
  39. package/dist/runtime/cloudflare-shared.js +1 -1
  40. package/dist/runtime/cloudflare-vite.d.ts +10 -11
  41. package/dist/runtime/cloudflare-vite.js +47 -1
  42. package/dist/runtime/dev-runs.d.ts +4 -0
  43. package/dist/runtime/dev-runs.js +73 -0
  44. package/dist/runtime/execute.d.ts +24 -7
  45. package/dist/runtime/execute.js +135 -6
  46. package/dist/runtime/openworkflow-worker.d.ts +34 -9
  47. package/dist/runtime/openworkflow-worker.js +156 -37
  48. package/dist/runtime/openworkflow.d.ts +2 -23
  49. package/dist/runtime/openworkflow.js +289 -46
  50. package/dist/runtime/state.d.ts +22 -21
  51. package/dist/runtime/state.js +99 -25
  52. package/dist/runtime/vercel-vite.d.ts +10 -12
  53. package/dist/runtime/vercel-vite.js +7 -4
  54. package/dist/types-CnKVDnEp.d.ts +241 -0
  55. package/dist/{vercel-B0MuIVgJ.js → vercel-BZU_O6ay.js} +78 -24
  56. package/dist/vite.d.ts +529 -23
  57. package/dist/vite.js +2789 -1609
  58. package/package.json +62 -34
  59. package/dist/cloudflare-env-DjxQNbrx.js +0 -58
  60. package/dist/cloudflare-shared-BVVgDSdq.d.ts +0 -1
  61. package/dist/cloudflare-vite-BkDgB6Sr.js +0 -46
  62. package/dist/config-BHknO_rT.js +0 -136
  63. package/dist/provider-operation-CW2cYfVy.js +0 -65
  64. package/dist/runtime-type-DGUn8Ple.js +0 -37
  65. package/dist/types-B9RdRkKh.d.ts +0 -169
@@ -1,9 +1,16 @@
1
- import { a as createWorkflowError, r as runWorkflowProviderOperation, t as getWorkflowProviderStatus } from "../provider-operation-CW2cYfVy.js";
2
- import { runWorkflowHandler } from "./execute.js";
1
+ import { t as workflowErrorDiagnostics } from "../error-diagnostics-8YNJ37rP.js";
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";
5
+ 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";
3
8
  //#region src/runtime/openworkflow.ts
4
- const defaultImporter = new Function("specifier", "return import(specifier)");
9
+ const defaultImporter = (specifier) => import(
10
+ /* @vite-ignore */
11
+ specifier
12
+ );
5
13
  let openWorkflowImporter = defaultImporter;
6
- const defaultOpenWorkflowSqlitePath = ".vitehub/data/openworkflow.sqlite.db";
7
14
  let runtimes = /* @__PURE__ */ new Map();
8
15
  async function importOpenWorkflowModule(specifier, importer) {
9
16
  return await runWorkflowProviderOperation("openworkflow", "import", () => importer(specifier));
@@ -24,8 +31,8 @@ function getRuntimeEnvNames(value) {
24
31
  return value.source?.names ?? (value.source?.name ? [value.source.name] : []);
25
32
  }
26
33
  function normalizeSqlitePath(path) {
27
- if (/^(?:libsql:|https?:\/\/)/i.test(path)) throw new Error(`OpenWorkflow SQLite storage requires a local SQLite file path, received ${JSON.stringify(path)}.`);
28
- if (/^[a-z][a-z0-9+.-]*:/i.test(path) && !path.startsWith("file:")) throw new Error(`OpenWorkflow SQLite storage received unsupported storage URL ${JSON.stringify(path)}.`);
34
+ if (/^(?:libsql:|https?:\/\/)/i.test(path)) throw workflowErrorDiagnostics.WORKFLOW_R0018({ message: `OpenWorkflow SQLite storage requires a local SQLite file path, received ${JSON.stringify(path)}.` });
35
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path) && !path.startsWith("file:")) throw workflowErrorDiagnostics.WORKFLOW_R0019({ message: `OpenWorkflow SQLite storage received unsupported storage URL ${JSON.stringify(path)}.` });
29
36
  return path.startsWith("file:") ? path.slice(5) : path;
30
37
  }
31
38
  async function prepareSqlitePath(path, importer) {
@@ -35,37 +42,128 @@ async function prepareSqlitePath(path, importer) {
35
42
  }
36
43
  return path;
37
44
  }
45
+ let databaseUrlResolver;
46
+ /**
47
+ * Makes OpenWorkflow use the Postgres Default Database of the app when no OpenWorkflow storage is configured. The
48
+ * generated startup plugin installs it when the build has a Postgres Default Database.
49
+ */
50
+ function setOpenWorkflowDatabaseUrl(resolve) {
51
+ databaseUrlResolver = resolve;
52
+ }
53
+ /** The Postgres URL of the Default Database, when the app has a Postgres Default Database. */
54
+ function readDatabasePostgresUrl() {
55
+ if (!databaseUrlResolver) return void 0;
56
+ const url = databaseUrlResolver()?.trim();
57
+ if (!url) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_DATABASE_URL_MISSING();
58
+ return url;
59
+ }
38
60
  function getOpenWorkflowConfig(config) {
39
- if (config.provider !== "openworkflow") throw new Error(`OpenWorkflow runtime requires workflow.provider "openworkflow", received "${config.provider}".`);
61
+ if (config.driver !== "openworkflow") throw workflowErrorDiagnostics.WORKFLOW_R0020({ message: `OpenWorkflow runtime requires workflow.driver "openworkflow", received "${config.driver}".` });
62
+ if ("database" in config && config.database !== void 0) throw workflowErrorDiagnostics.WORKFLOW_R0027({ message: "`workflow.database` is not supported. Set `workflow.sqlite.path` or `workflow.postgres.url` explicitly." });
40
63
  const sqlite = config.sqlite || {};
41
- const sqlitePath = resolveRuntimeConfigValue(sqlite.path) || readEnv("OPENWORKFLOW_SQLITE_PATH");
42
- if (sqlitePath) return {
64
+ const postgres = config.postgres || {};
65
+ if (postgres.url !== void 0 && sqlite.path !== void 0) throw workflowErrorDiagnostics.WORKFLOW_R0030({ message: "`workflow.postgres.url` and `workflow.sqlite.path` cannot both configure OpenWorkflow storage." });
66
+ const explicitSqlitePath = resolveRuntimeConfigValue(sqlite.path);
67
+ const explicitPostgresUrl = resolveRuntimeConfigValue(postgres.url)?.trim();
68
+ if (sqlite.path !== void 0 && !explicitSqlitePath?.trim()) throw workflowErrorDiagnostics.WORKFLOW_R0028({ message: "`workflow.sqlite.path` must resolve to a non-empty local SQLite path. Check its runtime environment declaration." });
69
+ if (postgres.url !== void 0 && !explicitPostgresUrl) throw workflowErrorDiagnostics.WORKFLOW_R0029({ message: "`workflow.postgres.url` must resolve to a non-empty Postgres URL. Check its runtime environment declaration." });
70
+ const storage = resolveOpenWorkflowStorage({
71
+ postgresUrl: explicitPostgresUrl,
72
+ sqlitePath: explicitSqlitePath
73
+ }, readEnv);
74
+ if (storage.backend === "sqlite" && storage.source !== "default") return {
43
75
  backend: "sqlite",
44
76
  namespaceId: sqlite.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
45
- path: normalizeSqlitePath(sqlitePath),
46
- runMigrations: sqlite.runMigrations
77
+ path: normalizeSqlitePath(storage.path),
78
+ runMigrations: sqlite.runMigrations,
79
+ source: "configured"
47
80
  };
48
- const postgres = config.postgres || {};
49
- const url = resolveRuntimeConfigValue(postgres.url) || readEnv("OPENWORKFLOW_POSTGRES_URL") || readEnv("DATABASE_URL");
81
+ const configuredUrl = storage.backend === "postgres" ? storage.url : void 0;
82
+ const url = configuredUrl || readDatabasePostgresUrl();
50
83
  if (url) return {
51
84
  backend: "postgres",
52
85
  namespaceId: postgres.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
53
86
  runMigrations: postgres.runMigrations,
54
87
  schema: postgres.schema || readEnv("OPENWORKFLOW_SCHEMA") || "openworkflow",
88
+ source: configuredUrl ? "configured" : "database",
55
89
  url
56
90
  };
91
+ if (/^postgres(?:ql)?:\/\//i.test(readEnv("DATABASE_URL") || "")) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_DATABASE_URL_IGNORED();
57
92
  return {
58
93
  backend: "sqlite",
59
94
  namespaceId: sqlite.namespaceId || readEnv("OPENWORKFLOW_NAMESPACE_ID") || "production",
60
95
  path: defaultOpenWorkflowSqlitePath,
61
- runMigrations: sqlite.runMigrations
96
+ runMigrations: sqlite.runMigrations,
97
+ source: "default"
62
98
  };
63
99
  }
64
- function getRuntimeKey(config) {
65
- return JSON.stringify(getOpenWorkflowConfig(config));
100
+ /** How long a server waits for the setup lock that another server holds, before the worker start tries again. */
101
+ const postgresSetupWaitMs = 12e4;
102
+ /** How long the server that holds the setup lock waits for the second connection that the OpenWorkflow migration needs. */
103
+ const postgresSecondConnectionTimeoutMs = 1e4;
104
+ function sleep(ms) {
105
+ return new Promise((resolve) => setTimeout(resolve, ms).unref?.());
66
106
  }
67
- async function createOpenWorkflowRuntime(config, importer) {
68
- const options = getOpenWorkflowConfig(config);
107
+ /** Resolves `true` when `task` settles first, `false` when `ms` passes first. */
108
+ function settlesWithin(task, ms) {
109
+ let timer;
110
+ return Promise.race([task.then(() => true), new Promise((resolve) => {
111
+ timer = setTimeout(() => resolve(false), ms);
112
+ timer.unref?.();
113
+ })]).finally(() => clearTimeout(timer));
114
+ }
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
+ async function withPostgresSetupLock(postgres, url, schema, setup) {
133
+ const sql = postgres.default(url, {
134
+ idle_timeout: 1,
135
+ max: 1,
136
+ onnotice: () => {}
137
+ });
138
+ const key = `vitehub:openworkflow:${schema}`;
139
+ const deadline = Date.now() + postgresSetupWaitMs;
140
+ try {
141
+ for (let attempt = 1;; attempt++) {
142
+ let result;
143
+ await sql.begin(async (transaction) => {
144
+ const [lock] = await transaction`select pg_try_advisory_xact_lock(hashtextextended(${key}, 0)) as locked`;
145
+ if (!lock?.locked) return;
146
+ const probe = postgres.default(url, {
147
+ max: 1,
148
+ onnotice: () => {}
149
+ });
150
+ const answered = Promise.resolve(probe`select 1`).then(() => {}, () => {});
151
+ if (!await settlesWithin(answered, postgresSecondConnectionTimeoutMs)) {
152
+ answered.then(() => probe.end());
153
+ throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_SETUP_CONNECTION_UNAVAILABLE();
154
+ }
155
+ await probe.end();
156
+ result = { value: await setup() };
157
+ });
158
+ if (result) return result.value;
159
+ if (Date.now() >= deadline) throw workflowErrorDiagnostics.WORKFLOW_OPENWORKFLOW_SETUP_LOCK_TIMEOUT({ seconds: postgresSetupWaitMs / 1e3 });
160
+ await sleep(Math.min(250 * attempt, 2e3));
161
+ }
162
+ } finally {
163
+ await sql.end({ timeout: 5 });
164
+ }
165
+ }
166
+ async function createOpenWorkflowRuntime(options, importer) {
69
167
  const [{ OpenWorkflow }, backendModule] = await Promise.all([importOpenWorkflowModule("openworkflow", importer), options.backend === "sqlite" ? importOpenWorkflowModule("openworkflow/sqlite", importer) : importOpenWorkflowModule("openworkflow/postgres", importer)]);
70
168
  const { backend, client } = await runWorkflowProviderOperation("openworkflow", "connect", async () => {
71
169
  let backend;
@@ -73,11 +171,15 @@ async function createOpenWorkflowRuntime(config, importer) {
73
171
  namespaceId: options.namespaceId,
74
172
  ...typeof options.runMigrations === "boolean" ? { runMigrations: options.runMigrations } : {}
75
173
  });
76
- else backend = await backendModule.BackendPostgres.connect(options.url, {
77
- namespaceId: options.namespaceId,
78
- ...typeof options.runMigrations === "boolean" ? { runMigrations: options.runMigrations } : {},
79
- schema: options.schema
80
- });
174
+ else {
175
+ const { BackendPostgres } = backendModule;
176
+ const connect = () => BackendPostgres.connect(options.url, {
177
+ namespaceId: options.namespaceId,
178
+ ...typeof options.runMigrations === "boolean" ? { runMigrations: options.runMigrations } : {},
179
+ schema: options.schema
180
+ });
181
+ backend = options.runMigrations === false ? await connect() : await withPostgresSetupLock(await importOpenWorkflowModule("postgres", importer), options.url, options.schema, connect);
182
+ }
81
183
  return {
82
184
  backend,
83
185
  client: new OpenWorkflow({ backend })
@@ -86,15 +188,56 @@ async function createOpenWorkflowRuntime(config, importer) {
86
188
  return {
87
189
  backend,
88
190
  client,
191
+ findRunId: createRunIdLookup(backend, options),
89
192
  workflows: /* @__PURE__ */ new Map()
90
193
  };
91
194
  }
195
+ function isSqliteHandle(value) {
196
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "prepare") === "function";
197
+ }
198
+ function isPostgresHandle(value) {
199
+ return typeof value === "function";
200
+ }
201
+ function readRowId(row) {
202
+ if (typeof row !== "object" || row === null) return void 0;
203
+ const id = Reflect.get(row, "id");
204
+ return typeof id === "string" ? id : void 0;
205
+ }
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
+ function createRunIdLookup(backend, options) {
211
+ const connection = Reflect.get(backend, options.backend === "sqlite" ? "db" : "pg");
212
+ return async (name, key) => {
213
+ if (options.backend === "sqlite" && isSqliteHandle(connection)) return readRowId(connection.prepare(`SELECT "id" FROM "workflow_runs" WHERE "namespace_id" = ? AND "workflow_name" = ? AND "idempotency_key" = ? ORDER BY "created_at" ASC, "id" ASC LIMIT 1`).get(options.namespaceId, name, key));
214
+ if (options.backend === "postgres" && isPostgresHandle(connection)) {
215
+ const [row] = await connection`SELECT "id" FROM ${connection(options.schema)}.${connection("workflow_runs")} WHERE "namespace_id" = ${options.namespaceId} AND "workflow_name" = ${name} AND "idempotency_key" = ${key} ORDER BY "created_at" ASC, "id" ASC LIMIT 1`;
216
+ return readRowId(row);
217
+ }
218
+ throw invariantError(`OpenWorkflow 0.9 backends keep their connection in \`db\` (SQLite) or \`pg\` (Postgres), but the ${options.backend} backend has neither`);
219
+ };
220
+ }
221
+ /** The storage that OpenWorkflow uses for `config` now, without credentials. */
222
+ function describeOpenWorkflowStorage(config) {
223
+ const storage = getOpenWorkflowConfig(config);
224
+ return storage.backend === "sqlite" ? {
225
+ backend: "sqlite",
226
+ location: storage.path,
227
+ source: storage.source
228
+ } : {
229
+ backend: "postgres",
230
+ location: `schema ${storage.schema}`,
231
+ source: storage.source
232
+ };
233
+ }
92
234
  async function getOpenWorkflowRuntime(config) {
93
235
  const cache = runtimes;
94
- const key = getRuntimeKey(config);
236
+ const options = getOpenWorkflowConfig(config);
237
+ const key = JSON.stringify(options);
95
238
  let runtime = cache.get(key);
96
239
  if (!runtime) {
97
- runtime = createOpenWorkflowRuntime(config, openWorkflowImporter);
240
+ runtime = createOpenWorkflowRuntime(options, openWorkflowImporter);
98
241
  cache.set(key, runtime);
99
242
  runtime.catch(() => {
100
243
  if (cache.get(key) === runtime) cache.delete(key);
@@ -119,12 +262,23 @@ function toOpenWorkflowRetryPolicy(options) {
119
262
  function createOpenWorkflowProviderStep(step) {
120
263
  return {
121
264
  async do(name, options, run) {
122
- return await step.run({
265
+ const output = await step.run({
123
266
  name,
124
267
  ...toOpenWorkflowRetryPolicy(options) ? { retryPolicy: toOpenWorkflowRetryPolicy(options) } : {}
125
- }, run);
268
+ }, async () => {
269
+ try {
270
+ return await run();
271
+ } catch (error) {
272
+ const result = toNonRetryableStepResult(error);
273
+ if (result) return result;
274
+ throw error;
275
+ }
276
+ });
277
+ const error = readNonRetryableStepResult(output);
278
+ if (error) throw error;
279
+ return output;
126
280
  },
127
- sleep: async (name, duration) => await step.sleep(name, duration)
281
+ sleep: async (name, milliseconds) => await step.sleep(name, `${milliseconds}ms`)
128
282
  };
129
283
  }
130
284
  async function registerOpenWorkflowDefinition(runtime, name, definition) {
@@ -132,8 +286,9 @@ async function registerOpenWorkflowDefinition(runtime, name, definition) {
132
286
  if (existing) return existing;
133
287
  const openWorkflowDefinition = definition;
134
288
  const workflow = runtime.client.defineWorkflow({ name }, async ({ input, run, step }) => {
135
- return await runWorkflowHandler({
136
- id: run.id,
289
+ const stored = await runtime.backend.getWorkflowRun({ workflowRunId: run.id });
290
+ return await runSerializedWorkflowHandler({
291
+ id: stored?.idempotencyKey || run.id,
137
292
  name,
138
293
  payload: input,
139
294
  provider: "openworkflow",
@@ -161,57 +316,145 @@ function serializeOpenWorkflowRun(run, name) {
161
316
  provider: "openworkflow",
162
317
  status: "unknown"
163
318
  };
164
- const result = run.output;
319
+ const result = isSerializedResponse(run.output) ? deserializeResponse(run.output) : run.output;
320
+ const status = normalizeOpenWorkflowStatus(run.status);
165
321
  return {
166
- id: run.id,
167
- metadata: run.error || {
322
+ ...status === "failed" ? { error: toWorkflowRunError(run.error) } : {},
323
+ ...run.finishedAt ? { completedAt: run.finishedAt } : {},
324
+ createdAt: run.createdAt,
325
+ ...run.startedAt ? { startedAt: run.startedAt } : {},
326
+ id: run.idempotencyKey || run.id,
327
+ metadata: {
168
328
  namespaceId: run.namespaceId,
169
329
  version: run.version,
170
330
  workflowName: run.workflowName
171
331
  },
332
+ payload: run.input,
172
333
  provider: "openworkflow",
173
334
  result,
174
- status: normalizeOpenWorkflowStatus(run.status)
335
+ status
175
336
  };
176
337
  }
177
- async function runOpenWorkflow(config, name, payload, definition, options) {
178
- const workflow = await registerOpenWorkflowDefinition(await getOpenWorkflowRuntime(config), name, definition);
338
+ /** OpenWorkflow stores `name`, `message`, and `stack`. The stack has server paths, so the step keeps the message only. */
339
+ function toWorkflowRunStepError(error) {
340
+ const message = typeof error === "object" && error !== null ? Reflect.get(error, "message") : void 0;
341
+ return { message: typeof message === "string" && message ? message : "Workflow step failed." };
342
+ }
343
+ /** OpenWorkflow stores one row per step attempt. A run reports each step once, with its latest attempt. */
344
+ function toWorkflowRunSteps(attempts) {
345
+ const steps = /* @__PURE__ */ new Map();
346
+ for (const attempt of attempts) {
347
+ const nonRetryable = readNonRetryableStepResult(attempt.output);
348
+ steps.set(attempt.stepName, {
349
+ attempt: (steps.get(attempt.stepName)?.attempt ?? 0) + 1,
350
+ ...attempt.finishedAt ? { completedAt: attempt.finishedAt } : {},
351
+ ...attempt.status === "failed" || nonRetryable ? { error: toWorkflowRunStepError(nonRetryable ?? attempt.error) } : {},
352
+ id: attempt.id,
353
+ name: attempt.stepName,
354
+ ...attempt.context?.kind === "sleep" ? { sleepUntil: new Date(attempt.context.resumeAt) } : {},
355
+ ...attempt.startedAt ? { startedAt: attempt.startedAt } : {},
356
+ status: nonRetryable ? "failed" : normalizeOpenWorkflowStatus(attempt.status)
357
+ });
358
+ }
359
+ return [...steps.values()];
360
+ }
361
+ async function listOpenWorkflowStepAttempts(backend, workflowRunId) {
362
+ const attempts = [];
363
+ let after;
364
+ do {
365
+ const page = await backend.listStepAttempts({
366
+ workflowRunId,
367
+ limit: 100,
368
+ ...after ? { after } : {}
369
+ });
370
+ attempts.push(...page.data);
371
+ after = page.pagination.next ?? void 0;
372
+ } while (after);
373
+ return attempts;
374
+ }
375
+ async function runOpenWorkflow(config, name, payload, definition, options, onDispatch, startAt) {
376
+ const runtime = await getOpenWorkflowRuntime(config);
377
+ const workflow = await registerOpenWorkflowDefinition(runtime, name, definition);
378
+ onDispatch?.();
179
379
  let firstAcknowledgementUnknown = false;
180
380
  const handle = await runWorkflowProviderOperation("openworkflow", "run", async () => {
181
- const start = () => workflow.run(payload, options.id ? { idempotencyKey: options.id } : void 0);
381
+ const existingId = options.id ? await runtime.findRunId(name, options.id) ?? options.id : void 0;
382
+ const existing = existingId ? await runtime.backend.getWorkflowRun({ workflowRunId: existingId }) : null;
383
+ if (existing?.workflowName === name) return { workflowRun: existing };
384
+ const runOptions = options.id || startAt !== void 0 ? {
385
+ ...options.id ? { idempotencyKey: options.id } : {},
386
+ ...startAt === void 0 ? {} : { availableAt: new Date(startAt) }
387
+ } : void 0;
388
+ const start = () => workflow.run(payload, runOptions);
182
389
  return await start().catch((error) => {
183
390
  if (!options.id) throw error;
184
391
  firstAcknowledgementUnknown = getWorkflowProviderStatus(error) === void 0;
185
392
  return start();
186
393
  });
187
- }, { acknowledgementUnknown: (_error, status) => firstAcknowledgementUnknown || status === void 0 });
394
+ }, { acknowledgement: (_error, status) => firstAcknowledgementUnknown || status === void 0 ? "unknown" : status < 500 ? "rejected" : void 0 });
188
395
  return await runWorkflowProviderOperation("openworkflow", "run", async () => {
189
- const serialized = serializeOpenWorkflowRun(handle.workflowRun, name);
190
396
  return {
191
- ...serialized,
192
- metadata: serialized.status === "failed" ? serialized.metadata : {
397
+ ...serializeOpenWorkflowRun(handle.workflowRun, name),
398
+ metadata: {
193
399
  ...options.id ? { idempotencyKey: options.id } : {},
194
400
  workflow: name
195
401
  },
196
- payload
402
+ payload: handle.workflowRun.input
197
403
  };
198
404
  });
199
405
  }
200
406
  async function getOpenWorkflowRun(config, name, id) {
201
407
  const runtime = await getOpenWorkflowRuntime(config);
202
408
  return await runWorkflowProviderOperation("openworkflow", "get", async () => {
203
- const serialized = serializeOpenWorkflowRun(await runtime.backend.getWorkflowRun({ workflowRunId: id }), name);
204
- return serialized.id ? serialized : {
409
+ const run = await runtime.backend.getWorkflowRun({ workflowRunId: await runtime.findRunId(name, id) ?? id });
410
+ if (!run || run.workflowName !== name) return {
205
411
  id,
206
412
  provider: "openworkflow",
207
413
  status: "unknown"
208
414
  };
415
+ return {
416
+ ...serializeOpenWorkflowRun(run, name),
417
+ steps: toWorkflowRunSteps(await listOpenWorkflowStepAttempts(runtime.backend, run.id))
418
+ };
209
419
  });
210
420
  }
421
+ const terminalOpenWorkflowStatuses = /* @__PURE__ */ new Set([
422
+ "cancelled",
423
+ "completed",
424
+ "failed"
425
+ ]);
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
+ async function cancelOpenWorkflowRun(config, name, id) {
431
+ const current = await getOpenWorkflowRun(config, name, id);
432
+ if (current.status === "unknown" || terminalOpenWorkflowStatuses.has(current.status)) return current;
433
+ const runtime = await getOpenWorkflowRuntime(config);
434
+ try {
435
+ await runWorkflowProviderOperation("openworkflow", "cancel", async () => await runtime.client.cancelWorkflowRun(await runtime.findRunId(name, id) ?? id));
436
+ } catch (error) {
437
+ const latest = await getOpenWorkflowRun(config, name, id).catch(() => void 0);
438
+ if (latest && terminalOpenWorkflowStatuses.has(latest.status)) return latest;
439
+ throw error;
440
+ }
441
+ return await getOpenWorkflowRun(config, name, id);
442
+ }
211
443
  async function resetOpenWorkflowRuntime() {
444
+ openWorkflowImporter = defaultImporter;
445
+ databaseUrlResolver = void 0;
446
+ await detachOpenWorkflowRuntimes()();
447
+ }
448
+ /**
449
+ * Starts a new runtime cache, so the next acquisition opens a fresh backend. Returns a function that closes the
450
+ * backends of the old cache. Call it after the work that still uses them, such as a stopping worker, finishes.
451
+ */
452
+ function detachOpenWorkflowRuntimes() {
212
453
  const closing = runtimes;
213
454
  runtimes = /* @__PURE__ */ new Map();
214
- openWorkflowImporter = defaultImporter;
455
+ return () => closeOpenWorkflowRuntimes(closing);
456
+ }
457
+ async function closeOpenWorkflowRuntimes(closing) {
215
458
  const fulfilled = (await Promise.allSettled(closing.values())).flatMap((entry) => entry.status === "fulfilled" ? [entry.value] : []);
216
459
  const failures = (await Promise.allSettled(fulfilled.map((runtime) => Promise.resolve().then(() => runtime.backend.stop())))).flatMap((entry) => entry.status === "rejected" ? [createWorkflowError({
217
460
  cause: entry.reason,
@@ -225,4 +468,4 @@ function setOpenWorkflowImporter(importer) {
225
468
  openWorkflowImporter = importer;
226
469
  }
227
470
  //#endregion
228
- export { getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, runOpenWorkflow, setOpenWorkflowImporter };
471
+ export { cancelOpenWorkflowRun, describeOpenWorkflowStorage, detachOpenWorkflowRuntimes, getOpenWorkflowRun, getOpenWorkflowRuntime, registerOpenWorkflowDefinition, resetOpenWorkflowRuntime, runOpenWorkflow, setOpenWorkflowDatabaseUrl, setOpenWorkflowImporter };
@@ -1,35 +1,36 @@
1
- import { h as WorkflowDefinitionRegistry, l as ResolvedWorkflowOptions, p as WorkflowDefinition } from "../types-B9RdRkKh.js";
2
-
1
+ import { f as WorkflowDefinition, l as ResolvedWorkflowOptions, m as WorkflowDefinitionRegistry } from "../types-CnKVDnEp.js";
3
2
  //#region src/runtime/state.d.ts
4
- interface WorkflowRunState<TResult = unknown> {
3
+ export interface WorkflowRunState<TResult = unknown> {
5
4
  error?: unknown;
6
5
  expiresAt?: number;
6
+ payload?: unknown;
7
7
  promise: Promise<{
8
8
  result?: TResult;
9
9
  status: "completed" | "failed";
10
10
  error?: unknown;
11
11
  }>;
12
12
  result?: TResult;
13
+ /** Set while a delayed inline run waits for its start time, in milliseconds. The run reports `queued` until then. */
14
+ startAt?: number;
13
15
  status: "running" | "completed" | "failed";
14
16
  }
15
- declare function setWorkflowRuntimeConfig(config: false | ResolvedWorkflowOptions | undefined): void;
16
- declare function getWorkflowRuntimeConfig(): false | ResolvedWorkflowOptions | undefined;
17
- declare function setWorkflowRuntimeRegistry(registry: WorkflowDefinitionRegistry | undefined): void;
18
- declare function getWorkflowRuntimeRegistry(): WorkflowDefinitionRegistry | undefined;
19
- declare function getInlineWorkflowDefinitions(): ReadonlyMap<string, WorkflowDefinition>;
20
- declare function takeInlineWorkflowDefinition(name: string): WorkflowDefinition | undefined;
21
- declare function takeInlineWorkflowDefinitionForModule(name: string, loaded: unknown): WorkflowDefinition | undefined;
22
- declare function registerInlineWorkflowDefinition(name: string, definition: WorkflowDefinition): void;
23
- declare function enterWorkflowRuntimeEvent(event: unknown): void;
24
- declare function getWorkflowRuntimeEvent(): unknown;
25
- declare function runWithWorkflowRuntimeEvent<T>(event: unknown, run: () => T | Promise<T>): Promise<T>;
26
- declare function loadWorkflowDefinition(name: string): Promise<WorkflowDefinition | undefined>;
27
- declare function setWorkflowRun<TResult = unknown>(name: string, id: string, promise: Promise<{
17
+ export declare function setWorkflowRuntimeConfig(config: false | ResolvedWorkflowOptions | undefined): void;
18
+ export declare function getWorkflowRuntimeConfig(): false | ResolvedWorkflowOptions | undefined;
19
+ export declare function setWorkflowRuntimeRegistry(registry: WorkflowDefinitionRegistry | undefined): void;
20
+ export declare function getWorkflowRuntimeRegistry(): WorkflowDefinitionRegistry | undefined;
21
+ export declare function getInlineWorkflowDefinitions(): ReadonlyMap<string, WorkflowDefinition>;
22
+ export declare function takeInlineWorkflowDefinition(name: string): WorkflowDefinition | undefined;
23
+ export declare function takeInlineWorkflowDefinitionForModule(name: string, loaded: unknown): WorkflowDefinition | undefined;
24
+ export declare function registerInlineWorkflowDefinition(name: string, definition: WorkflowDefinition): void;
25
+ export declare function enterWorkflowRuntimeEvent(event: unknown): void;
26
+ export declare function getWorkflowRuntimeEvent(): unknown;
27
+ export declare function runWithWorkflowRuntimeEvent<T>(event: unknown, run: () => T | Promise<T>): Promise<T>;
28
+ export declare function loadWorkflowDefinition(name: string): Promise<WorkflowDefinition | undefined>;
29
+ export declare function setWorkflowRun<TResult = unknown>(name: string, id: string, promise: Promise<{
28
30
  result?: TResult;
29
31
  status: "completed" | "failed";
30
32
  error?: unknown;
31
- }>): WorkflowRunState<TResult>;
32
- declare function getWorkflowRunState(name: string, id: string): WorkflowRunState | undefined;
33
- declare function resetWorkflowRuntime(): void;
34
- //#endregion
35
- export { WorkflowRunState, enterWorkflowRuntimeEvent, getInlineWorkflowDefinitions, getWorkflowRunState, getWorkflowRuntimeConfig, getWorkflowRuntimeEvent, getWorkflowRuntimeRegistry, loadWorkflowDefinition, registerInlineWorkflowDefinition, resetWorkflowRuntime, runWithWorkflowRuntimeEvent, setWorkflowRun, setWorkflowRuntimeConfig, setWorkflowRuntimeRegistry, takeInlineWorkflowDefinition, takeInlineWorkflowDefinitionForModule };
33
+ }>, payload?: unknown, retainInFlight?: boolean): WorkflowRunState<TResult>;
34
+ export declare function getWorkflowRunState(name: string, id: string): WorkflowRunState | undefined;
35
+ export declare function resetWorkflowRuntime(): void;
36
+ //#endregion