@lunora/container 1.0.0-alpha.4 → 1.0.0-alpha.41

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.
@@ -1,200 +0,0 @@
1
- const NAMED_INSTANCE_TYPES = /* @__PURE__ */ new Set(["basic", "lite", "standard-1", "standard-2", "standard-3", "standard-4"]);
2
- const ENV_NAME_PATTERN = /^[A-Z_]\w*$/i;
3
- const SLEEP_AFTER_PATTERN = /^\d+[smh]$/;
4
- const DURATION_UNIT_SECONDS = { h: 3600, m: 60, s: 1 };
5
- const parseDurationSeconds = (duration) => {
6
- if (typeof duration === "number") {
7
- return Math.floor(duration);
8
- }
9
- const match = SLEEP_AFTER_PATTERN.exec(duration);
10
- if (match === null) {
11
- throw new TypeError(`Invalid duration "${duration}" — expected a number of seconds or "<n>[smh]"`);
12
- }
13
- return Number(duration.slice(0, -1)) * (DURATION_UNIT_SECONDS[duration.slice(-1)] ?? 1);
14
- };
15
- const basename = (path) => {
16
- const trimmed = path.endsWith("/") ? path.slice(0, -1) : path;
17
- const separatorIndex = trimmed.lastIndexOf("/");
18
- return separatorIndex === -1 ? trimmed : trimmed.slice(separatorIndex + 1);
19
- };
20
- const dirname = (path) => {
21
- const separatorIndex = path.lastIndexOf("/");
22
- return separatorIndex === -1 ? "." : path.slice(0, separatorIndex) || "/";
23
- };
24
- const normalizeContainerImage = (image) => {
25
- if (typeof image !== "string") {
26
- if ("build" in image) {
27
- const buildDirectory = image.build.endsWith("/") ? image.build.slice(0, -1) : image.build;
28
- return { buildDir: buildDirectory, kind: "build" };
29
- }
30
- return { kind: "registry", reference: image.registry };
31
- }
32
- if (basename(image).startsWith("Dockerfile")) {
33
- return { buildContext: dirname(image), dockerfilePath: image, kind: "dockerfile" };
34
- }
35
- const context = image.endsWith("/") ? image.slice(0, -1) : image;
36
- return { buildContext: context, dockerfilePath: `${context}/Dockerfile`, kind: "dockerfile" };
37
- };
38
- const containerClassName = (exportName) => `${exportName.charAt(0).toUpperCase()}${exportName.slice(1)}Container`;
39
- const containerBindingName = (exportName) => `CONTAINER_${exportName.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g, "_").toUpperCase()}`;
40
- const containerBuildTag = (exportName) => `lunora-${exportName.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g, "-").toLowerCase()}:build`;
41
- const assertValidImage = (image) => {
42
- if (typeof image === "string") {
43
- if (image.length === 0) {
44
- throw new TypeError("defineContainer: `image` must be a non-empty path or a { registry } reference");
45
- }
46
- if (image.includes(":")) {
47
- throw new TypeError(
48
- `defineContainer: \`image\` string "${image}" looks like a registry reference — pass it as { registry: "${image}" } instead. Plain strings are local Dockerfile paths.`
49
- );
50
- }
51
- return;
52
- }
53
- if ("build" in image) {
54
- if (typeof image.build !== "string" || image.build.length === 0) {
55
- throw new TypeError("defineContainer: `image.build` must be a non-empty source directory for Railpack to build");
56
- }
57
- return;
58
- }
59
- if (typeof image.registry !== "string" || image.registry.length === 0) {
60
- throw new TypeError("defineContainer: `image.registry` must be a non-empty fully-qualified image reference");
61
- }
62
- };
63
- const assertValidEnvAndSecrets = (config) => {
64
- for (const name of Object.keys(config.env ?? {})) {
65
- if (!ENV_NAME_PATTERN.test(name)) {
66
- throw new TypeError(`defineContainer: env variable name "${name}" is not a valid environment variable name`);
67
- }
68
- }
69
- for (const name of Object.keys(config.buildArgs ?? {})) {
70
- if (!ENV_NAME_PATTERN.test(name)) {
71
- throw new TypeError(`defineContainer: buildArg name "${name}" is not a valid environment variable name`);
72
- }
73
- }
74
- const envNames = new Set(Object.keys(config.env ?? {}));
75
- for (const secret of config.secrets ?? []) {
76
- if (!ENV_NAME_PATTERN.test(secret)) {
77
- throw new TypeError(`defineContainer: secret name "${secret}" is not a valid environment variable name`);
78
- }
79
- if (envNames.has(secret)) {
80
- throw new TypeError(
81
- `defineContainer: "${secret}" is declared in both \`env\` and \`secrets\` — a secret would silently overwrite the static env value; pick one`
82
- );
83
- }
84
- }
85
- };
86
- const assertValidPort = (port, field) => {
87
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
88
- throw new TypeError(`defineContainer: \`${field}\` must be an integer in 1–65535 (got ${String(port)})`);
89
- }
90
- };
91
- const assertValidReadyOnChecks = (config) => {
92
- for (const check of config.readyOn ?? []) {
93
- if (typeof check.path !== "string" || check.path.trim().length === 0) {
94
- throw new TypeError("defineContainer: `readyOn[].path` must be a non-empty HTTP path string");
95
- }
96
- if (check.path !== check.path.trim()) {
97
- throw new TypeError("defineContainer: `readyOn[].path` must not have leading or trailing whitespace");
98
- }
99
- if (check.port !== void 0) {
100
- assertValidPort(check.port, "readyOn[].port");
101
- }
102
- if (check.status !== void 0 && (!Number.isInteger(check.status) || check.status < 100 || check.status > 599)) {
103
- throw new TypeError(`defineContainer: \`readyOn[].status\` must be an HTTP status code in 100–599 (got ${String(check.status)})`);
104
- }
105
- }
106
- };
107
- const assertValidHardTimeout = (hardTimeout) => {
108
- if (hardTimeout === void 0) {
109
- return;
110
- }
111
- if (typeof hardTimeout === "string") {
112
- if (!SLEEP_AFTER_PATTERN.test(hardTimeout)) {
113
- throw new TypeError(
114
- `defineContainer: \`hardTimeout\` string "${hardTimeout}" must be a number of seconds followed by a unit, e.g. "30s", "5m", or "1h"`
115
- );
116
- }
117
- } else if (!Number.isInteger(hardTimeout) || hardTimeout < 1) {
118
- throw new TypeError(
119
- `defineContainer: \`hardTimeout\` must be a positive integer number of seconds or a duration string like "5m" (got ${String(hardTimeout)})`
120
- );
121
- }
122
- };
123
- const assertValidEgressFields = (config) => {
124
- for (const field of ["allowedHosts", "deniedHosts"]) {
125
- const hosts = config[field];
126
- if (hosts?.some((host) => typeof host !== "string" || host.trim().length === 0)) {
127
- throw new TypeError(`defineContainer: \`${field}\` must be an array of non-empty hostname patterns`);
128
- }
129
- }
130
- if (config.interceptHttps !== void 0 && typeof config.interceptHttps !== "boolean") {
131
- throw new TypeError("defineContainer: `interceptHttps` must be a boolean, or omitted");
132
- }
133
- };
134
- const assertValidContainerRuntimeFields = (config) => {
135
- if (config.requiredPorts !== void 0) {
136
- if (config.requiredPorts.length === 0) {
137
- throw new TypeError("defineContainer: `requiredPorts` must be a non-empty array of ports, or omitted");
138
- }
139
- for (const port of config.requiredPorts) {
140
- assertValidPort(port, "requiredPorts[]");
141
- }
142
- }
143
- if (config.entrypoint !== void 0 && (config.entrypoint.length === 0 || config.entrypoint.some((part) => typeof part !== "string" || part.trim().length === 0))) {
144
- throw new TypeError("defineContainer: `entrypoint` must be a non-empty array of non-empty strings, or omitted");
145
- }
146
- assertValidEgressFields(config);
147
- if (config.pingEndpoint !== void 0 && (typeof config.pingEndpoint !== "string" || config.pingEndpoint.trim().length === 0)) {
148
- throw new TypeError("defineContainer: `pingEndpoint` must be a non-empty path string");
149
- }
150
- for (const [key, value] of Object.entries(config.labels ?? {})) {
151
- if (key.trim().length === 0 || typeof value !== "string") {
152
- throw new TypeError("defineContainer: `labels` must be a record of non-empty keys to string values");
153
- }
154
- }
155
- assertValidReadyOnChecks(config);
156
- };
157
- const defineContainer = (config) => {
158
- assertValidImage(config.image);
159
- if (config.defaultPort !== void 0) {
160
- assertValidPort(config.defaultPort, "defaultPort");
161
- }
162
- const stepPercentage = config.rollout?.stepPercentage;
163
- if (stepPercentage !== void 0 && (!Number.isInteger(stepPercentage) || stepPercentage < 1 || stepPercentage > 100)) {
164
- throw new TypeError(`defineContainer: \`rollout.stepPercentage\` must be an integer in 1–100 (got ${String(stepPercentage)})`);
165
- }
166
- if (config.maxInstances !== void 0 && (!Number.isInteger(config.maxInstances) || config.maxInstances < 1)) {
167
- throw new TypeError(`defineContainer: \`maxInstances\` must be a positive integer (got ${String(config.maxInstances)})`);
168
- }
169
- if (typeof config.instanceType === "string" && !NAMED_INSTANCE_TYPES.has(config.instanceType)) {
170
- throw new TypeError(
171
- `defineContainer: unknown \`instanceType\` "${config.instanceType}" — use one of ${[...NAMED_INSTANCE_TYPES].join(", ")}, or a custom { vcpu, memoryMib, diskMb } object`
172
- );
173
- }
174
- if (typeof config.sleepAfter === "string" && !SLEEP_AFTER_PATTERN.test(config.sleepAfter)) {
175
- throw new TypeError(
176
- `defineContainer: \`sleepAfter\` string "${config.sleepAfter}" must be a number of seconds followed by a unit, e.g. "30s", "5m", or "1h"`
177
- );
178
- }
179
- assertValidHardTimeout(config.hardTimeout);
180
- assertValidEnvAndSecrets(config);
181
- assertValidContainerRuntimeFields(config);
182
- return { ...config, isLunoraContainer: true };
183
- };
184
- const isContainerDefinition = (value) => typeof value === "object" && value !== null && value.isLunoraContainer === true;
185
- const resolveContainerEnvVariables = (definition, workerEnv, exportName) => {
186
- const resolved = { ...definition.env };
187
- for (const secret of definition.secrets ?? []) {
188
- const value = workerEnv[secret];
189
- if (typeof value !== "string") {
190
- const label = exportName === void 0 ? "container" : `container "${exportName}"`;
191
- throw new Error(
192
- `${label}: declared secret "${secret}" is not set on the Worker environment. Add it to .dev.vars for local dev and run \`wrangler secret put ${secret}\` for production.`
193
- );
194
- }
195
- resolved[secret] = value;
196
- }
197
- return resolved;
198
- };
199
-
200
- export { containerBindingName, containerBuildTag, containerClassName, defineContainer, isContainerDefinition, normalizeContainerImage, parseDurationSeconds, resolveContainerEnvVariables as resolveContainerEnvVars };
@@ -1,158 +0,0 @@
1
- const applyJurisdiction = (namespace, jurisdiction) => {
2
- if (jurisdiction === void 0) {
3
- return namespace;
4
- }
5
- if (typeof namespace.jurisdiction !== "function") {
6
- throw new TypeError(
7
- `@lunora/container: Durable Object namespace does not support jurisdiction("${jurisdiction}") — update @cloudflare/workers-types or remove the jurisdiction option`
8
- );
9
- }
10
- return namespace.jurisdiction(jurisdiction);
11
- };
12
- const DEFAULT_POOL_SIZE = 3;
13
- const DEFAULT_MAX_BACKOFF_MS = 3e4;
14
- const TARGET_PORT_HEADER = "cf-container-target-port";
15
- const toRequest = (input, init, port) => {
16
- const request = typeof input === "string" && input.startsWith("/") ? new Request(`http://container${input}`, init) : new Request(input, init);
17
- if (port !== void 0) {
18
- request.headers.set(TARGET_PORT_HEADER, String(port));
19
- }
20
- return request;
21
- };
22
- const sendingHandle = (send, port) => {
23
- return {
24
- fetch: async (input, init) => send(toRequest(input, init, port)),
25
- port: (targetPort) => sendingHandle(send, targetPort)
26
- };
27
- };
28
- const handleFor = (namespace, instanceName) => sendingHandle(async (request) => namespace.get(namespace.idFromName(instanceName)).fetch(request));
29
- const lifecycleCall = async (stub, method, binding, argument) => {
30
- const rpc = stub[method];
31
- if (typeof rpc !== "function") {
32
- throw new TypeError(`ctx.containers: the "${binding}" container DO does not expose ${method}() — is @lunora/container/do up to date?`);
33
- }
34
- return rpc(argument);
35
- };
36
- const egressControlsFor = (stub, binding) => {
37
- return {
38
- allow: async (hostname) => lifecycleCall(stub(), "allowHost", binding, hostname),
39
- deny: async (hostname) => lifecycleCall(stub(), "denyHost", binding, hostname),
40
- removeAllowed: async (hostname) => lifecycleCall(stub(), "removeAllowedHost", binding, hostname),
41
- removeDenied: async (hostname) => lifecycleCall(stub(), "removeDeniedHost", binding, hostname),
42
- setAllowed: async (hosts) => lifecycleCall(stub(), "setAllowedHosts", binding, [...hosts]),
43
- setDenied: async (hosts) => lifecycleCall(stub(), "setDeniedHosts", binding, [...hosts])
44
- };
45
- };
46
- const instanceHandleFor = (namespace, spec, instanceName) => {
47
- const stub = () => namespace.get(namespace.idFromName(instanceName));
48
- return {
49
- ...sendingHandle(async (request) => stub().fetch(request)),
50
- destroy: async () => lifecycleCall(stub(), "destroy", spec.binding),
51
- egress: egressControlsFor(stub, spec.binding),
52
- getState: async () => lifecycleCall(stub(), "getState", spec.binding),
53
- renewActivityTimeout: async () => lifecycleCall(stub(), "renewActivityTimeout", spec.binding),
54
- start: async (options) => lifecycleCall(stub(), "start", spec.binding, options),
55
- stop: async (signal) => lifecycleCall(stub(), "stop", spec.binding, signal)
56
- };
57
- };
58
- const randomPoolName = (size) => (
59
- // eslint-disable-next-line sonarjs/pseudo-random -- load-balancing pick across interchangeable instances, not a security decision
60
- `pool-${String(Math.floor(Math.random() * size))}`
61
- );
62
- const sleep = async (ms) => {
63
- if (ms <= 0) {
64
- return;
65
- }
66
- await new Promise((resolve) => {
67
- setTimeout(resolve, ms);
68
- });
69
- };
70
- const retryOnServerError = (response) => response.status >= 500;
71
- const poolHandleFor = (namespace, spec, options = {}, port) => {
72
- const size = options.size ?? spec.maxInstances ?? DEFAULT_POOL_SIZE;
73
- const attempts = Math.max(1, options.attempts ?? 3);
74
- const baseBackoff = options.backoffMs ?? 100;
75
- const maxBackoff = options.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
76
- const shouldRetry = options.retryOn ?? retryOnServerError;
77
- return {
78
- fetch: async (input, init) => {
79
- let lastError;
80
- for (let attempt = 0; attempt < attempts; attempt += 1) {
81
- if (attempt > 0) {
82
- await sleep(Math.min(baseBackoff * 2 ** (attempt - 1), maxBackoff));
83
- }
84
- const request = toRequest(input, init, port);
85
- try {
86
- const response = await namespace.get(namespace.idFromName(randomPoolName(size))).fetch(request);
87
- if (attempt === attempts - 1 || !shouldRetry(response)) {
88
- return response;
89
- }
90
- } catch (error) {
91
- lastError = error;
92
- }
93
- }
94
- throw lastError instanceof Error ? lastError : new Error(`ctx.containers.${spec.exportName}.pool(): all ${String(attempts)} attempts failed`);
95
- },
96
- port: (targetPort) => poolHandleFor(namespace, spec, options, targetPort)
97
- };
98
- };
99
- const accessorFor = (namespace, spec) => {
100
- return {
101
- any: (count) => handleFor(namespace, randomPoolName(count ?? spec.maxInstances ?? DEFAULT_POOL_SIZE)),
102
- get: (name) => instanceHandleFor(namespace, spec, name),
103
- pool: (options) => poolHandleFor(namespace, spec, options)
104
- };
105
- };
106
- const missingBindingAccessor = (spec) => {
107
- const fail = () => {
108
- throw new Error(
109
- `ctx.containers.${spec.exportName}: no "${spec.binding}" Durable Object binding found. Run \`lunora dev\` (or \`lunora deploy\`) to reconcile wrangler.jsonc, and make sure the worker entry re-exports the generated container classes.`
110
- );
111
- };
112
- return { any: fail, get: fail, pool: fail };
113
- };
114
- const createContainerContext = (env, specs, jurisdiction) => {
115
- const containers = {};
116
- for (const spec of specs) {
117
- const binding = env[spec.binding];
118
- containers[spec.exportName] = binding && typeof binding.idFromName === "function" && typeof binding.get === "function" ? accessorFor(applyJurisdiction(binding, jurisdiction), spec) : missingBindingAccessor(spec);
119
- }
120
- return containers;
121
- };
122
- const testNamespaceFor = (handler) => {
123
- const stubFor = (name) => {
124
- return {
125
- allowHost: () => Promise.resolve(),
126
- denyHost: () => Promise.resolve(),
127
- destroy: () => Promise.resolve(),
128
- fetch: (request) => Promise.resolve(handler(request, { name })),
129
- getState: () => Promise.resolve({ lastChange: 0 }),
130
- removeAllowedHost: () => Promise.resolve(),
131
- removeDeniedHost: () => Promise.resolve(),
132
- renewActivityTimeout: () => Promise.resolve(),
133
- setAllowedHosts: () => Promise.resolve(),
134
- setDeniedHosts: () => Promise.resolve(),
135
- start: () => Promise.resolve(),
136
- stop: () => Promise.resolve()
137
- };
138
- };
139
- return { get: (id) => stubFor(String(id)), idFromName: (name) => name };
140
- };
141
- const createContainerTestContext = (handlers) => {
142
- const containers = {};
143
- for (const [exportName, handler] of Object.entries(handlers)) {
144
- const namespace = testNamespaceFor(handler);
145
- const spec = { binding: `CONTAINER_${exportName.toUpperCase()}`};
146
- containers[exportName] = {
147
- // `.any()`/`.pool()` route to a fixed `pool-0` so the handler's
148
- // `instance.name` is deterministic under test; the double doesn't
149
- // simulate the random-pick or retry/backoff the real pool does.
150
- any: () => handleFor(namespace, "pool-0"),
151
- get: (name) => instanceHandleFor(namespace, spec, name),
152
- pool: () => handleFor(namespace, "pool-0")
153
- };
154
- }
155
- return containers;
156
- };
157
-
158
- export { createContainerContext, createContainerTestContext };
@@ -1,234 +0,0 @@
1
- /**
2
- * Public configuration types for `@lunora/container`.
3
- *
4
- * Everything in this module is pure data — no Cloudflare runtime imports — so
5
- * it is safe to import from Node tooling (codegen, the config layer) as well
6
- * as from worker code.
7
- */
8
- /** Named instance types Cloudflare Containers provides. */
9
- type NamedContainerInstanceType = "basic" | "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4";
10
- /**
11
- * A custom instance type. Cloudflare's bounds at the time of writing: up to
12
- * 4 vCPU, 12 GiB memory, 20 GB disk, ≥ 3 GiB memory per vCPU and ≤ 2 GB disk
13
- * per GiB memory. The config-layer validator enforces the documented ranges.
14
- */
15
- interface CustomContainerInstanceType {
16
- /** Disk in MB. Cloudflare's default is 2000 (2 GB). */
17
- diskMb?: number;
18
- /** Memory in MiB. Cloudflare's default is 256. */
19
- memoryMib?: number;
20
- /** vCPU count. Cloudflare's default is 0.0625 (1/16 vCPU). */
21
- vcpu?: number;
22
- }
23
- type ContainerInstanceType = CustomContainerInstanceType | NamedContainerInstanceType;
24
- /** Rolling-deploy tuning for a container. */
25
- interface ContainerRollout {
26
- /** Seconds an active instance runs before it's eligible for update (wrangler `rollout_active_grace_period`). */
27
- gracePeriodSeconds?: number;
28
- /** Percentage of instances updated per rollout step, 1–100 (wrangler `rollout_step_percentage`). */
29
- stepPercentage?: number;
30
- }
31
- /**
32
- * A pre-built image pulled from a registry — the Cloudflare Registry, Docker
33
- * Hub, or Amazon ECR (the registries `wrangler deploy` supports). The
34
- * reference must be fully qualified, e.g. `docker.io/acme/transcoder:1.4`.
35
- */
36
- interface RegistryImageSource {
37
- registry: string;
38
- }
39
- /**
40
- * A Dockerfile-less build via [Railpack](https://railpack.com): point at a
41
- * source directory and `lunora deploy` builds an OCI image with Railpack
42
- * (needs a BuildKit instance) and pushes it to the Cloudflare Registry before
43
- * wrangler runs. Opt-in — the Dockerfile path is the zero-extra-deps default.
44
- */
45
- interface BuildImageSource {
46
- build: string;
47
- }
48
- /**
49
- * Where the container image comes from. A `string` is a **local path** —
50
- * either a directory containing a `Dockerfile` (normalized to
51
- * `&lt;dir>/Dockerfile` with the directory as the build context) or a path to
52
- * the Dockerfile itself — while `{ registry }` is a pre-built image reference.
53
- */
54
- type ContainerImageSource = BuildImageSource | RegistryImageSource | string;
55
- /**
56
- * An application-level readiness probe that gates request proxying. Layered on
57
- * top of the platform's own port/`pingEndpoint` health wait, it lets you hold
58
- * traffic back until the app inside the container is *functionally* ready —
59
- * migrations applied, caches warmed — which an open-port check can't see.
60
- *
61
- * Declarative on purpose: a `defineContainer` value stays pure data (no handler
62
- * functions), so codegen and the config layer can read it without evaluating
63
- * code. (Upstream cloudflare/containers#188 expresses the same idea as handler
64
- * functions; the Lunora config is data-only, so it's modelled as descriptors.)
65
- */
66
- interface ContainerReadinessCheck {
67
- /** HTTP path probed on the container, e.g. `"/ready"` (a leading slash is optional). */
68
- path: string;
69
- /** Port to probe. Defaults to {@link ContainerConfig.defaultPort}. */
70
- port?: number;
71
- /** HTTP status that means "ready". Defaults to `200`. */
72
- status?: number;
73
- }
74
- interface ContainerConfig {
75
- /**
76
- * Hostnames the container may reach **even when {@link ContainerConfig.enableInternet}
77
- * is `false`** — an egress allow-list (Cloudflare's `allowedHosts`). Glob
78
- * patterns like `*.stripe.com` are supported. Pair with `enableInternet:
79
- * false` to deny all egress except these hosts (the firewall pattern
80
- * upstream issue cloudflare/containers#30 asked for). The interception path
81
- * needs the `ContainerProxy` worker entrypoint, which codegen re-exports
82
- * from the generated container file automatically; the named-instance
83
- * handle's `egress` controls adjust the lists at runtime.
84
- */
85
- allowedHosts?: ReadonlyArray<string>;
86
- /**
87
- * Build-time variables for a Dockerfile/Railpack image — wrangler's
88
- * `image_vars` (equivalent to `docker build --build-arg`). For *runtime*
89
- * values use {@link ContainerConfig.env} / {@link ContainerConfig.secrets}.
90
- * Ignored for a pre-built `{ registry }` image.
91
- */
92
- buildArgs?: Readonly<Record<string, string>>;
93
- /**
94
- * The port the container listens on. Worker → container requests target
95
- * this port. Locally the Dockerfile must also `EXPOSE` it. For a
96
- * multi-port container also declare {@link ContainerConfig.requiredPorts}
97
- * and route per request with the handle's `.port(n)`.
98
- */
99
- defaultPort?: number;
100
- /**
101
- * Hostnames the container may **never** reach — an egress deny-list
102
- * (Cloudflare's `deniedHosts`). Overrides everything else, including
103
- * `enableInternet: true` and {@link ContainerConfig.allowedHosts}. Glob
104
- * patterns like `*.evil.com` are supported.
105
- */
106
- deniedHosts?: ReadonlyArray<string>;
107
- /**
108
- * Whether the container may open outbound internet connections. Defaults
109
- * to `true` — the platform default. Note that container egress is billed
110
- * per GB by Cloudflare. Combine with {@link ContainerConfig.allowedHosts} /
111
- * {@link ContainerConfig.deniedHosts} for a precise egress firewall.
112
- */
113
- enableInternet?: boolean;
114
- /**
115
- * Default command to run inside the container, overriding the image's
116
- * `ENTRYPOINT`/`CMD` (Cloudflare's `entrypoint`). A per-start override is
117
- * still available via the named-instance handle's `start({ entrypoint })`.
118
- */
119
- entrypoint?: ReadonlyArray<string>;
120
- /**
121
- * Static environment variables passed to the container on every start.
122
- * For secret values use {@link ContainerConfig.secrets} instead so they
123
- * flow through Worker Secrets rather than source code.
124
- */
125
- env?: Readonly<Record<string, string>>;
126
- /**
127
- * Hard cap on how long an instance may run, measured from start regardless
128
- * of activity — a runaway-cost backstop on top of the idle
129
- * {@link ContainerConfig.sleepAfter}. Same grammar as `sleepAfter`
130
- * (`"30s"`, `"5m"`, `"1h"`, or a plain number of seconds). When it elapses,
131
- * the `LunoraContainer.onHardTimeoutExpired` hook runs (default: `stop()`).
132
- * (Upstream cloudflare/containers#85.)
133
- */
134
- hardTimeout?: number | string;
135
- /** Image source — a local Dockerfile path/directory or a registry reference. */
136
- image: ContainerImageSource;
137
- /**
138
- * Resource class for each instance: a named Cloudflare instance type or a
139
- * custom `{ vcpu, memoryMib, diskMb }` object.
140
- */
141
- instanceType?: ContainerInstanceType;
142
- /**
143
- * Intercept the container's outbound **HTTPS** traffic so the egress
144
- * allow/deny lists apply to TLS connections too (Cloudflare's
145
- * `interceptHttps`). Requires the image to trust the Cloudflare CA at
146
- * `/etc/cloudflare/certs/cloudflare-containers-ca.crt`. Defaults to `false`
147
- * (HTTP egress is gated regardless).
148
- */
149
- interceptHttps?: boolean;
150
- /**
151
- * Key-value metadata attached to every instance for metrics/observability
152
- * (Cloudflare's container `labels`), e.g. `{ tenant: "acme", env: "prod" }`.
153
- * A per-start override is available via the named-instance handle's
154
- * `start({ labels })`.
155
- */
156
- labels?: Readonly<Record<string, string>>;
157
- /**
158
- * Maximum number of concurrently *running* instances. Stopped (slept)
159
- * containers don't count. Also the default pool size for `.any()`.
160
- */
161
- maxInstances?: number;
162
- /**
163
- * Override for the wrangler `containers[].name` identifier. Defaults to
164
- * wrangler's own default (worker name + class name + environment).
165
- */
166
- name?: string;
167
- /**
168
- * HTTP path Cloudflare polls to decide an instance is healthy
169
- * (Cloudflare's `pingEndpoint`). Defaults to upstream's slash-less `"ping"`;
170
- * either `"ping"` or `"/healthz"`-style paths are accepted. Set this when
171
- * the container exposes its readiness check under a different route.
172
- */
173
- pingEndpoint?: string;
174
- /**
175
- * Application-level readiness probes that gate request proxying: a
176
- * `ctx.containers.&lt;name>` fetch waits until every probe responds with its
177
- * expected status before the request reaches the container — on top of the
178
- * platform's port/`pingEndpoint` health wait. All probes run in parallel.
179
- * Use these for readiness an open-port check can't see (migrations applied,
180
- * caches warm). (Upstream cloudflare/containers#188.)
181
- */
182
- readyOn?: ReadonlyArray<ContainerReadinessCheck>;
183
- /**
184
- * Ports the container must be listening on before it's considered ready
185
- * (Cloudflare's `requiredPorts`) — for multi-port containers. Start-up
186
- * waits for every listed port, and the handle's `.port(n)` routes a request
187
- * to any of them; {@link ContainerConfig.defaultPort} is the target when a
188
- * request doesn't pick one.
189
- */
190
- requiredPorts?: ReadonlyArray<number>;
191
- /**
192
- * Rolling-deploy tuning. `stepPercentage` is the share of instances updated
193
- * per rollout step (wrangler `rollout_step_percentage`); `gracePeriodSeconds`
194
- * is how long an active instance is left running before it's eligible for
195
- * update (wrangler `rollout_active_grace_period`).
196
- */
197
- rollout?: ContainerRollout;
198
- /**
199
- * Names of Worker secrets (from `wrangler secret` / `.dev.vars`) forwarded
200
- * into the container's environment at instance start. Each declared name
201
- * must exist on the Worker `env` — a missing one fails fast with a
202
- * directed error instead of starting the container without it.
203
- */
204
- secrets?: ReadonlyArray<string>;
205
- /**
206
- * Idle timeout after which the instance is put to sleep, e.g. `"5m"`,
207
- * `"30s"`, or a number of seconds. Cloudflare's default is `"10m"`.
208
- */
209
- sleepAfter?: number | string;
210
- }
211
- /**
212
- * The value `defineContainer` returns: the validated config plus a brand the
213
- * codegen discovery and the generated Container DO class key on.
214
- */
215
- interface ContainerDefinition extends ContainerConfig {
216
- /** Brand marking a value as a Lunora container definition. */
217
- readonly isLunoraContainer: true;
218
- }
219
- /** A normalized image source, as written into `wrangler.jsonc`. */
220
- type NormalizedContainerImage = {
221
- /** Build context directory (wrangler `image_build_context`). */
222
- buildContext: string;
223
- /** Path to the Dockerfile (wrangler `image`). */
224
- dockerfilePath: string;
225
- kind: "dockerfile";
226
- } | {
227
- /** Railpack source directory built + pushed at deploy time. */
228
- buildDir: string;
229
- kind: "build";
230
- } | {
231
- kind: "registry"; /** Fully-qualified image reference (wrangler `image`). */
232
- reference: string;
233
- };
234
- export { BuildImageSource as B, ContainerDefinition as C, NormalizedContainerImage as N, RegistryImageSource as R, ContainerConfig as a, ContainerImageSource as b, ContainerInstanceType as c, ContainerReadinessCheck as d, ContainerRollout as e, CustomContainerInstanceType as f, NamedContainerInstanceType as g };