@astrale-os/adapter-cloudflare 0.4.10 → 0.5.0-beta.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 (214) hide show
  1. package/CHANGELOG.md +1193 -0
  2. package/README.md +29 -0
  3. package/dist/adapter.d.ts +15 -0
  4. package/dist/adapter.js +76 -0
  5. package/dist/build/artifact.d.ts +7 -0
  6. package/dist/build/artifact.js +165 -0
  7. package/dist/build/bundle/admit.d.ts +1 -0
  8. package/dist/build/bundle/admit.js +9 -0
  9. package/dist/build/closure.d.ts +2 -0
  10. package/dist/build/closure.js +22 -0
  11. package/dist/build/codegen/execution.d.ts +3 -0
  12. package/dist/build/codegen/execution.js +2 -0
  13. package/dist/{codegen → build/codegen}/merge.d.ts +0 -1
  14. package/dist/{codegen → build/codegen}/merge.js +0 -1
  15. package/dist/{codegen → build/codegen}/wrangler.d.ts +19 -4
  16. package/dist/{codegen → build/codegen}/wrangler.js +49 -13
  17. package/dist/build/configuration/addressing.d.ts +2 -0
  18. package/dist/build/configuration/addressing.js +11 -0
  19. package/dist/build/configuration/invocation-timeout.d.ts +2 -0
  20. package/dist/build/configuration/invocation-timeout.js +9 -0
  21. package/dist/build/configuration/request-limit.d.ts +2 -0
  22. package/dist/build/configuration/request-limit.js +9 -0
  23. package/dist/build/configuration/router.d.ts +7 -0
  24. package/dist/build/configuration/router.js +11 -0
  25. package/dist/build/configuration/worker-name.d.ts +2 -0
  26. package/dist/build/configuration/worker-name.js +18 -0
  27. package/dist/build/configuration.d.ts +5 -0
  28. package/dist/build/configuration.js +5 -0
  29. package/dist/build/direct.d.ts +4 -0
  30. package/dist/build/direct.js +93 -0
  31. package/dist/build/frontend/files.d.ts +7 -0
  32. package/dist/build/frontend/files.js +60 -0
  33. package/dist/build/frontend/routes.d.ts +2 -0
  34. package/dist/build/frontend/routes.js +11 -0
  35. package/dist/build/index.d.ts +8 -0
  36. package/dist/build/index.js +7 -0
  37. package/dist/build/materialize.d.ts +4 -0
  38. package/dist/build/materialize.js +10 -0
  39. package/dist/build/metafile.d.ts +5 -0
  40. package/dist/build/metafile.js +14 -0
  41. package/dist/build/qualification.d.ts +5 -0
  42. package/dist/build/qualification.js +7 -0
  43. package/dist/build/roots.d.ts +2 -0
  44. package/dist/build/roots.js +34 -0
  45. package/dist/build/worker/artifact.d.ts +40 -0
  46. package/dist/build/worker/artifact.js +1 -0
  47. package/dist/build/worker/artifact.load.d.ts +3 -0
  48. package/dist/build/worker/artifact.load.js +308 -0
  49. package/dist/build/worker/artifact.manifest.d.ts +48 -0
  50. package/dist/build/worker/artifact.manifest.js +87 -0
  51. package/dist/build/worker/artifact.paths.d.ts +4 -0
  52. package/dist/build/worker/artifact.paths.js +25 -0
  53. package/dist/build/worker/codegen/entry.d.ts +2 -0
  54. package/dist/build/worker/codegen/entry.js +28 -0
  55. package/dist/build/worker/codegen/service.d.ts +18 -0
  56. package/dist/build/worker/codegen/service.js +53 -0
  57. package/dist/build/worker/execution.prepare.d.ts +18 -0
  58. package/dist/build/worker/execution.prepare.js +112 -0
  59. package/dist/build/worker/index.d.ts +2 -0
  60. package/dist/build/worker/index.js +1 -0
  61. package/dist/build/worker/modules.d.ts +11 -0
  62. package/dist/build/worker/modules.js +26 -0
  63. package/dist/build/worker/runtime.d.ts +10 -0
  64. package/dist/build/worker/runtime.js +35 -0
  65. package/dist/build/worker/specifier.d.ts +1 -0
  66. package/dist/build/worker/specifier.js +5 -0
  67. package/dist/cloudflare.d.ts +1 -37
  68. package/dist/cloudflare.js +1 -271
  69. package/dist/deploy/deploy.d.ts +16 -0
  70. package/dist/deploy/deploy.js +204 -0
  71. package/dist/deploy/index.d.ts +1 -0
  72. package/dist/deploy/index.js +1 -0
  73. package/dist/deploy/output.d.ts +2 -0
  74. package/dist/deploy/output.js +10 -0
  75. package/dist/development/develop.d.ts +15 -0
  76. package/dist/development/develop.js +270 -0
  77. package/dist/development/frontend.d.ts +11 -0
  78. package/dist/development/frontend.js +109 -0
  79. package/dist/development/host.d.ts +2 -0
  80. package/dist/development/host.js +46 -0
  81. package/dist/development/port.d.ts +1 -0
  82. package/dist/development/port.js +12 -0
  83. package/dist/development/readiness.d.ts +14 -0
  84. package/dist/development/readiness.js +71 -0
  85. package/dist/development/resolved-fetch.d.ts +17 -0
  86. package/dist/development/resolved-fetch.js +80 -0
  87. package/dist/development/worker-output.d.ts +2 -0
  88. package/dist/development/worker-output.js +25 -0
  89. package/dist/development/worker.d.ts +17 -0
  90. package/dist/development/worker.js +147 -0
  91. package/dist/identity/binding.d.ts +2 -0
  92. package/dist/identity/binding.js +2 -0
  93. package/dist/identity/index.d.ts +3 -0
  94. package/dist/identity/index.js +3 -0
  95. package/dist/identity/material.d.ts +7 -0
  96. package/dist/identity/material.js +42 -0
  97. package/dist/identity/secret.d.ts +3 -0
  98. package/dist/identity/secret.js +7 -0
  99. package/dist/identity/source.d.ts +26 -0
  100. package/dist/identity/source.js +127 -0
  101. package/dist/index.d.ts +8 -8
  102. package/dist/index.js +7 -7
  103. package/dist/params.d.ts +50 -23
  104. package/dist/params.js +0 -1
  105. package/dist/release/deployment.d.ts +44 -0
  106. package/dist/release/deployment.js +141 -0
  107. package/dist/release/index.d.ts +2 -0
  108. package/dist/release/index.js +2 -0
  109. package/dist/release/staged-worker-name.d.ts +3 -0
  110. package/dist/release/staged-worker-name.js +10 -0
  111. package/dist/worker/entry.d.ts +44 -0
  112. package/dist/worker/entry.js +184 -0
  113. package/dist/worker/fetch.d.ts +11 -0
  114. package/dist/worker/fetch.js +31 -0
  115. package/dist/worker/identity.d.ts +7 -0
  116. package/dist/worker/identity.js +23 -0
  117. package/dist/worker/index.d.ts +2 -0
  118. package/dist/worker/index.js +2 -0
  119. package/dist/wrangler/bundle.d.ts +10 -0
  120. package/dist/wrangler/bundle.js +27 -0
  121. package/dist/wrangler/deploy.d.ts +24 -0
  122. package/dist/wrangler/deploy.js +44 -0
  123. package/dist/wrangler/index.d.ts +5 -0
  124. package/dist/wrangler/index.js +5 -0
  125. package/dist/wrangler/process.d.ts +17 -0
  126. package/dist/wrangler/process.js +115 -0
  127. package/dist/wrangler/secrets.d.ts +6 -0
  128. package/dist/wrangler/secrets.js +58 -0
  129. package/dist/wrangler/status.d.ts +14 -0
  130. package/dist/wrangler/status.js +56 -0
  131. package/dist/wrangler/type-generation.d.ts +6 -0
  132. package/dist/wrangler/type-generation.js +19 -0
  133. package/package.json +41 -18
  134. package/template/astrale.config.ts +26 -18
  135. package/dist/assets-pack.d.ts +0 -8
  136. package/dist/assets-pack.d.ts.map +0 -1
  137. package/dist/assets-pack.js +0 -30
  138. package/dist/assets-pack.js.map +0 -1
  139. package/dist/build.d.ts +0 -16
  140. package/dist/build.d.ts.map +0 -1
  141. package/dist/build.js +0 -15
  142. package/dist/build.js.map +0 -1
  143. package/dist/client.d.ts +0 -17
  144. package/dist/client.d.ts.map +0 -1
  145. package/dist/client.js +0 -59
  146. package/dist/client.js.map +0 -1
  147. package/dist/cloudflare.d.ts.map +0 -1
  148. package/dist/cloudflare.js.map +0 -1
  149. package/dist/codegen/identity.d.ts +0 -10
  150. package/dist/codegen/identity.d.ts.map +0 -1
  151. package/dist/codegen/identity.js +0 -32
  152. package/dist/codegen/identity.js.map +0 -1
  153. package/dist/codegen/merge.d.ts.map +0 -1
  154. package/dist/codegen/merge.js.map +0 -1
  155. package/dist/codegen/worker.d.ts +0 -51
  156. package/dist/codegen/worker.d.ts.map +0 -1
  157. package/dist/codegen/worker.js +0 -120
  158. package/dist/codegen/worker.js.map +0 -1
  159. package/dist/codegen/wrangler.d.ts.map +0 -1
  160. package/dist/codegen/wrangler.js.map +0 -1
  161. package/dist/index.d.ts.map +0 -1
  162. package/dist/index.js.map +0 -1
  163. package/dist/params.d.ts.map +0 -1
  164. package/dist/params.js.map +0 -1
  165. package/dist/parse-output.d.ts +0 -25
  166. package/dist/parse-output.d.ts.map +0 -1
  167. package/dist/parse-output.js +0 -53
  168. package/dist/parse-output.js.map +0 -1
  169. package/dist/wrangler-cli.d.ts +0 -78
  170. package/dist/wrangler-cli.d.ts.map +0 -1
  171. package/dist/wrangler-cli.js +0 -251
  172. package/dist/wrangler-cli.js.map +0 -1
  173. package/src/assets-pack.ts +0 -32
  174. package/src/build.ts +0 -16
  175. package/src/client.ts +0 -89
  176. package/src/cloudflare.ts +0 -321
  177. package/src/codegen/identity.ts +0 -40
  178. package/src/codegen/merge.ts +0 -92
  179. package/src/codegen/worker.ts +0 -136
  180. package/src/codegen/wrangler.ts +0 -105
  181. package/src/index.ts +0 -21
  182. package/src/params.ts +0 -96
  183. package/src/parse-output.ts +0 -54
  184. package/src/wrangler-cli.ts +0 -324
  185. package/template/.env.example +0 -9
  186. package/template/.gitignore.template +0 -16
  187. package/template/CLAUDE.md +0 -13
  188. package/template/README.md +0 -47
  189. package/template/client/.gitignore.template +0 -4
  190. package/template/client/__tests__/app.test.tsx +0 -15
  191. package/template/client/components.json +0 -25
  192. package/template/client/index.html +0 -12
  193. package/template/client/package.json +0 -35
  194. package/template/client/src/app.tsx +0 -52
  195. package/template/client/src/components/ui/cn.ts +0 -6
  196. package/template/client/src/main.tsx +0 -9
  197. package/template/client/src/styles.css +0 -78
  198. package/template/client/tsconfig.json +0 -26
  199. package/template/client/vite.config.ts +0 -22
  200. package/template/client/vitest.config.ts +0 -13
  201. package/template/core/README.md +0 -7
  202. package/template/deps.ts +0 -9
  203. package/template/domain.ts +0 -11
  204. package/template/env.ts +0 -8
  205. package/template/icons.ts +0 -4
  206. package/template/integrations/README.md +0 -7
  207. package/template/oxlint.config.ts +0 -1
  208. package/template/package.json +0 -58
  209. package/template/pnpm-workspace.yaml +0 -31
  210. package/template/runtime/index.ts +0 -8
  211. package/template/schema/index.ts +0 -10
  212. package/template/simulation/README.md +0 -12
  213. package/template/tsconfig.json +0 -28
  214. package/template/vitest.config.ts +0 -7
