@lovable.dev/workflows-sdk 0.0.0-dev.7 → 0.0.0-dev.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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,7 +156,24 @@ 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 buildRouteSource(routeFile, routeLiteral, param, entry, root) {
159
+ function collectionSpecifier(routeFile, entry, aliases, tsconfigPathsPlugin) {
160
+ return aliasedSpecifier(entry, aliases, tsconfigPathsPlugin) ?? relativeImportSpecifier(routeFile, entry);
161
+ }
162
+ const SURFACES = [
163
+ {
164
+ segment: "",
165
+ factory: "createRunHandler"
166
+ },
167
+ {
168
+ segment: "nextSteps",
169
+ factory: "createNextStepsHandler"
170
+ },
171
+ {
172
+ segment: "executeSteps",
173
+ factory: "createExecuteStepsHandler"
174
+ }
175
+ ];
176
+ function buildRouteSource(routeFile, routeLiteral, param, specifier, root, factory) {
65
177
  return `${GENERATED_BANNER}
66
178
  // route: ${routeLiteral}
67
179
  // emitted to: ${normalizePath(relative(root, routeFile))}
@@ -70,14 +182,14 @@ function buildRouteSource(routeFile, routeLiteral, param, entry, root) {
70
182
 
71
183
  import { createFileRoute } from "@tanstack/react-router";
72
184
 
73
- import { createTanStackWorkflowHandler } from "@lovable.dev/workflows-sdk/stacks/tanstack";
185
+ import { ${factory} } from "@lovable.dev/workflows-sdk";
74
186
 
75
- import workflows from "${relativeImportSpecifier(routeFile, entry)}";
187
+ import workflows from "${specifier}";
76
188
 
77
189
  export const Route = createFileRoute("${routeLiteral}")({
78
190
  server: {
79
191
  handlers: {
80
- POST: createTanStackWorkflowHandler(workflows, { workflowIdParam: "${param}" }),
192
+ POST: ${factory}(workflows, { workflowIdParam: "${param}" }),
81
193
  },
82
194
  },
83
195
  });
@@ -130,22 +242,30 @@ function findAdoptedFiles(routesDir) {
130
242
  function createRouteEmitter(options) {
131
243
  const param = assertParamShape(options.workflowIdParam);
132
244
  const pathSegments = assertUrlPathShape(options.path);
133
- const routeLiteral = `/${pathSegments}/$${param}`;
134
- const routeFileName = join(...pathSegments.split("/"), `$${param}.ts`);
245
+ const base = `/${pathSegments}/$${param}`;
246
+ const surfaces = SURFACES.map((surface) => ({
247
+ ...surface,
248
+ literal: surface.segment ? `${base}/${surface.segment}` : base,
249
+ fileName: surface.segment ? join(...pathSegments.split("/"), `$${param}`, `${surface.segment}.ts`) : join(...pathSegments.split("/"), `$${param}.ts`)
250
+ }));
135
251
  let root = process.cwd();
136
252
  let entry = resolve(root, options.entry);
137
253
  let routesDir = resolve(root, options.routesDir);
138
- let routeFile = resolve(routesDir, routeFileName);
254
+ let routeFiles = surfaces.map((surface) => resolve(routesDir, surface.fileName));
255
+ let aliases = [];
256
+ let tsconfigPathsPlugin = false;
139
257
  return {
140
258
  entryPath: () => entry,
141
- setRoot(next) {
259
+ setRoot(next, context) {
142
260
  root = next;
261
+ aliases = [...viteAliases(context?.alias), ...tsconfigAliases(next)];
262
+ tsconfigPathsPlugin = context?.tsconfigPathsPlugin === true;
143
263
  entry = resolve(root, options.entry);
144
264
  assertContains(root, entry, `entry "${options.entry}"`);
145
265
  routesDir = resolve(root, options.routesDir);
146
266
  assertContains(root, routesDir, `routesDir "${options.routesDir}"`);
147
- routeFile = resolve(routesDir, routeFileName);
148
- assertContains(routesDir, routeFile, `path "${routeLiteral}"`);
267
+ routeFiles = surfaces.map((surface) => resolve(routesDir, surface.fileName));
268
+ routeFiles.forEach((file, index) => assertContains(routesDir, file, `path "${surfaces[index].literal}"`));
149
269
  },
150
270
  regenerate() {
151
271
  let entryExists = true;
@@ -156,10 +276,12 @@ function createRouteEmitter(options) {
156
276
  entryExists = false;
157
277
  }
158
278
  const expected = /* @__PURE__ */ new Set();
159
- if (entryExists) {
160
- expected.add(routeFile);
161
- writeIfChanged(routeFile, buildRouteSource(routeFile, routeLiteral, param, entry, root));
162
- }
279
+ if (entryExists) surfaces.forEach((surface, index) => {
280
+ const file = routeFiles[index];
281
+ expected.add(file);
282
+ const specifier = collectionSpecifier(file, entry, aliases, tsconfigPathsPlugin);
283
+ writeIfChanged(file, buildRouteSource(file, surface.literal, param, specifier, root, surface.factory));
284
+ });
163
285
  for (const file of findAdoptedFiles(routesDir)) {
164
286
  if (expected.has(file)) continue;
165
287
  try {
@@ -173,6 +295,7 @@ function createRouteEmitter(options) {
173
295
  }
174
296
  //#endregion
175
297
  //#region src/vite/plugin.ts
298
+ const TSCONFIG_PATHS_PLUGINS = /* @__PURE__ */ new Set(["vite-tsconfig-paths", "vite-plugin-tsconfig-paths"]);
176
299
  /**
177
300
  * Build the collection's manifests and emit the route serving them; one `entry`
178
301
  * feeds both, so the two can never describe different sets.
@@ -190,7 +313,10 @@ function workflowsPlugin(options = {}) {
190
313
  name: "@lovable.dev/workflows-sdk",
191
314
  configResolved(resolved) {
192
315
  config = resolved;
193
- emitter.setRoot(config.root);
316
+ emitter.setRoot(config.root, {
317
+ alias: config.resolve.alias,
318
+ tsconfigPathsPlugin: config.plugins.some((plugin) => TSCONFIG_PATHS_PLUGINS.has(plugin.name))
319
+ });
194
320
  emitter.regenerate();
195
321
  },
196
322
  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.7",
3
+ "version": "0.0.0-dev.9",
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 };