@composable-os/cli 0.0.0-stage → 0.1.0-beta.10
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.
- package/LICENSE +109 -0
- package/README.md +24 -2
- package/dist/accounts-X4CKM3HL.js +46 -0
- package/dist/blocks-YWDHEBOK.js +233 -0
- package/dist/chunk-2ABSVMGB.js +13 -0
- package/dist/chunk-5KSXSK7Y.js +47 -0
- package/dist/chunk-6GDEDOV7.js +157 -0
- package/dist/chunk-6UPUF4ML.js +29998 -0
- package/dist/chunk-6UWRT4VM.js +220 -0
- package/dist/chunk-6VXHPKGG.js +1302 -0
- package/dist/chunk-7CQGMVDO.js +63 -0
- package/dist/chunk-A4NTSYWV.js +11092 -0
- package/dist/chunk-CP6BXI6F.js +25825 -0
- package/dist/chunk-DU6OIFOU.js +2358 -0
- package/dist/chunk-E4WCYTCT.js +347 -0
- package/dist/chunk-GYSGVT6R.js +284 -0
- package/dist/chunk-GYTEW66E.js +50 -0
- package/dist/chunk-HDIOVFAZ.js +544 -0
- package/dist/chunk-IFG4FRW5.js +504 -0
- package/dist/chunk-JJHHNV46.js +227 -0
- package/dist/chunk-K6T42YCH.js +704 -0
- package/dist/chunk-KGHA67HG.js +765 -0
- package/dist/chunk-LJFLENFC.js +88 -0
- package/dist/chunk-LLULPZAJ.js +365 -0
- package/dist/chunk-M7A6FR2Z.js +2586 -0
- package/dist/chunk-O2UIZHND.js +249 -0
- package/dist/chunk-Q4N55M2Z.js +552 -0
- package/dist/chunk-QGGJ2G6Z.js +349 -0
- package/dist/chunk-R4W5XAUD.js +837 -0
- package/dist/chunk-TQFGGSA4.js +748 -0
- package/dist/chunk-VY64DMQO.js +15302 -0
- package/dist/chunk-WC5LHBBA.js +426 -0
- package/dist/chunk-WO6D3XP3.js +9351 -0
- package/dist/chunk-Y7JZFSTQ.js +1425 -0
- package/dist/chunk-YJJHF65I.js +759 -0
- package/dist/chunk-Z3RMMB6S.js +668 -0
- package/dist/cli-2DFENR62.js +134 -0
- package/dist/cli-YIOVSKOD.js +24531 -0
- package/dist/cli.js +25 -0
- package/dist/client-repo-PRU3VCQQ.js +55 -0
- package/dist/create.js +25 -0
- package/dist/fields-2NC7LSYE.js +50 -0
- package/dist/grants-QXMKYMGB.js +32 -0
- package/dist/invoke-I3NNNXVL.js +39 -0
- package/dist/order-PUWD65BC.js +19 -0
- package/dist/person-WIQQ7ITU.js +68 -0
- package/dist/plan-on-sale-NB774CQL.js +26 -0
- package/dist/platform/migrations/0001_init.sql +59 -0
- package/dist/platform/migrations/0002_users_settings.sql +34 -0
- package/dist/platform/migrations/0003_people_organisations.sql +225 -0
- package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
- package/dist/platform/migrations/0005_views_audit.sql +79 -0
- package/dist/platform/migrations/0006_search.sql +223 -0
- package/dist/platform/migrations/0007_crm_views.sql +141 -0
- package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
- package/dist/platform/migrations/0010_approval_queue.sql +90 -0
- package/dist/platform/migrations/0011_connected_apps.sql +36 -0
- package/dist/platform/migrations/0020_extensions.sql +373 -0
- package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
- package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
- package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
- package/dist/platform/migrations/0061_audit_retention.sql +95 -0
- package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
- package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
- package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
- package/dist/platform/migrations/0065_storage_stats.sql +13 -0
- package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
- package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
- package/dist/platform/migrations/0100_stage_history.sql +54 -0
- package/dist/platform/migrations/0110_integrations.sql +103 -0
- package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
- package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
- package/dist/platform/migrations/0130_automations.sql +113 -0
- package/dist/platform/migrations/0131_notifications.sql +29 -0
- package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
- package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
- package/dist/platform/migrations/0160_releases.sql +41 -0
- package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
- package/dist/platform/migrations/0170_automation_connections.sql +32 -0
- package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
- package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
- package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
- package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
- package/dist/platform/migrations/0210_daily_digest.sql +33 -0
- package/dist/platform/migrations/0220_entitlements.sql +13 -0
- package/dist/platform/migrations/0221_support_grants.sql +33 -0
- package/dist/platform/migrations/0250_judge.sql +11 -0
- package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
- package/dist/platform/migrations/0252_judge_usage.sql +14 -0
- package/dist/platform/migrations/0255_summary_checks.sql +9 -0
- package/dist/platform/migrations/0256_outbound_check.sql +9 -0
- package/dist/platform/migrations/0260_ai_usage.sql +20 -0
- package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
- package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
- package/dist/platform/migrations/0320_duplicates.sql +41 -0
- package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
- package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
- package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
- package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
- package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
- package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
- package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
- package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
- package/dist/platform/migrations/0362_voice_usage.sql +17 -0
- package/dist/platform/migrations/0365_routines.sql +38 -0
- package/dist/platform/migrations/0370_approval_execution.sql +20 -0
- package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
- package/dist/platform/migrations/0380_rec_views.sql +94 -0
- package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
- package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
- package/dist/platform/migrations/0402_erase_requests.sql +34 -0
- package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
- package/dist/platform/migrations/0411_device_sessions.sql +33 -0
- package/dist/platform/migrations/0420_transition_history.sql +100 -0
- package/dist/platform/migrations/0421_orders.sql +134 -0
- package/dist/platform/migrations/0422_order_payments.sql +109 -0
- package/dist/platform/migrations/0440_capacity.sql +100 -0
- package/dist/platform/migrations/0441_capacity_views.sql +40 -0
- package/dist/platform/migrations/0450_order_grants.sql +21 -0
- package/dist/platform/migrations/0451_pack_roles.sql +18 -0
- package/dist/platform/migrations/0460_content.sql +59 -0
- package/dist/platform/migrations/0461_media.sql +52 -0
- package/dist/platform/migrations/0470_publish_versions.sql +36 -0
- package/dist/platform/migrations/0471_permission_grants.sql +18 -0
- package/dist/platform/migrations/0490_staff_invites.sql +40 -0
- package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
- package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
- package/dist/platform/migrations/0500_published_media_field.sql +25 -0
- package/dist/platform/migrations/0501_import_keys.sql +23 -0
- package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
- package/dist/platform/migrations/0516_order_tax.sql +63 -0
- package/dist/platform/migrations/0520_publish_requests.sql +20 -0
- package/dist/platform/migrations/0530_subscriptions.sql +173 -0
- package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
- package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
- package/dist/platform/migrations/0533_allowances.sql +262 -0
- package/dist/platform/migrations/0560_recurring.sql +75 -0
- package/dist/platform/migrations/0580_subscription_grants.sql +21 -0
- package/dist/platform/migrations/0581_once_per_person.sql +34 -0
- package/dist/platform/migrations/0600_tool_actions_ran_at_queue.sql +22 -0
- package/dist/platform/sdk/allowance.ts +522 -0
- package/dist/platform/sdk/automation-check.ts +534 -0
- package/dist/platform/sdk/automation.ts +743 -0
- package/dist/platform/sdk/behaviour.ts +215 -0
- package/dist/platform/sdk/capacity.ts +201 -0
- package/dist/platform/sdk/contract.ts +884 -0
- package/dist/platform/sdk/document.ts +935 -0
- package/dist/platform/sdk/field-types.ts +111 -0
- package/dist/platform/sdk/formula/ast.ts +72 -0
- package/dist/platform/sdk/formula/compile.ts +454 -0
- package/dist/platform/sdk/formula/index.ts +4 -0
- package/dist/platform/sdk/formula/parser.ts +417 -0
- package/dist/platform/sdk/index.ts +36 -0
- package/dist/platform/sdk/manifest.ts +1709 -0
- package/dist/platform/sdk/media.ts +108 -0
- package/dist/platform/sdk/permissions.ts +60 -0
- package/dist/platform/sdk/recurring.ts +321 -0
- package/dist/platform/sdk/renamed.ts +63 -0
- package/dist/platform/sdk/rich-text-fixture.ts +68 -0
- package/dist/platform/sdk/rich-text.ts +221 -0
- package/dist/platform/sdk/runtime.ts +410 -0
- package/dist/platform/sdk/sellable.ts +888 -0
- package/dist/platform/sdk/slug.ts +25 -0
- package/dist/platform/sdk/states.ts +484 -0
- package/dist/platform/sdk/testing.ts +847 -0
- package/dist/platform/sdk/unique.ts +81 -0
- package/dist/products-2H5DR232.js +11 -0
- package/dist/run-PZUCSDDL.js +508 -0
- package/dist/run-RT2HVWMK.js +648 -0
- package/dist/run-Y7T4TVOL.js +309 -0
- package/dist/src-GYS6NBQB.js +44 -0
- package/dist/src-XTOD7EXW.js +348 -0
- package/dist/token-MOJUA2U6.js +70 -0
- package/dist/token-util-TENRN4V7.js +6 -0
- package/dist/visibility-DLGHU4YN.js +33 -0
- package/package.json +33 -4
|
@@ -0,0 +1,2358 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
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
|
+
}
|
|
289
|
+
|
|
290
|
+
// ../release/src/cloudflare.ts
|
|
291
|
+
var CLOUDFLARE_API = "https://api.cloudflare.com/client/v4";
|
|
292
|
+
var CloudflareApiError = class extends Error {
|
|
293
|
+
name = "CloudflareApiError";
|
|
294
|
+
status;
|
|
295
|
+
codes;
|
|
296
|
+
constructor(message, status, codes) {
|
|
297
|
+
super(message);
|
|
298
|
+
this.status = status;
|
|
299
|
+
this.codes = codes;
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
var CONTENT_TYPES = {
|
|
303
|
+
esm: "application/javascript+module",
|
|
304
|
+
text: "text/plain",
|
|
305
|
+
data: "application/octet-stream",
|
|
306
|
+
wasm: "application/wasm"
|
|
307
|
+
};
|
|
308
|
+
var GATEWAY_SETTING_KEYS = [
|
|
309
|
+
"authentication",
|
|
310
|
+
"byok_only",
|
|
311
|
+
"cache_invalidate_on_update",
|
|
312
|
+
"cache_ttl",
|
|
313
|
+
"collect_logs",
|
|
314
|
+
"log_management",
|
|
315
|
+
"log_management_strategy",
|
|
316
|
+
"logpush",
|
|
317
|
+
"rate_limiting_interval",
|
|
318
|
+
"rate_limiting_limit",
|
|
319
|
+
"rate_limiting_technique",
|
|
320
|
+
"retry_backoff",
|
|
321
|
+
"retry_delay",
|
|
322
|
+
"retry_max_attempts",
|
|
323
|
+
"store_id",
|
|
324
|
+
"zdr"
|
|
325
|
+
];
|
|
326
|
+
function gatewaySettingsOf(gateway) {
|
|
327
|
+
const out = {};
|
|
328
|
+
for (const key of GATEWAY_SETTING_KEYS) {
|
|
329
|
+
if (gateway[key] !== void 0 && gateway[key] !== null) out[key] = gateway[key];
|
|
330
|
+
}
|
|
331
|
+
return out;
|
|
332
|
+
}
|
|
333
|
+
var CloudflareClient = class _CloudflareClient {
|
|
334
|
+
apiBase;
|
|
335
|
+
token;
|
|
336
|
+
fetchImpl;
|
|
337
|
+
/** The dispatch namespace script calls go to, if any (ADR 0210). */
|
|
338
|
+
namespace;
|
|
339
|
+
constructor(options) {
|
|
340
|
+
this.token = options.token;
|
|
341
|
+
this.apiBase = options.apiBase ?? CLOUDFLARE_API;
|
|
342
|
+
this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
|
|
343
|
+
this.namespace = options.namespace;
|
|
344
|
+
}
|
|
345
|
+
/** The same client, with script calls addressed to user Workers in a dispatch namespace. */
|
|
346
|
+
forNamespace(namespace) {
|
|
347
|
+
return new _CloudflareClient({
|
|
348
|
+
token: this.token,
|
|
349
|
+
apiBase: this.apiBase,
|
|
350
|
+
fetch: this.fetchImpl,
|
|
351
|
+
namespace
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
scripts(accountId) {
|
|
355
|
+
return this.namespace ? `/accounts/${accountId}/workers/dispatch/namespaces/${encodeURIComponent(this.namespace)}/scripts` : `/accounts/${accountId}/workers/scripts`;
|
|
356
|
+
}
|
|
357
|
+
/** Workers for Platforms has no versions, deployments, schedules or workers.dev for user Workers. */
|
|
358
|
+
accountOnly(what) {
|
|
359
|
+
if (this.namespace) {
|
|
360
|
+
throw new Error(`${what} is not available for user Workers in a dispatch namespace`);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
async request(method, path, body, init = {}) {
|
|
364
|
+
const headers2 = {
|
|
365
|
+
authorization: `Bearer ${init.auth ?? this.token}`,
|
|
366
|
+
...init.headers
|
|
367
|
+
};
|
|
368
|
+
let payload = init.raw;
|
|
369
|
+
if (body !== void 0) {
|
|
370
|
+
headers2["content-type"] = "application/json";
|
|
371
|
+
payload = JSON.stringify(body);
|
|
372
|
+
}
|
|
373
|
+
const response = await this.fetchImpl(`${this.apiBase}${path}`, {
|
|
374
|
+
method,
|
|
375
|
+
headers: headers2,
|
|
376
|
+
body: payload
|
|
377
|
+
});
|
|
378
|
+
let envelope = null;
|
|
379
|
+
try {
|
|
380
|
+
envelope = await response.json();
|
|
381
|
+
} catch {
|
|
382
|
+
envelope = null;
|
|
383
|
+
}
|
|
384
|
+
if (!response.ok || !envelope?.success) {
|
|
385
|
+
const errors = envelope?.errors ?? [];
|
|
386
|
+
const detail = errors.map((e) => `${e.code}: ${e.message}`).join("; ") || response.statusText;
|
|
387
|
+
throw new CloudflareApiError(
|
|
388
|
+
`${method} ${path.replace(/\?.*$/, "")} failed (HTTP ${response.status}): ${detail}`,
|
|
389
|
+
response.status,
|
|
390
|
+
errors.map((e) => e.code)
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
return { result: envelope.result, info: envelope.result_info };
|
|
394
|
+
}
|
|
395
|
+
async all(path) {
|
|
396
|
+
const out = [];
|
|
397
|
+
for (let page = 1; page < 100; page++) {
|
|
398
|
+
const sep = path.includes("?") ? "&" : "?";
|
|
399
|
+
const { result, info } = await this.request(
|
|
400
|
+
"GET",
|
|
401
|
+
`${path}${sep}page=${page}&per_page=50`
|
|
402
|
+
);
|
|
403
|
+
out.push(...result);
|
|
404
|
+
if (!info?.total_pages || page >= info.total_pages || result.length === 0) break;
|
|
405
|
+
}
|
|
406
|
+
return out;
|
|
407
|
+
}
|
|
408
|
+
// ---- Token, accounts, zones ---------------------------------------------------------------
|
|
409
|
+
/** Verifies the token (user-owned, then account-owned). Returns its status. */
|
|
410
|
+
async verifyToken(accountId) {
|
|
411
|
+
try {
|
|
412
|
+
return (await this.request("GET", "/user/tokens/verify")).result;
|
|
413
|
+
} catch (error) {
|
|
414
|
+
if (!accountId) throw error;
|
|
415
|
+
return (await this.request(
|
|
416
|
+
"GET",
|
|
417
|
+
`/accounts/${accountId}/tokens/verify`
|
|
418
|
+
)).result;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
listAccounts() {
|
|
422
|
+
return this.all("/accounts");
|
|
423
|
+
}
|
|
424
|
+
listZones(accountId) {
|
|
425
|
+
return this.all(
|
|
426
|
+
`/zones?account.id=${encodeURIComponent(accountId)}&status=active`
|
|
427
|
+
);
|
|
428
|
+
}
|
|
429
|
+
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
|
+
}
|
|
436
|
+
}
|
|
437
|
+
async createWorkersSubdomain(accountId, subdomain) {
|
|
438
|
+
return (await this.request("PUT", `/accounts/${accountId}/workers/subdomain`, {
|
|
439
|
+
subdomain
|
|
440
|
+
})).result.subdomain;
|
|
441
|
+
}
|
|
442
|
+
// ---- Storage resources ----------------------------------------------------------------------
|
|
443
|
+
async listD1(accountId) {
|
|
444
|
+
return (await this.request(
|
|
445
|
+
"GET",
|
|
446
|
+
`/accounts/${accountId}/d1/database?per_page=10000`
|
|
447
|
+
)).result;
|
|
448
|
+
}
|
|
449
|
+
async createD1(accountId, name) {
|
|
450
|
+
return (await this.request(
|
|
451
|
+
"POST",
|
|
452
|
+
`/accounts/${accountId}/d1/database`,
|
|
453
|
+
{
|
|
454
|
+
name
|
|
455
|
+
}
|
|
456
|
+
)).result;
|
|
457
|
+
}
|
|
458
|
+
async deleteD1(accountId, id) {
|
|
459
|
+
await this.request("DELETE", `/accounts/${accountId}/d1/database/${id}`);
|
|
460
|
+
}
|
|
461
|
+
/** Runs SQL (several `;`-separated statements run as one batch). */
|
|
462
|
+
async queryD1(accountId, databaseId, sql, params = []) {
|
|
463
|
+
return (await this.request(
|
|
464
|
+
"POST",
|
|
465
|
+
`/accounts/${accountId}/d1/database/${databaseId}/query`,
|
|
466
|
+
{ sql, params }
|
|
467
|
+
)).result;
|
|
468
|
+
}
|
|
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)}` : "";
|
|
472
|
+
return (await this.request(
|
|
473
|
+
"GET",
|
|
474
|
+
`/accounts/${accountId}/d1/database/${databaseId}/time_travel/bookmark${query}`
|
|
475
|
+
)).result.bookmark;
|
|
476
|
+
}
|
|
477
|
+
/** Restores a database to a bookmark, in place. Returns the bookmark that undoes it. */
|
|
478
|
+
async d1Restore(accountId, databaseId, bookmark) {
|
|
479
|
+
return (await this.request(
|
|
480
|
+
"POST",
|
|
481
|
+
`/accounts/${accountId}/d1/database/${databaseId}/time_travel/restore?bookmark=${encodeURIComponent(bookmark)}`
|
|
482
|
+
)).result;
|
|
483
|
+
}
|
|
484
|
+
async listR2(accountId) {
|
|
485
|
+
return (await this.request(
|
|
486
|
+
"GET",
|
|
487
|
+
`/accounts/${accountId}/r2/buckets?per_page=1000`
|
|
488
|
+
)).result.buckets;
|
|
489
|
+
}
|
|
490
|
+
async createR2(accountId, name) {
|
|
491
|
+
await this.request("POST", `/accounts/${accountId}/r2/buckets`, { name });
|
|
492
|
+
}
|
|
493
|
+
async deleteR2(accountId, name) {
|
|
494
|
+
await this.request("DELETE", `/accounts/${accountId}/r2/buckets/${name}`);
|
|
495
|
+
}
|
|
496
|
+
listKv(accountId) {
|
|
497
|
+
return this.all(`/accounts/${accountId}/storage/kv/namespaces`);
|
|
498
|
+
}
|
|
499
|
+
async createKv(accountId, title) {
|
|
500
|
+
return (await this.request(
|
|
501
|
+
"POST",
|
|
502
|
+
`/accounts/${accountId}/storage/kv/namespaces`,
|
|
503
|
+
{ title }
|
|
504
|
+
)).result;
|
|
505
|
+
}
|
|
506
|
+
async deleteKv(accountId, id) {
|
|
507
|
+
await this.request("DELETE", `/accounts/${accountId}/storage/kv/namespaces/${id}`);
|
|
508
|
+
}
|
|
509
|
+
listQueues(accountId) {
|
|
510
|
+
return this.all(`/accounts/${accountId}/queues`);
|
|
511
|
+
}
|
|
512
|
+
async createQueue(accountId, name) {
|
|
513
|
+
return (await this.request(
|
|
514
|
+
"POST",
|
|
515
|
+
`/accounts/${accountId}/queues`,
|
|
516
|
+
{ queue_name: name }
|
|
517
|
+
)).result;
|
|
518
|
+
}
|
|
519
|
+
async deleteQueue(accountId, id) {
|
|
520
|
+
await this.request("DELETE", `/accounts/${accountId}/queues/${id}`);
|
|
521
|
+
}
|
|
522
|
+
async putQueueConsumer(accountId, queueId, scriptName, settings, existingConsumerId, deadLetterQueue) {
|
|
523
|
+
const body = {
|
|
524
|
+
type: "worker",
|
|
525
|
+
script_name: scriptName,
|
|
526
|
+
settings,
|
|
527
|
+
...deadLetterQueue ? { dead_letter_queue: deadLetterQueue } : {}
|
|
528
|
+
};
|
|
529
|
+
if (existingConsumerId) {
|
|
530
|
+
await this.request(
|
|
531
|
+
"PUT",
|
|
532
|
+
`/accounts/${accountId}/queues/${queueId}/consumers/${existingConsumerId}`,
|
|
533
|
+
body
|
|
534
|
+
);
|
|
535
|
+
} else {
|
|
536
|
+
await this.request("POST", `/accounts/${accountId}/queues/${queueId}/consumers`, body);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
async listVectorize(accountId) {
|
|
540
|
+
return (await this.request("GET", `/accounts/${accountId}/vectorize/v2/indexes`)).result;
|
|
541
|
+
}
|
|
542
|
+
async createVectorize(accountId, name, config) {
|
|
543
|
+
await this.request("POST", `/accounts/${accountId}/vectorize/v2/indexes`, { name, config });
|
|
544
|
+
}
|
|
545
|
+
async listVectorizeMetadataIndexes(accountId, index) {
|
|
546
|
+
return (await this.request(
|
|
547
|
+
"GET",
|
|
548
|
+
`/accounts/${accountId}/vectorize/v2/indexes/${index}/metadata_index/list`
|
|
549
|
+
)).result.metadataIndexes ?? [];
|
|
550
|
+
}
|
|
551
|
+
/** Metadata indexes make a property filterable; create them before inserting vectors. */
|
|
552
|
+
async createVectorizeMetadataIndex(accountId, index, propertyName, indexType) {
|
|
553
|
+
await this.request(
|
|
554
|
+
"POST",
|
|
555
|
+
`/accounts/${accountId}/vectorize/v2/indexes/${index}/metadata_index/create`,
|
|
556
|
+
{ propertyName, indexType }
|
|
557
|
+
);
|
|
558
|
+
}
|
|
559
|
+
async deleteVectorize(accountId, name) {
|
|
560
|
+
await this.request("DELETE", `/accounts/${accountId}/vectorize/v2/indexes/${name}`);
|
|
561
|
+
}
|
|
562
|
+
// ---- Workers --------------------------------------------------------------------------------
|
|
563
|
+
async listScripts(accountId) {
|
|
564
|
+
const { result } = await this.request(
|
|
565
|
+
"GET",
|
|
566
|
+
this.scripts(accountId)
|
|
567
|
+
);
|
|
568
|
+
return result.map((entry) => entry.script ?? entry);
|
|
569
|
+
}
|
|
570
|
+
form(metadata, modules) {
|
|
571
|
+
const form = new FormData();
|
|
572
|
+
form.set(
|
|
573
|
+
"metadata",
|
|
574
|
+
new Blob([JSON.stringify(metadata)], { type: "application/json" }),
|
|
575
|
+
"metadata.json"
|
|
576
|
+
);
|
|
577
|
+
for (const module of modules) {
|
|
578
|
+
form.set(
|
|
579
|
+
module.name,
|
|
580
|
+
new Blob([module.bytes], { type: CONTENT_TYPES[module.type] }),
|
|
581
|
+
module.name
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
return form;
|
|
585
|
+
}
|
|
586
|
+
/** Uploads and deploys a script (needed for a first deploy and for Durable Object migrations). */
|
|
587
|
+
async putScript(accountId, name, metadata, modules) {
|
|
588
|
+
return (await this.request(
|
|
589
|
+
"PUT",
|
|
590
|
+
`${this.scripts(accountId)}/${name}`,
|
|
591
|
+
void 0,
|
|
592
|
+
{ raw: this.form(metadata, modules) }
|
|
593
|
+
)).result;
|
|
594
|
+
}
|
|
595
|
+
/** Uploads a version without moving traffic to it. */
|
|
596
|
+
async uploadVersion(accountId, name, metadata, modules) {
|
|
597
|
+
this.accountOnly("Worker versions");
|
|
598
|
+
return (await this.request(
|
|
599
|
+
"POST",
|
|
600
|
+
`${this.scripts(accountId)}/${name}/versions`,
|
|
601
|
+
void 0,
|
|
602
|
+
{ raw: this.form(metadata, modules) }
|
|
603
|
+
)).result.id;
|
|
604
|
+
}
|
|
605
|
+
/** Sends 100% of traffic to a version. */
|
|
606
|
+
async deployVersion(accountId, name, versionId, message) {
|
|
607
|
+
this.accountOnly("Worker deployments");
|
|
608
|
+
await this.request("POST", `${this.scripts(accountId)}/${name}/deployments`, {
|
|
609
|
+
strategy: "percentage",
|
|
610
|
+
versions: [{ version_id: versionId, percentage: 100 }],
|
|
611
|
+
...message ? { annotations: { "workers/message": message } } : {}
|
|
612
|
+
});
|
|
613
|
+
}
|
|
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
|
+
async deleteScript(accountId, name) {
|
|
622
|
+
await this.request("DELETE", `${this.scripts(accountId)}/${name}?force=true`);
|
|
623
|
+
}
|
|
624
|
+
// ---- Workers for Platforms (ADR 0210) -------------------------------------------------------
|
|
625
|
+
async getDispatchNamespace(accountId, name) {
|
|
626
|
+
try {
|
|
627
|
+
return (await this.request(
|
|
628
|
+
"GET",
|
|
629
|
+
`/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
|
+
}
|
|
635
|
+
}
|
|
636
|
+
async createDispatchNamespace(accountId, name) {
|
|
637
|
+
await this.request("POST", `/accounts/${accountId}/workers/dispatch/namespaces`, { name });
|
|
638
|
+
}
|
|
639
|
+
/** Deletes every user Worker in this client's namespace carrying `tag` (one tenant's Workers). */
|
|
640
|
+
async deleteScriptsByTag(accountId, tag) {
|
|
641
|
+
if (!this.namespace) throw new Error("deleting scripts by tag needs a dispatch namespace");
|
|
642
|
+
await this.request(
|
|
643
|
+
"DELETE",
|
|
644
|
+
`${this.scripts(accountId)}?tags=${encodeURIComponent(`${tag}:yes`)}`
|
|
645
|
+
);
|
|
646
|
+
}
|
|
647
|
+
// ---- Cloudflare for SaaS custom hostnames (enterprise, ADR 0210) ---------------------------
|
|
648
|
+
async customHostname(zoneId, hostname) {
|
|
649
|
+
const { result } = await this.request(
|
|
650
|
+
"GET",
|
|
651
|
+
`/zones/${zoneId}/custom_hostnames?hostname=${encodeURIComponent(hostname)}`
|
|
652
|
+
);
|
|
653
|
+
const found = result.find((h) => h.hostname === hostname);
|
|
654
|
+
return found ? { id: found.id, status: found.status } : null;
|
|
655
|
+
}
|
|
656
|
+
async createCustomHostname(zoneId, hostname) {
|
|
657
|
+
return (await this.request(
|
|
658
|
+
"POST",
|
|
659
|
+
`/zones/${zoneId}/custom_hostnames`,
|
|
660
|
+
{ hostname, ssl: { method: "http", type: "dv" } }
|
|
661
|
+
)).result;
|
|
662
|
+
}
|
|
663
|
+
// ---- AI Gateway logs (metering, ADR 0213) --------------------------------------------------
|
|
664
|
+
/**
|
|
665
|
+
* One page (≤ 50) of a gateway's logs created in [from, to), oldest first, with the fields
|
|
666
|
+
* metering needs. `cost` is AI Gateway's estimate in US dollars. `metadataValue` keeps only
|
|
667
|
+
* logs with that value in their `cf-aig-metadata` (the shared platform gateway's tenant tag,
|
|
668
|
+
* ADR 0213 amendment); `metadata` is the JSON string AI Gateway stores.
|
|
669
|
+
*/
|
|
670
|
+
async gatewayLogs(accountId, gatewayId, window) {
|
|
671
|
+
const filters = JSON.stringify([
|
|
672
|
+
{ key: "created_at", operator: "gt", value: [window.from] },
|
|
673
|
+
{ key: "created_at", operator: "lt", value: [window.to] },
|
|
674
|
+
...window.metadataValue ? [{ key: "metadata.value", operator: "eq", value: [window.metadataValue] }] : []
|
|
675
|
+
]);
|
|
676
|
+
const { result, info } = await this.request(
|
|
677
|
+
"GET",
|
|
678
|
+
`/accounts/${accountId}/ai-gateway/gateways/${gatewayId}/logs?per_page=50&page=${window.page}&order_by=created_at&order_by_direction=asc&filters=${encodeURIComponent(filters)}`
|
|
679
|
+
);
|
|
680
|
+
return { logs: result, totalPages: info?.total_pages ?? 1 };
|
|
681
|
+
}
|
|
682
|
+
async listSecrets(accountId, name) {
|
|
683
|
+
return (await this.request("GET", `${this.scripts(accountId)}/${name}/secrets`)).result.map((s) => s.name);
|
|
684
|
+
}
|
|
685
|
+
async putSecret(accountId, name, secret, value) {
|
|
686
|
+
await this.request("PUT", `${this.scripts(accountId)}/${name}/secrets`, {
|
|
687
|
+
name: secret,
|
|
688
|
+
text: value,
|
|
689
|
+
type: "secret_text"
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
/** 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
|
+
}
|
|
703
|
+
}
|
|
704
|
+
async putSchedules(accountId, name, crons) {
|
|
705
|
+
this.accountOnly("Cron Triggers");
|
|
706
|
+
await this.request(
|
|
707
|
+
"PUT",
|
|
708
|
+
`${this.scripts(accountId)}/${name}/schedules`,
|
|
709
|
+
crons.map((cron) => ({ cron }))
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
async setWorkersDev(accountId, name, enabled) {
|
|
713
|
+
this.accountOnly("workers.dev");
|
|
714
|
+
await this.request("POST", `${this.scripts(accountId)}/${name}/subdomain`, {
|
|
715
|
+
enabled,
|
|
716
|
+
previews_enabled: false
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
async putDomain(accountId, hostname, service, zoneId) {
|
|
720
|
+
await this.request("PUT", `/accounts/${accountId}/workers/domains`, {
|
|
721
|
+
hostname,
|
|
722
|
+
service,
|
|
723
|
+
zone_id: zoneId,
|
|
724
|
+
environment: "production"
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
// ---- AI Gateway (ADR 0180) -----------------------------------------------------------------
|
|
728
|
+
/** A gateway by id, or null when there is none. Needs AI Gateway Read or Edit. */
|
|
729
|
+
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
|
+
}
|
|
736
|
+
}
|
|
737
|
+
async createAiGateway(accountId, settings) {
|
|
738
|
+
return (await this.request("POST", `/accounts/${accountId}/ai-gateway/gateways`, settings)).result;
|
|
739
|
+
}
|
|
740
|
+
/** Replaces a gateway's settings (send them all: omitted ones fall back to defaults). */
|
|
741
|
+
async updateAiGateway(accountId, id, settings) {
|
|
742
|
+
return (await this.request(
|
|
743
|
+
"PUT",
|
|
744
|
+
`/accounts/${accountId}/ai-gateway/gateways/${id}`,
|
|
745
|
+
settings
|
|
746
|
+
)).result;
|
|
747
|
+
}
|
|
748
|
+
async deleteAiGateway(accountId, id) {
|
|
749
|
+
await this.request("DELETE", `/accounts/${accountId}/ai-gateway/gateways/${id}`);
|
|
750
|
+
}
|
|
751
|
+
/** The account's custom providers (account-wide, shared by every gateway). */
|
|
752
|
+
listCustomProviders(accountId) {
|
|
753
|
+
return this.all(`/accounts/${accountId}/ai-gateway/custom-providers`);
|
|
754
|
+
}
|
|
755
|
+
async createCustomProvider(accountId, provider) {
|
|
756
|
+
return (await this.request(
|
|
757
|
+
"POST",
|
|
758
|
+
`/accounts/${accountId}/ai-gateway/custom-providers`,
|
|
759
|
+
provider
|
|
760
|
+
)).result;
|
|
761
|
+
}
|
|
762
|
+
async updateCustomProvider(accountId, id, changes) {
|
|
763
|
+
return (await this.request(
|
|
764
|
+
"PATCH",
|
|
765
|
+
`/accounts/${accountId}/ai-gateway/custom-providers/${id}`,
|
|
766
|
+
changes
|
|
767
|
+
)).result;
|
|
768
|
+
}
|
|
769
|
+
/** A gateway's stored provider keys (BYOK); only previews of the keys come back. */
|
|
770
|
+
async listProviderConfigs(accountId, gatewayId) {
|
|
771
|
+
return (await this.request(
|
|
772
|
+
"GET",
|
|
773
|
+
`/accounts/${accountId}/ai-gateway/gateways/${gatewayId}/provider_configs`
|
|
774
|
+
)).result;
|
|
775
|
+
}
|
|
776
|
+
async deleteProviderConfig(accountId, gatewayId, id) {
|
|
777
|
+
await this.request(
|
|
778
|
+
"DELETE",
|
|
779
|
+
`/accounts/${accountId}/ai-gateway/gateways/${gatewayId}/provider_configs/${id}`
|
|
780
|
+
);
|
|
781
|
+
}
|
|
782
|
+
listSecretsStores(accountId) {
|
|
783
|
+
return this.all(`/accounts/${accountId}/secrets_store/stores`);
|
|
784
|
+
}
|
|
785
|
+
async createSecretsStore(accountId, name) {
|
|
786
|
+
return (await this.request(
|
|
787
|
+
"POST",
|
|
788
|
+
`/accounts/${accountId}/secrets_store/stores`,
|
|
789
|
+
{ name }
|
|
790
|
+
)).result;
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* Stores a provider key in a gateway as BYOK (the `default` alias), replacing any key already
|
|
794
|
+
* stored for that provider. `provider` is the gateway's provider slug: a built-in one
|
|
795
|
+
* (`openai`, `google-ai-studio`, …) or `custom-<slug>` for a custom provider. The key goes in
|
|
796
|
+
* the request body only: it is never logged, returned or put in an error message.
|
|
797
|
+
*
|
|
798
|
+
* The key lands in the Secrets Store the gateway uses; a gateway without one is pointed at the
|
|
799
|
+
* account's store (created if the account has none). Needs AI Gateway Edit and Secrets Store
|
|
800
|
+
* Write. Used by `create-composable-os --provider-key` and meant for Settings → AI.
|
|
801
|
+
*/
|
|
802
|
+
async setGatewayProviderKey(accountId, gatewayId, provider, key) {
|
|
803
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(provider)) throw new Error(`bad provider slug ${provider}`);
|
|
804
|
+
if (!key.trim()) throw new Error("the provider key is empty");
|
|
805
|
+
const gateway = await this.getAiGateway(accountId, gatewayId);
|
|
806
|
+
if (!gateway) throw new Error(`AI Gateway ${gatewayId} does not exist`);
|
|
807
|
+
if (!gateway.store_id) {
|
|
808
|
+
const store = (await this.listSecretsStores(accountId))[0] ?? await this.createSecretsStore(accountId, "default_secrets_store");
|
|
809
|
+
await this.updateAiGateway(accountId, gatewayId, {
|
|
810
|
+
...gatewaySettingsOf(gateway),
|
|
811
|
+
store_id: store.id
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
const alias = "default";
|
|
815
|
+
for (const config of await this.listProviderConfigs(accountId, gatewayId)) {
|
|
816
|
+
if (config.provider_slug === provider && config.alias === alias) {
|
|
817
|
+
await this.deleteProviderConfig(accountId, gatewayId, config.id);
|
|
818
|
+
}
|
|
819
|
+
}
|
|
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 };
|
|
826
|
+
}
|
|
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);
|
|
834
|
+
}
|
|
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
|
+
});
|
|
844
|
+
}
|
|
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
|
+
}
|
|
861
|
+
);
|
|
862
|
+
return { id: result.id, value: result.value };
|
|
863
|
+
}
|
|
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");
|
|
882
|
+
}
|
|
883
|
+
async deleteAccountToken(accountId, id) {
|
|
884
|
+
await this.request("DELETE", `/accounts/${accountId}/tokens/${id}`);
|
|
885
|
+
}
|
|
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;
|
|
894
|
+
}
|
|
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;
|
|
903
|
+
}
|
|
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);
|
|
909
|
+
}
|
|
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;
|
|
917
|
+
}
|
|
918
|
+
};
|
|
919
|
+
|
|
920
|
+
// ../release/src/deploy.ts
|
|
921
|
+
var MIGRATIONS_TABLE = "core_migrations";
|
|
922
|
+
var CREATE_MIGRATIONS = `CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)`;
|
|
923
|
+
function d1ApiMigrations(api, accountId, databaseId) {
|
|
924
|
+
return {
|
|
925
|
+
async applied() {
|
|
926
|
+
await api.queryD1(accountId, databaseId, CREATE_MIGRATIONS);
|
|
927
|
+
const [first] = await api.queryD1(
|
|
928
|
+
accountId,
|
|
929
|
+
databaseId,
|
|
930
|
+
`SELECT name FROM ${MIGRATIONS_TABLE} ORDER BY id`
|
|
931
|
+
);
|
|
932
|
+
return (first?.results ?? []).map((row) => row.name);
|
|
933
|
+
},
|
|
934
|
+
async apply(name, sql) {
|
|
935
|
+
if (!/^[\w.-]+$/.test(name)) throw new Error(`unsafe migration name ${name}`);
|
|
936
|
+
await api.queryD1(
|
|
937
|
+
accountId,
|
|
938
|
+
databaseId,
|
|
939
|
+
`${sql.trimEnd()}
|
|
940
|
+
INSERT INTO ${MIGRATIONS_TABLE} (name) VALUES ('${name}');`
|
|
941
|
+
);
|
|
942
|
+
}
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
async function applyBundleMigrations(bundle, runner, log = () => {
|
|
946
|
+
}) {
|
|
947
|
+
const applied = new Set(await runner.applied());
|
|
948
|
+
const pending = bundle.manifest.migrations.filter((m) => !applied.has(m.name));
|
|
949
|
+
for (const migration of pending) {
|
|
950
|
+
log(` migration ${migration.name}`);
|
|
951
|
+
await runner.apply(migration.name, bundle.migration(migration.name));
|
|
952
|
+
}
|
|
953
|
+
return pending.map((m) => m.name);
|
|
954
|
+
}
|
|
955
|
+
async function readDeploymentState(api, accountId, databaseId) {
|
|
956
|
+
try {
|
|
957
|
+
const [first] = await api.queryD1(
|
|
958
|
+
accountId,
|
|
959
|
+
databaseId,
|
|
960
|
+
"SELECT value FROM core_install WHERE key = 'deployment'"
|
|
961
|
+
);
|
|
962
|
+
const row = first?.results[0];
|
|
963
|
+
return row ? JSON.parse(row.value) : null;
|
|
964
|
+
} catch (error) {
|
|
965
|
+
if (error instanceof CloudflareApiError && /no such table/i.test(error.message)) return null;
|
|
966
|
+
throw error;
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
async function writeDeploymentState(api, databaseId, state) {
|
|
970
|
+
await api.queryD1(
|
|
971
|
+
state.accountId,
|
|
972
|
+
databaseId,
|
|
973
|
+
"INSERT INTO core_install (key, value, updated_at) VALUES ('deployment', ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
|
|
974
|
+
[JSON.stringify(state), (/* @__PURE__ */ new Date()).toISOString()]
|
|
975
|
+
);
|
|
976
|
+
}
|
|
977
|
+
function featureOn(state, feature) {
|
|
978
|
+
return feature === "ai" ? state.ai !== false : true;
|
|
979
|
+
}
|
|
980
|
+
function neededResources(manifest, gatekeepers2, features = {}) {
|
|
981
|
+
const installed = new Set(gatekeepers2);
|
|
982
|
+
return manifest.resources.filter(
|
|
983
|
+
(r) => (!r.optional || r.usedBy.some((worker) => installed.has(worker))) && (!r.feature || featureOn(features, r.feature))
|
|
984
|
+
);
|
|
985
|
+
}
|
|
986
|
+
async function provisionResources(api, accountId, manifestResources, log = () => {
|
|
987
|
+
}, names = {}) {
|
|
988
|
+
const out = {};
|
|
989
|
+
const key = (r) => (r.placeholder ?? "").replace(/^\$/, "");
|
|
990
|
+
for (const entry of manifestResources) {
|
|
991
|
+
if (entry.implicit) continue;
|
|
992
|
+
const resource = { ...entry, name: names[entry.name] ?? entry.name };
|
|
993
|
+
switch (resource.type) {
|
|
994
|
+
case "d1": {
|
|
995
|
+
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"}`);
|
|
998
|
+
out[key(resource)] = db.uuid;
|
|
999
|
+
break;
|
|
1000
|
+
}
|
|
1001
|
+
case "r2": {
|
|
1002
|
+
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"}`);
|
|
1005
|
+
out[key(resource)] = resource.name;
|
|
1006
|
+
break;
|
|
1007
|
+
}
|
|
1008
|
+
case "kv": {
|
|
1009
|
+
const existing = (await api.listKv(accountId)).find((n) => n.title === resource.name);
|
|
1010
|
+
const ns = existing ?? await api.createKv(accountId, resource.name);
|
|
1011
|
+
log(` KV ${resource.name}: ${existing ? "exists" : "created"}`);
|
|
1012
|
+
out[key(resource)] = ns.id;
|
|
1013
|
+
break;
|
|
1014
|
+
}
|
|
1015
|
+
case "queue": {
|
|
1016
|
+
const existing = (await api.listQueues(accountId)).find(
|
|
1017
|
+
(q) => q.queue_name === resource.name
|
|
1018
|
+
);
|
|
1019
|
+
if (!existing) await api.createQueue(accountId, resource.name);
|
|
1020
|
+
log(` Queue ${resource.name}: ${existing ? "exists" : "created"}`);
|
|
1021
|
+
out[key(resource)] = resource.name;
|
|
1022
|
+
break;
|
|
1023
|
+
}
|
|
1024
|
+
case "vectorize": {
|
|
1025
|
+
const exists = (await api.listVectorize(accountId)).some((i) => i.name === resource.name);
|
|
1026
|
+
const { metadataIndexes, ...indexConfig } = resource.config ?? {};
|
|
1027
|
+
if (!exists) await api.createVectorize(accountId, resource.name, indexConfig);
|
|
1028
|
+
log(` Vectorize ${resource.name}: ${exists ? "exists" : "created"}`);
|
|
1029
|
+
if (metadataIndexes?.length) {
|
|
1030
|
+
const have = new Set(
|
|
1031
|
+
(await api.listVectorizeMetadataIndexes(accountId, resource.name)).map(
|
|
1032
|
+
(m) => m.propertyName
|
|
1033
|
+
)
|
|
1034
|
+
);
|
|
1035
|
+
for (const m of metadataIndexes) {
|
|
1036
|
+
if (have.has(m.propertyName)) continue;
|
|
1037
|
+
await api.createVectorizeMetadataIndex(
|
|
1038
|
+
accountId,
|
|
1039
|
+
resource.name,
|
|
1040
|
+
m.propertyName,
|
|
1041
|
+
m.indexType
|
|
1042
|
+
);
|
|
1043
|
+
log(` Vectorize ${resource.name}: metadata index ${m.propertyName}`);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
out[key(resource)] = resource.name;
|
|
1047
|
+
break;
|
|
1048
|
+
}
|
|
1049
|
+
default:
|
|
1050
|
+
break;
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
return out;
|
|
1054
|
+
}
|
|
1055
|
+
function databaseIdOf(manifest, resources) {
|
|
1056
|
+
const d1 = manifest.resources.find((r) => r.type === "d1");
|
|
1057
|
+
const key = d1?.placeholder?.slice(1);
|
|
1058
|
+
const id = key ? resources[key] : void 0;
|
|
1059
|
+
if (!id) throw new Error("the release has no D1 database, or it was not provisioned");
|
|
1060
|
+
return id;
|
|
1061
|
+
}
|
|
1062
|
+
function durableObjectMigration(history, currentTag) {
|
|
1063
|
+
if (history.length === 0) return void 0;
|
|
1064
|
+
const index = currentTag === void 0 ? -1 : history.findIndex((m) => m.tag === currentTag);
|
|
1065
|
+
if (currentTag !== void 0 && index === -1) {
|
|
1066
|
+
throw new Error(
|
|
1067
|
+
`deployed Durable Object migration tag ${currentTag} is not in this release's history`
|
|
1068
|
+
);
|
|
1069
|
+
}
|
|
1070
|
+
const steps = history.slice(index + 1);
|
|
1071
|
+
if (steps.length === 0) return void 0;
|
|
1072
|
+
const last = steps[steps.length - 1];
|
|
1073
|
+
return {
|
|
1074
|
+
...currentTag !== void 0 ? { old_tag: currentTag } : {},
|
|
1075
|
+
new_tag: last.tag,
|
|
1076
|
+
steps: steps.map(({ tag: _tag, ...step }) => step)
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
function workerName(state, name) {
|
|
1080
|
+
return state.workerNames[name] ?? name;
|
|
1081
|
+
}
|
|
1082
|
+
function placeholderValues(state, secretsFor) {
|
|
1083
|
+
return {
|
|
1084
|
+
accountId: state.accountId,
|
|
1085
|
+
hostname: state.hostname,
|
|
1086
|
+
workerName: (name) => workerName(state, name),
|
|
1087
|
+
resource: (kind, name) => {
|
|
1088
|
+
const value = state.resources[`${kind}(${name})`];
|
|
1089
|
+
if (value === void 0) throw new Error(`resource ${kind}(${name}) was not provisioned`);
|
|
1090
|
+
return value;
|
|
1091
|
+
},
|
|
1092
|
+
secret: (name) => secretsFor[name]
|
|
1093
|
+
};
|
|
1094
|
+
}
|
|
1095
|
+
function workerBindings(worker, manifest, state, secrets) {
|
|
1096
|
+
const values = placeholderValues(state, secrets);
|
|
1097
|
+
const overrides = state.vars[worker.name] ?? {};
|
|
1098
|
+
const wanted = worker.bindings.filter((b) => !b.feature || featureOn(state, b.feature)).map(({ feature: _feature, ...binding }) => binding);
|
|
1099
|
+
const deployedNames = state.resourceNames ?? {};
|
|
1100
|
+
const bindings = renderBindings(wanted, values).map((binding) => {
|
|
1101
|
+
if (binding.type === "plain_text" && overrides[binding.name] !== void 0) {
|
|
1102
|
+
return { ...binding, text: overrides[binding.name] };
|
|
1103
|
+
}
|
|
1104
|
+
const email = state.sendEmail?.[worker.name]?.[binding.name];
|
|
1105
|
+
if (binding.type === "send_email" && email) {
|
|
1106
|
+
return { ...binding, ...email };
|
|
1107
|
+
}
|
|
1108
|
+
const workflow = binding.workflow_name;
|
|
1109
|
+
if (binding.type === "workflow" && workflow && deployedNames[workflow]) {
|
|
1110
|
+
return { ...binding, workflow_name: deployedNames[workflow] };
|
|
1111
|
+
}
|
|
1112
|
+
return binding;
|
|
1113
|
+
});
|
|
1114
|
+
for (const [name, text] of Object.entries(overrides)) {
|
|
1115
|
+
if ((worker.secrets ?? []).some((s) => s.name === name)) continue;
|
|
1116
|
+
if (!bindings.some((b) => b.name === name)) bindings.push({ type: "plain_text", name, text });
|
|
1117
|
+
}
|
|
1118
|
+
if (worker.gatekeeperBindings) {
|
|
1119
|
+
const { prefix, entrypoint } = worker.gatekeeperBindings;
|
|
1120
|
+
for (const gk of manifest.workers) {
|
|
1121
|
+
if (gk.role !== "gatekeeper" || !gk.shortName || !state.gatekeepers.includes(gk.name))
|
|
1122
|
+
continue;
|
|
1123
|
+
const name = gatekeeperBindingName(prefix, gk.shortName);
|
|
1124
|
+
if (bindings.some((b) => b.name === name)) continue;
|
|
1125
|
+
bindings.push({ type: "service", name, service: workerName(state, gk.name), entrypoint });
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
for (const [name, text] of Object.entries(secrets)) {
|
|
1129
|
+
if (!bindings.some((b) => b.name === name)) bindings.push({ type: "secret_text", name, text });
|
|
1130
|
+
}
|
|
1131
|
+
return bindings;
|
|
1132
|
+
}
|
|
1133
|
+
async function uploadAssets(input, worker, deployedName) {
|
|
1134
|
+
if (!worker.assets) return void 0;
|
|
1135
|
+
const { bundle, state } = input;
|
|
1136
|
+
const api = scriptsApi(input.api, state);
|
|
1137
|
+
const files = worker.assets.files;
|
|
1138
|
+
const session = await api.assetsUploadSession(state.accountId, deployedName, files);
|
|
1139
|
+
const byHash = new Map(Object.entries(files).map(([path, f]) => [f.hash, path]));
|
|
1140
|
+
let completion = session.buckets?.length ? void 0 : session.jwt;
|
|
1141
|
+
for (const bucket of session.buckets ?? []) {
|
|
1142
|
+
const parts = bucket.map((hash) => ({
|
|
1143
|
+
hash,
|
|
1144
|
+
base64: toBase64(bundle.asset(hash)),
|
|
1145
|
+
contentType: contentTypeOf(byHash.get(hash) ?? "")
|
|
1146
|
+
}));
|
|
1147
|
+
const token = await api.uploadAssets(state.accountId, session.jwt, parts);
|
|
1148
|
+
if (token) completion = token;
|
|
1149
|
+
}
|
|
1150
|
+
if (!completion) throw new Error(`${deployedName}: assets upload did not complete`);
|
|
1151
|
+
return completion;
|
|
1152
|
+
}
|
|
1153
|
+
function contentTypeOf(path) {
|
|
1154
|
+
const ext = path.slice(path.lastIndexOf(".") + 1).toLowerCase();
|
|
1155
|
+
const types = {
|
|
1156
|
+
html: "text/html",
|
|
1157
|
+
js: "text/javascript",
|
|
1158
|
+
mjs: "text/javascript",
|
|
1159
|
+
css: "text/css",
|
|
1160
|
+
json: "application/json",
|
|
1161
|
+
svg: "image/svg+xml",
|
|
1162
|
+
png: "image/png",
|
|
1163
|
+
jpg: "image/jpeg",
|
|
1164
|
+
jpeg: "image/jpeg",
|
|
1165
|
+
webp: "image/webp",
|
|
1166
|
+
ico: "image/x-icon",
|
|
1167
|
+
woff: "font/woff",
|
|
1168
|
+
woff2: "font/woff2",
|
|
1169
|
+
txt: "text/plain",
|
|
1170
|
+
webmanifest: "application/manifest+json"
|
|
1171
|
+
};
|
|
1172
|
+
return types[ext] ?? "application/octet-stream";
|
|
1173
|
+
}
|
|
1174
|
+
function selectedWorkers(manifest, state) {
|
|
1175
|
+
return deployOrder(manifest.workers).filter(
|
|
1176
|
+
(w) => !w.optional || state.gatekeepers.includes(w.name)
|
|
1177
|
+
);
|
|
1178
|
+
}
|
|
1179
|
+
function scriptsApi(api, state) {
|
|
1180
|
+
return state.dispatchNamespace && api.namespace !== state.dispatchNamespace ? api.forNamespace(state.dispatchNamespace) : api;
|
|
1181
|
+
}
|
|
1182
|
+
async function deployWorkers(input) {
|
|
1183
|
+
const { api, bundle, state } = input;
|
|
1184
|
+
const log = input.log ?? (() => {
|
|
1185
|
+
});
|
|
1186
|
+
const manifest = bundle.manifest;
|
|
1187
|
+
const scriptApi = scriptsApi(api, state);
|
|
1188
|
+
const namespaced = Boolean(state.dispatchNamespace);
|
|
1189
|
+
const scripts = new Map((await scriptApi.listScripts(state.accountId)).map((s) => [s.id, s]));
|
|
1190
|
+
const workers = selectedWorkers(manifest, state);
|
|
1191
|
+
const staged = [];
|
|
1192
|
+
for (const worker of workers) {
|
|
1193
|
+
const deployedName = workerName(state, worker.name);
|
|
1194
|
+
const existing = scripts.get(deployedName);
|
|
1195
|
+
const migration = durableObjectMigration(
|
|
1196
|
+
worker.durableObjectMigrations,
|
|
1197
|
+
existing ? existing.migration_tag : void 0
|
|
1198
|
+
);
|
|
1199
|
+
const assetsJwt = await uploadAssets(input, worker, deployedName);
|
|
1200
|
+
const metadata = {
|
|
1201
|
+
main_module: worker.mainModule,
|
|
1202
|
+
compatibility_date: worker.compatibilityDate,
|
|
1203
|
+
compatibility_flags: worker.compatibilityFlags,
|
|
1204
|
+
bindings: workerBindings(worker, manifest, state, input.secrets[worker.name] ?? {}),
|
|
1205
|
+
// Secrets not set in this deploy keep their stored values.
|
|
1206
|
+
keep_bindings: ["secret_text", "secret_key"],
|
|
1207
|
+
...worker.observability ? { observability: worker.observability } : {},
|
|
1208
|
+
...assetsJwt ? { assets: { jwt: assetsJwt, config: worker.assets?.config ?? {} } } : {},
|
|
1209
|
+
annotations: {
|
|
1210
|
+
"workers/message": `${manifest.productLabel} ${manifest.version}`,
|
|
1211
|
+
"workers/tag": manifest.version
|
|
1212
|
+
},
|
|
1213
|
+
...namespaced && state.tags?.length ? { tags: state.tags } : {}
|
|
1214
|
+
};
|
|
1215
|
+
const modules = worker.modules.map((m) => ({
|
|
1216
|
+
name: m.name,
|
|
1217
|
+
type: m.type,
|
|
1218
|
+
bytes: bundle.module(m.sha256)
|
|
1219
|
+
}));
|
|
1220
|
+
if (existing && !migration && !namespaced) {
|
|
1221
|
+
const { annotations: _a, observability: _o, ...versionMetadata } = metadata;
|
|
1222
|
+
const versionId = await api.uploadVersion(
|
|
1223
|
+
state.accountId,
|
|
1224
|
+
deployedName,
|
|
1225
|
+
versionMetadata,
|
|
1226
|
+
modules
|
|
1227
|
+
);
|
|
1228
|
+
log(` staged ${deployedName} (version ${versionId.slice(0, 8)})`);
|
|
1229
|
+
staged.push({ worker, deployedName, versionId, metadata, modules });
|
|
1230
|
+
} else {
|
|
1231
|
+
if (migration) metadata.migrations = migration;
|
|
1232
|
+
log(` staged ${deployedName} (${existing ? "Durable Object migration" : "new Worker"})`);
|
|
1233
|
+
staged.push({ worker, deployedName, metadata, modules });
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
const result = [];
|
|
1237
|
+
for (const item of staged) {
|
|
1238
|
+
if (item.versionId) {
|
|
1239
|
+
await scriptApi.deployVersion(
|
|
1240
|
+
state.accountId,
|
|
1241
|
+
item.deployedName,
|
|
1242
|
+
item.versionId,
|
|
1243
|
+
`${manifest.productLabel} ${manifest.version}`
|
|
1244
|
+
);
|
|
1245
|
+
result.push({ name: item.worker.name, deployedAs: item.deployedName, via: "version" });
|
|
1246
|
+
} else {
|
|
1247
|
+
await scriptApi.putScript(state.accountId, item.deployedName, item.metadata, item.modules);
|
|
1248
|
+
result.push({ name: item.worker.name, deployedAs: item.deployedName, via: "upload" });
|
|
1249
|
+
}
|
|
1250
|
+
log(` switched ${item.deployedName}`);
|
|
1251
|
+
}
|
|
1252
|
+
const values = placeholderValues(state, {});
|
|
1253
|
+
const queues = manifest.resources.some((r) => r.type === "queue") ? await api.listQueues(state.accountId) : [];
|
|
1254
|
+
for (const { worker, deployedName } of staged) {
|
|
1255
|
+
if (!namespaced) await api.putSchedules(state.accountId, deployedName, worker.crons);
|
|
1256
|
+
for (const consumer of worker.queueConsumers) {
|
|
1257
|
+
const queueName = renderString(consumer.queue, values);
|
|
1258
|
+
const queue = queues.find((q) => q.queue_name === queueName);
|
|
1259
|
+
if (!queue) throw new Error(`queue ${queueName} does not exist`);
|
|
1260
|
+
const existing = queue.consumers?.find(
|
|
1261
|
+
(c) => (c.script_name ?? c.script) === deployedName
|
|
1262
|
+
)?.consumer_id;
|
|
1263
|
+
await api.putQueueConsumer(
|
|
1264
|
+
state.accountId,
|
|
1265
|
+
queue.queue_id,
|
|
1266
|
+
deployedName,
|
|
1267
|
+
consumer.settings,
|
|
1268
|
+
existing,
|
|
1269
|
+
consumer.deadLetterQueue ? renderString(consumer.deadLetterQueue, values) : void 0
|
|
1270
|
+
);
|
|
1271
|
+
}
|
|
1272
|
+
if (namespaced) continue;
|
|
1273
|
+
const onWorkersDev = worker.public && state.hostnameMode === "workers.dev";
|
|
1274
|
+
await api.setWorkersDev(state.accountId, deployedName, onWorkersDev);
|
|
1275
|
+
if (worker.public && state.hostnameMode === "custom" && state.zoneId) {
|
|
1276
|
+
await api.putDomain(state.accountId, state.hostname, deployedName, state.zoneId);
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
return { url: `https://${state.hostname}`, workers: result };
|
|
1280
|
+
}
|
|
1281
|
+
async function workersDevHostname(api, accountId, appWorker, subdomainPrefix) {
|
|
1282
|
+
let subdomain = await api.workersSubdomain(accountId);
|
|
1283
|
+
if (!subdomain) {
|
|
1284
|
+
subdomain = await api.createWorkersSubdomain(
|
|
1285
|
+
accountId,
|
|
1286
|
+
`${subdomainPrefix}-${accountId.slice(0, 8).toLowerCase()}`
|
|
1287
|
+
);
|
|
1288
|
+
}
|
|
1289
|
+
return `${appWorker}.${subdomain}.workers.dev`;
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
// ../release/src/operator.ts
|
|
1293
|
+
async function locateDeployment(api, accountId, databaseName) {
|
|
1294
|
+
const databases = await api.listD1(accountId);
|
|
1295
|
+
const db = databases.find((d) => d.name === databaseName);
|
|
1296
|
+
if (!db) return null;
|
|
1297
|
+
return { databaseId: db.uuid, state: await readDeploymentState(api, accountId, db.uuid) };
|
|
1298
|
+
}
|
|
1299
|
+
async function installedExtensionsViaApi(api, accountId, databaseId) {
|
|
1300
|
+
try {
|
|
1301
|
+
const [first] = await api.queryD1(
|
|
1302
|
+
accountId,
|
|
1303
|
+
databaseId,
|
|
1304
|
+
"SELECT id, source, status, json_extract(manifest, '$.contractVersion') AS contract FROM core_extensions"
|
|
1305
|
+
);
|
|
1306
|
+
return (first?.results ?? []).map((row) => ({
|
|
1307
|
+
id: row.id,
|
|
1308
|
+
source: row.source,
|
|
1309
|
+
status: row.status,
|
|
1310
|
+
contractVersion: Number(row.contract ?? 0)
|
|
1311
|
+
}));
|
|
1312
|
+
} catch (error) {
|
|
1313
|
+
if (error instanceof CloudflareApiError && /no such table/i.test(error.message)) return [];
|
|
1314
|
+
throw error;
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
async function appliedMigrationsViaApi(api, accountId, databaseId) {
|
|
1318
|
+
const [first] = await api.queryD1(
|
|
1319
|
+
accountId,
|
|
1320
|
+
databaseId,
|
|
1321
|
+
"SELECT name FROM core_migrations ORDER BY id"
|
|
1322
|
+
);
|
|
1323
|
+
return (first?.results ?? []).map((r) => r.name);
|
|
1324
|
+
}
|
|
1325
|
+
async function saveRunViaApi(api, accountId, databaseId, run) {
|
|
1326
|
+
const columns = Object.keys(run);
|
|
1327
|
+
await api.queryD1(
|
|
1328
|
+
accountId,
|
|
1329
|
+
databaseId,
|
|
1330
|
+
`INSERT OR REPLACE INTO core_update_runs (${columns.join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`,
|
|
1331
|
+
columns.map((c) => run[c])
|
|
1332
|
+
);
|
|
1333
|
+
}
|
|
1334
|
+
async function runsViaApi(api, accountId, databaseId, limit = 10) {
|
|
1335
|
+
const [first] = await api.queryD1(
|
|
1336
|
+
accountId,
|
|
1337
|
+
databaseId,
|
|
1338
|
+
`SELECT * FROM core_update_runs ORDER BY started_at DESC LIMIT ${Math.max(1, Math.min(100, limit))}`
|
|
1339
|
+
);
|
|
1340
|
+
return first?.results ?? [];
|
|
1341
|
+
}
|
|
1342
|
+
function rollbackTarget(runs) {
|
|
1343
|
+
const latest = runs.find((r) => r.status !== "running");
|
|
1344
|
+
return latest && latest.kind === "update" && latest.status === "succeeded" ? latest : null;
|
|
1345
|
+
}
|
|
1346
|
+
function newRunId() {
|
|
1347
|
+
const bytes = crypto.getRandomValues(new Uint8Array(10));
|
|
1348
|
+
return `upd_${Date.now().toString(36)}${[...bytes].map((b) => b.toString(36).padStart(2, "0")).join("").slice(0, 12)}`;
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
// ../release/src/semver.ts
|
|
1352
|
+
var CHANNELS = ["stable", "beta"];
|
|
1353
|
+
var VERSION_RE = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-beta\.(0|[1-9]\d*))?$/;
|
|
1354
|
+
function parseVersion(text) {
|
|
1355
|
+
const match = VERSION_RE.exec(text.trim());
|
|
1356
|
+
if (!match) return null;
|
|
1357
|
+
return {
|
|
1358
|
+
major: Number(match[1]),
|
|
1359
|
+
minor: Number(match[2]),
|
|
1360
|
+
patch: Number(match[3]),
|
|
1361
|
+
beta: match[4] === void 0 ? null : Number(match[4])
|
|
1362
|
+
};
|
|
1363
|
+
}
|
|
1364
|
+
function isVersion(text) {
|
|
1365
|
+
return parseVersion(text) !== null;
|
|
1366
|
+
}
|
|
1367
|
+
function channelOf(version) {
|
|
1368
|
+
const parsed = parseVersion(version);
|
|
1369
|
+
if (!parsed) throw new Error(`not a release version: ${version}`);
|
|
1370
|
+
return parsed.beta === null ? "stable" : "beta";
|
|
1371
|
+
}
|
|
1372
|
+
function compareVersions(a, b) {
|
|
1373
|
+
const x = parseVersion(a);
|
|
1374
|
+
const y = parseVersion(b);
|
|
1375
|
+
if (!x || !y) throw new Error(`cannot compare ${a} and ${b}`);
|
|
1376
|
+
for (const key of ["major", "minor", "patch"]) {
|
|
1377
|
+
if (x[key] !== y[key]) return x[key] - y[key];
|
|
1378
|
+
}
|
|
1379
|
+
if (x.beta === y.beta) return 0;
|
|
1380
|
+
if (x.beta === null) return 1;
|
|
1381
|
+
if (y.beta === null) return -1;
|
|
1382
|
+
return x.beta - y.beta;
|
|
1383
|
+
}
|
|
1384
|
+
function visibleOnChannel(version, channel) {
|
|
1385
|
+
const kind = channelOf(version);
|
|
1386
|
+
return channel === "beta" || kind === "stable";
|
|
1387
|
+
}
|
|
1388
|
+
function bareVersion(tagOrVersion) {
|
|
1389
|
+
return tagOrVersion.startsWith("v") ? tagOrVersion.slice(1) : tagOrVersion;
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
// ../release/src/github.ts
|
|
1393
|
+
var GITHUB_API = "https://api.github.com";
|
|
1394
|
+
var USER_AGENT = "cos-updater";
|
|
1395
|
+
function headers(options) {
|
|
1396
|
+
return {
|
|
1397
|
+
accept: "application/vnd.github+json",
|
|
1398
|
+
"x-github-api-version": "2022-11-28",
|
|
1399
|
+
"user-agent": USER_AGENT,
|
|
1400
|
+
...options.token ? { authorization: `Bearer ${options.token}` } : {}
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1403
|
+
var GitHubRateLimitError = class extends Error {
|
|
1404
|
+
name = "GitHubRateLimitError";
|
|
1405
|
+
};
|
|
1406
|
+
function rateLimited(response, withToken) {
|
|
1407
|
+
const remaining = response.headers.get("x-ratelimit-remaining");
|
|
1408
|
+
if (response.status !== 429 && !(response.status === 403 && remaining === "0")) return null;
|
|
1409
|
+
const reset = Number(response.headers.get("x-ratelimit-reset"));
|
|
1410
|
+
const at = Number.isFinite(reset) && reset > 0 ? ` It resets at ${new Date(reset * 1e3).toISOString()}.` : "";
|
|
1411
|
+
return new GitHubRateLimitError(
|
|
1412
|
+
withToken ? `GitHub's API rate limit for this token was reached.${at}` : `GitHub's API rate limit for calls without a token was reached (60 an hour).${at} Set GH_TOKEN or GITHUB_TOKEN to a GitHub token (no scopes needed) and run again.`
|
|
1413
|
+
);
|
|
1414
|
+
}
|
|
1415
|
+
async function githubJson(path, options) {
|
|
1416
|
+
const response = await (options.fetch ?? fetch)(`${options.apiBase ?? GITHUB_API}${path}`, {
|
|
1417
|
+
headers: headers(options)
|
|
1418
|
+
});
|
|
1419
|
+
if (!response.ok) {
|
|
1420
|
+
const limit = rateLimited(response, Boolean(options.token));
|
|
1421
|
+
if (limit) throw limit;
|
|
1422
|
+
throw new Error(`GitHub ${path}: HTTP ${response.status}`);
|
|
1423
|
+
}
|
|
1424
|
+
return await response.json();
|
|
1425
|
+
}
|
|
1426
|
+
function toInfo(release, product) {
|
|
1427
|
+
const version = bareVersion(release.tag_name);
|
|
1428
|
+
if (release.draft || !isVersion(version)) return null;
|
|
1429
|
+
const channel = version.includes("-") ? "beta" : "stable";
|
|
1430
|
+
if (release.prerelease !== (channel === "beta")) return null;
|
|
1431
|
+
const names = releaseAssetNames(product, version);
|
|
1432
|
+
const find = (name) => release.assets.find((a) => a.name === name)?.browser_download_url;
|
|
1433
|
+
return {
|
|
1434
|
+
version,
|
|
1435
|
+
tag: release.tag_name,
|
|
1436
|
+
channel,
|
|
1437
|
+
name: release.name ?? release.tag_name,
|
|
1438
|
+
notes: release.body ?? "",
|
|
1439
|
+
publishedAt: release.published_at,
|
|
1440
|
+
url: release.html_url,
|
|
1441
|
+
assets: {
|
|
1442
|
+
bundle: find(names.bundle),
|
|
1443
|
+
manifest: find(names.manifest),
|
|
1444
|
+
sums: find(names.sums)
|
|
1445
|
+
}
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1448
|
+
async function listReleases(channel, options) {
|
|
1449
|
+
const repo = options.repository;
|
|
1450
|
+
const releases = await githubJson(
|
|
1451
|
+
`/repos/${repo}/releases?per_page=50`,
|
|
1452
|
+
options
|
|
1453
|
+
);
|
|
1454
|
+
return releases.map((release) => toInfo(release, options.product)).filter((r) => r !== null && visibleOnChannel(r.version, channel)).sort((a, b) => compareVersions(b.version, a.version));
|
|
1455
|
+
}
|
|
1456
|
+
async function getRelease(version, options) {
|
|
1457
|
+
const repo = options.repository;
|
|
1458
|
+
const release = await githubJson(
|
|
1459
|
+
`/repos/${repo}/releases/tags/v${bareVersion(version)}`,
|
|
1460
|
+
options
|
|
1461
|
+
);
|
|
1462
|
+
const info = toInfo(release, options.product);
|
|
1463
|
+
if (!info) throw new Error(`v${version} is not a published release`);
|
|
1464
|
+
return info;
|
|
1465
|
+
}
|
|
1466
|
+
async function downloadAsset(url, options = {}) {
|
|
1467
|
+
const response = await (options.fetch ?? fetch)(url, {
|
|
1468
|
+
headers: { "user-agent": USER_AGENT, accept: "application/octet-stream" },
|
|
1469
|
+
redirect: "follow"
|
|
1470
|
+
});
|
|
1471
|
+
if (!response.ok) {
|
|
1472
|
+
const limit = rateLimited(response, Boolean(options.token));
|
|
1473
|
+
if (limit) throw limit;
|
|
1474
|
+
throw new Error(`download ${url}: HTTP ${response.status}`);
|
|
1475
|
+
}
|
|
1476
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
// ../release/src/attestation.ts
|
|
1480
|
+
var RELEASE_WORKFLOW_PATH = ".github/workflows/release.yml";
|
|
1481
|
+
var SLSA_PROVENANCE_V1 = "https://slsa.dev/provenance/v1";
|
|
1482
|
+
var VerificationError = class extends Error {
|
|
1483
|
+
name = "VerificationError";
|
|
1484
|
+
};
|
|
1485
|
+
function snappyDecompress(input) {
|
|
1486
|
+
let pos = 0;
|
|
1487
|
+
let length = 0;
|
|
1488
|
+
let shift = 0;
|
|
1489
|
+
for (; ; ) {
|
|
1490
|
+
const byte = input[pos++];
|
|
1491
|
+
if (byte === void 0) throw new Error("truncated snappy header");
|
|
1492
|
+
length |= (byte & 127) << shift;
|
|
1493
|
+
if (byte < 128) break;
|
|
1494
|
+
shift += 7;
|
|
1495
|
+
}
|
|
1496
|
+
const out = new Uint8Array(length);
|
|
1497
|
+
let o = 0;
|
|
1498
|
+
while (pos < input.length) {
|
|
1499
|
+
const tag = input[pos++];
|
|
1500
|
+
const kind = tag & 3;
|
|
1501
|
+
if (kind === 0) {
|
|
1502
|
+
let len2 = tag >> 2;
|
|
1503
|
+
if (len2 >= 60) {
|
|
1504
|
+
const bytes = len2 - 59;
|
|
1505
|
+
len2 = 0;
|
|
1506
|
+
for (let i = 0; i < bytes; i++) len2 |= input[pos++] << 8 * i;
|
|
1507
|
+
}
|
|
1508
|
+
len2 += 1;
|
|
1509
|
+
out.set(input.subarray(pos, pos + len2), o);
|
|
1510
|
+
pos += len2;
|
|
1511
|
+
o += len2;
|
|
1512
|
+
continue;
|
|
1513
|
+
}
|
|
1514
|
+
let len;
|
|
1515
|
+
let offset;
|
|
1516
|
+
if (kind === 1) {
|
|
1517
|
+
len = (tag >> 2 & 7) + 4;
|
|
1518
|
+
offset = tag >> 5 << 8 | input[pos++];
|
|
1519
|
+
} else if (kind === 2) {
|
|
1520
|
+
len = (tag >> 2) + 1;
|
|
1521
|
+
offset = input[pos] | input[pos + 1] << 8;
|
|
1522
|
+
pos += 2;
|
|
1523
|
+
} else {
|
|
1524
|
+
len = (tag >> 2) + 1;
|
|
1525
|
+
offset = (input[pos] | input[pos + 1] << 8 | input[pos + 2] << 16 | input[pos + 3] << 24) >>> 0;
|
|
1526
|
+
pos += 4;
|
|
1527
|
+
}
|
|
1528
|
+
if (offset === 0 || offset > o) throw new Error("bad snappy copy offset");
|
|
1529
|
+
for (let i = 0; i < len; i++, o++) out[o] = out[o - offset];
|
|
1530
|
+
}
|
|
1531
|
+
if (o !== length) throw new Error("snappy length mismatch");
|
|
1532
|
+
return out;
|
|
1533
|
+
}
|
|
1534
|
+
async function loadBundle(attestation, options) {
|
|
1535
|
+
if (attestation.bundle) return attestation.bundle;
|
|
1536
|
+
if (!attestation.bundle_url) return null;
|
|
1537
|
+
const response = await (options.fetch ?? fetch)(attestation.bundle_url);
|
|
1538
|
+
if (!response.ok) return null;
|
|
1539
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
1540
|
+
const json = bytes[0] === 123 ? bytes : snappyDecompress(bytes);
|
|
1541
|
+
return JSON.parse(new TextDecoder().decode(json));
|
|
1542
|
+
}
|
|
1543
|
+
function decodeStatement(bundle) {
|
|
1544
|
+
const envelope = bundle?.dsseEnvelope;
|
|
1545
|
+
if (!envelope?.payload || envelope.payloadType !== "application/vnd.in-toto+json") return null;
|
|
1546
|
+
try {
|
|
1547
|
+
return JSON.parse(new TextDecoder().decode(fromBase64(envelope.payload)));
|
|
1548
|
+
} catch {
|
|
1549
|
+
return null;
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
async function verifyProvenance(digest, expected, options = {}) {
|
|
1553
|
+
let response;
|
|
1554
|
+
try {
|
|
1555
|
+
response = await githubJson(
|
|
1556
|
+
`/repos/${expected.repository}/attestations/sha256:${digest}`,
|
|
1557
|
+
options
|
|
1558
|
+
);
|
|
1559
|
+
} catch (error) {
|
|
1560
|
+
throw new VerificationError(
|
|
1561
|
+
`no build attestation for sha256:${digest} in ${expected.repository} (${error.message})`
|
|
1562
|
+
);
|
|
1563
|
+
}
|
|
1564
|
+
const wantRepo = `https://github.com/${expected.repository}`;
|
|
1565
|
+
const wantRef = `refs/tags/v${expected.version}`;
|
|
1566
|
+
const reasons = [];
|
|
1567
|
+
for (const attestation of response.attestations ?? []) {
|
|
1568
|
+
let statement = null;
|
|
1569
|
+
try {
|
|
1570
|
+
statement = decodeStatement(await loadBundle(attestation, options));
|
|
1571
|
+
} catch {
|
|
1572
|
+
statement = null;
|
|
1573
|
+
}
|
|
1574
|
+
if (!statement) {
|
|
1575
|
+
reasons.push("an attestation is not an in-toto statement");
|
|
1576
|
+
continue;
|
|
1577
|
+
}
|
|
1578
|
+
const subjects = statement.subject ?? [];
|
|
1579
|
+
if (!subjects.some((s) => s.digest?.sha256 && sameDigest(s.digest.sha256, digest))) {
|
|
1580
|
+
reasons.push("an attestation does not name this digest");
|
|
1581
|
+
continue;
|
|
1582
|
+
}
|
|
1583
|
+
if (statement.predicateType !== SLSA_PROVENANCE_V1) {
|
|
1584
|
+
reasons.push(`an attestation has predicate ${statement.predicateType}`);
|
|
1585
|
+
continue;
|
|
1586
|
+
}
|
|
1587
|
+
const workflow = statement.predicate?.buildDefinition?.externalParameters?.workflow;
|
|
1588
|
+
if (!workflow || !sameRepository(workflow.repository, expected.repository)) {
|
|
1589
|
+
reasons.push(
|
|
1590
|
+
`an attestation was built in ${workflow?.repository ?? "an unknown repository"}`
|
|
1591
|
+
);
|
|
1592
|
+
continue;
|
|
1593
|
+
}
|
|
1594
|
+
if (workflow.path !== RELEASE_WORKFLOW_PATH) {
|
|
1595
|
+
reasons.push(`an attestation was built by ${workflow.path}, not the release workflow`);
|
|
1596
|
+
continue;
|
|
1597
|
+
}
|
|
1598
|
+
if (workflow.ref !== wantRef) {
|
|
1599
|
+
reasons.push(`an attestation was built from ${workflow.ref}, not ${wantRef}`);
|
|
1600
|
+
continue;
|
|
1601
|
+
}
|
|
1602
|
+
return {
|
|
1603
|
+
digest,
|
|
1604
|
+
repository: expected.repository,
|
|
1605
|
+
workflow: {
|
|
1606
|
+
repository: workflow.repository ?? wantRepo,
|
|
1607
|
+
path: workflow.path,
|
|
1608
|
+
ref: workflow.ref
|
|
1609
|
+
}
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
throw new VerificationError(
|
|
1613
|
+
`no valid build attestation for sha256:${digest}${reasons.length ? `: ${reasons.join("; ")}` : ""}`
|
|
1614
|
+
);
|
|
1615
|
+
}
|
|
1616
|
+
function sameRepository(actual, expected) {
|
|
1617
|
+
if (!actual) return false;
|
|
1618
|
+
const norm = (r) => r.toLowerCase().replace(/^https:\/\/github\.com\//, "");
|
|
1619
|
+
return norm(actual) === norm(expected);
|
|
1620
|
+
}
|
|
1621
|
+
async function verifyBundleBytes(input) {
|
|
1622
|
+
const digest = await sha256Hex(input.bytes);
|
|
1623
|
+
const sums = parseSums(input.sums);
|
|
1624
|
+
const name = releaseAssetNames(input.product, input.version).bundle;
|
|
1625
|
+
const listed = sums.get(name);
|
|
1626
|
+
if (!listed) throw new VerificationError(`SHA256SUMS does not list ${name}`);
|
|
1627
|
+
if (!sameDigest(listed, digest)) {
|
|
1628
|
+
throw new VerificationError(
|
|
1629
|
+
`${name} has sha256 ${digest}, but the release lists ${listed}: the bundle was changed after it was built`
|
|
1630
|
+
);
|
|
1631
|
+
}
|
|
1632
|
+
if (input.skipProvenance) return { digest, provenance: null };
|
|
1633
|
+
const provenance = await verifyProvenance(
|
|
1634
|
+
digest,
|
|
1635
|
+
{ repository: input.repository, version: input.version },
|
|
1636
|
+
input.github ?? {}
|
|
1637
|
+
);
|
|
1638
|
+
if (input.extra) {
|
|
1639
|
+
await input.extra({
|
|
1640
|
+
bytes: input.bytes,
|
|
1641
|
+
digest,
|
|
1642
|
+
repository: input.repository,
|
|
1643
|
+
product: input.product,
|
|
1644
|
+
version: input.version
|
|
1645
|
+
});
|
|
1646
|
+
}
|
|
1647
|
+
return { digest, provenance };
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
// ../release/src/channel.ts
|
|
1651
|
+
var encoder2 = new TextEncoder();
|
|
1652
|
+
|
|
1653
|
+
// ../release/src/gateway.ts
|
|
1654
|
+
var GATEWAY_ID_VAR = "AI_GATEWAY_ID";
|
|
1655
|
+
var GATEWAY_TOKEN_SECRET = "AI_GATEWAY_TOKEN";
|
|
1656
|
+
var GATEWAY_RUN_PERMISSION = "AI Gateway Run";
|
|
1657
|
+
var WORKERS_AI_READ_PERMISSION = "Workers AI Read";
|
|
1658
|
+
var GATEWAY_REST_VAR = "AI_GATEWAY_REST";
|
|
1659
|
+
var DEFAULT_GATEWAY_SETTINGS = {
|
|
1660
|
+
collect_logs: true,
|
|
1661
|
+
cache_ttl: 0,
|
|
1662
|
+
cache_invalidate_on_update: true,
|
|
1663
|
+
rate_limiting_interval: 0,
|
|
1664
|
+
rate_limiting_limit: 0,
|
|
1665
|
+
rate_limiting_technique: "fixed"
|
|
1666
|
+
};
|
|
1667
|
+
function workerName2(state, name) {
|
|
1668
|
+
return state.workerNames[name] ?? name;
|
|
1669
|
+
}
|
|
1670
|
+
function gatewayIdFor(state, manifest) {
|
|
1671
|
+
if (typeof state.aiGateway === "string" && state.aiGateway) return state.aiGateway;
|
|
1672
|
+
const app = manifest.workers.find((w) => w.role === "app")?.name ?? "";
|
|
1673
|
+
const base = workerName2(state, app).toLowerCase().replace(/-app$/, "").replace(/[^a-z0-9-]/g, "-").replace(/^-+|-+$/g, "");
|
|
1674
|
+
return (base || manifest.product).slice(0, 64);
|
|
1675
|
+
}
|
|
1676
|
+
function gatewayWorkers(manifest) {
|
|
1677
|
+
const declared = manifest.inputs.find((i) => i.name === GATEWAY_ID_VAR)?.workers;
|
|
1678
|
+
if (declared?.length) return declared;
|
|
1679
|
+
const app = manifest.workers.find((w) => w.role === "app")?.name;
|
|
1680
|
+
return app ? [app] : [];
|
|
1681
|
+
}
|
|
1682
|
+
var MODEL_ROLES_VAR = "AI_MODEL_ROLES";
|
|
1683
|
+
var GATEWAY_BYOK_VAR = "AI_GATEWAY_BYOK";
|
|
1684
|
+
var JUDGE_GATEWAY_PROVIDER = "custom-typesafe";
|
|
1685
|
+
var JUDGE_BYOK_VAR = "JUDGE_BYOK";
|
|
1686
|
+
function varWorkers(manifest, name) {
|
|
1687
|
+
const declared = manifest.inputs.find((i) => i.kind === "var" && i.name === name)?.workers;
|
|
1688
|
+
return declared?.length ? declared : gatewayWorkers(manifest);
|
|
1689
|
+
}
|
|
1690
|
+
function withDeploymentVar(vars, manifest, name, value) {
|
|
1691
|
+
const out = { ...vars };
|
|
1692
|
+
for (const worker of varWorkers(manifest, name)) {
|
|
1693
|
+
const { [name]: _old, ...rest } = out[worker] ?? {};
|
|
1694
|
+
out[worker] = value ? { ...rest, [name]: value } : rest;
|
|
1695
|
+
}
|
|
1696
|
+
return out;
|
|
1697
|
+
}
|
|
1698
|
+
function withByokProvider(vars, manifest, provider) {
|
|
1699
|
+
const out = { ...vars };
|
|
1700
|
+
for (const worker of varWorkers(manifest, GATEWAY_BYOK_VAR)) {
|
|
1701
|
+
const current = (out[worker]?.[GATEWAY_BYOK_VAR] ?? "").split(",").map((p) => p.trim());
|
|
1702
|
+
const list = [.../* @__PURE__ */ new Set([...current, provider])].filter(Boolean).sort();
|
|
1703
|
+
out[worker] = { ...out[worker], [GATEWAY_BYOK_VAR]: list.join(",") };
|
|
1704
|
+
}
|
|
1705
|
+
return out;
|
|
1706
|
+
}
|
|
1707
|
+
function gatewayProviderSlug(manifest, name) {
|
|
1708
|
+
const slug = name.trim().toLowerCase();
|
|
1709
|
+
if (slug.startsWith("custom-")) return slug;
|
|
1710
|
+
return manifest.aiGateway?.customProviders.some((p) => p.slug === slug) ? `custom-${slug}` : slug;
|
|
1711
|
+
}
|
|
1712
|
+
var isPermissionError = (error) => error instanceof CloudflareApiError && (error.status === 401 || error.status === 403);
|
|
1713
|
+
async function provisionAiGateway(input) {
|
|
1714
|
+
const { api, manifest, state } = input;
|
|
1715
|
+
const log = input.log ?? (() => {
|
|
1716
|
+
});
|
|
1717
|
+
const accountId = state.accountId;
|
|
1718
|
+
const kept = {
|
|
1719
|
+
...state.aiGateway !== void 0 ? { aiGateway: state.aiGateway } : {},
|
|
1720
|
+
...state.aiGatewayCreated ? { aiGatewayCreated: true } : {},
|
|
1721
|
+
...state.aiGatewayTokenId ? { aiGatewayTokenId: state.aiGatewayTokenId } : {},
|
|
1722
|
+
...state.aiGatewayTokenWorkersAi ? { aiGatewayTokenWorkersAi: true } : {}
|
|
1723
|
+
};
|
|
1724
|
+
const none = {
|
|
1725
|
+
gatewayId: null,
|
|
1726
|
+
vars: state.vars,
|
|
1727
|
+
secrets: {},
|
|
1728
|
+
state: kept,
|
|
1729
|
+
warnings: []
|
|
1730
|
+
};
|
|
1731
|
+
if (!featureOn(state, "ai") || state.aiGateway === false) {
|
|
1732
|
+
return { ...none, vars: withoutVar(state.vars, GATEWAY_REST_VAR) };
|
|
1733
|
+
}
|
|
1734
|
+
const id = gatewayIdFor(state, manifest);
|
|
1735
|
+
const workers = gatewayWorkers(manifest);
|
|
1736
|
+
const withVar = (rest = false) => {
|
|
1737
|
+
const vars = { ...state.vars };
|
|
1738
|
+
for (const worker of workers) {
|
|
1739
|
+
const { [GATEWAY_REST_VAR]: _old, ...others } = vars[worker] ?? {};
|
|
1740
|
+
vars[worker] = {
|
|
1741
|
+
...others,
|
|
1742
|
+
[GATEWAY_ID_VAR]: id,
|
|
1743
|
+
...rest ? { [GATEWAY_REST_VAR]: "true" } : {}
|
|
1744
|
+
};
|
|
1745
|
+
}
|
|
1746
|
+
return vars;
|
|
1747
|
+
};
|
|
1748
|
+
const config = manifest.aiGateway;
|
|
1749
|
+
if (!config) {
|
|
1750
|
+
return typeof state.aiGateway === "string" ? { ...none, gatewayId: id, vars: withVar() } : none;
|
|
1751
|
+
}
|
|
1752
|
+
const warnings = [];
|
|
1753
|
+
const warn = (message) => {
|
|
1754
|
+
warnings.push(message);
|
|
1755
|
+
log(` warning: ${message}`);
|
|
1756
|
+
};
|
|
1757
|
+
let created = state.aiGatewayCreated === true;
|
|
1758
|
+
try {
|
|
1759
|
+
const existing = await api.getAiGateway(accountId, id);
|
|
1760
|
+
if (!existing) {
|
|
1761
|
+
await api.createAiGateway(accountId, {
|
|
1762
|
+
...DEFAULT_GATEWAY_SETTINGS,
|
|
1763
|
+
...config.settings,
|
|
1764
|
+
id,
|
|
1765
|
+
authentication: true
|
|
1766
|
+
});
|
|
1767
|
+
created = true;
|
|
1768
|
+
log(` AI Gateway ${id}: created (logging and authentication on)`);
|
|
1769
|
+
} else {
|
|
1770
|
+
const wanted = { ...config.settings, authentication: true };
|
|
1771
|
+
const off = ["collect_logs", "authentication"].filter(
|
|
1772
|
+
(key) => wanted[key] === true && existing[key] !== true
|
|
1773
|
+
);
|
|
1774
|
+
if (off.length) {
|
|
1775
|
+
await api.updateAiGateway(accountId, id, {
|
|
1776
|
+
...gatewaySettingsOf(existing),
|
|
1777
|
+
...Object.fromEntries(off.map((key) => [key, true]))
|
|
1778
|
+
});
|
|
1779
|
+
log(` AI Gateway ${id}: exists; turned on ${off.join(" and ")}`);
|
|
1780
|
+
} else {
|
|
1781
|
+
log(` AI Gateway ${id}: exists`);
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
} catch (error) {
|
|
1785
|
+
if (!isPermissionError(error)) throw error;
|
|
1786
|
+
warn(
|
|
1787
|
+
`the API token cannot manage AI Gateway (needs AI Gateway Edit), so model calls go to Workers AI directly: ${error.message}`
|
|
1788
|
+
);
|
|
1789
|
+
return { ...none, warnings };
|
|
1790
|
+
}
|
|
1791
|
+
try {
|
|
1792
|
+
const providers = config.customProviders.length ? await api.listCustomProviders(accountId) : [];
|
|
1793
|
+
for (const provider of config.customProviders) {
|
|
1794
|
+
const found = providers.find((p) => p.slug === provider.slug);
|
|
1795
|
+
const fields = {
|
|
1796
|
+
name: provider.name,
|
|
1797
|
+
slug: provider.slug,
|
|
1798
|
+
base_url: provider.baseUrl,
|
|
1799
|
+
...provider.description ? { description: provider.description } : {},
|
|
1800
|
+
...provider.link ? { link: provider.link } : {},
|
|
1801
|
+
enable: true
|
|
1802
|
+
};
|
|
1803
|
+
if (!found) {
|
|
1804
|
+
await api.createCustomProvider(accountId, fields);
|
|
1805
|
+
log(` custom provider custom-${provider.slug}: created (${provider.baseUrl})`);
|
|
1806
|
+
} else if (found.base_url !== provider.baseUrl || found.enable === false) {
|
|
1807
|
+
await api.updateCustomProvider(accountId, found.id, {
|
|
1808
|
+
base_url: provider.baseUrl,
|
|
1809
|
+
enable: true
|
|
1810
|
+
});
|
|
1811
|
+
log(` custom provider custom-${provider.slug}: updated (${provider.baseUrl})`);
|
|
1812
|
+
} else {
|
|
1813
|
+
log(` custom provider custom-${provider.slug}: exists`);
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
} catch (error) {
|
|
1817
|
+
if (!isPermissionError(error)) throw error;
|
|
1818
|
+
warn(`could not create custom providers (needs AI Gateway Edit): ${error.message}`);
|
|
1819
|
+
}
|
|
1820
|
+
const secrets = {};
|
|
1821
|
+
let tokenId = state.aiGatewayTokenId;
|
|
1822
|
+
let workersAi = state.aiGatewayTokenWorkersAi === true;
|
|
1823
|
+
let retiredTokenId;
|
|
1824
|
+
const setAll = (value) => {
|
|
1825
|
+
for (const worker of workers) secrets[worker] = { [GATEWAY_TOKEN_SECRET]: value };
|
|
1826
|
+
};
|
|
1827
|
+
if (input.token) {
|
|
1828
|
+
setAll(input.token);
|
|
1829
|
+
if (tokenId) retiredTokenId = tokenId;
|
|
1830
|
+
tokenId = void 0;
|
|
1831
|
+
workersAi = await canCallWorkersAi(api, accountId, input.token);
|
|
1832
|
+
log(
|
|
1833
|
+
` ${GATEWAY_TOKEN_SECRET}: supplied${workersAi ? ` (with ${WORKERS_AI_READ_PERMISSION})` : ""}`
|
|
1834
|
+
);
|
|
1835
|
+
if (!workersAi) {
|
|
1836
|
+
warn(
|
|
1837
|
+
`the supplied ${GATEWAY_TOKEN_SECRET} cannot call Workers AI (it needs ${WORKERS_AI_READ_PERMISSION} as well as ${GATEWAY_RUN_PERMISSION}), so Workers AI stays on the binding and AI Gateway logs its prompts and responses`
|
|
1838
|
+
);
|
|
1839
|
+
}
|
|
1840
|
+
} else {
|
|
1841
|
+
const scriptApi = scriptsApi(api, state);
|
|
1842
|
+
const scripts = new Set((await scriptApi.listScripts(accountId)).map((s) => s.id));
|
|
1843
|
+
let missing = false;
|
|
1844
|
+
for (const worker of workers) {
|
|
1845
|
+
const deployed = workerName2(state, worker);
|
|
1846
|
+
if (!scripts.has(deployed)) {
|
|
1847
|
+
missing = true;
|
|
1848
|
+
break;
|
|
1849
|
+
}
|
|
1850
|
+
if (!(await scriptApi.listSecrets(accountId, deployed)).includes(GATEWAY_TOKEN_SECRET)) {
|
|
1851
|
+
missing = true;
|
|
1852
|
+
break;
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
const upgrade = !missing && Boolean(tokenId) && !workersAi;
|
|
1856
|
+
if (!missing && !upgrade) {
|
|
1857
|
+
log(` ${GATEWAY_TOKEN_SECRET}: set`);
|
|
1858
|
+
if (!workersAi) {
|
|
1859
|
+
warn(
|
|
1860
|
+
`${GATEWAY_TOKEN_SECRET} was set by hand and is not known to call Workers AI, so Workers AI stays on the binding and AI Gateway logs its prompts and responses. To turn that off, supply a token with ${GATEWAY_RUN_PERMISSION} and ${WORKERS_AI_READ_PERMISSION} with --secret ${GATEWAY_TOKEN_SECRET}=\u2026 (ADR 0330)`
|
|
1861
|
+
);
|
|
1862
|
+
}
|
|
1863
|
+
} else {
|
|
1864
|
+
try {
|
|
1865
|
+
const [run] = await api.permissionGroups(accountId, GATEWAY_RUN_PERMISSION);
|
|
1866
|
+
if (!run) throw new Error(`no "${GATEWAY_RUN_PERMISSION}" permission group`);
|
|
1867
|
+
const [read] = await api.permissionGroups(accountId, WORKERS_AI_READ_PERMISSION);
|
|
1868
|
+
const token = await api.createAccountToken(
|
|
1869
|
+
accountId,
|
|
1870
|
+
`${id} AI Gateway (${manifest.productLabel})`,
|
|
1871
|
+
read ? [run.id, read.id] : [run.id]
|
|
1872
|
+
);
|
|
1873
|
+
setAll(token.value);
|
|
1874
|
+
workersAi = Boolean(read);
|
|
1875
|
+
log(
|
|
1876
|
+
` ${GATEWAY_TOKEN_SECRET}: ${upgrade ? "replaced" : "generated"} (an account token with ${GATEWAY_RUN_PERMISSION}${read ? ` and ${WORKERS_AI_READ_PERMISSION}` : ""})`
|
|
1877
|
+
);
|
|
1878
|
+
if (!read) {
|
|
1879
|
+
warn(
|
|
1880
|
+
`no "${WORKERS_AI_READ_PERMISSION}" permission group, so Workers AI stays on the binding and AI Gateway logs its prompts and responses`
|
|
1881
|
+
);
|
|
1882
|
+
}
|
|
1883
|
+
if (tokenId && tokenId !== token.id) retiredTokenId = tokenId;
|
|
1884
|
+
tokenId = token.id;
|
|
1885
|
+
} catch (error) {
|
|
1886
|
+
if (!isPermissionError(error)) throw error;
|
|
1887
|
+
if (upgrade) {
|
|
1888
|
+
warn(
|
|
1889
|
+
`could not replace ${GATEWAY_TOKEN_SECRET} with one that can call Workers AI (needs Account API Tokens Edit), so Workers AI stays on the binding and AI Gateway logs its prompts and responses until an install or upgrade with that permission`
|
|
1890
|
+
);
|
|
1891
|
+
} else {
|
|
1892
|
+
warn(
|
|
1893
|
+
`could not generate the gateway token (needs Account API Tokens Edit). Workers AI still works through the gateway, on the binding; for other providers, and for Workers AI without prompt logging, create a token with ${GATEWAY_RUN_PERMISSION} and ${WORKERS_AI_READ_PERMISSION} and set it with --secret ${GATEWAY_TOKEN_SECRET}=\u2026 for ${workers.join(" and ")}`
|
|
1894
|
+
);
|
|
1895
|
+
workersAi = false;
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
return {
|
|
1901
|
+
gatewayId: id,
|
|
1902
|
+
vars: withVar(workersAi),
|
|
1903
|
+
secrets,
|
|
1904
|
+
state: {
|
|
1905
|
+
aiGateway: id,
|
|
1906
|
+
...created ? { aiGatewayCreated: true } : {},
|
|
1907
|
+
...tokenId ? { aiGatewayTokenId: tokenId } : {},
|
|
1908
|
+
...workersAi ? { aiGatewayTokenWorkersAi: true } : {}
|
|
1909
|
+
},
|
|
1910
|
+
...retiredTokenId ? { retiredTokenId } : {},
|
|
1911
|
+
warnings
|
|
1912
|
+
};
|
|
1913
|
+
}
|
|
1914
|
+
async function canCallWorkersAi(api, accountId, token) {
|
|
1915
|
+
try {
|
|
1916
|
+
await api.probeWorkersAi(accountId, token);
|
|
1917
|
+
return true;
|
|
1918
|
+
} catch {
|
|
1919
|
+
return false;
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
async function retireGatewayToken(api, accountId, tokenId, log = () => {
|
|
1923
|
+
}) {
|
|
1924
|
+
if (!tokenId) return;
|
|
1925
|
+
try {
|
|
1926
|
+
await api.deleteAccountToken(accountId, tokenId);
|
|
1927
|
+
log(" the replaced AI Gateway token: deleted");
|
|
1928
|
+
} catch (error) {
|
|
1929
|
+
log(` warning: could not delete the replaced AI Gateway token: ${error.message}`);
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
function withoutVar(vars, name) {
|
|
1933
|
+
const out = {};
|
|
1934
|
+
for (const [worker, values] of Object.entries(vars)) {
|
|
1935
|
+
const { [name]: _gone, ...rest } = values;
|
|
1936
|
+
out[worker] = rest;
|
|
1937
|
+
}
|
|
1938
|
+
return out;
|
|
1939
|
+
}
|
|
1940
|
+
function mergeSecrets(...maps) {
|
|
1941
|
+
const out = {};
|
|
1942
|
+
for (const map of maps) {
|
|
1943
|
+
for (const [worker, values] of Object.entries(map)) out[worker] = { ...out[worker], ...values };
|
|
1944
|
+
}
|
|
1945
|
+
return out;
|
|
1946
|
+
}
|
|
1947
|
+
|
|
1948
|
+
// ../release/src/preflight.ts
|
|
1949
|
+
function gatekeepers(manifest) {
|
|
1950
|
+
return new Map(
|
|
1951
|
+
(manifest?.workers ?? []).filter((w) => w.role === "gatekeeper").map((w) => [w.name, w])
|
|
1952
|
+
);
|
|
1953
|
+
}
|
|
1954
|
+
function preflight(input) {
|
|
1955
|
+
const { target } = input;
|
|
1956
|
+
const blockers = [];
|
|
1957
|
+
const warnings = [];
|
|
1958
|
+
if (input.currentVersion && isVersion(input.currentVersion)) {
|
|
1959
|
+
const order = compareVersions(target.version, input.currentVersion);
|
|
1960
|
+
if (order < 0 || order === 0 && !input.allowSameVersion) {
|
|
1961
|
+
blockers.push({
|
|
1962
|
+
code: "not_newer",
|
|
1963
|
+
message: `${target.version} is not newer than the installed ${input.currentVersion}. To go back, use Roll back.`
|
|
1964
|
+
});
|
|
1965
|
+
}
|
|
1966
|
+
} else {
|
|
1967
|
+
warnings.push({
|
|
1968
|
+
code: "unknown_current",
|
|
1969
|
+
message: "The installed version is not a release (a source deploy), so changes are listed against nothing."
|
|
1970
|
+
});
|
|
1971
|
+
}
|
|
1972
|
+
const supported = target.extensionContract.supported;
|
|
1973
|
+
const extensions = input.extensions.filter((e) => e.source === "runtime").map((e) => ({
|
|
1974
|
+
id: e.id,
|
|
1975
|
+
contractVersion: e.contractVersion,
|
|
1976
|
+
compatible: supported.includes(e.contractVersion),
|
|
1977
|
+
status: e.status
|
|
1978
|
+
}));
|
|
1979
|
+
for (const extension of extensions) {
|
|
1980
|
+
if (extension.compatible) continue;
|
|
1981
|
+
const issue = {
|
|
1982
|
+
code: "extension_incompatible",
|
|
1983
|
+
message: `Extension "${extension.id}" is written against extension contract ${extension.contractVersion}, but ${target.version} runs contracts ${supported.join(" and ")} only. It would stop working. Update the extension to contract ${target.extensionContract.version} (ask Claude to port it and approve the proposal), or disable it, then run preflight again.`
|
|
1984
|
+
};
|
|
1985
|
+
if (extension.status === "active") blockers.push(issue);
|
|
1986
|
+
else warnings.push({ ...issue, message: `${issue.message} (It is ${extension.status} now.)` });
|
|
1987
|
+
}
|
|
1988
|
+
const known = new Set(target.migrations.map((m) => m.name));
|
|
1989
|
+
const unknown = input.appliedMigrations.filter((name) => !known.has(name));
|
|
1990
|
+
if (unknown.length) {
|
|
1991
|
+
blockers.push({
|
|
1992
|
+
code: "database_newer",
|
|
1993
|
+
message: `The database has migrations ${target.version} does not know (${unknown.join(", ")}); it is newer than this release.`
|
|
1994
|
+
});
|
|
1995
|
+
}
|
|
1996
|
+
const applied = new Set(input.appliedMigrations);
|
|
1997
|
+
const migrations = target.migrations.map((m) => m.name).filter((name) => !applied.has(name));
|
|
1998
|
+
const before = gatekeepers(input.current);
|
|
1999
|
+
const after = gatekeepers(target);
|
|
2000
|
+
const installed = new Set(input.installedGatekeepers);
|
|
2001
|
+
const changedGatekeepers = {
|
|
2002
|
+
added: [...after.keys()].filter((name) => !before.has(name)).sort(),
|
|
2003
|
+
removed: [...before.keys()].filter((name) => !after.has(name)).sort(),
|
|
2004
|
+
changed: [...after.entries()].filter(([name, entry]) => before.has(name) && before.get(name)?.sha256 !== entry.sha256).map(([name]) => name).sort()
|
|
2005
|
+
};
|
|
2006
|
+
for (const name of changedGatekeepers.removed) {
|
|
2007
|
+
if (installed.has(name)) {
|
|
2008
|
+
warnings.push({
|
|
2009
|
+
code: "unknown_current",
|
|
2010
|
+
message: `Gatekeeper ${name} is installed but no longer ships in ${target.version}; it stays deployed as it is.`
|
|
2011
|
+
});
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
const secrets = [];
|
|
2015
|
+
for (const worker of target.workers) {
|
|
2016
|
+
if (worker.role === "gatekeeper" && !installed.has(worker.name)) continue;
|
|
2017
|
+
const previous = new Set(
|
|
2018
|
+
input.current?.workers.find((w) => w.name === worker.name)?.secrets.map((s) => s.name) ?? []
|
|
2019
|
+
);
|
|
2020
|
+
for (const secret of worker.secrets) {
|
|
2021
|
+
const setList = input.secretsSet?.[worker.name];
|
|
2022
|
+
const set = setList ? setList.includes(secret.name) : null;
|
|
2023
|
+
const isNew = input.current ? !previous.has(secret.name) : false;
|
|
2024
|
+
if (!isNew && !(secret.required && set === false)) continue;
|
|
2025
|
+
secrets.push({ worker: worker.name, name: secret.name, required: secret.required, set });
|
|
2026
|
+
if (secret.required && set === false && secret.source !== "generated") {
|
|
2027
|
+
blockers.push({
|
|
2028
|
+
code: "missing_secret",
|
|
2029
|
+
message: `${target.version} needs the secret ${secret.name} on ${worker.name}${secret.description ? ` (${secret.description})` : ""}. Set it, then run preflight again.`
|
|
2030
|
+
});
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
const previousInputs = new Set(input.current?.inputs.map((i) => i.name) ?? []);
|
|
2035
|
+
const inputs = input.current ? target.inputs.map((i) => i.name).filter((name) => !previousInputs.has(name)) : [];
|
|
2036
|
+
return {
|
|
2037
|
+
ok: blockers.length === 0,
|
|
2038
|
+
from: input.currentVersion,
|
|
2039
|
+
to: target.version,
|
|
2040
|
+
blockers,
|
|
2041
|
+
warnings,
|
|
2042
|
+
migrations,
|
|
2043
|
+
extensions,
|
|
2044
|
+
gatekeepers: changedGatekeepers,
|
|
2045
|
+
secrets,
|
|
2046
|
+
inputs
|
|
2047
|
+
};
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
// ../release/src/source.ts
|
|
2051
|
+
async function fetchVerifiedRelease(version, options) {
|
|
2052
|
+
const { repository, product } = options;
|
|
2053
|
+
const info = await getRelease(version, options);
|
|
2054
|
+
if (!info.assets.bundle || !info.assets.sums) {
|
|
2055
|
+
throw new VerificationError(`release ${info.tag} has no bundle or SHA256SUMS asset`);
|
|
2056
|
+
}
|
|
2057
|
+
const download = { ...options, fetch: options.downloadFetch ?? options.fetch };
|
|
2058
|
+
const [bytes, sumsBytes] = await Promise.all([
|
|
2059
|
+
downloadAsset(info.assets.bundle, download),
|
|
2060
|
+
downloadAsset(info.assets.sums, download)
|
|
2061
|
+
]);
|
|
2062
|
+
const { digest } = await verifyBundleBytes({
|
|
2063
|
+
bytes,
|
|
2064
|
+
product,
|
|
2065
|
+
version: info.version,
|
|
2066
|
+
sums: new TextDecoder().decode(sumsBytes),
|
|
2067
|
+
repository,
|
|
2068
|
+
github: options,
|
|
2069
|
+
...options.extra ? { extra: options.extra } : {}
|
|
2070
|
+
});
|
|
2071
|
+
const bundle = await openBundle(bytes);
|
|
2072
|
+
if (bundle.manifest.version !== info.version) {
|
|
2073
|
+
throw new VerificationError(
|
|
2074
|
+
`bundle says it is ${bundle.manifest.version}, but the release is ${info.version}`
|
|
2075
|
+
);
|
|
2076
|
+
}
|
|
2077
|
+
if (bundle.manifest.product !== product) {
|
|
2078
|
+
throw new VerificationError(
|
|
2079
|
+
`bundle is a release of ${bundle.manifest.product}, not ${product}`
|
|
2080
|
+
);
|
|
2081
|
+
}
|
|
2082
|
+
if (!sameRepository(bundle.manifest.repository, repository)) {
|
|
2083
|
+
throw new VerificationError(
|
|
2084
|
+
`bundle was built for ${bundle.manifest.repository}, not ${repository}`
|
|
2085
|
+
);
|
|
2086
|
+
}
|
|
2087
|
+
return { info, bundle, digest };
|
|
2088
|
+
}
|
|
2089
|
+
async function fetchReleaseManifest(info, options = {}) {
|
|
2090
|
+
if (!info.assets.manifest) throw new Error(`release ${info.tag} has no manifest asset`);
|
|
2091
|
+
return parseManifest(
|
|
2092
|
+
new TextDecoder().decode(await downloadAsset(info.assets.manifest, options))
|
|
2093
|
+
);
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
// ../release/src/update.ts
|
|
2097
|
+
var noAutomationControl = {
|
|
2098
|
+
async pause() {
|
|
2099
|
+
},
|
|
2100
|
+
async resume() {
|
|
2101
|
+
}
|
|
2102
|
+
};
|
|
2103
|
+
var KILL_SWITCH_SETTING = "automations_kill_switch";
|
|
2104
|
+
function killSwitchControl(store) {
|
|
2105
|
+
let turnedOn = false;
|
|
2106
|
+
return {
|
|
2107
|
+
async pause() {
|
|
2108
|
+
if (await store.read()) return;
|
|
2109
|
+
await store.write(true);
|
|
2110
|
+
turnedOn = true;
|
|
2111
|
+
},
|
|
2112
|
+
async resume() {
|
|
2113
|
+
if (!turnedOn) return;
|
|
2114
|
+
await store.write(false);
|
|
2115
|
+
turnedOn = false;
|
|
2116
|
+
}
|
|
2117
|
+
};
|
|
2118
|
+
}
|
|
2119
|
+
function apiKillSwitchStore(api, accountId, databaseId) {
|
|
2120
|
+
return {
|
|
2121
|
+
async read() {
|
|
2122
|
+
try {
|
|
2123
|
+
const [first] = await api.queryD1(
|
|
2124
|
+
accountId,
|
|
2125
|
+
databaseId,
|
|
2126
|
+
"SELECT value FROM core_settings WHERE key = ?",
|
|
2127
|
+
[KILL_SWITCH_SETTING]
|
|
2128
|
+
);
|
|
2129
|
+
const row = first?.results[0];
|
|
2130
|
+
return row ? JSON.parse(row.value) === true : false;
|
|
2131
|
+
} catch {
|
|
2132
|
+
return true;
|
|
2133
|
+
}
|
|
2134
|
+
},
|
|
2135
|
+
async write(on) {
|
|
2136
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2137
|
+
await api.queryD1(
|
|
2138
|
+
accountId,
|
|
2139
|
+
databaseId,
|
|
2140
|
+
"INSERT INTO core_settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
|
|
2141
|
+
[KILL_SWITCH_SETTING, JSON.stringify(on), now]
|
|
2142
|
+
);
|
|
2143
|
+
}
|
|
2144
|
+
};
|
|
2145
|
+
}
|
|
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
|
+
async function runUpdate(input) {
|
|
2154
|
+
const log = input.log ?? (() => {
|
|
2155
|
+
});
|
|
2156
|
+
const automations = input.automations ?? noAutomationControl;
|
|
2157
|
+
const { api, databaseId, target } = input;
|
|
2158
|
+
const state = input.state;
|
|
2159
|
+
const outcome = {
|
|
2160
|
+
status: "failed",
|
|
2161
|
+
from: state.version,
|
|
2162
|
+
to: target.manifest.version,
|
|
2163
|
+
bookmark: null,
|
|
2164
|
+
migrations: []
|
|
2165
|
+
};
|
|
2166
|
+
const step = async (name) => {
|
|
2167
|
+
log(`${name}\u2026`);
|
|
2168
|
+
await input.onStep?.(name, outcome);
|
|
2169
|
+
};
|
|
2170
|
+
let phase = "before";
|
|
2171
|
+
try {
|
|
2172
|
+
await step("pause");
|
|
2173
|
+
await automations.pause();
|
|
2174
|
+
await step("bookmark");
|
|
2175
|
+
outcome.bookmark = await api.d1Bookmark(state.accountId, databaseId);
|
|
2176
|
+
await step("migrate");
|
|
2177
|
+
outcome.migrations = await applyBundleMigrations(target, input.migrations, log);
|
|
2178
|
+
phase = "migrated";
|
|
2179
|
+
await step("switch");
|
|
2180
|
+
const resources = {
|
|
2181
|
+
...state.resources,
|
|
2182
|
+
...await provisionResources(
|
|
2183
|
+
api,
|
|
2184
|
+
state.accountId,
|
|
2185
|
+
neededResources(target.manifest, state.gatekeepers, state).filter(
|
|
2186
|
+
(r) => r.placeholder && !(r.placeholder.slice(1) in state.resources)
|
|
2187
|
+
),
|
|
2188
|
+
log,
|
|
2189
|
+
state.resourceNames
|
|
2190
|
+
)
|
|
2191
|
+
};
|
|
2192
|
+
const gateway = await provisionAiGateway({
|
|
2193
|
+
api,
|
|
2194
|
+
manifest: target.manifest,
|
|
2195
|
+
state: { ...state, resources },
|
|
2196
|
+
...suppliedGatewayToken(input.secrets),
|
|
2197
|
+
log
|
|
2198
|
+
});
|
|
2199
|
+
const switched = {
|
|
2200
|
+
...state,
|
|
2201
|
+
resources,
|
|
2202
|
+
vars: gateway.vars,
|
|
2203
|
+
...gateway.state
|
|
2204
|
+
};
|
|
2205
|
+
await deployWorkers({
|
|
2206
|
+
api,
|
|
2207
|
+
bundle: target,
|
|
2208
|
+
state: switched,
|
|
2209
|
+
secrets: mergeSecrets(input.secrets ?? {}, gateway.secrets),
|
|
2210
|
+
log
|
|
2211
|
+
});
|
|
2212
|
+
phase = "switched";
|
|
2213
|
+
await step("smoke");
|
|
2214
|
+
await input.smoke(state.hostname, target.manifest.version);
|
|
2215
|
+
const next = {
|
|
2216
|
+
...switched,
|
|
2217
|
+
version: target.manifest.version,
|
|
2218
|
+
...input.targetDigest ? { bundleDigest: input.targetDigest } : {},
|
|
2219
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2220
|
+
};
|
|
2221
|
+
await writeDeploymentState(api, databaseId, next);
|
|
2222
|
+
outcome.status = "succeeded";
|
|
2223
|
+
await retireGatewayToken(api, state.accountId, gateway.retiredTokenId, log);
|
|
2224
|
+
} catch (error) {
|
|
2225
|
+
outcome.error = error.message;
|
|
2226
|
+
log(`update failed: ${outcome.error}`);
|
|
2227
|
+
if (outcome.bookmark) {
|
|
2228
|
+
await step("rollback");
|
|
2229
|
+
try {
|
|
2230
|
+
if (phase === "switched" || phase === "migrated") {
|
|
2231
|
+
const previous = await input.previous();
|
|
2232
|
+
if (previous) {
|
|
2233
|
+
await deployWorkers({ api, bundle: previous, state, secrets: {}, log });
|
|
2234
|
+
} else if (phase === "switched") {
|
|
2235
|
+
throw new Error("the previous release's bundle is not available to redeploy");
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
await api.d1Restore(state.accountId, databaseId, outcome.bookmark);
|
|
2239
|
+
outcome.status = "rolled_back";
|
|
2240
|
+
await input.onStep?.("restored", outcome);
|
|
2241
|
+
} catch (rollbackError) {
|
|
2242
|
+
outcome.rollbackError = rollbackError.message;
|
|
2243
|
+
log(`rollback failed: ${outcome.rollbackError}`);
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
} finally {
|
|
2247
|
+
try {
|
|
2248
|
+
await step("resume");
|
|
2249
|
+
await automations.resume();
|
|
2250
|
+
} catch (error) {
|
|
2251
|
+
log(`could not resume automations: ${error.message}`);
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
await input.onStep?.("done", outcome);
|
|
2255
|
+
return outcome;
|
|
2256
|
+
}
|
|
2257
|
+
async function runRollback(input) {
|
|
2258
|
+
const automations = input.automations ?? noAutomationControl;
|
|
2259
|
+
const log = input.log ?? (() => {
|
|
2260
|
+
});
|
|
2261
|
+
await automations.pause();
|
|
2262
|
+
try {
|
|
2263
|
+
log(`redeploying ${input.previous.manifest.version}\u2026`);
|
|
2264
|
+
await deployWorkers({
|
|
2265
|
+
api: input.api,
|
|
2266
|
+
bundle: input.previous,
|
|
2267
|
+
state: input.state,
|
|
2268
|
+
secrets: {},
|
|
2269
|
+
log
|
|
2270
|
+
});
|
|
2271
|
+
if (input.bookmark) {
|
|
2272
|
+
log("restoring the database bookmark\u2026");
|
|
2273
|
+
await input.api.d1Restore(input.state.accountId, input.databaseId, input.bookmark);
|
|
2274
|
+
}
|
|
2275
|
+
await writeDeploymentState(input.api, input.databaseId, {
|
|
2276
|
+
...input.state,
|
|
2277
|
+
version: input.previous.manifest.version,
|
|
2278
|
+
...input.previousDigest ? { bundleDigest: input.previousDigest } : {},
|
|
2279
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2280
|
+
});
|
|
2281
|
+
} finally {
|
|
2282
|
+
await automations.resume();
|
|
2283
|
+
}
|
|
2284
|
+
return { version: input.previous.manifest.version, restoredBookmark: input.bookmark };
|
|
2285
|
+
}
|
|
2286
|
+
async function healthSmoke(hostname, version, options = {}) {
|
|
2287
|
+
const doFetch = options.fetch ?? fetch;
|
|
2288
|
+
const attempts = options.attempts ?? 20;
|
|
2289
|
+
let last = "no response";
|
|
2290
|
+
for (let i = 0; i < attempts; i++) {
|
|
2291
|
+
try {
|
|
2292
|
+
const response = await doFetch(`${options.origin ?? `https://${hostname}`}/api/health`, {
|
|
2293
|
+
headers: { "cache-control": "no-cache" }
|
|
2294
|
+
});
|
|
2295
|
+
const body = await response.json();
|
|
2296
|
+
if (response.ok && body.status === "ok" && body.version === version && body.migrations?.upToDate !== false) {
|
|
2297
|
+
return;
|
|
2298
|
+
}
|
|
2299
|
+
last = `status ${body.status}, version ${body.version}`;
|
|
2300
|
+
} catch (error) {
|
|
2301
|
+
last = error.message;
|
|
2302
|
+
}
|
|
2303
|
+
if (options.delayMs !== 0) await new Promise((r) => setTimeout(r, options.delayMs ?? 3e3));
|
|
2304
|
+
}
|
|
2305
|
+
throw new Error(`smoke check failed for ${hostname}: ${last}`);
|
|
2306
|
+
}
|
|
2307
|
+
|
|
2308
|
+
export {
|
|
2309
|
+
sha256Hex,
|
|
2310
|
+
toHex,
|
|
2311
|
+
toBase64,
|
|
2312
|
+
assetHash,
|
|
2313
|
+
openBundle,
|
|
2314
|
+
releaseAssetNames,
|
|
2315
|
+
CHANNELS,
|
|
2316
|
+
isVersion,
|
|
2317
|
+
compareVersions,
|
|
2318
|
+
listReleases,
|
|
2319
|
+
getRelease,
|
|
2320
|
+
VerificationError,
|
|
2321
|
+
verifyBundleBytes,
|
|
2322
|
+
CloudflareClient,
|
|
2323
|
+
d1ApiMigrations,
|
|
2324
|
+
applyBundleMigrations,
|
|
2325
|
+
writeDeploymentState,
|
|
2326
|
+
neededResources,
|
|
2327
|
+
provisionResources,
|
|
2328
|
+
databaseIdOf,
|
|
2329
|
+
contentTypeOf,
|
|
2330
|
+
deployWorkers,
|
|
2331
|
+
workersDevHostname,
|
|
2332
|
+
GATEWAY_TOKEN_SECRET,
|
|
2333
|
+
MODEL_ROLES_VAR,
|
|
2334
|
+
JUDGE_GATEWAY_PROVIDER,
|
|
2335
|
+
JUDGE_BYOK_VAR,
|
|
2336
|
+
varWorkers,
|
|
2337
|
+
withDeploymentVar,
|
|
2338
|
+
withByokProvider,
|
|
2339
|
+
gatewayProviderSlug,
|
|
2340
|
+
provisionAiGateway,
|
|
2341
|
+
retireGatewayToken,
|
|
2342
|
+
mergeSecrets,
|
|
2343
|
+
locateDeployment,
|
|
2344
|
+
installedExtensionsViaApi,
|
|
2345
|
+
appliedMigrationsViaApi,
|
|
2346
|
+
saveRunViaApi,
|
|
2347
|
+
runsViaApi,
|
|
2348
|
+
rollbackTarget,
|
|
2349
|
+
newRunId,
|
|
2350
|
+
preflight,
|
|
2351
|
+
fetchVerifiedRelease,
|
|
2352
|
+
fetchReleaseManifest,
|
|
2353
|
+
killSwitchControl,
|
|
2354
|
+
apiKillSwitchStore,
|
|
2355
|
+
runUpdate,
|
|
2356
|
+
runRollback,
|
|
2357
|
+
healthSmoke
|
|
2358
|
+
};
|