@lunora/container 1.0.0-alpha.1 → 1.0.0-alpha.100

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.
Files changed (37) hide show
  1. package/LICENSE.md +26 -0
  2. package/README.md +118 -3
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/bridge.d.mts +60 -35
  5. package/dist/bridge.d.ts +60 -35
  6. package/dist/bridge.mjs +1 -76
  7. package/dist/do/index.d.mts +870 -32
  8. package/dist/do/index.d.ts +870 -32
  9. package/dist/do/index.mjs +1 -119
  10. package/dist/index.d.mts +634 -109
  11. package/dist/index.d.ts +634 -109
  12. package/dist/index.mjs +1 -2
  13. package/dist/otel.d.mts +217 -0
  14. package/dist/otel.d.ts +217 -0
  15. package/dist/otel.mjs +1 -0
  16. package/dist/packem_shared/CONTAINER_EXEC_PATH-7Hcd6-zs.mjs +1 -0
  17. package/dist/packem_shared/CUSTOM_INSTANCE_MIN_MEMORY_MIB_PER_VCPU-D8Hy9Rxv.mjs +1 -0
  18. package/dist/packem_shared/ContainerProxy-CfXjS6ZI.mjs +27 -0
  19. package/dist/packem_shared/DURABLE_OBJECT_POLICY_FORBIDDEN_KEYS-gYi8RBUO.mjs +1 -0
  20. package/dist/packem_shared/LunoraSandboxContainer-DPnhJUu1.mjs +1 -0
  21. package/dist/packem_shared/abort-deadline-jwbW9Ala.mjs +1 -0
  22. package/dist/packem_shared/createContainerContext-p6QxWjsm.mjs +1 -0
  23. package/dist/packem_shared/exec-BYLW70sR.mjs +1 -0
  24. package/dist/packem_shared/jurisdiction-DtE9s70w.mjs +1 -0
  25. package/dist/packem_shared/jurisdiction.d-BwpauCoI.d.mts +471 -0
  26. package/dist/packem_shared/jurisdiction.d-BwpauCoI.d.ts +471 -0
  27. package/dist/packem_shared/sampling-D21rpu_s.mjs +1 -0
  28. package/dist/packem_shared/sandbox-types.d-DXlHnsEg.d.mts +110 -0
  29. package/dist/packem_shared/sandbox-types.d-DXlHnsEg.d.ts +110 -0
  30. package/dist/sandbox/index.d.mts +66 -0
  31. package/dist/sandbox/index.d.ts +66 -0
  32. package/dist/sandbox/index.mjs +1 -0
  33. package/package.json +13 -3
  34. package/dist/packem_shared/containerBindingName-BGdSdFNA.mjs +0 -116
  35. package/dist/packem_shared/createContainerContext-ChDD53ys.mjs +0 -122
  36. package/dist/packem_shared/types.d-D2l2SYol.d.mts +0 -140
  37. package/dist/packem_shared/types.d-D2l2SYol.d.ts +0 -140
