@astrale-os/adapter-cloudflare 0.4.10 → 0.5.0-beta.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/CHANGELOG.md +1193 -0
  2. package/README.md +29 -0
  3. package/dist/adapter.d.ts +15 -0
  4. package/dist/adapter.js +76 -0
  5. package/dist/build/artifact.d.ts +7 -0
  6. package/dist/build/artifact.js +165 -0
  7. package/dist/build/bundle/admit.d.ts +1 -0
  8. package/dist/build/bundle/admit.js +9 -0
  9. package/dist/build/closure.d.ts +2 -0
  10. package/dist/build/closure.js +22 -0
  11. package/dist/build/codegen/execution.d.ts +3 -0
  12. package/dist/build/codegen/execution.js +2 -0
  13. package/dist/{codegen → build/codegen}/merge.d.ts +0 -1
  14. package/dist/{codegen → build/codegen}/merge.js +0 -1
  15. package/dist/{codegen → build/codegen}/wrangler.d.ts +19 -4
  16. package/dist/{codegen → build/codegen}/wrangler.js +49 -13
  17. package/dist/build/configuration/addressing.d.ts +2 -0
  18. package/dist/build/configuration/addressing.js +11 -0
  19. package/dist/build/configuration/invocation-timeout.d.ts +2 -0
  20. package/dist/build/configuration/invocation-timeout.js +9 -0
  21. package/dist/build/configuration/request-limit.d.ts +2 -0
  22. package/dist/build/configuration/request-limit.js +9 -0
  23. package/dist/build/configuration/router.d.ts +7 -0
  24. package/dist/build/configuration/router.js +11 -0
  25. package/dist/build/configuration/worker-name.d.ts +2 -0
  26. package/dist/build/configuration/worker-name.js +18 -0
  27. package/dist/build/configuration.d.ts +5 -0
  28. package/dist/build/configuration.js +5 -0
  29. package/dist/build/direct.d.ts +4 -0
  30. package/dist/build/direct.js +93 -0
  31. package/dist/build/frontend/files.d.ts +7 -0
  32. package/dist/build/frontend/files.js +60 -0
  33. package/dist/build/frontend/routes.d.ts +2 -0
  34. package/dist/build/frontend/routes.js +11 -0
  35. package/dist/build/index.d.ts +8 -0
  36. package/dist/build/index.js +7 -0
  37. package/dist/build/materialize.d.ts +4 -0
  38. package/dist/build/materialize.js +10 -0
  39. package/dist/build/metafile.d.ts +5 -0
  40. package/dist/build/metafile.js +14 -0
  41. package/dist/build/qualification.d.ts +5 -0
  42. package/dist/build/qualification.js +7 -0
  43. package/dist/build/roots.d.ts +2 -0
  44. package/dist/build/roots.js +34 -0
  45. package/dist/build/worker/artifact.d.ts +40 -0
  46. package/dist/build/worker/artifact.js +1 -0
  47. package/dist/build/worker/artifact.load.d.ts +3 -0
  48. package/dist/build/worker/artifact.load.js +308 -0
  49. package/dist/build/worker/artifact.manifest.d.ts +48 -0
  50. package/dist/build/worker/artifact.manifest.js +87 -0
  51. package/dist/build/worker/artifact.paths.d.ts +4 -0
  52. package/dist/build/worker/artifact.paths.js +25 -0
  53. package/dist/build/worker/codegen/entry.d.ts +2 -0
  54. package/dist/build/worker/codegen/entry.js +28 -0
  55. package/dist/build/worker/codegen/service.d.ts +18 -0
  56. package/dist/build/worker/codegen/service.js +53 -0
  57. package/dist/build/worker/execution.prepare.d.ts +18 -0
  58. package/dist/build/worker/execution.prepare.js +112 -0
  59. package/dist/build/worker/index.d.ts +2 -0
  60. package/dist/build/worker/index.js +1 -0
  61. package/dist/build/worker/modules.d.ts +11 -0
  62. package/dist/build/worker/modules.js +26 -0
  63. package/dist/build/worker/runtime.d.ts +10 -0
  64. package/dist/build/worker/runtime.js +35 -0
  65. package/dist/build/worker/specifier.d.ts +1 -0
  66. package/dist/build/worker/specifier.js +5 -0
  67. package/dist/cloudflare.d.ts +1 -37
  68. package/dist/cloudflare.js +1 -271
  69. package/dist/deploy/deploy.d.ts +16 -0
  70. package/dist/deploy/deploy.js +204 -0
  71. package/dist/deploy/index.d.ts +1 -0
  72. package/dist/deploy/index.js +1 -0
  73. package/dist/deploy/output.d.ts +2 -0
  74. package/dist/deploy/output.js +10 -0
  75. package/dist/development/develop.d.ts +15 -0
  76. package/dist/development/develop.js +270 -0
  77. package/dist/development/frontend.d.ts +11 -0
  78. package/dist/development/frontend.js +109 -0
  79. package/dist/development/host.d.ts +2 -0
  80. package/dist/development/host.js +46 -0
  81. package/dist/development/port.d.ts +1 -0
  82. package/dist/development/port.js +12 -0
  83. package/dist/development/readiness.d.ts +14 -0
  84. package/dist/development/readiness.js +71 -0
  85. package/dist/development/resolved-fetch.d.ts +17 -0
  86. package/dist/development/resolved-fetch.js +80 -0
  87. package/dist/development/worker-output.d.ts +2 -0
  88. package/dist/development/worker-output.js +25 -0
  89. package/dist/development/worker.d.ts +17 -0
  90. package/dist/development/worker.js +147 -0
  91. package/dist/identity/binding.d.ts +2 -0
  92. package/dist/identity/binding.js +2 -0
  93. package/dist/identity/index.d.ts +3 -0
  94. package/dist/identity/index.js +3 -0
  95. package/dist/identity/material.d.ts +7 -0
  96. package/dist/identity/material.js +42 -0
  97. package/dist/identity/secret.d.ts +3 -0
  98. package/dist/identity/secret.js +7 -0
  99. package/dist/identity/source.d.ts +26 -0
  100. package/dist/identity/source.js +127 -0
  101. package/dist/index.d.ts +8 -8
  102. package/dist/index.js +7 -7
  103. package/dist/params.d.ts +50 -23
  104. package/dist/params.js +0 -1
  105. package/dist/release/deployment.d.ts +44 -0
  106. package/dist/release/deployment.js +141 -0
  107. package/dist/release/index.d.ts +2 -0
  108. package/dist/release/index.js +2 -0
  109. package/dist/release/staged-worker-name.d.ts +3 -0
  110. package/dist/release/staged-worker-name.js +10 -0
  111. package/dist/worker/entry.d.ts +44 -0
  112. package/dist/worker/entry.js +184 -0
  113. package/dist/worker/fetch.d.ts +11 -0
  114. package/dist/worker/fetch.js +31 -0
  115. package/dist/worker/identity.d.ts +7 -0
  116. package/dist/worker/identity.js +23 -0
  117. package/dist/worker/index.d.ts +2 -0
  118. package/dist/worker/index.js +2 -0
  119. package/dist/wrangler/bundle.d.ts +10 -0
  120. package/dist/wrangler/bundle.js +27 -0
  121. package/dist/wrangler/deploy.d.ts +24 -0
  122. package/dist/wrangler/deploy.js +44 -0
  123. package/dist/wrangler/index.d.ts +5 -0
  124. package/dist/wrangler/index.js +5 -0
  125. package/dist/wrangler/process.d.ts +17 -0
  126. package/dist/wrangler/process.js +115 -0
  127. package/dist/wrangler/secrets.d.ts +6 -0
  128. package/dist/wrangler/secrets.js +58 -0
  129. package/dist/wrangler/status.d.ts +14 -0
  130. package/dist/wrangler/status.js +56 -0
  131. package/dist/wrangler/type-generation.d.ts +6 -0
  132. package/dist/wrangler/type-generation.js +19 -0
  133. package/package.json +41 -18
  134. package/template/astrale.config.ts +26 -18
  135. package/dist/assets-pack.d.ts +0 -8
  136. package/dist/assets-pack.d.ts.map +0 -1
  137. package/dist/assets-pack.js +0 -30
  138. package/dist/assets-pack.js.map +0 -1
  139. package/dist/build.d.ts +0 -16
  140. package/dist/build.d.ts.map +0 -1
  141. package/dist/build.js +0 -15
  142. package/dist/build.js.map +0 -1
  143. package/dist/client.d.ts +0 -17
  144. package/dist/client.d.ts.map +0 -1
  145. package/dist/client.js +0 -59
  146. package/dist/client.js.map +0 -1
  147. package/dist/cloudflare.d.ts.map +0 -1
  148. package/dist/cloudflare.js.map +0 -1
  149. package/dist/codegen/identity.d.ts +0 -10
  150. package/dist/codegen/identity.d.ts.map +0 -1
  151. package/dist/codegen/identity.js +0 -32
  152. package/dist/codegen/identity.js.map +0 -1
  153. package/dist/codegen/merge.d.ts.map +0 -1
  154. package/dist/codegen/merge.js.map +0 -1
  155. package/dist/codegen/worker.d.ts +0 -51
  156. package/dist/codegen/worker.d.ts.map +0 -1
  157. package/dist/codegen/worker.js +0 -120
  158. package/dist/codegen/worker.js.map +0 -1
  159. package/dist/codegen/wrangler.d.ts.map +0 -1
  160. package/dist/codegen/wrangler.js.map +0 -1
  161. package/dist/index.d.ts.map +0 -1
  162. package/dist/index.js.map +0 -1
  163. package/dist/params.d.ts.map +0 -1
  164. package/dist/params.js.map +0 -1
  165. package/dist/parse-output.d.ts +0 -25
  166. package/dist/parse-output.d.ts.map +0 -1
  167. package/dist/parse-output.js +0 -53
  168. package/dist/parse-output.js.map +0 -1
  169. package/dist/wrangler-cli.d.ts +0 -78
  170. package/dist/wrangler-cli.d.ts.map +0 -1
  171. package/dist/wrangler-cli.js +0 -251
  172. package/dist/wrangler-cli.js.map +0 -1
  173. package/src/assets-pack.ts +0 -32
  174. package/src/build.ts +0 -16
  175. package/src/client.ts +0 -89
  176. package/src/cloudflare.ts +0 -321
  177. package/src/codegen/identity.ts +0 -40
  178. package/src/codegen/merge.ts +0 -92
  179. package/src/codegen/worker.ts +0 -136
  180. package/src/codegen/wrangler.ts +0 -105
  181. package/src/index.ts +0 -21
  182. package/src/params.ts +0 -96
  183. package/src/parse-output.ts +0 -54
  184. package/src/wrangler-cli.ts +0 -324
  185. package/template/.env.example +0 -9
  186. package/template/.gitignore.template +0 -16
  187. package/template/CLAUDE.md +0 -13
  188. package/template/README.md +0 -47
  189. package/template/client/.gitignore.template +0 -4
  190. package/template/client/__tests__/app.test.tsx +0 -15
  191. package/template/client/components.json +0 -25
  192. package/template/client/index.html +0 -12
  193. package/template/client/package.json +0 -35
  194. package/template/client/src/app.tsx +0 -52
  195. package/template/client/src/components/ui/cn.ts +0 -6
  196. package/template/client/src/main.tsx +0 -9
  197. package/template/client/src/styles.css +0 -78
  198. package/template/client/tsconfig.json +0 -26
  199. package/template/client/vite.config.ts +0 -22
  200. package/template/client/vitest.config.ts +0 -13
  201. package/template/core/README.md +0 -7
  202. package/template/deps.ts +0 -9
  203. package/template/domain.ts +0 -11
  204. package/template/env.ts +0 -8
  205. package/template/icons.ts +0 -4
  206. package/template/integrations/README.md +0 -7
  207. package/template/oxlint.config.ts +0 -1
  208. package/template/package.json +0 -58
  209. package/template/pnpm-workspace.yaml +0 -31
  210. package/template/runtime/index.ts +0 -8
  211. package/template/schema/index.ts +0 -10
  212. package/template/simulation/README.md +0 -12
  213. package/template/tsconfig.json +0 -28
  214. package/template/vitest.config.ts +0 -7
