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

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.
@@ -0,0 +1,54 @@
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-Ci7cGckB.js";
2
+ //#region src/manifests/nested-operations.ts
3
+ const durableMethods = [
4
+ "step",
5
+ "approve",
6
+ "waitForEvent",
7
+ "sleep",
8
+ "sleepUntil",
9
+ "now",
10
+ "uuid"
11
+ ];
12
+ async function findNestedDurableOperations(handler) {
13
+ const api = await loadTypeScript();
14
+ if (!api) return [];
15
+ const ts = api;
16
+ const handlerSource = workflowHandlerSource(handler);
17
+ if (!handlerSource) return [];
18
+ const declaration = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS).statements[0];
19
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
20
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return [];
21
+ const parameter = fn.parameters[0]?.name;
22
+ if (!parameter || !ts.isIdentifier(parameter)) return [];
23
+ const context = parameter.text;
24
+ function methodOf(node) {
25
+ if (!ts.isCallExpression(node)) return void 0;
26
+ const expression = node.expression;
27
+ let name;
28
+ if (ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === context) name = expression.name.text;
29
+ else if (ts.isElementAccessExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === context && expression.argumentExpression && (ts.isStringLiteral(expression.argumentExpression) || ts.isNoSubstitutionTemplateLiteral(expression.argumentExpression))) name = expression.argumentExpression.text;
30
+ return durableMethods.find((method) => method === name);
31
+ }
32
+ function stepIdOf(node) {
33
+ const argument = node.arguments[0];
34
+ return argument && (ts.isStringLiteral(argument) || ts.isNoSubstitutionTemplateLiteral(argument)) ? argument.text : void 0;
35
+ }
36
+ const nested = [];
37
+ const visit = (node, parentStepId) => {
38
+ const method = methodOf(node);
39
+ if (method && parentStepId !== void 0) nested.push({
40
+ method,
41
+ parentStepId
42
+ });
43
+ if (method === "step" && ts.isCallExpression(node)) {
44
+ visit(node.expression, parentStepId);
45
+ node.arguments.forEach((argument, index) => visit(argument, index === 1 ? stepIdOf(node) ?? "" : parentStepId));
46
+ return;
47
+ }
48
+ ts.forEachChild(node, (child) => visit(child, parentStepId));
49
+ };
50
+ visit(fn);
51
+ return nested;
52
+ }
53
+ //#endregion
54
+ export { findNestedDurableOperations };
@@ -0,0 +1,46 @@
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-Ci7cGckB.js";
2
+ //#region src/manifests/operation-descriptions.ts
3
+ const optionsArgument = {
4
+ approve: 0,
5
+ sleep: 1,
6
+ sleepUntil: 1,
7
+ waitForEvent: 1,
8
+ now: 0,
9
+ uuid: 0
10
+ };
11
+ async function findOperationDescriptionIssues(handler) {
12
+ const api = await loadTypeScript();
13
+ if (!api) return [];
14
+ const ts = api;
15
+ const handlerSource = workflowHandlerSource(handler);
16
+ if (!handlerSource) return [];
17
+ const declaration = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS).statements[0];
18
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
19
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return [];
20
+ const parameter = fn.parameters[0]?.name;
21
+ if (!parameter || !ts.isIdentifier(parameter)) return [];
22
+ const context = parameter.text;
23
+ function literalString(node) {
24
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
25
+ }
26
+ function property(node, name) {
27
+ if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
28
+ for (const entry of node.properties) {
29
+ if (!ts.isPropertyAssignment(entry)) continue;
30
+ if ((ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name) ? entry.name.text : void 0) === name) return entry.initializer;
31
+ }
32
+ }
33
+ const issues = [];
34
+ const visit = (node) => {
35
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text in optionsArgument) {
36
+ const method = node.expression.name.text;
37
+ const options = node.arguments[optionsArgument[method]];
38
+ if ((method === "approve" ? literalString(property(options, "description")) : literalString(property(property(options, "meta"), "description"))) === void 0) issues.push({ method });
39
+ }
40
+ ts.forEachChild(node, visit);
41
+ };
42
+ visit(fn);
43
+ return issues;
44
+ }
45
+ //#endregion
46
+ export { findOperationDescriptionIssues };
@@ -0,0 +1,101 @@
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-Ci7cGckB.js";
2
+ //#region src/manifests/step-metadata.ts
3
+ async function findStepMetadataIssues(handler) {
4
+ const api = await loadTypeScript();
5
+ if (!api) return [];
6
+ const ts = api;
7
+ const handlerSource = workflowHandlerSource(handler);
8
+ if (!handlerSource) return [];
9
+ const declaration = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS).statements[0];
10
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
11
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return [];
12
+ const parameter = fn.parameters[0]?.name;
13
+ if (!parameter || !ts.isIdentifier(parameter)) return [];
14
+ const context = parameter.text;
15
+ function literalString(node) {
16
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
17
+ }
18
+ function property(node, name) {
19
+ if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
20
+ for (const entry of node.properties) {
21
+ if (!ts.isPropertyAssignment(entry)) continue;
22
+ if ((ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name) ? entry.name.text : void 0) === name) return entry.initializer;
23
+ }
24
+ }
25
+ function repeatedLoopRegion(parent, child) {
26
+ if (ts.isForOfStatement(parent) || ts.isForInStatement(parent)) return parent.statement === child;
27
+ if (ts.isForStatement(parent)) return parent.statement === child || parent.condition === child || parent.incrementor === child;
28
+ return ts.isWhileStatement(parent) || ts.isDoStatement(parent);
29
+ }
30
+ function repeatable(call) {
31
+ let child = call;
32
+ let parent = call.parent;
33
+ while (parent && parent !== fn) {
34
+ if (repeatedLoopRegion(parent, child) || ts.isFunctionLike(parent)) return true;
35
+ child = parent;
36
+ parent = parent.parent;
37
+ }
38
+ return false;
39
+ }
40
+ function loopAncestors(call) {
41
+ const loops = [];
42
+ let child = call;
43
+ let parent = call.parent;
44
+ while (parent && parent !== fn) {
45
+ if (repeatedLoopRegion(parent, child)) loops.push(parent);
46
+ child = parent;
47
+ parent = parent.parent;
48
+ }
49
+ return loops;
50
+ }
51
+ function isDirectSequentialLoopStep(loop, call) {
52
+ if (!ts.isForOfStatement(loop) || loop.awaitModifier || !ts.isVariableDeclarationList(loop.initializer)) return false;
53
+ const declarations = loop.initializer.declarations;
54
+ if (declarations.length !== 1 || !ts.isIdentifier(declarations[0].name) || declarations[0].initializer) return false;
55
+ let statement = loop.statement;
56
+ if (ts.isBlock(statement)) statement = statement.statements.length === 1 ? statement.statements[0] : void 0;
57
+ if (!statement || !ts.isExpressionStatement(statement)) return false;
58
+ let expression = statement.expression;
59
+ while (ts.isParenthesizedExpression(expression)) expression = expression.expression;
60
+ if (!ts.isAwaitExpression(expression)) return false;
61
+ let awaited = expression.expression;
62
+ while (ts.isParenthesizedExpression(awaited)) awaited = awaited.expression;
63
+ return awaited === call;
64
+ }
65
+ const issues = [];
66
+ const groups = /* @__PURE__ */ new Set();
67
+ const visit = (node) => {
68
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text === "step") {
69
+ const stepId = literalString(node.arguments[0]);
70
+ const loops = loopAncestors(node);
71
+ if (loops.length > 0 && (loops.length !== 1 || !isDirectSequentialLoopStep(loops[0], node))) issues.push({
72
+ kind: "loop-form",
73
+ ...stepId === void 0 ? {} : { stepId }
74
+ });
75
+ const meta = property(node.arguments[2], "meta");
76
+ if (literalString(property(meta, "description")) === void 0) issues.push({
77
+ kind: "description",
78
+ ...stepId === void 0 ? {} : { stepId }
79
+ });
80
+ if (repeatable(node)) {
81
+ const group = property(meta, "group");
82
+ const groupId = literalString(property(group, "id"));
83
+ const label = literalString(property(group, "label"));
84
+ if (groupId === void 0 || label === void 0) issues.push({
85
+ kind: "group",
86
+ ...stepId === void 0 ? {} : { stepId }
87
+ });
88
+ else if (groups.has(groupId)) issues.push({
89
+ kind: "duplicate-group",
90
+ groupId
91
+ });
92
+ else groups.add(groupId);
93
+ }
94
+ }
95
+ ts.forEachChild(node, visit);
96
+ };
97
+ visit(fn);
98
+ return issues;
99
+ }
100
+ //#endregion
101
+ export { findStepMetadataIssues };
package/dist/vite.d.ts CHANGED
@@ -1,7 +1,20 @@
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
+ }
14
+ /**
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.
17
+ */
18
+ declare function workflowsPlugin(options?: WorkflowsPluginOptions): Plugin;
6
19
  //#endregion
