@astrale-os/adapter-cloudflare 0.5.0-beta.19 → 0.5.0-beta.191

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 (242) hide show
  1. package/README.md +241 -2
  2. package/dist/adapter.d.ts +8 -17
  3. package/dist/adapter.js +41 -310
  4. package/dist/build/bundle/admit.d.ts +3 -0
  5. package/dist/build/bundle/admit.js +46 -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 +4 -2
  11. package/dist/build/closure.js +7 -2
  12. package/dist/build/codegen/execution.d.ts +3 -14
  13. package/dist/build/codegen/execution.js +2 -41
  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 +30 -6
  17. package/dist/build/codegen/wrangler.js +76 -20
  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 -9
  27. package/dist/build/configuration.js +4 -26
  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 +10 -5
  41. package/dist/build/index.js +10 -5
  42. package/dist/build/material.d.ts +10 -0
  43. package/dist/build/material.js +25 -0
  44. package/dist/build/metafile.d.ts +0 -1
  45. package/dist/build/metafile.js +0 -1
  46. package/dist/build/qualification.d.ts +0 -1
  47. package/dist/build/qualification.js +0 -1
  48. package/dist/build/roots.d.ts +0 -1
  49. package/dist/build/roots.js +0 -1
  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 +128 -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 -2
  67. package/dist/cloudflare.js +1 -2
  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 +59 -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/build-digest.d.ts +10 -0
  160. package/dist/worker/build-digest.js +22 -0
  161. package/dist/worker/cache.d.ts +28 -0
  162. package/dist/worker/cache.js +70 -0
  163. package/dist/worker/durable.d.ts +3 -0
  164. package/dist/worker/durable.js +5 -0
  165. package/dist/worker/entry.d.ts +38 -25
  166. package/dist/worker/entry.js +82 -110
  167. package/dist/worker/fetch.d.ts +0 -1
  168. package/dist/worker/fetch.js +0 -1
  169. package/dist/worker/front.d.ts +56 -0
  170. package/dist/worker/front.js +59 -0
  171. package/dist/worker/frontend.d.ts +4 -0
  172. package/dist/worker/frontend.js +83 -0
  173. package/dist/worker/identity.d.ts +7 -0
  174. package/dist/worker/identity.js +23 -0
  175. package/dist/worker/index.d.ts +5 -1
  176. package/dist/worker/index.js +5 -1
  177. package/dist/worker/restate.d.ts +6 -0
  178. package/dist/worker/restate.js +6 -0
  179. package/dist/worker/settings.d.ts +47 -0
  180. package/dist/worker/settings.js +161 -0
  181. package/dist/wrangler/bundle.d.ts +10 -0
  182. package/dist/wrangler/bundle.js +27 -0
  183. package/dist/wrangler/index.d.ts +3 -0
  184. package/dist/wrangler/index.js +3 -0
  185. package/dist/wrangler/process.d.ts +15 -0
  186. package/dist/wrangler/process.js +102 -0
  187. package/dist/wrangler/type-generation.d.ts +6 -0
  188. package/dist/wrangler/type-generation.js +19 -0
  189. package/package.json +40 -16
  190. package/template/astrale.config.ts +43 -31
  191. package/dist/adapter.d.ts.map +0 -1
  192. package/dist/adapter.js.map +0 -1
  193. package/dist/build/artifact.d.ts +0 -9
  194. package/dist/build/artifact.d.ts.map +0 -1
  195. package/dist/build/artifact.js +0 -145
  196. package/dist/build/artifact.js.map +0 -1
  197. package/dist/build/closure.d.ts.map +0 -1
  198. package/dist/build/closure.js.map +0 -1
  199. package/dist/build/codegen/execution.d.ts.map +0 -1
  200. package/dist/build/codegen/execution.js.map +0 -1
  201. package/dist/build/codegen/identity.d.ts +0 -10
  202. package/dist/build/codegen/identity.d.ts.map +0 -1
  203. package/dist/build/codegen/identity.js +0 -32
  204. package/dist/build/codegen/identity.js.map +0 -1
  205. package/dist/build/codegen/merge.d.ts.map +0 -1
  206. package/dist/build/codegen/merge.js.map +0 -1
  207. package/dist/build/codegen/wrangler.d.ts.map +0 -1
  208. package/dist/build/codegen/wrangler.js.map +0 -1
  209. package/dist/build/configuration.d.ts.map +0 -1
  210. package/dist/build/configuration.js.map +0 -1
  211. package/dist/build/frontend-v1.d.ts +0 -17
  212. package/dist/build/frontend-v1.d.ts.map +0 -1
  213. package/dist/build/frontend-v1.js +0 -134
  214. package/dist/build/frontend-v1.js.map +0 -1
  215. package/dist/build/index.d.ts.map +0 -1
  216. package/dist/build/index.js.map +0 -1
  217. package/dist/build/metafile.d.ts.map +0 -1
  218. package/dist/build/metafile.js.map +0 -1
  219. package/dist/build/parse-output.d.ts +0 -27
  220. package/dist/build/parse-output.d.ts.map +0 -1
  221. package/dist/build/parse-output.js +0 -58
  222. package/dist/build/parse-output.js.map +0 -1
  223. package/dist/build/qualification.d.ts.map +0 -1
  224. package/dist/build/qualification.js.map +0 -1
  225. package/dist/build/roots.d.ts.map +0 -1
  226. package/dist/build/roots.js.map +0 -1
  227. package/dist/build/wrangler-cli.d.ts +0 -115
  228. package/dist/build/wrangler-cli.d.ts.map +0 -1
  229. package/dist/build/wrangler-cli.js +0 -377
  230. package/dist/build/wrangler-cli.js.map +0 -1
  231. package/dist/cloudflare.d.ts.map +0 -1
  232. package/dist/cloudflare.js.map +0 -1
  233. package/dist/index.d.ts.map +0 -1
  234. package/dist/index.js.map +0 -1
  235. package/dist/params.d.ts.map +0 -1
  236. package/dist/params.js.map +0 -1
  237. package/dist/worker/entry.d.ts.map +0 -1
  238. package/dist/worker/entry.js.map +0 -1
  239. package/dist/worker/fetch.d.ts.map +0 -1
  240. package/dist/worker/fetch.js.map +0 -1
  241. package/dist/worker/index.d.ts.map +0 -1
  242. package/dist/worker/index.js.map +0 -1
