@lovable.dev/workflows-sdk 0.0.0-dev.2 → 0.0.0-dev.20

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,64 @@
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-CHhlUDD3.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 repeatable(call) {
26
+ let parent = call.parent;
27
+ while (parent && parent !== fn) {
28
+ if (ts.isForStatement(parent) || ts.isForOfStatement(parent) || ts.isForInStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent) || ts.isFunctionLike(parent)) return true;
29
+ parent = parent.parent;
30
+ }
31
+ return false;
32
+ }
33
+ const issues = [];
34
+ const groups = /* @__PURE__ */ new Set();
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 === "step") {
37
+ const stepId = literalString(node.arguments[0]);
38
+ const meta = property(node.arguments[2], "meta");
39
+ if (literalString(property(meta, "description")) === void 0) issues.push({
40
+ kind: "description",
41
+ ...stepId === void 0 ? {} : { stepId }
42
+ });
43
+ if (repeatable(node)) {
44
+ const group = property(meta, "group");
45
+ const groupId = literalString(property(group, "id"));
46
+ const label = literalString(property(group, "label"));
47
+ if (groupId === void 0 || label === void 0) issues.push({
48
+ kind: "group",
49
+ ...stepId === void 0 ? {} : { stepId }
50
+ });
51
+ else if (groups.has(groupId)) issues.push({
52
+ kind: "duplicate-group",
53
+ groupId
54
+ });
55
+ else groups.add(groupId);
56
+ }
57
+ }
58
+ ts.forEachChild(node, visit);
59
+ };
60
+ visit(fn);
61
+ return issues;
62
+ }
63
+ //#endregion
64
+ export { findStepMetadataIssues };
package/dist/vite.d.ts CHANGED
@@ -1,7 +1,20 @@
1
1
  import { Plugin } from "vite";
