@lunora/container 0.0.0 → 1.0.0-alpha.10

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,131 @@
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.
106
+
107
+ <!-- DEPENDENCIES -->
108
+
109
+ # Licenses of bundled dependencies
110
+ The published @lunora/container artifact additionally contains code with the following licenses:
111
+ MIT OR Apache-2.0
112
+
113
+ # Bundled dependencies:
114
+ ## @cloudflare/containers
115
+ License: MIT OR Apache-2.0
116
+ Repository: git+https://github.com/cloudflare/containers.git
117
+
118
+ <!-- /DEPENDENCIES -->
119
+
120
+ <!-- TYPE_DEPENDENCIES -->
121
+
122
+ # Licenses of bundled types
123
+ The published @lunora/container artifact additionally contains code with the following licenses:
124
+ MIT OR Apache-2.0
125
+
126
+ # Bundled types:
127
+ ## @cloudflare/containers
128
+ License: MIT OR Apache-2.0
129
+ Repository: git+https://github.com/cloudflare/containers.git
130
+
131
+ <!-- /TYPE_DEPENDENCIES -->
package/README.md CHANGED
@@ -1,18 +1,258 @@
1
- # @lunora/container
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
- Cloudflare Containers for Lunora: defineContainer, generated Container DO classes, and the ctx.containers action surface
5
+ <img src="__assets__/package-og.svg" alt="container" />
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">Cloudflare Containers for Lunora: defineContainer, generated Container DO classes, and the ctx.containers action 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
+ Cloudflare Containers for Lunora: `defineContainer`, generated Container Durable Object classes, and the `ctx.containers` action surface.
38
+
39
+ 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.
40
+
41
+ ## Install
42
+
43
+ ```sh
44
+ npm install @lunora/container
45
+ ```
46
+
47
+ ```sh
48
+ yarn add @lunora/container
49
+ ```
50
+
51
+ ```sh
52
+ pnpm add @lunora/container
53
+ ```
54
+
55
+ ## Usage
56
+
57
+ Declare containers in `lunora/containers.ts`:
58
+
59
+ ```ts
60
+ import { defineContainer } from "@lunora/container";
61
+
62
+ export const transcoder = defineContainer({
63
+ image: "./containers/transcoder", // dir with a Dockerfile, or { registry: "docker.io/acme/transcoder:1.4" }
64
+ defaultPort: 8080,
65
+ instanceType: "standard-1",
66
+ maxInstances: 5,
67
+ sleepAfter: "5m",
68
+ secrets: ["TRANSCODER_API_KEY"], // forwarded from Worker secrets / .dev.vars
69
+ labels: { team: "media" }, // metadata attached to every instance for metrics/observability
70
+ });
71
+ ```
72
+
73
+ Codegen emits the Container Durable Object class into `_generated/containers.ts` (re-export it from your worker entry) and wires a typed handle onto `ActionCtx`:
74
+
75
+ ```ts
76
+ // lunora/transcode.ts — `action` and `v` come from your generated server module.
77
+ import { action, v } from "@/lunora/_generated/server";
78
+
79
+ export const transcode = action.input({ videoId: v.id("videos") }).action(async ({ args: { videoId }, ctx }) => {
80
+ // one instance per entity (same id always routes to the same container)
81
+ const res = await ctx.containers.transcoder.get(videoId).fetch("/transcode", { method: "POST" });
82
+
83
+ // a random instance from a fixed pool, for stateless work
84
+ const probe = await ctx.containers.transcoder.any().fetch("/healthz");
85
+
86
+ // .pool() is like .any() but retries on another instance on a 5xx / thrown error
87
+ const out = await ctx.containers.transcoder.pool({ attempts: 3 }).fetch("/transcode", { method: "POST" });
88
+
89
+ return res.json();
90
+ });
91
+ ```
92
+
93
+ `.get()` and `.any()` retry the **same** instance through a cold start — when a request lands while Cloudflare is still provisioning (a `503` "no instance", `500` "Failed to start", `429`, or "not listening"), they back off and retry (default 3 attempts) so the provisioning race never reaches your handler. Genuine app `5xx`s pass straight through. Tune or disable per call with `.get(id, { attempts, backoffMs })` (a pre-built `Request` is sent once and not retried, since its body may not be replayable).
94
+
95
+ `ctx.containers` is action-only (container calls are external I/O, like `ctx.fetch`); `.get(name)` handles also expose `start`/`stop`/`destroy`/`getState` lifecycle control plus `renewActivityTimeout()` and `egress.*` (adjust the allow/deny lists at runtime). HTTP requests and WebSocket frames already keep a busy container awake automatically; `renewActivityTimeout()` is the escape hatch for non-HTTP/non-WS activity.
96
+
97
+ The config layer (`lunora dev` / `lunora deploy`) reconciles the wrangler `containers[]` entry, the `CONTAINER_*` Durable Object binding, and the SQLite-class migration automatically; `wrangler deploy` builds the Dockerfile with local Docker and pushes it to the Cloudflare Registry.
98
+
99
+ ### Multi-port containers
100
+
101
+ Declare every port the container must be listening on with `requiredPorts` (start-up waits for all of them); `defaultPort` is the target when a request doesn't pick one. Route a single request to another port with `.port(n)` — it composes with `.get()`, `.any()`, and `.pool()`:
102
+
103
+ ```ts
104
+ export const app = defineContainer({
105
+ image: "./containers/app",
106
+ defaultPort: 8080,
107
+ requiredPorts: [8080, 9090], // app + admin
108
+ });
109
+
110
+ // in an action:
111
+ await ctx.containers.app.get(tenantId).fetch("/work"); // → 8080
112
+ await ctx.containers.app.get(tenantId).port(9090).fetch("/admin"); // → 9090
113
+ ```
114
+
115
+ ### Build-time args
116
+
117
+ `env` and `secrets` are runtime values; for build-time `docker build --build-arg` values (wrangler `image_vars`, exposed to the Dockerfile as `ARG`) use `buildArgs`. They apply only to an image Lunora builds and are ignored for a pre-built `{ registry }` image.
118
+
119
+ ```ts
120
+ export const worker = defineContainer({
121
+ image: "./containers/worker",
122
+ buildArgs: { NODE_VERSION: "22", BUILD_TARGET: "production" },
123
+ });
124
+ ```
125
+
126
+ ### Secrets and Secrets Store
127
+
128
+ `secrets` forwards plain Worker secrets into the container env; `secretsStore` maps a _container env-var name → Cloudflare [Secrets Store](https://developers.cloudflare.com/secrets-store/) binding name_ and resolves each with its async `.get()` at first start (memoised). A collision with `env`/`secrets` is rejected at authoring time; a missing binding fails the start — the same fail-closed stance as `secrets`. Like `env`/`secrets`, these injected values only apply to implicit starts or a bare `start()`; a per-instance `start({ envVars })` replaces the env set wholesale (and skips Secrets Store resolution entirely).
129
+
130
+ ```ts
131
+ export const worker = defineContainer({
132
+ image: "./containers/worker",
133
+ secrets: ["TRANSCODER_API_KEY"], // plain Worker secret → same-named env var
134
+ secretsStore: { STRIPE_KEY: "STRIPE_SECRET" }, // env.STRIPE_SECRET.get() → STRIPE_KEY
135
+ });
136
+ ```
137
+
138
+ ### Egress firewall
139
+
140
+ Pair `enableInternet: false` with an `allowedHosts` allow-list (or layer a `deniedHosts` deny-list that overrides everything) to constrain a container's outbound traffic; `interceptHttps: true` extends the lists to TLS connections (the image must trust the Cloudflare CA). Codegen re-exports the `ContainerProxy` worker entrypoint the interception path needs automatically.
141
+
142
+ ```ts
143
+ export const fetcher = defineContainer({
144
+ image: "./containers/fetcher",
145
+ enableInternet: false,
146
+ allowedHosts: ["*.stripe.com", "api.github.com"],
147
+ deniedHosts: ["*.evil.com"],
148
+ });
149
+
150
+ // tighten or relax one running instance at runtime:
151
+ await ctx.containers.fetcher.get(tenantId).egress.allow("hooks.slack.com");
152
+ ```
153
+
154
+ For advanced egress rewriting in worker code, `@lunora/container/do` re-exports Cloudflare's custom outbound-handler types (`OutboundHandler`, `OutboundHandlers`, `outboundParams`) — wire them onto a hand-authored `LunoraContainer` subclass to inject auth, route, or mock a container's outbound calls.
155
+
156
+ ### Readiness gating
157
+
158
+ The platform health check waits for an open port, not necessarily a _ready_ app. `readyOn` adds application-level probes that gate request proxying: a `ctx.containers.<name>` fetch holds until every probe responds with its expected status, so callers never hit a container still applying migrations or warming caches. Probes are declarative data (path + optional `port`/`status`), run in parallel at start, and probe the container's TCP port directly.
159
+
160
+ ```ts
161
+ export const api = defineContainer({
162
+ image: "./containers/api",
163
+ defaultPort: 8080,
164
+ readyOn: [
165
+ { path: "/ready" }, // expect 200 on defaultPort
166
+ { path: "/live", port: 9090, status: 204 }, // own port + expected status
167
+ ],
168
+ });
169
+ ```
170
+
171
+ ### Hard timeout
172
+
173
+ `sleepAfter` caps _idle_ time; `hardTimeout` caps _total_ lifetime — a runaway-cost backstop measured from start, regardless of activity (same grammar as `sleepAfter`). When it elapses the generated class's `onHardTimeoutExpired` hook runs (default: `stop()`); the timer is run-generation-stamped so a stale timer from a slept/crashed run can't kill a fresh one.
174
+
175
+ ```ts
176
+ export const job = defineContainer({
177
+ image: "./containers/job",
178
+ hardTimeout: "1h", // never run longer than an hour, busy or not
179
+ });
180
+ ```
181
+
182
+ ### Calling Lunora from inside a container
183
+
184
+ Container code calls back into your app's functions with the bridge client (any JS runtime), over the Worker's HTTP RPC endpoint:
185
+
186
+ ```ts
187
+ import { createContainerBridge } from "@lunora/container/bridge";
188
+
189
+ const lunora = createContainerBridge({ baseUrl: process.env.LUNORA_URL!, token: process.env.LUNORA_TOKEN });
190
+
191
+ const pending = await lunora.query("jobs:listPending", { limit: 10 });
192
+ await lunora.mutation("jobs:markDone", { id: pending[0].id });
193
+ ```
194
+
195
+ The token is a bearer your Worker's `resolveIdentity` recognizes — pass it to the container as a `secret`. Non-JS containers can `POST /_lunora/rpc` with `{ functionPath, args }` directly.
196
+
197
+ Secure the bridge in `resolveIdentity`: read `request.headers.get("authorization")`, strip the `Bearer ` prefix, and compare the token against a Worker secret (e.g. `env.LUNORA_CONTAINER_TOKEN`) you also forward to the container. Return a `{ userId }` identity only on a match and `null` otherwise — an unrecognised request then runs anonymously and is rejected by your functions' own authorization checks. See [Securing the bridge](https://lunora.sh/docs/addons/containers#securing-the-bridge) for the full example.
198
+
199
+ ### Entry points
200
+
201
+ - `@lunora/container` — Node-safe: `defineContainer`, naming/normalization helpers, `createContainerContext`, and the Docker-free `createContainerTestContext` test double.
202
+ - `@lunora/container/do` — workerd-only: the `LunoraContainer` base class the generated DO classes extend (pulls in `@cloudflare/containers`).
203
+ - `@lunora/container/bridge` — runtime-agnostic: `createContainerBridge` for calling Lunora functions from inside a container.
204
+
205
+ > This README covers the basics. For the full API, options, and guides, see the **[documentation](https://lunora.sh/docs/addons/containers)**.
206
+
207
+ ### Known platform limitations
208
+
209
+ Some constraints live in Cloudflare Containers itself (open issues on [`cloudflare/containers`](https://github.com/cloudflare/containers/issues)). Lunora papers over what it can — cold-start retry and WebSocket keep-alive — and surfaces the rest:
210
+
211
+ - **No autoscaling / location-aware routing** — pools are fixed-size and pick uniformly at random ([#226](https://github.com/cloudflare/containers/issues/226)).
212
+ - **Ephemeral disk; no FUSE / tmpfs / some `node:net` modes** — persist to [`@lunora/storage`](https://www.npmjs.com/package/@lunora/storage) (R2) ([#112](https://github.com/cloudflare/containers/issues/112), [#160](https://github.com/cloudflare/containers/issues/160), [#67](https://github.com/cloudflare/containers/issues/67)).
213
+ - **Egress interception is HTTP-first** — HTTPS needs `interceptHttps`; raw gRPC isn't interceptable yet ([#195](https://github.com/cloudflare/containers/issues/195)).
214
+ - **Long jobs can be terminated on rollout** — use `hardTimeout` and make work resumable ([#138](https://github.com/cloudflare/containers/issues/138)).
215
+ - **Local dev can't pull from the Cloudflare Registry** — build from a local Dockerfile ([#155](https://github.com/cloudflare/containers/issues/155)).
216
+
217
+ ## Related
218
+
219
+ - [`@lunora/server`](https://www.npmjs.com/package/@lunora/server) — defines the actions that drive containers via `ctx.containers`.
220
+ - [`@lunora/config`](https://www.npmjs.com/package/@lunora/config) — reconciles the wrangler `containers[]` entry and Durable Object binding.
221
+ - [`@lunora/runtime`](https://www.npmjs.com/package/@lunora/runtime) — the Worker runtime the bridge client calls back into.
222
+
223
+ ## Supported Node.js Versions
224
+
225
+ Libraries in this ecosystem make the best effort to track [Node.js' release schedule](https://github.com/nodejs/release#release-schedule).
226
+ 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).
227
+
228
+ ## Contributing
229
+
230
+ 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.
231
+
232
+ > **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.
233
+
234
+ ## Credits
235
+
236
+ - [Daniel Bannert](https://github.com/prisis)
237
+ - [All Contributors](https://github.com/anolilab/lunora/graphs/contributors)
238
+
239
+ ## Made with ❤️ at Anolilab
240
+
241
+ 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
242
 
16
243
  ## License
17
244
 
18
- FSL-1.1-Apache-2.0
245
+ The Lunora container package is open-sourced software licensed under the [FSL-1.1-Apache-2.0][license].
246
+
247
+ <!-- badges -->
248
+
249
+ [license-badge]: https://img.shields.io/badge/license-FSL--1.1--Apache--2.0-blue.svg?style=for-the-badge
250
+ [license]: https://github.com/anolilab/lunora/blob/alpha/LICENSE.md
251
+ [npm-version-badge]: https://img.shields.io/npm/v/@lunora/container?style=for-the-badge
252
+ [npm-version]: https://www.npmjs.com/package/@lunora/container
253
+ [npm-downloads-badge]: https://img.shields.io/npm/dm/@lunora/container?style=for-the-badge
254
+ [npm-downloads]: https://www.npmjs.com/package/@lunora/container
255
+ [prs-welcome-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=for-the-badge
256
+ [prs-welcome]: https://github.com/anolilab/lunora/blob/alpha/.github/CONTRIBUTING.md
257
+ [typescript-badge]: https://img.shields.io/badge/Typescript-294E80.svg?style=for-the-badge&logo=typescript
258
+ [typescript-url]: https://www.typescriptlang.org/