7
- export { workflowsManifest };
20
+ export { type WorkflowsPluginOptions, workflowsPlugin };
package/dist/vite.js CHANGED
@@ -1,7 +1,8 @@
1
- import { t as generateManifests } from "./generate-IXn3QGVb.js";
2
- import { join, resolve } from "node:path";
1
+ import { t as generateManifests } from "./generate-BIqGbMQO.js";
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
+ 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 {
@@ -17,9 +18,10 @@ async function writeManifests(root, manifests) {
17
18
  const directory = join(lovable, "workflows");
18
19
  await ensureDirectory(directory);
19
20
  const staging = await mkdtemp(join(directory, ".tmp-"));
20
- const names = new Set(manifests.map((manifest) => `${manifest.workflow.id}.json`));
21
+ const nameOf = (manifest) => `${manifest.workflowId}.${manifest.workflowVersion}.json`;
22
+ const names = new Set(manifests.map(nameOf));
21
23
  try {
22
- for (const manifest of manifests) await writeFile(join(staging, `${manifest.workflow.id}.json`), JSON.stringify(manifest, null, 2) + "\n");
24
+ for (const manifest of manifests) await writeFile(join(staging, nameOf(manifest)), JSON.stringify(manifest, null, 2) + "\n");
23
25
  for (const name of names) await rename(join(staging, name), join(directory, name));
24
26
  for (const entry of await readdir(directory, { withFileTypes: true })) if (entry.name.endsWith(".json") && !names.has(entry.name) && !entry.isDirectory()) await rm(join(directory, entry.name), { force: true });
25
27
  } finally {
@@ -30,14 +32,296 @@ async function writeManifests(root, manifests) {
30
32
  }
31
33
  }
32
34
  //#endregion
35
+ //#region src/vite/alias.ts
36
+ function normalize(path) {
37
+ return path.split(sep).join("/");
38
+ }
39
+ function parseTsconfig(text) {
40
+ const withoutComments = text.replace(/"(?:\\.|[^"\\])*"|(\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g, (match, comment) => comment ? "" : match);
41
+ return JSON.parse(withoutComments.replace(/,(\s*[}\]])/g, "$1"));
42
+ }
43
+ function isRecord(value) {
44
+ return typeof value === "object" && value !== null;
45
+ }
46
+ /** Wildcard `paths` entries (`"@/*": ["./src/*"]`), the only shape an emitted import can use. */
47
+ function tsconfigAliases(root, tsconfigPath = "tsconfig.json") {
48
+ let parsed;
49
+ try {
50
+ parsed = parseTsconfig(readFileSync(resolve(root, tsconfigPath), "utf8"));
51
+ } catch {
52
+ return [];
53
+ }
54
+ if (!isRecord(parsed)) return [];
55
+ const options = parsed.compilerOptions;
56
+ if (!isRecord(options)) return [];
57
+ const paths = options.paths;
58
+ if (!isRecord(paths)) return [];
59
+ const baseUrl = typeof options.baseUrl === "string" ? resolve(root, options.baseUrl) : root;
60
+ const entries = [];
61
+ for (const [pattern, targets] of Object.entries(paths)) {
62
+ if (!pattern.endsWith("/*") || !Array.isArray(targets)) continue;
63
+ const target = targets[0];
64
+ if (typeof target !== "string" || !target.endsWith("/*")) continue;
65
+ entries.push({
66
+ prefix: pattern.slice(0, -2),
67
+ dir: resolve(baseUrl, target.slice(0, -2)),
68
+ sources: {
69
+ vite: false,
70
+ tsconfig: true
71
+ }
72
+ });
73
+ }
74
+ return entries;
75
+ }
76
+ /** String-`find` entries of a resolved Vite `resolve.alias`; a regex alias cannot be re-emitted. */
77
+ function viteAliases(alias) {
78
+ if (!alias) return [];
79
+ const entries = [];
80
+ for (const { find, replacement } of alias) {
81
+ if (typeof find !== "string" || !find || !isAbsolute(replacement)) continue;
82
+ entries.push({
83
+ prefix: find.replace(/\/$/, ""),
84
+ dir: replacement.replace(/\/$/, ""),
85
+ sources: {
86
+ vite: true,
87
+ tsconfig: false
88
+ }
89
+ });
90
+ }
91
+ return entries;
92
+ }
93
+ function merge(entries) {
94
+ const byKey = /* @__PURE__ */ new Map();
95
+ for (const entry of entries) {
96
+ const key = `${entry.prefix}::${normalize(entry.dir)}`;
97
+ const existing = byKey.get(key);
98
+ if (existing) {
99
+ existing.sources.vite ||= entry.sources.vite;
100
+ existing.sources.tsconfig ||= entry.sources.tsconfig;
101
+ } else byKey.set(key, {
102
+ ...entry,
103
+ sources: { ...entry.sources }
104
+ });
105
+ }
106
+ return [...byKey.values()];
107
+ }
108
+ function contains(dir, file) {
109
+ return normalize(file).startsWith(`${normalize(dir)}/`);
110
+ }
111
+ function score(entry) {
112
+ if (entry.sources.vite && entry.sources.tsconfig) return 2;
113
+ return entry.sources.vite ? 1 : 0;
114
+ }
115
+ function isResolvable(entry, tsconfigPathsPlugin) {
116
+ return entry.sources.vite || tsconfigPathsPlugin;
117
+ }
118
+ /**
119
+ * The aliased specifier for `target`, or `undefined` when no alias resolves it.
120
+ * Prefers an alias both sources agree on, then the deepest directory.
121
+ */
122
+ function aliasedSpecifier(target, entries, tsconfigPathsPlugin = false) {
123
+ const matches = merge(entries).filter((entry) => contains(entry.dir, target) && isResolvable(entry, tsconfigPathsPlugin));
124
+ if (matches.length === 0) return void 0;
125
+ matches.sort((a, b) => score(b) - score(a) || normalize(b.dir).length - normalize(a.dir).length);
126
+ const best = matches[0];
127
+ return `${best.prefix}/${normalize(relative(best.dir, target)).replace(/\.tsx?$/, "")}`;
128
+ }
129
+ //#endregion
130
+ //#region src/vite/route-emitter.ts
131
+ 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.";
132
+ function isFileMissing(error) {
133
+ const code = error?.code;
134
+ return code === "ENOENT" || code === "ENOTDIR";
135
+ }
136
+ function normalizePath(path) {
137
+ return path.split(sep).join("/");
138
+ }
139
+ function assertContains(parent, child, label) {
140
+ const from = normalizePath(parent).replace(/\/$/, "");
141
+ const to = normalizePath(child);
142
+ if (to !== from && !to.startsWith(`${from}/`)) throw new Error(`@lovable.dev/workflows-sdk: ${label} must resolve under ${from}, got ${to}`);
143
+ }
144
+ function assertUrlPathShape(urlPath) {
145
+ if (!urlPath.startsWith("/")) throw new Error(`@lovable.dev/workflows-sdk: path must start with "/", got "${urlPath}"`);
146
+ if (/\/{2,}/.test(urlPath)) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" contains empty segments ("//")`);
147
+ const trimmed = urlPath.replace(/^\/+/, "").replace(/\/+$/, "");
148
+ if (!trimmed) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" has no route segment`);
149
+ if (!/^[a-zA-Z0-9_\-/]+$/.test(trimmed)) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" contains unsupported characters`);
150
+ return trimmed;
151
+ }
152
+ function assertParamShape(param) {
153
+ if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(param)) throw new Error(`@lovable.dev/workflows-sdk: workflowIdParam "${param}" must be a JavaScript identifier`);
154
+ return param;
155
+ }
156
+ function relativeImportSpecifier(routeFile, target) {
157
+ const withoutExt = normalizePath(relative(dirname(routeFile), target)).replace(/\.tsx?$/, "");
158
+ return withoutExt.startsWith(".") ? withoutExt : `./${withoutExt}`;
159
+ }
160
+ function collectionSpecifier(routeFile, entry, aliases, tsconfigPathsPlugin) {
161
+ return aliasedSpecifier(entry, aliases, tsconfigPathsPlugin) ?? relativeImportSpecifier(routeFile, entry);
162
+ }
163
+ const SURFACES = [{
164
+ segment: "steps",
165
+ factory: "createStepsHandler"
166
+ }];
167
+ function buildRouteSource(routeFile, routeLiteral, param, specifier, root, factory) {
168
+ return `${GENERATED_BANNER}
169
+ // route: ${routeLiteral}
170
+ // emitted to: ${normalizePath(relative(root, routeFile))}
171
+
172
+ import { createFileRoute } from "@tanstack/react-router";
173
+
174
+ import { ${factory} } from "@lovable.dev/workflows-sdk";
175
+
176
+ import workflows from "${specifier}";
177
+
178
+ export const Route = createFileRoute("${routeLiteral}")({
179
+ server: {
180
+ handlers: {
181
+ POST: ${factory}(workflows, { workflowIdParam: "${param}" }),
182
+ },
183
+ },
184
+ });
185
+ `;
186
+ }
187
+ function hasGeneratedBanner(content) {
188
+ return content.replace(/\r\n/g, "\n").startsWith(GENERATED_BANNER);
189
+ }
190
+ function writeIfChanged(file, content) {
191
+ let existing;
192
+ try {
193
+ existing = readFileSync(file, "utf8");
194
+ } catch (error) {
195
+ if (!isFileMissing(error)) throw error;
196
+ }
197
+ if (existing !== void 0 && (!hasGeneratedBanner(existing) || existing === content)) return;
198
+ mkdirSync(dirname(file), { recursive: true });
199
+ writeFileSync(file, content, "utf8");
200
+ }
201
+ function findAdoptedFiles(routesDir) {
202
+ const adopted = [];
203
+ const visit = (dir) => {
204
+ let entries;
205
+ try {
206
+ entries = readdirSync(dir);
207
+ } catch (error) {
208
+ if (isFileMissing(error)) return;
209
+ throw error;
210
+ }
211
+ for (const entry of entries) {
212
+ const full = join(dir, entry);
213
+ let stat;
214
+ try {
215
+ stat = lstatSync(full);
216
+ } catch (error) {
217
+ if (isFileMissing(error)) continue;
218
+ throw error;
219
+ }
220
+ if (stat.isDirectory()) visit(full);
221
+ else if (entry.endsWith(".ts")) try {
222
+ if (hasGeneratedBanner(readFileSync(full, "utf8"))) adopted.push(full);
223
+ } catch (error) {
224
+ if (!isFileMissing(error)) throw error;
225
+ }
226
+ }
227
+ };
228
+ visit(routesDir);
229
+ return adopted;
230
+ }
231
+ function createRouteEmitter(options) {
232
+ const param = assertParamShape(options.workflowIdParam);
233
+ const pathSegments = assertUrlPathShape(options.path);
234
+ const base = `/${pathSegments}/$${param}`;
235
+ const surfaces = SURFACES.map((surface) => ({
236
+ ...surface,
237
+ literal: surface.segment ? `${base}/${surface.segment}` : base,
238
+ fileName: surface.segment ? join(...pathSegments.split("/"), `$${param}`, `${surface.segment}.ts`) : join(...pathSegments.split("/"), `$${param}.ts`)
239
+ }));
240
+ let root = process.cwd();
241
+ let entry = resolve(root, options.entry);
242
+ let routesDir = resolve(root, options.routesDir);
243
+ let routeFiles = surfaces.map((surface) => resolve(routesDir, surface.fileName));
244
+ let aliases = [];
245
+ let tsconfigPathsPlugin = false;
246
+ return {
247
+ entryPath: () => entry,
248
+ setRoot(next, context) {
249
+ root = next;
250
+ aliases = [...viteAliases(context?.alias), ...tsconfigAliases(next)];
251
+ tsconfigPathsPlugin = context?.tsconfigPathsPlugin === true;
252
+ entry = resolve(root, options.entry);
253
+ assertContains(root, entry, `entry "${options.entry}"`);
254
+ routesDir = resolve(root, options.routesDir);
255
+ assertContains(root, routesDir, `routesDir "${options.routesDir}"`);
256
+ routeFiles = surfaces.map((surface) => resolve(routesDir, surface.fileName));
257
+ routeFiles.forEach((file, index) => assertContains(routesDir, file, `path "${surfaces[index].literal}"`));
258
+ },
259
+ regenerate() {
260
+ let entryExists = true;
261
+ try {
262
+ lstatSync(entry);
263
+ } catch (error) {
264
+ if (!isFileMissing(error)) throw error;
265
+ entryExists = false;
266
+ }
267
+ const expected = /* @__PURE__ */ new Set();
268
+ if (entryExists) surfaces.forEach((surface, index) => {
269
+ const file = routeFiles[index];
270
+ expected.add(file);
271
+ const specifier = collectionSpecifier(file, entry, aliases, tsconfigPathsPlugin);
272
+ writeIfChanged(file, buildRouteSource(file, surface.literal, param, specifier, root, surface.factory));
273
+ });
274
+ for (const file of findAdoptedFiles(routesDir)) {
275
+ if (expected.has(file)) continue;
276
+ try {
277
+ unlinkSync(file);
278
+ } catch (error) {
279
+ if (!isFileMissing(error)) throw error;
280
+ }
281
+ }
282
+ }
283
+ };
284
+ }
285
+ //#endregion
33
286
  //#region src/vite/plugin.ts
