@lunora/workflow 0.0.0 → 1.0.0-alpha.1

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/LICENSE.md ADDED
@@ -0,0 +1,105 @@
1
+ # Functional Source License, Version 1.1, Apache 2.0 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-Apache-2.0
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 anolilab and contributors
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or service
34
+ that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software that
39
+ exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee using
52
+ the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to the
59
+ infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, EVEN
79
+ IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following will
93
+ apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
package/README.md CHANGED
@@ -1,18 +1,269 @@
1
- # @lunora/workflow
1
+ <!-- START_PACKAGE_OG_IMAGE_PLACEHOLDER -->
2
2
 
3
- > ⚠️ **Placeholder release.** This package name is reserved for the [Lunora](https://lunora.sh) framework. The real `1.0.0-alpha` release is coming soon.
3
+ <a href="https://www.anolilab.com/open-source" align="center">
4
4
 
5
- Durable workflows for Lunora: defineWorkflow over Cloudflare Workflows, generated WorkflowEntrypoint classes, and the ctx.workflows surface
5
+ <img src="__assets__/package-og.svg" alt="workflow" />
6
6
 
7
- Lunora is a type-safe, real-time backend framework for Cloudflare Workers + Durable Objects with a Vite-first developer experience.
7
+ </a>
8
8
 
9
- - Website: https://lunora.sh
10
- - Repository: https://github.com/anolilab/lunora
9
+ <h3 align="center">Durable workflows for Lunora: defineWorkflow over Cloudflare Workflows, generated WorkflowEntrypoint classes, and the ctx.workflows surface</h3>
11
10
 
12
- ## Status
11
+ <!-- END_PACKAGE_OG_IMAGE_PLACEHOLDER -->
13
12
 
14
- This is a `0.0.0` placeholder to reserve the npm name. Do not depend on it yet — APIs and exports are not published in this version. Watch the repository for the alpha release.
13
+ <br />
14
+
15
+ <div align="center">
16
+
17
+ [![typescript-image][typescript-badge]][typescript-url]
18
+ [![FSL-1.1-Apache-2.0 licence][license-badge]][license]
19
+ [![npm version][npm-version-badge]][npm-version]
20
+ [![npm downloads][npm-downloads-badge]][npm-downloads]
21
+ [![PRs Welcome][prs-welcome-badge]][prs-welcome]
22
+
23
+ </div>
24
+
25
+ ---
26
+
27
+ <div align="center">
28
+ <p>
29
+ <sup>
30
+ Daniel Bannert's open source work is supported by the community on <a href="https://github.com/sponsors/prisis">GitHub Sponsors</a>
31
+ </sup>
32
+ </p>
33
+ </div>
34
+
35
+ ---
36
+
37
+ Durable workflows for Lunora, built on [Cloudflare Workflows](https://developers.cloudflare.com/workflows/) (GA durable execution).
38
+
39
+ `defineWorkflow` lets you author a multi-step, durable program whose steps are **memoized and retried** automatically and that **survives Worker restarts and redeploys**. Codegen emits the `WorkflowEntrypoint` class and wires the typed `ctx.workflows` handle; `@lunora/config` reconciles the `[[workflows]]` binding.
40
+
41
+ Part of the [Lunora](https://github.com/anolilab/lunora) framework — a type-safe, real-time backend on Cloudflare Workers + Durable Objects with a Vite-first DX.
42
+
43
+ ## Install
44
+
45
+ ```sh
46
+ npm install @lunora/workflow
47
+ ```
48
+
49
+ ```sh
50
+ yarn add @lunora/workflow
51
+ ```
52
+
53
+ ```sh
54
+ pnpm add @lunora/workflow
55
+ ```
56
+
57
+ ## Usage
58
+
59
+ ### Authoring
60
+
61
+ ```ts
62
+ // lunora/workflows.ts
63
+ import { defineWorkflow } from "@lunora/workflow";
64
+ import { api } from "./_generated/api";
65
+
66
+ export const orderPipeline = defineWorkflow<{ orderId: string }>({
67
+ handler: async (ctx) => {
68
+ // ctx.step.do(...) is the durability boundary — memoized + retried.
69
+ const order = await ctx.step.do("load", () => ctx.run(api.orders.get, { id: ctx.params.orderId }));
70
+
71
+ await ctx.step.sleep("cool-off", "1 minute");
72
+
73
+ await ctx.step.do("charge", () => ctx.run(api.payments.charge, { orderId: ctx.params.orderId }));
74
+
75
+ // Hibernate until an external event arrives (webhook, approval, …).
76
+ const shipped = await ctx.step.waitForEvent<{ trackingId: string }>("await-shipment", { type: "shipment.created" });
77
+
78
+ return { order, trackingId: shipped.payload.trackingId };
79
+ },
80
+ });
81
+ ```
82
+
83
+ The handler context bundles:
84
+
85
+ - `ctx.step` — the native Cloudflare durable-step API (`do` / `sleep` / `sleepUntil` / `waitForEvent`).
86
+ - `ctx.run(ref, args, opts?)` — call a Lunora query / mutation / action; wrap in `ctx.step.do(...)` for durability.
87
+ - `ctx.runStep(step, args, opts?)` — run a reusable, schema-validated `defineStep` as a durable step (see below).
88
+ - `ctx.event` / `ctx.params` — the triggering event and its payload.
89
+ - `ctx.env` — the Worker bindings.
90
+ - `ctx.log` — a workflow-prefixed logger surfaced in `wrangler tail` / Studio.
91
+
92
+ ### Reusable steps (`defineStep`)
93
+
94
+ A step authored inline with `ctx.step.do("name", () => …)` is fine for one-offs, but `defineStep` lets you define a step **once** — schema-validated and reusable across workflows. Args are validated (with `@lunora/values`) **before** the body runs, and the return value is validated **after** (when you declare `returns`), so a bad payload fails fast instead of corrupting later steps. Scaffold one with `vis generate lunora-step --name=chargeOrder` (appends to `lunora/steps.ts`), or write it by hand:
95
+
96
+ ```ts
97
+ // lunora/steps.ts
98
+ import { defineStep } from "@lunora/workflow";
99
+ import { v } from "@lunora/values";
100
+
101
+ import { api } from "./_generated/api";
102
+
103
+ export const charge = defineStep("charge", {
104
+ args: { orderId: v.string(), amount: v.number() },
105
+ returns: v.object({ receiptId: v.string() }),
106
+ config: { retries: { limit: 3, backoff: "exponential", delay: "10 seconds" } },
107
+ handler: async (ctx, { orderId, amount }) => {
108
+ if (ctx.attempt > 1) ctx.log.warn(`retrying charge for ${orderId}`);
109
+ return ctx.run(api.payments.charge, { orderId, amount });
110
+ },
111
+ // Compensation — runs if a *later* step fails after this one committed.
112
+ rollback: async (ctx) => {
113
+ await ctx.run(api.payments.refund, { orderId: ctx.args.orderId });
114
+ },
115
+ });
116
+ ```
117
+
118
+ Run it from a workflow body — `ctx.runStep` wraps it in a durable `step.do(...)` for you:
119
+
120
+ ```ts
121
+ export const orderPipeline = defineWorkflow<{ orderId: string }>({
122
+ handler: async (ctx) => {
123
+ const { receiptId } = await ctx.runStep(charge, { orderId: ctx.params.orderId, amount: 4200 });
124
+ return { receiptId };
125
+ },
126
+ });
127
+ ```
128
+
129
+ The step handler context gives you `ctx.attempt` (1-based retry counter), `ctx.config`, `ctx.env`, `ctx.run`, `ctx.log`, and `ctx.step` (`{ name, count }`). Pass `ctx.runStep(step, args, { config })` to override the step's durability config for a single call.
130
+
131
+ ### Rollback (saga compensation)
132
+
133
+ A step's optional `rollback` handler is forwarded to Cloudflare's **native** step rollback — it runs when a later step in the same instance fails, letting you undo a committed side effect (refund a charge, delete an uploaded object). The rollback context carries the original `args`, the `error` that triggered it, the step's `output` (if it completed), and `env` / `run` / `log`. Cloudflare owns rollback ordering and execution; `defineStep` just wires the handler and an optional `rollbackConfig`.
134
+
135
+ ### Failing without retries (`NonRetryableError`)
136
+
137
+ Throw `NonRetryableError` from a step or the handler to fail the instance immediately, skipping retries — the portable, Node-importable mirror of `cloudflare:workflows`' native error (so your workflow code stays unit-testable). The runtime converts it to the native error at the workflow boundary.
138
+
139
+ ```ts
140
+ import { defineStep, NonRetryableError } from "@lunora/workflow";
141
+ import { v } from "@lunora/values";
142
+
143
+ import { api } from "./_generated/api";
144
+
145
+ export const charge = defineStep("charge", {
146
+ args: { orderId: v.string() },
147
+ handler: async (ctx, { orderId }) => {
148
+ const order = await ctx.run(api.orders.get, { id: orderId });
149
+ if (order.status === "cancelled") {
150
+ throw new NonRetryableError("order cancelled — retrying will never succeed");
151
+ }
152
+ return ctx.run(api.payments.charge, { orderId });
153
+ },
154
+ });
155
+ ```
156
+
157
+ ### Starting instances
158
+
159
+ Codegen wires a typed `ctx.workflows` handle onto mutations and actions. Resolve a handle by export name and start an instance:
160
+
161
+ ```ts
162
+ // lunora/orders.ts
163
+ import { mutation, v } from "./_generated/server";
164
+
165
+ export const checkout = mutation.input({ orderId: v.string() }).mutation(async ({ ctx, args: { orderId } }) => {
166
+ const instance = await ctx.workflows.get<{ orderId: string }>("orderPipeline").create({ params: { orderId } });
167
+
168
+ return { instanceId: instance.id };
169
+ });
170
+ ```
171
+
172
+ A handle exposes `create({ id?, params?, retention? })`, `createBatch([...])`, and `get(id)`. An instance handle exposes its lifecycle: `status()`, `pause()`, `resume()`, `terminate()`, and `sendEvent({ type, payload })` (to satisfy a `waitForEvent`).
173
+
174
+ ### Runtime requirements
175
+
176
+ `ctx.run` dispatches back into the Worker, so the workflow's `env` must carry:
177
+
178
+ - `LUNORA_ORIGIN_URL` — where the Worker is mounted.
179
+ - `LUNORA_ADMIN_TOKEN` — the admin bearer the dispatch endpoint accepts.
180
+
181
+ ### Manual wiring (without codegen)
182
+
183
+ 1. Author `lunora/workflows.ts` as above.
184
+ 2. Re-export the generated class from your worker entry — wrangler requires every `workflows[].class_name` to be exported:
185
+
186
+ ```ts
187
+ import LunoraWorkflow from "@lunora/workflow/do";
188
+ import { orderPipeline } from "./lunora/workflows";
189
+
190
+ export class OrderPipelineWorkflow extends LunoraWorkflow {
191
+ constructor(ctx: ExecutionContext, env: Record<string, unknown>) {
192
+ super(ctx, env, orderPipeline, "orderPipeline");
193
+ }
194
+ }
195
+ ```
196
+
197
+ 3. Add the binding to `wrangler.jsonc`:
198
+
199
+ ```jsonc
200
+ {
201
+ "workflows": [{ "name": "order-pipeline", "binding": "WORKFLOW_ORDER_PIPELINE", "class_name": "OrderPipelineWorkflow" }],
202
+ }
203
+ ```
204
+
205
+ 4. Build `ctx.workflows` from the binding: `createWorkflows({ bindings: { orderPipeline: env.WORKFLOW_ORDER_PIPELINE } })`.
206
+
207
+ The `workflowClassName` / `workflowBindingName` / `workflowDefaultName` helpers produce exactly these names so codegen and config never disagree.
208
+
209
+ ### Observing instances (REST client)
210
+
211
+ The Worker `Workflow` binding can only `create`/`get` an instance and read one instance's status — it has no instance list and no per-step detail. To list instances or read a step timeline, use `createWorkflowsRestClient`, which talks to Cloudflare's account-scoped Workflows REST API. The API token is a secret, so this runs server-side only (the Studio reaches it through the admin-gated runtime proxy).
212
+
213
+ ```ts
214
+ import { createWorkflowsRestClient } from "@lunora/workflow";
215
+
216
+ const client = createWorkflowsRestClient({
217
+ accountId: env.CLOUDFLARE_ACCOUNT_ID,
218
+ apiToken: env.CLOUDFLARE_API_TOKEN, // scope: Workflows Read (Edit for setInstanceStatus)
219
+ });
220
+
221
+ const page = await client.listInstances({ workflowName: "order-pipeline", status: "running" });
222
+ const detail = await client.getInstance({ workflowName: "order-pipeline", instanceId: page.instances[0].id });
223
+ await client.setInstanceStatus({ workflowName: "order-pipeline", instanceId: detail.id, action: "terminate" });
224
+ ```
225
+
226
+ > This README covers the basics. For the full API, options, and guides, see the **[documentation](https://lunora.sh/docs/addons/workflows)**.
227
+
228
+ ## Related
229
+
230
+ - [`@lunora/server`](https://www.npmjs.com/package/@lunora/server) — start workflows via `ctx.workflows` from a mutation or action.
231
+ - [`@lunora/scheduler`](https://www.npmjs.com/package/@lunora/scheduler) — `runAfter` / `runAt` + Cron Triggers for non-durable scheduling.
232
+ - [`@lunora/config`](https://www.npmjs.com/package/@lunora/config) — reconciles the `[[workflows]]` binding.
233
+
234
+ ## Supported Node.js Versions
235
+
236
+ Libraries in this ecosystem make the best effort to track [Node.js' release schedule](https://github.com/nodejs/release#release-schedule).
237
+ Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a).
238
+
239
+ ## Contributing
240
+
241
+ If you would like to help take a look at the [list of issues](https://github.com/anolilab/lunora/issues) and check our [Contributing](https://github.com/anolilab/lunora/blob/alpha/.github/CONTRIBUTING.md) guidelines.
242
+
243
+ > **Note:** please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.
244
+
245
+ ## Credits
246
+
247
+ - [Daniel Bannert](https://github.com/prisis)
248
+ - [All Contributors](https://github.com/anolilab/lunora/graphs/contributors)
249
+
250
+ ## Made with ❤️ at Anolilab
251
+
252
+ This is an open source project and will always remain free to use. If you think it's cool, please star it 🌟. [Anolilab](https://www.anolilab.com/open-source) is a Development and AI Studio. Contact us at [hello@anolilab.com](mailto:hello@anolilab.com) if you need any help with these technologies or just want to say hi!
15
253
 
16
254
  ## License
17
255
 
18
- FSL-1.1-Apache-2.0
256
+ The Lunora workflow package is open-sourced software licensed under the [FSL-1.1-Apache-2.0][license].
257
+
258
+ <!-- badges -->
259
+
260
+ [license-badge]: https://img.shields.io/badge/license-FSL--1.1--Apache--2.0-blue.svg?style=for-the-badge
261
+ [license]: https://github.com/anolilab/lunora/blob/alpha/LICENSE.md
262
+ [npm-version-badge]: https://img.shields.io/npm/v/@lunora/workflow?style=for-the-badge
263
+ [npm-version]: https://www.npmjs.com/package/@lunora/workflow
264
+ [npm-downloads-badge]: https://img.shields.io/npm/dm/@lunora/workflow?style=for-the-badge
265
+ [npm-downloads]: https://www.npmjs.com/package/@lunora/workflow
266
+ [prs-welcome-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=for-the-badge
267
+ [prs-welcome]: https://github.com/anolilab/lunora/blob/alpha/.github/CONTRIBUTING.md
268
+ [typescript-badge]: https://img.shields.io/badge/Typescript-294E80.svg?style=for-the-badge&logo=typescript
269
+ [typescript-url]: https://www.typescriptlang.org/