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

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.
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.
9
-
10
- ## Authoring
11
-
12
- 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
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
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @lovable.dev/workflows-sdk
27
11
  ```
28
12
 
29
- Each workflow's `index.ts` exports its definition. The collection entry imports
30
- all workflow definitions and default-exports `registerWorkflows(...)`:
13
+ ## Define workflows
14
+
15
+ Use `createWorkflow({ id, version, input, output }).handler(...)` to define a workflow
16
+ and `createMiddleware` to extend its typed context. Standard Schema libraries
17
+ such as Zod provide input and output inference.
18
+
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,245 +26,156 @@ 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
+ ## Workflow versions
48
35
 
49
- ## Triggers
36
+ Every workflow requires an explicit `version`, including retained definitions.
37
+ Start with `"v1"`; introduce a new label when changing behavior, schemas, or
38
+ relevant helpers. Keep existing version implementations unchanged while runs drain.
39
+ Registration rejects missing, empty, and invalid labels. Existing unversioned
40
+ runs must drain on their original SDK deployment before upgrading.
50
41
 
51
- A workflow runs when something triggers it, and a schedule is the first kind of
52
- trigger: a clock. Triggers go in `registerWorkflows({ workflows, triggers })`,
53
- and each carries a `type` naming its kind. Webhook and app-event triggers will
54
- join the same array.
42
+ Keep the current definition in `workflows` and attach older definitions with
43
+ `.previousVersions([v1])` before `.handler(...)`. Each definition has the same
44
+ workflow ID and a distinct `version` passed to `createWorkflow`. Versions accept
45
+ 1–128 letters, digits, dots, hyphens, or underscores, starting with a letter or
46
+ digit. The combined manifest filename must fit 255 characters. See the [versioned example](examples/src/lib/workflows/versioned/index.ts).
55
47
 
56
- A schedule's *cadence* is how often the clock fires. `every()`, `hourly()`,
57
- `daily()`, and `weekly()` build one; there is no raw cron.
48
+ The build emits one manifest per version. The top-level definition has
49
+ `current: true`; retained definitions have `current: false` and no triggers.
50
+ Schedules reference the top-level definition and start its version.
58
51
 
59
- ## Schedules
52
+ Steps responses include `workflowVersion`. Persist it with the run and send it
53
+ on every later request, including an empty memo. A missing version on a
54
+ resume or an unavailable version fails before replay.
60
55
 
61
- Declare a schedule with `defineSchedule({ id, workflow, cadence, timeZone, input })` and
62
- include it in `registerWorkflows({ workflows, triggers })`. `workflow` refers to
63
- the same definition object included in `workflows`; `input` is required and
64
- inferred from that workflow. Multiple schedules can target one workflow. Schedule
65
- IDs must be unique within the app's collection. This API declares schedules but
66
- does not install timers or start runs.
56
+ Keep old definitions and their relevant helpers unchanged until their runs and
57
+ pending execution attempts drain. Removing a definition makes its version
58
+ unavailable; existing runs never switch to the current version automatically.
59
+
60
+ ## Durable operations
61
+
62
+ Every durable operation needs a static, user-facing description:
63
+
64
+ | Operation | Description field |
65
+ | --- | --- |
66
+ | `ctx.step` | Third argument: `meta.description` |
67
+ | `ctx.sleep`, `ctx.sleepUntil` | Second argument: `meta.description` |
68
+ | `ctx.waitForEvent` | Second argument: `meta.description` |
69
+ | `ctx.now`, `ctx.uuid` | First argument: `meta.description` |
70
+ | `ctx.approve` | First argument: `description` |
71
+
72
+ Both `ctx.approve` and `ctx.waitForEvent` require `timeoutMs`: a duration in
73
+ milliseconds, written as a finite numeric literal of at least 60000 (one minute) (for example,
74
+ `3600000` for one hour or `86400000` for one day). The Vite build fails if it
75
+ is omitted, computed, or invalid. Do not pass an absolute timestamp or the
76
+ upstream `deadline` option. Execution computes expiry when the wait first
77
+ parks, then preserves that expiry across replays.
67
78
 
68
79
  ```ts
