@astrale-os/adapter-cloudflare 0.5.0-beta.23 → 0.5.0-beta.231

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 +258 -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 +23 -0
  9. package/dist/build/bundler.js +103 -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 +56 -0
  48. package/dist/build/worker/execution.prepare.d.ts +22 -0
  49. package/dist/build/worker/execution.prepare.js +131 -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 +46 -0
  59. package/dist/hosting/activation.js +127 -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 +153 -0
  67. package/dist/hosting/client.js +516 -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 +106 -0
  88. package/dist/hosting/kv.js +235 -0
  89. package/dist/hosting/listing.d.ts +34 -0
  90. package/dist/hosting/listing.js +49 -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 +79 -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 +68 -0
  108. package/dist/hosting/retirement.js +99 -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 +25 -0
  118. package/dist/hosting/time.js +48 -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 +387 -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 +32 -0
  138. package/dist/namespace/readiness.js +35 -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 +18 -0
  169. package/dist/wrangler/bundle.js +36 -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 +36 -14
  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
@@ -1,448 +0,0 @@
1
- /**
2
- * Thin wrapper around the `wrangler` binary — the only place the adapter shells
3
- * out. `watch` runs `wrangler dev` (local workerd) and resolves once the worker
4
- * reports its local URL; `deploy` runs `wrangler deploy` and parses the
5
- * authoritative public URL from the output; secrets go through `wrangler secret
6
- * bulk`. The wrangler binary is resolved from the project's `node_modules/.bin`,
7
- * falling back to `npx wrangler`.
8
- */
9
- import { spawn } from 'node:child_process';
10
- import { existsSync, readdirSync } from 'node:fs';
11
- import { readFileSync } from 'node:fs';
12
- import { mkdtemp, rm, writeFile } from 'node:fs/promises';
13
- import { createRequire } from 'node:module';
14
- import { createServer } from 'node:net';
15
- import { tmpdir } from 'node:os';
16
- import { dirname, join, resolve } from 'node:path';
17
- import { parseDeployUrl, parseDeployVersionId, parseDevReadyUrl } from './parse-output.js';
18
- function wranglerCommand(projectDir) {
19
- const local = join(projectDir, 'node_modules', '.bin', 'wrangler');
20
- if (existsSync(local))
21
- return { cmd: local, prefix: [] };
22
- const require = createRequire(import.meta.url);
23
- const packagePath = require.resolve('wrangler/package.json');
24
- const manifest = JSON.parse(readFileSync(packagePath, 'utf8'));
25
- const executable = typeof manifest.bin === 'string' ? manifest.bin : manifest.bin?.wrangler;
26
- if (!executable)
27
- throw new TypeError('Installed Wrangler package has no wrangler executable.');
28
- return { cmd: process.execPath, prefix: [resolve(dirname(packagePath), executable)] };
29
- }
30
- /** Keep Wrangler CLI diagnostic logs inside the generated project state. */
31
- export function wranglerProcessEnv(projectDir) {
32
- return {
33
- ...process.env,
34
- WRANGLER_SEND_METRICS: 'false',
35
- WRANGLER_LOG_PATH: process.env.WRANGLER_LOG_PATH || resolve(projectDir, '.astrale', 'logs', 'wrangler'),
36
- };
37
- }
38
- /**
39
- * True when `port` is free on `host`. A taken port previously made `wrangler
40
- * dev` either die ("Address already in use") or — worse — a FIRST probe hit a
41
- * DIFFERENT project's dev server on the same port (observed in agent runs:
42
- * every reader of the docs converges on 8787/8899).
43
- */
44
- function portFree(port, host) {
45
- return new Promise((resolve) => {
46
- const srv = createServer();
47
- srv.once('error', () => resolve(false));
48
- srv.once('listening', () => srv.close(() => resolve(true)));
49
- srv.listen(port, host);
50
- });
51
- }
52
- /** An OS-assigned free port. */
53
- function ephemeralPort(host) {
54
- return new Promise((resolve, reject) => {
55
- const srv = createServer();
56
- srv.once('error', reject);
57
- srv.listen(0, host, () => {
58
- const addr = srv.address();
59
- const port = typeof addr === 'object' && addr ? addr.port : 0;
60
- srv.close(() => resolve(port));
61
- });
62
- });
63
- }
64
- export async function runWranglerDev(args) {
65
- await runWranglerTypes(args);
66
- const { cmd, prefix } = wranglerCommand(args.projectDir);
67
- const bindHost = args.ip ?? '127.0.0.1';
68
- if (args.autoPickPort && !(await portFree(args.port, bindHost))) {
69
- const picked = await ephemeralPort(bindHost);
70
- args.onLog?.(`port ${args.port} is taken — using ${picked} instead (pass --port to pin one)`);
71
- args = { ...args, port: picked };
72
- }
73
- const secretEnvironment = await createSecretEnvironment(args.secrets);
74
- const wranglerArgs = [
75
- ...prefix,
76
- 'dev',
77
- '--config',
78
- args.configPath,
79
- '--port',
80
- String(args.port),
81
- '--local-protocol',
82
- 'http',
83
- '--ip',
84
- args.ip ?? '127.0.0.1',
85
- ...(secretEnvironment === undefined ? [] : ['--env-file', secretEnvironment.path]),
86
- ...(args.remote ? ['--remote'] : []),
87
- ];
88
- let child;
89
- try {
90
- child = spawn(cmd, wranglerArgs, {
91
- cwd: args.projectDir,
92
- stdio: ['ignore', 'pipe', 'pipe'],
93
- env: wranglerProcessEnv(args.projectDir),
94
- });
95
- }
96
- catch (cause) {
97
- await secretEnvironment?.remove();
98
- throw cause;
99
- }
100
- const fallbackUrl = `http://localhost:${args.port}`;
101
- // (args.port may have been re-picked above — everything below reads args.port)
102
- let resolved = false;
103
- // Wrangler's watch mode STAYS ALIVE on a build failure (listener up, worker
104
- // never answers) — the classic silent hang. Track build errors so the
105
- // safety net can fail LOUD instead of resolving a dead URL.
106
- let buildErrorTail = '';
107
- let outputTail = '';
108
- let url;
109
- try {
110
- url = await new Promise((resolve, reject) => {
111
- const onData = (buf) => {
112
- const text = buf.toString();
113
- outputTail = (outputTail + text).slice(-3000);
114
- for (const line of text.split('\n')) {
115
- if (line.trim())
116
- args.onLog?.(line);
117
- }
118
- if (/✘ \[ERROR\]|Build failed|Could not resolve "/.test(text)) {
119
- buildErrorTail = (buildErrorTail + text).slice(-2000);
120
- }
121
- if (!resolved) {
122
- const ready = parseDevReadyUrl(text, args.port);
123
- if (ready) {
124
- resolved = true;
125
- resolve(ready);
126
- }
127
- }
128
- else if (/Reloading|Detected changes|Updated/i.test(text)) {
129
- args.onReload();
130
- }
131
- };
132
- child.stdout?.on('data', onData);
133
- child.stderr?.on('data', onData);
134
- child.on('exit', (code) => {
135
- if (!resolved) {
136
- resolved = true;
137
- reject(new Error(`wrangler dev exited before becoming ready (code ${code ?? 'null'}).\n${outputTail}`));
138
- }
139
- });
140
- child.on('error', (err) => {
141
- if (!resolved) {
142
- resolved = true;
143
- reject(err);
144
- }
145
- });
146
- // Safety net: if we never matched a URL but the process is alive, assume the
147
- // conventional localhost URL after a grace period — UNLESS the build
148
- // failed, in which case a listener may be up but the worker will never
149
- // answer: fail loud with the build output instead of handing back a dead
150
- // URL.
151
- setTimeout(() => {
152
- if (!resolved && child.exitCode === null) {
153
- resolved = true;
154
- if (buildErrorTail) {
155
- void stopChild(child);
156
- reject(new Error(`worker build failed — the dev server would hang silently.\n${buildErrorTail}`));
157
- }
158
- else {
159
- resolve(fallbackUrl);
160
- }
161
- }
162
- }, 15_000).unref?.();
163
- });
164
- }
165
- catch (cause) {
166
- await stopChild(child);
167
- await secretEnvironment?.remove();
168
- throw cause;
169
- }
170
- return {
171
- url,
172
- async stop() {
173
- try {
174
- await stopChild(child);
175
- }
176
- finally {
177
- await secretEnvironment?.remove();
178
- }
179
- },
180
- };
181
- }
182
- export class WranglerDeployError extends Error {
183
- applied;
184
- constructor(message, applied) {
185
- super(message);
186
- this.name = 'WranglerDeployError';
187
- if (applied !== undefined)
188
- this.applied = Object.freeze({ ...applied });
189
- }
190
- }
191
- export async function runWranglerDeploy(args) {
192
- await runWranglerTypes(args);
193
- const { cmd, prefix } = wranglerCommand(args.projectDir);
194
- const { code, out } = await runCapture(cmd, [...prefix, 'deploy', '--config', args.configPath], args.projectDir, args.onLog);
195
- const url = parseDeployUrl(out, args.route);
196
- const deploymentVersion = parseDeployVersionId(out);
197
- if (code !== 0) {
198
- throw new WranglerDeployError(`wrangler deploy failed (code ${code}):\n${out.slice(-2000)}`, url === undefined && deploymentVersion === undefined
199
- ? undefined
200
- : {
201
- ...(url === undefined ? {} : { url }),
202
- ...(deploymentVersion === undefined ? {} : { deploymentVersion }),
203
- });
204
- }
205
- if (deploymentVersion === undefined) {
206
- throw new WranglerDeployError('wrangler deploy did not report its Version ID.', url === undefined ? undefined : { url });
207
- }
208
- return Object.freeze({
209
- raw: out,
210
- ...(url === undefined ? {} : { url }),
211
- deploymentVersion,
212
- });
213
- }
214
- /** Upload one Schema-revision Worker without assigning it a public route. */
215
- export async function runWranglerReleaseDeploy(args) {
216
- await runWranglerTypes(args);
217
- const { cmd, prefix } = wranglerCommand(args.projectDir);
218
- const execute = async (secretsFile) => runCapture(cmd, [
219
- ...prefix,
220
- 'deploy',
221
- '--config',
222
- args.configPath,
223
- '--dispatch-namespace',
224
- args.namespace,
225
- ...(secretsFile === undefined ? [] : ['--secrets-file', secretsFile]),
226
- ], args.projectDir, args.onLog);
227
- const result = await withSecretsFile(args.secrets, execute);
228
- const deploymentVersion = parseDeployVersionId(result.out);
229
- if (result.code !== 0) {
230
- throw new WranglerDeployError(`wrangler Release deploy failed (code ${result.code}):\n${result.out.slice(-2000)}`, deploymentVersion === undefined ? undefined : { deploymentVersion });
231
- }
232
- if (deploymentVersion === undefined) {
233
- throw new WranglerDeployError('wrangler Release deploy did not report its Version ID.');
234
- }
235
- return Object.freeze({ raw: result.out, deploymentVersion });
236
- }
237
- const MISSING_DISPATCH_NAMESPACE = /\[code:\s*100119\]/u;
238
- export class WranglerDispatchNamespaceError extends Error {
239
- effect;
240
- constructor(message, effect) {
241
- super(message);
242
- this.name = 'WranglerDispatchNamespaceError';
243
- this.effect = effect;
244
- }
245
- }
246
- /** Establish the private dispatch namespace without advancing the public gateway. */
247
- export async function ensureWranglerDispatchNamespace(args) {
248
- const { cmd, prefix } = wranglerCommand(args.projectDir);
249
- const inspect = () => runCapture(cmd, [...prefix, 'dispatch-namespace', 'get', args.namespace], args.projectDir, args.onLog);
250
- const observed = await inspect();
251
- if (observed.code === 0)
252
- return;
253
- if (!MISSING_DISPATCH_NAMESPACE.test(observed.out)) {
254
- throw new WranglerDispatchNamespaceError(`wrangler dispatch namespace inspection failed (code ${observed.code}):\n${observed.out.slice(-2000)}`, 'none');
255
- }
256
- const created = await runCapture(cmd, [...prefix, 'dispatch-namespace', 'create', args.namespace], args.projectDir, args.onLog);
257
- if (created.code === 0)
258
- return;
259
- // Another convergent deployment may have created the namespace after inspection.
260
- if ((await inspect()).code === 0)
261
- return;
262
- throw new WranglerDispatchNamespaceError(`wrangler dispatch namespace creation failed (code ${created.code}):\n${created.out.slice(-2000)}`, 'unknown');
263
- }
264
- export async function runWranglerDeploymentStatus(args) {
265
- const { cmd, prefix } = wranglerCommand(args.projectDir);
266
- const result = await runCapture(cmd, [
267
- ...prefix,
268
- 'deployments',
269
- 'status',
270
- '--config',
271
- args.configPath,
272
- '--name',
273
- args.workerName,
274
- '--json',
275
- ], args.projectDir);
276
- if (result.code !== 0) {
277
- throw new Error(`wrangler deployments status failed (code ${result.code}):\n${result.out.slice(-2000)}`);
278
- }
279
- return admitWranglerDeploymentStatus(result.out);
280
- }
281
- /** Admit Wrangler's current-deployment JSON before it becomes provider evidence. */
282
- export function admitWranglerDeploymentStatus(output) {
283
- let decoded;
284
- try {
285
- decoded = JSON.parse(output);
286
- }
287
- catch (cause) {
288
- throw new TypeError('wrangler deployments status returned invalid JSON.', { cause });
289
- }
290
- if (decoded === null || typeof decoded !== 'object' || Array.isArray(decoded))
291
- invalidStatus();
292
- const deployment = Reflect.get(decoded, 'id');
293
- const traffic = Reflect.get(decoded, 'versions');
294
- if (typeof deployment !== 'string' ||
295
- deployment.length === 0 ||
296
- !Array.isArray(traffic) ||
297
- traffic.length === 0) {
298
- invalidStatus();
299
- }
300
- const versions = traffic.map((entry) => {
301
- if (entry === null || typeof entry !== 'object' || Array.isArray(entry))
302
- invalidStatus();
303
- const version = Reflect.get(entry, 'version_id');
304
- const percentage = Reflect.get(entry, 'percentage');
305
- if (typeof version !== 'string' ||
306
- version.length === 0 ||
307
- typeof percentage !== 'number' ||
308
- !Number.isFinite(percentage) ||
309
- percentage <= 0 ||
310
- percentage > 100) {
311
- invalidStatus();
312
- }
313
- return Object.freeze({ version, percentage });
314
- });
315
- return Object.freeze({ deployment, versions: Object.freeze(versions) });
316
- }
317
- function invalidStatus() {
318
- throw new TypeError('wrangler deployments status returned invalid deployment evidence.');
319
- }
320
- async function withSecretsFile(secrets, operation) {
321
- if (Object.keys(secrets).length === 0)
322
- return operation();
323
- const directory = await mkdtemp(join(tmpdir(), 'astrale-secrets-'));
324
- const path = join(directory, 'secrets.json');
325
- try {
326
- await writeFile(path, JSON.stringify(secrets), { mode: 0o600 });
327
- return await operation(path);
328
- }
329
- finally {
330
- await rm(directory, { recursive: true, force: true });
331
- }
332
- }
333
- async function createSecretEnvironment(secrets) {
334
- if (Object.keys(secrets).length === 0)
335
- return undefined;
336
- const source = Object.entries(secrets)
337
- .sort(([left], [right]) => left.localeCompare(right))
338
- .map(([name, value]) => `${secretName(name)}=${dotenvSecret(value)}`)
339
- .join('\n');
340
- const directory = await mkdtemp(join(tmpdir(), 'astrale-dev-secrets-'));
341
- const path = join(directory, '.dev.vars');
342
- await writeFile(path, `${source}\n`, { mode: 0o600 });
343
- return Object.freeze({
344
- path,
345
- remove: () => rm(directory, { recursive: true, force: true }),
346
- });
347
- }
348
- function secretName(input) {
349
- if (!/^[A-Za-z_]\w*$/u.test(input)) {
350
- throw new TypeError(`Cloudflare secret name '${input}' is not a Worker binding name.`);
351
- }
352
- return input;
353
- }
354
- /** Encode without changing a byte under Wrangler's dotenv boundary. */
355
- function dotenvSecret(input) {
356
- if (!input.includes("'"))
357
- return `'${input}'`;
358
- if (!input.includes('`'))
359
- return `\`${input}\``;
360
- if (!input.includes('"') && !input.includes('\\n') && !input.includes('\\r')) {
361
- return `"${input}"`;
362
- }
363
- if (input.trim() === input && !/[#\r\n]/u.test(input))
364
- return input;
365
- throw new TypeError('Cloudflare local secret cannot be represented losslessly as dotenv.');
366
- }
367
- // ── internals ──────────────────────────────────────────────────────────────
368
- function runCapture(cmd, args, cwd, onLog) {
369
- return new Promise((resolve, reject) => {
370
- const child = spawn(cmd, args, {
371
- cwd,
372
- stdio: ['ignore', 'pipe', 'pipe'],
373
- env: wranglerProcessEnv(cwd),
374
- });
375
- let out = '';
376
- const onData = (buf) => {
377
- const text = buf.toString();
378
- out += text;
379
- for (const line of text.split('\n'))
380
- if (line.trim())
381
- onLog?.(line);
382
- };
383
- child.stdout?.on('data', onData);
384
- child.stderr?.on('data', onData);
385
- child.on('exit', (code) => resolve({ code: code ?? 1, out }));
386
- child.on('error', reject);
387
- });
388
- }
389
- async function stopChild(child) {
390
- if (child.exitCode !== null)
391
- return;
392
- await new Promise((resolve) => {
393
- child.on('exit', () => resolve());
394
- child.kill('SIGTERM');
395
- setTimeout(() => {
396
- if (child.exitCode === null)
397
- child.kill('SIGKILL');
398
- resolve();
399
- }, 4000).unref?.();
400
- });
401
- }
402
- /**
403
- * Build the single-module worker bundle WITHOUT deploying — `wrangler deploy
404
- * --dry-run --outdir` (no Cloudflare auth required). Returns the path of the
405
- * bundled .js module (the managed adapter publishes its bytes).
406
- */
407
- export async function runWranglerBundle(args) {
408
- await runWranglerTypes(args);
409
- const { cmd, prefix } = wranglerCommand(args.projectDir);
410
- const { code, out } = await runCapture(cmd, [
411
- ...prefix,
412
- 'deploy',
413
- '--dry-run',
414
- '--outdir',
415
- args.outDir,
416
- '--metafile',
417
- '--config',
418
- args.configPath,
419
- ], args.projectDir, args.onLog);
420
- if (code !== 0)
421
- throw new Error(`wrangler bundle failed (exit ${code}): ${out.slice(-400)}`);
422
- const js = readdirSync(args.outDir).filter((f) => f.endsWith('.js'));
423
- if (js.length === 0)
424
- throw new Error(`wrangler bundle produced no .js in ${args.outDir}`);
425
- const preferred = js.find((f) => f.startsWith('worker')) ?? js[0];
426
- return Object.freeze({
427
- bundlePath: join(args.outDir, preferred),
428
- metafilePath: join(args.outDir, 'bundle-meta.json'),
429
- });
430
- }
431
- /** Generate the exact binding and runtime types selected by the generated config. */
432
- export async function runWranglerTypes(args) {
433
- const { cmd, prefix } = wranglerCommand(args.projectDir);
434
- const outputPath = join(dirname(args.configPath), 'worker-configuration.d.ts');
435
- const { code, out } = await runCapture(cmd, [
436
- ...prefix,
437
- 'types',
438
- outputPath,
439
- '--env-interface',
440
- 'CloudflareEnv',
441
- '--config',
442
- args.configPath,
443
- ], args.projectDir, args.onLog);
444
- if (code !== 0) {
445
- throw new Error(`wrangler types failed (code ${code}):\n${out.slice(-2000)}`);
446
- }
447
- return outputPath;
448
- }
@@ -1,17 +0,0 @@
1
- import type { DeployContext, DeployResult } from '@astrale-os/sdk/deployment/adapter';
2
- import type { Release } from '@astrale-os/sdk/deployment/release';
3
- import type { materialize } from '../build/artifact.js';
4
- import type { ensureWranglerDispatchNamespace, runWranglerDeploy, runWranglerDeploymentStatus, runWranglerReleaseDeploy } from '../build/wrangler-cli.js';
5
- import type { signingIdentity } from '../identity/source.js';
6
- import type { CloudflareParams } from '../params.js';
7
- export interface CloudflareDeployDependencies {
8
- readonly materialize: typeof materialize;
9
- readonly ensureWranglerDispatchNamespace: typeof ensureWranglerDispatchNamespace;
10
- readonly runWranglerDeploy: typeof runWranglerDeploy;
11
- readonly runWranglerReleaseDeploy: typeof runWranglerReleaseDeploy;
12
- readonly runWranglerDeploymentStatus: typeof runWranglerDeploymentStatus;
13
- readonly waitForReadiness: (release: Release) => Promise<void>;
14
- readonly signingIdentity: typeof signingIdentity;
15
- }
16
- /** Establish private placement and place one revision before advancing the public gateway. */
17
- export declare function deployCloudflare(parameters: CloudflareParams, context: DeployContext, dependencies: CloudflareDeployDependencies): Promise<DeployResult>;
@@ -1,207 +0,0 @@
1
- import { addressing, assemble } from '@astrale-os/sdk/deployment/release';
2
- import { join } from 'node:path';
3
- import { workerName } from '../build/configuration.js';
4
- import { WranglerDeployError, WranglerDispatchNamespaceError } from '../build/wrangler-cli.js';
5
- import { signingIdentitySecrets } from '../identity/secret.js';
6
- import { releaseNamespace } from '../release/index.js';
7
- const NONE = Object.freeze({ kind: 'none' });
8
- /** Establish private placement and place one revision before advancing the public gateway. */
9
- export async function deployCloudflare(parameters, context, dependencies) {
10
- let secrets;
11
- try {
12
- const identity = await dependencies.signingIdentity({
13
- projectDir: context.projectDir,
14
- source: parameters.signingIdentity,
15
- origin: context.artifact.build.schema.compiled.root.origin,
16
- mode: 'deploy',
17
- });
18
- secrets = signingIdentitySecrets(context.secrets, identity);
19
- }
20
- catch (cause) {
21
- return failed('prerequisite', progress({}), cause);
22
- }
23
- const directory = join(context.projectDir, '.astrale', 'deploy');
24
- await dependencies.materialize(directory, context.artifact.files);
25
- const name = workerName(parameters, context.artifact.build.schema.compiled.root.origin);
26
- const releaseConfigPath = join(directory, 'wrangler.release.jsonc');
27
- const gatewayConfigPath = join(directory, 'wrangler.gateway.jsonc');
28
- const namespace = releaseNamespace(name);
29
- try {
30
- await dependencies.ensureWranglerDispatchNamespace({
31
- projectDir: context.projectDir,
32
- namespace,
33
- });
34
- }
35
- catch (cause) {
36
- const provider = cause instanceof WranglerDispatchNamespaceError && cause.effect === 'none'
37
- ? NONE
38
- : Object.freeze({ kind: 'unknown' });
39
- return failed('provider', progress({ provider }), cause);
40
- }
41
- let revision;
42
- try {
43
- revision = await dependencies.runWranglerReleaseDeploy({
44
- projectDir: context.projectDir,
45
- configPath: releaseConfigPath,
46
- namespace,
47
- secrets,
48
- });
49
- }
50
- catch (cause) {
51
- const provider = partialProvider(cause, context.artifact);
52
- const configuration = Object.freeze({ kind: 'unknown' });
53
- return failed('provider', progress({ provider, configuration }), cause);
54
- }
55
- const configuration = Object.freeze({
56
- kind: 'applied',
57
- evidence: Object.freeze({ names: Object.keys(secrets).sort() }),
58
- });
59
- const retained = Object.freeze({
60
- kind: 'partial',
61
- evidence: Object.freeze({
62
- provider: 'cloudflare',
63
- deployment: revision.deploymentVersion,
64
- artifact: context.artifact.digest,
65
- }),
66
- });
67
- let gateway;
68
- try {
69
- gateway = await dependencies.runWranglerDeploy({
70
- projectDir: context.projectDir,
71
- configPath: gatewayConfigPath,
72
- ...(parameters.route === undefined ? {} : { route: parameters.route }),
73
- });
74
- }
75
- catch (cause) {
76
- return failed('provider', progress({ provider: retained, configuration }), cause);
77
- }
78
- let selected;
79
- try {
80
- selected = observeAddressing(context.artifact, gateway.url, name);
81
- }
82
- catch (cause) {
83
- return failed('addressing', progress({
84
- provider: retained,
85
- configuration,
86
- }), cause);
87
- }
88
- let observed;
89
- try {
90
- observed = await dependencies.runWranglerDeploymentStatus({
91
- projectDir: context.projectDir,
92
- configPath: gatewayConfigPath,
93
- workerName: name,
94
- });
95
- requireCurrentDeployment(observed, gateway.deploymentVersion);
96
- }
97
- catch (cause) {
98
- return failed('readiness', progress({
99
- provider: retained,
100
- configuration,
101
- }), cause);
102
- }
103
- let release;
104
- try {
105
- release = assemble(context.artifact.build, selected);
106
- }
107
- catch (cause) {
108
- return failed('release', progress({ provider: retained, configuration }), cause);
109
- }
110
- try {
111
- await dependencies.waitForReadiness(release);
112
- }
113
- catch (cause) {
114
- return failed('readiness', progress({ provider: retained, configuration }), cause, release);
115
- }
116
- const provider = Object.freeze({
117
- kind: 'applied',
118
- evidence: Object.freeze({
119
- provider: 'cloudflare',
120
- deployment: revision.deploymentVersion,
121
- artifact: context.artifact.digest,
122
- issuer: selected.issuer,
123
- }),
124
- });
125
- return Object.freeze({
126
- status: 'ready',
127
- phase: 'complete',
128
- progress: Object.freeze({ ...progress({ configuration }), provider }),
129
- release,
130
- });
131
- }
132
- function partialProvider(cause, artifact) {
133
- if (!(cause instanceof WranglerDeployError) || cause.applied?.deploymentVersion === undefined) {
134
- return Object.freeze({ kind: 'unknown' });
135
- }
136
- let issuer;
137
- if (cause.applied.url !== undefined) {
138
- try {
139
- issuer = addressing(cause.applied.url).issuer;
140
- }
141
- catch {
142
- // The provider effect remains known when its printed URL is not Addressing.
143
- }
144
- }
145
- return Object.freeze({
146
- kind: 'partial',
147
- evidence: Object.freeze({
148
- provider: 'cloudflare',
149
- deployment: cause.applied.deploymentVersion,
150
- artifact: artifact.digest,
151
- ...(issuer === undefined ? {} : { issuer }),
152
- }),
153
- });
154
- }
155
- function requireCurrentDeployment(observed, expectedVersion) {
156
- if (observed.versions.length !== 1 ||
157
- observed.versions[0].percentage !== 100 ||
158
- observed.versions[0].version !== expectedVersion) {
159
- throw new TypeError('Cloudflare gateway is not one exact Worker version at 100%.');
160
- }
161
- }
162
- function observeAddressing(artifact, deployedUrl, expectedWorker) {
163
- if (artifact.addressing.kind === 'configured') {
164
- if (deployedUrl === undefined)
165
- return artifact.addressing.addressing;
166
- const observed = addressing(deployedUrl);
167
- if (observed.issuer !== artifact.addressing.addressing.issuer) {
168
- throw new TypeError('Cloudflare deployed URL differs from configured Addressing.');
169
- }
170
- return observed;
171
- }
172
- if (deployedUrl === undefined) {
173
- throw new TypeError('Cloudflare did not report provider-assigned Addressing.');
174
- }
175
- const observed = addressing(deployedUrl);
176
- if (artifact.addressing.claim !== expectedWorker) {
177
- throw new TypeError('PreparedArtifact worker claim differs from the gateway target.');
178
- }
179
- const url = new URL(observed.issuer);
180
- const labels = url.hostname.split('.');
181
- if (url.protocol !== 'https:' ||
182
- labels.length < 4 ||
183
- labels[0] !== artifact.addressing.claim ||
184
- labels.at(-2) !== 'workers' ||
185
- labels.at(-1) !== 'dev') {
186
- throw new TypeError('Cloudflare workers.dev URL does not satisfy its prepared worker claim.');
187
- }
188
- return observed;
189
- }
190
- function progress(input) {
191
- return Object.freeze({
192
- prerequisite: input.prerequisite ?? NONE,
193
- provider: input.provider ?? NONE,
194
- configuration: input.configuration ?? NONE,
195
- installation: input.installation ?? NONE,
196
- });
197
- }
198
- function failed(phase, progressValue, cause, release) {
199
- const error = cause instanceof Error ? cause : new Error(String(cause));
200
- return Object.freeze({
201
- status: 'failed',
202
- phase,
203
- progress: progressValue,
204
- error,
205
- ...(release === undefined ? {} : { release }),
206
- });
207
- }
@@ -1 +0,0 @@
1
- export { deployCloudflare, type CloudflareDeployDependencies } from './deploy.js';
@@ -1 +0,0 @@
1
- export { deployCloudflare } from './deploy.js';
@@ -1,3 +0,0 @@
1
- import type { SigningIdentitySource } from './source.js';
2
- /** Add the adapter-owned identity without allowing a second secret authority. */
3
- export declare function signingIdentitySecrets(secrets: Readonly<Record<string, string>>, identity: SigningIdentitySource): Readonly<Record<string, string>>;
@@ -1,7 +0,0 @@
1
- /** Add the adapter-owned identity without allowing a second secret authority. */
2
- export function signingIdentitySecrets(secrets, identity) {
3
- if (Object.hasOwn(secrets, identity.binding)) {
4
- throw new TypeError(`${identity.binding} is adapter-owned; configure 'signingIdentity' instead of declaring that secret.`);
5
- }
6
- return Object.freeze({ ...secrets, [identity.binding]: identity.secret });
7
- }