@composable-os/cli 0.1.0-beta.11 → 0.1.0-beta.14

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 (166) hide show
  1. package/dist/{accounts-UHYLCLEY.js → accounts-GOCNY6WI.js} +17 -13
  2. package/dist/app-OSPZHKOI.js +43 -0
  3. package/dist/app-upload-LH4PXKI4.js +198 -0
  4. package/dist/{blocks-5IFU25J6.js → blocks-6DZIP47W.js} +207 -25
  5. package/dist/{chunk-XIDLW3EP.js → chunk-2B6YUYZV.js} +23499 -11766
  6. package/dist/{run-7P4RQALH.js → chunk-2CCHB37H.js} +9 -146
  7. package/dist/{chunk-DU6OIFOU.js → chunk-3OGDWKJ3.js} +530 -434
  8. package/dist/{chunk-DHS2CV2M.js → chunk-5D7BDF4Y.js} +15 -13
  9. package/dist/{chunk-MBIKVRAC.js → chunk-5YDYQM6V.js} +830 -47
  10. package/dist/{chunk-ZAWES2UD.js → chunk-6CM3WZG5.js} +13 -2483
  11. package/dist/{chunk-7D4GKZOX.js → chunk-CIBJGB5H.js} +422 -75
  12. package/dist/chunk-EPDTPGZJ.js +330 -0
  13. package/dist/{chunk-LAAL4YGR.js → chunk-HAYF4G5V.js} +66 -23
  14. package/dist/chunk-HCG6T53D.js +61904 -0
  15. package/dist/{chunk-K34UKWEI.js → chunk-JX4IFWNT.js} +64 -32
  16. package/dist/{chunk-6XTU2MTP.js → chunk-KFHKNXGH.js} +632 -418
  17. package/dist/chunk-KMFMD52Z.js +13276 -0
  18. package/dist/{chunk-E4WCYTCT.js → chunk-LX2TTLVY.js} +174 -55
  19. package/dist/{chunk-PDD2ETVF.js → chunk-O37YUZ52.js} +172 -16
  20. package/dist/{chunk-GYTEW66E.js → chunk-O3R4FS2J.js} +1 -1
  21. package/dist/{chunk-E64SG24J.js → chunk-Q6Y45DY6.js} +25 -2
  22. package/dist/chunk-RGKJKC5T.js +876 -0
  23. package/dist/{chunk-YFTLIEWU.js → chunk-RSEWEFAV.js} +12 -2
  24. package/dist/{chunk-2ABSVMGB.js → chunk-SMJZIK2O.js} +1 -1
  25. package/dist/{chunk-LO6WGU5Y.js → chunk-U72NEGCT.js} +8089 -3464
  26. package/dist/{chunk-P6UWZ6QQ.js → chunk-Z4IKF23A.js} +11 -7
  27. package/dist/{chunk-2IVEVPMY.js → chunk-Z7OVQ6BC.js} +105 -61
  28. package/dist/{chunk-6UWRT4VM.js → chunk-ZJSFX4RD.js} +175 -3
  29. package/dist/{cli-5UNY5G5L.js → cli-OKQHHSOE.js} +17 -25
  30. package/dist/{cli-UYZMVQMR.js → cli-VYSD2S4Z.js} +227 -81
  31. package/dist/cli.js +5 -5
  32. package/dist/{client-repo-SE4EKG6W.js → client-repo-MPCPTXLF.js} +7 -5
  33. package/dist/create.js +5 -5
  34. package/dist/{fields-FTWWMD7N.js → fields-GTHE6TTS.js} +27 -3
  35. package/dist/gateway-DPPEQZT4.js +25 -0
  36. package/dist/grants-6JY4XZO7.js +27 -0
  37. package/dist/invoke-MRONRZ5Q.js +33 -0
  38. package/dist/moves-UAUCMWL5.js +36 -0
  39. package/dist/{order-U4KZLLSJ.js → order-RKLGT74L.js} +2 -2
  40. package/dist/{person-UHLVBVLR.js → person-YOZTFV4Q.js} +11 -10
  41. package/dist/plan-on-sale-H4F26YIN.js +26 -0
  42. package/dist/platform/migrations/0730_practitioners.sql +79 -0
  43. package/dist/platform/migrations/0750_routine_mail.sql +98 -0
  44. package/dist/platform/migrations/0770_clear_fixed_role_grants.sql +64 -0
  45. package/dist/platform/migrations/0810_recurrence_exceptions.sql +66 -0
  46. package/dist/platform/migrations/0811_staff_time.sql +109 -0
  47. package/dist/platform/migrations/0812_staff_offers.sql +112 -0
  48. package/dist/platform/migrations/0813_pay_periods.sql +241 -0
  49. package/dist/platform/migrations/0814_staff_feed.sql +47 -0
  50. package/dist/platform/migrations/0815_checklists.sql +237 -0
  51. package/dist/platform/migrations/0816_checklist_schedules.sql +121 -0
  52. package/dist/platform/migrations/0817_checklist_day_window.sql +35 -0
  53. package/dist/platform/migrations/0850_agreements.sql +271 -0
  54. package/dist/platform/migrations/0851_agreement_acceptances.sql +387 -0
  55. package/dist/platform/migrations/0853_agreement_enforcement.sql +58 -0
  56. package/dist/platform/migrations/0854_agreement_copy.sql +149 -0
  57. package/dist/platform/migrations/0855_agreement_retention.sql +279 -0
  58. package/dist/platform/migrations/0856_subscription_cooling_off.sql +159 -0
  59. package/dist/platform/migrations/0857_agreement_copy_guardian.sql +337 -0
  60. package/dist/platform/migrations/0858_agreement_desk.sql +175 -0
  61. package/dist/platform/migrations/0910_routine_messages.sql +99 -0
  62. package/dist/platform/migrations/0911_texts.sql +60 -0
  63. package/dist/platform/migrations/0913_contact_consent.sql +93 -0
  64. package/dist/platform/migrations/0916_contact_mailbox_index.sql +29 -0
  65. package/dist/platform/migrations/0930_stock_movements.sql +95 -0
  66. package/dist/platform/migrations/0931_stock_low.sql +25 -0
  67. package/dist/platform/migrations/0932_order_delivery.sql +78 -0
  68. package/dist/platform/migrations/0950_order_adjustments.sql +111 -0
  69. package/dist/platform/migrations/0951_order_price_guards.sql +33 -0
  70. package/dist/platform/migrations/0952_order_paid_another_way.sql +194 -0
  71. package/dist/platform/migrations/0953_discount_uses.sql +183 -0
  72. package/dist/platform/migrations/0955_folded_addresses.sql +92 -0
  73. package/dist/platform/migrations/0970_published_text.sql +59 -0
  74. package/dist/platform/migrations/0971_publish_acks.sql +68 -0
  75. package/dist/platform/migrations/0990_customer_email_change.sql +65 -0
  76. package/dist/platform/migrations/1010_intake_links.sql +148 -0
  77. package/dist/platform/migrations/1030_invoices.sql +747 -0
  78. package/dist/platform/migrations/1031_invoice_orders.sql +327 -0
  79. package/dist/platform/migrations/1050_inbox_conversations.sql +83 -0
  80. package/dist/platform/migrations/1090_staff_hours.sql +43 -0
  81. package/dist/platform/migrations/1091_staff_time_margins.sql +12 -0
  82. package/dist/platform/migrations/1092_client_guard.sql +26 -0
  83. package/dist/platform/migrations/1095_thing_time.sql +70 -0
  84. package/dist/platform/migrations/1130_devices.sql +162 -0
  85. package/dist/platform/migrations/1135_person_codes.sql +88 -0
  86. package/dist/platform/migrations/1150_finance_periods.sql +316 -0
  87. package/dist/platform/migrations/1151_payouts.sql +202 -0
  88. package/dist/platform/migrations/1153_finance_money_dates.sql +18 -0
  89. package/dist/platform/migrations/1170_journeys.sql +318 -0
  90. package/dist/platform/migrations/1171_person_birthday.sql +52 -0
  91. package/dist/platform/migrations/1175_person_signals.sql +29 -0
  92. package/dist/platform/migrations/1190_restricted_values.sql +25 -0
  93. package/dist/platform/migrations/1230_note_levels.sql +113 -0
  94. package/dist/platform/migrations/1231_person_carers.sql +33 -0
  95. package/dist/platform/migrations/1232_note_kinds.sql +122 -0
  96. package/dist/platform/migrations/1270_time_entries.sql +145 -0
  97. package/dist/platform/migrations/1271_leave.sql +249 -0
  98. package/dist/platform/migrations/1273_time_entry_reopened.sql +21 -0
  99. package/dist/platform/migrations/1330_accounting.sql +260 -0
  100. package/dist/platform/migrations/1350_customer_feed.sql +24 -0
  101. package/dist/platform/migrations/1390_locations.sql +77 -0
  102. package/dist/platform/migrations/1410_outside_copy.sql +213 -0
  103. package/dist/platform/migrations/1430_inbox_activities.sql +231 -0
  104. package/dist/platform/migrations/1450_wrong_guesses.sql +23 -0
  105. package/dist/platform/sdk/acknowledge.ts +100 -0
  106. package/dist/platform/sdk/agreements.ts +185 -0
  107. package/dist/platform/sdk/allowance.ts +98 -8
  108. package/dist/platform/sdk/automation-check.ts +120 -9
  109. package/dist/platform/sdk/automation.ts +78 -10
  110. package/dist/platform/sdk/behaviour.ts +26 -6
  111. package/dist/platform/sdk/calendar-entry.ts +258 -0
  112. package/dist/platform/sdk/capacity.ts +1 -2
  113. package/dist/platform/sdk/checklists.ts +118 -0
  114. package/dist/platform/sdk/contract.ts +489 -27
  115. package/dist/platform/sdk/discount.ts +408 -0
  116. package/dist/platform/sdk/document.ts +4 -2
  117. package/dist/platform/sdk/field-types.ts +5 -0
  118. package/dist/platform/sdk/formula/compile.ts +10 -0
  119. package/dist/platform/sdk/index.ts +17 -0
  120. package/dist/platform/sdk/intake.ts +380 -0
  121. package/dist/platform/sdk/journey-signals.ts +215 -0
  122. package/dist/platform/sdk/manifest.ts +1236 -65
  123. package/dist/platform/sdk/mine.ts +161 -0
  124. package/dist/platform/sdk/occupies.ts +192 -0
  125. package/dist/platform/sdk/questions.ts +681 -0
  126. package/dist/platform/sdk/recurring.ts +90 -9
  127. package/dist/platform/sdk/restricted-fields.ts +129 -0
  128. package/dist/platform/sdk/rich-text.ts +112 -0
  129. package/dist/platform/sdk/routine-mail.ts +1272 -0
  130. package/dist/platform/sdk/runtime.ts +25 -12
  131. package/dist/platform/sdk/screens.ts +91 -0
  132. package/dist/platform/sdk/sellable.ts +344 -0
  133. package/dist/platform/sdk/slug.ts +7 -2
  134. package/dist/platform/sdk/staffed.ts +474 -0
  135. package/dist/platform/sdk/states.ts +68 -26
  136. package/dist/platform/sdk/stock.ts +332 -0
  137. package/dist/platform/sdk/team.ts +83 -0
  138. package/dist/platform/sdk/testing.ts +70 -6
  139. package/dist/platform/sdk/worked-on.ts +134 -0
  140. package/dist/{products-2H5DR232.js → products-GCQLSZ3U.js} +2 -2
  141. package/dist/run-7ID64RA6.js +65 -0
  142. package/dist/run-FH7OGGTV.js +131 -0
  143. package/dist/run-OYZIAP6M.js +3363 -0
  144. package/dist/{run-ZCGFMEZF.js → run-QOFRRSZV.js} +41 -60
  145. package/dist/{run-PO3W5BFA.js → run-TJAEWR5U.js} +21 -51
  146. package/dist/{src-I3IJ4NKC.js → src-52VERUPK.js} +306 -4
  147. package/dist/src-PHRELWN5.js +40 -0
  148. package/dist/{visibility-TVXZ67FD.js → visibility-SZCINPP4.js} +21 -4
  149. package/package.json +2 -2
  150. package/dist/chunk-2TWV3SVB.js +0 -349
  151. package/dist/chunk-2XC5JLBO.js +0 -1931
  152. package/dist/chunk-324WJXNP.js +0 -320
  153. package/dist/chunk-6ELZRNUU.js +0 -116
  154. package/dist/chunk-6WGFA2IV.js +0 -643
  155. package/dist/chunk-7CQGMVDO.js +0 -63
  156. package/dist/chunk-7OGCMQXG.js +0 -284
  157. package/dist/chunk-FJIZGS5Q.js +0 -698
  158. package/dist/chunk-UB4I2QKR.js +0 -31575
  159. package/dist/chunk-WHKJGF36.js +0 -2418
  160. package/dist/chunk-YNUZRTPH.js +0 -182
  161. package/dist/chunk-ZZFWMVJO.js +0 -704
  162. package/dist/grants-LOW6TSWD.js +0 -32
  163. package/dist/invoke-6KVT6WJI.js +0 -41
  164. package/dist/moves-E2HKYCTK.js +0 -41
  165. package/dist/plan-on-sale-TJPFCNL7.js +0 -26
  166. package/dist/src-CRO35DYY.js +0 -46
