@lovable.dev/workflows-sdk 0.0.0-dev.4 → 0.0.0-dev.5

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
@@ -179,9 +179,9 @@ report, a five-minute heartbeat, an hourly sweep, and a paused daily digest.
179
179
 
180
180
  ## Manifest generation
181
181
 
182
- Add `workflowsManifest({ entry: "src/lib/workflows/index.ts" })` from
183
- `@lovable.dev/workflows-sdk/vite` to the app's Vite plugins. The entry must
184
- default-export its `registerWorkflows()` collection. Each production build writes
182
+ Add `workflowsPlugin()` from `@lovable.dev/workflows-sdk/vite` to the app's Vite
183
+ plugins. Its `entry` defaults to `src/lib/workflows/index.ts` and must
184
+ default-export the app's `registerWorkflows()` collection. Each production build writes
185
185
  one manifest per workflow to `.lovable/workflows/{workflow-name}.json` relative
186
186
  to the app root. For example, `greet` produces `.lovable/workflows/greet.json`.
187
187
  Generation errors fail the build. See [the Vite example](examples/vite.config.ts).
@@ -253,6 +253,78 @@ unsupported code are not expanded. The UI should show these unknown nodes and
253
253
  mark partial graphs. Transforms that rewrite the handler may also produce a
254
254
  partial graph. A handler with no steps can have an empty graph.
255
255
 
256
+ ## Run endpoint (TanStack Start)
257
+
258
+ Pass `runRoute: true` to the same `workflowsPlugin` that writes the manifests. It
259
+ then also emits one dynamic route, `src/routes/api/workflows/$workflowId.ts`,
260
+ serving every registered workflow. One plugin and one `entry` cover both, so a
261
+ manifest can never describe a collection the route does not serve:
262
+
263
+ ```ts
264
+ import { tanstackStart } from "@tanstack/react-start/plugin/vite";
265
+ import { workflowsPlugin } from "@lovable.dev/workflows-sdk/vite";
266
+
267
+ export default defineConfig({
268
+ plugins: [workflowsPlugin({ runRoute: true }), tanstackStart()],
269
+ });
270
+ ```
271
+
272
+ `runRoute` defaults to `false`. The route is unauthenticated: any caller who
273
+ reaches it runs any declared workflow. Turn it on only where that is acceptable,
274
+ until signed invocation lands.
275
+
276
+ The emitted file is thin — it imports the collection and mounts
277
+ `createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk/stacks/tanstack`
278
+ as the route's `POST` handler. All runtime logic stays in the package. The file
279
+ carries a generated banner, which is the plugin's ownership token: it rewrites
280
+ and deletes only files that have it, and deletes its own orphans when `path`,
281
+ `workflowIdParam`, or `runRoute` changes. Delete the banner line to take the
282
+ route over — the plugin then leaves that file alone, and the build keeps
283
+ working.
284
+
285
+ | Option | Default | Meaning |
286
+ | --- | --- | --- |
287
+ | `entry` | `src/lib/workflows/index.ts` | Collection entry; a missing file means no route |
288
+ | `routesDir` | `src/routes` | Where the route file is written |
289
+ | `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
290
+ | `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
291
+ | `runRoute` | `false` | Emit the route at all |
292
+
293
+ ### Calling it
294
+
295
+ `POST /api/workflows/{workflow-id}` with a JSON body. The body is decoded by
296
+ `parseWorkflowRequest`, so one route takes every traffic shape: `{ "input": ... }`
297
+ starts a run, `{ "runId", "approval" }` delivers an approval decision, and
298
+ `{ "runId", "signal" }` delivers a signal. A run that parks on `ctx.approve` or
299
+ `ctx.waitForEvent` resumes on this same route — there is no separate resume
300
+ endpoint. An unknown workflow ID returns 404, an unparseable body 400, and
301
+ `{ "abort": true }` returns 501 until a shared run registry exists.
302
+
303
+ The response is `text/event-stream`. Each engine event becomes one SSE message
304
+ whose event name is the event `type` and whose data is the whole event as JSON:
305
+
306
+ ```text
307
+ event: RUN_STARTED
308
+ data: {"type":"RUN_STARTED","ts":1790505539351,"runId":"run_1790505539350_yin41cp"}
309
+
310
+ event: STEP_FINISHED
311
+ data: {"type":"STEP_FINISHED","ts":1790505539352,"stepId":"greeting","result":"Hello, YEHYA!"}
312
+
313
+ event: RUN_FINISHED
314
+ data: {"type":"RUN_FINISHED","ts":1790505539352,"runId":"run_1790505539350_yin41cp","output":{"message":"Hello, YEHYA!"}}
315
+ ```
316
+
317
+ Run state lives in a process-local `inMemoryRunStore()`: runs are lost on restart
318
+ and are invisible to other instances. Pass `runStore` to
319
+ `createTanStackWorkflowHandler` to supply another one. The control-plane store is
320
+ a follow-up.
321
+
322
+ The path carries no build ID. Version pinning belongs to the signed invocation,
323
+ which leaves this path stable across deployments and safe to publish in a
324
+ manifest. Triggers name a workflow rather than an endpoint, so firing one is a
325
+ POST to that workflow's path with the trigger's input; no trigger identifier
326
+ appears in the URL.
327
+
256
328
  ## Next PRs
