@astrale-os/adapter-cloudflare 0.5.0-beta.20 → 0.5.0-beta.201

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 (201) hide show
  1. package/README.md +245 -0
  2. package/dist/adapter.d.ts +9 -15
  3. package/dist/adapter.js +43 -129
  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 +4 -1
  11. package/dist/build/closure.js +7 -1
  12. package/dist/build/codegen/execution.d.ts +3 -13
  13. package/dist/build/codegen/execution.js +2 -44
  14. package/dist/build/codegen/wrangler.d.ts +28 -10
  15. package/dist/build/codegen/wrangler.js +71 -21
  16. package/dist/build/configuration/invocation-timeout.d.ts +2 -0
  17. package/dist/build/configuration/invocation-timeout.js +9 -0
  18. package/dist/build/configuration/request-limit.d.ts +2 -0
  19. package/dist/build/configuration/request-limit.js +9 -0
  20. package/dist/build/configuration/router.d.ts +7 -0
  21. package/dist/build/configuration/router.js +17 -0
  22. package/dist/build/configuration/settings.d.ts +6 -0
  23. package/dist/build/configuration/settings.js +40 -0
  24. package/dist/build/configuration.d.ts +4 -9
  25. package/dist/build/configuration.js +4 -40
  26. package/dist/build/frontend/files.d.ts +19 -0
  27. package/dist/build/frontend/files.js +99 -0
  28. package/dist/build/frontend/readiness.d.ts +16 -0
  29. package/dist/build/frontend/readiness.js +21 -0
  30. package/dist/build/frontend/revision.d.ts +5 -0
  31. package/dist/build/frontend/revision.js +14 -0
  32. package/dist/build/frontend/vite.d.ts +14 -0
  33. package/dist/build/frontend/vite.js +42 -0
  34. package/dist/build/frontend/vite.process.d.ts +7 -0
  35. package/dist/build/frontend/vite.process.js +65 -0
  36. package/dist/build/frontend/vite.runner.d.ts +1 -0
  37. package/dist/build/frontend/vite.runner.js +155 -0
  38. package/dist/build/index.d.ts +10 -6
  39. package/dist/build/index.js +10 -6
  40. package/dist/build/material.d.ts +10 -0
  41. package/dist/build/material.js +25 -0
  42. package/dist/build/worker/codegen/entry.d.ts +9 -0
  43. package/dist/build/worker/codegen/entry.js +65 -0
  44. package/dist/build/worker/codegen/literal.d.ts +28 -0
  45. package/dist/build/worker/codegen/literal.js +136 -0
  46. package/dist/build/worker/codegen/service.d.ts +14 -0
  47. package/dist/build/worker/codegen/service.js +57 -0
  48. package/dist/build/worker/execution.prepare.d.ts +20 -0
  49. package/dist/build/worker/execution.prepare.js +129 -0
  50. package/dist/build/worker/media-type.d.ts +1 -0
  51. package/dist/build/worker/media-type.js +20 -0
  52. package/dist/build/worker/modules.d.ts +20 -0
  53. package/dist/build/worker/modules.js +32 -0
  54. package/dist/build/worker/specifier.d.ts +5 -0
  55. package/dist/build/worker/specifier.js +15 -0
  56. package/dist/build/worker/upload.d.ts +23 -0
  57. package/dist/build/worker/upload.js +42 -0
  58. package/dist/hosting/activation.d.ts +38 -0
  59. package/dist/hosting/activation.js +109 -0
  60. package/dist/hosting/assets.d.ts +14 -0
  61. package/dist/hosting/assets.js +53 -0
  62. package/dist/hosting/bounded.d.ts +10 -0
  63. package/dist/hosting/bounded.js +32 -0
  64. package/dist/hosting/bytes.d.ts +6 -0
  65. package/dist/hosting/bytes.js +25 -0
  66. package/dist/hosting/client.d.ts +144 -0
  67. package/dist/hosting/client.js +491 -0
  68. package/dist/hosting/dispatcher/cron.d.mts +10 -0
  69. package/dist/hosting/dispatcher/cron.mjs +135 -0
  70. package/dist/hosting/dispatcher/deployments.d.mts +26 -0
  71. package/dist/hosting/dispatcher/deployments.mjs +158 -0
  72. package/dist/hosting/dispatcher/dispatcher.d.mts +17 -0
  73. package/dist/hosting/dispatcher/dispatcher.mjs +76 -0
  74. package/dist/hosting/dispatcher/env.d.mts +51 -0
  75. package/dist/hosting/dispatcher/failure.d.mts +4 -0
  76. package/dist/hosting/dispatcher/failure.mjs +15 -0
  77. package/dist/hosting/dispatcher/index.d.mts +4 -0
  78. package/dist/hosting/dispatcher/index.mjs +8 -0
  79. package/dist/hosting/dispatcher/modules.d.ts +24 -0
  80. package/dist/hosting/dispatcher/modules.js +55 -0
  81. package/dist/hosting/dispatcher/services.d.mts +23 -0
  82. package/dist/hosting/dispatcher/services.mjs +202 -0
  83. package/dist/hosting/identity.d.ts +15 -0
  84. package/dist/hosting/identity.js +36 -0
  85. package/dist/hosting/index.d.ts +34 -0
  86. package/dist/hosting/index.js +32 -0
  87. package/dist/hosting/kv.d.ts +90 -0
  88. package/dist/hosting/kv.js +207 -0
  89. package/dist/hosting/listing.d.ts +34 -0
  90. package/dist/hosting/listing.js +50 -0
  91. package/dist/hosting/names.d.ts +16 -0
  92. package/dist/hosting/names.js +28 -0
  93. package/dist/hosting/provision/account.d.ts +11 -0
  94. package/dist/hosting/provision/account.js +86 -0
  95. package/dist/hosting/provision/dispatcher.d.ts +42 -0
  96. package/dist/hosting/provision/dispatcher.js +99 -0
  97. package/dist/hosting/provision/ingress.d.ts +12 -0
  98. package/dist/hosting/provision/ingress.js +31 -0
  99. package/dist/hosting/provision/plan.d.ts +143 -0
  100. package/dist/hosting/provision/plan.js +246 -0
  101. package/dist/hosting/provision/routing.d.ts +82 -0
  102. package/dist/hosting/provision/routing.js +226 -0
  103. package/dist/hosting/readiness.d.ts +53 -0
  104. package/dist/hosting/readiness.js +82 -0
  105. package/dist/hosting/refusal.d.ts +28 -0
  106. package/dist/hosting/refusal.js +13 -0
  107. package/dist/hosting/retirement.d.ts +70 -0
  108. package/dist/hosting/retirement.js +107 -0
  109. package/dist/hosting/retry-after.d.ts +6 -0
  110. package/dist/hosting/retry-after.js +55 -0
  111. package/dist/hosting/script.d.ts +186 -0
  112. package/dist/hosting/script.js +324 -0
  113. package/dist/hosting/testing/fake-cloudflare.d.ts +212 -0
  114. package/dist/hosting/testing/fake-cloudflare.js +757 -0
  115. package/dist/hosting/testing/index.d.ts +6 -0
  116. package/dist/hosting/testing/index.js +6 -0
  117. package/dist/hosting/time.d.ts +4 -0
  118. package/dist/hosting/time.js +20 -0
  119. package/dist/identity/binding.d.ts +1 -1
  120. package/dist/identity/binding.js +1 -1
  121. package/dist/identity/material.d.ts +1 -2
  122. package/dist/identity/material.js +5 -18
  123. package/dist/index.d.ts +14 -12
  124. package/dist/index.js +13 -11
  125. package/dist/namespace/configure.d.ts +22 -0
  126. package/dist/namespace/configure.js +199 -0
  127. package/dist/namespace/coordinates.d.ts +15 -0
  128. package/dist/namespace/coordinates.js +49 -0
  129. package/dist/namespace/deploy-release.d.ts +53 -0
  130. package/dist/namespace/deploy-release.js +389 -0
  131. package/dist/namespace/hosting.d.ts +29 -0
  132. package/dist/namespace/hosting.js +120 -0
  133. package/dist/namespace/index.d.ts +12 -0
  134. package/dist/namespace/index.js +12 -0
  135. package/dist/namespace/list.d.ts +18 -0
  136. package/dist/namespace/list.js +63 -0
  137. package/dist/namespace/readiness.d.ts +30 -0
  138. package/dist/namespace/readiness.js +31 -0
  139. package/dist/namespace/record.d.ts +21 -0
  140. package/dist/namespace/record.js +53 -0
  141. package/dist/params.d.ts +60 -76
  142. package/dist/release/build.d.ts +35 -0
  143. package/dist/release/build.js +44 -0
  144. package/dist/release/deployment.d.ts +44 -0
  145. package/dist/release/deployment.js +141 -0
  146. package/dist/release/index.d.ts +2 -2
  147. package/dist/release/index.js +2 -2
  148. package/dist/worker/binary.d.ts +21 -0
  149. package/dist/worker/binary.js +31 -0
  150. package/dist/worker/build-digest.d.ts +10 -0
  151. package/dist/worker/build-digest.js +22 -0
  152. package/dist/worker/cache.d.ts +28 -0
  153. package/dist/worker/cache.js +70 -0
  154. package/dist/worker/durable.d.ts +3 -0
  155. package/dist/worker/durable.js +5 -0
  156. package/dist/worker/entry.d.ts +38 -25
  157. package/dist/worker/entry.js +87 -109
  158. package/dist/worker/front.d.ts +56 -0
  159. package/dist/worker/front.js +59 -0
  160. package/dist/worker/frontend.d.ts +4 -0
  161. package/dist/worker/frontend.js +83 -0
  162. package/dist/worker/index.d.ts +4 -1
  163. package/dist/worker/index.js +4 -1
  164. package/dist/worker/restate.d.ts +6 -0
  165. package/dist/worker/restate.js +6 -0
  166. package/dist/worker/settings.d.ts +47 -0
  167. package/dist/worker/settings.js +163 -0
  168. package/dist/wrangler/bundle.d.ts +10 -0
  169. package/dist/wrangler/bundle.js +27 -0
  170. package/dist/wrangler/index.d.ts +3 -0
  171. package/dist/wrangler/index.js +3 -0
  172. package/dist/wrangler/process.d.ts +15 -0
  173. package/dist/wrangler/process.js +113 -0
  174. package/dist/wrangler/type-generation.d.ts +6 -0
  175. package/dist/wrangler/type-generation.js +19 -0
  176. package/package.json +39 -12
  177. package/template/astrale.config.ts +42 -36
  178. package/dist/build/artifact.d.ts +0 -8
  179. package/dist/build/artifact.js +0 -179
  180. package/dist/build/codegen/gateway.d.ts +0 -1
  181. package/dist/build/codegen/gateway.js +0 -7
  182. package/dist/build/frontend-v1.d.ts +0 -16
  183. package/dist/build/frontend-v1.js +0 -133
  184. package/dist/build/parse-output.d.ts +0 -26
  185. package/dist/build/parse-output.js +0 -57
  186. package/dist/build/wrangler-cli.d.ts +0 -105
  187. package/dist/build/wrangler-cli.js +0 -448
  188. package/dist/deploy/deploy.d.ts +0 -17
  189. package/dist/deploy/deploy.js +0 -207
  190. package/dist/deploy/index.d.ts +0 -1
  191. package/dist/deploy/index.js +0 -1
  192. package/dist/identity/secret.d.ts +0 -3
  193. package/dist/identity/secret.js +0 -7
  194. package/dist/identity/source.d.ts +0 -26
  195. package/dist/identity/source.js +0 -98
  196. package/dist/release/namespace.d.ts +0 -2
  197. package/dist/release/namespace.js +0 -6
  198. package/dist/release/target.d.ts +0 -2
  199. package/dist/release/target.js +0 -9
  200. package/dist/worker/gateway.d.ts +0 -15
  201. package/dist/worker/gateway.js +0 -26
