@lunora/container 1.0.0-alpha.3 → 1.0.0-alpha.5

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,6 +1,17 @@
1
1
  const NAMED_INSTANCE_TYPES = /* @__PURE__ */ new Set(["basic", "lite", "standard-1", "standard-2", "standard-3", "standard-4"]);
2
2
  const ENV_NAME_PATTERN = /^[A-Z_]\w*$/i;
3
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
+ };
4
15
  const basename = (path) => {
5
16
  const trimmed = path.endsWith("/") ? path.slice(0, -1) : path;
6
17
  const separatorIndex = trimmed.lastIndexOf("/");
@@ -49,6 +60,19 @@ const assertValidImage = (image) => {
49
60
  throw new TypeError("defineContainer: `image.registry` must be a non-empty fully-qualified image reference");
50
61
  }
51
62
  };
63
+ const assertValidSecretsStore = (config, envNames, secretNames) => {
64
+ for (const [envName, binding] of Object.entries(config.secretsStore ?? {})) {
65
+ if (!ENV_NAME_PATTERN.test(envName)) {
66
+ throw new TypeError(`defineContainer: secretsStore env name "${envName}" is not a valid environment variable name`);
67
+ }
68
+ if (typeof binding !== "string" || binding.trim().length === 0) {
69
+ throw new TypeError(`defineContainer: \`secretsStore["${envName}"]\` must be a non-empty Secrets Store binding name`);
70
+ }
71
+ if (envNames.has(envName) || secretNames.has(envName)) {
72
+ throw new TypeError(`defineContainer: "${envName}" is declared in both \`secretsStore\` and \`env\`/\`secrets\` — pick one source for the value`);
73
+ }
74
+ }
75
+ };
52
76
  const assertValidEnvAndSecrets = (config) => {
53
77
  for (const name of Object.keys(config.env ?? {})) {
54
78
  if (!ENV_NAME_PATTERN.test(name)) {
@@ -61,6 +85,7 @@ const assertValidEnvAndSecrets = (config) => {
61
85
  }
62
86
  }
63
87
  const envNames = new Set(Object.keys(config.env ?? {}));
88
+ const secretNames = new Set(config.secrets);
64
89
  for (const secret of config.secrets ?? []) {
65
90
  if (!ENV_NAME_PATTERN.test(secret)) {
66
91
  throw new TypeError(`defineContainer: secret name "${secret}" is not a valid environment variable name`);
@@ -71,11 +96,83 @@ const assertValidEnvAndSecrets = (config) => {
71
96
  );
72
97
  }
73
98
  }
99
+ assertValidSecretsStore(config, envNames, secretNames);
100
+ };
101
+ const assertValidPort = (port, field) => {
102
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
103
+ throw new TypeError(`defineContainer: \`${field}\` must be an integer in 1–65535 (got ${String(port)})`);
104
+ }
105
+ };
106
+ const assertValidReadyOnChecks = (config) => {
107
+ for (const check of config.readyOn ?? []) {
108
+ if (typeof check.path !== "string" || check.path.trim().length === 0) {
109
+ throw new TypeError("defineContainer: `readyOn[].path` must be a non-empty HTTP path string");
110
+ }
111
+ if (check.path !== check.path.trim()) {
112
+ throw new TypeError("defineContainer: `readyOn[].path` must not have leading or trailing whitespace");
113
+ }
114
+ if (check.port !== void 0) {
115
+ assertValidPort(check.port, "readyOn[].port");
116
+ }
117
+ if (check.status !== void 0 && (!Number.isInteger(check.status) || check.status < 100 || check.status > 599)) {
118
+ throw new TypeError(`defineContainer: \`readyOn[].status\` must be an HTTP status code in 100–599 (got ${String(check.status)})`);
119
+ }
120
+ }
121
+ };
122
+ const assertValidHardTimeout = (hardTimeout) => {
123
+ if (hardTimeout === void 0) {
124
+ return;
125
+ }
126
+ if (typeof hardTimeout === "string") {
127
+ if (!SLEEP_AFTER_PATTERN.test(hardTimeout)) {
128
+ throw new TypeError(
129
+ `defineContainer: \`hardTimeout\` string "${hardTimeout}" must be a number of seconds followed by a unit, e.g. "30s", "5m", or "1h"`
130
+ );
131
+ }
132
+ } else if (!Number.isInteger(hardTimeout) || hardTimeout < 1) {
133
+ throw new TypeError(
134
+ `defineContainer: \`hardTimeout\` must be a positive integer number of seconds or a duration string like "5m" (got ${String(hardTimeout)})`
135
+ );
136
+ }
137
+ };
138
+ const assertValidEgressFields = (config) => {
139
+ for (const field of ["allowedHosts", "deniedHosts"]) {
140
+ const hosts = config[field];
141
+ if (hosts?.some((host) => typeof host !== "string" || host.trim().length === 0)) {
142
+ throw new TypeError(`defineContainer: \`${field}\` must be an array of non-empty hostname patterns`);
143
+ }
144
+ }
145
+ if (config.interceptHttps !== void 0 && typeof config.interceptHttps !== "boolean") {
146
+ throw new TypeError("defineContainer: `interceptHttps` must be a boolean, or omitted");
147
+ }
148
+ };
149
+ const assertValidContainerRuntimeFields = (config) => {
150
+ if (config.requiredPorts !== void 0) {
151
+ if (config.requiredPorts.length === 0) {
152
+ throw new TypeError("defineContainer: `requiredPorts` must be a non-empty array of ports, or omitted");
153
+ }
154
+ for (const port of config.requiredPorts) {
155
+ assertValidPort(port, "requiredPorts[]");
156
+ }
157
+ }
158
+ if (config.entrypoint !== void 0 && (config.entrypoint.length === 0 || config.entrypoint.some((part) => typeof part !== "string" || part.trim().length === 0))) {
159
+ throw new TypeError("defineContainer: `entrypoint` must be a non-empty array of non-empty strings, or omitted");
160
+ }
161
+ assertValidEgressFields(config);
162
+ if (config.pingEndpoint !== void 0 && (typeof config.pingEndpoint !== "string" || config.pingEndpoint.trim().length === 0)) {
163
+ throw new TypeError("defineContainer: `pingEndpoint` must be a non-empty path string");
164
+ }
165
+ for (const [key, value] of Object.entries(config.labels ?? {})) {
166
+ if (key.trim().length === 0 || typeof value !== "string") {
167
+ throw new TypeError("defineContainer: `labels` must be a record of non-empty keys to string values");
168
+ }
169
+ }
170
+ assertValidReadyOnChecks(config);
74
171
  };