@@ -0,0 +1,93 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { generateWranglerConfig } from './codegen/wrangler.js';
3
+ import { resolveRouter, workerName } from './configuration.js';
4
+ import { frontendRoutes } from './frontend/routes.js';
5
+ import { workerModules } from './worker/modules.js';
6
+ export function admitDirectPlacement(artifact, worker, parameters) {
7
+ const name = workerName(parameters, worker.origin);
8
+ const release = config(artifact, 'wrangler.jsonc');
9
+ const router = resolveRouter(parameters.router);
10
+ const frontend = artifact.build.frontend;
11
+ const hasViteFrontend = frontend?.source.kind === 'vite';
12
+ equal(worker.assets !== undefined, hasViteFrontend);
13
+ if (worker.assets !== undefined) {
14
+ equal(worker.assets.notFound, 'none');
15
+ equal(worker.assets.runWorkerFirst, true);
16
+ }
17
+ equal(release, generated({
18
+ workerName: name,
19
+ main: `./${worker.release.entrypoint}`,
20
+ ...(parameters.route === undefined ? {} : { route: parameters.route }),
21
+ vars: worker.bindings.vars,
22
+ secretBindings: worker.bindings.requiredSecrets,
23
+ modules: directModules(worker.release),
24
+ ...(hasViteFrontend
25
+ ? {
26
+ frontend: {
27
+ directory: './frontend',
28
+ routes: frontendRoutes(frontend),
29
+ dev: false,
30
+ },
31
+ }
32
+ : {}),
33
+ ...(router === undefined
34
+ ? {}
35
+ : { router: { binding: router.binding, service: router.service } }),
36
+ ...(parameters.wrangler === undefined ? {} : { wrangler: parameters.wrangler }),
37
+ selfBinding: false,
38
+ }));
39
+ equal(release.compatibility_date, worker.runtime.compatibilityDate);
40
+ equalStringCollection(release.compatibility_flags, worker.runtime.compatibilityFlags);
41
+ equal(release.services ?? [], worker.bindings.services.map(serviceBinding));
42
+ equal(record(release.assets).html_handling, worker.assets?.htmlHandling);
43
+ }
44
+ function directModules(worker) {
45
+ try {
46
+ return workerModules(worker);
47
+ }
48
+ catch {
49
+ mismatch();
50
+ }
51
+ }
52
+ function generated(input) {
53
+ return JSON.parse(generateWranglerConfig(input));
54
+ }
55
+ function config(artifact, path) {
56
+ const file = artifact.files.find((candidate) => candidate.path === path);
57
+ if (file === undefined)
58
+ throw new TypeError(`Direct Cloudflare artifact is missing ${path}.`);
59
+ try {
60
+ const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(file.bytes()));
61
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
62
+ throw new Error();
63
+ return value;
64
+ }
65
+ catch (cause) {
66
+ throw new TypeError(`Direct Cloudflare artifact ${path} is invalid.`, { cause });
67
+ }
68
+ }
69
+ function serviceBinding(binding) {
70
+ return { binding: binding.name, service: binding.service };
71
+ }
72
+ function record(input) {
73
+ return input !== null && typeof input === 'object' && !Array.isArray(input)
74
+ ? input
75
+ : {};
76
+ }
77
+ function equal(actual, expected) {
78
+ if (!isDeepStrictEqual(actual, expected)) {
79
+ throw new TypeError('Direct Cloudflare placement differs from its admitted Worker artifact.', {
80
+ cause: { actual, expected },
81
+ });
82
+ }
83
+ }
84
+ function equalStringCollection(actual, expected) {
85
+ if (!Array.isArray(actual) ||
86
+ actual.some((value) => typeof value !== 'string') ||
87
+ !isDeepStrictEqual([...actual].sort(), [...expected].sort())) {
88
+ mismatch();
89
+ }
90
+ }
91
+ function mismatch() {
92
+ throw new TypeError('Direct Cloudflare placement differs from its admitted Worker artifact.');
93
+ }
@@ -0,0 +1,7 @@
1
+ import type { Build } from '@astrale-os/sdk/deployment/build';
2
+ import { frontend as frontendBuild } from '@astrale-os/sdk/deployment/build';
3
+ export declare function frontendFiles(input: {
4
+ readonly frontend: Build['frontend'];
5
+ readonly projectDir: string;
6
+ readonly onLog?: (line: string) => void;
7
+ }): Promise<readonly frontendBuild.FrontendFile[]>;
@@ -0,0 +1,60 @@
1
+ import { frontend as frontendBuild } from '@astrale-os/sdk/deployment/build';
2
+ import { spawn } from 'node:child_process';
3
+ import { existsSync } from 'node:fs';
4
+ import { readFile, readdir, rm } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
+ export async function frontendFiles(input) {
7
+ const frontend = input.frontend;
8
+ if (frontend === undefined)
9
+ return [];
10
+ if (frontend.source.kind === 'external')
11
+ return frontendBuild.files(frontend, []);
12
+ const output = join(input.projectDir, '.astrale', 'frontend-build');
13
+ await rm(output, { recursive: true, force: true });
14
+ await run(viteCommand(input.projectDir), [
15
+ 'build',
16
+ '--outDir',
17
+ output,
18
+ '--emptyOutDir',
19
+ ...(frontend.source.config === undefined ? [] : ['--config', frontend.source.config]),
20
+ ], input.projectDir, input.onLog);
21
+ return frontendBuild.files(frontend, await readFiles(output));
22
+ }
23
+ async function readFiles(root, current = '') {
24
+ const entries = await readdir(join(root, current), { withFileTypes: true });
25
+ const files = [];
26
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
27
+ const path = current === '' ? entry.name : `${current}/${entry.name}`;
28
+ if (entry.isDirectory())
29
+ files.push(...(await readFiles(root, path)));
30
+ else if (entry.isFile()) {
31
+ files.push({ path, content: new Uint8Array(await readFile(join(root, path))) });
32
+ }
33
+ }
34
+ return files;
35
+ }
36
+ function viteCommand(projectDir) {
37
+ const command = join(projectDir, 'node_modules', '.bin', 'vite');
38
+ if (!existsSync(command))
39
+ throw new TypeError('Vite frontend requires a project-local vite binary.');
40
+ return command;
41
+ }
42
+ function run(command, args, cwd, onLog) {
43
+ return new Promise((resolve, reject) => {
44
+ const child = spawn(command, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
45
+ let output = '';
46
+ const collect = (buffer) => {
47
+ const value = buffer.toString();
48
+ output += value;
49
+ for (const line of value.split('\n'))
50
+ if (line.trim() !== '')
51
+ onLog?.(line);
52
+ };
53
+ child.stdout?.on('data', collect);
54
+ child.stderr?.on('data', collect);
55
+ child.on('error', reject);
56
+ child.on('exit', (code) => code === 0
57
+ ? resolve()
58
+ : reject(new Error(`Vite failed (code ${code ?? 1}):\n${output.slice(-1500)}`)));
59
+ });
60
+ }
@@ -0,0 +1,2 @@
1
+ import type { PrepareContext } from '@astrale-os/sdk/deployment/adapter';
2
+ export declare function frontendRoutes(frontend: NonNullable<PrepareContext['build']['frontend']>): readonly string[];
@@ -0,0 +1,11 @@
1
+ export function frontendRoutes(frontend) {
2
+ if (frontend.source.kind !== 'vite')
3
+ return [];
4
+ return Object.freeze(frontend.routes
5
+ .flatMap((route) => frontend.source.kind === 'vite' && frontend.source.spa && route.path !== '/'
6
+ ? [route.path, `${route.path}/*`]
7
+ : route.path === '/'
8
+ ? ['/*']
9
+ : [route.path])
10
+ .sort());
11
+ }
@@ -0,0 +1,8 @@
1
+ export { artifact, materialize, prepareWorkerArtifact } from './artifact.js';
2
+ export { loadWorkerArtifact } from './worker/index.js';
3
+ export type { WorkerArtifact } from './worker/index.js';
4
+ export { resolveRouter, workerName } from './configuration.js';
5
+ export { frontendFiles } from './frontend/files.js';
6
+ export { qualifyWorkerBundle } from './qualification.js';
7
+ export { assertSingletonRuntimeRoots } from './roots.js';
8
+ export { runWranglerBundle, runWranglerDeploy, runWranglerDeploymentStatus, runWranglerTypes, } from '../wrangler/index.js';
@@ -0,0 +1,7 @@
1
+ export { artifact, materialize, prepareWorkerArtifact } from './artifact.js';
2
+ export { loadWorkerArtifact } from './worker/index.js';
3
+ export { resolveRouter, workerName } from './configuration.js';
4
+ export { frontendFiles } from './frontend/files.js';
5
+ export { qualifyWorkerBundle } from './qualification.js';
6
+ export { assertSingletonRuntimeRoots } from './roots.js';
7
+ export { runWranglerBundle, runWranglerDeploy, runWranglerDeploymentStatus, runWranglerTypes, } from '../wrangler/index.js';
@@ -0,0 +1,4 @@
1
+ export declare function materialize(root: string, files: readonly {
2
+ readonly path: string;
3
+ bytes(): Uint8Array;
4
+ }[]): Promise<void>;
@@ -0,0 +1,10 @@
1
+ import { mkdir, rm, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ export async function materialize(root, files) {
4
+ await rm(root, { recursive: true, force: true });
5
+ for (const file of files) {
6
+ const path = join(root, file.path);
7
+ await mkdir(dirname(path), { recursive: true });
8
+ await writeFile(path, file.bytes());
9
+ }
10
+ }
@@ -0,0 +1,5 @@
1
+ export interface WranglerMetafile {
2
+ readonly inputs: Readonly<Record<string, unknown>>;
3
+ }
4
+ /** Decode Wrangler's emitted esbuild graph at the provider-tooling boundary. */
5
+ export declare function readWranglerMetafile(path: string): Promise<WranglerMetafile>;
@@ -0,0 +1,14 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ /** Decode Wrangler's emitted esbuild graph at the provider-tooling boundary. */
3
+ export async function readWranglerMetafile(path) {
4
+ const source = await readFile(path, 'utf8');
5
+ const value = JSON.parse(source);
6
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
7
+ throw new TypeError('Wrangler metafile is not an object.');
8
+ }
9
+ const inputs = Reflect.get(value, 'inputs');
10
+ if (inputs === null || typeof inputs !== 'object' || Array.isArray(inputs)) {
11
+ throw new TypeError('Wrangler metafile has no input graph.');
12
+ }
13
+ return Object.freeze({ inputs: inputs });
14
+ }
@@ -0,0 +1,5 @@
1
+ /** Qualify Wrangler's emitted module, not generated source or an inferred graph. */
2
+ export declare function qualifyWorkerBundle(evidence: {
3
+ readonly metafilePath: string;
4
+ readonly inputRoot: string;
5
+ }): Promise<void>;
@@ -0,0 +1,7 @@
1
+ import { assertRuntimeClosure } from './closure.js';
2
+ import { assertSingletonRuntimeRoots } from './roots.js';
3
+ /** Qualify Wrangler's emitted module, not generated source or an inferred graph. */
4
+ export async function qualifyWorkerBundle(evidence) {
5
+ await assertRuntimeClosure(evidence.metafilePath);
6
+ await assertSingletonRuntimeRoots(evidence.metafilePath, evidence.inputRoot);
7
+ }
@@ -0,0 +1,2 @@
1
+ /** Prove that Wrangler emitted at most one physical root per runtime package. */
2
+ export declare function assertSingletonRuntimeRoots(metafilePath: string, inputRoot: string): Promise<void>;
@@ -0,0 +1,34 @@
1
+ import { realpath } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { readWranglerMetafile } from './metafile.js';
4
+ const RUNTIME_PACKAGES = [
5
+ '@astrale-os/adapter-cloudflare',
6
+ '@astrale-os/sdk',
7
+ '@astrale-os/kernel-core',
8
+ '@astrale-os/kernel-dsl',
9
+ '@astrale-os/kernel-ports',
10
+ '@astrale-os/kernel-protocol',
11
+ '@astrale-os/kernel-server',
12
+ '@astrale-os/kernel-client',
13
+ ];
14
+ /** Prove that Wrangler emitted at most one physical root per runtime package. */
15
+ export async function assertSingletonRuntimeRoots(metafilePath, inputRoot) {
16
+ const metafile = await readWranglerMetafile(metafilePath);
17
+ for (const name of RUNTIME_PACKAGES) {
18
+ const roots = new Set();
19
+ for (const input of Object.keys(metafile.inputs)) {
20
+ const root = packageRoot(input, name);
21
+ if (root !== undefined)
22
+ roots.add(await realpath(resolve(inputRoot, root)));
23
+ }
24
+ if (roots.size > 1) {
25
+ throw new Error(`Cloudflare Worker contains duplicate physical ${name} roots: ${[...roots].join(', ')}.`);
26
+ }
27
+ }
28
+ }
29
+ function packageRoot(input, name) {
30
+ const normalized = input.replaceAll('\\', '/');
31
+ const marker = `node_modules/${name}/`;
32
+ const index = normalized.lastIndexOf(marker);
33
+ return index < 0 ? undefined : normalized.slice(0, index + marker.length - 1);
34
+ }
@@ -0,0 +1,40 @@
1
+ import type { WorkerDeploymentId } from '../../release/deployment.js';
2
+ export type WorkerModuleKind = 'esm' | 'wasm' | 'text' | 'data';
3
+ export interface WorkerArtifactModule {
4
+ readonly path: string;
5
+ readonly kind: WorkerModuleKind;
6
+ bytes(): Uint8Array;
7
+ }
8
+ export interface WorkerArtifactExecutable {
9
+ readonly entrypoint: string;
10
+ readonly modules: readonly WorkerArtifactModule[];
11
+ }
12
+ export interface WorkerArtifact {
13
+ readonly origin: string;
14
+ readonly revision: string;
15
+ readonly deployment: WorkerDeploymentId;
16
+ readonly release: WorkerArtifactExecutable;
17
+ readonly runtime: {
18
+ readonly compatibilityDate: string;
19
+ readonly compatibilityFlags: readonly string[];
20
+ };
21
+ readonly bindings: {
22
+ readonly vars: Readonly<Record<string, string>>;
23
+ readonly services: readonly {
24
+ readonly name: string;
25
+ readonly service: string;
26
+ }[];
27
+ readonly requiredSecrets: readonly string[];
28
+ };
29
+ readonly assets?: {
30
+ readonly files: readonly {
31
+ readonly path: string;
32
+ readonly artifactPath: string;
33
+ readonly contentType?: string;
34
+ bytes(): Uint8Array;
35
+ }[];
36
+ readonly notFound: 'none' | '404-page' | 'single-page-application';
37
+ readonly runWorkerFirst: boolean;
38
+ readonly htmlHandling?: 'none';
39
+ };
40
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ import type { PreparedArtifact } from '@astrale-os/sdk/deployment/adapter';
2
+ import type { WorkerArtifact } from './artifact.js';
3
+ export declare function loadWorkerArtifact(artifact: PreparedArtifact): WorkerArtifact;
@@ -0,0 +1,308 @@
1
+ import { isPreparedArtifact } from '@astrale-os/sdk/deployment/verify';
2
+ import { createHash } from 'node:crypto';
3
+ import { workerDeployment } from '../../release/deployment.js';
4
+ import { WORKER_ARTIFACT_FORMAT, WORKER_ARTIFACT_VERSION } from './artifact.manifest.js';
5
+ import { artifactPath, assetPath, comparePath, WORKER_MANIFEST_PATH } from './artifact.paths.js';
6
+ const decoder = new TextDecoder('utf-8', { fatal: true });
7
+ const REVISION = /^sha256:[0-9a-f]{64}$/u;
8
+ const BINDING = /^[A-Za-z_$][A-Za-z0-9_$]{0,127}$/u;
9
+ const DATE = /^\d{4}-\d{2}-\d{2}$/u;
10
+ const KINDS = new Set(['esm', 'wasm', 'text', 'data']);
11
+ export function loadWorkerArtifact(artifact) {
12
+ if (!isPreparedArtifact(artifact))
13
+ throw new TypeError('PreparedArtifact is not admitted.');
14
+ const manifestFile = requiredFile(artifact, WORKER_MANIFEST_PATH);
15
+ let decoded;
16
+ try {
17
+ decoded = JSON.parse(decoder.decode(manifestFile.bytes()));
18
+ }
19
+ catch (cause) {
20
+ throw new TypeError('Cloudflare Worker artifact manifest is invalid JSON.', { cause });
21
+ }
22
+ const manifest = admitManifest(decoded);
23
+ if (artifact.entrypoint !== manifest.release.entrypoint) {
24
+ throw new TypeError('Cloudflare Worker artifact entrypoint differs from its manifest.');
25
+ }
26
+ const origin = artifact.build.schema.compiled.root.origin;
27
+ const revision = artifact.build.schema.compiled.root.revision;
28
+ if (manifest.origin !== origin || manifest.revision !== revision) {
29
+ throw new TypeError('Cloudflare Worker artifact identity differs from its Build.');
30
+ }
31
+ const claimed = new Set([WORKER_MANIFEST_PATH]);
32
+ const release = executable(artifact, manifest.release, claimed, 'release');
33
+ const assets = manifest.assets?.files.map((file) => {
34
+ claim(claimed, file.artifactPath);
35
+ const source = requiredFile(artifact, file.artifactPath);
36
+ const content = source.bytes();
37
+ verifyContent(content, file.digest, file.artifactPath);
38
+ return Object.freeze({
39
+ path: file.path,
40
+ artifactPath: file.artifactPath,
41
+ ...(file.contentType === undefined ? {} : { contentType: file.contentType }),
42
+ bytes: () => new Uint8Array(content),
43
+ });
44
+ });
45
+ const deployment = workerDeployment({
46
+ release: {
47
+ entrypoint: release.entrypoint,
48
+ modules: release.modules.map((module) => ({
49
+ path: module.path,
50
+ kind: module.kind,
51
+ content: module.bytes(),
52
+ })),
53
+ },
54
+ runtime: manifest.runtime,
55
+ bindings: manifest.bindings,
56
+ ...(manifest.assets === undefined
57
+ ? {}
58
+ : {
59
+ assets: {
60
+ files: assets.map((file) => ({
61
+ path: file.path,
62
+ content: file.bytes(),
63
+ ...(file.contentType === undefined ? {} : { contentType: file.contentType }),
64
+ })),
65
+ notFound: manifest.assets.notFound,
66
+ runWorkerFirst: manifest.assets.runWorkerFirst,
67
+ ...(manifest.assets.htmlHandling === undefined
68
+ ? {}
69
+ : { htmlHandling: manifest.assets.htmlHandling }),
70
+ },
71
+ }),
72
+ });
73
+ if (deployment !== manifest.deployment) {
74
+ throw new TypeError('Cloudflare Worker deployment identity differs from its material.');
75
+ }
76
+ return Object.freeze({
77
+ origin,
78
+ revision,
79
+ deployment,
80
+ release,
81
+ runtime: Object.freeze({
82
+ compatibilityDate: manifest.runtime.compatibilityDate,
83
+ compatibilityFlags: Object.freeze([...manifest.runtime.compatibilityFlags]),
84
+ }),
85
+ bindings: Object.freeze({
86
+ vars: Object.freeze({ ...manifest.bindings.vars }),
87
+ services: Object.freeze(manifest.bindings.services.map((binding) => Object.freeze({ ...binding }))),
88
+ requiredSecrets: Object.freeze([...manifest.bindings.requiredSecrets]),
89
+ }),
90
+ ...(manifest.assets === undefined
91
+ ? {}
92
+ : {
93
+ assets: Object.freeze({
94
+ files: Object.freeze(assets),
95
+ notFound: manifest.assets.notFound,
96
+ runWorkerFirst: manifest.assets.runWorkerFirst,
97
+ ...(manifest.assets.htmlHandling === undefined
98
+ ? {}
99
+ : { htmlHandling: manifest.assets.htmlHandling }),
100
+ }),
101
+ }),
102
+ });
103
+ }
104
+ function executable(artifact, manifest, claimed, label) {
105
+ const modules = manifest.modules.map((module) => {
106
+ claim(claimed, module.path);
107
+ const source = requiredFile(artifact, module.path);
108
+ const content = source.bytes();
109
+ verifyContent(content, module.digest, module.path);
110
+ return Object.freeze({
111
+ path: module.path,
112
+ kind: module.kind,
113
+ bytes: () => new Uint8Array(content),
114
+ });
115
+ });
116
+ if (!manifest.modules.some((module) => module.path === manifest.entrypoint)) {
117
+ throw new TypeError(`Cloudflare Worker ${label} entrypoint is not a module.`);
118
+ }
119
+ if (manifest.modules.find((module) => module.path === manifest.entrypoint)?.kind !== 'esm') {
120
+ throw new TypeError(`Cloudflare Worker ${label} entrypoint is not an ES module.`);
121
+ }
122
+ return Object.freeze({ entrypoint: manifest.entrypoint, modules: Object.freeze(modules) });
123
+ }
124
+ function admitManifest(input) {
125
+ const value = record(input, [
126
+ 'format',
127
+ 'version',
128
+ 'origin',
129
+ 'revision',
130
+ 'deployment',
131
+ 'release',
132
+ 'runtime',
133
+ 'bindings',
134
+ 'assets',
135
+ ]);
136
+ if (value.format !== WORKER_ARTIFACT_FORMAT || value.version !== WORKER_ARTIFACT_VERSION) {
137
+ throw new TypeError('Cloudflare Worker artifact format or version is unsupported.');
138
+ }
139
+ if (typeof value.origin !== 'string' ||
140
+ value.origin.length === 0 ||
141
+ !REVISION.test(String(value.revision)) ||
142
+ !REVISION.test(String(value.deployment))) {
143
+ invalid();
144
+ }
145
+ const release = admitExecutable(value.release);
146
+ const runtime = record(value.runtime, ['compatibilityDate', 'compatibilityFlags']);
147
+ if (typeof runtime.compatibilityDate !== 'string' || !DATE.test(runtime.compatibilityDate))
148
+ invalid();
149
+ const compatibilityFlags = uniqueStrings(runtime.compatibilityFlags, 'compatibility flag');
150
+ const bindings = record(value.bindings, ['vars', 'services', 'requiredSecrets']);
151
+ const vars = stringRecord(bindings.vars);
152
+ const services = admitServices(bindings.services);
153
+ const requiredSecrets = uniqueStrings(bindings.requiredSecrets, 'secret binding');
154
+ const names = new Set();
155
+ for (const name of [
156
+ ...Object.keys(vars),
157
+ ...services.map((item) => item.name),
158
+ ...requiredSecrets,
159
+ ]) {
160
+ if (!BINDING.test(name) || names.has(name))
161
+ throw new TypeError(`Worker binding ${name} is invalid or duplicated.`);
162
+ names.add(name);
163
+ }
164
+ const assets = value.assets === undefined ? undefined : admitAssets(value.assets);
165
+ return Object.freeze({
166
+ format: WORKER_ARTIFACT_FORMAT,
167
+ version: WORKER_ARTIFACT_VERSION,
168
+ origin: value.origin,
169
+ revision: value.revision,
170
+ deployment: value.deployment,
171
+ release,
172
+ runtime: Object.freeze({
173
+ compatibilityDate: runtime.compatibilityDate,
174
+ compatibilityFlags,
175
+ }),
176
+ bindings: Object.freeze({ vars, services, requiredSecrets }),
177
+ ...(assets === undefined ? {} : { assets }),
178
+ });
179
+ }
180
+ function admitExecutable(input) {
181
+ const value = record(input, ['entrypoint', 'modules']);
182
+ const entrypoint = artifactPath(value.entrypoint, 'Worker entrypoint');
183
+ if (!Array.isArray(value.modules) || value.modules.length === 0)
184
+ invalid();
185
+ const paths = new Set();
186
+ const modules = value.modules.map((input) => {
187
+ const module = record(input, ['path', 'kind', 'digest']);
188
+ const path = artifactPath(module.path, 'Worker module path');
189
+ if (paths.has(path) ||
190
+ !KINDS.has(module.kind) ||
191
+ typeof module.digest !== 'string' ||
192
+ !REVISION.test(module.digest))
193
+ invalid();
194
+ paths.add(path);
195
+ return Object.freeze({ path, kind: module.kind, digest: module.digest });
196
+ });
197
+ canonical(modules.map((module) => module.path));
198
+ return Object.freeze({ entrypoint, modules: Object.freeze(modules) });
199
+ }
200
+ function admitServices(input) {
201
+ if (!Array.isArray(input))
202
+ invalid();
203
+ const names = new Set();
204
+ const services = input.map((item) => {
205
+ const value = record(item, ['name', 'service']);
206
+ if (typeof value.name !== 'string' ||
207
+ typeof value.service !== 'string' ||
208
+ value.service.length === 0 ||
209
+ names.has(value.name))
210
+ invalid();
211
+ names.add(value.name);
212
+ return Object.freeze({ name: value.name, service: value.service });
213
+ });
214
+ canonical(services.map((service) => service.name));
215
+ return Object.freeze(services);
216
+ }
217
+ function admitAssets(input) {
218
+ const value = record(input, ['files', 'notFound', 'runWorkerFirst', 'htmlHandling']);
219
+ if (!Array.isArray(value.files) ||
220
+ !['none', '404-page', 'single-page-application'].includes(String(value.notFound)) ||
221
+ typeof value.runWorkerFirst !== 'boolean' ||
222
+ (value.htmlHandling !== undefined && value.htmlHandling !== 'none'))
223
+ invalid();
224
+ const paths = new Set();
225
+ const files = value.files.map((input) => {
226
+ const file = record(input, ['path', 'artifactPath', 'digest', 'contentType']);
227
+ const path = assetPath(file.path);
228
+ if (paths.has(path))
229
+ invalid();
230
+ paths.add(path);
231
+ if (file.contentType !== undefined &&
232
+ (typeof file.contentType !== 'string' ||
233
+ file.contentType.length === 0 ||
234
+ file.contentType.length > 256))
235
+ invalid();
236
+ if (typeof file.digest !== 'string' || !REVISION.test(file.digest))
237
+ invalid();
238
+ return Object.freeze({
239
+ path,
240
+ artifactPath: artifactPath(file.artifactPath, 'Worker asset artifact path'),
241
+ digest: file.digest,
242
+ ...(file.contentType === undefined ? {} : { contentType: file.contentType }),
243
+ });
244
+ });
245
+ canonical(files.map((file) => file.path));
246
+ return Object.freeze({
247
+ files: Object.freeze(files),
248
+ notFound: value.notFound,
249
+ runWorkerFirst: value.runWorkerFirst,
250
+ ...(value.htmlHandling === undefined ? {} : { htmlHandling: 'none' }),
251
+ });
252
+ }
253
+ function record(input, allowed) {
254
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
255
+ invalid();
256
+ const value = input;
257
+ if (Reflect.ownKeys(value).some((key) => typeof key !== 'string' || !allowed.includes(key)))
258
+ invalid();
259
+ return value;
260
+ }
261
+ function stringRecord(input) {
262
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
263
+ invalid();
264
+ const value = input;
265
+ if (Reflect.ownKeys(value).some((key) => typeof key !== 'string'))
266
+ invalid();
267
+ if (Object.values(value).some((item) => typeof item !== 'string'))
268
+ invalid();
269
+ const entries = Object.entries(value);
270
+ canonical(entries.map(([name]) => name));
271
+ return Object.freeze(Object.fromEntries(entries));
272
+ }
273
+ function uniqueStrings(input, label) {
274
+ if (!Array.isArray(input) || input.some((item) => typeof item !== 'string' || item.length === 0))
275
+ invalid();
276
+ const values = input;
277
+ if (new Set(values).size !== values.length)
278
+ throw new TypeError(`Worker ${label} is duplicated.`);
279
+ canonical(values);
280
+ return Object.freeze([...values]);
281
+ }
282
+ function canonical(values) {
283
+ const sorted = [...values].sort(comparePath);
284
+ if (values.some((value, index) => value !== sorted[index])) {
285
+ throw new TypeError('Cloudflare Worker artifact manifest is not canonical.');
286
+ }
287
+ }
288
+ function claim(claimed, path) {
289
+ if (path === WORKER_MANIFEST_PATH || claimed.has(path)) {
290
+ throw new TypeError(`Cloudflare Worker artifact file ${path} has conflicting roles.`);
291
+ }
292
+ claimed.add(path);
293
+ }
294
+ function requiredFile(artifact, path) {
295
+ const file = artifact.files.find((candidate) => candidate.path === path);
296
+ if (file === undefined)
297
+ throw new TypeError(`Cloudflare Worker artifact is missing ${path}.`);
298
+ return file;
299
+ }
300
+ function verifyContent(content, expected, path) {
301
+ const digest = `sha256:${createHash('sha256').update(content).digest('hex')}`;
302
+ if (digest !== expected) {
303
+ throw new TypeError(`Cloudflare Worker artifact content differs at ${path}.`);
304
+ }
305
+ }
306
+ function invalid() {
307
+ throw new TypeError('Cloudflare Worker artifact manifest is invalid.');
308
+ }