34
- function workflowsManifest({ entry }) {
287
+ const TSCONFIG_PATHS_PLUGINS = /* @__PURE__ */ new Set(["vite-tsconfig-paths", "vite-plugin-tsconfig-paths"]);
288
+ /**
289
+ * Build the collection's manifests and emit the route serving them; one `entry`
290
+ * feeds both, so the two can never describe different sets.
291
+ */
292
+ function workflowsPlugin(options = {}) {
293
+ const entry = options.entry ?? "src/lib/workflows/index.ts";
294
+ const path = options.path ?? "/api/workflows";
295
+ const emitter = createRouteEmitter({
296
+ entry,
297
+ routesDir: options.routesDir ?? "src/routes",
298
+ path,
299
+ workflowIdParam: options.workflowIdParam ?? "workflowId"
300
+ });
35
301
  let config;
36
302
  return {
37
- name: "@lovable.dev/workflows-sdk/manifest",
38
- apply: "build",
303
+ name: "@lovable.dev/workflows-sdk",
39
304
  configResolved(resolved) {
40
305
  config = resolved;
306
+ emitter.setRoot(config.root, {
307
+ alias: config.resolve.alias,
308
+ tsconfigPathsPlugin: config.plugins.some((plugin) => TSCONFIG_PATHS_PLUGINS.has(plugin.name))
309
+ });
310
+ emitter.regenerate();
311
+ },
312
+ configureServer(server) {
313
+ const onChange = (file) => {
314
+ if (normalizePath(file) === normalizePath(emitter.entryPath())) emitter.regenerate();
315
+ };
316
+ server.watcher.on("add", onChange);
317
+ server.watcher.on("unlink", onChange);
318
+ server.watcher.once("close", () => {
319
+ server.watcher.off("add", onChange);
320
+ server.watcher.off("unlink", onChange);
321
+ });
322
+ },
323
+ buildStart() {
324
+ emitter.regenerate();
41
325
  },
42
326
  async generateBundle() {
43
327
  const entryPath = resolve(config.root, entry);
@@ -64,7 +348,7 @@ function workflowsManifest({ entry }) {
64
348
  try {
65
349
  const module = await server.ssrLoadModule(entryPath);
66
350
  if (!module.default || !Array.isArray(module.default.workflows) || !Array.isArray(module.default.triggers)) throw new Error(`@lovable.dev/workflows-sdk: ${entry} must default-export a registerWorkflows() collection`);
67
- const manifests = await generateManifests(module.default);
351
+ const manifests = await generateManifests(module.default, { routePath: path });
68
352
  await writeManifests(config.root, manifests);
69
353
  } finally {
70
354
  for (const file of server.moduleGraph.fileToModulesMap.keys()) this.addWatchFile(file);
@@ -74,4 +358,4 @@ function workflowsManifest({ entry }) {
74
358
  };
75
359
  }
76
360
  //#endregion
77
- export { workflowsManifest };
361
+ export { workflowsPlugin };
@@ -0,0 +1,63 @@
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-Ci7cGckB.js";
2
+ //#region src/manifests/wait-deadlines.ts
3
+ const optionsArgument = {
4
+ approve: 0,
5
+ waitForEvent: 1
6
+ };
7
+ async function findWaitDeadlineIssues(handler) {
8
+ const api = await loadTypeScript();
9
+ if (!api) return [];
10
+ const ts = api;
11
+ const handlerSource = workflowHandlerSource(handler);
12
+ if (!handlerSource) return [];
13
+ const declaration = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS).statements[0];
14
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
15
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return [];
16
+ const parameter = fn.parameters[0]?.name;
17
+ if (!parameter || !ts.isIdentifier(parameter)) return [];
18
+ const context = parameter.text;
19
+ function property(node, name) {
20
+ if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
21
+ let result;
22
+ for (const entry of node.properties) {
23
+ if (ts.isSpreadAssignment(entry) || entry.name && ts.isComputedPropertyName(entry.name)) {
24
+ if (name === "timeoutMs") return node;
25
+ continue;
26
+ }
27
+ if ((entry.name && (ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name)) ? entry.name.text : void 0) === name) {
28
+ if (result !== void 0) return node;
29
+ result = ts.isPropertyAssignment(entry) ? entry.initializer : node;
30
+ }
31
+ }
32
+ return result;
33
+ }
34
+ const issues = [];
35
+ const visit = (node) => {
36
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text in optionsArgument) {
37
+ const method = node.expression.name.text;
38
+ const options = node.arguments[optionsArgument[method]];
39
+ const given = property(options, "timeoutMs");
40
+ if (property(options, "deadline") !== void 0) issues.push({
41
+ method,
42
+ reason: "absolute"
43
+ });
44
+ if (given === void 0) issues.push({
45
+ method,
46
+ reason: "missing"
47
+ });
48
+ else if (!ts.isNumericLiteral(given)) issues.push({
49
+ method,
50
+ reason: "dynamic"
51
+ });
52
+ else if (!(Number(given.text) >= 6e4 && Number.isFinite(Number(given.text)))) issues.push({
53
+ method,
54
+ reason: "invalid"
55
+ });
56
+ }
57
+ ts.forEachChild(node, visit);
58
+ };
59
+ visit(fn);
60
+ return issues;
61
+ }
62
+ //#endregion
63
+ export { findWaitDeadlineIssues };
@@ -0,0 +1,4 @@
1
+ //#region src/core/wait-deadlines.ts
2
+ const WAIT_DEADLINE_REQUIRED = "every waiting operation needs a static timeoutMs duration in milliseconds (a finite numeric literal of at least 60000 (one minute)), measured from when the wait first parks: ctx.approve({ id, title, timeoutMs: 3600000 }), ctx.waitForEvent(name, { id, timeoutMs: 3600000 }); absolute deadlines are not supported";
3
+ //#endregion
4
+ export { WAIT_DEADLINE_REQUIRED };
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.41",
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",
@@ -32,6 +33,7 @@
32
33
  "@tanstack/workflow-core": "0.0.4"
33
34
  },
34
35
  "devDependencies": {
36
+ "@bufbuild/protobuf": "^2.10.1",
35
37
  "@types/node": "22.13.13",
36
38
  "vite": "^7.3.1",
37
39
  "zod": "^4.1.13",