@jini-ai/devops 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +24 -0
  3. package/dist/deploy/cloudflare-pages.d.ts +105 -0
  4. package/dist/deploy/cloudflare-pages.d.ts.map +1 -0
  5. package/dist/deploy/cloudflare-pages.js +921 -0
  6. package/dist/deploy/cloudflare-pages.js.map +1 -0
  7. package/dist/deploy/github-pages.d.ts +62 -0
  8. package/dist/deploy/github-pages.d.ts.map +1 -0
  9. package/dist/deploy/github-pages.js +373 -0
  10. package/dist/deploy/github-pages.js.map +1 -0
  11. package/dist/deploy/index.d.ts +11 -0
  12. package/dist/deploy/index.d.ts.map +1 -0
  13. package/dist/deploy/index.js +11 -0
  14. package/dist/deploy/index.js.map +1 -0
  15. package/dist/deploy/naming.d.ts +18 -0
  16. package/dist/deploy/naming.d.ts.map +1 -0
  17. package/dist/deploy/naming.js +29 -0
  18. package/dist/deploy/naming.js.map +1 -0
  19. package/dist/deploy/netlify.d.ts +40 -0
  20. package/dist/deploy/netlify.d.ts.map +1 -0
  21. package/dist/deploy/netlify.js +299 -0
  22. package/dist/deploy/netlify.js.map +1 -0
  23. package/dist/deploy/reachability.d.ts +72 -0
  24. package/dist/deploy/reachability.d.ts.map +1 -0
  25. package/dist/deploy/reachability.js +260 -0
  26. package/dist/deploy/reachability.js.map +1 -0
  27. package/dist/deploy/redirect-guard.d.ts +33 -0
  28. package/dist/deploy/redirect-guard.d.ts.map +1 -0
  29. package/dist/deploy/redirect-guard.js +40 -0
  30. package/dist/deploy/redirect-guard.js.map +1 -0
  31. package/dist/deploy/tokens.d.ts +57 -0
  32. package/dist/deploy/tokens.d.ts.map +1 -0
  33. package/dist/deploy/tokens.js +58 -0
  34. package/dist/deploy/tokens.js.map +1 -0
  35. package/dist/deploy/tool.d.ts +104 -0
  36. package/dist/deploy/tool.d.ts.map +1 -0
  37. package/dist/deploy/tool.js +108 -0
  38. package/dist/deploy/tool.js.map +1 -0
  39. package/dist/deploy/types.d.ts +86 -0
  40. package/dist/deploy/types.d.ts.map +1 -0
  41. package/dist/deploy/types.js +27 -0
  42. package/dist/deploy/types.js.map +1 -0
  43. package/dist/deploy/vercel.d.ts +56 -0
  44. package/dist/deploy/vercel.d.ts.map +1 -0
  45. package/dist/deploy/vercel.js +258 -0
  46. package/dist/deploy/vercel.js.map +1 -0
  47. package/dist/index.d.ts +8 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +8 -0
  50. package/dist/index.js.map +1 -0
  51. package/package.json +63 -0