package/README.md CHANGED
@@ -9,3 +9,248 @@ npm install @astrale-os/sdk@beta @astrale-os/adapter-cloudflare@beta
9
9
  ```
10
10
 
11
11
  Bare installs return to stable releases when the package set is promoted and npm `latest` advances.
12
+
13
+ One `cloudflare()` value configures one Project Environment in a Workers for Platforms dispatch
14
+ namespace. Each release becomes one immutable deployment on your own Cloudflare account or on a
15
+ platform's. A deploy never installs: install the URL it prints with
16
+ `astrale domain install <url> -i <instance>`.
17
+
18
+ Generated Worker modules are minified by default, including separately loaded runtime modules.
19
+ The Environment's `wrangler` overlay cannot change minification: every Environment of one source
20
+ must emit the same JavaScript bytes. `cloudflare({ wrangler: { minify: false } })` is rejected.
21
+
22
+ ## Host it yourself
23
+
24
+ Anyone with a Cloudflare account, Workers for Platforms and a domain of their own can host
25
+ immutable deployments, with no Astrale infrastructure:
26
+
27
+ 1. **A domain.** Add a zone to Cloudflare and pick a routing domain under it dedicated to the
28
+ deployments, such as `deploy.example.dev`: every deployment answers at
29
+ `https://<label>.deploy.example.dev`. Nothing else may serve a host at, under or above it, and
30
+ its wildcard name needs an edge certificate (Advanced Certificate Manager, or Total TLS).
31
+ 2. **A token.** Create an API token with Workers Scripts Edit, Workers KV Storage Edit, Workers
32
+ Routes Edit and Zone DNS Edit on that zone. Export it as `CLOUDFLARE_API_TOKEN`, with
33
+ `CLOUDFLARE_ACCOUNT_ID` (and `CLOUDFLARE_ZONE_ID` when the zone cannot be found from the domain).
34
+ 3. **The Environment.**
35
+
36
+ ```ts
37
+ production: {
38
+ deployment: cloudflare({
39
+ namespace: { name: 'my-deployments', routingDomain: 'deploy.example.dev' },
40
+ secrets: '.env.production',
41
+ }),
42
+ },
43
+ ```
44
+
45
+ 4. **Provision once.** `astrale-domain cloudflare plan production` reads the account and prints
46
+ what provisioning does and what blocks it; `astrale-domain cloudflare init production`
47
+ provisions it (both are commands this adapter declares; `--json` prints the result):
48
+ the dispatch namespace, its routing KV, the dispatcher Worker (`<name>-dispatcher`, or
49
+ `--dispatcher <worker>`), a proxied `AAAA 100::` record `*.<domain>` and the route
50
+ `*.<domain>/*` to the dispatcher, then checks that a never-deployed host reaches it over HTTPS.
51
+ It is idempotent: a rerun adopts what exists and uploads the dispatcher again.
52
+ 5. **Deploy.** `astrale-domain deploy production` prints the deployment URL, which
53
+ `astrale domain install` takes.
54
+
55
+ ## Namespace mode
56
+
57
+ `astrale-domain deploy <environment>` uploads one script named by the deployment label, create-only
58
+ (`If-None-Match: *`), which answers at `https://<label>.<routingDomain>` through the namespace's
59
+ dispatcher. Nothing is ever replaced in place: another build or configuration is another label.
60
+ Every line is readable. Namespace mode is a thin layer over the hosting kit below.
61
+
62
+ - **Credentials.** `CLOUDFLARE_API_TOKEN` must edit the namespace's scripts and the values of its
63
+ routing KV; the account is `namespace.account`, else `CLOUDFLARE_ACCOUNT_ID`. Neither is ever
64
+ written to the configuration.
65
+ - **Routing KV.** The deploy finds the namespace's routing KV by its title,
66
+ `astrale-deployment-routing-<first 16 bytes of sha256(name), in hexadecimal>`, which
67
+ provisioning creates. A namespace without it is refused before any effect. The names of
68
+ Services' deployments namespaces (`astrale-deployments-<hex>`) are refused: Services manages
69
+ their scripts.
70
+ - **Bindings.** Each new deployment binds `WORKER_URL`, `ASTRALE_BUILD_DIGEST`, `ASTRALE_SETTINGS`
71
+ (the router as `ROUTER`), the author's `vars`, the service and dispatch namespace bindings of
72
+ `wrangler`, the router, its version metadata, and as `secret_text` exactly the Environment's
73
+ secrets and `ASTRALE_SIGNING_IDENTITY`, a key generated for that deployment and kept nowhere
74
+ else. Its tags name its artifact (build digest), line and key; never `astrale-service`, which is
75
+ Services'.
76
+ - **Activation.** The deploy writes `record:<label>` with its media type metadata, whose presence
77
+ makes the dispatcher route the label: the canonical `DeploymentRecordV1`, published through the
78
+ kit's opaque record, which the dispatcher serves at `/.well-known/astrale/deployment.json`. It
79
+ never holds a provider version or a secret digest. Readiness then waits, bounded, until the URL serves the
80
+ sealed release from the provider version the upload created.
81
+ - **Reuse.** A redeploy of the same release finds the script under its label. It is reused only
82
+ when its artifact and line tags and its record name this build and configuration (only the
83
+ record's commit may differ: the deployment keeps the record it was first activated with), or,
84
+ when an interrupted deploy left it unactivated, when it binds exactly this configuration. Then only that
85
+ script's declared secrets are rewritten in place, and readiness waits for the version the
86
+ rewrite minted. Anything else is a `deployment-conflict`, refused with nothing written; no other
87
+ deployment is ever touched. A `summary:<label>` an older adapter wrote is ignored.
88
+ - **Retirement.** A label whose `retirement:<label>` the kit's `markRetired` wrote answers
89
+ `DEPLOYMENT_RETIRED` at the dispatcher and is refused by every later deploy. The namespace keeps
90
+ every deployment until then: there is no retention, preview expiry or `retain`.
91
+ - **Listing.** `astrale-domain list` lists the Environment's deployments from the routing KV and
92
+ the namespace, and writes nothing: one row per label of the Environment's line that
93
+ `record:<label>` activated or `retirement:<label>` withdrew, with its record as stored (a record
94
+ the SDK refuses is listed with `record: null` and the refusal), its script's creation instant and
95
+ key while the script exists, and the call target `{ kind: 'namespace', namespace, script }`. Its
96
+ state is `active`, `retiring` (tombstoned, script not deleted yet), `retired` (script deleted) or
97
+ `failed` (activated, script gone).
98
+ - **Refused.** A removed direct-mode parameter (`route`, `workerName`, `identityIssuer`,
99
+ `addressing`, `signingIdentity`), any `router` key but `service`, `hostSuffix` and `minLabels`
100
+ (the binding is always `ROUTER`), and any `wrangler` key
101
+ but `services`, `dispatch_namespaces` and `compatibility_flags`, `triggers` first: an immutable
102
+ deployment runs no cron of its own. A `dispatch_namespaces` entry is exactly
103
+ `{ binding, namespace }`; it is frozen into the configuration (`bindings.dispatchNamespaces`), so
104
+ into the label, bound at the create-only upload, and never names the namespace the deployment
105
+ lives in (AM-174). Which namespaces a deployment may bind is its host's to decide.
106
+ `durable` is frozen into the configuration (`settings.durableOptions`, AM-175), so into the
107
+ label, and bound in `ASTRALE_SETTINGS`: a durable run stays on the deployment that started it.
108
+
109
+ ## Hosting kit
110
+
111
+ `@astrale-os/adapter-cloudflare/hosting` is the one implementation of this hosting, for namespace
112
+ mode and for any other host that keeps its own routing beside it. Everything but provisioning runs in
113
+ Node and inside a Worker (`fetch` and WebCrypto only).
114
+
115
+ - **Client.** `CloudflareClient`: bounded bodies, `Retry-After`/429 waits by policy
116
+ (`DEFAULT_RATE_LIMIT`, `OPERATOR_RATE_LIMIT` or none), timeouts and a deadline, typed
117
+ `CloudflareApiError`s (`kind`, `status`, `codes`), cursor and numbered pagination, multipart
118
+ forms, raw KV text and bytes.
119
+ - **Routing KV.** `RoutingKv` (by title or id) and the contract: `record:<label>` (the deployment's
120
+ record, opaque bytes with their media type in the value's metadata, `{"contentType":...}`, or
121
+ `-` with `{"contentType":null}` for a deployment that publishes none; written once and kept only
122
+ for the same bytes and media type), `retirement:<label>` (`withdrawn`), `current:<name>` (one of
123
+ the name's labels), `cron:<name>` (canonical UTC crons). The record's metadata is mandatory: a
124
+ `record:<label>` without it activates nothing at the dispatcher (every path of the label answers
125
+ as not active yet, and no cron fires on it) and the kit refuses it (`record-invalid`) instead of
126
+ reading it as any record. Every write is read back before it counts.
127
+ - **Scripts.** `deploymentBindings`, `deploymentTags` (with a host's extra tags),
128
+ `uploadDeploymentScript` (create-only, every module kind, assets in parallel),
129
+ `observeScript`, `scriptSettings`, `scriptSecretNames`, `putScriptSecret`, `deleteScript`, and
130
+ `createSigningIdentity` (WebCrypto Ed25519).
131
+ - **Lifecycle.** `activateDeployment` (a label and its record, `WorkerRecord` of
132
+ `@astrale-os/sdk/deployment/worker`, or `null`), `readRecord`, `promoteDeployment`,
133
+ `replaceSchedules`, two-phase retirement
134
+ (`markRetired`, then `completeRetirement` once `retirementVisible` sees the dispatcher answer
135
+ `DEPLOYMENT_RETIRED`), `waitForReadiness` through the public URL or a dispatch binding, and
136
+ `listLineDeployments`.
137
+ - **Dispatcher.** Plain ES modules shipped with the package (`dispatcherModules()`), routing a label
138
+ to its script, a name to `current:<name>`, and firing `cron:<name>` on schedule. It serves a
139
+ label's record at `/.well-known/astrale/deployment.json`, its bytes and media type as published
140
+ (immutable, `405` but for `GET` and `HEAD`), and hands that path to a deployment that publishes
141
+ none. `createDispatcher()` owns routing and schedule admission. The public never reaches
142
+ `/__scheduled`; cron targets serve that internal POST endpoint.
143
+ - **Provisioning.** `planHosting` reads; `applyHosting` refuses any blocker before its first write;
144
+ `provisionHosting` does both.
145
+ - **Testing.** `@astrale-os/adapter-cloudflare/hosting/testing` exports `FakeCloudflare`, one fake
146
+ account that serves public requests with the real dispatcher.
147
+
148
+ ## Frontend files
149
+
150
+ The Worker runs before Workers Static Assets on every request and owns frontend response headers
151
+ and routing, for `cloudflare()` and `astrale()` deployments alike. Frontend preparation therefore
152
+ refuses a built frontend whose root contains `_headers`, `_redirects`, or `.assetsignore`, in any
153
+ letter case, as a file or a directory. Wrangler and managed deployments would otherwise interpret these files differently. The refusal happens while
154
+ the artifact is prepared, before any provider change. Vite copies its public directory (`public/`
155
+ by default) to that root: remove them there, or stop the plugin that emits them. The same names
156
+ below the root, such as `docs/_headers`, remain ordinary files.
157
+
158
+ The Worker is also the only server-side code, so preparation likewise refuses a root name starting
159
+ with `_worker.js`, the name of a Cloudflare Pages worker script: a `_worker.js` file or directory,
160
+ or a sibling such as `_worker.js.map`. Wrangler refuses to upload these as assets, since they may
161
+ hold server-side code, so a direct deployment would fail at upload, while a managed deployment would
162
+ publish them. Unlike the names above, the match is case-sensitive, as Wrangler's is: `_Worker.js`
163
+ and a nested `docs/_worker.js` remain ordinary files. Remove such a file from the public directory,
164
+ or rename it if it is a browser script.
165
+
166
+ ## Deployment bindings
167
+
168
+ The bundled Worker carries no Environment value, so every Environment of one source bundles the
169
+ same bytes. Each deployment binds its own values as plain Worker bindings:
170
+
171
+ | Binding | Value |
172
+ | --- | --- |
173
+ | `WORKER_URL` | serving origin of the deployment |
174
+ | `ASTRALE_SETTINGS` | canonical JSON of `{ invocationTimeoutMs, maximumRequestBytes, router, tokenExchange }`, defaults resolved, with optional `durableOptions` |
175
+ | `ASTRALE_BUILD_DIGEST` | required build digest the host recomputed from the uploaded bytes |
176
+
177
+ These names are adapter-owned: preparation refuses an author var, or a `wrangler.vars` entry, that
178
+ takes one, and deployment refuses a secret that does. A host that deploys the Worker itself encodes
179
+ the settings with `encodeWorkerSettings` from `@astrale-os/adapter-cloudflare/worker`. A generated
180
+ Worker refuses execution without `ASTRALE_SETTINGS`.
181
+
182
+ `maximumRequestBytes` bounds the invocation bodies the Worker buffers. A streamed binary body is
183
+ bounded by the Build instead: the largest `maximumBytes` among the Domain's binary Functions, with
184
+ 30 minutes to arrive (or `invocationTimeoutMs` when longer) and at most 60 seconds between chunks.
185
+ A Domain without a binary Function keeps the Kernel Server defaults.
186
+
187
+ Every Worker requires `WORKER_URL` and `ASTRALE_BUILD_DIGEST`. It seals the `DomainRelease` v4
188
+ of its code at that serving URL, which is also its issuer, and serves it at
189
+ `/.well-known/astrale/release.json`. Routing must name that exact Release. The Worker refuses
190
+ execution when either binding is missing or invalid; a foreign request origin is refused before
191
+ loading the Service. `domain.json` serves no compatibility projection.
192
+
193
+ The `wrangler` overlay reaches the deployment configuration, never the bundle. Preparation refuses
194
+ an overlay key the bundler reads (`alias`, `build`, `define`, `jsx_factory`, `jsx_fragment`,
195
+ `keep_names`, `minify`, `no_bundle`, `node_compat`, `preserve_file_names`, `rules`, `tsconfig`,
196
+ `upload_source_maps`) and a compatibility flag it reads (Node.js, `navigator`, fetch iterable
197
+ typing, Python) beyond the adapter's own `nodejs_compat`.
198
+
199
+ ## Deployment cache
200
+
201
+ A Worker keeps the admissions of callables that declare an admission age (`admission: { maxAge }`)
202
+ in its deployment cache: the Cache API cache `astrale-deployment`, behind a bounded in-isolate memory
203
+ tier read first. Cloudflare gives each Worker script, so each immutable deployment, its own Cache API
204
+ cache: no other deployment reads these entries, and a new release starts empty. An entry is kept
205
+ for its whole remaining seconds at most (`cache-control: max-age`), and in memory only when less
206
+ than one second remains. A hand-composed entrypoint keeps none with `cache: false`; every call is
207
+ then admitted by its source Kernel. `cloudflareCache()` from `@astrale-os/adapter-cloudflare/worker`
208
+ is the same cache for a Worker that calls `serve()` itself. See the SDK's `docs/admission-age.md`.
209
+
210
+ ## Build digest
211
+
212
+ `cloudflare()` and `astrale()` bundle through one bundler, `cloudflare-worker` version `1`, so
213
+ every Environment of either adapter shares one build: `astrale-domain build` prints its build
214
+ digest, and `deploy` places that same Bundle. Two installed versions of this package are two
215
+ copies of the bundler: when their code differs, `build` prints one build digest per copy and warns
216
+ until the adapter versions are aligned.
217
+
218
+ Services and namespace deployments upload the placed modules unchanged, so the digest names the
219
+ bytes the deployment runs. A host with its own Worker entrypoint describes its final upload with
220
+ `workerBuildManifest` and `WorkerUpload` from `@astrale-os/adapter-cloudflare/build`, then computes
221
+ its digest with `buildDigest` from `@astrale-os/sdk/deployment/build/manifest`. Modules retain
222
+ their uploaded names and an asset `/<path>` becomes the file `assets/<path>`. The host binds that
223
+ digest as `ASTRALE_BUILD_DIGEST` and uploads those exact bytes without bundling them again.
224
+ The bundler version names this layout, not a package release.
225
+
226
+ ## Material for a custom Worker entrypoint
227
+
228
+ Workers with provider-specific routes or environment initialization can reuse the adapter's
229
+ material emission without adopting the entire generated entrypoint:
230
+
231
+ ```ts
232
+ import { generateBuildMaterialModule } from '@astrale-os/adapter-cloudflare/build'
233
+ import { writeFile } from 'node:fs/promises'
234
+
235
+ // build is an admitted Build returned by compile(domain).
236
+ await writeFile('src/build-material.gen.ts', generateBuildMaterialModule(build))
237
+ ```
238
+
239
+ The generated TypeScript module exports `loadBuildMaterial()`. Call it from the
240
+ `load` callback of `generatedCloudflareWorkerEntry` alongside the Domain's Runtime.
241
+ That callback loads deterministic local modules once per entrypoint. Concurrent execution and
242
+ `prepare()` calls share the same result, including a rejection; subsequent calls do not retry it.
243
+ A newly constructed entrypoint starts independently. Keep remote preparation that may recover
244
+ from transient failures in its own lifecycle, rather than putting it in `load`.
245
+ Such an entrypoint states its execution settings (`invocationTimeoutMs`, `maximumRequestBytes`,
246
+ `tokenExchange`, `routeSubrequest`) in its configuration, or reads them from its
247
+ deployment bindings with `settings: deploymentSettings`; one Worker never takes both.
248
+ It constructs the same verified, deduplicated material as the adapter's generated Service;
249
+ allocation is deferred until the factory is called and the SDK deep-freezes it before use.
250
+ The generated file needs only a type import from the SDK. Keep its compiler and runtime SDK
251
+ versions aligned, and regenerate it when either the Domain or that SDK version changes.
252
+
253
+ Such an entrypoint can keep the same fast frontend path by answering from
254
+ `cloudflareFrontDoor()` (`@astrale-os/adapter-cloudflare/worker/front`, which reaches no SDK
255
+ runtime module) before importing its Service, and calling that Service's `prepare()` through
256
+ `waitUntil` when the front door served a frontend file.
package/dist/adapter.d.ts CHANGED
@@ -1,17 +1,11 @@
1
- import type { Release } from '@astrale-os/sdk/deployment/release';
2
- import { verifyReadiness } from '@astrale-os/sdk/deployment/verify';
1
+ import type { Deployment } from '@astrale-os/sdk/deployment';
2
+ import type { Adapter } from '@astrale-os/sdk/deployment/adapter';
3
+ import type { NamespaceDependencies } from './namespace/index.js';
3
4
  import type { CloudflareParams } from './params.js';
4
- import { artifact } from './build/artifact.js';
5
- import { startFrontend } from './build/frontend-v1.js';
6
- import { runWranglerDev } from './build/wrangler-cli.js';
7
- import { type CloudflareDeployDependencies } from './deploy/index.js';
8
- import { signingIdentity } from './identity/source.js';
9
- export interface CloudflareDependencies extends CloudflareDeployDependencies {
10
- readonly artifact: typeof artifact;
11
- readonly runWranglerDev: typeof runWranglerDev;
12
- readonly startFrontend: typeof startFrontend;
13
- readonly signingIdentity: typeof signingIdentity;
5
+ export type { NamespaceDependencies } from './namespace/index.js';
6
+ export interface CloudflareDependencies {
7
+ readonly namespace: NamespaceDependencies;
14
8
  }
15
- export declare function cloudflare(environments: Readonly<Record<string, CloudflareParams>>): import("@astrale-os/sdk/deployment/adapter").Adapter<CloudflareParams>;
16
- export declare function cloudflareWithDependencies(environments: Readonly<Record<string, CloudflareParams>>, dependencies: CloudflareDependencies): import("@astrale-os/sdk/deployment/adapter").Adapter<CloudflareParams>;
17
- export declare function waitForReadiness(verify: typeof verifyReadiness, release: Release): Promise<void>;
9
+ /** Deploy each release as one immutable deployment in a Cloudflare dispatch namespace. */
10
+ export declare function cloudflare(parameters: CloudflareParams): Deployment<CloudflareParams, Adapter<CloudflareParams>>;
11
+ export declare function cloudflareWithDependencies(parameters: CloudflareParams, dependencies: CloudflareDependencies): Deployment<CloudflareParams, Adapter<CloudflareParams>>;
package/dist/adapter.js CHANGED
@@ -1,140 +1,54 @@
1
- import { defineAdapter } from '@astrale-os/sdk/deployment/adapter';
2
- import { verifyReadiness } from '@astrale-os/sdk/deployment/verify';
3
- import { writeFile } from 'node:fs/promises';
1
+ import { defineAdapter, defineDeployment } from '@astrale-os/sdk/deployment/adapter';
4
2
  import { createRequire } from 'node:module';
5
- import { join } from 'node:path';
6
- import { artifact, materialize } from './build/artifact.js';
7
- import { generateWranglerConfig } from './build/codegen/wrangler.js';
8
- import { resolveRouter, workerName } from './build/configuration.js';
9
- import { startFrontend } from './build/frontend-v1.js';
10
- import { ensureWranglerDispatchNamespace, runWranglerDeploymentStatus, runWranglerDeploy, runWranglerDev, runWranglerReleaseDeploy, } from './build/wrangler-cli.js';
11
- import { deployCloudflare } from './deploy/index.js';
12
- import { signingIdentitySecrets } from './identity/secret.js';
13
- import { signingIdentity } from './identity/source.js';
3
+ import { cloudflareWorkerBundler } from './build/bundler.js';
4
+ import { workerSettings } from './build/configuration.js';
5
+ import { createSigningIdentity } from './hosting/identity.js';
6
+ import { configureNamespace, deployNamespaceRelease, listNamespaceDeployments, hostingCommands, namespaceCoordinates, placeNamespace, } from './namespace/index.js';
14
7
  const packageVersion = createRequire(import.meta.url)('../package.json')
15
8
  .version;
16
- export function cloudflare(environments) {
17
- return cloudflareWithDependencies(environments, {
18
- artifact,
19
- materialize,
20
- ensureWranglerDispatchNamespace,
21
- runWranglerDeploy,
22
- runWranglerReleaseDeploy,
23
- runWranglerDeploymentStatus,
24
- runWranglerDev,
25
- startFrontend,
26
- signingIdentity,
27
- waitForReadiness: (release) => waitForReadiness(verifyReadiness, release),
28
- });
9
+ /** Deploy each release as one immutable deployment in a Cloudflare dispatch namespace. */
10
+ export function cloudflare(parameters) {
11
+ return cloudflareWithDependencies(parameters, { namespace: platformNamespaceDependencies() });
29
12
  }
30
- export function cloudflareWithDependencies(environments, dependencies) {
31
- return defineAdapter({
13
+ export function cloudflareWithDependencies(parameters, dependencies) {
14
+ const namespace = dependencies.namespace;
15
+ const adapter = defineAdapter({
32
16
  name: 'cloudflare',
33
17
  version: packageVersion,
34
- environments,
35
- prepare: dependencies.artifact,
36
- async watch(parameters, context) {
37
- const identity = await dependencies.signingIdentity({
38
- projectDir: context.projectDir,
39
- source: parameters.signingIdentity,
40
- origin: context.artifact.build.schema.compiled.root.origin,
41
- mode: 'local',
42
- });
43
- const secrets = signingIdentitySecrets(context.secrets, identity);
44
- const directory = join(context.projectDir, '.astrale', 'runtime');
45
- await dependencies.materialize(directory, context.artifact.files);
46
- const frontend = await dependencies.startFrontend({
47
- frontend: context.artifact.build.frontend,
48
- projectDir: context.projectDir,
49
- });
50
- const name = workerName(parameters, context.artifact.build.schema.compiled.root.origin);
51
- const router = resolveRouter(parameters.router);
52
- const configPath = join(directory, 'wrangler.watch.jsonc');
53
- await writeFile(configPath, generateWranglerConfig({
54
- workerName: name,
55
- vars: {
56
- ...parameters.vars,
57
- ...(parameters.host === undefined ? {} : { WORKER_URL: parameters.host }),
58
- ...(frontend === undefined ? {} : { FRONTEND_DEV_URL: frontend.url }),
59
- },
60
- secretBindings: Object.keys(secrets).sort(),
61
- ...(context.artifact.build.frontend?.source.kind === 'vite'
62
- ? {
63
- frontend: {
64
- directory: './frontend',
65
- routes: frontendRoutes(context.artifact),
66
- dev: true,
67
- },
68
- }
69
- : {}),
70
- ...(router === undefined
71
- ? {}
72
- : { router: { binding: router.binding, service: router.service } }),
73
- ...(parameters.wrangler === undefined ? {} : { wrangler: parameters.wrangler }),
74
- selfBinding: true,
75
- }));
76
- let worker;
77
- try {
78
- worker = await dependencies.runWranglerDev({
79
- projectDir: context.projectDir,
80
- configPath,
81
- port: parameters.port ?? 8787,
82
- remote: parameters.remote ?? false,
83
- secrets,
84
- autoPickPort: parameters.port === undefined,
85
- ...(parameters.host === undefined ? {} : { ip: '0.0.0.0' }),
86
- onReload: context.onReload,
87
- });
88
- }
89
- catch (cause) {
90
- await frontend?.stop().catch(() => undefined);
91
- throw cause;
92
- }
93
- return Object.freeze({
94
- url: parameters.host ?? worker.url,
95
- localUrl: worker.url,
96
- async stop() {
97
- const results = await Promise.allSettled([
98
- worker.stop(),
99
- frontend?.stop() ?? Promise.resolve(),
100
- ]);
101
- const failures = results.filter((result) => result.status === 'rejected');
102
- if (failures.length === 1)
103
- throw failures[0].reason;
104
- if (failures.length > 1) {
105
- throw new AggregateError(failures.map((failure) => failure.reason), 'Cloudflare development cleanup failed.');
106
- }
107
- },
108
- });
109
- },
110
- deploy: (parameters, context) => deployCloudflare(parameters, context, dependencies),
18
+ bundler: cloudflareWorkerBundler,
19
+ admit: admitCloudflare,
20
+ configure: configureNamespace,
21
+ placement: async (parameters) => placeNamespace(parameters),
22
+ deployRelease: (parameters, context) => deployNamespaceRelease(parameters, context, namespace),
23
+ list: (parameters, context) => listNamespaceDeployments(parameters, context, namespace),
24
+ commands: hostingCommands(namespace),
111
25
  secretsFile: (parameters) => parameters.secrets,
112
26
  });
27
+ return defineDeployment(adapter, parameters);
113
28
  }
114
- function frontendRoutes(artifact) {
115
- const frontend = artifact.build.frontend;
116
- if (frontend === undefined || frontend.source.kind !== 'vite')
117
- return [];
118
- return Object.freeze(frontend.routes
119
- .flatMap((route) => frontend.source.kind === 'vite' && frontend.source.spa && route.path !== '/'
120
- ? [route.path, `${route.path}/*`]
121
- : route.path === '/'
122
- ? ['/*']
123
- : [route.path])
124
- .sort());
125
- }
126
- export async function waitForReadiness(verify, release) {
127
- const deadline = Date.now() + 90_000;
128
- let last;
129
- while (Date.now() < deadline) {
130
- try {
131
- await verify(release, { signal: AbortSignal.timeout(5_000) });
132
- return;
133
- }
134
- catch (cause) {
135
- last = cause;
136
- await new Promise((resolve) => setTimeout(resolve, 1_000));
137
- }
29
+ /** Validate the deployment contract when the Project loads, before any build or provider effect. */
30
+ function admitCloudflare(parameters) {
31
+ const allowed = [
32
+ 'namespace',
33
+ 'secrets',
34
+ 'vars',
35
+ 'maximumRequestBytes',
36
+ 'invocationTimeoutMs',
37
+ 'tokenExchange',
38
+ 'durable',
39
+ 'wrangler',
40
+ 'router',
41
+ ];
42
+ if (Reflect.ownKeys(parameters).some((key) => !allowed.includes(key))) {
43
+ throw new TypeError('Cloudflare deployment parameters contain unknown fields.');
138
44
  }
139
- throw last instanceof Error ? last : new Error('Cloudflare Release did not become ready.');
45
+ namespaceCoordinates(parameters);
46
+ workerSettings(parameters);
47
+ }
48
+ function platformNamespaceDependencies() {
49
+ return Object.freeze({
50
+ fetch: (input, init) => fetch(input, init),
51
+ environment: process.env,
52
+ createSigningIdentity,
53
+ });
140
54
  }
@@ -0,0 +1,3 @@
1
+ export declare function admitWorkerBundle(path: string): Promise<void>;
2
+ /** Admit the separately emitted engine's actual platform exports, including its compiled WASM. */
3
+ export declare function admitDurableEngineBundle(path: string): Promise<void>;
@@ -0,0 +1,47 @@
1
+ import { isDurableEngine } from '@astrale-os/sdk/execution';
2
+ import * as nodeModule from 'node:module';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { compiledWasmLoader, compiledWasmSource } from './compiled-wasm-loader.js';
5
+ let compiledWasm = false;
6
+ /**
7
+ * Import a WebAssembly module as Workers do for `CompiledWasm`: its default export is the compiled
8
+ * `WebAssembly.Module`, instantiated by the importing code. The CLI admits bundles under Bun; Node
9
+ * serves programmatic builds.
10
+ */
11
+ function admitCompiledWasm() {
12
+ if (compiledWasm)
13
+ return;
14
+ if (process.versions.bun !== undefined) {
15
+ ;
16
+ Reflect.get(globalThis, 'Bun').plugin({
17
+ name: 'astrale-compiled-wasm',
18
+ setup(build) {
19
+ build.onLoad({ filter: /\.wasm$/ }, ({ path }) => ({
20
+ loader: 'js',
21
+ contents: compiledWasmSource(JSON.stringify(path)),
22
+ }));
23
+ },
24
+ });
25
+ compiledWasm = true;
26
+ return;
27
+ }
28
+ nodeModule.register(compiledWasmLoader);
29
+ compiledWasm = true;
30
+ }
31
+ export async function admitWorkerBundle(path) {
32
+ admitCompiledWasm();
33
+ const loaded = (await import(`${pathToFileURL(path).href}?admit=${Date.now()}`));
34
+ if (loaded.default === null ||
35
+ typeof loaded.default !== 'object' ||
36
+ typeof Reflect.get(loaded.default, 'fetch') !== 'function') {
37
+ throw new TypeError('Generated Worker bundle does not export a Fetch handler.');
38
+ }
39
+ }
40
+ /** Admit the separately emitted engine's actual platform exports, including its compiled WASM. */
41
+ export async function admitDurableEngineBundle(path) {
42
+ admitCompiledWasm();
43
+ const engine = (await import(`${pathToFileURL(path).href}?admit=${Date.now()}`));
44
+ if (!isDurableEngine(engine)) {
45
+ throw new TypeError('Generated durable engine bundle does not export the platform Fetch entrypoint.');
46
+ }
47
+ }
@@ -0,0 +1,8 @@
1
+ /** Workers expose CompiledWasm imports as modules, rather than instantiated exports. */
2
+ export declare function compiledWasmSource(file: string): string;
3
+ /**
4
+ * Async hooks run in a separate Node thread. A self-contained ESM hook admits both emitted JS and
5
+ * source builds under tsx without requiring that thread to resolve or transpile our source files.
6
+ * The emitted import source is shared with Bun.
7
+ */
8
+ export declare const compiledWasmLoader: string;
@@ -0,0 +1,21 @@
1
+ const SOURCE_PREFIX = "import { readFileSync } from 'node:fs'\nexport default new WebAssembly.Module(readFileSync(";
2
+ const SOURCE_SUFFIX = '))\n';
3
+ /** Workers expose CompiledWasm imports as modules, rather than instantiated exports. */
4
+ export function compiledWasmSource(file) {
5
+ return `${SOURCE_PREFIX}${file}${SOURCE_SUFFIX}`;
6
+ }
7
+ /**
8
+ * Async hooks run in a separate Node thread. A self-contained ESM hook admits both emitted JS and
9
+ * source builds under tsx without requiring that thread to resolve or transpile our source files.
10
+ * The emitted import source is shared with Bun.
11
+ */
12
+ export const compiledWasmLoader = `data:text/javascript,${encodeURIComponent(`
13
+ export function load(url, context, nextLoad) {
14
+ if (!url.startsWith('file:') || !url.endsWith('.wasm')) return nextLoad(url, context);
15
+ return {
16
+ format: 'module',
17
+ shortCircuit: true,
18
+ source: ${JSON.stringify(SOURCE_PREFIX)} + 'new URL(' + JSON.stringify(url) + ')' + ${JSON.stringify(SOURCE_SUFFIX)},
19
+ };
20
+ }
21
+ `)}`;
@@ -0,0 +1,21 @@
1
+ import type { Bundle, BundleContext, Bundler } from '@astrale-os/sdk/deployment/adapter';
2
+ import type { frontend as frontendBuild } from '@astrale-os/sdk/deployment/build';
3
+ import type { ReleaseModule } from './worker/execution.prepare.js';
4
+ /**
5
+ * Environment-free bytes of one generated Worker: its entry, the modules it loads (the execution
6
+ * Service, the deferred workflow engine and their WASM) and its frontend.
7
+ */
8
+ export interface WorkerBytes {
9
+ readonly entry: Uint8Array;
10
+ readonly modules: readonly ReleaseModule[];
11
+ readonly frontend: readonly frontendBuild.FrontendFile[];
12
+ }
13
+ /**
14
+ * Bundles every generated Cloudflare Worker, for adapter-cloudflare and adapter-astrale alike. It
15
+ * reads no Environment: settings, address, issuer and key are bound at deploy.
16
+ */
17
+ export declare const cloudflareWorkerBundler: Bundler;
18
+ /** Bundle the Worker modules and build the frontend they serve, in one scratch directory. */
19
+ export declare function bundleWorker(context: BundleContext): Promise<WorkerBytes>;
20
+ /** Read back the Worker bytes of a Bundle this bundler produced for the same Build. */
21
+ export declare function bundledWorker(bundle: Bundle, build: Bundle['build']): WorkerBytes;