@astrale-os/adapter-cloudflare 0.5.0-beta.2 → 0.5.0-beta.200

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 (249) hide show
  1. package/README.md +256 -0
  2. package/dist/adapter.d.ts +11 -0
  3. package/dist/adapter.js +54 -0
  4. package/dist/build/bundle/admit.d.ts +3 -0
  5. package/dist/build/bundle/admit.js +47 -0
  6. package/dist/build/bundle/compiled-wasm-loader.d.ts +8 -0
  7. package/dist/build/bundle/compiled-wasm-loader.js +21 -0
  8. package/dist/build/bundler.d.ts +21 -0
  9. package/dist/build/bundler.js +96 -0
  10. package/dist/build/closure.d.ts +5 -0
  11. package/dist/build/closure.js +28 -0
  12. package/dist/build/codegen/execution.d.ts +3 -0
  13. package/dist/build/codegen/execution.js +2 -0
  14. package/dist/build/codegen/merge.d.ts +0 -1
  15. package/dist/build/codegen/merge.js +0 -1
  16. package/dist/build/codegen/wrangler.d.ts +32 -5
  17. package/dist/build/codegen/wrangler.js +77 -21
  18. package/dist/build/configuration/invocation-timeout.d.ts +2 -0
  19. package/dist/build/configuration/invocation-timeout.js +9 -0
  20. package/dist/build/configuration/request-limit.d.ts +2 -0
  21. package/dist/build/configuration/request-limit.js +9 -0
  22. package/dist/build/configuration/router.d.ts +7 -0
  23. package/dist/build/configuration/router.js +17 -0
  24. package/dist/build/configuration/settings.d.ts +6 -0
  25. package/dist/build/configuration/settings.js +40 -0
  26. package/dist/build/configuration.d.ts +4 -0
  27. package/dist/build/configuration.js +4 -0
  28. package/dist/build/frontend/files.d.ts +19 -0
  29. package/dist/build/frontend/files.js +99 -0
  30. package/dist/build/frontend/readiness.d.ts +16 -0
  31. package/dist/build/frontend/readiness.js +21 -0
  32. package/dist/build/frontend/revision.d.ts +5 -0
  33. package/dist/build/frontend/revision.js +14 -0
  34. package/dist/build/frontend/vite.d.ts +14 -0
  35. package/dist/build/frontend/vite.js +42 -0
  36. package/dist/build/frontend/vite.process.d.ts +7 -0
  37. package/dist/build/frontend/vite.process.js +65 -0
  38. package/dist/build/frontend/vite.runner.d.ts +1 -0
  39. package/dist/build/frontend/vite.runner.js +155 -0
  40. package/dist/build/index.d.ts +12 -16
  41. package/dist/build/index.js +12 -16
  42. package/dist/build/material.d.ts +10 -0
  43. package/dist/build/material.js +25 -0
  44. package/dist/build/metafile.d.ts +5 -0
  45. package/dist/build/metafile.js +14 -0
  46. package/dist/build/qualification.d.ts +5 -0
  47. package/dist/build/qualification.js +7 -0
  48. package/dist/build/roots.d.ts +2 -0
  49. package/dist/build/roots.js +34 -0
  50. package/dist/build/worker/codegen/entry.d.ts +9 -0
  51. package/dist/build/worker/codegen/entry.js +65 -0
  52. package/dist/build/worker/codegen/literal.d.ts +28 -0
  53. package/dist/build/worker/codegen/literal.js +136 -0
  54. package/dist/build/worker/codegen/service.d.ts +14 -0
  55. package/dist/build/worker/codegen/service.js +57 -0
  56. package/dist/build/worker/execution.prepare.d.ts +20 -0
  57. package/dist/build/worker/execution.prepare.js +129 -0
  58. package/dist/build/worker/media-type.d.ts +1 -0
  59. package/dist/build/worker/media-type.js +20 -0
  60. package/dist/build/worker/modules.d.ts +20 -0
  61. package/dist/build/worker/modules.js +32 -0
  62. package/dist/build/worker/specifier.d.ts +5 -0
  63. package/dist/build/worker/specifier.js +15 -0
  64. package/dist/build/worker/upload.d.ts +23 -0
  65. package/dist/build/worker/upload.js +42 -0
  66. package/dist/cloudflare.d.ts +1 -34
  67. package/dist/cloudflare.js +1 -205
  68. package/dist/hosting/activation.d.ts +38 -0
  69. package/dist/hosting/activation.js +109 -0
  70. package/dist/hosting/assets.d.ts +14 -0
  71. package/dist/hosting/assets.js +53 -0
  72. package/dist/hosting/bounded.d.ts +10 -0
  73. package/dist/hosting/bounded.js +32 -0
  74. package/dist/hosting/bytes.d.ts +6 -0
  75. package/dist/hosting/bytes.js +25 -0
  76. package/dist/hosting/client.d.ts +144 -0
  77. package/dist/hosting/client.js +491 -0
  78. package/dist/hosting/dispatcher/cron.d.mts +10 -0
  79. package/dist/hosting/dispatcher/cron.mjs +135 -0
  80. package/dist/hosting/dispatcher/deployments.d.mts +26 -0
  81. package/dist/hosting/dispatcher/deployments.mjs +158 -0
  82. package/dist/hosting/dispatcher/dispatcher.d.mts +17 -0
  83. package/dist/hosting/dispatcher/dispatcher.mjs +76 -0
  84. package/dist/hosting/dispatcher/env.d.mts +51 -0
  85. package/dist/hosting/dispatcher/failure.d.mts +4 -0
  86. package/dist/hosting/dispatcher/failure.mjs +15 -0
  87. package/dist/hosting/dispatcher/index.d.mts +4 -0
  88. package/dist/hosting/dispatcher/index.mjs +8 -0
  89. package/dist/hosting/dispatcher/modules.d.ts +24 -0
  90. package/dist/hosting/dispatcher/modules.js +55 -0
  91. package/dist/hosting/dispatcher/services.d.mts +23 -0
  92. package/dist/hosting/dispatcher/services.mjs +202 -0
  93. package/dist/hosting/identity.d.ts +15 -0
  94. package/dist/hosting/identity.js +36 -0
  95. package/dist/hosting/index.d.ts +34 -0
  96. package/dist/hosting/index.js +32 -0
  97. package/dist/hosting/kv.d.ts +90 -0
  98. package/dist/hosting/kv.js +207 -0
  99. package/dist/hosting/listing.d.ts +34 -0
  100. package/dist/hosting/listing.js +50 -0
  101. package/dist/hosting/names.d.ts +16 -0
  102. package/dist/hosting/names.js +28 -0
  103. package/dist/hosting/provision/account.d.ts +11 -0
  104. package/dist/hosting/provision/account.js +86 -0
  105. package/dist/hosting/provision/dispatcher.d.ts +42 -0
  106. package/dist/hosting/provision/dispatcher.js +99 -0
  107. package/dist/hosting/provision/ingress.d.ts +12 -0
  108. package/dist/hosting/provision/ingress.js +31 -0
  109. package/dist/hosting/provision/plan.d.ts +143 -0
  110. package/dist/hosting/provision/plan.js +246 -0
  111. package/dist/hosting/provision/routing.d.ts +82 -0
  112. package/dist/hosting/provision/routing.js +226 -0
  113. package/dist/hosting/readiness.d.ts +53 -0
  114. package/dist/hosting/readiness.js +82 -0
  115. package/dist/hosting/refusal.d.ts +28 -0
  116. package/dist/hosting/refusal.js +13 -0
  117. package/dist/hosting/retirement.d.ts +70 -0
  118. package/dist/hosting/retirement.js +107 -0
  119. package/dist/hosting/retry-after.d.ts +6 -0
  120. package/dist/hosting/retry-after.js +55 -0
  121. package/dist/hosting/script.d.ts +186 -0
  122. package/dist/hosting/script.js +324 -0
  123. package/dist/hosting/testing/fake-cloudflare.d.ts +212 -0
  124. package/dist/hosting/testing/fake-cloudflare.js +757 -0
  125. package/dist/hosting/testing/index.d.ts +6 -0
  126. package/dist/hosting/testing/index.js +6 -0
  127. package/dist/hosting/time.d.ts +4 -0
  128. package/dist/hosting/time.js +20 -0
  129. package/dist/identity/binding.d.ts +2 -0
  130. package/dist/identity/binding.js +2 -0
  131. package/dist/identity/material.d.ts +6 -0
  132. package/dist/identity/material.js +29 -0
  133. package/dist/index.d.ts +14 -13
  134. package/dist/index.js +13 -12
  135. package/dist/namespace/configure.d.ts +22 -0
  136. package/dist/namespace/configure.js +199 -0
  137. package/dist/namespace/coordinates.d.ts +15 -0
  138. package/dist/namespace/coordinates.js +49 -0
  139. package/dist/namespace/deploy-release.d.ts +53 -0
  140. package/dist/namespace/deploy-release.js +389 -0
  141. package/dist/namespace/hosting.d.ts +29 -0
  142. package/dist/namespace/hosting.js +120 -0
  143. package/dist/namespace/index.d.ts +12 -0
  144. package/dist/namespace/index.js +12 -0
  145. package/dist/namespace/list.d.ts +18 -0
  146. package/dist/namespace/list.js +63 -0
  147. package/dist/namespace/readiness.d.ts +30 -0
  148. package/dist/namespace/readiness.js +31 -0
  149. package/dist/namespace/record.d.ts +21 -0
  150. package/dist/namespace/record.js +53 -0
  151. package/dist/params.d.ts +63 -66
  152. package/dist/params.js +0 -1
  153. package/dist/release/build.d.ts +35 -0
  154. package/dist/release/build.js +44 -0
  155. package/dist/release/deployment.d.ts +44 -0
  156. package/dist/release/deployment.js +141 -0
  157. package/dist/release/index.d.ts +2 -0
  158. package/dist/release/index.js +2 -0
  159. package/dist/worker/binary.d.ts +21 -0
  160. package/dist/worker/binary.js +31 -0
  161. package/dist/worker/build-digest.d.ts +10 -0
  162. package/dist/worker/build-digest.js +22 -0
  163. package/dist/worker/cache.d.ts +28 -0
  164. package/dist/worker/cache.js +70 -0
  165. package/dist/worker/durable.d.ts +3 -0
  166. package/dist/worker/durable.js +5 -0
  167. package/dist/worker/entry.d.ts +47 -0
  168. package/dist/worker/entry.js +135 -0
  169. package/dist/worker/fetch.d.ts +11 -0
  170. package/dist/worker/fetch.js +31 -0
  171. package/dist/worker/front.d.ts +56 -0
  172. package/dist/worker/front.js +59 -0
  173. package/dist/worker/frontend.d.ts +4 -0
  174. package/dist/worker/frontend.js +83 -0
  175. package/dist/worker/identity.d.ts +7 -0
  176. package/dist/worker/identity.js +23 -0
  177. package/dist/worker/index.d.ts +6 -48
  178. package/dist/worker/index.js +6 -186
  179. package/dist/worker/restate.d.ts +6 -0
  180. package/dist/worker/restate.js +6 -0
  181. package/dist/worker/settings.d.ts +47 -0
  182. package/dist/worker/settings.js +163 -0
  183. package/dist/wrangler/bundle.d.ts +10 -0
  184. package/dist/wrangler/bundle.js +27 -0
  185. package/dist/wrangler/index.d.ts +3 -0
  186. package/dist/wrangler/index.js +3 -0
  187. package/dist/wrangler/process.d.ts +15 -0
  188. package/dist/wrangler/process.js +113 -0
  189. package/dist/wrangler/type-generation.d.ts +6 -0
  190. package/dist/wrangler/type-generation.js +19 -0
  191. package/package.json +47 -22
  192. package/template/astrale.config.ts +43 -29
  193. package/dist/build/codegen/identity.d.ts +0 -10
  194. package/dist/build/codegen/identity.d.ts.map +0 -1
  195. package/dist/build/codegen/identity.js +0 -32
  196. package/dist/build/codegen/identity.js.map +0 -1
  197. package/dist/build/codegen/merge.d.ts.map +0 -1
  198. package/dist/build/codegen/merge.js.map +0 -1
  199. package/dist/build/codegen/worker.d.ts +0 -12
  200. package/dist/build/codegen/worker.d.ts.map +0 -1
  201. package/dist/build/codegen/worker.js +0 -40
  202. package/dist/build/codegen/worker.js.map +0 -1
  203. package/dist/build/codegen/wrangler.d.ts.map +0 -1
  204. package/dist/build/codegen/wrangler.js.map +0 -1
  205. package/dist/build/frontend.d.ts +0 -26
  206. package/dist/build/frontend.d.ts.map +0 -1
  207. package/dist/build/frontend.js +0 -263
  208. package/dist/build/frontend.js.map +0 -1
  209. package/dist/build/index.d.ts.map +0 -1
  210. package/dist/build/index.js.map +0 -1
  211. package/dist/build/parse-output.d.ts +0 -27
  212. package/dist/build/parse-output.d.ts.map +0 -1
  213. package/dist/build/parse-output.js +0 -58
  214. package/dist/build/parse-output.js.map +0 -1
  215. package/dist/build/prepare.d.ts +0 -18
  216. package/dist/build/prepare.d.ts.map +0 -1
  217. package/dist/build/prepare.js +0 -117
  218. package/dist/build/prepare.js.map +0 -1
  219. package/dist/build/worker.d.ts +0 -15
  220. package/dist/build/worker.d.ts.map +0 -1
  221. package/dist/build/worker.js +0 -21
  222. package/dist/build/worker.js.map +0 -1
  223. package/dist/build/wrangler-cli.d.ts +0 -86
  224. package/dist/build/wrangler-cli.d.ts.map +0 -1
  225. package/dist/build/wrangler-cli.js +0 -275
  226. package/dist/build/wrangler-cli.js.map +0 -1
  227. package/dist/cloudflare.d.ts.map +0 -1
  228. package/dist/cloudflare.js.map +0 -1
  229. package/dist/index.d.ts.map +0 -1
  230. package/dist/index.js.map +0 -1
  231. package/dist/params.d.ts.map +0 -1
  232. package/dist/params.js.map +0 -1
  233. package/dist/worker/index.d.ts.map +0 -1
  234. package/dist/worker/index.js.map +0 -1
  235. package/src/build/codegen/identity.ts +0 -40
  236. package/src/build/codegen/merge.ts +0 -92
  237. package/src/build/codegen/worker.ts +0 -53
  238. package/src/build/codegen/wrangler.ts +0 -127
  239. package/src/build/frontend.ts +0 -324
  240. package/src/build/index.ts +0 -29
  241. package/src/build/parse-output.ts +0 -60
  242. package/src/build/prepare.ts +0 -161
  243. package/src/build/worker.ts +0 -37
  244. package/src/build/wrangler-cli.ts +0 -362
  245. package/src/cloudflare.ts +0 -251
  246. package/src/index.ts +0 -21
  247. package/src/params.ts +0 -92
  248. package/src/worker/index.ts +0 -276
  249. package/src/worker/tsconfig.json +0 -10