@@ -0,0 +1,110 @@
1
+ import { SandboxDirectoryEntry, SandboxFileStat, DirectoryBackupRecord, S3MountInspection } from '@cloudflare/sandbox';
2
+ /** Options every file operation accepts. */
3
+ interface ContainerFileOptions {
4
+ /** Absolute directory a relative path is joined onto. */
5
+ cwd?: string;
6
+ /** Numeric `uid:gid` that opens the file. */
7
+ user?: string;
8
+ }
9
+ /** What `handle.files.writeFile` accepts. A stream is written as it arrives. */
10
+ type ContainerFileContent = ArrayBuffer | ArrayBufferView | ReadableStream<Uint8Array> | string;
11
+ /**
12
+ * Structured file operations on the instance's own disk (`handle.files`),
13
+ * through `@cloudflare/sandbox`'s `Files`. A filesystem failure rejects with a
14
+ * `LunoraError` whose `data.errno` is the Linux code (`ENOENT`, `EACCES`, …).
15
+ */
16
+ interface ContainerFiles {
17
+ /** Create a directory; `recursive` creates parents and accepts an existing one. */
18
+ mkdir: (path: string, options?: ContainerFileOptions & {
19
+ recursive?: boolean;
20
+ }) => Promise<void>;
21
+ /** List a directory's immediate entries, without following symlinked entries. */
22
+ readDirectory: (path: string, options?: ContainerFileOptions) => Promise<SandboxDirectoryEntry[]>;
23
+ /**
24
+ * Stream a file out of the container. The body applies backpressure to the
25
+ * read. Read the body to the end or cancel it: the container is counted in
26
+ * flight until then, so an abandoned body keeps it from sleeping.
27
+ */
28
+ readFile: (path: string, options?: ContainerFileOptions) => Promise<Response>;
29
+ /** Remove a file or symlink; `recursive` removes a directory tree, `force` ignores a missing target. */
30
+ remove: (path: string, options?: ContainerFileOptions & {
31
+ force?: boolean;
32
+ recursive?: boolean;
33
+ }) => Promise<void>;
34
+ /** Rename within one filesystem (`EXDEV` across filesystems; there is no copy fallback). */
35
+ rename: (source: string, destination: string, options?: ContainerFileOptions) => Promise<void>;
36
+ /** Metadata for a path, following a final symlink. */
37
+ stat: (path: string, options?: ContainerFileOptions) => Promise<SandboxFileStat>;
38
+ /** Create or truncate a file and write `content` into it. */
39
+ writeFile: (path: string, content: ContainerFileContent, options?: ContainerFileOptions) => Promise<void>;
40
+ }
41
+ /** Options for `handle.backup()`. */
42
+ interface ContainerBackupOptions {
43
+ /** gitignore-syntax patterns, relative to the directory, to leave out. */
44
+ exclude?: ReadonlyArray<string>;
45
+ /** Also apply `.gitignore` files inside the directory and `.git/info/exclude`. */
46
+ gitignore?: boolean;
47
+ /** A label stored with the backup. */
48
+ name?: string;
49
+ }
50
+ /**
51
+ * Credentials for an S3-compatible bucket mount, by **name**: each value is the
52
+ * name of a Worker secret (`wrangler secret put`) the container Durable Object
53
+ * reads at mount time. The keys themselves never appear in source, and the
54
+ * Worker signs every storage request, so they never enter the container either.
55
+ */
56
+ interface ContainerMountCredentials {
57
+ /** Worker secret holding the access key id. */
58
+ accessKeyIdSecret: string;
59
+ /** Worker secret holding the secret access key. */
60
+ secretAccessKeySecret: string;
61
+ /** Worker secret holding a session token, for temporary credentials. */
62
+ sessionTokenSecret?: string;
63
+ }
64
+ /**
65
+ * An S3-compatible bucket (R2, S3, GCS) to mount at `path` with
66
+ * `handle.mount()`. For R2 the endpoint is
67
+ * `https://<account-id>.r2.cloudflarestorage.com` with region `"auto"`, and the
68
+ * credentials are an R2 API token's S3 keys — an R2 bucket binding is not used.
69
+ */
70
+ interface ContainerMountRequest {
71
+ access: "read-only" | "read-write";
72
+ bucket: string;
73
+ credentials: ContainerMountCredentials;
74
+ endpoint: string;
75
+ /** Mount only this key prefix. A non-empty prefix ends in `/`. */
76
+ keyPrefix?: string;
77
+ /** Absolute path inside the container to mount at. */
78
+ path: string;
79
+ region: string;
80
+ /** Extra s3fs options, passed through as-is. */
81
+ s3fsOptions?: Readonly<Record<string, boolean | number | string>>;
82
+ }
83
+ /** The sandbox operations on a named instance of a `defineContainer({ sandbox: true })` container. */
84
+ interface ContainerSandboxControls {
85
+ /**
86
+ * Save `directory` to the R2 bucket in the definition's `backups` and return its
87
+ * record — plain data to store and pass to `restore` later, here or on
88
+ * another instance, even one on a newer image. Pause writers in it first.
89
+ */
90
+ backup: (directory: string, options?: ContainerBackupOptions) => Promise<DirectoryBackupRecord>;
91
+ /** Delete a backup's object. Deleting one that is already gone succeeds. */
92
+ deleteBackup: (backup: DirectoryBackupRecord) => Promise<void>;
93
+ /** Structured file operations on the instance's disk. */
94
+ files: ContainerFiles;
95
+ /** Report a mount path's state without changing it. */
96
+ inspectMount: (path: string) => Promise<S3MountInspection>;
97
+ /** Mount an S3-compatible bucket at `request.path`. Mounting the same settings again reuses the mount. */
98
+ mount: (request: ContainerMountRequest) => Promise<void>;
99
+ /**
100
+ * Replace `options.directory` (default: the directory it was taken from) with the
101
+ * backup's contents. The target is swapped in only after the download is
102
+ * verified; a rejection means it was not replaced.
103
+ */
104
+ restore: (backup: DirectoryBackupRecord, options?: {
105
+ directory?: string;
106
+ }) => Promise<void>;
107
+ /** Stop access to a mount and unmount it. Never force-unmounts a busy path. */
108
+ unmount: (path: string) => Promise<void>;
109
+ }
110
+ export { ContainerFileOptions as C, ContainerFileContent as a, ContainerBackupOptions as b, ContainerMountRequest as c, ContainerSandboxControls as d, ContainerFiles as e, ContainerMountCredentials as f };
@@ -0,0 +1,66 @@
1
+ import { SandboxFileStat, SandboxDirectoryEntry, DirectoryBackupRecord, S3MountInspection } from '@cloudflare/sandbox';
2
+ export { DirectoryBackupGateway, S3Gateway } from '@cloudflare/sandbox';
3
+ import { LunoraContainer } from "../do/index.mjs";
4
+ import { C as ContainerFileOptions, a as ContainerFileContent, b as ContainerBackupOptions, c as ContainerMountRequest } from "../packem_shared/sandbox-types.d-DXlHnsEg.mjs";
5
+ import { C as ContainerDefinition } from "../packem_shared/jurisdiction.d-BwpauCoI.mjs";
6
+ import 'cloudflare:workers';
7
+ type DurableObjectContext = ConstructorParameters<typeof LunoraContainer>[0];
8
+ declare class LunoraSandboxContainer<Env = unknown> extends LunoraContainer<Env> {
9
+ #private;
10
+ constructor(context: DurableObjectContext, env: Env, definition: ContainerDefinition, exportName?: string, jurisdiction?: ConstructorParameters<typeof LunoraContainer>[4]);
11
+ lunoraReadFile(path: string, options?: ContainerFileOptions): Promise<Response>;
12
+ lunoraWriteFile(path: string, content: ContainerFileContent, options?: ContainerFileOptions): Promise<void>;
13
+ lunoraStat(path: string, options?: ContainerFileOptions): Promise<SandboxFileStat>;
14
+ lunoraReadDirectory(path: string, options?: ContainerFileOptions): Promise<SandboxDirectoryEntry[]>;
15
+ lunoraMkdir(path: string, options?: ContainerFileOptions & {
16
+ recursive?: boolean;
17
+ }): Promise<void>;
18
+ lunoraRename(source: string, destination: string, options?: ContainerFileOptions): Promise<void>;
19
+ lunoraRemove(path: string, options?: ContainerFileOptions & {
20
+ force?: boolean;
21
+ recursive?: boolean;
22
+ }): Promise<void>;
23
+ lunoraBackup(directory: string, options?: ContainerBackupOptions): Promise<DirectoryBackupRecord>;
24
+ lunoraRestore(backup: DirectoryBackupRecord, options?: {
25
+ directory?: string;
26
+ }): Promise<void>;
27
+ /** Needs no running container — it only deletes the object. */
28
+ lunoraDeleteBackup(backup: DirectoryBackupRecord): Promise<void>;
29
+ lunoraMount(request: ContainerMountRequest): Promise<void>;
30
+ lunoraInspectMount(path: string): Promise<S3MountInspection>;
31
+ lunoraUnmount(path: string): Promise<void>;
32
+ /**
33
+ * Route backup traffic to its gateway before the base installs the egress
34
+ * policy's catch-all, which takes every hostname registered after it.
35
+ * Without an egress policy there is no catch-all, and each backup or
36
+ * restore registers its own route when it runs.
37
+ */
38
+ protected override beforeContainerStart(): Promise<void>;
39
+ /** Run one helper operation on the running container, translating sandbox errors. */
40
+ private withContainer;
41
+ private files;
42
+ /** One `DirectoryBackup` per instance: it runs one operation at a time per container, which only holds if every call shares it. */
43
+ private backups;
44
+ private mounts;
45
+ /** A Worker entrypoint from `ctx.exports`, with the fix when the worker does not export it. */
46
+ private workerExport;
47
+ /** Resolve a mount's credentials from the Worker secrets they name. */
48
+ private mountCredentials;
49
+ private label;
50
+ }
51
+ export {
52
+ /**
53
+ * `@lunora/container/sandbox` — the workerd-only half of the Sandbox SDK
54
+ * helpers (`@cloudflare/sandbox`) a `defineContainer({ sandbox: true })`
55
+ * container uses. A separate subpath from `/do`, so an app that never opts in
56
+ * never loads `@cloudflare/sandbox` (or the `zod` it depends on).
57
+ *
58
+ * `LunoraSandboxContainer` is the base class codegen extends for a `sandbox:
59
+ * true` container: `LunoraContainer` plus the file, backup and bucket-mount
60
+ * RPCs the named-instance handle calls. `DirectoryBackupGateway` and
61
+ * `S3Gateway` are the `WorkerEntrypoint`s the backup and mount helpers route
62
+ * the container's storage traffic through (reached as `ctx.exports.<Name>`),
63
+ * so the deployed worker must export both; the generated
64
+ * `_generated/containers.ts` re-exports them from here.
65
+ */
66
+ LunoraSandboxContainer };
@@ -0,0 +1,66 @@
1
+ import { SandboxFileStat, SandboxDirectoryEntry, DirectoryBackupRecord, S3MountInspection } from '@cloudflare/sandbox';
2
+ export { DirectoryBackupGateway, S3Gateway } from '@cloudflare/sandbox';
3
+ import { LunoraContainer } from "../do/index.js";
4
+ import { C as ContainerFileOptions, a as ContainerFileContent, b as ContainerBackupOptions, c as ContainerMountRequest } from "../packem_shared/sandbox-types.d-DXlHnsEg.js";
5
+ import { C as ContainerDefinition } from "../packem_shared/jurisdiction.d-BwpauCoI.js";
6
+ import 'cloudflare:workers';
7
+ type DurableObjectContext = ConstructorParameters<typeof LunoraContainer>[0];
8
+ declare class LunoraSandboxContainer<Env = unknown> extends LunoraContainer<Env> {
9
+ #private;
10
+ constructor(context: DurableObjectContext, env: Env, definition: ContainerDefinition, exportName?: string, jurisdiction?: ConstructorParameters<typeof LunoraContainer>[4]);
11
+ lunoraReadFile(path: string, options?: ContainerFileOptions): Promise<Response>;
12
+ lunoraWriteFile(path: string, content: ContainerFileContent, options?: ContainerFileOptions): Promise<void>;
13
+ lunoraStat(path: string, options?: ContainerFileOptions): Promise<SandboxFileStat>;
14
+ lunoraReadDirectory(path: string, options?: ContainerFileOptions): Promise<SandboxDirectoryEntry[]>;
15
+ lunoraMkdir(path: string, options?: ContainerFileOptions & {
16
+ recursive?: boolean;
17
+ }): Promise<void>;
18
+ lunoraRename(source: string, destination: string, options?: ContainerFileOptions): Promise<void>;
19
+ lunoraRemove(path: string, options?: ContainerFileOptions & {
20
+ force?: boolean;
21
+ recursive?: boolean;
22
+ }): Promise<void>;
23
+ lunoraBackup(directory: string, options?: ContainerBackupOptions): Promise<DirectoryBackupRecord>;
24
+ lunoraRestore(backup: DirectoryBackupRecord, options?: {
25
+ directory?: string;
26
+ }): Promise<void>;
27
+ /** Needs no running container — it only deletes the object. */
28
+ lunoraDeleteBackup(backup: DirectoryBackupRecord): Promise<void>;
29
+ lunoraMount(request: ContainerMountRequest): Promise<void>;
30
+ lunoraInspectMount(path: string): Promise<S3MountInspection>;
31
+ lunoraUnmount(path: string): Promise<void>;
32
+ /**
33
+ * Route backup traffic to its gateway before the base installs the egress
34
+ * policy's catch-all, which takes every hostname registered after it.
35
+ * Without an egress policy there is no catch-all, and each backup or
36
+ * restore registers its own route when it runs.
37
+ */
38
+ protected override beforeContainerStart(): Promise<void>;
39
+ /** Run one helper operation on the running container, translating sandbox errors. */
40
+ private withContainer;
41
+ private files;
42
+ /** One `DirectoryBackup` per instance: it runs one operation at a time per container, which only holds if every call shares it. */
43
+ private backups;
44
+ private mounts;
45
+ /** A Worker entrypoint from `ctx.exports`, with the fix when the worker does not export it. */
46
+ private workerExport;
47
+ /** Resolve a mount's credentials from the Worker secrets they name. */
48
+ private mountCredentials;
49
+ private label;
50
+ }
51
+ export {
52
+ /**
53
+ * `@lunora/container/sandbox` — the workerd-only half of the Sandbox SDK
54
+ * helpers (`@cloudflare/sandbox`) a `defineContainer({ sandbox: true })`
55
+ * container uses. A separate subpath from `/do`, so an app that never opts in
56
+ * never loads `@cloudflare/sandbox` (or the `zod` it depends on).
57
+ *
58
+ * `LunoraSandboxContainer` is the base class codegen extends for a `sandbox:
59
+ * true` container: `LunoraContainer` plus the file, backup and bucket-mount
60
+ * RPCs the named-instance handle calls. `DirectoryBackupGateway` and
61
+ * `S3Gateway` are the `WorkerEntrypoint`s the backup and mount helpers route
62
+ * the container's storage traffic through (reached as `ctx.exports.<Name>`),
63
+ * so the deployed worker must export both; the generated
64
+ * `_generated/containers.ts` re-exports them from here.
65
+ */
66
+ LunoraSandboxContainer };
@@ -0,0 +1 @@
1
+ import{default as r}from"../packem_shared/LunoraSandboxContainer-DPnhJUu1.mjs";import{DirectoryBackupGateway as t,S3Gateway as n}from"@cloudflare/sandbox";export{t as DirectoryBackupGateway,r as LunoraSandboxContainer,n as S3Gateway};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/container",
3
- "version": "1.0.0-alpha.1",
3
+ "version": "1.0.0-alpha.100",
4
4
  "description": "Cloudflare Containers for Lunora: defineContainer, generated Container DO classes, and the ctx.containers action surface",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -23,7 +23,7 @@