2
- //#region src/vite.d.ts
3
- declare function workflowsManifest({ entry }: {
4
- entry: string;
5
- }): Plugin;
2
+ //#region src/vite/plugin.d.ts
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,8 +1,9 @@
1
- import { t as generateManifests } from "./manifest-DIeHMgS8.js";
2
- import { join, resolve } from "node:path";
1
+ import { t as generateManifests } from "./generate-BXCYaFf_.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
- //#region src/manifest-files.ts
5
+ import { lstatSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
6
+ //#region src/vite/manifest-files.ts
6
7
  async function ensureDirectory(path) {
7
8
  try {
8
9
  await mkdir(path);
@@ -30,14 +31,297 @@ async function writeManifests(root, manifests) {
30
31
  }
31
32
  }
32
33
  //#endregion
33
- //#region src/vite.ts
34
- function workflowsManifest({ entry }) {
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
129
+ //#region src/vite/route-emitter.ts
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.";
131
+ function isFileMissing(error) {
132
+ const code = error?.code;
133
+ return code === "ENOENT" || code === "ENOTDIR";
134
+ }
135
+ function normalizePath(path) {
136
+ return path.split(sep).join("/");
137
+ }
138
+ function assertContains(parent, child, label) {
139
+ const from = normalizePath(parent).replace(/\/$/, "");
140
+ const to = normalizePath(child);
141
+ if (to !== from && !to.startsWith(`${from}/`)) throw new Error(`@lovable.dev/workflows-sdk: ${label} must resolve under ${from}, got ${to}`);
142
+ }
143
+ function assertUrlPathShape(urlPath) {
144
+ if (!urlPath.startsWith("/")) throw new Error(`@lovable.dev/workflows-sdk: path must start with "/", got "${urlPath}"`);
145
+ if (/\/{2,}/.test(urlPath)) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" contains empty segments ("//")`);
146
+ const trimmed = urlPath.replace(/^\/+/, "").replace(/\/+$/, "");
147
+ if (!trimmed) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" has no route segment`);
148
+ if (!/^[a-zA-Z0-9_\-/]+$/.test(trimmed)) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" contains unsupported characters`);
149
+ return trimmed;
150
+ }
151
+ function assertParamShape(param) {
152
+ if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(param)) throw new Error(`@lovable.dev/workflows-sdk: workflowIdParam "${param}" must be a JavaScript identifier`);
153
+ return param;
154
+ }
155
+ function relativeImportSpecifier(routeFile, target) {
156
+ const withoutExt = normalizePath(relative(dirname(routeFile), target)).replace(/\.tsx?$/, "");
157
+ return withoutExt.startsWith(".") ? withoutExt : `./${withoutExt}`;
158
+ }
159
+ function collectionSpecifier(routeFile, entry, aliases, tsconfigPathsPlugin) {
160
+ return aliasedSpecifier(entry, aliases, tsconfigPathsPlugin) ?? relativeImportSpecifier(routeFile, entry);
161
+ }
162
+ const SURFACES = [{
163
+ segment: "steps",
164
+ factory: "createStepsHandler"
165
+ }];
166
+ function buildRouteSource(routeFile, routeLiteral, param, specifier, root, factory) {
167
+ return `${GENERATED_BANNER}
168
+ // route: ${routeLiteral}
169
+ // emitted to: ${normalizePath(relative(root, routeFile))}
170
+ // This route is unauthenticated: any caller who reaches it can run any declared
171
+ // workflow. Signed invocation is not available yet.
172
+
173
+ import { createFileRoute } from "@tanstack/react-router";
174
+
175
+ import { ${factory} } from "@lovable.dev/workflows-sdk";
176
+
177
+ import workflows from "${specifier}";
178
+
179
+ export const Route = createFileRoute("${routeLiteral}")({
180
+ server: {
181
+ handlers: {
182
+ POST: ${factory}(workflows, { workflowIdParam: "${param}" }),
183
+ },
184
+ },
185
+ });
186
+ `;
187
+ }
188
+ function hasGeneratedBanner(content) {
189
+ return content.replace(/\r\n/g, "\n").startsWith(GENERATED_BANNER);
190
+ }
191
+ function writeIfChanged(file, content) {
192
+ let existing;
193
+ try {
194
+ existing = readFileSync(file, "utf8");
195
+ } catch (error) {
196
+ if (!isFileMissing(error)) throw error;
197
+ }
198
+ if (existing !== void 0 && (!hasGeneratedBanner(existing) || existing === content)) return;
199
+ mkdirSync(dirname(file), { recursive: true });
200
+ writeFileSync(file, content, "utf8");
201
+ }
202
+ function findAdoptedFiles(routesDir) {
203
+ const adopted = [];
204
+ const visit = (dir) => {
205
+ let entries;
206
+ try {
207
+ entries = readdirSync(dir);
208
+ } catch (error) {
209
+ if (isFileMissing(error)) return;
210
+ throw error;
211
+ }
212
+ for (const entry of entries) {
213
+ const full = join(dir, entry);
214
+ let stat;
215
+ try {
216
+ stat = lstatSync(full);
217
+ } catch (error) {
218
+ if (isFileMissing(error)) continue;
219
+ throw error;
220
+ }
221
+ if (stat.isDirectory()) visit(full);
222
+ else if (entry.endsWith(".ts")) try {
223
+ if (hasGeneratedBanner(readFileSync(full, "utf8"))) adopted.push(full);
224
+ } catch (error) {
225
+ if (!isFileMissing(error)) throw error;
226
+ }
227
+ }
228
+ };
229
+ visit(routesDir);
230
+ return adopted;
231
+ }
232
+ function createRouteEmitter(options) {
233
+ const param = assertParamShape(options.workflowIdParam);
234
+ const pathSegments = assertUrlPathShape(options.path);
235
+ const base = `/${pathSegments}/$${param}`;
236
+ const surfaces = SURFACES.map((surface) => ({
237
+ ...surface,
238
+ literal: surface.segment ? `${base}/${surface.segment}` : base,
239
+ fileName: surface.segment ? join(...pathSegments.split("/"), `$${param}`, `${surface.segment}.ts`) : join(...pathSegments.split("/"), `$${param}.ts`)
240
+ }));
241
+ let root = process.cwd();
242
+ let entry = resolve(root, options.entry);
243
+ let routesDir = resolve(root, options.routesDir);
244
+ let routeFiles = surfaces.map((surface) => resolve(routesDir, surface.fileName));
245
+ let aliases = [];
246
+ let tsconfigPathsPlugin = false;
247
+ return {
248
+ entryPath: () => entry,
249
+ setRoot(next, context) {
250
+ root = next;
251
+ aliases = [...viteAliases(context?.alias), ...tsconfigAliases(next)];
252
+ tsconfigPathsPlugin = context?.tsconfigPathsPlugin === true;
253
+ entry = resolve(root, options.entry);
254
+ assertContains(root, entry, `entry "${options.entry}"`);
255
+ routesDir = resolve(root, options.routesDir);
256
+ assertContains(root, routesDir, `routesDir "${options.routesDir}"`);
257
+ routeFiles = surfaces.map((surface) => resolve(routesDir, surface.fileName));
258
+ routeFiles.forEach((file, index) => assertContains(routesDir, file, `path "${surfaces[index].literal}"`));
259
+ },
260
+ regenerate() {
261
+ let entryExists = true;
262
+ try {
263
+ lstatSync(entry);
264
+ } catch (error) {
265
+ if (!isFileMissing(error)) throw error;
266
+ entryExists = false;
267
+ }
268
+ const expected = /* @__PURE__ */ new Set();
269
+ if (entryExists) surfaces.forEach((surface, index) => {
270
+ const file = routeFiles[index];
271
+ expected.add(file);
272
+ const specifier = collectionSpecifier(file, entry, aliases, tsconfigPathsPlugin);
273
+ writeIfChanged(file, buildRouteSource(file, surface.literal, param, specifier, root, surface.factory));
274
+ });
275
+ for (const file of findAdoptedFiles(routesDir)) {
276
+ if (expected.has(file)) continue;
277
+ try {
278
+ unlinkSync(file);
279
+ } catch (error) {
280
+ if (!isFileMissing(error)) throw error;
281
+ }
282
+ }
283
+ }
284
+ };
285
+ }
286
+ //#endregion
287
+ //#region src/vite/plugin.ts
288
+ const TSCONFIG_PATHS_PLUGINS = /* @__PURE__ */ new Set(["vite-tsconfig-paths", "vite-plugin-tsconfig-paths"]);
289
+ /**
290
+ * Build the collection's manifests and emit the route serving them; one `entry`
291
+ * feeds both, so the two can never describe different sets.
292
+ */
293
+ function workflowsPlugin(options = {}) {
294
+ const entry = options.entry ?? "src/lib/workflows/index.ts";
295
+ const emitter = createRouteEmitter({
296
+ entry,
297
+ routesDir: options.routesDir ?? "src/routes",
298
+ path: options.path ?? "/api/workflows",
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);
@@ -63,7 +347,7 @@ function workflowsManifest({ entry }) {
63
347
  });
64
348
  try {
65
349
  const module = await server.ssrLoadModule(entryPath);
66
- if (!module.default || !Array.isArray(module.default.workflows) || !Array.isArray(module.default.schedules)) throw new Error(`@lovable.dev/workflows-sdk: ${entry} must default-export a registerWorkflows() collection`);
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
351
  const manifests = await generateManifests(module.default);
68
352
  await writeManifests(config.root, manifests);
69
353
  } finally {
@@ -74,4 +358,4 @@ function workflowsManifest({ entry }) {
74
358
  };
75
359
  }
76
360
  //#endregion
77
- export { workflowsManifest };
361
+ export { workflowsPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/workflows-sdk",
3
- "version": "0.0.0-dev.2",
3
+ "version": "0.0.0-dev.20",
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",
@@ -52,7 +53,7 @@
52
53
  },
53
54
  "scripts": {
54
55
  "build": "tsdown",
55
- "test": "node --test src/graph.test.mjs",
56
+ "test": "node --test tests/*.test.mjs",
56
57
  "typecheck": "tsc -p tsconfig.typecheck.json",
57
58
  "check:package": "tmp=$(mktemp -d) && pnpm pack --out \"$tmp/pkg.tgz\" && tar -xzf \"$tmp/pkg.tgz\" -C \"$tmp\" && publint \"$tmp/package\" --strict && attw \"$tmp/pkg.tgz\" && node scripts/check-deps.mjs \"$tmp/package/package.json\""
58
59
  }
@@ -1,119 +0,0 @@
1
- //#region src/graph-extract.ts
2
- let loaded;
3
- async function loadTypeScript() {
4
- if (loaded !== void 0) return loaded;
5
- try {
6
- const module = await import("typescript");
7
- const api = module.default ?? module;
8
- loaded = typeof api?.createSourceFile === "function" ? api : null;
9
- } catch {
10
- loaded = null;
11
- }
12
- return loaded;
13
- }
14
- async function extractWorkflowGraph(handler) {
15
- const graph = {
16
- source: "inferred",
17
- scope: "handler",
18
- complete: true,
19
- nodes: [],
20
- edges: [],
21
- diagnostics: []
22
- };
23
- function addNode(node, parents) {
24
- const id = `node-${graph.nodes.length}`;
25
- graph.nodes.push({
26
- id,
27
- ...node
28
- });
29
- for (const parent of new Set(parents)) graph.edges.push({
30
- source: parent,
31
- target: id,
32
- kind: "order"
33
- });
34
- return [id];
35
- }
36
- function unknown(reason, parents) {
37
- graph.complete = false;
38
- if (!graph.diagnostics.includes(reason)) graph.diagnostics.push(reason);
39
- return addNode({
40
- kind: "unknown",
41
- label: reason
42
- }, parents);
43
- }
44
- const api = await loadTypeScript();
45
- if (!api) {
46
- unknown("Install typescript to infer step graphs", []);
47
- return graph;
48
- }
49
- const ts = api;
50
- const source = ts.createSourceFile("handler.js", `const handler = ${Function.prototype.toString.call(handler)};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS);
51
- const declaration = source.statements[0];
52
- const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
53
- if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn) || source.text.includes("[native code]")) {
54
- unknown("Handler source is unavailable", []);
55
- return graph;
56
- }
57
- const parameter = fn.parameters[0]?.name;
58
- if (parameter && !ts.isIdentifier(parameter)) {
59
- unknown("Destructured workflow context is not supported yet", []);
60
- return graph;
61
- }
62
- const context = parameter?.text;
63
- function contains(node, predicate, skipFunctions = false) {
64
- if (skipFunctions && ts.isFunctionLike(node)) return false;
65
- return predicate(node) || Boolean(ts.forEachChild(node, (child) => contains(child, predicate, skipFunctions) || void 0));
66
- }
67
- function contextStep(node) {
68
- return ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text === "step";
69
- }
70
- function expression(node, parents, awaited = false) {
71
- if (ts.isParenthesizedExpression(node)) return expression(node.expression, parents, awaited);
72
- if (ts.isAwaitExpression(node)) return expression(node.expression, parents, true);
73
- if (contextStep(node)) {
74
- if (!awaited) return unknown("Unawaited steps are not supported yet", parents);
75
- const stepId = node.arguments[0];
76
- if (!stepId || !ts.isStringLiteral(stepId) && !ts.isNoSubstitutionTemplateLiteral(stepId)) return unknown("Dynamic step IDs are not supported yet", parents);
77
- const tails = addNode({
78
- kind: "step",
79
- stepId: stepId.text,
80
- label: stepId.text
81
- }, parents);
82
- if (node.arguments.slice(1).some((argument) => contains(argument, contextStep))) return unknown("Nested steps are not supported yet", tails);
83
- return tails;
84
- }
85
- if (awaited && ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "Promise" && node.expression.name.text === "all" && node.arguments.length === 1 && ts.isArrayLiteralExpression(node.arguments[0])) {
86
- const elements = node.arguments[0].elements;
87
- if (elements.some((element) => contains(element, ts.isAwaitExpression, true))) return unknown("Await expressions inside Promise.all are not supported yet", parents);
88
- return elements.length > 0 ? elements.flatMap((element) => {
89
- while (ts.isParenthesizedExpression(element)) element = element.expression;
90
- return ts.isCallExpression(element) ? expression(element, parents, true) : unknown("Dynamic Promise.all entries are not followed", parents);
91
- }) : parents;
92
- }
93
- if (contains(node, (child) => ts.isCallExpression(child) || ts.isAwaitExpression(child) || ts.isNewExpression(child))) return unknown("Helper calls and dynamic expressions are not followed", parents);
94
- if (ts.isIdentifier(node) && node.text === context) return unknown("Workflow context aliases are not followed", parents);
95
- return parents;
96
- }
97
- let tails = [];
98
- if (!ts.isBlock(fn.body)) {
99
- expression(fn.body, tails, true);
100
- return graph;
101
- }
102
- for (const statement of fn.body.statements) {
103
- if (ts.isReturnStatement(statement)) {
104
- if (statement.expression) expression(statement.expression, tails, true);
105
- break;
106
- }
107
- if (ts.isVariableStatement(statement)) {
108
- if (statement.declarationList.declarations.some((item) => contains(item.name, (child) => ts.isIdentifier(child) && (child.text === "Promise" || child.text === context)))) {
109
- tails = unknown("Shadowed context or Promise bindings are not supported yet", tails);
110
- break;
111
- }
112
- for (const item of statement.declarationList.declarations) if (item.initializer) tails = expression(item.initializer, tails);
113
- } else if (ts.isExpressionStatement(statement)) tails = expression(statement.expression, tails);
114
- else tails = unknown("Branches, loops, and other control flow are not supported yet", tails);
115
- }
116
- return graph;
117
- }
118
- //#endregion
119
- export { extractWorkflowGraph };
@@ -1,114 +0,0 @@
1
- //#region src/validation.ts
2
- function assertIdentifier(kind, id) {
3
- if (typeof id !== "string" || id.trim() === "" || id !== id.trim()) throw new Error(`@lovable.dev/workflows-sdk: ${kind} IDs must be non-empty and have no surrounding whitespace`);
4
- }
5
- //#endregion
6
- //#region src/schedule.ts
7
- function defineSchedule(schedule) {
8
- assertIdentifier("schedule", schedule.id);
9
- if (typeof schedule.cron !== "string" || schedule.cron.trim().split(/\s+/).length !== 5) throw new Error(`@lovable.dev/workflows-sdk: schedule "${schedule.id}" requires a five-field cron expression`);
10
- const timeZone = schedule.timeZone ?? "UTC";
11
- new Intl.DateTimeFormat("en", { timeZone });
12
- return {
13
- ...schedule,
14
- timeZone
15
- };
16
- }
17
- //#endregion
18
- //#region src/register.ts
19
- function registerWorkflows({ workflows, schedules = [] }) {
20
- const ids = /* @__PURE__ */ new Set();
21
- for (const workflow of workflows) {
22
- if (workflow.__kind !== "workflow" || typeof workflow.handler !== "function") throw new Error("@lovable.dev/workflows-sdk: expected a completed createWorkflow().handler() definition");
23
- assertIdentifier("workflow", workflow.id);
24
- if (!/^[a-z0-9][a-z0-9_-]{0,127}$/.test(workflow.id)) throw new Error("@lovable.dev/workflows-sdk: workflow names must be 1–128 lowercase letters, digits, hyphens or underscores, starting with a letter or digit");
25
- if (ids.has(workflow.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate workflow ID "${workflow.id}"`);
26
- ids.add(workflow.id);
27
- }
28
- const scheduleIds = /* @__PURE__ */ new Set();
29
- const registeredSchedules = schedules.map((schedule) => {
30
- const definition = defineSchedule(schedule);
31
- if (scheduleIds.has(definition.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate schedule ID "${definition.id}"`);
32
- if (!workflows.includes(definition.workflow)) throw new Error(`@lovable.dev/workflows-sdk: schedule "${definition.id}" references an unregistered workflow`);
33
- scheduleIds.add(definition.id);
34
- return definition;
35
- });
36
- return {
37
- workflows: [...workflows],
38
- schedules: registeredSchedules
39
- };
40
- }
41
- //#endregion
42
- //#region src/json.ts
43
- function toJson(value, path, ancestors = /* @__PURE__ */ new Set()) {
44
- if (value === null || typeof value === "string" || typeof value === "boolean") return value;
45
- if (typeof value === "number" && Number.isFinite(value)) return value;
46
- if (typeof value !== "object" || ancestors.has(value)) throw new Error(`@lovable.dev/workflows-sdk: ${path} must contain finite, acyclic JSON values`);
47
- ancestors.add(value);
48
- try {
49
- if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`@lovable.dev/workflows-sdk: ${path} must not contain symbol keys`);
50
- if (Array.isArray(value)) {
51
- if (Object.keys(value).length !== value.length) throw new Error(`@lovable.dev/workflows-sdk: ${path} must be a dense JSON array without extra properties`);
52
- return Array.from(value, (item, index) => toJson(item, `${path}[${index}]`, ancestors));
53
- }
54
- if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error(`@lovable.dev/workflows-sdk: ${path} must contain plain JSON objects`);
55
- return Object.fromEntries(Object.keys(value).sort().map((key) => [key, toJson(value[key], `${path}.${key}`, ancestors)]));
56
- } finally {
57
- ancestors.delete(value);
58
- }
59
- }
60
- //#endregion
61
- //#region src/manifest.ts
62
- function jsonSchema(schema, direction, label) {
63
- if (!schema) return void 0;
64
- const standard = schema["~standard"];
65
- if (typeof standard.jsonSchema?.[direction] !== "function") throw new Error(`@lovable.dev/workflows-sdk: ${label} must support Standard JSON Schema conversion`);
66
- try {
67
- return toJson(standard.jsonSchema[direction]({ target: "draft-2020-12" }), label);
68
- } catch (cause) {
69
- throw new Error(`@lovable.dev/workflows-sdk: cannot serialize ${label}`, { cause });
70
- }
71
- }
72
- async function generateManifests(definition) {
73
- const { extractWorkflowGraph } = await import("./graph-extract-CGLWzaln.js");
74
- const collection = registerWorkflows(definition);
75
- const manifests = [];
76
- for (const workflow of collection.workflows) {
77
- if (workflow.previousVersions?.length) throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" previousVersions are not supported yet`);
78
- const metadata = {
79
- id: workflow.id,
80
- ...workflow.description === void 0 ? {} : { description: workflow.description },
81
- ...workflow.version === void 0 ? {} : { version: workflow.version },
82
- ...workflow.inputSchema ? { inputSchema: jsonSchema(workflow.inputSchema, "input", `${workflow.id}.input`) } : {},
83
- ...workflow.outputSchema ? { outputSchema: jsonSchema(workflow.outputSchema, "output", `${workflow.id}.output`) } : {},
84
- ...workflow.stateSchema ? { stateSchema: jsonSchema(workflow.stateSchema, "output", `${workflow.id}.state`) } : {}
85
- };
86
- const schedules = [];
87
- for (const schedule of collection.schedules.filter((schedule) => schedule.workflow === workflow)) {
88
- const input = toJson(schedule.input, `schedule "${schedule.id}" input`);
89
- const schema = schedule.workflow.inputSchema;
90
- if (schema) {
91
- const result = await schema["~standard"].validate(input);
92
- if (result.issues) throw new Error(`@lovable.dev/workflows-sdk: schedule "${schedule.id}" input is invalid: ${result.issues.map((issue) => issue.message).join("; ")}`);
93
- }
94
- schedules.push({
95
- id: schedule.id,
96
- cron: schedule.cron,
97
- timeZone: schedule.timeZone ?? "UTC",
98
- input
99
- });
100
- }
101
- schedules.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
102
- const manifest = {
103
- version: 1,
104
- workflow: metadata,
105
- schedules,
106
- graph: await extractWorkflowGraph(workflow.handler)
107
- };
108
- toJson(manifest, "manifest");
109
- manifests.push(manifest);
110
- }
111
- return manifests.sort((a, b) => a.workflow.id < b.workflow.id ? -1 : a.workflow.id > b.workflow.id ? 1 : 0);
112
- }
113
- //#endregion
114
- export { registerWorkflows as n, defineSchedule as r, generateManifests as t };