@@ -0,0 +1,155 @@
1
+ import { readdir, writeFile } from 'node:fs/promises';
2
+ import { createRequire } from 'node:module';
3
+ import { isAbsolute, join, resolve } from 'node:path';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ const CONFIG_FILES = Object.freeze([
6
+ 'vite.config.js',
7
+ 'vite.config.mjs',
8
+ 'vite.config.ts',
9
+ 'vite.config.cjs',
10
+ 'vite.config.mts',
11
+ 'vite.config.cts',
12
+ ]);
13
+ await main();
14
+ async function main() {
15
+ const [output, evidence, configured, addressed] = process.argv.slice(2);
16
+ if (output === undefined || evidence === undefined) {
17
+ throw new TypeError('Vite preparation runner arguments are invalid.');
18
+ }
19
+ const projectDir = process.cwd();
20
+ const vite = await projectVite(projectDir);
21
+ const sources = new Set();
22
+ const named = new Set();
23
+ let publicDir = false;
24
+ let environment = {
25
+ directory: false,
26
+ mode: 'production',
27
+ };
28
+ const config = configured === '' || configured === undefined ? undefined : configured;
29
+ await vite.build({
30
+ logLevel: 'silent',
31
+ ...(config === undefined
32
+ ? {}
33
+ : { configFile: isAbsolute(config) ? config : resolve(projectDir, config) }),
34
+ build: { outDir: output, emptyOutDir: true },
35
+ plugins: [
36
+ {
37
+ name: 'astrale:preparation-sources',
38
+ configResolved(value) {
39
+ publicDir = value.publicDir;
40
+ environment = { directory: value.envDir, mode: value.mode };
41
+ for (const path of value.configFileDependencies)
42
+ sources.add(path);
43
+ },
44
+ transform(_source, id) {
45
+ const path = physicalModulePath(id);
46
+ if (path !== undefined)
47
+ sources.add(path);
48
+ },
49
+ // The bundler is the only party that knows which outputs it content-addressed: a served path
50
+ // is safe to retain exactly when its name changes with its bytes. Reading that here, from
51
+ // the build that produced them, is what keeps the answer a fact rather than a guess about
52
+ // directory layout or file naming.
53
+ generateBundle(options, bundle) {
54
+ for (const [fileName, entry] of Object.entries(bundle)) {
55
+ if (addressedName(options, entry))
56
+ named.add(fileName);
57
+ }
58
+ },
59
+ },
60
+ ],
61
+ });
62
+ for (const path of configCandidates(projectDir, config))
63
+ sources.add(path);
64
+ for (const path of environmentCandidates(environment))
65
+ sources.add(path);
66
+ if (publicDir !== false)
67
+ await collectTree(publicDir, sources);
68
+ await writeFile(evidence, JSON.stringify([...sources]));
69
+ if (addressed !== undefined)
70
+ await writeFile(addressed, JSON.stringify([...named].sort()));
71
+ }
72
+ /**
73
+ * Whether this output's name carries a content hash.
74
+ *
75
+ * Two facts are required, and each is necessary. The output must carry a `name`, which the bundler
76
+ * sets only for the outputs it named itself: a plugin emitting an explicit `fileName` bypasses the
77
+ * template entirely, and such a file can sit anywhere, including beside the bundle's own output. And
78
+ * the template that was applied must embed `[hash]`, since a project is free to strip it.
79
+ *
80
+ * Anything else leaves the answer unknown, and unknown must read as "not content-addressed": losing
81
+ * the optimization costs a revalidation, while claiming it wrongly serves a stale file for as long
82
+ * as the header says, with no way to recall it.
83
+ */
84
+ function addressedName(options, entry) {
85
+ if (typeof entry.name !== 'string')
86
+ return false;
87
+ const template = entry.type === 'asset'
88
+ ? options.assetFileNames
89
+ : entry.isEntry === true
90
+ ? options.entryFileNames
91
+ : options.chunkFileNames;
92
+ return typeof template === 'string' && template.includes('[hash]');
93
+ }
94
+ function environmentCandidates(input) {
95
+ const directory = input.directory;
96
+ if (directory === false)
97
+ return [];
98
+ return ['.env', '.env.local', `.env.${input.mode}`, `.env.${input.mode}.local`].map((name) => join(directory, name));
99
+ }
100
+ function physicalModulePath(id) {
101
+ if (id.startsWith('\0'))
102
+ return undefined;
103
+ const path = id.replace(/[?#].*$/u, '');
104
+ if (path.length === 0)
105
+ return undefined;
106
+ if (path.startsWith('file:')) {
107
+ try {
108
+ return fileURLToPath(path);
109
+ }
110
+ catch {
111
+ return undefined;
112
+ }
113
+ }
114
+ return isAbsolute(path) ? path : undefined;
115
+ }
116
+ async function projectVite(projectDir) {
117
+ try {
118
+ const manifest = createRequire(join(projectDir, 'package.json')).resolve('vite/package.json');
119
+ const entry = createRequire(manifest).resolve('vite');
120
+ return (await import(pathToFileURL(entry).href));
121
+ }
122
+ catch (cause) {
123
+ throw new TypeError('Vite frontend requires a project-local Vite package.', { cause });
124
+ }
125
+ }
126
+ function configCandidates(projectDir, configured) {
127
+ if (configured !== undefined) {
128
+ return [isAbsolute(configured) ? configured : resolve(projectDir, configured)];
129
+ }
130
+ return CONFIG_FILES.map((name) => join(projectDir, name));
131
+ }
132
+ async function collectTree(path, output) {
133
+ output.add(path);
134
+ let entries;
135
+ try {
136
+ entries = await readdir(path, { withFileTypes: true });
137
+ }
138
+ catch (cause) {
139
+ if (errorCode(cause) === 'ENOENT')
140
+ return;
141
+ throw cause;
142
+ }
143
+ for (const entry of entries) {
144
+ const child = join(path, entry.name);
145
+ if (entry.isDirectory())
146
+ await collectTree(child, output);
147
+ else if (entry.isFile())
148
+ output.add(child);
149
+ }
150
+ }
151
+ function errorCode(input) {
152
+ return input !== null && typeof input === 'object' && 'code' in input
153
+ ? String(Reflect.get(input, 'code'))
154
+ : undefined;
155
+ }
@@ -1,16 +1,12 @@
1
- /**
2
- * `@astrale-os/adapter-cloudflare/build` — the shared Cloudflare-Workers build
3
- * toolkit, exposed for sibling deploy adapters (e.g.
4
- * `@astrale-os/adapter-astrale`).
5
- *
6
- * This is the "compile a `defineDomain` into a Cloudflare Workers bundle + run
7
- * local dev" surface that every Cloudflare-Workers deploy strategy shares,
8
- * regardless of WHERE the bundle ultimately ships. It is NOT part of the public
9
- * adapter API (`@astrale-os/adapter-cloudflare`) — it's the seam two adapters
10
- * build on so the codegen/bundling/dev logic lives in exactly one place.
11
- */
12
- export { buildFrontend, FRONTEND_STAGE_DIR, watchFrontend, type FrontendWatchHandle, type FrontendWatchSubscribe, type FrontendWatchSubscription, } from './frontend.js';
13
- export { logTo, prepare } from './prepare.js';
14
- export { buildCloudflareWorker, type CloudflareWorkerBuild } from './worker.js';
15
- export { bulkPutSecrets, runWranglerBundle, runWranglerDeploy, runWranglerDev, runWranglerTypes, } from './wrangler-cli.js';
16
- //# sourceMappingURL=index.d.ts.map
1
+ export { generateBuildMaterialModule } from './material.js';
2
+ export { cloudflareWorkerBundler } from './bundler.js';
3
+ export { bundleUpload, type BundleUpload } from './worker/upload.js';
4
+ export { workerBuildManifest, type WorkerUpload } from '../release/build.js';
5
+ export { isAdapterVar, resolveRouter, workerSettings } from './configuration.js';
6
+ export { encodeWorkerSettings, SETTINGS_BINDING } from '../worker/settings.js';
7
+ export { GENERATED_WORKER_RUNTIME } from './codegen/wrangler.js';
8
+ export { frontendFiles } from './frontend/files.js';
9
+ export { verifyWorkerFrontend } from './frontend/readiness.js';
10
+ export { qualifyWorkerBundle } from './qualification.js';
11
+ export { assertSingletonRuntimeRoots } from './roots.js';
12
+ export { runWranglerBundle, runWranglerTypes } from '../wrangler/index.js';
@@ -1,16 +1,12 @@
1
- /**
2
- * `@astrale-os/adapter-cloudflare/build` — the shared Cloudflare-Workers build
3
- * toolkit, exposed for sibling deploy adapters (e.g.
4
- * `@astrale-os/adapter-astrale`).
5
- *
6
- * This is the "compile a `defineDomain` into a Cloudflare Workers bundle + run
7
- * local dev" surface that every Cloudflare-Workers deploy strategy shares,
8
- * regardless of WHERE the bundle ultimately ships. It is NOT part of the public
9
- * adapter API (`@astrale-os/adapter-cloudflare`) — it's the seam two adapters
10
- * build on so the codegen/bundling/dev logic lives in exactly one place.
11
- */
12
- export { buildFrontend, FRONTEND_STAGE_DIR, watchFrontend, } from './frontend.js';
13
- export { logTo, prepare } from './prepare.js';
14
- export { buildCloudflareWorker } from './worker.js';
15
- export { bulkPutSecrets, runWranglerBundle, runWranglerDeploy, runWranglerDev, runWranglerTypes, } from './wrangler-cli.js';
16
- //# sourceMappingURL=index.js.map
1
+ export { generateBuildMaterialModule } from './material.js';
2
+ export { cloudflareWorkerBundler } from './bundler.js';
3
+ export { bundleUpload } from './worker/upload.js';
4
+ export { workerBuildManifest } from '../release/build.js';
5
+ export { isAdapterVar, resolveRouter, workerSettings } from './configuration.js';
6
+ export { encodeWorkerSettings, SETTINGS_BINDING } from '../worker/settings.js';
7
+ export { GENERATED_WORKER_RUNTIME } from './codegen/wrangler.js';
8
+ export { frontendFiles } from './frontend/files.js';
9
+ export { verifyWorkerFrontend } from './frontend/readiness.js';
10
+ export { qualifyWorkerBundle } from './qualification.js';
11
+ export { assertSingletonRuntimeRoots } from './roots.js';
12
+ export { runWranglerBundle, runWranglerTypes } from '../wrangler/index.js';
@@ -0,0 +1,10 @@
1
+ import type { Build } from '@astrale-os/sdk/deployment/build';
2
+ /**
3
+ * Generate a TypeScript module exporting `loadBuildMaterial()` for a custom Worker entrypoint.
4
+ *
5
+ * The module uses the same verified shared literal as the adapter's generated Service. Its
6
+ * factory allocates the material on demand; `generatedCloudflareWorkerEntry` seals it before use.
7
+ * Write the source at build time and import its factory from the Worker. No authoring or
8
+ * compression dependency is needed by the generated module at runtime.
9
+ */
10
+ export declare function generateBuildMaterialModule(build: Build): string;
@@ -0,0 +1,25 @@
1
+ import { generatedMaterial } from '@astrale-os/sdk/deployment/build';
2
+ import { sharedLiteral, verifySharedLiteral } from './worker/codegen/literal.js';
3
+ /**
4
+ * Generate a TypeScript module exporting `loadBuildMaterial()` for a custom Worker entrypoint.
5
+ *
6
+ * The module uses the same verified shared literal as the adapter's generated Service. Its
7
+ * factory allocates the material on demand; `generatedCloudflareWorkerEntry` seals it before use.
8
+ * Write the source at build time and import its factory from the Worker. No authoring or
9
+ * compression dependency is needed by the generated module at runtime.
10
+ */
11
+ export function generateBuildMaterialModule(build) {
12
+ const generated = generatedMaterial(build);
13
+ const literal = sharedLiteral(generated);
14
+ verifySharedLiteral(literal, generated);
15
+ // An empty shared array otherwise has an implicit any[] type in strict TypeScript consumers.
16
+ const declarations = literal.declarations.map((line) => ` ${line.replace(/ = \[\]$/, ': readonly [] = []')}`);
17
+ return `// AUTO-GENERATED by @astrale-os/adapter-cloudflare — do not edit.
18
+ import type { GeneratedBuildMaterial } from '@astrale-os/sdk/deployment/build'
19
+
20
+ export function loadBuildMaterial(): GeneratedBuildMaterial {
21
+ ${declarations.join('\n')}
22
+ return ${literal.expression} as unknown as GeneratedBuildMaterial
23
+ }
24
+ `;
25
+ }
@@ -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,9 @@
1
+ import type { BuildMaterial } from '@astrale-os/sdk/deployment/build';
2
+ export interface ExecutionEntryOptions {
3
+ readonly frontSpecifier?: string;
4
+ readonly frontend?: BuildMaterial['frontend'];
5
+ readonly frontendRevision?: string;
6
+ readonly frontendAddressed?: readonly string[];
7
+ }
8
+ /** Generate the isolate-startup entry that realizes the heavy Service on first request. */
9
+ export declare function generateExecutionEntry(serviceSpecifier: string, options?: ExecutionEntryOptions): string;
@@ -0,0 +1,65 @@
1
+ /** Generate the isolate-startup entry that realizes the heavy Service on first request. */
2
+ export function generateExecutionEntry(serviceSpecifier, options = {}) {
3
+ const frontSpecifier = options.frontSpecifier ?? '@astrale-os/adapter-cloudflare/worker/front';
4
+ const configuration = [
5
+ options.frontend === undefined
6
+ ? ''
7
+ : ` frontend: ${JSON.stringify(options.frontend)} as const satisfies NonNullable<BuildMaterial['frontend']>,\n`,
8
+ options.frontendRevision === undefined
9
+ ? ''
10
+ : ` frontendRevision: ${JSON.stringify(options.frontendRevision)},\n`,
11
+ options.frontendAddressed === undefined
12
+ ? ''
13
+ : ` frontendAddressed: ${JSON.stringify(options.frontendAddressed)},\n`,
14
+ ].join('');
15
+ // Keep adapter types on the resolved value import: consumers may only depend on adapter-astrale.
16
+ // esbuild subtracts value-import paths from its minifier histogram, but not standalone type
17
+ // imports, so an absolute type-only path would make bundle bytes depend on the checkout.
18
+ return `// AUTO-GENERATED by @astrale-os/adapter-cloudflare — do not edit.
19
+ import type { BuildMaterial } from '@astrale-os/sdk/deployment/build'
20
+
21
+ import { cloudflareFrontDoor, type CloudflareAdapterBindings, type CloudflareWorker } from ${JSON.stringify(frontSpecifier)}
22
+
23
+ type WorkerEnv = CloudflareEnv & CloudflareAdapterBindings
24
+
25
+ const SERVICE_SPECIFIER = ${JSON.stringify(serviceSpecifier)}
26
+ let servicePromise: Promise<CloudflareWorker<CloudflareEnv>> | undefined
27
+
28
+ // Admission and public frontend files answer from startup, so a View's document never waits for
29
+ // the execution Service to load. Each such file starts that load for the calls the View makes next.
30
+ const frontDoor = cloudflareFrontDoor<WorkerEnv>({
31
+ ${configuration}})
32
+
33
+ export default {
34
+ async fetch(request: Request, environment: WorkerEnv, context: ExecutionContext) {
35
+ const admission = await frontDoor.admit(request, environment)
36
+ if (admission.kind === 'refused') return admission.response
37
+ if (admission.kind === 'frontend') {
38
+ context.waitUntil(prepare())
39
+ return admission.response
40
+ }
41
+ return (await service()).fetch(request, environment, context)
42
+ },
43
+ }
44
+
45
+ function service(): Promise<CloudflareWorker<CloudflareEnv>> {
46
+ return (servicePromise ??= import(SERVICE_SPECIFIER).then((loaded: unknown) => {
47
+ if (loaded === null || typeof loaded !== 'object') invalid()
48
+ const worker = Reflect.get(loaded, 'default') as unknown
49
+ if (worker === null || typeof worker !== 'object' || typeof Reflect.get(worker, 'fetch') !== 'function') invalid()
50
+ return worker as CloudflareWorker<CloudflareEnv>
51
+ }))
52
+ }
53
+
54
+ function prepare(): Promise<void> {
55
+ // A failure stays memoized by the Service and resurfaces on the request that needs it.
56
+ return service().then((worker) => worker.prepare?.()).then(ignore, ignore)
57
+ }
58
+
59
+ function ignore(): void {}
60
+
61
+ function invalid(): never {
62
+ throw new TypeError('Cloudflare execution Service module is invalid.')
63
+ }
64
+ `;
65
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Emit one JavaScript literal that shares every structurally identical subtree.
3
+ *
4
+ * Build material reaches a Worker as an inline literal, and JSON has no references, so a flat
5
+ * literal repeats every repeated subtree. A compiled Domain is dominated by pattern automata, and
6
+ * a handful of distinct expressions account for dozens of identical copies of one automaton, so
7
+ * the flat form allocates an order of magnitude more objects than the value actually contains.
8
+ *
9
+ * Sharing changes nothing an observer can see. The literal evaluates to a value that serialises
10
+ * identically, so the material digest taken over it is unchanged, and the material is deeply
11
+ * frozen before anything reads it, so no holder can observe the aliasing.
12
+ */
13
+ export interface SharedLiteral {
14
+ /** `const` declarations for each subtree used more than once, each one after its children. */
15
+ readonly declarations: readonly string[];
16
+ /** The expression for the value itself, referencing those declarations. */
17
+ readonly expression: string;
18
+ }
19
+ export declare function sharedLiteral(value: unknown, prefix?: string): SharedLiteral;
20
+ /**
21
+ * Refuse a literal that does not evaluate back to the value it was built from.
22
+ *
23
+ * Emitting source is the one part of sharing that a type cannot check, so the generator proves its
24
+ * own output instead: a defect becomes a failed build rather than a Worker that boots with the
25
+ * wrong material. The comparison is the serialised form, which is also what the material digest
26
+ * is taken over.
27
+ */
28
+ export declare function verifySharedLiteral(literal: SharedLiteral, expected: unknown): void;
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Emit one JavaScript literal that shares every structurally identical subtree.
3
+ *
4
+ * Build material reaches a Worker as an inline literal, and JSON has no references, so a flat
5
+ * literal repeats every repeated subtree. A compiled Domain is dominated by pattern automata, and
6
+ * a handful of distinct expressions account for dozens of identical copies of one automaton, so
7
+ * the flat form allocates an order of magnitude more objects than the value actually contains.
8
+ *
9
+ * Sharing changes nothing an observer can see. The literal evaluates to a value that serialises
10
+ * identically, so the material digest taken over it is unchanged, and the material is deeply
11
+ * frozen before anything reads it, so no holder can observe the aliasing.
12
+ */
13
+ /**
14
+ * An object literal assigns the prototype for a plain `__proto__` key, where a computed key
15
+ * defines an own property, as JSON does.
16
+ */
17
+ function memberKey(key) {
18
+ return key === '__proto__' ? `[${JSON.stringify(key)}]:` : `${JSON.stringify(key)}:`;
19
+ }
20
+ export function sharedLiteral(value, prefix = '$m') {
21
+ const subtrees = [];
22
+ const references = [];
23
+ const byShape = new Map();
24
+ const byIdentity = new WeakMap();
25
+ /** A piece list, plus the shape text that decides whether two subtrees are the same one. */
26
+ const encode = (input) => {
27
+ const pieces = [];
28
+ const shape = [];
29
+ const open = Array.isArray(input) ? '[' : '{';
30
+ pieces.push(open);
31
+ shape.push(open);
32
+ const keys = Array.isArray(input) ? undefined : Object.keys(input);
33
+ const values = Array.isArray(input)
34
+ ? input
35
+ : (keys ?? []).map((key) => input[key]);
36
+ for (const [index, element] of values.entries()) {
37
+ if (index > 0) {
38
+ pieces.push(',');
39
+ shape.push(',');
40
+ }
41
+ if (keys !== undefined) {
42
+ const member = memberKey(keys[index] ?? '');
43
+ pieces.push(member);
44
+ shape.push(member);
45
+ }
46
+ if (element !== null && typeof element === 'object') {
47
+ const id = identify(element);
48
+ pieces.push({ subtree: id });
49
+ // Quoted JSON text can never start with `#`, so a reference is unambiguous here.
50
+ shape.push(`#${id}`);
51
+ }
52
+ else {
53
+ const text = JSON.stringify(element);
54
+ if (text === undefined) {
55
+ throw new TypeError(`Build material cannot hold a ${typeof element} value.`);
56
+ }
57
+ pieces.push(text);
58
+ shape.push(text);
59
+ }
60
+ }
61
+ const close = Array.isArray(input) ? ']' : '}';
62
+ pieces.push(close);
63
+ shape.push(close);
64
+ return { pieces, shape: shape.join('') };
65
+ };
66
+ const identify = (input) => {
67
+ const known = byIdentity.get(input);
68
+ if (known !== undefined) {
69
+ references[known] += 1;
70
+ return known;
71
+ }
72
+ const { pieces, shape } = encode(input);
73
+ const existing = byShape.get(shape);
74
+ if (existing !== undefined) {
75
+ byIdentity.set(input, existing);
76
+ references[existing] += 1;
77
+ return existing;
78
+ }
79
+ const id = subtrees.length;
80
+ subtrees.push({ pieces });
81
+ references.push(1);
82
+ byShape.set(shape, id);
83
+ byIdentity.set(input, id);
84
+ return id;
85
+ };
86
+ if (value === null || typeof value !== 'object') {
87
+ const text = JSON.stringify(value);
88
+ if (text === undefined)
89
+ throw new TypeError('Build material cannot hold an undefined value.');
90
+ return { declarations: [], expression: text };
91
+ }
92
+ const root = identify(value);
93
+ references[root] -= 1; // The root is the expression itself, not a nested reference.
94
+ // A nested subtree always carries a lower identifier than the one holding it, so ascending
95
+ // order declares every name before its first use.
96
+ const declarations = [];
97
+ const names = new Map();
98
+ const inlined = new Map();
99
+ for (const [id, subtree] of subtrees.entries()) {
100
+ const text = subtree.pieces
101
+ .map((piece) => typeof piece === 'string'
102
+ ? piece
103
+ : (names.get(piece.subtree) ?? inlined.get(piece.subtree) ?? ''))
104
+ .join('');
105
+ if (id !== root && (references[id] ?? 0) > 1) {
106
+ const name = `${prefix}${id}`;
107
+ names.set(id, name);
108
+ declarations.push(`const ${name} = ${text}`);
109
+ }
110
+ else {
111
+ inlined.set(id, text);
112
+ }
113
+ }
114
+ return { declarations, expression: names.get(root) ?? inlined.get(root) ?? 'null' };
115
+ }
116
+ /**
117
+ * Refuse a literal that does not evaluate back to the value it was built from.
118
+ *
119
+ * Emitting source is the one part of sharing that a type cannot check, so the generator proves its
120
+ * own output instead: a defect becomes a failed build rather than a Worker that boots with the
121
+ * wrong material. The comparison is the serialised form, which is also what the material digest
122
+ * is taken over.
123
+ */
124
+ export function verifySharedLiteral(literal, expected) {
125
+ const source = `${literal.declarations.join('\n')}\nreturn ${literal.expression}`;
126
+ let produced;
127
+ try {
128
+ produced = new Function(source)();
129
+ }
130
+ catch (cause) {
131
+ throw new TypeError('Generated Build material literal is not valid JavaScript.', { cause });
132
+ }
133
+ if (JSON.stringify(produced) !== JSON.stringify(expected)) {
134
+ throw new TypeError('Generated Build material literal does not reproduce its material.');
135
+ }
136
+ }
@@ -0,0 +1,14 @@
1
+ import type { Build } from '@astrale-os/sdk/deployment/build';
2
+ /** Build inputs only: the deployment binds every environment value (`deploymentSettings`). */
3
+ export interface ExecutionCodegenOptions {
4
+ readonly origin: string;
5
+ readonly runtimeSpecifier: string;
6
+ readonly workerSpecifier?: string;
7
+ readonly build: Build;
8
+ readonly frontendRevision?: string;
9
+ readonly frontendAddressed?: readonly string[];
10
+ /** Static Schema capability; deployment options remain in bindings. */
11
+ readonly durable?: boolean;
12
+ readonly restateSpecifier?: string;
13
+ }
14
+ export declare function generateExecutionService(options: ExecutionCodegenOptions): string;
@@ -0,0 +1,57 @@
1
+ import { generatedMaterial } from '@astrale-os/sdk/deployment/build';
2
+ import { sharedLiteral, verifySharedLiteral } from './literal.js';
3
+ export function generateExecutionService(options) {
4
+ const workerSpecifier = options.workerSpecifier ?? '@astrale-os/adapter-cloudflare/worker';
5
+ const generated = generatedMaterial(options.build);
6
+ // JSON has no references, so a flat literal repeats every repeated subtree. A compiled Domain
7
+ // is dominated by pattern automata, of which a few expressions account for dozens of identical
8
+ // copies, so sharing them cuts what the isolate allocates and seals by an order of magnitude.
9
+ const material = sharedLiteral(generated);
10
+ verifySharedLiteral(material, generated);
11
+ const materialDeclarations = material.declarations.map((line) => ` ${line}\n`).join('');
12
+ const durableImports = options.durable === true
13
+ ? `import { restateServing } from ${JSON.stringify(workerSpecifier)}
14
+ import { isCanonicalDurableRequest } from '@astrale-os/sdk/execution'
15
+ // A variable specifier preserves the engine as a separate deployed module.
16
+ const RESTATE_SPECIFIER = ${JSON.stringify(options.restateSpecifier ?? './restate.mjs')}
17
+ `
18
+ : '';
19
+ const frontend = generated.material.frontend === undefined
20
+ ? ''
21
+ : ` frontend: ${JSON.stringify(generated.material.frontend)} as const satisfies NonNullable<BuildMaterial['frontend']>,\n`;
22
+ // Keep adapter types on the resolved value import. A standalone absolute type import leaks
23
+ // checkout characters into esbuild's minifier histogram, making identical Services differ.
24
+ return `// AUTO-GENERATED by @astrale-os/adapter-cloudflare — do not edit.
25
+ // Domain origin: ${options.origin}
26
+ import type { BuildMaterial, GeneratedBuildMaterial } from '@astrale-os/sdk/deployment/build'
27
+
28
+ import { generatedCloudflareWorkerEntry, type CloudflareAdapterBindings } from ${JSON.stringify(workerSpecifier)}
29
+ import { decodeSigningIdentity, deploymentSettings, runtimeBindings } from ${JSON.stringify(workerSpecifier)}
30
+
31
+ ${durableImports}
32
+ type WorkerEnv = CloudflareEnv & CloudflareAdapterBindings & {
33
+ readonly ASTRALE_SIGNING_IDENTITY: string
34
+ }
35
+ type RuntimeEnv = Omit<WorkerEnv, 'ASTRALE_SIGNING_IDENTITY'>
36
+
37
+ export default generatedCloudflareWorkerEntry<WorkerEnv, RuntimeEnv>()({
38
+ ${frontend}${options.frontendRevision === undefined ? '' : ` frontendRevision: ${JSON.stringify(options.frontendRevision)},\n`}${options.frontendAddressed === undefined ? '' : ` frontendAddressed: ${JSON.stringify(options.frontendAddressed)},\n`} load: async () => {
39
+ ${materialDeclarations} return {
40
+ runtime: (await import(${JSON.stringify(options.runtimeSpecifier)})).default,
41
+ material: ${material.expression} as unknown as GeneratedBuildMaterial,
42
+ }
43
+ },
44
+ privateKey: (env) => decodeSigningIdentity(env.ASTRALE_SIGNING_IDENTITY),
45
+ resolveEnvironment: runtimeBindings,
46
+ settings: deploymentSettings,
47
+ selfBinding: (env) => env.SELF,${options.durable === true
48
+ ? `
49
+ durable: async (env, request, options) => {
50
+ if (!isCanonicalDurableRequest(request)) return undefined
51
+ const restate = await import(RESTATE_SPECIFIER)
52
+ return restateServing(restate, request, options)
53
+ },`
54
+ : ''}
55
+ })
56
+ `;
57
+ }