@@ -0,0 +1,141 @@
1
+ import { sha256 } from '@noble/hashes/sha2.js';
2
+ const DEPLOYMENT = /^sha256:[0-9a-f]{64}$/u;
3
+ /** Canonical provider material used only for staging, promotion, rollback, and cleanup. */
4
+ export function workerDeploymentMaterial(input) {
5
+ const release = executable(input.release);
6
+ const compatibilityFlags = uniqueStrings(input.runtime.compatibilityFlags, 'compatibility flag');
7
+ const vars = Object.fromEntries(Object.entries(input.bindings.vars)
8
+ .map(([name, value]) => {
9
+ stable(name, 'Variable binding name');
10
+ if (typeof value !== 'string')
11
+ invalid();
12
+ return [name, value];
13
+ })
14
+ .sort(([left], [right]) => compare(left, right)));
15
+ const services = [...input.bindings.services]
16
+ .map((binding) => ({
17
+ name: stable(binding.name, 'Service binding name'),
18
+ service: stable(binding.service, 'Service binding target'),
19
+ }))
20
+ .sort((left, right) => compare(left.name, right.name));
21
+ unique(services.map((binding) => binding.name), 'Service binding name');
22
+ const requiredSecrets = uniqueStrings(input.bindings.requiredSecrets, 'required secret');
23
+ unique([...Object.keys(vars), ...services.map((binding) => binding.name), ...requiredSecrets], 'Worker binding name');
24
+ const assets = input.assets === undefined ? undefined : canonicalAssets(input.assets);
25
+ return new TextEncoder().encode(`${JSON.stringify({
26
+ format: 'astrale.cloudflare.deployment',
27
+ version: 1,
28
+ release,
29
+ runtime: {
30
+ compatibilityDate: stable(input.runtime.compatibilityDate, 'compatibility date'),
31
+ compatibilityFlags,
32
+ },
33
+ bindings: { vars, services, requiredSecrets },
34
+ ...(assets === undefined ? {} : { assets }),
35
+ })}\n`);
36
+ }
37
+ /** Identify one immutable Cloudflare implementation without changing SDK or Publication identity. */
38
+ export function workerDeployment(input) {
39
+ let hexadecimal = '';
40
+ for (const byte of sha256(workerDeploymentMaterial(input))) {
41
+ hexadecimal += byte.toString(16).padStart(2, '0');
42
+ }
43
+ return `sha256:${hexadecimal}`;
44
+ }
45
+ /** Admit a serialized provider deployment identity at a Cloudflare boundary. */
46
+ export function acceptWorkerDeployment(input) {
47
+ if (typeof input !== 'string' || !DEPLOYMENT.test(input)) {
48
+ throw new TypeError('Cloudflare Worker deployment identity is invalid.');
49
+ }
50
+ return input;
51
+ }
52
+ function executable(input) {
53
+ const entrypoint = stablePath(input.entrypoint, 'Worker release entrypoint');
54
+ const modules = input.modules
55
+ .map((module) => ({
56
+ path: stablePath(module.path, 'Worker release module path'),
57
+ kind: module.kind,
58
+ digest: content(module.content),
59
+ }))
60
+ .sort((left, right) => compare(left.path, right.path));
61
+ unique(modules.map((module) => module.path), 'Worker release module path');
62
+ if (!modules.some((module) => module.path === entrypoint && module.kind === 'esm')) {
63
+ throw new TypeError('Worker release entrypoint must be an ES module in its module set.');
64
+ }
65
+ return { entrypoint, modules };
66
+ }
67
+ function canonicalAssets(input) {
68
+ const files = input.files
69
+ .map((file) => ({
70
+ path: stableAssetPath(file.path),
71
+ digest: content(file.content),
72
+ ...(file.contentType === undefined
73
+ ? {}
74
+ : { contentType: stable(file.contentType, 'Worker asset content type') }),
75
+ }))
76
+ .sort((left, right) => compare(left.path, right.path));
77
+ unique(files.map((file) => file.path), 'Worker asset path');
78
+ if (!['none', '404-page', 'single-page-application'].includes(input.notFound))
79
+ invalid();
80
+ if (input.htmlHandling !== undefined && input.htmlHandling !== 'none')
81
+ invalid();
82
+ return {
83
+ files,
84
+ notFound: input.notFound,
85
+ runWorkerFirst: input.runWorkerFirst,
86
+ htmlHandling: input.htmlHandling ?? 'none',
87
+ };
88
+ }
89
+ function uniqueStrings(input, label) {
90
+ const values = input.map((value) => stable(value, label)).sort(compare);
91
+ unique(values, label);
92
+ return values;
93
+ }
94
+ function unique(values, label) {
95
+ if (new Set(values).size !== values.length) {
96
+ throw new TypeError(`${label} must be unique.`);
97
+ }
98
+ }
99
+ function content(value) {
100
+ if (!(value instanceof Uint8Array))
101
+ invalid();
102
+ let hexadecimal = '';
103
+ for (const byte of sha256(value))
104
+ hexadecimal += byte.toString(16).padStart(2, '0');
105
+ return `sha256:${hexadecimal}`;
106
+ }
107
+ function stablePath(value, label) {
108
+ const admitted = stable(value, label);
109
+ if (admitted.startsWith('/') ||
110
+ admitted.includes('\\') ||
111
+ admitted.split('/').some((part) => part.length === 0 || part === '.' || part === '..')) {
112
+ invalid();
113
+ }
114
+ return admitted;
115
+ }
116
+ function stableAssetPath(value) {
117
+ const admitted = stable(value, 'Worker asset path');
118
+ if (!admitted.startsWith('/') ||
119
+ admitted.includes('\\') ||
120
+ admitted.includes('?') ||
121
+ admitted.includes('#') ||
122
+ admitted
123
+ .slice(1)
124
+ .split('/')
125
+ .some((part) => part.length === 0 || part === '.' || part === '..')) {
126
+ invalid();
127
+ }
128
+ return admitted;
129
+ }
130
+ function stable(value, label) {
131
+ if (typeof value !== 'string' || value.length === 0 || value.trim() !== value) {
132
+ throw new TypeError(`${label} must be stable non-empty text.`);
133
+ }
134
+ return value;
135
+ }
136
+ function compare(left, right) {
137
+ return left < right ? -1 : left > right ? 1 : 0;
138
+ }
139
+ function invalid() {
140
+ throw new TypeError('Cloudflare Worker deployment material is invalid.');
141
+ }
@@ -0,0 +1,2 @@
1
+ export { acceptWorkerDeployment, workerDeployment, workerDeploymentMaterial, type WorkerDeploymentId, type WorkerDeploymentInput, } from './deployment.js';
2
+ export { stagedWorkerName } from './staged-worker-name.js';
@@ -0,0 +1,2 @@
1
+ export { acceptWorkerDeployment, workerDeployment, workerDeploymentMaterial, } from './deployment.js';
2
+ export { stagedWorkerName } from './staged-worker-name.js';
@@ -0,0 +1,3 @@
1
+ import type { WorkerDeploymentId } from './deployment.js';
2
+ /** Provider deployment identities select immutable Workers inside the private namespace. */
3
+ export declare function stagedWorkerName(deployment: WorkerDeploymentId): string;
@@ -0,0 +1,10 @@
1
+ import { acceptWorkerDeployment } from './deployment.js';
2
+ const DEPLOYMENT = /^sha256:([0-9a-f]{64})$/u;
3
+ /** Provider deployment identities select immutable Workers inside the private namespace. */
4
+ export function stagedWorkerName(deployment) {
5
+ const digest = DEPLOYMENT.exec(acceptWorkerDeployment(deployment))?.[1];
6
+ if (digest === undefined)
7
+ throw new TypeError('Cloudflare Worker deployment identity is invalid.');
8
+ const encoded = BigInt(`0x${digest}`).toString(36).padStart(50, '0');
9
+ return `r-${encoded}`;
10
+ }
@@ -0,0 +1,44 @@
1
+ import type { JsonWebKey } from '@astrale-os/sdk/auth';
2
+ import type { BuildMaterial, GeneratedBuildMaterial } from '@astrale-os/sdk/deployment/build/material';
3
+ import type { ExchangeOptions, ExecutionContext } from '@astrale-os/sdk/execution';
4
+ import type { Runtime } from '@astrale-os/sdk/runtime';
5
+ export interface Fetcher {
6
+ fetch(request: Request): Response | Promise<Response>;
7
+ }
8
+ export interface CloudflareAdapterBindings {
9
+ readonly ASTRALE_SIGNING_IDENTITY?: string;
10
+ readonly WORKER_URL?: string;
11
+ readonly IDENTITY_ISS?: string;
12
+ readonly ASSETS?: Fetcher;
13
+ readonly SELF?: Fetcher;
14
+ readonly FRONTEND_DEV_URL?: string;
15
+ readonly DISPATCHER?: {
16
+ get(name: string): Fetcher;
17
+ };
18
+ }
19
+ export interface CloudflareWorkerConfig<RuntimeValue extends Runtime, Bindings extends CloudflareAdapterBindings, Environment, Material = BuildMaterial> {
20
+ /** Generated frontend evidence available without restoring the execution Build. */
21
+ readonly frontend?: BuildMaterial['frontend'];
22
+ /** Load the exact Runtime and Build once, after the isolate has accepted a request. */
23
+ readonly load: () => CloudflareWorkerSource<RuntimeValue, Material> | Promise<CloudflareWorkerSource<RuntimeValue, Material>>;
24
+ readonly privateKey: JsonWebKey | ((bindings: Bindings) => JsonWebKey);
25
+ readonly resolveEnvironment?: (bindings: Bindings) => Environment;
26
+ readonly resolveUrl?: (bindings: Bindings, requestOrigin: string) => string;
27
+ readonly providerAssignedWorker?: string;
28
+ readonly selfBinding?: (bindings: Bindings) => Fetcher | null | undefined;
29
+ readonly routeSubrequest?: (url: URL, bindings: Bindings) => Fetcher | null | undefined;
30
+ readonly invocationTimeoutMs?: number;
31
+ readonly maximumRequestBytes?: number;
32
+ readonly tokenExchange?: ExchangeOptions | false;
33
+ }
34
+ export interface CloudflareWorkerSource<RuntimeValue extends Runtime, Material = BuildMaterial> {
35
+ readonly runtime: RuntimeValue;
36
+ readonly material: Material;
37
+ }
38
+ export interface CloudflareWorker<Bindings> {
39
+ fetch(request: Request, environment: Bindings, executionContext?: ExecutionContext): Response | Promise<Response>;
40
+ }
41
+ /** Compose one Service implementation behind its provider-owned stable address. */
42
+ export declare function cloudflareWorkerEntry<Bindings extends CloudflareAdapterBindings, Environment = Bindings>(): <RuntimeValue extends Runtime>(config: CloudflareWorkerConfig<RuntimeValue, Bindings, Environment, BuildMaterial>) => CloudflareWorker<Bindings>;
43
+ /** Compose generated execution code whose exact Build material carries build-owner evidence. */
44
+ export declare function generatedCloudflareWorkerEntry<Bindings extends CloudflareAdapterBindings, Environment = Bindings>(): <RuntimeValue extends Runtime>(config: CloudflareWorkerConfig<RuntimeValue, Bindings, Environment, GeneratedBuildMaterial>) => CloudflareWorker<Bindings>;
@@ -0,0 +1,184 @@
1
+ import { issuer } from '@astrale-os/sdk/auth';
2
+ import { restoreBuild, restoreGeneratedBuild } from '@astrale-os/sdk/deployment/build/material';
3
+ import { addressing, assemble } from '@astrale-os/sdk/deployment/release/runtime';
4
+ import { createIdentity, serve } from '@astrale-os/sdk/execution';
5
+ import { dispatchCloudflareRequest, prepareCloudflareRequest } from './fetch.js';
6
+ /** Compose one Service implementation behind its provider-owned stable address. */
7
+ export function cloudflareWorkerEntry() {
8
+ return createCloudflareWorkerEntry(restoreBuild);
9
+ }
10
+ /** Compose generated execution code whose exact Build material carries build-owner evidence. */
11
+ export function generatedCloudflareWorkerEntry() {
12
+ return createCloudflareWorkerEntry(restoreGeneratedBuild);
13
+ }
14
+ function createCloudflareWorkerEntry(restore) {
15
+ return function (config) {
16
+ let currentIssuer;
17
+ let realized;
18
+ const realize = () => {
19
+ if (realized !== undefined)
20
+ return realized;
21
+ realized = Promise.resolve()
22
+ .then(config.load)
23
+ .then((source) => {
24
+ const build = restore(source.material, source.runtime);
25
+ const application = serve({
26
+ runtime: source.runtime,
27
+ load(environment) {
28
+ if (currentIssuer !== environment.issuer) {
29
+ throw new TypeError('Cloudflare Worker request origin differs from its current Release.');
30
+ }
31
+ return assemble(build, addressing(environment.issuer));
32
+ },
33
+ initialize: (environment) => config.resolveEnvironment === undefined
34
+ ? environment.bindings
35
+ : config.resolveEnvironment(environment.bindings),
36
+ identity(environment) {
37
+ return createIdentity({
38
+ issuer: issuer.accept(environment.issuer),
39
+ subject: build.schema.compiled.root.origin,
40
+ privateKey: typeof config.privateKey === 'function'
41
+ ? config.privateKey(environment.bindings)
42
+ : config.privateKey,
43
+ fetch: routedFetch(application, environment, config),
44
+ ...(new URL(environment.issuer).protocol === 'http:'
45
+ ? { allowInsecureHttp: true }
46
+ : {}),
47
+ ...(config.tokenExchange === undefined
48
+ ? {}
49
+ : { tokenExchange: config.tokenExchange }),
50
+ });
51
+ },
52
+ server: {
53
+ health: { probe: { check: () => true } },
54
+ limits: {
55
+ maximumRequestBytes: config.maximumRequestBytes ?? 1024 * 1024,
56
+ maximumPublicationBytes: 1024 * 1024,
57
+ maximumBundleBytes: 8 * 1024 * 1024,
58
+ maximumDeliveryBytes: 8 * 1024 * 1024,
59
+ invocationTimeoutMs: config.invocationTimeoutMs ?? 30_000,
60
+ },
61
+ },
62
+ });
63
+ return Object.freeze({ build, application });
64
+ });
65
+ return realized;
66
+ };
67
+ return Object.freeze({
68
+ async fetch(request, bindings, context) {
69
+ const url = new URL(request.url);
70
+ const issuer = canonicalServingUrl(bindings.WORKER_URL ??
71
+ bindings.IDENTITY_ISS ??
72
+ config.resolveUrl?.(bindings, requestOrigin(url, request)) ??
73
+ requestOrigin(url, request));
74
+ if (config.providerAssignedWorker !== undefined &&
75
+ bindings.WORKER_URL === undefined &&
76
+ bindings.IDENTITY_ISS === undefined &&
77
+ !matchesWorkersDevClaim(issuer, config.providerAssignedWorker)) {
78
+ return new Response('Request origin differs from provider-assigned Addressing.', {
79
+ status: 421,
80
+ });
81
+ }
82
+ if (currentIssuer !== undefined && currentIssuer !== issuer) {
83
+ return new Response('Request origin differs from the current Release.', { status: 421 });
84
+ }
85
+ currentIssuer = issuer;
86
+ if (config.frontend !== undefined) {
87
+ const frontend = await frontendAsset(config.frontend, bindings, url, request);
88
+ if (frontend !== undefined)
89
+ return frontend;
90
+ }
91
+ const { application, build } = await realize();
92
+ if (config.frontend === undefined) {
93
+ const frontend = await frontendAsset(build.frontend, bindings, url, request);
94
+ if (frontend !== undefined)
95
+ return frontend;
96
+ }
97
+ return application.fetch(request, Object.freeze({ bindings, issuer }), context);
98
+ },
99
+ });
100
+ };
101
+ }
102
+ function routedFetch(application, environment, config) {
103
+ return async (input, init) => {
104
+ const { request, rejectRedirect } = prepareCloudflareRequest(input, init);
105
+ const destination = new URL(request.url);
106
+ if (destination.origin === environment.issuer) {
107
+ const self = config.selfBinding?.(environment.bindings);
108
+ return dispatchCloudflareRequest(request, rejectRedirect, (selected) => self === null || self === undefined
109
+ ? application.fetch(selected, environment)
110
+ : self.fetch(selected));
111
+ }
112
+ const route = config.routeSubrequest?.(destination, environment.bindings);
113
+ return dispatchCloudflareRequest(request, rejectRedirect, (selected) => route === null || route === undefined ? fetch(selected) : route.fetch(selected));
114
+ };
115
+ }
116
+ async function frontendAsset(frontend, environment, url, request) {
117
+ if (frontend === undefined || frontend.source.kind === 'external')
118
+ return undefined;
119
+ if (reserved(url.pathname) || (request.method !== 'GET' && request.method !== 'HEAD')) {
120
+ return undefined;
121
+ }
122
+ const development = environment.FRONTEND_DEV_URL?.replace(/\/+$/u, '');
123
+ if (development !== undefined && development.length > 0) {
124
+ return fetch(new Request(new URL(`${url.pathname}${url.search}`, `${development}/`), request));
125
+ }
126
+ const assetPath = url.pathname.startsWith('/assets/');
127
+ const route = assetPath
128
+ ? undefined
129
+ : frontend.routes
130
+ .filter((candidate) => candidate.path === url.pathname ||
131
+ (frontend.source.kind === 'vite' &&
132
+ frontend.source.spa &&
133
+ (candidate.path === '/' || url.pathname.startsWith(`${candidate.path}/`))))
134
+ .sort((left, right) => right.path.length - left.path.length)[0];
135
+ const assets = environment.ASSETS;
136
+ if (assets === undefined)
137
+ return undefined;
138
+ if (route === undefined) {
139
+ const response = await assets.fetch(request);
140
+ return assetPath || response.status !== 404 ? response : undefined;
141
+ }
142
+ if (route.path !== url.pathname) {
143
+ const response = await assets.fetch(request);
144
+ if (response.status !== 404)
145
+ return response;
146
+ }
147
+ return assets.fetch(new Request(new URL(`/${route.document}${url.search}`, url.origin), request));
148
+ }
149
+ function reserved(path) {
150
+ return ['/releases', '/install', '/health', '/meta', '/.well-known'].some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
151
+ }
152
+ function requestOrigin(url, request) {
153
+ if (url.protocol !== 'http:')
154
+ return url.origin;
155
+ const forwarded = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase();
156
+ return forwarded === 'https' ? `https://${url.host}` : url.origin;
157
+ }
158
+ function canonicalServingUrl(input) {
159
+ let url;
160
+ try {
161
+ url = new URL(input);
162
+ }
163
+ catch (cause) {
164
+ throw new TypeError('Cloudflare Worker serving URL is invalid.', { cause });
165
+ }
166
+ if ((url.protocol !== 'https:' && url.protocol !== 'http:') ||
167
+ url.username !== '' ||
168
+ url.password !== '' ||
169
+ url.pathname !== '/' ||
170
+ url.search !== '' ||
171
+ url.hash !== '') {
172
+ throw new TypeError('Cloudflare Worker serving URL must be one HTTP(S) origin.');
173
+ }
174
+ return url.origin;
175
+ }
176
+ function matchesWorkersDevClaim(issuer, expectedWorker) {
177
+ const url = new URL(issuer);
178
+ const labels = url.hostname.split('.');
179
+ return (url.protocol === 'https:' &&
180
+ labels.length >= 4 &&
181
+ labels[0] === expectedWorker &&
182
+ labels.at(-2) === 'workers' &&
183
+ labels.at(-1) === 'dev');
184
+ }
@@ -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,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
+ }
@@ -0,0 +1,2 @@
1
+ export * from './entry.js';
2
+ export { decodeSigningIdentity, runtimeBindings } from './identity.js';
@@ -0,0 +1,2 @@
1
+ export * from './entry.js';
2
+ export { decodeSigningIdentity, runtimeBindings } from './identity.js';
@@ -0,0 +1,10 @@
1
+ export declare function runWranglerBundle(args: {
2
+ projectDir: string;
3
+ configPath: string;
4
+ outDir: string;
5
+ onLog?: (line: string) => void;
6
+ signal?: AbortSignal;
7
+ }): Promise<{
8
+ readonly bundlePath: string;
9
+ readonly metafilePath: string;
10
+ }>;
@@ -0,0 +1,27 @@
1
+ import { readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { runCapture, wranglerCommand } from './process.js';
4
+ export async function runWranglerBundle(args) {
5
+ const { cmd, prefix } = wranglerCommand(args.projectDir);
6
+ const { code, out } = await runCapture(cmd, [
7
+ ...prefix,
8
+ 'deploy',
9
+ '--dry-run',
10
+ '--outdir',
11
+ args.outDir,
12
+ '--metafile',
13
+ '--config',
14
+ args.configPath,
15
+ ], args.projectDir, args.onLog, args.signal);
16
+ if (code !== 0)
17
+ throw new Error(`wrangler bundle failed (exit ${code}): ${out.slice(-400)}`);
18
+ const javascript = readdirSync(args.outDir).filter((file) => file.endsWith('.js'));
19
+ if (javascript.length === 0) {
20
+ throw new Error(`wrangler bundle produced no .js in ${args.outDir}`);
21
+ }
22
+ const preferred = javascript.find((file) => file.startsWith('worker')) ?? javascript[0];
23
+ return Object.freeze({
24
+ bundlePath: join(args.outDir, preferred),
25
+ metafilePath: join(args.outDir, 'bundle-meta.json'),
26
+ });
27
+ }
@@ -0,0 +1,24 @@
1
+ export interface DeployArgs {
2
+ configPath: string;
3
+ secrets?: Readonly<Record<string, string>>;
4
+ route?: string;
5
+ onLog?: (line: string) => void;
6
+ signal?: AbortSignal;
7
+ }
8
+ export declare class WranglerDeployError extends Error {
9
+ readonly applied?: {
10
+ readonly url?: string;
11
+ readonly deploymentVersion?: string;
12
+ };
13
+ constructor(message: string, applied?: {
14
+ readonly url?: string;
15
+ readonly deploymentVersion?: string;
16
+ });
17
+ }
18
+ export declare function runWranglerDeploy(args: DeployArgs & {
19
+ projectDir: string;
20
+ }): Promise<{
21
+ url?: string;
22
+ raw: string;
23
+ deploymentVersion: string;
24
+ }>;
@@ -0,0 +1,44 @@
1
+ import { parseDeployUrl, parseDeployVersionId } from '../deploy/output.js';
2
+ import { runCapture, wranglerCommand } from './process.js';
3
+ import { secretRedactor, withSecretsFile } from './secrets.js';
4
+ import { runWranglerTypes } from './type-generation.js';
5
+ export class WranglerDeployError extends Error {
6
+ applied;
7
+ constructor(message, applied) {
8
+ super(message);
9
+ this.name = 'WranglerDeployError';
10
+ if (applied !== undefined)
11
+ this.applied = Object.freeze({ ...applied });
12
+ }
13
+ }
14
+ export async function runWranglerDeploy(args) {
15
+ await runWranglerTypes(args);
16
+ const { cmd, prefix } = wranglerCommand(args.projectDir);
17
+ const secrets = args.secrets ?? {};
18
+ const execute = (secretsFile) => runCapture(cmd, [
19
+ ...prefix,
20
+ 'deploy',
21
+ '--config',
22
+ args.configPath,
23
+ ...(secretsFile === undefined ? [] : ['--secrets-file', secretsFile]),
24
+ ], args.projectDir, args.onLog, args.signal, secretRedactor(secrets));
25
+ const { code, out } = await withSecretsFile(secrets, execute);
26
+ const url = parseDeployUrl(out, args.route);
27
+ const deploymentVersion = parseDeployVersionId(out);
28
+ if (code !== 0) {
29
+ throw new WranglerDeployError(`wrangler deploy failed (code ${code}):\n${out.slice(-2000)}`, url === undefined && deploymentVersion === undefined
30
+ ? undefined
31
+ : {
32
+ ...(url === undefined ? {} : { url }),
33
+ ...(deploymentVersion === undefined ? {} : { deploymentVersion }),
34
+ });
35
+ }
36
+ if (deploymentVersion === undefined) {
37
+ throw new WranglerDeployError('wrangler deploy did not report its Version ID.', url === undefined ? undefined : { url });
38
+ }
39
+ return Object.freeze({
40
+ raw: out,
41
+ ...(url === undefined ? {} : { url }),
42
+ deploymentVersion,
43
+ });
44
+ }
@@ -0,0 +1,5 @@
1
+ export { runWranglerBundle } from './bundle.js';
2
+ export { runWranglerDeploy, WranglerDeployError, type DeployArgs } from './deploy.js';
3
+ export { wranglerProcessEnv } from './process.js';
4
+ export { admitWranglerDeploymentStatus, runWranglerDeploymentStatus, type WranglerDeploymentStatus, } from './status.js';
5
+ export { runWranglerTypes } from './type-generation.js';
@@ -0,0 +1,5 @@
1
+ export { runWranglerBundle } from './bundle.js';
2
+ export { runWranglerDeploy, WranglerDeployError } from './deploy.js';
3
+ export { wranglerProcessEnv } from './process.js';
4
+ export { admitWranglerDeploymentStatus, runWranglerDeploymentStatus, } from './status.js';
5
+ export { runWranglerTypes } from './type-generation.js';
@@ -0,0 +1,17 @@
1
+ import type { ChildProcess } from 'node:child_process';
2
+ export declare function wranglerCommand(projectDir: string, runtime?: {
3
+ readonly executable: string;
4
+ readonly bun: boolean;
5
+ }): {
6
+ cmd: string;
7
+ prefix: string[];
8
+ };
9
+ /** Keep Wrangler CLI diagnostic logs inside the generated project state. */
10
+ export declare function wranglerProcessEnv(projectDir: string): NodeJS.ProcessEnv;
11
+ export declare function runCapture(cmd: string, args: string[], cwd: string, onLog?: (line: string) => void, signal?: AbortSignal, redact?: (input: string) => string): Promise<{
12
+ code: number;
13
+ out: string;
14
+ stdout: string;
15
+ stderr: string;
16
+ }>;
17
+ export declare function stopChild(child: ChildProcess): Promise<void>;