@@ -1,291 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  releaseFilePrefix
4
- } from "./chunk-6UWRT4VM.js";
5
-
6
- // ../release/src/hash.ts
7
- async function sha256Hex(bytes) {
8
- const data = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
9
- const digest = await crypto.subtle.digest("SHA-256", data);
10
- return toHex(new Uint8Array(digest));
11
- }
12
- function toHex(bytes) {
13
- let out = "";
14
- for (const byte of bytes) out += byte.toString(16).padStart(2, "0");
15
- return out;
16
- }
17
- function toBase64(bytes) {
18
- let binary = "";
19
- const chunk = 32768;
20
- for (let i = 0; i < bytes.length; i += chunk) {
21
- binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
22
- }
23
- return btoa(binary);
24
- }
25
- function fromBase64(text) {
26
- const binary = atob(text);
27
- const out = new Uint8Array(binary.length);
28
- for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
29
- return out;
30
- }
31
- function extensionOf(path) {
32
- const name = path.slice(path.lastIndexOf("/") + 1);
33
- const dot = name.lastIndexOf(".");
34
- return dot <= 0 ? "" : name.slice(dot + 1);
35
- }
36
- async function assetHash(bytes, path) {
37
- return (await sha256Hex(toBase64(bytes) + extensionOf(path))).slice(0, 32);
38
- }
39
- function sameDigest(a, b) {
40
- if (a.length !== b.length) return false;
41
- let diff = 0;
42
- for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
43
- return diff === 0;
44
- }
45
-
46
- // ../release/src/archive.ts
47
- var BLOCK = 512;
48
- var encoder = new TextEncoder();
49
- var decoder = new TextDecoder();
50
- function readOctal(block, offset, length) {
51
- const text = decoder.decode(block.subarray(offset, offset + length)).replace(/[\0 ]+$/g, "");
52
- return text ? Number.parseInt(text.trim(), 8) : 0;
53
- }
54
- function readTar(bytes) {
55
- const files = /* @__PURE__ */ new Map();
56
- let offset = 0;
57
- while (offset + BLOCK <= bytes.length) {
58
- const header = bytes.subarray(offset, offset + BLOCK);
59
- if (header.every((byte) => byte === 0)) break;
60
- let stored = 0;
61
- for (let i = 0; i < BLOCK; i++) stored += i >= 148 && i < 156 ? 32 : header[i];
62
- if (stored !== readOctal(header, 148, 8)) throw new Error("corrupt tar header checksum");
63
- const nameEnd = header.indexOf(0);
64
- const name = decoder.decode(
65
- header.subarray(0, nameEnd === -1 || nameEnd > 100 ? 100 : nameEnd)
66
- );
67
- const prefixBytes = header.subarray(345, 500);
68
- const prefixEnd = prefixBytes.indexOf(0);
69
- const prefix = decoder.decode(prefixBytes.subarray(0, prefixEnd === -1 ? 155 : prefixEnd));
70
- const path = prefix ? `${prefix}/${name}` : name;
71
- const size = readOctal(header, 124, 12);
72
- const type = String.fromCharCode(header[156] ?? 0);
73
- offset += BLOCK;
74
- if (offset + size > bytes.length) throw new Error(`truncated tar entry ${path}`);
75
- if (type === "0" || type === "\0") {
76
- if (path.startsWith("/") || path.split("/").includes("..")) {
77
- throw new Error(`unsafe path in bundle: ${path}`);
78
- }
79
- if (files.has(path)) throw new Error(`duplicate path in bundle: ${path}`);
80
- files.set(path, bytes.slice(offset, offset + size));
81
- }
82
- offset += Math.ceil(size / BLOCK) * BLOCK;
83
- }
84
- return files;
85
- }
86
- async function pipe(bytes, transform) {
87
- const stream = new Blob([bytes]).stream().pipeThrough(transform);
88
- return new Uint8Array(await new Response(stream).arrayBuffer());
89
- }
90
- async function gunzip(bytes) {
91
- return pipe(bytes, new DecompressionStream("gzip"));
92
- }
93
-
94
- // ../release/src/manifest.ts
95
- var MANIFEST_VERSION = 1;
96
- var FUNCTION_PLACEHOLDERS = [
97
- "SECRET",
98
- "WORKER_NAME",
99
- "D1_ID",
100
- "KV_ID",
101
- "R2_NAME",
102
- "QUEUE_NAME",
103
- "VECTORIZE_NAME"
104
- ];
105
- var BARE_PLACEHOLDERS = ["ACCOUNT_ID", "HOSTNAME"];
106
- var TOKEN_RE = /\$([A-Z][A-Z0-9_]*)(?:\(([^()\s]*)\))?/g;
107
- var UnresolvedSecret = class extends Error {
108
- secretName;
109
- constructor(secretName) {
110
- super(`secret ${secretName} has no value in this deploy`);
111
- this.secretName = secretName;
112
- }
113
- };
114
- function renderString(value, values) {
115
- return value.replace(TOKEN_RE, (whole, kind, arg) => {
116
- if (BARE_PLACEHOLDERS.includes(kind)) {
117
- if (arg !== void 0) throw new Error(`placeholder $${kind} takes no argument: ${whole}`);
118
- return kind === "ACCOUNT_ID" ? values.accountId : values.hostname;
119
- }
120
- if (!FUNCTION_PLACEHOLDERS.includes(kind) || !arg) {
121
- throw new Error(`unknown placeholder ${whole} (manifest version ${MANIFEST_VERSION})`);
122
- }
123
- switch (kind) {
124
- case "SECRET": {
125
- const secret = values.secret(arg);
126
- if (secret === void 0) throw new UnresolvedSecret(arg);
127
- return secret;
128
- }
129
- case "WORKER_NAME":
130
- return values.workerName(arg);
131
- default:
132
- return values.resource(kind, arg);
133
- }
134
- });
135
- }
136
- function renderValue(value, values) {
137
- if (typeof value === "string") return renderString(value, values);
138
- if (Array.isArray(value)) return value.map((item) => renderValue(item, values));
139
- if (value && typeof value === "object") {
140
- const out = {};
141
- for (const [key, item] of Object.entries(value)) out[key] = renderValue(item, values);
142
- return out;
143
- }
144
- return value;
145
- }
146
- function renderBindings(bindings, values) {
147
- const out = [];
148
- for (const binding of bindings) {
149
- try {
150
- out.push(renderValue(binding, values));
151
- } catch (error) {
152
- if (error instanceof UnresolvedSecret && binding.type === "secret_text") continue;
153
- throw error;
154
- }
155
- }
156
- return out;
157
- }
158
- function parseManifest(text) {
159
- const manifest = JSON.parse(text);
160
- if (typeof manifest?.product !== "string" || !manifest.product) {
161
- throw new Error("not a release manifest");
162
- }
163
- if (typeof manifest.productLabel !== "string" || !manifest.productLabel) {
164
- throw new Error("malformed manifest: no product label");
165
- }
166
- if (manifest.manifestVersion !== MANIFEST_VERSION) {
167
- throw new Error(
168
- `manifest version ${manifest.manifestVersion} is not supported by this tool (expects ${MANIFEST_VERSION}); update create-composable-os`
169
- );
170
- }
171
- if (!Array.isArray(manifest.workers) || !Array.isArray(manifest.migrations)) {
172
- throw new Error("malformed manifest");
173
- }
174
- return manifest;
175
- }
176
- function deployOrder(workers) {
177
- const byName = new Map(workers.map((w) => [w.name, w]));
178
- const out = [];
179
- const state = /* @__PURE__ */ new Map();
180
- const visit = (worker) => {
181
- const seen = state.get(worker.name);
182
- if (seen === "done") return;
183
- if (seen === "visiting") return;
184
- state.set(worker.name, "visiting");
185
- for (const dep of [...worker.dependsOn].sort()) {
186
- const target = byName.get(dep);
187
- if (target && target !== worker) visit(target);
188
- }
189
- state.set(worker.name, "done");
190
- out.push(worker);
191
- };
192
- for (const worker of [...workers].sort((a, b) => a.name.localeCompare(b.name))) visit(worker);
193
- return out;
194
- }
195
- function gatekeeperBindingName(prefix, shortName) {
196
- return `${prefix}${shortName.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
197
- }
198
-
199
- // ../release/src/bundle.ts
200
- var BundleError = class extends Error {
201
- name = "BundleError";
202
- };
203
- async function openBundle(bytes) {
204
- let files;
205
- try {
206
- files = readTar(await gunzip(bytes));
207
- } catch (error) {
208
- throw new BundleError(`not a release bundle: ${error.message}`);
209
- }
210
- const manifestBytes = files.get("manifest.json");
211
- if (!manifestBytes) throw new BundleError("bundle has no manifest.json");
212
- const manifestText = new TextDecoder().decode(manifestBytes);
213
- const manifest = parseManifest(manifestText);
214
- const decoder2 = new TextDecoder();
215
- const expected = /* @__PURE__ */ new Set(["manifest.json"]);
216
- for (const worker of manifest.workers) {
217
- for (const module of worker.modules) {
218
- const path = `modules/${module.sha256}`;
219
- expected.add(path);
220
- const data = files.get(path);
221
- if (!data) throw new BundleError(`${worker.name}: module ${module.name} is missing`);
222
- if (data.length !== module.size || await sha256Hex(data) !== module.sha256) {
223
- throw new BundleError(`${worker.name}: module ${module.name} does not match its hash`);
224
- }
225
- }
226
- for (const [path, file] of Object.entries(worker.assets?.files ?? {})) {
227
- const data = files.get(`assets/${file.hash}`);
228
- expected.add(`assets/${file.hash}`);
229
- if (!data) throw new BundleError(`${worker.name}: asset ${path} is missing`);
230
- if (data.length !== file.size || await assetHash(data, path) !== file.hash) {
231
- throw new BundleError(`${worker.name}: asset ${path} does not match its hash`);
232
- }
233
- }
234
- }
235
- for (const migration of manifest.migrations) {
236
- const path = `migrations/${migration.name}`;
237
- expected.add(path);
238
- const data = files.get(path);
239
- if (!data || await sha256Hex(data) !== migration.sha256) {
240
- throw new BundleError(`migration ${migration.name} is missing or does not match its hash`);
241
- }
242
- }
243
- const clientFiles = /* @__PURE__ */ new Map();
244
- for (const file of manifest.client?.files ?? []) {
245
- if (file.path.split("/").some((part) => part === ".." || part === "")) {
246
- throw new BundleError(`client file ${file.path} has an invalid path`);
247
- }
248
- const path = `client/${file.path}`;
249
- expected.add(path);
250
- const data = files.get(path);
251
- if (!data || data.length !== file.size || await sha256Hex(data) !== file.sha256) {
252
- throw new BundleError(`client file ${file.path} is missing or does not match its hash`);
253
- }
254
- clientFiles.set(file.path, data);
255
- }
256
- for (const path of files.keys()) {
257
- if (!expected.has(path)) throw new BundleError(`unexpected file in bundle: ${path}`);
258
- }
259
- const get = (path) => {
260
- const data = files.get(path);
261
- if (!data) throw new BundleError(`bundle has no ${path}`);
262
- return data;
263
- };
264
- return {
265
- manifest,
266
- manifestText,
267
- module: (sha) => get(`modules/${sha}`),
268
- asset: (hash) => get(`assets/${hash}`),
269
- migration: (name) => decoder2.decode(get(`migrations/${name}`)),
270
- clientFiles
271
- };
272
- }
273
- function releaseAssetNames(product, version) {
274
- const prefix = releaseFilePrefix(product);
275
- return {
276
- bundle: `${prefix}-${version}.tar.gz`,
277
- manifest: `${prefix}-${version}.manifest.json`,
278
- sums: "SHA256SUMS"
279
- };
280
- }
281
- function parseSums(text) {
282
- const out = /* @__PURE__ */ new Map();
283
- for (const line of text.split("\n")) {
284
- const match = /^([0-9a-f]{64})\s+\*?(\S+)\s*$/.exec(line.trim());
285
- if (match) out.set(match[2], match[1]);
286
- }
287
- return out;
288
- }
4
+ } from "./chunk-ZJSFX4RD.js";
289
5
 
290
6
  // ../release/src/cloudflare.ts
291
7
  var CLOUDFLARE_API = "https://api.cloudflare.com/client/v4";
@@ -299,6 +15,14 @@ var CloudflareApiError = class extends Error {
299
15
  this.codes = codes;
300
16
  }
301
17
  };
18
+ async function unless404(call) {
19
+ try {
20
+ return await call;
21
+ } catch (error) {
22
+ if (error instanceof CloudflareApiError && error.status === 404) return null;
23
+ throw error;
24
+ }
25
+ }
302
26
  var CONTENT_TYPES = {
303
27
  esm: "application/javascript+module",
304
28
  text: "text/plain",
@@ -427,12 +151,10 @@ var CloudflareClient = class _CloudflareClient {
427
151
  );
428
152
  }
429
153
  async workersSubdomain(accountId) {
430
- try {
431
- return (await this.request("GET", `/accounts/${accountId}/workers/subdomain`)).result.subdomain;
432
- } catch (error) {
433
- if (error instanceof CloudflareApiError && error.status === 404) return null;
434
- throw error;
435
- }
154
+ const found = await unless404(
155
+ this.request("GET", `/accounts/${accountId}/workers/subdomain`)
156
+ );
157
+ return found ? found.result.subdomain : null;
436
158
  }
437
159
  async createWorkersSubdomain(accountId, subdomain) {
438
160
  return (await this.request("PUT", `/accounts/${accountId}/workers/subdomain`, {
@@ -446,12 +168,17 @@ var CloudflareClient = class _CloudflareClient {
446
168
  `/accounts/${accountId}/d1/database?per_page=10000`
447
169
  )).result;
448
170
  }
449
- async createD1(accountId, name) {
171
+ /**
172
+ * Creates a database. A location hint (ADR 0580) is sent as `primary_location_hint`, the D1
173
+ * create API's field; Cloudflare honours it only at creation, and best effort.
174
+ */
175
+ async createD1(accountId, name, options = {}) {
450
176
  return (await this.request(
451
177
  "POST",
452
178
  `/accounts/${accountId}/d1/database`,
453
179
  {
454
- name
180
+ name,
181
+ ...options.locationHint ? { primary_location_hint: options.locationHint } : {}
455
182
  }
456
183
  )).result;
457
184
  }
@@ -466,12 +193,11 @@ var CloudflareClient = class _CloudflareClient {
466
193
  { sql, params }
467
194
  )).result;
468
195
  }
469
- /** The current D1 Time Travel bookmark (or the one at `timestamp`). */
470
- async d1Bookmark(accountId, databaseId, timestamp) {
471
- const query = timestamp ? `?timestamp=${encodeURIComponent(timestamp)}` : "";
196
+ /** The current D1 Time Travel bookmark. */
197
+ async d1Bookmark(accountId, databaseId) {
472
198
  return (await this.request(
473
199
  "GET",
474
- `/accounts/${accountId}/d1/database/${databaseId}/time_travel/bookmark${query}`
200
+ `/accounts/${accountId}/d1/database/${databaseId}/time_travel/bookmark`
475
201
  )).result.bookmark;
476
202
  }
477
203
  /** Restores a database to a bookmark, in place. Returns the bookmark that undoes it. */
@@ -487,8 +213,15 @@ var CloudflareClient = class _CloudflareClient {
487
213
  `/accounts/${accountId}/r2/buckets?per_page=1000`
488
214
  )).result.buckets;
489
215
  }
490
- async createR2(accountId, name) {
491
- await this.request("POST", `/accounts/${accountId}/r2/buckets`, { name });
216
+ /**
217
+ * Creates a bucket. A location hint (ADR 0580) is sent as `locationHint`, the R2 create API's
218
+ * field; Cloudflare honours it only the first time a bucket of that name is created, best effort.
219
+ */
220
+ async createR2(accountId, name, options = {}) {
221
+ await this.request("POST", `/accounts/${accountId}/r2/buckets`, {
222
+ name,
223
+ ...options.locationHint ? { locationHint: options.locationHint } : {}
224
+ });
492
225
  }
493
226
  async deleteR2(accountId, name) {
494
227
  await this.request("DELETE", `/accounts/${accountId}/r2/buckets/${name}`);
@@ -611,27 +344,18 @@ var CloudflareClient = class _CloudflareClient {
611
344
  ...message ? { annotations: { "workers/message": message } } : {}
612
345
  });
613
346
  }
614
- /** The version currently taking all traffic, or null. */
615
- async currentVersion(accountId, name) {
616
- this.accountOnly("Worker deployments");
617
- const { result } = await this.request("GET", `${this.scripts(accountId)}/${name}/deployments`);
618
- const latest = result.deployments[0];
619
- return latest?.versions.find((v) => v.percentage === 100)?.version_id ?? null;
620
- }
621
347
  async deleteScript(accountId, name) {
622
348
  await this.request("DELETE", `${this.scripts(accountId)}/${name}?force=true`);
623
349
  }
624
350
  // ---- Workers for Platforms (ADR 0210) -------------------------------------------------------
625
351
  async getDispatchNamespace(accountId, name) {
626
- try {
627
- return (await this.request(
352
+ const found = await unless404(
353
+ this.request(
628
354
  "GET",
629
355
  `/accounts/${accountId}/workers/dispatch/namespaces/${encodeURIComponent(name)}`
630
- )).result ? { name } : null;
631
- } catch (error) {
632
- if (error instanceof CloudflareApiError && error.status === 404) return null;
633
- throw error;
634
- }
356
+ )
357
+ );
358
+ return found?.result ? { name } : null;
635
359
  }
636
360
  async createDispatchNamespace(accountId, name) {
637
361
  await this.request("POST", `/accounts/${accountId}/workers/dispatch/namespaces`, { name });
@@ -690,16 +414,13 @@ var CloudflareClient = class _CloudflareClient {
690
414
  });
691
415
  }
692
416
  /** Removes a secret from a Worker (a user Worker with `forNamespace`). Missing is not an error. */
693
- async deleteSecret(accountId, name, secret) {
694
- try {
695
- await this.request(
696
- "DELETE",
697
- `${this.scripts(accountId)}/${name}/secrets/${encodeURIComponent(secret)}`
698
- );
699
- } catch (error) {
700
- if (error instanceof CloudflareApiError && error.status === 404) return;
701
- throw error;
702
- }
417
+ async deleteSecret(accountId, name, secret) {
418
+ await unless404(
419
+ this.request(
420
+ "DELETE",
421
+ `${this.scripts(accountId)}/${name}/secrets/${encodeURIComponent(secret)}`
422
+ )
423
+ );
703
424
  }
704
425
  async putSchedules(accountId, name, crons) {
705
426
  this.accountOnly("Cron Triggers");
@@ -727,12 +448,10 @@ var CloudflareClient = class _CloudflareClient {
727
448
  // ---- AI Gateway (ADR 0180) -----------------------------------------------------------------
728
449
  /** A gateway by id, or null when there is none. Needs AI Gateway Read or Edit. */
729
450
  async getAiGateway(accountId, id) {
730
- try {
731
- return (await this.request("GET", `/accounts/${accountId}/ai-gateway/gateways/${id}`)).result;
732
- } catch (error) {
733
- if (error instanceof CloudflareApiError && error.status === 404) return null;
734
- throw error;
735
- }
451
+ const found = await unless404(
452
+ this.request("GET", `/accounts/${accountId}/ai-gateway/gateways/${id}`)
453
+ );
454
+ return found ? found.result : null;
736
455
  }
737
456
  async createAiGateway(accountId, settings) {
738
457
  return (await this.request("POST", `/accounts/${accountId}/ai-gateway/gateways`, settings)).result;
@@ -817,105 +536,460 @@ var CloudflareClient = class _CloudflareClient {
817
536
  await this.deleteProviderConfig(accountId, gatewayId, config.id);
818
537
  }
819
538
  }
820
- await this.request(
821
- "POST",
822
- `/accounts/${accountId}/ai-gateway/gateways/${gatewayId}/provider_configs`,
823
- { provider_slug: provider, alias, default_config: true, secret: key }
824
- );
825
- return { provider, alias };
539
+ await this.request(
540
+ "POST",
541
+ `/accounts/${accountId}/ai-gateway/gateways/${gatewayId}/provider_configs`,
542
+ { provider_slug: provider, alias, default_config: true, secret: key }
543
+ );
544
+ return { provider, alias };
545
+ }
546
+ // ---- Account API tokens ---------------------------------------------------------------------
547
+ /** Permission groups an account token can be given, by exact name. Needs Account API Tokens Read. */
548
+ async permissionGroups(accountId, name) {
549
+ return (await this.request(
550
+ "GET",
551
+ `/accounts/${accountId}/tokens/permission_groups?name=${encodeURIComponent(name)}`
552
+ )).result.filter((g) => g.name === name);
553
+ }
554
+ /**
555
+ * Checks that `token` can call Workers AI in the account (ADR 0330): lists one model of the
556
+ * catalogue, which needs Workers AI Read. Throws (CloudflareApiError 401/403) when it cannot.
557
+ * The token is sent only to the Cloudflare API, and never logged.
558
+ */
559
+ async probeWorkersAi(accountId, token) {
560
+ await this.request("GET", `/accounts/${accountId}/ai/models/search?per_page=1`, void 0, {
561
+ auth: token
562
+ });
563
+ }
564
+ /** Creates an account-owned API token. Returns its id and value (shown once). */
565
+ async createAccountToken(accountId, name, permissionGroupIds, options = {}) {
566
+ const { result } = await this.request(
567
+ "POST",
568
+ `/accounts/${accountId}/tokens`,
569
+ {
570
+ name,
571
+ ...options.expiresOn ? { expires_on: options.expiresOn } : {},
572
+ policies: [
573
+ {
574
+ effect: "allow",
575
+ resources: options.resources ?? { [`com.cloudflare.api.account.${accountId}`]: "*" },
576
+ permission_groups: permissionGroupIds.map((id) => ({ id }))
577
+ }
578
+ ]
579
+ }
580
+ );
581
+ return { id: result.id, value: result.value };
582
+ }
583
+ /**
584
+ * A full SQL dump of a D1 database (the export API, polled until done). Returns the
585
+ * Cloudflare-hosted, time-limited download URL: the dump never passes through the caller.
586
+ */
587
+ async exportD1(accountId, databaseId) {
588
+ let bookmark;
589
+ for (let i = 0; i < 30; i++) {
590
+ const { result } = await this.request("POST", `/accounts/${accountId}/d1/database/${databaseId}/export`, {
591
+ output_format: "polling",
592
+ ...bookmark ? { current_bookmark: bookmark } : {}
593
+ });
594
+ if (result.status === "error") throw new Error(`D1 export failed: ${result.error ?? ""}`);
595
+ if (result.status === "complete" && result.result?.signed_url)
596
+ return result.result.signed_url;
597
+ bookmark = result.at_bookmark ?? bookmark;
598
+ await new Promise((r) => setTimeout(r, 1e3));
599
+ }
600
+ throw new Error("D1 export did not finish in time");
601
+ }
602
+ async deleteAccountToken(accountId, id) {
603
+ await this.request("DELETE", `/accounts/${accountId}/tokens/${id}`);
604
+ }
605
+ /** Puts one object in an R2 bucket (the org's extensions, stage 24). */
606
+ async putR2Object(accountId, bucket, key, bytes) {
607
+ return (await this.request(
608
+ "PUT",
609
+ `/accounts/${accountId}/r2/buckets/${bucket}/objects/${encodeURIComponent(key)}`,
610
+ void 0,
611
+ { raw: bytes, headers: { "content-type": "application/octet-stream" } }
612
+ )).result;
613
+ }
614
+ // ---- Static assets (direct upload) ----------------------------------------------------------
615
+ /** Starts an assets upload session; returns the JWT and the hashes the API still needs. */
616
+ async assetsUploadSession(accountId, name, manifest) {
617
+ return (await this.request(
618
+ "POST",
619
+ `${this.scripts(accountId)}/${name}/assets-upload-session`,
620
+ { manifest }
621
+ )).result;
622
+ }
623
+ /** Uploads one bucket of assets (base64 parts named by hash). Returns the completion JWT, if any. */
624
+ async uploadAssets(accountId, jwt, files) {
625
+ const form = new FormData();
626
+ for (const file of files) {
627
+ form.set(file.hash, new Blob([file.base64], { type: file.contentType }), file.hash);
628
+ }
629
+ const { result } = await this.request(
630
+ "POST",
631
+ `/accounts/${accountId}/workers/assets/upload?base64=true`,
632
+ void 0,
633
+ { raw: form, auth: jwt }
634
+ );
635
+ return result?.jwt;
636
+ }
637
+ };
638
+
639
+ // ../release/src/app-builds.ts
640
+ var APP_PLATFORMS = ["ios", "android"];
641
+ var COLUMNS = [
642
+ "environment",
643
+ "platform",
644
+ "app_version",
645
+ "build_number",
646
+ "api_version",
647
+ "app_id",
648
+ "commit_sha",
649
+ "uploaded_at",
650
+ "supported"
651
+ ];
652
+ var AppBuildRefused = class extends Error {
653
+ };
654
+ var missingTable = (error) => error instanceof CloudflareApiError && /no such table/i.test(error.message);
655
+ async function appBuildsViaApi(api, accountId, databaseId, environment, limit = 200) {
656
+ try {
657
+ const [first] = await api.queryD1(
658
+ accountId,
659
+ databaseId,
660
+ `SELECT ${COLUMNS.join(", ")} FROM core_app_build WHERE environment = ? ORDER BY build_number DESC, platform LIMIT ${Math.max(1, Math.min(1e3, limit))}`,
661
+ [environment]
662
+ );
663
+ return first?.results ?? [];
664
+ } catch (error) {
665
+ if (missingTable(error)) return null;
666
+ throw error;
667
+ }
668
+ }
669
+ function nextBuildNumber(builds) {
670
+ return builds.reduce((max, b) => Math.max(max, Number(b.build_number)), 0) + 1;
671
+ }
672
+ function recordedIdProblem(builds, platform, appId) {
673
+ const latest = builds.find((b) => b.platform === platform);
674
+ if (!latest || latest.app_id === appId) return null;
675
+ return `the ${platform} app was recorded as ${latest.app_id} (build ${latest.build_number}); product.ts now says ${appId}. A store id never changes once published: put it back, or make a new app in the store on purpose and say so in an ADR`;
676
+ }
677
+ async function recordAppBuildViaApi(api, accountId, databaseId, record) {
678
+ const builds = await appBuildsViaApi(api, accountId, databaseId, record.environment, 1e3);
679
+ if (builds === null) {
680
+ throw new AppBuildRefused(
681
+ "the host has no core_app_build yet: it is on a release from before the app's builds were recorded (stage 63). Upgrade the host first (cos deploy), then record the build"
682
+ );
683
+ }
684
+ const same = builds.find(
685
+ (b) => b.platform === record.platform && Number(b.build_number) === record.build_number
686
+ );
687
+ if (same) {
688
+ if (same.commit_sha === record.commit_sha && same.app_id === record.app_id) return "already";
689
+ throw new AppBuildRefused(
690
+ `${record.platform} build ${record.build_number} is already recorded (commit ${same.commit_sha ?? "none"}): each build number is used once`
691
+ );
692
+ }
693
+ const problem = recordedIdProblem(builds, record.platform, record.app_id);
694
+ if (problem) throw new AppBuildRefused(problem);
695
+ const highest = builds.find((b) => b.platform === record.platform);
696
+ if (highest && Number(highest.build_number) > record.build_number) {
697
+ throw new AppBuildRefused(
698
+ `${record.platform} build ${record.build_number} is lower than build ${highest.build_number}, already recorded: the stores take only a higher one`
699
+ );
700
+ }
701
+ await api.queryD1(
702
+ accountId,
703
+ databaseId,
704
+ `INSERT INTO core_app_build (${COLUMNS.join(", ")}) VALUES (${COLUMNS.map(() => "?").join(", ")})`,
705
+ COLUMNS.map((c) => record[c])
706
+ );
707
+ return "recorded";
708
+ }
709
+
710
+ // ../release/src/hash.ts
711
+ async function sha256Hex(bytes) {
712
+ const data = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
713
+ const digest = await crypto.subtle.digest("SHA-256", data);
714
+ return toHex(new Uint8Array(digest));
715
+ }
716
+ function toHex(bytes) {
717
+ let out = "";
718
+ for (const byte of bytes) out += byte.toString(16).padStart(2, "0");
719
+ return out;
720
+ }
721
+ function toBase64(bytes) {
722
+ let binary = "";
723
+ const chunk = 32768;
724
+ for (let i = 0; i < bytes.length; i += chunk) {
725
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
726
+ }
727
+ return btoa(binary);
728
+ }
729
+ function fromBase64(text) {
730
+ const binary = atob(text);
731
+ const out = new Uint8Array(binary.length);
732
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
733
+ return out;
734
+ }
735
+ function extensionOf(path) {
736
+ const name = path.slice(path.lastIndexOf("/") + 1);
737
+ const dot = name.lastIndexOf(".");
738
+ return dot <= 0 ? "" : name.slice(dot + 1);
739
+ }
740
+ async function assetHash(bytes, path) {
741
+ return (await sha256Hex(toBase64(bytes) + extensionOf(path))).slice(0, 32);
742
+ }
743
+ function sameDigest(a, b) {
744
+ if (a.length !== b.length) return false;
745
+ let diff = 0;
746
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
747
+ return diff === 0;
748
+ }
749
+
750
+ // ../release/src/archive.ts
751
+ var BLOCK = 512;
752
+ var encoder = new TextEncoder();
753
+ var decoder = new TextDecoder();
754
+ function readOctal(block, offset, length) {
755
+ const text = decoder.decode(block.subarray(offset, offset + length)).replace(/[\0 ]+$/g, "");
756
+ return text ? Number.parseInt(text.trim(), 8) : 0;
757
+ }
758
+ function readTar(bytes) {
759
+ const files = /* @__PURE__ */ new Map();
760
+ let offset = 0;
761
+ while (offset + BLOCK <= bytes.length) {
762
+ const header = bytes.subarray(offset, offset + BLOCK);
763
+ if (header.every((byte) => byte === 0)) break;
764
+ let stored = 0;
765
+ for (let i = 0; i < BLOCK; i++) stored += i >= 148 && i < 156 ? 32 : header[i];
766
+ if (stored !== readOctal(header, 148, 8)) throw new Error("corrupt tar header checksum");
767
+ const nameEnd = header.indexOf(0);
768
+ const name = decoder.decode(
769
+ header.subarray(0, nameEnd === -1 || nameEnd > 100 ? 100 : nameEnd)
770
+ );
771
+ const prefixBytes = header.subarray(345, 500);
772
+ const prefixEnd = prefixBytes.indexOf(0);
773
+ const prefix = decoder.decode(prefixBytes.subarray(0, prefixEnd === -1 ? 155 : prefixEnd));
774
+ const path = prefix ? `${prefix}/${name}` : name;
775
+ const size = readOctal(header, 124, 12);
776
+ const type = String.fromCharCode(header[156] ?? 0);
777
+ offset += BLOCK;
778
+ if (offset + size > bytes.length) throw new Error(`truncated tar entry ${path}`);
779
+ if (type === "0" || type === "\0") {
780
+ if (path.startsWith("/") || path.split("/").includes("..")) {
781
+ throw new Error(`unsafe path in bundle: ${path}`);
782
+ }
783
+ if (files.has(path)) throw new Error(`duplicate path in bundle: ${path}`);
784
+ files.set(path, bytes.slice(offset, offset + size));
785
+ }
786
+ offset += Math.ceil(size / BLOCK) * BLOCK;
787
+ }
788
+ return files;
789
+ }
790
+ async function pipe(bytes, transform) {
791
+ const stream = new Blob([bytes]).stream().pipeThrough(transform);
792
+ return new Uint8Array(await new Response(stream).arrayBuffer());
793
+ }
794
+ async function gunzip(bytes) {
795
+ return pipe(bytes, new DecompressionStream("gzip"));
796
+ }
797
+
798
+ // ../release/src/manifest.ts
799
+ var MANIFEST_VERSION = 1;
800
+ var FUNCTION_PLACEHOLDERS = [
801
+ "SECRET",
802
+ "WORKER_NAME",
803
+ "D1_ID",
804
+ "KV_ID",
805
+ "R2_NAME",
806
+ "QUEUE_NAME",
807
+ "VECTORIZE_NAME"
808
+ ];
809
+ var BARE_PLACEHOLDERS = ["ACCOUNT_ID", "HOSTNAME"];
810
+ var TOKEN_RE = /\$([A-Z][A-Z0-9_]*)(?:\(([^()\s]*)\))?/g;
811
+ var UnresolvedSecret = class extends Error {
812
+ secretName;
813
+ constructor(secretName) {
814
+ super(`secret ${secretName} has no value in this deploy`);
815
+ this.secretName = secretName;
816
+ }
817
+ };
818
+ function renderString(value, values) {
819
+ return value.replace(TOKEN_RE, (whole, kind, arg) => {
820
+ if (BARE_PLACEHOLDERS.includes(kind)) {
821
+ if (arg !== void 0) throw new Error(`placeholder $${kind} takes no argument: ${whole}`);
822
+ return kind === "ACCOUNT_ID" ? values.accountId : values.hostname;
823
+ }
824
+ if (!FUNCTION_PLACEHOLDERS.includes(kind) || !arg) {
825
+ throw new Error(`unknown placeholder ${whole} (manifest version ${MANIFEST_VERSION})`);
826
+ }
827
+ switch (kind) {
828
+ case "SECRET": {
829
+ const secret = values.secret(arg);
830
+ if (secret === void 0) throw new UnresolvedSecret(arg);
831
+ return secret;
832
+ }
833
+ case "WORKER_NAME":
834
+ return values.workerName(arg);
835
+ default:
836
+ return values.resource(kind, arg);
837
+ }
838
+ });
839
+ }
840
+ function renderValue(value, values) {
841
+ if (typeof value === "string") return renderString(value, values);
842
+ if (Array.isArray(value)) return value.map((item) => renderValue(item, values));
843
+ if (value && typeof value === "object") {
844
+ const out = {};
845
+ for (const [key, item] of Object.entries(value)) out[key] = renderValue(item, values);
846
+ return out;
826
847
  }
827
- // ---- Account API tokens ---------------------------------------------------------------------
828
- /** Permission groups an account token can be given, by exact name. Needs Account API Tokens Read. */
829
- async permissionGroups(accountId, name) {
830
- return (await this.request(
831
- "GET",
832
- `/accounts/${accountId}/tokens/permission_groups?name=${encodeURIComponent(name)}`
833
- )).result.filter((g) => g.name === name);
848
+ return value;
849
+ }
850
+ function renderBindings(bindings, values) {
851
+ const out = [];
852
+ for (const binding of bindings) {
853
+ try {
854
+ out.push(renderValue(binding, values));
855
+ } catch (error) {
856
+ if (error instanceof UnresolvedSecret && binding.type === "secret_text") continue;
857
+ throw error;
858
+ }
834
859
  }
835
- /**
836
- * Checks that `token` can call Workers AI in the account (ADR 0330): lists one model of the
837
- * catalogue, which needs Workers AI Read. Throws (CloudflareApiError 401/403) when it cannot.
838
- * The token is sent only to the Cloudflare API, and never logged.
839
- */
840
- async probeWorkersAi(accountId, token) {
841
- await this.request("GET", `/accounts/${accountId}/ai/models/search?per_page=1`, void 0, {
842
- auth: token
843
- });
860
+ return out;
861
+ }
862
+ function parseManifest(text) {
863
+ const manifest = JSON.parse(text);
864
+ if (typeof manifest?.product !== "string" || !manifest.product) {
865
+ throw new Error("not a release manifest");
844
866
  }
845
- /** Creates an account-owned API token. Returns its id and value (shown once). */
846
- async createAccountToken(accountId, name, permissionGroupIds, options = {}) {
847
- const { result } = await this.request(
848
- "POST",
849
- `/accounts/${accountId}/tokens`,
850
- {
851
- name,
852
- ...options.expiresOn ? { expires_on: options.expiresOn } : {},
853
- policies: [
854
- {
855
- effect: "allow",
856
- resources: options.resources ?? { [`com.cloudflare.api.account.${accountId}`]: "*" },
857
- permission_groups: permissionGroupIds.map((id) => ({ id }))
858
- }
859
- ]
860
- }
867
+ if (typeof manifest.productLabel !== "string" || !manifest.productLabel) {
868
+ throw new Error("malformed manifest: no product label");
869
+ }
870
+ if (manifest.manifestVersion !== MANIFEST_VERSION) {
871
+ throw new Error(
872
+ `manifest version ${manifest.manifestVersion} is not supported by this tool (expects ${MANIFEST_VERSION}); update create-composable-os`
861
873
  );
862
- return { id: result.id, value: result.value };
863
874
  }
864
- /**
865
- * A full SQL dump of a D1 database (the export API, polled until done). Returns the
866
- * Cloudflare-hosted, time-limited download URL: the dump never passes through the caller.
867
- */
868
- async exportD1(accountId, databaseId, attempts = 30) {
869
- let bookmark;
870
- for (let i = 0; i < attempts; i++) {
871
- const { result } = await this.request("POST", `/accounts/${accountId}/d1/database/${databaseId}/export`, {
872
- output_format: "polling",
873
- ...bookmark ? { current_bookmark: bookmark } : {}
874
- });
875
- if (result.status === "error") throw new Error(`D1 export failed: ${result.error ?? ""}`);
876
- if (result.status === "complete" && result.result?.signed_url)
877
- return result.result.signed_url;
878
- bookmark = result.at_bookmark ?? bookmark;
879
- await new Promise((r) => setTimeout(r, 1e3));
880
- }
881
- throw new Error("D1 export did not finish in time");
875
+ if (!Array.isArray(manifest.workers) || !Array.isArray(manifest.migrations)) {
876
+ throw new Error("malformed manifest");
882
877
  }
883
- async deleteAccountToken(accountId, id) {
884
- await this.request("DELETE", `/accounts/${accountId}/tokens/${id}`);
878
+ return manifest;
879
+ }
880
+ function deployOrder(workers) {
881
+ const byName = new Map(workers.map((w) => [w.name, w]));
882
+ const out = [];
883
+ const state = /* @__PURE__ */ new Map();
884
+ const visit = (worker) => {
885
+ const seen = state.get(worker.name);
886
+ if (seen === "done") return;
887
+ if (seen === "visiting") return;
888
+ state.set(worker.name, "visiting");
889
+ for (const dep of [...worker.dependsOn].sort()) {
890
+ const target = byName.get(dep);
891
+ if (target && target !== worker) visit(target);
892
+ }
893
+ state.set(worker.name, "done");
894
+ out.push(worker);
895
+ };
896
+ for (const worker of [...workers].sort((a, b) => a.name.localeCompare(b.name))) visit(worker);
897
+ return out;
898
+ }
899
+ function gatekeeperBindingName(prefix, shortName) {
900
+ return `${prefix}${shortName.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
901
+ }
902
+
903
+ // ../release/src/bundle.ts
904
+ var BundleError = class extends Error {
905
+ name = "BundleError";
906
+ };
907
+ async function openBundle(bytes) {
908
+ let files;
909
+ try {
910
+ files = readTar(await gunzip(bytes));
911
+ } catch (error) {
912
+ throw new BundleError(`not a release bundle: ${error.message}`);
885
913
  }
886
- /** Puts one object in an R2 bucket (the org's extensions, stage 24). */
887
- async putR2Object(accountId, bucket, key, bytes) {
888
- return (await this.request(
889
- "PUT",
890
- `/accounts/${accountId}/r2/buckets/${bucket}/objects/${encodeURIComponent(key)}`,
891
- void 0,
892
- { raw: bytes, headers: { "content-type": "application/octet-stream" } }
893
- )).result;
914
+ const manifestBytes = files.get("manifest.json");
915
+ if (!manifestBytes) throw new BundleError("bundle has no manifest.json");
916
+ const manifestText = new TextDecoder().decode(manifestBytes);
917
+ const manifest = parseManifest(manifestText);
918
+ const decoder2 = new TextDecoder();
919
+ const expected = /* @__PURE__ */ new Set(["manifest.json"]);
920
+ for (const worker of manifest.workers) {
921
+ for (const module of worker.modules) {
922
+ const path = `modules/${module.sha256}`;
923
+ expected.add(path);
924
+ const data = files.get(path);
925
+ if (!data) throw new BundleError(`${worker.name}: module ${module.name} is missing`);
926
+ if (data.length !== module.size || await sha256Hex(data) !== module.sha256) {
927
+ throw new BundleError(`${worker.name}: module ${module.name} does not match its hash`);
928
+ }
929
+ }
930
+ for (const [path, file] of Object.entries(worker.assets?.files ?? {})) {
931
+ const data = files.get(`assets/${file.hash}`);
932
+ expected.add(`assets/${file.hash}`);
933
+ if (!data) throw new BundleError(`${worker.name}: asset ${path} is missing`);
934
+ if (data.length !== file.size || await assetHash(data, path) !== file.hash) {
935
+ throw new BundleError(`${worker.name}: asset ${path} does not match its hash`);
936
+ }
937
+ }
894
938
  }
895
- // ---- Static assets (direct upload) ----------------------------------------------------------
896
- /** Starts an assets upload session; returns the JWT and the hashes the API still needs. */
897
- async assetsUploadSession(accountId, name, manifest) {
898
- return (await this.request(
899
- "POST",
900
- `${this.scripts(accountId)}/${name}/assets-upload-session`,
901
- { manifest }
902
- )).result;
939
+ for (const migration of manifest.migrations) {
940
+ const path = `migrations/${migration.name}`;
941
+ expected.add(path);
942
+ const data = files.get(path);
943
+ if (!data || await sha256Hex(data) !== migration.sha256) {
944
+ throw new BundleError(`migration ${migration.name} is missing or does not match its hash`);
945
+ }
903
946
  }
904
- /** Uploads one bucket of assets (base64 parts named by hash). Returns the completion JWT, if any. */
905
- async uploadAssets(accountId, jwt, files) {
906
- const form = new FormData();
907
- for (const file of files) {
908
- form.set(file.hash, new Blob([file.base64], { type: file.contentType }), file.hash);
947
+ const clientFiles = /* @__PURE__ */ new Map();
948
+ for (const file of manifest.client?.files ?? []) {
949
+ if (file.path.split("/").some((part) => part === ".." || part === "")) {
950
+ throw new BundleError(`client file ${file.path} has an invalid path`);
909
951
  }
910
- const { result } = await this.request(
911
- "POST",
912
- `/accounts/${accountId}/workers/assets/upload?base64=true`,
913
- void 0,
914
- { raw: form, auth: jwt }
915
- );
916
- return result?.jwt;
952
+ const path = `client/${file.path}`;
953
+ expected.add(path);
954
+ const data = files.get(path);
955
+ if (!data || data.length !== file.size || await sha256Hex(data) !== file.sha256) {
956
+ throw new BundleError(`client file ${file.path} is missing or does not match its hash`);
957
+ }
958
+ clientFiles.set(file.path, data);
917
959
  }
918
- };
960
+ for (const path of files.keys()) {
961
+ if (!expected.has(path)) throw new BundleError(`unexpected file in bundle: ${path}`);
962
+ }
963
+ const get = (path) => {
964
+ const data = files.get(path);
965
+ if (!data) throw new BundleError(`bundle has no ${path}`);
966
+ return data;
967
+ };
968
+ return {
969
+ manifest,
970
+ manifestText,
971
+ module: (sha) => get(`modules/${sha}`),
972
+ asset: (hash) => get(`assets/${hash}`),
973
+ migration: (name) => decoder2.decode(get(`migrations/${name}`)),
974
+ clientFiles
975
+ };
976
+ }
977
+ function releaseAssetNames(product, version) {
978
+ const prefix = releaseFilePrefix(product);
979
+ return {
980
+ bundle: `${prefix}-${version}.tar.gz`,
981
+ manifest: `${prefix}-${version}.manifest.json`,
982
+ sums: "SHA256SUMS"
983
+ };
984
+ }
985
+ function parseSums(text) {
986
+ const out = /* @__PURE__ */ new Map();
987
+ for (const line of text.split("\n")) {
988
+ const match = /^([0-9a-f]{64})\s+\*?(\S+)\s*$/.exec(line.trim());
989
+ if (match) out.set(match[2], match[1]);
990
+ }
991
+ return out;
992
+ }
919
993
 
920
994
  // ../release/src/deploy.ts
921
995
  var MIGRATIONS_TABLE = "core_migrations";
@@ -984,8 +1058,10 @@ function neededResources(manifest, gatekeepers2, features = {}) {
984
1058
  );
985
1059
  }
986
1060
  async function provisionResources(api, accountId, manifestResources, log = () => {
987
- }, names = {}) {
1061
+ }, names = {}, options = {}) {
988
1062
  const out = {};
1063
+ const hint = options.locationHint ? { locationHint: options.locationHint } : {};
1064
+ const created = options.locationHint ? `created (location hint ${options.locationHint})` : "created";
989
1065
  const key = (r) => (r.placeholder ?? "").replace(/^\$/, "");
990
1066
  for (const entry of manifestResources) {
991
1067
  if (entry.implicit) continue;
@@ -993,15 +1069,15 @@ async function provisionResources(api, accountId, manifestResources, log = () =>
993
1069
  switch (resource.type) {
994
1070
  case "d1": {
995
1071
  const existing = (await api.listD1(accountId)).find((d) => d.name === resource.name);
996
- const db = existing ?? await api.createD1(accountId, resource.name);
997
- log(` D1 ${resource.name}: ${existing ? "exists" : "created"}`);
1072
+ const db = existing ?? await api.createD1(accountId, resource.name, hint);
1073
+ log(` D1 ${resource.name}: ${existing ? "exists" : created}`);
998
1074
  out[key(resource)] = db.uuid;
999
1075
  break;
1000
1076
  }
1001
1077
  case "r2": {
1002
1078
  const exists = (await api.listR2(accountId)).some((b) => b.name === resource.name);
1003
- if (!exists) await api.createR2(accountId, resource.name);
1004
- log(` R2 ${resource.name}: ${exists ? "exists" : "created"}`);
1079
+ if (!exists) await api.createR2(accountId, resource.name, hint);
1080
+ log(` R2 ${resource.name}: ${exists ? "exists" : created}`);
1005
1081
  out[key(resource)] = resource.name;
1006
1082
  break;
1007
1083
  }
@@ -1092,6 +1168,9 @@ function placeholderValues(state, secretsFor) {
1092
1168
  secret: (name) => secretsFor[name]
1093
1169
  };
1094
1170
  }
1171
+ function deskHostname(state) {
1172
+ return state.hostnameMode === "custom" ? `desk.${state.hostname}` : "";
1173
+ }
1095
1174
  function workerBindings(worker, manifest, state, secrets) {
1096
1175
  const values = placeholderValues(state, secrets);
1097
1176
  const overrides = state.vars[worker.name] ?? {};
@@ -1101,6 +1180,9 @@ function workerBindings(worker, manifest, state, secrets) {
1101
1180
  if (binding.type === "plain_text" && overrides[binding.name] !== void 0) {
1102
1181
  return { ...binding, text: overrides[binding.name] };
1103
1182
  }
1183
+ if (binding.type === "plain_text" && binding.name === "DESK_HOSTNAME") {
1184
+ return { ...binding, text: deskHostname(state) };
1185
+ }
1104
1186
  const email = state.sendEmail?.[worker.name]?.[binding.name];
1105
1187
  if (binding.type === "send_email" && email) {
1106
1188
  return { ...binding, ...email };
@@ -1274,6 +1356,9 @@ async function deployWorkers(input) {
1274
1356
  await api.setWorkersDev(state.accountId, deployedName, onWorkersDev);
1275
1357
  if (worker.public && state.hostnameMode === "custom" && state.zoneId) {
1276
1358
  await api.putDomain(state.accountId, state.hostname, deployedName, state.zoneId);
1359
+ if (worker.bindings.some((b) => b.type === "plain_text" && b.name === "DESK_HOSTNAME")) {
1360
+ await api.putDomain(state.accountId, deskHostname(state), deployedName, state.zoneId);
1361
+ }
1277
1362
  }
1278
1363
  }
1279
1364
  return { url: `https://${state.hostname}`, workers: result };
@@ -1426,7 +1511,7 @@ async function githubJson(path, options) {
1426
1511
  function toInfo(release, product) {
1427
1512
  const version = bareVersion(release.tag_name);
1428
1513
  if (release.draft || !isVersion(version)) return null;
1429
- const channel = version.includes("-") ? "beta" : "stable";
1514
+ const channel = channelOf(version);
1430
1515
  if (release.prerelease !== (channel === "beta")) return null;
1431
1516
  const names = releaseAssetNames(product, version);
1432
1517
  const find = (name) => release.assets.find((a) => a.name === name)?.browser_download_url;
@@ -1653,6 +1738,13 @@ var encoder2 = new TextEncoder();
1653
1738
  // ../release/src/gateway.ts
1654
1739
  var GATEWAY_ID_VAR = "AI_GATEWAY_ID";
1655
1740
  var GATEWAY_TOKEN_SECRET = "AI_GATEWAY_TOKEN";
1741
+ function suppliedGatewayToken(secrets) {
1742
+ for (const values of Object.values(secrets ?? {})) {
1743
+ const token = values[GATEWAY_TOKEN_SECRET];
1744
+ if (token) return { token };
1745
+ }
1746
+ return {};
1747
+ }
1656
1748
  var GATEWAY_RUN_PERMISSION = "AI Gateway Run";
1657
1749
  var WORKERS_AI_READ_PERMISSION = "Workers AI Read";
1658
1750
  var GATEWAY_REST_VAR = "AI_GATEWAY_REST";
@@ -2006,7 +2098,7 @@ function preflight(input) {
2006
2098
  for (const name of changedGatekeepers.removed) {
2007
2099
  if (installed.has(name)) {
2008
2100
  warnings.push({
2009
- code: "unknown_current",
2101
+ code: "gatekeeper_removed",
2010
2102
  message: `Gatekeeper ${name} is installed but no longer ships in ${target.version}; it stays deployed as it is.`
2011
2103
  });
2012
2104
  }
@@ -2143,13 +2235,6 @@ function apiKillSwitchStore(api, accountId, databaseId) {
2143
2235
  }
2144
2236
  };
2145
2237
  }
2146
- function suppliedGatewayToken(secrets) {
2147
- for (const values of Object.values(secrets ?? {})) {
2148
- const token = values[GATEWAY_TOKEN_SECRET];
2149
- if (token) return { token };
2150
- }
2151
- return {};
2152
- }
2153
2238
  async function runUpdate(input) {
2154
2239
  const log = input.log ?? (() => {
2155
2240
  });
@@ -2186,7 +2271,10 @@ async function runUpdate(input) {
2186
2271
  (r) => r.placeholder && !(r.placeholder.slice(1) in state.resources)
2187
2272
  ),
2188
2273
  log,
2189
- state.resourceNames
2274
+ state.resourceNames,
2275
+ // Only resources the new release adds are created here, with the install's hint (ADR
2276
+ // 0580); nothing that exists is sent a hint or moved.
2277
+ { locationHint: state.locationHint }
2190
2278
  )
2191
2279
  };
2192
2280
  const gateway = await provisionAiGateway({
@@ -2300,12 +2388,21 @@ async function healthSmoke(hostname, version, options = {}) {
2300
2388
  } catch (error) {
2301
2389
  last = error.message;
2302
2390
  }
2303
- if (options.delayMs !== 0) await new Promise((r) => setTimeout(r, options.delayMs ?? 3e3));
2391
+ if (i < attempts - 1 && options.delayMs !== 0) {
2392
+ await new Promise((r) => setTimeout(r, options.delayMs ?? 3e3));
2393
+ }
2304
2394
  }
2305
2395
  throw new Error(`smoke check failed for ${hostname}: ${last}`);
2306
2396
  }
2307
2397
 
2308
2398
  export {
2399
+ CloudflareClient,
2400
+ APP_PLATFORMS,
2401
+ AppBuildRefused,
2402
+ appBuildsViaApi,
2403
+ nextBuildNumber,
2404
+ recordedIdProblem,
2405
+ recordAppBuildViaApi,
2309
2406
  sha256Hex,
2310
2407
  toHex,
2311
2408
  toBase64,
@@ -2319,7 +2416,6 @@ export {
2319
2416
  getRelease,
2320
2417
  VerificationError,
2321
2418
  verifyBundleBytes,
2322
- CloudflareClient,
2323
2419
  d1ApiMigrations,
2324
2420
  applyBundleMigrations,
2325
2421
  writeDeploymentState,