@lovable.dev/workflows-sdk 0.0.0-dev.56 → 0.0.0-dev.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -276,6 +276,87 @@ Lovable supports only `skip` today. If any schedule of a workflow declares
276
276
  `allow` or `buffer-one`, publishing registers none of that workflow's
277
277
  schedules.
278
278
 
279
+ ## Start runs from app code
280
+
281
+ `startRun`, `getRun` and `deliverEvent` start, read and resume runs of the
282
+ app's published workflows. They require SDK `0.0.0-dev.57` or newer. Call them
283
+ from server code only, such as a server route or a `*.server.ts` helper: they
284
+ send the app's `LOVABLE_API_KEY`, and they throw in a browser. The
285
+ `LOVABLE_WORKFLOWS_KEY` that authenticates the `/steps` route is a different
286
+ key and plays no part here.
287
+
288
+ ```ts
289
+ const run = await startRun(orderShipped, { orderId: shipment.orderId }, { idempotencyKey: `shipment:${shipment.id}` });
290
+ const latest = await getRun(run.runId);
291
+ await deliverEvent(run.runId, { eventId: `approval:${approval.id}`, name: "approved", payload: { by: approval.by } });
292
+ ```
293
+
294
+ | Call | Returns |
295
+ | --- | --- |
296
+ | `startRun(workflow, input?, options?)` | `{ runId, workflowId, status, trigger, createdAt }`; `trigger` is `api` |
297
+ | `getRun(runId, options?)` | The summary plus `updatedAt`, `closedAt`, `error`, `input` and `output` |
298
+ | `deliverEvent(runId, { eventId, name, payload? }, options?)` | `{ recorded }`, false when the `eventId` was already recorded |
299
+
300
+ A start runs the published version of the workflow. Preview and sandbox starts
301
+ run the published build too, and a start before the first publish throws
302
+ `WorkflowNotPublishedError`. Pass the workflow's definition to type the input
303
+ and check it against the workflow's input schema before anything is sent. An
304
+ input that fails the check throws `RunInputInvalidError`, creates no run and
305
+ leaves the idempotency key unused. In preview, between a schema change and the
306
+ next publish, the check uses the changed schema while the run uses the
307
+ published one. A workflow id string also works, without the check.
308
+
309
+ Derive `idempotencyKey` (1–64 printable ASCII characters) from the event that
310
+ starts the run. A repeat with the same key and input returns the run the key
311
+ started, in its current state. The same key with another input throws
312
+ `IdempotencyKeyReusedError`; an input object rebuilt with another key order
313
+ counts as another input. The SDK never retries a call and never makes up a key.
314
+
315
+ The input is any JSON value, at most 2 MiB serialized. Pass larger data by
316
+ reference: store it and pass its id. Integers above 2^53 lose precision, so
317
+ pass them as strings. A project can start 100 runs, read 1,000 runs and deliver
318
+ 100 events a second.
319
+
320
+ `getRun` reads every run of the app's project, scheduled and editor test runs
321
+ included. `completed`, `failed`, `cancelled` and `skipped` are final; treat
322
+ `unknown` and any status added later as open. `output` is set once the run is
323
+ `completed`.
324
+
325
+ `deliverEvent` resumes the `ctx.waitForEvent(name)` call that waits on `name`.
326
+ Events are not queued: an open run that doesn't wait on the name yet throws
327
+ `RunNotWaitingError`, and a finished run throws `RunClosedError`. A retry with
328
+ the same `eventId` is always safe. An omitted `payload` resolves the wait with
329
+ no value, and `null` resolves it with `null`.
330
+
331
+ Every call takes an optional `signal`. Aborting stops the wait for the answer;
332
+ it does not undo a start or a delivery the gateway already received, so retry
333
+ with the same idempotency key or `eventId`.
334
+
335
+ Every error extends `WorkflowsApiError`, with `type`, `status`, `requestId`,
336
+ `retryable` and `retryAfterMs`. Its `toJSON()` never contains the API key.
337
+
338
+ | Error | Cause | Retryable |
339
+ | --- | --- | --- |
340
+ | `WorkflowNotPublishedError` | The workflow has no published version: ask the user to publish | No |
341
+ | `IdempotencyKeyReusedError` | The key already started a run from another request | No |
342
+ | `RunInputInvalidError` | The input fails the workflow's input schema | No |
343
+ | `RunNotWaitingError` | No step of the open run waits on the event name now | Yes, while the run is open |
344
+ | `RunClosedError` | The run has finished | No |
345
+ | `RunNotFoundError` | No such run in this project | No |
346
+ | `EventAlreadyDeliveredError` | The `eventId` already answered a wait with another name | No |
347
+ | `WorkflowsPayloadTooLargeError` | The input or payload is over its limit | No |
348
+ | `WorkflowsRateLimitedError`, `WorkflowsUnavailableError` | Over the project's limit, or the service is busy | Yes, after `retryAfterMs` |
349
+ | `WorkflowsNetworkError` | No answer arrived; the start may have happened | Yes, with the same key |
350
+ | `WorkflowsAuthenticationError` | The key is invalid or no longer registered: rotate `LOVABLE_API_KEY`, then republish or restart the backend | No |
351
+ | `WorkflowsKeyLookupError` | The gateway could not check the key | Yes |
352
+ | `WorkflowsDevelopmentKeyError` | A development key reached production | No |
353
+ | `WorkflowsDisabledError` | App workflows are off for the project | No |
354
+ | `WorkflowsRequestInvalidError` | An argument or the request is invalid | No |
355
+ | `WorkflowsConfigurationError` | A browser, a missing `LOVABLE_API_KEY` or a bad `LOVABLE_WORKFLOWS_API_URL` | No |
356
+
357
+ `LOVABLE_WORKFLOWS_API_URL` overrides the gateway URL, which defaults to
358
+ `https://connector-gateway.lovable.dev`. Lovable sets it for local development.
359
+
279
360
  ## Build integration
280
361
 
281
362
  Add `workflowsPlugin()` before the TanStack Start plugin. Its `entry` defaults
