@lovable.dev/workflows-sdk 0.0.0-dev.6 → 0.0.0-dev.60

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,245 +1,2 @@
1
- import { t as generateManifests } from "./generate-DyUHbtre.js";
2
- import { dirname, join, relative, resolve, sep } from "node:path";
3
- import { createServer } from "vite";
4
- import { lstat, mkdir, mkdtemp, readdir, rename, rm, writeFile } from "node:fs/promises";
5
- import { lstatSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
6
- //#region src/vite/manifest-files.ts
7
- async function ensureDirectory(path) {
8
- try {
9
- await mkdir(path);
10
- } catch (error) {
11
- if (error.code !== "EEXIST") throw error;
12
- }
13
- if (!(await lstat(path)).isDirectory()) throw new Error(`@lovable.dev/workflows-sdk: ${path} must be a directory, not a file or symlink`);
14
- }
15
- async function writeManifests(root, manifests) {
16
- const lovable = join(root, ".lovable");
17
- await ensureDirectory(lovable);
18
- const directory = join(lovable, "workflows");
19
- await ensureDirectory(directory);
20
- const staging = await mkdtemp(join(directory, ".tmp-"));
21
- const names = new Set(manifests.map((manifest) => `${manifest.workflow.id}.json`));
22
- try {
23
- for (const manifest of manifests) await writeFile(join(staging, `${manifest.workflow.id}.json`), JSON.stringify(manifest, null, 2) + "\n");
24
- for (const name of names) await rename(join(staging, name), join(directory, name));
25
- 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 });
26
- } finally {
27
- await rm(staging, {
28
- recursive: true,
29
- force: true
30
- });
31
- }
32
- }
33
- //#endregion
34
- //#region src/vite/route-emitter.ts
35
- const GENERATED_BANNER = "// AUTO-GENERATED by @lovable.dev/workflows-sdk — do not edit. Regenerated by the Vite plugin.\n// To take ownership, delete this banner line; the plugin then leaves the file alone.";
36
- function isFileMissing(error) {
37
- const code = error?.code;
38
- return code === "ENOENT" || code === "ENOTDIR";
39
- }
40
- function normalizePath(path) {
41
- return path.split(sep).join("/");
42
- }
43
- function assertContains(parent, child, label) {
44
- const from = normalizePath(parent).replace(/\/$/, "");
45
- const to = normalizePath(child);
46
- if (to !== from && !to.startsWith(`${from}/`)) throw new Error(`@lovable.dev/workflows-sdk: ${label} must resolve under ${from}, got ${to}`);
47
- }
48
- function assertUrlPathShape(urlPath) {
49
- if (!urlPath.startsWith("/")) throw new Error(`@lovable.dev/workflows-sdk: path must start with "/", got "${urlPath}"`);
50
- if (/\/{2,}/.test(urlPath)) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" contains empty segments ("//")`);
51
- const trimmed = urlPath.replace(/^\/+/, "").replace(/\/+$/, "");
52
- if (!trimmed) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" has no route segment`);
53
- if (!/^[a-zA-Z0-9_\-/]+$/.test(trimmed)) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" contains unsupported characters`);
54
- return trimmed;
55
- }
56
- function assertParamShape(param) {
57
- if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(param)) throw new Error(`@lovable.dev/workflows-sdk: workflowIdParam "${param}" must be a JavaScript identifier`);
58
- return param;
59
- }
60
- function relativeImportSpecifier(routeFile, target) {
61
- const withoutExt = normalizePath(relative(dirname(routeFile), target)).replace(/\.tsx?$/, "");
62
- return withoutExt.startsWith(".") ? withoutExt : `./${withoutExt}`;
63
- }
64
- function buildRouteSource(routeFile, routeLiteral, param, entry, root) {
65
- return `${GENERATED_BANNER}
66
- // route: ${routeLiteral}
67
- // emitted to: ${normalizePath(relative(root, routeFile))}
68
- // This route is unauthenticated: any caller can run any declared workflow.
69
-
70
- import { createFileRoute } from "@tanstack/react-router";
71
-
72
- import { createTanStackWorkflowHandler } from "@lovable.dev/workflows-sdk/stacks/tanstack";
73
-
74
- import workflows from "${relativeImportSpecifier(routeFile, entry)}";
75
-
76
- export const Route = createFileRoute("${routeLiteral}")({
77
- server: {
78
- handlers: {
79
- POST: createTanStackWorkflowHandler(workflows, { workflowIdParam: "${param}" }),
80
- },
81
- },
82
- });
83
- `;
84
- }
85
- function hasGeneratedBanner(content) {
86
- return content.replace(/\r\n/g, "\n").startsWith(GENERATED_BANNER);
87
- }
88
- function writeIfChanged(file, content) {
89
- let existing;
90
- try {
91
- existing = readFileSync(file, "utf8");
92
- } catch (error) {
93
- if (!isFileMissing(error)) throw error;
94
- }
95
- if (existing !== void 0 && (!hasGeneratedBanner(existing) || existing === content)) return;
96
- mkdirSync(dirname(file), { recursive: true });
97
- writeFileSync(file, content, "utf8");
98
- }
99
- function findAdoptedFiles(routesDir) {
100
- const adopted = [];
101
- const visit = (dir) => {
102
- let entries;
103
- try {
104
- entries = readdirSync(dir);
105
- } catch (error) {
106
- if (isFileMissing(error)) return;
107
- throw error;
108
- }
109
- for (const entry of entries) {
110
- const full = join(dir, entry);
111
- let stat;
112
- try {
113
- stat = lstatSync(full);
114
- } catch (error) {
115
- if (isFileMissing(error)) continue;
116
- throw error;
117
- }
118
- if (stat.isDirectory()) visit(full);
119
- else if (entry.endsWith(".ts")) try {
120
- if (hasGeneratedBanner(readFileSync(full, "utf8"))) adopted.push(full);
121
- } catch (error) {
122
- if (!isFileMissing(error)) throw error;
123
- }
124
- }
125
- };
126
- visit(routesDir);
127
- return adopted;
128
- }
129
- function createRouteEmitter(options) {
130
- const param = assertParamShape(options.workflowIdParam);
131
- const pathSegments = assertUrlPathShape(options.path);
132
- const routeLiteral = `/${pathSegments}/$${param}`;
133
- const routeFileName = join(...pathSegments.split("/"), `$${param}.ts`);
134
- let root = process.cwd();
135
- let entry = resolve(root, options.entry);
136
- let routesDir = resolve(root, options.routesDir);
137
- let routeFile = resolve(routesDir, routeFileName);
138
- return {
139
- entryPath: () => entry,
140
- setRoot(next) {
141
- root = next;
142
- entry = resolve(root, options.entry);
143
- assertContains(root, entry, `entry "${options.entry}"`);
144
- routesDir = resolve(root, options.routesDir);
145
- assertContains(root, routesDir, `routesDir "${options.routesDir}"`);
146
- routeFile = resolve(routesDir, routeFileName);
147
- assertContains(routesDir, routeFile, `path "${routeLiteral}"`);
148
- },
149
- regenerate() {
150
- let entryExists = true;
151
- try {
152
- lstatSync(entry);
153
- } catch (error) {
154
- if (!isFileMissing(error)) throw error;
155
- entryExists = false;
156
- }
157
- const expected = /* @__PURE__ */ new Set();
158
- if (entryExists && options.runRoute) {
159
- expected.add(routeFile);
160
- writeIfChanged(routeFile, buildRouteSource(routeFile, routeLiteral, param, entry, root));
161
- }
162
- for (const file of findAdoptedFiles(routesDir)) {
163
- if (expected.has(file)) continue;
164
- try {
165
- unlinkSync(file);
166
- } catch (error) {
167
- if (!isFileMissing(error)) throw error;
168
- }
169
- }
170
- }
171
- };
172
- }
173
- //#endregion
174
- //#region src/vite/plugin.ts
175
- /**
176
- * Build the collection's manifests and, with `runRoute`, emit the route serving
177
- * them; one `entry` feeds both, so the two can never describe different sets.
178
- */
179
- function workflowsPlugin(options = {}) {
180
- const entry = options.entry ?? "src/lib/workflows/index.ts";
181
- const emitter = createRouteEmitter({
182
- entry,
183
- routesDir: options.routesDir ?? "src/routes",
184
- path: options.path ?? "/api/workflows",
185
- workflowIdParam: options.workflowIdParam ?? "workflowId",
186
- runRoute: options.runRoute === true
187
- });
188
- let config;
189
- return {
190
- name: "@lovable.dev/workflows-sdk",
191
- configResolved(resolved) {
192
- config = resolved;
193
- emitter.setRoot(config.root);
194
- emitter.regenerate();
195
- },
196
- configureServer(server) {
197
- const onChange = (file) => {
198
- if (normalizePath(file) === normalizePath(emitter.entryPath())) emitter.regenerate();
199
- };
200
- server.watcher.on("add", onChange);
201
- server.watcher.on("unlink", onChange);
202
- server.watcher.once("close", () => {
203
- server.watcher.off("add", onChange);
204
- server.watcher.off("unlink", onChange);
205
- });
206
- },
207
- buildStart() {
208
- emitter.regenerate();
209
- },
210
- async generateBundle() {
211
- const entryPath = resolve(config.root, entry);
212
- this.addWatchFile(entryPath);
213
- const server = await createServer({
214
- configFile: false,
215
- root: config.root,
216
- mode: config.mode,
217
- envDir: config.envDir,
218
- define: config.define,
219
- logLevel: "silent",
220
- resolve: { alias: config.resolve.alias },
221
- ssr: {
222
- external: config.ssr.external,
223
- noExternal: config.ssr.noExternal
224
- },
225
- server: {
226
- middlewareMode: true,
227
- hmr: false,
228
- watch: null
229
- },
230
- optimizeDeps: { noDiscovery: true }
231
- });
232
- try {
233
- const module = await server.ssrLoadModule(entryPath);
234
- 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`);
235
- const manifests = await generateManifests(module.default);
236
- await writeManifests(config.root, manifests);
237
- } finally {
238
- for (const file of server.moduleGraph.fileToModulesMap.keys()) this.addWatchFile(file);
239
- await server.close();
240
- }
241
- }
242
- };
243
- }
244
- //#endregion
1
+ import { r as workflowsPlugin } from "./plugin-CXlzS4_y.js";
245
2
  export { workflowsPlugin };
@@ -0,0 +1,63 @@
1
+ import { n as loadTypeScript, r as workflowHandlerSource } from "./graph-DSYE4aER.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 };