@lovable.dev/workflows-sdk 0.0.0-dev.3 → 0.0.0-dev.31

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/dist/index.js CHANGED
@@ -1,2 +1,703 @@
1
- import { a as defineSchedule, i as registerWorkflows, n as createMiddleware, r as createWorkflow, t as generateManifests } from "./generate-DFS-ezZy.js";
2
- export { createMiddleware, createWorkflow, defineSchedule, generateManifests, registerWorkflows };
1
+ import { C as registerWorkflows, D as hourly, E as daily, O as weekly, S as createWorkflow, T as defineSchedule, t as generateManifests, w as workflowVersions, x as createMiddleware } from "./generate-Dk1_3N-g.js";
2
+ import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
3
+ import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
4
+ //#region src/stacks/tanstack/sse.ts
5
+ const HEADERS = {
6
+ "content-type": "text/event-stream; charset=utf-8",
7
+ "cache-control": "no-cache, no-transform",
8
+ connection: "keep-alive",
9
+ "x-accel-buffering": "no"
10
+ };
11
+ function describe$1(error) {
12
+ return error instanceof Error ? error.message : String(error);
13
+ }
14
+ function frame(name, data) {
15
+ return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
16
+ }
17
+ /**
18
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
19
+ * engine `type` as the SSE event name and its whole JSON as the data line.
20
+ */
21
+ function toServerSentEventsResponse(events) {
22
+ const encoder = new TextEncoder();
23
+ const body = new ReadableStream({ async start(controller) {
24
+ let connected = true;
25
+ const write = (text) => {
26
+ if (!connected) return;
27
+ try {
28
+ controller.enqueue(encoder.encode(text));
29
+ } catch {
30
+ connected = false;
31
+ }
32
+ };
33
+ const send = (name, data) => {
34
+ try {
35
+ write(frame(name, data));
36
+ } catch (error) {
37
+ write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe$1(error)}` }));
38
+ }
39
+ };
40
+ try {
41
+ for await (const event of events) send(event.type, event);
42
+ } catch (error) {
43
+ send("STREAM_ERRORED", { message: describe$1(error) });
44
+ } finally {
45
+ try {
46
+ controller.close();
47
+ } catch {
48
+ connected = false;
49
+ }
50
+ }
51
+ } });
52
+ return new Response(body, { headers: HEADERS });
53
+ }
54
+ //#endregion
55
+ //#region src/stacks/tanstack/handlers.ts
56
+ function json$1(status, body) {
57
+ return new Response(JSON.stringify(body), {
58
+ status,
59
+ headers: { "content-type": "application/json; charset=utf-8" }
60
+ });
61
+ }
62
+ function resolveWorkflowId$1(ctx, param) {
63
+ const fromParams = ctx.params?.[param];
64
+ if (fromParams) return fromParams;
65
+ return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
66
+ }
67
+ /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
68
+ function createTanStackWorkflowHandler(collection, options = {}) {
69
+ const runStore = options.runStore ?? inMemoryRunStore();
70
+ const param = options.workflowIdParam ?? "workflowId";
71
+ const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
72
+ return async (ctx) => {
73
+ const workflowId = resolveWorkflowId$1(ctx, param);
74
+ const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
75
+ if (!workflow) return json$1(404, {
76
+ error: "unknown_workflow",
77
+ workflowId: workflowId ?? ""
78
+ });
79
+ let params;
80
+ try {
81
+ params = await parseWorkflowRequest(ctx.request);
82
+ } catch (error) {
83
+ if (error instanceof WorkflowRequestParseError) return json$1(400, {
84
+ error: "invalid_request",
85
+ message: error.message
86
+ });
87
+ throw error;
88
+ }
89
+ if (params.abort) return json$1(501, {
90
+ error: "abort_unsupported",
91
+ message: "Cancelling an in-flight run needs a shared run registry (WOR-53)."
92
+ });
93
+ const state = params.runId ? await runStore.getRunState(params.runId) : void 0;
94
+ if (state && state.workflowId !== workflow.id) return json$1(409, { error: "workflow_version_unavailable" });
95
+ const readOnly = state && [
96
+ "finished",
97
+ "errored",
98
+ "aborted"
99
+ ].includes(state.status);
100
+ const selected = state && !readOnly ? workflowVersions(workflow).find((candidate) => candidate.version === state.workflowVersion) : workflow;
101
+ if (!selected) return json$1(409, { error: "workflow_version_unavailable" });
102
+ return toServerSentEventsResponse(runWorkflow({
103
+ workflow: selected,
104
+ runStore,
105
+ ...params
106
+ }));
107
+ };
108
+ }
109
+ //#endregion
110
+ //#region src/runtime/input-hash.ts
111
+ /** Key order must not change the hash, so objects are serialized sorted. */
112
+ function canonical(value) {
113
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
114
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
115
+ return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
116
+ }
117
+ /**
118
+ * Identifies the input a run started with. A resume carries it back so replay
119
+ * cannot be pointed at a different record than the one its memo came from.
120
+ */
121
+ async function hashInput(input) {
122
+ const bytes = new TextEncoder().encode(canonical(input));
123
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
124
+ return [...new Uint8Array(digest)].slice(0, 16).map((byte) => byte.toString(16).padStart(2, "0")).join("");
125
+ }
126
+ //#endregion
127
+ //#region src/runtime/replay.ts
128
+ /** How long a pass waits for handler work that is not a durable operation. */
129
+ const DEFAULT_SETTLE_MS = 5e3;
130
+ function memoKey(stepId, occurrence) {
131
+ return `${stepId}#${occurrence}`;
132
+ }
133
+ const EXECUTABLE = /* @__PURE__ */ new Set([
134
+ "step",
135
+ "now",
136
+ "uuid"
137
+ ]);
138
+ function describe(error) {
139
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
140
+ }
141
+ function groupId(meta) {
142
+ const group = meta?.group;
143
+ if (group === null || typeof group !== "object") return void 0;
144
+ const id = group.id;
145
+ return typeof id === "string" ? id : void 0;
146
+ }
147
+ function runtimeContext() {
148
+ return {
149
+ timeRemaining: () => Number.POSITIVE_INFINITY,
150
+ shouldYield: () => false,
151
+ yield: async () => {}
152
+ };
153
+ }
154
+ /** Thread the handler through `.middleware([...])`, merging each extension into ctx. */
155
+ async function throughMiddleware(middlewares, ctx, handler) {
156
+ let index = 0;
157
+ const dispatch = async () => {
158
+ const middleware = middlewares[index++];
159
+ if (!middleware) return handler(ctx);
160
+ return middleware.server({
161
+ ctx,
162
+ next: async ({ context }) => {
163
+ Object.assign(ctx, context);
164
+ return dispatch();
165
+ }
166
+ });
167
+ };
168
+ return dispatch();
169
+ }
170
+ async function replay(options) {
171
+ const { workflow, input, runId } = options;
172
+ const byKey = new Map(options.memo.map((entry) => [memoKey(entry.stepId, entry.occurrence ?? 0), entry]));
173
+ const allow = options.shouldExecute ?? (() => true);
174
+ const never = new Promise(() => {});
175
+ const pending = [];
176
+ const settled = /* @__PURE__ */ new Map();
177
+ const pass = { stepsSettled: 0 };
178
+ const occurrences = /* @__PURE__ */ new Map();
179
+ const consumed = /* @__PURE__ */ new Set();
180
+ let lastProgress = Date.now();
181
+ let currentParent;
182
+ const results = [];
183
+ const emitted = [];
184
+ const inflight = [];
185
+ let seq = 0;
186
+ let nonDeterminism;
187
+ function record(entry) {
188
+ settled.set(memoKey(entry.stepId, entry.occurrence), entry);
189
+ lastProgress = Date.now();
190
+ if (entry.kind === "step") pass.stepsSettled += 1;
191
+ const result = {
192
+ seq: entry.seq,
193
+ stepId: entry.stepId,
194
+ occurrence: entry.occurrence,
195
+ kind: entry.kind,
196
+ ...entry.meta ? { meta: entry.meta } : {},
197
+ status: entry.status,
198
+ result: entry.result,
199
+ error: entry.error
200
+ };
201
+ results.push(result);
202
+ options.onStepSettle?.(result);
203
+ }
204
+ function durable(kind, stepId, run, config, defaulted = false, meta) {
205
+ const index = seq++;
206
+ const occurrence = occurrences.get(stepId) ?? 0;
207
+ occurrences.set(stepId, occurrence + 1);
208
+ if (kind === "step" && occurrence > 0) {
209
+ nonDeterminism = `ctx.step() was reached more than once with id "${stepId}"; every step id must be unique within a workflow`;
210
+ return never;
211
+ }
212
+ if (defaulted && occurrence > 0) {
213
+ nonDeterminism = `ctx.${kind}() was reached more than once with the default id "${stepId}"; pass an explicit { id } per call site`;
214
+ return never;
215
+ }
216
+ const key = memoKey(stepId, occurrence);
217
+ consumed.add(key);
218
+ const answered = byKey.get(key) ?? settled.get(key);
219
+ if (answered) {
220
+ if (answered.kind !== kind) {
221
+ nonDeterminism = `memo has ${answered.kind} "${stepId}" (#${occurrence}), replay produced ${kind}`;
222
+ return never;
223
+ }
224
+ const recordedGroupId = groupId(answered.meta);
225
+ if (recordedGroupId !== void 0 && recordedGroupId !== groupId(meta)) {
226
+ nonDeterminism = `memo has group "${recordedGroupId}" for step "${stepId}", replay produced a different group`;
227
+ return never;
228
+ }
229
+ if (answered.status === "completed") return Promise.resolve(answered.result);
230
+ return Promise.reject(new Error(answered.error ?? `step "${stepId}" failed`));
231
+ }
232
+ const parent = currentParent;
233
+ const intent = {
234
+ seq: index,
235
+ stepId,
236
+ occurrence,
237
+ kind,
238
+ ...config ? { config } : {},
239
+ ...meta ? { meta } : {}
240
+ };
241
+ if (!run || !EXECUTABLE.has(kind) || !allow(intent, pass)) {
242
+ pending.push(intent);
243
+ return never;
244
+ }
245
+ options.onStepStart?.(intent);
246
+ const enclosing = currentParent;
247
+ currentParent = key;
248
+ let body;
249
+ try {
250
+ body = run();
251
+ } finally {
252
+ currentParent = enclosing;
253
+ }
254
+ const running = body.then((result) => {
255
+ record({
256
+ seq: index,
257
+ stepId,
258
+ occurrence,
259
+ kind,
260
+ status: "completed",
261
+ result,
262
+ ...parent ? { parent } : {},
263
+ ...meta ? { meta } : {}
264
+ });
265
+ return result;
266
+ }, (error) => {
267
+ record({
268
+ seq: index,
269
+ stepId,
270
+ occurrence,
271
+ kind,
272
+ status: "failed",
273
+ error: describe(error),
274
+ ...parent ? { parent } : {},
275
+ ...meta ? { meta } : {}
276
+ });
277
+ throw error;
278
+ });
279
+ inflight.push(running.then(noop, noop));
280
+ return running;
281
+ }
282
+ const state = { ...workflow.initialize?.({ input }) };
283
+ const runtime = runtimeContext();
284
+ const controller = new AbortController();
285
+ const ctx = {
286
+ runId,
287
+ input,
288
+ state,
289
+ signal: controller.signal,
290
+ runtime,
291
+ step: (id, fn, stepOptions) => durable("step", id, async () => fn({
292
+ id,
293
+ attempt: 1,
294
+ runtime,
295
+ signal: controller.signal
296
+ }), void 0, false, stepOptions?.meta),
297
+ sleep: (ms, opts) => durable("sleep", opts?.id ?? defaultDurableId({
298
+ kind: "sleep",
299
+ ms
300
+ }), void 0, { ms }, opts?.id === void 0, opts?.meta),
301
+ sleepUntil: (timestamp, opts) => durable("sleep", opts?.id ?? defaultDurableId({
302
+ kind: "sleepUntil",
303
+ timestamp
304
+ }), void 0, { timestamp }, opts?.id === void 0, opts?.meta),
305
+ waitForEvent: (name, opts) => durable("waitForEvent", opts?.id ?? defaultDurableId({
306
+ kind: "waitForEvent",
307
+ name
308
+ }), void 0, { name }, opts?.id === void 0, opts?.meta),
309
+ approve: (opts) => durable("approve", opts.id ?? defaultDurableId({
310
+ kind: "approve",
311
+ title: opts.title
312
+ }), void 0, {
313
+ title: opts.title,
314
+ ...opts.description === void 0 ? {} : { description: opts.description }
315
+ }, opts.id === void 0, {
316
+ ...opts.meta,
317
+ ...opts.description === void 0 ? {} : { description: opts.description }
318
+ }),
319
+ now: (opts) => durable("now", opts?.id ?? defaultDurableId({ kind: "now" }), async () => Date.now(), void 0, opts?.id === void 0, opts?.meta),
320
+ uuid: (opts) => durable("uuid", opts?.id ?? defaultDurableId({ kind: "uuid" }), async () => crypto.randomUUID(), void 0, opts?.id === void 0, opts?.meta),
321
+ emit: (name, value) => {
322
+ emitted.push({
323
+ name,
324
+ value
325
+ });
326
+ }
327
+ };
328
+ let outcome;
329
+ throughMiddleware(workflow.middlewares ?? [], ctx, workflow.handler).then((output) => {
330
+ outcome = {
331
+ status: "completed",
332
+ output: output ?? null
333
+ };
334
+ }, (error) => {
335
+ outcome = {
336
+ status: "failed",
337
+ error: describe(error)
338
+ };
339
+ });
340
+ const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
341
+ for (;;) {
342
+ for (let tick = 0; tick < 20; tick++) await new Promise((resolve) => setTimeout(resolve, 0));
343
+ if (outcome || nonDeterminism) break;
344
+ if (inflight.length > 0) {
345
+ await Promise.all(inflight.splice(0));
346
+ lastProgress = Date.now();
347
+ continue;
348
+ }
349
+ if (pending.length > 0 || Date.now() - lastProgress >= settleMs) break;
350
+ await new Promise((resolve) => setTimeout(resolve, 5));
351
+ }
352
+ while (inflight.length > 0) await Promise.all(inflight.splice(0));
353
+ const memo = [...byKey.values(), ...settled.values()];
354
+ const hidden = (start) => {
355
+ const seen = /* @__PURE__ */ new Set([start]);
356
+ let key = start;
357
+ for (;;) {
358
+ const parent = byKey.get(key)?.parent;
359
+ if (parent === void 0 || seen.has(parent)) return false;
360
+ if (consumed.has(parent)) return true;
361
+ seen.add(parent);
362
+ key = parent;
363
+ }
364
+ };
365
+ const orphan = [...byKey.keys()].find((key) => !consumed.has(key) && !hidden(key));
366
+ pending.sort((a, b) => a.seq - b.seq);
367
+ results.sort((a, b) => a.seq - b.seq);
368
+ const base = {
369
+ memo,
370
+ results,
371
+ emitted
372
+ };
373
+ if (nonDeterminism) return {
374
+ ...base,
375
+ status: "failed",
376
+ steps: [],
377
+ error: `non-deterministic replay: ${nonDeterminism}`
378
+ };
379
+ if (orphan !== void 0) return {
380
+ ...base,
381
+ status: "failed",
382
+ steps: [],
383
+ error: `stale memo: no operation matched "${orphan}"`
384
+ };
385
+ if (outcome?.status === "completed") return {
386
+ ...base,
387
+ status: "completed",
388
+ steps: [],
389
+ output: outcome.output
390
+ };
391
+ if (outcome?.status === "failed") return {
392
+ ...base,
393
+ status: "failed",
394
+ steps: [],
395
+ error: outcome.error
396
+ };
397
+ if (pending.length > 0) return {
398
+ ...base,
399
+ status: "pending",
400
+ steps: pending
401
+ };
402
+ return {
403
+ ...base,
404
+ status: "failed",
405
+ steps: [],
406
+ error: `workflow stalled: no durable operation and nothing settled for ${settleMs}ms`
407
+ };
408
+ }
409
+ function noop() {}
410
+ //#endregion
411
+ //#region src/stacks/tanstack/project-auth.ts
412
+ const PROJECT_SECRET_ENV_VAR = "LOVABLE_WORKFLOWS_KEY";
413
+ let cloudflareEnvPromise;
414
+ function readProcessSecret() {
415
+ const value = (globalThis.process?.env)?.[PROJECT_SECRET_ENV_VAR];
416
+ return typeof value === "string" && value ? value : void 0;
417
+ }
418
+ async function readCloudflareSecret() {
419
+ cloudflareEnvPromise ??= import(
420
+ /* @vite-ignore */
421
+ "cloudflare:workers"
422
+ ).then((module) => module.env).catch(() => void 0);
423
+ const value = (await cloudflareEnvPromise)?.[PROJECT_SECRET_ENV_VAR];
424
+ return typeof value === "string" && value ? value : void 0;
425
+ }
426
+ async function resolveProjectSecret() {
427
+ return readProcessSecret() ?? await readCloudflareSecret();
428
+ }
429
+ function bearerToken(request) {
430
+ const header = request.headers.get("authorization");
431
+ if (!header) return void 0;
432
+ const parts = header.trim().split(/\s+/);
433
+ if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") return void 0;
434
+ return parts[1] || void 0;
435
+ }
436
+ async function equalSecrets(left, right) {
437
+ const encoder = new TextEncoder();
438
+ const [leftHash, rightHash] = await Promise.all([crypto.subtle.digest("SHA-256", encoder.encode(left)), crypto.subtle.digest("SHA-256", encoder.encode(right))]);
439
+ const leftBytes = new Uint8Array(leftHash);
440
+ const rightBytes = new Uint8Array(rightHash);
441
+ let difference = 0;
442
+ for (let index = 0; index < leftBytes.length; index += 1) difference |= leftBytes[index] ^ rightBytes[index];
443
+ return difference === 0;
444
+ }
445
+ async function authorizeProjectRequest(request, getProjectSecret) {
446
+ let projectSecret;
447
+ try {
448
+ projectSecret = await getProjectSecret();
449
+ } catch {
450
+ return "unavailable";
451
+ }
452
+ if (!projectSecret) return "unavailable";
453
+ const token = bearerToken(request);
454
+ if (!token) return "unauthorized";
455
+ try {
456
+ return await equalSecrets(token, projectSecret) ? "authorized" : "unauthorized";
457
+ } catch {
458
+ return "unavailable";
459
+ }
460
+ }
461
+ //#endregion
462
+ //#region src/stacks/tanstack/steps.ts
463
+ function json(status, body) {
464
+ return new Response(JSON.stringify(body), {
465
+ status,
466
+ headers: { "content-type": "application/json; charset=utf-8" }
467
+ });
468
+ }
469
+ function unauthorized() {
470
+ const response = json(401, { error: "unauthorized" });
471
+ response.headers.set("www-authenticate", "Bearer");
472
+ return response;
473
+ }
474
+ function authUnavailable() {
475
+ return json(503, {
476
+ error: "workflow_auth_unavailable",
477
+ message: "LOVABLE_WORKFLOWS_KEY is not configured in this app runtime"
478
+ });
479
+ }
480
+ function resolveWorkflowId(ctx, param) {
481
+ const fromParams = ctx.params?.[param];
482
+ if (fromParams) return fromParams;
483
+ return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-2);
484
+ }
485
+ function isMemoEntry(value) {
486
+ const entry = value;
487
+ return typeof entry === "object" && entry !== null && Number.isInteger(entry.seq) && entry.seq >= 0 && typeof entry.stepId === "string" && Number.isInteger(entry.seq) && Number.isInteger(entry.occurrence) && entry.occurrence >= 0 && (entry.status === "completed" || entry.status === "failed");
488
+ }
489
+ function parseBody(value) {
490
+ if (value === null || typeof value !== "object") return "body must be a JSON object";
491
+ const body = value;
492
+ if (body.workflowVersion !== void 0 && typeof body.workflowVersion !== "string") return "workflowVersion must be a string";
493
+ if (body.memo !== void 0) {
494
+ if (!Array.isArray(body.memo) || !body.memo.every(isMemoEntry)) return "memo must be an array of settled step entries";
495
+ if (new Set(body.memo.map((entry) => memoKey(entry.stepId, entry.occurrence))).size !== body.memo.length) return "memo entries must be unique per stepId and occurrence";
496
+ }
497
+ if (body.action !== void 0 && body.action !== "advance" && body.action !== "execute") return "action must be \"advance\" or \"execute\"";
498
+ if (body.action === "execute" && !isStepReference(body.step)) return "step must be a { kind: \"step\", stepId, occurrence } reference when action is \"execute\"";
499
+ if (body.action !== "execute" && body.step !== void 0) return "step is only valid when action is \"execute\"";
500
+ if (body.memo !== void 0 && body.memo.length > 0 && !("input" in value)) return "input must be sent with every call, including a resume";
501
+ return body;
502
+ }
503
+ async function readBody(request) {
504
+ const text = await request.text();
505
+ if (!text.trim()) return {};
506
+ return JSON.parse(text);
507
+ }
508
+ function operationKey(operation) {
509
+ return memoKey(operation.stepId, operation.occurrence);
510
+ }
511
+ function isStepReference(value) {
512
+ const step = value;
513
+ return typeof step === "object" && step !== null && step.kind === "step" && typeof step.stepId === "string" && Number.isInteger(step.occurrence) && step.occurrence >= 0;
514
+ }
515
+ function disposition(outcome) {
516
+ if (outcome.status === "completed") return "completed";
517
+ if (outcome.status === "failed") return "failed";
518
+ if (!outcome.steps.some((step) => step.kind === "step")) return "waiting";
519
+ return outcome.steps.length > 1 ? "fork" : "advanced";
520
+ }
521
+ function memoDelta(before, after) {
522
+ const existing = new Set(before.map((entry) => memoKey(entry.stepId, entry.occurrence)));
523
+ return after.filter((entry) => !existing.has(memoKey(entry.stepId, entry.occurrence)));
524
+ }
525
+ function respond(runId, inputHash, workflowVersion, before, outcome, executed) {
526
+ const { steps, emitted, output, error } = outcome;
527
+ return json(200, {
528
+ runId,
529
+ inputHash,
530
+ workflowVersion,
531
+ disposition: disposition(outcome),
532
+ memoDelta: memoDelta(before, outcome.memo),
533
+ next: steps,
534
+ ...executed === void 0 ? {} : { executed },
535
+ ...emitted.length > 0 ? { emitted } : {},
536
+ ...output === void 0 ? {} : { output },
537
+ ...error === void 0 ? {} : { error }
538
+ });
539
+ }
540
+ function prepare(collection, options) {
541
+ return {
542
+ param: options.workflowIdParam ?? "workflowId",
543
+ byId: new Map(collection.workflows.map((workflow) => [workflow.id, workflow])),
544
+ getProjectSecret: options.getProjectSecret ?? resolveProjectSecret
545
+ };
546
+ }
547
+ async function validateSchema(schema, value) {
548
+ return schema["~standard"].validate(value);
549
+ }
550
+ function validationError(label, issues) {
551
+ const detail = issues.map((issue) => issue.message).join("; ");
552
+ return `workflow ${label} failed validation${detail ? `: ${detail}` : ""}`;
553
+ }
554
+ async function validateInput(workflow, input) {
555
+ if (!workflow.inputSchema) return { input };
556
+ let result;
557
+ try {
558
+ result = await validateSchema(workflow.inputSchema, input);
559
+ } catch {
560
+ return json(500, {
561
+ error: "input_validation_failed",
562
+ message: "workflow input schema could not be evaluated"
563
+ });
564
+ }
565
+ if (result.issues) return json(400, {
566
+ error: "invalid_input",
567
+ message: validationError("input", result.issues)
568
+ });
569
+ return { input: result.value };
570
+ }
571
+ async function validateOutput(workflow, outcome) {
572
+ if (outcome.status !== "completed" || !workflow.outputSchema) return outcome;
573
+ let result;
574
+ try {
575
+ result = await validateSchema(workflow.outputSchema, outcome.output);
576
+ } catch {
577
+ return {
578
+ status: "failed",
579
+ memo: outcome.memo,
580
+ steps: [],
581
+ results: outcome.results,
582
+ emitted: outcome.emitted,
583
+ error: "workflow output schema could not be evaluated"
584
+ };
585
+ }
586
+ if (result.issues) return {
587
+ status: "failed",
588
+ memo: outcome.memo,
589
+ steps: [],
590
+ results: outcome.results,
591
+ emitted: outcome.emitted,
592
+ error: validationError("output", result.issues)
593
+ };
594
+ return {
595
+ ...outcome,
596
+ output: result.value
597
+ };
598
+ }
599
+ async function resolve(ctx, param, byId) {
600
+ const workflowId = resolveWorkflowId(ctx, param);
601
+ const current = workflowId === void 0 ? void 0 : byId.get(workflowId);
602
+ if (!current) return json(404, {
603
+ error: "unknown_workflow",
604
+ workflowId: workflowId ?? ""
605
+ });
606
+ let raw;
607
+ try {
608
+ raw = await readBody(ctx.request);
609
+ } catch (error) {
610
+ return json(400, {
611
+ error: "invalid_request",
612
+ message: `body is not valid JSON: ${String(error)}`
613
+ });
614
+ }
615
+ const body = parseBody(raw);
616
+ if (typeof body === "string") return json(400, {
617
+ error: "invalid_request",
618
+ message: body
619
+ });
620
+ const versions = workflowVersions(current);
621
+ if (body.workflowVersion === void 0 && (body.runId !== void 0 || body.memo !== void 0 || body.action === "execute")) return json(400, {
622
+ error: "workflow_version_required",
623
+ message: "Resuming a run requires its pinned workflowVersion"
624
+ });
625
+ const workflow = body.workflowVersion === void 0 ? versions[0] : versions.find((candidate) => candidate.version === body.workflowVersion);
626
+ if (!workflow) return json(409, {
627
+ error: "workflow_version_unavailable",
628
+ workflowId,
629
+ workflowVersion: body.workflowVersion
630
+ });
631
+ if (workflow !== current && !body.runId) return json(400, {
632
+ error: "retained_version_requires_run",
633
+ message: "Retained versions can only resume an existing run"
634
+ });
635
+ const wireInput = body.input ?? null;
636
+ const validated = await validateInput(workflow, wireInput);
637
+ if (validated instanceof Response) return validated;
638
+ const { input } = validated;
639
+ const inputHash = await hashInput(wireInput);
640
+ if (body.memo !== void 0 && body.memo.length > 0 && body.inputHash !== inputHash) return json(400, {
641
+ error: "invalid_request",
642
+ message: body.inputHash === void 0 ? "inputHash must be sent with a memo; echo the value from the previous response" : "input does not match the run this memo came from"
643
+ });
644
+ return {
645
+ workflow,
646
+ body,
647
+ input,
648
+ runId: body.runId ?? `run_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,
649
+ inputHash
650
+ };
651
+ }
652
+ function createStepsHandler(collection, options = {}) {
653
+ const { param, byId, getProjectSecret } = prepare(collection, options);
654
+ return async (ctx) => {
655
+ const auth = await authorizeProjectRequest(ctx.request, getProjectSecret);
656
+ if (auth === "unauthorized") return unauthorized();
657
+ if (auth === "unavailable") return authUnavailable();
658
+ const resolved = await resolve(ctx, param, byId);
659
+ if (resolved instanceof Response) return resolved;
660
+ const { workflow, body, input, runId, inputHash } = resolved;
661
+ const before = body.memo ?? [];
662
+ if (body.action === "execute") {
663
+ const selected = body.step;
664
+ const outcome = await validateOutput(workflow, await replay({
665
+ workflow,
666
+ input,
667
+ memo: before,
668
+ runId,
669
+ shouldExecute: (intent) => intent.kind !== "step" || operationKey(intent) === operationKey(selected)
670
+ }));
671
+ const executed = outcome.results.find((result) => result.kind === "step" && operationKey(result) === operationKey(selected));
672
+ if (executed === void 0 && outcome.status !== "failed") return json(409, {
673
+ error: "stale_step",
674
+ message: `step "${selected.stepId}" (#${selected.occurrence}) is not executable from this memo`
675
+ });
676
+ return respond(runId, inputHash, workflow.version, before, outcome, executed);
677
+ }
678
+ const described = await validateOutput(workflow, await replay({
679
+ workflow,
680
+ input,
681
+ memo: before,
682
+ runId,
683
+ shouldExecute: (intent) => intent.kind !== "step"
684
+ }));
685
+ const only = described.steps.length === 1 ? described.steps[0] : void 0;
686
+ if (described.status !== "pending" || only?.kind !== "step") return respond(runId, inputHash, workflow.version, before, described);
687
+ const outcome = await validateOutput(workflow, await replay({
688
+ workflow,
689
+ input,
690
+ memo: described.memo,
691
+ runId,
692
+ shouldExecute: (intent) => intent.kind !== "step" || operationKey(intent) === operationKey(only)
693
+ }));
694
+ const executed = outcome.results.find((result) => result.kind === "step" && operationKey(result) === operationKey(only));
695
+ if (executed === void 0 && outcome.status !== "failed") return json(409, {
696
+ error: "stale_step",
697
+ message: `step "${only.stepId}" (#${only.occurrence}) is not executable from this memo`
698
+ });
699
+ return respond(runId, inputHash, workflow.version, before, outcome, executed);
700
+ };
701
+ }
702
+ //#endregion
703
+ export { createMiddleware, createStepsHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };