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

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
@@ -53,8 +53,8 @@ trigger: a clock. Triggers go in `registerWorkflows({ workflows, triggers })`,
53
53
  and each carries a `type` naming its kind. Webhook and app-event triggers will
54
54
  join the same array.
55
55
 
56
- A schedule's *cadence* is how often the clock fires. `every()`, `hourly()`,
57
- `daily()`, and `weekly()` build one; there is no raw cron.
56
+ A schedule's *cadence* is how often the clock fires. `hourly()`, `daily()`,
57
+ and `weekly()` build one; there is no raw cron.
58
58
 
59
59
  ## Schedules
60
60
 
@@ -66,25 +66,31 @@ IDs must be unique within the app's collection. This API declares schedules but
66
66
  does not install timers or start runs.
67
67
 
68
68
  ```ts
69
- import { daily, defineSchedule, every, hourly, weekly } from "@lovable.dev/workflows-sdk";
69
+ import { daily, defineSchedule, hourly, weekly } from "@lovable.dev/workflows-sdk";
70
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: {} });
71
+ defineSchedule({ id: "sweep", workflow: sync, cadence: hourly(), timeZone: "UTC", input: {} });
73
72
  defineSchedule({ id: "digest", workflow: digest, cadence: daily(), timeZone: "Europe/Stockholm", input: {} });
74
73
 
74
+ defineSchedule({
75
+ id: "refresh",
76
+ workflow: sync,
77
+ cadence: daily({ at: [0, 6, 12, 18] }),
78
+ timeZone: "UTC",
79
+ input: {},
80
+ });
81
+
75
82
  defineSchedule({
76
83
  id: "weekday-digest",
77
84
  workflow: digest,
78
- cadence: daily({ at: "09:00", days: ["mon", "tue", "wed", "thu", "fri"] }),
85
+ cadence: daily({ at: 9, days: ["mon", "tue", "wed", "thu", "fri"] }),
79
86
  timeZone: "America/New_York",
80
- smear: { window: "15m" },
81
87
  input: {},
82
88
  });
83
89
 
84
90
  defineSchedule({
85
91
  id: "monday-report",
86
92
  workflow: report,
87
- cadence: weekly({ on: "monday", at: "07:00" }),
93
+ cadence: weekly({ on: "monday", at: 7 }),
88
94
  timeZone: "Europe/Stockholm",
89
95
  input: {},
90
96
  });
@@ -92,96 +98,136 @@ defineSchedule({
92
98
 
93
99
  | Field | Default | Meaning |
94
100
  | --- | --- | --- |
95
- | `cadence` | — | `every()`, `hourly()`, `daily()`, or `weekly()` |
101
+ | `cadence` | — | `hourly()`, `daily()`, or `weekly()` |
96
102
  | `timeZone` | — | IANA region name the cadence is interpreted in |
97
- | `overlapPolicy` | `"skip"` | `skip`, `cancel-previous`, or `terminate-previous` |
103
+ | `overlapPolicy` | `"skip"` | `skip`, `allow`, or `buffer-one` |
98
104
  | `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.