23
23
  "directory": "packages/container"
24
24
  },
25
25
  "files": [
26
- "dist",
26
+ "./dist",
27
27
  "README.md",
28
28
  "LICENSE.md",
29
29
  "__assets__"
@@ -46,13 +46,23 @@
46
46
  "types": "./dist/bridge.d.ts",
47
47
  "import": "./dist/bridge.mjs"
48
48
  },
49
+ "./otel": {
50
+ "types": "./dist/otel.d.ts",
51
+ "import": "./dist/otel.mjs"
52
+ },
53
+ "./sandbox": {
54
+ "types": "./dist/sandbox/index.d.ts",
55
+ "import": "./dist/sandbox/index.mjs"
56
+ },
49
57
  "./package.json": "./package.json"
50
58
  },
51
59
  "publishConfig": {
52
60
  "access": "public"
53
61
  },
54
62
  "dependencies": {
55
- "@cloudflare/containers": "^0.3.7"
63
+ "@cloudflare/sandbox": "1.0.0",
64
+ "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
65
+ "@lunora/wire": "1.0.0-alpha.5"
56
66
  },
57
67
  "engines": {
58
68
  "node": "^22.15.0 || >=24.11.0"
@@ -1,116 +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 basename = (path) => {
5
- const trimmed = path.endsWith("/") ? path.slice(0, -1) : path;
6
- const separatorIndex = trimmed.lastIndexOf("/");
7
- return separatorIndex === -1 ? trimmed : trimmed.slice(separatorIndex + 1);
8
- };
9
- const dirname = (path) => {
10
- const separatorIndex = path.lastIndexOf("/");
11
- return separatorIndex === -1 ? "." : path.slice(0, separatorIndex) || "/";
12
- };
13
- const normalizeContainerImage = (image) => {
14
- if (typeof image !== "string") {
15
- if ("build" in image) {
16
- const buildDirectory = image.build.endsWith("/") ? image.build.slice(0, -1) : image.build;
17
- return { buildDir: buildDirectory, kind: "build" };
18
- }
19
- return { kind: "registry", reference: image.registry };
20
- }
21
- if (basename(image).startsWith("Dockerfile")) {
22
- return { buildContext: dirname(image), dockerfilePath: image, kind: "dockerfile" };
23
- }
24
- const context = image.endsWith("/") ? image.slice(0, -1) : image;
25
- return { buildContext: context, dockerfilePath: `${context}/Dockerfile`, kind: "dockerfile" };
26
- };
27
- const containerClassName = (exportName) => `${exportName.charAt(0).toUpperCase()}${exportName.slice(1)}Container`;
28
- const containerBindingName = (exportName) => `CONTAINER_${exportName.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g, "_").toUpperCase()}`;
29
- const containerBuildTag = (exportName) => `lunora-${exportName.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g, "-").toLowerCase()}:build`;
30
- const assertValidImage = (image) => {
31
- if (typeof image === "string") {
32
- if (image.length === 0) {
33
- throw new TypeError("defineContainer: `image` must be a non-empty path or a { registry } reference");
34
- }
35
- if (image.includes(":")) {
36
- throw new TypeError(
37
- `defineContainer: \`image\` string "${image}" looks like a registry reference — pass it as { registry: "${image}" } instead. Plain strings are local Dockerfile paths.`
38
- );
39
- }
40
- return;
41
- }
42
- if ("build" in image) {
43
- if (typeof image.build !== "string" || image.build.length === 0) {
44
- throw new TypeError("defineContainer: `image.build` must be a non-empty source directory for Railpack to build");
45
- }
46
- return;
47
- }
48
- if (typeof image.registry !== "string" || image.registry.length === 0) {
49
- throw new TypeError("defineContainer: `image.registry` must be a non-empty fully-qualified image reference");
50
- }
51
- };
52
- const assertValidEnvAndSecrets = (config) => {
53
- for (const name of Object.keys(config.env ?? {})) {
54
- if (!ENV_NAME_PATTERN.test(name)) {
55
- throw new TypeError(`defineContainer: env variable name "${name}" is not a valid environment variable name`);
56
- }
57
- }
58
- for (const name of Object.keys(config.buildArgs ?? {})) {
59
- if (!ENV_NAME_PATTERN.test(name)) {
60
- throw new TypeError(`defineContainer: buildArg name "${name}" is not a valid environment variable name`);
61
- }
62
- }
63
- const envNames = new Set(Object.keys(config.env ?? {}));
64
- for (const secret of config.secrets ?? []) {
65
- if (!ENV_NAME_PATTERN.test(secret)) {
66
- throw new TypeError(`defineContainer: secret name "${secret}" is not a valid environment variable name`);
67
- }
68
- if (envNames.has(secret)) {
69
- throw new TypeError(
70
- `defineContainer: "${secret}" is declared in both \`env\` and \`secrets\` — a secret would silently overwrite the static env value; pick one`
71
- );
72
- }
73
- }
74
- };
75
- const defineContainer = (config) => {
76
- 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)})`);
79
- }
80
- const stepPercentage = config.rollout?.stepPercentage;
81
- if (stepPercentage !== void 0 && (!Number.isInteger(stepPercentage) || stepPercentage < 1 || stepPercentage > 100)) {
82
- throw new TypeError(`defineContainer: \`rollout.stepPercentage\` must be an integer in 1–100 (got ${String(stepPercentage)})`);
83
- }
84
- if (config.maxInstances !== void 0 && (!Number.isInteger(config.maxInstances) || config.maxInstances < 1)) {
85
- throw new TypeError(`defineContainer: \`maxInstances\` must be a positive integer (got ${String(config.maxInstances)})`);
86
- }
87
- if (typeof config.instanceType === "string" && !NAMED_INSTANCE_TYPES.has(config.instanceType)) {
88
- throw new TypeError(
89
- `defineContainer: unknown \`instanceType\` "${config.instanceType}" — use one of ${[...NAMED_INSTANCE_TYPES].join(", ")}, or a custom { vcpu, memoryMib, diskMb } object`
90
- );
91
- }
92
- if (typeof config.sleepAfter === "string" && !SLEEP_AFTER_PATTERN.test(config.sleepAfter)) {
93
- throw new TypeError(
94
- `defineContainer: \`sleepAfter\` string "${config.sleepAfter}" must be a number of seconds followed by a unit, e.g. "30s", "5m", or "1h"`
95
- );
96
- }
97
- assertValidEnvAndSecrets(config);
98
- return { ...config, isLunoraContainer: true };
99
- };
100
- const isContainerDefinition = (value) => typeof value === "object" && value !== null && value.isLunoraContainer === true;
101
- const resolveContainerEnvVariables = (definition, workerEnv, exportName) => {
102
- const resolved = { ...definition.env };
103
- for (const secret of definition.secrets ?? []) {
104
- const value = workerEnv[secret];
105
- if (typeof value !== "string") {
106
- const label = exportName === void 0 ? "container" : `container "${exportName}"`;
107
- throw new Error(
108
- `${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.`
109
- );
110
- }
111
- resolved[secret] = value;
112
- }
113
- return resolved;
114
- };
115
-
116
- export { containerBindingName, containerBuildTag, containerClassName, defineContainer, isContainerDefinition, normalizeContainerImage, resolveContainerEnvVariables as resolveContainerEnvVars };
@@ -1,122 +0,0 @@
1
- const DEFAULT_POOL_SIZE = 3;
2
- const DEFAULT_MAX_BACKOFF_MS = 3e4;
3
- const toRequest = (input, init) => {
4
- if (typeof input === "string" && input.startsWith("/")) {
5
- return new Request(`http://container${input}`, init);
6
- }
7
- return new Request(input, init);
8
- };
9
- const handleFor = (namespace, instanceName) => {
10
- return {
11
- fetch: async (input, init) => namespace.get(namespace.idFromName(instanceName)).fetch(toRequest(input, init))
12
- };
13
- };
14
- const lifecycleCall = async (stub, method, binding, argument) => {
15
- const rpc = stub[method];
16
- if (typeof rpc !== "function") {
17
- throw new TypeError(`ctx.containers: the "${binding}" container DO does not expose ${method}() — is @lunora/container/do up to date?`);
18
- }
19
- return rpc(argument);
20
- };
21
- const instanceHandleFor = (namespace, spec, instanceName) => {
22
- const stub = () => namespace.get(namespace.idFromName(instanceName));
23
- return {
24
- destroy: async () => lifecycleCall(stub(), "destroy", spec.binding),
25
- fetch: async (input, init) => stub().fetch(toRequest(input, init)),
26
- getState: async () => lifecycleCall(stub(), "getState", spec.binding),
27
- start: async (options) => lifecycleCall(stub(), "start", spec.binding, options),
28
- stop: async (signal) => lifecycleCall(stub(), "stop", spec.binding, signal)
29
- };
30
- };
31
- const randomPoolName = (size) => (
32
- // eslint-disable-next-line sonarjs/pseudo-random -- load-balancing pick across interchangeable instances, not a security decision
33
- `pool-${String(Math.floor(Math.random() * size))}`
34
- );
35
- const sleep = async (ms) => {
36
- if (ms <= 0) {
37
- return;
38
- }
39
- await new Promise((resolve) => {
40
- setTimeout(resolve, ms);
41
- });
42
- };
43
- const retryOnServerError = (response) => response.status >= 500;
44
- const poolHandleFor = (namespace, spec, options = {}) => {
45
- const size = options.size ?? spec.maxInstances ?? DEFAULT_POOL_SIZE;
46
- const attempts = Math.max(1, options.attempts ?? 3);
47
- const baseBackoff = options.backoffMs ?? 100;
48
- const maxBackoff = options.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
49
- const shouldRetry = options.retryOn ?? retryOnServerError;
50
- return {
51
- fetch: async (input, init) => {
52
- let lastError;
53
- for (let attempt = 0; attempt < attempts; attempt += 1) {
54
- if (attempt > 0) {
55
- await sleep(Math.min(baseBackoff * 2 ** (attempt - 1), maxBackoff));
56
- }
57
- const request = toRequest(input, init);
58
- try {
59
- const response = await namespace.get(namespace.idFromName(randomPoolName(size))).fetch(request);
60
- if (attempt === attempts - 1 || !shouldRetry(response)) {
61
- return response;
62
- }
63
- } catch (error) {
64
- lastError = error;
65
- }
66
- }
67
- throw lastError instanceof Error ? lastError : new Error(`ctx.containers.${spec.exportName}.pool(): all ${String(attempts)} attempts failed`);
68
- }
69
- };
70
- };
71
- const accessorFor = (namespace, spec) => {
72
- return {
73
- any: (count) => handleFor(namespace, randomPoolName(count ?? spec.maxInstances ?? DEFAULT_POOL_SIZE)),
74
- get: (name) => instanceHandleFor(namespace, spec, name),
75
- pool: (options) => poolHandleFor(namespace, spec, options)
76
- };
77
- };
78
- const missingBindingAccessor = (spec) => {
79
- const fail = () => {
80
- throw new Error(
81
- `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.`
82
- );
83
- };
84
- return { any: fail, get: fail, pool: fail };
85
- };
86
- const createContainerContext = (env, specs) => {
87
- const containers = {};
88
- for (const spec of specs) {
89
- const namespace = env[spec.binding];
90
- containers[spec.exportName] = namespace && typeof namespace.idFromName === "function" && typeof namespace.get === "function" ? accessorFor(namespace, spec) : missingBindingAccessor(spec);
91
- }
92
- return containers;
93
- };
94
- const createContainerTestContext = (handlers) => {
95
- const containers = {};
96
- for (const [exportName, handler] of Object.entries(handlers)) {
97
- const testHandleFor = (instanceName) => {
98
- return {
99
- fetch: async (input, init) => handler(toRequest(input, init), { name: instanceName })
100
- };
101
- };
102
- const testInstanceHandleFor = (instanceName) => {
103
- return {
104
- ...testHandleFor(instanceName),
105
- destroy: () => Promise.resolve(),
106
- getState: () => Promise.resolve({ lastChange: 0 }),
107
- start: () => Promise.resolve(),
108
- stop: () => Promise.resolve()
109
- };
110
- };
111
- containers[exportName] = {
112
- any: () => testHandleFor("pool-0"),
113
- get: (name) => testInstanceHandleFor(name),
114
- // The double doesn't simulate failure/retry — pool() just routes to
115
- // the handler like any other call, so tests stay deterministic.
116
- pool: () => testHandleFor("pool-0")
117
- };
118
- }
119
- return containers;
120
- };
121
-
122
- export { createContainerContext, createContainerTestContext };
@@ -1,140 +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
- interface ContainerConfig {
56
- /**
57
- * Build-time variables for a Dockerfile/Railpack image — wrangler's
58
- * `image_vars` (equivalent to `docker build --build-arg`). For *runtime*
59
- * values use {@link ContainerConfig.env} / {@link ContainerConfig.secrets}.
60
- * Ignored for a pre-built `{ registry }` image.
61
- */
62
- buildArgs?: Readonly<Record<string, string>>;
63
- /**
64
- * The port the container listens on. Worker → container requests target
65
- * this port. Locally the Dockerfile must also `EXPOSE` it.
66
- */
67
- defaultPort?: number;
68
- /**
69
- * Whether the container may open outbound internet connections. Defaults
70
- * to `true` — the platform default. Note that container egress is billed
71
- * per GB by Cloudflare.
72
- */
73
- enableInternet?: boolean;
74
- /**
75
- * Static environment variables passed to the container on every start.
76
- * For secret values use {@link ContainerConfig.secrets} instead so they
77
- * flow through Worker Secrets rather than source code.
78
- */
79
- env?: Readonly<Record<string, string>>;
80
- /** Image source — a local Dockerfile path/directory or a registry reference. */
81
- image: ContainerImageSource;
82
- /**
83
- * Resource class for each instance: a named Cloudflare instance type or a
84
- * custom `{ vcpu, memoryMib, diskMb }` object.
85
- */
86
- instanceType?: ContainerInstanceType;
87
- /**
88
- * Maximum number of concurrently *running* instances. Stopped (slept)
89
- * containers don't count. Also the default pool size for `.any()`.
90
- */
91
- maxInstances?: number;
92
- /**
93
- * Override for the wrangler `containers[].name` identifier. Defaults to
94
- * wrangler's own default (worker name + class name + environment).
95
- */
96
- name?: string;
97
- /**
98
- * Rolling-deploy tuning. `stepPercentage` is the share of instances updated
99
- * per rollout step (wrangler `rollout_step_percentage`); `gracePeriodSeconds`
100
- * is how long an active instance is left running before it's eligible for
101
- * update (wrangler `rollout_active_grace_period`).
102
- */
103
- rollout?: ContainerRollout;
104
- /**
105
- * Names of Worker secrets (from `wrangler secret` / `.dev.vars`) forwarded
106
- * into the container's environment at instance start. Each declared name
107
- * must exist on the Worker `env` — a missing one fails fast with a
108
- * directed error instead of starting the container without it.
109
- */
110
- secrets?: ReadonlyArray<string>;
111
- /**
112
- * Idle timeout after which the instance is put to sleep, e.g. `"5m"`,
113
- * `"30s"`, or a number of seconds. Cloudflare's default is `"10m"`.
114
- */
115
- sleepAfter?: number | string;
116
- }
117
- /**
118
- * The value `defineContainer` returns: the validated config plus a brand the
119
- * codegen discovery and the generated Container DO class key on.
120
- */
121
- interface ContainerDefinition extends ContainerConfig {
122
- /** Brand marking a value as a Lunora container definition. */
123
- readonly isLunoraContainer: true;
124
- }
125
- /** A normalized image source, as written into `wrangler.jsonc`. */
126
- type NormalizedContainerImage = {
127
- /** Build context directory (wrangler `image_build_context`). */
128
- buildContext: string;
129
- /** Path to the Dockerfile (wrangler `image`). */
130
- dockerfilePath: string;
131
- kind: "dockerfile";
132
- } | {
133
- /** Railpack source directory built + pushed at deploy time. */
134
- buildDir: string;
135
- kind: "build";
136
- } | {
137
- kind: "registry"; /** Fully-qualified image reference (wrangler `image`). */
138
- reference: string;
139
- };
140
- export { BuildImageSource as B, ContainerDefinition as C, NormalizedContainerImage as N, RegistryImageSource as R, ContainerConfig as a, ContainerImageSource as b, ContainerInstanceType as c, ContainerRollout as d, CustomContainerInstanceType as e, NamedContainerInstanceType as f };