@lovable.dev/workflows-sdk 0.0.0-dev.6 → 0.0.0-dev.60

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,1284 @@
1
- import { a as defineSchedule, c as weekly, i as registerWorkflows, n as createMiddleware, o as daily, r as createWorkflow, s as hourly, t as generateManifests } from "./generate-DyUHbtre.js";
2
- export { createMiddleware, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, weekly };
1
+ import { a as workflowVersions, c as every, d as WORKFLOW_ID_PATTERN, i as registerWorkflows, l as hourly, n as createMiddleware, o as defineSchedule, r as createWorkflow, s as daily, t as generateManifests, u as weekly } from "./generate-DGdzUQcG.js";
2
+ import { t as DURABLE_ID_REQUIRED } from "./durable-ids-CdlFkNKw.js";
3
+ import { n as assertLlmOptions, r as assertLlmRequest } from "./llm-validation-DdDO6csU.js";
4
+ import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
5
+ import { generateChatCompletion, generateMessage } from "@lovable.dev/ai-gateway";
6
+ //#region src/stacks/tanstack/sse.ts
7
+ const HEADERS = {
8
+ "content-type": "text/event-stream; charset=utf-8",
9
+ "cache-control": "no-cache, no-transform",
10
+ connection: "keep-alive",
11
+ "x-accel-buffering": "no"
12
+ };
13
+ function describe$1(error) {
14
+ return error instanceof Error ? error.message : String(error);
15
+ }
16
+ function frame(name, data) {
17
+ return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
18
+ }
19
+ /**
20
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
21
+ * engine `type` as the SSE event name and its whole JSON as the data line.
22
+ */
23
+ function toServerSentEventsResponse(events) {
24
+ const encoder = new TextEncoder();
25
+ const body = new ReadableStream({ async start(controller) {
26
+ let connected = true;
27
+ const write = (text) => {
28
+ if (!connected) return;
29
+ try {
30
+ controller.enqueue(encoder.encode(text));
31
+ } catch {
32
+ connected = false;
33
+ }
34
+ };
35
+ const send = (name, data) => {
36
+ try {
37
+ write(frame(name, data));
38
+ } catch (error) {
39
+ write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe$1(error)}` }));
40
+ }
41
+ };
42
+ try {
43
+ for await (const event of events) send(event.type, event);
44
+ } catch (error) {
45
+ send("STREAM_ERRORED", { message: describe$1(error) });
46
+ } finally {
47
+ try {
48
+ controller.close();
49
+ } catch {
50
+ connected = false;
51
+ }
52
+ }
53
+ } });
54
+ return new Response(body, { headers: HEADERS });
55
+ }
56
+ //#endregion
57
+ //#region src/stacks/tanstack/handlers.ts
58
+ function json$1(status, body) {
59
+ return new Response(JSON.stringify(body), {
60
+ status,
61
+ headers: { "content-type": "application/json; charset=utf-8" }
62
+ });
63
+ }
64
+ function resolveWorkflowId$1(ctx, param) {
65
+ const fromParams = ctx.params?.[param];
66
+ if (fromParams) return fromParams;
67
+ return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
68
+ }
69
+ /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
70
+ function createTanStackWorkflowHandler(collection, options = {}) {
71
+ const runStore = options.runStore ?? inMemoryRunStore();
72
+ const param = options.workflowIdParam ?? "workflowId";
73
+ const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
74
+ return async (ctx) => {
75
+ const workflowId = resolveWorkflowId$1(ctx, param);
76
+ const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
77
+ if (!workflow) return json$1(404, {
78
+ error: "unknown_workflow",
79
+ workflowId: workflowId ?? ""
80
+ });
81
+ let params;
82
+ try {
83
+ params = await parseWorkflowRequest(ctx.request);
84
+ } catch (error) {
85
+ if (error instanceof WorkflowRequestParseError) return json$1(400, {
86
+ error: "invalid_request",
87
+ message: error.message
88
+ });
89
+ throw error;
90
+ }
91
+ if (params.abort) return json$1(501, {
92
+ error: "abort_unsupported",
93
+ message: "Cancelling an in-flight run needs a shared run registry (WOR-53)."
94
+ });
95
+ const state = params.runId ? await runStore.getRunState(params.runId) : void 0;
96
+ if (state && state.workflowId !== workflow.id) return json$1(409, { error: "workflow_version_unavailable" });
97
+ const readOnly = state && [
98
+ "finished",
99
+ "errored",
100
+ "aborted"
101
+ ].includes(state.status);
102
+ const selected = state && !readOnly ? workflowVersions(workflow).find((candidate) => candidate.version === state.workflowVersion) : workflow;
103
+ if (!selected) return json$1(409, { error: "workflow_version_unavailable" });
104
+ return toServerSentEventsResponse(runWorkflow({
105
+ workflow: selected,
106
+ runStore,
107
+ ...params
108
+ }));
109
+ };
110
+ }
111
+ //#endregion
112
+ //#region src/runtime/input-hash.ts
113
+ /** Key order must not change the hash, so objects are serialized sorted. */
114
+ function canonical(value) {
115
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
116
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
117
+ 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(",")}}`;
118
+ }
119
+ /**
120
+ * Identifies the input a run started with. A resume carries it back so replay
121
+ * cannot be pointed at a different record than the one its memo came from.
122
+ */
123
+ async function hashInput(input) {
124
+ const bytes = new TextEncoder().encode(canonical(input));
125
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
126
+ return [...new Uint8Array(digest)].slice(0, 16).map((byte) => byte.toString(16).padStart(2, "0")).join("");
127
+ }
128
+ //#endregion
129
+ //#region src/runtime/operations.ts
130
+ var ReplayOperations = class {
131
+ memo;
132
+ settled;
133
+ pending = [];
134
+ consumed = /* @__PURE__ */ new Set();
135
+ never = new Promise(() => {});
136
+ error;
137
+ seq = 0;
138
+ constructor(memo, settled) {
139
+ this.memo = memo;
140
+ this.settled = settled;
141
+ }
142
+ reach(kind, stepId, meta) {
143
+ if (!stepId) {
144
+ this.error = `ctx.${kind}() was called without an id; ${DURABLE_ID_REQUIRED}`;
145
+ return;
146
+ }
147
+ const seq = this.seq++;
148
+ if (this.consumed.has(stepId)) {
149
+ this.error = `id "${stepId}" was reached more than once; every durable operation id must be unique within a workflow`;
150
+ return;
151
+ }
152
+ this.consumed.add(stepId);
153
+ const answered = this.memo.get(stepId) ?? this.settled.get(stepId);
154
+ if (!answered) return { seq };
155
+ if (answered.kind !== kind) {
156
+ this.error = `memo has ${answered.kind} "${stepId}", replay produced ${kind}`;
157
+ return;
158
+ }
159
+ if (kind === "connector" && (answered.meta?.connectorId !== meta?.connectorId || answered.meta?.connectionId !== meta?.connectionId)) {
160
+ this.error = `memo has a different connectorId or connectionId for connector "${stepId}"`;
161
+ return;
162
+ }
163
+ const recordedGroupId = groupId(answered.meta);
164
+ if (recordedGroupId !== void 0 && recordedGroupId !== groupId(meta)) {
165
+ this.error = `memo has group "${recordedGroupId}" for step "${stepId}", replay produced a different group`;
166
+ return;
167
+ }
168
+ if (answered.status === "completed") {
169
+ if (kind === "llm" && typeof answered.result !== "string") {
170
+ this.error = `memo has a non-string result for llm "${stepId}"`;
171
+ return;
172
+ }
173
+ return {
174
+ seq,
175
+ answer: Promise.resolve(answered.result)
176
+ };
177
+ }
178
+ return {
179
+ seq,
180
+ answer: Promise.reject(new Error(answered.error ?? `step "${stepId}" failed`))
181
+ };
182
+ }
183
+ };
184
+ function isRunnableKind(kind) {
185
+ return kind === "step" || kind === "llm" || kind === "connector";
186
+ }
187
+ function groupId(meta) {
188
+ const group = meta?.group;
189
+ if (group === null || typeof group !== "object") return void 0;
190
+ const id = group.id;
191
+ return typeof id === "string" ? id : void 0;
192
+ }
193
+ //#endregion
194
+ //#region src/core/connector.ts
195
+ function assertConnectorOptions(options) {
196
+ if (options === null || typeof options !== "object") throw new Error("@lovable.dev/workflows-sdk: ctx.connector() requires an options object");
197
+ const fields = options;
198
+ for (const field of ["connectorId", "connectionId"]) {
199
+ const value = fields[field];
200
+ if (typeof value !== "string" || !value.trim()) throw new Error(`@lovable.dev/workflows-sdk: ctx.connector() requires a nonempty ${field}`);
201
+ }
202
+ }
203
+ //#endregion
204
+ //#region src/runtime/llm.ts
205
+ const completeChat = generateChatCompletion;
206
+ const completeMessage = generateMessage;
207
+ function chatRequest(request) {
208
+ const messages = request.prompt !== void 0 ? [{
209
+ role: "user",
210
+ content: request.prompt
211
+ }] : request.messages;
212
+ const conversation = [...request.system === void 0 ? [] : [{
213
+ role: "system",
214
+ content: request.system
215
+ }], ...messages];
216
+ const maxTokens = request.maxTokens ?? 4096;
217
+ if (request.model.startsWith("openai/")) return {
218
+ model: request.model,
219
+ messages: conversation,
220
+ max_completion_tokens: maxTokens
221
+ };
222
+ if (request.model.startsWith("google/gemini-")) return {
223
+ model: request.model,
224
+ messages: conversation,
225
+ max_tokens: maxTokens,
226
+ modalities: ["text"]
227
+ };
228
+ throw new Error("ctx.llm requires an OpenAI or Gemini Chat Completions model, or a Claude Messages model");
229
+ }
230
+ function claudeText(response) {
231
+ if (response === null || typeof response !== "object" || !("content" in response) || !Array.isArray(response.content) || "stop_reason" in response && (response.stop_reason === "refusal" || response.stop_reason === "tool_use" || response.stop_reason === "pause_turn")) throw new Error("AI Gateway returned no assistant text");
232
+ if ("stop_reason" in response && (response.stop_reason === "max_tokens" || response.stop_reason === "model_context_window_exceeded")) throw new Error(`AI Gateway returned truncated Claude text (${response.stop_reason})`);
233
+ const text = response.content.map((block) => {
234
+ if (block === null || typeof block !== "object" || !("type" in block)) throw new Error("AI Gateway returned no assistant text");
235
+ if (block.type !== "text") return "";
236
+ if (!("text" in block) || typeof block.text !== "string") throw new Error("AI Gateway returned no assistant text");
237
+ return block.text;
238
+ }).join("");
239
+ if (text.trim() === "") throw new Error("AI Gateway returned no assistant text");
240
+ return text;
241
+ }
242
+ async function generateLlmText(request, options) {
243
+ assertLlmRequest(request);
244
+ if (request.model.startsWith("anthropic/claude-")) return claudeText(await completeMessage({
245
+ model: request.model,
246
+ messages: request.prompt !== void 0 ? [{
247
+ role: "user",
248
+ content: request.prompt
249
+ }] : request.messages,
250
+ ...request.system === void 0 ? {} : { system: request.system },
251
+ max_tokens: request.maxTokens ?? 4096
252
+ }, {
253
+ ...options,
254
+ maxRetries: 0
255
+ }));
256
+ const message = (await completeChat(chatRequest(request), {
257
+ ...options,
258
+ maxRetries: 0
259
+ }))?.choices?.[0]?.message;
260
+ if (message?.refusal || typeof message?.content !== "string" || message.content.trim() === "") throw new Error("AI Gateway returned no assistant text");
261
+ return message.content;
262
+ }
263
+ //#endregion
264
+ //#region src/runtime/replay.ts
265
+ /** How long a pass waits for handler work that is not a durable operation. */
266
+ const DEFAULT_SETTLE_MS = 5e3;
267
+ const EXECUTABLE = /* @__PURE__ */ new Set([
268
+ "step",
269
+ "llm",
270
+ "connector",
271
+ "now",
272
+ "uuid"
273
+ ]);
274
+ function describe(error) {
275
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
276
+ }
277
+ function runtimeContext() {
278
+ return {
279
+ timeRemaining: () => Number.POSITIVE_INFINITY,
280
+ shouldYield: () => false,
281
+ yield: async () => {}
282
+ };
283
+ }
284
+ /** Thread the handler through `.middleware([...])`, merging each extension into ctx. */
285
+ async function throughMiddleware(middlewares, ctx, handler) {
286
+ let index = 0;
287
+ const dispatch = async () => {
288
+ const middleware = middlewares[index++];
289
+ if (!middleware) return handler(ctx);
290
+ return middleware.server({
291
+ ctx,
292
+ next: async ({ context }) => {
293
+ Object.assign(ctx, context);
294
+ return dispatch();
295
+ }
296
+ });
297
+ };
298
+ return dispatch();
299
+ }
300
+ async function replay(options) {
301
+ const { workflow, input, runId } = options;
302
+ const attempt = options.attempt ?? 1;
303
+ const byKey = new Map(options.memo.map((entry) => [entry.stepId, entry]));
304
+ const allow = options.shouldExecute ?? (() => true);
305
+ const settled = /* @__PURE__ */ new Map();
306
+ const operations = new ReplayOperations(byKey, settled);
307
+ const { pending, consumed, never } = operations;
308
+ const pass = { stepsSettled: 0 };
309
+ let lastProgress = Date.now();
310
+ let currentParent;
311
+ const results = [];
312
+ const emitted = [];
313
+ const inflight = [];
314
+ function record(entry) {
315
+ settled.set(entry.stepId, entry);
316
+ lastProgress = Date.now();
317
+ if (isRunnableKind(entry.kind)) pass.stepsSettled += 1;
318
+ const result = {
319
+ seq: entry.seq,
320
+ stepId: entry.stepId,
321
+ kind: entry.kind,
322
+ ...entry.meta ? { meta: entry.meta } : {},
323
+ status: entry.status,
324
+ result: entry.result,
325
+ error: entry.error
326
+ };
327
+ results.push(result);
328
+ options.onStepSettle?.(result);
329
+ }
330
+ function durable(kind, stepId, run, config, meta) {
331
+ const operation = operations.reach(kind, stepId, meta);
332
+ if (!operation || !stepId) return never;
333
+ if (operation.answer) return operation.answer;
334
+ const index = operation.seq;
335
+ const parent = currentParent;
336
+ const intent = {
337
+ seq: index,
338
+ stepId,
339
+ kind,
340
+ ...config ? { config } : {},
341
+ ...meta ? { meta } : {}
342
+ };
343
+ if (!run || !EXECUTABLE.has(kind) || !allow(intent, pass)) {
344
+ pending.push(intent);
345
+ return never;
346
+ }
347
+ options.onStepStart?.(intent);
348
+ const enclosing = currentParent;
349
+ currentParent = stepId;
350
+ let body;
351
+ try {
352
+ body = run();
353
+ } finally {
354
+ currentParent = enclosing;
355
+ }
356
+ const running = body.then((result) => {
357
+ record({
358
+ seq: index,
359
+ stepId,
360
+ kind,
361
+ status: "completed",
362
+ result,
363
+ ...parent ? { parent } : {},
364
+ ...meta ? { meta } : {}
365
+ });
366
+ return result;
367
+ }, (error) => {
368
+ record({
369
+ seq: index,
370
+ stepId,
371
+ kind,
372
+ status: "failed",
373
+ error: describe(error),
374
+ ...parent ? { parent } : {},
375
+ ...meta ? { meta } : {}
376
+ });
377
+ throw error;
378
+ });
379
+ inflight.push(running.then(noop, noop));
380
+ return running;
381
+ }
382
+ const state = { ...workflow.initialize?.({ input }) };
383
+ const runtime = runtimeContext();
384
+ const signal = options.signal ?? new AbortController().signal;
385
+ function connector(id, callback, stepOptions) {
386
+ assertConnectorOptions(stepOptions);
387
+ return durable("connector", id, async () => {
388
+ const result = await callback({
389
+ id,
390
+ attempt,
391
+ runtime,
392
+ signal
393
+ });
394
+ return result === void 0 ? null : result;
395
+ }, void 0, {
396
+ ...stepOptions.meta,
397
+ connectorId: stepOptions.connectorId,
398
+ connectionId: stepOptions.connectionId
399
+ });
400
+ }
401
+ const llm = (request, stepOptions) => {
402
+ assertLlmOptions(stepOptions);
403
+ return durable("llm", stepOptions.id, () => generateLlmText(request, {
404
+ signal,
405
+ runId,
406
+ metadata: {
407
+ workflow_id: workflow.id,
408
+ workflow_step_id: stepOptions.id
409
+ }
410
+ }), void 0, stepOptions.meta);
411
+ };
412
+ const ctx = {
413
+ runId,
414
+ input,
415
+ state,
416
+ signal,
417
+ runtime,
418
+ connector,
419
+ llm,
420
+ step: (id, fn, stepOptions) => durable("step", id, async () => fn({
421
+ id,
422
+ attempt,
423
+ runtime,
424
+ signal
425
+ }), void 0, stepOptions?.meta),
426
+ sleep: (ms, opts) => durable("sleep", opts?.id, void 0, { ms }, opts?.meta),
427
+ sleepUntil: (timestamp, opts) => durable("sleep", opts?.id, void 0, { timestamp }, opts?.meta),
428
+ waitForEvent: (name, opts) => durable("waitForEvent", opts?.id, void 0, { name }, opts?.meta),
429
+ approve: (opts) => durable("approve", opts.id, void 0, {
430
+ title: opts.title,
431
+ ...opts.description === void 0 ? {} : { description: opts.description }
432
+ }, {
433
+ ...opts.meta,
434
+ ...opts.description === void 0 ? {} : { description: opts.description }
435
+ }),
436
+ now: (opts) => durable("now", opts?.id, async () => Date.now(), void 0, opts?.meta),
437
+ uuid: (opts) => durable("uuid", opts?.id, async () => crypto.randomUUID(), void 0, opts?.meta),
438
+ emit: (name, value) => {
439
+ emitted.push({
440
+ name,
441
+ value
442
+ });
443
+ }
444
+ };
445
+ let outcome;
446
+ throughMiddleware(workflow.middlewares ?? [], ctx, workflow.handler).then((output) => {
447
+ outcome = {
448
+ status: "completed",
449
+ output: output ?? null
450
+ };
451
+ }, (error) => {
452
+ outcome = {
453
+ status: "failed",
454
+ error: describe(error)
455
+ };
456
+ });
457
+ const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
458
+ for (;;) {
459
+ for (let tick = 0; tick < 20; tick++) await new Promise((resolve) => setTimeout(resolve, 0));
460
+ if (outcome || operations.error) break;
461
+ if (inflight.length > 0) {
462
+ await Promise.all(inflight.splice(0));
463
+ lastProgress = Date.now();
464
+ continue;
465
+ }
466
+ if (pending.length > 0 || Date.now() - lastProgress >= settleMs) break;
467
+ await new Promise((resolve) => setTimeout(resolve, 5));
468
+ }
469
+ while (inflight.length > 0) await Promise.all(inflight.splice(0));
470
+ const memo = [...byKey.values(), ...settled.values()];
471
+ const hidden = (start) => {
472
+ const seen = /* @__PURE__ */ new Set([start]);
473
+ let key = start;
474
+ for (;;) {
475
+ const parent = byKey.get(key)?.parent;
476
+ if (parent === void 0 || seen.has(parent)) return false;
477
+ if (consumed.has(parent)) return true;
478
+ seen.add(parent);
479
+ key = parent;
480
+ }
481
+ };
482
+ const orphan = [...byKey.keys()].find((key) => !consumed.has(key) && !hidden(key));
483
+ pending.sort((a, b) => a.seq - b.seq);
484
+ results.sort((a, b) => a.seq - b.seq);
485
+ const base = {
486
+ memo,
487
+ results,
488
+ emitted
489
+ };
490
+ if (operations.error) return {
491
+ ...base,
492
+ status: "failed",
493
+ steps: [],
494
+ error: `non-deterministic replay: ${operations.error}`
495
+ };
496
+ if (orphan !== void 0) return {
497
+ ...base,
498
+ status: "failed",
499
+ steps: [],
500
+ error: `stale memo: no operation matched "${orphan}"`
501
+ };
502
+ if (outcome?.status === "completed") return {
503
+ ...base,
504
+ status: "completed",
505
+ steps: [],
506
+ output: outcome.output
507
+ };
508
+ if (outcome?.status === "failed") return {
509
+ ...base,
510
+ status: "failed",
511
+ steps: [],
512
+ error: outcome.error
513
+ };
514
+ if (pending.length > 0) return {
515
+ ...base,
516
+ status: "pending",
517
+ steps: pending
518
+ };
519
+ return {
520
+ ...base,
521
+ status: "failed",
522
+ steps: [],
523
+ error: `workflow stalled: no durable operation and nothing settled for ${settleMs}ms`
524
+ };
525
+ }
526
+ function noop() {}
527
+ //#endregion
528
+ //#region src/core/runtime-env.ts
529
+ let cloudflareEnvPromise;
530
+ function readCloudflareEnv() {
531
+ cloudflareEnvPromise ??= import(
532
+ /* @vite-ignore */
533
+ "cloudflare:workers"
534
+ ).then((module) => module.env).catch(() => void 0);
535
+ return cloudflareEnvPromise;
536
+ }
537
+ /**
538
+ * Returns a server environment variable from `process.env`, or else from the `cloudflare:workers` env.
539
+ *
540
+ * Call it inside a request: on Workers, `process.env` can be empty at module scope. An empty value counts as unset.
541
+ */
542
+ async function readRuntimeEnv(name) {
543
+ const value = (globalThis.process?.env)?.[name];
544
+ if (typeof value === "string" && value) return value;
545
+ const cloudflareValue = (await readCloudflareEnv())?.[name];
546
+ return typeof cloudflareValue === "string" && cloudflareValue ? cloudflareValue : void 0;
547
+ }
548
+ //#endregion
549
+ //#region src/stacks/tanstack/project-auth.ts
550
+ const PROJECT_SECRET_ENV_VAR = "LOVABLE_WORKFLOWS_KEY";
551
+ function resolveProjectSecret() {
552
+ return readRuntimeEnv(PROJECT_SECRET_ENV_VAR);
553
+ }
554
+ function bearerToken(request) {
555
+ const header = request.headers.get("authorization");
556
+ if (!header) return void 0;
557
+ const parts = header.trim().split(/\s+/);
558
+ if (parts.length !== 2 || parts[0].toLowerCase() !== "bearer") return void 0;
559
+ return parts[1] || void 0;
560
+ }
561
+ async function equalSecrets(left, right) {
562
+ const encoder = new TextEncoder();
563
+ const [leftHash, rightHash] = await Promise.all([crypto.subtle.digest("SHA-256", encoder.encode(left)), crypto.subtle.digest("SHA-256", encoder.encode(right))]);
564
+ const leftBytes = new Uint8Array(leftHash);
565
+ const rightBytes = new Uint8Array(rightHash);
566
+ let difference = 0;
567
+ for (let index = 0; index < leftBytes.length; index += 1) difference |= leftBytes[index] ^ rightBytes[index];
568
+ return difference === 0;
569
+ }
570
+ async function authorizeProjectRequest(request, getProjectSecret) {
571
+ let projectSecret;
572
+ try {
573
+ projectSecret = await getProjectSecret();
574
+ } catch {
575
+ return "unavailable";
576
+ }
577
+ if (!projectSecret) return "unavailable";
578
+ const token = bearerToken(request);
579
+ if (!token) return "unauthorized";
580
+ try {
581
+ return await equalSecrets(token, projectSecret) ? "authorized" : "unauthorized";
582
+ } catch {
583
+ return "unavailable";
584
+ }
585
+ }
586
+ //#endregion
587
+ //#region src/stacks/tanstack/steps-response.ts
588
+ function disposition(outcome) {
589
+ if (outcome.status === "completed") return "completed";
590
+ if (outcome.status === "failed") return "failed";
591
+ if (!outcome.steps.some((step) => isRunnableKind(step.kind))) return "waiting";
592
+ return outcome.steps.length > 1 ? "fork" : "advanced";
593
+ }
594
+ function memoDelta(before, after) {
595
+ const existing = new Set(before.map((entry) => entry.stepId));
596
+ return after.filter((entry) => !existing.has(entry.stepId));
597
+ }
598
+ function stepsResponse(runId, inputHash, workflowVersion, before, outcome, executed) {
599
+ const { steps, emitted, output, error } = outcome;
600
+ const base = {
601
+ runId,
602
+ inputHash,
603
+ workflowVersion,
604
+ memoDelta: memoDelta(before, outcome.memo),
605
+ next: steps,
606
+ ...emitted.length > 0 ? { emitted } : {}
607
+ };
608
+ const nextDisposition = disposition(outcome);
609
+ const deferred = executed?.status === "completed" && nextDisposition !== "fork";
610
+ return {
611
+ ...base,
612
+ disposition: deferred ? "advanced" : nextDisposition,
613
+ next: deferred && nextDisposition === "waiting" ? [] : steps,
614
+ ...executed === void 0 ? {} : { executed },
615
+ ...deferred || output === void 0 ? {} : { output },
616
+ ...deferred || error === void 0 ? {} : { error }
617
+ };
618
+ }
619
+ //#endregion
620
+ //#region src/stacks/tanstack/steps.ts
621
+ const ATTEMPT_HEADER = "x-lovable-workflow-attempt";
622
+ function attemptOf(request) {
623
+ const attempt = Number(request.headers.get(ATTEMPT_HEADER));
624
+ return Number.isInteger(attempt) && attempt > 0 ? attempt : 1;
625
+ }
626
+ function json(status, body) {
627
+ return new Response(JSON.stringify(body), {
628
+ status,
629
+ headers: { "content-type": "application/json; charset=utf-8" }
630
+ });
631
+ }
632
+ function unauthorized() {
633
+ const response = json(401, { error: "unauthorized" });
634
+ response.headers.set("www-authenticate", "Bearer");
635
+ return response;
636
+ }
637
+ function authUnavailable() {
638
+ return json(503, {
639
+ error: "workflow_auth_unavailable",
640
+ message: "LOVABLE_WORKFLOWS_KEY is not configured in this app runtime"
641
+ });
642
+ }
643
+ function resolveWorkflowId(ctx, param) {
644
+ const fromParams = ctx.params?.[param];
645
+ if (fromParams) return fromParams;
646
+ return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-2);
647
+ }
648
+ function isMemoEntry(value) {
649
+ const entry = value;
650
+ return typeof entry === "object" && entry !== null && Number.isInteger(entry.seq) && entry.seq >= 0 && typeof entry.stepId === "string" && Number.isInteger(entry.seq) && (entry.status === "completed" || entry.status === "failed");
651
+ }
652
+ function parseBody(value) {
653
+ if (value === null || typeof value !== "object") return "body must be a JSON object";
654
+ const body = value;
655
+ if (body.workflowVersion !== void 0 && typeof body.workflowVersion !== "string") return "workflowVersion must be a string";
656
+ if (body.memo !== void 0) {
657
+ if (!Array.isArray(body.memo) || !body.memo.every(isMemoEntry)) return "memo must be an array of settled step entries";
658
+ if (new Set(body.memo.map((entry) => entry.stepId)).size !== body.memo.length) return "memo entries must be unique per stepId";
659
+ }
660
+ if (body.action !== void 0 && body.action !== "advance" && body.action !== "execute") return "action must be \"advance\" or \"execute\"";
661
+ if (body.action === "execute" && !isStepReference(body.step)) return "step must be a { kind: \"step\" | \"llm\" | \"connector\", stepId } reference when action is \"execute\"";
662
+ if (body.action !== "execute" && body.step !== void 0) return "step is only valid when action is \"execute\"";
663
+ if (body.describe !== void 0 && typeof body.describe !== "boolean") return "describe must be a boolean";
664
+ if (body.memo !== void 0 && body.memo.length > 0 && !("input" in value)) return "input must be sent with every call, including a resume";
665
+ return body;
666
+ }
667
+ async function readBody(request) {
668
+ const text = await request.text();
669
+ if (!text.trim()) return {};
670
+ return JSON.parse(text);
671
+ }
672
+ function isStepReference(value) {
673
+ const step = value;
674
+ return typeof step === "object" && step !== null && isRunnableKind(step.kind) && typeof step.stepId === "string";
675
+ }
676
+ function prepare(collection, options) {
677
+ return {
678
+ param: options.workflowIdParam ?? "workflowId",
679
+ byId: new Map(collection.workflows.map((workflow) => [workflow.id, workflow])),
680
+ getProjectSecret: options.getProjectSecret ?? resolveProjectSecret
681
+ };
682
+ }
683
+ async function validateSchema(schema, value) {
684
+ return schema["~standard"].validate(value);
685
+ }
686
+ function validationError(label, issues) {
687
+ const detail = issues.map((issue) => issue.message).join("; ");
688
+ return `workflow ${label} failed validation${detail ? `: ${detail}` : ""}`;
689
+ }
690
+ async function validateInput(workflow, input) {
691
+ if (!workflow.inputSchema) return { input };
692
+ let result;
693
+ try {
694
+ result = await validateSchema(workflow.inputSchema, input);
695
+ } catch {
696
+ return json(500, {
697
+ error: "input_validation_failed",
698
+ message: "workflow input schema could not be evaluated"
699
+ });
700
+ }
701
+ if (result.issues) return json(400, {
702
+ error: "invalid_input",
703
+ message: validationError("input", result.issues)
704
+ });
705
+ return { input: result.value };
706
+ }
707
+ async function validateOutput(workflow, outcome) {
708
+ if (outcome.status !== "completed" || !workflow.outputSchema || outcome.results.some((result) => isRunnableKind(result.kind) && result.status === "completed")) return outcome;
709
+ let result;
710
+ try {
711
+ result = await validateSchema(workflow.outputSchema, outcome.output);
712
+ } catch {
713
+ return {
714
+ status: "failed",
715
+ memo: outcome.memo,
716
+ steps: [],
717
+ results: outcome.results,
718
+ emitted: outcome.emitted,
719
+ error: "workflow output schema could not be evaluated"
720
+ };
721
+ }
722
+ if (result.issues) return {
723
+ status: "failed",
724
+ memo: outcome.memo,
725
+ steps: [],
726
+ results: outcome.results,
727
+ emitted: outcome.emitted,
728
+ error: validationError("output", result.issues)
729
+ };
730
+ return {
731
+ ...outcome,
732
+ output: result.value
733
+ };
734
+ }
735
+ async function resolve(ctx, param, byId) {
736
+ const workflowId = resolveWorkflowId(ctx, param);
737
+ const current = workflowId === void 0 ? void 0 : byId.get(workflowId);
738
+ if (!current) return json(404, {
739
+ error: "unknown_workflow",
740
+ workflowId: workflowId ?? ""
741
+ });
742
+ let raw;
743
+ try {
744
+ raw = await readBody(ctx.request);
745
+ } catch (error) {
746
+ return json(400, {
747
+ error: "invalid_request",
748
+ message: `body is not valid JSON: ${String(error)}`
749
+ });
750
+ }
751
+ const body = parseBody(raw);
752
+ if (typeof body === "string") return json(400, {
753
+ error: "invalid_request",
754
+ message: body
755
+ });
756
+ const versions = workflowVersions(current);
757
+ if (body.workflowVersion === void 0 && (body.runId !== void 0 || body.memo !== void 0 || body.action === "execute")) return json(400, {
758
+ error: "workflow_version_required",
759
+ message: "Resuming a run requires its pinned workflowVersion"
760
+ });
761
+ const workflow = body.workflowVersion === void 0 ? versions[0] : versions.find((candidate) => candidate.version === body.workflowVersion);
762
+ if (!workflow) return json(409, {
763
+ error: "workflow_version_unavailable",
764
+ workflowId,
765
+ workflowVersion: body.workflowVersion
766
+ });
767
+ if (workflow !== current && !body.runId) return json(400, {
768
+ error: "retained_version_requires_run",
769
+ message: "Retained versions can only resume an existing run"
770
+ });
771
+ const wireInput = body.input ?? null;
772
+ const validated = await validateInput(workflow, wireInput);
773
+ if (validated instanceof Response) return validated;
774
+ const { input } = validated;
775
+ const inputHash = await hashInput(wireInput);
776
+ if (body.memo !== void 0 && body.memo.length > 0 && body.inputHash !== inputHash) return json(400, {
777
+ error: "invalid_request",
778
+ 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"
779
+ });
780
+ return {
781
+ workflow,
782
+ body,
783
+ input,
784
+ runId: body.runId ?? `run_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,
785
+ inputHash
786
+ };
787
+ }
788
+ function createStepsHandler(collection, options = {}) {
789
+ const { param, byId, getProjectSecret } = prepare(collection, options);
790
+ return async (ctx) => {
791
+ const auth = await authorizeProjectRequest(ctx.request, getProjectSecret);
792
+ if (auth === "unauthorized") return unauthorized();
793
+ if (auth === "unavailable") return authUnavailable();
794
+ const resolved = await resolve(ctx, param, byId);
795
+ if (resolved instanceof Response) return resolved;
796
+ const { workflow, body, input, runId, inputHash } = resolved;
797
+ const before = body.memo ?? [];
798
+ const attempt = attemptOf(ctx.request);
799
+ if (body.action === "execute") {
800
+ const selected = body.step;
801
+ const outcome = await validateOutput(workflow, await replay({
802
+ workflow,
803
+ input,
804
+ memo: before,
805
+ runId,
806
+ signal: ctx.request.signal,
807
+ attempt,
808
+ shouldExecute: (intent) => !isRunnableKind(intent.kind) || intent.kind === selected.kind && intent.stepId === selected.stepId
809
+ }));
810
+ const executed = outcome.results.find((result) => result.kind === selected.kind && result.stepId === selected.stepId);
811
+ if (executed === void 0 && outcome.status !== "failed") return json(409, {
812
+ error: "stale_step",
813
+ message: `step "${selected.stepId}" is not executable from this memo`
814
+ });
815
+ return json(200, stepsResponse(runId, inputHash, workflow.version, before, outcome, executed));
816
+ }
817
+ const described = await validateOutput(workflow, await replay({
818
+ workflow,
819
+ input,
820
+ memo: before,
821
+ runId,
822
+ signal: ctx.request.signal,
823
+ attempt,
824
+ shouldExecute: (intent) => !isRunnableKind(intent.kind)
825
+ }));
826
+ const only = described.steps.length === 1 ? described.steps[0] : void 0;
827
+ if (described.status !== "pending" || !only || !isRunnableKind(only.kind) || body.describe === true) return json(200, stepsResponse(runId, inputHash, workflow.version, before, described));
828
+ const outcome = await validateOutput(workflow, await replay({
829
+ workflow,
830
+ input,
831
+ memo: described.memo,
832
+ runId,
833
+ signal: ctx.request.signal,
834
+ attempt,
835
+ shouldExecute: (intent) => !isRunnableKind(intent.kind) || intent.kind === only.kind && intent.stepId === only.stepId
836
+ }));
837
+ const executed = outcome.results.find((result) => result.kind === only.kind && result.stepId === only.stepId);
838
+ if (executed === void 0 && outcome.status !== "failed") return json(409, {
839
+ error: "stale_step",
840
+ message: `step "${only.stepId}" is not executable from this memo`
841
+ });
842
+ return json(200, stepsResponse(runId, inputHash, workflow.version, before, outcome, executed));
843
+ };
844
+ }
845
+ //#endregion
846
+ //#region src/client/errors.ts
847
+ /**
848
+ * A failed `startRun`, `getRun` or `deliverEvent` call.
849
+ *
850
+ * `status` is the gateway's HTTP status, and is undefined when the SDK refused the call before sending it or got no
851
+ * response. `retryable` is true when repeating the same call later can succeed without a change to the code, the
852
+ * configuration or the app; the SDK itself never retries.
853
+ */
854
+ var WorkflowsApiError = class extends Error {
855
+ name = "WorkflowsApiError";
856
+ type;
857
+ status;
858
+ requestId;
859
+ title;
860
+ detail;
861
+ errors;
862
+ retryable;
863
+ retryAfterMs;
864
+ constructor(message, fields) {
865
+ super(message, fields.cause === void 0 ? void 0 : { cause: fields.cause });
866
+ this.type = fields.type;
867
+ this.status = fields.status;
868
+ this.requestId = fields.requestId;
869
+ this.title = fields.title;
870
+ this.detail = fields.detail;
871
+ this.errors = fields.errors;
872
+ this.retryable = fields.retryable;
873
+ this.retryAfterMs = fields.retryAfterMs;
874
+ }
875
+ toJSON() {
876
+ return {
877
+ name: this.name,
878
+ message: this.message,
879
+ type: this.type,
880
+ status: this.status,
881
+ requestId: this.requestId,
882
+ title: this.title,
883
+ detail: this.detail,
884
+ errors: this.errors,
885
+ retryable: this.retryable,
886
+ retryAfterMs: this.retryAfterMs
887
+ };
888
+ }
889
+ };
890
+ var WorkflowsConfigurationError = class extends WorkflowsApiError {
891
+ name = "WorkflowsConfigurationError";
892
+ reason;
893
+ constructor(reason, message) {
894
+ super(message, {
895
+ type: "configuration_error",
896
+ retryable: false
897
+ });
898
+ this.reason = reason;
899
+ }
900
+ };
901
+ var WorkflowsRequestInvalidError = class extends WorkflowsApiError {
902
+ name = "WorkflowsRequestInvalidError";
903
+ };
904
+ /** The input fails the workflow's input schema. The SDK sent no request, so the Idempotency-Key is still unused. */
905
+ var RunInputInvalidError = class extends WorkflowsRequestInvalidError {
906
+ name = "RunInputInvalidError";
907
+ issues;
908
+ constructor(message, fields) {
909
+ super(message, fields);
910
+ this.issues = fields.issues;
911
+ }
912
+ };
913
+ var WorkflowsNetworkError = class extends WorkflowsApiError {
914
+ name = "WorkflowsNetworkError";
915
+ };
916
+ var WorkflowsAuthenticationError = class extends WorkflowsApiError {
917
+ name = "WorkflowsAuthenticationError";
918
+ };
919
+ var WorkflowsKeyLookupError = class extends WorkflowsApiError {
920
+ name = "WorkflowsKeyLookupError";
921
+ };
922
+ var WorkflowsDevelopmentKeyError = class extends WorkflowsApiError {
923
+ name = "WorkflowsDevelopmentKeyError";
924
+ };
925
+ var WorkflowsDisabledError = class extends WorkflowsApiError {
926
+ name = "WorkflowsDisabledError";
927
+ };
928
+ var RunNotFoundError = class extends WorkflowsApiError {
929
+ name = "RunNotFoundError";
930
+ };
931
+ var WorkflowNotPublishedError = class extends WorkflowsApiError {
932
+ name = "WorkflowNotPublishedError";
933
+ };
934
+ var IdempotencyKeyReusedError = class extends WorkflowsApiError {
935
+ name = "IdempotencyKeyReusedError";
936
+ };
937
+ var RunClosedError = class extends WorkflowsApiError {
938
+ name = "RunClosedError";
939
+ };
940
+ var RunNotWaitingError = class extends WorkflowsApiError {
941
+ name = "RunNotWaitingError";
942
+ };
943
+ var EventAlreadyDeliveredError = class extends WorkflowsApiError {
944
+ name = "EventAlreadyDeliveredError";
945
+ };
946
+ var WorkflowsPayloadTooLargeError = class extends WorkflowsApiError {
947
+ name = "WorkflowsPayloadTooLargeError";
948
+ };
949
+ var WorkflowsRateLimitedError = class extends WorkflowsApiError {
950
+ name = "WorkflowsRateLimitedError";
951
+ };
952
+ var WorkflowsUnavailableError = class extends WorkflowsApiError {
953
+ name = "WorkflowsUnavailableError";
954
+ };
955
+ const CLASS_BY_TYPE = /* @__PURE__ */ new Map([
956
+ ["invalid_request", WorkflowsRequestInvalidError],
957
+ ["invalid_api_key", WorkflowsAuthenticationError],
958
+ ["lovable_api_key_not_registered", WorkflowsAuthenticationError],
959
+ ["lovable_api_key_registry_lookup_failed", WorkflowsKeyLookupError],
960
+ ["lovable_api_key_development_only", WorkflowsDevelopmentKeyError],
961
+ ["app_workflows_disabled", WorkflowsDisabledError],
962
+ ["run_not_found", RunNotFoundError],
963
+ ["workflow_not_published", WorkflowNotPublishedError],
964
+ ["idempotency_key_reused", IdempotencyKeyReusedError],
965
+ ["run_closed", RunClosedError],
966
+ ["run_not_waiting", RunNotWaitingError],
967
+ ["event_already_delivered", EventAlreadyDeliveredError],
968
+ ["run_input_too_large", WorkflowsPayloadTooLargeError],
969
+ ["payload_too_large", WorkflowsPayloadTooLargeError]
970
+ ]);
971
+ const RETRYABLE_CLASSES = /* @__PURE__ */ new Set([
972
+ WorkflowsKeyLookupError,
973
+ RunNotWaitingError,
974
+ WorkflowsRateLimitedError,
975
+ WorkflowsUnavailableError
976
+ ]);
977
+ const HINT_BY_TYPE = /* @__PURE__ */ new Map([["lovable_api_key_not_registered", "Rotate the project's LOVABLE_API_KEY, then republish the app or restart its backend so the server sends the new key."], ["invalid_api_key", "Check that the server's LOVABLE_API_KEY is this project's current key."]]);
978
+ const TYPE_BY_STATUS = /* @__PURE__ */ new Map([
979
+ [400, "bad_request"],
980
+ [401, "unauthorized"],
981
+ [403, "forbidden"],
982
+ [404, "not_found"],
983
+ [405, "method_not_allowed"],
984
+ [408, "request_timeout"],
985
+ [409, "conflict"],
986
+ [413, "request_entity_too_large"],
987
+ [415, "unsupported_media_type"],
988
+ [429, "too_many_requests"],
989
+ [500, "internal_server_error"],
990
+ [502, "bad_gateway"],
991
+ [503, "service_unavailable"],
992
+ [504, "gateway_timeout"]
993
+ ]);
994
+ const DEFAULT_RETRY_AFTER_MS = 1e3;
995
+ const MAX_ERROR_BODY_BYTES = 16384;
996
+ const ERROR_BODY_TIMEOUT_MS = 1e3;
997
+ const PACKAGE_PREFIX = "@lovable.dev/workflows-sdk";
998
+ function object(value) {
999
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
1000
+ }
1001
+ async function readErrorBody(response) {
1002
+ if (!response.body) return void 0;
1003
+ const reader = response.body.getReader();
1004
+ let timer;
1005
+ try {
1006
+ return await Promise.race([(async () => {
1007
+ const decoder = new TextDecoder();
1008
+ let text = "";
1009
+ let bytes = 0;
1010
+ while (true) {
1011
+ const { done, value } = await reader.read();
1012
+ if (done) return JSON.parse(text + decoder.decode());
1013
+ bytes += value.byteLength;
1014
+ if (bytes > MAX_ERROR_BODY_BYTES) return void 0;
1015
+ text += decoder.decode(value, { stream: true });
1016
+ }
1017
+ })(), new Promise((resolve) => {
1018
+ timer = setTimeout(() => resolve(void 0), ERROR_BODY_TIMEOUT_MS);
1019
+ })]);
1020
+ } catch {
1021
+ return;
1022
+ } finally {
1023
+ clearTimeout(timer);
1024
+ reader.cancel().catch(() => void 0);
1025
+ }
1026
+ }
1027
+ function parseRetryAfter(value) {
1028
+ if (!value || value.length > 128) return void 0;
1029
+ const trimmed = value.trim();
1030
+ if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
1031
+ const milliseconds = Number(trimmed) * 1e3;
1032
+ return Number.isFinite(milliseconds) ? milliseconds : void 0;
1033
+ }
1034
+ if (!/^[A-Za-z]/.test(trimmed)) return void 0;
1035
+ const timestamp = Date.parse(trimmed);
1036
+ return Number.isFinite(timestamp) ? Math.max(0, timestamp - Date.now()) : void 0;
1037
+ }
1038
+ /** Replaces the API key in text that reaches an error, and caps its length. */
1039
+ function redactor(apiKey) {
1040
+ return (value, maxLength = 2e3) => (apiKey ? value.replaceAll(apiKey, "[redacted]") : value).slice(0, maxLength);
1041
+ }
1042
+ function errorDetails(value, redact) {
1043
+ if (!Array.isArray(value)) return void 0;
1044
+ const details = [];
1045
+ for (const entry of value.slice(0, 50)) {
1046
+ const { location, message } = object(entry);
1047
+ if (typeof message !== "string") continue;
1048
+ details.push({
1049
+ location: typeof location === "string" ? redact(location, 200) : null,
1050
+ message: redact(message)
1051
+ });
1052
+ }
1053
+ return details;
1054
+ }
1055
+ async function errorFromResponse(call, response, apiKey) {
1056
+ const redact = redactor(apiKey);
1057
+ const text = (value, maxLength) => typeof value === "string" && value ? redact(value, maxLength) : void 0;
1058
+ const body = object(await readErrorBody(response));
1059
+ const status = response.status;
1060
+ const envelopeType = text(body.type, 200);
1061
+ const type = envelopeType ?? TYPE_BY_STATUS.get(status) ?? `http_${status}`;
1062
+ let ErrorClass = WorkflowsApiError;
1063
+ if (status === 429) ErrorClass = WorkflowsRateLimitedError;
1064
+ else if (status === 503) ErrorClass = WorkflowsUnavailableError;
1065
+ else if (envelopeType) ErrorClass = CLASS_BY_TYPE.get(envelopeType) ?? WorkflowsApiError;
1066
+ const retryable = RETRYABLE_CLASSES.has(ErrorClass) || ErrorClass === WorkflowsApiError && (status === 408 || status >= 500);
1067
+ const retryAfterMs = parseRetryAfter(response.headers.get("Retry-After")) ?? (status === 429 || status === 503 ? DEFAULT_RETRY_AFTER_MS : void 0);
1068
+ const title = text(body.title, 200);
1069
+ const detail = text(body.detail);
1070
+ const hint = HINT_BY_TYPE.get(type);
1071
+ return new ErrorClass(`${PACKAGE_PREFIX}: ${call} failed (${status} ${type}): ${detail ?? title ?? "The gateway answered without an error body."}${hint ? ` ${hint}` : ""}`, {
1072
+ type,
1073
+ status,
1074
+ requestId: text(response.headers.get("X-Request-Id"), 200) ?? text(body.request_id, 200),
1075
+ title,
1076
+ detail,
1077
+ errors: errorDetails(body.errors, redact),
1078
+ retryable,
1079
+ retryAfterMs
1080
+ });
1081
+ }
1082
+ //#endregion
1083
+ //#region src/client/transport.ts
1084
+ const DEFAULT_BASE_URL = "https://connector-gateway.lovable.dev";
1085
+ function assertServerRuntime() {
1086
+ const runtime = globalThis;
1087
+ if (typeof runtime.window !== "undefined" && typeof runtime.document !== "undefined") throw new WorkflowsConfigurationError("server_only", `${PACKAGE_PREFIX}: startRun, getRun and deliverEvent run only in server code, because they send the app's LOVABLE_API_KEY.`);
1088
+ }
1089
+ async function connect() {
1090
+ const apiKey = (await readRuntimeEnv("LOVABLE_API_KEY"))?.trim();
1091
+ if (!apiKey) throw new WorkflowsConfigurationError("missing_api_key", `${PACKAGE_PREFIX}: LOVABLE_API_KEY is missing from the server environment.`);
1092
+ const baseURL = ((await readRuntimeEnv("LOVABLE_WORKFLOWS_API_URL"))?.trim() || DEFAULT_BASE_URL).replace(/\/+$/, "");
1093
+ let url;
1094
+ try {
1095
+ url = new URL(baseURL);
1096
+ } catch {
1097
+ url = void 0;
1098
+ }
1099
+ if (!url || !["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new WorkflowsConfigurationError("invalid_url", `${PACKAGE_PREFIX}: LOVABLE_WORKFLOWS_API_URL must be an http or https URL without credentials, a query or a fragment.`);
1100
+ return {
1101
+ apiKey,
1102
+ baseURL
1103
+ };
1104
+ }
1105
+ function networkError(call, cause) {
1106
+ return new WorkflowsNetworkError(`${PACKAGE_PREFIX}: ${call} failed before the gateway answered.${call === "startRun" ? " The run may have started. Retry with the same idempotency key and input." : call === "deliverEvent" ? " The event may have been recorded. Retry with the same eventId." : ""}`, {
1107
+ type: "network_error",
1108
+ retryable: true,
1109
+ cause
1110
+ });
1111
+ }
1112
+ function invalidResponse(call, response, cause) {
1113
+ return new WorkflowsApiError(`${PACKAGE_PREFIX}: ${call} got a ${response.status} response that is not the expected JSON.`, {
1114
+ type: "invalid_response",
1115
+ status: response.status,
1116
+ requestId: response.headers.get("X-Request-Id")?.slice(0, 200) || void 0,
1117
+ retryable: true,
1118
+ cause
1119
+ });
1120
+ }
1121
+ async function send(request) {
1122
+ const connection = await connect();
1123
+ const headers = new Headers(request.headers);
1124
+ headers.set("Authorization", `Bearer ${connection.apiKey}`);
1125
+ headers.set("Accept", "application/json");
1126
+ headers.set("User-Agent", `lovable-workflows-sdk/0.0.0-dev.60`);
1127
+ if (request.body !== void 0) headers.set("Content-Type", "application/json");
1128
+ let response;
1129
+ try {
1130
+ response = await fetch(`${connection.baseURL}${request.path}`, {
1131
+ method: request.method,
1132
+ headers,
1133
+ body: request.body,
1134
+ signal: request.signal,
1135
+ redirect: "manual"
1136
+ });
1137
+ } catch (cause) {
1138
+ if (request.signal?.aborted) throw request.signal.reason;
1139
+ throw networkError(request.call, cause);
1140
+ }
1141
+ if (!response.ok) throw await errorFromResponse(request.call, response, connection.apiKey);
1142
+ let parsed;
1143
+ try {
1144
+ parsed = await response.json();
1145
+ } catch (cause) {
1146
+ if (request.signal?.aborted) throw request.signal.reason;
1147
+ if (cause instanceof SyntaxError) throw invalidResponse(request.call, response, cause);
1148
+ throw networkError(request.call, cause);
1149
+ }
1150
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw invalidResponse(request.call, response);
1151
+ return parsed;
1152
+ }
1153
+ //#endregion
1154
+ //#region src/client/runs.ts
1155
+ const IDEMPOTENCY_KEY_PATTERN = /^[\x20-\x7E]{1,64}$/;
1156
+ const MAX_RUN_ID_LENGTH = 64;
1157
+ function invalidRequest(call, location, message, cause) {
1158
+ return new WorkflowsRequestInvalidError(`${PACKAGE_PREFIX}: ${call}: ${message}`, {
1159
+ type: "invalid_request",
1160
+ retryable: false,
1161
+ errors: [{
1162
+ location,
1163
+ message
1164
+ }],
1165
+ cause
1166
+ });
1167
+ }
1168
+ function serialize(call, body, location) {
1169
+ try {
1170
+ return JSON.stringify(body);
1171
+ } catch (cause) {
1172
+ throw invalidRequest(call, location, "the value is not JSON-serializable", cause);
1173
+ }
1174
+ }
1175
+ function checkRunId(call, runId) {
1176
+ if (typeof runId !== "string" || runId === "" || runId.length > MAX_RUN_ID_LENGTH) throw invalidRequest(call, "path.run_id", "runId must be a non-empty string of at most 64 characters");
1177
+ }
1178
+ function issueLocation(issue) {
1179
+ let location = "body.input";
1180
+ for (const segment of issue.path ?? []) {
1181
+ const key = typeof segment === "object" ? segment.key : segment;
1182
+ location += typeof key === "number" ? `[${key}]` : `.${String(key)}`;
1183
+ }
1184
+ return location;
1185
+ }
1186
+ async function checkInput(workflow, body) {
1187
+ if (!workflow.inputSchema) return;
1188
+ const input = JSON.parse(body).input ?? null;
1189
+ const result = await workflow.inputSchema["~standard"].validate(input);
1190
+ if (!result.issues) return;
1191
+ const summary = result.issues.map((issue) => issue.message).join("; ");
1192
+ throw new RunInputInvalidError(`${PACKAGE_PREFIX}: startRun: the input fails the input schema of workflow "${workflow.id}"${summary ? `: ${summary}` : ""}`, {
1193
+ type: "invalid_input",
1194
+ retryable: false,
1195
+ errors: result.issues.map((issue) => ({
1196
+ location: issueLocation(issue),
1197
+ message: issue.message
1198
+ })),
1199
+ issues: result.issues
1200
+ });
1201
+ }
1202
+ function toRunSummary(wire) {
1203
+ const run = wire;
1204
+ return {
1205
+ runId: run.run_id,
1206
+ workflowId: run.workflow_id,
1207
+ status: run.status,
1208
+ trigger: run.trigger,
1209
+ createdAt: run.created_at
1210
+ };
1211
+ }
1212
+ function toRun(wire) {
1213
+ const run = wire;
1214
+ return {
1215
+ ...toRunSummary(wire),
1216
+ updatedAt: run.updated_at,
1217
+ closedAt: run.closed_at,
1218
+ error: run.error,
1219
+ input: run.input,
1220
+ output: run.output
1221
+ };
1222
+ }
1223
+ async function startRun(workflow, input, options = {}) {
1224
+ options.signal?.throwIfAborted();
1225
+ assertServerRuntime();
1226
+ const definition = typeof workflow === "string" ? void 0 : workflow;
1227
+ if (definition !== void 0 && (typeof definition !== "object" || definition?.__kind !== "workflow")) throw invalidRequest("startRun", "path.workflow_id", "pass a workflow id or a createWorkflow() definition");
1228
+ const workflowId = definition?.id ?? workflow;
1229
+ if (typeof workflowId !== "string" || !WORKFLOW_ID_PATTERN.test(workflowId)) throw invalidRequest("startRun", "path.workflow_id", "workflow ids are 1–128 lowercase letters, digits, hyphens or underscores, starting with a letter or digit");
1230
+ const { idempotencyKey } = options;
1231
+ if (idempotencyKey !== void 0 && (typeof idempotencyKey !== "string" || !IDEMPOTENCY_KEY_PATTERN.test(idempotencyKey))) throw invalidRequest("startRun", "header.Idempotency-Key", "idempotencyKey must be 1–64 printable ASCII characters");
1232
+ const body = serialize("startRun", input === void 0 ? {} : { input }, "body.input");
1233
+ if (definition) await checkInput(definition, body);
1234
+ return toRunSummary(await send({
1235
+ call: "startRun",
1236
+ method: "POST",
1237
+ path: `/api/v1/app-workflows/${encodeURIComponent(workflowId)}/runs`,
1238
+ body,
1239
+ headers: idempotencyKey === void 0 ? void 0 : { "Idempotency-Key": idempotencyKey },
1240
+ signal: options.signal
1241
+ }));
1242
+ }
1243
+ /**
1244
+ * Reads one of the app's runs, with its input and output. Call it from server code only.
1245
+ *
1246
+ * The app's key reads every run of its project: runs it started, scheduled runs and editor test runs.
1247
+ */
1248
+ async function getRun(runId, options = {}) {
1249
+ options.signal?.throwIfAborted();
1250
+ assertServerRuntime();
1251
+ checkRunId("getRun", runId);
1252
+ return toRun(await send({
1253
+ call: "getRun",
1254
+ method: "GET",
1255
+ path: `/api/v1/app-workflow-runs/${encodeURIComponent(runId)}`,
1256
+ signal: options.signal
1257
+ }));
1258
+ }
1259
+ /**
1260
+ * Resumes the run's `ctx.waitForEvent` call that waits on the event's name. Call it from server code only.
1261
+ *
1262
+ * Events are not queued: an open run that doesn't wait on the name yet throws `RunNotWaitingError`, which can be
1263
+ * retried, and a finished run throws `RunClosedError`. A retry with the same `eventId` is always safe.
1264
+ */
1265
+ async function deliverEvent(runId, event, options = {}) {
1266
+ options.signal?.throwIfAborted();
1267
+ assertServerRuntime();
1268
+ checkRunId("deliverEvent", runId);
1269
+ if (event === null || typeof event !== "object") throw invalidRequest("deliverEvent", "body", "pass the event as { eventId, name, payload? }");
1270
+ const body = serialize("deliverEvent", {
1271
+ event_id: event.eventId,
1272
+ name: event.name,
1273
+ ...event.payload === void 0 ? {} : { payload: event.payload }
1274
+ }, "body.payload");
1275
+ return { recorded: (await send({
1276
+ call: "deliverEvent",
1277
+ method: "POST",
1278
+ path: `/api/v1/app-workflow-runs/${encodeURIComponent(runId)}/events`,
1279
+ body,
1280
+ signal: options.signal
1281
+ })).recorded === true };
1282
+ }
1283
+ //#endregion
1284
+ export { EventAlreadyDeliveredError, IdempotencyKeyReusedError, RunClosedError, RunInputInvalidError, RunNotFoundError, RunNotWaitingError, WorkflowNotPublishedError, WorkflowsApiError, WorkflowsAuthenticationError, WorkflowsConfigurationError, WorkflowsDevelopmentKeyError, WorkflowsDisabledError, WorkflowsKeyLookupError, WorkflowsNetworkError, WorkflowsPayloadTooLargeError, WorkflowsRateLimitedError, WorkflowsRequestInvalidError, WorkflowsUnavailableError, createMiddleware, createStepsHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, deliverEvent, every, generateManifests, getRun, hourly, registerWorkflows, startRun, toServerSentEventsResponse, weekly };