105
+
106
+ There are three cadences and no raw cron:
107
+
108
+ | Cadence | Says | Example |
109
+ | --- | --- | --- |
110
+ | `hourly()` | once an hour | `hourly()` |
111
+ | `daily({ at, days })` | hours of the day, days of the week | `daily({ at: [0, 6, 12, 18] })` |
112
+ | `weekly({ on, at })` | one weekday, hours of the day | `weekly({ on: "monday", at: 7 })` |
113
+
114
+ **The SDK never derives a cron.** The manifest carries the cadence, and the
115
+ `app-workflows-service` backend translates it when it registers the schedule.
116
+ An app declares intent; one service owns the translation, so there is no second
117
+ implementation to drift. Every cadence here is shaped to be exactly
118
+ translatable — that constraint is why the vocabulary is closed and why `at` is
119
+ whole hours.
120
+
121
+ ### Hours, never minutes
122
+
123
+ `at` is a whole hour, `0` through `23`, or a list of them. There is no minute:
124
+ an app says *which hours*, and the platform picks where inside the hour a run
125
+ actually starts (see [Timing](#timing)). `hourly()` takes no options for the
126
+ same reason. An app that could pin a minute would opt itself out of the smear,
127
+ and the herd would come back.
128
+
129
+ This is also what keeps the vocabulary exactly translatable by the backend.
130
+ Cron pairs every value in its minute field with every value in its hour field,
131
+ so a cadence that could say 09:15 and 17:45 has no faithful cron — it would
132
+ become `15,45 9,17 * * *` and fire four times a day instead of twice. With the
133
+ minute fixed, any set of hours translates exactly.
134
+
135
+ `at` accepts a list, so several runs a day need one schedule rather than
136
+ several: `daily({ at: [0, 6, 12, 18] })` is four evenly spaced runs, and
137
+ `daily({ at: [9, 17] })` is two uneven ones — the start and end of a working
138
+ day, which no fixed interval can express. The list is sorted and deduplicated,
139
+ so two orderings are one schedule.
140
+
141
+ ### One schedule, one representation
118
142
 
119
143
  `weekly({ on, at })` is the single-day shorthand for `daily({ at, days: [on] })`
120
144
  and resolves into exactly that cadence. There is one internal representation of
121
145
  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
146
+ and hash alike.
147
+
148
+ There is no `"weekdays"` or `"weekends"` shorthand: it would add a third
149
+ spelling of a set `days` already states, and "the weekend" is Friday and
124
150
  Saturday in much of the world, so the word would quietly mean the wrong days.
125
151
 
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.
152
+ There is no interval cadence — no `every("6h")`, no `every("3d")`. Intervals
153
+ are not calendar positions and have no faithful cron: `0 0 */3 * *` restarts its
154
+ count every month, so it means "every 3 days" only until the 28th and then fires
155
+ twice in two days. The sub-daily intervals that *are* faithful are exactly the
156
+ ones `daily({ at })` already covers, and `daily({ at: [0, 6, 12, 18] })` says the
157
+ same thing as "every 6 hours" while staying anchored to the calendar and to the
158
+ app's time zone.
159
+
160
+ ## Timing
161
+
162
+ **A declared hour is approximate, and an app does not control how approximate.**
163
+ Tens of thousands of apps declaring `daily()` must not fire in the same minute,
164
+ so the platform spreads each schedule over a window — a *smear* — and then keeps
165
+ that schedule on the same offset for every later run.
166
+
167
+ Apps do not declare the smear, and there is no field for it. The platform
168
+ derives the window per schedule from the cadence, so what an app leaves
169
+ unspecified is exactly what the platform is free to choose:
170
+
171
+ | Cadence | Smeared across |
172
+ | --- | --- |
173
+ | `daily()` | the whole day |
174
+ | `daily({ at })`, `weekly({ on, at })` | a window around each declared hour |
175
+ | `hourly()` | the hour |
176
+
177
+ Higher plans get tighter windows, so a declared 07:00 lands nearer to 07:00 the
178
+ more an app pays; the exact windows belong to the platform and can change
179
+ without an SDK release.
180
+
181
+ Two consequences worth designing around. A schedule that must run at an exact
182
+ instant is not expressible, by design. And the offset is stable per schedule,
183
+ not random per run, so a report that reads "yesterday's rows" reads the same
184
+ shape every day.
185
+
186
+ Neither the smear nor the schedule itself runs yet; see
187
+ [Next PRs](#next-prs).
129
188
 
130
189
  ### Time zone
131
190
 
132
191
  `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`.
192
+ available default is wrong: `daily({ at: 9 })` in UTC is not the 09:00 a reader
193
+ of the digest expects, and the build machine's own zone would make one app
194
+ source fire at different times depending on where it was built.
195
+
196
+ It must be `"UTC"` or a canonical IANA name as `Intl.supportedValuesOf("timeZone")`
197
+ lists it, such as `"Europe/Stockholm"`. That rejects the fixed-offset family
198
+ `Intl` otherwise accepts — `"+05:00"`, `"-0800"`, `"EST"`, `"GMT"`,
199
+ `"Etc/GMT+5"` — none of which observe daylight saving, so `"EST"` is an hour
200
+ off US Eastern for two-thirds of the year, and `"Etc/GMT+5"` is UTC-5 rather
201
+ than UTC+5. It also rejects tzdata's backward-compatibility aliases such as
202
+ `"US/Pacific"`; write the canonical `"America/Los_Angeles"`, so one zone has
203
+ one spelling and one manifest.
204
+
205
+ ### Overlap policy
206
+
207
+ `overlapPolicy` says what happens when an occurrence comes due while the
208
+ previous run is still going: `skip` drops it, `allow` lets runs overlap, and
209
+ `buffer-one` holds the earliest due occurrence and fires it once the in-flight
210
+ run finishes.
211
+
212
+ ### Validation
213
+
214
+ Everything is validated when the schedule is defined, at build time: an hour
215
+ outside `0`-`23`, a fractional hour, a weekday name that is not a weekday, an
216
+ unknown `overlapPolicy`, a missing or non-canonical zone, and a hand-written
217
+ cadence object no constructor produced all fail the build. `registerWorkflows`
218
+ likewise rejects any key other than `workflows` and `triggers`, so a collection
219
+ left on the old `schedules:` name fails the build instead of emitting an empty
220
+ manifest.
175
221
 
176
222
  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.
223
+ Europe/Stockholm, a weekday greeting in America/New_York, a Monday report, a
224
+ four-times-daily refresh, an hourly sweep, and a paused daily digest.
179
225
 
180
226
  ## Manifest generation
181
227
 
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
228
+ Add `workflowsPlugin()` from `@lovable.dev/workflows-sdk/vite` to the app's Vite
229
+ plugins. Its `entry` defaults to `src/lib/workflows/index.ts` and must
230
+ default-export the app's `registerWorkflows()` collection. Each production build writes
185
231
  one manifest per workflow to `.lovable/workflows/{workflow-name}.json` relative
186
232
  to the app root. For example, `greet` produces `.lovable/workflows/greet.json`.
187
233
  Generation errors fail the build. See [the Vite example](examples/vite.config.ts).
@@ -190,8 +236,7 @@ Each version-1 manifest contains a single `workflow` with its ID, description,
190
236
  version, and input/output/state JSON Schemas, a `graph` for visualization, and a
191
237
  `triggers` array containing only that workflow's triggers and static inputs. Each
192
238
  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
239
+ its `cadence`, `timeZone`, `enabled`, `overlapPolicy`, and `input`. It is an SDK discovery format, not the engine's deployment or execution
195
240
  contract. Handlers and middleware stay in app code. Triggers and JSON object keys
196
241
  are sorted for stable output.
197
242
 
@@ -253,10 +298,83 @@ unsupported code are not expanded. The UI should show these unknown nodes and
253
298
  mark partial graphs. Transforms that rewrite the handler may also produce a
254
299
  partial graph. A handler with no steps can have an empty graph.
255
300
 
301
+ ## Run endpoint (TanStack Start)
302
+
303
+ Pass `runRoute: true` to the same `workflowsPlugin` that writes the manifests. It
304
+ then also emits one dynamic route, `src/routes/api/workflows/$workflowId.ts`,
305
+ serving every registered workflow. One plugin and one `entry` cover both, so a
306
+ manifest can never describe a collection the route does not serve:
307
+
308
+ ```ts
309
+ import { tanstackStart } from "@tanstack/react-start/plugin/vite";
310
+ import { workflowsPlugin } from "@lovable.dev/workflows-sdk/vite";
311
+
312
+ export default defineConfig({
313
+ plugins: [workflowsPlugin({ runRoute: true }), tanstackStart()],
314
+ });
315
+ ```
316
+
317
+ `runRoute` defaults to `false`. The route is unauthenticated: any caller who
318
+ reaches it runs any declared workflow. Turn it on only where that is acceptable,
319
+ until signed invocation lands.
320
+
321
+ The emitted file is thin — it imports the collection and mounts
322
+ `createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk/stacks/tanstack`
323
+ as the route's `POST` handler. All runtime logic stays in the package. The file
324
+ carries a generated banner, which is the plugin's ownership token: it rewrites
325
+ and deletes only files that have it, and deletes its own orphans when `path`,
326
+ `workflowIdParam`, or `runRoute` changes. Delete the banner line to take the
327
+ route over — the plugin then leaves that file alone, and the build keeps
328
+ working.
329
+
330
+ | Option | Default | Meaning |
331
+ | --- | --- | --- |
332
+ | `entry` | `src/lib/workflows/index.ts` | Collection entry; a missing file means no route |
333
+ | `routesDir` | `src/routes` | Where the route file is written |
334
+ | `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
335
+ | `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
336
+ | `runRoute` | `false` | Emit the route at all |
337
+
338
+ ### Calling it
339
+
340
+ `POST /api/workflows/{workflow-id}` with a JSON body. The body is decoded by
341
+ `parseWorkflowRequest`, so one route takes every traffic shape: `{ "input": ... }`
342
+ starts a run, `{ "runId", "approval" }` delivers an approval decision, and
343
+ `{ "runId", "signal" }` delivers a signal. A run that parks on `ctx.approve` or
344
+ `ctx.waitForEvent` resumes on this same route — there is no separate resume
345
+ endpoint. An unknown workflow ID returns 404, an unparseable body 400, and
346
+ `{ "abort": true }` returns 501 until a shared run registry exists.
347
+
348
+ The response is `text/event-stream`. Each engine event becomes one SSE message
349
+ whose event name is the event `type` and whose data is the whole event as JSON:
350
+
351
+ ```text
352
+ event: RUN_STARTED
353
+ data: {"type":"RUN_STARTED","ts":1790505539351,"runId":"run_1790505539350_yin41cp"}
354
+
355
+ event: STEP_FINISHED
356
+ data: {"type":"STEP_FINISHED","ts":1790505539352,"stepId":"greeting","result":"Hello, YEHYA!"}
357
+
358
+ event: RUN_FINISHED
359
+ data: {"type":"RUN_FINISHED","ts":1790505539352,"runId":"run_1790505539350_yin41cp","output":{"message":"Hello, YEHYA!"}}
360
+ ```
361
+
362
+ Run state lives in a process-local `inMemoryRunStore()`: runs are lost on restart
363
+ and are invisible to other instances. Pass `runStore` to
364
+ `createTanStackWorkflowHandler` to supply another one. The control-plane store is
365
+ a follow-up.
366
+
367
+ The path carries no build ID. Version pinning belongs to the signed invocation,
368
+ which leaves this path stable across deployments and safe to publish in a
369
+ manifest. Triggers name a workflow rather than an endpoint, so firing one is a
370
+ POST to that workflow's path with the trigger's input; no trigger identifier
371
+ appears in the URL.
372
+
256
373
  ## Next PRs
257
374
 
258
375
  Connect the manifest and app code to Lovable deployment and runtime execution.
259
- Define support for TanStack primitives, version routing, and schedule policies.
376
+ Derive and apply the per-schedule smear on the control plane. Define support for
377
+ TanStack primitives, version routing, and schedule policies.
260
378
  Add webhook and app-event triggers to the same `triggers` array.
261
379
 
262
380
  ## Publishing dev builds
@@ -5,28 +5,6 @@ function assertIdentifier(kind, id) {
5
5
  }
6
6
  //#endregion
7
7
  //#region src/core/cadence.ts
8
- const MINUTE_DIVISORS = [
9
- 1,
10
- 2,
11
- 3,
12
- 4,
13
- 5,
14
- 6,
15
- 10,
16
- 12,
17
- 15,
18
- 20,
19
- 30
20
- ];
21
- const HOUR_DIVISORS = [
22
- 1,
23
- 2,
24
- 3,
25
- 4,
26
- 6,
27
- 8,
28
- 12
29
- ];
30
8
  const WEEKDAYS = [
31
9
  "mon",
32
10
  "tue",
@@ -52,15 +30,6 @@ const WEEKDAY_NAMES = {
52
30
  sun: "sun",
53
31
  sunday: "sun"
54
32
  };
55
- const CRON_DAY = {
56
- sun: 0,
57
- mon: 1,
58
- tue: 2,
59
- wed: 3,
60
- thu: 4,
61
- fri: 5,
62
- sat: 6
63
- };
64
33
  function fail$1(message) {
65
34
  throw new Error(`@lovable.dev/workflows-sdk: ${message}`);
66
35
  }
@@ -74,141 +43,71 @@ function parseDays(value, label) {
74
43
  const days = [...new Set(value.map((entry) => parseWeekday(entry, label)))].sort((a, b) => WEEKDAYS.indexOf(a) - WEEKDAYS.indexOf(b));
75
44
  return days.length === WEEKDAYS.length ? null : days;
76
45
  }
77
- function parseTimeOfDay(value, label) {
78
- if (typeof value !== "string" || !/^([01][0-9]|2[0-3]):[0-5][0-9]$/.test(value)) fail$1(`${label}: "${String(value)}" must be a 24-hour "HH:MM" time`);
79
- return value;
80
- }
81
- function every(interval) {
82
- if (typeof interval !== "string" || !/^[0-9]+[mhd]$/.test(interval)) fail$1(`every("${String(interval)}") must be a whole number of minutes, hours, or days, such as "5m", "2h", or "1d"`);
83
- const amount = Number(interval.slice(0, -1));
84
- const unit = interval.slice(-1);
85
- if (amount < 1) fail$1(`every("${interval}") must be at least one unit`);
86
- if (unit === "m" && !MINUTE_DIVISORS.includes(amount)) fail$1(`every("${interval}") must divide an hour evenly: ${MINUTE_DIVISORS.map((n) => `${n}m`).join(", ")}`);
87
- if (unit === "h" && !HOUR_DIVISORS.includes(amount)) fail$1(`every("${interval}") must divide a day evenly: ${HOUR_DIVISORS.map((n) => `${n}h`).join(", ")}`);
88
- if (unit === "d" && amount !== 1) fail$1(`every("${interval}") supports only "1d"; use daily() for calendar days`);
89
- return {
90
- kind: "every",
91
- seconds: amount * (unit === "m" ? 60 : unit === "h" ? 3600 : 86400)
92
- };
46
+ function parseHoursOfDay(value, label) {
47
+ const entries = Array.isArray(value) ? value : [value];
48
+ if (entries.length === 0) fail$1(`${label} must name at least one hour`);
49
+ for (const entry of entries) if (!Number.isInteger(entry) || entry < 0 || entry > 23) fail$1(`${label}: ${JSON.stringify(entry)} must be a whole hour from 0 to 23; the platform picks the minute`);
50
+ return [...new Set(entries)].sort((a, b) => a - b);
93
51
  }
94
- function hourly(options = {}) {
95
- if (options.at === void 0) return {
96
- kind: "hourly",
97
- minute: null
98
- };
99
- if (typeof options.at !== "string" || !/^:[0-5][0-9]$/.test(options.at)) fail$1(`hourly({ at: "${String(options.at)}" }) must pin a minute past the hour, such as ":30"`);
100
- return {
101
- kind: "hourly",
102
- minute: Number(options.at.slice(1))
103
- };
52
+ function hourly(options) {
53
+ if (options !== void 0) fail$1(`hourly() takes no options; the platform decides where in the hour a schedule runs`);
54
+ return { kind: "hourly" };
104
55
  }
105
56
  function daily(options = {}) {
106
57
  return {
107
58
  kind: "daily",
108
- at: options.at === void 0 ? null : parseTimeOfDay(options.at, "daily({ at })"),
59
+ at: options.at === void 0 ? null : parseHoursOfDay(options.at, "daily({ at })"),
109
60
  days: options.days === void 0 ? null : parseDays(options.days, "daily({ days })")
110
61
  };
111
62
  }
112
63
  function weekly(options) {
113
- if (typeof options !== "object" || options === null) fail$1(`weekly() requires { on: "monday", at: "07:00" }`);
64
+ if (typeof options !== "object" || options === null) fail$1(`weekly() requires { on: "monday", at: 7 }`);
114
65
  return {
115
66
  kind: "daily",
116
- at: options.at === void 0 ? null : parseTimeOfDay(options.at, "weekly({ at })"),
67
+ at: options.at === void 0 ? null : parseHoursOfDay(options.at, "weekly({ at })"),
117
68
  days: [parseWeekday(options.on, "weekly({ on })")]
118
69
  };
119
70
  }
120
- function isCadence(value) {
121
- if (typeof value !== "object" || value === null) return false;
122
- const kind = value.kind;
123
- return kind === "every" || kind === "hourly" || kind === "daily";
124
- }
125
- function cronDayField(days) {
126
- if (days === null) return "*";
127
- const numbers = days.map((day) => CRON_DAY[day]).sort((a, b) => a - b);
128
- const parts = [];
129
- let start = 0;
130
- for (let index = 1; index <= numbers.length; index += 1) {
131
- if (index < numbers.length && numbers[index] === numbers[index - 1] + 1) continue;
132
- const run = numbers.slice(start, index);
133
- parts.push(run.length >= 3 ? `${run[0]}-${run[run.length - 1]}` : run.join(","));
134
- start = index;
135
- }
136
- return parts.join(",");
137
- }
138
- function cadenceCron(cadence) {
139
- if (cadence.kind === "every") {
140
- const seconds = cadence.seconds;
141
- if (seconds < 3600) return `*/${seconds / 60} * * * *`;
142
- if (seconds < 86400) return `0 */${seconds / 3600} * * *`;
143
- return "0 0 * * *";
144
- }
145
- if (cadence.kind === "hourly") return `${cadence.minute ?? 0} * * * *`;
146
- const [hour, minute] = (cadence.at ?? "00:00").split(":");
147
- return `${Number(minute)} ${Number(hour)} * * ${cronDayField(cadence.days)}`;
71
+ function isHourSet(value) {
72
+ if (value === null) return true;
73
+ if (!Array.isArray(value) || value.length === 0) return false;
74
+ return value.every((hour, index) => Number.isInteger(hour) && hour >= 0 && hour <= 23 && (index === 0 || hour > value[index - 1]));
148
75
  }
149
- function cadencePeriodSeconds(cadence) {
150
- if (cadence.kind === "every") return cadence.seconds;
151
- if (cadence.kind === "hourly") return 3600;
152
- if (cadence.days === null) return 86400;
153
- const indexes = cadence.days.map((day) => WEEKDAYS.indexOf(day)).sort((a, b) => a - b);
154
- let gap = WEEKDAYS.length - indexes[indexes.length - 1] + indexes[0];
155
- for (let index = 1; index < indexes.length; index += 1) gap = Math.min(gap, indexes[index] - indexes[index - 1]);
156
- return gap * 86400;
76
+ function isDaySet(value) {
77
+ if (value === null) return true;
78
+ if (!Array.isArray(value) || value.length === 0 || value.length >= WEEKDAYS.length) return false;
79
+ const indexes = value.map((day) => WEEKDAYS.indexOf(day));
80
+ return indexes.every((index, position) => index >= 0 && (position === 0 || index > indexes[position - 1]));
157
81
  }
158
- function parseWindowSeconds(interval, id) {
159
- if (typeof interval !== "string" || !/^[0-9]+[mhd]$/.test(interval)) fail$1(`schedule "${id}" smear window must be an interval such as "15m", "1h", or "1d"`);
160
- const amount = Number(interval.slice(0, -1));
161
- const unit = interval.slice(-1);
162
- const seconds = amount * (unit === "m" ? 60 : unit === "h" ? 3600 : 86400);
163
- if (seconds < 60 || seconds > 86400) fail$1(`schedule "${id}" smear window must be between "1m" and "1d"`);
164
- return seconds;
82
+ function isCadence(value) {
83
+ if (typeof value !== "object" || value === null) return false;
84
+ const cadence = value;
85
+ if (cadence.kind === "hourly") return Object.keys(cadence).length === 1;
86
+ if (cadence.kind === "daily") return isHourSet(cadence.at) && isDaySet(cadence.days);
87
+ return false;
165
88
  }
166
89
  //#endregion
167
90
  //#region src/core/schedule.ts
168
91
  const OVERLAP_POLICIES = [
169
92
  "skip",
170
- "cancel-previous",
171
- "terminate-previous"
93
+ "allow",
94
+ "buffer-one"
172
95
  ];
173
96
  function fail(message) {
174
97
  throw new Error(`@lovable.dev/workflows-sdk: ${message}`);
175
98
  }
99
+ const CANONICAL_ZONES = new Set(typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : []);
176
100
  function resolveTimeZone(schedule) {
177
101
  const timeZone = schedule.timeZone;
178
102
  if (typeof timeZone !== "string" || timeZone === "") fail(`schedule "${schedule.id}" needs a timeZone, such as "Europe/Stockholm" or "UTC"`);
179
- if (timeZone !== "UTC" && !timeZone.includes("/")) fail(`schedule "${schedule.id}" timeZone "${timeZone}" must be an IANA region name such as "Europe/Stockholm", not a fixed offset or abbreviation`);
103
+ if (timeZone !== "UTC" && CANONICAL_ZONES.size > 0 && !CANONICAL_ZONES.has(timeZone)) fail(`schedule "${schedule.id}" timeZone "${timeZone}" must be "UTC" or a canonical IANA name such as "Europe/Stockholm"; fixed offsets and aliases such as "EST", "GMT", "Etc/GMT+5", and "US/Pacific" are not accepted`);
180
104
  new Intl.DateTimeFormat("en", { timeZone });
181
105
  return timeZone;
182
106
  }
183
- function unpinnedWindowSeconds(cadence) {
184
- if (cadence.kind === "daily" && cadence.at === null) return 86400;
185
- if (cadence.kind === "hourly" && cadence.minute === null) return 3600;
186
- return null;
187
- }
188
- function resolveSmear(schedule, cadence) {
189
- const unpinned = unpinnedWindowSeconds(cadence);
190
- if (schedule.smear === void 0) return unpinned === null ? { strategy: "none" } : {
191
- strategy: "hash",
192
- windowSeconds: unpinned
193
- };
194
- if (schedule.smear === false || typeof schedule.smear === "object" && "strategy" in schedule.smear && schedule.smear.strategy === "none") {
195
- if (unpinned !== null) fail(`schedule "${schedule.id}" uses ${cadence.kind}() with no time; pass { at } or keep the smear`);
196
- return { strategy: "none" };
197
- }
198
- if (typeof schedule.smear !== "object") fail(`schedule "${schedule.id}" smear must be false or { window }`);
199
- const windowSeconds = "window" in schedule.smear ? parseWindowSeconds(schedule.smear.window, schedule.id) : schedule.smear.windowSeconds;
200
- const period = cadencePeriodSeconds(cadence);
201
- if (windowSeconds > period) fail(`schedule "${schedule.id}" smear window must not exceed its ${period}s firing period`);
202
- return {
203
- strategy: "hash",
204
- windowSeconds
205
- };
206
- }
207
107
  function defineSchedule(schedule) {
208
108
  assertIdentifier("schedule", schedule.id);
209
- if (!isCadence(schedule.cadence)) fail(`schedule "${schedule.id}" cadence must come from every(), hourly(), daily(), or weekly()`);
109
+ if (!isCadence(schedule.cadence)) fail(`schedule "${schedule.id}" cadence must come from hourly(), daily(), or weekly()`);
210
110
  const cadence = schedule.cadence;
211
- const cron = cadenceCron(cadence);
212
111
  const timeZone = resolveTimeZone(schedule);
213
112
  const overlapPolicy = schedule.overlapPolicy ?? "skip";
214
113
  if (!OVERLAP_POLICIES.includes(overlapPolicy)) fail(`schedule "${schedule.id}" overlapPolicy must be one of ${OVERLAP_POLICIES.join(", ")}`);
@@ -218,16 +117,19 @@ function defineSchedule(schedule) {
218
117
  ...schedule,
219
118
  type: "schedule",
220
119
  cadence,
221
- cron,
222
120
  timeZone,
223
121
  overlapPolicy,
224
- enabled,
225
- smear: resolveSmear(schedule, cadence)
122
+ enabled
226
123
  };
227
124
  }
228
125
  //#endregion
229
126
  //#region src/core/workflow.ts
230
- function registerWorkflows({ workflows, triggers = [] }) {
127
+ function registerWorkflows(definition) {
128
+ for (const key of Object.keys(definition)) {
129
+ if (key === "workflows" || key === "triggers") continue;
130
+ throw new Error(key === "schedules" ? `@lovable.dev/workflows-sdk: registerWorkflows() no longer takes "schedules"; rename the key to "triggers"` : `@lovable.dev/workflows-sdk: registerWorkflows() does not take "${key}"`);
131
+ }
132
+ const { workflows, triggers = [] } = definition;
231
133
  const ids = /* @__PURE__ */ new Set();
232
134
  for (const workflow of workflows) {
233
135
  if (workflow.__kind !== "workflow" || typeof workflow.handler !== "function") throw new Error("@lovable.dev/workflows-sdk: expected a completed createWorkflow().handler() definition");
@@ -306,11 +208,9 @@ async function generateManifests(definition) {
306
208
  type: schedule.type,
307
209
  id: schedule.id,
308
210
  cadence: schedule.cadence,
309
- cron: schedule.cron,
310
211
  timeZone: schedule.timeZone,
311
212
  enabled: schedule.enabled,
312
213
  overlapPolicy: schedule.overlapPolicy,
313
- smear: schedule.smear,
314
214
  input
315
215
  });
316
216
  }
@@ -330,4 +230,4 @@ async function generateManifests(definition) {
330
230
  return manifests.sort((a, b) => a.workflow.id < b.workflow.id ? -1 : a.workflow.id > b.workflow.id ? 1 : 0);
331
231
  }
332
232
  //#endregion
333
- export { defineSchedule as a, hourly as c, registerWorkflows as i, weekly as l, createMiddleware as n, daily as o, createWorkflow as r, every as s, generateManifests as t };
233
+ export { defineSchedule as a, weekly as c, registerWorkflows as i, createMiddleware as n, daily as o, createWorkflow as r, hourly as s, generateManifests as t };
package/dist/index.d.ts CHANGED
@@ -2,43 +2,24 @@ import { AnyWorkflowDefinition, AnyWorkflowDefinition as AnyWorkflowDefinition$1
2
2
  //#region src/core/cadence.d.ts
3
3
  type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
4
4
  type Cadence = {
5
- readonly kind: "every";
6
- readonly seconds: number;
7
- } | {
8
5
  readonly kind: "hourly";
9
- readonly minute: number | null;
10
6
  } | {
11
7
  readonly kind: "daily";
12
- readonly at: string | null;
8
+ readonly at: readonly number[] | null;
13
9
  readonly days: readonly Weekday[] | null;
14
10
  };
15
- declare function every(interval: string): Cadence;
16
- declare function hourly(options?: {
17
- at?: string;
18
- }): Cadence;
11
+ declare function hourly(options?: never): Cadence;
19
12
  declare function daily(options?: {
20
- at?: string;
13
+ at?: number | readonly number[];
21
14
  days?: readonly string[];
22
15
  }): Cadence;
23
16
  declare function weekly(options: {
24
17
  on: string;
25
- at?: string;
18
+ at?: number | readonly number[];
26
19
  }): Cadence;
27
20
  //#endregion
28
- //#region src/core/smear.d.ts
29
- type SmearPolicy = {
30
- readonly strategy: "none";
31
- } | {
32
- readonly strategy: "hash";
33
- readonly windowSeconds: number;
34
- };
35
- declare function smearOffsetSeconds(projectId: string, scheduleId: string, windowSeconds: number): number;
36
- //#endregion
37
21
  //#region src/core/schedule.d.ts
38
- type OverlapPolicy = "skip" | "cancel-previous" | "terminate-previous";
39
- type SmearOption = false | {
40
- readonly window: string;
41
- } | SmearPolicy;
22
+ type OverlapPolicy = "skip" | "allow" | "buffer-one";
42
23
  interface ScheduleDefinition<TWorkflow extends AnyWorkflowDefinition$1 = AnyWorkflowDefinition$1> {
43
24
  readonly id: string;
44
25
  readonly workflow: TWorkflow;
@@ -46,15 +27,12 @@ interface ScheduleDefinition<TWorkflow extends AnyWorkflowDefinition$1 = AnyWork
46
27
  readonly timeZone: string;
47
28
  readonly overlapPolicy?: OverlapPolicy;
48
29
  readonly enabled?: boolean;
49
- readonly smear?: SmearOption;
50
30
  readonly input: WorkflowInput$1<NoInfer<TWorkflow>>;
51
31
  }
52
32
  interface ResolvedSchedule<TWorkflow extends AnyWorkflowDefinition$1 = AnyWorkflowDefinition$1> extends ScheduleDefinition<TWorkflow> {
53
33
  readonly type: "schedule";
54
- readonly cron: string;
55
34
  readonly overlapPolicy: OverlapPolicy;
56
35
  readonly enabled: boolean;
57
- readonly smear: SmearPolicy;
58
36
  }
59
37
  declare function defineSchedule<TWorkflow extends AnyWorkflowDefinition$1>(schedule: ScheduleDefinition<TWorkflow>): ResolvedSchedule<TWorkflow>;
60
38
  //#endregion
@@ -67,7 +45,7 @@ interface WorkflowsDefinition<TWorkflow extends AnyWorkflowDefinition$1 = AnyWor
67
45
  readonly workflows: readonly TWorkflow[];
68
46
  readonly triggers: readonly ResolvedTrigger[];
69
47
  }
70
- declare function registerWorkflows<const TWorkflows extends readonly AnyWorkflowDefinition$1[]>({ workflows, triggers }: {
48
+ declare function registerWorkflows<const TWorkflows extends readonly AnyWorkflowDefinition$1[]>(definition: {
71
49
  workflows: TWorkflows;
72
50
  triggers?: readonly TriggerDefinition[];
73
51
  }): WorkflowsDefinition<TWorkflows[number]>;
@@ -138,15 +116,13 @@ interface WorkflowManifest {
138
116
  type: "schedule";
139
117
  id: string;
140
118
  cadence: Cadence;
141
- cron: string;
142
119
  timeZone: string;
143
120
  enabled: boolean;
144
121
  overlapPolicy: OverlapPolicy;
145
- smear: SmearPolicy;
146
122
  input: JsonValue;
147
123
  }[];
148
124
  graph: WorkflowGraph;
149
125
  }
150
126
  declare function generateManifests(definition: WorkflowsDefinition): Promise<WorkflowManifest[]>;
151
127
  //#endregion
152
- export { type AnyWorkflowDefinition, type Cadence, type Ctx, type OverlapPolicy, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type SmearOption, type SmearPolicy, type StepContext, type StepOptions, type TriggerDefinition, type Weekday, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createMiddleware, createWorkflow, daily, defineSchedule, every, generateManifests, hourly, registerWorkflows, smearOffsetSeconds, weekly };
128
+ export { type AnyWorkflowDefinition, type Cadence, type Ctx, type OverlapPolicy, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type StepContext, type StepOptions, type TriggerDefinition, type Weekday, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createMiddleware, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, weekly };
package/dist/index.js CHANGED
@@ -1,16 +1,2 @@
1
- import { a as defineSchedule, c as hourly, i as registerWorkflows, l as weekly, n as createMiddleware, o as daily, r as createWorkflow, s as every, t as generateManifests } from "./generate-IXn3QGVb.js";
2
- //#region src/core/smear.ts
3
- const FNV_OFFSET = 14695981039346656037n;
4
- const FNV_PRIME = 1099511628211n;
5
- const MASK = (1n << 64n) - 1n;
6
- function fnv1a64(value) {
7
- let hash = FNV_OFFSET;
8
- for (const byte of new TextEncoder().encode(value)) hash = (hash ^ BigInt(byte)) * FNV_PRIME & MASK;
9
- return hash;
10
- }
11
- function smearOffsetSeconds(projectId, scheduleId, windowSeconds) {
12
- if (!Number.isSafeInteger(windowSeconds) || windowSeconds <= 0) throw new Error("@lovable.dev/workflows-sdk: smear window must be a positive whole number of seconds");
13
- return Number(fnv1a64(`${projectId}\u0000${scheduleId}`) % BigInt(windowSeconds));
14
- }
15
- //#endregion
16
- export { createMiddleware, createWorkflow, daily, defineSchedule, every, generateManifests, hourly, registerWorkflows, smearOffsetSeconds, weekly };
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-DyUHbtre.js";
2
+ export { createMiddleware, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, weekly };
@@ -0,0 +1,31 @@
1
+ import { AnyWorkflowDefinition, RunStore, WorkflowEvent } from "@tanstack/workflow-core";
2
+ //#region src/stacks/tanstack/handlers.d.ts
3
+ /** The shape `registerWorkflows()` returns; only the list is needed to dispatch. */
4
+ interface WorkflowCollection {
5
+ readonly workflows: readonly AnyWorkflowDefinition[];
6
+ }
7
+ interface TanStackWorkflowHandlerOptions {
8
+ /** @default a process-local `inMemoryRunStore()`, lost on restart */
9
+ runStore?: RunStore;
10
+ /**
11
+ * Route parameter carrying the workflow ID.
12
+ * @default "workflowId"
13
+ */
14
+ workflowIdParam?: string;
15
+ }
16
+ interface TanStackRouteCtx {
17
+ request: Request;
18
+ params?: Record<string, string | undefined>;
19
+ }
20
+ type TanStackWorkflowHandler = (ctx: TanStackRouteCtx) => Promise<Response>;
21
+ /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
22
+ declare function createTanStackWorkflowHandler(collection: WorkflowCollection, options?: TanStackWorkflowHandlerOptions): TanStackWorkflowHandler;
23
+ //#endregion
24
+ //#region src/stacks/tanstack/sse.d.ts
25
+ /**
26
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
27
+ * engine `type` as the SSE event name and its whole JSON as the data line.
28
+ */
29
+ declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
30
+ //#endregion
31
+ export { type TanStackWorkflowHandler, type TanStackWorkflowHandlerOptions, type WorkflowCollection, createTanStackWorkflowHandler, toServerSentEventsResponse };
@@ -0,0 +1,99 @@
1
+ import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
2
+ //#region src/stacks/tanstack/sse.ts
3
+ const HEADERS = {
4
+ "content-type": "text/event-stream; charset=utf-8",
5
+ "cache-control": "no-cache, no-transform",
6
+ connection: "keep-alive",
7
+ "x-accel-buffering": "no"
8
+ };
9
+ function describe(error) {
10
+ return error instanceof Error ? error.message : String(error);
11
+ }
12
+ function frame(name, data) {
13
+ return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
14
+ }
15
+ /**
16
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
17
+ * engine `type` as the SSE event name and its whole JSON as the data line.
18
+ */
19
+ function toServerSentEventsResponse(events) {
20
+ const encoder = new TextEncoder();
21
+ const body = new ReadableStream({ async start(controller) {
22
+ let connected = true;
23
+ const write = (text) => {
24
+ if (!connected) return;
25
+ try {
26
+ controller.enqueue(encoder.encode(text));
27
+ } catch {
28
+ connected = false;
29
+ }
30
+ };
31
+ const send = (name, data) => {
32
+ try {
33
+ write(frame(name, data));
34
+ } catch (error) {
35
+ write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe(error)}` }));
36
+ }
37
+ };
38
+ try {
39
+ for await (const event of events) send(event.type, event);
40
+ } catch (error) {
41
+ send("STREAM_ERRORED", { message: describe(error) });
42
+ } finally {
43
+ try {
44
+ controller.close();
45
+ } catch {
46
+ connected = false;
47
+ }
48
+ }
49
+ } });
50
+ return new Response(body, { headers: HEADERS });
51
+ }
52
+ //#endregion
53
+ //#region src/stacks/tanstack/handlers.ts
54
+ function json(status, body) {
55
+ return new Response(JSON.stringify(body), {
56
+ status,
57
+ headers: { "content-type": "application/json; charset=utf-8" }
58
+ });
59
+ }
60
+ function resolveWorkflowId(ctx, param) {
61
+ const fromParams = ctx.params?.[param];
62
+ if (fromParams) return fromParams;
63
+ return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
64
+ }
65
+ /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
66
+ function createTanStackWorkflowHandler(collection, options = {}) {
67
+ const runStore = options.runStore ?? inMemoryRunStore();
68
+ const param = options.workflowIdParam ?? "workflowId";
69
+ const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
70
+ return async (ctx) => {
71
+ const workflowId = resolveWorkflowId(ctx, param);
72
+ const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
73
+ if (!workflow) return json(404, {
74
+ error: "unknown_workflow",
75
+ workflowId: workflowId ?? ""
76
+ });
77
+ let params;
78
+ try {
79
+ params = await parseWorkflowRequest(ctx.request);
80
+ } catch (error) {
81
+ if (error instanceof WorkflowRequestParseError) return json(400, {
82
+ error: "invalid_request",
83
+ message: error.message
84
+ });
85
+ throw error;
86
+ }
87
+ if (params.abort) return json(501, {
88
+ error: "abort_unsupported",
89
+ message: "Cancelling an in-flight run needs a shared run registry (WOR-53)."
90
+ });
91
+ return toServerSentEventsResponse(runWorkflow({
92
+ workflow,
93
+ runStore,
94
+ ...params
95
+ }));
96
+ };
97
+ }
98
+ //#endregion
99
+ export { createTanStackWorkflowHandler, toServerSentEventsResponse };
package/dist/vite.d.ts CHANGED
@@ -1,7 +1,22 @@
1
1
  import { Plugin } from "vite";
2
2
  //#region src/vite/plugin.d.ts
3
- declare function workflowsManifest({ entry }: {
4
- entry: string;
5
- }): Plugin;
3
+ interface WorkflowsPluginOptions {
4
+ /** Collection entry, relative to the project root. @default "src/lib/workflows/index.ts" */
5
+ entry?: string;
6
+ /** Where TanStack route files live; the plugin emits under this directory.
7
+ * @default "src/routes" */
8
+ routesDir?: string;
9
+ /** URL prefix; the workflow ID is appended as a dynamic segment. @default "/api/workflows" */
10
+ path?: string;
11
+ /** Route parameter carrying the workflow ID. @default "workflowId" */
12
+ workflowIdParam?: string;
13
+ /** @default false */
14
+ runRoute?: boolean;
15
+ }
16
+ /**
17
+ * Build the collection's manifests and, with `runRoute`, emit the route serving
18
+ * them; one `entry` feeds both, so the two can never describe different sets.
19
+ */
20
+ declare function workflowsPlugin(options?: WorkflowsPluginOptions): Plugin;
6
21
  //#endregion
7
- export { workflowsManifest };
22
+ export { type WorkflowsPluginOptions, workflowsPlugin };
package/dist/vite.js CHANGED
@@ -1,7 +1,8 @@
1
- import { t as generateManifests } from "./generate-IXn3QGVb.js";
2
- import { join, resolve } from "node:path";
1
+ import { t as generateManifests } from "./generate-DyUHbtre.js";
2
+ import { dirname, join, relative, resolve, sep } from "node:path";
3
3
  import { createServer } from "vite";
4
4
  import { lstat, mkdir, mkdtemp, readdir, rename, rm, writeFile } from "node:fs/promises";
5
+ import { lstatSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
5
6
  //#region src/vite/manifest-files.ts
6
7
  async function ensureDirectory(path) {
7
8
  try {
@@ -30,14 +31,181 @@ async function writeManifests(root, manifests) {
30
31
  }
31
32
  }
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
33
174
  //#region src/vite/plugin.ts
34
- function workflowsManifest({ entry }) {
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
+ });
35
188
  let config;
36
189
  return {
37
- name: "@lovable.dev/workflows-sdk/manifest",
38
- apply: "build",
190
+ name: "@lovable.dev/workflows-sdk",
39
191
  configResolved(resolved) {
40
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();
41
209
  },
42
210
  async generateBundle() {
43
211
  const entryPath = resolve(config.root, entry);
@@ -74,4 +242,4 @@ function workflowsManifest({ entry }) {
74
242
  };
75
243
  }
76
244
  //#endregion
77
- export { workflowsManifest };
245
+ export { workflowsPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/workflows-sdk",
3
- "version": "0.0.0-dev.4",
3
+ "version": "0.0.0-dev.6",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "dev",
@@ -22,6 +22,10 @@
22
22
  "./vite": {
23
23
  "types": "./dist/vite.d.ts",
24
24
  "import": "./dist/vite.js"
25
+ },
26
+ "./stacks/tanstack": {
27
+ "types": "./dist/stacks/tanstack/index.d.ts",
28
+ "import": "./dist/stacks/tanstack/index.js"
25
29
  }
26
30
  },
27
31
  "files": [