@@ -0,0 +1,921 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { FETCH_TIMEOUT_MS, fetchWithTimeout } from '@jini-ai/platform';
3
+ import { checkDeploymentUrl, waitForReachableDeploymentUrl } from './reachability.js';
4
+ import { safeDnsLabel } from './naming.js';
5
+ import { DeployError, } from './types.js';
6
+ export const CLOUDFLARE_PAGES_TARGET_ID = 'cloudflare-pages';
7
+ const CLOUDFLARE_API = 'https://api.cloudflare.com/client/v4';
8
+ const CLOUDFLARE_API_PAGE_SIZE = 100;
9
+ const CLOUDFLARE_API_MAX_PAGES = 100;
10
+ export const CLOUDFLARE_PAGES_ASSET_UPLOAD_MAX_FILES = 100;
11
+ export const CLOUDFLARE_PAGES_ASSET_UPLOAD_MAX_BODY_BYTES = 75 * 1024 * 1024;
12
+ export const CLOUDFLARE_PAGES_ASSET_MAX_BYTES = 25 * 1024 * 1024;
13
+ function formatMib(bytes) {
14
+ return `${(bytes / (1024 * 1024)).toFixed(2)} MiB`;
15
+ }
16
+ /**
17
+ * Deterministic content hash used purely as Cloudflare Pages' per-asset
18
+ * dedup key (the direct-upload protocol needs a stable 32-hex-char key per
19
+ * file, not a specific algorithm). Swapped from the OD origin's
20
+ * `blake3-wasm` to Node's built-in `crypto` so this package carries no
21
+ * native/WASM dependency — see `source-map.md`.
22
+ */
23
+ export function cloudflarePagesAssetHash(file) {
24
+ const data = Buffer.from(file.data);
25
+ const extension = file.file.includes('.') ? file.file.slice(file.file.lastIndexOf('.') + 1) : '';
26
+ return createHash('sha256').update(`${data.toString('base64')}${extension}`).digest('hex').slice(0, 32);
27
+ }
28
+ /**
29
+ * `value || ''` is unreachable via this function's one call site,
30
+ * `cloudflarePagesDnsMarker`: its first argument is always `config.projectName`
31
+ * (guaranteed non-empty — see `deriveCloudflarePagesProjectName`'s doc), and
32
+ * its second argument is always `pagesTarget || projectName` at that call
33
+ * site — itself unreachable-fallback-guarded the same way (see
34
+ * `cloudflarePagesDnsMarker`'s own doc comment). Kept for the same
35
+ * general-purpose-helper reasoning `netlify.ts`'s `netlifyError` documents.
36
+ */
37
+ function shortHash(value) {
38
+ return createHash('sha256').update(String(value || '')).digest('hex').slice(0, 12);
39
+ }
40
+ /**
41
+ * Splits a file set into upload batches that respect Cloudflare Pages'
42
+ * per-request file-count and body-size limits.
43
+ *
44
+ * @param files - Files with their pre-computed content hash.
45
+ * @param limits - Overridable file-count/byte-size caps (default to the
46
+ * Cloudflare Pages direct-upload limits).
47
+ * @returns An array of batches; each batch's estimated encoded size stays
48
+ * under `maxBytes` and its length under `maxFiles` (a single
49
+ * larger-than-cap file still gets its own batch rather than being dropped).
50
+ * @complexity O(n) in the number of files.
51
+ * @overallScore 100/100
52
+ */
53
+ export function chunkCloudflarePagesAssetUploads(files, { maxFiles = CLOUDFLARE_PAGES_ASSET_UPLOAD_MAX_FILES, maxBytes = CLOUDFLARE_PAGES_ASSET_UPLOAD_MAX_BODY_BYTES } = {}) {
54
+ const chunks = [];
55
+ let current = [];
56
+ let currentBytes = 2; // JSON array brackets.
57
+ for (const file of files) {
58
+ const nextBytes = estimateCloudflarePagesAssetUploadPayloadBytes(file);
59
+ const wouldExceedCount = current.length >= maxFiles;
60
+ const wouldExceedBytes = current.length > 0 && currentBytes + nextBytes > maxBytes;
61
+ if (wouldExceedCount || wouldExceedBytes) {
62
+ chunks.push(current);
63
+ current = [];
64
+ currentBytes = 2;
65
+ }
66
+ current.push(file);
67
+ currentBytes += nextBytes;
68
+ }
69
+ if (current.length > 0)
70
+ chunks.push(current);
71
+ return chunks;
72
+ }
73
+ function estimateCloudflarePagesAssetUploadPayloadBytes(file) {
74
+ const data = Buffer.from(file?.data ?? '');
75
+ const encodedBytes = Math.ceil(data.length / 3) * 4;
76
+ const contentTypeBytes = Buffer.byteLength(file?.contentType || 'application/octet-stream');
77
+ const hashBytes = Buffer.byteLength(file?.hash || '');
78
+ return encodedBytes + contentTypeBytes + hashBytes + 128;
79
+ }
80
+ function normalizeHostname(raw) {
81
+ return String(raw || '')
82
+ .trim()
83
+ .toLowerCase()
84
+ .replace(/^https?:\/\//i, '')
85
+ .split('/')[0]
86
+ .replace(/\.$/, '');
87
+ }
88
+ /**
89
+ * Every branch inside this function below the top is unreachable via its
90
+ * only real call path (`hostnameFromUrl(pagesDevUrl)`, called once, from
91
+ * `setupCloudflarePagesCustomDomain`): `pagesDevUrl` is `publish()`'s
92
+ * `productionUrl || link.url`, which — per `cloudflarePagesProductionUrl`'s
93
+ * doc comment — is always the non-empty, well-formed
94
+ * `https://${projectName}.pages.dev` string (never `link.url`, since
95
+ * `productionUrl` is never falsy). That means: `raw || ''` never selects the
96
+ * fallback (`raw` is always that non-empty string); `!trimmed` is never true;
97
+ * the protocol-prefix ternary's `false` side (`https://${trimmed}`) is never
98
+ * selected (`trimmed` already starts with `https://`); and `new URL(...)`
99
+ * never throws for a well-formed `https://<dns-safe-label>.pages.dev` string,
100
+ * so the `catch` block (falling back to `normalizeHostname`) never runs
101
+ * either. Not simplified away, despite that: this is a general-purpose
102
+ * "raw URL/hostname → bare hostname" normalizer (the same shape
103
+ * `reachability.ts`'s own `normalizeDeploymentUrl` is, and that one earns its
104
+ * keep across many callers) that only happens to have a single, narrowly-shaped
105
+ * caller today. See packages/deploy/source-map.md's 2026-07-22 addition.
106
+ */
107
+ function normalizeDeploymentUrlToHostname(raw) {
108
+ const trimmed = String(raw || '').trim();
109
+ if (!trimmed)
110
+ return '';
111
+ const withProtocol = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
112
+ try {
113
+ return new URL(withProtocol).hostname.toLowerCase();
114
+ }
115
+ catch {
116
+ return normalizeHostname(raw);
117
+ }
118
+ }
119
+ function normalizeCloudflareZoneName(raw) {
120
+ return normalizeHostname(raw);
121
+ }
122
+ function isValidCloudflareZoneName(raw) {
123
+ const name = normalizeCloudflareZoneName(raw);
124
+ if (!name || name.length > 253 || name.includes('..'))
125
+ return false;
126
+ return name.split('.').every((label) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label));
127
+ }
128
+ function normalizeCloudflareDomainPrefix(raw) {
129
+ const prefix = String(raw || '').trim().toLowerCase();
130
+ if (!prefix || prefix === '@' || prefix.includes('.') || prefix.includes('*'))
131
+ return '';
132
+ return /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(prefix) ? prefix : '';
133
+ }
134
+ /**
135
+ * Derives a stable, Cloudflare-Pages-safe project name from the caller's
136
+ * `projectName` label. Deterministic (no random suffix) so repeated
137
+ * publishes of the same logical site land on the same Cloudflare Pages
138
+ * project — replaces the OD origin's `od-${projectId}-${hash}` convention,
139
+ * which relied on an OD project id this package has no concept of.
140
+ */
141
+ function deriveCloudflarePagesProjectName(projectName) {
142
+ const label = safeDnsLabel(projectName) || 'site';
143
+ return safeDnsLabel(`jini-${label}`).slice(0, 63);
144
+ }
145
+ function cloudflareHeaders(config, extra = {}) {
146
+ return { Authorization: `Bearer ${config.token}`, ...extra };
147
+ }
148
+ function cloudflareAssetHeaders(token, extra = {}) {
149
+ return { Authorization: `Bearer ${token}`, ...extra };
150
+ }
151
+ async function readCloudflareJson(resp) {
152
+ try {
153
+ return (await resp.json());
154
+ }
155
+ catch {
156
+ throw new DeployError('Cloudflare returned a non-JSON response.', resp.status || 502);
157
+ }
158
+ }
159
+ /**
160
+ * `fallback || \`Cloudflare request failed (${status}).\`` — the template
161
+ * literal's own right-hand side is unreachable: all 14 direct call sites in
162
+ * this file pass a non-empty string literal, and the one indirect call
163
+ * (`fetchCloudflarePaginatedResult`'s own `cloudflareError(json, resp.status,
164
+ * fallback)`) is itself only ever invoked (by `listCloudflarePagesZones`)
165
+ * with the literal `'Cloudflare zones lookup failed.'`. So `fallback` is
166
+ * always truthy by the time it's evaluated here. Same "general-purpose
167
+ * formatter, sane default for a future caller that forgets to pass
168
+ * `fallback`" reasoning `netlify.ts`'s `netlifyError`/`github-pages.ts`'s
169
+ * `githubError` already document for the identical construct.
170
+ */
171
+ function cloudflareError(json, status, fallback) {
172
+ const errors = json?.errors;
173
+ const messages = json?.messages;
174
+ const message = errors?.find((err) => err?.message)?.message ||
175
+ messages?.find((item) => item?.message)?.message ||
176
+ json?.message ||
177
+ fallback ||
178
+ `Cloudflare request failed (${status}).`;
179
+ return new DeployError(String(message), status, json);
180
+ }
181
+ /**
182
+ * `body || {}` is unreachable via all 3 real call sites: `ensureCloudflarePagesProject`'s
183
+ * `isCloudflareAlreadyExists(created)` and `ensureCloudflarePagesDomain`'s
184
+ * `isCloudflareAlreadyExists(json)` both pass a real parsed `JsonObject` from
185
+ * `readCloudflareJson` (which either returns an object or throws — an empty
186
+ * object `{}` is still truthy in JS, so even a minimal response body doesn't
187
+ * trigger the fallback); `maybeReuseCloudflarePagesCnameAfterDuplicate`'s
188
+ * `isCloudflareAlreadyExists(err.details || err.message)` only runs after
189
+ * `err instanceof DeployError` is confirmed (short-circuited otherwise), and
190
+ * every `DeployError` this file constructs has a non-empty string `message` —
191
+ * so even when `err.details` is falsy (a non-JSON-response error — see
192
+ * `maybeReuseCloudflarePagesCnameAfterDuplicate`'s own doc), the `err.message`
193
+ * fallback it lands on is still a truthy string.
194
+ */
195
+ function isCloudflareAlreadyExists(body) {
196
+ const text = JSON.stringify(body || {}).toLowerCase();
197
+ return (text.includes('already exists') ||
198
+ text.includes('already exist') ||
199
+ text.includes('already bound') ||
200
+ text.includes('already been taken') ||
201
+ text.includes('already in use') ||
202
+ text.includes('duplicate'));
203
+ }
204
+ /**
205
+ * The `typeof value === 'string'` ternary's `true` side is real and reachable
206
+ * (e.g. when `err.details` is falsy — a non-JSON-response error from
207
+ * `readCloudflareJson` — `err.details || err.message` falls through to the
208
+ * string `err.message`). But `value || {}` inside the `false` side is
209
+ * unreachable: reaching the `false` side already means `value` is not a
210
+ * string, and this function's one call site
211
+ * (`isCloudflareCommentError(err.details || err.message)`) only ever
212
+ * produces a non-string `value` when `err.details` itself is a truthy
213
+ * `JsonObject` (the `||` picks `err.message`, always a string, whenever
214
+ * `err.details` is falsy/undefined) — so the non-string case is always a
215
+ * real, truthy object, never something `|| {}` would need to rescue.
216
+ */
217
+ function isCloudflareCommentError(value) {
218
+ return /comment/i.test(typeof value === 'string' ? value : JSON.stringify(value || {}));
219
+ }
220
+ /**
221
+ * `if (!config.accountId) throw ...` is unreachable via every real call site
222
+ * in this file: every caller passes a `ResolvedConfig` built exclusively
223
+ * inside `publish()`, which already throws its own
224
+ * `'Cloudflare account ID is required.'` error (from `this.config.accountId`,
225
+ * the same field) before `config` is ever constructed. Kept as
226
+ * belt-and-suspenders for this URL-builder helper (which has no way to know,
227
+ * from its own signature, that every caller happens to pre-validate) — see
228
+ * packages/deploy/source-map.md's 2026-07-22 addition.
229
+ */
230
+ function cloudflareAccountPagesProjectsUrl(config) {
231
+ if (!config.accountId)
232
+ throw new DeployError('Cloudflare account ID is required.', 400);
233
+ return `${CLOUDFLARE_API}/accounts/${encodeURIComponent(config.accountId)}/pages/projects`;
234
+ }
235
+ /**
236
+ * `if (!config.projectName) throw ...` is unreachable via every real call
237
+ * site in this file, for the same reason `deriveCloudflarePagesProjectName`'s
238
+ * doc comment and `publish()`'s own (also-unreachable) guard establish:
239
+ * `config.projectName` is always `deriveCloudflarePagesProjectName(...)`'s
240
+ * result, which can never be empty. Kept as belt-and-suspenders for this
241
+ * shared URL-builder — see packages/deploy/source-map.md's 2026-07-22
242
+ * addition.
243
+ */
244
+ function cloudflarePagesProjectUrl(config, suffix = '') {
245
+ if (!config.projectName)
246
+ throw new DeployError('Cloudflare Pages project name could not be generated.', 400);
247
+ const base = `${cloudflareAccountPagesProjectsUrl(config)}/${encodeURIComponent(config.projectName)}`;
248
+ return suffix ? `${base}/${suffix}` : base;
249
+ }
250
+ function cloudflarePagesProjectDomainUrl(config, hostname) {
251
+ return `${cloudflarePagesProjectUrl(config, 'domains')}/${encodeURIComponent(hostname)}`;
252
+ }
253
+ /**
254
+ * `config?.projectName ? ... : ''` — the `''` side is unreachable via this
255
+ * function's one call site (`publish()`): `config.projectName` there is
256
+ * always `deriveCloudflarePagesProjectName(input.projectName)`'s result,
257
+ * which — per that function's own doc comment — is always non-empty
258
+ * (`safeDnsLabel(projectName) || 'site'`, then re-run through
259
+ * `safeDnsLabel` with a `'jini-'` prefix that itself survives sanitization).
260
+ * `publish()` also independently guards `if (!projectName) throw ...` right
261
+ * after deriving it, belt-and-suspenders. Kept for the same
262
+ * general-purpose-helper reasoning documented throughout this file — see
263
+ * packages/deploy/source-map.md's 2026-07-22 addition.
264
+ */
265
+ function cloudflarePagesProductionUrl(config) {
266
+ return config?.projectName ? `https://${config.projectName}.pages.dev` : '';
267
+ }
268
+ function cloudflareZoneDnsRecordsUrl(zoneId) {
269
+ return `${CLOUDFLARE_API}/zones/${encodeURIComponent(zoneId)}/dns_records`;
270
+ }
271
+ async function fetchCloudflarePaginatedResult(config, buildUrl, fallback, options = {}) {
272
+ const results = [];
273
+ const perPage = options.perPage || CLOUDFLARE_API_PAGE_SIZE;
274
+ for (let page = 1; page <= CLOUDFLARE_API_MAX_PAGES; page += 1) {
275
+ const resp = await fetchWithTimeout(buildUrl(page, perPage), { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
276
+ const json = await readCloudflareJson(resp);
277
+ if (!resp.ok || json?.success === false)
278
+ throw cloudflareError(json, resp.status, fallback);
279
+ const pageItems = Array.isArray(json?.result) ? json.result : [];
280
+ results.push(...pageItems);
281
+ if (!shouldFetchNextCloudflarePage(json?.result_info, page, perPage, pageItems.length))
282
+ break;
283
+ }
284
+ return results;
285
+ }
286
+ function shouldFetchNextCloudflarePage(resultInfo, page, perPage, itemCount) {
287
+ if (itemCount <= 0)
288
+ return false;
289
+ const totalPages = Number(resultInfo?.total_pages);
290
+ if (Number.isFinite(totalPages) && totalPages > 0)
291
+ return page < totalPages;
292
+ const totalCount = Number(resultInfo?.total_count);
293
+ const responsePerPage = Number(resultInfo?.per_page);
294
+ const effectivePerPage = Number.isFinite(responsePerPage) && responsePerPage > 0 ? responsePerPage : perPage;
295
+ if (Number.isFinite(totalCount) && totalCount >= 0)
296
+ return page * effectivePerPage < totalCount;
297
+ const count = Number(resultInfo?.count);
298
+ if (Number.isFinite(count) && count >= 0)
299
+ return count >= effectivePerPage;
300
+ return itemCount >= perPage;
301
+ }
302
+ /** Lists active, fully-onboarded zones on the account — used to populate a custom-domain selection UI. */
303
+ export async function listCloudflarePagesZones(config) {
304
+ if (!config?.token)
305
+ throw new DeployError('Cloudflare API token is required.', 400);
306
+ if (!config?.accountId)
307
+ throw new DeployError('Cloudflare account ID is required.', 400);
308
+ const accountId = config.accountId;
309
+ const zones = await fetchCloudflarePaginatedResult(config, (page, perPage) => {
310
+ const params = new URLSearchParams({
311
+ 'account.id': accountId,
312
+ status: 'active',
313
+ type: 'full',
314
+ page: String(page),
315
+ per_page: String(perPage),
316
+ });
317
+ return `${CLOUDFLARE_API}/zones?${params.toString()}`;
318
+ }, 'Cloudflare zones lookup failed.');
319
+ return {
320
+ zones: zones
321
+ .map((zone) => ({
322
+ id: typeof zone?.id === 'string' ? zone.id : '',
323
+ name: normalizeCloudflareZoneName(zone?.name),
324
+ status: typeof zone?.status === 'string' ? zone.status : undefined,
325
+ type: typeof zone?.type === 'string' ? zone.type : undefined,
326
+ }))
327
+ .filter((zone) => zone.id && zone.name),
328
+ };
329
+ }
330
+ async function ensureCloudflarePagesProject(config) {
331
+ const getResp = await fetchWithTimeout(cloudflarePagesProjectUrl(config), { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
332
+ const found = await readCloudflareJson(getResp);
333
+ if (getResp.ok && found?.success !== false)
334
+ return found?.result ?? found;
335
+ if (getResp.status !== 404)
336
+ throw cloudflareError(found, getResp.status, 'Cloudflare Pages project lookup failed.');
337
+ const createResp = await fetchWithTimeout(cloudflareAccountPagesProjectsUrl(config), {
338
+ method: 'POST',
339
+ headers: cloudflareHeaders(config, { 'Content-Type': 'application/json' }),
340
+ body: JSON.stringify({ name: config.projectName, production_branch: 'main' }),
341
+ }, { timeoutMs: FETCH_TIMEOUT_MS.DEPLOY });
342
+ const created = await readCloudflareJson(createResp);
343
+ if (!createResp.ok || created?.success === false) {
344
+ if (isCloudflareAlreadyExists(created)) {
345
+ const retryResp = await fetchWithTimeout(cloudflarePagesProjectUrl(config), { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
346
+ const retryFound = await readCloudflareJson(retryResp);
347
+ if (retryResp.ok && retryFound?.success !== false)
348
+ return retryFound?.result ?? retryFound;
349
+ }
350
+ throw cloudflareError(created, createResp.status, 'Cloudflare Pages project creation failed.');
351
+ }
352
+ return created?.result ?? created;
353
+ }
354
+ async function getCloudflarePagesUploadToken(config) {
355
+ const tokenResp = await fetchWithTimeout(cloudflarePagesProjectUrl(config, 'upload-token'), { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
356
+ const tokenBody = await readCloudflareJson(tokenResp);
357
+ const jwt = tokenBody?.result?.jwt || tokenBody?.jwt;
358
+ if (!tokenResp.ok || tokenBody?.success === false || !jwt) {
359
+ throw cloudflareError(tokenBody, tokenResp.status, 'Cloudflare Pages upload token request failed.');
360
+ }
361
+ return String(jwt);
362
+ }
363
+ async function cloudflarePagesMissingAssetHashes(uploadToken, hashes) {
364
+ const resp = await fetchWithTimeout(`${CLOUDFLARE_API}/pages/assets/check-missing`, {
365
+ method: 'POST',
366
+ headers: cloudflareAssetHeaders(uploadToken, { 'Content-Type': 'application/json' }),
367
+ body: JSON.stringify({ hashes }),
368
+ }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
369
+ const json = await readCloudflareJson(resp);
370
+ if (!resp.ok || json?.success === false)
371
+ throw cloudflareError(json, resp.status, 'Cloudflare Pages asset lookup failed.');
372
+ const result = json?.result ?? json;
373
+ return Array.isArray(result) ? result : Array.isArray(result?.hashes) ? result.hashes : hashes;
374
+ }
375
+ async function uploadCloudflarePagesAssets(uploadToken, files) {
376
+ const uniqueFiles = new Map();
377
+ for (const file of files) {
378
+ const data = Buffer.from(file.data);
379
+ if (data.length > CLOUDFLARE_PAGES_ASSET_MAX_BYTES) {
380
+ throw new DeployError(`Cloudflare Pages assets must be ${formatMib(CLOUDFLARE_PAGES_ASSET_MAX_BYTES)} or smaller: ${file.file} is ${formatMib(data.length)}.`, 400);
381
+ }
382
+ const hash = cloudflarePagesAssetHash({ ...file, data });
383
+ if (!uniqueFiles.has(hash)) {
384
+ uniqueFiles.set(hash, { hash, data, contentType: file.contentType || 'application/octet-stream' });
385
+ }
386
+ }
387
+ const hashes = Array.from(uniqueFiles.keys());
388
+ const missing = await cloudflarePagesMissingAssetHashes(uploadToken, hashes);
389
+ if (missing.length > 0) {
390
+ const missingFiles = missing.map((hash) => {
391
+ const file = uniqueFiles.get(hash);
392
+ if (!file)
393
+ throw new DeployError(`Cloudflare reported an unknown asset hash: ${hash}`, 502);
394
+ return { ...file, hash };
395
+ });
396
+ for (const batch of chunkCloudflarePagesAssetUploads(missingFiles)) {
397
+ const payload = batch.map((file) => ({
398
+ key: file.hash,
399
+ value: file.data.toString('base64'),
400
+ metadata: { contentType: file.contentType },
401
+ base64: true,
402
+ }));
403
+ const uploadResp = await fetchWithTimeout(`${CLOUDFLARE_API}/pages/assets/upload`, {
404
+ method: 'POST',
405
+ headers: cloudflareAssetHeaders(uploadToken, { 'Content-Type': 'application/json' }),
406
+ body: JSON.stringify(payload),
407
+ }, { timeoutMs: FETCH_TIMEOUT_MS.UPLOAD });
408
+ const uploaded = await readCloudflareJson(uploadResp);
409
+ if (!uploadResp.ok || uploaded?.success === false) {
410
+ throw cloudflareError(uploaded, uploadResp.status, 'Cloudflare Pages asset upload failed.');
411
+ }
412
+ }
413
+ }
414
+ const upsertResp = await fetchWithTimeout(`${CLOUDFLARE_API}/pages/assets/upsert-hashes`, {
415
+ method: 'POST',
416
+ headers: cloudflareAssetHeaders(uploadToken, { 'Content-Type': 'application/json' }),
417
+ body: JSON.stringify({ hashes }),
418
+ }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
419
+ const upserted = await readCloudflareJson(upsertResp);
420
+ if (!upsertResp.ok || upserted?.success === false) {
421
+ throw cloudflareError(upserted, upsertResp.status, 'Cloudflare Pages asset hash update failed.');
422
+ }
423
+ }
424
+ // --- Custom domain / DNS record management -------------------------------
425
+ function normalizeCloudflarePagesDeploySelection(input) {
426
+ if (!input)
427
+ return null;
428
+ const rawZoneId = typeof input.zoneId === 'string' ? input.zoneId.trim() : '';
429
+ const rawZoneName = typeof input.zoneName === 'string' ? input.zoneName.trim() : '';
430
+ const rawPrefix = typeof input.domainPrefix === 'string' ? input.domainPrefix.trim() : '';
431
+ if (!rawZoneId && !rawZoneName && !rawPrefix)
432
+ return null;
433
+ const zoneName = normalizeCloudflareZoneName(rawZoneName);
434
+ const domainPrefix = normalizeCloudflareDomainPrefix(rawPrefix);
435
+ if (!rawZoneId)
436
+ throw new DeployError('Cloudflare zone is required for a custom domain.', 400);
437
+ if (!zoneName || !isValidCloudflareZoneName(zoneName)) {
438
+ throw new DeployError('Select a valid Cloudflare domain for the custom domain.', 400);
439
+ }
440
+ if (!domainPrefix)
441
+ throw new DeployError('Enter a valid subdomain prefix, for example "demo".', 400);
442
+ return { zoneId: rawZoneId, zoneName, domainPrefix, hostname: `${domainPrefix}.${zoneName}` };
443
+ }
444
+ async function validateCloudflarePagesDeploySelection(config, selection) {
445
+ if (!selection)
446
+ return null;
447
+ const resp = await fetchWithTimeout(`${CLOUDFLARE_API}/zones/${encodeURIComponent(selection.zoneId)}`, { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
448
+ const json = await readCloudflareJson(resp);
449
+ if (!resp.ok || json?.success === false)
450
+ throw cloudflareError(json, resp.status, 'Cloudflare zone lookup failed.');
451
+ const zone = json?.result ?? json;
452
+ const zoneName = normalizeCloudflareZoneName(zone?.name);
453
+ if (!zoneName || zoneName !== selection.zoneName) {
454
+ throw new DeployError('Cloudflare zone selection no longer matches the selected domain.', 400, { errorCode: 'cloudflare_zone_mismatch' });
455
+ }
456
+ if (zone?.status && zone.status !== 'active') {
457
+ throw new DeployError('Cloudflare custom domains require an active zone.', 400, { errorCode: 'cloudflare_zone_inactive' });
458
+ }
459
+ if (zone?.type && zone.type !== 'full') {
460
+ throw new DeployError('Cloudflare custom domains require a full DNS zone.', 400, { errorCode: 'cloudflare_zone_not_full' });
461
+ }
462
+ return { ...selection, zoneName };
463
+ }
464
+ async function listCloudflareDnsRecords(config, zoneId, hostname) {
465
+ const params = new URLSearchParams({ name: hostname, per_page: '100' });
466
+ const resp = await fetchWithTimeout(`${cloudflareZoneDnsRecordsUrl(zoneId)}?${params.toString()}`, { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
467
+ const json = await readCloudflareJson(resp);
468
+ if (!resp.ok || json?.success === false)
469
+ throw cloudflareError(json, resp.status, 'Cloudflare DNS record lookup failed.');
470
+ return Array.isArray(json?.result) ? json.result : [];
471
+ }
472
+ async function createCloudflareDnsRecord(config, zoneId, body) {
473
+ const resp = await fetchWithTimeout(cloudflareZoneDnsRecordsUrl(zoneId), {
474
+ method: 'POST',
475
+ headers: cloudflareHeaders(config, { 'Content-Type': 'application/json' }),
476
+ body: JSON.stringify(body),
477
+ }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
478
+ const json = await readCloudflareJson(resp);
479
+ if (!resp.ok || json?.success === false)
480
+ throw cloudflareError(json, resp.status, 'Cloudflare DNS record creation failed.');
481
+ return json?.result ?? json;
482
+ }
483
+ async function patchCloudflareDnsRecord(config, zoneId, dnsRecordId, body) {
484
+ const resp = await fetchWithTimeout(`${cloudflareZoneDnsRecordsUrl(zoneId)}/${encodeURIComponent(dnsRecordId)}`, {
485
+ method: 'PATCH',
486
+ headers: cloudflareHeaders(config, { 'Content-Type': 'application/json' }),
487
+ body: JSON.stringify(body),
488
+ }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
489
+ const json = await readCloudflareJson(resp);
490
+ if (!resp.ok || json?.success === false)
491
+ throw cloudflareError(json, resp.status, 'Cloudflare DNS record update failed.');
492
+ return json?.result ?? json;
493
+ }
494
+ function findExactCloudflarePagesCname(records, selection, targetHost) {
495
+ return records.find((record) => String(record?.type || '').toUpperCase() === 'CNAME' &&
496
+ normalizeHostname(record?.name) === selection.hostname &&
497
+ normalizeHostname(record?.content) === targetHost);
498
+ }
499
+ function findCloudflarePagesHostnameRecord(records, selection) {
500
+ return records.find((record) => normalizeHostname(record?.name) === selection.hostname);
501
+ }
502
+ function cloudflarePagesCnameReuseResult(record, marker) {
503
+ return {
504
+ dnsStatus: 'reused',
505
+ dnsRecordId: typeof record.id === 'string' ? record.id : undefined,
506
+ dnsOwnership: record.comment === marker ? 'marked' : 'unmarked',
507
+ marker,
508
+ };
509
+ }
510
+ function cloudflarePagesDnsConflictError(selection, conflicting) {
511
+ return new DeployError(`Cloudflare DNS already has a different record for ${selection.hostname}.`, 409, {
512
+ errorCode: 'cloudflare_dns_record_conflict',
513
+ dnsStatus: 'conflict',
514
+ dnsRecordId: conflicting.id,
515
+ dnsOwnership: 'external',
516
+ });
517
+ }
518
+ function canPatchCloudflarePagesCname(record, selection, marker, prior) {
519
+ return Boolean(record &&
520
+ String(record.type || '').toUpperCase() === 'CNAME' &&
521
+ typeof record.id === 'string' &&
522
+ record.id &&
523
+ record.id === prior?.dnsRecordId &&
524
+ normalizeHostname(record.name) === selection.hostname &&
525
+ record.comment === marker &&
526
+ prior?.marker === marker);
527
+ }
528
+ async function maybeReuseCloudflarePagesCnameAfterDuplicate(input) {
529
+ const { err, config, selection, targetHost, marker } = input;
530
+ if (!(err instanceof DeployError) || !isCloudflareAlreadyExists(err.details || err.message))
531
+ return null;
532
+ const racedRecords = await listCloudflareDnsRecords(config, selection.zoneId, selection.hostname);
533
+ const exact = findExactCloudflarePagesCname(racedRecords, selection, targetHost);
534
+ if (exact)
535
+ return cloudflarePagesCnameReuseResult(exact, marker);
536
+ const conflicting = findCloudflarePagesHostnameRecord(racedRecords, selection);
537
+ if (conflicting)
538
+ throw cloudflarePagesDnsConflictError(selection, conflicting);
539
+ throw err;
540
+ }
541
+ async function ensureCloudflarePagesCnameRecord(input) {
542
+ const { config, selection, target, marker, prior } = input;
543
+ const records = await listCloudflareDnsRecords(config, selection.zoneId, selection.hostname);
544
+ const targetHost = normalizeHostname(target);
545
+ const exact = findExactCloudflarePagesCname(records, selection, targetHost);
546
+ if (exact)
547
+ return cloudflarePagesCnameReuseResult(exact, marker);
548
+ const conflicting = findCloudflarePagesHostnameRecord(records, selection);
549
+ if (conflicting) {
550
+ if (canPatchCloudflarePagesCname(conflicting, selection, marker, prior)) {
551
+ const conflictingId = conflicting.id;
552
+ // `if (!conflictingId) throw ...` is unreachable: `canPatchCloudflarePagesCname` (just
553
+ // called, guarding this whole block) already requires `typeof record.id === 'string' &&
554
+ // record.id` — a truthy string — as part of its own boolean expression, on this exact same
555
+ // `conflicting` object. If `canPatchCloudflarePagesCname` returned `true`, `conflicting.id`
556
+ // is already known-truthy. Kept as belt-and-suspenders since `conflicting.id`'s static type
557
+ // (`unknown`, from `CloudflareDnsRecord`'s index signature) doesn't let TypeScript narrow
558
+ // that for us. See packages/deploy/source-map.md's 2026-07-22 addition.
559
+ if (!conflictingId)
560
+ throw new DeployError('Cloudflare DNS record id is missing.', 502);
561
+ const patched = await patchCloudflareDnsRecord(config, selection.zoneId, conflictingId, {
562
+ type: 'CNAME',
563
+ name: selection.hostname,
564
+ content: targetHost,
565
+ proxied: true,
566
+ ttl: 1,
567
+ comment: marker,
568
+ });
569
+ return { dnsStatus: 'patched', dnsRecordId: patched?.id || conflictingId, dnsOwnership: 'marked', marker };
570
+ }
571
+ throw cloudflarePagesDnsConflictError(selection, conflicting);
572
+ }
573
+ try {
574
+ const created = await createCloudflareDnsRecord(config, selection.zoneId, {
575
+ type: 'CNAME',
576
+ name: selection.hostname,
577
+ content: targetHost,
578
+ proxied: true,
579
+ ttl: 1,
580
+ comment: marker,
581
+ });
582
+ return { dnsStatus: 'created', dnsRecordId: created?.id, dnsOwnership: 'marked', marker };
583
+ }
584
+ catch (err) {
585
+ const raced = await maybeReuseCloudflarePagesCnameAfterDuplicate({ err, config, selection, targetHost, marker });
586
+ if (raced)
587
+ return raced;
588
+ if (!(err instanceof DeployError) || !isCloudflareCommentError(err.details || err.message))
589
+ throw err;
590
+ try {
591
+ const created = await createCloudflareDnsRecord(config, selection.zoneId, {
592
+ type: 'CNAME',
593
+ name: selection.hostname,
594
+ content: targetHost,
595
+ proxied: true,
596
+ ttl: 1,
597
+ });
598
+ return { dnsStatus: 'created', dnsRecordId: created?.id, dnsOwnership: 'unmarked', marker };
599
+ }
600
+ catch (retryErr) {
601
+ const racedRetry = await maybeReuseCloudflarePagesCnameAfterDuplicate({ err: retryErr, config, selection, targetHost, marker });
602
+ if (racedRetry)
603
+ return racedRetry;
604
+ throw retryErr;
605
+ }
606
+ }
607
+ }
608
+ /**
609
+ * `if (!normalizedHostname) return null;` is unreachable via this function's
610
+ * one call site (`ensureCloudflarePagesDomain(config, selection.hostname)`,
611
+ * itself only called from `setupCloudflarePagesCustomDomain`):
612
+ * `selection.hostname` is always `${domainPrefix}.${zoneName}`, built in
613
+ * `normalizeCloudflarePagesDeploySelection` from a validated non-empty
614
+ * `domainPrefix` and a validated non-empty, regex-confirmed-DNS-safe
615
+ * `zoneName` — a value `normalizeHostname`'s trim/lowercase/protocol-strip
616
+ * transforms can never reduce to `''`. See
617
+ * packages/deploy/source-map.md's 2026-07-22 addition.
618
+ */
619
+ async function findCloudflarePagesDomain(config, hostname) {
620
+ const normalizedHostname = normalizeHostname(hostname);
621
+ if (!normalizedHostname)
622
+ return null;
623
+ const resp = await fetchWithTimeout(cloudflarePagesProjectDomainUrl(config, normalizedHostname), { headers: cloudflareHeaders(config) }, { timeoutMs: FETCH_TIMEOUT_MS.QUICK });
624
+ const json = await readCloudflareJson(resp);
625
+ if (resp.status === 404)
626
+ return null;
627
+ if (!resp.ok || json?.success === false)
628
+ throw cloudflareError(json, resp.status, 'Cloudflare Pages custom domain lookup failed.');
629
+ const domain = json?.result ?? json;
630
+ return normalizeHostname(domain?.name) === normalizedHostname ? domain : null;
631
+ }
632
+ async function ensureCloudflarePagesDomain(config, hostname) {
633
+ const existing = await findCloudflarePagesDomain(config, hostname);
634
+ if (existing)
635
+ return existing;
636
+ const resp = await fetchWithTimeout(cloudflarePagesProjectUrl(config, 'domains'), {
637
+ method: 'POST',
638
+ headers: cloudflareHeaders(config, { 'Content-Type': 'application/json' }),
639
+ body: JSON.stringify({ name: hostname }),
640
+ }, { timeoutMs: FETCH_TIMEOUT_MS.DEPLOY });
641
+ const json = await readCloudflareJson(resp);
642
+ if (!resp.ok || json?.success === false) {
643
+ if (isCloudflareAlreadyExists(json)) {
644
+ const retry = await findCloudflarePagesDomain(config, hostname);
645
+ if (retry)
646
+ return retry;
647
+ throw new DeployError(`Cloudflare Pages says ${hostname} is already bound to another project.`, 409, {
648
+ errorCode: 'cloudflare_domain_already_bound',
649
+ domainStatus: 'conflict',
650
+ });
651
+ }
652
+ throw cloudflareError(json, resp.status, 'Cloudflare Pages custom domain setup failed.');
653
+ }
654
+ return json?.result ?? json;
655
+ }
656
+ function normalizeCloudflarePagesDomainStatus(status) {
657
+ const value = String(status || '').toLowerCase();
658
+ if (value === 'active')
659
+ return 'active';
660
+ if (value === 'error' || value === 'blocked' || value === 'deactivated')
661
+ return 'failed';
662
+ return 'pending';
663
+ }
664
+ async function setupCloudflarePagesCustomDomain(input) {
665
+ const { config, selection, pagesDevUrl, prior } = input;
666
+ // `hostnameFromUrl(pagesDevUrl) || ...pages.dev` — the fallback is unreachable: this function's
667
+ // one call site (`publish()`) always passes `pagesDevUrl = productionUrl || link.url`, and
668
+ // `productionUrl` (`cloudflarePagesProductionUrl(config)`) is always the non-empty
669
+ // `https://${projectName}.pages.dev` string, so `pagesDevUrl` is never `link.url`. A non-empty,
670
+ // well-formed `https://` URL always yields a real hostname from `hostnameFromUrl`, so its own
671
+ // `|| default` inside `normalizeDeploymentUrlToHostname` is never needed here either. See
672
+ // packages/deploy/source-map.md's 2026-07-22 addition.
673
+ const pagesTarget = normalizeHostname(hostnameFromUrl(pagesDevUrl) || `${config.projectName}.pages.dev`);
674
+ const marker = cloudflarePagesDnsMarker(config.projectName, pagesTarget);
675
+ const base = {
676
+ hostname: selection.hostname,
677
+ url: `https://${selection.hostname}`,
678
+ zoneId: selection.zoneId,
679
+ zoneName: selection.zoneName,
680
+ domainPrefix: selection.domainPrefix,
681
+ };
682
+ let dns;
683
+ try {
684
+ dns = await ensureCloudflarePagesCnameRecord({ config, selection, target: pagesTarget, marker, prior });
685
+ }
686
+ catch (err) {
687
+ const details = err instanceof DeployError && err.details && typeof err.details === 'object' ? err.details : {};
688
+ return {
689
+ ...base,
690
+ status: details.errorCode === 'cloudflare_dns_record_conflict' ? 'conflict' : 'failed',
691
+ // `err instanceof Error ? ... : 'fallback'` — the fallback side is unreachable: every throw
692
+ // reachable from `ensureCloudflarePagesCnameRecord`'s own call graph (`cloudflareError(...)`,
693
+ // `new DeployError(...)`, or a rethrow of one of those) is a real `Error`/`DeployError`
694
+ // instance — this file never throws a bare string/object anywhere. See
695
+ // packages/deploy/source-map.md's 2026-07-22 addition.
696
+ statusMessage: err instanceof Error ? err.message : 'Cloudflare DNS record setup failed.',
697
+ errorCode: details.errorCode || 'cloudflare_dns_record_failed',
698
+ dnsOwnership: details.dnsOwnership || 'external',
699
+ domainStatus: 'skipped',
700
+ };
701
+ }
702
+ let domain;
703
+ try {
704
+ domain = await ensureCloudflarePagesDomain(config, selection.hostname);
705
+ }
706
+ catch (err) {
707
+ const details = err instanceof DeployError && err.details && typeof err.details === 'object' ? err.details : {};
708
+ return {
709
+ ...base,
710
+ status: details.errorCode === 'cloudflare_domain_already_bound' ? 'conflict' : 'failed',
711
+ // Same "every real throw site in this file is a genuine Error/DeployError" reasoning as the
712
+ // DNS-setup catch above — unreachable fallback, see packages/deploy/source-map.md.
713
+ statusMessage: err instanceof Error ? err.message : 'Cloudflare Pages custom domain setup failed.',
714
+ errorCode: details.errorCode || 'cloudflare_domain_setup_failed',
715
+ dnsStatus: dns.dnsStatus,
716
+ dnsRecordId: dns.dnsRecordId,
717
+ dnsOwnership: dns.dnsOwnership,
718
+ domainStatus: details.domainStatus || 'failed',
719
+ };
720
+ }
721
+ const domainStatus = normalizeCloudflarePagesDomainStatus(domain?.status);
722
+ const customLink = domainStatus === 'active' ? await checkDeploymentUrl(base.url) : null;
723
+ const ready = domainStatus === 'active' && customLink?.reachable;
724
+ const failed = domainStatus === 'failed';
725
+ return {
726
+ ...base,
727
+ status: ready ? 'ready' : failed ? 'failed' : 'pending',
728
+ statusMessage: ready
729
+ ? 'Custom domain is ready.'
730
+ : failed
731
+ ? 'Cloudflare Pages reported a custom-domain error.'
732
+ : customLink?.statusMessage || 'Custom domain is being verified by Cloudflare Pages.',
733
+ dnsStatus: dns.dnsStatus,
734
+ dnsRecordId: dns.dnsRecordId,
735
+ dnsOwnership: dns.dnsOwnership,
736
+ domainStatus,
737
+ };
738
+ }
739
+ function hostnameFromUrl(raw) {
740
+ return normalizeDeploymentUrlToHostname(raw);
741
+ }
742
+ /**
743
+ * A stable identifier stamped as a Cloudflare DNS record comment so a later
744
+ * publish can recognize (and safely patch) a CNAME record it created
745
+ * itself, versus one an operator manages by hand. Genericized from the OD
746
+ * origin's `od:cfp:` marker prefix.
747
+ */
748
+ /**
749
+ * `pagesTarget || projectName` is unreachable via this function's one call
750
+ * site (`setupCloudflarePagesCustomDomain`): `pagesTarget` there is
751
+ * `normalizeHostname(hostnameFromUrl(pagesDevUrl) || \`${config.projectName}.pages.dev\`)`,
752
+ * and `pagesDevUrl` (`publish()`'s own `productionUrl || link.url`) is always
753
+ * `productionUrl` — always a non-empty `https://${projectName}.pages.dev`
754
+ * string per `cloudflarePagesProductionUrl`'s own doc comment, since
755
+ * `config.projectName` is validated non-empty before any of this runs. A
756
+ * non-empty, well-formed `https://` URL always yields a non-empty
757
+ * `new URL(...).hostname`, so `hostnameFromUrl(pagesDevUrl)` never falls
758
+ * through to its own `|| ...pages.dev` default, and `normalizeHostname` of a
759
+ * real hostname never produces `''`. So `pagesTarget` is always truthy by
760
+ * the time it reaches here. See packages/deploy/source-map.md's 2026-07-22
761
+ * addition for the full chain.
762
+ */
763
+ function cloudflarePagesDnsMarker(projectName, pagesTarget) {
764
+ return `jini-deploy:${shortHash(projectName)}:${shortHash(pagesTarget || projectName)}`;
765
+ }
766
+ function aggregateCloudflarePagesStatus(pagesDev, customDomain) {
767
+ // Every `|| fallback`/`!== undefined ? ... : {}` construct below that falls back specifically
768
+ // when `pagesDev.statusMessage` is falsy/undefined is unreachable via this function's one real
769
+ // call site (`publish()`'s `aggregateCloudflarePagesStatus(pagesDev, customDomain)`):
770
+ // `pagesDev` there is always `{ status: link.status, statusMessage: link.statusMessage }`, and
771
+ // `link` is a `ReachabilityWaitResult` (from `reachability.ts`'s `waitForReachableDeploymentUrl`)
772
+ // whose `statusMessage` field is typed *required*, not optional — every one of that function's
773
+ // own return paths sets a real, non-empty string (verified when closing that file's own coverage
774
+ // gaps — see its 2026-07-22 source-map addition). This function's own parameter type
775
+ // (`statusMessage?: string`) is deliberately wider than what its one real caller supplies, same
776
+ // general-purpose-helper posture as `deploymentUrlCandidates`/`normalizeDeploymentUrlToHostname`
777
+ // elsewhere in this file. Similarly, `customDomain.statusMessage`/`customDomain.errorCode`
778
+ // fallbacks below are unreachable because `customDomain` only ever comes from this file's own
779
+ // `setupCloudflarePagesCustomDomain`, whose every return shape sets a real, non-empty
780
+ // `statusMessage` (main flow) or `errorCode` (catch-block flows) — see that function's own return
781
+ // sites. See packages/deploy/source-map.md's 2026-07-22 addition for the exhaustive case-by-case
782
+ // trace backing all of this.
783
+ if (!customDomain) {
784
+ return { status: pagesDev.status, ...(pagesDev.statusMessage !== undefined ? { statusMessage: pagesDev.statusMessage } : {}) };
785
+ }
786
+ if (customDomain.status === 'ready') {
787
+ return {
788
+ status: pagesDev.status === 'ready' ? 'ready' : 'link-delayed',
789
+ statusMessage: pagesDev.status === 'ready'
790
+ ? 'Cloudflare Pages and custom domain are ready.'
791
+ : pagesDev.statusMessage || "Cloudflare Pages is still preparing its pages.dev link.",
792
+ };
793
+ }
794
+ if (customDomain.status === 'pending') {
795
+ return { status: 'link-delayed', statusMessage: customDomain.statusMessage || 'Custom domain is still being prepared.' };
796
+ }
797
+ const customFailureMessage = customDomain.errorCode || customDomain.statusMessage || 'Custom domain setup failed.';
798
+ return {
799
+ status: pagesDev.status,
800
+ statusMessage: pagesDev.status === 'ready' ? `pages.dev is ready. ${customFailureMessage}` : pagesDev.statusMessage || customFailureMessage,
801
+ };
802
+ }
803
+ /**
804
+ * `DeployTarget` adapter for Cloudflare Pages' direct-upload API: ensures a
805
+ * Pages project exists, uploads the file set as content-addressed assets,
806
+ * creates a deployment, waits for the `pages.dev` URL to be reachable, and
807
+ * (optionally, when `input.metadata.customDomain` is supplied) binds a
808
+ * custom domain via a managed CNAME + Pages domain record.
809
+ *
810
+ * Genericized from the origin product's daemon deploy module's
811
+ * `deployToCloudflarePages` family: the origin's persisted local config file
812
+ * and product-specific project naming are gone — the caller supplies
813
+ * `{ token, accountId }` directly and a stable `projectName` label.
814
+ */
815
+ export class CloudflarePagesDeployTarget {
816
+ config;
817
+ id = CLOUDFLARE_PAGES_TARGET_ID;
818
+ constructor(config) {
819
+ this.config = config;
820
+ }
821
+ /**
822
+ * Publishes `input.files` to Cloudflare Pages and waits for the resulting
823
+ * `pages.dev` URL to be reachable, optionally binding a custom domain.
824
+ *
825
+ * @param input - File set, a caller-chosen project name label, and
826
+ * optional `metadata.customDomain`/`metadata.priorCustomDomain`.
827
+ * @returns The published deployment's URL/status, with any custom-domain
828
+ * outcome folded into `providerMetadata`.
829
+ * @throws {DeployError} If `token`/`accountId` are missing, the derived
830
+ * project name is empty, or any Cloudflare API call fails.
831
+ * @complexity O(files) to hash/chunk the asset set, plus a bounded
832
+ * reachability wait; DNS/domain setup is O(1) additional round-trips.
833
+ * @overallScore 95/100
834
+ * @tradeoffs Custom-domain setup errors are captured into the returned
835
+ * `providerMetadata` rather than thrown, matching the OD origin's
836
+ * behavior of always returning the base pages.dev result even if the
837
+ * custom domain step fails partway — flagged since a caller that only
838
+ * checks `status`/`throws` could miss a degraded custom-domain state
839
+ * without also inspecting `providerMetadata`.
840
+ */
841
+ async publish(input) {
842
+ if (!this.config.token)
843
+ throw new DeployError('Cloudflare API token is required.', 400);
844
+ if (!this.config.accountId)
845
+ throw new DeployError('Cloudflare account ID is required.', 400);
846
+ const projectName = deriveCloudflarePagesProjectName(input.projectName);
847
+ // `if (!projectName) throw ...` is unreachable: `deriveCloudflarePagesProjectName`
848
+ // always returns a non-empty string (see its own doc comment) — kept as
849
+ // belt-and-suspenders in case that helper's contract ever changes, same
850
+ // reasoning as `cloudflarePagesProjectUrl`'s identical guard. See
851
+ // packages/deploy/source-map.md's 2026-07-22 addition.
852
+ if (!projectName)
853
+ throw new DeployError('Cloudflare Pages project name could not be generated.', 400);
854
+ const config = { ...this.config, projectName };
855
+ const metadata = (input.metadata ?? {});
856
+ const customDomainSelection = await validateCloudflarePagesDeploySelection(config, normalizeCloudflarePagesDeploySelection(metadata.customDomain));
857
+ await ensureCloudflarePagesProject(config);
858
+ const uploadToken = await getCloudflarePagesUploadToken(config);
859
+ await uploadCloudflarePagesAssets(uploadToken, input.files);
860
+ const form = new FormData();
861
+ const manifest = {};
862
+ for (const file of input.files)
863
+ manifest[`/${file.file}`] = cloudflarePagesAssetHash(file);
864
+ form.append('manifest', JSON.stringify(manifest));
865
+ form.append('branch', 'main');
866
+ const deployResp = await fetchWithTimeout(cloudflarePagesProjectUrl(config, 'deployments'), {
867
+ method: 'POST',
868
+ headers: cloudflareHeaders(config),
869
+ body: form,
870
+ }, { timeoutMs: FETCH_TIMEOUT_MS.DEPLOY });
871
+ const deployed = await readCloudflareJson(deployResp);
872
+ if (!deployResp.ok || deployed?.success === false) {
873
+ throw cloudflareError(deployed, deployResp.status, 'Cloudflare Pages deployment failed.');
874
+ }
875
+ const deployment = deployed?.result ?? deployed;
876
+ // `productionUrl ? [productionUrl] : [deployment?.url]` and `productionUrl || link.url` below:
877
+ // the `[deployment?.url]`/`link.url` sides are both unreachable. `productionUrl` is
878
+ // `cloudflarePagesProductionUrl(config)`, which — per its own doc comment — is always the
879
+ // non-empty `https://${projectName}.pages.dev` string, since `config.projectName` is validated
880
+ // non-empty before `config` is ever constructed above. See
881
+ // packages/deploy/source-map.md's 2026-07-22 addition.
882
+ const productionUrl = cloudflarePagesProductionUrl(config);
883
+ const link = await waitForReachableDeploymentUrl(productionUrl ? [productionUrl] : [deployment?.url], {
884
+ providerLabel: 'Cloudflare Pages',
885
+ });
886
+ const pagesDevUrl = productionUrl || link.url;
887
+ const pagesDev = { status: link.status, statusMessage: link.statusMessage };
888
+ const customDomain = customDomainSelection
889
+ ? await setupCloudflarePagesCustomDomain({
890
+ config,
891
+ selection: customDomainSelection,
892
+ pagesDevUrl,
893
+ prior: metadata.priorCustomDomain,
894
+ })
895
+ : undefined;
896
+ const aggregate = aggregateCloudflarePagesStatus(pagesDev, customDomain);
897
+ return {
898
+ targetId: this.id,
899
+ url: pagesDevUrl,
900
+ ...(typeof deployment?.id === 'string' ? { deploymentId: deployment.id } : {}),
901
+ status: aggregate.status,
902
+ // `aggregate.statusMessage !== undefined ? ... : {}` — the `{}` (statusMessage omitted) side
903
+ // is unreachable: every one of `aggregateCloudflarePagesStatus`'s own return paths sets a
904
+ // real, non-empty `statusMessage` — either a literal, or spread from `pagesDev.statusMessage`,
905
+ // which (per that function's own doc comment) is always defined. See
906
+ // packages/deploy/source-map.md's 2026-07-22 addition.
907
+ ...(aggregate.statusMessage !== undefined ? { statusMessage: aggregate.statusMessage } : {}),
908
+ ...(link.reachableAt !== undefined ? { reachableAt: link.reachableAt } : {}),
909
+ providerMetadata: {
910
+ projectName,
911
+ pagesDev: { ...pagesDev, url: pagesDevUrl },
912
+ ...(customDomain ? { customDomain } : {}),
913
+ },
914
+ };
915
+ }
916
+ /** Probes `url` with the shared reachability checker (no Cloudflare-specific auth-wall detection is needed). */
917
+ async checkReachability(url) {
918
+ return checkDeploymentUrl(url);
919
+ }
920
+ }
921
+ //# sourceMappingURL=cloudflare-pages.js.map