@crawl82/cli 0.0.0-stage → 0.6.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.
Files changed (59) hide show
  1. package/AGENTS.md +259 -0
  2. package/README.md +120 -2
  3. package/dist/api-types.generated.js +12 -0
  4. package/dist/api-types.generated.js.map +1 -0
  5. package/dist/commands/api.js +111 -0
  6. package/dist/commands/api.js.map +1 -0
  7. package/dist/commands/audit.js +200 -0
  8. package/dist/commands/audit.js.map +1 -0
  9. package/dist/commands/auth.js +284 -0
  10. package/dist/commands/auth.js.map +1 -0
  11. package/dist/commands/completion.js +120 -0
  12. package/dist/commands/completion.js.map +1 -0
  13. package/dist/commands/doctor.js +141 -0
  14. package/dist/commands/doctor.js.map +1 -0
  15. package/dist/commands/feedback.js +39 -0
  16. package/dist/commands/feedback.js.map +1 -0
  17. package/dist/commands/help-json.js +145 -0
  18. package/dist/commands/help-json.js.map +1 -0
  19. package/dist/commands/mcp.js +133 -0
  20. package/dist/commands/mcp.js.map +1 -0
  21. package/dist/commands/read.js +107 -0
  22. package/dist/commands/read.js.map +1 -0
  23. package/dist/commands/sites.js +621 -0
  24. package/dist/commands/sites.js.map +1 -0
  25. package/dist/commands/workspaces.js +66 -0
  26. package/dist/commands/workspaces.js.map +1 -0
  27. package/dist/credentials.js +151 -0
  28. package/dist/credentials.js.map +1 -0
  29. package/dist/errors.js +150 -0
  30. package/dist/errors.js.map +1 -0
  31. package/dist/exit-codes.js +82 -0
  32. package/dist/exit-codes.js.map +1 -0
  33. package/dist/http.js +291 -0
  34. package/dist/http.js.map +1 -0
  35. package/dist/index.js +164 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/keychain.js +185 -0
  38. package/dist/keychain.js.map +1 -0
  39. package/dist/oauth/browser.js +33 -0
  40. package/dist/oauth/browser.js.map +1 -0
  41. package/dist/oauth/loopback.js +13 -0
  42. package/dist/oauth/loopback.js.map +1 -0
  43. package/dist/oauth/pkce.js +119 -0
  44. package/dist/oauth/pkce.js.map +1 -0
  45. package/dist/oauth/server.js +281 -0
  46. package/dist/oauth/server.js.map +1 -0
  47. package/dist/operations.generated.js +6712 -0
  48. package/dist/operations.generated.js.map +1 -0
  49. package/dist/output.js +161 -0
  50. package/dist/output.js.map +1 -0
  51. package/dist/refresh-lock.js +84 -0
  52. package/dist/refresh-lock.js.map +1 -0
  53. package/dist/run.js +188 -0
  54. package/dist/run.js.map +1 -0
  55. package/dist/session.js +181 -0
  56. package/dist/session.js.map +1 -0
  57. package/dist/version.js +34 -0
  58. package/dist/version.js.map +1 -0
  59. package/package.json +47 -4
