@lovable.dev/workflows-sdk 0.0.0-dev.6 → 0.0.0-dev.8
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 +81 -15
- package/dist/index.d.ts +31 -2
- package/dist/index.js +99 -1
- package/dist/vite.d.ts +2 -4
- package/dist/vite.js +120 -13
- package/package.json +2 -5
- package/dist/stacks/tanstack/index.d.ts +0 -31
- package/dist/stacks/tanstack/index.js +0 -99
package/README.md
CHANGED
|
@@ -300,32 +300,60 @@ partial graph. A handler with no steps can have an empty graph.
|
|
|
300
300
|
|
|
301
301
|
## Run endpoint (TanStack Start)
|
|
302
302
|
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
303
|
+
The same `workflowsPlugin` that writes the manifests also emits one dynamic
|
|
304
|
+
route, `src/routes/api/workflows/$workflowId.ts`, serving every registered
|
|
305
|
+
workflow. There is no opt-in: a declared workflow with no endpoint cannot run.
|
|
306
|
+
One plugin and one `entry` cover both, so a manifest can never describe a
|
|
307
|
+
collection the route does not serve:
|
|
307
308
|
|
|
308
309
|
```ts
|
|
309
310
|
import { tanstackStart } from "@tanstack/react-start/plugin/vite";
|
|
310
311
|
import { workflowsPlugin } from "@lovable.dev/workflows-sdk/vite";
|
|
311
312
|
|
|
312
313
|
export default defineConfig({
|
|
313
|
-
plugins: [workflowsPlugin(
|
|
314
|
+
plugins: [workflowsPlugin(), tanstackStart()],
|
|
314
315
|
});
|
|
315
316
|
```
|
|
316
317
|
|
|
317
|
-
`
|
|
318
|
-
|
|
319
|
-
|
|
318
|
+
A missing `entry` file is the only thing that suppresses the route: an app with
|
|
319
|
+
no collection gets no endpoint.
|
|
320
|
+
|
|
321
|
+
### The route is unauthenticated
|
|
322
|
+
|
|
323
|
+
**Any caller who reaches the route can run any declared workflow.** The SDK
|
|
324
|
+
ships no request authentication today; signed invocation is the next piece of
|
|
325
|
+
work on this endpoint. Until it lands, treat the endpoint as public and keep
|
|
326
|
+
anything a stranger must not trigger — spend, mutation of another user's data,
|
|
327
|
+
outbound mail — out of a declared workflow, or guard it inside the handler.
|
|
328
|
+
|
|
329
|
+
Reachability is the lever an app has in the meantime. Public apps expose the
|
|
330
|
+
route to the internet. Workspace and private apps are gated by the Lovable host,
|
|
331
|
+
which is why `path` matters (below).
|
|
332
|
+
|
|
333
|
+
### Relocating the route with `path`
|
|
334
|
+
|
|
335
|
+
`path` sets the URL prefix; the workflow ID is appended as a dynamic segment,
|
|
336
|
+
and the emitted file name follows the path. Workspace and private apps reach
|
|
337
|
+
anonymous traffic only under an `/api/public` prefix — everything else is
|
|
338
|
+
blocked by the host before it reaches the app — so those projects must move the
|
|
339
|
+
route there for it to be reachable at all:
|
|
340
|
+
|
|
341
|
+
```ts
|
|
342
|
+
workflowsPlugin({ path: "/api/public/workflows" });
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
That emits `src/routes/api/public/workflows/$workflowId.ts` and serves
|
|
346
|
+
`POST /api/public/workflows/{workflow-id}`. The trade is explicit: the prefix
|
|
347
|
+
that makes the route reachable also makes it anonymously reachable.
|
|
320
348
|
|
|
321
349
|
The emitted file is thin — it imports the collection and mounts
|
|
322
|
-
`createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk
|
|
323
|
-
|
|
350
|
+
`createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk` as the route's
|
|
351
|
+
`POST` handler. All runtime logic stays in the package. The file
|
|
324
352
|
carries a generated banner, which is the plugin's ownership token: it rewrites
|
|
325
|
-
and deletes only files that have it, and deletes its own orphans when `path
|
|
326
|
-
`workflowIdParam
|
|
327
|
-
|
|
328
|
-
|
|
353
|
+
and deletes only files that have it, and deletes its own orphans when `path` or
|
|
354
|
+
`workflowIdParam` changes. Delete the banner line to take the route over — the
|
|
355
|
+
plugin then leaves that file alone, and the build keeps working. That is also
|
|
356
|
+
the supported way to add a check of your own in front of the handler.
|
|
329
357
|
|
|
330
358
|
| Option | Default | Meaning |
|
|
331
359
|
| --- | --- | --- |
|
|
@@ -333,7 +361,29 @@ working.
|
|
|
333
361
|
| `routesDir` | `src/routes` | Where the route file is written |
|
|
334
362
|
| `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
|
|
335
363
|
| `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
|
|
336
|
-
|
|
364
|
+
|
|
365
|
+
### How the emitted file imports the collection
|
|
366
|
+
|
|
367
|
+
The plugin prefers an alias, so the specifier does not change when `path` moves:
|
|
368
|
+
|
|
369
|
+
```ts
|
|
370
|
+
import workflows from "@/lib/workflows/index";
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
It does not assume `@`. It reads the app's Vite `resolve.alias` and its
|
|
374
|
+
tsconfig `compilerOptions.paths`, and picks an alias whose target directory
|
|
375
|
+
contains the collection entry — preferring one both sources declare, then the
|
|
376
|
+
deepest match.
|
|
377
|
+
|
|
378
|
+
An alias is only emitted when the *bundler* can resolve it: a Vite
|
|
379
|
+
`resolve.alias` entry, or a tsconfig `paths` entry when a plugin such as
|
|
380
|
+
`vite-tsconfig-paths` is active. A tsconfig `paths` entry alone instructs the
|
|
381
|
+
typechecker and not the bundler, so emitting it would fail the build.
|
|
382
|
+
|
|
383
|
+
When no alias qualifies, the plugin falls back to a relative specifier
|
|
384
|
+
(`../../../lib/workflows/index`), which always resolves. An app with no alias
|
|
385
|
+
configured still builds; only the specifier is uglier, and its depth tracks
|
|
386
|
+
`path`.
|
|
337
387
|
|
|
338
388
|
### Calling it
|
|
339
389
|
|
|
@@ -370,6 +420,22 @@ manifest. Triggers name a workflow rather than an endpoint, so firing one is a
|
|
|
370
420
|
POST to that workflow's path with the trigger's input; no trigger identifier
|
|
371
421
|
appears in the URL.
|
|
372
422
|
|
|
423
|
+
## Public entry points
|
|
424
|
+
|
|
425
|
+
The package has two, and neither mirrors the source tree:
|
|
426
|
+
|
|
427
|
+
| Import | Provides |
|
|
428
|
+
| --- | --- |
|
|
429
|
+
| `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and `createTanStackWorkflowHandler` |
|
|
430
|
+
| `@lovable.dev/workflows-sdk/vite` | `workflowsPlugin`, the build-time Vite plugin |
|
|
431
|
+
|
|
432
|
+
The export map is a contract; the directory layout under `src/` is not. They are
|
|
433
|
+
deliberately decoupled, so the package can be reorganised without a breaking
|
|
434
|
+
change for apps that already have an emitted route.
|
|
435
|
+
|
|
436
|
+
The package sets `"sideEffects": false` and the handler is a plain re-export, so
|
|
437
|
+
a client bundle importing only authoring APIs drops the execution engine.
|
|
438
|
+
|
|
373
439
|
## Next PRs
|
|
374
440
|
|
|
375
441
|
Connect the manifest and app code to Lovable deployment and runtime execution.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AnyWorkflowDefinition, AnyWorkflowDefinition as AnyWorkflowDefinition$1, Ctx, StepContext, StepOptions, WorkflowDefinition, WorkflowInput, WorkflowInput as WorkflowInput$1, WorkflowOutput, WorkflowState, createMiddleware, createWorkflow } from "@tanstack/workflow-core";
|
|
1
|
+
import { AnyWorkflowDefinition, AnyWorkflowDefinition as AnyWorkflowDefinition$1, Ctx, RunStore, StepContext, StepOptions, WorkflowDefinition, WorkflowEvent, WorkflowInput, WorkflowInput as WorkflowInput$1, WorkflowOutput, WorkflowState, createMiddleware, createWorkflow } from "@tanstack/workflow-core";
|
|
2
2
|
//#region src/core/cadence.d.ts
|
|
3
3
|
type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
|
|
4
4
|
type Cadence = {
|
|
@@ -125,4 +125,33 @@ interface WorkflowManifest {
|
|
|
125
125
|
}
|
|
126
126
|
declare function generateManifests(definition: WorkflowsDefinition): Promise<WorkflowManifest[]>;
|
|
127
127
|
//#endregion
|
|
128
|
-
|
|
128
|
+
//#region src/stacks/tanstack/handlers.d.ts
|
|
129
|
+
/** The shape `registerWorkflows()` returns; only the list is needed to dispatch. */
|
|
130
|
+
interface WorkflowCollection {
|
|
131
|
+
readonly workflows: readonly AnyWorkflowDefinition$1[];
|
|
132
|
+
}
|
|
133
|
+
interface TanStackWorkflowHandlerOptions {
|
|
134
|
+
/** @default a process-local `inMemoryRunStore()`, lost on restart */
|
|
135
|
+
runStore?: RunStore;
|
|
136
|
+
/**
|
|
137
|
+
* Route parameter carrying the workflow ID.
|
|
138
|
+
* @default "workflowId"
|
|
139
|
+
*/
|
|
140
|
+
workflowIdParam?: string;
|
|
141
|
+
}
|
|
142
|
+
interface TanStackRouteCtx {
|
|
143
|
+
request: Request;
|
|
144
|
+
params?: Record<string, string | undefined>;
|
|
145
|
+
}
|
|
146
|
+
type TanStackWorkflowHandler = (ctx: TanStackRouteCtx) => Promise<Response>;
|
|
147
|
+
/** Build a TanStack Start `POST` handler serving every workflow in the collection. */
|
|
148
|
+
declare function createTanStackWorkflowHandler(collection: WorkflowCollection, options?: TanStackWorkflowHandlerOptions): TanStackWorkflowHandler;
|
|
149
|
+
//#endregion
|
|
150
|
+
//#region src/stacks/tanstack/sse.d.ts
|
|
151
|
+
/**
|
|
152
|
+
* Encode a workflow event stream as `text/event-stream`. Each event keeps its
|
|
153
|
+
* engine `type` as the SSE event name and its whole JSON as the data line.
|
|
154
|
+
*/
|
|
155
|
+
declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
|
|
156
|
+
//#endregion
|
|
157
|
+
export { type AnyWorkflowDefinition, type Cadence, type Ctx, type OverlapPolicy, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type StepContext, type StepOptions, type TanStackWorkflowHandler, type TanStackWorkflowHandlerOptions, type TriggerDefinition, type Weekday, type WorkflowCollection, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createMiddleware, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,100 @@
|
|
|
1
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
|
-
|
|
2
|
+
import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
|
|
3
|
+
//#region src/stacks/tanstack/sse.ts
|
|
4
|
+
const HEADERS = {
|
|
5
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
6
|
+
"cache-control": "no-cache, no-transform",
|
|
7
|
+
connection: "keep-alive",
|
|
8
|
+
"x-accel-buffering": "no"
|
|
9
|
+
};
|
|
10
|
+
function describe(error) {
|
|
11
|
+
return error instanceof Error ? error.message : String(error);
|
|
12
|
+
}
|
|
13
|
+
function frame(name, data) {
|
|
14
|
+
return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Encode a workflow event stream as `text/event-stream`. Each event keeps its
|
|
18
|
+
* engine `type` as the SSE event name and its whole JSON as the data line.
|
|
19
|
+
*/
|
|
20
|
+
function toServerSentEventsResponse(events) {
|
|
21
|
+
const encoder = new TextEncoder();
|
|
22
|
+
const body = new ReadableStream({ async start(controller) {
|
|
23
|
+
let connected = true;
|
|
24
|
+
const write = (text) => {
|
|
25
|
+
if (!connected) return;
|
|
26
|
+
try {
|
|
27
|
+
controller.enqueue(encoder.encode(text));
|
|
28
|
+
} catch {
|
|
29
|
+
connected = false;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
const send = (name, data) => {
|
|
33
|
+
try {
|
|
34
|
+
write(frame(name, data));
|
|
35
|
+
} catch (error) {
|
|
36
|
+
write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe(error)}` }));
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
try {
|
|
40
|
+
for await (const event of events) send(event.type, event);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
send("STREAM_ERRORED", { message: describe(error) });
|
|
43
|
+
} finally {
|
|
44
|
+
try {
|
|
45
|
+
controller.close();
|
|
46
|
+
} catch {
|
|
47
|
+
connected = false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
} });
|
|
51
|
+
return new Response(body, { headers: HEADERS });
|
|
52
|
+
}
|
|
53
|
+
//#endregion
|
|
54
|
+
//#region src/stacks/tanstack/handlers.ts
|
|
55
|
+
function json(status, body) {
|
|
56
|
+
return new Response(JSON.stringify(body), {
|
|
57
|
+
status,
|
|
58
|
+
headers: { "content-type": "application/json; charset=utf-8" }
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
function resolveWorkflowId(ctx, param) {
|
|
62
|
+
const fromParams = ctx.params?.[param];
|
|
63
|
+
if (fromParams) return fromParams;
|
|
64
|
+
return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
|
|
65
|
+
}
|
|
66
|
+
/** Build a TanStack Start `POST` handler serving every workflow in the collection. */
|
|
67
|
+
function createTanStackWorkflowHandler(collection, options = {}) {
|
|
68
|
+
const runStore = options.runStore ?? inMemoryRunStore();
|
|
69
|
+
const param = options.workflowIdParam ?? "workflowId";
|
|
70
|
+
const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
|
|
71
|
+
return async (ctx) => {
|
|
72
|
+
const workflowId = resolveWorkflowId(ctx, param);
|
|
73
|
+
const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
|
|
74
|
+
if (!workflow) return json(404, {
|
|
75
|
+
error: "unknown_workflow",
|
|
76
|
+
workflowId: workflowId ?? ""
|
|
77
|
+
});
|
|
78
|
+
let params;
|
|
79
|
+
try {
|
|
80
|
+
params = await parseWorkflowRequest(ctx.request);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (error instanceof WorkflowRequestParseError) return json(400, {
|
|
83
|
+
error: "invalid_request",
|
|
84
|
+
message: error.message
|
|
85
|
+
});
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
if (params.abort) return json(501, {
|
|
89
|
+
error: "abort_unsupported",
|
|
90
|
+
message: "Cancelling an in-flight run needs a shared run registry (WOR-53)."
|
|
91
|
+
});
|
|
92
|
+
return toServerSentEventsResponse(runWorkflow({
|
|
93
|
+
workflow,
|
|
94
|
+
runStore,
|
|
95
|
+
...params
|
|
96
|
+
}));
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
//#endregion
|
|
100
|
+
export { createMiddleware, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
|
package/dist/vite.d.ts
CHANGED
|
@@ -10,12 +10,10 @@ interface WorkflowsPluginOptions {
|
|
|
10
10
|
path?: string;
|
|
11
11
|
/** Route parameter carrying the workflow ID. @default "workflowId" */
|
|
12
12
|
workflowIdParam?: string;
|
|
13
|
-
/** @default false */
|
|
14
|
-
runRoute?: boolean;
|
|
15
13
|
}
|
|
16
14
|
/**
|
|
17
|
-
* Build the collection's manifests and
|
|
18
|
-
*
|
|
15
|
+
* Build the collection's manifests and emit the route serving them; one `entry`
|
|
16
|
+
* feeds both, so the two can never describe different sets.
|
|
19
17
|
*/
|
|
20
18
|
declare function workflowsPlugin(options?: WorkflowsPluginOptions): Plugin;
|
|
21
19
|
//#endregion
|
package/dist/vite.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as generateManifests } from "./generate-DyUHbtre.js";
|
|
2
|
-
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
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";
|
|
5
5
|
import { lstatSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
|
|
@@ -31,6 +31,101 @@ async function writeManifests(root, manifests) {
|
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
33
|
//#endregion
|
|
34
|
+
//#region src/vite/alias.ts
|
|
35
|
+
function normalize(path) {
|
|
36
|
+
return path.split(sep).join("/");
|
|
37
|
+
}
|
|
38
|
+
function parseTsconfig(text) {
|
|
39
|
+
const withoutComments = text.replace(/"(?:\\.|[^"\\])*"|(\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g, (match, comment) => comment ? "" : match);
|
|
40
|
+
return JSON.parse(withoutComments.replace(/,(\s*[}\]])/g, "$1"));
|
|
41
|
+
}
|
|
42
|
+
function isRecord(value) {
|
|
43
|
+
return typeof value === "object" && value !== null;
|
|
44
|
+
}
|
|
45
|
+
/** Wildcard `paths` entries (`"@/*": ["./src/*"]`), the only shape an emitted import can use. */
|
|
46
|
+
function tsconfigAliases(root, tsconfigPath = "tsconfig.json") {
|
|
47
|
+
let parsed;
|
|
48
|
+
try {
|
|
49
|
+
parsed = parseTsconfig(readFileSync(resolve(root, tsconfigPath), "utf8"));
|
|
50
|
+
} catch {
|
|
51
|
+
return [];
|
|
52
|
+
}
|
|
53
|
+
if (!isRecord(parsed)) return [];
|
|
54
|
+
const options = parsed.compilerOptions;
|
|
55
|
+
if (!isRecord(options)) return [];
|
|
56
|
+
const paths = options.paths;
|
|
57
|
+
if (!isRecord(paths)) return [];
|
|
58
|
+
const baseUrl = typeof options.baseUrl === "string" ? resolve(root, options.baseUrl) : root;
|
|
59
|
+
const entries = [];
|
|
60
|
+
for (const [pattern, targets] of Object.entries(paths)) {
|
|
61
|
+
if (!pattern.endsWith("/*") || !Array.isArray(targets)) continue;
|
|
62
|
+
const target = targets[0];
|
|
63
|
+
if (typeof target !== "string" || !target.endsWith("/*")) continue;
|
|
64
|
+
entries.push({
|
|
65
|
+
prefix: pattern.slice(0, -2),
|
|
66
|
+
dir: resolve(baseUrl, target.slice(0, -2)),
|
|
67
|
+
sources: {
|
|
68
|
+
vite: false,
|
|
69
|
+
tsconfig: true
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
return entries;
|
|
74
|
+
}
|
|
75
|
+
/** String-`find` entries of a resolved Vite `resolve.alias`; a regex alias cannot be re-emitted. */
|
|
76
|
+
function viteAliases(alias) {
|
|
77
|
+
if (!alias) return [];
|
|
78
|
+
const entries = [];
|
|
79
|
+
for (const { find, replacement } of alias) {
|
|
80
|
+
if (typeof find !== "string" || !find || !isAbsolute(replacement)) continue;
|
|
81
|
+
entries.push({
|
|
82
|
+
prefix: find.replace(/\/$/, ""),
|
|
83
|
+
dir: replacement.replace(/\/$/, ""),
|
|
84
|
+
sources: {
|
|
85
|
+
vite: true,
|
|
86
|
+
tsconfig: false
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return entries;
|
|
91
|
+
}
|
|
92
|
+
function merge(entries) {
|
|
93
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
94
|
+
for (const entry of entries) {
|
|
95
|
+
const key = `${entry.prefix}::${normalize(entry.dir)}`;
|
|
96
|
+
const existing = byKey.get(key);
|
|
97
|
+
if (existing) {
|
|
98
|
+
existing.sources.vite ||= entry.sources.vite;
|
|
99
|
+
existing.sources.tsconfig ||= entry.sources.tsconfig;
|
|
100
|
+
} else byKey.set(key, {
|
|
101
|
+
...entry,
|
|
102
|
+
sources: { ...entry.sources }
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
return [...byKey.values()];
|
|
106
|
+
}
|
|
107
|
+
function contains(dir, file) {
|
|
108
|
+
return normalize(file).startsWith(`${normalize(dir)}/`);
|
|
109
|
+
}
|
|
110
|
+
function score(entry) {
|
|
111
|
+
if (entry.sources.vite && entry.sources.tsconfig) return 2;
|
|
112
|
+
return entry.sources.vite ? 1 : 0;
|
|
113
|
+
}
|
|
114
|
+
function isResolvable(entry, tsconfigPathsPlugin) {
|
|
115
|
+
return entry.sources.vite || tsconfigPathsPlugin;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The aliased specifier for `target`, or `undefined` when no alias resolves it.
|
|
119
|
+
* Prefers an alias both sources agree on, then the deepest directory.
|
|
120
|
+
*/
|
|
121
|
+
function aliasedSpecifier(target, entries, tsconfigPathsPlugin = false) {
|
|
122
|
+
const matches = merge(entries).filter((entry) => contains(entry.dir, target) && isResolvable(entry, tsconfigPathsPlugin));
|
|
123
|
+
if (matches.length === 0) return void 0;
|
|
124
|
+
matches.sort((a, b) => score(b) - score(a) || normalize(b.dir).length - normalize(a.dir).length);
|
|
125
|
+
const best = matches[0];
|
|
126
|
+
return `${best.prefix}/${normalize(relative(best.dir, target)).replace(/\.tsx?$/, "")}`;
|
|
127
|
+
}
|
|
128
|
+
//#endregion
|
|
34
129
|
//#region src/vite/route-emitter.ts
|
|
35
130
|
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
131
|
function isFileMissing(error) {
|
|
@@ -61,17 +156,21 @@ function relativeImportSpecifier(routeFile, target) {
|
|
|
61
156
|
const withoutExt = normalizePath(relative(dirname(routeFile), target)).replace(/\.tsx?$/, "");
|
|
62
157
|
return withoutExt.startsWith(".") ? withoutExt : `./${withoutExt}`;
|
|
63
158
|
}
|
|
64
|
-
function
|
|
159
|
+
function collectionSpecifier(routeFile, entry, aliases, tsconfigPathsPlugin) {
|
|
160
|
+
return aliasedSpecifier(entry, aliases, tsconfigPathsPlugin) ?? relativeImportSpecifier(routeFile, entry);
|
|
161
|
+
}
|
|
162
|
+
function buildRouteSource(routeFile, routeLiteral, param, specifier, root) {
|
|
65
163
|
return `${GENERATED_BANNER}
|
|
66
164
|
// route: ${routeLiteral}
|
|
67
165
|
// emitted to: ${normalizePath(relative(root, routeFile))}
|
|
68
|
-
// This route is unauthenticated: any caller can run any declared
|
|
166
|
+
// This route is unauthenticated: any caller who reaches it can run any declared
|
|
167
|
+
// workflow. Signed invocation is not available yet.
|
|
69
168
|
|
|
70
169
|
import { createFileRoute } from "@tanstack/react-router";
|
|
71
170
|
|
|
72
|
-
import { createTanStackWorkflowHandler } from "@lovable.dev/workflows-sdk
|
|
171
|
+
import { createTanStackWorkflowHandler } from "@lovable.dev/workflows-sdk";
|
|
73
172
|
|
|
74
|
-
import workflows from "${
|
|
173
|
+
import workflows from "${specifier}";
|
|
75
174
|
|
|
76
175
|
export const Route = createFileRoute("${routeLiteral}")({
|
|
77
176
|
server: {
|
|
@@ -135,10 +234,14 @@ function createRouteEmitter(options) {
|
|
|
135
234
|
let entry = resolve(root, options.entry);
|
|
136
235
|
let routesDir = resolve(root, options.routesDir);
|
|
137
236
|
let routeFile = resolve(routesDir, routeFileName);
|
|
237
|
+
let aliases = [];
|
|
238
|
+
let tsconfigPathsPlugin = false;
|
|
138
239
|
return {
|
|
139
240
|
entryPath: () => entry,
|
|
140
|
-
setRoot(next) {
|
|
241
|
+
setRoot(next, context) {
|
|
141
242
|
root = next;
|
|
243
|
+
aliases = [...viteAliases(context?.alias), ...tsconfigAliases(next)];
|
|
244
|
+
tsconfigPathsPlugin = context?.tsconfigPathsPlugin === true;
|
|
142
245
|
entry = resolve(root, options.entry);
|
|
143
246
|
assertContains(root, entry, `entry "${options.entry}"`);
|
|
144
247
|
routesDir = resolve(root, options.routesDir);
|
|
@@ -155,9 +258,10 @@ function createRouteEmitter(options) {
|
|
|
155
258
|
entryExists = false;
|
|
156
259
|
}
|
|
157
260
|
const expected = /* @__PURE__ */ new Set();
|
|
158
|
-
if (entryExists
|
|
261
|
+
if (entryExists) {
|
|
159
262
|
expected.add(routeFile);
|
|
160
|
-
|
|
263
|
+
const specifier = collectionSpecifier(routeFile, entry, aliases, tsconfigPathsPlugin);
|
|
264
|
+
writeIfChanged(routeFile, buildRouteSource(routeFile, routeLiteral, param, specifier, root));
|
|
161
265
|
}
|
|
162
266
|
for (const file of findAdoptedFiles(routesDir)) {
|
|
163
267
|
if (expected.has(file)) continue;
|
|
@@ -172,9 +276,10 @@ function createRouteEmitter(options) {
|
|
|
172
276
|
}
|
|
173
277
|
//#endregion
|
|
174
278
|
//#region src/vite/plugin.ts
|
|
279
|
+
const TSCONFIG_PATHS_PLUGINS = /* @__PURE__ */ new Set(["vite-tsconfig-paths", "vite-plugin-tsconfig-paths"]);
|
|
175
280
|
/**
|
|
176
|
-
* Build the collection's manifests and
|
|
177
|
-
*
|
|
281
|
+
* Build the collection's manifests and emit the route serving them; one `entry`
|
|
282
|
+
* feeds both, so the two can never describe different sets.
|
|
178
283
|
*/
|
|
179
284
|
function workflowsPlugin(options = {}) {
|
|
180
285
|
const entry = options.entry ?? "src/lib/workflows/index.ts";
|
|
@@ -182,15 +287,17 @@ function workflowsPlugin(options = {}) {
|
|
|
182
287
|
entry,
|
|
183
288
|
routesDir: options.routesDir ?? "src/routes",
|
|
184
289
|
path: options.path ?? "/api/workflows",
|
|
185
|
-
workflowIdParam: options.workflowIdParam ?? "workflowId"
|
|
186
|
-
runRoute: options.runRoute === true
|
|
290
|
+
workflowIdParam: options.workflowIdParam ?? "workflowId"
|
|
187
291
|
});
|
|
188
292
|
let config;
|
|
189
293
|
return {
|
|
190
294
|
name: "@lovable.dev/workflows-sdk",
|
|
191
295
|
configResolved(resolved) {
|
|
192
296
|
config = resolved;
|
|
193
|
-
emitter.setRoot(config.root
|
|
297
|
+
emitter.setRoot(config.root, {
|
|
298
|
+
alias: config.resolve.alias,
|
|
299
|
+
tsconfigPathsPlugin: config.plugins.some((plugin) => TSCONFIG_PATHS_PLUGINS.has(plugin.name))
|
|
300
|
+
});
|
|
194
301
|
emitter.regenerate();
|
|
195
302
|
},
|
|
196
303
|
configureServer(server) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lovable.dev/workflows-sdk",
|
|
3
|
-
"version": "0.0.0-dev.
|
|
3
|
+
"version": "0.0.0-dev.8",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"tag": "dev",
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
},
|
|
9
9
|
"description": "Author workflows for Lovable apps.",
|
|
10
10
|
"type": "module",
|
|
11
|
+
"sideEffects": false,
|
|
11
12
|
"repository": {
|
|
12
13
|
"type": "git",
|
|
13
14
|
"url": "git+https://github.com/lovablelabs/lovable.git",
|
|
@@ -22,10 +23,6 @@
|
|
|
22
23
|
"./vite": {
|
|
23
24
|
"types": "./dist/vite.d.ts",
|
|
24
25
|
"import": "./dist/vite.js"
|
|
25
|
-
},
|
|
26
|
-
"./stacks/tanstack": {
|
|
27
|
-
"types": "./dist/stacks/tanstack/index.d.ts",
|
|
28
|
-
"import": "./dist/stacks/tanstack/index.js"
|
|
29
26
|
}
|
|
30
27
|
},
|
|
31
28
|
"files": [
|
|
@@ -1,31 +0,0 @@
|
|
|
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 };
|
|
@@ -1,99 +0,0 @@
|
|
|
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 };
|