75
172
  const defineContainer = (config) => {
76
173
  assertValidImage(config.image);
77
- if (config.defaultPort !== void 0 && (!Number.isInteger(config.defaultPort) || config.defaultPort < 1 || config.defaultPort > 65535)) {
78
- throw new TypeError(`defineContainer: \`defaultPort\` must be an integer in 1–65535 (got ${String(config.defaultPort)})`);
174
+ if (config.defaultPort !== void 0) {
175
+ assertValidPort(config.defaultPort, "defaultPort");
79
176
  }
80
177
  const stepPercentage = config.rollout?.stepPercentage;
81
178
  if (stepPercentage !== void 0 && (!Number.isInteger(stepPercentage) || stepPercentage < 1 || stepPercentage > 100)) {
@@ -94,7 +191,9 @@ const defineContainer = (config) => {
94
191
  `defineContainer: \`sleepAfter\` string "${config.sleepAfter}" must be a number of seconds followed by a unit, e.g. "30s", "5m", or "1h"`
95
192
  );
96
193
  }
194
+ assertValidHardTimeout(config.hardTimeout);
97
195
  assertValidEnvAndSecrets(config);
196
+ assertValidContainerRuntimeFields(config);
98
197
  return { ...config, isLunoraContainer: true };
99
198
  };
100
199
  const isContainerDefinition = (value) => typeof value === "object" && value !== null && value.isLunoraContainer === true;
@@ -113,4 +212,4 @@ const resolveContainerEnvVariables = (definition, workerEnv, exportName) => {
113
212
  return resolved;
114
213
  };
115
214
 
116
- export { containerBindingName, containerBuildTag, containerClassName, defineContainer, isContainerDefinition, normalizeContainerImage, resolveContainerEnvVariables as resolveContainerEnvVars };
215
+ export { containerBindingName, containerBuildTag, containerClassName, defineContainer, isContainerDefinition, normalizeContainerImage, parseDurationSeconds, resolveContainerEnvVariables as resolveContainerEnvVars };
@@ -0,0 +1,225 @@
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 DEFAULT_COLD_START_ATTEMPTS = 3;
15
+ const DEFAULT_COLD_START_BACKOFF_MS = 500;
16
+ const TARGET_PORT_HEADER = "cf-container-target-port";
17
+ const toRequest = (input, init, port) => {
18
+ const request = typeof input === "string" && input.startsWith("/") ? new Request(`http://container${input}`, init) : new Request(input, init);
19
+ if (port !== void 0) {
20
+ request.headers.set(TARGET_PORT_HEADER, String(port));
21
+ }
22
+ return request;
23
+ };
24
+ const sleep = async (ms) => {
25
+ if (ms <= 0) {
26
+ return;
27
+ }
28
+ await new Promise((resolve) => {
29
+ setTimeout(resolve, ms);
30
+ });
31
+ };
32
+ const COLD_START_ERROR_PATTERN = /no container instance|not listening|try again later|rate.?limit|provision/i;
33
+ const COLD_START_NO_INSTANCE_BODY = "no Container instance available";
34
+ const COLD_START_START_FAILURE_BODY = "Failed to start container:";
35
+ const COLD_START_SENTINEL_SCAN_BYTES = 1024;
36
+ const readBodyPrefix = async (response) => {
37
+ const stream = response.clone().body;
38
+ if (stream === null) {
39
+ return "";
40
+ }
41
+ const reader = stream.getReader();
42
+ const decoder = new TextDecoder();
43
+ let text = "";
44
+ try {
45
+ while (text.length < COLD_START_SENTINEL_SCAN_BYTES) {
46
+ const { done, value } = await reader.read();
47
+ if (done) {
48
+ break;
49
+ }
50
+ text += decoder.decode(value, { stream: true });
51
+ }
52
+ } finally {
53
+ await reader.cancel();
54
+ }
55
+ return text;
56
+ };
57
+ const isColdStartError = (error) => error instanceof Error && COLD_START_ERROR_PATTERN.test(error.message);
58
+ const isColdStartTransient = async (response) => {
59
+ if (response.status === 429) {
60
+ return true;
61
+ }
62
+ if (response.status !== 500 && response.status !== 503) {
63
+ return false;
64
+ }
65
+ try {
66
+ const body = await readBodyPrefix(response);
67
+ return body.includes(COLD_START_NO_INSTANCE_BODY) || body.startsWith(COLD_START_START_FAILURE_BODY);
68
+ } catch {
69
+ return false;
70
+ }
71
+ };
72
+ const coldStartRetryingHandle = (send, options = {}, port) => {
73
+ const attempts = Math.max(1, options.attempts ?? DEFAULT_COLD_START_ATTEMPTS);
74
+ const baseBackoff = options.backoffMs ?? DEFAULT_COLD_START_BACKOFF_MS;
75
+ const maxBackoff = options.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
76
+ return {
77
+ fetch: async (input, init) => {
78
+ const totalAttempts = typeof input === "string" ? attempts : 1;
79
+ let lastError;
80
+ for (let attempt = 0; attempt < totalAttempts; attempt += 1) {
81
+ const isLastAttempt = attempt === totalAttempts - 1;
82
+ if (attempt > 0) {
83
+ await sleep(Math.min(baseBackoff * 2 ** (attempt - 1), maxBackoff));
84
+ }
85
+ try {
86
+ const response = await send(toRequest(input, init, port));
87
+ if (isLastAttempt || !await isColdStartTransient(response)) {
88
+ return response;
89
+ }
90
+ } catch (error) {
91
+ lastError = error;
92
+ if (isLastAttempt || !isColdStartError(error)) {
93
+ throw error;
94
+ }
95
+ }
96
+ }
97
+ throw lastError instanceof Error ? lastError : new Error("ctx.containers: cold-start retry exhausted");
98
+ },
99
+ port: (targetPort) => coldStartRetryingHandle(send, options, targetPort)
100
+ };
101
+ };
102
+ const handleFor = (namespace, instanceName, options) => coldStartRetryingHandle(async (request) => namespace.get(namespace.idFromName(instanceName)).fetch(request), options);
103
+ const lifecycleCall = async (stub, method, binding, argument) => {
104
+ const rpc = stub[method];
105
+ if (typeof rpc !== "function") {
106
+ throw new TypeError(`ctx.containers: the "${binding}" container DO does not expose ${method}() — is @lunora/container/do up to date?`);
107
+ }
108
+ return rpc(argument);
109
+ };
110
+ const egressControlsFor = (stub, binding) => {
111
+ return {
112
+ allow: async (hostname) => lifecycleCall(stub(), "allowHost", binding, hostname),
113
+ deny: async (hostname) => lifecycleCall(stub(), "denyHost", binding, hostname),
114
+ removeAllowed: async (hostname) => lifecycleCall(stub(), "removeAllowedHost", binding, hostname),
115
+ removeDenied: async (hostname) => lifecycleCall(stub(), "removeDeniedHost", binding, hostname),
116
+ setAllowed: async (hosts) => lifecycleCall(stub(), "setAllowedHosts", binding, [...hosts]),
117
+ setDenied: async (hosts) => lifecycleCall(stub(), "setDeniedHosts", binding, [...hosts])
118
+ };
119
+ };
120
+ const instanceHandleFor = (namespace, spec, instanceName, options) => {
121
+ const stub = () => namespace.get(namespace.idFromName(instanceName));
122
+ return {
123
+ ...coldStartRetryingHandle(async (request) => stub().fetch(request), options),
124
+ destroy: async () => lifecycleCall(stub(), "destroy", spec.binding),
125
+ egress: egressControlsFor(stub, spec.binding),
126
+ getState: async () => lifecycleCall(stub(), "getState", spec.binding),
127
+ renewActivityTimeout: async () => lifecycleCall(stub(), "renewActivityTimeout", spec.binding),
128
+ start: async (startOptions) => lifecycleCall(stub(), "start", spec.binding, startOptions),
129
+ stop: async (signal) => lifecycleCall(stub(), "stop", spec.binding, signal)
130
+ };
131
+ };
132
+ const randomPoolName = (size) => (
133
+ // eslint-disable-next-line sonarjs/pseudo-random -- load-balancing pick across interchangeable instances, not a security decision
134
+ `pool-${String(Math.floor(Math.random() * size))}`
135
+ );
136
+ const retryOnServerError = (response) => response.status >= 500;
137
+ const poolHandleFor = (namespace, spec, options = {}, port) => {
138
+ const size = options.size ?? spec.maxInstances ?? DEFAULT_POOL_SIZE;
139
+ const attempts = Math.max(1, options.attempts ?? 3);
140
+ const baseBackoff = options.backoffMs ?? 100;
141
+ const maxBackoff = options.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
142
+ const shouldRetry = options.retryOn ?? retryOnServerError;
143
+ return {
144
+ fetch: async (input, init) => {
145
+ let lastError;
146
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
147
+ if (attempt > 0) {
148
+ await sleep(Math.min(baseBackoff * 2 ** (attempt - 1), maxBackoff));
149
+ }
150
+ const request = toRequest(input, init, port);
151
+ try {
152
+ const response = await namespace.get(namespace.idFromName(randomPoolName(size))).fetch(request);
153
+ if (attempt === attempts - 1 || !shouldRetry(response)) {
154
+ return response;
155
+ }
156
+ } catch (error) {
157
+ lastError = error;
158
+ }
159
+ }
160
+ throw lastError instanceof Error ? lastError : new Error(`ctx.containers.${spec.exportName}.pool(): all ${String(attempts)} attempts failed`);
161
+ },
162
+ port: (targetPort) => poolHandleFor(namespace, spec, options, targetPort)
163
+ };
164
+ };
165
+ const accessorFor = (namespace, spec) => {
166
+ return {
167
+ any: (count, options) => handleFor(namespace, randomPoolName(count ?? spec.maxInstances ?? DEFAULT_POOL_SIZE), options),
168
+ get: (name, options) => instanceHandleFor(namespace, spec, name, options),
169
+ pool: (options) => poolHandleFor(namespace, spec, options)
170
+ };
171
+ };
172
+ const missingBindingAccessor = (spec) => {
173
+ const fail = () => {
174
+ throw new Error(
175
+ `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.`
176
+ );
177
+ };
178
+ return { any: fail, get: fail, pool: fail };
179
+ };
180
+ const createContainerContext = (env, specs, jurisdiction) => {
181
+ const containers = {};
182
+ for (const spec of specs) {
183
+ const binding = env[spec.binding];
184
+ containers[spec.exportName] = binding && typeof binding.idFromName === "function" && typeof binding.get === "function" ? accessorFor(applyJurisdiction(binding, jurisdiction), spec) : missingBindingAccessor(spec);
185
+ }
186
+ return containers;
187
+ };
188
+ const testNamespaceFor = (handler) => {
189
+ const stubFor = (name) => {
190
+ return {
191
+ allowHost: () => Promise.resolve(),
192
+ denyHost: () => Promise.resolve(),
193
+ destroy: () => Promise.resolve(),
194
+ fetch: (request) => Promise.resolve(handler(request, { name })),
195
+ getState: () => Promise.resolve({ lastChange: 0 }),
196
+ removeAllowedHost: () => Promise.resolve(),
197
+ removeDeniedHost: () => Promise.resolve(),
198
+ renewActivityTimeout: () => Promise.resolve(),
199
+ setAllowedHosts: () => Promise.resolve(),
200
+ setDeniedHosts: () => Promise.resolve(),
201
+ start: () => Promise.resolve(),
202
+ stop: () => Promise.resolve()
203
+ };
204
+ };
205
+ return { get: (id) => stubFor(String(id)), idFromName: (name) => name };
206
+ };
207
+ const createContainerTestContext = (handlers) => {
208
+ const containers = {};
209
+ for (const [exportName, handler] of Object.entries(handlers)) {
210
+ const namespace = testNamespaceFor(handler);
211
+ const spec = { binding: `CONTAINER_${exportName.toUpperCase()}`};
212
+ containers[exportName] = {
213
+ // `.any()`/`.pool()` route to a fixed `pool-0` so the handler's
214
+ // `instance.name` is deterministic under test; the double doesn't
215
+ // simulate the random-pick or retry/backoff the real pool/cold-start
216
+ // path does (`attempts: 1` keeps a handler's own 5xx from looping).
217
+ any: () => handleFor(namespace, "pool-0", { attempts: 1 }),
218
+ get: (name) => instanceHandleFor(namespace, spec, name, { attempts: 1 }),
219
+ pool: () => handleFor(namespace, "pool-0", { attempts: 1 })
220
+ };
221
+ }
222
+ return containers;
223
+ };
224
+
225
+ export { createContainerContext, createContainerTestContext };
@@ -0,0 +1,250 @@
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
+ * Cloudflare **Secrets Store** secrets forwarded into the container's
207
+ * environment, as a map of *container env-var name → Worker Secrets Store
208
+ * binding name*. Each binding is resolved with its async `.get()` the first
209
+ * time the instance starts, then injected as that env var — e.g.
210
+ * `{ STRIPE_KEY: "STRIPE_SECRET" }` runs `env.STRIPE_SECRET.get()` and sets
211
+ * `STRIPE_KEY` inside the container. Unlike {@link ContainerConfig.secrets}
212
+ * (plain Worker text secrets), this pulls from a `secrets_store_secrets`
213
+ * binding. A name already used by `env`/`secrets` is rejected at authoring
214
+ * time; a missing binding or unreadable value fails the start. Applies
215
+ * to the default start (the `ctx.containers` proxy path and a bare
216
+ * `start()`); a per-instance `start({ envVars })` replaces the env set
217
+ * wholesale, as it does for `env`/`secrets`. (Upstream
218
+ * cloudflare/containers#96.)
219
+ */
220
+ secretsStore?: Readonly<Record<string, string>>;
221
+ /**
222
+ * Idle timeout after which the instance is put to sleep, e.g. `"5m"`,
223
+ * `"30s"`, or a number of seconds. Cloudflare's default is `"10m"`.
224
+ */
225
+ sleepAfter?: number | string;
226
+ }
227
+ /**
228
+ * The value `defineContainer` returns: the validated config plus a brand the
229
+ * codegen discovery and the generated Container DO class key on.
230
+ */
231
+ interface ContainerDefinition extends ContainerConfig {
232
+ /** Brand marking a value as a Lunora container definition. */
233
+ readonly isLunoraContainer: true;
234
+ }
235
+ /** A normalized image source, as written into `wrangler.jsonc`. */
236
+ type NormalizedContainerImage = {
237
+ /** Build context directory (wrangler `image_build_context`). */
238
+ buildContext: string;
239
+ /** Path to the Dockerfile (wrangler `image`). */
240
+ dockerfilePath: string;
241
+ kind: "dockerfile";
242
+ } | {
243
+ /** Railpack source directory built + pushed at deploy time. */
244
+ buildDir: string;
245
+ kind: "build";
246
+ } | {
247
+ kind: "registry"; /** Fully-qualified image reference (wrangler `image`). */
248
+ reference: string;
249
+ };
250
+ export { BuildImageSource as B, ContainerConfig as C, NormalizedContainerImage as N, RegistryImageSource as R, ContainerDefinition as a, ContainerImageSource as b, ContainerInstanceType as c, ContainerReadinessCheck as d, ContainerRollout as e, CustomContainerInstanceType as f, NamedContainerInstanceType as g };