@@ -0,0 +1,621 @@
1
+ /**
2
+ * `crawl82 sites | brief | issues | pages | actions | crawls | controls`: Crawl82's own commands.
3
+ *
4
+ * The same operations as the REST API (`/v1/sites/...`) and the MCP tools; the coverage test fails when an
5
+ * operation has no command here or a field has no flag. The rules of every command in this CLI:
6
+ *
7
+ * 1. One write per command, so a command cannot half-fail.
8
+ * 2. `session.printer.data(raw, view)`: the RAW object goes to JSON, the view only to a terminal.
9
+ * 3. Exit codes carry meaning (`run()` maps the API's error families).
10
+ * 4. `--help` is the documentation most people and every agent read: written for someone new.
11
+ *
12
+ * `crawl82 brief <site_id>` is the one an agent starts from: in a terminal it prints the Markdown brief
13
+ * itself, ready to read; `--json` gives the whole object.
14
+ */
15
+ import { readFileSync } from "node:fs";
16
+ import { ACTION_STATUS_VALUES, ISSUE_PRIORITY_VALUES, SETTABLE_ACTION_STATUS_VALUES, SITE_CADENCE_VALUES, } from "../api-types.generated.js";
17
+ import { formatDate, formatNumber } from "../output.js";
18
+ import { CliError, usageError } from "../errors.js";
19
+ import { EXIT } from "../exit-codes.js";
20
+ import { confirmSpend, run, typedCommand, unwrap } from "../run.js";
21
+ const list = (values) => values.join(" | ");
22
+ const csv = (value) => (value === undefined ? undefined : value.split(",").map((v) => v.trim()).filter(Boolean));
23
+ const int = (value, flag) => {
24
+ if (value === undefined)
25
+ return undefined;
26
+ const n = Number(value);
27
+ if (!Number.isInteger(n))
28
+ throw usageError(`${flag} takes a whole number.`, flag.slice(2));
29
+ return n;
30
+ };
31
+ const str = (value) => (value === null || value === undefined ? "-" : String(value));
32
+ /** A recipe run is answered when it is done: a batch of pages or of AI calls can pass the usual 60 seconds. */
33
+ const RECIPE_RUN_TIMEOUT_MS = 180_000;
34
+ export function registerSites(program) {
35
+ // ── sites ────────────────────────────────────────────────────────────────
36
+ const sites = program.command("sites").description("The workspace's sites: list, add, read, change");
37
+ sites
38
+ .command("list")
39
+ .description("List sites with their last crawl and open actions")
40
+ .action(async (_options, command) => {
41
+ await run(command, async (session) => {
42
+ const data = unwrap((await session.client.request("GET", "/sites")).body);
43
+ session.printer.data(data, {
44
+ rows: data.sites,
45
+ columns: [
46
+ { header: "ID", value: (row) => row.id },
47
+ { header: "NAME", value: (row) => row.name },
48
+ { header: "CADENCE", value: (row) => row.cadence },
49
+ { header: "OPEN ACTIONS", value: (row) => str(row.open_actions) },
50
+ { header: "NEXT CRAWL", value: (row) => (row.next_crawl_at ? formatDate(row.next_crawl_at) : "-") },
51
+ ],
52
+ });
53
+ });
54
+ });
55
+ sites
56
+ .command("add <url>")
57
+ .description("Add a site and start its first crawl (reads from the plan's pages a month; needs crawls:create)")
58
+ .option("--cadence <cadence>", list(SITE_CADENCE_VALUES))
59
+ .option("--max-urls <n>", "URLs per crawl, the first one included (default: the plan's limit)")
60
+ .option("-y, --yes", "Start the first crawl without asking")
61
+ .action(async (url, options, command) => {
62
+ await run(command, async (session) => {
63
+ await confirmSpend(session, `Add ${url} and crawl it now? Its first crawl reads from your plan's pages this month.`, { yes: options.yes, command: typedCommand(command, ["-y", "--yes"]), spends: "credits" });
64
+ const response = await session.client.request("POST", "/sites", { body: { url, ...(options.cadence ? { cadence: options.cadence } : {}), ...(options.maxUrls !== undefined ? { max_urls: int(options.maxUrls, "--max-urls") } : {}) } });
65
+ const data = unwrap(response.body);
66
+ session.printer.data(data, { fields: [{ label: "Site", value: data.siteId }, { label: "Crawling", value: data.crawlStarted ? "yes" : "no" }] });
67
+ });
68
+ });
69
+ sites
70
+ .command("get <site_id>")
71
+ .description("A site's settings and its crawl log, newest first")
72
+ .action(async (siteId, _options, command) => {
73
+ await run(command, async (session) => {
74
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}`)).body);
75
+ session.printer.data(data, {
76
+ fields: [
77
+ { label: "Name", value: data.site.name },
78
+ { label: "Start URL", value: data.site.start_url },
79
+ { label: "Cadence", value: data.site.cadence },
80
+ { label: "URLs per crawl", value: formatNumber(data.site.max_urls) },
81
+ ],
82
+ rows: data.crawls,
83
+ columns: [
84
+ { header: "CRAWL", value: (row) => `#${str(row.number)}` },
85
+ { header: "ID", value: (row) => row.id },
86
+ { header: "STATUS", value: (row) => row.status },
87
+ ],
88
+ });
89
+ });
90
+ });
91
+ sites
92
+ .command("overview <site_id>")
93
+ .description("The latest crawl, Search Console over 28 days, the open actions")
94
+ .action(async (siteId, _options, command) => {
95
+ await run(command, async (session) => {
96
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/overview`)).body);
97
+ session.printer.data(data, { fields: [{ label: "Latest crawl", value: data.crawl ? `#${str(data.crawl.number)}, ${str(data.crawl.finished_at)}` : "none yet" }, { label: "Open actions", value: String(data.open_actions.length) }] });
98
+ });
99
+ });
100
+ sites
101
+ .command("update <site_id>")
102
+ .description("Change a site's name, start URL, cadence, crawl days, URL budget, or include and exclude patterns")
103
+ .option("--name <name>", "New name")
104
+ .option("--start-url <url>", "New start URL")
105
+ .option("--cadence <cadence>", list(SITE_CADENCE_VALUES))
106
+ .option("--crawl-days <days>", "Weekly: the days, comma separated (mon,thu); one on Starter, several on Pro")
107
+ .option("--max-urls <n>", "URLs per crawl, within the plan's limit")
108
+ .option("--include <globs>", "Only crawl URLs matching these globs, comma separated (/blog/*). Replaces the list")
109
+ .option("--exclude <globs>", "Never crawl URLs matching these globs, comma separated. Replaces the list")
110
+ .action(async (siteId, options, command) => {
111
+ await run(command, async (session) => {
112
+ const body = {
113
+ ...(options.name !== undefined ? { name: options.name } : {}),
114
+ ...(options.startUrl !== undefined ? { start_url: options.startUrl } : {}),
115
+ ...(options.cadence !== undefined ? { cadence: options.cadence } : {}),
116
+ ...(options.crawlDays !== undefined ? { crawl_days: (csv(options.crawlDays) ?? []).map((d) => d.toLowerCase().slice(0, 3)) } : {}),
117
+ ...(options.maxUrls !== undefined ? { max_urls: int(options.maxUrls, "--max-urls") } : {}),
118
+ ...(options.include !== undefined ? { include: csv(options.include) } : {}),
119
+ ...(options.exclude !== undefined ? { exclude: csv(options.exclude) } : {}),
120
+ };
121
+ if (!Object.keys(body).length)
122
+ throw usageError("Pass at least one setting to change.", "name");
123
+ const data = unwrap((await session.client.request("PATCH", `/sites/${encodeURIComponent(siteId)}`, { body })).body);
124
+ session.printer.data(data, { summary: "Updated. It takes effect from the next crawl." });
125
+ });
126
+ });
127
+ sites
128
+ .command("identity <site_id>")
129
+ .description("Read a site's Identity Card (offer, audience, money pages, competitors, official anchors)")
130
+ .action(async (siteId, _options, command) => {
131
+ await run(command, async (session) => {
132
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/identity`)).body);
133
+ session.printer.data(data);
134
+ });
135
+ });
136
+ sites
137
+ .command("schema-plan <site_id>")
138
+ .description("Structured data plan per template: role, types to carry, each field's state and where the page shows it")
139
+ .option("--crawl-id <id>", "A past crawl (default: the latest)")
140
+ .action(async (siteId, options, command) => {
141
+ await run(command, async (session) => {
142
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/schema-plan`, { query: { crawl_id: options.crawlId } })).body);
143
+ session.printer.data(data);
144
+ });
145
+ });
146
+ sites
147
+ .command("identity-update <site_id>")
148
+ .description("Update a site's Identity Card and optional GA4 property")
149
+ .option("--summary <text>", "Short business summary")
150
+ .option("--audience <text>", "Target buyer or reader persona")
151
+ .option("--offer <text>", "Core commercial offer")
152
+ .option("--language <code>", "Primary ISO-639-1 language code")
153
+ .option("--site-profile <profile>", "Vertical profile: general | saas | ecommerce | jobs | local | media")
154
+ .option("--strategic-pages <json>", 'Strategic pages JSON array, e.g. \'[{"path":"/pricing","role":"money","goal":"Trials"}]\'')
155
+ .option("--money-pages <paths>", "Pinned money page paths, comma separated")
156
+ .option("--excluded-money-pages <paths>", "Excluded money page paths, comma separated")
157
+ .option("--competitors <hosts>", "Competitor hostnames, comma separated")
158
+ .option("--brand-names <names>", "How the site writes its own name, comma separated (read in AI answers)")
159
+ .option("--competitor-names <json>", 'Competitor host to name JSON object, e.g. \'{"example.com":"Example"}\'')
160
+ .option("--preview-hosts <hosts>", "Hosting preview addresses check_preview_url may read, comma separated (when the project is not named like the site)")
161
+ .option("--ga4-property <id>", "Optional GA4 property id")
162
+ .action(async (siteId, options, command) => {
163
+ await run(command, async (session) => {
164
+ let strategicPages;
165
+ if (options.strategicPages !== undefined) {
166
+ try {
167
+ strategicPages = JSON.parse(options.strategicPages);
168
+ }
169
+ catch {
170
+ throw usageError("--strategic-pages must be valid JSON.", "strategic-pages");
171
+ }
172
+ }
173
+ const body = {
174
+ ...(options.summary !== undefined ? { summary: options.summary } : {}),
175
+ ...(options.audience !== undefined ? { audience: options.audience } : {}),
176
+ ...(options.offer !== undefined ? { offer: options.offer } : {}),
177
+ ...(options.language !== undefined ? { language: options.language } : {}),
178
+ ...(options.siteProfile !== undefined ? { site_profile: options.siteProfile } : {}),
179
+ ...(strategicPages !== undefined ? { strategic_pages: strategicPages } : {}),
180
+ ...(options.brandNames !== undefined ? { brand_names: csv(options.brandNames) } : {}),
181
+ ...(options.competitorNames !== undefined ? { competitor_names: JSON.parse(options.competitorNames) } : {}),
182
+ ...(options.moneyPages !== undefined ? { money_pages: csv(options.moneyPages) } : {}),
183
+ ...(options.excludedMoneyPages !== undefined ? { excluded_money_pages: csv(options.excludedMoneyPages) } : {}),
184
+ ...(options.competitors !== undefined ? { competitors: csv(options.competitors) } : {}),
185
+ ...(options.previewHosts !== undefined ? { preview_hosts: csv(options.previewHosts) } : {}),
186
+ ...(options.ga4Property !== undefined ? { ga4_property: options.ga4Property || null } : {}),
187
+ };
188
+ const data = unwrap((await session.client.request("PATCH", `/sites/${encodeURIComponent(siteId)}/identity`, { body })).body);
189
+ session.printer.data(data, { summary: "Site identity updated." });
190
+ });
191
+ });
192
+ // ── brief ────────────────────────────────────────────────────────────────
193
+ program
194
+ .command("brief <site_id>")
195
+ .description("The fixes worth doing first on a site, written for an agent (start here)")
196
+ .option("--limit <n>", "How many actions (1-20, default 5)")
197
+ .action(async (siteId, options, command) => {
198
+ await run(command, async (session) => {
199
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/brief`, { query: { limit: options.limit } })).body);
200
+ if (session.printer.resolution.mode === "table")
201
+ process.stdout.write(`${data.markdown}\n`);
202
+ else
203
+ session.printer.data(data);
204
+ });
205
+ });
206
+ // ── issues ───────────────────────────────────────────────────────────────
207
+ const issues = program.command("issues").description("A crawl's findings, by control");
208
+ issues
209
+ .command("list <site_id>")
210
+ .description("The controls that found something, highest priority first")
211
+ .option("--crawl-id <id>", "A past crawl (default: the latest)")
212
+ .option("--category <name>", "Only this category, e.g. 'Response codes'")
213
+ .option("--priority <priority>", list(ISSUE_PRIORITY_VALUES))
214
+ .action(async (siteId, options, command) => {
215
+ await run(command, async (session) => {
216
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/issues`, { query: { crawl_id: options.crawlId, category: options.category, priority: options.priority } })).body);
217
+ session.printer.data(data, {
218
+ rows: data.controls,
219
+ columns: [
220
+ { header: "CODE", value: (row) => row.code },
221
+ { header: "PRIORITY", value: (row) => row.priority },
222
+ { header: "URLS", value: (row) => formatNumber(row.urls) },
223
+ { header: "LABEL", value: (row) => row.label },
224
+ ],
225
+ });
226
+ });
227
+ });
228
+ issues
229
+ .command("urls <site_id> <code>")
230
+ .description("One finding, ready to fix: how, the rule behind it, the templates and URLs (50 at a time)")
231
+ .option("--crawl-id <id>", "A past crawl (default: the latest)")
232
+ .option("--offset <n>", "Skip this many URLs")
233
+ .action(async (siteId, code, options, command) => {
234
+ await run(command, async (session) => {
235
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/issues/${encodeURIComponent(code)}/urls`, { query: { crawl_id: options.crawlId, offset: options.offset } })).body);
236
+ // For a person or an agent reading the terminal: the brief (how to fix, the rule, the templates).
237
+ // `--json` keeps every field, the URLs included.
238
+ if (session.printer.resolution.mode === "table")
239
+ process.stdout.write(`${data.markdown}\n`);
240
+ else
241
+ session.printer.data(data, { rows: data.urls, columns: [{ header: "URL", value: (row) => row.url }], summary: `${formatNumber(data.total)} in all` });
242
+ });
243
+ });
244
+ // ── pages ────────────────────────────────────────────────────────────────
245
+ const pages = program.command("pages").description("The crawled pages, like the page explorer");
246
+ pages
247
+ .command("query <site_id>")
248
+ .description("Query crawled URLs with conditions, a sort and columns (50 rows at most)")
249
+ .option("--crawl-id <id>", "A past crawl (default: the latest)")
250
+ .option("--join <join>", "and | or: how the conditions combine (default and)")
251
+ .option("--conditions <json>", 'A JSON array of conditions, e.g. \'[{"column":"status","op":"gte","value":400}]\'')
252
+ .option("--search <text>", "Text the URL or title contains")
253
+ .option("--sort <field>", "Field to sort by (default unique_inlinks)")
254
+ .option("--dir <dir>", "asc | desc")
255
+ .option("--columns <fields>", "Fields to return, comma separated (url always first)")
256
+ .option("--limit <n>", "Rows, at most 50 (default 25)")
257
+ .option("--offset <n>", "Skip this many rows")
258
+ .action(async (siteId, options, command) => {
259
+ await run(command, async (session) => {
260
+ let conditions;
261
+ if (options.conditions !== undefined) {
262
+ try {
263
+ conditions = JSON.parse(options.conditions);
264
+ }
265
+ catch {
266
+ throw usageError("--conditions takes a JSON array.", "conditions");
267
+ }
268
+ }
269
+ const body = {
270
+ ...(options.crawlId ? { crawl_id: options.crawlId } : {}),
271
+ ...(options.join ? { join: options.join } : {}),
272
+ ...(conditions !== undefined ? { conditions } : {}),
273
+ ...(options.search ? { search: options.search } : {}),
274
+ ...(options.sort ? { sort: options.sort } : {}),
275
+ ...(options.dir ? { dir: options.dir } : {}),
276
+ ...(options.columns ? { columns: csv(options.columns) } : {}),
277
+ ...(options.limit !== undefined ? { limit: int(options.limit, "--limit") } : {}),
278
+ ...(options.offset !== undefined ? { offset: int(options.offset, "--offset") } : {}),
279
+ };
280
+ const data = unwrap((await session.client.request("POST", `/sites/${encodeURIComponent(siteId)}/pages/query`, { body })).body);
281
+ session.printer.data(data, { rows: data.rows, summary: `${formatNumber(data.total)} match` });
282
+ });
283
+ });
284
+ pages
285
+ .command("get <site_id>")
286
+ .description("One crawled URL in full: status, headings, links, Search Console, findings")
287
+ .requiredOption("--url <url>", "The full URL")
288
+ .option("--crawl-id <id>", "A past crawl (default: the latest)")
289
+ .action(async (siteId, options, command) => {
290
+ await run(command, async (session) => {
291
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/page`, { query: { url: options.url, crawl_id: options.crawlId } })).body);
292
+ session.printer.data(data);
293
+ });
294
+ });
295
+ pages
296
+ .command("search <site_id>")
297
+ .description("Search the crawled pages: exact words (URL, title, H1, text) and the pages nearest in meaning")
298
+ .requiredOption("--q <text>", "Search term or phrase")
299
+ .option("--section <name>", "Optional top-level path section")
300
+ .option("--lang <code>", "Optional language code")
301
+ .option("--indexable-only", "Only search indexable pages")
302
+ .option("--limit <n>", "Max matches (1-50)")
303
+ .action(async (siteId, options, command) => {
304
+ await run(command, async (session) => {
305
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/search`, {
306
+ query: {
307
+ q: options.q,
308
+ section: options.section,
309
+ lang: options.lang,
310
+ indexable_only: options.indexableOnly ? "true" : undefined,
311
+ limit: options.limit,
312
+ },
313
+ })).body);
314
+ session.printer.data(data);
315
+ });
316
+ });
317
+ pages
318
+ .command("outline <site_id>")
319
+ .description("Compact LLM-friendly outline of one crawled URL")
320
+ .requiredOption("--url <url>", "The full URL")
321
+ .option("--crawl-id <id>", "A past crawl (default: the latest)")
322
+ .action(async (siteId, options, command) => {
323
+ await run(command, async (session) => {
324
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/page/outline`, { query: { url: options.url, crawl_id: options.crawlId } })).body);
325
+ session.printer.data(data);
326
+ });
327
+ });
328
+ pages
329
+ .command("links <site_id>")
330
+ .description("Local internal link neighborhood around one URL (inlinks, outlinks, siblings)")
331
+ .requiredOption("--url <url>", "The full URL")
332
+ .option("--crawl-id <id>", "A past crawl (default: the latest)")
333
+ .action(async (siteId, options, command) => {
334
+ await run(command, async (session) => {
335
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/page/links`, { query: { url: options.url, crawl_id: options.crawlId } })).body);
336
+ session.printer.data(data);
337
+ });
338
+ });
339
+ // ── actions ──────────────────────────────────────────────────────────────
340
+ const actions = program.command("actions").description("The fixes worth doing, and their status");
341
+ actions
342
+ .command("list <site_id>")
343
+ .description("A site's actions, highest score first (open and planned by default)")
344
+ .option("--status <status>", list(ACTION_STATUS_VALUES))
345
+ .option("--offset <n>", "Skip this many actions")
346
+ .action(async (siteId, options, command) => {
347
+ await run(command, async (session) => {
348
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/actions`, { query: { status: options.status, offset: options.offset } })).body);
349
+ session.printer.data(data, {
350
+ rows: data.actions,
351
+ columns: [
352
+ { header: "ID", value: (row) => row.id },
353
+ { header: "STATUS", value: (row) => row.status },
354
+ { header: "LANE", value: (row) => row.lane },
355
+ { header: "TITLE", value: (row) => row.title },
356
+ ],
357
+ summary: `${formatNumber(data.total)} in all`,
358
+ });
359
+ });
360
+ });
361
+ actions
362
+ .command("update <site_id>")
363
+ .description("Mark actions planned, done or dismissed (only a crawl marks them verified)")
364
+ .requiredOption("--action-ids <ids>", "Action ids, comma separated")
365
+ .requiredOption("--status <status>", list(SETTABLE_ACTION_STATUS_VALUES))
366
+ .option("--reason <text>", "For dismissed: why, in a sentence")
367
+ .action(async (siteId, options, command) => {
368
+ await run(command, async (session) => {
369
+ const body = { action_ids: csv(options.actionIds), status: options.status, ...(options.reason ? { reason: options.reason } : {}) };
370
+ const data = unwrap((await session.client.request("PATCH", `/sites/${encodeURIComponent(siteId)}/actions`, { body })).body);
371
+ session.printer.data(data, { summary: `${data.updated} updated` });
372
+ });
373
+ });
374
+ // ── crawls ───────────────────────────────────────────────────────────────
375
+ const crawls = program.command("crawls").description("Start, follow and stop crawls");
376
+ crawls
377
+ .command("quote <site_id>")
378
+ .description("What a crawl started now would read, what is left this month, and whether it can start (free)")
379
+ .action(async (siteId, _options, command) => {
380
+ await run(command, async (session) => {
381
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/crawls/quote`)).body);
382
+ session.printer.data(data, {
383
+ fields: [
384
+ { label: "URLs at most", value: formatNumber(data.urls_max) },
385
+ { label: "From this month's pages", value: `${formatNumber(data.pages.from_plan)} of ${formatNumber(data.pages.left)} left` },
386
+ { label: "Credits at most", value: data.credits.max ? `${formatNumber(data.credits.max)} for ${formatNumber(data.pages.from_credits)} more pages (${data.credits.pages_per_credit} a credit) of ${formatNumber(data.credits.balance)}` : "none" },
387
+ { label: "Last crawl", value: data.last_crawl?.finished_at ? `${formatDate(data.last_crawl.finished_at)}, ${formatNumber(data.last_crawl.urls ?? 0)} URLs` : "-" },
388
+ { label: "Next scheduled", value: data.next_scheduled_at ? formatDate(data.next_scheduled_at) : "-" },
389
+ ],
390
+ summary: data.message,
391
+ });
392
+ });
393
+ });
394
+ crawls
395
+ .command("start <site_id>")
396
+ .description("Crawl a site now: from the plan's pages a month, then credits past them (says how much first). Returns at once: follow it with crawls get")
397
+ .option("-y, --yes", "Start without asking")
398
+ .action(async (siteId, options, command) => {
399
+ await run(command, async (session) => {
400
+ const quote = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/crawls/quote`)).body);
401
+ if (!quote.can_start)
402
+ throw new CliError(quote.message, { exitCode: EXIT.CONFLICT, code: quote.blocked_reason === "running" ? "conflict" : "invalid_request" });
403
+ // Only a crawl that spends credits (pages past the month's) is asked about; the plan's pages are not money.
404
+ if (quote.credits.max > 0)
405
+ await confirmSpend(session, `${quote.message} Start it?`, { yes: options.yes, command: `crawls start ${siteId}`, reviewCommand: `crawls quote ${siteId}`, spends: "credits" });
406
+ const data = unwrap((await session.client.request("POST", `/sites/${encodeURIComponent(siteId)}/crawls`)).body);
407
+ session.printer.data(data, { fields: [{ label: "Crawl", value: data.crawl_id }], summary: `Follow it: crawl82 crawls get ${siteId} ${data.crawl_id}` });
408
+ });
409
+ });
410
+ crawls
411
+ .command("get <site_id> <crawl_id>")
412
+ .description("A crawl's status and progress")
413
+ .action(async (siteId, crawlId, _options, command) => {
414
+ await run(command, async (session) => {
415
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/crawls/${encodeURIComponent(crawlId)}`)).body);
416
+ session.printer.data(data);
417
+ });
418
+ });
419
+ crawls
420
+ .command("cancel <site_id> <crawl_id>")
421
+ .description("Stop a crawl at its next batch (URLs already read stay counted)")
422
+ .action(async (siteId, crawlId, _options, command) => {
423
+ await run(command, async (session) => {
424
+ const data = unwrap((await session.client.request("POST", `/sites/${encodeURIComponent(siteId)}/crawls/${encodeURIComponent(crawlId)}/cancel`)).body);
425
+ session.printer.data(data, { summary: data.cancelled ? "Stopping." : "Nothing to stop." });
426
+ });
427
+ });
428
+ // ── controls ─────────────────────────────────────────────────────────────
429
+ program
430
+ .command("controls")
431
+ .description("The controls Crawl82 runs")
432
+ .command("get <code>")
433
+ .description("Why a control's threshold is what it is, and its sources")
434
+ .action(async (code, _options, command) => {
435
+ await run(command, async (session) => {
436
+ const data = unwrap((await session.client.request("GET", `/controls/${encodeURIComponent(code)}`)).body);
437
+ session.printer.data(data);
438
+ });
439
+ });
440
+ // ── sql (read-only agentic SQL over CrawlDb) ────────────────────────────
441
+ const sqlCmd = program.command("sql").description("Read-only SQLite schema and SELECT queries on a crawl");
442
+ sqlCmd
443
+ .command("schema <site_id>")
444
+ .description("Describe tables, columns, and row counts of a crawl")
445
+ .option("--crawl-id <id>", "A past crawl (default: the latest)")
446
+ .action(async (siteId, options, command) => {
447
+ await run(command, async (session) => {
448
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/schema`, { query: { crawl_id: options.crawlId } })).body);
449
+ session.printer.data(data);
450
+ });
451
+ });
452
+ sqlCmd
453
+ .command("query <site_id>")
454
+ .description("Execute a read-only SELECT or WITH query on a crawl or site history (max 200 rows)")
455
+ .requiredOption("--sql <query>", "Read-only SQL SELECT or WITH query")
456
+ .option("--target <target>", "crawl (default) or history (GSC daily history, issue trends, URL inspections, CWV history, change log)")
457
+ .option("--crawl-id <id>", "A past crawl (when target is crawl; default: the latest)")
458
+ .option("--limit <n>", "Max rows (1-200)")
459
+ .action(async (siteId, options, command) => {
460
+ await run(command, async (session) => {
461
+ const body = {
462
+ sql: options.sql,
463
+ ...(options.target ? { target: options.target } : {}),
464
+ ...(options.crawlId ? { crawl_id: options.crawlId } : {}),
465
+ ...(options.limit !== undefined ? { limit: int(options.limit, "--limit") } : {}),
466
+ };
467
+ const data = unwrap((await session.client.request("POST", `/sites/${encodeURIComponent(siteId)}/sql`, { body })).body);
468
+ session.printer.data(data);
469
+ });
470
+ });
471
+ // ── links (raw internal links & anchor hygiene) ──────────────────────────
472
+ const links = program.command("links").description("Raw internal links and anchor hygiene");
473
+ links
474
+ .command("list <site_id>")
475
+ .description("List internal links with anchor hygiene flags")
476
+ .option("--crawl-id <id>", "A past crawl (default: the latest)")
477
+ .option("--q <text>", "Filter by source, target, or anchor text")
478
+ .option("--position <pos>", "DOM position (content, nav, header, footer)")
479
+ .option("--flag <flag>", "Hygiene flag: empty, generic, long_block, cannibalized, nofollow, broken_or_redirect")
480
+ .option("--conditions <json>", 'Conditions on any link field, a JSON array, e.g. \'[{"column":"generic","op":"is_true"}]\'')
481
+ .option("--join <join>", "and | or: how the conditions combine (default and)")
482
+ .option("--offset <n>", "Rows to skip")
483
+ .option("--limit <n>", "Rows to return (1-200)")
484
+ .action(async (siteId, options, command) => {
485
+ await run(command, async (session) => {
486
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/links`, {
487
+ query: { crawl_id: options.crawlId, q: options.q, position: options.position, flag: options.flag, conditions: options.conditions, join: options.join, offset: options.offset, limit: options.limit },
488
+ })).body);
489
+ session.printer.data(data);
490
+ });
491
+ });
492
+ // ── modules ──────────────────────────────────────────────────────────────
493
+ const modules = program.command("modules").description("Read SEO/GEO intelligence modules");
494
+ modules
495
+ .command("get <site_id> <module>")
496
+ .description("Read one module: technical, linking, pruning, serp, opportunities, backlinks, ai_readiness")
497
+ .option("--crawl-id <id>", "A past crawl (default: the latest)")
498
+ .action(async (siteId, mod, options, command) => {
499
+ await run(command, async (session) => {
500
+ const data = unwrap((await session.client.request("GET", `/sites/${encodeURIComponent(siteId)}/modules/${encodeURIComponent(mod)}`, { query: { crawl_id: options.crawlId } })).body);
501
+ session.printer.data(data);
502
+ });
503
+ });
504
+ // ── recipes ──────────────────────────────────────────────────────────────
505
+ const recipes = program.command("recipes").description("List and run SEO/GEO intelligence recipes");
506
+ recipes
507
+ .command("list")
508
+ .description("List all modules and runnable SEO/GEO recipes with their cost; --recipe for one with how to read its result")
509
+ .option("--recipe <id>", "One recipe, with its summary and how to read its result")
510
+ .action(async (options, command) => {
511
+ await run(command, async (session) => {
512
+ const data = unwrap((await session.client.request("GET", "/recipes", options.recipe ? { query: { recipe: options.recipe } } : {})).body);
513
+ session.printer.data(data);
514
+ });
515
+ });
516
+ recipes
517
+ .command("run <site_id> <recipe>")
518
+ .description("Run an SEO/GEO recipe. A paid one is quoted first and asks before spending (--yes to skip the question, --max-credits for a ceiling)")
519
+ .option("--mode <mode>", "standard | ai")
520
+ .option("--url <url>", "Single target page URL or path")
521
+ .option("--urls <list>", "Comma-separated list of target page URLs or paths")
522
+ .option("--url-pattern <pattern>", "Path regex or glob (e.g. ^/blog/ or /blog/**) for batch targeting")
523
+ .option("--all-urls", "Target all matching crawled pages (up to the recipe's batch ceiling)")
524
+ .option("--preview-url <url>", "check_preview_url: a public preview address, without query, fragment or password (previews that need a token are not supported yet)")
525
+ .option("--query <text>", "Target search query or topic")
526
+ .option("--keywords <list>", "Comma-separated keywords")
527
+ .option("--page-type <type>", "vs | alternatives | how_to | tool | landing")
528
+ .option("--draft-title <text>", "Draft title for plan_page_links or build_page_brief")
529
+ .option("--draft-text <text>", "Draft text for plan_page_links")
530
+ .option("--redirects-file <path>", "check_redirect_map: a file with one redirect per line, old URL then new URL (or 410)")
531
+ .option("--csv-file <path>", "audit_indexation_health: Google Search Console Pages CSV export file")
532
+ .option("--default-reason <text>", "audit_indexation_health: reason label for a single-reason GSC CSV")
533
+ .option("--log-file <path>", "audit_bot_logs: server/CDN log file (NDJSON, Combined, or CSV)")
534
+ .option("--site-profile <profile>", "audit_vertical_seo: general | saas | ecommerce | jobs | local | media")
535
+ .option("--min-clicks <n>", "diagnose_traffic_drop: minimum baseline clicks for affected pages")
536
+ .option("--action-id <id>", "verify_fix_impact: action id to link or filter; notify_search_engines: send the action's pages")
537
+ .option("--change-kind <kind>", "verify_fix_impact: title_meta | content | technical | links | schema | pruning | migration | other")
538
+ .option("--change-summary <text>", "verify_fix_impact: summary of a deployed fix to log")
539
+ .option("--commit-sha <sha>", "verify_fix_impact: optional git commit SHA")
540
+ .option("--deployed-at <iso>", "verify_fix_impact: when the fix went live (ISO date-time)")
541
+ .option("--lang <code>", "Language code")
542
+ .option("--country <code>", "Country code")
543
+ .option("--limit <n>", "Max pages or items (up to 200)")
544
+ .option("--runs <n>", "check_ai_citations: times each engine is sent each prompt (1 to 3, default 3)")
545
+ .option("--force-refresh", "Bypass fresh result cache and underlying raw caches")
546
+ .option("--dry-run", "Quote the credits, matched URL count, and revision, spend nothing")
547
+ .option("--expected-revision <rev>", "Revision returned by --dry-run")
548
+ .option("--max-credits <n>", "Refuse the run when it may take more credits than this")
549
+ .option("-y, --yes", "Run a paid recipe without asking (it is still quoted first)")
550
+ .action(async (siteId, recipe, options, command) => {
551
+ await run(command, async (session) => {
552
+ const body = {
553
+ ...(options.mode ? { mode: options.mode } : {}),
554
+ ...(options.url ? { url: options.url } : {}),
555
+ ...(options.urls ? { urls: csv(options.urls) } : {}),
556
+ ...(options.urlPattern ? { url_pattern: options.urlPattern } : {}),
557
+ ...(options.allUrls ? { all_urls: true } : {}),
558
+ ...(options.previewUrl ? { preview_url: options.previewUrl } : {}),
559
+ ...(options.query ? { query: options.query } : {}),
560
+ ...(options.keywords ? { keywords: csv(options.keywords) } : {}),
561
+ ...(options.pageType ? { page_type: options.pageType } : {}),
562
+ ...(options.draftTitle ? { draft_title: options.draftTitle } : {}),
563
+ ...(options.draftText ? { draft_text: options.draftText } : {}),
564
+ ...(options.redirectsFile ? { redirects: readFileSync(options.redirectsFile, "utf8") } : {}),
565
+ ...(options.csvFile ? { csv_data: readFileSync(options.csvFile, "utf8") } : {}),
566
+ ...(options.defaultReason ? { default_reason: options.defaultReason } : {}),
567
+ ...(options.logFile ? { log_data: readFileSync(options.logFile, "utf8") } : {}),
568
+ ...(options.siteProfile ? { profile: options.siteProfile } : {}),
569
+ ...(options.minClicks !== undefined ? { min_clicks: int(options.minClicks, "--min-clicks") } : {}),
570
+ ...(options.actionId ? { action_id: options.actionId } : {}),
571
+ ...(options.changeKind ? { change_kind: options.changeKind } : {}),
572
+ ...(options.changeSummary ? { change_summary: options.changeSummary } : {}),
573
+ ...(options.commitSha ? { commit_sha: options.commitSha } : {}),
574
+ ...(options.deployedAt ? { deployed_at: options.deployedAt } : {}),
575
+ ...(options.lang ? { lang: options.lang } : {}),
576
+ ...(options.country ? { country: options.country } : {}),
577
+ ...(options.limit !== undefined ? { limit: int(options.limit, "--limit") } : {}),
578
+ ...(options.runs !== undefined ? { runs: int(options.runs, "--runs") } : {}),
579
+ ...(options.forceRefresh ? { force_refresh: true } : {}),
580
+ ...(options.maxCredits !== undefined ? { max_credits: int(options.maxCredits, "--max-credits") } : {}),
581
+ };
582
+ const path = `/sites/${encodeURIComponent(siteId)}/recipes/${encodeURIComponent(recipe)}`;
583
+ // Quote first, always: a paid run is confirmed against its price and pinned to that revision.
584
+ const quote = unwrap((await session.client.request("POST", path, { body: { ...body, dry_run: true } })).body);
585
+ if (options.dryRun) {
586
+ session.printer.data(quote, { summary: quote.estimate.free ? "Free." : `About ${quote.estimate.typical} credits, at most ${quote.estimate.max} (balance ${formatNumber(quote.balance)}). Run it with --expected-revision ${quote.revision}.` });
587
+ return;
588
+ }
589
+ const openingCachedFree = Boolean(!quote.estimate.free && quote.cached_available && !options.forceRefresh);
590
+ let revision = options.expectedRevision;
591
+ let maxCredits = options.maxCredits !== undefined ? int(options.maxCredits, "--max-credits") : undefined;
592
+ if (openingCachedFree) {
593
+ // Opening a cached result must never silently charge if it expires before execution.
594
+ revision = options.expectedRevision ?? quote.revision;
595
+ maxCredits = maxCredits ?? 0;
596
+ }
597
+ else if (!quote.estimate.free) {
598
+ if (quote.within_max_credits === false)
599
+ throw usageError(`This run may take up to ${quote.estimate.max} credits, above --max-credits ${options.maxCredits}. Nothing was charged.`, "max_credits");
600
+ if (quote.balance < quote.estimate.max)
601
+ throw new CliError(`This run may take up to ${quote.estimate.max} credits and the workspace has ${formatNumber(quote.balance)}.`, { exitCode: EXIT.USAGE, code: "insufficient_credits", hint: "Add credits in the app (Billing), or use --mode standard when the recipe has it (1 credit)." });
602
+ // A few credits run without asking (CONFIRM_ABOVE_CREDITS on the server says when to ask).
603
+ if (quote.confirm_required !== false)
604
+ await confirmSpend(session, `${recipe} takes about ${quote.estimate.typical} credits, at most ${quote.estimate.max} (balance ${formatNumber(quote.balance)}). Run it?`, { yes: options.yes, command: typedCommand(command, ["-y", "--yes"]), reviewCommand: `${typedCommand(command, ["-y", "--yes"])} --dry-run` });
605
+ revision = options.expectedRevision ?? quote.revision;
606
+ maxCredits = maxCredits ?? quote.estimate.max;
607
+ }
608
+ const data = unwrap((await session.client.request("POST", path, {
609
+ timeoutMs: RECIPE_RUN_TIMEOUT_MS,
610
+ announceWait: true,
611
+ body: {
612
+ ...body,
613
+ ...(revision ? { expected_revision: revision } : {}),
614
+ ...(maxCredits !== undefined ? { max_credits: maxCredits } : {}),
615
+ },
616
+ })).body);
617
+ session.printer.data(data, { summary: typeof data.credits === "number" ? `${data.cached ? "From cache, " : ""}${data.credits} credits spent, ${formatNumber(Number(data.credits_remaining ?? 0))} left.` : undefined });
618
+ });
619
+ });
620
+ }
621
+ //# sourceMappingURL=sites.js.map