@@ -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
+ }
@@ -0,0 +1,20 @@
1
+ import type { BundleContext } from '@astrale-os/sdk/deployment/adapter';
2
+ export declare const RELEASE_ENTRY = "bundle/index.mjs";
3
+ export declare const RELEASE_SERVICE = "bundle/service.mjs";
4
+ export declare const RELEASE_RESTATE = "bundle/restate.mjs";
5
+ /** A deployed module retained outside the startup bundle. */
6
+ export interface ReleaseModule {
7
+ readonly kind: 'esm' | 'wasm';
8
+ readonly path: string;
9
+ readonly content: Uint8Array;
10
+ }
11
+ export declare function prepareExecution(input: {
12
+ readonly context: BundleContext;
13
+ readonly directory: string;
14
+ readonly frontendRevision?: string;
15
+ readonly frontendAddressed?: readonly string[];
16
+ }): Promise<{
17
+ readonly entry: Uint8Array;
18
+ readonly modules: readonly ReleaseModule[];
19
+ }>;
20
+ export declare function declaresDurable(build: BundleContext['build']): boolean;
@@ -0,0 +1,128 @@
1
+ import { generatedMaterial } from '@astrale-os/sdk/deployment/build';
2
+ import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { dirname, join, relative, resolve } from 'node:path';
4
+ import { SIGNING_IDENTITY_BINDING } from '../../identity/binding.js';
5
+ import { runWranglerBundle } from '../../wrangler/bundle.js';
6
+ import { admitDurableEngineBundle, admitWorkerBundle } from '../bundle/admit.js';
7
+ import { generateExecutionEntry, generateExecutionService } from '../codegen/execution.js';
8
+ import { generateWranglerConfig } from '../codegen/wrangler.js';
9
+ import { qualifyWorkerBundle } from '../qualification.js';
10
+ import { workerModules } from './modules.js';
11
+ import { frontModuleSpecifier, restateModuleSpecifier, workerModuleSpecifier } from './specifier.js';
12
+ export const RELEASE_ENTRY = 'bundle/index.mjs';
13
+ export const RELEASE_SERVICE = 'bundle/service.mjs';
14
+ export const RELEASE_RESTATE = 'bundle/restate.mjs';
15
+ /**
16
+ * Bundling sees the adapter base configuration only: no Environment, route, var, router or
17
+ * `wrangler` overlay reaches the bytes, so every Environment of one source bundles identically.
18
+ */
19
+ const BUNDLE_WORKER_NAME = 'astrale-domain';
20
+ export async function prepareExecution(input) {
21
+ const runtimePath = resolve(input.context.projectDir, input.context.runtime.reference.path);
22
+ const runtimeSpecifier = moduleSpecifier(relative(input.directory, runtimePath));
23
+ const workerSpecifier = workerModuleSpecifier();
24
+ const serviceSource = generateExecutionService({
25
+ origin: input.context.build.schema.compiled.root.origin,
26
+ runtimeSpecifier,
27
+ workerSpecifier,
28
+ build: input.context.build,
29
+ ...(declaresDurable(input.context.build)
30
+ ? { durable: true, restateSpecifier: './restate.mjs' }
31
+ : {}),
32
+ ...(input.frontendRevision === undefined ? {} : { frontendRevision: input.frontendRevision }),
33
+ ...(input.frontendAddressed === undefined
34
+ ? {}
35
+ : { frontendAddressed: input.frontendAddressed }),
36
+ });
37
+ const modules = [];
38
+ const bundle = async (name, path, source, admit) => {
39
+ const sourcePath = join(input.directory, `${name}.gen.ts`);
40
+ await writeFile(sourcePath, source);
41
+ const configPath = join(input.directory, `wrangler.${name}.prepare.jsonc`);
42
+ await writeFile(configPath, generateWranglerConfig({
43
+ workerName: BUNDLE_WORKER_NAME,
44
+ main: `./${name}.gen.ts`,
45
+ secretBindings: [SIGNING_IDENTITY_BINDING],
46
+ selfBinding: false,
47
+ }));
48
+ const output = join(input.directory, `dist-${name}`);
49
+ await rm(output, { recursive: true, force: true });
50
+ const emitted = await runWranglerBundle({
51
+ projectDir: input.context.projectDir,
52
+ configPath,
53
+ outDir: output,
54
+ signal: input.context.signal,
55
+ });
56
+ await qualifyWorkerBundle({
57
+ metafilePath: emitted.metafilePath,
58
+ inputRoot: dirname(configPath),
59
+ });
60
+ await admit(emitted.bundlePath);
61
+ const content = new Uint8Array(await readFile(emitted.bundlePath));
62
+ await mkdir(dirname(join(input.directory, path)), { recursive: true });
63
+ await writeFile(join(input.directory, path), content);
64
+ modules.push(Object.freeze({ path, kind: 'esm', content }));
65
+ // Imported WASM modules are emitted beside their owner under content-hashed names.
66
+ for (const file of (await readdir(output)).filter((name) => name.endsWith('.wasm')).sort()) {
67
+ const wasmPath = `${dirname(path)}/${file}`;
68
+ const content = new Uint8Array(await readFile(join(output, file)));
69
+ await writeFile(join(input.directory, wasmPath), content);
70
+ if (!modules.some((module) => module.path === wasmPath)) {
71
+ modules.push(Object.freeze({ path: wasmPath, kind: 'wasm', content }));
72
+ }
73
+ }
74
+ };
75
+ await bundle('service', RELEASE_SERVICE, serviceSource, admitWorkerBundle);
76
+ if (declaresDurable(input.context.build)) {
77
+ await bundle('restate', RELEASE_RESTATE,
78
+ // Wrangler requires a default export to classify an independently bundled ESM entry.
79
+ `export { createEndpointHandler, workflow, TerminalError, CancelledError } from ${JSON.stringify(restateModuleSpecifier())}\nexport default {}\n`, admitDurableEngineBundle);
80
+ }
81
+ const sourcePath = join(input.directory, 'worker.gen.ts');
82
+ const frontend = generatedMaterial(input.context.build).material.frontend;
83
+ await writeFile(sourcePath, generateExecutionEntry('./service.mjs', {
84
+ frontSpecifier: frontModuleSpecifier(),
85
+ ...(frontend === undefined ? {} : { frontend }),
86
+ ...(input.frontendRevision === undefined ? {} : { frontendRevision: input.frontendRevision }),
87
+ ...(input.frontendAddressed === undefined
88
+ ? {}
89
+ : { frontendAddressed: input.frontendAddressed }),
90
+ }));
91
+ const configPath = join(input.directory, 'wrangler.prepare.jsonc');
92
+ await writeFile(configPath, generateWranglerConfig({
93
+ workerName: BUNDLE_WORKER_NAME,
94
+ secretBindings: [SIGNING_IDENTITY_BINDING],
95
+ modules: workerModules({ entrypoint: 'worker.gen.ts', modules }),
96
+ selfBinding: false,
97
+ }));
98
+ const output = join(input.directory, 'dist-prepare');
99
+ await rm(output, { recursive: true, force: true });
100
+ const emitted = await runWranglerBundle({
101
+ projectDir: input.context.projectDir,
102
+ configPath,
103
+ outDir: output,
104
+ signal: input.context.signal,
105
+ });
106
+ await qualifyWorkerBundle({
107
+ metafilePath: emitted.metafilePath,
108
+ inputRoot: dirname(configPath),
109
+ });
110
+ await admitWorkerBundle(emitted.bundlePath);
111
+ return Object.freeze({
112
+ entry: new Uint8Array(await readFile(emitted.bundlePath)),
113
+ modules: Object.freeze(modules),
114
+ });
115
+ }
116
+ function moduleSpecifier(input) {
117
+ const normalized = input.split('\\').join('/');
118
+ return normalized.startsWith('.') ? normalized : `./${normalized}`;
119
+ }
120
+ export function declaresDurable(build) {
121
+ const compiled = build.schema.compiled;
122
+ const root = compiled.closure.find(({ origin }) => origin === compiled.root.origin);
123
+ if (root === undefined)
124
+ return false;
125
+ return (root.definitions.functions.some((definition) => definition.execution?.durable === true) ||
126
+ root.definitions.classes.some((definition) => 'methods' in definition &&
127
+ definition.methods.some((method) => method.execution?.durable === true)));
128
+ }
@@ -0,0 +1 @@
1
+ export declare function inferMediaType(path: string): string | undefined;
@@ -0,0 +1,20 @@
1
+ export function inferMediaType(path) {
2
+ const extension = path.split('.').at(-1)?.toLowerCase();
3
+ return extension === undefined ? undefined : MEDIA_TYPES[extension];
4
+ }
5
+ const MEDIA_TYPES = Object.freeze({
6
+ html: 'text/html; charset=utf-8',
7
+ js: 'text/javascript; charset=utf-8',
8
+ mjs: 'text/javascript; charset=utf-8',
9
+ css: 'text/css; charset=utf-8',
10
+ json: 'application/json; charset=utf-8',
11
+ svg: 'image/svg+xml',
12
+ png: 'image/png',
13
+ jpg: 'image/jpeg',
14
+ jpeg: 'image/jpeg',
15
+ webp: 'image/webp',
16
+ ico: 'image/x-icon',
17
+ woff: 'font/woff',
18
+ woff2: 'font/woff2',
19
+ wasm: 'application/wasm',
20
+ });
@@ -0,0 +1,20 @@
1
+ import type { WorkerModuleKind } from '@astrale-os/sdk/deployment/worker';
2
+ type WranglerModuleType = 'ESModule' | 'CompiledWasm' | 'Text' | 'Data';
3
+ /**
4
+ * Project one admitted Worker module inventory into Wrangler's relative module discovery. Rules
5
+ * follow module kinds, so the projection does not depend on the inventory's order.
6
+ */
7
+ export declare function workerModules(worker: {
8
+ readonly entrypoint: string;
9
+ readonly modules: readonly {
10
+ readonly path: string;
11
+ readonly kind: WorkerModuleKind;
12
+ }[];
13
+ }): {
14
+ readonly baseDir: string;
15
+ readonly rules: readonly {
16
+ readonly type: WranglerModuleType;
17
+ readonly globs: readonly string[];
18
+ }[];
19
+ };
20
+ export {};
@@ -0,0 +1,32 @@
1
+ import { posix } from 'node:path';
2
+ const TYPES = Object.freeze({
3
+ esm: 'ESModule',
4
+ wasm: 'CompiledWasm',
5
+ text: 'Text',
6
+ data: 'Data',
7
+ });
8
+ /**
9
+ * Project one admitted Worker module inventory into Wrangler's relative module discovery. Rules
10
+ * follow module kinds, so the projection does not depend on the inventory's order.
11
+ */
12
+ export function workerModules(worker) {
13
+ const directory = posix.dirname(worker.entrypoint);
14
+ const groups = new Map();
15
+ for (const module of worker.modules) {
16
+ if (module.path === worker.entrypoint)
17
+ continue;
18
+ const relative = posix.relative(directory, module.path);
19
+ if (relative === '' || relative === '..' || relative.startsWith('../')) {
20
+ throw new TypeError('Cloudflare Worker module escapes its entrypoint directory.');
21
+ }
22
+ const type = TYPES[module.kind];
23
+ const globs = groups.get(type) ?? [];
24
+ globs.push(relative);
25
+ groups.set(type, globs);
26
+ }
27
+ const rules = Object.values(TYPES).flatMap((type) => {
28
+ const globs = groups.get(type);
29
+ return globs === undefined ? [] : [Object.freeze({ type, globs: Object.freeze(globs) })];
30
+ });
31
+ return Object.freeze({ baseDir: `./${directory}`, rules: Object.freeze(rules) });
32
+ }
@@ -0,0 +1,5 @@
1
+ export declare function workerModuleSpecifier(): string;
2
+ /** The isolate-startup module, which must stay free of the execution Service's dependencies. */
3
+ export declare function frontModuleSpecifier(): string;
4
+ /** The engine's Workers build, resolved from this adapter so a Domain needs no engine dependency. */
5
+ export declare function restateModuleSpecifier(): string;
@@ -0,0 +1,15 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ const workerModule = import.meta.resolve('@astrale-os/adapter-cloudflare/worker');
3
+ const restateModule = import.meta.resolve('@astrale-os/adapter-cloudflare/worker/restate');
4
+ const frontModule = import.meta.resolve('@astrale-os/adapter-cloudflare/worker/front');
5
+ export function workerModuleSpecifier() {
6
+ return fileURLToPath(workerModule);
7
+ }
8
+ /** The isolate-startup module, which must stay free of the execution Service's dependencies. */
9
+ export function frontModuleSpecifier() {
10
+ return fileURLToPath(frontModule);
11
+ }
12
+ /** The engine's Workers build, resolved from this adapter so a Domain needs no engine dependency. */
13
+ export function restateModuleSpecifier() {
14
+ return fileURLToPath(restateModule);
15
+ }
@@ -0,0 +1,23 @@
1
+ import type { Bundle } from '@astrale-os/sdk/deployment/adapter';
2
+ import { type WorkerUpload } from '../../release/build.js';
3
+ /**
4
+ * The portable upload of one Bundle of the Cloudflare Worker bundler, as an immutable deployment's
5
+ * host receives it: the entry and the modules it loads (ES modules and their WASM), and the
6
+ * frontend as Worker assets with the media type their extension names. Its build digest is the Bundle's own, so the host that
7
+ * recomputes it from these bytes finds exactly the build the release names; any other Bundle is
8
+ * refused.
9
+ */
10
+ export declare function bundleUpload(bundle: Bundle): BundleUpload;
11
+ /** The Worker upload of one Bundle, with each module's kind and each asset's media type. */
12
+ export interface BundleUpload extends WorkerUpload {
13
+ readonly modules: readonly {
14
+ readonly name: string;
15
+ readonly kind: 'esm' | 'wasm';
16
+ readonly bytes: Uint8Array;
17
+ }[];
18
+ readonly assets?: readonly {
19
+ readonly path: string;
20
+ readonly bytes: Uint8Array;
21
+ readonly contentType?: string;
22
+ }[];
23
+ }
@@ -0,0 +1,42 @@
1
+ import { buildDigest } from '@astrale-os/sdk/deployment/build/manifest';
2
+ import { workerBuildManifest } from '../../release/build.js';
3
+ import { bundledWorker } from '../bundler.js';
4
+ import { RELEASE_ENTRY } from './execution.prepare.js';
5
+ import { inferMediaType } from './media-type.js';
6
+ /**
7
+ * The portable upload of one Bundle of the Cloudflare Worker bundler, as an immutable deployment's
8
+ * host receives it: the entry and the modules it loads (ES modules and their WASM), and the
9
+ * frontend as Worker assets with the media type their extension names. Its build digest is the Bundle's own, so the host that
10
+ * recomputes it from these bytes finds exactly the build the release names; any other Bundle is
11
+ * refused.
12
+ */
13
+ export function bundleUpload(bundle) {
14
+ const worker = bundledWorker(bundle, bundle.build);
15
+ const root = bundle.build.schema.compiled.root;
16
+ const upload = Object.freeze({
17
+ origin: root.origin,
18
+ revision: root.revision,
19
+ bundle: bundle.manifest.schema.bundle,
20
+ entry: RELEASE_ENTRY,
21
+ modules: Object.freeze([
22
+ Object.freeze({ name: RELEASE_ENTRY, kind: 'esm', bytes: worker.entry }),
23
+ ...worker.modules.map((module) => Object.freeze({ name: module.path, kind: module.kind, bytes: module.content })),
24
+ ]),
25
+ ...(worker.frontend.length === 0
26
+ ? {}
27
+ : {
28
+ assets: Object.freeze(worker.frontend.map((file) => {
29
+ const contentType = inferMediaType(file.path);
30
+ return Object.freeze({
31
+ path: `/${file.path}`,
32
+ bytes: file.bytes(),
33
+ ...(contentType === undefined ? {} : { contentType }),
34
+ });
35
+ })),
36
+ }),
37
+ });
38
+ if (buildDigest(workerBuildManifest(upload)) !== bundle.digest) {
39
+ throw new TypeError('Worker upload of the Bundle does not reproduce its build digest.');
40
+ }
41
+ return upload;
42
+ }
@@ -1,2 +1 @@
1
- export { cloudflare, cloudflareWithDependencies, type CloudflareDependencies } from './adapter.js';
2
- //# sourceMappingURL=cloudflare.d.ts.map
1
+ export { cloudflare } from './adapter.js';
@@ -1,2 +1 @@
1
- export { cloudflare, cloudflareWithDependencies } from './adapter.js';
2
- //# sourceMappingURL=cloudflare.js.map
1
+ export { cloudflare } from './adapter.js';