@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,22 @@
1
+ import { acceptBuildDigest } from '@astrale-os/sdk/deployment/build/manifest';
2
+ /**
3
+ * Plain binding an immutable-deployment host (Services, the platform namespace) binds at the
4
+ * create-only upload: the build digest it recomputed from the uploaded bytes. No stable Worker
5
+ * receives it, and no author var or secret may take its name.
6
+ */
7
+ export const BUILD_DIGEST_BINDING = 'ASTRALE_BUILD_DIGEST';
8
+ /** The exact host-bound build digest this immutable deployment serves. */
9
+ export function deploymentBuildDigest(bindings) {
10
+ const bound = bindings.ASTRALE_BUILD_DIGEST;
11
+ let digest;
12
+ try {
13
+ digest = acceptBuildDigest(bound);
14
+ }
15
+ catch (cause) {
16
+ throw new TypeError(`Cloudflare Worker ${BUILD_DIGEST_BINDING} binding is invalid.`, { cause });
17
+ }
18
+ if (bindings.WORKER_URL === undefined) {
19
+ throw new TypeError(`Cloudflare Worker ${BUILD_DIGEST_BINDING} requires the deployment URL bound as WORKER_URL.`);
20
+ }
21
+ return digest;
22
+ }
@@ -0,0 +1,28 @@
1
+ import type { DeploymentCache } from '@astrale-os/sdk/execution';
2
+ /**
3
+ * The Cache API cache a deployment keeps its entries in. Cloudflare isolates the Cache API of each
4
+ * Worker script, and so of each immutable deployment: no other deployment reads these entries.
5
+ */
6
+ export declare const DEPLOYMENT_CACHE_NAME = "astrale-deployment";
7
+ /** The part of the Cache API a deployment cache uses. */
8
+ export interface CacheApiStorage {
9
+ open(cacheName: string): Promise<CacheApiCache>;
10
+ }
11
+ export interface CacheApiCache {
12
+ match(request: string): Promise<Response | undefined>;
13
+ put(request: string, response: Response): Promise<void>;
14
+ }
15
+ export interface CloudflareCacheOptions {
16
+ /** The Cache API; defaults to the isolate's `caches`, and to none where the isolate has none. */
17
+ readonly caches?: CacheApiStorage;
18
+ /** The in-isolate tier read first; defaults to a bounded memory cache. */
19
+ readonly memory?: DeploymentCache;
20
+ }
21
+ /**
22
+ * A deployment cache shared by every isolate of one deployment in a data center: the Cache API,
23
+ * behind a bounded in-isolate memory tier read first. The Cache API keeps an entry for its whole
24
+ * remaining seconds at most, so an entry with less than one second left is kept in memory only.
25
+ * The cache is opened per operation and nothing pending is shared, because a Worker binds I/O to
26
+ * the request that started it.
27
+ */
28
+ export declare function cloudflareCache(options?: CloudflareCacheOptions): DeploymentCache;
@@ -0,0 +1,70 @@
1
+ import { memoryCache } from '@astrale-os/sdk/execution';
2
+ /**
3
+ * The Cache API cache a deployment keeps its entries in. Cloudflare isolates the Cache API of each
4
+ * Worker script, and so of each immutable deployment: no other deployment reads these entries.
5
+ */
6
+ export const DEPLOYMENT_CACHE_NAME = 'astrale-deployment';
7
+ /** Origin of the synthetic URLs that name entries; they are never fetched. */
8
+ const ENTRY_ORIGIN = 'https://deployment-cache.astrale.invalid/';
9
+ /** Absolute expiry of an entry, in Unix milliseconds, carried beside its value. */
10
+ const EXPIRES_AT = 'x-astrale-expires-at';
11
+ /**
12
+ * A deployment cache shared by every isolate of one deployment in a data center: the Cache API,
13
+ * behind a bounded in-isolate memory tier read first. The Cache API keeps an entry for its whole
14
+ * remaining seconds at most, so an entry with less than one second left is kept in memory only.
15
+ * The cache is opened per operation and nothing pending is shared, because a Worker binds I/O to
16
+ * the request that started it.
17
+ */
18
+ export function cloudflareCache(options = {}) {
19
+ if (options === null || typeof options !== 'object' || Array.isArray(options))
20
+ invalid();
21
+ const memory = options.memory ?? memoryCache();
22
+ const storage = options.caches ?? isolateCaches();
23
+ return Object.freeze({
24
+ async get(key) {
25
+ const near = await memory.get(key);
26
+ if (near !== undefined || storage === undefined)
27
+ return near;
28
+ const response = await (await storage.open(DEPLOYMENT_CACHE_NAME)).match(entryUrl(key));
29
+ if (response === undefined)
30
+ return undefined;
31
+ const value = await response.text();
32
+ const expiresAt = Number(response.headers.get(EXPIRES_AT));
33
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now())
34
+ return undefined;
35
+ await memory.put(key, value, expiresAt);
36
+ return value;
37
+ },
38
+ async put(key, value, expiresAt) {
39
+ await memory.put(key, value, expiresAt);
40
+ if (storage === undefined || !Number.isSafeInteger(expiresAt))
41
+ return;
42
+ const seconds = Math.floor((expiresAt - Date.now()) / 1000);
43
+ if (seconds < 1)
44
+ return;
45
+ await (await storage.open(DEPLOYMENT_CACHE_NAME)).put(entryUrl(key), new Response(value, {
46
+ headers: {
47
+ 'cache-control': `max-age=${seconds}`,
48
+ 'content-type': 'text/plain; charset=utf-8',
49
+ [EXPIRES_AT]: String(expiresAt),
50
+ },
51
+ }));
52
+ },
53
+ });
54
+ }
55
+ function entryUrl(key) {
56
+ if (typeof key !== 'string')
57
+ invalid();
58
+ return `${ENTRY_ORIGIN}${encodeURIComponent(key)}`;
59
+ }
60
+ function isolateCaches() {
61
+ const caches = Reflect.get(globalThis, 'caches');
62
+ return caches !== null &&
63
+ typeof caches === 'object' &&
64
+ typeof Reflect.get(caches, 'open') === 'function'
65
+ ? caches
66
+ : undefined;
67
+ }
68
+ function invalid() {
69
+ throw new TypeError('Cloudflare cache input is invalid.');
70
+ }
@@ -0,0 +1,3 @@
1
+ import type { DurableEngine, DurableServing } from '@astrale-os/sdk/execution';
2
+ /** Canonical callbacks discover engine authority from the Kernel named in their route. */
3
+ export declare function restateServing(engine: DurableEngine, request: Request, options?: Pick<DurableServing, 'retentionMs' | 'retry' | 'stepTimeoutMs'>): DurableServing | undefined;
@@ -0,0 +1,5 @@
1
+ import { isCanonicalDurableRequest } from '@astrale-os/sdk/execution';
2
+ /** Canonical callbacks discover engine authority from the Kernel named in their route. */
3
+ export function restateServing(engine, request, options = {}) {
4
+ return isCanonicalDurableRequest(request) ? Object.freeze({ ...options, engine }) : undefined;
5
+ }
@@ -0,0 +1,47 @@
1
+ import type { JsonWebKey } from '@astrale-os/sdk/auth';
2
+ import type { BuildMaterial, GeneratedBuildMaterial } from '@astrale-os/sdk/deployment/build/material';
3
+ import type { DurableServingProvider, ExecutionContext } from '@astrale-os/sdk/execution';
4
+ import type { Runtime } from '@astrale-os/sdk/runtime';
5
+ import type { DurableWorkerOptions } from '../params.js';
6
+ import type { CloudflareAdapterBindings, CloudflareFrontDoorConfig, Fetcher } from './front.js';
7
+ import type { CloudflareWorkerSettings } from './settings.js';
8
+ export type { CloudflareAdapterBindings, Fetcher } from './front.js';
9
+ export interface CloudflareWorkerConfig<RuntimeValue extends Runtime, Bindings extends CloudflareAdapterBindings, Environment, Material = BuildMaterial> extends CloudflareFrontDoorConfig, CloudflareWorkerSettings<Bindings> {
10
+ /**
11
+ * Load the exact local Runtime and Build once per entrypoint, after the isolate has accepted a
12
+ * request or execution is prepared. Concurrent callers share the result, including a rejection;
13
+ * later calls do not retry loading. A new entrypoint has an independent load. Keep recoverable
14
+ * remote preparation in its own lifecycle rather than this deterministic module loader.
15
+ */
16
+ readonly load: () => CloudflareWorkerSource<RuntimeValue, Material> | Promise<CloudflareWorkerSource<RuntimeValue, Material>>;
17
+ readonly privateKey: JsonWebKey | ((bindings: Bindings) => JsonWebKey);
18
+ readonly resolveEnvironment?: (bindings: Bindings) => Environment;
19
+ readonly selfBinding?: (bindings: Bindings) => Fetcher | null | undefined;
20
+ /**
21
+ * Read the execution settings from the deployment's bindings on the isolate's first execution
22
+ * request, as generated Workers do with `deploymentSettings`. A hand-composed Worker states
23
+ * them in this configuration instead; one Worker never takes both.
24
+ */
25
+ readonly settings?: (bindings: Bindings) => CloudflareWorkerSettings<Bindings>;
26
+ /**
27
+ * The deployment cache, which keeps the admissions of callables that declare an admission age:
28
+ * by default the Cache API behind an in-isolate memory tier. `false` keeps nothing, and every
29
+ * call is admitted by its source Kernel.
30
+ */
31
+ readonly cache?: false;
32
+ /** Resolve the engine for this durable request with the deployment's captured options. */
33
+ readonly durable?: (bindings: Bindings, request: Request, options?: DurableWorkerOptions) => ReturnType<DurableServingProvider>;
34
+ }
35
+ export interface CloudflareWorkerSource<RuntimeValue extends Runtime, Material = BuildMaterial> {
36
+ readonly runtime: RuntimeValue;
37
+ readonly material: Material;
38
+ }
39
+ export interface CloudflareWorker<Bindings> {
40
+ fetch(request: Request, environment: Bindings, executionContext?: ExecutionContext): Response | Promise<Response>;
41
+ /** Realize execution ahead of the request that needs it; failures resurface on that request. */
42
+ prepare?(): Promise<void>;
43
+ }
44
+ /** Compose one installed Domain implementation at its immutable deployment URL. */
45
+ export declare function cloudflareWorkerEntry<Bindings extends CloudflareAdapterBindings, Environment = Bindings>(): <RuntimeValue extends Runtime>(config: CloudflareWorkerConfig<RuntimeValue, Bindings, Environment, BuildMaterial>) => CloudflareWorker<Bindings>;
46
+ /** Compose generated execution code whose exact Build material carries build-owner evidence. */
47
+ export declare function generatedCloudflareWorkerEntry<Bindings extends CloudflareAdapterBindings, Environment = Bindings>(): <RuntimeValue extends Runtime>(config: CloudflareWorkerConfig<RuntimeValue, Bindings, Environment, GeneratedBuildMaterial>) => CloudflareWorker<Bindings>;
@@ -0,0 +1,135 @@
1
+ import { issuer } from '@astrale-os/sdk/auth';
2
+ import { restoreBuild, restoreGeneratedBuild } from '@astrale-os/sdk/deployment/build/material';
3
+ import { assemble } from '@astrale-os/sdk/deployment/release/runtime';
4
+ import { createIdentity, serve } from '@astrale-os/sdk/execution';
5
+ import { binaryRequestLimits } from './binary.js';
6
+ import { deploymentBuildDigest } from './build-digest.js';
7
+ import { cloudflareCache } from './cache.js';
8
+ import { dispatchCloudflareRequest, prepareCloudflareRequest } from './fetch.js';
9
+ import { cloudflareFrontDoor, withProviderVersion } from './front.js';
10
+ import { frontendAsset } from './frontend.js';
11
+ import { DEFAULT_INVOCATION_TIMEOUT_MS, DEFAULT_MAXIMUM_REQUEST_BYTES } from './settings.js';
12
+ /** Compose one installed Domain implementation at its immutable deployment URL. */
13
+ export function cloudflareWorkerEntry() {
14
+ return createCloudflareWorkerEntry(restoreBuild);
15
+ }
16
+ /** Compose generated execution code whose exact Build material carries build-owner evidence. */
17
+ export function generatedCloudflareWorkerEntry() {
18
+ return createCloudflareWorkerEntry(restoreGeneratedBuild);
19
+ }
20
+ /** The static settings a hand-composed Worker may state instead of reading its bindings. */
21
+ const SETTINGS = [
22
+ 'routeSubrequest',
23
+ 'invocationTimeoutMs',
24
+ 'maximumRequestBytes',
25
+ 'tokenExchange',
26
+ 'durableOptions',
27
+ ];
28
+ function createCloudflareWorkerEntry(restore) {
29
+ return function (config) {
30
+ if (config.settings !== undefined && SETTINGS.some((key) => config[key] !== undefined)) {
31
+ throw new TypeError('Cloudflare Worker settings come from its deployment bindings or its configuration, not both.');
32
+ }
33
+ const frontDoor = cloudflareFrontDoor(config);
34
+ let restored;
35
+ let application;
36
+ const realize = () => (restored ??= Promise.resolve()
37
+ .then(config.load)
38
+ .then((source) => Object.freeze({
39
+ runtime: source.runtime,
40
+ build: restore(source.material, source.runtime),
41
+ })));
42
+ // Settings and the build digest are a deployment's, so they are read from the first execution
43
+ // request's bindings.
44
+ const served = (source, bindings) => {
45
+ if (application !== undefined)
46
+ return application;
47
+ const { build } = source;
48
+ const settings = config.settings === undefined ? config : config.settings(bindings);
49
+ const buildDigest = deploymentBuildDigest(bindings);
50
+ const invocationTimeoutMs = settings.invocationTimeoutMs ?? DEFAULT_INVOCATION_TIMEOUT_MS;
51
+ const created = serve({
52
+ runtime: source.runtime,
53
+ load(environment) {
54
+ if (frontDoor.current() !== environment.publicUrl) {
55
+ throw new TypeError('Cloudflare Worker request origin differs from its current Release.');
56
+ }
57
+ return assemble(build, buildDigest, environment.publicUrl);
58
+ },
59
+ initialize: (environment) => config.resolveEnvironment === undefined
60
+ ? environment.bindings
61
+ : config.resolveEnvironment(environment.bindings),
62
+ identity(environment) {
63
+ return createIdentity({
64
+ issuer: issuer.accept(environment.publicUrl),
65
+ subject: build.schema.compiled.root.origin,
66
+ privateKey: typeof config.privateKey === 'function'
67
+ ? config.privateKey(environment.bindings)
68
+ : config.privateKey,
69
+ fetch: routedFetch(created, environment, config.selfBinding, settings.routeSubrequest),
70
+ ...(new URL(environment.publicUrl).protocol === 'http:'
71
+ ? { allowInsecureHttp: true }
72
+ : {}),
73
+ ...(settings.tokenExchange === undefined
74
+ ? {}
75
+ : { tokenExchange: settings.tokenExchange }),
76
+ });
77
+ },
78
+ cache: config.cache === false ? false : () => cloudflareCache(),
79
+ ...(config.durable === undefined
80
+ ? {}
81
+ : {
82
+ durable: (environment, request) => config.durable(environment.bindings, request, settings.durableOptions),
83
+ }),
84
+ server: {
85
+ health: { probe: { check: () => true } },
86
+ limits: {
87
+ maximumRequestBytes: settings.maximumRequestBytes ?? DEFAULT_MAXIMUM_REQUEST_BYTES,
88
+ maximumReleaseBytes: 1024 * 1024,
89
+ maximumBundleBytes: 8 * 1024 * 1024,
90
+ maximumDeliveryBytes: 8 * 1024 * 1024,
91
+ invocationTimeoutMs,
92
+ // Streamed binary bodies are never buffered, so their cap follows the Domain's binary
93
+ // Functions instead of maximumRequestBytes.
94
+ ...binaryRequestLimits(build, invocationTimeoutMs),
95
+ },
96
+ },
97
+ });
98
+ application = created;
99
+ return created;
100
+ };
101
+ return Object.freeze({
102
+ async fetch(request, bindings, context) {
103
+ const admission = await frontDoor.admit(request, bindings);
104
+ if (admission.kind !== 'execution')
105
+ return admission.response;
106
+ const { url, publicUrl } = admission;
107
+ const source = await realize();
108
+ if (config.frontend === undefined) {
109
+ const frontend = await frontendAsset(source.build.frontend, bindings.ASSETS, url, request, config.frontendRevision, config.frontendAddressed);
110
+ if (frontend !== undefined)
111
+ return withProviderVersion(frontend, bindings);
112
+ }
113
+ const response = await served(source, bindings).fetch(request, Object.freeze({ bindings, publicUrl }), context);
114
+ return withProviderVersion(response, bindings);
115
+ },
116
+ async prepare() {
117
+ await realize();
118
+ },
119
+ });
120
+ };
121
+ }
122
+ function routedFetch(application, environment, selfBinding, routeSubrequest) {
123
+ return async (input, init) => {
124
+ const { request, rejectRedirect } = prepareCloudflareRequest(input, init);
125
+ const destination = new URL(request.url);
126
+ if (destination.origin === environment.publicUrl) {
127
+ const self = selfBinding?.(environment.bindings);
128
+ return dispatchCloudflareRequest(request, rejectRedirect, (selected) => self === null || self === undefined
129
+ ? application.fetch(selected, environment)
130
+ : self.fetch(selected));
131
+ }
132
+ const route = routeSubrequest?.(destination, environment.bindings);
133
+ return dispatchCloudflareRequest(request, rejectRedirect, (selected) => route === null || route === undefined ? fetch(selected) : route.fetch(selected));
134
+ };
135
+ }
@@ -0,0 +1,11 @@
1
+ export type RequestDispatcher = (request: Request) => Response | Promise<Response>;
2
+ export interface CloudflareRequest {
3
+ readonly request: Request;
4
+ readonly rejectRedirect: boolean;
5
+ }
6
+ /** Construct a Cloudflare-compatible transport request without weakening redirect:error. */
7
+ export declare function prepareCloudflareRequest(input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]): CloudflareRequest;
8
+ /** Preserve Fetch redirect:error semantics on Cloudflare, whose transport rejects that mode. */
9
+ export declare function dispatchCloudflareRequest(request: Request, rejectRedirect: boolean, dispatch: RequestDispatcher): Promise<Response>;
10
+ /** Restore the requested URL omitted by Cloudflare service-binding Responses. */
11
+ export declare function adaptCloudflareResponse(request: Request, response: Response): Response;
@@ -0,0 +1,31 @@
1
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
2
+ /** Construct a Cloudflare-compatible transport request without weakening redirect:error. */
3
+ export function prepareCloudflareRequest(input, init) {
4
+ const rejectRedirect = init?.redirect === 'error' ||
5
+ (init?.redirect === undefined && input instanceof Request && input.redirect === 'error');
6
+ const request = new Request(input, rejectRedirect ? { ...init, redirect: 'manual' } : init);
7
+ return Object.freeze({ request, rejectRedirect });
8
+ }
9
+ /** Preserve Fetch redirect:error semantics on Cloudflare, whose transport rejects that mode. */
10
+ export async function dispatchCloudflareRequest(request, rejectRedirect, dispatch) {
11
+ const response = adaptCloudflareResponse(request, await dispatch(request));
12
+ if (!rejectRedirect)
13
+ return response;
14
+ if (!response.redirected && !REDIRECT_STATUSES.has(response.status))
15
+ return response;
16
+ await response.body?.cancel();
17
+ throw new TypeError('Redirects are not allowed for this request.');
18
+ }
19
+ /** Restore the requested URL omitted by Cloudflare service-binding Responses. */
20
+ export function adaptCloudflareResponse(request, response) {
21
+ if (response.url !== '')
22
+ return response;
23
+ return new Proxy(response, {
24
+ get(target, property) {
25
+ if (property === 'url')
26
+ return request.url;
27
+ const value = Reflect.get(target, property, target);
28
+ return typeof value === 'function' ? value.bind(target) : value;
29
+ },
30
+ });
31
+ }
@@ -0,0 +1,56 @@
1
+ import type { BuildMaterial } from '@astrale-os/sdk/deployment/build/material';
2
+ export type { CloudflareWorker } from './entry.js';
3
+ export interface Fetcher {
4
+ fetch(request: Request): Response | Promise<Response>;
5
+ }
6
+ /** Bindings the adapter owns; a deployment's host binds them beside the author's own. */
7
+ export interface CloudflareAdapterBindings {
8
+ readonly ASTRALE_SIGNING_IDENTITY?: string;
9
+ readonly ASTRALE_VERSION_METADATA?: {
10
+ readonly id: string;
11
+ };
12
+ /** Serving origin of this deployment. */
13
+ readonly WORKER_URL: string;
14
+ /**
15
+ * Build digest an immutable-deployment host recomputed from the uploaded bytes. Bound, the Worker
16
+ * serves the DomainRelease v4 of its code at release.json.
17
+ */
18
+ readonly ASTRALE_BUILD_DIGEST: string;
19
+ /** Execution settings of this deployment, as canonical JSON (see `deploymentSettings`). */
20
+ readonly ASTRALE_SETTINGS?: string;
21
+ readonly ASSETS?: Fetcher;
22
+ readonly SELF?: Fetcher;
23
+ }
24
+ export interface CloudflareFrontDoorConfig {
25
+ /** Generated frontend evidence available without restoring the execution Build. */
26
+ readonly frontend?: BuildMaterial['frontend'];
27
+ /** Generated browser-file identity used only for deployment propagation checks. */
28
+ readonly frontendRevision?: string;
29
+ /** Served frontend paths the bundler content-addressed; absent means none may be retained. */
30
+ readonly frontendAddressed?: readonly string[];
31
+ }
32
+ export type CloudflareFrontDoorAdmission =
33
+ /** The request is not for this isolate's serving origin. */
34
+ {
35
+ readonly kind: 'refused';
36
+ readonly response: Response;
37
+ }
38
+ /** A public frontend file answered the request without the execution Service. */
39
+ | {
40
+ readonly kind: 'frontend';
41
+ readonly response: Response;
42
+ }
43
+ /** The request needs the execution Service, under this isolate's one serving origin. */
44
+ | {
45
+ readonly kind: 'execution';
46
+ readonly url: URL;
47
+ readonly publicUrl: string;
48
+ };
49
+ export interface CloudflareFrontDoor<Bindings extends CloudflareAdapterBindings> {
50
+ admit(request: Request, bindings: Bindings): Promise<CloudflareFrontDoorAdmission>;
51
+ /** The serving origin this isolate pinned on its first admitted request. */
52
+ current(): string | undefined;
53
+ }
54
+ /** Admit requests to one serving origin and answer public frontend files, per isolate. */
55
+ export declare function cloudflareFrontDoor<Bindings extends CloudflareAdapterBindings>(config: CloudflareFrontDoorConfig): CloudflareFrontDoor<Bindings>;
56
+ export declare function withProviderVersion(response: Response, bindings: CloudflareAdapterBindings): Response;
@@ -0,0 +1,59 @@
1
+ import { frontendAsset } from './frontend.js';
2
+ /** Admit requests to one serving origin and answer public frontend files, per isolate. */
3
+ export function cloudflareFrontDoor(config) {
4
+ let currentPublicUrl;
5
+ return Object.freeze({
6
+ async admit(request, bindings) {
7
+ const url = new URL(request.url);
8
+ const publicUrl = canonicalServingUrl(bindings.WORKER_URL);
9
+ if (requestOrigin(url, request) !== publicUrl)
10
+ return refused('Request origin differs from this deployment URL.');
11
+ if (currentPublicUrl !== undefined && currentPublicUrl !== publicUrl) {
12
+ return refused('Request origin differs from the current Release.');
13
+ }
14
+ currentPublicUrl = publicUrl;
15
+ if (config.frontend !== undefined) {
16
+ const frontend = await frontendAsset(config.frontend, bindings.ASSETS, url, request, config.frontendRevision, config.frontendAddressed);
17
+ if (frontend !== undefined) {
18
+ return { kind: 'frontend', response: withProviderVersion(frontend, bindings) };
19
+ }
20
+ }
21
+ return { kind: 'execution', url, publicUrl };
22
+ },
23
+ current: () => currentPublicUrl,
24
+ });
25
+ }
26
+ export function withProviderVersion(response, bindings) {
27
+ if (bindings.ASTRALE_VERSION_METADATA === undefined)
28
+ return response;
29
+ const versioned = new Response(response.body, response);
30
+ versioned.headers.set('X-Astrale-Worker-Version', bindings.ASTRALE_VERSION_METADATA.id);
31
+ return versioned;
32
+ }
33
+ function refused(message) {
34
+ return { kind: 'refused', response: new Response(message, { status: 421 }) };
35
+ }
36
+ function requestOrigin(url, request) {
37
+ if (url.protocol !== 'http:')
38
+ return url.origin;
39
+ const forwarded = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase();
40
+ return forwarded === 'https' ? `https://${url.host}` : url.origin;
41
+ }
42
+ function canonicalServingUrl(input) {
43
+ let url;
44
+ try {
45
+ url = new URL(input);
46
+ }
47
+ catch (cause) {
48
+ throw new TypeError('Cloudflare Worker serving URL is invalid.', { cause });
49
+ }
50
+ if ((url.protocol !== 'https:' && url.protocol !== 'http:') ||
51
+ url.username !== '' ||
52
+ url.password !== '' ||
53
+ url.pathname !== '/' ||
54
+ url.search !== '' ||
55
+ url.hash !== '') {
56
+ throw new TypeError('Cloudflare Worker serving URL must be one HTTP(S) origin.');
57
+ }
58
+ return url.origin;
59
+ }
@@ -0,0 +1,4 @@
1
+ import type { BuildMaterial } from '@astrale-os/sdk/deployment/build/material';
2
+ import type { Fetcher } from './front.js';
3
+ /** Serve public frontend files without realizing the Domain's execution Runtime. */
4
+ export declare function frontendAsset(frontend: BuildMaterial['frontend'], assets: Fetcher | undefined, url: URL, request: Request, revision?: string, addressed?: readonly string[]): Promise<Response | undefined>;
@@ -0,0 +1,83 @@
1
+ /** Serve public frontend files without realizing the Domain's execution Runtime. */
2
+ export async function frontendAsset(frontend, assets, url, request, revision, addressed) {
3
+ if (frontend === undefined || frontend.source.kind === 'external')
4
+ return undefined;
5
+ if (reserved(url.pathname) || (request.method !== 'GET' && request.method !== 'HEAD')) {
6
+ return undefined;
7
+ }
8
+ const assetPath = url.pathname.startsWith('/assets/');
9
+ const route = assetPath
10
+ ? undefined
11
+ : frontend.routes
12
+ .filter((candidate) => candidate.path === url.pathname ||
13
+ (frontend.source.kind === 'vite' &&
14
+ frontend.source.spa &&
15
+ (candidate.path === '/' || url.pathname.startsWith(`${candidate.path}/`))))
16
+ .sort((left, right) => right.path.length - left.path.length)[0];
17
+ if (assets === undefined)
18
+ return undefined;
19
+ if (route === undefined) {
20
+ const response = await assets.fetch(request);
21
+ return assetPath || response.status !== 404
22
+ ? publicAsset(response, revision, retainable(url, addressed))
23
+ : undefined;
24
+ }
25
+ if (route.path !== url.pathname) {
26
+ const response = await assets.fetch(request);
27
+ if (response.status !== 404)
28
+ return publicAsset(response, revision, retainable(url, addressed));
29
+ }
30
+ // A route serves its document, never the requested path, so the document decides: it is named by
31
+ // the route rather than by its bytes, and `publicAsset` already refuses to retain it.
32
+ return publicAsset(await assets.fetch(new Request(new URL(`/${route.document}${url.search}`, url.origin), request)), revision, false);
33
+ }
34
+ /**
35
+ * Whether this exact served path is one the build content-addressed.
36
+ *
37
+ * The set is evidence from the bundler that named the file, not an inference from where it sits: a
38
+ * path under the bundle's own directory may still have been copied there verbatim from `public/`,
39
+ * and a content-addressed output may sit anywhere the project's configuration puts it.
40
+ */
41
+ function retainable(url, addressed) {
42
+ if (addressed === undefined || addressed.length === 0)
43
+ return false;
44
+ const path = decodeURIComponent(url.pathname).replace(/^\//u, '');
45
+ // A document's 304 carries no media type to recognise it by, so its name has to.
46
+ if (/\.html?$/iu.test(path))
47
+ return false;
48
+ return addressed.includes(path);
49
+ }
50
+ function publicAsset(response, revision, addressed) {
51
+ // Plain Views have an opaque sandbox origin. Their modules, CSS and fonts still need
52
+ // public reads; this neither enables credentials nor changes execution endpoint CORS.
53
+ const readable = new Response(response.body, response);
54
+ if (!readable.headers.has('Access-Control-Allow-Origin'))
55
+ readable.headers.set('Access-Control-Allow-Origin', '*');
56
+ if (revision !== undefined)
57
+ readable.headers.set('X-Astrale-Frontend', revision);
58
+ // A 304 states that the copy the browser already holds is current. Answering it with `no-store`
59
+ // would tell that browser to discard what it was just told to keep, so the next visit downloads
60
+ // the file again and every revalidation costs a full transfer: worse than never caching at all.
61
+ const validated = response.status === 304;
62
+ // Do not retain transient asset misses.
63
+ if (!response.ok && !validated) {
64
+ readable.headers.set('Cache-Control', 'no-store');
65
+ }
66
+ else if (response.headers.get('Content-Type')?.split(';')[0] === 'text/html') {
67
+ // Documents select hashed assets that a later Release removes, so a document is never used
68
+ // without asking first. Keeping it still lets that question be answered by a bodiless 304.
69
+ readable.headers.set('Cache-Control', 'no-cache');
70
+ }
71
+ else if (addressed) {
72
+ // The bytes behind this name can never change, so a revalidation could only ever confirm what
73
+ // the name already states. `immutable` is deliberately absent: it would also suppress the
74
+ // revalidation a reload performs, which is the one remedy a reader has if this were ever
75
+ // claimed wrongly. Anything not proved content-addressed keeps the platform default, which
76
+ // revalidates and is therefore never wrong, only slower.
77
+ readable.headers.set('Cache-Control', 'public, max-age=31536000');
78
+ }
79
+ return readable;
80
+ }
81
+ function reserved(path) {
82
+ return ['/releases', '/install', '/health', '/meta', '/.well-known', '/invoke'].some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
83
+ }
@@ -0,0 +1,7 @@
1
+ import type { JsonWebKey } from '@astrale-os/sdk/auth';
2
+ /** Decode the secret representation at the Worker binding boundary. */
3
+ export declare function decodeSigningIdentity(input: string): JsonWebKey;
4
+ /** Remove adapter-owned signing material before Runtime initialization. */
5
+ export declare function runtimeBindings<Bindings extends {
6
+ readonly ASTRALE_SIGNING_IDENTITY: string;
7
+ }>(bindings: Bindings): Omit<Bindings, 'ASTRALE_SIGNING_IDENTITY'>;
@@ -0,0 +1,23 @@
1
+ /** Decode the secret representation at the Worker binding boundary. */
2
+ export function decodeSigningIdentity(input) {
3
+ if (typeof input !== 'string' || input.length === 0)
4
+ invalid();
5
+ let decoded;
6
+ try {
7
+ decoded = JSON.parse(input);
8
+ }
9
+ catch (cause) {
10
+ throw new TypeError('Cloudflare signing identity secret is invalid JSON.', { cause });
11
+ }
12
+ if (decoded === null || typeof decoded !== 'object' || Array.isArray(decoded))
13
+ invalid();
14
+ return decoded;
15
+ }
16
+ /** Remove adapter-owned signing material before Runtime initialization. */
17
+ export function runtimeBindings(bindings) {
18
+ const { ASTRALE_SIGNING_IDENTITY: _identity, ...runtime } = bindings;
19
+ return runtime;
20
+ }
21
+ function invalid() {
22
+ throw new TypeError('Cloudflare signing identity secret is invalid.');
23
+ }