69
- import { daily, defineSchedule, every, hourly, weekly } from "@lovable.dev/workflows-sdk";
70
-
71
- defineSchedule({ id: "heartbeat", workflow: sync, cadence: every("5m"), timeZone: "UTC", input: {} });
72
- defineSchedule({ id: "sweep", workflow: sync, cadence: hourly({ at: ":30" }), timeZone: "UTC", input: {} });
73
- defineSchedule({ id: "digest", workflow: digest, cadence: daily(), timeZone: "Europe/Stockholm", input: {} });
74
-
75
- defineSchedule({
76
- id: "weekday-digest",
77
- workflow: digest,
78
- cadence: daily({ at: "09:00", days: ["mon", "tue", "wed", "thu", "fri"] }),
79
- timeZone: "America/New_York",
80
- smear: { window: "15m" },
81
- input: {},
80
+ await ctx.step("load-customer", () => loadCustomer(ctx.input.customerId), {
81
+ meta: { description: "Load the customer record" },
82
82
  });
83
+ ```
83
84
 
84
- defineSchedule({
85
- id: "monday-report",
86
- workflow: report,
87
- cadence: weekly({ on: "monday", at: "07:00" }),
88
- timeZone: "Europe/Stockholm",
89
- input: {},
85
+ Every durable operation takes an explicit `id` — `ctx.approve({ id, title, timeoutMs: 86400000 })`,
86
+ `ctx.waitForEvent(name, { id, timeoutMs: 3600000 })`, `ctx.sleep(ms, { id })`, `ctx.now({ id })` —
87
+ and none is derived from a title, name or duration. IDs share one namespace per
88
+ workflow, so the build fails on a missing or repeated one, including two calls
89
+ on mutually exclusive branches. Keep side effects inside step bodies;
90
+ handler code outside a step may run more than once. A step body is one atomic
91
+ execution unit and cannot contain another durable operation.
92
+
93
+ Keep durable control flow in the workflow handler. Do not pass, alias,
94
+ destructure, or return `ctx`, and do not detach methods such as `ctx.step`.
95
+ Pass extracted data such as `ctx.input.customerId` to helpers instead.
96
+
97
+ ### Repeated steps
98
+
99
+ A step inside a loop or callback needs `meta.group` with a stable ID and
100
+ user-facing label. Each repeated step still needs its own dynamic ID:
101
+
102
+ ```ts
103
+ ctx.step(`process-${item.id}`, () => processItem(item), {
104
+ meta: { description: "Process an item", group: { id: "process-items", label: "Process items" } },
105
+ });
106
+ ```
107
+
108
+ For dynamic sequential work, await one step directly as the only statement in
109
+ a `for...of` loop. For dynamic parallel work, use a mapped `Promise.all()`.
110
+ Fixed `Promise.all([stepA, stepB])` branches and ordinary sequential steps do
111
+ not need a group.
112
+
113
+ ### Conditional steps
114
+
115
+ Durable operations inside `if` and `else` branches include an outer-to-inner
116
+ `meta.branches` path. Both sides of one condition use the same static ID and
117
+ description:
118
+
119
+ ```ts
120
+ meta: {
121
+ description: "Publish the approved draft",
122
+ branches: [{ id: "editor-approved", description: "The editor approved the draft" }],
123
+ }
124
+ ```
125
+
126
+ ## Schedules
127
+
128
+ Declare schedules with `defineSchedule({ id, workflow, cadence, timeZone,
129
+ input })` and include them in the collection's `triggers`. The workflow must be
130
+ part of the same collection, and schedule IDs must be unique. This API declares
131
+ schedules; Lovable execution is not available yet.
132
+
133
+ ```ts
134
+ const morning = defineSchedule({
135
+ id: "morning-digest", workflow: digest, cadence: daily({ at: [9] }), timeZone: "Europe/Stockholm", input: {},
90
136
  });
91
137
  ```
92
138
 
93
139
  | Field | Default | Meaning |
94
140
  | --- | --- | --- |
95
- | `cadence` | — | `every()`, `hourly()`, `daily()`, or `weekly()` |
96
- | `timeZone` | — | IANA region name the cadence is interpreted in |
97
- | `overlapPolicy` | `"skip"` | `skip`, `cancel-previous`, or `terminate-previous` |
98
- | `enabled` | `true` | `false` declares a paused schedule without deleting it |
99
- | `smear` | see below | `false`, or `{ window: "15m" }` to spread firings over a window |
100
-
101
- There are four cadences and no raw cron, so every schedule has a firing period
102
- the SDK can compute and a calendar the SDK can check. `at` pins the position
103
- inside the period on all three calendar cadences, and omitting it hands that
104
- position to the smear:
105
-
106
- | Cadence | Pins | Example | Derived `cron` |
107
- | --- | --- | --- | --- |
108
- | `every(interval)` | — | `every("5m")` | `*/5 * * * *` |
109
- | `hourly({ at })` | minute past the hour | `hourly({ at: ":30" })` | `30 * * * *` |
110
- | `daily({ at, days })` | time of day, days of week | `daily({ at: "09:00", days: ["mon", "tue", "wed", "thu", "fri"] })` | `0 9 * * 1-5` |
111
- | `weekly({ on, at })` | one day, time of day | `weekly({ on: "monday", at: "07:00" })` | `0 7 * * 1` |
112
-
113
- `every` takes a whole number of minutes, hours, or days that divides its unit
114
- evenly — `1m` through `30m`, `1h` through `12h`, or `1d`. `hourly({ at: ":30" })`
115
- carries the leading colon so a minute past the hour can never be misread as an
116
- hour of the day. `days` accepts `"mon"` or `"monday"` in any case and is stored
117
- sorted and deduplicated, so two orderings of one weekday set are one schedule.
118
-
119
- `weekly({ on, at })` is the single-day shorthand for `daily({ at, days: [on] })`
120
- and resolves into exactly that cadence. There is one internal representation of
121
- a day-restricted schedule, so the two spellings emit byte-identical manifests
122
- and hash alike. There is no `"weekdays"` or `"weekends"` shorthand: it would add
123
- a third spelling of a set `days` already states, and "the weekend" is Friday and
124
- Saturday in much of the world, so the word would quietly mean the wrong days.
125
-
126
- The manifest still carries a five-field `cron` string derived from the cadence,
127
- because the engine registers native schedules that take cron. Apps no longer
128
- write it.
129
-
130
- ### Time zone
131
-
132
- `timeZone` is required on every schedule. There is no default, because every
133
- available default is wrong: `daily({ at: "09:00" })` in UTC is not the 09:00 a
134
- reader of the digest expects, and the build machine's own zone would make one
135
- app source fire at different times depending on where it was built.
136
-
137
- It must be an IANA region name such as `"Europe/Stockholm"`, or `"UTC"`.
138
- Fixed offsets and abbreviations — `"+05:00"`, `"-0800"`, `"EST"` — are
139
- rejected even though the platform accepts them: they do not observe daylight
140
- saving, so `"EST"` is an hour off US Eastern for two-thirds of the year.
141
- `every()` needs one too, since its derived cron anchors to hour and day
142
- boundaries that a DST change moves.
143
-
144
- Everything is validated when the schedule is defined, at build time: a malformed
145
- interval, time of day, or weekday name, an unknown `overlapPolicy`, a missing or
146
- non-IANA zone, and a smear window wider than the cadence's own firing period all
147
- fail the build.
148
-
149
- ### Smear
150
-
151
- Tens of thousands of apps declaring `daily()` must not fire in the same minute.
152
- A schedule therefore carries a smear *policy*, not a concrete offset. A cadence
153
- that leaves its position in the period unpinned defaults to spreading over that
154
- whole period: bare `daily()` to `{ strategy: "hash", windowSeconds: 86400 }` and
155
- bare `hourly()` to `{ strategy: "hash", windowSeconds: 3600 }`. Every pinned
156
- cadence — `every`, `hourly({ at })`, `daily({ at })`, `weekly({ on, at })` —
157
- defaults to `{ strategy: "none" }`, because the app author chose the time.
158
- `smear: false` on an unpinned cadence is rejected: pass `{ at }` instead.
159
-
160
- The concrete offset is derived once, when the control plane registers the
161
- manifest, as `fnv1a64(projectId + "\0" + scheduleId) % windowSeconds` seconds
162
- after the manifest's `cron`. That keeps the manifest project-independent and
163
- therefore content-addressable, while giving two projects that both name a
164
- schedule `digest` different fire minutes, and giving one project the same fire
165
- minute across every rebuild. `smearOffsetSeconds(projectId, scheduleId,
166
- windowSeconds)` is the reference implementation the engine and the run UI agree
167
- with.
168
-
169
- Any cadence can opt in with `smear: { window }`. The window may never exceed the
170
- cadence's own firing period, or two firings would overrun each other; the bound
171
- applies to every cadence, since every cadence's period is computable. For a day
172
- set the period is the shortest gap between two firings, not the repeat length:
173
- `daily({ days: ["mon", "fri"] })` fires again in three days and then in four, so
174
- its bound is three days — capped, as every window is, at `1d`.
175
-
176
- The [example](examples/src/lib/workflows/index.ts) declares a 09:00 greeting in
177
- Europe/Stockholm, a smeared weekday greeting in America/New_York, a Monday
178
- report, a five-minute heartbeat, an hourly sweep, and a paused daily digest.
179
-
180
- ## Manifest generation
181
-
182
- Add `workflowsManifest({ entry: "src/lib/workflows/index.ts" })` from
183
- `@lovable.dev/workflows-sdk/vite` to the app's Vite plugins. The entry must
184
- default-export its `registerWorkflows()` collection. Each production build writes
185
- one manifest per workflow to `.lovable/workflows/{workflow-name}.json` relative
186
- to the app root. For example, `greet` produces `.lovable/workflows/greet.json`.
187
- Generation errors fail the build. See [the Vite example](examples/vite.config.ts).
188
-
189
- Each version-1 manifest contains a single `workflow` with its ID, description,
190
- version, and input/output/state JSON Schemas, a `graph` for visualization, and a
191
- `triggers` array containing only that workflow's triggers and static inputs. Each
192
- entry names its kind in `type` — `"schedule"` today — and a schedule entry carries
193
- its `cadence`, derived `cron`, `timeZone`, `enabled`, `overlapPolicy`, `smear`, and
194
- `input`. It is an SDK discovery format, not the engine's deployment or execution
195
- contract. Handlers and middleware stay in app code. Triggers and JSON object keys
196
- are sorted for stable output.
197
-
198
- The SDK manages the JSON files in `.lovable/workflows/`. Successful generation
199
- removes manifests for deleted or renamed workflows; an empty collection removes
200
- all JSON manifests. Other files and subdirectories are preserved. All definitions
201
- are validated before writing, and each file is replaced by rename so readers
202
- never see a partially written JSON document.
203
-
204
- Schemas must implement [Standard JSON Schema](https://standardschema.dev/json-schema)
205
- conversion to draft 2020-12, as Zod 4 does. Missing conversion support and
206
- conversion errors fail generation. Schedule inputs must be plain JSON and pass
207
- the workflow's input schema; the manifest retains the raw input for validation
208
- when a run starts. Functions, undefined values, non-finite numbers, class
209
- instances, and cycles are rejected. `previousVersions` is rejected until version
210
- routing has a manifest contract.
211
-
212
- The plugin evaluates the entry using a separate Vite SSR loader with the app's
213
- aliases, mode, defines, and SSR dependency rules. Module-level code and schema
214
- validators run during extraction; workflow handlers and middleware do not.
215
- Custom app transform plugins and virtual modules are not loaded by this loader.
216
- For another build system, call `await generateManifests(collection)` and make
217
- synchronizing the returned manifests to `.lovable/workflows/` a required build step.
218
-
219
- ### Step graph
220
-
221
- Each manifest's `graph` contains `nodes` and directed `edges`. The SDK parses the
222
- handler's function source without executing it. No additional registration is needed.
223
-
224
- Graph inference reads the app's own `typescript`, an optional peer. Apps built
225
- from a Lovable template already have it. Without it — or with a copy exposing no
226
- stable JS API, as TypeScript 7 does before 7.1 — the build still succeeds and
227
- every graph carries one `unknown` node and the diagnostic
228
- `Install typescript to infer step graphs`.
229
- Sequential awaited `ctx.step("name", callback)` calls produce order edges;
230
- `await Promise.all([ctx.step(...), ctx.step(...)])` produces parallel branches
231
- that join at the next step. Returned step promises work too. Keep step IDs literal.
232
-
233
- | Field | Meaning |
141
+ | `cadence` | — | `hourly()`, `daily({ at })`, or `weekly({ on, at })` |
142
+ | `timeZone` | — | Canonical IANA region name |
143
+ | `overlapPolicy` | `"skip"` | `skip`, `allow`, or `buffer-one` |
144
+ | `enabled` | `true` | `false` declares a paused schedule |
145
+
146
+ | Cadence | Example |
147
+ | --- | --- |
148
+ | Hourly | `hourly()` |
149
+ | Selected hours | `daily({ at: [0, 6, 12, 18] })` |
150
+ | Weekly | `weekly({ on: ["mon", "fri"], at: [0, 12] })` |
151
+
152
+ `daily` requires a non-empty `at` list. `weekly` requires non-empty `on` and
153
+ `at` lists and runs at every selected hour on every selected weekday. Hours are
154
+ whole numbers from 0 through 23; schedules do not accept minute or raw-cron
155
+ fields. `timeZone` is required and accepts `"UTC"` or a canonical IANA region
156
+ such as `"America/New_York"`. A scheduled hour is approximate: Lovable chooses
157
+ a stable offset within the corresponding scheduling window.
158
+
159
+ `overlapPolicy` controls what happens when a schedule becomes due while its
160
+ previous run is active. `skip` drops it, `allow` starts another run, and
161
+ `buffer-one` starts the earliest missed run after the active run finishes.
162
+
163
+ ## Build integration
164
+
165
+ Add `workflowsPlugin()` before the TanStack Start plugin. Its `entry` defaults
166
+ to `src/lib/workflows/index.ts` and must default-export the registered
167
+ collection. See [the Vite example](examples/vite.config.ts).
168
+
169
+ ```ts
170
+ plugins: [
171
+ workflowsPlugin(),
172
+ tanstackStart(),
173
+ ];
174
+ ```
175
+
176
+ ## Imports
177
+
178
+ | Import | Provides |
234
179
  | --- | --- |
235
- | `nodes[].id` | Unique occurrence ID within this graph; use as the UI node key |
236
- | `nodes[].kind` | `step` or `unknown` |
237
- | `nodes[].stepId` | Literal step name, present for known steps |
238
- | `nodes[].label` | Step name or explanation of unsupported code |
239
- | `edges[]` | `{ source, target, kind: "order" }`, referencing node IDs |
240
- | `complete` | Whether the handler uses only supported syntax |
241
- | `diagnostics` | Reasons the graph is partial |
242
-
243
- For example, `read` followed by parallel `transform-a` and `transform-b`, then
244
- `save`, produces `read → transform-a → save` and `read → transform-b → save`.
245
- Repeated step names remain separate nodes. Node IDs are deterministic for the
246
- same source, but may change when the handler is edited.
247
-
248
- Graphs have `source: "inferred"` and `scope: "handler"`. They describe source
249
- structure, not run history or data dependencies, and exclude middleware and
250
- initialization. Branches, loops, helper calls, dynamic step IDs, nested steps,
251
- and unawaited steps produce `unknown` nodes and `complete: false`; steps inside
252
- unsupported code are not expanded. The UI should show these unknown nodes and
253
- mark partial graphs. Transforms that rewrite the handler may also produce a
254
- partial graph. A handler with no steps can have an empty graph.
255
-
256
- ## Next PRs
257
-
258
- Connect the manifest and app code to Lovable deployment and runtime execution.
259
- Define support for TanStack primitives, version routing, and schedule policies.
260
- Add webhook and app-event triggers to the same `triggers` array.
261
-
262
- ## Publishing dev builds
263
-
264
- The [publishing workflow](../../.github/workflows/publish-workflows-sdk.yml)
265
- publishes the version committed in `package.json` to npm's `latest` tag when SDK
266
- changes land on `main`. Manage versions manually: `0.0.0-dev`, `0.0.0-dev.1`,
267
- `0.0.0-dev.2`, and so on. The workflow rejects versions outside this series and
268
- skips versions already published. Manual runs default to a dry run.
269
- See [the setup guide](PUBLISHING.md) for the
270
- one-time bootstrap and npm trusted-publisher configuration.
271
-
272
- Install the newest build with `npm install @lovable.dev/workflows-sdk`, or pin
273
- the exact version shown in the workflow run's summary. `latest` tracks every dev
274
- publish while the SDK is pre-1.0; the older `dev` tag is frozen at `0.0.0-dev.2`.
275
-
276
- The engine's embedded SDK
277
- ([`sdk_embed/index.ts`](../../go/workflows/services/workflows/internal/bundler/sdk_embed/index.ts))
278
- provides the engine contract. Use [`mcp-js`](../lovable-mcp-js) as the reference
279
- for separating authoring, manifest extraction, and framework integration. The
280
- workflow prototype's `ts/workflow-sdk` supplies adapter and manifest examples.
180
+ | `@lovable.dev/workflows-sdk` | Workflow authoring, registration, cadences, and schedules |
181
+ | `@lovable.dev/workflows-sdk/vite` | Lovable build integration |
@@ -0,0 +1,111 @@
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-oG4uFJ0o.js";
2
+ //#region src/manifests/branch-metadata.ts
3
+ const optionsArgument = {
4
+ step: 2,
5
+ approve: 0,
6
+ sleep: 1,
7
+ sleepUntil: 1,
8
+ waitForEvent: 1,
9
+ now: 0,
10
+ uuid: 0
11
+ };
12
+ async function findBranchMetadataIssues(handler) {
13
+ const api = await loadTypeScript();
14
+ if (!api) return [];
15
+ const ts = api;
16
+ const handlerSource = workflowHandlerSource(handler);
17
+ if (!handlerSource) return [];
18
+ const declaration = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS).statements[0];
19
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
20
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return [];
21
+ const parameter = fn.parameters[0]?.name;
22
+ if (!parameter || !ts.isIdentifier(parameter)) return [];
23
+ const context = parameter.text;
24
+ function property(node, name) {
25
+ if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
26
+ for (const entry of node.properties) {
27
+ if (!ts.isPropertyAssignment(entry)) continue;
28
+ if ((ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name) ? entry.name.text : void 0) === name) return entry.initializer;
29
+ }
30
+ }
31
+ function literalString(node) {
32
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
33
+ }
34
+ function durableCall(node) {
35
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression) || !ts.isIdentifier(node.expression.expression) || node.expression.expression.text !== context || !(node.expression.name.text in optionsArgument)) return;
36
+ return {
37
+ call: node,
38
+ method: node.expression.name.text
39
+ };
40
+ }
41
+ function branchPath(call, method) {
42
+ const options = call.arguments[optionsArgument[method]];
43
+ const branches = property(property(options, "meta"), "branches");
44
+ if (!branches || !ts.isArrayLiteralExpression(branches)) return void 0;
45
+ const path = [];
46
+ for (const element of branches.elements) {
47
+ if (!ts.isObjectLiteralExpression(element)) return void 0;
48
+ const id = literalString(property(element, "id"));
49
+ const description = literalString(property(element, "description"));
50
+ if (id === void 0 || description === void 0) return void 0;
51
+ path.push({
52
+ id,
53
+ description
54
+ });
55
+ }
56
+ return path;
57
+ }
58
+ const issues = [];
59
+ const metadataByBranch = /* @__PURE__ */ new Map();
60
+ const branchById = /* @__PURE__ */ new Map();
61
+ function visit(node, branches) {
62
+ if (issues.length > 0) return;
63
+ if (ts.isIfStatement(node)) {
64
+ visit(node.expression, branches);
65
+ visit(node.thenStatement, [...branches, node]);
66
+ if (node.elseStatement) visit(node.elseStatement, [...branches, node]);
67
+ return;
68
+ }
69
+ const durable = durableCall(node);
70
+ if (durable) {
71
+ const path = branchPath(durable.call, durable.method);
72
+ const stepId = durable.method === "step" ? literalString(durable.call.arguments[0]) : void 0;
73
+ if (branches.length === 0 && path !== void 0 || branches.length > 0 && (path === void 0 || path.length !== branches.length)) {
74
+ issues.push({
75
+ kind: "path",
76
+ method: durable.method,
77
+ ...stepId === void 0 ? {} : { stepId }
78
+ });
79
+ return;
80
+ }
81
+ for (let index = 0; index < branches.length; index++) {
82
+ const branch = branches[index];
83
+ const entry = path?.[index];
84
+ if (!branch || !entry) continue;
85
+ const existing = metadataByBranch.get(branch);
86
+ if (existing && (existing.id !== entry.id || existing.description !== entry.description)) {
87
+ issues.push({
88
+ kind: "inconsistent",
89
+ branchId: existing.id
90
+ });
91
+ return;
92
+ }
93
+ const existingNode = branchById.get(entry.id);
94
+ if (existingNode && existingNode !== branch) {
95
+ issues.push({
96
+ kind: "duplicate-id",
97
+ branchId: entry.id
98
+ });
99
+ return;
100
+ }
101
+ metadataByBranch.set(branch, entry);
102
+ branchById.set(entry.id, branch);
103
+ }
104
+ }
105
+ ts.forEachChild(node, (child) => visit(child, branches));
106
+ }
107
+ visit(fn, []);
108
+ return issues;
109
+ }
110
+ //#endregion
111
+ export { findBranchMetadataIssues };
@@ -0,0 +1,78 @@
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-oG4uFJ0o.js";
2
+ //#region src/manifests/context-escapes.ts
3
+ const durableMethods = /* @__PURE__ */ new Set([
4
+ "step",
5
+ "approve",
6
+ "waitForEvent",
7
+ "sleep",
8
+ "sleepUntil",
9
+ "now",
10
+ "uuid"
11
+ ]);
12
+ async function findWorkflowContextEscapes(handler) {
13
+ const api = await loadTypeScript();
14
+ if (!api) return [];
15
+ const ts = api;
16
+ const handlerSource = workflowHandlerSource(handler);
17
+ if (!handlerSource) return [];
18
+ const declaration = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS).statements[0];
19
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
20
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return [];
21
+ const parameter = fn.parameters[0]?.name;
22
+ if (!parameter) return [];
23
+ if (!ts.isIdentifier(parameter)) return [{ kind: "destructured" }];
24
+ const context = parameter.text;
25
+ function bindingContains(node, name) {
26
+ if (ts.isIdentifier(node)) return node.text === name;
27
+ return node.elements.some((element) => !ts.isOmittedExpression(element) && bindingContains(element.name, name));
28
+ }
29
+ function contextMethod(node) {
30
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === context) return node.name.text;
31
+ if (ts.isElementAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === context && node.argumentExpression && (ts.isStringLiteral(node.argumentExpression) || ts.isNoSubstitutionTemplateLiteral(node.argumentExpression))) return node.argumentExpression.text;
32
+ }
33
+ function directCallTarget(node) {
34
+ let target = node;
35
+ while (ts.isParenthesizedExpression(target.parent)) target = target.parent;
36
+ return ts.isCallExpression(target.parent) && target.parent.expression === target;
37
+ }
38
+ function identifierIsValue(node) {
39
+ const parent = node.parent;
40
+ if (parent.name === node && !ts.isShorthandPropertyAssignment(parent)) return false;
41
+ return parent.label !== node;
42
+ }
43
+ const escapes = [];
44
+ const visit = (node, shadowed) => {
45
+ if (escapes.length > 0) return;
46
+ if (node !== fn && ts.isFunctionLike(node)) {
47
+ const hidesContext = node.parameters.some((item) => bindingContains(item.name, context));
48
+ ts.forEachChild(node, (child) => visit(child, shadowed || hidesContext));
49
+ return;
50
+ }
51
+ if (!shadowed) {
52
+ const method = contextMethod(node);
53
+ if (method && durableMethods.has(method) && !directCallTarget(node)) {
54
+ escapes.push({
55
+ kind: "method",
56
+ context,
57
+ method
58
+ });
59
+ return;
60
+ }
61
+ if (ts.isIdentifier(node) && node.text === context && identifierIsValue(node)) {
62
+ const parent = node.parent;
63
+ if (!(ts.isPropertyAccessExpression(parent) && parent.expression === node || ts.isElementAccessExpression(parent) && parent.expression === node && parent.argumentExpression && (ts.isStringLiteral(parent.argumentExpression) || ts.isNoSubstitutionTemplateLiteral(parent.argumentExpression)))) {
64
+ escapes.push({
65
+ kind: "context",
66
+ context
67
+ });
68
+ return;
69
+ }
70
+ }
71
+ }
72
+ ts.forEachChild(node, (child) => visit(child, shadowed));
73
+ };
74
+ visit(fn, false);
75
+ return escapes;
76
+ }
77
+ //#endregion
78
+ export { findWorkflowContextEscapes };