@workover/cli 0.15.0 → 0.26.0

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/site-setup.mjs ADDED
@@ -0,0 +1,925 @@
1
+ // Setting up a hosted Workover Help Center from a terminal: `workover project create`, the
2
+ // `workover site` commands, and the MCP server's site tools.
3
+ //
4
+ // THE SAME FILE ships in @workover/cli (apps/cli/site-setup.mjs) and @workover/mcp
5
+ // (apps/mcp/site-setup.mjs), because the two packages are published separately and neither may
6
+ // depend on the other. `apps/mcp/site-setup.test.mjs` fails when the copies differ, and
7
+ // `apps/web/src/views/publish/site-setup-parity.test.ts` fails when the records, the address
8
+ // split or the proxy setup printed here stop matching the app's Domain tab.
9
+ //
10
+ // WHY THIS EXISTS. setup.md hands an agent the whole Workover setup. Until Nov 2026 every step of a
11
+ // Help Center (create it, import the old docs, connect the domain, publish) was a button in the
12
+ // browser, so the agent could only tell the person where to click, and Alex setting up Workover's
13
+ // own docs on staging found the agent path could not do it at all. Every call here goes to a route
14
+ // opened to tokens holding the `site` scope (`workover login --site`), and to nothing else.
15
+ //
16
+ // No ANSI and no side effects: `call(path, { method, body })` does the requests and resolves the
17
+ // parsed JSON, or throws an Error whose `.status` is the HTTP status and whose message is the
18
+ // API's own sentence. The renderers return lines, for a terminal or an MCP text result alike.
19
+
20
+ /** The token scope these routes need, and the sign-in that grants it. */
21
+ export const SITE_SCOPE = 'site';
22
+ export const SITE_LOGIN = 'workover login --site';
23
+
24
+ // ------------------------------------------------------------------ the app's own rules
25
+ // Copies of apps/web/src/views/publish/domain-address.ts and mount-setup.ts, pinned against them
26
+ // by site-setup-parity.test.ts.
27
+
28
+ /** `s` without any run of `ch` at its end: a loop, not a regex, so a long run costs linear time. */
29
+ function trimEnd(s, ch) {
30
+ let end = s.length;
31
+ while (end > 0 && s[end - 1] === ch) end -= 1;
32
+ return s.slice(0, end);
33
+ }
34
+
35
+ /** `docs.example.com` → its own hostname; `example.com/docs` → a hostname and a path. */
36
+ export function splitAddress(raw) {
37
+ const v = String(raw ?? '')
38
+ .trim()
39
+ .replace(/^[a-z][a-z0-9+.-]*:\/\//i, '')
40
+ .split(/[?#]/)[0];
41
+ const slash = v.indexOf('/');
42
+ const hostname = (slash < 0 ? v : v.slice(0, slash)).toLowerCase().replace(/\.$/, '');
43
+ const path = slash < 0 ? '' : trimEnd(v.slice(slash), '/');
44
+ return { hostname, basePath: path && path !== '/' ? path.toLowerCase() : null };
45
+ }
46
+
47
+ const TWO_PART = /\.(?:co|com|net|org|gov|ac|edu)\.[a-z]{2}$/;
48
+
49
+ /** A whole (root) domain, which most DNS providers cannot point with a CNAME. A heuristic. */
50
+ export function isRootDomain(hostname) {
51
+ const labels = hostname.split('.').filter(Boolean).length;
52
+ return labels === 2 || (labels === 3 && TWO_PART.test(hostname));
53
+ }
54
+
55
+ /** The registrable domain a hostname's DNS is managed under: docs.acme.co.uk → acme.co.uk. */
56
+ export function zoneOf(hostname) {
57
+ const labels = hostname.split('.').filter(Boolean);
58
+ const keep = TWO_PART.test(hostname) && labels.length >= 3 ? 3 : 2;
59
+ return labels.slice(-keep).join('.');
60
+ }
61
+
62
+ /** A record's name as a DNS provider's form wants it: relative to the domain, `@` for the domain. */
63
+ export function relativeName(name, zone) {
64
+ const n = name.replace(/\.$/, '').toLowerCase();
65
+ if (n === zone) return '@';
66
+ return n.endsWith(`.${zone}`) ? n.slice(0, -(zone.length + 1)) : n;
67
+ }
68
+
69
+ /** One record as a zone file line, for a provider that imports BIND files. */
70
+ export function zoneLine(r) {
71
+ const fq = (n) => (n.endsWith('.') ? n : `${n}.`);
72
+ const value = r.type === 'TXT' ? `"${r.value.replace(/[\\"]/g, '\\$&')}"` : fq(r.value);
73
+ return `${fq(r.name)} 3600 IN ${r.type} ${value}`;
74
+ }
75
+
76
+ /** Paste-ready proxy setup for a site served under a path of the person's own website, one recipe per platform. */
77
+ export function mountSetup(hostname, basePath, mountHost) {
78
+ const site = `https://${mountHost}`;
79
+ const cloudflareWorker = `export default {
80
+ async fetch(request) {
81
+ const url = new URL(request.url);
82
+ const target = new URL(url.pathname + url.search, '${site}');
83
+ const headers = new Headers(request.headers);
84
+ headers.set('X-Forwarded-Host', '${hostname}');
85
+ headers.set('X-Forwarded-Proto', 'https');
86
+ return fetch(target, {
87
+ method: request.method,
88
+ headers,
89
+ body: ['GET', 'HEAD'].includes(request.method) ? undefined : request.body,
90
+ redirect: 'manual'
91
+ });
92
+ }
93
+ };
94
+ `;
95
+ const vercelRewrites = `${JSON.stringify(
96
+ {
97
+ rewrites: [
98
+ { source: basePath, destination: `${site}${basePath}` },
99
+ { source: `${basePath}/:path*`, destination: `${site}${basePath}/:path*` }
100
+ ]
101
+ },
102
+ null,
103
+ 2
104
+ )}
105
+ `;
106
+ const nextjs = `// next.config.js: merge into your config. beforeFiles runs before your own pages and routes.
107
+ module.exports = {
108
+ async rewrites() {
109
+ return {
110
+ beforeFiles: [
111
+ { source: '${basePath}', destination: '${site}${basePath}' },
112
+ { source: '${basePath}/:path*', destination: '${site}${basePath}/:path*' }
113
+ ]
114
+ };
115
+ }
116
+ };
117
+ `;
118
+ const behaviour = (pattern) => `ordered_cache_behavior {
119
+ path_pattern = "${pattern}"
120
+ target_origin_id = "workover-docs"
121
+ viewer_protocol_policy = "redirect-to-https"
122
+ allowed_methods = ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"]
123
+ cached_methods = ["GET", "HEAD"]
124
+ compress = true
125
+ cache_policy_id = data.aws_cloudfront_cache_policy.workover_docs.id
126
+ origin_request_policy_id = data.aws_cloudfront_origin_request_policy.workover_docs.id
127
+ }`;
128
+ const cloudfront = `# OpenTofu or Terraform. The two data sources go next to your aws_cloudfront_distribution;
129
+ # the origin and both behaviours go inside it, with the behaviours above any other
130
+ # ordered_cache_behavior so they match first.
131
+
132
+ data "aws_cloudfront_cache_policy" "workover_docs" {
133
+ name = "Managed-CachingDisabled"
134
+ }
135
+
136
+ data "aws_cloudfront_origin_request_policy" "workover_docs" {
137
+ name = "Managed-AllViewerExceptHostHeader"
138
+ }
139
+
140
+ # Inside resource "aws_cloudfront_distribution":
141
+
142
+ origin {
143
+ origin_id = "workover-docs"
144
+ domain_name = "${mountHost}"
145
+
146
+ custom_origin_config {
147
+ http_port = 80
148
+ https_port = 443
149
+ origin_protocol_policy = "https-only"
150
+ origin_ssl_protocols = ["TLSv1.2"]
151
+ }
152
+
153
+ custom_header {
154
+ name = "X-Workover-Host"
155
+ value = "${hostname}"
156
+ }
157
+ }
158
+
159
+ ${behaviour(basePath)}
160
+
161
+ ${behaviour(`${basePath}/*`)}
162
+ `;
163
+ const amplify = `${JSON.stringify(
164
+ [
165
+ { source: basePath, target: `${site}${basePath}`, status: '200' },
166
+ { source: `${basePath}/<*>`, target: `${site}${basePath}/<*>`, status: '200' }
167
+ ],
168
+ null,
169
+ 2
170
+ )}
171
+ `;
172
+ const netlify = [basePath, `${basePath}/*`]
173
+ .map(
174
+ (from, i) => `[[redirects]]
175
+ from = "${from}"
176
+ to = "${site}${basePath}${i ? '/:splat' : ''}"
177
+ status = 200
178
+ force = true
179
+ headers = { X-Workover-Host = "${hostname}" }
180
+ `
181
+ )
182
+ .join('\n');
183
+ const nginxBody = ` proxy_pass https://${mountHost};
184
+ proxy_http_version 1.1;
185
+ proxy_set_header Host ${mountHost};
186
+ proxy_set_header X-Workover-Host ${hostname};
187
+ proxy_set_header X-Forwarded-Proto https;
188
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
189
+ proxy_ssl_server_name on;
190
+ proxy_ssl_name ${mountHost};
191
+ proxy_redirect off;`;
192
+ const nginx = `# Inside the server { } block for ${hostname}. ^~ keeps your own regex locations
193
+ # (for .css or .js files, say) from taking the docs' assets.
194
+ location = ${basePath} {
195
+ ${nginxBody}
196
+ }
197
+
198
+ location ^~ ${basePath}/ {
199
+ ${nginxBody}
200
+ }
201
+ `;
202
+ const caddy = `# Inside the site block for ${hostname}, above your other handle blocks.
203
+ @workover_docs path ${basePath} ${basePath}/*
204
+ handle @workover_docs {
205
+ reverse_proxy https://${mountHost} {
206
+ header_up Host {upstream_hostport}
207
+ header_up X-Workover-Host ${hostname}
208
+ }
209
+ }
210
+ `;
211
+ const apache = `# Inside the <VirtualHost> for ${hostname}.
212
+ # Needs mod_proxy, mod_proxy_http, mod_ssl and mod_headers (a2enmod proxy proxy_http ssl headers).
213
+ SSLProxyEngine on
214
+ ProxyPreserveHost Off
215
+ ProxyPassMatch "^(${basePath}(?:/.*)?)$" "https://${mountHost}$1"
216
+ ProxyPassReverse "${basePath}" "https://${mountHost}${basePath}"
217
+ <LocationMatch "^${basePath}(/|$)">
218
+ RequestHeader set X-Workover-Host "${hostname}"
219
+ </LocationMatch>
220
+ `;
221
+ const recipes = [
222
+ {
223
+ platform: 'cloudflare',
224
+ label: 'Cloudflare',
225
+ where: `Create a Worker with this script, and add two routes to it: ${hostname}${basePath} and ${hostname}${basePath}/*. Do not use ${hostname}${basePath}*, which would also match paths like ${basePath}-audit.`,
226
+ file: 'workover-docs-worker.js',
227
+ lang: 'js',
228
+ code: cloudflareWorker,
229
+ steps: [],
230
+ indexable: true,
231
+ tested: true
232
+ },
233
+ {
234
+ platform: 'vercel',
235
+ label: 'Vercel',
236
+ where: `Merge this into vercel.json. Only ${basePath} and the paths under it go to Workover, and Vercel names your domain in X-Forwarded-Host itself.`,
237
+ file: 'vercel.json',
238
+ lang: 'json',
239
+ code: vercelRewrites,
240
+ steps: [],
241
+ indexable: true,
242
+ tested: false
243
+ },
244
+ {
245
+ platform: 'nextjs',
246
+ label: 'Next.js',
247
+ where: `For a Next.js site you run yourself (on Vercel, either this or the Vercel setup works). Merge the rewrites into next.config.js; Next.js names your domain in X-Forwarded-Host itself. If your rewrites() already returns a list, put these two first in it.`,
248
+ file: null,
249
+ lang: 'js',
250
+ code: nextjs,
251
+ steps: [],
252
+ indexable: true,
253
+ tested: true
254
+ },
255
+ {
256
+ platform: 'cloudfront',
257
+ label: 'AWS CloudFront',
258
+ where: `Add an origin and two behaviours to the distribution that serves ${hostname}. The origin sends the fixed header X-Workover-Host: ${hostname}, so no function is needed.`,
259
+ file: null,
260
+ lang: 'hcl',
261
+ code: cloudfront,
262
+ steps: [
263
+ `Origins → Create origin. Origin domain: ${mountHost}. Protocol: HTTPS only. Add custom header: X-Workover-Host = ${hostname}.`,
264
+ `Behaviors → Create behavior, twice: path pattern ${basePath}, then ${basePath}/*. Origin: the one above. Viewer protocol: Redirect HTTP to HTTPS. Allowed methods: GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE. Cache policy: CachingDisabled. Origin request policy: AllViewerExceptHostHeader.`,
265
+ `Move both behaviours above Default (*), and any other behaviour that could match ${basePath}.`
266
+ ],
267
+ indexable: true,
268
+ tested: false
269
+ },
270
+ {
271
+ platform: 'amplify',
272
+ label: 'AWS Amplify',
273
+ where: `In the Amplify console: Hosting → Rewrites and redirects → Manage redirects → Open text editor, and put these two rules first. Amplify cannot add a request header, so whether search engines may index the pages depends on what Amplify forwards: check the live site once it is in. For indexable docs, put CloudFront in front with the CloudFront setup.`,
274
+ file: null,
275
+ lang: 'json',
276
+ code: amplify,
277
+ steps: [],
278
+ indexable: false,
279
+ tested: false
280
+ },
281
+ {
282
+ platform: 'netlify',
283
+ label: 'Netlify',
284
+ where: `Add these to netlify.toml, above any other redirect that could match ${basePath} (a single-page app's /* rule, say).`,
285
+ file: 'netlify.toml',
286
+ lang: 'toml',
287
+ code: netlify,
288
+ steps: [],
289
+ indexable: true,
290
+ tested: false
291
+ },
292
+ {
293
+ platform: 'nginx',
294
+ label: 'nginx',
295
+ where: `Add both locations to the server block for ${hostname}, then reload nginx (nginx -t && nginx -s reload).`,
296
+ file: 'workover-docs.nginx.conf',
297
+ lang: 'nginx',
298
+ code: nginx,
299
+ steps: [],
300
+ indexable: true,
301
+ tested: true
302
+ },
303
+ {
304
+ platform: 'caddy',
305
+ label: 'Caddy',
306
+ where: `Add this to the site block for ${hostname} in your Caddyfile, then reload Caddy (caddy reload).`,
307
+ file: 'workover-docs.caddy',
308
+ lang: 'caddy',
309
+ code: caddy,
310
+ steps: [],
311
+ indexable: true,
312
+ tested: true
313
+ },
314
+ {
315
+ platform: 'apache',
316
+ label: 'Apache',
317
+ where: `Add this to the VirtualHost for ${hostname}, then reload Apache (apachectl configtest && apachectl graceful).`,
318
+ file: 'workover-docs.apache.conf',
319
+ lang: 'apache',
320
+ code: apache,
321
+ steps: [],
322
+ indexable: true,
323
+ tested: true
324
+ }
325
+ ];
326
+ const sitemapUrl = `https://${hostname}${basePath}/sitemap.xml`;
327
+ return {
328
+ sitemapUrl,
329
+ robotsLine: `Sitemap: ${sitemapUrl}`,
330
+ cloudflareRoutes: [`${hostname}${basePath}`, `${hostname}${basePath}/*`],
331
+ cloudflareWorker,
332
+ vercelRewrites,
333
+ recipes
334
+ };
335
+ }
336
+
337
+ /** Every platform a recipe exists for, in the order they are offered. */
338
+ export const MOUNT_PLATFORMS = ['cloudflare', 'vercel', 'nextjs', 'cloudfront', 'amplify', 'netlify', 'nginx', 'caddy', 'apache'];
339
+
340
+ /** The recipes with `platform`'s first (the one detected on the person's site), the rest as they were. */
341
+ export function recipesFirst(recipes, platform) {
342
+ const i = recipes.findIndex((r) => r.platform === platform);
343
+ return i < 0 ? recipes : [recipes[i], ...recipes.slice(0, i), ...recipes.slice(i + 1)];
344
+ }
345
+
346
+ /** What the Domain tab calls each status. */
347
+ export const DOMAIN_STATUS = {
348
+ none: 'Not connected',
349
+ pending: 'Waiting for DNS',
350
+ active: 'Live',
351
+ failed: 'Needs attention',
352
+ unmanaged: 'Local only',
353
+ };
354
+
355
+ /** A workover.site address to start from, made from a name: `Acme Docs!` → `acme-docs`. */
356
+ export function addressFromName(name) {
357
+ const dashed = String(name ?? '')
358
+ .normalize('NFKD')
359
+ .replace(/[̀-ͯ]/g, '')
360
+ .toLowerCase()
361
+ .replace(/[^a-z0-9]+/g, '-')
362
+ .replace(/^-+/, '')
363
+ .slice(0, 40);
364
+ const base = trimEnd(dashed, '-');
365
+ if (base.length >= 3) return base;
366
+ return base ? `${base}-docs` : '';
367
+ }
368
+
369
+ // ------------------------------------------------------------------ calls
370
+
371
+ /** An Error carrying the HTTP status, for `call` implementations. */
372
+ export const apiError = (status, message) =>
373
+ Object.assign(new Error(message || `Workover answered ${status}.`), { status });
374
+
375
+ /** The sentence an agent needs when a site route refuses the token. */
376
+ export const scopeHelp = (message) =>
377
+ /"site" scope|--site/.test(String(message || ''))
378
+ ? `This sign-in cannot set up a Help Center. Run \`${SITE_LOGIN}\` and ask the person to approve it in the browser (the approval screen lists "Set up and publish your Workover Help Center").`
379
+ : null;
380
+
381
+ /** Which workspace: by id or slug, or the only one there is. */
382
+ export async function resolveWorkspace(call, ref) {
383
+ const me = await call('/cli-auth/me');
384
+ const all = me?.workspaces || [];
385
+ if (!all.length)
386
+ throw apiError(400, 'This account has no workspace yet. The person creates one when they sign up, in the browser.');
387
+ const wanted = ref === undefined || ref === null ? '' : String(ref).trim().toLowerCase();
388
+ if (!wanted) {
389
+ if (all.length === 1) return all[0];
390
+ throw apiError(
391
+ 400,
392
+ `Which workspace? This account has ${all.length}: ${all.map((w) => `${w.slug ?? w.id} (${w.name})`).join(', ')}. Pass one by its slug or id.`,
393
+ );
394
+ }
395
+ const found = all.find(
396
+ (w) => String(w.id) === wanted || String(w.slug ?? '').toLowerCase() === wanted,
397
+ );
398
+ if (!found)
399
+ throw apiError(
400
+ 404,
401
+ `No workspace "${ref}" on this account. It has: ${all.map((w) => w.slug ?? w.id).join(', ')}.`,
402
+ );
403
+ return found;
404
+ }
405
+
406
+ /**
407
+ * A free workover.site address. The one asked for, or a refusal saying why and naming a free one;
408
+ * with none asked for, one made from the name, or the free alternative the API offers when that one
409
+ * is taken or reserved ("Workover Help Center" makes `workover-help-center`, which borrows a brand
410
+ * name, and gets `help-center`: WO-1401).
411
+ */
412
+ export async function pickAddress(call, { wanted, name, projectId }) {
413
+ const asked = typeof wanted === 'string' && wanted.trim() ? wanted.trim().toLowerCase() : '';
414
+ const candidate = asked || addressFromName(name);
415
+ if (!candidate) throw apiError(400, 'Choose an address for the site with --address <name>.');
416
+ const q = `name=${encodeURIComponent(candidate)}${projectId ? `&projectId=${projectId}` : ''}`;
417
+ const verdict = await call(`/sites/address?${q}`);
418
+ if (verdict?.available) return verdict.subdomain;
419
+ if (!asked && verdict?.suggestion) return verdict.suggestion;
420
+ let message = verdict?.message || 'That address cannot be used.';
421
+ // "Try another." is for a field with nothing beside it; here the free one is named instead.
422
+ const TRY = ' Try another.';
423
+ if (verdict?.suggestion && message.endsWith(TRY)) message = message.slice(0, -TRY.length);
424
+ throw apiError(409, `${candidate}: ${message}${verdict?.suggestion ? ` ${verdict.suggestion} is free.` : ''}`);
425
+ }
426
+
427
+ const START = { blank: 'blank', starter: 'starter', empty: 'import' };
428
+
429
+ /**
430
+ * A new project whose publish target is a Workover Help Center: the project, its site and address,
431
+ * and its first pages (`blank`: one page; `starter`: the starter template; `empty`: none, for an
432
+ * import to fill). `POST /sites/hosted`, the call the New Project modal makes. Nothing is published.
433
+ */
434
+ export async function createProject(call, { workspace, name, address, start = 'blank' }) {
435
+ const title = String(name ?? '').trim();
436
+ if (!title) throw apiError(400, 'Name the project with --name "<name>".');
437
+ const kind = START[start];
438
+ if (!kind) throw apiError(400, `--start is blank, starter or empty, not "${start}".`);
439
+ const ws = await resolveWorkspace(call, workspace);
440
+ const subdomain = await pickAddress(call, { wanted: address, name: title });
441
+ const created = await call('/sites/hosted', {
442
+ method: 'POST',
443
+ body: { organizationId: ws.id, name: title, subdomain, start: { kind } },
444
+ });
445
+ return { workspace: ws, start, ...created };
446
+ }
447
+
448
+ /** The name of a project the caller can see, from `GET /project`. */
449
+ async function projectName(call, projectId) {
450
+ const res = await call('/project');
451
+ const list = Array.isArray(res) ? res : res?.projects || [];
452
+ const p = list.find((x) => Number(x.id) === Number(projectId));
453
+ return p ? p.name || p.title || null : null;
454
+ }
455
+
456
+ /**
457
+ * Give an existing project a Workover Help Center (`PUT /sites/project/:id` with an address, the
458
+ * call the Publish page's first run makes). A project that already has one keeps it, renamed only
459
+ * when a different address is asked for.
460
+ */
461
+ export async function createSite(call, { projectId, address }) {
462
+ const before = await call(`/sites/project/${projectId}`);
463
+ const current = before?.site?.address?.subdomain ?? null;
464
+ const asked = typeof address === 'string' && address.trim() ? address.trim().toLowerCase() : '';
465
+ if (before?.site && (!asked || asked === current))
466
+ return { projectId, created: false, ...before };
467
+ const name = before?.site?.name || (await projectName(call, projectId)) || `project-${projectId}`;
468
+ const subdomain = await pickAddress(call, { wanted: asked, name, projectId });
469
+ await call(`/sites/project/${projectId}`, {
470
+ method: 'PUT',
471
+ body: before?.site ? { subdomain } : { name, subdomain },
472
+ });
473
+ const after = await call(`/sites/project/${projectId}`);
474
+ return { projectId, created: !before?.site, renamed: !!before?.site, ...after };
475
+ }
476
+
477
+ /**
478
+ * Connect a custom domain (`docs.example.com`) or a path on one (`example.com/docs`), then ask the
479
+ * provider at once, as the Domain tab does when it opens, so the answer carries every record to add
480
+ * (the ownership TXT included). `preverify` asks for the TXT records that prove a domain already live
481
+ * elsewhere before its CNAME moves, the Domain tab's "Show the TXT records".
482
+ */
483
+ export async function setDomain(call, { projectId, address, preverify = false, moveFrom = null }) {
484
+ const raw = String(address ?? '').trim();
485
+ if (!raw) throw apiError(400, 'Name the domain with --set <host>, like docs.example.com or example.com/docs.');
486
+ const disconnect = raw === 'none' || raw === 'off';
487
+ const { hostname, basePath } = splitAddress(disconnect ? '' : raw);
488
+ if (!disconnect && !hostname.includes('.'))
489
+ throw apiError(400, `"${raw}" is not a domain. Use one like docs.example.com, or example.com/docs.`);
490
+ // A move takes the domain from another Help Center in the same workspace in one step: its
491
+ // verification comes with it, so the DNS records stay as they are and neither site goes dark.
492
+ const from = moveFrom === null || moveFrom === undefined ? null : Number(moveFrom);
493
+ if (from !== null) {
494
+ if (disconnect) throw apiError(400, 'Name the domain to move with --set, like example.com/docs.');
495
+ if (!Number.isInteger(from) || from <= 0) throw apiError(400, 'Name the project to move the domain from by its id.');
496
+ if (from === Number(projectId)) throw apiError(400, 'Move the domain from another project, not this one.');
497
+ }
498
+ const saved = await call(`/sites/project/${projectId}`, {
499
+ method: 'PUT',
500
+ body: {
501
+ hostname: disconnect ? null : hostname,
502
+ basePath: disconnect ? null : basePath,
503
+ ...(from !== null ? { moveFrom: from } : {}),
504
+ },
505
+ });
506
+ if (disconnect) return { disconnected: true, domain: saved?.domain ?? null };
507
+ const domain = await freshDomain(call, projectId, saved?.domain, { preverify });
508
+ return from !== null ? { domain, movedFrom: from } : { domain };
509
+ }
510
+
511
+ /** The line a move opens with, before the domain's records. */
512
+ export function renderMoved(res) {
513
+ const d = res?.domain;
514
+ const where = d ? `${d.hostname}${d.basePath || ''}` : 'The domain';
515
+ return [
516
+ '',
517
+ ` Moved ${where} from project #${res.movedFrom}, with its verification. Its DNS records stay as they are.`,
518
+ ];
519
+ }
520
+
521
+ /** The domain as the provider sees it now; the saved view when it cannot be asked. */
522
+ async function freshDomain(call, projectId, fallback, { preverify = false } = {}) {
523
+ try {
524
+ const checked = await call(`/sites/project/${projectId}/domain/check`, { method: 'POST' });
525
+ if (!preverify || checked?.basePath || checked?.status === 'active') return checked;
526
+ return await call(`/sites/project/${projectId}/domain/preverify`, { method: 'POST' });
527
+ } catch (e) {
528
+ if (preverify) throw e;
529
+ return fallback ?? null;
530
+ }
531
+ }
532
+
533
+ /**
534
+ * Where the site, its domain and its certificate have got to, asked now; for a site under a path
535
+ * that is proved, also whether the live address serves it (the Domain tab's "Check the live site").
536
+ */
537
+ export async function checkSite(call, { projectId }) {
538
+ const view = await call(`/sites/project/${projectId}`);
539
+ if (!view?.site) return { ...view, domain: null, mount: null };
540
+ const saved = view.site.domain;
541
+ if (!saved?.hostname) return { ...view, domain: saved ?? null, mount: null };
542
+ const domain = await freshDomain(call, projectId, saved);
543
+ let mount = null;
544
+ if (domain?.basePath && domain.status === 'active') {
545
+ try {
546
+ mount = await call(`/sites/project/${projectId}/mount/check`, { method: 'POST' });
547
+ } catch (e) {
548
+ mount = { verdict: 'error', message: e.message };
549
+ }
550
+ }
551
+ return { ...view, domain, mount };
552
+ }
553
+
554
+ /**
555
+ * Poll `get` until a background job (an import, a publish) finishes or `timeoutMs` passes. Starting
556
+ * the same job again while it runs joins it on the server, so a caller that times out can simply ask
557
+ * again. `onProgress` hears each running state.
558
+ */
559
+ export async function waitForJob(get, { first, timeoutMs = 110_000, everyMs = 3000, onProgress, sleep, now = Date.now } = {}) {
560
+ const pause = sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
561
+ const deadline = now() + timeoutMs;
562
+ let state = first ?? (await get());
563
+ while (state?.status === 'running') {
564
+ onProgress?.(state);
565
+ if (now() + everyMs > deadline) return state;
566
+ await pause(everyMs);
567
+ state = await get();
568
+ }
569
+ return state;
570
+ }
571
+
572
+ /** A finished job's answer in the background-state shape: `{ status: 'done', result }`. */
573
+ const asState = (answer) =>
574
+ answer && typeof answer === 'object' && 'status' in answer && ['running', 'done', 'failed', 'none'].includes(answer.status)
575
+ ? answer
576
+ : { status: 'done', result: answer };
577
+
578
+ /** Import a public docs site (or a Workover export at a URL) into the site, and wait for it. */
579
+ export async function importSite(call, { projectId, url, ...wait }) {
580
+ const target = String(url ?? '').trim();
581
+ if (!target) throw apiError(400, 'Name the docs to import with --url https://docs.example.com.');
582
+ const first = asState(
583
+ await call(`/sites/project/${projectId}/import`, { method: 'POST', body: { url: target } }),
584
+ );
585
+ return waitForJob(() => call(`/sites/project/${projectId}/import`), { first, ...wait });
586
+ }
587
+
588
+ /** Publish the site, and wait for it. */
589
+ export async function publishSite(call, { projectId, ...wait }) {
590
+ const first = asState(await call(`/sites/project/${projectId}/publish`, { method: 'POST' }));
591
+ return waitForJob(() => call(`/sites/project/${projectId}/publish`), { first, ...wait });
592
+ }
593
+
594
+ /**
595
+ * Whether search engines may index the site: the Publish page's "Let search engines index this
596
+ * site". A new site starts with it off. Only for a project that has a site: the same save would
597
+ * otherwise create one with no address.
598
+ */
599
+ export async function setIndexing(call, { projectId, index }) {
600
+ const before = await call(`/sites/project/${projectId}`);
601
+ if (!before?.site)
602
+ throw apiError(404, `Project #${projectId} has no Help Center. \`workover site create --project ${projectId}\` adds one.`);
603
+ await call(`/sites/project/${projectId}`, { method: 'PUT', body: { noindex: !index } });
604
+ return { projectId, ...(await call(`/sites/project/${projectId}`)) };
605
+ }
606
+
607
+ /** `workover site index`. */
608
+ export function renderIndexing(res) {
609
+ const on = res.site && !res.site.noindex;
610
+ const lines = ['', on ? ' ✓ Search engines may index this site.' : ' ✓ Search engines are asked not to index this site.'];
611
+ if (res.site?.visibility === 'private') lines.push(' The site is private, so search engines never index it, whatever this says.');
612
+ lines.push('');
613
+ return lines;
614
+ }
615
+
616
+ /** Everything `site status` shows: the site, its domain as saved, the latest import and publish. */
617
+ export async function siteStatus(call, { projectId }) {
618
+ const view = await call(`/sites/project/${projectId}`);
619
+ if (!view?.site) return { ...view, import: null, publish: null };
620
+ const [imported, published] = await Promise.all([
621
+ call(`/sites/project/${projectId}/import`).catch(() => null),
622
+ call(`/sites/project/${projectId}/publish`).catch(() => null),
623
+ ]);
624
+ return { ...view, import: imported, publish: published };
625
+ }
626
+
627
+ // ------------------------------------------------------------------ what the agent relays
628
+
629
+ const publishPage = (web, workspace, projectId) =>
630
+ web && workspace?.slug ? `${web}/app/${workspace.slug}/p/${projectId}/publish` : null;
631
+
632
+ /** One line on what the plan allows, when it stops publishing. */
633
+ const hostingLine = (hosting) =>
634
+ hosting && hosting.canHostDocs === false
635
+ ? [
636
+ '',
637
+ ' ! The workspace\'s plan does not include a hosted Help Center yet, so publishing will be',
638
+ ' refused. The person chooses a plan in Settings, Plan & billing, in the browser.',
639
+ ]
640
+ : [];
641
+
642
+ const siteLines = (site) => {
643
+ if (!site) return [' No Help Center on this project yet.'];
644
+ const lines = [` Help Center: ${site.name}`];
645
+ if (site.address) lines.push(` Address: ${site.address.url}${site.publishedAt ? '' : ' (answers once published)'}`);
646
+ lines.push(` Published: ${site.publishedAt ? `yes, last at ${site.publishedAt}` : 'not yet'}`);
647
+ if (site.takenDown) lines.push(' ! Taken down by Workover support. Publishing is refused until support lifts it.');
648
+ if (site.noindex) lines.push(' Search engines: not indexed yet (a new site starts that way; `workover site index` turns it on)');
649
+ return lines;
650
+ };
651
+
652
+ /** `workover project create`. */
653
+ export function renderProjectCreated(res, { web } = {}) {
654
+ const p = res.project;
655
+ const lines = ['', ` ✓ Created project #${p.id} "${p.name}" in ${res.workspace?.name ?? 'the workspace'}, publishing to a Workover Help Center.`];
656
+ lines.push(...siteLines(res.site));
657
+ const page = publishPage(web, res.workspace, p.id);
658
+ if (page) lines.push(` Publish page: ${page}`);
659
+ lines.push(...hostingLine(res.hosting));
660
+ lines.push('', ' Next:');
661
+ if (res.start === 'empty')
662
+ lines.push(` workover site import --project ${p.id} --url <the docs site's address>`);
663
+ lines.push(` workover site domain --project ${p.id} --set docs.example.com (optional)`);
664
+ lines.push(` workover site publish --project ${p.id}`, '');
665
+ return lines;
666
+ }
667
+
668
+ /** `workover site create`. */
669
+ export function renderSiteCreated(res) {
670
+ const id = res.projectId;
671
+ const lines = [''];
672
+ if (res.created) lines.push(` ✓ Project #${id} now publishes to a Workover Help Center.`);
673
+ else if (res.renamed) lines.push(` ✓ Changed the Help Center's address on project #${id}.`);
674
+ else lines.push(` Project #${id} already has a Help Center. Nothing changed.`);
675
+ lines.push(...siteLines(res.site), ...hostingLine(res.hosting));
676
+ lines.push('', ' Next:', ` workover site import --project ${id} --url <the docs site's address> (optional)`);
677
+ lines.push(` workover site publish --project ${id}`, '');
678
+ return lines;
679
+ }
680
+
681
+ /** The sentence above the records, as the Domain tab words it for this state. */
682
+ function recordsSentence(domain, records) {
683
+ const host = domain.hostname;
684
+ const txt = domain.preverify ?? [];
685
+ const txtPending = txt.length > 0 && records.some((r) => r.type === 'TXT' && !r.verified);
686
+ const proofRow = !txt.length ? records.find((r) => r.type === 'TXT') : undefined;
687
+ if (txtPending)
688
+ return `Add the TXT records first, where the DNS for ${host} is managed. Once both are verified and the certificate is issued, add the CNAME record. Readers never see the domain without a certificate.`;
689
+ if (domain.record?.type === 'TXT') return `Add this record where the DNS for ${host} is managed, to prove the domain is yours.`;
690
+ if (txt.length) return `The TXT records are verified. Add the CNAME record where the DNS for ${host} is managed to send readers here.`;
691
+ if (proofRow && !proofRow.verified)
692
+ return `Add both records where the DNS for ${host} is managed. The TXT record proves the domain is yours: it is not served until that record is found.`;
693
+ if (proofRow)
694
+ return `The TXT record is verified. Add the CNAME record where the DNS for ${host} is managed. It usually goes live within a few minutes; the certificate is issued for you.`;
695
+ return `Add this record where the DNS for ${host} is managed. It usually goes live within a few minutes; the certificate is issued for you.`;
696
+ }
697
+
698
+ /** Every record, as the Domain tab's table has it, from an api that sent `records` or by role. */
699
+ export function domainRecords(domain) {
700
+ if (!domain?.hostname) return [];
701
+ if (Array.isArray(domain.records)) return domain.records;
702
+ if (!domain.record) return [];
703
+ const txt = domain.preverify ?? [];
704
+ const proof = domain.ownership ?? null;
705
+ const proofRecord = proof && !txt.some((r) => r.name === proof.name) ? [proof] : [];
706
+ return [...txt, ...proofRecord, domain.record].map((r) => ({ ...r, verified: false }));
707
+ }
708
+
709
+ /**
710
+ * The domain card: its status, then EVERY record to add, TXT included, with the name as a
711
+ * provider's form wants it (relative to the domain) and in full, the value, and whether it has been
712
+ * found. For a site under a path, the proxy setup the website needs as well. This is what the agent
713
+ * hands the person, verbatim.
714
+ */
715
+ export function renderDomain(domain, { projectId, platform = null, evidence = null } = {}) {
716
+ if (!domain?.hostname) return ['', ' No custom domain. The site answers at its workover.site address.', ''];
717
+ const shown = `${domain.hostname}${domain.basePath ?? ''}`;
718
+ const lines = ['', ` Custom domain: ${shown} (${DOMAIN_STATUS[domain.status] ?? domain.status})`];
719
+ if (domain.message) lines.push(` ${domain.message}`);
720
+ if (domain.steps)
721
+ lines.push(
722
+ ` Domain verified: ${domain.steps.ownership ? 'yes' : 'not yet'}. Certificate issued: ${domain.steps.certificate ? 'yes' : 'not yet'}.`,
723
+ );
724
+ const records = domainRecords(domain);
725
+ if (domain.status === 'active' && !domain.basePath) {
726
+ lines.push(` Live at https://${shown}. Keep these records in place:`);
727
+ } else if (records.length) {
728
+ lines.push('', ` ${recordsSentence(domain, records)}`);
729
+ }
730
+ const zone = zoneOf(domain.hostname);
731
+ if (records.length) {
732
+ lines.push('', ` DNS records for ${zone}:`, '');
733
+ records.forEach((r, i) => {
734
+ const rel = relativeName(r.name, zone);
735
+ lines.push(` ${i + 1}. ${r.type}`);
736
+ lines.push(` Name: ${rel}${rel !== r.name ? ` (full name: ${r.name})` : ''}`);
737
+ lines.push(` Value: ${r.value}`);
738
+ lines.push(` Status: ${r.verified ? 'Verified' : 'Pending'}`);
739
+ });
740
+ lines.push(
741
+ '',
742
+ ` In the provider's Name (or Host) field, enter only the part before ${zone}: the provider adds`,
743
+ ` ${zone} itself. TTL: the provider's default (Auto, or 3600).`,
744
+ );
745
+ if (records.some((r) => r.type === 'CNAME'))
746
+ lines.push(' On Cloudflare, set Proxy status to DNS only (a grey cloud). It is the simplest setup, though proxied also works.');
747
+ lines.push('', ' The same records as zone file lines, for a provider that imports them:');
748
+ for (const r of records) lines.push(` ${zoneLine(r)}`);
749
+ }
750
+ if (domain.basePath && domain.mountHost) {
751
+ const setup = mountSetup(domain.hostname, domain.basePath, domain.mountHost);
752
+ const proved = domain.status === 'active';
753
+ const detected = setup.recipes.find((r) => r.platform === platform);
754
+ // The detected platform's setup alone; with no guess, the two most sites use, as before.
755
+ const shown = detected ? [detected] : setup.recipes.filter((r) => r.platform === 'cloudflare' || r.platform === 'vercel');
756
+ lines.push(
757
+ '',
758
+ proved
759
+ ? ` Domain proved. The site is served from ${domain.mountHost}. Add ${shown.length > 1 ? 'one of these' : 'this'} on ${domain.hostname} to show it at ${domain.basePath}.`
760
+ : ` Step 1: add the TXT record above. Nothing is served until it is found. Step 2: add ${shown.length > 1 ? 'one of these' : 'this'} on ${domain.hostname}.`,
761
+ );
762
+ if (detected) lines.push(` ${domain.hostname} runs on ${detected.label}${evidence ? ` (${evidence})` : ''}.`);
763
+ shown.forEach((r, i) => lines.push('', ...renderRecipe(r, shown.length > 1 ? `${String.fromCharCode(65 + i)}. ` : '')));
764
+ const others = setup.recipes.filter((r) => !shown.includes(r)).map((r) => r.platform);
765
+ lines.push(
766
+ '',
767
+ ` Elsewhere (${others.join(', ')}): \`workover site proxy --project ${projectId ?? '<id>'} --platform <name>\` prints that setup,`,
768
+ ' and --write adds it to the website\'s repository.',
769
+ '',
770
+ ` Search engines: add this line to https://${domain.hostname}/robots.txt:`,
771
+ ` ${setup.robotsLine}`,
772
+ );
773
+ } else if (!domain.basePath && domain.status !== 'active' && isRootDomain(domain.hostname)) {
774
+ lines.push('', ` ${domain.hostname} is a root domain: most providers need CNAME flattening, ALIAS or ANAME there.`);
775
+ }
776
+ if (projectId && domain.status !== 'active')
777
+ lines.push('', ` Once the records are in, \`workover site check --project ${projectId}\` says what has been found.`);
778
+ lines.push('');
779
+ return lines;
780
+ }
781
+
782
+ /** One platform's setup as lines: what to do, any console steps, then the code, indented. */
783
+ export function renderRecipe(recipe, prefix = '') {
784
+ const lines = [` ${prefix}${recipe.label}. ${recipe.where}`];
785
+ if (!recipe.tested) lines.push(' (Not yet driven end to end by Workover. `workover site check` says whether it works.)');
786
+ if (recipe.steps.length) {
787
+ lines.push('', ' In the console:');
788
+ recipe.steps.forEach((step, i) => lines.push(` ${i + 1}. ${step}`));
789
+ lines.push('', ' Or as code:');
790
+ }
791
+ lines.push('', ...recipe.code.trimEnd().split('\n').map((l) => ` ${l}`));
792
+ return lines;
793
+ }
794
+
795
+ /** Where the person's website runs, as the api guesses it from the site's headers; null on any failure. */
796
+ export async function detectPlatform(call, { projectId }) {
797
+ try {
798
+ const res = await call(`/sites/project/${projectId}/mount/platform`);
799
+ return { platform: res?.platform ?? null, evidence: res?.evidence ?? null };
800
+ } catch {
801
+ return { platform: null, evidence: null };
802
+ }
803
+ }
804
+
805
+ /** `workover site proxy`: the setup for one platform, filled in with the site's values. */
806
+ export function proxyRecipe(domain, platform) {
807
+ if (!domain?.hostname || !domain.basePath)
808
+ throw apiError(400, 'This Help Center is not served under a path. `workover site domain --set example.com/docs` sets one.');
809
+ if (!domain.mountHost) throw apiError(409, 'The site has no public host yet. `workover site domain` shows where it stands.');
810
+ const recipes = mountSetup(domain.hostname, domain.basePath, domain.mountHost).recipes;
811
+ return recipes.find((r) => r.platform === platform) ?? null;
812
+ }
813
+
814
+ /** Take the site offline. Its pages, settings and domain stay; publishing again restores it. */
815
+ export async function unpublishSite(call, { projectId }) {
816
+ return call(`/sites/project/${projectId}/unpublish`, { method: 'POST' });
817
+ }
818
+
819
+ export function renderUnpublish({ projectId } = {}) {
820
+ return [
821
+ '',
822
+ ' Taken offline. Its pages, settings and domain are kept; readers get a "not found" page until it is published again.',
823
+ ` \`workover site publish --project ${projectId}\` puts it back.`,
824
+ '',
825
+ ];
826
+ }
827
+
828
+ const MOUNT_VERDICT_OK = new Set(['indexable', 'noindex-setting']);
829
+
830
+ /** `workover site check`. */
831
+ export function renderCheck(res, { projectId } = {}) {
832
+ if (!res?.site) return ['', ` Project #${projectId} has no Help Center. \`workover site create --project ${projectId}\` adds one.`, ''];
833
+ const lines = ['', ...siteLines(res.site)];
834
+ lines.push(
835
+ ...renderDomain(res.domain, { projectId, platform: res.mount?.platform ?? null, evidence: res.mount?.evidence ?? null }).slice(0, -1),
836
+ );
837
+ if (res.mount) {
838
+ lines.push('', ` Live check of https://${res.domain.hostname}${res.domain.basePath}: ${MOUNT_VERDICT_OK.has(res.mount.verdict) ? '✓' : '✗'} ${res.mount.message}`);
839
+ }
840
+ lines.push('');
841
+ return lines;
842
+ }
843
+
844
+ const importProgress = (p) =>
845
+ !p ? 'starting' : p.phase === 'discovering' ? 'finding pages' : `${p.phase} ${p.done} of ${p.total} pages`;
846
+
847
+ /** One running state of an import, for progress lines. */
848
+ export const importProgressLine = (state) => ` … importing: ${importProgress(state?.progress)}`;
849
+
850
+ /** `workover site import`. */
851
+ export function renderImport(state, { projectId } = {}) {
852
+ if (!state || state.status === 'none') return ['', ' No import has run on this site in the last hour.', ''];
853
+ if (state.status === 'running')
854
+ return [
855
+ '',
856
+ ` Still importing (${importProgress(state.progress)}), started ${state.startedAt}.`,
857
+ ` It carries on without you. \`workover site import --project ${projectId} --status\` checks again.`,
858
+ '',
859
+ ];
860
+ if (state.status === 'failed') return ['', ` ✗ The import failed: ${state.error}`, ''];
861
+ const r = state.result ?? {};
862
+ const lines = ['', ` ✓ Imported ${r.pages} page${r.pages === 1 ? '' : 's'}${r.source ? ` from ${r.source}` : ''}: ${r.created} new, ${r.kept} already here.`];
863
+ if (r.skipped) lines.push(` ${r.skipped} page${r.skipped === 1 ? ' was' : 's were'} skipped (not readable as docs).`);
864
+ if (r.truncated) lines.push(' The site has more pages than one import takes (500); run the import again for the rest.');
865
+ lines.push(' Nothing is live until the site is published:', ` workover site publish --project ${projectId}`, '');
866
+ return lines;
867
+ }
868
+
869
+ /** One running state of a publish, for progress lines. */
870
+ export const publishProgressLine = (state) =>
871
+ ` … publishing${state?.progress?.total ? `: ${state.progress.done} of ${state.progress.total} pages` : ''}`;
872
+
873
+ /** `workover site publish`. */
874
+ export function renderPublish(state, { projectId, site } = {}) {
875
+ if (!state || state.status === 'none') return ['', ' This site has not been published in the last hour.', ''];
876
+ if (state.status === 'running')
877
+ return [
878
+ '',
879
+ ` Still publishing${state.progress?.total ? ` (${state.progress.done} of ${state.progress.total} pages)` : ''}, started ${state.startedAt}.`,
880
+ ` It carries on without you. \`workover site publish --project ${projectId} --status\` checks again.`,
881
+ '',
882
+ ];
883
+ if (state.status === 'failed') return ['', ` ✗ The publish failed: ${state.error}`, ''];
884
+ const r = state.result ?? {};
885
+ const lines = ['', ` ✓ Published ${r.published} page${r.published === 1 ? '' : 's'}.`];
886
+ const urls = [];
887
+ if (site?.address?.url) urls.push(site.address.url);
888
+ const d = site?.domain;
889
+ if (d?.hostname && (d.status === 'active' || d.status === 'unmanaged')) urls.unshift(`https://${d.hostname}${d.basePath ?? ''}`);
890
+ if (urls.length) lines.push(` Live at ${urls.join(' and ')}`);
891
+ if (d?.hostname && d.status !== 'active' && d.status !== 'unmanaged')
892
+ lines.push(` ${d.hostname}${d.basePath ?? ''} follows once its DNS records are found (\`workover site check --project ${projectId}\`).`);
893
+ for (const k of r.kept ?? []) lines.push(` Kept as it was live: ${k}`);
894
+ for (const s of r.skipped ?? []) lines.push(` Skipped: ${s}`);
895
+ for (const h of r.held ?? []) lines.push(` Held back: ${h.title}. ${h.reason}`);
896
+ lines.push('');
897
+ return lines;
898
+ }
899
+
900
+ /** `workover site status`. */
901
+ export function renderSiteStatus(res, { projectId } = {}) {
902
+ if (!res?.site) return ['', ` Project #${projectId} has no Help Center. \`workover site create --project ${projectId}\` adds one.`, ...hostingLine(res?.hosting), ''];
903
+ const lines = ['', ` Project #${projectId}`, ...siteLines(res.site)];
904
+ const d = res.site.domain;
905
+ lines.push(
906
+ ` Domain: ${d?.hostname ? `${d.hostname}${d.basePath ?? ''}, ${DOMAIN_STATUS[d.status] ?? d.status}${d.message ? ` (${d.message})` : ''}` : 'none (optional)'}`,
907
+ );
908
+ const imp = res.import;
909
+ if (imp && imp.status !== 'none')
910
+ lines.push(
911
+ ` Last import: ${imp.status === 'done' ? `${imp.result?.pages ?? 0} pages${imp.result?.source ? ` from ${imp.result.source}` : ''}` : imp.status === 'running' ? `running (${importProgress(imp.progress)})` : `failed: ${imp.error}`}`,
912
+ );
913
+ const pub = res.publish;
914
+ if (pub && pub.status !== 'none')
915
+ lines.push(
916
+ ` Last publish: ${pub.status === 'done' ? `${pub.result?.published ?? 0} pages` : pub.status === 'running' ? 'running' : `failed: ${pub.error}`}`,
917
+ );
918
+ lines.push(` Pages in the navigation: ${countPages(res.nav)}`);
919
+ lines.push(...hostingLine(res.hosting));
920
+ lines.push('', ` \`workover site check --project ${projectId}\` asks the DNS provider now.`, '');
921
+ return lines;
922
+ }
923
+
924
+ const countPages = (nav = []) =>
925
+ nav.reduce((n, item) => n + (item.kind === 'page' || item.documentId ? 1 : 0) + countPages(item.children ?? []), 0);