@lovable.dev/workflows-sdk 0.0.0-dev.22 → 0.0.0-dev.24

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 CHANGED
@@ -1,33 +1,23 @@
1
1
  # @lovable.dev/workflows-sdk
2
2
 
3
- Author workflows with TanStack workflow-core and register them in an explicit
4
- collection for Lovable. This development SDK generates build manifests; execution
5
- and schedule installation on Lovable are not implemented yet.
3
+ Experimental SDK for authoring workflows in Lovable apps with
4
+ [`@tanstack/workflow-core`](https://github.com/TanStack/workflow). Releases stay
5
+ in the `0.0.0-dev` series and may change without compatibility guarantees.
6
6
 
7
- Experimental: every release stays in the `0.0.0-dev` series. The API may
8
- change without compatibility guarantees; this SDK is not production-ready.
7
+ ## Install
9
8
 
10
- ## Authoring
9
+ ```sh
10
+ npm install @lovable.dev/workflows-sdk
11
+ ```
12
+
13
+ ## Define workflows
11
14
 
12
15
  Use `createWorkflow({ id, input, output }).handler(...)` to define a workflow
13
- and `createMiddleware` to extend its typed context. Both builders come directly
14
- from [`@tanstack/workflow-core`](https://github.com/TanStack/workflow).
15
- Schema validation libraries implementing Standard Schema, such as Zod, provide
16
- input and output inference.
17
-
18
- Keep the app's workflow collection in `src/lib/workflows/index.ts`. Each workflow
19
- lives in `src/lib/workflows/{workflow-name}/index.ts`, with its helpers alongside it:
20
-
21
- ```text
22
- src/lib/workflows/
23
- ├── index.ts
24
- └── greet/
25
- ├── index.ts
26
- └── helpers.ts
27
- ```
16
+ and `createMiddleware` to extend its typed context. Standard Schema libraries
17
+ such as Zod provide input and output inference.
28
18
 
29
- Each workflow's `index.ts` exports its definition. The collection entry imports
30
- all workflow definitions and default-exports `registerWorkflows(...)`:
19
+ Keep definitions under `src/lib/workflows/{workflow-name}/` and default-export
20
+ one collection from `src/lib/workflows/index.ts`:
31
21
 
32
22
  ```ts
33
23
  import { registerWorkflows } from "@lovable.dev/workflows-sdk";
@@ -36,19 +26,14 @@ import { greet } from "./greet";
36
26
  export default registerWorkflows({ workflows: [greet] });
37
27
  ```
38
28
 
39
- The `id` passed to `createWorkflow` is its app-wide unique name and should match
40
- its folder name. Names contain 1–128 lowercase letters, digits, hyphens, or
41
- underscores, starting with a letter or digit. The app collection rejects duplicate
42
- names. An empty collection is valid. Registration copies the list, retains the
43
- definitions, and does not execute handlers or register global state. Treat
44
- definitions as immutable after registration.
29
+ Workflow IDs contain 1–128 lowercase letters, digits, hyphens, or underscores,
30
+ starting with a letter or digit. They must be unique within the collection.
31
+ See the [authoring example](examples/src/lib/workflows/greet/index.ts) for
32
+ schemas, typed middleware, and a durable step.
45
33
 
46
- See [the authoring example](examples/src/lib/workflows/greet/index.ts) for schemas,
47
- typed middleware, and a durable step. The package typecheck includes this example.
34
+ ## Durable operations
48
35
 
49
- Every durable operation needs a static, user-facing description. Lovable's
50
- agent supplies this text so the workflow UI can explain each operation before
51
- and during a run. Put it in the operation's options:
36
+ Every durable operation needs a static, user-facing description:
52
37
 
53
38
  | Operation | Description field |
54
39
  | --- | --- |
@@ -64,267 +49,35 @@ await ctx.step("load-customer", () => loadCustomer(ctx.input.customerId), {
64
49
  });
65
50
  ```
66
51
 
67
- Manifest generation rejects a missing or computed description. A step declared
68
- inside a loop or callback also needs a group with a stable ID and user-facing
69
- label. The group identifies the repeated callsite while each runtime step keeps
70
- its own concrete ID:
71
-
72
- ```ts
73
- await Promise.all(
74
- ctx.input.items.map((item) =>
75
- ctx.step(`process-${item.id}`, () => processItem(item), {
76
- meta: {
77
- description: "Process an item",
78
- group: { id: "process-items", label: "Process items" },
79
- },
80
- }),
81
- ),
82
- );
83
- ```
84
-
85
- Group IDs are unique per workflow callsite. Ordinary sequential steps and
86
- fixed `Promise.all([stepA, stepB])` branches do not need a group.
87
-
88
- ## Triggers
52
+ Step IDs must be unique within a workflow. Keep side effects inside step bodies;
53
+ handler code outside a step may run more than once. A step body is one atomic
54
+ execution unit and cannot contain another durable operation.
89
55
 
90
- A workflow runs when something triggers it, and a schedule is the first kind of
91
- trigger: a clock. Triggers go in `registerWorkflows({ workflows, triggers })`,
92
- and each carries a `type` naming its kind. Webhook and app-event triggers will
93
- join the same array.
56
+ Keep durable control flow in the workflow handler. Do not pass, alias,
57
+ destructure, or return `ctx`, and do not detach methods such as `ctx.step`.
58
+ Pass extracted data such as `ctx.input.customerId` to helpers instead.
94
59
 
95
- A schedule's *cadence* is how often the clock fires. `hourly()`, `daily()`,
96
- and `weekly()` build one; there is no raw cron.
97
-
98
- ## Schedules
60
+ ### Repeated steps
99
61
 
100
- Declare a schedule with `defineSchedule({ id, workflow, cadence, timeZone, input })` and
101
- include it in `registerWorkflows({ workflows, triggers })`. `workflow` refers to
102
- the same definition object included in `workflows`; `input` is required and
103
- inferred from that workflow. Multiple schedules can target one workflow. Schedule
104
- IDs must be unique within the app's collection. This API declares schedules but
105
- does not install timers or start runs.
62
+ A step inside a loop or callback needs `meta.group` with a stable ID and
63
+ user-facing label. Each repeated step still needs its own dynamic ID:
106
64
 
107
65
  ```ts
108
- import { daily, defineSchedule, hourly, weekly } from "@lovable.dev/workflows-sdk";
109
-
110
- defineSchedule({ id: "sweep", workflow: sync, cadence: hourly(), timeZone: "UTC", input: {} });
111
- defineSchedule({ id: "digest", workflow: digest, cadence: daily(), timeZone: "Europe/Stockholm", input: {} });
112
-
113
- defineSchedule({
114
- id: "refresh",
115
- workflow: sync,
116
- cadence: daily({ at: [0, 6, 12, 18] }),
117
- timeZone: "UTC",
118
- input: {},
119
- });
120
-
121
- defineSchedule({
122
- id: "weekday-digest",
123
- workflow: digest,
124
- cadence: daily({ at: 9, days: ["mon", "tue", "wed", "thu", "fri"] }),
125
- timeZone: "America/New_York",
126
- input: {},
127
- });
128
-
129
- defineSchedule({
130
- id: "monday-report",
131
- workflow: report,
132
- cadence: weekly({ on: "monday", at: 7 }),
133
- timeZone: "Europe/Stockholm",
134
- input: {},
66
+ ctx.step(`process-${item.id}`, () => processItem(item), {
67
+ meta: { description: "Process an item", group: { id: "process-items", label: "Process items" } },
135
68
  });
136
69
  ```
137
70
 
138
- | Field | Default | Meaning |
139
- | --- | --- | --- |
140
- | `cadence` | — | `hourly()`, `daily()`, or `weekly()` |
141
- | `timeZone` | — | IANA region name the cadence is interpreted in |
142
- | `overlapPolicy` | `"skip"` | `skip`, `allow`, or `buffer-one` |
143
- | `enabled` | `true` | `false` declares a paused schedule without deleting it |
71
+ For dynamic sequential work, await one step directly as the only statement in
72
+ a `for...of` loop. For dynamic parallel work, use a mapped `Promise.all()`.
73
+ Fixed `Promise.all([stepA, stepB])` branches and ordinary sequential steps do
74
+ not need a group.
144
75
 
145
- There are three cadences and no raw cron:
76
+ ### Conditional steps
146
77
 
147
- | Cadence | Says | Example |
148
- | --- | --- | --- |
149
- | `hourly()` | once an hour | `hourly()` |
150
- | `daily({ at, days })` | hours of the day, days of the week | `daily({ at: [0, 6, 12, 18] })` |
151
- | `weekly({ on, at })` | one weekday, hours of the day | `weekly({ on: "monday", at: 7 })` |
152
-
153
- **The SDK never derives a cron.** The manifest carries the cadence, and the
154
- `app-workflows-service` backend translates it when it registers the schedule.
155
- An app declares intent; one service owns the translation, so there is no second
156
- implementation to drift. Every cadence here is shaped to be exactly
157
- translatable — that constraint is why the vocabulary is closed and why `at` is
158
- whole hours.
159
-
160
- ### Hours, never minutes
161
-
162
- `at` is a whole hour, `0` through `23`, or a list of them. There is no minute:
163
- an app says *which hours*, and the platform picks where inside the hour a run
164
- actually starts (see [Timing](#timing)). `hourly()` takes no options for the
165
- same reason. An app that could pin a minute would opt itself out of the smear,
166
- and the herd would come back.
167
-
168
- This is also what keeps the vocabulary exactly translatable by the backend.
169
- Cron pairs every value in its minute field with every value in its hour field,
170
- so a cadence that could say 09:15 and 17:45 has no faithful cron — it would
171
- become `15,45 9,17 * * *` and fire four times a day instead of twice. With the
172
- minute fixed, any set of hours translates exactly.
173
-
174
- `at` accepts a list, so several runs a day need one schedule rather than
175
- several: `daily({ at: [0, 6, 12, 18] })` is four evenly spaced runs, and
176
- `daily({ at: [9, 17] })` is two uneven ones — the start and end of a working
177
- day, which no fixed interval can express. The list is sorted and deduplicated,
178
- so two orderings are one schedule.
179
-
180
- ### One schedule, one representation
181
-
182
- `weekly({ on, at })` is the single-day shorthand for `daily({ at, days: [on] })`
183
- and resolves into exactly that cadence. There is one internal representation of
184
- a day-restricted schedule, so the two spellings emit byte-identical manifests
185
- and hash alike.
186
-
187
- There is no `"weekdays"` or `"weekends"` shorthand: it would add a third
188
- spelling of a set `days` already states, and "the weekend" is Friday and
189
- Saturday in much of the world, so the word would quietly mean the wrong days.
190
-
191
- There is no interval cadence — no `every("6h")`, no `every("3d")`. Intervals
192
- are not calendar positions and have no faithful cron: `0 0 */3 * *` restarts its
193
- count every month, so it means "every 3 days" only until the 28th and then fires
194
- twice in two days. The sub-daily intervals that *are* faithful are exactly the
195
- ones `daily({ at })` already covers, and `daily({ at: [0, 6, 12, 18] })` says the
196
- same thing as "every 6 hours" while staying anchored to the calendar and to the
197
- app's time zone.
198
-
199
- ## Timing
200
-
201
- **A declared hour is approximate, and an app does not control how approximate.**
202
- Tens of thousands of apps declaring `daily()` must not fire in the same minute,
203
- so the platform spreads each schedule over a window — a *smear* — and then keeps
204
- that schedule on the same offset for every later run.
205
-
206
- Apps do not declare the smear, and there is no field for it. The platform
207
- derives the window per schedule from the cadence, so what an app leaves
208
- unspecified is exactly what the platform is free to choose:
209
-
210
- | Cadence | Smeared across |
211
- | --- | --- |
212
- | `daily()` | the whole day |
213
- | `daily({ at })`, `weekly({ on, at })` | a window around each declared hour |
214
- | `hourly()` | the hour |
215
-
216
- Higher plans get tighter windows, so a declared 07:00 lands nearer to 07:00 the
217
- more an app pays; the exact windows belong to the platform and can change
218
- without an SDK release.
219
-
220
- Two consequences worth designing around. A schedule that must run at an exact
221
- instant is not expressible, by design. And the offset is stable per schedule,
222
- not random per run, so a report that reads "yesterday's rows" reads the same
223
- shape every day.
224
-
225
- Neither the smear nor the schedule itself runs yet; see
226
- [Next PRs](#next-prs).
227
-
228
- ### Time zone
229
-
230
- `timeZone` is required on every schedule. There is no default, because every
231
- available default is wrong: `daily({ at: 9 })` in UTC is not the 09:00 a reader
232
- of the digest expects, and the build machine's own zone would make one app
233
- source fire at different times depending on where it was built.
234
-
235
- It must be `"UTC"` or a canonical IANA name as `Intl.supportedValuesOf("timeZone")`
236
- lists it, such as `"Europe/Stockholm"`. That rejects the fixed-offset family
237
- `Intl` otherwise accepts — `"+05:00"`, `"-0800"`, `"EST"`, `"GMT"`,
238
- `"Etc/GMT+5"` — none of which observe daylight saving, so `"EST"` is an hour
239
- off US Eastern for two-thirds of the year, and `"Etc/GMT+5"` is UTC-5 rather
240
- than UTC+5. It also rejects tzdata's backward-compatibility aliases such as
241
- `"US/Pacific"`; write the canonical `"America/Los_Angeles"`, so one zone has
242
- one spelling and one manifest.
243
-
244
- ### Overlap policy
245
-
246
- `overlapPolicy` says what happens when an occurrence comes due while the
247
- previous run is still going: `skip` drops it, `allow` lets runs overlap, and
248
- `buffer-one` holds the earliest due occurrence and fires it once the in-flight
249
- run finishes.
250
-
251
- ### Validation
252
-
253
- Everything is validated when the schedule is defined, at build time: an hour
254
- outside `0`-`23`, a fractional hour, a weekday name that is not a weekday, an
255
- unknown `overlapPolicy`, a missing or non-canonical zone, and a hand-written
256
- cadence object no constructor produced all fail the build. `registerWorkflows`
257
- likewise rejects any key other than `workflows` and `triggers`, so a collection
258
- left on the old `schedules:` name fails the build instead of emitting an empty
259
- manifest.
260
-
261
- The [example](examples/src/lib/workflows/index.ts) declares a 09:00 greeting in
262
- Europe/Stockholm, a weekday greeting in America/New_York, a Monday report, a
263
- four-times-daily refresh, an hourly sweep, and a paused daily digest.
264
-
265
- ## Manifest generation
266
-
267
- Add `workflowsPlugin()` from `@lovable.dev/workflows-sdk/vite` to the app's Vite
268
- plugins. Its `entry` defaults to `src/lib/workflows/index.ts` and must
269
- default-export the app's `registerWorkflows()` collection. Each production build writes
270
- one manifest per workflow to `.lovable/workflows/{workflow-name}.json` relative
271
- to the app root. For example, `greet` produces `.lovable/workflows/greet.json`.
272
- Generation errors fail the build. See [the Vite example](examples/vite.config.ts).
273
-
274
- Each version-1 manifest contains a single `workflow` with its ID, description,
275
- version, and input/output/state JSON Schemas, a `graph` for visualization, and a
276
- `triggers` array containing only that workflow's triggers and static inputs. Each
277
- entry names its kind in `type` — `"schedule"` today — and a schedule entry carries
278
- its `cadence`, `timeZone`, `enabled`, `overlapPolicy`, and `input`. It is an SDK discovery format, not the engine's deployment or execution
279
- contract. Handlers and middleware stay in app code. Triggers and JSON object keys
280
- are sorted for stable output.
281
-
282
- The SDK manages the JSON files in `.lovable/workflows/`. Successful generation
283
- removes manifests for deleted or renamed workflows; an empty collection removes
284
- all JSON manifests. Other files and subdirectories are preserved. All definitions
285
- are validated before writing, and each file is replaced by rename so readers
286
- never see a partially written JSON document.
287
-
288
- Schemas must implement [Standard JSON Schema](https://standardschema.dev/json-schema)
289
- conversion to draft 2020-12, as Zod 4 does. Missing conversion support and
290
- conversion errors fail generation. Schedule inputs must be plain JSON and pass
291
- the workflow's input schema; the manifest retains the raw input for validation
292
- when a run starts. Functions, undefined values, non-finite numbers, class
293
- instances, and cycles are rejected. `previousVersions` is rejected until version
294
- routing has a manifest contract.
295
-
296
- The plugin evaluates the entry using a separate Vite SSR loader with the app's
297
- aliases, mode, defines, and SSR dependency rules. Module-level code and schema
298
- validators run during extraction; workflow handlers and middleware do not.
299
- Custom app transform plugins and virtual modules are not loaded by this loader.
300
- For another build system, call `await generateManifests(collection)` and make
301
- synchronizing the returned manifests to `.lovable/workflows/` a required build step.
302
-
303
- ### Step graph
304
-
305
- Each manifest's `graph` contains `nodes` and directed `edges`. The SDK parses the
306
- handler's function source without executing it. No additional registration is needed.
307
-
308
- Graph inference reads the app's own `typescript`, an optional peer. Apps built
309
- from a Lovable template already have it. Without it — or with a copy exposing no
310
- stable JS API, as TypeScript 7 does before 7.1 — the build still succeeds and
311
- every graph carries one `unknown` node and the diagnostic
312
- `Install typescript to infer step graphs`.
313
- Sequential awaited `ctx.step("name", callback, options)` calls produce order edges;
314
- `await Promise.all([ctx.step(...), ctx.step(...)])` produces parallel branches
315
- that join at the next step. A `Promise.all()` mapped over a collection with the
316
- step ID template `step-${item.id}` produces one dynamic parallel node labeled
317
- from `meta.group.label`. Returned step promises work too. Keep step IDs literal
318
- outside this mapped form. A `try` block retains its durable operations when the
319
- `catch` only handles the error in ordinary code. Durable operations in a `catch`
320
- remain visible in a partial graph because edges do not encode error outcomes.
321
-
322
- An `if` whose body contains durable operations produces a `branch` node. Every
323
- durable operation inside it includes an outer-to-inner `meta.branches` path;
324
- each entry has a static `id` and agent-written `description`. Both sides of one
325
- condition use the same entry. The AST determines nesting and whether an edge is
326
- the `true` or `false` outcome, so metadata never declares topology. Branch IDs
327
- identify one `if` statement within the workflow.
78
+ Durable operations inside `if` and `else` branches include an outer-to-inner
79
+ `meta.branches` path. Both sides of one condition use the same static ID and
80
+ description:
328
81
 
329
82
  ```ts
330
83
  meta: {
@@ -333,368 +86,58 @@ meta: {
333
86
  }
334
87
  ```
335
88
 
336
- | Field | Meaning |
337
- | --- | --- |
338
- | `nodes[].id` | Unique occurrence ID within this graph; use as the UI node key |
339
- | `nodes[].kind` | Durable operation, `branch`, `parallel`, or `unknown` |
340
- | `nodes[].stepId` | Runtime durable ID for every statically known operation |
341
- | `nodes[].description` | User-facing description for every known durable operation and branch |
342
- | `nodes[].branchId` | Stable ID for an inferred `if` node |
343
- | `nodes[].condition` | Source expression from the corresponding `if` statement |
344
- | `nodes[].groupId` | Stable callsite ID for a dynamic parallel node |
345
- | `nodes[].cardinality` | `dynamic` for a runtime-sized parallel fan-out |
346
- | `nodes[].operation.kind` | Durable operation repeated by a parallel node |
347
- | `nodes[].operation.stepIdTemplate` | Display template for steps in a dynamic parallel node |
348
- | `nodes[].operation.description` | User-facing description shared by the repeated steps |
349
- | `nodes[].label` | Step ID, branch description, group label, or explanation of unsupported code |
350
- | `edges[]` | Order edges or branch edges with an AST-derived boolean `outcome`, referencing node IDs |
351
- | `complete` | Whether the handler uses only supported syntax |
352
- | `diagnostics` | Reasons the graph is partial |
353
-
354
- For example, `read` followed by parallel `transform-a` and `transform-b`, then
355
- `save`, produces `read → transform-a → save` and `read → transform-b → save`.
356
- Node IDs are deterministic for the same source, but may change when the handler
357
- is edited.
358
-
359
- Known durable nodes use the same `stepId` as runtime progress records. An
360
- explicit `{ id }` wins; otherwise the graph and runtime share the operation's
361
- derived default. `label` remains the display name.
362
-
363
- Graphs have `source: "inferred"` and `scope: "handler"`. They describe source
364
- structure, not run history or data dependencies, and exclude middleware and
365
- initialization. A mapped `Promise.all` is complete when its callback directly
366
- returns `ctx.step()` with a template-literal ID derived from a callback parameter.
367
- Loops, switch statements, conditional expressions, helper calls, dynamic step IDs,
368
- and unawaited steps produce `unknown` nodes and `complete: false`; steps inside
369
- unsupported code are not expanded. The UI should show these unknown nodes and mark
370
- partial graphs. Transforms that rewrite the handler may also produce a partial
371
- graph. A handler with no steps can have an empty graph.
372
-
373
- A step body is one atomic execution unit. Manifest generation rejects statically
374
- visible durable calls inside it, including `ctx.step`, `ctx.sleep`, `ctx.now`,
375
- and the other `ctx.*` operations. Move each durable operation into the workflow
376
- handler and pass its result into the step instead.
377
-
378
- Keep the workflow context in the handler. Manifest generation rejects passing,
379
- aliasing, destructuring, or returning `ctx`, and rejects detached durable methods
380
- such as `helper(ctx.step)`. Pass only extracted data such as `ctx.input` to
381
- helpers instead. This keeps durable control flow visible in the handler source
382
- used to build the graph.
383
-
384
- ## Steps endpoint (TanStack Start)
385
-
386
- The same `workflowsPlugin` that writes the manifests also emits
387
- `src/routes/api/workflows/$workflowId/steps.ts`, serving every registered
388
- workflow. There is no opt-in: a declared workflow with no endpoint cannot run.
389
- One plugin and one `entry` feed the manifest and route, so they cannot describe
390
- different workflow collections:
391
-
392
- ```ts
393
- import { tanstackStart } from "@tanstack/react-start/plugin/vite";
394
- import { workflowsPlugin } from "@lovable.dev/workflows-sdk/vite";
395
-
396
- export default defineConfig({
397
- plugins: [workflowsPlugin(), tanstackStart()],
398
- });
399
- ```
400
-
401
- A missing `entry` file is the only thing that suppresses the route: an app with
402
- no collection gets no endpoint.
403
-
404
- ### The route is unauthenticated
405
-
406
- **Any caller who reaches the route can run any declared workflow.** The SDK
407
- ships no request authentication today; signed invocation is the next piece of
408
- work on this endpoint. Until it lands, treat the endpoint as public and keep
409
- anything a stranger must not trigger — spend, mutation of another user's data,
410
- outbound mail — out of a declared workflow, or guard it inside the handler.
411
-
412
- Reachability is the lever an app has in the meantime. Public apps expose the
413
- route to the internet. Workspace and private apps are gated by the Lovable host,
414
- which is why `path` matters (below).
415
-
416
- ### Relocating the route with `path`
89
+ ## Schedules
417
90
 
418
- `path` sets the URL prefix; the workflow ID is appended as a dynamic segment,
419
- and the emitted file name follows the path. Workspace and private apps reach
420
- anonymous traffic only under an `/api/public` prefix — everything else is
421
- blocked by the host before it reaches the app — so those projects must move the
422
- route there for it to be reachable at all:
91
+ Declare schedules with `defineSchedule({ id, workflow, cadence, timeZone,
92
+ input })` and include them in the collection's `triggers`. The workflow must be
93
+ part of the same collection, and schedule IDs must be unique. This API declares
94
+ schedules; Lovable execution is not available yet.
423
95
 
424
96
  ```ts
425
- workflowsPlugin({ path: "/api/public/workflows" });
97
+ const morning = defineSchedule({
98
+ id: "morning-digest", workflow: digest, cadence: daily({ at: 9 }), timeZone: "Europe/Stockholm", input: {},
99
+ });
426
100
  ```
427
101
 
428
- That emits `src/routes/api/public/workflows/$workflowId/steps.ts` and serves
429
- `POST /api/public/workflows/{workflow-id}/steps`. The trade is explicit: the
430
- prefix that makes the route reachable also makes it anonymously reachable.
431
-
432
- The emitted file imports the collection and mounts its package handler. All
433
- runtime logic stays in the package. A generated banner is the plugin's
434
- ownership token: it rewrites and deletes only files that have it, and deletes
435
- its own orphans when `path` or `workflowIdParam` changes. Delete the banner line
436
- to take the route over. That is also the supported way to add a check of your
437
- own in front of the handler.
438
-
439
- | Option | Default | Meaning |
102
+ | Field | Default | Meaning |
440
103
  | --- | --- | --- |
441
- | `entry` | `src/lib/workflows/index.ts` | Collection entry; a missing file means no route |
442
- | `routesDir` | `src/routes` | Where the route file is written |
443
- | `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
444
- | `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
445
-
446
- ### How the emitted file imports the collection
447
-
448
- The plugin prefers an alias, so the specifier does not change when `path` moves:
449
-
450
- ```ts
451
- import workflows from "@/lib/workflows/index";
452
- ```
453
-
454
- It does not assume `@`. It reads the app's Vite `resolve.alias` and its
455
- tsconfig `compilerOptions.paths`, and picks an alias whose target directory
456
- contains the collection entry — preferring one both sources declare, then the
457
- deepest match.
458
-
459
- An alias is only emitted when the *bundler* can resolve it: a Vite
460
- `resolve.alias` entry, or a tsconfig `paths` entry when a plugin such as
461
- `vite-tsconfig-paths` is active. A tsconfig `paths` entry alone instructs the
462
- typechecker and not the bundler, so emitting it would fail the build.
463
-
464
- When no alias qualifies, the plugin falls back to a relative specifier
465
- (`../../../lib/workflows/index`), which always resolves. An app with no alias
466
- configured still builds; only the specifier is uglier, and its depth tracks
467
- `path`.
468
-
469
- ### Calling it
470
-
471
- Each workflow gets one route for an external engine to drive one atomic step per
472
- request.
104
+ | `cadence` | — | `hourly()`, `daily()`, or `weekly()` |
105
+ | `timeZone` | — | Canonical IANA region name |
106
+ | `overlapPolicy` | `"skip"` | `skip`, `allow`, or `buffer-one` |
107
+ | `enabled` | `true` | `false` declares a paused schedule |
473
108
 
474
- | Route | Does |
109
+ | Cadence | Example |
475
110
  | --- | --- |
476
- | `POST /api/workflows/{id}/steps` | Advances a singleton frontier or executes one selected step |
477
-
478
- An unknown workflow ID returns 404 and an unparseable body 400.
479
-
480
- ### The memo is the run
481
-
482
- There is no run store. A run's entire state is its **memo** — the list of
483
- settled operations — and the caller carries it between calls:
484
-
485
- ```jsonc
486
- [{
487
- "seq": 0,
488
- "stepId": "greeting",
489
- "occurrence": 0,
490
- "kind": "step",
491
- "meta": { "description": "Create a personalized greeting" },
492
- "status": "completed",
493
- "result": "Hello, yehya!"
494
- }]
495
- ```
111
+ | Hourly | `hourly()` |
112
+ | Selected hours | `daily({ at: [0, 6, 12, 18] })` |
113
+ | Selected weekdays | `daily({ at: 9, days: ["mon", "tue", "wed", "thu", "fri"] })` |
114
+ | Weekly | `weekly({ on: "monday", at: 7 })` |
496
115
 
497
- An entry is keyed by `stepId` and `occurrence` (which call of that id in the
498
- run, from 0) — never by position or `seq`. Two parallel branches can reach the
499
- same pair of operations in either order from one pass to the next, so call order
500
- is reported but is not the identity.
501
-
502
- Every response returns a `memoDelta` and an `inputHash`. Merge the delta into the
503
- memo by `(stepId, occurrence)`, then send the full memo, `inputHash`, `runId`, and
504
- the same `input` on the next call. Replay re-runs the handler from the top, and
505
- the memo does not carry the input. `inputHash` binds the memo to the input it came
506
- from: resuming with a different one is a 400. Key order in the input does not
507
- affect it. Because state travels in the request, a run survives a restart and can
508
- continue on a different instance.
509
-
510
- Replay is what makes this work: the handler re-runs from the top on every call,
511
- settled operations answer from the memo instead of executing again, and
512
- `ctx.state` plus ordinary control flow rebuild themselves. A settled operation
513
- can sit beside an earlier pending one — `ctx.now()` pinned next to a step still
514
- waiting in the same `Promise.all`. An entry must match the kind of operation
515
- replay finds at its id, so a tampered or stale memo fails the call rather than
516
- answering the wrong one:
517
-
518
- ```json
519
- { "disposition": "failed", "error": "non-deterministic replay: memo has approve \"thing\" (#0), replay produced step" }
520
- ```
521
-
522
- **Every step ID must be unique within a workflow.** Manifest generation rejects
523
- a repeated literal ID in sequential calls, parallel branches, mutually exclusive
524
- branches, loops, and callbacks. Dynamic IDs cannot be proven at build time, so
525
- the runtime refuses the second step that resolves to an ID already reached.
526
-
527
- `ctx.now()`, `ctx.uuid()`, `ctx.sleep(ms)` and the other durable operations fall
528
- back to a default ID. Two calls sharing one cannot be told apart on replay, so
529
- the second is refused. Pass `{ id }` per call site: `ctx.now({ id: "started" })`.
530
-
531
- Manifest generation rejects this before a run exists, when the arguments are
532
- literal:
533
-
534
- ```text
535
- workflow "greet" calls ctx.now() 2 times with the default id "now";
536
- replay cannot tell them apart, so pass an explicit { id } per call site
537
- ```
538
-
539
- The same applies to two `ctx.sleep(1000)` calls, two waits on one event name, or
540
- two approvals with one title. Their default ID is derived from the argument, so
541
- only a repeated argument collides. A dynamic argument is left to the runtime
542
- check.
543
-
544
- **Handler code outside a step runs on every call.** Keep side effects inside
545
- `ctx.step`, which is memoized; a bare `fetch` in the handler body repeats each
546
- pass. A pass also allows only a bounded amount of such work — 5s by default —
547
- before reporting the run stalled.
548
-
549
- ### The memo is unauthenticated input
550
-
551
- **A caller supplies the memo, and the route does not authenticate it.** Anything
552
- the memo says is already settled is taken as settled, including an approval's
553
- decision. A caller who can reach the route can therefore hand back
554
- `{"kind": "approve", "status": "completed", "result": {"approved": true}}` and
555
- skip the human, or mark an expensive step completed with a fabricated result and
556
- skip the work. `inputHash` binds a memo to one input, so a forged memo cannot be
557
- replayed against a different record, but it is computed from the request and so
558
- is no barrier on its own.
559
-
560
- Until signed invocation lands, **do not treat `ctx.approve` as a security
561
- boundary on these routes**, and do not put an operation behind one that a
562
- stranger must not be able to declare done. Reachability is the only control an
563
- app has in the meantime; see `path` above.
564
-
565
- ### Stepping through a run
566
-
567
- ```bash
568
- POST /api/workflows/greet/steps
569
- { "input": { "name": "yehya" } }
570
- -> { "disposition": "advanced",
571
- "executed": { "stepId": "greeting", "occurrence": 0, "kind": "step", "status": "completed" },
572
- "memoDelta": [{ "stepId": "greeting", "occurrence": 0, ... }],
573
- "next": [{ "seq": 1, "stepId": "shout", "occurrence": 0, "kind": "step" }] }
574
-
575
- POST /api/workflows/greet/steps
576
- { "action": "execute", "step": { "stepId": "shout", "occurrence": 0, "kind": "step" },
577
- "input": { "name": "yehya" }, "memo": [...], "inputHash": "9f2c...", "runId": "run_..." }
578
- -> { "disposition": "completed", "memoDelta": [...], "next": [], "output": "HELLO, YEHYA!" }
579
- ```
580
-
581
- Omitting `action` means `"advance"`. When the current frontier contains exactly
582
- one app-executable step, `advance` executes it and returns the next frontier. A
583
- sequential workflow therefore needs one HTTP call per step, including the first.
116
+ Hours are whole numbers from 0 through 23; schedules do not accept minute or
117
+ raw-cron fields. `timeZone` is required and accepts `"UTC"` or a canonical IANA
118
+ region such as `"America/New_York"`. A scheduled hour is approximate: Lovable
119
+ chooses a stable offset within the corresponding scheduling window.
584
120
 
585
- ### Driving a run from an orchestrator
121
+ `overlapPolicy` controls what happens when a schedule becomes due while its
122
+ previous run is active. `skip` drops it, `allow` starts another run, and
123
+ `buffer-one` starts the earliest missed run after the active run finishes.
586
124
 
587
- Use the response disposition to choose the next call:
125
+ ## Build integration
588
126
 
589
- | Disposition | Engine action |
590
- | --- | --- |
591
- | `advanced` | Merge `memoDelta`, then execute the single entry in `next`. |
592
- | `fork` | Merge `memoDelta`, then execute each app-executable entry in `next` in a separate concurrent request using that same memo. |
593
- | `waiting` | Settle the external operations in `next`, then call `advance`. |
594
- | `completed` | Persist `output`; the run is done. |
595
- | `failed` | Apply the engine's retry or failure policy. |
596
-
597
- At a fork, every `execute` request receives the same base memo and selects one
598
- `{ kind: "step", stepId, occurrence }`. Merge all returned deltas, then call
599
- `advance` once. That replay crosses the join and immediately executes a
600
- singleton tail when one exists. Do not schedule from one branch's `next`: a
601
- partial branch response cannot see results still running in its siblings.
602
-
603
- An `execute` call runs only its selected step. The endpoint returns 409
604
- `stale_step` if that reference is not executable from the supplied memo.
605
-
606
- Keep a step's result small: it travels in the memo on every later call, so a
607
- large payload is resent for the rest of the run. Write bulk data to storage
608
- inside the step and return the key.
609
-
610
- Each call re-runs the handler from the top. Step bodies run only in their
611
- selected request, so side effects belong inside a step.
612
-
613
- `next` reports an operation's `stepId`, `kind`, and author-supplied `meta`,
614
- including its description and group. An approval's top-level authoring
615
- description is copied into runtime metadata for the same response shape. `next`
616
- does not report a step's input:
617
- `ctx.step(id, fn, options)` closes over its arguments rather than declaring
618
- them, so the input is not knowable without running `fn`. Deterministic values
619
- (`ctx.now`, `ctx.uuid`) are pinned into `memoDelta`, so concurrent calls replay
620
- the same values after the engine merges the delta.
621
-
622
- ### Waiting on something outside the app
623
-
624
- `ctx.sleep`, `ctx.waitForEvent` and `ctx.approve` cannot be settled by the app,
625
- so they are never executed — they come back as pending operations carrying what
626
- a caller needs to resolve them:
627
-
628
- ```json
629
- { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
630
- "meta": { "description": "Ask a reviewer to approve the refund" },
631
- "config": { "title": "Approve refund", "description": "Ask a reviewer to approve the refund" } }
632
- ```
633
-
634
- The endpoint returns `waiting` with that list in `next`. Resume by appending the
635
- decision to the memo, preserving its `meta`, and calling `advance`:
127
+ Add `workflowsPlugin()` before the TanStack Start plugin. Its `entry` defaults
128
+ to `src/lib/workflows/index.ts` and must default-export the registered
129
+ collection. See [the Vite example](examples/vite.config.ts).
636
130
 
637
- ```jsonc
638
- { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
639
- "meta": { "description": "Ask a reviewer to approve the refund" },
640
- "status": "completed", "result": { "approved": true, "approvalId": "apr_1" } }
131
+ ```ts
132
+ plugins: [
133
+ workflowsPlugin(),
134
+ tanstackStart(),
135
+ ];
641
136
  ```
642
137
 
643
- `createTanStackWorkflowHandler` is still exported for the engine-backed path
644
- (`runWorkflow` plus a `RunStore`, `inMemoryRunStore()` by default). No emitted
645
- route uses it: a process-local store loses runs on restart and is invisible to
646
- other instances, which is what the memo model replaces.
647
-
648
- ### Not yet carried over
649
-
650
- `ctx.step`'s `retries` and `timeout` options are accepted and ignored — the
651
- caller decides whether to re-issue a failed step. Step retry, timeouts, and
652
- `previousVersions` routing are follow-ups.
653
-
654
- The path carries no build ID. Version pinning belongs to the signed invocation,
655
- which leaves it stable across deployments and safe to publish in a manifest.
656
- Triggers name a workflow rather than an endpoint, so no trigger identifier
657
- appears in the URL.
658
-
659
- ## Public entry points
660
-
661
- The package has two, and neither mirrors the source tree:
138
+ ## Imports
662
139
 
663
140
  | Import | Provides |
664
141
  | --- | --- |
665
- | `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and the `createStepsHandler` route handler |
666
- | `@lovable.dev/workflows-sdk/vite` | `workflowsPlugin`, the build-time Vite plugin |
667
-
668
- The export map is a contract; the directory layout under `src/` is not. They are
669
- deliberately decoupled, so the package can be reorganised without a breaking
670
- change for apps that already have an emitted route.
671
-
672
- The package sets `"sideEffects": false` and the handler is a plain re-export, so
673
- a client bundle importing only authoring APIs drops the execution engine.
674
-
675
- ## Next PRs
676
-
677
- Connect the manifest and app code to Lovable deployment and runtime execution.
678
- Derive and apply the per-schedule smear on the control plane. Define support for
679
- TanStack primitives, version routing, and schedule policies.
680
- Add webhook and app-event triggers to the same `triggers` array.
681
-
682
- ## Publishing dev builds
683
-
684
- The [publishing workflow](../../.github/workflows/publish-workflows-sdk.yml)
685
- publishes the version committed in `package.json` to npm's `latest` tag when SDK
686
- changes land on `main`. Manage versions manually: `0.0.0-dev`, `0.0.0-dev.1`,
687
- `0.0.0-dev.2`, and so on. The workflow rejects versions outside this series and
688
- skips versions already published. Manual runs default to a dry run.
689
- See [the setup guide](PUBLISHING.md) for the
690
- one-time bootstrap and npm trusted-publisher configuration.
691
-
692
- Install the newest build with `npm install @lovable.dev/workflows-sdk`, or pin
693
- the exact version shown in the workflow run's summary. `latest` tracks every dev
694
- publish while the SDK is pre-1.0; the older `dev` tag is frozen at `0.0.0-dev.2`.
695
-
696
- The engine's embedded SDK
697
- ([`sdk_embed/index.ts`](../../go/workflows/services/workflows/internal/bundler/sdk_embed/index.ts))
698
- provides the engine contract. Use [`mcp-js`](../lovable-mcp-js) as the reference
699
- for separating authoring, manifest extraction, and framework integration. The
700
- workflow prototype's `ts/workflow-sdk` supplies adapter and manifest examples.
142
+ | `@lovable.dev/workflows-sdk` | Workflow authoring, registration, cadences, and schedules |
143
+ | `@lovable.dev/workflows-sdk/vite` | Lovable build integration |
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DKuhUjgo.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-Qx9mvqnC.js";
2
2
  //#region src/manifests/branch-metadata.ts
3
3
  const optionsArgument = {
4
4
  step: 2,
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DKuhUjgo.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-Qx9mvqnC.js";
2
2
  //#region src/manifests/context-escapes.ts
3
3
  const durableMethods = /* @__PURE__ */ new Set([
4
4
  "step",
@@ -1,5 +1,5 @@
1
1
  import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
2
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DKuhUjgo.js";
2
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-Qx9mvqnC.js";
3
3
  //#region src/manifests/duplicate-ids.ts
4
4
  /** Where an explicit `{ id }` would sit for each operation. */
5
5
  const optionsArgument = {
@@ -83,6 +83,11 @@ async function findDuplicateOperationIds(handler) {
83
83
  case "step": return;
84
84
  }
85
85
  }
86
+ function repeatedLoopRegion(parent, child) {
87
+ if (ts.isForOfStatement(parent) || ts.isForInStatement(parent)) return parent.statement === child;
88
+ if (ts.isForStatement(parent)) return parent.statement === child || parent.condition === child || parent.incrementor === child;
89
+ return ts.isWhileStatement(parent) || ts.isDoStatement(parent);
90
+ }
86
91
  function placement(call) {
87
92
  const branches = /* @__PURE__ */ new Map();
88
93
  let repeatable = false;
@@ -96,7 +101,7 @@ async function findDuplicateOperationIds(handler) {
96
101
  if (parent.whenTrue === child) branches.set(String(parent.pos), "true");
97
102
  else if (parent.whenFalse === child) branches.set(String(parent.pos), "false");
98
103
  } else if (ts.isCaseClause(parent) || ts.isDefaultClause(parent)) branches.set(String(parent.parent.pos), String(parent.parent.clauses.indexOf(parent)));
99
- else if (parent !== fn && (ts.isForStatement(parent) || ts.isForOfStatement(parent) || ts.isForInStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent) || ts.isFunctionLike(parent))) repeatable = true;
104
+ else if (parent !== fn && (repeatedLoopRegion(parent, child) || ts.isFunctionLike(parent))) repeatable = true;
100
105
  child = parent;
101
106
  parent = parent.parent;
102
107
  }
@@ -183,13 +183,13 @@ function serializeSchema(schema, direction, label) {
183
183
  }
184
184
  }
185
185
  async function generateManifests(definition) {
186
- const { extractWorkflowGraph } = await import("./graph-DKuhUjgo.js");
187
- const { findBranchMetadataIssues } = await import("./branch-metadata-BBVwmGtr.js");
188
- const { findWorkflowContextEscapes } = await import("./context-escapes-hJTV5O7I.js");
189
- const { findDuplicateOperationIds } = await import("./duplicate-ids-CBASgH8g.js");
190
- const { findNestedDurableOperations } = await import("./nested-operations-CspliO3h.js");
191
- const { findOperationDescriptionIssues } = await import("./operation-descriptions-ugamonwF.js");
192
- const { findStepMetadataIssues } = await import("./step-metadata-DJRmHyNE.js");
186
+ const { extractWorkflowGraph } = await import("./graph-Qx9mvqnC.js");
187
+ const { findBranchMetadataIssues } = await import("./branch-metadata-IXuazOmY.js");
188
+ const { findWorkflowContextEscapes } = await import("./context-escapes-x0J0HUgC.js");
189
+ const { findDuplicateOperationIds } = await import("./duplicate-ids-NnTrnieX.js");
190
+ const { findNestedDurableOperations } = await import("./nested-operations-DYVa5c5A.js");
191
+ const { findOperationDescriptionIssues } = await import("./operation-descriptions-BLZC8bxV.js");
192
+ const { findStepMetadataIssues } = await import("./step-metadata-MjyYQjOy.js");
193
193
  const collection = registerWorkflows(definition);
194
194
  const manifests = [];
195
195
  for (const workflow of collection.workflows) {
@@ -220,6 +220,10 @@ async function generateManifests(definition) {
220
220
  const step = metadataIssue.stepId ? `ctx.step(${JSON.stringify(metadataIssue.stepId)})` : "ctx.step()";
221
221
  throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" ${step} is declared in a loop or callback and must include a static { meta: { group: { id: "...", label: "..." } } }`);
222
222
  }
223
+ if (metadataIssue?.kind === "loop-form") {
224
+ const step = metadataIssue.stepId ? `ctx.step(${JSON.stringify(metadataIssue.stepId)})` : "ctx.step()";
225
+ throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" ${step} uses an unsupported loop form; await ctx.step() directly as the only statement in a for...of loop for sequential execution, or use Promise.all(items.map((item) => ctx.step(...))) for parallel execution`);
226
+ }
223
227
  if (metadataIssue?.kind === "duplicate-group") throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" uses group id ${JSON.stringify(metadataIssue.groupId)} at more than one repeated step callsite; every group id must identify one callsite`);
224
228
  const operationDescriptionIssue = (await findOperationDescriptionIssues(workflow.handler))[0];
225
229
  if (operationDescriptionIssue) {
@@ -152,6 +152,27 @@ async function extractWorkflowGraph(handler) {
152
152
  template
153
153
  };
154
154
  }
155
+ function sequentialLoopStep(node) {
156
+ if (node.awaitModifier || !ts.isVariableDeclarationList(node.initializer)) return void 0;
157
+ const declarations = node.initializer.declarations;
158
+ if (declarations.length !== 1) return void 0;
159
+ const declaration = declarations[0];
160
+ if (!ts.isIdentifier(declaration.name) || declaration.initializer) return void 0;
161
+ let statement = node.statement;
162
+ if (ts.isBlock(statement)) statement = statement.statements.length === 1 ? statement.statements[0] : void 0;
163
+ if (!statement || !ts.isExpressionStatement(statement)) return void 0;
164
+ let body = statement.expression;
165
+ while (ts.isParenthesizedExpression(body)) body = body.expression;
166
+ if (!ts.isAwaitExpression(body)) return void 0;
167
+ let awaited = body.expression;
168
+ while (ts.isParenthesizedExpression(awaited)) awaited = awaited.expression;
169
+ if (!durableCall(awaited) || awaited.expression.name.text !== "step") return;
170
+ const template = stepIdTemplate(awaited.arguments[0], /* @__PURE__ */ new Set([declaration.name.text]));
171
+ return template === void 0 ? void 0 : {
172
+ call: awaited,
173
+ template
174
+ };
175
+ }
155
176
  function readableOptions(node) {
156
177
  return node && ts.isObjectLiteralExpression(node) && node.properties.every(ts.isPropertyAssignment) ? node : void 0;
157
178
  }
@@ -530,6 +551,26 @@ async function extractWorkflowGraph(handler) {
530
551
  const completedFinally = finallyFlow.normal.reachable;
531
552
  return statementFlow(path(finallyFlow.normal.tails, normal.reachable && completedFinally), mergePaths(finallyFlow.thrown, path(finallyFlow.normal.tails, thrown.reachable && completedFinally)), mergePaths(finallyFlow.returned, path(finallyFlow.normal.tails, returned.reachable && completedFinally)), mergePaths(finallyFlow.stopped, path(finallyFlow.normal.tails, stopped.reachable && completedFinally)));
532
553
  }
554
+ if (ts.isForOfStatement(statement)) {
555
+ const repeated = sequentialLoopStep(statement);
556
+ if (repeated) {
557
+ const iterable = expression(statement.expression, parents);
558
+ const metadata = stepMetadata(repeated.call);
559
+ const tails = metadata?.group ? addNode({
560
+ kind: "loop",
561
+ groupId: metadata.group.id,
562
+ cardinality: "dynamic",
563
+ execution: "sequential",
564
+ operation: {
565
+ kind: "step",
566
+ stepIdTemplate: repeated.template,
567
+ description: metadata.description
568
+ },
569
+ label: metadata.group.label
570
+ }, iterable.tails) : unknown("Dynamic sequential steps need static group metadata", iterable.tails);
571
+ return statementFlow(path(tails), mergePaths(iterable.thrown, path(tails)));
572
+ }
573
+ }
533
574
  if (ts.isEmptyStatement(statement)) return statementFlow(path(parents));
534
575
  return statementFlow(path(unknown("Loops and other control flow are not supported yet", parents)));
535
576
  }
package/dist/index.d.ts CHANGED
@@ -82,6 +82,16 @@ type WorkflowGraphNodeDetails = {
82
82
  stepIdTemplate: string;
83
83
  description: string;
84
84
  };
85
+ } | {
86
+ kind: "loop";
87
+ groupId: string;
88
+ cardinality: "dynamic";
89
+ execution: "sequential";
90
+ operation: {
91
+ kind: "step";
92
+ stepIdTemplate: string;
93
+ description: string;
94
+ };
85
95
  } | {
86
96
  kind: "approve";
87
97
  stepId: string;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
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-DJ7bQOT7.js";
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-BNbOHB23.js";
2
2
  import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
3
3
  import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
4
4
  //#region src/stacks/tanstack/sse.ts
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DKuhUjgo.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-Qx9mvqnC.js";
2
2
  //#region src/manifests/nested-operations.ts
3
3
  const durableMethods = [
4
4
  "step",
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DKuhUjgo.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-Qx9mvqnC.js";
2
2
  //#region src/manifests/operation-descriptions.ts
3
3
  const optionsArgument = {
4
4
  approve: 0,
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-DKuhUjgo.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-Qx9mvqnC.js";
2
2
  //#region src/manifests/step-metadata.ts
3
3
  async function findStepMetadataIssues(handler) {
4
4
  const api = await loadTypeScript();
@@ -22,19 +22,56 @@ async function findStepMetadataIssues(handler) {
22
22
  if ((ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name) ? entry.name.text : void 0) === name) return entry.initializer;
23
23
  }
24
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
+ }
25
30
  function repeatable(call) {
31
+ let child = call;
26
32
  let parent = call.parent;
27
33
  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;
34
+ if (repeatedLoopRegion(parent, child) || ts.isFunctionLike(parent)) return true;
35
+ child = parent;
29
36
  parent = parent.parent;
30
37
  }
31
38
  return false;
32
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
+ }
33
65
  const issues = [];
34
66
  const groups = /* @__PURE__ */ new Set();
35
67
  const visit = (node) => {
36
68
  if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text === "step") {
37
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
+ });
38
75
  const meta = property(node.arguments[2], "meta");
39
76
  if (literalString(property(meta, "description")) === void 0) issues.push({
40
77
  kind: "description",
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as generateManifests } from "./generate-DJ7bQOT7.js";
1
+ import { t as generateManifests } from "./generate-BNbOHB23.js";
2
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";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/workflows-sdk",
3
- "version": "0.0.0-dev.22",
3
+ "version": "0.0.0-dev.24",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "dev",