257
329
 
258
330
  Connect the manifest and app code to Lovable deployment and runtime execution.
@@ -0,0 +1,31 @@
1
+ import { AnyWorkflowDefinition, RunStore, WorkflowEvent } from "@tanstack/workflow-core";
2
+ //#region src/stacks/tanstack/handlers.d.ts
3
+ /** The shape `registerWorkflows()` returns; only the list is needed to dispatch. */
4
+ interface WorkflowCollection {
5
+ readonly workflows: readonly AnyWorkflowDefinition[];
6
+ }
7
+ interface TanStackWorkflowHandlerOptions {
8
+ /** @default a process-local `inMemoryRunStore()`, lost on restart */
9
+ runStore?: RunStore;
10
+ /**
11
+ * Route parameter carrying the workflow ID.
12
+ * @default "workflowId"
13
+ */
14
+ workflowIdParam?: string;
15
+ }
16
+ interface TanStackRouteCtx {
17
+ request: Request;
18
+ params?: Record<string, string | undefined>;
19
+ }
20
+ type TanStackWorkflowHandler = (ctx: TanStackRouteCtx) => Promise<Response>;
21
+ /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
22
+ declare function createTanStackWorkflowHandler(collection: WorkflowCollection, options?: TanStackWorkflowHandlerOptions): TanStackWorkflowHandler;
23
+ //#endregion
24
+ //#region src/stacks/tanstack/sse.d.ts
25
+ /**
26
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
27
+ * engine `type` as the SSE event name and its whole JSON as the data line.
28
+ */
29
+ declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
30
+ //#endregion
31
+ export { type TanStackWorkflowHandler, type TanStackWorkflowHandlerOptions, type WorkflowCollection, createTanStackWorkflowHandler, toServerSentEventsResponse };
@@ -0,0 +1,99 @@
1
+ import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
2
+ //#region src/stacks/tanstack/sse.ts
3
+ const HEADERS = {
4
+ "content-type": "text/event-stream; charset=utf-8",
5
+ "cache-control": "no-cache, no-transform",
6
+ connection: "keep-alive",
7
+ "x-accel-buffering": "no"
8
+ };
9
+ function describe(error) {
10
+ return error instanceof Error ? error.message : String(error);
11
+ }
12
+ function frame(name, data) {
13
+ return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
14
+ }
15
+ /**
16
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
17
+ * engine `type` as the SSE event name and its whole JSON as the data line.
18
+ */
19
+ function toServerSentEventsResponse(events) {
20
+ const encoder = new TextEncoder();
21
+ const body = new ReadableStream({ async start(controller) {
22
+ let connected = true;
23
+ const write = (text) => {
24
+ if (!connected) return;
25
+ try {
26
+ controller.enqueue(encoder.encode(text));
27
+ } catch {
28
+ connected = false;
29
+ }
30
+ };
31
+ const send = (name, data) => {
32
+ try {
33
+ write(frame(name, data));
34
+ } catch (error) {
35
+ write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe(error)}` }));
36
+ }
37
+ };
38
+ try {
39
+ for await (const event of events) send(event.type, event);
40
+ } catch (error) {
41
+ send("STREAM_ERRORED", { message: describe(error) });
42
+ } finally {
43
+ try {
44
+ controller.close();
45
+ } catch {
46
+ connected = false;
47
+ }
48
+ }
49
+ } });
50
+ return new Response(body, { headers: HEADERS });
51
+ }
52
+ //#endregion
53
+ //#region src/stacks/tanstack/handlers.ts
54
+ function json(status, body) {
55
+ return new Response(JSON.stringify(body), {
56
+ status,
57
+ headers: { "content-type": "application/json; charset=utf-8" }
58
+ });
59
+ }
60
+ function resolveWorkflowId(ctx, param) {
61
+ const fromParams = ctx.params?.[param];
62
+ if (fromParams) return fromParams;
63
+ return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
64
+ }
65
+ /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
66
+ function createTanStackWorkflowHandler(collection, options = {}) {
67
+ const runStore = options.runStore ?? inMemoryRunStore();
68
+ const param = options.workflowIdParam ?? "workflowId";
69
+ const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
70
+ return async (ctx) => {
71
+ const workflowId = resolveWorkflowId(ctx, param);
72
+ const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
73
+ if (!workflow) return json(404, {
74
+ error: "unknown_workflow",
75
+ workflowId: workflowId ?? ""
76
+ });
77
+ let params;
78
+ try {
79
+ params = await parseWorkflowRequest(ctx.request);
80
+ } catch (error) {
81
+ if (error instanceof WorkflowRequestParseError) return json(400, {
82
+ error: "invalid_request",
83
+ message: error.message
84
+ });
85
+ throw error;
86
+ }
87
+ if (params.abort) return json(501, {
88
+ error: "abort_unsupported",
89
+ message: "Cancelling an in-flight run needs a shared run registry (WOR-53)."
90
+ });
91
+ return toServerSentEventsResponse(runWorkflow({
92
+ workflow,
93
+ runStore,
94
+ ...params
95
+ }));
96
+ };
97
+ }
98
+ //#endregion
99
+ export { createTanStackWorkflowHandler, toServerSentEventsResponse };
package/dist/vite.d.ts CHANGED
@@ -1,7 +1,24 @@
1
1
  import { Plugin } from "vite";
2
2
  //#region src/vite/plugin.d.ts
3
- declare function workflowsManifest({ entry }: {
4
- entry: string;
5
- }): Plugin;
3
+ interface WorkflowsPluginOptions {
4
+ /** Collection entry, relative to the project root. @default "src/lib/workflows/index.ts" */
5
+ entry?: string;
6
+ /** Where TanStack route files live; the plugin emits under this directory.
7
+ * @default "src/routes" */
8
+ routesDir?: string;
9
+ /** URL prefix; the workflow ID is appended as a dynamic segment. @default "/api/workflows" */
10
+ path?: string;
11
+ /** Route parameter carrying the workflow ID. @default "workflowId" */
12
+ workflowIdParam?: string;
13
+ /** @default false */
14
+ runRoute?: boolean;
15
+ }
16
+ /**
17
+ * Build the collection's manifests and, with `runRoute`, emit the route serving
18
+ * them; one `entry` feeds both, so the two can never describe different sets.
19
+ */
20
+ declare function workflowsPlugin(options?: WorkflowsPluginOptions): Plugin;
21
+ /** @deprecated Renamed to `workflowsPlugin`, which also emits the run route. */
22
+ declare const workflowsManifest: typeof workflowsPlugin;
6
23
  //#endregion
7
- export { workflowsManifest };
24
+ export { type WorkflowsPluginOptions, workflowsManifest, workflowsPlugin };
package/dist/vite.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { t as generateManifests } from "./generate-IXn3QGVb.js";
2
- import { join, resolve } from "node:path";
2
+ import { dirname, 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";
5
+ import { lstatSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
5
6
  //#region src/vite/manifest-files.ts
6
7
  async function ensureDirectory(path) {
7
8
  try {
@@ -30,14 +31,181 @@ async function writeManifests(root, manifests) {
30
31
  }
31
32
  }
32
33
  //#endregion
34
+ //#region src/vite/route-emitter.ts
35
+ const GENERATED_BANNER = "// AUTO-GENERATED by @lovable.dev/workflows-sdk — do not edit. Regenerated by the Vite plugin.\n// To take ownership, delete this banner line; the plugin then leaves the file alone.";
36
+ function isFileMissing(error) {
37
+ const code = error?.code;
38
+ return code === "ENOENT" || code === "ENOTDIR";
39
+ }
40
+ function normalizePath(path) {
41
+ return path.split(sep).join("/");
42
+ }
43
+ function assertContains(parent, child, label) {
44
+ const from = normalizePath(parent).replace(/\/$/, "");
45
+ const to = normalizePath(child);
46
+ if (to !== from && !to.startsWith(`${from}/`)) throw new Error(`@lovable.dev/workflows-sdk: ${label} must resolve under ${from}, got ${to}`);
47
+ }
48
+ function assertUrlPathShape(urlPath) {
49
+ if (!urlPath.startsWith("/")) throw new Error(`@lovable.dev/workflows-sdk: path must start with "/", got "${urlPath}"`);
50
+ if (/\/{2,}/.test(urlPath)) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" contains empty segments ("//")`);
51
+ const trimmed = urlPath.replace(/^\/+/, "").replace(/\/+$/, "");
52
+ if (!trimmed) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" has no route segment`);
53
+ if (!/^[a-zA-Z0-9_\-/]+$/.test(trimmed)) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" contains unsupported characters`);
54
+ return trimmed;
55
+ }
56
+ function assertParamShape(param) {
57
+ if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(param)) throw new Error(`@lovable.dev/workflows-sdk: workflowIdParam "${param}" must be a JavaScript identifier`);
58
+ return param;
59
+ }
60
+ function relativeImportSpecifier(routeFile, target) {
61
+ const withoutExt = normalizePath(relative(dirname(routeFile), target)).replace(/\.tsx?$/, "");
62
+ return withoutExt.startsWith(".") ? withoutExt : `./${withoutExt}`;
63
+ }
64
+ function buildRouteSource(routeFile, routeLiteral, param, entry, root) {
65
+ return `${GENERATED_BANNER}
66
+ // route: ${routeLiteral}
67
+ // emitted to: ${normalizePath(relative(root, routeFile))}
68
+ // This route is unauthenticated: any caller can run any declared workflow.
69
+
70
+ import { createFileRoute } from "@tanstack/react-router";
71
+
72
+ import { createTanStackWorkflowHandler } from "@lovable.dev/workflows-sdk/stacks/tanstack";
73
+
74
+ import workflows from "${relativeImportSpecifier(routeFile, entry)}";
75
+
76
+ export const Route = createFileRoute("${routeLiteral}")({
77
+ server: {
78
+ handlers: {
79
+ POST: createTanStackWorkflowHandler(workflows, { workflowIdParam: "${param}" }),
80
+ },
81
+ },
82
+ });
83
+ `;
84
+ }
85
+ function hasGeneratedBanner(content) {
86
+ return content.replace(/\r\n/g, "\n").startsWith(GENERATED_BANNER);
87
+ }
88
+ function writeIfChanged(file, content) {
89
+ let existing;
90
+ try {
91
+ existing = readFileSync(file, "utf8");
92
+ } catch (error) {
93
+ if (!isFileMissing(error)) throw error;
94
+ }
95
+ if (existing !== void 0 && (!hasGeneratedBanner(existing) || existing === content)) return;
96
+ mkdirSync(dirname(file), { recursive: true });
97
+ writeFileSync(file, content, "utf8");
98
+ }
99
+ function findAdoptedFiles(routesDir) {
100
+ const adopted = [];
101
+ const visit = (dir) => {
102
+ let entries;
103
+ try {
104
+ entries = readdirSync(dir);
105
+ } catch (error) {
106
+ if (isFileMissing(error)) return;
107
+ throw error;
108
+ }
109
+ for (const entry of entries) {
110
+ const full = join(dir, entry);
111
+ let stat;
112
+ try {
113
+ stat = lstatSync(full);
114
+ } catch (error) {
115
+ if (isFileMissing(error)) continue;
116
+ throw error;
117
+ }
118
+ if (stat.isDirectory()) visit(full);
119
+ else if (entry.endsWith(".ts")) try {
120
+ if (hasGeneratedBanner(readFileSync(full, "utf8"))) adopted.push(full);
121
+ } catch (error) {
122
+ if (!isFileMissing(error)) throw error;
123
+ }
124
+ }
125
+ };
126
+ visit(routesDir);
127
+ return adopted;
128
+ }
129
+ function createRouteEmitter(options) {
130
+ const param = assertParamShape(options.workflowIdParam);
131
+ const pathSegments = assertUrlPathShape(options.path);
132
+ const routeLiteral = `/${pathSegments}/$${param}`;
133
+ const routeFileName = join(...pathSegments.split("/"), `$${param}.ts`);
134
+ let root = process.cwd();
135
+ let entry = resolve(root, options.entry);
136
+ let routesDir = resolve(root, options.routesDir);
137
+ let routeFile = resolve(routesDir, routeFileName);
138
+ return {
139
+ entryPath: () => entry,
140
+ setRoot(next) {
141
+ root = next;
142
+ entry = resolve(root, options.entry);
143
+ assertContains(root, entry, `entry "${options.entry}"`);
144
+ routesDir = resolve(root, options.routesDir);
145
+ assertContains(root, routesDir, `routesDir "${options.routesDir}"`);
146
+ routeFile = resolve(routesDir, routeFileName);
147
+ assertContains(routesDir, routeFile, `path "${routeLiteral}"`);
148
+ },
149
+ regenerate() {
150
+ let entryExists = true;
151
+ try {
152
+ lstatSync(entry);
153
+ } catch (error) {
154
+ if (!isFileMissing(error)) throw error;
155
+ entryExists = false;
156
+ }
157
+ const expected = /* @__PURE__ */ new Set();
158
+ if (entryExists && options.runRoute) {
159
+ expected.add(routeFile);
160
+ writeIfChanged(routeFile, buildRouteSource(routeFile, routeLiteral, param, entry, root));
161
+ }
162
+ for (const file of findAdoptedFiles(routesDir)) {
163
+ if (expected.has(file)) continue;
164
+ try {
165
+ unlinkSync(file);
166
+ } catch (error) {
167
+ if (!isFileMissing(error)) throw error;
168
+ }
169
+ }
170
+ }
171
+ };
172
+ }
173
+ //#endregion
33
174
  //#region src/vite/plugin.ts
34
- function workflowsManifest({ entry }) {
175
+ /**
176
+ * Build the collection's manifests and, with `runRoute`, emit the route serving
177
+ * them; one `entry` feeds both, so the two can never describe different sets.
178
+ */
179
+ function workflowsPlugin(options = {}) {
180
+ const entry = options.entry ?? "src/lib/workflows/index.ts";
181
+ const emitter = createRouteEmitter({
182
+ entry,
183
+ routesDir: options.routesDir ?? "src/routes",
184
+ path: options.path ?? "/api/workflows",
185
+ workflowIdParam: options.workflowIdParam ?? "workflowId",
186
+ runRoute: options.runRoute === true
187
+ });
35
188
  let config;
36
189
  return {
37
- name: "@lovable.dev/workflows-sdk/manifest",
38
- apply: "build",
190
+ name: "@lovable.dev/workflows-sdk",
39
191
  configResolved(resolved) {
40
192
  config = resolved;
193
+ emitter.setRoot(config.root);
194
+ emitter.regenerate();
195
+ },
196
+ configureServer(server) {
197
+ const onChange = (file) => {
198
+ if (normalizePath(file) === normalizePath(emitter.entryPath())) emitter.regenerate();
199
+ };
200
+ server.watcher.on("add", onChange);
201
+ server.watcher.on("unlink", onChange);
202
+ server.watcher.once("close", () => {
203
+ server.watcher.off("add", onChange);
204
+ server.watcher.off("unlink", onChange);
205
+ });
206
+ },
207
+ buildStart() {
208
+ emitter.regenerate();
41
209
  },
42
210
  async generateBundle() {
43
211
  const entryPath = resolve(config.root, entry);
@@ -73,5 +241,7 @@ function workflowsManifest({ entry }) {
73
241
  }
74
242
  };
75
243
  }
244
+ /** @deprecated Renamed to `workflowsPlugin`, which also emits the run route. */
245
+ const workflowsManifest = workflowsPlugin;
76
246
  //#endregion
77
- export { workflowsManifest };
247
+ export { workflowsManifest, workflowsPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/workflows-sdk",
3
- "version": "0.0.0-dev.4",
3
+ "version": "0.0.0-dev.5",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "dev",
@@ -22,6 +22,10 @@
22
22
  "./vite": {
23
23
  "types": "./dist/vite.d.ts",
24
24
  "import": "./dist/vite.js"
25
+ },
26
+ "./stacks/tanstack": {
27
+ "types": "./dist/stacks/tanstack/index.d.ts",
28
+ "import": "./dist/stacks/tanstack/index.js"
25
29
  }
26
30
  },
27
31
  "files": [