@@ -293,5 +374,5 @@ plugins: [
293
374
 
294
375
  | Import | Provides |
295
376
  | --- | --- |
296
- | `@lovable.dev/workflows-sdk` | Workflow authoring, registration, cadences, and schedules |
377
+ | `@lovable.dev/workflows-sdk` | Workflow authoring, registration, cadences, schedules, and `startRun`, `getRun` and `deliverEvent` |
297
378
  | `@lovable.dev/workflows-sdk/vite` | Lovable build integration |
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DZKqS7JU.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-qDFxy3v5.js";
2
2
  //#region src/manifests/branch-metadata.ts
3
3
  const optionsArgument = {
4
4
  step: 2,
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DZKqS7JU.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-qDFxy3v5.js";
2
2
  //#region src/manifests/context-escapes.ts
3
3
  const durableMethods = /* @__PURE__ */ new Set([
4
4
  "step",
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DZKqS7JU.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-qDFxy3v5.js";
2
2
  //#region src/manifests/duplicate-ids.ts
3
3
  /** Where an explicit `{ id }` would sit for each operation. */
4
4
  const optionsArgument = {
@@ -1,5 +1,6 @@
1
1
  import { createMiddleware, createWorkflow } from "@tanstack/workflow-core";
2
2
  //#region src/core/identifier.ts
3
+ const WORKFLOW_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,127}$/;
3
4
  function assertIdentifier(kind, id) {
4
5
  if (typeof id !== "string" || id.trim() === "" || id !== id.trim()) throw new Error(`@lovable.dev/workflows-sdk: ${kind} IDs must be non-empty and have no surrounding whitespace`);
5
6
  }
@@ -171,7 +172,7 @@ function registerWorkflows(definition) {
171
172
  for (const workflow of workflows) {
172
173
  if (workflow.__kind !== "workflow" || typeof workflow.handler !== "function") throw new Error("@lovable.dev/workflows-sdk: expected a completed createWorkflow().handler() definition");
173
174
  assertIdentifier("workflow", workflow.id);
174
- if (!/^[a-z0-9][a-z0-9_-]{0,127}$/.test(workflow.id)) throw new Error("@lovable.dev/workflows-sdk: workflow names must be 1–128 lowercase letters, digits, hyphens or underscores, starting with a letter or digit");
175
+ if (!WORKFLOW_ID_PATTERN.test(workflow.id)) throw new Error("@lovable.dev/workflows-sdk: workflow names must be 1–128 lowercase letters, digits, hyphens or underscores, starting with a letter or digit");
175
176
  if (ids.has(workflow.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate workflow ID "${workflow.id}"`);
176
177
  ids.add(workflow.id);
177
178
  workflowVersions(workflow);
@@ -6643,7 +6644,7 @@ function listValueFromJson(listValue, json) {
6643
6644
  }
6644
6645
  //#endregion
6645
6646
  //#region package.json
6646
- var version = "0.0.0-dev.56";
6647
+ var version = "0.0.0-dev.57";
6647
6648
  //#endregion
6648
6649
  //#region src/proto/lovable/appworkflows/v1/workflow_manifest_pb.ts
6649
6650
  /**
@@ -6865,15 +6866,15 @@ function serializeSchema(schema, direction, label) {
6865
6866
  }
6866
6867
  }
6867
6868
  async function generateManifests(definition, options = {}) {
6868
- const { extractWorkflowGraph } = await import("./graph-DZKqS7JU.js");
6869
- const { findBranchMetadataIssues } = await import("./branch-metadata-DdlPicB2.js");
6870
- const { findWorkflowContextEscapes } = await import("./context-escapes-BkqZwZQD.js");
6871
- const { findDuplicateOperationIds } = await import("./duplicate-ids-BqvEnwrg.js");
6869
+ const { extractWorkflowGraph } = await import("./graph-qDFxy3v5.js");
6870
+ const { findBranchMetadataIssues } = await import("./branch-metadata-11JARM_f.js");
6871
+ const { findWorkflowContextEscapes } = await import("./context-escapes-CCFe2Xly.js");
6872
+ const { findDuplicateOperationIds } = await import("./duplicate-ids-C-UQFcg0.js");
6872
6873
  const { DURABLE_ID_REQUIRED } = await import("./durable-ids-Cx341nJQ.js").then((n) => n.n);
6873
- const { findNestedDurableOperations } = await import("./nested-operations-DzqRySTw.js");
6874
- const { findOperationDescriptionIssues } = await import("./operation-descriptions-CysWwDdv.js");
6875
- const { findStepMetadataIssues } = await import("./step-metadata-OA665DZL.js");
6876
- const { findWaitDeadlineIssues } = await import("./wait-deadlines-Bq7CK982.js");
6874
+ const { findNestedDurableOperations } = await import("./nested-operations-CrF-T-F3.js");
6875
+ const { findOperationDescriptionIssues } = await import("./operation-descriptions-YWlxdFR4.js");
6876
+ const { findStepMetadataIssues } = await import("./step-metadata-C2Gq6_oU.js");
6877
+ const { findWaitDeadlineIssues } = await import("./wait-deadlines-DjYbGO09.js");
6877
6878
  const { WAIT_DEADLINE_REQUIRED } = await import("./wait-deadlines-DpK-Fgnd.js");
6878
6879
  const collection = registerWorkflows(definition);
6879
6880
  const manifests = [];
@@ -6981,4 +6982,4 @@ async function generateManifests(definition, options = {}) {
6981
6982
  });
6982
6983
  }
6983
6984
  //#endregion
6984
- export { daily as A, WorkflowManifestWaitForEventNodeV1Schema as C, registerWorkflows as D, createWorkflow$1 as E, hourly as M, weekly as N, workflowVersions as O, WorkflowManifestUuidNodeV1Schema as S, createMiddleware as T, WorkflowManifestSleepNodeV1Schema as _, WorkflowManifestConnectorNodeV1Schema as a, WorkflowManifestStepNodeV1Schema as b, WorkflowManifestGraphV1Schema as c, WorkflowManifestNowNodeV1Schema as d, WorkflowManifestOrderEdgeV1Schema as f, WorkflowManifestRepeatedStepV1Schema as g, WorkflowManifestRepeatedLlmV1Schema as h, WorkflowManifestBranchNodeV1Schema as i, every as j, defineSchedule as k, WorkflowManifestLlmNodeV1Schema as l, WorkflowManifestRepeatedConnectorV1Schema as m, WorkflowManifestApproveNodeV1Schema as n, WorkflowManifestGraphEdgeV1Schema as o, WorkflowManifestParallelNodeV1Schema as p, WorkflowManifestBranchEdgeV1Schema as r, WorkflowManifestGraphNodeV1Schema as s, generateManifests as t, WorkflowManifestLoopNodeV1Schema as u, WorkflowManifestSleepUntilNodeV1Schema as v, create as w, WorkflowManifestUnknownNodeV1Schema as x, WorkflowManifestStepExecutionPolicyV1Schema as y };
6985
+ export { daily as A, WorkflowManifestWaitForEventNodeV1Schema as C, registerWorkflows as D, createWorkflow$1 as E, hourly as M, weekly as N, workflowVersions as O, WORKFLOW_ID_PATTERN as P, WorkflowManifestUuidNodeV1Schema as S, createMiddleware as T, WorkflowManifestSleepNodeV1Schema as _, WorkflowManifestConnectorNodeV1Schema as a, WorkflowManifestStepNodeV1Schema as b, WorkflowManifestGraphV1Schema as c, WorkflowManifestNowNodeV1Schema as d, WorkflowManifestOrderEdgeV1Schema as f, WorkflowManifestRepeatedStepV1Schema as g, WorkflowManifestRepeatedLlmV1Schema as h, WorkflowManifestBranchNodeV1Schema as i, every as j, defineSchedule as k, WorkflowManifestLlmNodeV1Schema as l, WorkflowManifestRepeatedConnectorV1Schema as m, WorkflowManifestApproveNodeV1Schema as n, WorkflowManifestGraphEdgeV1Schema as o, WorkflowManifestParallelNodeV1Schema as p, WorkflowManifestBranchEdgeV1Schema as r, WorkflowManifestGraphNodeV1Schema as s, generateManifests as t, WorkflowManifestLoopNodeV1Schema as u, WorkflowManifestSleepUntilNodeV1Schema as v, create as w, WorkflowManifestUnknownNodeV1Schema as x, WorkflowManifestStepExecutionPolicyV1Schema as y };
@@ -1,4 +1,4 @@
1
- import { C as WorkflowManifestWaitForEventNodeV1Schema, S as WorkflowManifestUuidNodeV1Schema, _ as WorkflowManifestSleepNodeV1Schema, a as WorkflowManifestConnectorNodeV1Schema, b as WorkflowManifestStepNodeV1Schema, c as WorkflowManifestGraphV1Schema, d as WorkflowManifestNowNodeV1Schema, f as WorkflowManifestOrderEdgeV1Schema, g as WorkflowManifestRepeatedStepV1Schema, h as WorkflowManifestRepeatedLlmV1Schema, i as WorkflowManifestBranchNodeV1Schema, l as WorkflowManifestLlmNodeV1Schema, m as WorkflowManifestRepeatedConnectorV1Schema, n as WorkflowManifestApproveNodeV1Schema, o as WorkflowManifestGraphEdgeV1Schema, p as WorkflowManifestParallelNodeV1Schema, r as WorkflowManifestBranchEdgeV1Schema, s as WorkflowManifestGraphNodeV1Schema, u as WorkflowManifestLoopNodeV1Schema, v as WorkflowManifestSleepUntilNodeV1Schema, w as create, x as WorkflowManifestUnknownNodeV1Schema, y as WorkflowManifestStepExecutionPolicyV1Schema } from "./generate-W-NgD43q.js";
1
+ import { C as WorkflowManifestWaitForEventNodeV1Schema, S as WorkflowManifestUuidNodeV1Schema, _ as WorkflowManifestSleepNodeV1Schema, a as WorkflowManifestConnectorNodeV1Schema, b as WorkflowManifestStepNodeV1Schema, c as WorkflowManifestGraphV1Schema, d as WorkflowManifestNowNodeV1Schema, f as WorkflowManifestOrderEdgeV1Schema, g as WorkflowManifestRepeatedStepV1Schema, h as WorkflowManifestRepeatedLlmV1Schema, i as WorkflowManifestBranchNodeV1Schema, l as WorkflowManifestLlmNodeV1Schema, m as WorkflowManifestRepeatedConnectorV1Schema, n as WorkflowManifestApproveNodeV1Schema, o as WorkflowManifestGraphEdgeV1Schema, p as WorkflowManifestParallelNodeV1Schema, r as WorkflowManifestBranchEdgeV1Schema, s as WorkflowManifestGraphNodeV1Schema, u as WorkflowManifestLoopNodeV1Schema, v as WorkflowManifestSleepUntilNodeV1Schema, w as create, x as WorkflowManifestUnknownNodeV1Schema, y as WorkflowManifestStepExecutionPolicyV1Schema } from "./generate-CzKPbFyR.js";
2
2
  import { n as assertLlmOptions, t as assertLlmModel } from "./llm-validation-DdDO6csU.js";
3
3
  //#region src/manifests/handler-source.ts
4
4
  const nativeFunctionSource = /\{\s*\[native code\]\s*\}\s*$/;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AccumulateExtensions, AnyMiddleware, AnyWorkflowDefinition, AnyWorkflowDefinition as AnyWorkflowDefinition$1, ApprovalResult, ApproveOptions as ApproveOptions$1, CreateWorkflowConfig, Ctx as Ctx$1, InferSchema, RunStore, SchemaInput, StepContext, StepContext as StepContext$1, StepOptions, StepOptions as StepOptions$1, WaitForEventOptions as WaitForEventOptions$1, WorkflowBuilder, WorkflowDefinition, WorkflowDefinition as WorkflowDefinition$1, WorkflowEvent, WorkflowInput, WorkflowInput as WorkflowInput$1, WorkflowMetadata, WorkflowOutput, WorkflowState, createMiddleware } from "@tanstack/workflow-core";
2
+ import { StandardSchemaV1 } from "@standard-schema/spec";
2
3
  //#region src/core/step-metadata.d.ts
3
4
  interface WorkflowStepGroup {
4
5
  id: string;
@@ -1042,4 +1043,299 @@ declare function createStepsHandler(collection: WorkflowCollection, options?: St
1042
1043
  */
1043
1044
  declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
1044
1045
  //#endregion
1045
- export { type AnyWorkflowDefinition, type ApproveOptions, type Cadence, type ConnectorStep, type ConnectorStepOptions, type Ctx, type LlmRequest, type LlmStep, type LlmStepOptions, type MemoEntry, type MinuteInterval, type NextStep, type OverlapPolicy, type ReplayOutcome, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type StepContext, type StepIntent, type StepKind, type StepOptions, type StepReference, type StepResult, type StepsDisposition, type StepsHandler, type StepsHandlerOptions, type StepsRequest, type StepsResponse, type TanStackWorkflowHandler, type TanStackWorkflowHandlerOptions, type TriggerDefinition, type WaitForEventOptions, type Weekday, type WorkflowBranchMetadata, type WorkflowCollection, type WorkflowDefinition, type WorkflowInput, type WorkflowManifest, type WorkflowOperationMetadata, type WorkflowOutput, type WorkflowState, type WorkflowStepGroup, type WorkflowStepMetadata, type WorkflowsDefinition, createMiddleware, createStepsHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, every, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
1046
+ //#region src/client/generated/gateway.d.ts
1047
+ interface components {
1048
+ schemas: {
1049
+ DeliverEventRequest: {
1050
+ /** @description Makes the delivery safe to retry. A delivery that repeats the event_id is accepted and records nothing new. The same event_id with another name answers 409. */
1051
+ event_id: string;
1052
+ /** @description The event name that the run's ctx.waitForEvent call waits on. */
1053
+ name: string;
1054
+ /** @description The value that the ctx.waitForEvent call resolves to, any JSON value. Omit it for an event that carries no data. */
1055
+ payload?: unknown;
1056
+ };
1057
+ DeliverEventResponse: {
1058
+ /** @description Is false when an earlier delivery with the same event_id already recorded the event. */
1059
+ recorded: boolean;
1060
+ };
1061
+ Error: {
1062
+ /** @description Explanation of this occurrence, or null. */
1063
+ detail: string | null;
1064
+ /** @description The invalid request values, or null. */
1065
+ errors: components["schemas"]["ErrorDetail"][] | null;
1066
+ /** @description Extra data for the error type, or null. */
1067
+ props: {
1068
+ [key: string]: unknown;
1069
+ } | null;
1070
+ /** @description Identifier of this request. Quote it when you report a failure. */
1071
+ request_id: string;
1072
+ /**
1073
+ * Format: int64
1074
+ * @description HTTP status code.
1075
+ */
1076
+ status: number;
1077
+ /** @description Short, human-readable summary. */
1078
+ title: string;
1079
+ /** @description Machine-readable error type in snake_case. */
1080
+ type: string;
1081
+ };
1082
+ ErrorDetail: {
1083
+ /** @description Where the value is, such as body.input, or null. */
1084
+ location: string | null;
1085
+ /** @description What is wrong with the value. */
1086
+ message: string;
1087
+ };
1088
+ Run: {
1089
+ /**
1090
+ * Format: date-time
1091
+ * @description When the run reached a final status, or null while it is open.
1092
+ */
1093
+ closed_at: string | null;
1094
+ /**
1095
+ * Format: date-time
1096
+ * @description When the run was created.
1097
+ */
1098
+ created_at: string;
1099
+ /** @description Why the run failed or was cancelled, or null. */
1100
+ error: string | null;
1101
+ /** @description The run's input, any JSON value, or null when the run has no input. */
1102
+ input: unknown;
1103
+ /** @description The value that the workflow returned, any JSON value, or null until the run is completed. */
1104
+ output: unknown;
1105
+ /** @description Identifier of the run. */
1106
+ run_id: string;
1107
+ /**
1108
+ * @description The run's status. completed, failed, cancelled and skipped are final.
1109
+ * @enum {string}
1110
+ */
1111
+ status: "queued" | "running" | "waiting" | "completed" | "failed" | "cancelled" | "skipped" | "unknown";
1112
+ /**
1113
+ * @description What started the run. A run that the app's code starts is api.
1114
+ * @enum {string}
1115
+ */
1116
+ trigger: "manual" | "schedule" | "event" | "webhook" | "api" | "unknown";
1117
+ /**
1118
+ * Format: date-time
1119
+ * @description When the run last changed.
1120
+ */
1121
+ updated_at: string;
1122
+ /** @description The workflow that the run executes. */
1123
+ workflow_id: string;
1124
+ };
1125
+ RunSummary: {
1126
+ /**
1127
+ * Format: date-time
1128
+ * @description When the run was created.
1129
+ */
1130
+ created_at: string;
1131
+ /** @description Identifier of the run. */
1132
+ run_id: string;
1133
+ /**
1134
+ * @description The run's status when the response was written.
1135
+ * @enum {string}
1136
+ */
1137
+ status: "queued" | "running" | "waiting" | "completed" | "failed" | "cancelled" | "skipped" | "unknown";
1138
+ /**
1139
+ * @description What started the run. A run that the app's code starts is api.
1140
+ * @enum {string}
1141
+ */
1142
+ trigger: "manual" | "schedule" | "event" | "webhook" | "api" | "unknown";
1143
+ /** @description The workflow that the run executes. */
1144
+ workflow_id: string;
1145
+ };
1146
+ StartRunRequest: {
1147
+ /** @description The run's input, any JSON value. Omit it for a workflow that takes no input. */
1148
+ input?: unknown;
1149
+ };
1150
+ };
1151
+ responses: never;
1152
+ parameters: never;
1153
+ requestBodies: never;
1154
+ headers: never;
1155
+ pathItems: never;
1156
+ }
1157
+ //#endregion
1158
+ //#region src/client/runs.d.ts
1159
+ type WireRun = components["schemas"]["Run"];
1160
+ /** `completed`, `failed`, `cancelled` and `skipped` are final. Treat `unknown`, and any status added later, as open. */
1161
+ type RunStatus = WireRun["status"];
1162
+ type RunTrigger = WireRun["trigger"];
1163
+ interface RunSummary {
1164
+ runId: string;
1165
+ workflowId: string;
1166
+ /** The status when the gateway answered. A start that repeats an Idempotency-Key returns the run in its current state. */
1167
+ status: RunStatus;
1168
+ /** `api` for a run that app code started. */
1169
+ trigger: RunTrigger;
1170
+ createdAt: string;
1171
+ }
1172
+ interface Run extends RunSummary {
1173
+ updatedAt: string;
1174
+ /** Null while the run is open. */
1175
+ closedAt: string | null;
1176
+ /** Why the run failed or was cancelled, or null. */
1177
+ error: string | null;
1178
+ input: unknown;
1179
+ /** Set only once the run is `completed`. */
1180
+ output: unknown;
1181
+ }
1182
+ interface StartRunOptions {
1183
+ /**
1184
+ * Makes the start safe to retry: 1–64 printable ASCII characters, derived from the event that starts the run.
1185
+ * A repeat with the same key and input returns the run the key started.
1186
+ */
1187
+ idempotencyKey?: string;
1188
+ signal?: AbortSignal;
1189
+ }
1190
+ interface GetRunOptions {
1191
+ signal?: AbortSignal;
1192
+ }
1193
+ interface DeliverEventInput {
1194
+ /** Makes the delivery safe to retry. */
1195
+ eventId: string;
1196
+ /** The name that the run's `ctx.waitForEvent` call waits on. */
1197
+ name: string;
1198
+ /** What `ctx.waitForEvent` resolves to. Omit it for an event that carries no data. */
1199
+ payload?: unknown;
1200
+ }
1201
+ interface DeliverEventOptions {
1202
+ signal?: AbortSignal;
1203
+ }
1204
+ interface DeliverEventResult {
1205
+ /** False when an earlier delivery with the same `eventId` already recorded the event. */
1206
+ recorded: boolean;
1207
+ }
1208
+ type StartRunArgs<W extends AnyWorkflowDefinition$1> = undefined extends WorkflowInput$1<W> ? [input?: WorkflowInput$1<W>, options?: StartRunOptions] : [input: WorkflowInput$1<W>, options?: StartRunOptions];
1209
+ /**
1210
+ * Starts a run of the published version of one of the app's workflows. Call it from server code only.
1211
+ *
1212
+ * Pass the workflow's definition to type the input and check it against the workflow's input schema before anything
1213
+ * is sent, or pass the workflow id. The SDK never retries and never makes up an Idempotency-Key: derive the key from
1214
+ * the event, and retry with the same key and input.
1215
+ */
1216
+ declare function startRun<W extends AnyWorkflowDefinition$1>(workflow: W, ...args: StartRunArgs<W>): Promise<RunSummary>;
1217
+ declare function startRun(workflowId: string, input?: unknown, options?: StartRunOptions): Promise<RunSummary>;
1218
+ /**
1219
+ * Reads one of the app's runs, with its input and output. Call it from server code only.
1220
+ *
1221
+ * The app's key reads every run of its project: runs it started, scheduled runs and editor test runs.
1222
+ */
1223
+ declare function getRun(runId: string, options?: GetRunOptions): Promise<Run>;
1224
+ /**
1225
+ * Resumes the run's `ctx.waitForEvent` call that waits on the event's name. Call it from server code only.
1226
+ *
1227
+ * Events are not queued: an open run that doesn't wait on the name yet throws `RunNotWaitingError`, which can be
1228
+ * retried, and a finished run throws `RunClosedError`. A retry with the same `eventId` is always safe.
1229
+ */
1230
+ declare function deliverEvent(runId: string, event: DeliverEventInput, options?: DeliverEventOptions): Promise<DeliverEventResult>;
1231
+ //#endregion
1232
+ //#region src/client/errors.d.ts
1233
+ /** One invalid request value, as the gateway reports it in `errors`. */
1234
+ interface WorkflowsErrorDetail {
1235
+ location: string | null;
1236
+ message: string;
1237
+ }
1238
+ interface WorkflowsApiErrorJSON {
1239
+ name: string;
1240
+ message: string;
1241
+ type: string;
1242
+ status?: number;
1243
+ requestId?: string;
1244
+ title?: string;
1245
+ detail?: string;
1246
+ errors?: WorkflowsErrorDetail[];
1247
+ retryable: boolean;
1248
+ retryAfterMs?: number;
1249
+ }
1250
+ interface WorkflowsApiErrorFields {
1251
+ type: string;
1252
+ retryable: boolean;
1253
+ status?: number;
1254
+ requestId?: string;
1255
+ title?: string;
1256
+ detail?: string;
1257
+ errors?: WorkflowsErrorDetail[];
1258
+ retryAfterMs?: number;
1259
+ cause?: unknown;
1260
+ }
1261
+ /**
1262
+ * A failed `startRun`, `getRun` or `deliverEvent` call.
1263
+ *
1264
+ * `status` is the gateway's HTTP status, and is undefined when the SDK refused the call before sending it or got no
1265
+ * response. `retryable` is true when repeating the same call later can succeed without a change to the code, the
1266
+ * configuration or the app; the SDK itself never retries.
1267
+ */
1268
+ declare class WorkflowsApiError extends Error {
1269
+ readonly name: string;
1270
+ readonly type: string;
1271
+ readonly status?: number;
1272
+ readonly requestId?: string;
1273
+ readonly title?: string;
1274
+ readonly detail?: string;
1275
+ readonly errors?: WorkflowsErrorDetail[];
1276
+ readonly retryable: boolean;
1277
+ readonly retryAfterMs?: number;
1278
+ constructor(message: string, fields: WorkflowsApiErrorFields);
1279
+ toJSON(): WorkflowsApiErrorJSON;
1280
+ }
1281
+ type ConfigurationErrorReason = "server_only" | "missing_api_key" | "invalid_url";
1282
+ declare class WorkflowsConfigurationError extends WorkflowsApiError {
1283
+ readonly name = "WorkflowsConfigurationError";
1284
+ readonly reason: ConfigurationErrorReason;
1285
+ constructor(reason: ConfigurationErrorReason, message: string);
1286
+ }
1287
+ declare class WorkflowsRequestInvalidError extends WorkflowsApiError {
1288
+ readonly name: string;
1289
+ }
1290
+ /** The input fails the workflow's input schema. The SDK sent no request, so the Idempotency-Key is still unused. */
1291
+ declare class RunInputInvalidError extends WorkflowsRequestInvalidError {
1292
+ readonly name = "RunInputInvalidError";
1293
+ readonly issues: readonly StandardSchemaV1.Issue[];
1294
+ constructor(message: string, fields: WorkflowsApiErrorFields & {
1295
+ issues: readonly StandardSchemaV1.Issue[];
1296
+ });
1297
+ }
1298
+ declare class WorkflowsNetworkError extends WorkflowsApiError {
1299
+ readonly name = "WorkflowsNetworkError";
1300
+ }
1301
+ declare class WorkflowsAuthenticationError extends WorkflowsApiError {
1302
+ readonly name = "WorkflowsAuthenticationError";
1303
+ }
1304
+ declare class WorkflowsKeyLookupError extends WorkflowsApiError {
1305
+ readonly name = "WorkflowsKeyLookupError";
1306
+ }
1307
+ declare class WorkflowsDevelopmentKeyError extends WorkflowsApiError {
1308
+ readonly name = "WorkflowsDevelopmentKeyError";
1309
+ }
1310
+ declare class WorkflowsDisabledError extends WorkflowsApiError {
1311
+ readonly name = "WorkflowsDisabledError";
1312
+ }
1313
+ declare class RunNotFoundError extends WorkflowsApiError {
1314
+ readonly name = "RunNotFoundError";
1315
+ }
1316
+ declare class WorkflowNotPublishedError extends WorkflowsApiError {
1317
+ readonly name = "WorkflowNotPublishedError";
1318
+ }
1319
+ declare class IdempotencyKeyReusedError extends WorkflowsApiError {
1320
+ readonly name = "IdempotencyKeyReusedError";
1321
+ }
1322
+ declare class RunClosedError extends WorkflowsApiError {
1323
+ readonly name = "RunClosedError";
1324
+ }
1325
+ declare class RunNotWaitingError extends WorkflowsApiError {
1326
+ readonly name = "RunNotWaitingError";
1327
+ }
1328
+ declare class EventAlreadyDeliveredError extends WorkflowsApiError {
1329
+ readonly name = "EventAlreadyDeliveredError";
1330
+ }
1331
+ declare class WorkflowsPayloadTooLargeError extends WorkflowsApiError {
1332
+ readonly name = "WorkflowsPayloadTooLargeError";
1333
+ }
1334
+ declare class WorkflowsRateLimitedError extends WorkflowsApiError {
1335
+ readonly name = "WorkflowsRateLimitedError";
1336
+ }
1337
+ declare class WorkflowsUnavailableError extends WorkflowsApiError {
1338
+ readonly name = "WorkflowsUnavailableError";
1339
+ }
1340
+ //#endregion
1341
+ export { type AnyWorkflowDefinition, type ApproveOptions, type Cadence, type ConfigurationErrorReason, type ConnectorStep, type ConnectorStepOptions, type Ctx, type DeliverEventInput, type DeliverEventOptions, type DeliverEventResult, EventAlreadyDeliveredError, type GetRunOptions, IdempotencyKeyReusedError, type LlmRequest, type LlmStep, type LlmStepOptions, type MemoEntry, type MinuteInterval, type NextStep, type OverlapPolicy, type ReplayOutcome, type ResolvedSchedule, type ResolvedTrigger, type Run, RunClosedError, RunInputInvalidError, RunNotFoundError, RunNotWaitingError, type RunStatus, type RunSummary, type RunTrigger, type ScheduleDefinition, type StartRunOptions, type StepContext, type StepIntent, type StepKind, type StepOptions, type StepReference, type StepResult, type StepsDisposition, type StepsHandler, type StepsHandlerOptions, type StepsRequest, type StepsResponse, type TanStackWorkflowHandler, type TanStackWorkflowHandlerOptions, type TriggerDefinition, type WaitForEventOptions, type Weekday, type WorkflowBranchMetadata, type WorkflowCollection, type WorkflowDefinition, type WorkflowInput, type WorkflowManifest, WorkflowNotPublishedError, type WorkflowOperationMetadata, type WorkflowOutput, type WorkflowState, type WorkflowStepGroup, type WorkflowStepMetadata, WorkflowsApiError, type WorkflowsApiErrorJSON, WorkflowsAuthenticationError, WorkflowsConfigurationError, type WorkflowsDefinition, WorkflowsDevelopmentKeyError, WorkflowsDisabledError, type WorkflowsErrorDetail, WorkflowsKeyLookupError, WorkflowsNetworkError, WorkflowsPayloadTooLargeError, WorkflowsRateLimitedError, WorkflowsRequestInvalidError, WorkflowsUnavailableError, createMiddleware, createStepsHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, deliverEvent, every, generateManifests, getRun, hourly, registerWorkflows, startRun, toServerSentEventsResponse, weekly };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as DURABLE_ID_REQUIRED } from "./durable-ids-Cx341nJQ.js";
2
- import { A as daily, D as registerWorkflows, E as createWorkflow, M as hourly, N as weekly, O as workflowVersions, T as createMiddleware, j as every, k as defineSchedule, t as generateManifests } from "./generate-W-NgD43q.js";
2
+ import { A as daily, D as registerWorkflows, E as createWorkflow, M as hourly, N as weekly, O as workflowVersions, P as WORKFLOW_ID_PATTERN, T as createMiddleware, j as every, k as defineSchedule, t as generateManifests } from "./generate-CzKPbFyR.js";
3
3
  import { n as assertLlmOptions, r as assertLlmRequest } from "./llm-validation-DdDO6csU.js";
4
4
  import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
5
5
  import { generateChatCompletion, generateMessage } from "@lovable.dev/ai-gateway";
@@ -524,23 +524,31 @@ async function replay(options) {
524
524
  }
525
525
  function noop() {}
526
526
  //#endregion
527
- //#region src/stacks/tanstack/project-auth.ts
528
- const PROJECT_SECRET_ENV_VAR = "LOVABLE_WORKFLOWS_KEY";
527
+ //#region src/core/runtime-env.ts
529
528
  let cloudflareEnvPromise;
530
- function readProcessSecret() {
531
- const value = (globalThis.process?.env)?.[PROJECT_SECRET_ENV_VAR];
532
- return typeof value === "string" && value ? value : void 0;
533
- }
534
- async function readCloudflareSecret() {
529
+ function readCloudflareEnv() {
535
530
  cloudflareEnvPromise ??= import(
536
531
  /* @vite-ignore */
537
532
  "cloudflare:workers"
538
533
  ).then((module) => module.env).catch(() => void 0);
539
- const value = (await cloudflareEnvPromise)?.[PROJECT_SECRET_ENV_VAR];
540
- return typeof value === "string" && value ? value : void 0;
534
+ return cloudflareEnvPromise;
541
535
  }
542
- async function resolveProjectSecret() {
543
- return readProcessSecret() ?? await readCloudflareSecret();
536
+ /**
537
+ * Returns a server environment variable from `process.env`, or else from the `cloudflare:workers` env.
538
+ *
539
+ * Call it inside a request: on Workers, `process.env` can be empty at module scope. An empty value counts as unset.
540
+ */
541
+ async function readRuntimeEnv(name) {
542
+ const value = (globalThis.process?.env)?.[name];
543
+ if (typeof value === "string" && value) return value;
544
+ const cloudflareValue = (await readCloudflareEnv())?.[name];
545
+ return typeof cloudflareValue === "string" && cloudflareValue ? cloudflareValue : void 0;
546
+ }
547
+ //#endregion
548
+ //#region src/stacks/tanstack/project-auth.ts
549
+ const PROJECT_SECRET_ENV_VAR = "LOVABLE_WORKFLOWS_KEY";
550
+ function resolveProjectSecret() {
551
+ return readRuntimeEnv(PROJECT_SECRET_ENV_VAR);
544
552
  }
545
553
  function bearerToken(request) {
546
554
  const header = request.headers.get("authorization");
@@ -824,4 +832,442 @@ function createStepsHandler(collection, options = {}) {
824
832
  };
825
833
  }
826
834
  //#endregion
827
- export { createMiddleware, createStepsHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, every, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
835
+ //#region src/client/errors.ts
836
+ /**
837
+ * A failed `startRun`, `getRun` or `deliverEvent` call.
838
+ *
839
+ * `status` is the gateway's HTTP status, and is undefined when the SDK refused the call before sending it or got no
840
+ * response. `retryable` is true when repeating the same call later can succeed without a change to the code, the
841
+ * configuration or the app; the SDK itself never retries.
842
+ */
843
+ var WorkflowsApiError = class extends Error {
844
+ name = "WorkflowsApiError";
845
+ type;
846
+ status;
847
+ requestId;
848
+ title;
849
+ detail;
850
+ errors;
851
+ retryable;
852
+ retryAfterMs;
853
+ constructor(message, fields) {
854
+ super(message, fields.cause === void 0 ? void 0 : { cause: fields.cause });
855
+ this.type = fields.type;
856
+ this.status = fields.status;
857
+ this.requestId = fields.requestId;
858
+ this.title = fields.title;
859
+ this.detail = fields.detail;
860
+ this.errors = fields.errors;
861
+ this.retryable = fields.retryable;
862
+ this.retryAfterMs = fields.retryAfterMs;
863
+ }
864
+ toJSON() {
865
+ return {
866
+ name: this.name,
867
+ message: this.message,
868
+ type: this.type,
869
+ status: this.status,
870
+ requestId: this.requestId,
871
+ title: this.title,
872
+ detail: this.detail,
873
+ errors: this.errors,
874
+ retryable: this.retryable,
875
+ retryAfterMs: this.retryAfterMs
876
+ };
877
+ }
878
+ };
879
+ var WorkflowsConfigurationError = class extends WorkflowsApiError {
880
+ name = "WorkflowsConfigurationError";
881
+ reason;
882
+ constructor(reason, message) {
883
+ super(message, {
884
+ type: "configuration_error",
885
+ retryable: false
886
+ });
887
+ this.reason = reason;
888
+ }
889
+ };
890
+ var WorkflowsRequestInvalidError = class extends WorkflowsApiError {
891
+ name = "WorkflowsRequestInvalidError";
892
+ };
893
+ /** The input fails the workflow's input schema. The SDK sent no request, so the Idempotency-Key is still unused. */
894
+ var RunInputInvalidError = class extends WorkflowsRequestInvalidError {
895
+ name = "RunInputInvalidError";
896
+ issues;
897
+ constructor(message, fields) {
898
+ super(message, fields);
899
+ this.issues = fields.issues;
900
+ }
901
+ };
902
+ var WorkflowsNetworkError = class extends WorkflowsApiError {
903
+ name = "WorkflowsNetworkError";
904
+ };
905
+ var WorkflowsAuthenticationError = class extends WorkflowsApiError {
906
+ name = "WorkflowsAuthenticationError";
907
+ };
908
+ var WorkflowsKeyLookupError = class extends WorkflowsApiError {
909
+ name = "WorkflowsKeyLookupError";
910
+ };
911
+ var WorkflowsDevelopmentKeyError = class extends WorkflowsApiError {
912
+ name = "WorkflowsDevelopmentKeyError";
913
+ };
914
+ var WorkflowsDisabledError = class extends WorkflowsApiError {
915
+ name = "WorkflowsDisabledError";
916
+ };
917
+ var RunNotFoundError = class extends WorkflowsApiError {
918
+ name = "RunNotFoundError";
919
+ };
920
+ var WorkflowNotPublishedError = class extends WorkflowsApiError {
921
+ name = "WorkflowNotPublishedError";
922
+ };
923
+ var IdempotencyKeyReusedError = class extends WorkflowsApiError {
924
+ name = "IdempotencyKeyReusedError";
925
+ };
926
+ var RunClosedError = class extends WorkflowsApiError {
927
+ name = "RunClosedError";
928
+ };
929
+ var RunNotWaitingError = class extends WorkflowsApiError {
930
+ name = "RunNotWaitingError";
931
+ };
932
+ var EventAlreadyDeliveredError = class extends WorkflowsApiError {
933
+ name = "EventAlreadyDeliveredError";
934
+ };
935
+ var WorkflowsPayloadTooLargeError = class extends WorkflowsApiError {
936
+ name = "WorkflowsPayloadTooLargeError";
937
+ };
938
+ var WorkflowsRateLimitedError = class extends WorkflowsApiError {
939
+ name = "WorkflowsRateLimitedError";
940
+ };
941
+ var WorkflowsUnavailableError = class extends WorkflowsApiError {
942
+ name = "WorkflowsUnavailableError";
943
+ };
944
+ const CLASS_BY_TYPE = /* @__PURE__ */ new Map([
945
+ ["invalid_request", WorkflowsRequestInvalidError],
946
+ ["invalid_api_key", WorkflowsAuthenticationError],
947
+ ["lovable_api_key_not_registered", WorkflowsAuthenticationError],
948
+ ["lovable_api_key_registry_lookup_failed", WorkflowsKeyLookupError],
949
+ ["lovable_api_key_development_only", WorkflowsDevelopmentKeyError],
950
+ ["app_workflows_disabled", WorkflowsDisabledError],
951
+ ["run_not_found", RunNotFoundError],
952
+ ["workflow_not_published", WorkflowNotPublishedError],
953
+ ["idempotency_key_reused", IdempotencyKeyReusedError],
954
+ ["run_closed", RunClosedError],
955
+ ["run_not_waiting", RunNotWaitingError],
956
+ ["event_already_delivered", EventAlreadyDeliveredError],
957
+ ["run_input_too_large", WorkflowsPayloadTooLargeError],
958
+ ["payload_too_large", WorkflowsPayloadTooLargeError]
959
+ ]);
960
+ const RETRYABLE_CLASSES = /* @__PURE__ */ new Set([
961
+ WorkflowsKeyLookupError,
962
+ RunNotWaitingError,
963
+ WorkflowsRateLimitedError,
964
+ WorkflowsUnavailableError
965
+ ]);
966
+ 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."]]);
967
+ const TYPE_BY_STATUS = /* @__PURE__ */ new Map([
968
+ [400, "bad_request"],
969
+ [401, "unauthorized"],
970
+ [403, "forbidden"],
971
+ [404, "not_found"],
972
+ [405, "method_not_allowed"],
973
+ [408, "request_timeout"],
974
+ [409, "conflict"],
975
+ [413, "request_entity_too_large"],
976
+ [415, "unsupported_media_type"],
977
+ [429, "too_many_requests"],
978
+ [500, "internal_server_error"],
979
+ [502, "bad_gateway"],
980
+ [503, "service_unavailable"],
981
+ [504, "gateway_timeout"]
982
+ ]);
983
+ const DEFAULT_RETRY_AFTER_MS = 1e3;
984
+ const MAX_ERROR_BODY_BYTES = 16384;
985
+ const ERROR_BODY_TIMEOUT_MS = 1e3;
986
+ const PACKAGE_PREFIX = "@lovable.dev/workflows-sdk";
987
+ function object(value) {
988
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
989
+ }
990
+ async function readErrorBody(response) {
991
+ if (!response.body) return void 0;
992
+ const reader = response.body.getReader();
993
+ let timer;
994
+ try {
995
+ return await Promise.race([(async () => {
996
+ const decoder = new TextDecoder();
997
+ let text = "";
998
+ let bytes = 0;
999
+ while (true) {
1000
+ const { done, value } = await reader.read();
1001
+ if (done) return JSON.parse(text + decoder.decode());
1002
+ bytes += value.byteLength;
1003
+ if (bytes > MAX_ERROR_BODY_BYTES) return void 0;
1004
+ text += decoder.decode(value, { stream: true });
1005
+ }
1006
+ })(), new Promise((resolve) => {
1007
+ timer = setTimeout(() => resolve(void 0), ERROR_BODY_TIMEOUT_MS);
1008
+ })]);
1009
+ } catch {
1010
+ return;
1011
+ } finally {
1012
+ clearTimeout(timer);
1013
+ reader.cancel().catch(() => void 0);
1014
+ }
1015
+ }
1016
+ function parseRetryAfter(value) {
1017
+ if (!value || value.length > 128) return void 0;
1018
+ const trimmed = value.trim();
1019
+ if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
1020
+ const milliseconds = Number(trimmed) * 1e3;
1021
+ return Number.isFinite(milliseconds) ? milliseconds : void 0;
1022
+ }
1023
+ if (!/^[A-Za-z]/.test(trimmed)) return void 0;
1024
+ const timestamp = Date.parse(trimmed);
1025
+ return Number.isFinite(timestamp) ? Math.max(0, timestamp - Date.now()) : void 0;
1026
+ }
1027
+ /** Replaces the API key in text that reaches an error, and caps its length. */
1028
+ function redactor(apiKey) {
1029
+ return (value, maxLength = 2e3) => (apiKey ? value.replaceAll(apiKey, "[redacted]") : value).slice(0, maxLength);
1030
+ }
1031
+ function errorDetails(value, redact) {
1032
+ if (!Array.isArray(value)) return void 0;
1033
+ const details = [];
1034
+ for (const entry of value.slice(0, 50)) {
1035
+ const { location, message } = object(entry);
1036
+ if (typeof message !== "string") continue;
1037
+ details.push({
1038
+ location: typeof location === "string" ? redact(location, 200) : null,
1039
+ message: redact(message)
1040
+ });
1041
+ }
1042
+ return details;
1043
+ }
1044
+ async function errorFromResponse(call, response, apiKey) {
1045
+ const redact = redactor(apiKey);
1046
+ const text = (value, maxLength) => typeof value === "string" && value ? redact(value, maxLength) : void 0;
1047
+ const body = object(await readErrorBody(response));
1048
+ const status = response.status;
1049
+ const envelopeType = text(body.type, 200);
1050
+ const type = envelopeType ?? TYPE_BY_STATUS.get(status) ?? `http_${status}`;
1051
+ let ErrorClass = WorkflowsApiError;
1052
+ if (status === 429) ErrorClass = WorkflowsRateLimitedError;
1053
+ else if (status === 503) ErrorClass = WorkflowsUnavailableError;
1054
+ else if (envelopeType) ErrorClass = CLASS_BY_TYPE.get(envelopeType) ?? WorkflowsApiError;
1055
+ const retryable = RETRYABLE_CLASSES.has(ErrorClass) || ErrorClass === WorkflowsApiError && (status === 408 || status >= 500);
1056
+ const retryAfterMs = parseRetryAfter(response.headers.get("Retry-After")) ?? (status === 429 || status === 503 ? DEFAULT_RETRY_AFTER_MS : void 0);
1057
+ const title = text(body.title, 200);
1058
+ const detail = text(body.detail);
1059
+ const hint = HINT_BY_TYPE.get(type);
1060
+ return new ErrorClass(`${PACKAGE_PREFIX}: ${call} failed (${status} ${type}): ${detail ?? title ?? "The gateway answered without an error body."}${hint ? ` ${hint}` : ""}`, {
1061
+ type,
1062
+ status,
1063
+ requestId: text(response.headers.get("X-Request-Id"), 200) ?? text(body.request_id, 200),
1064
+ title,
1065
+ detail,
1066
+ errors: errorDetails(body.errors, redact),
1067
+ retryable,
1068
+ retryAfterMs
1069
+ });
1070
+ }
1071
+ //#endregion
1072
+ //#region src/client/transport.ts
1073
+ const DEFAULT_BASE_URL = "https://connector-gateway.lovable.dev";
1074
+ function assertServerRuntime() {
1075
+ const runtime = globalThis;
1076
+ 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.`);
1077
+ }
1078
+ async function connect() {
1079
+ const apiKey = (await readRuntimeEnv("LOVABLE_API_KEY"))?.trim();
1080
+ if (!apiKey) throw new WorkflowsConfigurationError("missing_api_key", `${PACKAGE_PREFIX}: LOVABLE_API_KEY is missing from the server environment.`);
1081
+ const baseURL = ((await readRuntimeEnv("LOVABLE_WORKFLOWS_API_URL"))?.trim() || DEFAULT_BASE_URL).replace(/\/+$/, "");
1082
+ let url;
1083
+ try {
1084
+ url = new URL(baseURL);
1085
+ } catch {
1086
+ url = void 0;
1087
+ }
1088
+ 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.`);
1089
+ return {
1090
+ apiKey,
1091
+ baseURL
1092
+ };
1093
+ }
1094
+ function networkError(call, cause) {
1095
+ 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." : ""}`, {
1096
+ type: "network_error",
1097
+ retryable: true,
1098
+ cause
1099
+ });
1100
+ }
1101
+ function invalidResponse(call, response, cause) {
1102
+ return new WorkflowsApiError(`${PACKAGE_PREFIX}: ${call} got a ${response.status} response that is not the expected JSON.`, {
1103
+ type: "invalid_response",
1104
+ status: response.status,
1105
+ requestId: response.headers.get("X-Request-Id")?.slice(0, 200) || void 0,
1106
+ retryable: true,
1107
+ cause
1108
+ });
1109
+ }
1110
+ async function send(request) {
1111
+ const connection = await connect();
1112
+ const headers = new Headers(request.headers);
1113
+ headers.set("Authorization", `Bearer ${connection.apiKey}`);
1114
+ headers.set("Accept", "application/json");
1115
+ headers.set("User-Agent", `lovable-workflows-sdk/0.0.0-dev.57`);
1116
+ if (request.body !== void 0) headers.set("Content-Type", "application/json");
1117
+ let response;
1118
+ try {
1119
+ response = await fetch(`${connection.baseURL}${request.path}`, {
1120
+ method: request.method,
1121
+ headers,
1122
+ body: request.body,
1123
+ signal: request.signal,
1124
+ redirect: "manual"
1125
+ });
1126
+ } catch (cause) {
1127
+ if (request.signal?.aborted) throw request.signal.reason;
1128
+ throw networkError(request.call, cause);
1129
+ }
1130
+ if (!response.ok) throw await errorFromResponse(request.call, response, connection.apiKey);
1131
+ let parsed;
1132
+ try {
1133
+ parsed = await response.json();
1134
+ } catch (cause) {
1135
+ if (request.signal?.aborted) throw request.signal.reason;
1136
+ if (cause instanceof SyntaxError) throw invalidResponse(request.call, response, cause);
1137
+ throw networkError(request.call, cause);
1138
+ }
1139
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw invalidResponse(request.call, response);
1140
+ return parsed;
1141
+ }
1142
+ //#endregion
1143
+ //#region src/client/runs.ts
1144
+ const IDEMPOTENCY_KEY_PATTERN = /^[\x20-\x7E]{1,64}$/;
1145
+ const MAX_RUN_ID_LENGTH = 64;
1146
+ function invalidRequest(call, location, message, cause) {
1147
+ return new WorkflowsRequestInvalidError(`${PACKAGE_PREFIX}: ${call}: ${message}`, {
1148
+ type: "invalid_request",
1149
+ retryable: false,
1150
+ errors: [{
1151
+ location,
1152
+ message
1153
+ }],
1154
+ cause
1155
+ });
1156
+ }
1157
+ function serialize(call, body, location) {
1158
+ try {
1159
+ return JSON.stringify(body);
1160
+ } catch (cause) {
1161
+ throw invalidRequest(call, location, "the value is not JSON-serializable", cause);
1162
+ }
1163
+ }
1164
+ function checkRunId(call, runId) {
1165
+ 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");
1166
+ }
1167
+ function issueLocation(issue) {
1168
+ let location = "body.input";
1169
+ for (const segment of issue.path ?? []) {
1170
+ const key = typeof segment === "object" ? segment.key : segment;
1171
+ location += typeof key === "number" ? `[${key}]` : `.${String(key)}`;
1172
+ }
1173
+ return location;
1174
+ }
1175
+ async function checkInput(workflow, body) {
1176
+ if (!workflow.inputSchema) return;
1177
+ const input = JSON.parse(body).input ?? null;
1178
+ const result = await workflow.inputSchema["~standard"].validate(input);
1179
+ if (!result.issues) return;
1180
+ const summary = result.issues.map((issue) => issue.message).join("; ");
1181
+ throw new RunInputInvalidError(`${PACKAGE_PREFIX}: startRun: the input fails the input schema of workflow "${workflow.id}"${summary ? `: ${summary}` : ""}`, {
1182
+ type: "invalid_input",
1183
+ retryable: false,
1184
+ errors: result.issues.map((issue) => ({
1185
+ location: issueLocation(issue),
1186
+ message: issue.message
1187
+ })),
1188
+ issues: result.issues
1189
+ });
1190
+ }
1191
+ function toRunSummary(wire) {
1192
+ const run = wire;
1193
+ return {
1194
+ runId: run.run_id,
1195
+ workflowId: run.workflow_id,
1196
+ status: run.status,
1197
+ trigger: run.trigger,
1198
+ createdAt: run.created_at
1199
+ };
1200
+ }
1201
+ function toRun(wire) {
1202
+ const run = wire;
1203
+ return {
1204
+ ...toRunSummary(wire),
1205
+ updatedAt: run.updated_at,
1206
+ closedAt: run.closed_at,
1207
+ error: run.error,
1208
+ input: run.input,
1209
+ output: run.output
1210
+ };
1211
+ }
1212
+ async function startRun(workflow, input, options = {}) {
1213
+ options.signal?.throwIfAborted();
1214
+ assertServerRuntime();
1215
+ const definition = typeof workflow === "string" ? void 0 : workflow;
1216
+ if (definition !== void 0 && (typeof definition !== "object" || definition?.__kind !== "workflow")) throw invalidRequest("startRun", "path.workflow_id", "pass a workflow id or a createWorkflow() definition");
1217
+ const workflowId = definition?.id ?? workflow;
1218
+ 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");
1219
+ const { idempotencyKey } = options;
1220
+ 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");
1221
+ const body = serialize("startRun", input === void 0 ? {} : { input }, "body.input");
1222
+ if (definition) await checkInput(definition, body);
1223
+ return toRunSummary(await send({
1224
+ call: "startRun",
1225
+ method: "POST",
1226
+ path: `/api/v1/app-workflows/${encodeURIComponent(workflowId)}/runs`,
1227
+ body,
1228
+ headers: idempotencyKey === void 0 ? void 0 : { "Idempotency-Key": idempotencyKey },
1229
+ signal: options.signal
1230
+ }));
1231
+ }
1232
+ /**
1233
+ * Reads one of the app's runs, with its input and output. Call it from server code only.
1234
+ *
1235
+ * The app's key reads every run of its project: runs it started, scheduled runs and editor test runs.
1236
+ */
1237
+ async function getRun(runId, options = {}) {
1238
+ options.signal?.throwIfAborted();
1239
+ assertServerRuntime();
1240
+ checkRunId("getRun", runId);
1241
+ return toRun(await send({
1242
+ call: "getRun",
1243
+ method: "GET",
1244
+ path: `/api/v1/app-workflow-runs/${encodeURIComponent(runId)}`,
1245
+ signal: options.signal
1246
+ }));
1247
+ }
1248
+ /**
1249
+ * Resumes the run's `ctx.waitForEvent` call that waits on the event's name. Call it from server code only.
1250
+ *
1251
+ * Events are not queued: an open run that doesn't wait on the name yet throws `RunNotWaitingError`, which can be
1252
+ * retried, and a finished run throws `RunClosedError`. A retry with the same `eventId` is always safe.
1253
+ */
1254
+ async function deliverEvent(runId, event, options = {}) {
1255
+ options.signal?.throwIfAborted();
1256
+ assertServerRuntime();
1257
+ checkRunId("deliverEvent", runId);
1258
+ if (event === null || typeof event !== "object") throw invalidRequest("deliverEvent", "body", "pass the event as { eventId, name, payload? }");
1259
+ const body = serialize("deliverEvent", {
1260
+ event_id: event.eventId,
1261
+ name: event.name,
1262
+ ...event.payload === void 0 ? {} : { payload: event.payload }
1263
+ }, "body.payload");
1264
+ return { recorded: (await send({
1265
+ call: "deliverEvent",
1266
+ method: "POST",
1267
+ path: `/api/v1/app-workflow-runs/${encodeURIComponent(runId)}/events`,
1268
+ body,
1269
+ signal: options.signal
1270
+ })).recorded === true };
1271
+ }
1272
+ //#endregion
1273
+ 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 };
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DZKqS7JU.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-qDFxy3v5.js";
2
2
  //#region src/manifests/nested-operations.ts
3
3
  const durableMethods = [
4
4
  "step",
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DZKqS7JU.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-qDFxy3v5.js";
2
2
  //#region src/manifests/operation-descriptions.ts
3
3
  const optionsArgument = {
4
4
  approve: 0,
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DZKqS7JU.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-qDFxy3v5.js";
2
2
  //#region src/manifests/step-metadata.ts
3
3
  async function findStepMetadataIssues(handler) {
4
4
  const api = await loadTypeScript();
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as generateManifests } from "./generate-W-NgD43q.js";
1
+ import { t as generateManifests } from "./generate-CzKPbFyR.js";
2
2
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import { createServer } from "vite";
4
4
  import { lstat, mkdir, mkdtemp, readdir, rename, rm, writeFile } from "node:fs/promises";
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DZKqS7JU.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-qDFxy3v5.js";
2
2
  //#region src/manifests/wait-deadlines.ts
3
3
  const optionsArgument = {
4
4
  approve: 0,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/workflows-sdk",
3
- "version": "0.0.0-dev.56",
3
+ "version": "0.0.0-dev.57",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "dev",