seo 0.2.9 → 0.2.12

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/dist/cli.js CHANGED
@@ -1,186 +1,296 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __seoCreateRequire } from 'node:module'; const require = __seoCreateRequire(import.meta.url);
3
- import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as l,E as u,Et as d,F as f,Ft as p,G as m,Gt as h,H as g,Ht as ee,I as te,It as ne,J as _,Jt as v,K as re,Kt as ie,L as ae,Lt as oe,M as se,Mt as ce,N as le,Nt as ue,O as de,Ot as fe,P as pe,Pt as me,Q as he,Qt as ge,R as _e,Rt as ve,S as ye,Sn as be,St as xe,T as Se,Tt as Ce,U as we,Ut as Te,V as Ee,Vt as De,W as Oe,Wt as ke,X as Ae,Xt as je,Y as Me,Yt as Ne,Z as Pe,Zt as Fe,_ as Ie,_n as Le,_t as Re,a as ze,an as Be,at as Ve,b as He,bn as y,bt as Ue,cn as We,ct as Ge,d as Ke,dn as qe,dt as Je,en as Ye,et as Xe,f as Ze,fn as Qe,ft as $e,g as et,gn as tt,gt as nt,h as rt,hn as it,ht as at,i as ot,in as st,it as ct,j as lt,jt as ut,k as dt,kt as ft,l as pt,ln as mt,lt as ht,m as gt,mn as _t,mt as vt,nn as yt,nt as bt,o as xt,on as St,ot as Ct,p as wt,pn as Tt,pt as Et,q as Dt,qt as Ot,r as kt,rn as At,rt as jt,sn as Mt,st as Nt,t as Pt,tn as Ft,tt as It,u as Lt,un as Rt,ut as zt,v as Bt,vn as Vt,vt as Ht,w as Ut,wt as Wt,x as Gt,xn as Kt,xt as qt,y as Jt,yn as Yt,yt as Xt,z as Zt,zt as Qt}from"./dist-C6zXDARm.js";import{constants as $t,copyFileSync as en,existsSync as b,mkdirSync as tn,readFileSync as nn,readdirSync as rn,realpathSync as an,renameSync as on,rmSync as sn,statSync as cn,writeFileSync as ln}from"node:fs";import{homedir as un}from"node:os";import{basename as dn,dirname as x,isAbsolute as fn,join as S,posix as pn,relative as mn,resolve as hn,win32 as gn}from"node:path";import{randomUUID as _n}from"node:crypto";import{spawn as vn,spawnSync as yn}from"node:child_process";import{fileURLToPath as bn}from"node:url";import{isDeepStrictEqual as xn,stripVTControlCharacters as Sn}from"node:util";import{lstat as Cn,mkdir as wn,mkdtemp as Tn,readFile as En,readdir as Dn,rename as On,rm as kn,writeFile as An}from"node:fs/promises";import{defineCommand as C,runCommand as jn,runMain as Mn}from"citty";import{cancel as Nn,confirm as Pn,intro as Fn,isCancel as In,log as Ln,multiselect as Rn,note as w,outro as zn,password as Bn,select as Vn,text as Hn}from"@clack/prompts";import Un from"picocolors";import Wn from"string-width";import Gn from"cli-table3";import{applyEdits as Kn,modify as qn,parse as Jn,printParseErrorCode as Yn}from"jsonc-parser";import Xn from"update-notifier";const Zn={summary:`workflow.site.generated_at.summary.attribution.confidence.classification.updates_matched.known_confounders.page_segment_status.page_segment_eligible_rows.page_segment_returned_rows.page_segment_limited_rows.page_segment_result_limit.page_segment_source_row_limit.page_segment_source_possibly_truncated.page_segment_warnings.query_segment_status.query_segment_eligible_rows.query_segment_returned_rows.query_segment_limited_rows.query_segment_result_limit.query_segment_source_row_limit.query_segment_source_possibly_truncated.query_segment_warnings.device_segment_status.device_segment_eligible_rows.device_segment_returned_rows.device_segment_limited_rows.device_segment_result_limit.device_segment_source_row_limit.device_segment_source_possibly_truncated.device_segment_warnings.country_segment_status.country_segment_eligible_rows.country_segment_returned_rows.country_segment_limited_rows.country_segment_result_limit.country_segment_source_row_limit.country_segment_source_possibly_truncated.country_segment_warnings`.split(`.`),steps:[`rank`,`tool`,`status`,`summary`],actions:[`rank`,`title`,`confidence`,`action`],findings:[`dimension`,`data_status`,`eligible_rows`,`returned_rows`,`limited_rows`,`result_limit`,`unmatched_rows`,`summary`,`winner_key`,`winner_click_delta`,`winner_impression_delta`,`winner_position_delta`,`loser_key`,`loser_click_delta`,`loser_impression_delta`,`loser_position_delta`],templates:[`rank`,`direction`,`template`,`confidence`,`url_count`,`click_delta`,`impression_delta`,`movement_share`,`movement_share_scope`,`confidence_scope`,`eligible_rows`,`returned_rows`,`limited_rows`,`result_limit`,`source_possibly_truncated`,`common_terms`,`sample_urls`,`summary`],evidence:[`rank`,`evidence`],confounders:[`rank`,`source`,`title`,`date`,`scope`,`target`,`description`],segment:[`rank`,`dimension`,`data_status`,`evidence_scope`,`key`,`before_clicks`,`after_clicks`,`click_delta`,`before_impressions`,`after_impressions`,`impression_delta`,`before_position`,`after_position`,`position_delta`],unmatchedSegment:[`rank`,`dimension`,`data_status`,`key`,`retained_in`,`clicks`,`impressions`,`position`,`reason`]};function Qn(e,t){return[...e.output.segments[t].winners,...e.output.segments[t].losers].map((n,r)=>({rank:r+1,dimension:t,data_status:e.output.segments[t].dataStatus,evidence_scope:n.evidenceScope,key:n.key,before_clicks:n.beforeClicks,after_clicks:n.afterClicks,click_delta:n.clickDelta,before_impressions:n.beforeImpressions,after_impressions:n.afterImpressions,impression_delta:n.impressionDelta,before_position:n.beforePosition,after_position:n.afterPosition,position_delta:n.positionDelta}))}function $n(e,t){return e.output.segments[t].unmatchedSegments.map((n,r)=>({rank:r+1,dimension:t,data_status:e.output.segments[t].dataStatus,key:n.key,retained_in:n.retainedIn,clicks:n.clicks,impressions:n.impressions,position:n.position,reason:n.reason}))}function er(e){return[{filename:`postmortem-summary.csv`,headers:[...Zn.summary],rows:[{workflow:e.workflow,site:e.site,generated_at:e.generatedAt,summary:e.summary,attribution:e.output.update.attribution,confidence:e.output.update.confidence,classification:e.output.update.classification,updates_matched:e.output.update.overlappingUpdates.length,known_confounders:e.output.update.confounders.length,page_segment_status:e.output.segments.page.dataStatus,page_segment_eligible_rows:e.output.segments.page.coverage.eligibleRows,page_segment_returned_rows:e.output.segments.page.coverage.returnedRows,page_segment_limited_rows:e.output.segments.page.coverage.limitedRows,page_segment_result_limit:e.output.segments.page.coverage.resultLimit,page_segment_source_row_limit:e.output.segments.page.coverage.sourceRowLimit,page_segment_source_possibly_truncated:e.output.segments.page.coverage.sourcePossiblyTruncated,page_segment_warnings:e.output.segments.page.warnings.join(`; `),query_segment_status:e.output.segments.query.dataStatus,query_segment_eligible_rows:e.output.segments.query.coverage.eligibleRows,query_segment_returned_rows:e.output.segments.query.coverage.returnedRows,query_segment_limited_rows:e.output.segments.query.coverage.limitedRows,query_segment_result_limit:e.output.segments.query.coverage.resultLimit,query_segment_source_row_limit:e.output.segments.query.coverage.sourceRowLimit,query_segment_source_possibly_truncated:e.output.segments.query.coverage.sourcePossiblyTruncated,query_segment_warnings:e.output.segments.query.warnings.join(`; `),device_segment_status:e.output.segments.device.dataStatus,device_segment_eligible_rows:e.output.segments.device.coverage.eligibleRows,device_segment_returned_rows:e.output.segments.device.coverage.returnedRows,device_segment_limited_rows:e.output.segments.device.coverage.limitedRows,device_segment_result_limit:e.output.segments.device.coverage.resultLimit,device_segment_source_row_limit:e.output.segments.device.coverage.sourceRowLimit,device_segment_source_possibly_truncated:e.output.segments.device.coverage.sourcePossiblyTruncated,device_segment_warnings:e.output.segments.device.warnings.join(`; `),country_segment_status:e.output.segments.country.dataStatus,country_segment_eligible_rows:e.output.segments.country.coverage.eligibleRows,country_segment_returned_rows:e.output.segments.country.coverage.returnedRows,country_segment_limited_rows:e.output.segments.country.coverage.limitedRows,country_segment_result_limit:e.output.segments.country.coverage.resultLimit,country_segment_source_row_limit:e.output.segments.country.coverage.sourceRowLimit,country_segment_source_possibly_truncated:e.output.segments.country.coverage.sourcePossiblyTruncated,country_segment_warnings:e.output.segments.country.warnings.join(`; `)}]},{filename:`workflow-steps.csv`,headers:[...Zn.steps],rows:e.steps.map((e,t)=>({rank:t+1,tool:e.tool,status:e.status,summary:e.summary}))},{filename:`workflow-actions.csv`,headers:[...Zn.actions],rows:e.actions.map((e,t)=>({rank:t+1,title:e.title,confidence:e.confidence,action:e.action}))},{filename:`postmortem-findings.csv`,headers:[...Zn.findings],rows:e.output.insights.map(e=>({dimension:e.dimension,data_status:e.dataStatus,eligible_rows:e.coverage.eligibleRows,returned_rows:e.coverage.returnedRows,limited_rows:e.coverage.limitedRows,result_limit:e.coverage.resultLimit,unmatched_rows:e.unmatchedRows,summary:e.summary,winner_key:e.winner?.key,winner_click_delta:e.winner?.clickDelta,winner_impression_delta:e.winner?.impressionDelta,winner_position_delta:e.winner?.positionDelta,loser_key:e.loser?.key,loser_click_delta:e.loser?.clickDelta,loser_impression_delta:e.loser?.impressionDelta,loser_position_delta:e.loser?.positionDelta}))},{filename:`postmortem-template-movement.csv`,headers:[...Zn.templates],rows:e.output.templateMovement.map((e,t)=>({rank:t+1,direction:e.direction,template:e.signature,confidence:e.confidence,url_count:e.urlCount,click_delta:e.clickDelta,impression_delta:e.impressionDelta,movement_share:e.movementShare,movement_share_scope:e.movementShareScope,confidence_scope:e.confidenceScope,eligible_rows:e.segmentCoverage.eligibleRows,returned_rows:e.segmentCoverage.returnedRows,limited_rows:e.segmentCoverage.limitedRows,result_limit:e.segmentCoverage.resultLimit,source_possibly_truncated:e.segmentCoverage.sourcePossiblyTruncated,common_terms:e.commonTerms.join(`; `),sample_urls:e.sampleUrls.join(`; `),summary:e.summary}))},{filename:`postmortem-update-evidence.csv`,headers:[...Zn.evidence],rows:e.output.update.evidence.map((e,t)=>({rank:t+1,evidence:e}))},{filename:`postmortem-confounders.csv`,headers:[...Zn.confounders],rows:e.output.update.confounders.map((e,t)=>({rank:t+1,source:e.source,title:e.title,date:e.date,scope:e.scope,target:e.target,description:e.description}))},...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}.csv`,headers:[...Zn.segment],rows:Qn(e,t)})),...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}-unmatched.csv`,headers:[...Zn.unmatchedSegment],rows:$n(e,t)}))]}function tr(e){try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.hostname.toLowerCase().replace(/\.$/,``)||void 0}catch{return}}function nr(e){if(!e.startsWith(`sc-domain:`))return;let t=e.slice(10).trim().toLowerCase();if(!(!t||/[/:]/.test(t)))return t.replace(/\.$/,``)||void 0}function rr(e,t){let n=nr(e);return n?t===n||t.endsWith(`.${n}`)?`domain`:void 0:tr(e)===t?`hostname`:void 0}function ir(e,t){return t.flatMap(t=>{let n=t.stream.webStreamData?.defaultUri;if(!n)return[];let r=tr(n);if(!r)return[];let i=rr(e,r);return i?[{...t,defaultUri:n,hostname:r,match:i}]:[]})}function ar(e,t){let n=e.stream.displayName??e.defaultUri,r=e.match===`domain`?`is inside`:`matches`;return`Matched Google Analytics web stream ${n} (${e.defaultUri}): its hostname ${r} ${t}.`}function or(e){let t=e-Date.now();if(t<=0)return`expired`;let n=Math.round(t/6e4);if(n<60)return`in ${n}m`;let r=Math.floor(n/60),i=n%60;return i?`in ${r}h ${i}m`:`in ${r}h`}function T(e,t){return{type:`boolean`,default:!0,description:e,negativeDescription:t}}function E(e){return typeof e==`string`?e:void 0}function D(e){let t=E(e.project),n=E(e.client);if(t&&n&&t!==n)throw Error(`Use either --project or --client, not both.`);return t??n}function O(e){return typeof e==`boolean`?e:void 0}function sr(e){let t=E(e.rendering);if(t!==void 0&&t!==`auto`&&t!==`on`&&t!==`off`)throw new y(`INVALID_INPUT`,`--rendering must be auto, on, or off.`);if(O(e.js)===!0&&t&&t!==`on`)throw new y(`INVALID_INPUT`,`Use either --js or --rendering on, not both with different modes.`);return t??(O(e.js)?`on`:`auto`)}function cr(e,t){let n=O(e[t]);if(n===!1)return!0;if(n===!0)return!1;let r=O(e[lr(t)]);if(r===!1)return!0;if(r===!0)return!1;if(O(e[`no-${t}`])===!0||O(e[`no${ur(t)}`])===!0)return!0}function lr(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function ur(e){let t=lr(e);return t?`${t[0]?.toUpperCase()}${t.slice(1)}`:``}function k(e){if(typeof e==`number`)return e;if(typeof e!=`string`||!e.trim())return;let t=Number(e);return Number.isFinite(t)?t:void 0}function A(e,t){if(e===void 0||e===``)return;let n=k(e);if(n===void 0)throw new y(`INVALID_INPUT`,`${t} must be a number.`);return n}function j(e){if(typeof e!=`string`)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length?t:void 0}function M(e){return j(e)??[]}function dr(e){let t={concurrency:k(e[`fetch-concurrency`]),intervalCap:k(e[`fetch-interval-cap`]),intervalMs:k(e[`fetch-interval-ms`])};return Object.values(t).some(e=>e!==void 0)?t:void 0}function fr(e){let t={concurrency:A(e[`fetch-concurrency`],`--fetch-concurrency`),intervalCap:A(e[`fetch-interval-cap`],`--fetch-interval-cap`),intervalMs:A(e[`fetch-interval-ms`],`--fetch-interval-ms`)};return Object.values(t).some(e=>e!==void 0)?t:void 0}function N(e){return e.json===!0}async function pr(e,t){let n=E(e),r=E(t);if(n&&r)throw Error(`Use either --body or --body-file, not both.`);if(!n&&!r)return;let i=n??await En(r??``,`utf8`),a=JSON.parse(i);if(!a||typeof a!=`object`||Array.isArray(a))throw Error(`JSON body must be an object.`);return a}function mr(e){if(typeof e==`number`)return Number.isFinite(e)?Math.round(e):void 0;if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function hr(e={}){let t=e.env??process.env,n=mr(e.columns)??mr(e.streamColumns)??mr(t.COLUMNS)??80;return Math.min(200,Math.max(40,n))}function P(e={}){let t=e.env??process.env,n=e.isTTY??!!process.stdout.isTTY,r=e.color??!!(n&&t.NO_COLOR===void 0);return{columns:hr({...e,env:t,streamColumns:e.streamColumns??process.stdout.columns}),colors:Un.createColors(r),hasColor:r,isInteractive:n&&!t.CI}}function F(e){return Wn(Sn(e))}function gr(e,t){let n=[],r=``;for(let i of e)r&&F(`${r}${i}`)>t?(n.push(r),r=i):r+=i;return r&&n.push(r),n}function _r(e,t){if(!e)return[``];let n=e.trim().split(/\s+/u),r=[],i=``;for(let e of n){let n=F(e)>t?gr(e,t):[e];for(let e of n)i?F(`${i} ${e}`)<=t?i+=` ${e}`:(r.push(i),i=e):i=e}return i&&r.push(i),r.length>0?r:[``]}function I(e,t){let n=Math.max(1,t);return e.replaceAll(`\r
3
+ import{$ as e,$t as t,A as n,An as r,At as i,B as a,Bn as o,Bt as s,C as c,Cn as l,Ct as u,D as d,Dn as f,Dt as p,E as m,En as h,Et as ee,F as g,Fn as te,Ft as ne,G as _,Gt as v,H as y,Hn as b,Ht as re,I as ie,In as ae,It as oe,J as se,Jt as ce,K as le,Kt as ue,L as de,Ln as fe,Lt as pe,M as me,Mn as he,Mt as ge,N as _e,Nn as ve,Nt as ye,O as be,On as xe,Ot as Se,P as Ce,Pn as we,Pt as Te,Q as Ee,Qt as De,R as Oe,Rn as ke,Rt as Ae,S as je,Sn as Me,St as Ne,T as Pe,Tn as Fe,Tt as Ie,U as Le,Un as Re,Ut as ze,V as Be,Vn as Ve,Vt as He,W as Ue,Wn as We,Wt as Ge,X as Ke,Xt as qe,Y as Je,Yt as Ye,Z as Xe,Zt as Ze,_ as Qe,_n as $e,_t as et,a as tt,an as nt,at as rt,b as it,bn as at,bt as ot,cn as st,ct,d as lt,dn as ut,dt,en as ft,et as pt,f as mt,fn as ht,ft as gt,g as _t,gn as vt,gt as yt,h as bt,hn as xt,ht as St,i as Ct,in as wt,it as Tt,j as Et,jn as Dt,jt as Ot,k as kt,kn as At,kt as jt,l as Mt,ln as Nt,lt as Pt,m as Ft,mn as It,mt as Lt,nn as Rt,nt as zt,o as Bt,on as Vt,ot as Ht,p as Ut,pn as Wt,pt as Gt,q as Kt,qt,r as Jt,rn as Yt,rt as Xt,sn as Zt,st as Qt,t as $t,tn as en,tt as tn,u as nn,un as rn,ut as an,v as on,vn as sn,vt as cn,w as ln,wn as un,wt as dn,x as fn,xn as pn,xt as mn,y as hn,yn as gn,yt as _n,z as vn,zn as yn,zt as bn}from"./dist-DaHrxVkW.js";import{constants as xn,copyFileSync as Sn,createWriteStream as Cn,existsSync as x,mkdirSync as wn,readFileSync as Tn,readdirSync as En,realpathSync as Dn,renameSync as On,rmSync as kn,statSync as An,writeFileSync as jn}from"node:fs";import{homedir as Mn}from"node:os";import{basename as Nn,dirname as S,isAbsolute as Pn,join as C,posix as Fn,relative as In,resolve as Ln,win32 as Rn}from"node:path";import{randomUUID as zn}from"node:crypto";import{spawn as Bn,spawnSync as Vn}from"node:child_process";import{fileURLToPath as Hn}from"node:url";import{isDeepStrictEqual as Un,stripVTControlCharacters as Wn}from"node:util";import{lstat as Gn,mkdir as Kn,mkdtemp as qn,readFile as Jn,readdir as Yn,rename as Xn,rm as Zn,stat as Qn,unlink as $n,writeFile as er}from"node:fs/promises";import{defineCommand as w,runCommand as tr,runMain as nr}from"citty";import{cancel as rr,confirm as ir,intro as ar,isCancel as or,log as sr,multiselect as cr,note as T,outro as lr,password as ur,select as dr,text as fr}from"@clack/prompts";import pr from"picocolors";import mr from"string-width";import hr from"cli-table3";import{applyEdits as gr,modify as _r,parse as vr,printParseErrorCode as yr}from"jsonc-parser";import{finished as br}from"node:stream/promises";import xr from"update-notifier";function E(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`).replaceAll(`'`,`&#39;`)}function Sr(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t.toString():void 0}catch{return}}function Cr(e){let t=Sr(e),n=E(e);return t?`<a href="${E(t)}" rel="noreferrer">${n}</a>`:n}function wr(e){return e.length===0?`<p class="empty">No items to report.</p>`:`<ul>${e.map(e=>`<li>${E(e)}</li>`).join(``)}</ul>`}function Tr(e){return e.sections.map(e=>`<section class="panel">
4
+ <h2>${E(e.title)}</h2>
5
+ ${wr(e.bullets)}
6
+ </section>`).join(``)}function Er(e){return e.map(e=>`<section class="panel">
7
+ <h2>${E(e.title)}</h2>
8
+ ${e.summary?`<p>${E(e.summary)}</p>`:``}
9
+ ${wr(e.items)}
10
+ </section>`).join(``)}function Dr(e){return e.priorities.length===0?`<p class="empty">No evidence-backed priorities were found.</p>`:`<ol class="priorities">${e.priorities.map(e=>`<li>
11
+ <div class="priority-heading">
12
+ <strong>${E(e.title)}</strong>
13
+ <span class="confidence">${E(e.confidence)} confidence</span>
14
+ </div>
15
+ <p>${E(e.action)}</p>
16
+ </li>`).join(``)}</ol>`}function Or(e){let t=e.diagnosis.skippedSections??[],n=e.changeMeasurementAttempts;return`<section class="panel analyst-only">
17
+ <h2>Evidence coverage</h2>
18
+ <dl class="facts">
19
+ <div><dt>Data status</dt><dd>${E(e.dataStatus)}</dd></div>
20
+ <div><dt>Generated</dt><dd>${E(e.generatedAt)}</dd></div>
21
+ <div><dt>Saved changes checked</dt><dd>${n.length}</dd></div>
22
+ <div><dt>Unavailable sections</dt><dd>${t.length}</dd></div>
23
+ </dl>
24
+ ${t.length?`<h3>Unavailable sections</h3>${wr(t.map(e=>`reason`in e&&typeof e.reason==`string`?`${e.section}: ${e.reason}`:e.section))}`:``}
25
+ </section>`}function kr(e){let t=e.report,n=e.view??`client`,r=e.title??`SEO report`,i=t.dataStatus===`complete`?``:` open`,a=n===`analyst`?Or(t):``;return`<!doctype html>
26
+ <html lang="en">
27
+ <head>
28
+ <meta charset="utf-8">
29
+ <meta name="viewport" content="width=device-width, initial-scale=1">
30
+ <meta name="robots" content="noindex,nofollow">
31
+ <title>${E(r)}: ${E(t.site)}</title>
32
+ <style>
33
+ :root { color-scheme: light; font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: #17211b; background: #f2f4ef; }
34
+ * { box-sizing: border-box; }
35
+ body { margin: 0; line-height: 1.55; }
36
+ a { color: inherit; text-decoration-color: #ff5b35; text-underline-offset: 0.18em; }
37
+ main { width: min(980px, calc(100% - 32px)); margin: 32px auto 64px; }
38
+ header { padding: clamp(28px, 6vw, 64px); color: #f9fbf7; background: #17211b; border-radius: 20px; }
39
+ .eyebrow { margin: 0 0 12px; color: #ff7958; font-size: 0.78rem; font-weight: 800; letter-spacing: 0.12em; text-transform: uppercase; }
40
+ h1 { max-width: 760px; margin: 0; font-size: clamp(2rem, 5vw, 4rem); line-height: 1.02; letter-spacing: -0.04em; }
41
+ header .headline { max-width: 760px; margin: 24px 0 0; font-size: clamp(1.05rem, 2vw, 1.3rem); color: #d9e1d9; }
42
+ .meta { display: flex; flex-wrap: wrap; gap: 10px 22px; margin-top: 28px; color: #b9c5ba; font-size: 0.9rem; }
43
+ .status { display: inline-flex; width: fit-content; margin-top: 22px; padding: 6px 10px; border: 1px solid #4f6153; border-radius: 999px; font-size: 0.8rem; font-weight: 700; text-transform: capitalize; }
44
+ .panel { margin-top: 20px; padding: clamp(22px, 4vw, 38px); background: #fff; border: 1px solid #dfe4dc; border-radius: 16px; box-shadow: 0 8px 30px rgba(23, 33, 27, 0.05); }
45
+ h2 { margin: 0 0 16px; font-size: clamp(1.25rem, 3vw, 1.65rem); letter-spacing: -0.02em; }
46
+ h3 { margin: 26px 0 10px; font-size: 1rem; }
47
+ p { margin: 0 0 14px; }
48
+ ul, ol { margin: 0; padding-left: 1.25rem; }
49
+ li + li { margin-top: 10px; }
50
+ .priorities { list-style: none; padding: 0; counter-reset: priority; }
51
+ .priorities > li { counter-increment: priority; padding: 18px 0 18px 52px; position: relative; border-top: 1px solid #e6eae4; }
52
+ .priorities > li:first-child { border-top: 0; padding-top: 4px; }
53
+ .priorities > li::before { content: counter(priority); position: absolute; left: 0; top: 16px; display: grid; width: 34px; height: 34px; place-items: center; border-radius: 50%; color: #17211b; background: #ff7958; font-weight: 800; }
54
+ .priorities > li:first-child::before { top: 2px; }
55
+ .priority-heading { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 8px 20px; }
56
+ .confidence { color: #647067; font-size: 0.82rem; text-transform: capitalize; }
57
+ .priorities p { margin: 8px 0 0; color: #3e4941; }
58
+ .facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 0; }
59
+ .facts div { padding: 14px; background: #f5f7f3; border-radius: 10px; }
60
+ dt { color: #647067; font-size: 0.78rem; font-weight: 700; text-transform: uppercase; }
61
+ dd { margin: 4px 0 0; font-weight: 700; }
62
+ details summary { cursor: pointer; font-weight: 750; }
63
+ details ul { margin-top: 14px; }
64
+ .empty { color: #647067; font-style: italic; }
65
+ footer { margin-top: 26px; color: #647067; font-size: 0.8rem; text-align: center; }
66
+ @media print { :root { background: #fff; } main { width: 100%; margin: 0; } header, .panel { break-inside: avoid; box-shadow: none; } header { border-radius: 0; } }
67
+ </style>
68
+ </head>
69
+ <body>
70
+ <main>
71
+ <header>
72
+ <p class="eyebrow">${E(r)}</p>
73
+ <h1>${Cr(t.site)}</h1>
74
+ <p class="headline">${E(t.headline)}</p>
75
+ <div class="meta">
76
+ <span>${E(t.period.startDate)} to ${E(t.period.endDate)}</span>
77
+ <span>Generated ${E(t.generatedAt.slice(0,10))}</span>
78
+ <span>${E(n)} view</span>
79
+ </div>
80
+ <span class="status">${E(t.dataStatus)} data</span>
81
+ </header>
82
+
83
+ <section class="panel">
84
+ <h2>Priorities</h2>
85
+ ${Dr(t)}
86
+ </section>
87
+
88
+ ${Tr(t)}
89
+ ${Er(e.additionalSections??[])}
90
+ ${a}
91
+
92
+ <section class="panel">
93
+ <details${i}>
94
+ <summary>Evidence notes and limitations</summary>
95
+ ${wr(t.caveats)}
96
+ </details>
97
+ </section>
98
+
99
+ <footer>Generated locally from observed report evidence.</footer>
100
+ </main>
101
+ </body>
102
+ </html>`}const Ar={summary:`workflow.site.generated_at.summary.attribution.confidence.classification.updates_matched.known_confounders.page_segment_status.page_segment_eligible_rows.page_segment_returned_rows.page_segment_limited_rows.page_segment_result_limit.page_segment_source_row_limit.page_segment_source_possibly_truncated.page_segment_warnings.query_segment_status.query_segment_eligible_rows.query_segment_returned_rows.query_segment_limited_rows.query_segment_result_limit.query_segment_source_row_limit.query_segment_source_possibly_truncated.query_segment_warnings.device_segment_status.device_segment_eligible_rows.device_segment_returned_rows.device_segment_limited_rows.device_segment_result_limit.device_segment_source_row_limit.device_segment_source_possibly_truncated.device_segment_warnings.country_segment_status.country_segment_eligible_rows.country_segment_returned_rows.country_segment_limited_rows.country_segment_result_limit.country_segment_source_row_limit.country_segment_source_possibly_truncated.country_segment_warnings`.split(`.`),steps:[`rank`,`tool`,`status`,`summary`],actions:[`rank`,`title`,`confidence`,`action`],findings:[`dimension`,`data_status`,`eligible_rows`,`returned_rows`,`limited_rows`,`result_limit`,`unmatched_rows`,`summary`,`winner_key`,`winner_click_delta`,`winner_impression_delta`,`winner_position_delta`,`loser_key`,`loser_click_delta`,`loser_impression_delta`,`loser_position_delta`],templates:[`rank`,`direction`,`template`,`confidence`,`url_count`,`click_delta`,`impression_delta`,`movement_share`,`movement_share_scope`,`confidence_scope`,`eligible_rows`,`returned_rows`,`limited_rows`,`result_limit`,`source_possibly_truncated`,`common_terms`,`sample_urls`,`summary`],evidence:[`rank`,`evidence`],confounders:[`rank`,`source`,`title`,`date`,`scope`,`target`,`description`],segment:[`rank`,`dimension`,`data_status`,`evidence_scope`,`key`,`before_clicks`,`after_clicks`,`click_delta`,`before_impressions`,`after_impressions`,`impression_delta`,`before_position`,`after_position`,`position_delta`],unmatchedSegment:[`rank`,`dimension`,`data_status`,`key`,`retained_in`,`clicks`,`impressions`,`position`,`reason`]};function jr(e,t){return[...e.output.segments[t].winners,...e.output.segments[t].losers].map((n,r)=>({rank:r+1,dimension:t,data_status:e.output.segments[t].dataStatus,evidence_scope:n.evidenceScope,key:n.key,before_clicks:n.beforeClicks,after_clicks:n.afterClicks,click_delta:n.clickDelta,before_impressions:n.beforeImpressions,after_impressions:n.afterImpressions,impression_delta:n.impressionDelta,before_position:n.beforePosition,after_position:n.afterPosition,position_delta:n.positionDelta}))}function Mr(e,t){return e.output.segments[t].unmatchedSegments.map((n,r)=>({rank:r+1,dimension:t,data_status:e.output.segments[t].dataStatus,key:n.key,retained_in:n.retainedIn,clicks:n.clicks,impressions:n.impressions,position:n.position,reason:n.reason}))}function Nr(e){return[{filename:`postmortem-summary.csv`,headers:[...Ar.summary],rows:[{workflow:e.workflow,site:e.site,generated_at:e.generatedAt,summary:e.summary,attribution:e.output.update.attribution,confidence:e.output.update.confidence,classification:e.output.update.classification,updates_matched:e.output.update.overlappingUpdates.length,known_confounders:e.output.update.confounders.length,page_segment_status:e.output.segments.page.dataStatus,page_segment_eligible_rows:e.output.segments.page.coverage.eligibleRows,page_segment_returned_rows:e.output.segments.page.coverage.returnedRows,page_segment_limited_rows:e.output.segments.page.coverage.limitedRows,page_segment_result_limit:e.output.segments.page.coverage.resultLimit,page_segment_source_row_limit:e.output.segments.page.coverage.sourceRowLimit,page_segment_source_possibly_truncated:e.output.segments.page.coverage.sourcePossiblyTruncated,page_segment_warnings:e.output.segments.page.warnings.join(`; `),query_segment_status:e.output.segments.query.dataStatus,query_segment_eligible_rows:e.output.segments.query.coverage.eligibleRows,query_segment_returned_rows:e.output.segments.query.coverage.returnedRows,query_segment_limited_rows:e.output.segments.query.coverage.limitedRows,query_segment_result_limit:e.output.segments.query.coverage.resultLimit,query_segment_source_row_limit:e.output.segments.query.coverage.sourceRowLimit,query_segment_source_possibly_truncated:e.output.segments.query.coverage.sourcePossiblyTruncated,query_segment_warnings:e.output.segments.query.warnings.join(`; `),device_segment_status:e.output.segments.device.dataStatus,device_segment_eligible_rows:e.output.segments.device.coverage.eligibleRows,device_segment_returned_rows:e.output.segments.device.coverage.returnedRows,device_segment_limited_rows:e.output.segments.device.coverage.limitedRows,device_segment_result_limit:e.output.segments.device.coverage.resultLimit,device_segment_source_row_limit:e.output.segments.device.coverage.sourceRowLimit,device_segment_source_possibly_truncated:e.output.segments.device.coverage.sourcePossiblyTruncated,device_segment_warnings:e.output.segments.device.warnings.join(`; `),country_segment_status:e.output.segments.country.dataStatus,country_segment_eligible_rows:e.output.segments.country.coverage.eligibleRows,country_segment_returned_rows:e.output.segments.country.coverage.returnedRows,country_segment_limited_rows:e.output.segments.country.coverage.limitedRows,country_segment_result_limit:e.output.segments.country.coverage.resultLimit,country_segment_source_row_limit:e.output.segments.country.coverage.sourceRowLimit,country_segment_source_possibly_truncated:e.output.segments.country.coverage.sourcePossiblyTruncated,country_segment_warnings:e.output.segments.country.warnings.join(`; `)}]},{filename:`workflow-steps.csv`,headers:[...Ar.steps],rows:e.steps.map((e,t)=>({rank:t+1,tool:e.tool,status:e.status,summary:e.summary}))},{filename:`workflow-actions.csv`,headers:[...Ar.actions],rows:e.actions.map((e,t)=>({rank:t+1,title:e.title,confidence:e.confidence,action:e.action}))},{filename:`postmortem-findings.csv`,headers:[...Ar.findings],rows:e.output.insights.map(e=>({dimension:e.dimension,data_status:e.dataStatus,eligible_rows:e.coverage.eligibleRows,returned_rows:e.coverage.returnedRows,limited_rows:e.coverage.limitedRows,result_limit:e.coverage.resultLimit,unmatched_rows:e.unmatchedRows,summary:e.summary,winner_key:e.winner?.key,winner_click_delta:e.winner?.clickDelta,winner_impression_delta:e.winner?.impressionDelta,winner_position_delta:e.winner?.positionDelta,loser_key:e.loser?.key,loser_click_delta:e.loser?.clickDelta,loser_impression_delta:e.loser?.impressionDelta,loser_position_delta:e.loser?.positionDelta}))},{filename:`postmortem-template-movement.csv`,headers:[...Ar.templates],rows:e.output.templateMovement.map((e,t)=>({rank:t+1,direction:e.direction,template:e.signature,confidence:e.confidence,url_count:e.urlCount,click_delta:e.clickDelta,impression_delta:e.impressionDelta,movement_share:e.movementShare,movement_share_scope:e.movementShareScope,confidence_scope:e.confidenceScope,eligible_rows:e.segmentCoverage.eligibleRows,returned_rows:e.segmentCoverage.returnedRows,limited_rows:e.segmentCoverage.limitedRows,result_limit:e.segmentCoverage.resultLimit,source_possibly_truncated:e.segmentCoverage.sourcePossiblyTruncated,common_terms:e.commonTerms.join(`; `),sample_urls:e.sampleUrls.join(`; `),summary:e.summary}))},{filename:`postmortem-update-evidence.csv`,headers:[...Ar.evidence],rows:e.output.update.evidence.map((e,t)=>({rank:t+1,evidence:e}))},{filename:`postmortem-confounders.csv`,headers:[...Ar.confounders],rows:e.output.update.confounders.map((e,t)=>({rank:t+1,source:e.source,title:e.title,date:e.date,scope:e.scope,target:e.target,description:e.description}))},...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}.csv`,headers:[...Ar.segment],rows:jr(e,t)})),...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}-unmatched.csv`,headers:[...Ar.unmatchedSegment],rows:Mr(e,t)}))]}function Pr(e){try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.hostname.toLowerCase().replace(/\.$/,``)||void 0}catch{return}}function Fr(e){if(!e.startsWith(`sc-domain:`))return;let t=e.slice(10).trim().toLowerCase();if(!(!t||/[/:]/.test(t)))return t.replace(/\.$/,``)||void 0}function Ir(e,t){let n=Fr(e);return n?t===n||t.endsWith(`.${n}`)?`domain`:void 0:Pr(e)===t?`hostname`:void 0}function Lr(e,t){return t.flatMap(t=>{let n=t.stream.webStreamData?.defaultUri;if(!n)return[];let r=Pr(n);if(!r)return[];let i=Ir(e,r);return i?[{...t,defaultUri:n,hostname:r,match:i}]:[]})}function Rr(e,t){let n=e.stream.displayName??e.defaultUri,r=e.match===`domain`?`is inside`:`matches`;return`Matched Google Analytics web stream ${n} (${e.defaultUri}): its hostname ${r} ${t}.`}function zr(e){let t=e-Date.now();if(t<=0)return`expired`;let n=Math.round(t/6e4);if(n<60)return`in ${n}m`;let r=Math.floor(n/60),i=n%60;return i?`in ${r}h ${i}m`:`in ${r}h`}function Br(e,t){return{type:`boolean`,default:!0,description:e,negativeDescription:t}}function D(e){return typeof e==`string`?e:void 0}function O(e){let t=D(e.project),n=D(e.client);if(t&&n&&t!==n)throw Error(`Use either --project or --client, not both.`);return t??n}function k(e){return typeof e==`boolean`?e:void 0}function Vr(e){let t=D(e.rendering);if(t!==void 0&&t!==`auto`&&t!==`on`&&t!==`off`)throw new b(`INVALID_INPUT`,`--rendering must be auto, on, or off.`);if(k(e.js)===!0&&t&&t!==`on`)throw new b(`INVALID_INPUT`,`Use either --js or --rendering on, not both with different modes.`);return t??(k(e.js)?`on`:`auto`)}function Hr(e,t){let n=k(e[t]);if(n===!1)return!0;if(n===!0)return!1;let r=k(e[Ur(t)]);if(r===!1)return!0;if(r===!0)return!1;if(k(e[`no-${t}`])===!0||k(e[`no${Wr(t)}`])===!0)return!0}function Ur(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Wr(e){let t=Ur(e);return t?`${t[0]?.toUpperCase()}${t.slice(1)}`:``}function A(e){if(typeof e==`number`)return e;if(typeof e!=`string`||!e.trim())return;let t=Number(e);return Number.isFinite(t)?t:void 0}function j(e,t){if(e===void 0||e===``)return;let n=A(e);if(n===void 0)throw new b(`INVALID_INPUT`,`${t} must be a number.`);return n}function M(e){if(typeof e!=`string`)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length?t:void 0}function N(e){return M(e)??[]}function Gr(e){let t={concurrency:A(e[`fetch-concurrency`]),intervalCap:A(e[`fetch-interval-cap`]),intervalMs:A(e[`fetch-interval-ms`])};return Object.values(t).some(e=>e!==void 0)?t:void 0}function Kr(e){let t={concurrency:j(e[`fetch-concurrency`],`--fetch-concurrency`),intervalCap:j(e[`fetch-interval-cap`],`--fetch-interval-cap`),intervalMs:j(e[`fetch-interval-ms`],`--fetch-interval-ms`)};return Object.values(t).some(e=>e!==void 0)?t:void 0}function P(e){return e.json===!0}async function qr(e,t){let n=D(e),r=D(t);if(n&&r)throw Error(`Use either --body or --body-file, not both.`);if(!n&&!r)return;let i=n??await Jn(r??``,`utf8`),a=JSON.parse(i);if(!a||typeof a!=`object`||Array.isArray(a))throw Error(`JSON body must be an object.`);return a}function Jr(e){if(typeof e==`number`)return Number.isFinite(e)?Math.round(e):void 0;if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function Yr(e={}){let t=e.env??process.env,n=Jr(e.columns)??Jr(e.streamColumns)??Jr(t.COLUMNS)??80;return Math.min(200,Math.max(40,n))}function F(e={}){let t=e.env??process.env,n=e.isTTY??!!process.stdout.isTTY,r=e.color??!!(n&&t.NO_COLOR===void 0);return{columns:Yr({...e,env:t,streamColumns:e.streamColumns??process.stdout.columns}),colors:pr.createColors(r),hasColor:r,isInteractive:n&&!t.CI}}function I(e){return mr(Wn(e))}function Xr(e,t){let n=[],r=``;for(let i of e)r&&I(`${r}${i}`)>t?(n.push(r),r=i):r+=i;return r&&n.push(r),n}function Zr(e,t){if(!e)return[``];let n=e.trim().split(/\s+/u),r=[],i=``;for(let e of n){let n=I(e)>t?Xr(e,t):[e];for(let e of n)i?I(`${i} ${e}`)<=t?i+=` ${e}`:(r.push(i),i=e):i=e}return i&&r.push(i),r.length>0?r:[``]}function L(e,t){let n=Math.max(1,t);return e.replaceAll(`\r
4
103
  `,`
5
104
  `).split(`
6
- `).flatMap(e=>_r(e,n))}function vr(e,t){if(F(e)<=t)return e;let n=Math.max(1,t-F(`...`)),r=``;for(let t of e){if(F(`${r}${t}`)>n)break;r+=t}return`${r}...`}const yr={top:``,"top-mid":``,"top-left":``,"top-right":``,bottom:``,"bottom-mid":``,"bottom-left":``,"bottom-right":``,left:``,"left-mid":``,mid:``,"mid-mid":``,right:``,"right-mid":``,middle:``};function br(e){return e===void 0?``:String(e)}function xr(e,t){return e.map((e,n)=>{let r=t.map(e=>br(e[n]));return Math.min(42,Math.max(F(e),...r.map(F),4))})}function Sr(e,t,n){return e.length===0||e.length>4?!1:xr(e,t).reduce((e,t)=>e+t+2,0)<=n.columns}function Cr(e,t,n){let r=xr(e,t).map(e=>e+2),i=new Gn({chars:yr,colWidths:r,head:e.map(e=>n.colors.bold(e)),style:{border:[],head:[],"padding-left":0,"padding-right":2},wordWrap:!1});for(let n of t)i.push(e.map((e,t)=>I(br(n[t]),Math.max(1,(r[t]??3)-2)).join(`
7
- `)));return i.toString()}function wr(e,t,n,r){let i=r.columns-n-2;return i<24?[r.colors.dim(e),...I(t,r.columns-2).map(e=>` ${e}`)]:I(t,i).map((t,i)=>{let a=i===0?e.padEnd(n):``.padEnd(n);return`${r.colors.dim(a)}${` `.repeat(2)}${t}`})}function Tr(e,t,n,r={}){let i=Math.min(28,Math.max(...e.map(e=>F(e)),0)),a=r.rowNumbers??t.length>1,o=String(t.length).length;return t.map((t,r)=>{let s=[];a&&s.push(n.colors.bold(String(r+1).padStart(o,`0`)));for(let[r,a]of e.entries())s.push(...wr(a,br(t[r]),i,n));return s.join(`
105
+ `).flatMap(e=>Zr(e,n))}function Qr(e,t){if(I(e)<=t)return e;let n=Math.max(1,t-I(`...`)),r=``;for(let t of e){if(I(`${r}${t}`)>n)break;r+=t}return`${r}...`}const $r={top:``,"top-mid":``,"top-left":``,"top-right":``,bottom:``,"bottom-mid":``,"bottom-left":``,"bottom-right":``,left:``,"left-mid":``,mid:``,"mid-mid":``,right:``,"right-mid":``,middle:``};function ei(e){return e===void 0?``:String(e)}function ti(e,t){return e.map((e,n)=>{let r=t.map(e=>ei(e[n]));return Math.min(42,Math.max(I(e),...r.map(I),4))})}function ni(e,t,n){return e.length===0||e.length>4?!1:ti(e,t).reduce((e,t)=>e+t+2,0)<=n.columns}function ri(e,t,n){let r=ti(e,t).map(e=>e+2),i=new hr({chars:$r,colWidths:r,head:e.map(e=>n.colors.bold(e)),style:{border:[],head:[],"padding-left":0,"padding-right":2},wordWrap:!1});for(let n of t)i.push(e.map((e,t)=>L(ei(n[t]),Math.max(1,(r[t]??3)-2)).join(`
106
+ `)));return i.toString()}function ii(e,t,n,r){let i=r.columns-n-2;return i<24?[r.colors.dim(e),...L(t,r.columns-2).map(e=>` ${e}`)]:L(t,i).map((t,i)=>{let a=i===0?e.padEnd(n):``.padEnd(n);return`${r.colors.dim(a)}${` `.repeat(2)}${t}`})}function ai(e,t,n,r={}){let i=Math.min(28,Math.max(...e.map(e=>I(e)),0)),a=r.rowNumbers??t.length>1,o=String(t.length).length;return t.map((t,r)=>{let s=[];a&&s.push(n.colors.bold(String(r+1).padStart(o,`0`)));for(let[r,a]of e.entries())s.push(...ii(a,ei(t[r]),i,n));return s.join(`
8
107
  `)}).join(`
9
108
 
10
- `)}function Er(e,t,n,r={}){return t.length===0?n.colors.dim(`No results.`):r.layout===`table`||r.layout!==`records`&&Sr(e,t,n)?Cr(e,t,n):Tr(e,t,n,r)}function Dr(e,t){if(e.length===0)return``;let n=Math.min(28,Math.max(...e.map(([e])=>F(e))));return e.flatMap(([e,r])=>{let i=wr(e,r,n,t);return i.length>0&&(i[0]=(i[0]??``).replace(e,t.colors.bold(e))),i}).join(`
11
- `)}function Or(e,t){let n=[t.colors.bold(e.title)];return e.body&&n.push(...I(e.body,t.columns)),e.command&&n.push(t.colors.cyan(vr(e.command,t.columns))),n.join(`
12
- `)}function kr(e,t,n=`${t}s`){return e===1?t:n}function Ar(e,t,n){let r=` `.repeat(t);return I(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function jr(e,t,n){return[t.colors.bold(e),...n?I(n,t.columns):[]].join(`
13
- `)}function Mr(e,t){let n={pass:t.colors.green,warn:t.colors.yellow,fail:t.colors.red};return e.map(e=>{let r=[`${n[e.status](e.status.toUpperCase().padEnd(4))} ${t.colors.bold(e.label)}`];if(r.push(...Ar(e.detail,6,t.columns)),e.fix){let n=I(e.fix,Math.max(1,t.columns-11));r.push(...n.map((e,n)=>`${` `.repeat(6)}${n===0?`${t.colors.bold(`Fix`)} `:` `}${e}`))}return r.join(`
109
+ `)}function oi(e,t,n,r={}){return t.length===0?n.colors.dim(`No results.`):r.layout===`table`||r.layout!==`records`&&ni(e,t,n)?ri(e,t,n):ai(e,t,n,r)}function si(e,t){if(e.length===0)return``;let n=Math.min(28,Math.max(...e.map(([e])=>I(e))));return e.flatMap(([e,r])=>{let i=ii(e,r,n,t);return i.length>0&&(i[0]=(i[0]??``).replace(e,t.colors.bold(e))),i}).join(`
110
+ `)}function ci(e,t){let n=[t.colors.bold(e.title)];return e.body&&n.push(...L(e.body,t.columns)),e.command&&n.push(t.colors.cyan(Qr(e.command,t.columns))),n.join(`
111
+ `)}function li(e,t,n=`${t}s`){return e===1?t:n}function ui(e,t,n){let r=` `.repeat(t);return L(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function di(e,t,n){return[t.colors.bold(e),...n?L(n,t.columns):[]].join(`
112
+ `)}function fi(e,t){let n={pass:t.colors.green,warn:t.colors.yellow,fail:t.colors.red};return e.map(e=>{let r=[`${n[e.status](e.status.toUpperCase().padEnd(4))} ${t.colors.bold(e.label)}`];if(r.push(...ui(e.detail,6,t.columns)),e.fix){let n=L(e.fix,Math.max(1,t.columns-11));r.push(...n.map((e,n)=>`${` `.repeat(6)}${n===0?`${t.colors.bold(`Fix`)} `:` `}${e}`))}return r.join(`
14
113
  `)}).join(`
15
114
 
16
- `)}function Nr(e){let t=e.filter(e=>e.status===`pass`).length,n=e.filter(e=>e.status===`warn`).length,r=e.filter(e=>e.status===`fail`).length;return`${t} ${kr(t,`check`)} passed, ${n} ${kr(n,`warning`)}, ${r} failed.`}function Pr(e,t,n){let r=n.columns-t-2-2;return r<24||F(e.id)>t?[...Ar(e.id,2,n.columns).map(e=>n.colors.cyan(e)),...Ar(e.name,4,n.columns)].join(`
17
- `):I(e.name,r).map((r,i)=>{let a=i===0?e.id.padEnd(t):``.padEnd(t);return` ${n.colors.cyan(a)}${` `.repeat(2)}${r}`}).join(`
18
- `)}function Fr(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Ir(e,t,n){let r=new Map;for(let t of e){let e=r.get(t.category)??[];e.push(t),r.set(t.category,e)}let i=`${e.length} ${kr(e.length,n.noun)} across ${r.size} ${kr(r.size,`category`,`categories`)}.`,a=Math.min(30,Math.max(...e.map(e=>F(e.id)),0)),o=Object.keys(n.categoryLabels??{}).filter(e=>r.has(e)),s=[...r.keys()].filter(e=>!o.includes(e));return[i,...[...o,...s].map(e=>{let i=r.get(e)??[],o=n.categoryLabels?.[e]??Fr(e);return[t.colors.bold(`${o} (${i.length})`),...i.map(e=>Pr(e,a,t))].join(`
115
+ `)}function pi(e){let t=e.filter(e=>e.status===`pass`).length,n=e.filter(e=>e.status===`warn`).length,r=e.filter(e=>e.status===`fail`).length;return`${t} ${li(t,`check`)} passed, ${n} ${li(n,`warning`)}, ${r} failed.`}function mi(e,t,n){let r=n.columns-t-2-2;return r<24||I(e.id)>t?[...ui(e.id,2,n.columns).map(e=>n.colors.cyan(e)),...ui(e.name,4,n.columns)].join(`
116
+ `):L(e.name,r).map((r,i)=>{let a=i===0?e.id.padEnd(t):``.padEnd(t);return` ${n.colors.cyan(a)}${` `.repeat(2)}${r}`}).join(`
117
+ `)}function hi(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function gi(e,t,n){let r=new Map;for(let t of e){let e=r.get(t.category)??[];e.push(t),r.set(t.category,e)}let i=`${e.length} ${li(e.length,n.noun)} across ${r.size} ${li(r.size,`category`,`categories`)}.`,a=Math.min(30,Math.max(...e.map(e=>I(e.id)),0)),o=Object.keys(n.categoryLabels??{}).filter(e=>r.has(e)),s=[...r.keys()].filter(e=>!o.includes(e));return[i,...[...o,...s].map(e=>{let i=r.get(e)??[],o=n.categoryLabels?.[e]??hi(e);return[t.colors.bold(`${o} (${i.length})`),...i.map(e=>mi(e,a,t))].join(`
19
118
  `)})].join(`
20
119
 
21
- `)}function Lr(e,t,n){return e.length===0?t.colors.dim(n.empty):e.map(e=>{let n=[t.colors.bold(e.title)];e.description&&n.push(...Ar(e.description,2,t.columns));let r=e.meta?.filter(Boolean).join(` · `);return r&&n.push(...Ar(r,2,t.columns).map(e=>t.colors.dim(e))),n.join(`
120
+ `)}function _i(e,t,n){return e.length===0?t.colors.dim(n.empty):e.map(e=>{let n=[t.colors.bold(e.title)];e.description&&n.push(...ui(e.description,2,t.columns));let r=e.meta?.filter(Boolean).join(` · `);return r&&n.push(...ui(r,2,t.columns).map(e=>t.colors.dim(e))),n.join(`
22
121
  `)}).join(`
23
122
 
24
- `)}function Rr(e,t,n){let r=t.filter(e=>e.trim().length>0).flatMap(e=>I(e,n.columns));return[n.colors.bold(e),...r].join(`
25
- `)}function zr(e,t,n){let r=t.flatMap(e=>I(e,Math.max(1,n.columns-2)).map((e,t)=>`${t===0?`- `:` `}${e}`));return[n.colors.bold(e),...r].join(`
26
- `)}function Br(e,t){return e.length===0?t.colors.dim(`No parameters.`):Lr(e.map(e=>({title:e.name,description:e.description,meta:[e.type,e.required?`required`:`optional`]})),t,{empty:`No parameters.`})}function L(e={}){return!!(!e.json&&process.stdin.isTTY&&process.stdout.isTTY&&!process.env.CI)}function R(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}function z(e){let t=Dr(e,P());t&&process.stdout.write(`${t}\n`)}function B(e,t){process.stdout.write(`${Er(e,t,P())}\n`)}function Vr(e){process.stdout.write(`${Or(e,P())}\n`)}function Hr(e,t){process.stdout.write(`${jr(e,P(),t)}\n`)}function Ur(e){process.stdout.write(`${Mr(e,P())}\n`)}function Wr(e,t){process.stdout.write(`${Ir(e,P(),t)}\n`)}function Gr(e,t){process.stdout.write(`${Lr(e,P(),t)}\n`)}function V(e,...t){process.stdout.write(`${Rr(e,t,P())}\n`)}function Kr(e,t){process.stdout.write(`${zr(e,t,P())}\n`)}function qr(e){process.stdout.write(`${Br(e,P())}\n`)}function Jr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function H(e){return typeof e==`symbol`&&process.exit(1),e}function Yr(e,t){let n=t.trim().toLowerCase();return!n||e.some(e=>e.toLowerCase().includes(n))}async function Xr(e){let t=e.choices;if(e.choices.length>8){let n=H(await Hn({message:e.searchMessage,placeholder:`Type part of the name or URL, or leave blank`}));if(t=e.choices.filter(t=>Yr(e.searchValues(t),n)),!t.length)throw new y(`INVALID_INPUT`,e.emptyMessage)}return H(await Vn({message:e.message,options:t.map(t=>{let n=e.hint?.(t);return{value:t,label:e.label(t),...n?{hint:n}:{}}})}))}async function Zr(e){if(e.site)return e.site;let t=_t(),n=!!t.defaultSite&&(t.clients.some(e=>e.siteUrl===t.defaultSite)||t.sites.some(e=>e.siteUrl===t.defaultSite));if(t.defaultSite&&n)return t.defaultSite;if(e.options?.json||!L())throw new y(`INVALID_INPUT`,t.defaultSite?`Saved default site ${t.defaultSite} does not match any saved project. Pass --site or --project, or run \`seo start\` to save a new default.`:"No site selected. Pass --site, use --project on supported commands, or run `seo start` in a terminal.");let r=await je(e.options?.refresh);if(!r.length)throw new y(`PROPERTY_NOT_FOUND`,`No Search Console properties found for this Google login.`);return r.length===1?r[0]?.siteUrl??``:(await Xr({message:`Choose a Search Console property`,searchMessage:`Search Search Console properties`,emptyMessage:`No Search Console properties matched that search.`,choices:r,label:e=>e.siteUrl,hint:e=>e.permissionLevel,searchValues:e=>[e.siteUrl,e.permissionLevel??``]})).siteUrl}async function U(e){if(e.client&&e.project&&e.client!==e.project)throw new y(`INVALID_INPUT`,`Use either --project or --client, not both.`);let t=e.project??e.client;if(t){let e=Gt(t);if(!e)throw new y(`INVALID_INPUT`,`Project not found: ${t}`);return{client:e,site:e.siteUrl}}let n=Gt();return!e.site&&n?{client:n,site:n.siteUrl}:{site:await Zr({site:e.site,options:e.options})}}async function Qr(e){if(e.client&&e.project&&e.client!==e.project)throw new y(`INVALID_INPUT`,`Use either --project or --client, not both.`);let t=e.project??e.client;if(t){let e=Gt(t);if(!e)throw new y(`INVALID_INPUT`,`Project not found: ${t}`);return e}let n=o();if(!n.length)return;let r=Gt();if(r)return r;if(!(e.options?.json||!L()))return Xr({message:`Choose a project`,searchMessage:`Search projects`,emptyMessage:`No projects matched that search.`,choices:n,label:e=>e.name,hint:e=>e.siteUrl,searchValues:e=>[e.id,e.name,e.siteUrl]})}async function $r(e){if(e.property)return e.property;let t=_t();if(t.analytics.google.defaultPropertyId)return t.analytics.google.defaultPropertyId;if(e.options?.json||!L())throw new y(`INVALID_INPUT`,`No Google Analytics property selected. Pass --property or run this command in a terminal to choose one.`);let n=(await At()).flatMap(e=>e.propertySummaries.map(t=>({property:Ft(t.property),displayName:t.displayName??t.property,account:e.displayName??e.account})));if(!n.length)throw new y(`PROPERTY_NOT_FOUND`,`No Google Analytics properties found for this Google login.`);return n.length===1?n[0]?.property??``:(await Xr({message:`Choose a Google Analytics property`,searchMessage:`Search Google Analytics properties`,emptyMessage:`No Google Analytics properties matched that search.`,choices:n,label:e=>`${e.displayName} (${e.property})`,hint:e=>e.account,searchValues:e=>[e.property,e.displayName,e.account]})).property}function W(e){return Math.round(e).toLocaleString(`en-GB`)}function ei(e){return e.toFixed(1)}function G(e){return`${(e*100).toFixed(1)}%`}function K(e,t=72){return vr(e,t)}function ti(e){return e.verification?.requested?`${e.verification.verified} checked, ${e.verification.failed} failed`:`off`}function q(e,t){B(e,t.slice(0,25)),t.length>25&&process.stdout.write(`Showing 25 of ${t.length}. Use --json for full data.\n`)}function J(e,t,n=5){let r=t.filter(e=>e.action.trim().length>0).slice(0,n);if(r.length){process.stdout.write(`\n${e}\n`);for(let[e,t]of r.entries()){let n=t.context?` (${t.context})`:``;process.stdout.write(`${e+1}. ${t.label}${n}: ${t.action}\n`)}t.length>r.length&&process.stdout.write(`Showing ${r.length} of ${t.length}. Use --json for full data.\n`)}}function ni(e){process.stdout.write(`\nNext: ${e}\n`)}function Y(e,t){let n=t.filter(e=>e.trim().length>0);if(n.length){process.stdout.write(`\n${e}\n`);for(let e of n)process.stdout.write(`- ${e}\n`)}}async function ri(e,t={}){let n=E(e[`report-id`]);if(n){let e=p(n);if(!e)throw Error(`No saved crawl report found for ${n}.`);return e}let r=D(e),i=E(e.site),a=r||i?await U({client:r,site:i,options:t}):void 0,o=ue(a?.site);if(!o)throw Error(a?.site?`No saved crawl report found for ${a.site}. Run \`seo crawl --project ${a.client?.id??a.site} --save\` first.`:"No saved crawl report found. Run `seo crawl <url> --save` first, or pass --report-id.");return o}function ii(e){process.stdout.write(`AI-search evidence for ${e.url}\n\n`),z([[`Assessment`,`evidence only`],[`Data`,e.dataStatus],[`Report`,e.reportId]]),process.stdout.write(`\n${e.headline}\n`),e.topActions.length&&(process.stdout.write(`
123
+ `)}function vi(e,t,n){let r=t.filter(e=>e.trim().length>0).flatMap(e=>L(e,n.columns));return[n.colors.bold(e),...r].join(`
124
+ `)}function yi(e,t,n){let r=t.flatMap(e=>L(e,Math.max(1,n.columns-2)).map((e,t)=>`${t===0?`- `:` `}${e}`));return[n.colors.bold(e),...r].join(`
125
+ `)}function bi(e,t){return e.length===0?t.colors.dim(`No parameters.`):_i(e.map(e=>({title:e.name,description:e.description,meta:[e.type,e.required?`required`:`optional`]})),t,{empty:`No parameters.`})}function R(e={}){return!!(!e.json&&process.stdin.isTTY&&process.stdout.isTTY&&!process.env.CI)}function z(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}function B(e){let t=si(e,F());t&&process.stdout.write(`${t}\n`)}function V(e,t){process.stdout.write(`${oi(e,t,F())}\n`)}function xi(e){process.stdout.write(`${ci(e,F())}\n`)}function Si(e,t){process.stdout.write(`${di(e,F(),t)}\n`)}function Ci(e){process.stdout.write(`${fi(e,F())}\n`)}function wi(e,t){process.stdout.write(`${gi(e,F(),t)}\n`)}function Ti(e,t){process.stdout.write(`${_i(e,F(),t)}\n`)}function Ei(e,...t){process.stdout.write(`${vi(e,t,F())}\n`)}function Di(e,t){process.stdout.write(`${yi(e,t,F())}\n`)}function Oi(e){process.stdout.write(`${bi(e,F())}\n`)}function ki(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function H(e){return typeof e==`symbol`&&process.exit(1),e}function Ai(e,t){let n=t.trim().toLowerCase();return!n||e.some(e=>e.toLowerCase().includes(n))}async function ji(e){let t=e.choices;if(e.choices.length>8){let n=H(await fr({message:e.searchMessage,placeholder:`Type part of the name or URL, or leave blank`}));if(t=e.choices.filter(t=>Ai(e.searchValues(t),n)),!t.length)throw new b(`INVALID_INPUT`,e.emptyMessage)}return H(await dr({message:e.message,options:t.map(t=>{let n=e.hint?.(t);return{value:t,label:e.label(t),...n?{hint:n}:{}}})}))}async function Mi(e){if(e.site)return e.site;let t=ae(),n=!!t.defaultSite&&(t.clients.some(e=>e.siteUrl===t.defaultSite)||t.sites.some(e=>e.siteUrl===t.defaultSite));if(t.defaultSite&&n)return t.defaultSite;if(e.options?.json||!R())throw new b(`INVALID_INPUT`,t.defaultSite?`Saved default site ${t.defaultSite} does not match any saved project. Pass --site or --project, or run \`seo start\` to save a new default.`:"No site selected. Pass --site, use --project on supported commands, or run `seo start` in a terminal.");let r=await sn(e.options?.refresh);if(!r.length)throw new b(`PROPERTY_NOT_FOUND`,`No Search Console properties found for this Google login.`);return r.length===1?r[0]?.siteUrl??``:(await ji({message:`Choose a Search Console property`,searchMessage:`Search Search Console properties`,emptyMessage:`No Search Console properties matched that search.`,choices:r,label:e=>e.siteUrl,hint:e=>e.permissionLevel,searchValues:e=>[e.siteUrl,e.permissionLevel??``]})).siteUrl}async function U(e){if(e.client&&e.project&&e.client!==e.project)throw new b(`INVALID_INPUT`,`Use either --project or --client, not both.`);let t=e.project??e.client;if(t){let e=Ce(t);if(!e)throw new b(`INVALID_INPUT`,`Project not found: ${t}`);return{client:e,site:e.siteUrl}}let n=Ce();return!e.site&&n?{client:n,site:n.siteUrl}:{site:await Mi({site:e.site,options:e.options})}}async function Ni(e){if(e.client&&e.project&&e.client!==e.project)throw new b(`INVALID_INPUT`,`Use either --project or --client, not both.`);let t=e.project??e.client;if(t){let e=Ce(t);if(!e)throw new b(`INVALID_INPUT`,`Project not found: ${t}`);return e}let n=ie();if(!n.length)return;let r=Ce();if(r)return r;if(!(e.options?.json||!R()))return ji({message:`Choose a project`,searchMessage:`Search projects`,emptyMessage:`No projects matched that search.`,choices:n,label:e=>e.name,hint:e=>e.siteUrl,searchValues:e=>[e.id,e.name,e.siteUrl]})}async function Pi(e){if(e.property)return e.property;let t=ae();if(t.analytics.google.defaultPropertyId)return t.analytics.google.defaultPropertyId;if(e.options?.json||!R())throw new b(`INVALID_INPUT`,`No Google Analytics property selected. Pass --property or run this command in a terminal to choose one.`);let n=(await Fe()).flatMap(e=>e.propertySummaries.map(t=>({property:l(t.property),displayName:t.displayName??t.property,account:e.displayName??e.account})));if(!n.length)throw new b(`PROPERTY_NOT_FOUND`,`No Google Analytics properties found for this Google login.`);return n.length===1?n[0]?.property??``:(await ji({message:`Choose a Google Analytics property`,searchMessage:`Search Google Analytics properties`,emptyMessage:`No Google Analytics properties matched that search.`,choices:n,label:e=>`${e.displayName} (${e.property})`,hint:e=>e.account,searchValues:e=>[e.property,e.displayName,e.account]})).property}function W(e){return Math.round(e).toLocaleString(`en-GB`)}function Fi(e){return e.toFixed(1)}function G(e){return`${(e*100).toFixed(1)}%`}function K(e,t=72){return Qr(e,t)}function Ii(e){return e.verification?.requested?`${e.verification.verified} checked, ${e.verification.failed} failed`:`off`}function q(e,t){V(e,t.slice(0,25)),t.length>25&&process.stdout.write(`Showing 25 of ${t.length}. Use --json for full data.\n`)}function J(e,t,n=5){let r=t.filter(e=>e.action.trim().length>0).slice(0,n);if(r.length){process.stdout.write(`\n${e}\n`);for(let[e,t]of r.entries()){let n=t.context?` (${t.context})`:``;process.stdout.write(`${e+1}. ${t.label}${n}: ${t.action}\n`)}t.length>r.length&&process.stdout.write(`Showing ${r.length} of ${t.length}. Use --json for full data.\n`)}}function Li(e){process.stdout.write(`\nNext: ${e}\n`)}function Y(e,t){let n=t.filter(e=>e.trim().length>0);if(n.length){process.stdout.write(`\n${e}\n`);for(let e of n)process.stdout.write(`- ${e}\n`)}}async function Ri(e,t={}){let n=D(e[`report-id`]);if(n){let e=Yt(n);if(!e)throw Error(`No saved crawl report found for ${n}.`);return e}let r=O(e),i=D(e.site),a=r||i?await U({client:r,site:i,options:t}):void 0,o=en(a?.site);if(!o)throw Error(a?.site?`No saved crawl report found for ${a.site}. Run \`seo crawl --project ${a.client?.id??a.site} --save\` first.`:"No saved crawl report found. Run `seo crawl <url> --save` first, or pass --report-id.");return o}function zi(e){process.stdout.write(`AI-search evidence for ${e.url}\n\n`),B([[`Assessment`,`evidence only`],[`Data`,e.dataStatus],[`Report`,e.reportId]]),process.stdout.write(`\n${e.headline}\n`),e.topActions.length&&(process.stdout.write(`
27
126
  Top actions
28
- `),B([`Status`,`Check`,`Action`],e.topActions.map(e=>[e.status,e.title,K(e.action,96)]))),e.botAccess.length&&(process.stdout.write(`
127
+ `),V([`Status`,`Check`,`Action`],e.topActions.map(e=>[e.status,e.title,K(e.action,96)]))),e.botAccess.length&&(process.stdout.write(`
29
128
  Bot access
30
- `),B([`User agent`,`Allowed`,`Declared`],e.botAccess.map(e=>[e.userAgent,e.allowed===null?`unknown`:e.allowed?`yes`:`no`,e.declared?`yes`:e.coveredByWildcard?`wildcard`:`no`]))),Y(`Caveats`,e.caveats)}const ai=C({meta:{name:`ai-readiness`,description:`Review AI-search technical evidence and optional observations`},args:{"report-id":{type:`string`,description:`Saved crawl report id to analyze.`},site:{type:`string`,description:`GSC property URL for selecting the latest saved crawl.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=De(await ri(e,{json:t}));if(t){R(n);return}ii(n)}});function oi(e){let t=E(e.agentReadinessUrl),n=E(e.url);if(t&&n&&t!==n)throw Error(`Use either the positional URL or --url, not both.`);return t??n}function si(e){process.stdout.write(`AI agent readiness for ${e.url}\n\n`),z([[`Profile`,e.profile],[`Assessment`,`evidence only`],[`Data`,e.dataStatus],[`Report`,e.reportId],[`Passed`,String(e.summary.passed)],[`Needs review`,String(e.summary.warnings)],[`Failed`,String(e.summary.failed)],[`Unknown`,String(e.summary.unknown)],[`Information`,String(e.summary.information)]]),process.stdout.write(`\n${e.headline}\n`),process.stdout.write(`
129
+ `),V([`User agent`,`Allowed`,`Declared`],e.botAccess.map(e=>[e.userAgent,e.allowed===null?`unknown`:e.allowed?`yes`:`no`,e.declared?`yes`:e.coveredByWildcard?`wildcard`:`no`]))),Y(`Caveats`,e.caveats)}const Bi=w({meta:{name:`ai-readiness`,description:`Review AI-search technical evidence and optional observations`},args:{"report-id":{type:`string`,description:`Saved crawl report id to analyze.`},site:{type:`string`,description:`GSC property URL for selecting the latest saved crawl.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=Nt(await Ri(e,{json:t}));if(t){z(n);return}zi(n)}});function Vi(e){let t=D(e.agentReadinessUrl),n=D(e.url);if(t&&n&&t!==n)throw Error(`Use either the positional URL or --url, not both.`);return t??n}function Hi(e){process.stdout.write(`AI agent readiness for ${e.url}\n\n`),B([[`Profile`,e.profile],[`Assessment`,`evidence only`],[`Data`,e.dataStatus],[`Report`,e.reportId],[`Passed`,String(e.summary.passed)],[`Needs review`,String(e.summary.warnings)],[`Failed`,String(e.summary.failed)],[`Unknown`,String(e.summary.unknown)],[`Information`,String(e.summary.information)]]),process.stdout.write(`\n${e.headline}\n`),process.stdout.write(`
31
130
  Profile scope
32
- `),B([`Profile`,`Status`,`Reason`],Object.entries(e.profileApplicability).map(([e,t])=>[e,t.status===`notApplicable`?`not applicable`:t.status,K(t.reason,96)])),e.topActions.length&&(process.stdout.write(`
131
+ `),V([`Profile`,`Status`,`Reason`],Object.entries(e.profileApplicability).map(([e,t])=>[e,t.status===`notApplicable`?`not applicable`:t.status,K(t.reason,96)])),e.topActions.length&&(process.stdout.write(`
33
132
  What to check next
34
- `),B([`Status`,`Check`,`Action`],e.topActions.map(e=>[e.status,e.title,K(e.action,96)]))),Y(`Caveats`,e.caveats)}const ci=C({meta:{name:`agent-readiness`,description:`Check content-site access, Markdown alternatives, discovery, and identity for AI agents`},args:{agentReadinessUrl:{type:`positional`,required:!1,description:`Public site URL to check.`},url:{type:`string`,description:`Public site URL to check.`},"report-id":{type:`string`,description:`Saved crawl report id to analyze without fetching again.`},site:{type:`string`,description:`GSC property URL for selecting the latest saved crawl.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},"max-pages":{type:`string`,description:`Maximum public HTML pages to crawl.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache and fetch fresh pages.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=oi(e),r=E(e[`report-id`]);if(n&&r)throw Error(`Use either a URL or --report-id, not both.`);let i=Te(n?await(async()=>{let r=D(e),i=E(e.site),a=r||i?await U({client:r,site:i,options:{json:t}}):void 0;return ut({url:n,projectId:a?.client?.id,site:a?.site,maxPages:k(e[`max-pages`]),fetchRate:dr(e),refresh:O(e.refresh),checkAgentDiscovery:!0,useSitemap:!0,checkExternal:!1})})():await ri(e,{json:t}));if(t){R(i);return}si(i)}}),li=C({meta:{name:`properties`,description:`List Google Analytics accounts and properties`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},save:{type:`string`,description:`Save this numeric Google Analytics property ID as the default.`}},run:async({args:e})=>{let t=await At(),n=t.flatMap(e=>e.propertySummaries.map(t=>({account:e.displayName??e.account,property:Ft(t.property),displayName:t.displayName??t.property}))),r=E(e.save);if(r){let e=_t();e.analytics.google.defaultPropertyId=r,tt(e)}if(N(e)){R({accountSummaries:t,properties:n,saved:r});return}r&&process.stdout.write(`Saved default Google Analytics property ${r}.\n`),B([`Property`,`Name`,`Account`],n.map(e=>[e.property,e.displayName,e.account]))}});async function ui(e,t={resolveClient:Qr,resolveGoogleAnalyticsProperty:$r}){if(e.property)return t.resolveGoogleAnalyticsProperty({property:e.property,options:e.options});let n=await t.resolveClient({client:e.project,options:e.options});return t.resolveGoogleAnalyticsProperty({property:ye(n),options:e.options})}const di=C({meta:{name:`analytics`,description:`Read analytics data from connected providers`},subCommands:{google:C({meta:{name:`google`,description:`Read Google Analytics properties and reports`},subCommands:{properties:li,report:C({meta:{name:`report`,description:`Run a Google Analytics report`},args:{property:{type:`string`,description:`Google Analytics property ID. If omitted in a terminal, choose one.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name with an optional Google Analytics property.`},"start-date":{type:`string`,default:`28daysAgo`},"end-date":{type:`string`,default:`yesterday`},dimensions:{type:`string`,default:`landingPage`},metrics:{type:`string`,default:`sessions,totalUsers,eventCount`},limit:{type:`string`,default:`25`},body:{type:`string`},"body-file":{type:`string`},refresh:{type:`boolean`,default:!1,description:`Bypass the local Google Analytics cache.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=await ui({property:E(e.property),project:D(e),options:{json:t}}),r=await Be(n,await pr(e.body,e[`body-file`])??{dateRanges:[{startDate:E(e[`start-date`]),endDate:E(e[`end-date`])}],dimensions:(j(e.dimensions)??[]).map(e=>({name:e})),metrics:(j(e.metrics)??[]).map(e=>({name:e})),limit:E(e.limit)},{refresh:O(e.refresh)});if(t){R(r);return}let i=yt(r);if(z([[`Property`,n],[`Rows`,String(r.rowCount??i.length)]]),i.length){let e=Object.keys(i[0]??{});B(e,i.slice(0,25).map(t=>e.map(e=>t[e]??``)))}}})}})}});function fi(e){return e?e===`environment-json`?`SEO_GOOGLE_SERVICE_ACCOUNT_JSON`:e===`environment-file`?`SEO_GOOGLE_SERVICE_ACCOUNT_FILE`:`GOOGLE_APPLICATION_CREDENTIALS`:`invalid or conflicting configuration`}function pi(e){return e.active===`keychain`?`system keychain`:e.configured===`keychain`?`private file fallback`:`private file`}function mi(e){return e===`shared`?`SEO Skill app`:`Local OAuth config`}function hi(e){let t=[[`Account`,e.accountEmail]],n=new Set(e.scope.split(/\s+/u).filter(Boolean));return n.has(`https://www.googleapis.com/auth/webmasters.readonly`)?t.push([`Search Console`,`Read only`]):t.push([`Search Console`,`Not granted`]),n.has(`https://www.googleapis.com/auth/analytics.readonly`)?t.push([`Google Analytics`,`Read only`]):t.push([`Google Analytics`,`Not granted`]),t.push([`OAuth app`,mi(e.clientSource)],[`Expires`,or(e.expiresAt)]),t}const gi=C({meta:{name:`auth`,description:`Authentication commands`},subCommands:{login:C({meta:{name:`login`,description:`Run Google OAuth flow`},run:async()=>{if((await mt()).activeMode===`service-account`)throw new y(`AUTH_CONFIG_REQUIRED`,`A service account is active from the environment. Unset its credential variable before running browser OAuth.`);let e=await We();z(hi({accountEmail:e.account_email,clientSource:e.client_source,expiresAt:e.expires_at,scope:e.scope}))}}),logout:C({meta:{name:`logout`,description:`Delete locally stored tokens`},run:async()=>{let e=await mt();if(await qe(),e.activeMode===`service-account`){process.stdout.write(`Deleted local OAuth tokens. Service account credentials remain available through the environment.
133
+ `),V([`Status`,`Check`,`Action`],e.topActions.map(e=>[e.status,e.title,K(e.action,96)]))),Y(`Caveats`,e.caveats)}const Ui=w({meta:{name:`agent-readiness`,description:`Check content-site access, Markdown alternatives, discovery, and identity for AI agents`},args:{agentReadinessUrl:{type:`positional`,required:!1,description:`Public site URL to check.`},url:{type:`string`,description:`Public site URL to check.`},"report-id":{type:`string`,description:`Saved crawl report id to analyze without fetching again.`},site:{type:`string`,description:`GSC property URL for selecting the latest saved crawl.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},"max-pages":{type:`string`,description:`Maximum public HTML pages to crawl.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache and fetch fresh pages.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let n=P(e),r=Vi(e),i=D(e[`report-id`]);if(r&&i)throw Error(`Use either a URL or --report-id, not both.`);let a=ut(r?await(async()=>{let i=O(e),a=D(e.site),o=i||a?await U({client:i,site:a,options:{json:n}}):void 0;return t({url:r,projectId:o?.client?.id,site:o?.site,maxPages:A(e[`max-pages`]),fetchRate:Gr(e),refresh:k(e.refresh),checkAgentDiscovery:!0,useSitemap:!0,checkExternal:!1})})():await Ri(e,{json:n}));if(n){z(a);return}Hi(a)}}),Wi=w({meta:{name:`properties`,description:`List Google Analytics accounts and properties`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},save:{type:`string`,description:`Save this numeric Google Analytics property ID as the default.`}},run:async({args:e})=>{let t=await Fe(),n=t.flatMap(e=>e.propertySummaries.map(t=>({account:e.displayName??e.account,property:l(t.property),displayName:t.displayName??t.property}))),r=D(e.save);if(r){let e=ae();e.analytics.google.defaultPropertyId=r,ke(e)}if(P(e)){z({accountSummaries:t,properties:n,saved:r});return}r&&process.stdout.write(`Saved default Google Analytics property ${r}.\n`),V([`Property`,`Name`,`Account`],n.map(e=>[e.property,e.displayName,e.account]))}});async function Gi(e,t={resolveClient:Ni,resolveGoogleAnalyticsProperty:Pi}){if(e.property)return t.resolveGoogleAnalyticsProperty({property:e.property,options:e.options});let n=await t.resolveClient({client:e.project,options:e.options});return t.resolveGoogleAnalyticsProperty({property:g(n),options:e.options})}const Ki=w({meta:{name:`analytics`,description:`Read analytics data from connected providers`},subCommands:{google:w({meta:{name:`google`,description:`Read Google Analytics properties and reports`},subCommands:{properties:Wi,report:w({meta:{name:`report`,description:`Run a Google Analytics report`},args:{property:{type:`string`,description:`Google Analytics property ID. If omitted in a terminal, choose one.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name with an optional Google Analytics property.`},"start-date":{type:`string`,default:`28daysAgo`},"end-date":{type:`string`,default:`yesterday`},dimensions:{type:`string`,default:`landingPage`},metrics:{type:`string`,default:`sessions,totalUsers,eventCount`},limit:{type:`string`,default:`25`},body:{type:`string`},"body-file":{type:`string`},refresh:{type:`boolean`,default:!1,description:`Bypass the local Google Analytics cache.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=await Gi({property:D(e.property),project:O(e),options:{json:t}}),r=await f(n,await qr(e.body,e[`body-file`])??{dateRanges:[{startDate:D(e[`start-date`]),endDate:D(e[`end-date`])}],dimensions:(M(e.dimensions)??[]).map(e=>({name:e})),metrics:(M(e.metrics)??[]).map(e=>({name:e})),limit:D(e.limit)},{refresh:k(e.refresh)});if(t){z(r);return}let i=un(r);if(B([[`Property`,n],[`Rows`,String(r.rowCount??i.length)]]),i.length){let e=Object.keys(i[0]??{});V(e,i.slice(0,25).map(t=>e.map(e=>t[e]??``)))}}})}})}});function qi(e){return e?e===`environment-json`?`SEO_GOOGLE_SERVICE_ACCOUNT_JSON`:e===`environment-file`?`SEO_GOOGLE_SERVICE_ACCOUNT_FILE`:`GOOGLE_APPLICATION_CREDENTIALS`:`invalid or conflicting configuration`}function Ji(e){return e.active===`keychain`?`system keychain`:e.configured===`keychain`?`private file fallback`:`private file`}function Yi(e){return e===`shared`?`SEO Skill app`:`Local OAuth config`}function Xi(e){let t=[[`Account`,e.accountEmail]],n=new Set(e.scope.split(/\s+/u).filter(Boolean));return n.has(`https://www.googleapis.com/auth/webmasters.readonly`)?t.push([`Search Console`,`Read only`]):t.push([`Search Console`,`Not granted`]),n.has(`https://www.googleapis.com/auth/analytics.readonly`)?t.push([`Google Analytics`,`Read only`]):t.push([`Google Analytics`,`Not granted`]),t.push([`OAuth app`,Yi(e.clientSource)],[`Expires`,zr(e.expiresAt)]),t}const Zi=w({meta:{name:`auth`,description:`Authentication commands`},subCommands:{login:w({meta:{name:`login`,description:`Run Google OAuth flow`},run:async()=>{if((await Dt()).activeMode===`service-account`)throw new b(`AUTH_CONFIG_REQUIRED`,`A service account is active from the environment. Unset its credential variable before running browser OAuth.`);let e=await r();B(Xi({accountEmail:e.account_email,clientSource:e.client_source,expiresAt:e.expires_at,scope:e.scope}))}}),logout:w({meta:{name:`logout`,description:`Delete locally stored tokens`},run:async()=>{let e=await Dt();if(await ve(),e.activeMode===`service-account`){process.stdout.write(`Deleted local OAuth tokens. Service account credentials remain available through the environment.
35
134
  `);return}process.stdout.write(`Deleted local OAuth tokens.
36
135
  Revoke at https://myaccount.google.com/permissions if you also want Google to forget the grant.
37
- `)}}),whoami:C({meta:{name:`whoami`,description:`Show the signed-in Google account`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await mt();if(t.activeMode===`service-account`){let n={mode:`service-account`,account:t.identity??null,source:fi(t.serviceAccount.source)};if(N(e)){R(n);return}z([[`Account type`,`Service account`],[`Account`,t.identity??`Invalid configuration`],[`Credentials`,n.source],[`Access`,`Search Console and Google Analytics, read only`]]);return}let n=t.tokens;if(!n){if(N(e)){R({mode:`oauth`,account:null});return}process.stdout.write(`Not logged in.
38
- `);return}if(N(e)){R({mode:`oauth`,account:n.account_email,scopes:n.scope.split(/\s+/u).filter(Boolean),clientSource:n.client_source,expiresAt:n.expires_at});return}z(hi({accountEmail:n.account_email,clientSource:n.client_source,expiresAt:n.expires_at,scope:n.scope}))}}),status:C({meta:{name:`status`,description:`Show local Google auth status`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await mt(),n=t.activeMode===`oauth`?await Tt():void 0;if(N(e)){R({authenticated:t.activeMode===`oauth`?!!t.tokens:t.serviceAccount.configured,mode:t.activeMode,identity:t.identity,account:t.activeMode===`oauth`?t.tokens?.account_email:void 0,scopes:t.activeMode===`oauth`?t.tokens?.scope:void 0,clientSource:t.activeMode===`oauth`?t.tokens?.client_source:void 0,expiresAt:t.activeMode===`oauth`?t.tokens?.expires_at:void 0,sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured,serviceAccount:{configured:t.serviceAccount.configured,identity:t.serviceAccount.identity,source:t.serviceAccount.source,error:t.serviceAccount.error},...n?{tokenStorage:n}:{}});return}if(t.activeMode===`service-account`){let e=[[`Mode`,`service account`],[`Identity`,t.identity??`unavailable`],[`Source`,fi(t.serviceAccount.source)],[`Scopes`,`Search Console readonly, Google Analytics readonly`],[`Storage`,`credentials stay in the environment`]];t.serviceAccount.error&&e.push([`Status`,t.serviceAccount.error]),z(e);return}if(!t.tokens){let e=t.serviceAccount.error?t.serviceAccount.error:t.sharedConfigured?`Shared seo app available`:t.byoConfigured?`Local OAuth config available`:`No OAuth client configured`;process.stdout.write(`Not logged in. ${e}. Run \`seo auth login\` to connect Google.\n`);return}let r=n??await Tt();z([[`Account`,t.tokens.account_email],[`Scopes`,t.tokens.scope],[`Client`,mi(t.tokens.client_source)],[`Expires`,or(t.tokens.expires_at)],[`Tokens file`,Yt().tokensFile],[`Token storage`,pi(r)],...r.reason?[[`Storage note`,r.reason]]:[],[`OAuth mode`,t.sharedConfigured?`SEO Skill app available`:t.byoConfigured?`Local OAuth config available`:`missing`],[`Revoke at`,`https://myaccount.google.com/permissions`]])}}),storage:C({meta:{name:`storage`,description:`Show or change local OAuth token storage`},args:{keychain:{type:`boolean`,default:!1,description:`Store OAuth tokens in the system keychain when available.`},file:{type:`boolean`,default:!1,description:`Store OAuth tokens in the private local file.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(e.keychain&&e.file)throw new y(`INVALID_INPUT`,`Choose either --keychain or --file, not both.`);let t=e.keychain||e.file?await it(e.keychain?`keychain`:`file`):await Tt();if(N(e)){R(t);return}z([[`Configured storage`,t.configured],[`Active storage`,pi(t)],...t.reason?[[`Note`,t.reason]]:[]])}}),refresh:C({meta:{name:`refresh`,description:`Refresh the Google OAuth token`},run:async()=>{if((await mt()).activeMode===`service-account`){process.stdout.write(`Service accounts request short-lived Google tokens automatically. No local refresh token is stored.
39
- `);return}let e=await Rt();process.stdout.write(`Refreshed. New expiry ${new Date(e.expires_at).toISOString()}.\n`)}}),"setup-client":C({meta:{name:`setup-client`,description:`Save your own Google Desktop OAuth client`},args:{json:{type:`boolean`,default:!1,description:`Return a structured error instead of prompting.`}},run:async({args:e})=>{if(!L({json:N(e)}))throw new y(`INVALID_INPUT`,"`seo auth setup-client` needs an interactive terminal. Run it without --json, or set SEO_GOOGLE_CLIENT_ID and SEO_GOOGLE_CLIENT_SECRET.");Fn(`Local Google OAuth client`),w([`This is the advanced path.`,`Most users should use the shared seo Google app.`,`Your actual sensitive data is the local refresh token, not the desktop app client secret.`].join(`
40
- `),`Advanced`),Le({clientId:H(await Hn({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),clientSecret:H(await Bn({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}))}),zn(`Saved local OAuth config to ${Yt().oauthClientFile}`)}})}}),_i=C({meta:{name:`cache`,description:`Cache helpers`},subCommands:{stats:C({meta:{name:`stats`,description:`Show local cache size and row counts`},run:async()=>{let e=Mt();z([[`DB`,e.dbPath],[`Size`,Jr(e.sizeBytes)],[`Cached data`,`${Jr(e.logicalSizeBytes)} of ${Jr(e.maxSizeBytes)} automatic limit`],[`Sites`,String(e.counts.sites??0)],[`Search Console`,String(e.counts.gsc_cache??0)],[`Google Analytics`,String(e.counts.google_analytics_cache??0)],[`Semrush`,String(e.counts.semrush_cache??0)],[`HTTP`,String(e.counts.http_cache??0)]])}}),clear:C({meta:{name:`clear`,description:`Clear cached API and HTTP data`},args:{provider:{type:`string`,description:`Optional cache provider: gsc, google-analytics, semrush, or http`}},run:async({args:e})=>{let t=St(e.provider);process.stdout.write(`Removed ${t} cached rows.\n`)}})}});async function vi(e,t={}){return(await U({client:e.client,project:e.project,site:e.site,options:t})).site}function yi(e){if(e.startsWith(`http://`)||e.startsWith(`https://`))return e;if(e.startsWith(`sc-domain:`))return`https://${e.slice(10)}/`}function bi(e){return e.replace(/^sc-domain:/,``).replace(/^https?:\/\//,``)}function xi(e){return e.toLowerCase().replace(/^https?:\/\//,``).replace(/^sc-domain:/,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,60)}function Si(e){return e?e.backpressure?.status===`stopped`?`stopped: ${e.backpressure.reason??`origin cooldown`}`:e.backpressure?.status===`slowed`?`slowed ${e.backpressure.delayMs}ms`:e.rendering?.status===`unavailable`?`raw HTML; rendering unavailable`:e.rendering?.status===`failed`?`raw HTML; rendering failed`:e.blocked?`blocked`:e.rendered?`rendered`:e.cache===`hit`?`cached`:e.fetched?`fetched`:e.source:`-`}function Ci(e){return e?e===`serp-framing`?`wording gap`:e===`content-gap`?`content gap`:e===`technical-check`?`technical check`:`covered`:`-`}function wi(e){let t=e.platform===`win32`?gn:pn;return e.platform===`win32`?e.env.APPDATA??t.resolve(e.home,`AppData/Roaming`):e.platform===`darwin`?t.resolve(e.home,`Library/Application Support`):e.env.XDG_CONFIG_HOME??t.resolve(e.home,`.config`)}function Ti(e={}){let t=e.home??un(),n=e.platform??process.platform,r=wi({home:t,platform:n,env:e.env??process.env}),i=n===`win32`?gn:pn,a=[];if(n===`darwin`||n===`win32`){let e=i.resolve(r,`Claude`);a.push({kind:`json`,client:`claude-desktop`,label:`Claude Desktop`,path:i.resolve(e,`claude_desktop_config.json`),commandNames:[],detectionPaths:n===`darwin`?[e,`/Applications/Claude.app`]:[e]})}return a.push({kind:`json`,client:`claude-code`,label:`Claude Code`,path:i.resolve(t,`.claude.json`),includeType:!0,commandNames:[`claude`],detectionPaths:[i.resolve(t,`.claude`)]},{kind:`native`,client:`codex`,label:`Codex`,path:i.resolve(t,`.codex/config.toml`),executable:`codex`,commandNames:[`codex`],detectionPaths:[i.resolve(t,`.codex`)]},{kind:`json`,client:`cursor`,label:`Cursor`,path:i.resolve(t,`.cursor/mcp.json`),commandNames:[`cursor`,`cursor-agent`],detectionPaths:[i.resolve(t,`.cursor`),...n===`darwin`?[`/Applications/Cursor.app`]:[]]}),a}function Ei(e,t={}){let n=t.platform??process.platform,r=t.exists??b,i=t.nodePath??process.execPath,a=n===`win32`?[`${e}.cmd`,`${e}.exe`,e]:[e],o=(t.path??process.env.PATH??``).split(n===`win32`?`;`:`:`).filter(Boolean);for(let e of o)for(let t of a){let n=S(e,t);if(r(n))return n}for(let e of a){let t=S(x(i),e);if(r(t))return t}return e}function Di(e){return Ei(e)!==e}function Oi(e={}){let t=e.targets??Ti(),n=e.hasCommand??Di,r=e.hasPath??b;return t.filter(e=>e.kind===`native`?e.commandNames.some(n):r(e.path)||e.detectionPaths.some(r)||e.commandNames.some(n))}const ki={insertSpaces:!0,tabSize:2,eol:`
41
- `};function Ai(){return new Date().toISOString().replace(/[:.]/g,`-`)}function ji(e,t){tn(x(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.${Date.now()}.tmp`;ln(n,t,{encoding:`utf8`,mode:b(e)?cn(e).mode&511:384}),on(n,e)}function Mi(e){let t=`${e}.bak-${Ai()}`,n=t,r=2;for(;b(n);)n=`${t}-${r}`,r+=1;en(e,n,$t.COPYFILE_EXCL)}function Ni(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pi(e){if(!b(e.path))return{source:`{}
42
- `,config:{}};let t=nn(e.path,`utf8`),n=[],r=Jn(t,n,{allowTrailingComma:!0});if(n.length>0){let t=n[0],r=t?`${Yn(t.error)} at offset ${t.offset}`:`unknown parse error`;throw Error(`Cannot update ${e.path}: invalid JSONC (${r}).`)}if(!Ni(r))throw Error(`Cannot update ${e.path}: config root must be an object.`);if(r.mcpServers!==void 0&&!Ni(r.mcpServers))throw Error(`Cannot update ${e.path}: mcpServers must be an object.`);return{source:t,config:r}}function Fi(e){return e.includes(`mcp`)&&e.includes(`serve`)&&e.some(e=>e===`seo`||e.startsWith(`seo@`)||e===`@seo/cli`)}function Ii(e,t){return typeof e.command!=`string`||t.length!==3||t[1]!==`mcp`||t[2]!==`serve`||!Ni(e.env)?!1:e.env.SEO_MCP_CONFIGURED_BY===`seo`}function Li(e){if(!Ni(e)||!Array.isArray(e.args))return!1;let t=e.args.filter(e=>typeof e==`string`);return Fi(t)||Ii(e,t)}function Ri(e){let t=Kn(e.source,qn(e.source,[`mcpServers`,`seo`],e.value,{formattingOptions:ki}));b(e.target.path)&&Mi(e.target.path),ji(e.target.path,t)}function zi(e,t){let n=yn(e,t,{encoding:`utf8`});return{status:n.status,stdout:n.stdout??``,stderr:n.stderr??``,error:n.error}}function Bi(e){let t=e.replaceAll(`\\`,`/`).toLowerCase();return t.includes(`/_npx/`)||t.includes(`/.npm/_npx/`)||t.includes(`/.cache/pnpm/dlx/`)}function Vi(e){if(!e||!b(e))return;let t=an(e);return Bi(t)?void 0:t}function Hi(e={}){let n=Vi(e.cliPath??process.argv[1]);if(n)return{command:e.nodePath??process.execPath,args:[n,`mcp`,`serve`]};let r=`seo@${e.version??t}`;return(e.platform??process.platform)===`win32`?{command:`cmd`,args:[`/c`,`npx`,`-y`,r,`mcp`,`serve`]}:{command:`npx`,args:[`-y`,r,`mcp`,`serve`]}}function Ui(e=!1,t=Hi()){let n=Yt(),r={command:t.command,args:t.args,env:{SEO_CONFIG_DIR:n.configDir,SEO_MCP_CONFIGURED_BY:`seo`}};return e&&(r.type=`stdio`),r}function Wi(e){return e.includes(`SEO_MCP_CONFIGURED_BY`)||/args:\s+-y\s+(?:seo(?:@\S+)?|@seo\/cli)\s+mcp\s+serve\b/.test(e)}function Gi(e,t,n){let r=Ei(e.executable),i=n.runCommand(r,[`mcp`,`get`,`seo`]);if(i.error?.code===`ENOENT`)throw Error("Cannot install SEO MCP for Codex: the `codex` command is not available on PATH. Install Codex CLI or choose another MCP client.");let a=i.status===0;if(a&&!Wi(i.stdout))throw Error(`Cannot ${t} SEO MCP: ${e.path} already has an unmanaged mcp_servers.seo entry.`);if(t===`install`&&a&&!n.reinstall||t===`uninstall`&&!a)return{client:e.client,path:e.path,changed:!1};if(t===`install`&&a){let e=n.runCommand(r,[`mcp`,`remove`,`seo`]);if(e.error||e.status!==0){let t=e.error?.message??e.stderr.trim()??`unknown error`;throw Error(`Cannot reinstall SEO MCP for Codex: ${t}`)}}let o=Yt(),s=t===`install`?[`mcp`,`add`,`seo`,`--env`,`SEO_CONFIG_DIR=${o.configDir}`,`--env`,`SEO_MCP_CONFIGURED_BY=seo`,`--`,n.serverCommand.command,...n.serverCommand.args]:[`mcp`,`remove`,`seo`],c=n.runCommand(r,s);if(c.error||c.status!==0){let e=c.error?.message??c.stderr.trim()??`unknown error`;throw Error(`Cannot ${t} SEO MCP for Codex: ${e}`)}return{client:e.client,path:e.path,changed:!0}}function Ki(e,t={}){let n={runCommand:t.runCommand??zi,reinstall:t.reinstall??!1,serverCommand:t.serverCommand??Hi()};if(e.kind===`native`)return Gi(e,`install`,n);let{source:r,config:i}=Pi(e),a=i.mcpServers?.seo,o=Ui(e.includeType,n.serverCommand);if(xn(a,o)&&!n.reinstall)return{client:e.client,path:e.path,changed:!1};if(a!==void 0&&!Li(a))throw Error(`Cannot install SEO MCP: ${e.path} already has an unmanaged mcpServers.seo entry.`);return Ri({target:e,source:r,value:o}),{client:e.client,path:e.path,changed:!0}}function qi(e,t={}){if(e.kind===`native`)return Gi(e,`uninstall`,{runCommand:t.runCommand??zi,reinstall:!1,serverCommand:Hi()});if(!b(e.path))return{client:e.client,path:e.path,changed:!1};let{source:n,config:r}=Pi(e),i=r.mcpServers;if(i?.seo===void 0)return{client:e.client,path:e.path,changed:!1};if(!Li(i.seo))throw Error(`Cannot uninstall SEO MCP: ${e.path} has an unmanaged mcpServers.seo entry.`);return Ri({target:e,source:n,value:void 0}),{client:e.client,path:e.path,changed:!0}}function Ji(e={}){let t=yn(`npx`,[`-y`,`skills`,`add`,`iannuttall/seo`],{stdio:e.quiet?`ignore`:`inherit`});return t.error?{status:`failed`,error:t.error.message}:t.status===0?{status:`installed`}:{status:`failed`,error:`npx skills add exited with status ${t.status??`unknown`}.`}}function Yi(e){let t=e.canSkip?[{value:`skip`,label:`Skip for now`}]:[];return e.sharedConfigured||e.byoConfigured?[{value:`login`,label:`Connect Google`,hint:`Opens your browser for read-only Search Console and Google Analytics access`},...t]:[{value:`setup`,label:`Set up Google login for local development`,hint:`This source checkout does not include the public app credentials`},...t]}async function Xi(e){let t=[],n=!0,r=0;async function i(){for(;r<e.length;){let i=e[r];if(r+=1,i)try{let e=await st(i.property);t.push(...e.filter(e=>e.webStreamData).map(e=>({account:i.account,property:i.property,propertyName:i.label,stream:e})))}catch{n=!1}}}return await Promise.all(Array.from({length:Math.min(e.length,4)},()=>i())),{candidates:t,complete:n}}async function Zi(e){let t=await mt();if(t.activeMode===`service-account`)return`service-account`;if(t.tokens)return`already-connected`;if(e[`skip-auth`])return`skipped`;if(!L({json:e.json===!0}))throw new y(`AUTH_REQUIRED`,"Not logged in. Run `seo auth login`, or pass --skip-auth to save a project profile without connecting Google.");let n=H(await Vn({message:`Connect Google now?`,options:Yi({sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured,canSkip:typeof e.site==`string`&&e.site.length>0})}));return n===`skip`?`skipped`:(n===`setup`&&Le({clientId:H(await Hn({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),clientSecret:H(await Bn({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}))}),w(`Connected as ${(await We()).account_email}. seo has read-only access and cannot change your site.`,`Google connected`),`connected`)}async function Qi(e){if(e.property)return{propertyId:e.property,selection:`explicit`,reason:`Set with --google-analytics-property.`};if(!(e.interactive??L()))return;let t=(await At().catch(()=>[])).flatMap(e=>e.propertySummaries.map(t=>({property:Ft(t.property),label:t.displayName??t.property,account:e.displayName??e.account})));if(!t.length)return;let{candidates:n,complete:r}=await Xi(t),i=r?ir(e.site,n):[],a=new Map;for(let e of i)a.set(e.property,e);let o=[...a.values()];if(o.length===1){let t=o[0];return t?{propertyId:t.property,selection:`matched`,reason:ar(t,e.site)}:void 0}let s=o.length?o.map(e=>({property:e.property,label:e.propertyName,account:e.account,match:e})):t,c=H(await Vn({message:o.length?`Several Google Analytics properties match this site. Which property should seo use?`:r?`No Google Analytics web stream clearly matches this site. Attach a property?`:`Some Google Analytics web streams could not be read. Attach a property?`,options:[{value:``,label:`Skip Google Analytics for now`},...s.map(t=>({value:t,label:`${t.label} (${t.property})`,hint:t.match?ar(t.match,e.site):t.account}))]}));if(c)return{propertyId:c.property,selection:`manual`,reason:c.match?ar(c.match,e.site):r?`Selected ${c.label} during setup. Its web stream did not clearly match ${e.site}.`:`Selected ${c.label} during setup. seo could not read every Google Analytics web stream, so it did not guess a match.`}}async function $i(e){return e[`skip-skill`]||!L({json:e.json===!0})?{status:`skipped`}:H(await Pn({message:`Install the SEO skill so coding agents know how to run reports?`,initialValue:!0}))?Ji():{status:`declined`}}async function ea(e){if(e[`skip-mcp`]||!L({json:e.json===!0}))return[];let t=Oi();if(t.length===0||!H(await Pn({message:`Install seo as an MCP server too?`,initialValue:!0})))return[];let n=H(await Rn({message:`Which MCP clients?`,options:t.map(e=>({value:e.client,label:e.label,hint:e.path})),initialValues:t.map(e=>e.client)}));return t.filter(e=>n.includes(e.client)).map(e=>{try{return Ki(e)}catch(t){return{client:e.client,path:e.path,changed:!1,error:t instanceof Error?t.message:String(t)}}})}function ta(e){return e.status===`installed`?`installed`:e.status===`failed`?`install failed`:`not installed`}function na(e){return/^[A-Za-z0-9_./:@-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function ra(){process.stdout.write(`
43
- `),Vr({title:`Help other people find SEO Skill`,body:`If SEO Skill saved you time, a GitHub star helps other people find it.`,command:`https://github.com/iannuttall/seo`})}function ia(e){let t=e.filter(e=>e.error).length,n=e.length-t;return e.length===0?`not installed`:t===0?`${n} installed`:n===0?`${t} skipped`:`${n} installed, ${t} skipped`}function aa(e){let t=e.filter(e=>!!e.error);if(t.length!==0)return t.map(e=>`${e.client}: ${e.error}`).join(`
44
- `)}function oa(e,t,n){if(n)return;let r=o().filter(t=>t.siteUrl===e);return r.length===1?r[0]:r.find(e=>e.isDefault)??r.find(e=>e.name.toLocaleLowerCase()===t.toLocaleLowerCase())}async function sa(e){let t=N(e);if(t||Fn(process.argv[2]===`start`?`seo start`:`seo setup`),e[`dry-run`]){let e=[`seo auth login`,`seo start`,`seo report --project acme`,`seo refresh-priorities --project acme --verify-content`,`seo technical-watch --project acme`];t?R({dryRun:!0,next:e}):(w(e.join(`
45
- `),`This setup will guide you through`),zn(`Dry run complete.`));return}Vt();let n={site:E(e.site),options:{json:t,refresh:O(e.refresh)}},r=t?await Zr(n):void 0,i=await Zi(e),a=r??await Zr(n),o=bi(a);if(L({json:t})&&w(`A project profile remembers the site and report defaults so future commands stay short.`,`Project profile`),!(O(e[`skip-profile`])!==!0&&(!L({json:t})||H(await Pn({message:`Save this site as a project profile?`,initialValue:!0}))))){let n=await ea(e),r=await $i(e),o=`--site ${na(a)}`,s=[`seo report ${o}`,`seo refresh-priorities ${o} --verify-content`,`seo technical-watch ${o}`],c={site:a,auth:i,mcp:n,skill:r,next:s};if(t){R(c);return}z([[`Project profile`,`not saved`],[`GSC property`,a],[`Auth`,i],[`MCP`,ia(n)],[`SEO skill`,ta(r)]]);let l=aa(n);l&&w(l,`MCP setup skipped`),r.error&&w(r.error,`SEO skill install failed`),w(s.join(`
46
- `),`Try next`),zn(`Setup complete.`),ra();return}let s=E(e.name)??(L({json:t})?H(await Hn({message:`Project name`,placeholder:o,defaultValue:o})):o),c=E(e.id),l=c??oa(a,s,c)?.id??xi(s),u=yi(a)??``,d=E(e.url)??(L({json:t})?H(await Hn({message:`Website URL to crawl`,placeholder:u||`https://example.com`,defaultValue:u})):u||void 0),f=M(e.urls).length>0?M(e.urls):[],p=await Qi({property:E(e[`google-analytics-property`]),site:a,interactive:L({json:t})}),m=p?.propertyId,h=Ot({id:l,name:s,siteUrl:a}),g=M(e.brand).length>0?M(e.brand):h,ee=k(e[`report-day`])??1,te=k(e.weekday)??1,ne=O(e.default)??!0,_=Ut({id:l,name:s,siteUrl:a,startUrl:d,watchUrls:f,brandTerms:g,analytics:m?{google:{propertyId:m}}:void 0,reportDay:ee,technicalWeekday:te,isDefault:ne}),v=await ea(e),re=await $i(e),ie=[`seo report --project ${_.id}`,`seo refresh-priorities --project ${_.id} --verify-content`,`seo technical-watch --project ${_.id}`],ae={client:_,site:a,auth:i,googleAnalytics:p,mcp:v,skill:re,next:ie};if(t){R(ae);return}z([[`Project profile`,`${_.name} (${_.id})`],[`GSC property`,_.siteUrl],[`Crawl URL`,_.startUrl??`not set`],[`Watch URLs`,String(_.watchUrls.length)],[`Brand terms`,_.brandTerms.join(`, `)||`not set`],[`Google Analytics property`,_.analytics.google?.propertyId??`not connected (optional)`],...p?[[`Google Analytics selection`,p.reason]]:[],[`Auth`,i],[`MCP`,ia(v)],[`SEO skill`,ta(re)]]);let oe=aa(v);oe&&w(oe,`MCP setup skipped`),re.error&&w(re.error,`SEO skill install failed`),w(ie.join(`
47
- `),`Try next`),zn(`Setup complete.`),ra()}const ca=C({meta:{name:`setup`,description:`Guided setup for auth, one project profile, MCP, and next commands`},args:{id:{type:`string`,description:`Short stable project id.`},name:{type:`string`,description:`Human project name.`},site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},url:{type:`string`,description:`Default technical crawl start URL.`},urls:{type:`string`,description:`Comma-separated URLs to watch with URL Inspection.`},"google-analytics-property":{type:`string`,description:`Optional Google Analytics property ID.`},brand:{type:`string`,description:`Comma-separated branded query terms to exclude by default.`},"report-day":{type:`string`,description:`Preferred monthly report day. Defaults to 1.`},weekday:{type:`string`,description:`Preferred technical-watch weekday. Defaults to Monday.`},default:{type:`boolean`,description:`Make this the default project.`},"skip-profile":{type:`boolean`,default:!1,description:`Do not save a project profile during setup.`},"skip-auth":{type:`boolean`,default:!1,description:`Skip Google sign-in during setup.`},"skip-mcp":{type:`boolean`,default:!1,description:`Skip MCP install prompts.`},"skip-skill":{type:`boolean`,default:!1,description:`Skip the SEO skill install prompt.`},refresh:{type:`boolean`,default:!1,description:`Refresh GSC property discovery.`},"dry-run":{type:`boolean`,default:!1,description:`Show what setup does without changing files.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>sa(e)}),la=C({...ca,meta:{name:`start`,description:`Start here: connect Google, save a profile, and get the first report commands`}}),ua=C({...ca,meta:{name:`setup`,description:`Guided setup for one saved project profile`}}),da=C({meta:{name:`brand`,description:`Detect and manage project brand query terms`},subCommands:{detect:C({meta:{name:`detect`,description:`Suggest branded query terms from GSC navigational queries`},args:{client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name. Defaults to default.`},site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},days:{type:`string`,description:`Detection window length in days. Defaults to 28.`},limit:{type:`string`,description:`Maximum candidate terms. Defaults to 10.`},"min-impressions":{type:`string`,description:`Minimum query impressions. Defaults to 10.`},save:{type:`boolean`,default:!1,description:`Save suggested terms to the selected project.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass local GSC cache.`}},run:async({args:e})=>{let t=N(e),n=Gt(D(e)),r=await v({site:await Zr({site:E(e.site)??n?.siteUrl,options:{json:t,refresh:O(e.refresh)}}),id:n?.id,name:n?.name,days:k(e.days),limit:k(e.limit),minImpressions:k(e[`min-impressions`]),refresh:O(e.refresh)}),i=O(e.save)&&n?Ut({id:n.id,name:n.name,siteUrl:n.siteUrl,startUrl:n.startUrl,watchUrls:n.watchUrls,analytics:n.analytics,brandTerms:r.suggestedTerms,reportDay:n.reportDay,technicalWeekday:n.technicalWeekday,isDefault:n.isDefault}):void 0;if(O(e.save)&&!n)throw Error(`Pass --project to save detected brand terms.`);if(t){R({...r,saved:i});return}z([[`Property`,r.site],[`Derived terms`,r.derivedTerms.join(`, `)],[`Suggested terms`,r.suggestedTerms.join(`, `)],[`Saved`,i?i.id:`no`]]),B([`Term`,`Score`,`Evidence`],r.candidates.map(e=>[e.term,e.score,e.evidence.map(e=>`${e.query} (${Math.round(e.clicks)} clicks)`).join(`, `)]))}})}});function fa(e){Gr(e.map(e=>({title:`${e.name}${e.isDefault?` (default)`:``}`,description:e.siteUrl,meta:[e.id,e.startUrl?`crawl ${e.startUrl}`:``,e.watchUrls.length?`${e.watchUrls.length} watched URL${e.watchUrls.length===1?``:`s`}`:``,e.brandTerms.length?`${e.brandTerms.length} brand term${e.brandTerms.length===1?``:`s`}`:``]})),{empty:`No saved projects.`})}function pa(e){z([[`ID`,e.id],[`Name`,e.name],[`GSC property`,e.siteUrl],[`Crawl URL`,e.startUrl??`not set`],[`Watch URLs`,e.watchUrls.join(`, `)||`not set`],[`Brand terms`,e.brandTerms.join(`, `)||`not set`],[`Google Analytics property`,e.analytics.google?.propertyId??`not set`],[`Report day`,e.reportDay?String(e.reportDay):`not set`],[`Technical weekday`,e.technicalWeekday===void 0?`not set`:String(e.technicalWeekday)],[`Default`,e.isDefault?`yes`:`no`]])}const ma=C({meta:{name:`add`,description:`Create or update a project profile`},args:{id:{type:`string`,description:`Short stable project id, for example acme.`},name:{type:`string`,description:`Human project name.`},site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},url:{type:`string`,description:`Default technical crawl start URL.`},urls:{type:`string`,description:`Comma-separated URLs to watch with URL Inspection.`},"google-analytics-property":{type:`string`,description:`Optional Google Analytics property ID for this project.`},brand:{type:`string`,description:`Comma-separated branded query terms to exclude by default.`},"report-day":{type:`string`,description:`Preferred monthly report day, 1-31.`},weekday:{type:`string`,description:`Preferred technical-watch weekday, 0-7.`},default:{type:`boolean`,description:`Make this the default project.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=Ut({id:E(e.id),name:E(e.name),siteUrl:await Zr({site:E(e.site),options:{json:t}}),startUrl:E(e.url),watchUrls:M(e.urls),brandTerms:M(e.brand),analytics:E(e[`google-analytics-property`])?{google:{propertyId:E(e[`google-analytics-property`])??``}}:void 0,reportDay:k(e[`report-day`]),technicalWeekday:k(e.weekday),isDefault:O(e.default)});if(t){R(n);return}pa(n)}}),ha=C({meta:{name:`default`,description:`Set the default project`},args:{id:{type:`string`,required:!0,description:`Project id or name.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Se(E(e.id)??``);if(N(e)){R(t);return}process.stdout.write(`Default project set to ${t.id}.\n`)}}),ga=C({meta:{name:`delete`,description:`Delete a project profile`},args:{id:{type:`string`,required:!0,description:`Project id or name.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=E(e.id)??``,n=He(t);if(N(e)){R({id:t,deleted:n});return}process.stdout.write(`${n?`Deleted`:`Not found`} ${t}.\n`)}}),_a=C({meta:{name:`client`,description:`Manage saved project profiles`},subCommands:{setup:ua,brand:da,list:C({meta:{name:`list`,description:`List saved project profiles`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=o();if(N(e)){R({clients:t});return}fa(t)}}),add:ma,show:C({meta:{name:`show`,description:`Show one project profile`},args:{id:{type:`string`,description:`Project id or name. Defaults to the default project.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Gt(E(e.id));if(!t)throw Error(`Project not found.`);if(N(e)){R(t);return}pa(t)}}),default:ha,delete:ga}}),va=C({..._a,meta:{name:`projects`,description:`Manage saved project profiles`}}),ya=C({meta:{name:`content`,description:`Optimize page content from real GSC queries`},subCommands:{optimize:C({meta:{name:`optimize`,description:`Build a content optimization report for one URL`},args:{site:{type:`string`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},url:{type:`string`,required:!0},days:{type:`string`,description:`GSC lookback days. Defaults to 28.`},limit:{type:`string`,description:`Maximum GSC queries to inspect. Defaults to 25.`},"min-impressions":{type:`string`,description:`Minimum query impressions. Defaults to 10.`},"include-brand":{type:`boolean`,default:!1,description:`Include branded queries.`},"verify-content":T(`Fetch the page for content checks. Defaults to true.`,`Skip fetching the page for content checks.`),js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for page extraction.`},refresh:{type:`boolean`,default:!1,description:`Bypass local GSC and HTTP cache.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),r=await ke({site:n.site,url:E(e.url)??``,days:k(e.days),limit:k(e.limit),minImpressions:k(e[`min-impressions`]),brandTerms:n.client?.brandTerms,includeBrand:O(e[`include-brand`]),verifyContent:O(e[`verify-content`])!==!1,js:O(e.js)?!0:`auto`,refresh:O(e.refresh)});if(t){R(r);return}z([[`Property`,r.site],[`URL`,r.url],[`Score`,`${r.summary.score}/100`],[`Primary intent`,r.summary.primaryIntent],[`Primary query`,r.summary.primaryQuery??`none`],[`Queries`,W(r.summary.queries)],[`Opportunities`,W(r.summary.opportunities)],[`Estimated lift`,W(r.summary.estimatedClickLift)],[`Verdict`,r.summary.verdict]]),J(`Top actions`,r.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),r.brief.sections.length&&(process.stdout.write(`
136
+ `)}}),whoami:w({meta:{name:`whoami`,description:`Show the signed-in Google account`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await Dt();if(t.activeMode===`service-account`){let n={mode:`service-account`,account:t.identity??null,source:qi(t.serviceAccount.source)};if(P(e)){z(n);return}B([[`Account type`,`Service account`],[`Account`,t.identity??`Invalid configuration`],[`Credentials`,n.source],[`Access`,`Search Console and Google Analytics, read only`]]);return}let n=t.tokens;if(!n){if(P(e)){z({mode:`oauth`,account:null});return}process.stdout.write(`Not logged in.
137
+ `);return}if(P(e)){z({mode:`oauth`,account:n.account_email,scopes:n.scope.split(/\s+/u).filter(Boolean),clientSource:n.client_source,expiresAt:n.expires_at});return}B(Xi({accountEmail:n.account_email,clientSource:n.client_source,expiresAt:n.expires_at,scope:n.scope}))}}),status:w({meta:{name:`status`,description:`Show local Google auth status`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await Dt(),n=t.activeMode===`oauth`?await te():void 0;if(P(e)){z({authenticated:t.activeMode===`oauth`?!!t.tokens:t.serviceAccount.configured,mode:t.activeMode,identity:t.identity,account:t.activeMode===`oauth`?t.tokens?.account_email:void 0,scopes:t.activeMode===`oauth`?t.tokens?.scope:void 0,clientSource:t.activeMode===`oauth`?t.tokens?.client_source:void 0,expiresAt:t.activeMode===`oauth`?t.tokens?.expires_at:void 0,sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured,serviceAccount:{configured:t.serviceAccount.configured,identity:t.serviceAccount.identity,source:t.serviceAccount.source,error:t.serviceAccount.error},...n?{tokenStorage:n}:{}});return}if(t.activeMode===`service-account`){let e=[[`Mode`,`service account`],[`Identity`,t.identity??`unavailable`],[`Source`,qi(t.serviceAccount.source)],[`Scopes`,`Search Console readonly, Google Analytics readonly`],[`Storage`,`credentials stay in the environment`]];t.serviceAccount.error&&e.push([`Status`,t.serviceAccount.error]),B(e);return}if(!t.tokens){let e=t.serviceAccount.error?t.serviceAccount.error:t.sharedConfigured?`Shared seo app available`:t.byoConfigured?`Local OAuth config available`:`No OAuth client configured`;process.stdout.write(`Not logged in. ${e}. Run \`seo auth login\` to connect Google.\n`);return}let r=n??await te();B([[`Account`,t.tokens.account_email],[`Scopes`,t.tokens.scope],[`Client`,Yi(t.tokens.client_source)],[`Expires`,zr(t.tokens.expires_at)],[`Tokens file`,Ve().tokensFile],[`Token storage`,Ji(r)],...r.reason?[[`Storage note`,r.reason]]:[],[`OAuth mode`,t.sharedConfigured?`SEO Skill app available`:t.byoConfigured?`Local OAuth config available`:`missing`],[`Revoke at`,`https://myaccount.google.com/permissions`]])}}),storage:w({meta:{name:`storage`,description:`Show or change local OAuth token storage`},args:{keychain:{type:`boolean`,default:!1,description:`Store OAuth tokens in the system keychain when available.`},file:{type:`boolean`,default:!1,description:`Store OAuth tokens in the private local file.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(e.keychain&&e.file)throw new b(`INVALID_INPUT`,`Choose either --keychain or --file, not both.`);let t=e.keychain||e.file?await fe(e.keychain?`keychain`:`file`):await te();if(P(e)){z(t);return}B([[`Configured storage`,t.configured],[`Active storage`,Ji(t)],...t.reason?[[`Note`,t.reason]]:[]])}}),refresh:w({meta:{name:`refresh`,description:`Refresh the Google OAuth token`},run:async()=>{if((await Dt()).activeMode===`service-account`){process.stdout.write(`Service accounts request short-lived Google tokens automatically. No local refresh token is stored.
138
+ `);return}let e=await he();process.stdout.write(`Refreshed. New expiry ${new Date(e.expires_at).toISOString()}.\n`)}}),"setup-client":w({meta:{name:`setup-client`,description:`Save your own Google Desktop OAuth client`},args:{json:{type:`boolean`,default:!1,description:`Return a structured error instead of prompting.`}},run:async({args:e})=>{if(!R({json:P(e)}))throw new b(`INVALID_INPUT`,"`seo auth setup-client` needs an interactive terminal. Run it without --json, or set SEO_GOOGLE_CLIENT_ID and SEO_GOOGLE_CLIENT_SECRET.");ar(`Local Google OAuth client`),T([`This is the advanced path.`,`Most users should use the shared seo Google app.`,`Your actual sensitive data is the local refresh token, not the desktop app client secret.`].join(`
139
+ `),`Advanced`),yn({clientId:H(await fr({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),clientSecret:H(await ur({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}))}),lr(`Saved local OAuth config to ${Ve().oauthClientFile}`)}})}}),Qi=w({meta:{name:`cache`,description:`Cache helpers`},subCommands:{stats:w({meta:{name:`stats`,description:`Show local cache size and row counts`},run:async()=>{let e=At();B([[`DB`,e.dbPath],[`Size`,ki(e.sizeBytes)],[`Cached data`,`${ki(e.logicalSizeBytes)} of ${ki(e.maxSizeBytes)} automatic limit`],[`Sites`,String(e.counts.sites??0)],[`Search Console`,String(e.counts.gsc_cache??0)],[`Google Analytics`,String(e.counts.google_analytics_cache??0)],[`Semrush`,String(e.counts.semrush_cache??0)],[`HTTP`,String(e.counts.http_cache??0)]])}}),clear:w({meta:{name:`clear`,description:`Clear cached API and HTTP data`},args:{provider:{type:`string`,description:`Optional cache provider: gsc, google-analytics, semrush, or http`}},run:async({args:e})=>{let t=xe(e.provider);process.stdout.write(`Removed ${t} cached rows.\n`)}})}});async function $i(e,t={}){return(await U({client:e.client,project:e.project,site:e.site,options:t})).site}function ea(e){if(e.startsWith(`http://`)||e.startsWith(`https://`))return e;if(e.startsWith(`sc-domain:`))return`https://${e.slice(10)}/`}function ta(e){return e.replace(/^sc-domain:/,``).replace(/^https?:\/\//,``)}function na(e){return e.toLowerCase().replace(/^https?:\/\//,``).replace(/^sc-domain:/,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,60)}function ra(e){return e?e.backpressure?.status===`stopped`?`stopped: ${e.backpressure.reason??`origin cooldown`}`:e.backpressure?.status===`slowed`?`slowed ${e.backpressure.delayMs}ms`:e.rendering?.status===`unavailable`?`raw HTML; rendering unavailable`:e.rendering?.status===`failed`?`raw HTML; rendering failed`:e.blocked?`blocked`:e.rendered?`rendered`:e.cache===`hit`?`cached`:e.fetched?`fetched`:e.source:`-`}function ia(e){return e?e===`serp-framing`?`wording gap`:e===`content-gap`?`content gap`:e===`technical-check`?`technical check`:`covered`:`-`}function aa(e){let t=e.platform===`win32`?Rn:Fn;return e.platform===`win32`?e.env.APPDATA??t.resolve(e.home,`AppData/Roaming`):e.platform===`darwin`?t.resolve(e.home,`Library/Application Support`):e.env.XDG_CONFIG_HOME??t.resolve(e.home,`.config`)}function oa(e={}){let t=e.home??Mn(),n=e.platform??process.platform,r=aa({home:t,platform:n,env:e.env??process.env}),i=n===`win32`?Rn:Fn,a=[];if(n===`darwin`||n===`win32`){let e=i.resolve(r,`Claude`);a.push({kind:`json`,client:`claude-desktop`,label:`Claude Desktop`,path:i.resolve(e,`claude_desktop_config.json`),commandNames:[],detectionPaths:n===`darwin`?[e,`/Applications/Claude.app`]:[e]})}return a.push({kind:`json`,client:`claude-code`,label:`Claude Code`,path:i.resolve(t,`.claude.json`),includeType:!0,commandNames:[`claude`],detectionPaths:[i.resolve(t,`.claude`)]},{kind:`native`,client:`codex`,label:`Codex`,path:i.resolve(t,`.codex/config.toml`),executable:`codex`,commandNames:[`codex`],detectionPaths:[i.resolve(t,`.codex`)]},{kind:`json`,client:`cursor`,label:`Cursor`,path:i.resolve(t,`.cursor/mcp.json`),commandNames:[`cursor`,`cursor-agent`],detectionPaths:[i.resolve(t,`.cursor`),...n===`darwin`?[`/Applications/Cursor.app`]:[]]}),a}function sa(e,t={}){let n=t.platform??process.platform,r=t.exists??x,i=t.nodePath??process.execPath,a=n===`win32`?[`${e}.cmd`,`${e}.exe`,e]:[e],o=(t.path??process.env.PATH??``).split(n===`win32`?`;`:`:`).filter(Boolean);for(let e of o)for(let t of a){let n=C(e,t);if(r(n))return n}for(let e of a){let t=C(S(i),e);if(r(t))return t}return e}function ca(e){return sa(e)!==e}function la(e={}){let t=e.targets??oa(),n=e.hasCommand??ca,r=e.hasPath??x;return t.filter(e=>e.kind===`native`?e.commandNames.some(n):r(e.path)||e.detectionPaths.some(r)||e.commandNames.some(n))}const ua={insertSpaces:!0,tabSize:2,eol:`
140
+ `};function da(){return new Date().toISOString().replace(/[:.]/g,`-`)}function fa(e,t){wn(S(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.${Date.now()}.tmp`;jn(n,t,{encoding:`utf8`,mode:x(e)?An(e).mode&511:384}),On(n,e)}function pa(e){let t=`${e}.bak-${da()}`,n=t,r=2;for(;x(n);)n=`${t}-${r}`,r+=1;Sn(e,n,xn.COPYFILE_EXCL)}function ma(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ha(e){if(!x(e.path))return{source:`{}
141
+ `,config:{}};let t=Tn(e.path,`utf8`),n=[],r=vr(t,n,{allowTrailingComma:!0});if(n.length>0){let t=n[0],r=t?`${yr(t.error)} at offset ${t.offset}`:`unknown parse error`;throw Error(`Cannot update ${e.path}: invalid JSONC (${r}).`)}if(!ma(r))throw Error(`Cannot update ${e.path}: config root must be an object.`);if(r.mcpServers!==void 0&&!ma(r.mcpServers))throw Error(`Cannot update ${e.path}: mcpServers must be an object.`);return{source:t,config:r}}function ga(e){return e.includes(`mcp`)&&e.includes(`serve`)&&e.some(e=>e===`seo`||e.startsWith(`seo@`)||e===`@seo/cli`)}function _a(e,t){return typeof e.command!=`string`||t.length!==3||t[1]!==`mcp`||t[2]!==`serve`||!ma(e.env)?!1:e.env.SEO_MCP_CONFIGURED_BY===`seo`}function va(e){if(!ma(e)||!Array.isArray(e.args))return!1;let t=e.args.filter(e=>typeof e==`string`);return ga(t)||_a(e,t)}function ya(e){let t=gr(e.source,_r(e.source,[`mcpServers`,`seo`],e.value,{formattingOptions:ua}));x(e.target.path)&&pa(e.target.path),fa(e.target.path,t)}function ba(e,t){let n=Vn(e,t,{encoding:`utf8`});return{status:n.status,stdout:n.stdout??``,stderr:n.stderr??``,error:n.error}}function xa(e){let t=e.replaceAll(`\\`,`/`).toLowerCase();return t.includes(`/_npx/`)||t.includes(`/.npm/_npx/`)||t.includes(`/.cache/pnpm/dlx/`)}function Sa(e){if(!e||!x(e))return;let t=Dn(e);return xa(t)?void 0:t}function Ca(e={}){let t=Sa(e.cliPath??process.argv[1]);if(t)return{command:e.nodePath??process.execPath,args:[t,`mcp`,`serve`]};let n=`seo@${e.version??pn}`;return(e.platform??process.platform)===`win32`?{command:`cmd`,args:[`/c`,`npx`,`-y`,n,`mcp`,`serve`]}:{command:`npx`,args:[`-y`,n,`mcp`,`serve`]}}function wa(e=!1,t=Ca()){let n=Ve(),r={command:t.command,args:t.args,env:{SEO_CONFIG_DIR:n.configDir,SEO_MCP_CONFIGURED_BY:`seo`}};return e&&(r.type=`stdio`),r}function Ta(e){return e.includes(`SEO_MCP_CONFIGURED_BY`)||/args:\s+-y\s+(?:seo(?:@\S+)?|@seo\/cli)\s+mcp\s+serve\b/.test(e)}function Ea(e,t,n){let r=sa(e.executable),i=n.runCommand(r,[`mcp`,`get`,`seo`]);if(i.error?.code===`ENOENT`)throw Error("Cannot install SEO MCP for Codex: the `codex` command is not available on PATH. Install Codex CLI or choose another MCP client.");let a=i.status===0;if(a&&!Ta(i.stdout))throw Error(`Cannot ${t} SEO MCP: ${e.path} already has an unmanaged mcp_servers.seo entry.`);if(t===`install`&&a&&!n.reinstall||t===`uninstall`&&!a)return{client:e.client,path:e.path,changed:!1};if(t===`install`&&a){let e=n.runCommand(r,[`mcp`,`remove`,`seo`]);if(e.error||e.status!==0){let t=e.error?.message??e.stderr.trim()??`unknown error`;throw Error(`Cannot reinstall SEO MCP for Codex: ${t}`)}}let o=Ve(),s=t===`install`?[`mcp`,`add`,`seo`,`--env`,`SEO_CONFIG_DIR=${o.configDir}`,`--env`,`SEO_MCP_CONFIGURED_BY=seo`,`--`,n.serverCommand.command,...n.serverCommand.args]:[`mcp`,`remove`,`seo`],c=n.runCommand(r,s);if(c.error||c.status!==0){let e=c.error?.message??c.stderr.trim()??`unknown error`;throw Error(`Cannot ${t} SEO MCP for Codex: ${e}`)}return{client:e.client,path:e.path,changed:!0}}function Da(e,t={}){let n={runCommand:t.runCommand??ba,reinstall:t.reinstall??!1,serverCommand:t.serverCommand??Ca()};if(e.kind===`native`)return Ea(e,`install`,n);let{source:r,config:i}=ha(e),a=i.mcpServers?.seo,o=wa(e.includeType,n.serverCommand);if(Un(a,o)&&!n.reinstall)return{client:e.client,path:e.path,changed:!1};if(a!==void 0&&!va(a))throw Error(`Cannot install SEO MCP: ${e.path} already has an unmanaged mcpServers.seo entry.`);return ya({target:e,source:r,value:o}),{client:e.client,path:e.path,changed:!0}}function Oa(e,t={}){if(e.kind===`native`)return Ea(e,`uninstall`,{runCommand:t.runCommand??ba,reinstall:!1,serverCommand:Ca()});if(!x(e.path))return{client:e.client,path:e.path,changed:!1};let{source:n,config:r}=ha(e),i=r.mcpServers;if(i?.seo===void 0)return{client:e.client,path:e.path,changed:!1};if(!va(i.seo))throw Error(`Cannot uninstall SEO MCP: ${e.path} has an unmanaged mcpServers.seo entry.`);return ya({target:e,source:n,value:void 0}),{client:e.client,path:e.path,changed:!0}}function ka(e={}){let t=Vn(`npx`,[`-y`,`skills`,`add`,`iannuttall/seo`],{stdio:e.quiet?`ignore`:`inherit`});return t.error?{status:`failed`,error:t.error.message}:t.status===0?{status:`installed`}:{status:`failed`,error:`npx skills add exited with status ${t.status??`unknown`}.`}}function Aa(e){let t=e.canSkip?[{value:`skip`,label:`Skip for now`}]:[];return e.sharedConfigured||e.byoConfigured?[{value:`login`,label:`Connect Google`,hint:`Opens your browser for read-only Search Console and Google Analytics access`},...t]:[{value:`setup`,label:`Set up Google login for local development`,hint:`This source checkout does not include the public app credentials`},...t]}async function ja(e){let t=[],n=!0,r=0;async function i(){for(;r<e.length;){let i=e[r];if(r+=1,i)try{let e=await h(i.property);t.push(...e.filter(e=>e.webStreamData).map(e=>({account:i.account,property:i.property,propertyName:i.label,stream:e})))}catch{n=!1}}}return await Promise.all(Array.from({length:Math.min(e.length,4)},()=>i())),{candidates:t,complete:n}}async function Ma(e){let t=await Dt();if(t.activeMode===`service-account`)return`service-account`;if(t.tokens)return`already-connected`;if(e[`skip-auth`])return`skipped`;if(!R({json:e.json===!0}))throw new b(`AUTH_REQUIRED`,"Not logged in. Run `seo auth login`, or pass --skip-auth to save a project profile without connecting Google.");let n=H(await dr({message:`Connect Google now?`,options:Aa({sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured,canSkip:typeof e.site==`string`&&e.site.length>0})}));return n===`skip`?`skipped`:(n===`setup`&&yn({clientId:H(await fr({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),clientSecret:H(await ur({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}))}),T(`Connected as ${(await r()).account_email}. seo has read-only access and cannot change your site.`,`Google connected`),`connected`)}async function Na(e){if(e.property)return{propertyId:e.property,selection:`explicit`,reason:`Set with --google-analytics-property.`};if(!(e.interactive??R()))return;let t=(await Fe().catch(()=>[])).flatMap(e=>e.propertySummaries.map(t=>({property:l(t.property),label:t.displayName??t.property,account:e.displayName??e.account})));if(!t.length)return;let{candidates:n,complete:r}=await ja(t),i=r?Lr(e.site,n):[],a=new Map;for(let e of i)a.set(e.property,e);let o=[...a.values()];if(o.length===1){let t=o[0];return t?{propertyId:t.property,selection:`matched`,reason:Rr(t,e.site)}:void 0}let s=o.length?o.map(e=>({property:e.property,label:e.propertyName,account:e.account,match:e})):t,c=H(await dr({message:o.length?`Several Google Analytics properties match this site. Which property should seo use?`:r?`No Google Analytics web stream clearly matches this site. Attach a property?`:`Some Google Analytics web streams could not be read. Attach a property?`,options:[{value:``,label:`Skip Google Analytics for now`},...s.map(t=>({value:t,label:`${t.label} (${t.property})`,hint:t.match?Rr(t.match,e.site):t.account}))]}));if(c)return{propertyId:c.property,selection:`manual`,reason:c.match?Rr(c.match,e.site):r?`Selected ${c.label} during setup. Its web stream did not clearly match ${e.site}.`:`Selected ${c.label} during setup. seo could not read every Google Analytics web stream, so it did not guess a match.`}}async function Pa(e){return e[`skip-skill`]||!R({json:e.json===!0})?{status:`skipped`}:H(await ir({message:`Install the SEO skill so coding agents know how to run reports?`,initialValue:!0}))?ka():{status:`declined`}}async function Fa(e){if(e[`skip-mcp`]||!R({json:e.json===!0}))return[];let t=la();if(t.length===0||!H(await ir({message:`Install seo as an MCP server too?`,initialValue:!0})))return[];let n=H(await cr({message:`Which MCP clients?`,options:t.map(e=>({value:e.client,label:e.label,hint:e.path})),initialValues:t.map(e=>e.client)}));return t.filter(e=>n.includes(e.client)).map(e=>{try{return Da(e)}catch(t){return{client:e.client,path:e.path,changed:!1,error:t instanceof Error?t.message:String(t)}}})}function Ia(e){return e.status===`installed`?`installed`:e.status===`failed`?`install failed`:`not installed`}function La(e){return/^[A-Za-z0-9_./:@-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function Ra(){process.stdout.write(`
142
+ `),xi({title:`Help other people find SEO Skill`,body:`If SEO Skill saved you time, a GitHub star helps other people find it.`,command:`https://github.com/iannuttall/seo`})}function za(e){let t=e.filter(e=>e.error).length,n=e.length-t;return e.length===0?`not installed`:t===0?`${n} installed`:n===0?`${t} skipped`:`${n} installed, ${t} skipped`}function Ba(e){let t=e.filter(e=>!!e.error);if(t.length!==0)return t.map(e=>`${e.client}: ${e.error}`).join(`
143
+ `)}function Va(e,t,n){if(n)return;let r=ie().filter(t=>t.siteUrl===e);return r.length===1?r[0]:r.find(e=>e.isDefault)??r.find(e=>e.name.toLocaleLowerCase()===t.toLocaleLowerCase())}async function Ha(e){let t=P(e);if(t||ar(process.argv[2]===`start`?`seo start`:`seo setup`),e[`dry-run`]){let e=[`seo auth login`,`seo start`,`seo report --project acme`,`seo refresh-priorities --project acme --verify-content`,`seo technical-watch --project acme`];t?z({dryRun:!0,next:e}):(T(e.join(`
144
+ `),`This setup will guide you through`),lr(`Dry run complete.`));return}o();let n={site:D(e.site),options:{json:t,refresh:k(e.refresh)}},r=t?await Mi(n):void 0,i=await Ma(e),a=r??await Mi(n),s=ta(a);if(R({json:t})&&T(`A project profile remembers the site and report defaults so future commands stay short.`,`Project profile`),!(k(e[`skip-profile`])!==!0&&(!R({json:t})||H(await ir({message:`Save this site as a project profile?`,initialValue:!0}))))){let n=await Fa(e),r=await Pa(e),o=`--site ${La(a)}`,s=[`seo report ${o}`,`seo refresh-priorities ${o} --verify-content`,`seo technical-watch ${o}`],c={site:a,auth:i,mcp:n,skill:r,next:s};if(t){z(c);return}B([[`Project profile`,`not saved`],[`GSC property`,a],[`Auth`,i],[`MCP`,za(n)],[`SEO skill`,Ia(r)]]);let l=Ba(n);l&&T(l,`MCP setup skipped`),r.error&&T(r.error,`SEO skill install failed`),T(s.join(`
145
+ `),`Try next`),lr(`Setup complete.`),Ra();return}let c=D(e.name)??(R({json:t})?H(await fr({message:`Project name`,placeholder:s,defaultValue:s})):s),l=D(e.id),u=l??Va(a,c,l)?.id??na(c),d=ea(a)??``,f=D(e.url)??(R({json:t})?H(await fr({message:`Website URL to crawl`,placeholder:d||`https://example.com`,defaultValue:d})):d||void 0),p=N(e.urls).length>0?N(e.urls):[],m=await Na({property:D(e[`google-analytics-property`]),site:a,interactive:R({json:t})}),h=m?.propertyId,ee=xt({id:u,name:c,siteUrl:a}),g=N(e.brand).length>0?N(e.brand):ee,te=A(e[`report-day`])??1,ne=A(e.weekday)??1,_=k(e.default)??!0,v=de({id:u,name:c,siteUrl:a,startUrl:f,watchUrls:p,brandTerms:g,analytics:h?{google:{propertyId:h}}:void 0,reportDay:te,technicalWeekday:ne,isDefault:_}),y=await Fa(e),b=await Pa(e),re=[`seo report --project ${v.id}`,`seo refresh-priorities --project ${v.id} --verify-content`,`seo technical-watch --project ${v.id}`],ie={client:v,site:a,auth:i,googleAnalytics:m,mcp:y,skill:b,next:re};if(t){z(ie);return}B([[`Project profile`,`${v.name} (${v.id})`],[`GSC property`,v.siteUrl],[`Crawl URL`,v.startUrl??`not set`],[`Watch URLs`,String(v.watchUrls.length)],[`Brand terms`,v.brandTerms.join(`, `)||`not set`],[`Google Analytics property`,v.analytics.google?.propertyId??`not connected (optional)`],...m?[[`Google Analytics selection`,m.reason]]:[],[`Auth`,i],[`MCP`,za(y)],[`SEO skill`,Ia(b)]]);let ae=Ba(y);ae&&T(ae,`MCP setup skipped`),b.error&&T(b.error,`SEO skill install failed`),T(re.join(`
146
+ `),`Try next`),lr(`Setup complete.`),Ra()}const Ua=w({meta:{name:`setup`,description:`Guided setup for auth, one project profile, MCP, and next commands`},args:{id:{type:`string`,description:`Short stable project id.`},name:{type:`string`,description:`Human project name.`},site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},url:{type:`string`,description:`Default technical crawl start URL.`},urls:{type:`string`,description:`Comma-separated URLs to watch with URL Inspection.`},"google-analytics-property":{type:`string`,description:`Optional Google Analytics property ID.`},brand:{type:`string`,description:`Comma-separated branded query terms to exclude by default.`},"report-day":{type:`string`,description:`Preferred monthly report day. Defaults to 1.`},weekday:{type:`string`,description:`Preferred technical-watch weekday. Defaults to Monday.`},default:{type:`boolean`,description:`Make this the default project.`},"skip-profile":{type:`boolean`,default:!1,description:`Do not save a project profile during setup.`},"skip-auth":{type:`boolean`,default:!1,description:`Skip Google sign-in during setup.`},"skip-mcp":{type:`boolean`,default:!1,description:`Skip MCP install prompts.`},"skip-skill":{type:`boolean`,default:!1,description:`Skip the SEO skill install prompt.`},refresh:{type:`boolean`,default:!1,description:`Refresh GSC property discovery.`},"dry-run":{type:`boolean`,default:!1,description:`Show what setup does without changing files.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>Ha(e)}),Wa=w({...Ua,meta:{name:`start`,description:`Start here: connect Google, save a profile, and get the first report commands`}}),Ga=w({...Ua,meta:{name:`setup`,description:`Guided setup for one saved project profile`}}),Ka=w({meta:{name:`brand`,description:`Detect and manage project brand query terms`},subCommands:{detect:w({meta:{name:`detect`,description:`Suggest branded query terms from GSC navigational queries`},args:{client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name. Defaults to default.`},site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},days:{type:`string`,description:`Detection window length in days. Defaults to 28.`},limit:{type:`string`,description:`Maximum candidate terms. Defaults to 10.`},"min-impressions":{type:`string`,description:`Minimum query impressions. Defaults to 10.`},save:{type:`boolean`,default:!1,description:`Save suggested terms to the selected project.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass local GSC cache.`}},run:async({args:e})=>{let t=P(e),n=Ce(O(e)),r=await vt({site:await Mi({site:D(e.site)??n?.siteUrl,options:{json:t,refresh:k(e.refresh)}}),id:n?.id,name:n?.name,days:A(e.days),limit:A(e.limit),minImpressions:A(e[`min-impressions`]),refresh:k(e.refresh)}),i=k(e.save)&&n?de({id:n.id,name:n.name,siteUrl:n.siteUrl,startUrl:n.startUrl,watchUrls:n.watchUrls,analytics:n.analytics,brandTerms:r.suggestedTerms,reportDay:n.reportDay,technicalWeekday:n.technicalWeekday,isDefault:n.isDefault}):void 0;if(k(e.save)&&!n)throw Error(`Pass --project to save detected brand terms.`);if(t){z({...r,saved:i});return}B([[`Property`,r.site],[`Derived terms`,r.derivedTerms.join(`, `)],[`Suggested terms`,r.suggestedTerms.join(`, `)],[`Saved`,i?i.id:`no`]]),V([`Term`,`Score`,`Evidence`],r.candidates.map(e=>[e.term,e.score,e.evidence.map(e=>`${e.query} (${Math.round(e.clicks)} clicks)`).join(`, `)]))}})}});function qa(e){Ti(e.map(e=>({title:`${e.name}${e.isDefault?` (default)`:``}`,description:e.siteUrl,meta:[e.id,e.startUrl?`crawl ${e.startUrl}`:``,e.watchUrls.length?`${e.watchUrls.length} watched URL${e.watchUrls.length===1?``:`s`}`:``,e.brandTerms.length?`${e.brandTerms.length} brand term${e.brandTerms.length===1?``:`s`}`:``]})),{empty:`No saved projects.`})}function Ja(e){B([[`ID`,e.id],[`Name`,e.name],[`GSC property`,e.siteUrl],[`Crawl URL`,e.startUrl??`not set`],[`Watch URLs`,e.watchUrls.join(`, `)||`not set`],[`Brand terms`,e.brandTerms.join(`, `)||`not set`],[`Google Analytics property`,e.analytics.google?.propertyId??`not set`],[`Report day`,e.reportDay?String(e.reportDay):`not set`],[`Technical weekday`,e.technicalWeekday===void 0?`not set`:String(e.technicalWeekday)],[`Default`,e.isDefault?`yes`:`no`]])}const Ya=w({meta:{name:`add`,description:`Create or update a project profile`},args:{id:{type:`string`,description:`Short stable project id, for example acme.`},name:{type:`string`,description:`Human project name.`},site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},url:{type:`string`,description:`Default technical crawl start URL.`},urls:{type:`string`,description:`Comma-separated URLs to watch with URL Inspection.`},"google-analytics-property":{type:`string`,description:`Optional Google Analytics property ID for this project.`},brand:{type:`string`,description:`Comma-separated branded query terms to exclude by default.`},"report-day":{type:`string`,description:`Preferred monthly report day, 1-31.`},weekday:{type:`string`,description:`Preferred technical-watch weekday, 0-7.`},default:{type:`boolean`,description:`Make this the default project.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=de({id:D(e.id),name:D(e.name),siteUrl:await Mi({site:D(e.site),options:{json:t}}),startUrl:D(e.url),watchUrls:N(e.urls),brandTerms:N(e.brand),analytics:D(e[`google-analytics-property`])?{google:{propertyId:D(e[`google-analytics-property`])??``}}:void 0,reportDay:A(e[`report-day`]),technicalWeekday:A(e.weekday),isDefault:k(e.default)});if(t){z(n);return}Ja(n)}}),Xa=w({meta:{name:`default`,description:`Set the default project`},args:{id:{type:`string`,required:!0,description:`Project id or name.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=vn(D(e.id)??``);if(P(e)){z(t);return}process.stdout.write(`Default project set to ${t.id}.\n`)}}),Za=w({meta:{name:`delete`,description:`Delete a project profile`},args:{id:{type:`string`,required:!0,description:`Project id or name.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=D(e.id)??``,n=_e(t);if(P(e)){z({id:t,deleted:n});return}process.stdout.write(`${n?`Deleted`:`Not found`} ${t}.\n`)}}),Qa=w({meta:{name:`client`,description:`Manage saved project profiles`},subCommands:{setup:Ga,brand:Ka,list:w({meta:{name:`list`,description:`List saved project profiles`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=ie();if(P(e)){z({clients:t});return}qa(t)}}),add:Ya,show:w({meta:{name:`show`,description:`Show one project profile`},args:{id:{type:`string`,description:`Project id or name. Defaults to the default project.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Ce(D(e.id));if(!t)throw Error(`Project not found.`);if(P(e)){z(t);return}Ja(t)}}),default:Xa,delete:Za}}),$a=w({...Qa,meta:{name:`projects`,description:`Manage saved project profiles`}}),eo=w({meta:{name:`content`,description:`Optimize page content from real GSC queries`},subCommands:{optimize:w({meta:{name:`optimize`,description:`Build a content optimization report for one URL`},args:{site:{type:`string`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},url:{type:`string`,required:!0},days:{type:`string`,description:`GSC lookback days. Defaults to 28.`},limit:{type:`string`,description:`Maximum GSC queries to inspect. Defaults to 25.`},"min-impressions":{type:`string`,description:`Minimum query impressions. Defaults to 10.`},"include-brand":{type:`boolean`,default:!1,description:`Include branded queries.`},"verify-content":Br(`Fetch the page for content checks. Defaults to true.`,`Skip fetching the page for content checks.`),js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for page extraction.`},refresh:{type:`boolean`,default:!1,description:`Bypass local GSC and HTTP cache.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),r=await ht({site:n.site,url:D(e.url)??``,days:A(e.days),limit:A(e.limit),minImpressions:A(e[`min-impressions`]),brandTerms:n.client?.brandTerms,includeBrand:k(e[`include-brand`]),verifyContent:k(e[`verify-content`])!==!1,js:k(e.js)?!0:`auto`,refresh:k(e.refresh)});if(t){z(r);return}B([[`Property`,r.site],[`URL`,r.url],[`Score`,`${r.summary.score}/100`],[`Primary intent`,r.summary.primaryIntent],[`Primary query`,r.summary.primaryQuery??`none`],[`Queries`,W(r.summary.queries)],[`Opportunities`,W(r.summary.opportunities)],[`Estimated lift`,W(r.summary.estimatedClickLift)],[`Verdict`,r.summary.verdict]]),J(`Top actions`,r.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),r.brief.sections.length&&(process.stdout.write(`
48
147
  Suggested sections
49
148
  `),q([`Heading`,`Queries`],r.brief.sections.map(e=>[K(e.heading,48),K(e.queries.join(`, `),80)]))),r.intentMix.length&&(process.stdout.write(`
50
149
  Intent mix
51
- `),q([`Intent`,`Queries`,`Impressions`,`Clicks`],r.intentMix.map(e=>[e.intent,W(e.queries),W(e.impressions),W(e.clicks)]))),Y(`Caveats`,r.caveats)}})}}),ba={high:3,medium:2,low:1},xa=C({meta:{name:`crawl`,description:`Run a fast sitemap health pass or a full technical crawl`},args:{crawlUrl:{type:`positional`,required:!1,description:`Site start URL. Optional with --sitemap-url.`},url:{type:`string`,description:`Start URL to crawl. Optional when --project has a saved crawl URL.`},site:{type:`string`,description:`GSC property URL for joining page metrics.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},"google-analytics-property":{type:`string`,description:`Google Analytics property ID for landing-page sessions. Defaults from --project when saved.`},mode:{type:`string`,description:`Crawl mode: site, page, list, or sitemap. Start with sitemap --health for large sites.`},health:{type:`boolean`,default:!1,description:`Run the uncached sitemap status and redirect pass before a full audit. No page-body analysis.`},"sitemap-url":{type:`string`,description:`Explicit sitemap URL. Selects sitemap mode when --mode is omitted.`},urls:{type:`string`,description:`Comma-separated URLs for list mode.`},"urls-file":{type:`string`,description:`File with one URL per line for list mode.`},"max-pages":{type:`string`,description:`Maximum pages to crawl, up to 10,000. Defaults to 500.`},"max-depth":{type:`string`,description:`Maximum click depth, up to 64. Defaults to 16.`},concurrency:{type:`string`,description:`Parallel page fetches, up to 16. Defaults to 8, or progressively up to 4 with --health.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache and fetch fresh pages.`},include:{type:`string`,description:`Comma-separated URL patterns to include.`},exclude:{type:`string`,description:`Comma-separated URL patterns to exclude.`},"no-sitemap":{type:`boolean`,default:!1,description:`Do not seed URLs from sitemap.xml.`},"no-robots":{type:`boolean`,default:!1,description:`Do not skip URLs disallowed by robots.txt.`},"no-external":{type:`boolean`,default:!1,description:`Do not check external links. Reserved for full link checks.`},js:{type:`boolean`,default:!1,description:`Legacy alias for --rendering on.`},rendering:{type:`string`,description:`JavaScript rendering mode: auto, on, or off. Defaults to auto.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON. Alias for --format json.`},format:{type:`string`,description:`Output format: pretty, json, csv, html, markdown, or junit. JUnit requires --health.`},output:{type:`string`,description:`Write output to this path instead of stdout.`},csv:{type:`string`,description:`CSV table to render: issues or pages. Defaults to issues.`},save:{type:`boolean`,default:!1,description:`Save the crawl report locally.`},severity:{type:`string`,description:`Only show top fixes at this severity.`},"fail-on":{type:`string`,description:`Exit non-zero when issues exist at this severity or above.`}},run:async({args:e})=>{let t=N(e),n=Ta(e.format,t),r=E(e.output),i=Ea(e.csv),a=Ca(e.severity),o=Ca(e[`fail-on`]),c=D(e),l=await Da(e),u=wa(e),d=E(e[`sitemap-url`]),f=O(e.health),p=Sa(e.mode);if(n===`junit`&&!f)throw Error(`--format junit requires --health.`);if((f||d)&&p&&p!==`sitemap`)throw Error(`--health and --sitemap-url require sitemap mode.`);if(f&&cr(e,`sitemap`))throw Error(`--health cannot be combined with --no-sitemap.`);if((f||d)&&l.length)throw Error(`--health and --sitemap-url cannot be combined with URL list input.`);let m=E(e.site)||c||!u&&!l.length&&!d?await U({client:c,site:E(e.site),options:{json:t}}):void 0,h=u??m?.client?.startUrl??(m?.site?yi(m.site):void 0)??(d?new URL(`/`,d).toString():void 0)??l[0];if(!h)throw Error(`No crawl URL selected. Pass a URL, --url, or use --project with a saved crawl URL.`);let g=await ut({url:h,projectId:m?.client?.id,site:m?.site,mode:p??(f||d?`sitemap`:l.length?`list`:void 0),strategy:f?`health`:`full`,sitemapUrl:d,urls:l,maxPages:k(e[`max-pages`]),maxDepth:k(e[`max-depth`]),concurrency:k(e.concurrency),refresh:O(e.refresh),fetchRate:dr({...e,"fetch-concurrency":e.concurrency}),include:j(e.include),exclude:j(e.exclude),googleAnalyticsPropertyId:E(e[`google-analytics-property`])??m?.client?.analytics.google?.propertyId,useSitemap:!cr(e,`sitemap`),respectRobots:!cr(e,`robots`),checkExternal:!cr(e,`external`),js:sr(e)}),ee=O(e.save)?ne(g):void 0,te=Wt(g,{severity:a}),_=o?g.issues.some(e=>ba[e.severity]>=ba[o]):!1,v=g.status===`failed`,re={...g,topFixes:te,reviewObservations:s(g,{severity:a}),...o?{failOn:o,failedThreshold:_}:{},...ee?{saved:ee}:{}};if(n===`json`){await ka(r,`${JSON.stringify(re,null,2)}\n`),(v||_)&&(process.exitCode=1);return}if(n===`csv`){await ka(r,i===`pages`?qt(g):Re(g)),(v||_)&&(process.exitCode=1);return}if(n===`html`){await ka(r,Ht(g,te)),(v||_)&&(process.exitCode=1);return}if(n===`junit`){await ka(r,Xt(g)),(v||_)&&(process.exitCode=1);return}if(n===`markdown`){await ka(r,Ue(g,te)),(v||_)&&(process.exitCode=1);return}if(r){await ka(r,xe(g,te)),(v||_)&&(process.exitCode=1);return}process.stdout.write(xe(g,te)),(ee||o)&&(process.stdout.write(`
150
+ `),q([`Intent`,`Queries`,`Impressions`,`Clicks`],r.intentMix.map(e=>[e.intent,W(e.queries),W(e.impressions),W(e.clicks)]))),Y(`Caveats`,r.caveats)}})}});var to=class{stream;buffer=``;constructor(e){this.stream=e}async write(e){this.buffer+=e,this.buffer.length>=65536&&await this.flush()}async flush(){if(!this.buffer)return;let e=this.buffer;this.buffer=``,this.stream.write(e)||await new Promise((e,t)=>{let n=()=>{i(),e()},r=e=>{i(),t(e)},i=()=>{this.stream.off(`drain`,n),this.stream.off(`error`,r)};this.stream.once(`drain`,n),this.stream.once(`error`,r)})}};function no(e){return` `.repeat(e)}function ro(e){return e&&typeof e==`object`&&`toJSON`in e&&typeof e.toJSON==`function`?e.toJSON():e}async function io(e,t,n,r,i=!1){let a=ro(t);if(a===null)return await e.write(`null`),!0;if(typeof a==`string`||typeof a==`boolean`)return await e.write(JSON.stringify(a)),!0;if(typeof a==`number`)return await e.write(Number.isFinite(a)?String(a):`null`),!0;if(typeof a==`bigint`&&JSON.stringify(a),a===void 0||typeof a==`function`||typeof a==`symbol`)return i&&await e.write(`null`),i;if(!a||typeof a!=`object`)return!1;if(r.has(a))throw TypeError(`Converting circular structure to JSON`);r.add(a);try{if(Array.isArray(a)){if(a.length===0)return await e.write(`[]`),!0;await e.write(`[
151
+ `);for(let t=0;t<a.length;t+=1)t>0&&await e.write(`,
152
+ `),await e.write(no(n+1)),await io(e,a[t],n+1,r,!0);return await e.write(`\n${no(n)}]`),!0}let t=Object.entries(a).filter(([,e])=>{let t=ro(e);return![`undefined`,`function`,`symbol`].includes(typeof t)});if(t.length===0)return await e.write(`{}`),!0;await e.write(`{
153
+ `);for(let i=0;i<t.length;i+=1){let[a,o]=t[i];i>0&&await e.write(`,
154
+ `),await e.write(`${no(n+1)}${JSON.stringify(a)}: `),await io(e,o,n+1,r)}return await e.write(`\n${no(n)}}`),!0}finally{r.delete(a)}}async function ao(e,t){let n=new to(e);await io(n,t,0,new Set)||await n.write(`undefined`),await n.write(`
155
+ `),await n.flush()}async function oo(e,t){if(!e){await ao(process.stdout,t);return}await Kn(S(e),{recursive:!0});let n=Cn(e);try{await ao(n,t),n.end(),await br(n)}catch(e){throw n.destroy(),e}process.stdout.write(`Wrote ${e}\n`)}const so={high:3,medium:2,low:1},co=w({meta:{name:`crawl`,description:`Run a fast sitemap health pass or a full technical crawl`},args:{crawlUrl:{type:`positional`,required:!1,description:`Site start URL. Optional with --sitemap-url.`},url:{type:`string`,description:`Start URL to crawl. Optional when --project has a saved crawl URL.`},site:{type:`string`,description:`GSC property URL for joining page metrics.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},"google-analytics-property":{type:`string`,description:`Google Analytics property ID for landing-page sessions. Defaults from --project when saved.`},mode:{type:`string`,description:`Crawl mode: site, page, list, or sitemap. Start with sitemap --health for large sites.`},health:{type:`boolean`,default:!1,description:`Run the uncached sitemap status and redirect pass before a full audit. No page-body analysis.`},"sitemap-url":{type:`string`,description:`Explicit sitemap URL. Selects sitemap mode when --mode is omitted.`},urls:{type:`string`,description:`Comma-separated URLs for list mode.`},"urls-file":{type:`string`,description:`File with one URL per line for list mode.`},"max-pages":{type:`string`,description:`Maximum pages to crawl, up to 10,000. Defaults to 500.`},"max-depth":{type:`string`,description:`Maximum click depth, up to 64. Defaults to 16.`},concurrency:{type:`string`,description:`Parallel page fetches, up to 16. Defaults to 8, or progressively up to 4 with --health.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache and fetch fresh pages.`},include:{type:`string`,description:`Comma-separated URL patterns to include.`},exclude:{type:`string`,description:`Comma-separated URL patterns to exclude.`},"no-sitemap":{type:`boolean`,default:!1,description:`Do not seed URLs from sitemap.xml.`},"no-robots":{type:`boolean`,default:!1,description:`Do not skip URLs disallowed by robots.txt.`},"no-external":{type:`boolean`,default:!1,description:`Do not check external links. Reserved for full link checks.`},js:{type:`boolean`,default:!1,description:`Legacy alias for --rendering on.`},rendering:{type:`string`,description:`JavaScript rendering mode: auto, on, or off. Defaults to auto.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON. Alias for --format json.`},format:{type:`string`,description:`Output format: pretty, json, csv, html, markdown, or junit. JUnit requires --health.`},output:{type:`string`,description:`Write output to this path instead of stdout.`},csv:{type:`string`,description:`CSV table to render: issues or pages. Defaults to issues.`},save:{type:`boolean`,default:!1,description:`Save the crawl report locally.`},severity:{type:`string`,description:`Only show top fixes at this severity.`},"fail-on":{type:`string`,description:`Exit non-zero when issues exist at this severity or above.`}},run:async({args:e})=>{let n=P(e),r=po(e.format,n),i=D(e.output),a=mo(e.csv),o=uo(e.severity),c=uo(e[`fail-on`]),l=O(e),u=await ho(e),d=fo(e),f=D(e[`sitemap-url`]),p=k(e.health),m=lo(e.mode);if(r===`junit`&&!p)throw Error(`--format junit requires --health.`);if((p||f)&&m&&m!==`sitemap`)throw Error(`--health and --sitemap-url require sitemap mode.`);if(p&&Hr(e,`sitemap`))throw Error(`--health cannot be combined with --no-sitemap.`);if((p||f)&&u.length)throw Error(`--health and --sitemap-url cannot be combined with URL list input.`);let h=D(e.site)||l||!d&&!u.length&&!f?await U({client:l,site:D(e.site),options:{json:n}}):void 0,ee=d??h?.client?.startUrl??(h?.site?ea(h.site):void 0)??(f?new URL(`/`,f).toString():void 0)??u[0];if(!ee)throw Error(`No crawl URL selected. Pass a URL, --url, or use --project with a saved crawl URL.`);let g=await t({url:ee,projectId:h?.client?.id,site:h?.site,mode:m??(p||f?`sitemap`:u.length?`list`:void 0),strategy:p?`health`:`full`,sitemapUrl:f,urls:u,maxPages:A(e[`max-pages`]),maxDepth:A(e[`max-depth`]),concurrency:A(e.concurrency),refresh:k(e.refresh),fetchRate:Gr({...e,"fetch-concurrency":e.concurrency}),include:M(e.include),exclude:M(e.exclude),googleAnalyticsPropertyId:D(e[`google-analytics-property`])??h?.client?.analytics.google?.propertyId,useSitemap:!Hr(e,`sitemap`),respectRobots:!Hr(e,`robots`),checkExternal:!Hr(e,`external`),js:Vr(e)}),te=k(e.save)?wt(g):void 0,ne=ue(g,{severity:o}),_=c?g.issues.some(e=>so[e.severity]>=so[c]):!1,y=g.status===`failed`,b={...g,topFixes:ne,reviewObservations:v(g,{severity:o}),...c?{failOn:c,failedThreshold:_}:{},...te?{saved:te}:{}};if(r===`json`){await oo(i,b),(y||_)&&(process.exitCode=1);return}if(r===`csv`){await _o(i,a===`pages`?ze(g):bn(g)),(y||_)&&(process.exitCode=1);return}if(r===`html`){await _o(i,s(g,ne)),(y||_)&&(process.exitCode=1);return}if(r===`junit`){await _o(i,He(g)),(y||_)&&(process.exitCode=1);return}if(r===`markdown`){await _o(i,re(g,ne)),(y||_)&&(process.exitCode=1);return}if(i){await _o(i,Ge(g,ne)),(y||_)&&(process.exitCode=1);return}process.stdout.write(Ge(g,ne)),(te||c)&&(process.stdout.write(`
52
156
  Run metadata
53
- `),z([[`Saved report`,ee?.id??`no`],[`Fail threshold`,o??`off`]])),(v||_)&&(process.exitCode=1)}});function Sa(e){let t=E(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function Ca(e){let t=E(e);if(t){if([`low`,`medium`,`high`].includes(t))return t;throw Error(`Severity must be one of: low, medium, high.`)}}function wa(e){let t=E(e.crawlUrl),n=E(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}function Ta(e,t){let n=E(e);if(t&&n&&n!==`json`)throw Error(`Use either --json or --format, not both.`);if(!n)return t?`json`:`pretty`;if([`pretty`,`json`,`csv`,`html`,`markdown`,`junit`].includes(n))return n;throw Error(`Format must be one of: pretty, json, csv, html, markdown, junit.`)}function Ea(e){let t=E(e);if(!t)return`issues`;if([`issues`,`pages`].includes(t))return t;throw Error(`CSV table must be one of: issues, pages.`)}async function Da(e){let t=j(e.urls)??[],n=E(e[`urls-file`]);return n&&t.push(...Oa(await En(n,`utf8`))),[...new Set(t)]}function Oa(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}async function ka(e,t){if(!e){process.stdout.write(t);return}await wn(x(e),{recursive:!0}),await An(e,t),process.stdout.write(`Wrote ${e}\n`)}async function Aa(e,t){let n=D(e),r=E(e.site);if(!(!n&&!r))return(await U({client:n,site:r,options:{json:t}})).site}function ja(e){Gr(e.map(e=>({title:e.id,description:e.site??e.url,meta:[e.status,`${e.totalPages} page${e.totalPages===1?``:`s`}`,`${e.issueCount} issue${e.issueCount===1?``:`s`}`,e.createdAt]})),{empty:`No saved crawl reports.`})}function Ma(e){let t=[[`ID`,e.id],[`URL`,e.config.url],[`Site`,e.site??`-`],[`Status`,e.status],[`Generated`,e.generatedAt],[`Pages`,String(e.summary.totalPages)],[`Discovered`,String(e.summary.discoveredUrls)],[`Queued`,String(e.summary.queuedUrls)],[`Skipped`,String(e.summary.skippedUrls)],[`Failed fetches`,String(e.summary.failedUrls)],[`Observed internal links`,String(e.summary.observedInternalLinks)],[`Indexable`,String(e.summary.indexablePages)],[`Issues`,String(e.issues.length)],[`High`,String(e.summary.highIssues)],[`Medium`,String(e.summary.mediumIssues)],[`Low`,String(e.summary.lowIssues)]];if(e.externalLinkVerification){let n=e.externalLinkVerification;t.push([`External links`,`${n.fetchedUrls} fetched, ${n.failedUrls} failed, ${n.deferredUrls} deferred (${n.dataStatus})`])}z(t),e.issueGroups.length&&(process.stdout.write(`
157
+ `),B([[`Saved report`,te?.id??`no`],[`Fail threshold`,c??`off`]])),(y||_)&&(process.exitCode=1)}});function lo(e){let t=D(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function uo(e){let t=D(e);if(t){if([`low`,`medium`,`high`].includes(t))return t;throw Error(`Severity must be one of: low, medium, high.`)}}function fo(e){let t=D(e.crawlUrl),n=D(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}function po(e,t){let n=D(e);if(t&&n&&n!==`json`)throw Error(`Use either --json or --format, not both.`);if(!n)return t?`json`:`pretty`;if([`pretty`,`json`,`csv`,`html`,`markdown`,`junit`].includes(n))return n;throw Error(`Format must be one of: pretty, json, csv, html, markdown, junit.`)}function mo(e){let t=D(e);if(!t)return`issues`;if([`issues`,`pages`].includes(t))return t;throw Error(`CSV table must be one of: issues, pages.`)}async function ho(e){let t=M(e.urls)??[],n=D(e[`urls-file`]);return n&&t.push(...go(await Jn(n,`utf8`))),[...new Set(t)]}function go(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}async function _o(e,t){if(!e){process.stdout.write(t);return}await Kn(S(e),{recursive:!0}),await er(e,t),process.stdout.write(`Wrote ${e}\n`)}async function vo(e,t){let n=O(e),r=D(e.site);if(!(!n&&!r))return(await U({client:n,site:r,options:{json:t}})).site}function yo(e){Ti(e.map(e=>({title:e.id,description:e.site??e.url,meta:[e.status,`${e.totalPages} page${e.totalPages===1?``:`s`}`,`${e.issueCount} issue${e.issueCount===1?``:`s`}`,e.createdAt]})),{empty:`No saved crawl reports.`})}function bo(e){let t=[[`ID`,e.id],[`URL`,e.config.url],[`Site`,e.site??`-`],[`Status`,e.status],[`Generated`,e.generatedAt],[`Pages`,String(e.summary.totalPages)],[`Discovered`,String(e.summary.discoveredUrls)],[`Queued`,String(e.summary.queuedUrls)],[`Skipped`,String(e.summary.skippedUrls)],[`Failed fetches`,String(e.summary.failedUrls)],[`Observed internal links`,String(e.summary.observedInternalLinks)],[`Indexable`,String(e.summary.indexablePages)],[`Issues`,String(e.issues.length)],[`High`,String(e.summary.highIssues)],[`Medium`,String(e.summary.mediumIssues)],[`Low`,String(e.summary.lowIssues)]];if(e.externalLinkVerification){let n=e.externalLinkVerification;t.push([`External links`,`${n.fetchedUrls} fetched, ${n.failedUrls} failed, ${n.deferredUrls} deferred (${n.dataStatus})`])}B(t),e.issueGroups.length&&(process.stdout.write(`
54
158
  Top issues
55
- `),B([`Severity`,`Rule`,`Count`,`Sample URL`],e.issueGroups.slice(0,10).map(e=>[e.severity,e.ruleId,String(e.count),K(e.sampleUrls[0]??``,64)]))),Y(`Warnings`,e.warnings.slice(0,10)),Y(`Caveats`,e.caveats)}function Na(e){if(z([[`Before`,`${e.before.id} (${e.before.generatedAt})`],[`After`,`${e.after.id} (${e.after.generatedAt})`],[`Comparability`,e.comparability.status],[`Completeness`,e.completeness.status],[`Truncated`,e.completeness.truncated?`yes`:`no`],[`Headline`,e.headline],[`Pages`,`${e.after.summary.totalPages} (${e.summary.pageDelta>=0?`+`:``}${e.summary.pageDelta})`],[`Issues`,`${e.after.summary.highIssues+e.after.summary.mediumIssues+e.after.summary.lowIssues} (${e.summary.issueDelta>=0?`+`:``}${e.summary.issueDelta})`],[`New status errors`,String(e.summary.newStatusErrors)],[`Fixed status errors`,String(e.summary.fixedStatusErrors)],[`Issue groups worse`,String(e.summary.issueGroupsWorse)],[`Issue groups better`,String(e.summary.issueGroupsBetter)],[`Changed pages`,String(e.summary.changedPages)],[`Added pages`,String(e.summary.addedPages)],[`Removed pages`,String(e.summary.removedPages)]]),e.topActions.length){process.stdout.write(`
159
+ `),V([`Severity`,`Rule`,`Count`,`Sample URL`],e.issueGroups.slice(0,10).map(e=>[e.severity,e.ruleId,String(e.count),K(e.sampleUrls[0]??``,64)]))),Y(`Warnings`,e.warnings.slice(0,10)),Y(`Caveats`,e.caveats)}function xo(e){if(B([[`Before`,`${e.before.id} (${e.before.generatedAt})`],[`After`,`${e.after.id} (${e.after.generatedAt})`],[`Comparability`,e.comparability.status],[`Completeness`,e.completeness.status],[`Truncated`,e.completeness.truncated?`yes`:`no`],[`Headline`,e.headline],[`Pages`,`${e.after.summary.totalPages} (${e.summary.pageDelta>=0?`+`:``}${e.summary.pageDelta})`],[`Issues`,`${e.after.summary.highIssues+e.after.summary.mediumIssues+e.after.summary.lowIssues} (${e.summary.issueDelta>=0?`+`:``}${e.summary.issueDelta})`],[`New status errors`,String(e.summary.newStatusErrors)],[`Fixed status errors`,String(e.summary.fixedStatusErrors)],[`Issue groups worse`,String(e.summary.issueGroupsWorse)],[`Issue groups better`,String(e.summary.issueGroupsBetter)],[`Changed pages`,String(e.summary.changedPages)],[`Added pages`,String(e.summary.addedPages)],[`Removed pages`,String(e.summary.removedPages)]]),e.topActions.length){process.stdout.write(`
56
160
  Top actions
57
161
  `);for(let[t,n]of e.topActions.entries())process.stdout.write(`${t+1}. ${n.title}: ${n.action}\n`),process.stdout.write(` ${n.plainEnglish}\n`)}e.pageChanges.length&&(process.stdout.write(`
58
162
  Changed pages
59
- `),B([`Kind`,`Changes`,`URL`],e.pageChanges.slice(0,15).map(e=>[e.kind,e.changes.join(`, `),K(e.url,80)])),e.pageChanges.length>15&&process.stdout.write(`Showing 15 of ${e.pageChanges.length}. Use --json for all changes.\n`)),e.issueChanges.length&&(process.stdout.write(`
163
+ `),V([`Kind`,`Changes`,`URL`],e.pageChanges.slice(0,15).map(e=>[e.kind,e.changes.join(`, `),K(e.url,80)])),e.pageChanges.length>15&&process.stdout.write(`Showing 15 of ${e.pageChanges.length}. Use --json for all changes.\n`)),e.issueChanges.length&&(process.stdout.write(`
60
164
  Issue movement
61
- `),B([`Rule`,`Before`,`After`,`Delta`],e.issueChanges.slice(0,10).map(e=>[e.ruleId,String(e.before),String(e.after),`${e.delta>=0?`+`:``}${e.delta}`]))),Y(`Caveats`,e.caveats)}function Pa(e,t){if(t.value===`latest`)return e.find(e=>e.id!==t.skipId);if(t.skipId){let n=e.findIndex(e=>e.id===t.skipId);return(n>=0?e.slice(n+1):e).find(e=>e.id!==t.skipId)}return e[1]}function Fa(e){if(e.value!==`latest`&&e.value!==`previous`)return p(e.value);let t=Pa(me({site:e.site,limit:20}),{value:e.value,skipId:e.skipId});return t?p(t.id):void 0}const Ia=C({meta:{name:`crawl-reports`,description:`List, show, or delete saved crawl reports`},args:{site:{type:`string`,description:`GSC property URL for filtering reports.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},id:{type:`string`,description:`Saved crawl report id to show.`},latest:{type:`boolean`,default:!1,description:`Show the latest saved crawl report.`},delete:{type:`string`,description:`Delete a saved crawl report by id.`},rerun:{type:`string`,description:`Rerun a saved crawl report by id, or pass latest.`},compare:{type:`string`,description:`Compare a saved report id, latest, or previous.`},against:{type:`string`,description:`Baseline report id. Defaults to previous.`},limit:{type:`string`,description:`Maximum reports to list. Defaults to 20.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=await Aa(e,t),r=E(e.delete),i=E(e.rerun),a=E(e.compare),o=E(e.id);if(r){let e=ce(r);if(t){R({id:r,deleted:e});return}process.stdout.write(e?`Deleted crawl report ${r}.\n`:`No saved crawl report found for ${r}.\n`);return}if(i){let e=i===`latest`?ue(n):p(i);if(!e)throw Error(i===`latest`?`No saved crawl reports found.`:`No saved crawl report found for ${i}.`);let r=await ut({...e.config,projectId:e.projectId,site:e.site,googleAnalyticsPropertyId:e.googleAnalyticsPropertyId}),a=ne(r);if(t){R({...r,rerunOf:e.id,saved:a,topFixes:Wt(r),reviewObservations:s(r)});return}process.stdout.write(`Reran crawl report ${e.id}.\n\n`),Ma(r);return}if(a){let r=Fa({value:a,site:n});if(!r)throw Error(`No saved crawl report found for ${a}.`);let i=E(e.against)??`previous`,o=Fa({value:i,site:r.site??n,skipId:r.id});if(!o)throw Error(`No baseline crawl report found for ${i}. Save at least two reports or pass --against <id>.`);let s=nt({before:o,after:r});if(t){R(s);return}Na(s);return}if(o||O(e.latest)){let e=o?p(o):ue(n);if(!e)throw Error(o?`No saved crawl report found for ${o}.`:`No saved crawl reports found.`);if(t){R(e);return}Ma(e);return}let c=me({site:n,limit:k(e.limit)});if(t){R({reports:c});return}ja(c)}}),La=C({meta:{name:`gsc-query`,description:`Run a raw Search Console Search Analytics query`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},"start-date":{type:`string`,description:`Start date YYYY-MM-DD.`},"end-date":{type:`string`,description:`End date YYYY-MM-DD.`},dimensions:{type:`string`,description:`Comma-separated GSC dimensions, for example query,page.`},type:{type:`string`,description:`Search type. Defaults to web.`},limit:{type:`string`,description:`Maximum rows to request and print.`},body:{type:`string`,description:`Raw Search Analytics JSON body.`},"body-file":{type:`string`,description:`Path to a Search Analytics JSON body file.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh GSC data.`}},run:async({args:e})=>{let t=await pr(e.body,e[`body-file`])??{startDate:E(e[`start-date`]),endDate:E(e[`end-date`]),dimensions:j(e.dimensions)??[`query`,`page`],type:E(e.type)??`web`,rowLimit:k(e.limit),dataState:`final`},n=N(e),r=await vi({client:D(e),site:E(e.site)??E(t.siteUrl)},{json:n,refresh:O(e.refresh)});delete t.siteUrl;let i=await Fe(r,t,{refresh:O(e.refresh)}),a=k(e.limit),o=a?i.rows.slice(0,a):i.rows;if(n){R({site:r,request:t,...i,rows:o,rowsReturned:o.length});return}z([[`Property`,r],[`Rows returned`,String(o.length)],[`Rows fetched`,String(i.rowsFetched)],[`API calls`,String(i.calls)]]),B([`Keys`,`Clicks`,`Impr`,`CTR`,`Pos`],o.slice(0,25).map(e=>[e.keys.join(` | `),Math.round(e.clicks),Math.round(e.impressions),e.ctr.toFixed(3),e.position.toFixed(1)]))}}),Ra=C({meta:{name:`url-inspect`,description:`Inspect a URL with the Search Console URL Inspection API`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},url:{type:`string`,description:`URL to inspect.`},language:{type:`string`,description:`Optional inspection language code.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=await vi({client:D(e),site:E(e.site)},{json:t}),r=E(e.url);if(!r)throw Error(`Pass --url.`);let i=await ge({siteUrl:n,inspectionUrl:r,languageCode:E(e.language)});if(t){R(i);return}let a=i.inspectionResult?.indexStatusResult;z([[`Property`,n],[`URL`,r],[`Verdict`,a?.verdict??`unknown`],[`Coverage`,a?.coverageState??`unknown`],[`Robots`,a?.robotsTxtState??`unknown`],[`Last crawl`,a?.lastCrawlTime??`unknown`],[`Google canonical`,a?.googleCanonical??`unknown`]])}}),za={days:{cli:`days`,arg:{type:`string`,description:`GSC lookback window. Defaults to 28.`}},recentDays:{cli:`recent`,arg:{type:`string`,description:`Recent anomaly window in days. Defaults to 14.`}},range:{cli:`days`,arg:{type:`string`,description:`GSC lookback window. Defaults to 28.`}},limit:{cli:`limit`,arg:{type:`string`,description:`Maximum rows to return.`}},checkLimit:{cli:`check-limit`,arg:{type:`string`,description:`Maximum candidate pages to fetch and check.`}},minImpressions:{cli:`min-impressions`,arg:{type:`string`,description:`Minimum query impressions.`}},includeBrand:{cli:`include-brand`,arg:{type:`boolean`,default:!1,description:`Include branded queries in opportunity reports.`}},verifyContent:{cli:`verify-content`,arg:{type:`boolean`,default:!1,description:`Verify top opportunities against page title, meta, and content.`}},verifyLimit:{cli:`verify-limit`,arg:{type:`string`,description:`Maximum opportunity URLs to verify.`}},js:{cli:`js`,arg:{type:`boolean`,default:!1,description:`Force JavaScript rendering for verified pages.`}},fetchConcurrency:{cli:`fetch-concurrency`,arg:{type:`string`,description:`Maximum concurrent page fetches per host, up to 16. Defaults to 4.`}},fetchIntervalCap:{cli:`fetch-interval-cap`,arg:{type:`string`,description:`Maximum page fetches per interval per host. Defaults to 4.`}},fetchIntervalMs:{cli:`fetch-interval-ms`,arg:{type:`string`,description:`Fetch rate interval in milliseconds. Defaults to 1000.`}},refresh:{cli:`refresh`,arg:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh data.`}}};function X(e,t={}){return Object.fromEntries(e.map(e=>{let n=za[e];return[n.cli,{...n.arg,...t[e]}]}))}function Ba(e){return e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function Va(e){if(e===null)return`n/a`;let t=Math.abs(e)>=10?e.toFixed(0):e.toFixed(1);return`${e>0?`+`:``}${t}%`}const Ha=C({meta:{name:`traffic-anomaly`,description:`Detect unusual recent GSC traffic movement`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`recentDays`,`refresh`],{days:{description:`Baseline window length in days. Defaults to 90.`},recentDays:{description:`Recent anomaly window in days. Defaults to 7.`},refresh:{description:`Bypass local cache and fetch fresh GSC data.`}}),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:t})=>{let n=N(t),r=await e({site:await vi({client:D(t),site:E(t.site)},{json:n,refresh:O(t.refresh)}),days:k(t.days),recentDays:k(t.recent),refresh:O(t.refresh)});if(n){R(r);return}q([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`,`Significant`],r.anomalies.map(e=>[e.metric,e.direction,Ba(e.baselineMean),Ba(e.comparisonMean),Va(e.percentChange),e.zScore??`n/a`,e.significant?`yes`:`no`])),r.coverage&&Y(`Evidence coverage`,[`${r.coverage.observedDays} of ${r.coverage.expectedDays} requested calendar days returned date aggregates.`,...r.coverage.caveats])}}),Ua=C({meta:{name:`update-correlate`,description:`Compare traffic movement with official Google update windows`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`recentDays`,`refresh`],{days:{description:`Baseline window length in days. Defaults to 90.`},recentDays:{description:`Recent anomaly window in days. Defaults to 7.`},refresh:{description:`Bypass local cache and fetch fresh GSC data.`}}),"padding-days":{type:`string`,description:`Days around update windows to count as overlap.`},"known-change":{type:`string`,description:`Manual site-side change to treat as a confounder, for example pruning pages or blocking traffic.`},"ignore-change-log":{type:`boolean`,default:!1,description:`Do not use saved change-log entries as confounders.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=D(e),r=await vi({client:n,site:E(e.site)},{json:t,refresh:O(e.refresh)}),i=await Xe({site:r,days:k(e.days),recentDays:k(e.recent),paddingDays:k(e[`padding-days`]),knownConfounders:E(e[`known-change`])?[E(e[`known-change`])??``]:void 0,includeChangeLog:!O(e[`ignore-change-log`]),refresh:O(e.refresh)});if(t){R(i);return}z([[`Classification`,i.classification.replaceAll(`-`,` `)],[`Causal attribution`,i.attribution.replaceAll(`-`,` `)],[`Causal confidence`,i.confidence],[`Updates matched`,String(i.overlappingUpdates.length)],[`Known confounders`,String(i.confounders.length)],[`Source`,i.source.name]]),process.stdout.write(`\n${i.summary}\n`),Y(`Evidence`,i.evidence),Y(`Report caveats`,i.caveats),Y(`Recommended next checks`,i.actions),q([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`],i.anomalies.map(e=>[e.metric,e.direction,Ba(e.baselineMean),Ba(e.comparisonMean),Va(e.percentChange),e.zScore??`n/a`])),i.overlappingUpdates.length&&(process.stdout.write(`
165
+ `),V([`Rule`,`Before`,`After`,`Delta`],e.issueChanges.slice(0,10).map(e=>[e.ruleId,String(e.before),String(e.after),`${e.delta>=0?`+`:``}${e.delta}`]))),Y(`Caveats`,e.caveats)}function So(e,t){if(t.value===`latest`)return e.find(e=>e.id!==t.skipId);if(t.skipId){let n=e.findIndex(e=>e.id===t.skipId);return(n>=0?e.slice(n+1):e).find(e=>e.id!==t.skipId)}return e[1]}function Co(e){if(e.value!==`latest`&&e.value!==`previous`)return Yt(e.value);let t=So(Rt({site:e.site,limit:20}),{value:e.value,skipId:e.skipId});return t?Yt(t.id):void 0}const wo=w({meta:{name:`crawl-reports`,description:`List, show, or delete saved crawl reports`},args:{site:{type:`string`,description:`GSC property URL for filtering reports.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},id:{type:`string`,description:`Saved crawl report id to show.`},latest:{type:`boolean`,default:!1,description:`Show the latest saved crawl report.`},delete:{type:`string`,description:`Delete a saved crawl report by id.`},rerun:{type:`string`,description:`Rerun a saved crawl report by id, or pass latest.`},compare:{type:`string`,description:`Compare a saved report id, latest, or previous.`},against:{type:`string`,description:`Baseline report id. Defaults to previous.`},limit:{type:`string`,description:`Maximum reports to list. Defaults to 20.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let n=P(e),r=await vo(e,n),i=D(e.delete),a=D(e.rerun),o=D(e.compare),s=D(e.id);if(i){let e=ft(i);if(n){z({id:i,deleted:e});return}process.stdout.write(e?`Deleted crawl report ${i}.\n`:`No saved crawl report found for ${i}.\n`);return}if(a){let e=a===`latest`?en(r):Yt(a);if(!e)throw Error(a===`latest`?`No saved crawl reports found.`:`No saved crawl report found for ${a}.`);let i=await t({...e.config,projectId:e.projectId,site:e.site,googleAnalyticsPropertyId:e.googleAnalyticsPropertyId}),o=wt(i);if(n){z({...i,rerunOf:e.id,saved:o,topFixes:ue(i),reviewObservations:v(i)});return}process.stdout.write(`Reran crawl report ${e.id}.\n\n`),bo(i);return}if(o){let t=Co({value:o,site:r});if(!t)throw Error(`No saved crawl report found for ${o}.`);let i=D(e.against)??`previous`,a=Co({value:i,site:t.site??r,skipId:t.id});if(!a)throw Error(`No baseline crawl report found for ${i}. Save at least two reports or pass --against <id>.`);let s=Ae({before:a,after:t});if(n){z(s);return}xo(s);return}if(s||k(e.latest)){let e=s?Yt(s):en(r);if(!e)throw Error(s?`No saved crawl report found for ${s}.`:`No saved crawl reports found.`);if(n){z(e);return}bo(e);return}let c=Rt({site:r,limit:A(e.limit)});if(n){z({reports:c});return}yo(c)}}),To=w({meta:{name:`gsc-query`,description:`Run a raw Search Console Search Analytics query`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},"start-date":{type:`string`,description:`Start date YYYY-MM-DD.`},"end-date":{type:`string`,description:`End date YYYY-MM-DD.`},dimensions:{type:`string`,description:`Comma-separated GSC dimensions, for example query,page.`},type:{type:`string`,description:`Search type. Defaults to web.`},limit:{type:`string`,description:`Maximum rows to request and print.`},body:{type:`string`,description:`Raw Search Analytics JSON body.`},"body-file":{type:`string`,description:`Path to a Search Analytics JSON body file.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh GSC data.`}},run:async({args:e})=>{let t=await qr(e.body,e[`body-file`])??{startDate:D(e[`start-date`]),endDate:D(e[`end-date`]),dimensions:M(e.dimensions)??[`query`,`page`],type:D(e.type)??`web`,rowLimit:A(e.limit),dataState:`final`},n=P(e),r=await $i({client:O(e),site:D(e.site)??D(t.siteUrl)},{json:n,refresh:k(e.refresh)});delete t.siteUrl;let i=await gn(r,t,{refresh:k(e.refresh)}),a=A(e.limit),o=a?i.rows.slice(0,a):i.rows;if(n){z({site:r,request:t,...i,rows:o,rowsReturned:o.length});return}B([[`Property`,r],[`Rows returned`,String(o.length)],[`Rows fetched`,String(i.rowsFetched)],[`API calls`,String(i.calls)]]),V([`Keys`,`Clicks`,`Impr`,`CTR`,`Pos`],o.slice(0,25).map(e=>[e.keys.join(` | `),Math.round(e.clicks),Math.round(e.impressions),e.ctr.toFixed(3),e.position.toFixed(1)]))}}),Eo=w({meta:{name:`url-inspect`,description:`Inspect a URL with the Search Console URL Inspection API`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},url:{type:`string`,description:`URL to inspect.`},language:{type:`string`,description:`Optional inspection language code.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=await $i({client:O(e),site:D(e.site)},{json:t}),r=D(e.url);if(!r)throw Error(`Pass --url.`);let i=await at({siteUrl:n,inspectionUrl:r,languageCode:D(e.language)});if(t){z(i);return}let a=i.inspectionResult?.indexStatusResult;B([[`Property`,n],[`URL`,r],[`Verdict`,a?.verdict??`unknown`],[`Coverage`,a?.coverageState??`unknown`],[`Robots`,a?.robotsTxtState??`unknown`],[`Last crawl`,a?.lastCrawlTime??`unknown`],[`Google canonical`,a?.googleCanonical??`unknown`]])}}),Do={days:{cli:`days`,arg:{type:`string`,description:`GSC lookback window. Defaults to 28.`}},recentDays:{cli:`recent`,arg:{type:`string`,description:`Recent anomaly window in days. Defaults to 14.`}},range:{cli:`days`,arg:{type:`string`,description:`GSC lookback window. Defaults to 28.`}},limit:{cli:`limit`,arg:{type:`string`,description:`Maximum rows to return.`}},checkLimit:{cli:`check-limit`,arg:{type:`string`,description:`Maximum candidate pages to fetch and check.`}},minImpressions:{cli:`min-impressions`,arg:{type:`string`,description:`Minimum query impressions.`}},includeBrand:{cli:`include-brand`,arg:{type:`boolean`,default:!1,description:`Include branded queries in opportunity reports.`}},verifyContent:{cli:`verify-content`,arg:{type:`boolean`,default:!1,description:`Verify top opportunities against page title, meta, and content.`}},verifyLimit:{cli:`verify-limit`,arg:{type:`string`,description:`Maximum opportunity URLs to verify.`}},js:{cli:`js`,arg:{type:`boolean`,default:!1,description:`Force JavaScript rendering for verified pages.`}},fetchConcurrency:{cli:`fetch-concurrency`,arg:{type:`string`,description:`Maximum concurrent page fetches per host, up to 16. Defaults to 4.`}},fetchIntervalCap:{cli:`fetch-interval-cap`,arg:{type:`string`,description:`Maximum page fetches per interval per host. Defaults to 4.`}},fetchIntervalMs:{cli:`fetch-interval-ms`,arg:{type:`string`,description:`Fetch rate interval in milliseconds. Defaults to 1000.`}},refresh:{cli:`refresh`,arg:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh data.`}}};function X(e,t={}){return Object.fromEntries(e.map(e=>{let n=Do[e];return[n.cli,{...n.arg,...t[e]}]}))}function Oo(e){return e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function ko(e){if(e===null)return`n/a`;let t=Math.abs(e)>=10?e.toFixed(0):e.toFixed(1);return`${e>0?`+`:``}${t}%`}const Ao=w({meta:{name:`traffic-anomaly`,description:`Detect unusual recent GSC traffic movement`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`recentDays`,`refresh`],{days:{description:`Baseline window length in days. Defaults to 90.`},recentDays:{description:`Recent anomaly window in days. Defaults to 7.`},refresh:{description:`Bypass local cache and fetch fresh GSC data.`}}),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=await mn({site:await $i({client:O(e),site:D(e.site)},{json:t,refresh:k(e.refresh)}),days:A(e.days),recentDays:A(e.recent),refresh:k(e.refresh)});if(t){z(n);return}q([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`,`Significant`],n.anomalies.map(e=>[e.metric,e.direction,Oo(e.baselineMean),Oo(e.comparisonMean),ko(e.percentChange),e.zScore??`n/a`,e.significant?`yes`:`no`])),n.coverage&&Y(`Evidence coverage`,[`${n.coverage.observedDays} of ${n.coverage.expectedDays} requested calendar days returned date aggregates.`,...n.coverage.caveats])}}),jo=w({meta:{name:`update-correlate`,description:`Compare traffic movement with official Google update windows`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`recentDays`,`refresh`],{days:{description:`Baseline window length in days. Defaults to 90.`},recentDays:{description:`Recent anomaly window in days. Defaults to 7.`},refresh:{description:`Bypass local cache and fetch fresh GSC data.`}}),"padding-days":{type:`string`,description:`Days around update windows to count as overlap.`},"known-change":{type:`string`,description:`Manual site-side change to treat as a confounder, for example pruning pages or blocking traffic.`},"ignore-change-log":{type:`boolean`,default:!1,description:`Do not use saved change-log entries as confounders.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=O(e),r=await $i({client:n,site:D(e.site)},{json:t,refresh:k(e.refresh)}),i=await Ne({site:r,days:A(e.days),recentDays:A(e.recent),paddingDays:A(e[`padding-days`]),knownConfounders:D(e[`known-change`])?[D(e[`known-change`])??``]:void 0,includeChangeLog:!k(e[`ignore-change-log`]),refresh:k(e.refresh)});if(t){z(i);return}B([[`Classification`,i.classification.replaceAll(`-`,` `)],[`Causal attribution`,i.attribution.replaceAll(`-`,` `)],[`Causal confidence`,i.confidence],[`Updates matched`,String(i.overlappingUpdates.length)],[`Known confounders`,String(i.confounders.length)],[`Source`,i.source.name]]),process.stdout.write(`\n${i.summary}\n`),Y(`Evidence`,i.evidence),Y(`Report caveats`,i.caveats),Y(`Recommended next checks`,i.actions),q([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`],i.anomalies.map(e=>[e.metric,e.direction,Oo(e.baselineMean),Oo(e.comparisonMean),ko(e.percentChange),e.zScore??`n/a`])),i.overlappingUpdates.length&&(process.stdout.write(`
62
166
  Updates
63
- `),B([`Start`,`End`,`Type`,`Name`],i.overlappingUpdates.map(e=>[e.start.slice(0,10),e.end?.slice(0,10)??`open`,e.type,e.name]))),ni(`seo segment-impact ${n?`--project ${JSON.stringify(n)}`:`--site ${JSON.stringify(r)}`} --dimension page`)}});function Wa(e){process.stdout.write(`Entity evidence for ${e.url}\n\n`),z([[`Assessment`,`evidence only`],[`Data`,e.dataStatus],[`Evaluated pages`,`${e.evaluatedPages}/${e.crawlPages}`],[`Report`,e.reportId],[`sameAs profiles`,String(e.entities.sameAs.length)],[`Social profiles`,String(e.entities.socialProfiles.length)],[`Authors`,String(e.entities.authors.length)]]),process.stdout.write(`\n${e.headline}\n`);let t=Object.entries(e.entities.schemaTypes).sort((e,t)=>t[1]-e[1]).slice(0,10);t.length&&(process.stdout.write(`
167
+ `),V([`Start`,`End`,`Type`,`Name`],i.overlappingUpdates.map(e=>[e.start.slice(0,10),e.end?.slice(0,10)??`open`,e.type,e.name]))),Li(`seo segment-impact ${n?`--project ${JSON.stringify(n)}`:`--site ${JSON.stringify(r)}`} --dimension page`)}});function Mo(e){process.stdout.write(`Entity evidence for ${e.url}\n\n`),B([[`Assessment`,`evidence only`],[`Data`,e.dataStatus],[`Evaluated pages`,`${e.evaluatedPages}/${e.crawlPages}`],[`Report`,e.reportId],[`sameAs profiles`,String(e.entities.sameAs.length)],[`Social profiles`,String(e.entities.socialProfiles.length)],[`Authors`,String(e.entities.authors.length)]]),process.stdout.write(`\n${e.headline}\n`);let t=Object.entries(e.entities.schemaTypes).sort((e,t)=>t[1]-e[1]).slice(0,10);t.length&&(process.stdout.write(`
64
168
  Schema types
65
- `),B([`Type`,`Pages`],t.map(([e,t])=>[e,String(t)]))),Y(`sameAs`,e.entities.sameAs.slice(0,10)),Y(`Social profiles`,e.entities.socialProfiles.slice(0,10))}const Ga=C({meta:{name:`entity-readiness`,description:`Check schema, sameAs, social, author, and naming signals from a saved crawl`},args:{"report-id":{type:`string`,description:`Saved crawl report id to analyze.`},site:{type:`string`,description:`GSC property URL for selecting the latest saved crawl.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=ee(await ri(e,{json:t}));if(t){R(n);return}Wa(n)}});function Ka(){return new Date().toISOString().slice(0,10)}function qa(e){let t=E(e)??`page`;if(t!==`site`&&t!==`page`&&t!==`query`&&t!==`group`)throw Error(`Invalid --scope. Use site, page, query, or group.`);return t}const Ja=C({meta:{name:`change-log`,description:`Annotate SEO changes and measure before/after impact`},subCommands:{list:C({meta:{name:`list`,description:`List recorded SEO changes`},args:{site:{type:`string`},limit:{type:`string`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=bt({site:E(e.site),limit:k(e.limit)});if(N(e)){R({changes:t});return}B([`ID`,`Date`,`Site`,`Scope`,`Target`,`Title`],t.map(e=>[e.id,e.changedAt,e.site,e.scope,e.target,e.title]))}}),add:C({meta:{name:`add`,description:`Record an SEO change`},args:{site:{type:`string`},scope:{type:`string`,default:`page`},target:{type:`string`,required:!0},title:{type:`string`,required:!0},description:{type:`string`},date:{type:`string`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=jt({site:await Zr({site:E(e.site),options:{json:t}}),scope:qa(e.scope),target:E(e.target)??``,title:E(e.title)??``,description:E(e.description),changedAt:E(e.date)??Ka()});if(t){R(n);return}z([[`ID`,n.id],[`Date`,n.changedAt],[`Site`,n.site],[`Scope`,n.scope],[`Target`,n.target],[`Title`,n.title]])}}),delete:C({meta:{name:`delete`,description:`Delete a recorded SEO change`},args:{id:{type:`string`,required:!0},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=E(e.id)??``,n=It(t);if(N(e)){R({id:t,deleted:n});return}process.stdout.write(`${n?`Deleted`:`Not found`} ${t}.\n`)}}),measure:C({meta:{name:`measure`,description:`Measure a change with equal finalized before/after windows`},args:{id:{type:`string`},site:{type:`string`},scope:{type:`string`},target:{type:`string`},title:{type:`string`},date:{type:`string`},before:{type:`string`},after:{type:`string`},json:{type:`boolean`,default:!1},refresh:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=E(e.id);if(!n&&(!E(e.site)||!E(e.scope)||!E(e.target)||!E(e.date)))throw Error(`Pass --id, or pass --site, --scope, --target, and --date for an ad hoc measurement.`);let r=await _({id:n,site:n?void 0:await Zr({site:E(e.site),options:{json:t}}),scope:n?void 0:qa(e.scope),target:n?void 0:E(e.target),title:E(e.title),changedAt:n?void 0:E(e.date),beforeDays:A(e.before,`--before`),afterDays:A(e.after,`--after`),refresh:O(e.refresh)});if(t){R(r);return}z([[`Change`,r.change.title],[`Data status`,r.dataStatus],[`Verdict`,r.verdict],[`Confidence`,r.confidence],[`Before`,`${r.before.startDate} to ${r.before.endDate}`],[`After`,`${r.after.startDate} to ${r.after.endDate}`],[`Window`,`${r.window.effectiveDays}/${r.window.requestedDays} finalized days`],[`Note`,r.note]]),B([`Metric`,`Before`,`After`,`Delta`],[[`Clicks`,r.before.metrics?.clicks??`unavailable`,r.after.metrics?.clicks??`unavailable`,r.delta.clicks===null?`unavailable`:r.delta.clickPct===null?`${r.delta.clicks}`:`${r.delta.clicks} (${r.delta.clickPct}%)`],[`Impressions`,r.before.metrics?.impressions??`unavailable`,r.after.metrics?.impressions??`unavailable`,r.delta.impressions===null?`unavailable`:r.delta.impressionPct===null?`${r.delta.impressions}`:`${r.delta.impressions} (${r.delta.impressionPct}%)`],[`CTR`,r.before.metrics?.ctr??`unavailable`,r.after.metrics?.ctr??`unavailable`,r.delta.ctr??`unavailable`],[`Position`,r.before.metrics?.position??`unavailable`,r.after.metrics?.position??`unavailable`,r.delta.position??`unavailable`]]),Y(`Warnings`,r.warnings),Y(`Caveats`,r.caveats)}})}});function Ya(e){let t=E(e)??`page`;if(t!==`page`&&t!==`query`)throw Error(`Invalid --dimension. Use page or query.`);return t}function Xa(e){let t=E(e)??`contains`;if(t!==`equals`&&t!==`contains`&&t!==`regex`)throw Error(`Invalid --match. Use equals, contains, or regex.`);return t}const Za=C({meta:{name:`content-groups`,description:`Create and manage reusable page/query groups`},subCommands:{list:C({meta:{name:`list`,description:`List saved content groups`},args:{site:{type:`string`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=Pe(E(e.site));if(N(e)){R({groups:t});return}B([`ID`,`Site`,`Name`,`Dimension`,`Match`,`Pattern`],t.map(e=>[e.id,e.site,e.name,e.dimension,e.matchType,e.pattern]))}}),add:C({meta:{name:`add`,description:`Create a reusable page or query group`},args:{site:{type:`string`},name:{type:`string`,required:!0},dimension:{type:`string`,default:`page`},match:{type:`string`,default:`contains`},pattern:{type:`string`,required:!0},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=Me({site:await Zr({site:E(e.site),options:{json:t}}),name:E(e.name)??``,dimension:Ya(e.dimension),matchType:Xa(e.match),pattern:E(e.pattern)??``});if(t){R(n);return}z([[`ID`,n.id],[`Site`,n.site],[`Name`,n.name],[`Filter`,`${n.dimension} ${n.matchType} ${n.pattern}`]])}}),delete:C({meta:{name:`delete`,description:`Delete a content group`},args:{id:{type:`string`,required:!0},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=E(e.id)??``,n=Ae(t);if(N(e)){R({id:t,deleted:n});return}process.stdout.write(`${n?`Deleted`:`Not found`} ${t}.\n`)}})}});function Qa(){return new Date().toISOString().slice(0,10)}function $a(e){let t=E(e)??`page`;if(t!==`site`&&t!==`page`&&t!==`query`&&t!==`group`)throw Error(`Invalid --scope. Use site, page, query, or group.`);return t}function eo(e){return e?$a(e):void 0}function to(e){return e===null?`n/a`:`${e.toFixed(1)}%`}function no(e){return e==null?`unavailable`:W(e)}function ro(e,t){return e===null?`unavailable`:`${W(e)} (${to(t)})`}function io(e,t=1){return e==null?`unavailable`:e.toFixed(t)}function ao(e){z([[`Test`,e.change.title],[`Data status`,e.dataStatus],[`Verdict`,e.verdict],[`Confidence`,e.confidence],[`Before`,`${e.before.startDate} to ${e.before.endDate}`],[`After`,`${e.after.startDate} to ${e.after.endDate}`],[`Window`,`${e.window.effectiveDays}/${e.window.requestedDays} finalized days`],[`Note`,e.note]]),B([`Metric`,`Before`,`After`,`Delta`],[[`GSC clicks`,no(e.before.metrics?.clicks),no(e.after.metrics?.clicks),ro(e.delta.clicks,e.delta.clickPct)],[`GSC impressions`,no(e.before.metrics?.impressions),no(e.after.metrics?.impressions),ro(e.delta.impressions,e.delta.impressionPct)],[`GSC CTR`,e.before.metrics?`${(e.before.metrics.ctr*100).toFixed(1)}%`:`unavailable`,e.after.metrics?`${(e.after.metrics.ctr*100).toFixed(1)}%`:`unavailable`,e.delta.ctr===null?`unavailable`:`${(e.delta.ctr*100).toFixed(1)} pts`],[`GSC position`,io(e.before.metrics?.position),io(e.after.metrics?.position),io(e.delta.position)]]),e.analytics&&(process.stdout.write(`
169
+ `),V([`Type`,`Pages`],t.map(([e,t])=>[e,String(t)]))),Y(`sameAs`,e.entities.sameAs.slice(0,10)),Y(`Social profiles`,e.entities.socialProfiles.slice(0,10))}const No=w({meta:{name:`entity-readiness`,description:`Check schema, sameAs, social, author, and naming signals from a saved crawl`},args:{"report-id":{type:`string`,description:`Saved crawl report id to analyze.`},site:{type:`string`,description:`GSC property URL for selecting the latest saved crawl.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=rn(await Ri(e,{json:t}));if(t){z(n);return}Mo(n)}});function Po(){return new Date().toISOString().slice(0,10)}function Fo(e){let t=D(e)??`page`;if(t!==`site`&&t!==`page`&&t!==`query`&&t!==`group`)throw Error(`Invalid --scope. Use site, page, query, or group.`);return t}const Io=w({meta:{name:`change-log`,description:`Annotate SEO changes and measure before/after impact`},subCommands:{list:w({meta:{name:`list`,description:`List recorded SEO changes`},args:{site:{type:`string`},limit:{type:`string`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=dn({site:D(e.site),limit:A(e.limit)});if(P(e)){z({changes:t});return}V([`ID`,`Date`,`Site`,`Scope`,`Target`,`Title`],t.map(e=>[e.id,e.changedAt,e.site,e.scope,e.target,e.title]))}}),add:w({meta:{name:`add`,description:`Record an SEO change`},args:{site:{type:`string`},scope:{type:`string`,default:`page`},target:{type:`string`,required:!0},title:{type:`string`,required:!0},description:{type:`string`},date:{type:`string`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=Ie({site:await Mi({site:D(e.site),options:{json:t}}),scope:Fo(e.scope),target:D(e.target)??``,title:D(e.title)??``,description:D(e.description),changedAt:D(e.date)??Po()});if(t){z(n);return}B([[`ID`,n.id],[`Date`,n.changedAt],[`Site`,n.site],[`Scope`,n.scope],[`Target`,n.target],[`Title`,n.title]])}}),delete:w({meta:{name:`delete`,description:`Delete a recorded SEO change`},args:{id:{type:`string`,required:!0},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=D(e.id)??``,n=u(t);if(P(e)){z({id:t,deleted:n});return}process.stdout.write(`${n?`Deleted`:`Not found`} ${t}.\n`)}}),measure:w({meta:{name:`measure`,description:`Measure a change with equal finalized before/after windows`},args:{id:{type:`string`},site:{type:`string`},scope:{type:`string`},target:{type:`string`},title:{type:`string`},date:{type:`string`},before:{type:`string`},after:{type:`string`},json:{type:`boolean`,default:!1},refresh:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=D(e.id);if(!n&&(!D(e.site)||!D(e.scope)||!D(e.target)||!D(e.date)))throw Error(`Pass --id, or pass --site, --scope, --target, and --date for an ad hoc measurement.`);let r=await yt({id:n,site:n?void 0:await Mi({site:D(e.site),options:{json:t}}),scope:n?void 0:Fo(e.scope),target:n?void 0:D(e.target),title:D(e.title),changedAt:n?void 0:D(e.date),beforeDays:j(e.before,`--before`),afterDays:j(e.after,`--after`),refresh:k(e.refresh)});if(t){z(r);return}B([[`Change`,r.change.title],[`Data status`,r.dataStatus],[`Verdict`,r.verdict],[`Confidence`,r.confidence],[`Before`,`${r.before.startDate} to ${r.before.endDate}`],[`After`,`${r.after.startDate} to ${r.after.endDate}`],[`Window`,`${r.window.effectiveDays}/${r.window.requestedDays} finalized days`],[`Note`,r.note]]),V([`Metric`,`Before`,`After`,`Delta`],[[`Clicks`,r.before.metrics?.clicks??`unavailable`,r.after.metrics?.clicks??`unavailable`,r.delta.clicks===null?`unavailable`:r.delta.clickPct===null?`${r.delta.clicks}`:`${r.delta.clicks} (${r.delta.clickPct}%)`],[`Impressions`,r.before.metrics?.impressions??`unavailable`,r.after.metrics?.impressions??`unavailable`,r.delta.impressions===null?`unavailable`:r.delta.impressionPct===null?`${r.delta.impressions}`:`${r.delta.impressions} (${r.delta.impressionPct}%)`],[`CTR`,r.before.metrics?.ctr??`unavailable`,r.after.metrics?.ctr??`unavailable`,r.delta.ctr??`unavailable`],[`Position`,r.before.metrics?.position??`unavailable`,r.after.metrics?.position??`unavailable`,r.delta.position??`unavailable`]]),Y(`Warnings`,r.warnings),Y(`Caveats`,r.caveats)}})}});function Lo(e){let t=D(e)??`page`;if(t!==`page`&&t!==`query`)throw Error(`Invalid --dimension. Use page or query.`);return t}function Ro(e){let t=D(e)??`contains`;if(t!==`equals`&&t!==`contains`&&t!==`regex`)throw Error(`Invalid --match. Use equals, contains, or regex.`);return t}const zo=w({meta:{name:`content-groups`,description:`Create and manage reusable page/query groups`},subCommands:{list:w({meta:{name:`list`,description:`List saved content groups`},args:{site:{type:`string`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=_n(D(e.site));if(P(e)){z({groups:t});return}V([`ID`,`Site`,`Name`,`Dimension`,`Match`,`Pattern`],t.map(e=>[e.id,e.site,e.name,e.dimension,e.matchType,e.pattern]))}}),add:w({meta:{name:`add`,description:`Create a reusable page or query group`},args:{site:{type:`string`},name:{type:`string`,required:!0},dimension:{type:`string`,default:`page`},match:{type:`string`,default:`contains`},pattern:{type:`string`,required:!0},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=et({site:await Mi({site:D(e.site),options:{json:t}}),name:D(e.name)??``,dimension:Lo(e.dimension),matchType:Ro(e.match),pattern:D(e.pattern)??``});if(t){z(n);return}B([[`ID`,n.id],[`Site`,n.site],[`Name`,n.name],[`Filter`,`${n.dimension} ${n.matchType} ${n.pattern}`]])}}),delete:w({meta:{name:`delete`,description:`Delete a content group`},args:{id:{type:`string`,required:!0},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=D(e.id)??``,n=cn(t);if(P(e)){z({id:t,deleted:n});return}process.stdout.write(`${n?`Deleted`:`Not found`} ${t}.\n`)}})}});function Bo(){return new Date().toISOString().slice(0,10)}function Vo(e){let t=D(e)??`page`;if(t!==`site`&&t!==`page`&&t!==`query`&&t!==`group`)throw Error(`Invalid --scope. Use site, page, query, or group.`);return t}function Ho(e){return e?Vo(e):void 0}function Uo(e){return e===null?`n/a`:`${e.toFixed(1)}%`}function Wo(e){return e==null?`unavailable`:W(e)}function Go(e,t){return e===null?`unavailable`:`${W(e)} (${Uo(t)})`}function Ko(e,t=1){return e==null?`unavailable`:e.toFixed(t)}function qo(e){B([[`Test`,e.change.title],[`Data status`,e.dataStatus],[`Verdict`,e.verdict],[`Confidence`,e.confidence],[`Before`,`${e.before.startDate} to ${e.before.endDate}`],[`After`,`${e.after.startDate} to ${e.after.endDate}`],[`Window`,`${e.window.effectiveDays}/${e.window.requestedDays} finalized days`],[`Note`,e.note]]),V([`Metric`,`Before`,`After`,`Delta`],[[`GSC clicks`,Wo(e.before.metrics?.clicks),Wo(e.after.metrics?.clicks),Go(e.delta.clicks,e.delta.clickPct)],[`GSC impressions`,Wo(e.before.metrics?.impressions),Wo(e.after.metrics?.impressions),Go(e.delta.impressions,e.delta.impressionPct)],[`GSC CTR`,e.before.metrics?`${(e.before.metrics.ctr*100).toFixed(1)}%`:`unavailable`,e.after.metrics?`${(e.after.metrics.ctr*100).toFixed(1)}%`:`unavailable`,e.delta.ctr===null?`unavailable`:`${(e.delta.ctr*100).toFixed(1)} pts`],[`GSC position`,Ko(e.before.metrics?.position),Ko(e.after.metrics?.position),Ko(e.delta.position)]]),e.analytics&&(process.stdout.write(`
66
170
  Google Analytics impact
67
- `),B([`Metric`,`Before`,`After`,`Delta`],[[`Sessions`,W(e.analytics.before.metrics.sessions),W(e.analytics.after.metrics.sessions),`${W(e.analytics.delta.sessions)} (${to(e.analytics.delta.sessionPct)})`],[`Conversions`,W(e.analytics.before.metrics.conversions),W(e.analytics.after.metrics.conversions),`${W(e.analytics.delta.conversions)} (${to(e.analytics.delta.conversionPct)})`],[`Revenue`,e.analytics.before.metrics.totalRevenue.toFixed(2),e.analytics.after.metrics.totalRevenue.toFixed(2),`${e.analytics.delta.totalRevenue.toFixed(2)} (${to(e.analytics.delta.revenuePct)})`]])),e.control&&(process.stdout.write(`
171
+ `),V([`Metric`,`Before`,`After`,`Delta`],[[`Sessions`,W(e.analytics.before.metrics.sessions),W(e.analytics.after.metrics.sessions),`${W(e.analytics.delta.sessions)} (${Uo(e.analytics.delta.sessionPct)})`],[`Conversions`,W(e.analytics.before.metrics.conversions),W(e.analytics.after.metrics.conversions),`${W(e.analytics.delta.conversions)} (${Uo(e.analytics.delta.conversionPct)})`],[`Revenue`,e.analytics.before.metrics.totalRevenue.toFixed(2),e.analytics.after.metrics.totalRevenue.toFixed(2),`${e.analytics.delta.totalRevenue.toFixed(2)} (${Uo(e.analytics.delta.revenuePct)})`]])),e.control&&(process.stdout.write(`
68
172
  Control comparison
69
- `),z([[`Control`,e.control.change.title],[`Adjusted clicks`,e.control.adjusted.clickDelta===null?`n/a`:W(e.control.adjusted.clickDelta)],[`Adjusted click %`,e.control.adjusted.clickPctPoints===null?`n/a`:`${e.control.adjusted.clickPctPoints.toFixed(1)} pts`],[`Note`,e.control.note]])),Y(`Warnings`,e.warnings),Y(`Caveats`,e.caveats)}const oo=C({meta:{name:`tests`,description:`Create and report local SEO tests from Search Console and Google Analytics data`},subCommands:{list:C({meta:{name:`list`,description:`List saved SEO tests`},args:{site:{type:`string`,description:`GSC property URL.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},limit:{type:`string`,description:`Maximum tests to list. Defaults to 20.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=D(e),r=bt({site:(n||E(e.site)?await U({client:n,site:E(e.site),options:{json:t}}):void 0)?.site,limit:k(e.limit)});if(t){R({tests:r});return}B([`ID`,`Date`,`Scope`,`Target`,`Title`],r.map(e=>[e.id,e.changedAt,e.scope,e.target,e.title]))}}),create:C({meta:{name:`create`,description:`Create a local SEO test`},args:{site:{type:`string`,description:`GSC property URL.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},scope:{type:`string`,default:`page`,description:`Change scope: site, page, query, or group.`},target:{type:`string`,required:!0,description:`Changed URL, query, group pattern, or site marker.`},title:{type:`string`,required:!0,description:`Plain-English name for the test.`},description:{type:`string`,description:`Optional note about what changed.`},date:{type:`string`,description:`Change date in YYYY-MM-DD. Defaults to today.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t}}),r=jt({site:n.site,scope:$a(e.scope),target:E(e.target)??``,title:E(e.title)??``,description:E(e.description),changedAt:E(e.date)??Qa()});if(t){R(r);return}z([[`ID`,r.id],[`Date`,r.changedAt],[`Project`,n.client?.name??n.site],[`Scope`,r.scope],[`Target`,r.target],[`Title`,r.title]])}}),report:C({meta:{name:`report`,description:`Report an SEO test with equal finalized before/after windows`},args:{id:{type:`string`,description:`Saved SEO test id.`},site:{type:`string`,description:`GSC property URL.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},scope:{type:`string`,description:`Ad-hoc change scope: site, page, query, or group.`},target:{type:`string`,description:`Ad-hoc changed URL, query, group pattern, or site marker.`},title:{type:`string`,description:`Ad-hoc test title.`},date:{type:`string`,description:`Ad-hoc change date in YYYY-MM-DD.`},property:{type:`string`,description:`Google Analytics property ID.`},"control-scope":{type:`string`,description:`Control scope: site, page, query, or group.`},"control-target":{type:`string`,description:`Control URL, query, group pattern, or site marker.`},"control-title":{type:`string`,description:`Plain-English name for the control group.`},before:{type:`string`,description:`Days before the change date. Defaults to 28.`},after:{type:`string`,description:`Days after the change date. Defaults to 28.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local Search Console and Google Analytics cache.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=E(e.id),r=!n||D(e)||E(e.site)?await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}):void 0,i=await _({id:n,site:n?void 0:r?.site,scope:n?void 0:eo(e.scope),target:n?void 0:E(e.target),title:E(e.title),changedAt:n?void 0:E(e.date),googleAnalyticsPropertyId:E(e.property)??r?.client?.analytics.google?.propertyId,controlScope:eo(e[`control-scope`]),controlTarget:E(e[`control-target`]),controlTitle:E(e[`control-title`]),beforeDays:A(e.before,`--before`),afterDays:A(e.after,`--after`),refresh:O(e.refresh)});if(t){R(i);return}ao(i)}})}});function so(e){if(!e)return;let t=Date.now();return e=>{let n=((Date.now()-t)/1e3).toFixed(1);process.stderr.write(`[seo ${n}s] ${e}\n`)}}const co={site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`}},lo={...X([`includeBrand`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}};function uo(e){return{includeBrand:O(e[`include-brand`]),verifyContent:O(e[`verify-content`]),verifyLimit:k(e[`verify-limit`])??3,js:O(e.js)?!0:void 0,rate:dr(e),refresh:O(e.refresh)}}function fo(e){return{client:D(e),site:E(e.site),refresh:O(e.refresh)}}const{json:po,...mo}=lo,ho=mo,go={client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name. Defaults to the configured default.`},site:{type:`string`,description:`GSC property URL/id when not using a saved project.`}};function _o(e){return{type:`string`,description:`Output folder. Defaults to ./seo-export/<project>-${e}-YYYY-MM-DD.`}}function vo(e){return e.toLowerCase().replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)}function yo(e){let t=new Date().toISOString().slice(0,10),n=vo(e.clientId??e.site);return hn(process.cwd(),`seo-export`,`${n}-${e.report}-${t}`)}async function bo(e,t){await wn(e,{recursive:!0});let n=[];for(let r of t){let t=hn(e,r.filename);await An(t,ft(r.rows,r.headers),`utf8`),n.push(t)}return n}function xo(e,t){process.stdout.write(`Wrote ${at(t.length,`CSV file`)} to ${e}\n`);for(let e of t)process.stdout.write(`- ${e}\n`)}const So=C({meta:{name:`diagnose`,description:`Export diagnosis tables: priorities, anomalies, movement, decay, cannibalisation, striking-distance, and quick wins.`},args:{...go,out:_o(`diagnose`),days:{type:`string`,description:`GSC lookback window. Defaults to 90.`},recent:{type:`string`,description:`Recent anomaly window in days.`},limit:{type:`string`,description:`Maximum rows per movement/opportunity table.`},"include-brand":{type:`boolean`,default:!1,description:`Include branded queries in opportunity reports.`},"verify-content":{type:`boolean`,default:!1,description:`Verify top opportunities against page title, meta, and content.`},"verify-limit":{type:`string`,description:`Maximum opportunity URLs to verify.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for verified pages.`},"fetch-concurrency":{type:`string`,description:`Maximum concurrent page fetches per host. Defaults to 4.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host. Defaults to 4.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds. Defaults to 1000.`},refresh:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh data.`}},run:async({args:e})=>{let t=await U({client:D(e),site:E(e.site)}),n=await he({site:t.site,days:k(e.days),recentDays:k(e.recent),limit:k(e.limit),brandTerms:t.client?.brandTerms,includeBrand:O(e[`include-brand`]),verifyContent:O(e[`verify-content`]),verifyLimit:k(e[`verify-limit`]),js:O(e.js)?!0:`auto`,rate:dr(e),refresh:O(e.refresh),progress:so(!0)}),r=E(e.out)??yo({report:`diagnose`,clientId:t.client?.id,site:t.site});xo(r,await bo(r,Ce(n)))}}),Co=`.seo-okf.json`,wo=`${JSON.stringify({generator:`seo`,format:`okf`,version:1})}\n`;function To(e,t){let n=hn(e,t),r=mn(hn(e),n);if(!r||r.startsWith(`..`)||fn(r))throw new y(`INVALID_INPUT`,`Unsafe OKF file path: ${t}`);return n}async function Eo(e,t){for(let n of t){let t=To(e,n.path);await wn(x(t),{recursive:!0}),await An(t,n.content)}await An(S(e,Co),wo)}async function Do(e){let t=[];async function n(e,r=``){let i=await Dn(e,{withFileTypes:!0});for(let a of i){let i=r?`${r}/${a.name}`:a.name,o=S(e,a.name);a.isDirectory()?await n(o,i):a.isFile()&&a.name.endsWith(`.md`)&&t.push({path:i,content:await En(o,`utf8`)})}}return await n(e),t.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}async function Oo(e){try{let t=await Cn(e);if(t.isSymbolicLink()||!t.isDirectory())throw new y(`INVALID_INPUT`,`OKF output must be a real directory: ${e}`);if(!(await Dn(e)).length)return!0;try{if(await En(S(e,Co),`utf8`)===wo)return!0}catch{}throw new y(`INVALID_INPUT`,`Refusing to replace non-empty unmanaged directory: ${e}`)}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function ko(e,t){if(!vt(t).valid)throw new y(`INVALID_INPUT`,`Generated bundle did not pass seo OKF checks and was not written.`);let n=hn(e),r=x(n);await wn(r,{recursive:!0});let i=await Oo(n),a=await Tn(S(r,`.${dn(n)}-staging-`)),o=S(r,`.${dn(n)}-backup-${_n()}`),s=!1;try{await Eo(a,t);let e=vt(await Do(a));if(!e.valid)throw new y(`INTERNAL_ERROR`,`Staged OKF files failed validation after writing.`);return i&&(await On(n,o),s=!0),await On(a,n),s&&await kn(o,{recursive:!0,force:!0}),e}catch(e){throw await kn(a,{recursive:!0,force:!0}),s&&(await kn(n,{recursive:!0,force:!0}),await On(o,n)),e}}async function Ao(e,t){if(!e){process.stdout.write(t);return}await wn(x(e),{recursive:!0}),await An(e,t),process.stdout.write(`Wrote ${e}\n`)}function jo(e){let t=E(e)??`okf`;if([`okf`,`markdown`,`json`].includes(t))return t;throw Error(`Format must be one of: okf, markdown, json.`)}function Mo(e){return{reportId:e.id,url:e.config.url,generatedAt:e.generatedAt,crawl:{summary:e.summary,caveats:e.caveats,warnings:e.warnings,pages:e.pages.map(e=>({url:e.finalUrl,title:e.title,metaDescription:e.metaDescription,status:e.status,indexable:e.indexable,wordCount:e.wordCount,schemaTypes:e.schemaTypes,sameAs:e.schemaSameAs,internalInlinks:e.internalInlinkCount,contentSample:e.contentSample}))},aiReadiness:De(e),entityReadiness:ee(e),llmsTxt:Qt(e)}}function No(e){let t=Mo(e);return`${[`# Site Knowledge Export`,``,`Source: ${e.config.url}`,`Crawl report: ${e.id}`,`Generated: ${t.generatedAt}`,``,`## Summary`,``,`- Documents: ${e.summary.totalPages}${e.requestEvidenceStatus===`available`?` from ${e.requests.length} URL requests`:e.requestEvidenceStatus===`partial`?` from ${e.requests.length} observed URL requests (request evidence is partial)`:` (request evidence unavailable for this legacy report)`}`,`- Indexable pages: ${e.summary.indexablePages}`,`- Crawl findings: ${e.issues.length} (${e.summary.highIssues} high, ${e.summary.mediumIssues} medium, ${e.summary.lowIssues} low)`,`- AI-search evidence: ${t.aiReadiness.dataStatus} (${t.aiReadiness.assessment})`,`- Entity evidence: ${t.entityReadiness.dataStatus} (${t.entityReadiness.assessment})`,``,`## Top AI Readiness Actions`,``,...t.aiReadiness.topActions.length?t.aiReadiness.topActions.map(e=>`- ${e.title}: ${e.action}`):[`- No AI-search technical actions in this crawl.`],``,`## Entity Signals`,``,`- sameAs profiles: ${t.entityReadiness.entities.sameAs.length}`,`- Social profiles: ${t.entityReadiness.entities.socialProfiles.length}`,`- Authors: ${t.entityReadiness.entities.authors.length}`,``,`## Important Pages`,``,...e.pages.filter(e=>e.indexable&&e.status<400).slice(0,100).map(e=>`- [${e.title??e.finalUrl}](${e.finalUrl}) - ${e.metaDescription??e.contentSample??`No summary available.`}`),``,`# Citations`,``,`- [Crawl start URL](${e.config.url})`,``].join(`
70
- `)}\n`}const Po=C({meta:{name:`knowledge`,description:`Export site knowledge from a saved crawl as OKF, Markdown, or JSON`},args:{"report-id":{type:`string`,description:`Saved crawl report id to export.`},site:{type:`string`,description:`GSC property URL for selecting the latest saved crawl.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},format:{type:`string`,description:`Output format: okf, markdown, or json. Defaults to okf.`},output:{type:`string`,description:`Output directory for OKF, or output file for Markdown/JSON.`},"max-concepts":{type:`string`,description:`Maximum OKF concept files. Defaults to 500.`},json:{type:`boolean`,default:!1,description:`Print command metadata as JSON.`}},run:async({args:e})=>{let t=N(e),n=jo(e.format),r=n===`okf`?Et(A(e[`max-concepts`],`--max-concepts`)):void 0,i=await ri(e,{json:t}),a=E(e.output);if(n===`okf`){let e=Je(i,{maxConcepts:r}),o=a??`./okf`,s=await ko(o,e.files);if(t){R({format:n,output:o,bundle:e,validation:s});return}process.stdout.write(`Wrote OKF bundle to ${o}\n\n`),z([[`Files`,String(e.files.length)],[`Concepts`,String(e.conceptCount)],[`Valid`,s.valid?`yes`:`no`]]);return}if(n===`json`){await Ao(a,`${JSON.stringify(Mo(i),null,2)}\n`);return}await Ao(a,No(i))}}),Fo=C({meta:{name:`monthly`,description:`Export monthly report tables plus the underlying diagnosis detail CSVs.`},args:{...go,out:_o(`monthly`),month:{type:`string`,description:`Report month as YYYY-MM. Defaults to the latest month with final GSC data.`},...X([`limit`],{limit:{description:`Maximum rows per diagnostic section. Defaults to 10.`}}),...ho},run:async({args:e})=>{let t=await U({client:D(e),site:E(e.site),options:{refresh:O(e.refresh)}}),n=await le({site:t.site,month:E(e.month),limit:k(e.limit),brandTerms:t.client?.brandTerms,...uo(e),progress:so(!0)}),r=E(e.out)??yo({report:`monthly`,clientId:t.client?.id,site:t.site});xo(r,await bo(r,d(n)))}}),Io=C({meta:{name:`narrative`,description:`Export report narrative tables plus the underlying diagnosis detail CSVs.`},args:{...go,out:_o(`narrative`),...X([`days`,`recentDays`],{days:{description:`Diagnosis window length in days. Defaults to 90.`}}),"start-date":{type:`string`,description:`Optional report start date as YYYY-MM-DD.`},"end-date":{type:`string`,description:`Optional report end date as YYYY-MM-DD.`},...X([`limit`],{limit:{description:`Maximum rows per diagnostic section. Defaults to 10.`}}),"change-limit":{type:`string`,description:`Maximum saved changes to measure. Defaults to 5.`},...ho},run:async({args:e})=>{let t=await U({client:D(e),site:E(e.site),options:{refresh:O(e.refresh)}}),n=await pe({site:t.site,days:k(e.days),recentDays:k(e.recent),startDate:E(e[`start-date`]),endDate:E(e[`end-date`]),limit:k(e.limit),changeLimit:k(e[`change-limit`]),brandTerms:t.client?.brandTerms,...uo(e),progress:so(!0)}),r=E(e.out)??yo({report:`narrative`,clientId:t.client?.id,site:t.site});xo(r,await bo(r,d(n)))}});function Lo(e){return te({days:A(e.days,`--days`),sitemaps:j(e.sitemap),maxSitemapUrls:A(e[`max-sitemap-urls`],`--max-sitemap-urls`),templateLimit:A(e.limit,`--limit`),minimumTemplateUrls:A(e[`minimum-template-urls`],`--minimum-template-urls`),minimumTemplateShare:A(e[`minimum-template-share`],`--minimum-template-share`),minimumTemplateImpressions:A(e[`minimum-template-impressions`],`--minimum-template-impressions`),crawlSamples:A(e[`crawl-samples`],`--crawl-samples`),inspectSamples:A(e[`inspect-samples`],`--inspect-samples`),brandTerms:j(e[`brand-terms`]),includeBrand:O(e[`include-brand`]),js:O(e.js)?!0:`auto`,refresh:O(e.refresh),rate:fr(e)})}const Ro=C({meta:{name:`pseo`,description:`Export pSEO audit tables: templates, demand patterns, top queries, sample coverage, crawl samples, and inspection samples.`},args:{...go,out:_o(`pseo`),days:{type:`string`,description:`GSC lookback window. Defaults to 28.`},limit:{type:`string`,description:`Maximum pSEO templates to export.`},sitemap:{type:`string`,description:`Comma-separated sitemap URLs. Can be passed once.`},"crawl-samples":{type:`string`,description:`Number of representative URLs to fetch per template. Defaults to 0.`},"inspect-samples":{type:`string`,description:`Number of representative URLs to inspect in GSC per template. Defaults to 0.`},"max-sitemap-urls":{type:`string`,description:`Maximum discovered URLs per sitemap. Defaults to 50000.`},"minimum-template-urls":{type:`string`,description:`Minimum repeated URLs required for a template. Defaults to 3.`},"minimum-template-share":{type:`string`,description:`Minimum share of discovered URLs from 0 to 1. Defaults to 0.`},"minimum-template-impressions":{type:`string`,description:`Minimum retained page impressions for a template. Defaults to 0.`},"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude from query evidence.`},"include-brand":{type:`boolean`,default:!1,description:`Include branded queries in pSEO demand analysis.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for crawled samples.`},"fetch-concurrency":{type:`string`,description:`Maximum concurrent page fetches per host. Defaults to 4.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host. Defaults to 4.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds. Defaults to 1000.`},refresh:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh data.`}},run:async({args:e})=>{let t=Lo(e),n=await U({client:D(e),site:E(e.site)}),r=await ae({site:n.site,...t,brandTerms:t.brandTerms??n.client?.brandTerms,progress:so(!0)}),i=E(e.out)??yo({report:`pseo`,clientId:n.client?.id,site:n.site});xo(i,await bo(i,l(r)))}}),zo=C({meta:{name:`refresh-priorities`,description:`Export the ranked SEO priority queue, score breakdowns, grouped findings, and diagnosis detail CSVs.`},args:{...go,out:_o(`refresh-priorities`),...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum queue items to export. Defaults to 25.`}}),"google-analytics-property":{type:`string`,description:`Google Analytics property ID to use for analytics value. Defaults from the selected project.`},"verify-content":T(`Verify top opportunities against page title, meta, and content. Defaults to true.`,`Skip page content verification.`),"verify-limit":{type:`string`,description:`Maximum opportunity URLs to verify. Defaults to 5.`}},run:async({args:e})=>{let t=await U({client:D(e),site:E(e.site),options:{refresh:O(e.refresh)}}),n=await de({site:t.site,days:k(e.days),recentDays:k(e.recent),limit:k(e.limit),brandTerms:t.client?.brandTerms,includeBrand:O(e[`include-brand`]),googleAnalyticsPropertyId:E(e[`google-analytics-property`])??t.client?.analytics.google?.propertyId,verifyContent:O(e[`verify-content`]),verifyLimit:k(e[`verify-limit`]),refresh:O(e.refresh)}),r=E(e.out)??yo({report:`refresh-priorities`,clientId:t.client?.id,site:t.site});xo(r,await bo(r,fe(n)))}}),Bo=C({meta:{name:`export`,description:`Export full report data to CSV files`},subCommands:{diagnose:So,knowledge:Po,narrative:Io,monthly:Fo,"update-postmortem":C({meta:{name:`update-postmortem`,description:`Export update postmortem attribution, findings, template movement, and segment movers.`},args:{...go,out:_o(`update-postmortem`),...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum winners/losers per segment. Defaults to 20.`}}),"known-change":{type:`string`,description:`Manual site-side change to treat as a confounder, for example pruning pages or blocking traffic.`},"ignore-change-log":{type:`boolean`,default:!1,description:`Do not use saved change-log entries as confounders.`}},run:async({args:e})=>{let t=await U({client:D(e),site:E(e.site),options:{refresh:O(e.refresh)}}),n=await u({site:t.site,days:k(e.days),recentDays:k(e.recent),limit:k(e.limit),brandTerms:t.client?.brandTerms,includeBrand:O(e[`include-brand`]),knownConfounders:E(e[`known-change`])?[E(e[`known-change`])??``]:void 0,includeChangeLog:!O(e[`ignore-change-log`]),refresh:O(e.refresh)}),r=E(e.out)??yo({report:`update-postmortem`,clientId:t.client?.id,site:t.site});xo(r,await bo(r,er(n)))}}),"refresh-priorities":zo,pseo:Ro}}),Vo=C({...la,meta:{name:`init`,description:"Legacy alias for `seo start`."}});async function Ho(e,t){if(!e){process.stdout.write(t);return}await wn(x(e),{recursive:!0}),await An(e,t),process.stdout.write(`Wrote ${e}\n`)}const Uo={"report-id":{type:`string`,description:`Saved crawl report id to use.`},site:{type:`string`,description:`GSC property URL for selecting the latest saved crawl.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},Wo=C({meta:{name:`llms`,description:`Inspect or generate optional llms.txt from saved crawl data`},subCommands:{audit:C({meta:{name:`audit`,description:`Inspect optional llms.txt presence from a saved crawl`},args:Uo,run:async({args:e})=>{let t=N(e),n=Qt(await ri(e,{json:t}));if(t){R(n);return}process.stdout.write(`llms.txt audit for ${n.url}\n\n`),z([[`SEO impact`,n.googleSearchImpact],[`Optional`,n.optional?`yes`:`no`],[`Found`,n.exists?`yes`:`no`],[`URL`,n.llmsTxtUrl],[`Status`,n.status?String(n.status):`-`]]),process.stdout.write(`\n${n.headline}\n`),n.issues.length&&(process.stdout.write(`
173
+ `),B([[`Control`,e.control.change.title],[`Adjusted clicks`,e.control.adjusted.clickDelta===null?`n/a`:W(e.control.adjusted.clickDelta)],[`Adjusted click %`,e.control.adjusted.clickPctPoints===null?`n/a`:`${e.control.adjusted.clickPctPoints.toFixed(1)} pts`],[`Note`,e.control.note]])),Y(`Warnings`,e.warnings),Y(`Caveats`,e.caveats)}const Jo=w({meta:{name:`tests`,description:`Create and report local SEO tests from Search Console and Google Analytics data`},subCommands:{list:w({meta:{name:`list`,description:`List saved SEO tests`},args:{site:{type:`string`,description:`GSC property URL.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},limit:{type:`string`,description:`Maximum tests to list. Defaults to 20.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=O(e),r=dn({site:(n||D(e.site)?await U({client:n,site:D(e.site),options:{json:t}}):void 0)?.site,limit:A(e.limit)});if(t){z({tests:r});return}V([`ID`,`Date`,`Scope`,`Target`,`Title`],r.map(e=>[e.id,e.changedAt,e.scope,e.target,e.title]))}}),create:w({meta:{name:`create`,description:`Create a local SEO test`},args:{site:{type:`string`,description:`GSC property URL.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},scope:{type:`string`,default:`page`,description:`Change scope: site, page, query, or group.`},target:{type:`string`,required:!0,description:`Changed URL, query, group pattern, or site marker.`},title:{type:`string`,required:!0,description:`Plain-English name for the test.`},description:{type:`string`,description:`Optional note about what changed.`},date:{type:`string`,description:`Change date in YYYY-MM-DD. Defaults to today.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t}}),r=Ie({site:n.site,scope:Vo(e.scope),target:D(e.target)??``,title:D(e.title)??``,description:D(e.description),changedAt:D(e.date)??Bo()});if(t){z(r);return}B([[`ID`,r.id],[`Date`,r.changedAt],[`Project`,n.client?.name??n.site],[`Scope`,r.scope],[`Target`,r.target],[`Title`,r.title]])}}),report:w({meta:{name:`report`,description:`Report an SEO test with equal finalized before/after windows`},args:{id:{type:`string`,description:`Saved SEO test id.`},site:{type:`string`,description:`GSC property URL.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},scope:{type:`string`,description:`Ad-hoc change scope: site, page, query, or group.`},target:{type:`string`,description:`Ad-hoc changed URL, query, group pattern, or site marker.`},title:{type:`string`,description:`Ad-hoc test title.`},date:{type:`string`,description:`Ad-hoc change date in YYYY-MM-DD.`},property:{type:`string`,description:`Google Analytics property ID.`},"control-scope":{type:`string`,description:`Control scope: site, page, query, or group.`},"control-target":{type:`string`,description:`Control URL, query, group pattern, or site marker.`},"control-title":{type:`string`,description:`Plain-English name for the control group.`},before:{type:`string`,description:`Days before the change date. Defaults to 28.`},after:{type:`string`,description:`Days after the change date. Defaults to 28.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local Search Console and Google Analytics cache.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=D(e.id),r=!n||O(e)||D(e.site)?await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}):void 0,i=await yt({id:n,site:n?void 0:r?.site,scope:n?void 0:Ho(e.scope),target:n?void 0:D(e.target),title:D(e.title),changedAt:n?void 0:D(e.date),googleAnalyticsPropertyId:D(e.property)??r?.client?.analytics.google?.propertyId,controlScope:Ho(e[`control-scope`]),controlTarget:D(e[`control-target`]),controlTitle:D(e[`control-title`]),beforeDays:j(e.before,`--before`),afterDays:j(e.after,`--after`),refresh:k(e.refresh)});if(t){z(i);return}qo(i)}})}});function Yo(e){if(!e)return;let t=Date.now();return e=>{let n=((Date.now()-t)/1e3).toFixed(1);process.stderr.write(`[seo ${n}s] ${e}\n`)}}const Xo={site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`}},Zo={...X([`includeBrand`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}};function Qo(e){return{includeBrand:k(e[`include-brand`]),verifyContent:k(e[`verify-content`]),verifyLimit:A(e[`verify-limit`])??3,js:k(e.js)?!0:void 0,rate:Gr(e),refresh:k(e.refresh)}}function $o(e){return{client:O(e),site:D(e.site),refresh:k(e.refresh)}}const{json:es,...ts}=Zo,ns=ts,rs={client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name. Defaults to the configured default.`},site:{type:`string`,description:`GSC property URL/id when not using a saved project.`}};function is(e){return{type:`string`,description:`Output folder. Defaults to ./seo-export/<project>-${e}-YYYY-MM-DD.`}}function as(e){return e.toLowerCase().replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)}function os(e){let t=new Date().toISOString().slice(0,10),n=as(e.clientId??e.site);return Ln(process.cwd(),`seo-export`,`${n}-${e.report}-${t}`)}async function ss(e,t){await Kn(e,{recursive:!0});let n=[];for(let r of t){let t=Ln(e,r.filename);await er(t,Ze(r.rows,r.headers),`utf8`),n.push(t)}return n}function cs(e,t){process.stdout.write(`Wrote ${pe(t.length,`CSV file`)} to ${e}\n`);for(let e of t)process.stdout.write(`- ${e}\n`)}const ls=w({meta:{name:`diagnose`,description:`Export diagnosis tables: priorities, anomalies, movement, decay, cannibalisation, striking-distance, and quick wins.`},args:{...rs,out:is(`diagnose`),days:{type:`string`,description:`GSC lookback window. Defaults to 90.`},recent:{type:`string`,description:`Recent anomaly window in days.`},limit:{type:`string`,description:`Maximum rows per movement/opportunity table.`},"include-brand":{type:`boolean`,default:!1,description:`Include branded queries in opportunity reports.`},"verify-content":{type:`boolean`,default:!1,description:`Verify top opportunities against page title, meta, and content.`},"verify-limit":{type:`string`,description:`Maximum opportunity URLs to verify.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for verified pages.`},"fetch-concurrency":{type:`string`,description:`Maximum concurrent page fetches per host. Defaults to 4.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host. Defaults to 4.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds. Defaults to 1000.`},refresh:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh data.`}},run:async({args:e})=>{let t=await U({client:O(e),site:D(e.site)}),n=await ot({site:t.site,days:A(e.days),recentDays:A(e.recent),limit:A(e.limit),brandTerms:t.client?.brandTerms,includeBrand:k(e[`include-brand`]),verifyContent:k(e[`verify-content`]),verifyLimit:A(e[`verify-limit`]),js:k(e.js)?!0:`auto`,rate:Gr(e),refresh:k(e.refresh),progress:Yo(!0)}),r=D(e.out)??os({report:`diagnose`,clientId:t.client?.id,site:t.site});cs(r,await ss(r,qt(n)))}}),us=`.seo-okf.json`,ds=`${JSON.stringify({generator:`seo`,format:`okf`,version:1})}\n`;function fs(e,t){let n=Ln(e,t),r=In(Ln(e),n);if(!r||r.startsWith(`..`)||Pn(r))throw new b(`INVALID_INPUT`,`Unsafe OKF file path: ${t}`);return n}async function ps(e,t){for(let n of t){let t=fs(e,n.path);await Kn(S(t),{recursive:!0}),await er(t,n.content)}await er(C(e,us),ds)}async function ms(e){let t=[];async function n(e,r=``){let i=await Yn(e,{withFileTypes:!0});for(let a of i){let i=r?`${r}/${a.name}`:a.name,o=C(e,a.name);a.isDirectory()?await n(o,i):a.isFile()&&a.name.endsWith(`.md`)&&t.push({path:i,content:await Jn(o,`utf8`)})}}return await n(e),t.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}async function hs(e){try{let t=await Gn(e);if(t.isSymbolicLink()||!t.isDirectory())throw new b(`INVALID_INPUT`,`OKF output must be a real directory: ${e}`);if(!(await Yn(e)).length)return!0;try{if(await Jn(C(e,us),`utf8`)===ds)return!0}catch{}throw new b(`INVALID_INPUT`,`Refusing to replace non-empty unmanaged directory: ${e}`)}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function gs(e,t){if(!oe(t).valid)throw new b(`INVALID_INPUT`,`Generated bundle did not pass seo OKF checks and was not written.`);let n=Ln(e),r=S(n);await Kn(r,{recursive:!0});let i=await hs(n),a=await qn(C(r,`.${Nn(n)}-staging-`)),o=C(r,`.${Nn(n)}-backup-${zn()}`),s=!1;try{await ps(a,t);let e=oe(await ms(a));if(!e.valid)throw new b(`INTERNAL_ERROR`,`Staged OKF files failed validation after writing.`);return i&&(await Xn(n,o),s=!0),await Xn(a,n),s&&await Zn(o,{recursive:!0,force:!0}),e}catch(e){throw await Zn(a,{recursive:!0,force:!0}),s&&(await Zn(n,{recursive:!0,force:!0}),await Xn(o,n)),e}}async function _s(e,t){if(!e){process.stdout.write(t);return}await Kn(S(e),{recursive:!0}),await er(e,t),process.stdout.write(`Wrote ${e}\n`)}function vs(e){let t=D(e)??`okf`;if([`okf`,`markdown`,`json`].includes(t))return t;throw Error(`Format must be one of: okf, markdown, json.`)}function ys(e){return{reportId:e.id,url:e.config.url,generatedAt:e.generatedAt,crawl:{summary:e.summary,caveats:e.caveats,warnings:e.warnings,pages:e.pages.map(e=>({url:e.finalUrl,title:e.title,metaDescription:e.metaDescription,status:e.status,indexable:e.indexable,wordCount:e.wordCount,schemaTypes:e.schemaTypes,sameAs:e.schemaSameAs,internalInlinks:e.internalInlinkCount,contentSample:e.contentSample}))},aiReadiness:Nt(e),entityReadiness:rn(e),llmsTxt:Zt(e)}}function bs(e){let t=ys(e);return`${[`# Site Knowledge Export`,``,`Source: ${e.config.url}`,`Crawl report: ${e.id}`,`Generated: ${t.generatedAt}`,``,`## Summary`,``,`- Documents: ${e.summary.totalPages}${e.requestEvidenceStatus===`available`?` from ${e.requests.length} URL requests`:e.requestEvidenceStatus===`partial`?` from ${e.requests.length} observed URL requests (request evidence is partial)`:` (request evidence unavailable for this legacy report)`}`,`- Indexable pages: ${e.summary.indexablePages}`,`- Crawl findings: ${e.issues.length} (${e.summary.highIssues} high, ${e.summary.mediumIssues} medium, ${e.summary.lowIssues} low)`,`- AI-search evidence: ${t.aiReadiness.dataStatus} (${t.aiReadiness.assessment})`,`- Entity evidence: ${t.entityReadiness.dataStatus} (${t.entityReadiness.assessment})`,``,`## Top AI Readiness Actions`,``,...t.aiReadiness.topActions.length?t.aiReadiness.topActions.map(e=>`- ${e.title}: ${e.action}`):[`- No AI-search technical actions in this crawl.`],``,`## Entity Signals`,``,`- sameAs profiles: ${t.entityReadiness.entities.sameAs.length}`,`- Social profiles: ${t.entityReadiness.entities.socialProfiles.length}`,`- Authors: ${t.entityReadiness.entities.authors.length}`,``,`## Important Pages`,``,...e.pages.filter(e=>e.indexable&&e.status<400).slice(0,100).map(e=>`- [${e.title??e.finalUrl}](${e.finalUrl}) - ${e.metaDescription??e.contentSample??`No summary available.`}`),``,`# Citations`,``,`- [Crawl start URL](${e.config.url})`,``].join(`
174
+ `)}\n`}const xs=w({meta:{name:`knowledge`,description:`Export site knowledge from a saved crawl as OKF, Markdown, or JSON`},args:{"report-id":{type:`string`,description:`Saved crawl report id to export.`},site:{type:`string`,description:`GSC property URL for selecting the latest saved crawl.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},format:{type:`string`,description:`Output format: okf, markdown, or json. Defaults to okf.`},output:{type:`string`,description:`Output directory for OKF, or output file for Markdown/JSON.`},"max-concepts":{type:`string`,description:`Maximum OKF concept files. Defaults to 500.`},json:{type:`boolean`,default:!1,description:`Print command metadata as JSON.`}},run:async({args:e})=>{let t=P(e),n=vs(e.format),r=n===`okf`?ne(j(e[`max-concepts`],`--max-concepts`)):void 0,i=await Ri(e,{json:t}),a=D(e.output);if(n===`okf`){let e=ye(i,{maxConcepts:r}),o=a??`./okf`,s=await gs(o,e.files);if(t){z({format:n,output:o,bundle:e,validation:s});return}process.stdout.write(`Wrote OKF bundle to ${o}\n\n`),B([[`Files`,String(e.files.length)],[`Concepts`,String(e.conceptCount)],[`Valid`,s.valid?`yes`:`no`]]);return}if(n===`json`){await _s(a,`${JSON.stringify(ys(i),null,2)}\n`);return}await _s(a,bs(i))}}),Ss=w({meta:{name:`monthly`,description:`Export monthly report tables plus the underlying diagnosis detail CSVs.`},args:{...rs,out:is(`monthly`),month:{type:`string`,description:`Report month as YYYY-MM. Defaults to the latest month with final GSC data.`},...X([`limit`],{limit:{description:`Maximum rows per diagnostic section. Defaults to 10.`}}),...ns},run:async({args:e})=>{let t=await U({client:O(e),site:D(e.site),options:{refresh:k(e.refresh)}}),n=await tn({site:t.site,month:D(e.month),limit:A(e.limit),brandTerms:t.client?.brandTerms,...Qo(e),progress:Yo(!0)}),r=D(e.out)??os({report:`monthly`,clientId:t.client?.id,site:t.site});cs(r,await ss(r,ce(n)))}}),Cs=w({meta:{name:`narrative`,description:`Export report narrative tables plus the underlying diagnosis detail CSVs.`},args:{...rs,out:is(`narrative`),...X([`days`,`recentDays`],{days:{description:`Diagnosis window length in days. Defaults to 90.`}}),"start-date":{type:`string`,description:`Optional report start date as YYYY-MM-DD.`},"end-date":{type:`string`,description:`Optional report end date as YYYY-MM-DD.`},...X([`limit`],{limit:{description:`Maximum rows per diagnostic section. Defaults to 10.`}}),"change-limit":{type:`string`,description:`Maximum saved changes to measure. Defaults to 5.`},...ns},run:async({args:e})=>{let t=await U({client:O(e),site:D(e.site),options:{refresh:k(e.refresh)}}),n=await zt({site:t.site,days:A(e.days),recentDays:A(e.recent),startDate:D(e[`start-date`]),endDate:D(e[`end-date`]),limit:A(e.limit),changeLimit:A(e[`change-limit`]),brandTerms:t.client?.brandTerms,...Qo(e),progress:Yo(!0)}),r=D(e.out)??os({report:`narrative`,clientId:t.client?.id,site:t.site});cs(r,await ss(r,ce(n)))}});function ws(e){return Tt({days:j(e.days,`--days`),sitemaps:M(e.sitemap),maxSitemapUrls:j(e[`max-sitemap-urls`],`--max-sitemap-urls`),templateLimit:j(e.limit,`--limit`),minimumTemplateUrls:j(e[`minimum-template-urls`],`--minimum-template-urls`),minimumTemplateShare:j(e[`minimum-template-share`],`--minimum-template-share`),minimumTemplateImpressions:j(e[`minimum-template-impressions`],`--minimum-template-impressions`),crawlSamples:j(e[`crawl-samples`],`--crawl-samples`),inspectSamples:j(e[`inspect-samples`],`--inspect-samples`),brandTerms:M(e[`brand-terms`]),includeBrand:k(e[`include-brand`]),js:k(e.js)?!0:`auto`,refresh:k(e.refresh),rate:Kr(e)})}const Ts=w({meta:{name:`pseo`,description:`Export pSEO audit tables: templates, demand patterns, top queries, sample coverage, crawl samples, and inspection samples.`},args:{...rs,out:is(`pseo`),days:{type:`string`,description:`GSC lookback window. Defaults to 28.`},limit:{type:`string`,description:`Maximum pSEO templates to export.`},sitemap:{type:`string`,description:`Comma-separated sitemap URLs. Can be passed once.`},"crawl-samples":{type:`string`,description:`Number of representative URLs to fetch per template. Defaults to 0.`},"inspect-samples":{type:`string`,description:`Number of representative URLs to inspect in GSC per template. Defaults to 0.`},"max-sitemap-urls":{type:`string`,description:`Maximum discovered URLs per sitemap. Defaults to 50000.`},"minimum-template-urls":{type:`string`,description:`Minimum repeated URLs required for a template. Defaults to 3.`},"minimum-template-share":{type:`string`,description:`Minimum share of discovered URLs from 0 to 1. Defaults to 0.`},"minimum-template-impressions":{type:`string`,description:`Minimum retained page impressions for a template. Defaults to 0.`},"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude from query evidence.`},"include-brand":{type:`boolean`,default:!1,description:`Include branded queries in pSEO demand analysis.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for crawled samples.`},"fetch-concurrency":{type:`string`,description:`Maximum concurrent page fetches per host. Defaults to 4.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host. Defaults to 4.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds. Defaults to 1000.`},refresh:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh data.`}},run:async({args:e})=>{let t=ws(e),n=await U({client:O(e),site:D(e.site)}),r=await rt({site:n.site,...t,brandTerms:t.brandTerms??n.client?.brandTerms,progress:Yo(!0)}),i=D(e.out)??os({report:`pseo`,clientId:n.client?.id,site:n.site});cs(i,await ss(i,Ye(r)))}}),Es=w({meta:{name:`refresh-priorities`,description:`Export the ranked SEO priority queue, score breakdowns, grouped findings, and diagnosis detail CSVs.`},args:{...rs,out:is(`refresh-priorities`),...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum queue items to export. Defaults to 25.`}}),"google-analytics-property":{type:`string`,description:`Google Analytics property ID to use for analytics value. Defaults from the selected project.`},"verify-content":Br(`Verify top opportunities against page title, meta, and content. Defaults to true.`,`Skip page content verification.`),"verify-limit":{type:`string`,description:`Maximum opportunity URLs to verify. Defaults to 5.`}},run:async({args:e})=>{let t=await U({client:O(e),site:D(e.site),options:{refresh:k(e.refresh)}}),n=await Ke({site:t.site,days:A(e.days),recentDays:A(e.recent),limit:A(e.limit),brandTerms:t.client?.brandTerms,includeBrand:k(e[`include-brand`]),googleAnalyticsPropertyId:D(e[`google-analytics-property`])??t.client?.analytics.google?.propertyId,verifyContent:k(e[`verify-content`]),verifyLimit:A(e[`verify-limit`]),refresh:k(e.refresh)}),r=D(e.out)??os({report:`refresh-priorities`,clientId:t.client?.id,site:t.site});cs(r,await ss(r,qe(n)))}}),Ds=w({meta:{name:`export`,description:`Export full report data to CSV files`},subCommands:{diagnose:ls,knowledge:xs,narrative:Cs,monthly:Ss,"update-postmortem":w({meta:{name:`update-postmortem`,description:`Export update postmortem attribution, findings, template movement, and segment movers.`},args:{...rs,out:is(`update-postmortem`),...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum winners/losers per segment. Defaults to 20.`}}),"known-change":{type:`string`,description:`Manual site-side change to treat as a confounder, for example pruning pages or blocking traffic.`},"ignore-change-log":{type:`boolean`,default:!1,description:`Do not use saved change-log entries as confounders.`}},run:async({args:e})=>{let t=await U({client:O(e),site:D(e.site),options:{refresh:k(e.refresh)}}),n=await se({site:t.site,days:A(e.days),recentDays:A(e.recent),limit:A(e.limit),brandTerms:t.client?.brandTerms,includeBrand:k(e[`include-brand`]),knownConfounders:D(e[`known-change`])?[D(e[`known-change`])??``]:void 0,includeChangeLog:!k(e[`ignore-change-log`]),refresh:k(e.refresh)}),r=D(e.out)??os({report:`update-postmortem`,clientId:t.client?.id,site:t.site});cs(r,await ss(r,Nr(n)))}}),"refresh-priorities":Es,pseo:Ts}}),Os={project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},site:{type:`string`,description:`Site URL.`}};async function ks(e){let t=D(e.site);if(t)return t;let n=await Ni({project:O(e),options:{json:P(e)}});if(!n)throw new b(`INVALID_INPUT`,`Pass --site or select a saved project.`);return n.siteUrl}async function As(e){let t=D(e.url),n=M(e.urls)??[],r=D(e.file);if(!t&&n.length===0&&!r)throw new b(`INVALID_INPUT`,`Pass --url, comma-separated --urls, or a newline-delimited --file.`);let i=[...t?[t]:[],...n];if(r){let e=await Qn(r).catch(()=>void 0);if(!e)throw new b(`INVALID_INPUT`,`IndexNow URL file not found: ${r}`);if(!e.isFile()||e.size>21e5)throw new b(`INVALID_INPUT`,`IndexNow URL files must be regular files no larger than 2.1 MB.`);i.push(...(await Jn(r,`utf8`)).split(/\r?\n/).map(e=>e.trim()).filter(Boolean))}return i}const js=w({meta:{name:`indexnow`,description:`Set up and submit changed URLs with IndexNow`},subCommands:{setup:w({meta:{name:`setup`,description:`Generate an IndexNow key file for one site`},args:{...Os,output:{type:`string`,description:`Public asset directory for the generated key file.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=D(e.output);if(!t)throw new b(`INVALID_INPUT`,`Pass --output with the public asset directory that deploys at the site root.`);let r=m({site:await ks(e)}),i=Ln(t),a=C(i,`${r.key}.txt`);await Kn(i,{recursive:!0});try{await er(a,`${r.key}\n`,{encoding:`utf8`,flag:`wx`,mode:384})}catch(e){throw e.code===`EEXIST`?new b(`INVALID_INPUT`,`Refusing to overwrite the existing file at ${a}.`):e}let o;try{o=await n(r)}catch(e){throw await $n(a).catch(()=>void 0),e}let s={configured:!0,host:r.host,keyLocation:r.keyLocation,keyFile:a,credentialSource:o,nextStep:`Deploy ${a}, then run seo indexnow verify --site ${new URL(r.keyLocation).origin}`};P(e)?z(s):B([[`Host`,s.host],[`Key file`,s.keyFile],[`Public URL`,s.keyLocation],[`Saved in`,s.credentialSource],[`Next`,s.nextStep]])}}),status:w({meta:{name:`status`,description:`Show saved IndexNow hosts`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await d(),n={configuredSites:t.length,sites:t};P(e)?z(n):V([`Host`,`Key location`,`Created`],t.map(e=>[e.host,e.keyLocation,e.createdAt]))}}),verify:w({meta:{name:`verify`,description:`Check the public IndexNow key file`},args:{...Os,json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await kt({site:await ks(e)}),n={...await Pe({record:t.record}),credentialSource:t.source};P(e)?z(n):B([[`Verified`,n.verified?`yes`:`no`],[`HTTP status`,String(n.status)],[`Key location`,n.keyLocation],[`Credential`,n.credentialSource]]),n.verified||(process.exitCode=4)}}),submit:w({meta:{name:`submit`,description:`Notify IndexNow about changed URLs`},args:{...Os,url:{type:`string`,description:`One changed URL.`},urls:{type:`string`,description:`Comma-separated changed URLs.`},file:{type:`string`,description:`Newline-delimited changed URL file.`},"dry-run":{type:`boolean`,default:!1,description:`Validate without notifying IndexNow.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await kt({site:await ks(e)}),n=await ln({record:t.record,urls:await As(e),dryRun:k(e[`dry-run`])}),r={...n,credentialSource:t.source};if(P(e)){z(r);return}B([[`Host`,n.host],[`Status`,n.status],[`URLs`,String(n.submittedUrls)],[`Dry run`,n.dryRun?`yes`:`no`],[`Key location`,n.keyLocation]]);for(let e of n.caveats)process.stdout.write(`\n${e}\n`)}}),remove:w({meta:{name:`remove`,description:`Remove a saved IndexNow key`},args:{...Os,json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await be(await ks(e)),n={removed:t,note:`The deployed key file was not removed.`};P(e)?z(n):process.stdout.write(`${t?`Saved key removed.`:`No saved key found.`} ${n.note}\n`)}})}}),Ms=w({...Wa,meta:{name:`init`,description:"Legacy alias for `seo start`."}}),Ns=w({meta:{name:`links`,description:`Review bounded referring-link evidence from Bing or a file`},args:{project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},site:{type:`string`,description:`Verified Bing Webmaster site URL.`},file:{type:`string`,description:`Local CSV, JSON, JSONL, or NDJSON link export.`},format:{type:`string`,description:`Import format override: csv, json, or jsonl.`},"row-limit":{type:`string`,description:`Maximum imported or Bing link rows. Defaults to 500 for Bing and 10000 for files.`},"target-limit":{type:`string`,description:`Maximum Bing target pages to inspect. Defaults to 20.`},"detail-pages":{type:`string`,description:`Maximum Bing result pages per target. Defaults to 1.`},limit:{type:`string`,description:`Maximum link rows returned. Defaults to 100.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=D(e.file),r=D(e.format);if(r&&![`csv`,`json`,`jsonl`].includes(r))throw new b(`INVALID_INPUT`,`--format must be csv, json, or jsonl.`);let i=j(e[`row-limit`],`--row-limit`),a;if(n)a=await je({file:n,format:r,rowLimit:i});else{let n=await Ni({project:O(e),options:{json:t}}),r=D(e.site)??me(n);if(!r)throw new b(`INVALID_INPUT`,`Pass --site, connect Bing to a saved project, or import a link file with --file.`);a=await c({site:r,rowLimit:i,targetLimit:j(e[`target-limit`],`--target-limit`),detailPagesPerTarget:j(e[`detail-pages`],`--detail-pages`)})}let o=fn({evidence:a,limit:j(e.limit,`--limit`)});if(t){z(o);return}B([[`Source`,o.provenance.provider],[`Evidence`,o.dataStatus],[`Observed links`,W(o.summary.observedLinks)],[`Referring domains`,W(o.summary.referringDomains)],[`Target pages`,W(o.summary.targetPages)],[`Returned rows`,`${W(o.selection.returnedRows)} of ${W(o.selection.availableRows)}`]]),o.links.length&&q([`Source`,`Target`,`Anchor`],o.links.map(e=>[K(e.sourceUrl,58),K(e.targetUrl,58),K(e.anchorText??``,36)]));for(let e of o.warnings)process.stdout.write(`\nWarning: ${e}\n`);process.stdout.write(`\nNote: ${o.caveats[0]}\n`)}});async function Ps(e,t){if(!e){process.stdout.write(t);return}await Kn(S(e),{recursive:!0}),await er(e,t),process.stdout.write(`Wrote ${e}\n`)}const Fs={"report-id":{type:`string`,description:`Saved crawl report id to use.`},site:{type:`string`,description:`GSC property URL for selecting the latest saved crawl.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},Is=w({meta:{name:`llms`,description:`Inspect or generate optional llms.txt from saved crawl data`},subCommands:{audit:w({meta:{name:`audit`,description:`Inspect optional llms.txt presence from a saved crawl`},args:Fs,run:async({args:e})=>{let t=P(e),n=Zt(await Ri(e,{json:t}));if(t){z(n);return}process.stdout.write(`llms.txt audit for ${n.url}\n\n`),B([[`SEO impact`,n.googleSearchImpact],[`Optional`,n.optional?`yes`:`no`],[`Found`,n.exists?`yes`:`no`],[`URL`,n.llmsTxtUrl],[`Status`,n.status?String(n.status):`-`]]),process.stdout.write(`\n${n.headline}\n`),n.issues.length&&(process.stdout.write(`
71
175
  Issues
72
- `),B([`Severity`,`Issue`,`Action`],n.issues.map(e=>[e.severity,e.title,K(e.action,96)]))),Y(`Recommended pages`,n.recommendedPages.slice(0,10).map(e=>`${e.section}: ${e.url}`))}}),generate:C({meta:{name:`generate`,description:`Generate an llms.txt draft from a saved crawl`},args:{...Uo,output:{type:`string`,description:`Write llms.txt to this path instead of stdout.`},"max-urls":{type:`string`,description:`Maximum URLs to include. Defaults to 250.`},"token-budget":{type:`string`,description:`Approximate token budget. Defaults to 12000.`},exclude:{type:`string`,description:`Comma-separated URL patterns to exclude.`},title:{type:`string`,description:`Override the llms.txt title.`},description:{type:`string`,description:`Override the llms.txt description.`}},run:async({args:e})=>{let t=N(e),n=a(await ri(e,{json:t}),{maxUrls:k(e[`max-urls`]),tokenBudget:k(e[`token-budget`]),exclude:j(e.exclude),title:E(e.title),description:E(e.description)});if(t){R(n);return}await Ho(E(e.output),n.content),E(e.output)&&z([[`URLs`,String(n.includedUrls)],[`Estimated tokens`,String(n.estimatedTokens)]])}})}}),Go=C({meta:{name:`logs`,description:`Manage local log retention`},subCommands:{prune:C({meta:{name:`prune`,description:`Rotate large logs and remove old local logs`},args:{quiet:{type:`boolean`,default:!1,description:`Do not print a result.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Bt();if(N(e)){R(t);return}e.quiet||process.stdout.write(`Rotated ${t.rotated} and removed ${t.removed} log files. ${Jr(t.sizeBytes)} retained.\n`)}})}}),Ko=[{client:`claude-desktop`,flag:`claude-desktop`},{client:`claude-code`,flag:`claude-code`},{client:`codex`,flag:`codex`},{client:`cursor`,flag:`cursor`}];function qo(e,t){return O(e.all)?t:Ko.filter(({flag:t})=>O(e[t])).map(({client:e})=>e)}const Jo=C({meta:{name:`mcp`,description:`MCP server helpers`},subCommands:{serve:C({meta:{name:`serve`,description:`Run the SEO MCP server`},args:{test:{type:`boolean`,default:!1,description:`Start in test mode`}},run:async({args:e})=>{let{startMcpServer:t}=await import(`./dist-BrBR9umh.js`);await t({test:O(e.test)})}}),install:C({meta:{name:`install`,description:`Install or remove SEO MCP config for local clients`},args:{uninstall:{type:`boolean`,default:!1,description:`Remove the SEO MCP config instead of adding it`},reinstall:{type:`boolean`,default:!1,description:`Rewrite an existing managed SEO MCP config`},"claude-desktop":{type:`boolean`,default:!1,description:`Update Claude Desktop`},"claude-code":{type:`boolean`,default:!1,description:`Update Claude Code`},codex:{type:`boolean`,default:!1,description:`Update Codex CLI, app, and IDE extension`},cursor:{type:`boolean`,default:!1,description:`Update Cursor`},all:{type:`boolean`,default:!1,description:`Update every detected MCP client`},json:{type:`boolean`,default:!1,description:`Print structured JSON output`}},run:async({args:e})=>{if(O(e.uninstall)&&O(e.reinstall))throw new y(`INVALID_INPUT`,`Use either --uninstall or --reinstall, not both.`);let t=Ti(),n=Oi({targets:t}),r=N(e),i=qo(e,n.map(e=>e.client));if(i.length===0){if(!L({json:r}))throw new y(`INVALID_INPUT`,`Choose an MCP client with --claude-desktop, --claude-code, --codex, --cursor, or --all.`);let a=n.length>0?n:t;i=H(await Rn({message:e.uninstall?`Remove seo from which MCP clients?`:`Install seo into which MCP clients?`,options:a.map(e=>({value:e.client,label:e.label,hint:e.path})),initialValues:n.map(e=>e.client),required:!0}))}let a=i.filter(e=>!t.some(t=>t.client===e));if(a.length>0)throw new y(`INVALID_INPUT`,`MCP setup is not supported for ${a.join(`, `)} on ${process.platform}.`);let o=t.filter(e=>i.includes(e.client)).map(t=>O(e.uninstall)?qi(t):Ki(t,{reinstall:O(e.reinstall)}));if(r){R({operation:O(e.uninstall)?`uninstall`:`install`,results:o});return}for(let e of o)process.stdout.write(`${e.changed?`updated`:`skipped`} ${e.client} · ${e.path}\n`)}})}}),Yo=C({meta:{name:`crawl-diff`,description:`Crawl a site and diff technical/page changes vs last run`},args:{url:{type:`string`,required:!0,description:`Start URL to crawl.`},site:{type:`string`,description:`Optional GSC property to associate with the crawl.`},limit:{type:`string`,description:`Maximum pages to crawl. Defaults to 50.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering when Playwright is installed.`}},run:async({args:e})=>{let t=await re({startUrl:E(e.url)??``,site:E(e.site),limit:k(e.limit),refresh:O(e.refresh),js:O(e.js)?!0:`auto`});if(N(e)){R(t);return}if(z([[`Run`,t.run.id],[`Start URL`,t.run.startUrl],[`Crawled`,String(t.summary.crawled)],[`Previous run`,t.previousRun?.id??`none`],[`Added`,String(t.summary.added)],[`Removed`,String(t.summary.removed)],[`Changed`,String(t.summary.changed)],[`New errors`,String(t.summary.newErrors)],[`Indexability flips`,String(t.summary.indexabilityFlips)],[`High-priority actions`,String(t.summary.highPriorityRecommendations)]]),t.recommendations.length&&(process.stdout.write(`
176
+ `),V([`Severity`,`Issue`,`Action`],n.issues.map(e=>[e.severity,e.title,K(e.action,96)]))),Y(`Recommended pages`,n.recommendedPages.slice(0,10).map(e=>`${e.section}: ${e.url}`))}}),generate:w({meta:{name:`generate`,description:`Generate an llms.txt draft from a saved crawl`},args:{...Fs,output:{type:`string`,description:`Write llms.txt to this path instead of stdout.`},"max-urls":{type:`string`,description:`Maximum URLs to include. Defaults to 250.`},"token-budget":{type:`string`,description:`Approximate token budget. Defaults to 12000.`},exclude:{type:`string`,description:`Comma-separated URL patterns to exclude.`},title:{type:`string`,description:`Override the llms.txt title.`},description:{type:`string`,description:`Override the llms.txt description.`}},run:async({args:e})=>{let t=P(e),n=st(await Ri(e,{json:t}),{maxUrls:A(e[`max-urls`]),tokenBudget:A(e[`token-budget`]),exclude:M(e.exclude),title:D(e.title),description:D(e.description)});if(t){z(n);return}await Ps(D(e.output),n.content),D(e.output)&&B([[`URLs`,String(n.includedUrls)],[`Estimated tokens`,String(n.estimatedTokens)]])}})}}),Ls=w({meta:{name:`logs`,description:`Manage local log retention`},subCommands:{prune:w({meta:{name:`prune`,description:`Rotate large logs and remove old local logs`},args:{quiet:{type:`boolean`,default:!1,description:`Do not print a result.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=it();if(P(e)){z(t);return}e.quiet||process.stdout.write(`Rotated ${t.rotated} and removed ${t.removed} log files. ${ki(t.sizeBytes)} retained.\n`)}})}}),Rs=[{client:`claude-desktop`,flag:`claude-desktop`},{client:`claude-code`,flag:`claude-code`},{client:`codex`,flag:`codex`},{client:`cursor`,flag:`cursor`}];function zs(e,t){return k(e.all)?t:Rs.filter(({flag:t})=>k(e[t])).map(({client:e})=>e)}const Bs=w({meta:{name:`mcp`,description:`MCP server helpers`},subCommands:{serve:w({meta:{name:`serve`,description:`Run the SEO MCP server`},args:{test:{type:`boolean`,default:!1,description:`Start in test mode`}},run:async({args:e})=>{let{startMcpServer:t}=await import(`./dist-D0EI_L8C.js`);await t({test:k(e.test)})}}),install:w({meta:{name:`install`,description:`Install or remove SEO MCP config for local clients`},args:{uninstall:{type:`boolean`,default:!1,description:`Remove the SEO MCP config instead of adding it`},reinstall:{type:`boolean`,default:!1,description:`Rewrite an existing managed SEO MCP config`},"claude-desktop":{type:`boolean`,default:!1,description:`Update Claude Desktop`},"claude-code":{type:`boolean`,default:!1,description:`Update Claude Code`},codex:{type:`boolean`,default:!1,description:`Update Codex CLI, app, and IDE extension`},cursor:{type:`boolean`,default:!1,description:`Update Cursor`},all:{type:`boolean`,default:!1,description:`Update every detected MCP client`},json:{type:`boolean`,default:!1,description:`Print structured JSON output`}},run:async({args:e})=>{if(k(e.uninstall)&&k(e.reinstall))throw new b(`INVALID_INPUT`,`Use either --uninstall or --reinstall, not both.`);let t=oa(),n=la({targets:t}),r=P(e),i=zs(e,n.map(e=>e.client));if(i.length===0){if(!R({json:r}))throw new b(`INVALID_INPUT`,`Choose an MCP client with --claude-desktop, --claude-code, --codex, --cursor, or --all.`);let a=n.length>0?n:t;i=H(await cr({message:e.uninstall?`Remove seo from which MCP clients?`:`Install seo into which MCP clients?`,options:a.map(e=>({value:e.client,label:e.label,hint:e.path})),initialValues:n.map(e=>e.client),required:!0}))}let a=i.filter(e=>!t.some(t=>t.client===e));if(a.length>0)throw new b(`INVALID_INPUT`,`MCP setup is not supported for ${a.join(`, `)} on ${process.platform}.`);let o=t.filter(e=>i.includes(e.client)).map(t=>k(e.uninstall)?Oa(t):Da(t,{reinstall:k(e.reinstall)}));if(r){z({operation:k(e.uninstall)?`uninstall`:`install`,results:o});return}for(let e of o)process.stdout.write(`${e.changed?`updated`:`skipped`} ${e.client} · ${e.path}\n`)}})}}),Vs=w({meta:{name:`crawl-diff`,description:`Crawl a site and diff technical/page changes vs last run`},args:{url:{type:`string`,required:!0,description:`Start URL to crawl.`},site:{type:`string`,description:`Optional GSC property to associate with the crawl.`},limit:{type:`string`,description:`Maximum pages to crawl. Defaults to 50.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering when Playwright is installed.`}},run:async({args:e})=>{let t=await Lt({startUrl:D(e.url)??``,site:D(e.site),limit:A(e.limit),refresh:k(e.refresh),js:k(e.js)?!0:`auto`});if(P(e)){z(t);return}if(B([[`Run`,t.run.id],[`Start URL`,t.run.startUrl],[`Crawled`,String(t.summary.crawled)],[`Previous run`,t.previousRun?.id??`none`],[`Added`,String(t.summary.added)],[`Removed`,String(t.summary.removed)],[`Changed`,String(t.summary.changed)],[`New errors`,String(t.summary.newErrors)],[`Indexability flips`,String(t.summary.indexabilityFlips)],[`High-priority actions`,String(t.summary.highPriorityRecommendations)]]),t.recommendations.length&&(process.stdout.write(`
73
177
  Recommended actions
74
- `),B([`Severity`,`Category`,`URL`,`Action`],t.recommendations.slice(0,10).map(e=>[e.severity,e.category,K(e.url,56),K(e.action,72)])),J(`Top crawl actions`,t.recommendations.map(e=>({label:e.category,context:`${e.severity}, ${K(e.url,96)}`,action:e.action})))),t.items.length&&(process.stdout.write(`
178
+ `),V([`Severity`,`Category`,`URL`,`Action`],t.recommendations.slice(0,10).map(e=>[e.severity,e.category,K(e.url,56),K(e.action,72)])),J(`Top crawl actions`,t.recommendations.map(e=>({label:e.category,context:`${e.severity}, ${K(e.url,96)}`,action:e.action})))),t.items.length&&(process.stdout.write(`
75
179
  Changed URLs
76
- `),B([`Kind`,`URL`,`Changes`,`Recommendation`],t.items.slice(0,50).map(e=>[e.kind,K(e.url,56),e.changes.join(`, `),e.recommendation?.title??`-`]))),t.warnings.length){process.stdout.write(`
180
+ `),V([`Kind`,`URL`,`Changes`,`Recommendation`],t.items.slice(0,50).map(e=>[e.kind,K(e.url,56),e.changes.join(`, `),e.recommendation?.title??`-`]))),t.warnings.length){process.stdout.write(`
77
181
  Warnings
78
- `);for(let e of t.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}}});function Xo(){return{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},url:{type:`string`,description:`Start URL to crawl. Defaults from the project or GSC property.`},urls:{type:`string`,description:`Comma-separated URLs to inspect with URL Inspection.`},sitemaps:{type:`string`,description:`Comma-separated XML sitemap URLs for quota-aware index monitoring.`},properties:{type:`string`,description:`Comma-separated GSC properties for sitemap index monitoring.`},limit:{type:`string`,description:`Maximum pages to crawl. Defaults to 50.`},"daily-limit":{type:`string`,description:`URL Inspection daily limit per property. Defaults to 2000.`},"inspect-limit":{type:`string`,description:`Maximum sitemap URLs to inspect in this run. Defaults to 100.`},"max-urls":{type:`string`,description:`Maximum sitemap URLs to load for monitoring. Defaults to 50000.`},language:{type:`string`,description:`Optional URL Inspection language code.`},"recover-links":T(`Check search-value GSC pages for broken, blocked, or poorly redirected URLs.`,`Skip link recovery checks.`),"recover-days":{type:`string`,description:`GSC lookback window for link recovery. Defaults to 90.`},"recover-limit":{type:`string`,description:`Maximum search-value pages to check for link recovery. Defaults to 10.`},"recover-min-clicks":{type:`string`,description:`Minimum clicks for link recovery candidates. Defaults to 1.`},"recover-min-impressions":{type:`string`,description:`Minimum impressions for link recovery candidates. Defaults to 100.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP/GSC cache where supported.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering when Playwright is installed.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}}}function Zo(){return{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},"stale-days":{type:`string`,description:`Mark checks stale after this many days. Defaults to 8.`},refresh:{type:`boolean`,default:!1,description:`Refresh property selection data when prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}}}function Qo(e){z([[`Workflow`,e.workflow],[`Property`,e.site],[`Summary`,e.summary]]),B([`Tool`,`Status`,`Summary`],e.steps.map(e=>[e.tool,e.status,e.summary])),e.actions.length&&(B([`Priority`,`Confidence`,`Action`],e.actions.map(e=>[e.title,e.confidence,e.action])),J(`Priority action details`,e.actions.map(e=>({label:e.title,context:e.confidence,action:e.action}))))}function $o(e){if(Qo(e),e.output.crawl?.recommendations.length&&(process.stdout.write(`
182
+ `);for(let e of t.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}}});function Hs(){return{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},url:{type:`string`,description:`Start URL to crawl. Defaults from the project or GSC property.`},urls:{type:`string`,description:`Comma-separated URLs to inspect with URL Inspection.`},sitemaps:{type:`string`,description:`Comma-separated XML sitemap URLs for quota-aware index monitoring.`},properties:{type:`string`,description:`Comma-separated GSC properties for sitemap index monitoring.`},limit:{type:`string`,description:`Maximum pages to crawl. Defaults to 50.`},"daily-limit":{type:`string`,description:`URL Inspection daily limit per property. Defaults to 2000.`},"inspect-limit":{type:`string`,description:`Maximum sitemap URLs to inspect in this run. Defaults to 100.`},"max-urls":{type:`string`,description:`Maximum sitemap URLs to load for monitoring. Defaults to 50000.`},language:{type:`string`,description:`Optional URL Inspection language code.`},"recover-links":Br(`Check search-value GSC pages for broken, blocked, or poorly redirected URLs.`,`Skip link recovery checks.`),"recover-days":{type:`string`,description:`GSC lookback window for link recovery. Defaults to 90.`},"recover-limit":{type:`string`,description:`Maximum search-value pages to check for link recovery. Defaults to 10.`},"recover-min-clicks":{type:`string`,description:`Minimum clicks for link recovery candidates. Defaults to 1.`},"recover-min-impressions":{type:`string`,description:`Minimum impressions for link recovery candidates. Defaults to 100.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP/GSC cache where supported.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering when Playwright is installed.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}}}function Us(){return{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},"stale-days":{type:`string`,description:`Mark checks stale after this many days. Defaults to 8.`},refresh:{type:`boolean`,default:!1,description:`Refresh property selection data when prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}}}function Ws(e){B([[`Workflow`,e.workflow],[`Property`,e.site],[`Summary`,e.summary]]),V([`Tool`,`Status`,`Summary`],e.steps.map(e=>[e.tool,e.status,e.summary])),e.actions.length&&(V([`Priority`,`Confidence`,`Action`],e.actions.map(e=>[e.title,e.confidence,e.action])),J(`Priority action details`,e.actions.map(e=>({label:e.title,context:e.confidence,action:e.action}))))}function Gs(e){if(Ws(e),e.output.crawl?.recommendations.length&&(process.stdout.write(`
79
183
  Crawl actions
80
- `),B([`Severity`,`URL`,`Action`],e.output.crawl.recommendations.slice(0,10).map(e=>[e.severity,K(e.url,56),K(e.action,72)])),J(`Top crawl actions`,e.output.crawl.recommendations.map(e=>({label:e.severity,context:K(e.url,96),action:e.action})))),e.output.index?.items.length){let t=e.output.index.items.filter(e=>e.currentIssue||e.changed||e.inspectionStatus!==`succeeded`).slice(0,25);t.length&&(process.stdout.write(`
184
+ `),V([`Severity`,`URL`,`Action`],e.output.crawl.recommendations.slice(0,10).map(e=>[e.severity,K(e.url,56),K(e.action,72)])),J(`Top crawl actions`,e.output.crawl.recommendations.map(e=>({label:e.severity,context:K(e.url,96),action:e.action})))),e.output.index?.items.length){let t=e.output.index.items.filter(e=>e.currentIssue||e.changed||e.inspectionStatus!==`succeeded`).slice(0,25);t.length&&(process.stdout.write(`
81
185
  Index reviews, changes, and failed checks
82
- `),B([`Check`,`Change`,`Index state`,`Evidence`,`URL`],t.map(e=>[e.inspectionStatus,e.changeKind,e.indexStatus,K((e.errorCode??e.issueCodes.join(`, `))||`none`,40),K(e.url,64)])))}e.output.recovery?.items.length&&(process.stdout.write(`
186
+ `),V([`Check`,`Change`,`Index state`,`Evidence`,`URL`],t.map(e=>[e.inspectionStatus,e.changeKind,e.indexStatus,K((e.errorCode??e.issueCodes.join(`, `))||`none`,40),K(e.url,64)])))}e.output.recovery?.items.length&&(process.stdout.write(`
83
187
  Recoverable URLs
84
- `),B([`Severity`,`Issue`,`Clicks`,`Impr`,`URL`,`Action`],e.output.recovery.items.slice(0,10).map(e=>[e.severity,e.issue,W(e.clicks),W(e.impressions),K(e.url,56),K(e.recommendation.action,72)])),J(`Top recovery actions`,e.output.recovery.items.map(e=>({label:K(e.url,96),context:`${e.severity}, ${W(e.clicks)} clicks at risk`,action:e.recommendation.action}))))}function es(e){z([[`Property`,e.site],[`Health`,e.health],[`Attention`,String(e.summary.attention)],[`Stale`,String(e.summary.stale)],[`Not run`,String(e.summary.notRun)]]),B([`Check`,`Status`,`Last run`,`Summary`],e.checks.map(e=>[e.name,e.status,e.lastRunAt??`-`,e.summary]));let t=e.checks.filter(e=>e.action);t.length&&(process.stdout.write(`
188
+ `),V([`Severity`,`Issue`,`Clicks`,`Impr`,`URL`,`Action`],e.output.recovery.items.slice(0,10).map(e=>[e.severity,e.issue,W(e.clicks),W(e.impressions),K(e.url,56),K(e.recommendation.action,72)])),J(`Top recovery actions`,e.output.recovery.items.map(e=>({label:K(e.url,96),context:`${e.severity}, ${W(e.clicks)} clicks at risk`,action:e.recommendation.action}))))}function Ks(e){B([[`Property`,e.site],[`Health`,e.health],[`Attention`,String(e.summary.attention)],[`Stale`,String(e.summary.stale)],[`Not run`,String(e.summary.notRun)]]),V([`Check`,`Status`,`Last run`,`Summary`],e.checks.map(e=>[e.name,e.status,e.lastRunAt??`-`,e.summary]));let t=e.checks.filter(e=>e.action);t.length&&(process.stdout.write(`
85
189
  Next actions
86
- `),B([`Check`,`Action`],t.map(e=>[e.name,K(e.action??``,96)])),J(`Next action details`,t.map(e=>({label:e.name,action:e.action??``}))))}function Z(e,t){let n=E(t);return n?`--${e} ${JSON.stringify(n)}`:void 0}function ts(e,t){return O(t)?`--${e}`:void 0}function ns(e){return O(e)===!1?`--recover-links=false`:void 0}const rs=C({meta:{name:`monitoring`,description:`Run and review recurring technical SEO monitoring`},subCommands:{run:C({meta:{name:`run`,description:`Run crawl, index, and link recovery monitoring for a property`},args:Xo(),run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),r=M(e.urls),i=M(e.sitemaps),a=E(e.url)??n.client?.startUrl??yi(n.site),o=await c({site:n.site,startUrl:a,urls:r.length?r:n.client?.watchUrls,sitemaps:i.length?i:void 0,properties:M(e.properties).length?M(e.properties):void 0,limit:k(e.limit),languageCode:E(e.language),dailyLimit:k(e[`daily-limit`]),inspectLimit:k(e[`inspect-limit`]),maxUrls:k(e[`max-urls`]),refresh:O(e.refresh),js:O(e.js)?!0:`auto`,recoverLinks:O(e[`recover-links`]),recoverDays:k(e[`recover-days`]),recoverLimit:k(e[`recover-limit`]),recoverMinClicks:k(e[`recover-min-clicks`]),recoverMinImpressions:k(e[`recover-min-impressions`])});if(t){R(o);return}$o(o)}}),status:C({meta:{name:`status`,description:`Show the latest saved monitoring state for a property`},args:Zo(),run:async({args:e})=>{let t=N(e),n=Zt({site:(await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}})).site,staleAfterDays:k(e[`stale-days`])});if(t){R(n);return}es(n)}}),cron:C({meta:{name:`cron`,description:`Print a local cron line for recurring monitoring`},args:{...Xo(),hour:{type:`string`,default:`9`,description:`Hour in local cron time. Defaults to 9.`},minute:{type:`string`,default:`0`,description:`Minute in local cron time. Defaults to 0.`},weekday:{type:`string`,description:`Weekly monitoring day. Defaults to client setting, then Monday.`}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),r=k(e.hour)??9,i=k(e.minute)??0,a=k(e.weekday)??n.client?.technicalWeekday??1,o=[`seo monitoring run`,n.client?`--project ${JSON.stringify(n.client.id)}`:`--site ${JSON.stringify(n.site)}`,Z(`url`,e.url),Z(`urls`,e.urls),Z(`sitemaps`,e.sitemaps),Z(`properties`,e.properties),Z(`limit`,e.limit),Z(`daily-limit`,e[`daily-limit`]),Z(`inspect-limit`,e[`inspect-limit`]),Z(`max-urls`,e[`max-urls`]),Z(`language`,e.language),Z(`recover-days`,e[`recover-days`]),Z(`recover-limit`,e[`recover-limit`]),Z(`recover-min-clicks`,e[`recover-min-clicks`]),Z(`recover-min-impressions`,e[`recover-min-impressions`]),ns(e[`recover-links`]),ts(`refresh`,e.refresh),ts(`js`,e.js),`--json`].filter(Boolean).join(` `),s={name:`monitoring`,cron:`${i} ${r} * * ${a}`,command:o};if(t){R({site:n.site,line:s});return}z([[`Property`,n.site],[`Install`,`crontab -e`]]),process.stdout.write(`${s.cron} ${s.command}\n`)}})}}),is=C({meta:{name:`index-coverage`,description:`Find crawlable pages that deserve a closer Google index check`},args:{project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},"crawl-report-id":{type:`string`,description:`Saved crawl report id. Defaults to the latest for the site.`},sitemaps:{type:`string`,description:`Comma-separated XML sitemap URLs. Defaults to declarations captured by the crawl.`},days:{type:`string`,description:`Finalized Search Console date range. Defaults to 90 days.`},"row-limit":{type:`string`,description:`Maximum Search Console page rows. Defaults to 100000.`},"max-sitemap-urls":{type:`string`,description:`Maximum sitemap inventory URLs. Defaults to 100000.`},limit:{type:`string`,description:`Maximum URLs returned in each evidence group. Defaults to 100.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local Search Console cache.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),r=M(e.sitemaps),i=await m({site:n.site,crawlReportId:E(e[`crawl-report-id`]),sitemaps:r.length?r:void 0,days:k(e.days),rowLimit:k(e[`row-limit`]),maxSitemapUrls:k(e[`max-sitemap-urls`]),itemsPerSection:k(e.limit),refresh:O(e.refresh)});if(t){R(i);return}if(z([[`Project site`,i.site],[`Crawl report`,i.input.crawlReport.id],[`Crawl evidence`,i.sources.crawl.completeness],[`Sitemap evidence`,i.sources.sitemap.completeness],[`Search Console window`,`${i.sources.searchConsole.startDate} to ${i.sources.searchConsole.endDate}`],[`Search Console evidence`,i.sources.searchConsole.completeness],[`Pages in returned Search Console data`,String(i.summary.retainedSearchVisibleUrls)],[`Crawlable pages to review`,String(i.summary.crawlableCandidatesWithoutRetainedSearchVisibility)],[`Blocked or non-indexable crawl pages`,String(i.summary.blockedOrNonIndexableCrawlUrls)],[`Sitemap-only pages`,String(i.summary.sitemapOnlyUrls)],[`Search Console-only pages`,String(i.summary.searchConsoleOnlyUrls)]]),i.crawlableWithoutRetainedSearchVisibility.items.length&&(process.stdout.write(`
190
+ `),V([`Check`,`Action`],t.map(e=>[e.name,K(e.action??``,96)])),J(`Next action details`,t.map(e=>({label:e.name,action:e.action??``}))))}function Z(e,t){let n=D(t);return n?`--${e} ${JSON.stringify(n)}`:void 0}function qs(e,t){return k(t)?`--${e}`:void 0}function Js(e){return k(e)===!1?`--recover-links=false`:void 0}const Ys=w({meta:{name:`monitoring`,description:`Run and review recurring technical SEO monitoring`},subCommands:{run:w({meta:{name:`run`,description:`Run crawl, index, and link recovery monitoring for a property`},args:Hs(),run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),r=N(e.urls),i=N(e.sitemaps),a=D(e.url)??n.client?.startUrl??ea(n.site),o=await Je({site:n.site,startUrl:a,urls:r.length?r:n.client?.watchUrls,sitemaps:i.length?i:void 0,properties:N(e.properties).length?N(e.properties):void 0,limit:A(e.limit),languageCode:D(e.language),dailyLimit:A(e[`daily-limit`]),inspectLimit:A(e[`inspect-limit`]),maxUrls:A(e[`max-urls`]),refresh:k(e.refresh),js:k(e.js)?!0:`auto`,recoverLinks:k(e[`recover-links`]),recoverDays:A(e[`recover-days`]),recoverLimit:A(e[`recover-limit`]),recoverMinClicks:A(e[`recover-min-clicks`]),recoverMinImpressions:A(e[`recover-min-impressions`])});if(t){z(o);return}Gs(o)}}),status:w({meta:{name:`status`,description:`Show the latest saved monitoring state for a property`},args:Us(),run:async({args:e})=>{let t=P(e),n=Qt({site:(await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}})).site,staleAfterDays:A(e[`stale-days`])});if(t){z(n);return}Ks(n)}}),cron:w({meta:{name:`cron`,description:`Print a local cron line for recurring monitoring`},args:{...Hs(),hour:{type:`string`,default:`9`,description:`Hour in local cron time. Defaults to 9.`},minute:{type:`string`,default:`0`,description:`Minute in local cron time. Defaults to 0.`},weekday:{type:`string`,description:`Weekly monitoring day. Defaults to client setting, then Monday.`}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),r=A(e.hour)??9,i=A(e.minute)??0,a=A(e.weekday)??n.client?.technicalWeekday??1,o=[`seo monitoring run`,n.client?`--project ${JSON.stringify(n.client.id)}`:`--site ${JSON.stringify(n.site)}`,Z(`url`,e.url),Z(`urls`,e.urls),Z(`sitemaps`,e.sitemaps),Z(`properties`,e.properties),Z(`limit`,e.limit),Z(`daily-limit`,e[`daily-limit`]),Z(`inspect-limit`,e[`inspect-limit`]),Z(`max-urls`,e[`max-urls`]),Z(`language`,e.language),Z(`recover-days`,e[`recover-days`]),Z(`recover-limit`,e[`recover-limit`]),Z(`recover-min-clicks`,e[`recover-min-clicks`]),Z(`recover-min-impressions`,e[`recover-min-impressions`]),Js(e[`recover-links`]),qs(`refresh`,e.refresh),qs(`js`,e.js),`--json`].filter(Boolean).join(` `),s={name:`monitoring`,cron:`${i} ${r} * * ${a}`,command:o};if(t){z({site:n.site,line:s});return}B([[`Property`,n.site],[`Install`,`crontab -e`]]),process.stdout.write(`${s.cron} ${s.command}\n`)}})}}),Xs=w({meta:{name:`index-coverage`,description:`Find crawlable pages that deserve a closer Google index check`},args:{project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},"crawl-report-id":{type:`string`,description:`Saved crawl report id. Defaults to the latest for the site.`},sitemaps:{type:`string`,description:`Comma-separated XML sitemap URLs. Defaults to declarations captured by the crawl.`},days:{type:`string`,description:`Finalized Search Console date range. Defaults to 90 days.`},"row-limit":{type:`string`,description:`Maximum Search Console page rows. Defaults to 100000.`},"max-sitemap-urls":{type:`string`,description:`Maximum sitemap inventory URLs. Defaults to 100000.`},limit:{type:`string`,description:`Maximum URLs returned in each evidence group. Defaults to 100.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local Search Console cache.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),r=N(e.sitemaps),i=await Gt({site:n.site,crawlReportId:D(e[`crawl-report-id`]),sitemaps:r.length?r:void 0,days:A(e.days),rowLimit:A(e[`row-limit`]),maxSitemapUrls:A(e[`max-sitemap-urls`]),itemsPerSection:A(e.limit),refresh:k(e.refresh)});if(t){z(i);return}if(B([[`Project site`,i.site],[`Crawl report`,i.input.crawlReport.id],[`Crawl evidence`,i.sources.crawl.completeness],[`Sitemap evidence`,i.sources.sitemap.completeness],[`Search Console window`,`${i.sources.searchConsole.startDate} to ${i.sources.searchConsole.endDate}`],[`Search Console evidence`,i.sources.searchConsole.completeness],[`Pages in returned Search Console data`,String(i.summary.retainedSearchVisibleUrls)],[`Crawlable pages to review`,String(i.summary.crawlableCandidatesWithoutRetainedSearchVisibility)],[`Blocked or non-indexable crawl pages`,String(i.summary.blockedOrNonIndexableCrawlUrls)],[`Sitemap-only pages`,String(i.summary.sitemapOnlyUrls)],[`Search Console-only pages`,String(i.summary.searchConsoleOnlyUrls)]]),i.crawlableWithoutRetainedSearchVisibility.items.length&&(process.stdout.write(`
87
191
  Representative URL Inspection candidates
88
- `),B([`URL`,`Status`,`In sitemap`],i.crawlableWithoutRetainedSearchVisibility.items.map(e=>[K(e.url,80),e.status,e.inSitemap?`yes`:`no`]))),i.caveats.length){process.stdout.write(`
192
+ `),V([`URL`,`Status`,`In sitemap`],i.crawlableWithoutRetainedSearchVisibility.items.map(e=>[K(e.url,80),e.status,e.inSitemap?`yes`:`no`]))),i.caveats.length){process.stdout.write(`
89
193
  How to read this report
90
- `);for(let e of i.caveats)process.stdout.write(`- ${e}\n`)}}}),as=C({meta:{name:`index-watch`,description:`Inspect URLs with GSC and alert on index status changes`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},urls:{type:`string`,description:`Comma-separated URLs to inspect.`},sitemaps:{type:`string`,description:`Comma-separated XML sitemap URLs to plan quota-aware monitoring.`},plan:{type:`boolean`,default:!1,description:`Plan sitemap URL allocation across GSC properties without inspecting URLs.`},properties:{type:`string`,description:`Comma-separated GSC properties to use for planning. Defaults to account properties.`},"daily-limit":{type:`string`,description:`URL Inspection daily limit per property. Defaults to 2000.`},"target-days":{type:`string`,description:`Target number of days to inspect all monitored URLs. Defaults to 1.`},"max-urls":{type:`string`,description:`Maximum sitemap URLs to load for planning. Defaults to 50000.`},"inspect-limit":{type:`string`,description:`Maximum URLs to inspect in this run from sitemap mode. Defaults to 100.`},language:{type:`string`,description:`Optional URL Inspection language code.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=M(e.urls),r=await Zr({site:E(e.site),options:{json:t}}),i=M(e.sitemaps);if(O(e.plan)){if(!i.length)throw Error(`Pass at least one sitemap with --sitemaps.`);let n=await Oe({site:r,sitemaps:i,properties:M(e.properties).length?M(e.properties):void 0,dailyLimit:k(e[`daily-limit`]),targetCycleDays:k(e[`target-days`]),maxUrls:k(e[`max-urls`])});if(t){R(n);return}if(z([[`Project site`,n.site],[`Sitemap URLs`,String(n.summary.urlCount)],[`Properties used`,String(n.summary.properties)],[`Daily capacity`,String(n.summary.dailyCapacity)],[`Estimated cycle`,at(n.summary.estimatedCycleDays,`day`)],[`Target cycle`,at(n.summary.targetCycleDays,`day`)],[`Suggested properties`,String(n.summary.suggestedProperties)]]),n.properties.length&&B([`Property`,`URLs`,`Cycle`,`Sample URL`],n.properties.map(e=>[e.property,e.urlCount,at(e.cycleDays,`day`),e.sampleUrls[0]??`-`])),n.suggestions.length&&(process.stdout.write(`
194
+ `);for(let e of i.caveats)process.stdout.write(`- ${e}\n`)}}}),Zs=w({meta:{name:`index-watch`,description:`Inspect URLs with GSC and alert on index status changes`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},urls:{type:`string`,description:`Comma-separated URLs to inspect.`},sitemaps:{type:`string`,description:`Comma-separated XML sitemap URLs to plan quota-aware monitoring.`},plan:{type:`boolean`,default:!1,description:`Plan sitemap URL allocation across GSC properties without inspecting URLs.`},properties:{type:`string`,description:`Comma-separated GSC properties to use for planning. Defaults to account properties.`},"daily-limit":{type:`string`,description:`URL Inspection daily limit per property. Defaults to 2000.`},"target-days":{type:`string`,description:`Target number of days to inspect all monitored URLs. Defaults to 1.`},"max-urls":{type:`string`,description:`Maximum sitemap URLs to load for planning. Defaults to 50000.`},"inspect-limit":{type:`string`,description:`Maximum URLs to inspect in this run from sitemap mode. Defaults to 100.`},language:{type:`string`,description:`Optional URL Inspection language code.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=N(e.urls),r=await Mi({site:D(e.site),options:{json:t}}),i=N(e.sitemaps);if(k(e.plan)){if(!i.length)throw Error(`Pass at least one sitemap with --sitemaps.`);let n=await gt({site:r,sitemaps:i,properties:N(e.properties).length?N(e.properties):void 0,dailyLimit:A(e[`daily-limit`]),targetCycleDays:A(e[`target-days`]),maxUrls:A(e[`max-urls`])});if(t){z(n);return}if(B([[`Project site`,n.site],[`Sitemap URLs`,String(n.summary.urlCount)],[`Properties used`,String(n.summary.properties)],[`Daily capacity`,String(n.summary.dailyCapacity)],[`Estimated cycle`,pe(n.summary.estimatedCycleDays,`day`)],[`Target cycle`,pe(n.summary.targetCycleDays,`day`)],[`Suggested properties`,String(n.summary.suggestedProperties)]]),n.properties.length&&V([`Property`,`URLs`,`Cycle`,`Sample URL`],n.properties.map(e=>[e.property,e.urlCount,pe(e.cycleDays,`day`),e.sampleUrls[0]??`-`])),n.suggestions.length&&(process.stdout.write(`
91
195
  Suggested URL-prefix properties
92
- `),B([`Property`,`URLs`,`Current property`,`Cycle`,`Reason`],n.suggestions.map(e=>[e.property,e.urlCount,e.currentProperty,at(e.estimatedCycleDays,`day`),e.reason]))),n.warnings.length){process.stdout.write(`
196
+ `),V([`Property`,`URLs`,`Current property`,`Cycle`,`Reason`],n.suggestions.map(e=>[e.property,e.urlCount,e.currentProperty,pe(e.estimatedCycleDays,`day`),e.reason]))),n.warnings.length){process.stdout.write(`
93
197
  Warnings
94
- `);for(let e of n.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}return}if(i.length){let n=await g({site:r,sitemaps:i,properties:M(e.properties).length?M(e.properties):void 0,dailyLimit:k(e[`daily-limit`]),inspectLimit:k(e[`inspect-limit`]),maxUrls:k(e[`max-urls`]),languageCode:E(e.language)});if(t){R(n);return}z([[`Project site`,n.site],[`Discovered sitemap URLs`,String(n.source.discoveredUrls)],[`Invalid sitemap URLs`,String(n.source.invalidUrls)],[`Inventory URLs`,String(n.summary.inventoryUrls)],[`Properties used`,String(n.summary.properties)],[`Daily capacity`,String(n.summary.dailyCapacity)],[`Never attempted`,String(n.summary.neverAttempted)],[`Never succeeded`,String(n.summary.neverSucceeded)],[`Retry waiting`,String(n.summary.retryWaiting)],[`Fresh`,String(n.summary.fresh)],[`Stale`,String(n.summary.stale)],[`Due`,String(n.summary.due)],[`Selected this run`,String(n.summary.selected)],[`Due but not selected`,String(n.summary.unselectedDue)],[`Attempted`,String(n.summary.attempted)],[`Inspected`,String(n.summary.inspected)],[`Failed`,String(n.summary.failed)],[`Quota blocked`,String(n.summary.quotaBlocked)],[`Deferred`,String(n.summary.deferred)],[`Current reviews`,String(n.summary.currentIssues)],[`Regressions`,String(n.summary.regressions)],[`Recoveries`,String(n.summary.recoveries)],[`Changed`,String(n.summary.changed)],[`New alerts`,String(n.summary.alerts)],[`Skipped`,String(n.summary.skipped)]]),n.properties.length&&B([`Property`,`Inventory`,`Selected`,`Inspected`,`Failed`,`Current`,`Alerts`],n.properties.map(e=>[e.property,e.inventoryUrls,e.selectedUrls,e.inspected,e.failed+e.quotaBlocked,e.currentIssues,e.alerts]));let a=n.items.filter(e=>e.currentIssue||e.changed||e.inspectionStatus!==`succeeded`).slice(0,50);if(a.length&&(process.stdout.write(`
198
+ `);for(let e of n.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}return}if(i.length){let n=await an({site:r,sitemaps:i,properties:N(e.properties).length?N(e.properties):void 0,dailyLimit:A(e[`daily-limit`]),inspectLimit:A(e[`inspect-limit`]),maxUrls:A(e[`max-urls`]),languageCode:D(e.language)});if(t){z(n);return}B([[`Project site`,n.site],[`Discovered sitemap URLs`,String(n.source.discoveredUrls)],[`Invalid sitemap URLs`,String(n.source.invalidUrls)],[`Inventory URLs`,String(n.summary.inventoryUrls)],[`Properties used`,String(n.summary.properties)],[`Daily capacity`,String(n.summary.dailyCapacity)],[`Never attempted`,String(n.summary.neverAttempted)],[`Never succeeded`,String(n.summary.neverSucceeded)],[`Retry waiting`,String(n.summary.retryWaiting)],[`Fresh`,String(n.summary.fresh)],[`Stale`,String(n.summary.stale)],[`Due`,String(n.summary.due)],[`Selected this run`,String(n.summary.selected)],[`Due but not selected`,String(n.summary.unselectedDue)],[`Attempted`,String(n.summary.attempted)],[`Inspected`,String(n.summary.inspected)],[`Failed`,String(n.summary.failed)],[`Quota blocked`,String(n.summary.quotaBlocked)],[`Deferred`,String(n.summary.deferred)],[`Current reviews`,String(n.summary.currentIssues)],[`Regressions`,String(n.summary.regressions)],[`Recoveries`,String(n.summary.recoveries)],[`Changed`,String(n.summary.changed)],[`New alerts`,String(n.summary.alerts)],[`Skipped`,String(n.summary.skipped)]]),n.properties.length&&V([`Property`,`Inventory`,`Selected`,`Inspected`,`Failed`,`Current`,`Alerts`],n.properties.map(e=>[e.property,e.inventoryUrls,e.selectedUrls,e.inspected,e.failed+e.quotaBlocked,e.currentIssues,e.alerts]));let a=n.items.filter(e=>e.currentIssue||e.changed||e.inspectionStatus!==`succeeded`).slice(0,50);if(a.length&&(process.stdout.write(`
95
199
  Index reviews, changes, and failed checks
96
- `),B([`Check`,`Change`,`Index state`,`Evidence`,`URL`],a.map(e=>[e.inspectionStatus,e.changeKind,e.indexStatus,(e.errorCode??e.issueCodes.join(`, `))||`none`,e.url]))),n.warnings.length){process.stdout.write(`
200
+ `),V([`Check`,`Change`,`Index state`,`Evidence`,`URL`],a.map(e=>[e.inspectionStatus,e.changeKind,e.indexStatus,(e.errorCode??e.issueCodes.join(`, `))||`none`,e.url]))),n.warnings.length){process.stdout.write(`
97
201
  Warnings
98
- `);for(let e of n.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}return}if(!n.length)throw Error(`Pass at least one URL with --urls.`);let a=await we({site:r,urls:n,languageCode:E(e.language),dailyLimit:k(e[`daily-limit`])});if(t){R(a);return}z([[`Project site`,a.site],[`Inspection property`,a.source.property],[`Attempted`,String(a.summary.attempted)],[`Inspected`,String(a.summary.inspected)],[`Failed`,String(a.summary.failed)],[`Quota blocked`,String(a.summary.quotaBlocked)],[`Deferred`,String(a.summary.deferred)],[`Current reviews`,String(a.summary.currentIssues)],[`Regressions`,String(a.summary.regressions)],[`Recoveries`,String(a.summary.recoveries)],[`Changed`,String(a.summary.changed)],[`New alerts`,String(a.summary.alerts)]]),B([`Check`,`Change`,`Index state`,`Evidence`,`URL`],a.items.map(e=>[e.inspectionStatus,e.changeKind,e.indexStatus,(e.errorCode??e.issueCodes.join(`, `))||`none`,e.url]))}}),os=C({meta:{name:`link-recover`,description:`Find search-value URLs that are now broken, blocked, or poorly redirected`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`limit`,`minImpressions`,`refresh`,`js`],{days:{description:`GSC lookback window. Defaults to 90.`},limit:{description:`Maximum GSC pages to check. Defaults to 50.`},minImpressions:{description:`Minimum impressions to check a page. Defaults to 100.`},refresh:{description:`Bypass local GSC and HTTP caches.`},js:{description:`Force JavaScript rendering for final page extraction.`}}),"min-clicks":{type:`string`,description:`Minimum clicks to check a page. Defaults to 1.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=await i({site:await vi({client:D(e),site:E(e.site)},{json:t}),days:k(e.days),limit:k(e.limit),minClicks:k(e[`min-clicks`]),minImpressions:k(e[`min-impressions`]),refresh:O(e.refresh),js:O(e.js)?!0:`auto`});if(t){R(n);return}if(z([[`Site`,n.site],[`Range`,`${n.range.startDate} to ${n.range.endDate}`],[`Checked`,W(n.summary.checked)],[`Recoverable`,W(n.summary.recoverable)],[`High severity`,W(n.summary.high)],[`Clicks at risk`,W(n.summary.clicksAtRisk)],[`Impressions at risk`,W(n.summary.impressionsAtRisk)]]),n.items.length&&(q([`Severity`,`Issue`,`Clicks`,`Impr`,`URL`,`Action`],n.items.map(e=>[e.severity,e.issue,W(e.clicks),W(e.impressions),K(e.url,56),K(e.recommendation.action,72)])),J(`Top recovery actions`,n.items.map(e=>({label:K(e.url,96),context:`${e.severity}, ${W(e.clicks)} clicks at risk`,action:e.recommendation.action})))),n.warnings.length){process.stdout.write(`
202
+ `);for(let e of n.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}return}if(!n.length)throw Error(`Pass at least one URL with --urls.`);let a=await dt({site:r,urls:n,languageCode:D(e.language),dailyLimit:A(e[`daily-limit`])});if(t){z(a);return}B([[`Project site`,a.site],[`Inspection property`,a.source.property],[`Attempted`,String(a.summary.attempted)],[`Inspected`,String(a.summary.inspected)],[`Failed`,String(a.summary.failed)],[`Quota blocked`,String(a.summary.quotaBlocked)],[`Deferred`,String(a.summary.deferred)],[`Current reviews`,String(a.summary.currentIssues)],[`Regressions`,String(a.summary.regressions)],[`Recoveries`,String(a.summary.recoveries)],[`Changed`,String(a.summary.changed)],[`New alerts`,String(a.summary.alerts)]]),V([`Check`,`Change`,`Index state`,`Evidence`,`URL`],a.items.map(e=>[e.inspectionStatus,e.changeKind,e.indexStatus,(e.errorCode??e.issueCodes.join(`, `))||`none`,e.url]))}}),Qs=w({meta:{name:`link-recover`,description:`Find search-value URLs that are now broken, blocked, or poorly redirected`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`limit`,`minImpressions`,`refresh`,`js`],{days:{description:`GSC lookback window. Defaults to 90.`},limit:{description:`Maximum GSC pages to check. Defaults to 50.`},minImpressions:{description:`Minimum impressions to check a page. Defaults to 100.`},refresh:{description:`Bypass local GSC and HTTP caches.`},js:{description:`Force JavaScript rendering for final page extraction.`}}),"min-clicks":{type:`string`,description:`Minimum clicks to check a page. Defaults to 1.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=await ct({site:await $i({client:O(e),site:D(e.site)},{json:t}),days:A(e.days),limit:A(e.limit),minClicks:A(e[`min-clicks`]),minImpressions:A(e[`min-impressions`]),refresh:k(e.refresh),js:k(e.js)?!0:`auto`});if(t){z(n);return}if(B([[`Site`,n.site],[`Range`,`${n.range.startDate} to ${n.range.endDate}`],[`Checked`,W(n.summary.checked)],[`Recoverable`,W(n.summary.recoverable)],[`High severity`,W(n.summary.high)],[`Clicks at risk`,W(n.summary.clicksAtRisk)],[`Impressions at risk`,W(n.summary.impressionsAtRisk)]]),n.items.length&&(q([`Severity`,`Issue`,`Clicks`,`Impr`,`URL`,`Action`],n.items.map(e=>[e.severity,e.issue,W(e.clicks),W(e.impressions),K(e.url,56),K(e.recommendation.action,72)])),J(`Top recovery actions`,n.items.map(e=>({label:K(e.url,96),context:`${e.severity}, ${W(e.clicks)} clicks at risk`,action:e.recommendation.action})))),n.warnings.length){process.stdout.write(`
99
203
  Warnings
100
- `);for(let e of n.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}}}),ss=C({meta:{name:`redirect-trace`,description:`Trace redirects and report final indexability/canonical issues`},args:{url:{type:`string`,required:!0,description:`URL to trace.`},"max-hops":{type:`string`,description:`Maximum redirect hops to follow. Defaults to 10.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache for final page extraction.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for final page extraction.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await Ee({url:E(e.url)??``,maxHops:k(e[`max-hops`]),refresh:O(e.refresh),js:O(e.js)?!0:`auto`});if(N(e)){R(t);return}if(z([[`URL`,t.url],[`Final URL`,t.finalUrl],[`Final status`,String(t.summary.finalStatus)],[`Indexable`,t.summary.finalIndexable===void 0?`unknown`:t.summary.finalIndexable?`yes`:`no`],[`Hops`,String(t.summary.hops)],[`Issues`,t.summary.issues.length?t.summary.issues.join(`, `):`none`]]),B([`#`,`Status`,`URL`,`Next`],t.chain.map((e,t)=>[t+1,e.status,K(e.url,72),K(e.nextUrl??`-`,72)])),t.finalPage&&(process.stdout.write(`
204
+ `);for(let e of n.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}}}),$s=w({meta:{name:`redirect-trace`,description:`Trace redirects and report final indexability/canonical issues`},args:{url:{type:`string`,required:!0,description:`URL to trace.`},"max-hops":{type:`string`,description:`Maximum redirect hops to follow. Defaults to 10.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache for final page extraction.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for final page extraction.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await Pt({url:D(e.url)??``,maxHops:A(e[`max-hops`]),refresh:k(e.refresh),js:k(e.js)?!0:`auto`});if(P(e)){z(t);return}if(B([[`URL`,t.url],[`Final URL`,t.finalUrl],[`Final status`,String(t.summary.finalStatus)],[`Indexable`,t.summary.finalIndexable===void 0?`unknown`:t.summary.finalIndexable?`yes`:`no`],[`Hops`,String(t.summary.hops)],[`Issues`,t.summary.issues.length?t.summary.issues.join(`, `):`none`]]),V([`#`,`Status`,`URL`,`Next`],t.chain.map((e,t)=>[t+1,e.status,K(e.url,72),K(e.nextUrl??`-`,72)])),t.finalPage&&(process.stdout.write(`
101
205
  Final page
102
- `),z([[`Title`,t.finalPage.title??`-`],[`Canonical`,t.finalPage.canonical??`-`],[`Meta robots`,t.finalPage.metaRobots??`-`]])),t.warnings.length){process.stdout.write(`
206
+ `),B([[`Title`,t.finalPage.title??`-`],[`Canonical`,t.finalPage.canonical??`-`],[`Meta robots`,t.finalPage.metaRobots??`-`]])),t.warnings.length){process.stdout.write(`
103
207
  Warnings
104
- `);for(let e of t.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}}});function cs(e,t){process.stdout.write(`OKF validation for ${e}\n\n`),z([[`Valid`,t.valid?`yes`:`no`],[`Files`,String(t.files)],[`Concepts`,String(t.concepts)],[`Errors`,String(t.issues.filter(e=>e.severity===`error`).length)],[`Warnings`,String(t.issues.filter(e=>e.severity===`warning`).length)]]),t.issues.length&&(process.stdout.write(`
208
+ `);for(let e of t.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}}});function ec(e,t){process.stdout.write(`OKF validation for ${e}\n\n`),B([[`Valid`,t.valid?`yes`:`no`],[`Files`,String(t.files)],[`Concepts`,String(t.concepts)],[`Errors`,String(t.issues.filter(e=>e.severity===`error`).length)],[`Warnings`,String(t.issues.filter(e=>e.severity===`warning`).length)]]),t.issues.length&&(process.stdout.write(`
105
209
  Issues
106
- `),B([`Severity`,`Path`,`Message`],t.issues.slice(0,25).map(e=>[e.severity,e.path,e.message])))}const ls=C({meta:{name:`okf`,description:`Export, validate, and explain OKF site knowledge bundles`},subCommands:{export:C({meta:{name:`export`,description:`Export a saved crawl as an OKF bundle`},args:{"report-id":{type:`string`,description:`Saved crawl report id to export.`},site:{type:`string`,description:`GSC property URL for selecting the latest saved crawl.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},output:{type:`string`,description:`Output directory. Defaults to ./okf.`},"max-concepts":{type:`string`,description:`Maximum concept files to export. Defaults to 500.`},title:{type:`string`,description:`Override the root bundle title.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=Et(A(e[`max-concepts`],`--max-concepts`)),r=Je(await ri(e,{json:t}),{maxConcepts:n,title:E(e.title)}),i=E(e.output)??`./okf`,a=await ko(i,r.files);if(t){R({output:i,bundle:r,validation:a});return}process.stdout.write(`Wrote OKF bundle to ${i}\n\n`),z([[`Files`,String(r.files.length)],[`Concepts`,String(r.conceptCount)],[`Valid`,a.valid?`yes`:`no`]])}}),validate:C({meta:{name:`validate`,description:`Validate an OKF bundle directory`},args:{path:{type:`positional`,required:!0,description:`OKF bundle directory.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=E(e.path);if(!t)throw Error(`Pass an OKF bundle directory.`);let n=vt(await Do(t));if(n.valid||(process.exitCode=1),N(e)){R(n);return}cs(t,n)}}),explain:C({meta:{name:`explain`,description:`Explain OKF validation results in plain English`},args:{path:{type:`positional`,required:!0,description:`OKF bundle directory.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=E(e.path);if(!t)throw Error(`Pass an OKF bundle directory.`);let n=$e(vt(await Do(t)));if(n.valid||(process.exitCode=1),N(e)){R(n);return}if(process.stdout.write(`${n.summary}\n\n`),z([[`Valid`,n.valid?`yes`:`no`],[`Files`,String(n.files)],[`Concepts`,String(n.concepts)],[`Errors`,String(n.errors)],[`Warnings`,String(n.warnings)]]),n.nextActions.length){process.stdout.write(`
210
+ `),V([`Severity`,`Path`,`Message`],t.issues.slice(0,25).map(e=>[e.severity,e.path,e.message])))}const tc=w({meta:{name:`okf`,description:`Export, validate, and explain OKF site knowledge bundles`},subCommands:{export:w({meta:{name:`export`,description:`Export a saved crawl as an OKF bundle`},args:{"report-id":{type:`string`,description:`Saved crawl report id to export.`},site:{type:`string`,description:`GSC property URL for selecting the latest saved crawl.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},output:{type:`string`,description:`Output directory. Defaults to ./okf.`},"max-concepts":{type:`string`,description:`Maximum concept files to export. Defaults to 500.`},title:{type:`string`,description:`Override the root bundle title.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=ne(j(e[`max-concepts`],`--max-concepts`)),r=ye(await Ri(e,{json:t}),{maxConcepts:n,title:D(e.title)}),i=D(e.output)??`./okf`,a=await gs(i,r.files);if(t){z({output:i,bundle:r,validation:a});return}process.stdout.write(`Wrote OKF bundle to ${i}\n\n`),B([[`Files`,String(r.files.length)],[`Concepts`,String(r.conceptCount)],[`Valid`,a.valid?`yes`:`no`]])}}),validate:w({meta:{name:`validate`,description:`Validate an OKF bundle directory`},args:{path:{type:`positional`,required:!0,description:`OKF bundle directory.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=D(e.path);if(!t)throw Error(`Pass an OKF bundle directory.`);let n=oe(await ms(t));if(n.valid||(process.exitCode=1),P(e)){z(n);return}ec(t,n)}}),explain:w({meta:{name:`explain`,description:`Explain OKF validation results in plain English`},args:{path:{type:`positional`,required:!0,description:`OKF bundle directory.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=D(e.path);if(!t)throw Error(`Pass an OKF bundle directory.`);let n=Te(oe(await ms(t)));if(n.valid||(process.exitCode=1),P(e)){z(n);return}if(process.stdout.write(`${n.summary}\n\n`),B([[`Valid`,n.valid?`yes`:`no`],[`Files`,String(n.files)],[`Concepts`,String(n.concepts)],[`Errors`,String(n.errors)],[`Warnings`,String(n.warnings)]]),n.nextActions.length){process.stdout.write(`
107
211
  Next actions
108
- `);for(let e of n.nextActions)process.stdout.write(`- ${e}\n`)}}})}}),us=C({meta:{name:`ai-referrals`,description:`Find AI referral traffic detected in Google Analytics`},args:{property:{type:`string`,description:`Google Analytics property ID. If omitted in a terminal, choose one.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name with an optional Google Analytics property.`},"start-date":{type:`string`,default:`28daysAgo`},"end-date":{type:`string`,default:`yesterday`},"max-rows":{type:`string`,description:`Maximum Google Analytics rows per query. Defaults to 100000.`},"result-limit":{type:`string`,description:`Maximum ranked landing pages returned. Defaults to 25.`},limit:{type:`string`,description:`Legacy alias for --max-rows.`},refresh:{type:`boolean`,default:!1,description:`Bypass cached Google Analytics responses.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=await Qr({client:D(e),options:{json:t}}),r=await Ye({property:await $r({property:E(e.property)??n?.analytics.google?.propertyId,options:{json:t}}),startDate:E(e[`start-date`]),endDate:E(e[`end-date`]),maxRows:A(e[`max-rows`],`--max-rows`),resultLimit:A(e[`result-limit`],`--result-limit`),limit:A(e.limit,`--limit`),refresh:e.refresh===!0});if(t){R(r);return}if(z([[`Property`,r.property],[`Evidence`,r.dataStatus===`complete`?`Complete`:`Partial`],[`Verdict`,r.summary.verdict],[`AI sessions`,W(r.summary.sessions)],[`AI users`,r.summary.totalUsers===null?`Unavailable`:W(r.summary.totalUsers)],[`Sources`,W(r.summary.sources)],[`Landing pages`,W(r.summary.landingPages)],[`Landing-page output`,`${W(r.selection.landingPages.returnedRows)} returned / ${W(r.selection.landingPages.retainedRows)} retained`],[`Source rows`,W(r.dataSource.sourceDiscovery.returnedRows)]]),r.sources.length&&(process.stdout.write(`
212
+ `);for(let e of n.nextActions)process.stdout.write(`- ${e}\n`)}}})}}),nc=w({meta:{name:`ai-referrals`,description:`Find AI referral traffic detected in Google Analytics`},args:{property:{type:`string`,description:`Google Analytics property ID. If omitted in a terminal, choose one.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name with an optional Google Analytics property.`},"start-date":{type:`string`,default:`28daysAgo`},"end-date":{type:`string`,default:`yesterday`},"max-rows":{type:`string`,description:`Maximum Google Analytics rows per query. Defaults to 100000.`},"result-limit":{type:`string`,description:`Maximum ranked landing pages returned. Defaults to 25.`},limit:{type:`string`,description:`Legacy alias for --max-rows.`},refresh:{type:`boolean`,default:!1,description:`Bypass cached Google Analytics responses.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=await Ni({client:O(e),options:{json:t}}),r=await Me({property:await Pi({property:D(e.property)??n?.analytics.google?.propertyId,options:{json:t}}),startDate:D(e[`start-date`]),endDate:D(e[`end-date`]),maxRows:j(e[`max-rows`],`--max-rows`),resultLimit:j(e[`result-limit`],`--result-limit`),limit:j(e.limit,`--limit`),refresh:e.refresh===!0});if(t){z(r);return}if(B([[`Property`,r.property],[`Evidence`,r.dataStatus===`complete`?`Complete`:`Partial`],[`Verdict`,r.summary.verdict],[`AI sessions`,W(r.summary.sessions)],[`AI users`,r.summary.totalUsers===null?`Unavailable`:W(r.summary.totalUsers)],[`Sources`,W(r.summary.sources)],[`Landing pages`,W(r.summary.landingPages)],[`Landing-page output`,`${W(r.selection.landingPages.returnedRows)} returned / ${W(r.selection.landingPages.retainedRows)} retained`],[`Source rows`,W(r.dataSource.sourceDiscovery.returnedRows)]]),r.sources.length&&(process.stdout.write(`
109
213
  AI sources
110
214
  `),q([`Source`,`Sessions`,`Events`,`Share of AI sessions`],r.sources.map(e=>[e.label,W(e.sessions),W(e.eventCount),G(e.shareOfAiSessions)]))),r.landingPages.length&&(process.stdout.write(`
111
215
  Landing pages
112
216
  `),q([`Landing page`,`Sessions`,`Events`,`Top source`],r.landingPages.map(e=>[K(e.landingPage,64),W(e.sessions),W(e.eventCount),e.topSourceDetails.label]))),r.dataSource.partialReasons.length){process.stdout.write(`
113
217
  Evidence warnings
114
- `);for(let e of r.dataSource.partialReasons)process.stdout.write(`- ${e}\n`)}process.stdout.write(`\nNote: ${r.summary.caveat}\n`)}}),ds=C({meta:{name:`cannibal`,description:`Find queries with material exposure across multiple URLs`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`limit`,`includeBrand`,`minImpressions`,`refresh`],{minImpressions:{description:`Minimum query impressions. Defaults to 50.`}}),"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=O(e.refresh),r=await U({client:D(e),site:E(e.site),options:{json:t,refresh:n}}),i=await Ge({site:r.site,days:A(e.days,`--days`),limit:A(e.limit,`--limit`),minImpressions:A(e[`min-impressions`],`--min-impressions`),brandTerms:[...r.client?.brandTerms??[],...j(e[`brand-terms`])??[]],includeBrand:O(e[`include-brand`]),refresh:n});if(t){R(i);return}z([[`Site`,i.site],[`Status`,i.dataStatus],[`Range`,`${i.range.startDate} to ${i.range.endDate}`],[`Eligible candidates`,W(i.summary.eligibleClusters)],[`Returned candidates`,W(i.summary.returnedClusters)],[`Suppressed brand queries`,W(i.summary.suppressedQueries)],[`GSC completeness`,i.source.completeness],[`Brand queries`,O(e[`include-brand`])?`included`:`excluded`],[`Verdict`,i.summary.verdict]]),q([`Query`,`URLs`,`Property impr`,`Exposure`,`HHI`,`Review first`],i.items.map(e=>[K(e.query,42),e.pages.length,e.propertyImpressions===void 0?`n/a`:W(e.propertyImpressions),W(e.pageExposureImpressions),e.hhi.toFixed(2),K(e.suggestedOwnerUrl,56)])),J(`Top cannibalisation actions`,i.items.map(e=>({label:e.query,context:`${e.pages.length} material URLs; first review ${K(e.suggestedOwnerUrl,64)}`,action:e.recommendation.action}))),Y(`Report caveats`,i.caveats),Y(`Provider usage`,[i.ledgerSummary])}}),fs=C({meta:{name:`community-intent`,description:`Find GSC queries with forum, review, and comparison intent`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},"start-date":{type:`string`,description:`Exact GSC start date (YYYY-MM-DD). Use with --end-date.`},"end-date":{type:`string`,description:`Exact GSC end date (YYYY-MM-DD). Use with --start-date.`},"max-rows":{type:`string`,description:`Maximum retained GSC query rows. Defaults to 50000.`},"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},...X([`days`,`limit`,`minImpressions`,`includeBrand`,`refresh`],{days:{description:`GSC lookback within the current 16-month retention.`},limit:{description:`Maximum intent queries to print. Defaults to 25.`},minImpressions:{description:`Minimum query impressions. Defaults to 20.`},includeBrand:{description:`Include branded queries in community-intent reports.`},refresh:{description:`Bypass local GSC cache.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),r=await ie({site:n.site,days:A(e.days,`--days`),startDate:E(e[`start-date`]),endDate:E(e[`end-date`]),limit:A(e.limit,`--limit`),minImpressions:A(e[`min-impressions`],`--min-impressions`),maxRows:A(e[`max-rows`],`--max-rows`),brandTerms:[...n.client?.brandTerms??[],...j(e[`brand-terms`])??[]],includeBrand:O(e[`include-brand`]),refresh:O(e.refresh)});if(t){R(r);return}z([[`Property`,r.site],[`Status`,r.dataStatus],[`Verdict`,r.summary.verdict],[`Classified queries`,W(r.summary.classifiedQueries)],[`Returned queries`,W(r.summary.returnedQueries)],[`Returned impressions`,W(r.summary.returnedImpressions)],[`Returned clicks`,W(r.summary.returnedClicks)],[`GSC completeness`,r.source.completeness]]),q([`Intent`,`Query`,`Impr`,`Clicks`,`Confidence`,`Action`],r.items.map(e=>[e.intent,K(e.query,42),W(e.impressions),W(e.clicks),e.confidence,K(e.action,76)])),J(`Top community-intent actions`,r.items.map(e=>({label:e.query,context:`${e.intent}, ${W(e.impressions)} impressions`,action:e.action}))),Y(`Report caveats`,r.caveats),Y(`Warnings`,r.warnings)}}),ps=C({meta:{name:`ctr-underperformers`,description:`Find high-impression queries with weak CTR for their position`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`includeBrand`,`minImpressions`],{minImpressions:{description:`Minimum query impressions. Defaults to 200.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t}}),r=await zt({site:n.site,minImpressions:k(e[`min-impressions`]),brandTerms:n.client?.brandTerms,includeBrand:O(e[`include-brand`])});if(t){R(r);return}z([[`Site`,r.site],[`Underperformers`,W(r.summary.underperformers)],[`Estimated click gap`,W(r.summary.estimatedClickShortfall)],[`Brand queries`,r.summary.brandFiltering],[`Verdict`,r.summary.verdict]]),Y(`Why this matters`,[`These queries already have visibility; the fastest win is usually better SERP framing, not new content.`,`Start with high-impression rows where actual CTR is far below the expected CTR for that ranking position.`]),Y(`Recommended actions`,r.recommendations),Y(`Report caveats`,r.caveats),q([`Query`,`URL`,`Pos`,`Impr`,`CTR`,`Expected`,`Gap`,`Action`],r.items.map(e=>[K(e.query,36),K(e.url,48),ei(e.position),W(e.impressions),G(e.actualCtr),G(e.expectedCtr),W(e.clickShortfall),K(e.recommendation.action,72)])),J(`Top CTR actions`,r.items.map(e=>({label:e.query,context:`${W(e.clickShortfall)} click gap, ${G(e.actualCtr)} CTR`,action:e.recommendation.action})))}});function ms(e){return e>0?ei(e):`n/a`}const hs=C({meta:{name:`decaying`,description:`Find query/page rows losing clicks between two GSC windows`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`limit`,`includeBrand`,`refresh`]),comparison:{type:`string`,description:`Comparison: previous-period or year-over-year.`},"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},"min-drop-pct":{type:`string`,description:`Minimum click drop percentage. Defaults to 20.`},"min-previous-clicks":{type:`string`,description:`Minimum previous-window clicks for a query/page row. Defaults to 2.`},"min-click-loss":{type:`string`,description:`Minimum absolute click loss. Defaults to 1.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=O(e.refresh),r=E(e.comparison),i=A(e.days,`--days`),a=A(e.limit,`--limit`),o=A(e[`min-drop-pct`],`--min-drop-pct`),s=A(e[`min-previous-clicks`],`--min-previous-clicks`),c=A(e[`min-click-loss`],`--min-click-loss`);if(r!==void 0&&r!==`previous-period`&&r!==`year-over-year`)throw new y(`INVALID_INPUT`,`--comparison must be previous-period or year-over-year.`);let l=await U({client:D(e),site:E(e.site),options:{json:t,refresh:n}}),u=await Nt({site:l.site,days:i,limit:a,comparison:r,brandTerms:[...l.client?.brandTerms??[],...j(e[`brand-terms`])??[]],includeBrand:O(e[`include-brand`]),minDropPct:o,minPreviousClicks:s,minClickLoss:c,refresh:n});if(t){R(u);return}z([[`Site`,u.site],[`Status`,u.dataStatus],[`Comparison`,u.comparison],[`Observed query/page declines`,W(u.summary.returnedRows)],[`Eligible declines`,W(u.summary.eligibleRows)],[`Decay clusters`,W(u.summary.groups)],[`Eligible observed click decline`,W(u.summary.observedRetainedQueryClickLoss)],[`Returned observed click decline`,W(u.summary.returnedObservedRetainedQueryClickLoss)],[`Brand queries`,u.summary.brandFiltering],[`Min drop`,`${u.filters.minDropPct}%`],[`Min previous clicks`,W(u.filters.minPreviousClicks)],[`GSC completeness`,u.source.completeness],[`Verdict`,u.summary.verdict]]),Y(`Why this matters`,[`This report compares retained query/page rows and only counts declines observed in both windows.`,`Position, CTR, and impression movements are signals for investigation, not proof of cause.`]),Y(`Recommended actions`,u.recommendations),Y(`Report caveats`,u.caveats),Y(`Warnings`,u.warnings),u.items.length&&(u.groups.length&&(q([`Cluster`,`Rows`,`Observed loss`,`Drop`,`Sample query`,`Action`],u.groups.map(e=>[K(e.label,42),W(e.count),W(e.totalClickLoss),`${e.averageDropPct.toFixed(1)}%`,K(e.sampleQueries[0]??`-`,40),K(e.recommendation,72)])),J(`Top decay cluster actions`,u.groups.map(e=>({label:e.label,context:`${W(e.count)} retained rows, ${W(e.totalClickLoss)} observed click decline`,action:e.recommendation})))),q([`Query`,`Template`,`URL`,`Signals`,`Decline`,`Clicks`,`Impr`,`CTR`,`Pos`,`Action`],u.items.map(e=>[K(e.query,32),K(e.template.label,26),K(e.url,44),e.signals.join(`, `),W(e.clickLoss),`${W(e.previous.clicks)} -> ${W(e.current.clicks)}`,`${W(e.previous.impressions)} -> ${W(e.current.impressions)}`,`${G(e.previous.ctr)} -> ${G(e.current.ctr)}`,`${ms(e.previous.position)} -> ${ms(e.current.position)}`,K(e.recommendation.action,64)])),J(`Top decay actions`,u.items.map(e=>({label:e.query,context:`${e.template.label}, ${W(e.clickLoss)} fewer observed clicks`,action:e.recommendation.action}))))}}),gs=C({meta:{name:`internal-links`,description:`Find verified internal-link review candidates for one URL`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},url:{type:`string`,required:!0,description:`Target page that should receive relevant internal links.`},...X([`days`,`limit`,`checkLimit`,`minImpressions`,`includeBrand`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=O(e.refresh),r=A(e.days,`--days`),i=A(e.limit,`--limit`),a=A(e[`check-limit`],`--check-limit`),o=A(e[`min-impressions`],`--min-impressions`),s=fr(e),c=await U({client:D(e),site:E(e.site),options:{json:t,refresh:n}}),l=await Dt({site:c.site,targetUrl:E(e.url)??``,days:r,limit:i,checkLimit:a,minImpressions:o,brandTerms:[...c.client?.brandTerms??[],...j(e[`brand-terms`])??[]],includeBrand:O(e[`include-brand`]),js:O(e.js)?!0:void 0,rate:s,refresh:n});if(t){R(l);return}z([[`Site`,l.site],[`Target`,l.targetUrl],[`Preferred target`,l.target.preferredUrl],[`Target state`,l.target.verification],[`Target queries`,W(l.summary.targetQueries)],[`Matched sources`,W(l.summary.candidateSources)],[`Attempted sources`,W(l.summary.attemptedSources)],[`Checked sources`,W(l.summary.checkedSources)],[`Review candidates`,W(l.summary.returnedSources)],[`Existing contextual links`,W(l.summary.existingLinksObserved)],[`Technical exclusions`,W(l.summary.technicalExclusions)],[`Failed checks`,W(l.summary.failedChecks)],[`Unchecked sources`,W(l.summary.uncheckedCandidates)],[`GSC completeness`,l.source.completeness],[`Brand queries`,l.summary.brandFiltering],[`Verdict`,l.summary.verdict]]),Y(`Why this matters`,[`Exact-query overlap is useful affinity evidence; precision lexical matches are review evidence only.`,`Source and target pages are checked for redirects, indexability, canonicals, and existing link placement before an action is returned.`]),Y(`Recommended actions`,l.recommendations),Y(`Report caveats`,l.caveats),l.items.length&&(q([`Source URL`,`Matched impr`,`Match`,`Link evidence`,`Action`],l.items.map(e=>[K(e.sourceUrl,52),W(e.matchedQueryImpressions),e.bestMatchKind,e.linkEvidence.status,e.actionType])),J(`Top internal-link reviews`,l.items.map(e=>({label:K(e.sourceUrl,96),context:`${W(e.matchedQueryImpressions)} matched-query impressions; ${e.bestMatchKind}`,action:e.recommendation.action}))),Y(`Provider usage`,[l.ledgerSummary]))}}),_s=C({meta:{name:`page-opportunities`,description:`Find first-party traffic growth opportunities for one URL`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},url:{type:`string`,required:!0},...X([`days`,`limit`,`minImpressions`,`includeBrand`,`js`,`refresh`],{limit:{description:`Maximum page queries to inspect. Defaults to 25.`},minImpressions:{description:`Minimum query impressions. Defaults to 10.`},includeBrand:{description:`Include branded queries in page opportunity reports.`},js:{description:`Force JavaScript rendering for page extraction.`},refresh:{description:`Bypass local GSC and HTTP cache.`}}),"verify-content":T(`Fetch the page for title/H1/body checks. Defaults to true.`,`Skip fetching the page for title/H1/body checks.`),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),r=await h({site:n.site,url:E(e.url)??``,days:k(e.days),limit:k(e.limit),minImpressions:k(e[`min-impressions`]),brandTerms:n.client?.brandTerms,includeBrand:O(e[`include-brand`]),verifyContent:O(e[`verify-content`])!==!1,js:O(e.js)?!0:`auto`,refresh:O(e.refresh)});if(t){R(r);return}if(z([[`Property`,r.site],[`URL`,r.url],[`Title`,r.page?.title??`not fetched`],[`Fetch`,Si(r.page?.fetchDiagnostics)],[`Verification`,r.verification.status],[`Rows`,`${W(r.selection.returnedRows)} returned / ${W(r.selection.eligibleRows)} eligible / ${W(r.selection.sourceRows)} source`],[`Queries`,W(r.summary.queries)],[`Impressions`,W(r.summary.impressions)],[`Opportunities`,W(r.summary.opportunities)],[`CTR shortfall`,W(r.summary.estimatedCtrClickShortfall)],[`Focus`,r.summary.focus],[`Verdict`,r.summary.verdict]]),Y(`Why this matters`,[`This report starts from queries where this exact URL already has impressions, so recommendations stay tied to first-party demand.`,`Content verification separates body gaps from title/meta framing issues, which helps avoid adding copy when the page already covers the query.`]),Y(`Recommended actions`,r.recommendations),Y(`Report caveats`,r.caveats),!r.items.length){process.stdout.write(r.dataStatus===`empty`?`No GSC query rows found for this exact URL.
218
+ `);for(let e of r.dataSource.partialReasons)process.stdout.write(`- ${e}\n`)}process.stdout.write(`\nNote: ${r.summary.caveat}\n`)}}),rc=w({meta:{name:`cannibal`,description:`Find queries with material exposure across multiple URLs`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`limit`,`includeBrand`,`minImpressions`,`refresh`],{minImpressions:{description:`Minimum query impressions. Defaults to 50.`}}),"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=k(e.refresh),r=await U({client:O(e),site:D(e.site),options:{json:t,refresh:n}}),a=await i({site:r.site,days:j(e.days,`--days`),limit:j(e.limit,`--limit`),minImpressions:j(e[`min-impressions`],`--min-impressions`),brandTerms:[...r.client?.brandTerms??[],...M(e[`brand-terms`])??[]],includeBrand:k(e[`include-brand`]),refresh:n});if(t){z(a);return}B([[`Site`,a.site],[`Status`,a.dataStatus],[`Range`,`${a.range.startDate} to ${a.range.endDate}`],[`Eligible candidates`,W(a.summary.eligibleClusters)],[`Returned candidates`,W(a.summary.returnedClusters)],[`Suppressed brand queries`,W(a.summary.suppressedQueries)],[`GSC completeness`,a.source.completeness],[`Brand queries`,k(e[`include-brand`])?`included`:`excluded`],[`Verdict`,a.summary.verdict]]),q([`Query`,`URLs`,`Property impr`,`Exposure`,`HHI`,`Review first`],a.items.map(e=>[K(e.query,42),e.pages.length,e.propertyImpressions===void 0?`n/a`:W(e.propertyImpressions),W(e.pageExposureImpressions),e.hhi.toFixed(2),K(e.suggestedOwnerUrl,56)])),J(`Top cannibalisation actions`,a.items.map(e=>({label:e.query,context:`${e.pages.length} material URLs; first review ${K(e.suggestedOwnerUrl,64)}`,action:e.recommendation.action}))),Y(`Report caveats`,a.caveats),Y(`Provider usage`,[a.ledgerSummary])}}),ic=w({meta:{name:`community-intent`,description:`Find GSC queries with forum, review, and comparison intent`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},"start-date":{type:`string`,description:`Exact GSC start date (YYYY-MM-DD). Use with --end-date.`},"end-date":{type:`string`,description:`Exact GSC end date (YYYY-MM-DD). Use with --start-date.`},"max-rows":{type:`string`,description:`Maximum retained GSC query rows. Defaults to 50000.`},"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},...X([`days`,`limit`,`minImpressions`,`includeBrand`,`refresh`],{days:{description:`GSC lookback within the current 16-month retention.`},limit:{description:`Maximum intent queries to print. Defaults to 25.`},minImpressions:{description:`Minimum query impressions. Defaults to 20.`},includeBrand:{description:`Include branded queries in community-intent reports.`},refresh:{description:`Bypass local GSC cache.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),r=await It({site:n.site,days:j(e.days,`--days`),startDate:D(e[`start-date`]),endDate:D(e[`end-date`]),limit:j(e.limit,`--limit`),minImpressions:j(e[`min-impressions`],`--min-impressions`),maxRows:j(e[`max-rows`],`--max-rows`),brandTerms:[...n.client?.brandTerms??[],...M(e[`brand-terms`])??[]],includeBrand:k(e[`include-brand`]),refresh:k(e.refresh)});if(t){z(r);return}B([[`Property`,r.site],[`Status`,r.dataStatus],[`Verdict`,r.summary.verdict],[`Classified queries`,W(r.summary.classifiedQueries)],[`Returned queries`,W(r.summary.returnedQueries)],[`Returned impressions`,W(r.summary.returnedImpressions)],[`Returned clicks`,W(r.summary.returnedClicks)],[`GSC completeness`,r.source.completeness]]),q([`Intent`,`Query`,`Impr`,`Clicks`,`Confidence`,`Action`],r.items.map(e=>[e.intent,K(e.query,42),W(e.impressions),W(e.clicks),e.confidence,K(e.action,76)])),J(`Top community-intent actions`,r.items.map(e=>({label:e.query,context:`${e.intent}, ${W(e.impressions)} impressions`,action:e.action}))),Y(`Report caveats`,r.caveats),Y(`Warnings`,r.warnings)}}),ac=w({meta:{name:`ctr-underperformers`,description:`Find high-impression queries with weak CTR for their position`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`includeBrand`,`minImpressions`],{minImpressions:{description:`Minimum query impressions. Defaults to 200.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t}}),r=await ge({site:n.site,minImpressions:A(e[`min-impressions`]),brandTerms:n.client?.brandTerms,includeBrand:k(e[`include-brand`])});if(t){z(r);return}B([[`Site`,r.site],[`Underperformers`,W(r.summary.underperformers)],[`Estimated click gap`,W(r.summary.estimatedClickShortfall)],[`Brand queries`,r.summary.brandFiltering],[`Verdict`,r.summary.verdict]]),Y(`Why this matters`,[`These queries already have visibility; the fastest win is usually better SERP framing, not new content.`,`Start with high-impression rows where actual CTR is far below the expected CTR for that ranking position.`]),Y(`Recommended actions`,r.recommendations),Y(`Report caveats`,r.caveats),q([`Query`,`URL`,`Pos`,`Impr`,`CTR`,`Expected`,`Gap`,`Action`],r.items.map(e=>[K(e.query,36),K(e.url,48),Fi(e.position),W(e.impressions),G(e.actualCtr),G(e.expectedCtr),W(e.clickShortfall),K(e.recommendation.action,72)])),J(`Top CTR actions`,r.items.map(e=>({label:e.query,context:`${W(e.clickShortfall)} click gap, ${G(e.actualCtr)} CTR`,action:e.recommendation.action})))}});function oc(e){return e>0?Fi(e):`n/a`}const sc=w({meta:{name:`decaying`,description:`Find query/page rows losing clicks between two GSC windows`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`limit`,`includeBrand`,`refresh`]),comparison:{type:`string`,description:`Comparison: previous-period or year-over-year.`},"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},"min-drop-pct":{type:`string`,description:`Minimum click drop percentage. Defaults to 20.`},"min-previous-clicks":{type:`string`,description:`Minimum previous-window clicks for a query/page row. Defaults to 2.`},"min-click-loss":{type:`string`,description:`Minimum absolute click loss. Defaults to 1.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=k(e.refresh),r=D(e.comparison),i=j(e.days,`--days`),a=j(e.limit,`--limit`),o=j(e[`min-drop-pct`],`--min-drop-pct`),s=j(e[`min-previous-clicks`],`--min-previous-clicks`),c=j(e[`min-click-loss`],`--min-click-loss`);if(r!==void 0&&r!==`previous-period`&&r!==`year-over-year`)throw new b(`INVALID_INPUT`,`--comparison must be previous-period or year-over-year.`);let l=await U({client:O(e),site:D(e.site),options:{json:t,refresh:n}}),u=await jt({site:l.site,days:i,limit:a,comparison:r,brandTerms:[...l.client?.brandTerms??[],...M(e[`brand-terms`])??[]],includeBrand:k(e[`include-brand`]),minDropPct:o,minPreviousClicks:s,minClickLoss:c,refresh:n});if(t){z(u);return}B([[`Site`,u.site],[`Status`,u.dataStatus],[`Comparison`,u.comparison],[`Observed query/page declines`,W(u.summary.returnedRows)],[`Eligible declines`,W(u.summary.eligibleRows)],[`Decay clusters`,W(u.summary.groups)],[`Eligible observed click decline`,W(u.summary.observedRetainedQueryClickLoss)],[`Returned observed click decline`,W(u.summary.returnedObservedRetainedQueryClickLoss)],[`Brand queries`,u.summary.brandFiltering],[`Min drop`,`${u.filters.minDropPct}%`],[`Min previous clicks`,W(u.filters.minPreviousClicks)],[`GSC completeness`,u.source.completeness],[`Verdict`,u.summary.verdict]]),Y(`Why this matters`,[`This report compares retained query/page rows and only counts declines observed in both windows.`,`Position, CTR, and impression movements are signals for investigation, not proof of cause.`]),Y(`Recommended actions`,u.recommendations),Y(`Report caveats`,u.caveats),Y(`Warnings`,u.warnings),u.items.length&&(u.groups.length&&(q([`Cluster`,`Rows`,`Observed loss`,`Drop`,`Sample query`,`Action`],u.groups.map(e=>[K(e.label,42),W(e.count),W(e.totalClickLoss),`${e.averageDropPct.toFixed(1)}%`,K(e.sampleQueries[0]??`-`,40),K(e.recommendation,72)])),J(`Top decay cluster actions`,u.groups.map(e=>({label:e.label,context:`${W(e.count)} retained rows, ${W(e.totalClickLoss)} observed click decline`,action:e.recommendation})))),q([`Query`,`Template`,`URL`,`Signals`,`Decline`,`Clicks`,`Impr`,`CTR`,`Pos`,`Action`],u.items.map(e=>[K(e.query,32),K(e.template.label,26),K(e.url,44),e.signals.join(`, `),W(e.clickLoss),`${W(e.previous.clicks)} -> ${W(e.current.clicks)}`,`${W(e.previous.impressions)} -> ${W(e.current.impressions)}`,`${G(e.previous.ctr)} -> ${G(e.current.ctr)}`,`${oc(e.previous.position)} -> ${oc(e.current.position)}`,K(e.recommendation.action,64)])),J(`Top decay actions`,u.items.map(e=>({label:e.query,context:`${e.template.label}, ${W(e.clickLoss)} fewer observed clicks`,action:e.recommendation.action}))))}}),cc=w({meta:{name:`internal-links`,description:`Find verified internal-link review candidates for one URL`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},url:{type:`string`,required:!0,description:`Target page that should receive relevant internal links.`},...X([`days`,`limit`,`checkLimit`,`minImpressions`,`includeBrand`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=k(e.refresh),r=j(e.days,`--days`),i=j(e.limit,`--limit`),a=j(e[`check-limit`],`--check-limit`),o=j(e[`min-impressions`],`--min-impressions`),s=Kr(e),c=await U({client:O(e),site:D(e.site),options:{json:t,refresh:n}}),l=await St({site:c.site,targetUrl:D(e.url)??``,days:r,limit:i,checkLimit:a,minImpressions:o,brandTerms:[...c.client?.brandTerms??[],...M(e[`brand-terms`])??[]],includeBrand:k(e[`include-brand`]),js:k(e.js)?!0:void 0,rate:s,refresh:n});if(t){z(l);return}B([[`Site`,l.site],[`Target`,l.targetUrl],[`Preferred target`,l.target.preferredUrl],[`Target state`,l.target.verification],[`Target queries`,W(l.summary.targetQueries)],[`Matched sources`,W(l.summary.candidateSources)],[`Attempted sources`,W(l.summary.attemptedSources)],[`Checked sources`,W(l.summary.checkedSources)],[`Review candidates`,W(l.summary.returnedSources)],[`Existing contextual links`,W(l.summary.existingLinksObserved)],[`Technical exclusions`,W(l.summary.technicalExclusions)],[`Failed checks`,W(l.summary.failedChecks)],[`Unchecked sources`,W(l.summary.uncheckedCandidates)],[`GSC completeness`,l.source.completeness],[`Brand queries`,l.summary.brandFiltering],[`Verdict`,l.summary.verdict]]),Y(`Why this matters`,[`Exact-query overlap is useful affinity evidence; precision lexical matches are review evidence only.`,`Source and target pages are checked for redirects, indexability, canonicals, and existing link placement before an action is returned.`]),Y(`Recommended actions`,l.recommendations),Y(`Report caveats`,l.caveats),l.items.length&&(q([`Source URL`,`Matched impr`,`Match`,`Link evidence`,`Action`],l.items.map(e=>[K(e.sourceUrl,52),W(e.matchedQueryImpressions),e.bestMatchKind,e.linkEvidence.status,e.actionType])),J(`Top internal-link reviews`,l.items.map(e=>({label:K(e.sourceUrl,96),context:`${W(e.matchedQueryImpressions)} matched-query impressions; ${e.bestMatchKind}`,action:e.recommendation.action}))),Y(`Provider usage`,[l.ledgerSummary]))}}),lc=w({meta:{name:`page-opportunities`,description:`Find first-party traffic growth opportunities for one URL`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},url:{type:`string`,required:!0},...X([`days`,`limit`,`minImpressions`,`includeBrand`,`js`,`refresh`],{limit:{description:`Maximum page queries to inspect. Defaults to 25.`},minImpressions:{description:`Minimum query impressions. Defaults to 10.`},includeBrand:{description:`Include branded queries in page opportunity reports.`},js:{description:`Force JavaScript rendering for page extraction.`},refresh:{description:`Bypass local GSC and HTTP cache.`}}),"verify-content":Br(`Fetch the page for title/H1/body checks. Defaults to true.`,`Skip fetching the page for title/H1/body checks.`),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),r=await Wt({site:n.site,url:D(e.url)??``,days:A(e.days),limit:A(e.limit),minImpressions:A(e[`min-impressions`]),brandTerms:n.client?.brandTerms,includeBrand:k(e[`include-brand`]),verifyContent:k(e[`verify-content`])!==!1,js:k(e.js)?!0:`auto`,refresh:k(e.refresh)});if(t){z(r);return}if(B([[`Property`,r.site],[`URL`,r.url],[`Title`,r.page?.title??`not fetched`],[`Fetch`,ra(r.page?.fetchDiagnostics)],[`Verification`,r.verification.status],[`Rows`,`${W(r.selection.returnedRows)} returned / ${W(r.selection.eligibleRows)} eligible / ${W(r.selection.sourceRows)} source`],[`Queries`,W(r.summary.queries)],[`Impressions`,W(r.summary.impressions)],[`Opportunities`,W(r.summary.opportunities)],[`CTR shortfall`,W(r.summary.estimatedCtrClickShortfall)],[`Focus`,r.summary.focus],[`Verdict`,r.summary.verdict]]),Y(`Why this matters`,[`This report starts from queries where this exact URL already has impressions, so recommendations stay tied to first-party demand.`,`Content verification separates body gaps from title/meta framing issues, which helps avoid adding copy when the page already covers the query.`]),Y(`Recommended actions`,r.recommendations),Y(`Report caveats`,r.caveats),!r.items.length){process.stdout.write(r.dataStatus===`empty`?`No GSC query rows found for this exact URL.
115
219
  `:`GSC rows were found, but none met the report criteria.
116
- `);return}q([`Type`,`Query`,`Evidence`,`Pos`,`CTR`,`Expected`,`Impr`,`Shortfall`,`Action`],r.items.map(e=>[e.opportunityType,K(e.query,38),e.verification.signals.length?e.verification.signals.join(`, `):e.verification.status,e.position.toFixed(1),G(e.ctr),e.expectedCtr===void 0?`n/a`:G(e.expectedCtr),W(e.impressions),e.estimatedCtrClickShortfall===void 0?`n/a`:W(e.estimatedCtrClickShortfall),K(e.recommendation,72)])),J(`Top page actions`,r.items.map(e=>({label:e.query,context:`${e.opportunityType}, ${W(e.impressions)} impressions`,action:e.recommendation})))}}),vs=C({meta:{name:`query-cluster`,description:`Cluster GSC queries into repeated demand themes`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},scope:{type:`string`},...X([`includeBrand`,`minImpressions`,`limit`],{includeBrand:{description:`Include branded queries in query clustering.`},minImpressions:{description:`Minimum impressions per query. Defaults to 25.`},limit:{description:`Maximum clusters to return. Defaults to 25; max 100.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t}}),r=await f({site:n.site,scope:E(e.scope),brand:n.client?.brandTerms?.[0],brandTerms:n.client?.brandTerms,includeBrand:O(e[`include-brand`]),minImpressions:k(e[`min-impressions`]),limit:k(e.limit)});if(t){R(r);return}z([[`Site`,r.site],[`Scope`,r.scope??`all pages`],[`Clusters`,W(r.summary.clusters)],[`Queries`,W(r.summary.queries)],[`Impressions`,W(r.summary.impressions)],[`Clicks`,W(r.summary.clicks)],[`Minimum impressions`,W(r.summary.minImpressions)],[`Result limit`,W(r.summary.limit)],[`Brand queries`,r.summary.brandFiltering],[`High-opportunity clusters`,W(r.summary.highOpportunityClusters)],[`Verdict`,r.summary.verdict]]),Y(`Why this matters`,[`Clusters show repeated demand themes, so they are better inputs for page sections, hubs, and templates than one-off query exports.`,`Prioritise clusters with high impressions and low clicks; they usually reveal unclear intent coverage or weak SERP framing.`]),Y(`Recommended actions`,r.recommendations),Y(`Report caveats`,r.caveats),q([`Cluster`,`Intent`,`Queries`,`Impr`,`CTR`,`Expected`,`Lift`,`Action`],r.clusters.map(e=>[K(e.label,32),e.intent,e.queries.length,W(e.totals?.impressions??0),G(e.totals?.ctr??0),G(e.benchmark?.expectedCtr??0),e.estimatedClickLift===void 0?`-`:W(e.estimatedClickLift),K(e.recommendation??``,72)])),J(`Top cluster actions`,r.clusters.map(e=>({label:e.label,context:`${W(e.totals?.impressions??0)} impressions, ${e.estimatedClickLift===void 0?`ranking opportunity`:`${W(e.estimatedClickLift)} estimated click lift`}`,action:e.recommendation??``})))}}),ys=C({meta:{name:`quick-wins`,description:`Find high-ranking low-CTR query/page opportunities`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`limit`,`includeBrand`,`minImpressions`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=k(e[`verify-limit`]),r=O(e[`verify-content`])===!0||n!==void 0,i=await U({client:D(e),site:E(e.site),options:{json:t}}),a=await Ct({site:i.site,days:k(e.days),limit:k(e.limit),minImpressions:k(e[`min-impressions`]),brandTerms:[...i.client?.brandTerms??[],...j(e[`brand-terms`])??[]],includeBrand:O(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:O(e.js)?!0:void 0,rate:dr(e),refresh:O(e.refresh)});if(t){R(a);return}z([[`Site`,a.site],[`Eligible rows`,W(a.summary.eligibleRows)],[`Returned rows`,W(a.summary.returnedRows)],[`Repeated-query clusters`,W(a.summary.repeatedQueryGroups)],[`Template patterns`,W(a.summary.templatePatterns)],[`CTR click shortfall`,W(a.summary.returnedEstimatedCtrClickShortfall)],[`Brand queries`,a.summary.brandFiltering],[`Verification`,ti(a)],[`Verdict`,a.summary.verdict]]),Y(`Why this matters`,[`These rows have GSC average positions from 4 to 10 and observed CTR below a site-peer or versioned fallback target.`,`Page evidence is needed before treating a CTR shortfall as a title, content, or technical finding.`]),Y(`Recommended actions`,a.recommendations),Y(`Report caveats`,a.caveats),a.items.length&&(a.templateRecommendations.length&&(q([`Template`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Action`],a.templateRecommendations.map(e=>[K(e.templateLabel,34),W(e.urlCount),W(e.rowCount),W(e.totalEstimatedCtrClickShortfall),W(e.totalImpressions),K(e.action,72)])),J(`Top template actions`,a.templateRecommendations.map(e=>({label:e.templateLabel,context:`${W(e.urlCount)} URLs, ${W(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:`${e.action} ${e.evidence}`})))),a.groups.length&&(q([`Cluster`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Sample URL`,`Action`],a.groups.map(e=>[K(e.label,44),W(e.urlCount),W(e.rowCount),W(e.totalEstimatedCtrClickShortfall),W(e.totalImpressions),K(e.sampleUrls[0]??`-`,46),K(e.recommendation,72)])),J(`Top cluster actions`,a.groups.map(e=>({label:e.label,context:`${W(e.urlCount)} URLs, ${W(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:e.recommendation})))),q([`Query`,`Template`,`URL`,`Pos`,`Impr`,`CTR / target`,`Shortfall`,`Fetch`,`Check`,`Action`],a.items.map(e=>[K(e.query,36),K(e.template.label,24),K(e.url,48),ei(e.position),W(e.impressions),`${G(e.ctr)} / ${G(e.targetCtr)}`,W(e.estimatedCtrClickShortfall),Si(e.contentVerification?.fetchDiagnostics),Ci(e.contentVerification?.classification),K(e.recommendation.action,64)])),J(`Top opportunity actions`,a.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${ei(e.position)}, ${W(e.impressions)} impressions`,action:e.recommendation.action}))))}}),bs=C({meta:{name:`second-page`,description:`Find URLs averaging positions above 10 through 20 in GSC`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`range`,`minImpressions`,`limit`,`includeBrand`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=k(e[`verify-limit`]),r=O(e[`verify-content`])===!0||n!==void 0,i=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),a=await se({site:i.site,range:k(e.days),minImpressions:k(e[`min-impressions`]),limit:E(e.limit)?Number(E(e.limit)):10,brandTerms:i.client?.brandTerms,includeBrand:O(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:O(e.js)?!0:void 0,rate:dr(e),refresh:O(e.refresh)});if(t){R(a);return}if(z([[`Site`,a.site],[`Eligible pages`,W(a.summary.eligiblePages)],[`Returned pages`,W(a.summary.returnedPages)],[`Eligible queries`,W(a.summary.eligibleQueries)],[`Eligible impressions`,W(a.summary.eligibleImpressions)],[`Content issues`,W(a.summary.contentIssues)],[`Technical issues`,W(a.summary.technicalIssues)],[`Fetch failures`,W(a.summary.fetchFailures)],[`Brand queries`,a.summary.brandFiltering],[`Verification`,ti(a)],[`Verdict`,a.summary.verdict]]),Y(`Recommended actions`,a.recommendations),Y(`Report caveats`,a.caveats),!a.items.length){process.stdout.write(`No average-position candidates matched this report.
117
- `),process.stdout.write(`${a.ledgerSummary}\n`);return}q([`Query`,`Template`,`Pos`,`Impr`,`CTR`,`Queries`,`Fetch`,`Check`,`Action`],a.items.map(e=>[e.primaryQuery,e.template.label,e.position.toFixed(1),Math.round(e.impressions),e.ctr.toFixed(3),W(e.queryCount),Si(e.fetchDiagnostics),Ci(e.contentVerification?.classification),e.recommendation.action])),J(`Top second-page actions`,a.items.map(e=>({label:e.primaryQuery,context:`${e.template.label}, pos ${ei(e.position)}, ${W(e.impressions)} impressions`,action:e.recommendation.action}))),process.stdout.write(`${a.ledgerSummary}\n`)}}),xs=C({meta:{name:`seo-to-ai-query`,description:`Convert GSC search queries into AI-style monitoring prompts`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},"start-date":{type:`string`,description:`Exact GSC start date (YYYY-MM-DD). Use with --end-date.`},"end-date":{type:`string`,description:`Exact GSC end date (YYYY-MM-DD). Use with --start-date.`},"max-rows":{type:`string`,description:`Maximum retained GSC query rows. Defaults to 50000.`},"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},...X([`days`,`limit`,`minImpressions`,`includeBrand`,`refresh`],{days:{description:`GSC lookback within the current 16-month retention.`},limit:{description:`Maximum source queries to convert. Defaults to 25.`},minImpressions:{description:`Minimum query impressions. Defaults to 20.`},includeBrand:{description:`Include branded queries in prompt generation.`},refresh:{description:`Bypass local GSC cache.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),r=await lt({site:n.site,days:A(e.days,`--days`),startDate:E(e[`start-date`]),endDate:E(e[`end-date`]),limit:A(e.limit,`--limit`),minImpressions:A(e[`min-impressions`],`--min-impressions`),maxRows:A(e[`max-rows`],`--max-rows`),brandTerms:[...n.client?.brandTerms??[],...j(e[`brand-terms`])??[]],includeBrand:O(e[`include-brand`]),refresh:O(e.refresh)});if(t){R(r);return}z([[`Property`,r.site],[`Status`,r.dataStatus],[`Verdict`,r.summary.verdict],[`Eligible queries`,W(r.summary.eligibleQueries)],[`Returned queries`,W(r.summary.returnedQueries)],[`Prompts`,W(r.summary.prompts)],[`GSC completeness`,r.source.completeness]]),q([`Query`,`Impr`,`Prompt`],r.items.flatMap(e=>e.prompts.map(t=>[K(e.query,42),W(e.impressions),K(t,86)]))),Y(`Report caveats`,r.caveats),Y(`Warnings`,r.warnings)}}),Ss=C({meta:{name:`audit-page`,description:`Fetch one page and audit title, metadata, content, links, and schema`},args:{url:{type:`string`,required:!0,description:`URL to audit.`},site:{type:`string`,description:`Optional GSC property for page search metrics, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for extraction.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache.`}},run:async({args:e})=>{let t=D(e),n=E(e.site),r=t?await Qr({project:t,options:{json:N(e)}}):void 0,i=t||n?void 0:await Qr({options:{json:N(e)}}),a=await Ne({url:E(e.url)??``,site:r?.siteUrl??n??i?.siteUrl,js:O(e.js)?!0:`auto`,refresh:O(e.refresh)});if(N(e)){R(a);return}z([[`URL`,a.url],[`Final URL`,a.page.finalUrl],[`Title`,a.page.title??`missing`],[`Meta description`,a.page.metaDescription??`missing`],[`Word count`,String(a.page.wordCount)],[`Fetch`,Si(a.fetchDiagnostics)]]),a.issues.length&&(process.stdout.write(`
220
+ `);return}q([`Type`,`Query`,`Evidence`,`Pos`,`CTR`,`Expected`,`Impr`,`Shortfall`,`Action`],r.items.map(e=>[e.opportunityType,K(e.query,38),e.verification.signals.length?e.verification.signals.join(`, `):e.verification.status,e.position.toFixed(1),G(e.ctr),e.expectedCtr===void 0?`n/a`:G(e.expectedCtr),W(e.impressions),e.estimatedCtrClickShortfall===void 0?`n/a`:W(e.estimatedCtrClickShortfall),K(e.recommendation,72)])),J(`Top page actions`,r.items.map(e=>({label:e.query,context:`${e.opportunityType}, ${W(e.impressions)} impressions`,action:e.recommendation})))}}),uc=w({meta:{name:`query-cluster`,description:`Cluster GSC queries into repeated demand themes`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},scope:{type:`string`},...X([`includeBrand`,`minImpressions`,`limit`],{includeBrand:{description:`Include branded queries in query clustering.`},minImpressions:{description:`Minimum impressions per query. Defaults to 25.`},limit:{description:`Maximum clusters to return. Defaults to 25; max 100.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t}}),r=await Xt({site:n.site,scope:D(e.scope),brand:n.client?.brandTerms?.[0],brandTerms:n.client?.brandTerms,includeBrand:k(e[`include-brand`]),minImpressions:A(e[`min-impressions`]),limit:A(e.limit)});if(t){z(r);return}B([[`Site`,r.site],[`Scope`,r.scope??`all pages`],[`Clusters`,W(r.summary.clusters)],[`Queries`,W(r.summary.queries)],[`Impressions`,W(r.summary.impressions)],[`Clicks`,W(r.summary.clicks)],[`Minimum impressions`,W(r.summary.minImpressions)],[`Result limit`,W(r.summary.limit)],[`Brand queries`,r.summary.brandFiltering],[`High-opportunity clusters`,W(r.summary.highOpportunityClusters)],[`Verdict`,r.summary.verdict]]),Y(`Why this matters`,[`Clusters show repeated demand themes, so they are better inputs for page sections, hubs, and templates than one-off query exports.`,`Prioritise clusters with high impressions and low clicks; they usually reveal unclear intent coverage or weak SERP framing.`]),Y(`Recommended actions`,r.recommendations),Y(`Report caveats`,r.caveats),q([`Cluster`,`Intent`,`Queries`,`Impr`,`CTR`,`Expected`,`Lift`,`Action`],r.clusters.map(e=>[K(e.label,32),e.intent,e.queries.length,W(e.totals?.impressions??0),G(e.totals?.ctr??0),G(e.benchmark?.expectedCtr??0),e.estimatedClickLift===void 0?`-`:W(e.estimatedClickLift),K(e.recommendation??``,72)])),J(`Top cluster actions`,r.clusters.map(e=>({label:e.label,context:`${W(e.totals?.impressions??0)} impressions, ${e.estimatedClickLift===void 0?`ranking opportunity`:`${W(e.estimatedClickLift)} estimated click lift`}`,action:e.recommendation??``})))}}),dc=w({meta:{name:`quick-wins`,description:`Find high-ranking low-CTR query/page opportunities`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`limit`,`includeBrand`,`minImpressions`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=A(e[`verify-limit`]),r=k(e[`verify-content`])===!0||n!==void 0,i=await U({client:O(e),site:D(e.site),options:{json:t}}),a=await Se({site:i.site,days:A(e.days),limit:A(e.limit),minImpressions:A(e[`min-impressions`]),brandTerms:[...i.client?.brandTerms??[],...M(e[`brand-terms`])??[]],includeBrand:k(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:k(e.js)?!0:void 0,rate:Gr(e),refresh:k(e.refresh)});if(t){z(a);return}B([[`Site`,a.site],[`Eligible rows`,W(a.summary.eligibleRows)],[`Returned rows`,W(a.summary.returnedRows)],[`Repeated-query clusters`,W(a.summary.repeatedQueryGroups)],[`Template patterns`,W(a.summary.templatePatterns)],[`CTR click shortfall`,W(a.summary.returnedEstimatedCtrClickShortfall)],[`Brand queries`,a.summary.brandFiltering],[`Verification`,Ii(a)],[`Verdict`,a.summary.verdict]]),Y(`Why this matters`,[`These rows have GSC average positions from 4 to 10 and observed CTR below a site-peer or versioned fallback target.`,`Page evidence is needed before treating a CTR shortfall as a title, content, or technical finding.`]),Y(`Recommended actions`,a.recommendations),Y(`Report caveats`,a.caveats),a.items.length&&(a.templateRecommendations.length&&(q([`Template`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Action`],a.templateRecommendations.map(e=>[K(e.templateLabel,34),W(e.urlCount),W(e.rowCount),W(e.totalEstimatedCtrClickShortfall),W(e.totalImpressions),K(e.action,72)])),J(`Top template actions`,a.templateRecommendations.map(e=>({label:e.templateLabel,context:`${W(e.urlCount)} URLs, ${W(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:`${e.action} ${e.evidence}`})))),a.groups.length&&(q([`Cluster`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Sample URL`,`Action`],a.groups.map(e=>[K(e.label,44),W(e.urlCount),W(e.rowCount),W(e.totalEstimatedCtrClickShortfall),W(e.totalImpressions),K(e.sampleUrls[0]??`-`,46),K(e.recommendation,72)])),J(`Top cluster actions`,a.groups.map(e=>({label:e.label,context:`${W(e.urlCount)} URLs, ${W(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:e.recommendation})))),q([`Query`,`Template`,`URL`,`Pos`,`Impr`,`CTR / target`,`Shortfall`,`Fetch`,`Check`,`Action`],a.items.map(e=>[K(e.query,36),K(e.template.label,24),K(e.url,48),Fi(e.position),W(e.impressions),`${G(e.ctr)} / ${G(e.targetCtr)}`,W(e.estimatedCtrClickShortfall),ra(e.contentVerification?.fetchDiagnostics),ia(e.contentVerification?.classification),K(e.recommendation.action,64)])),J(`Top opportunity actions`,a.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${Fi(e.position)}, ${W(e.impressions)} impressions`,action:e.recommendation.action}))))}}),fc=w({meta:{name:`second-page`,description:`Find URLs averaging positions above 10 through 20 in GSC`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`range`,`minImpressions`,`limit`,`includeBrand`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=A(e[`verify-limit`]),r=k(e[`verify-content`])===!0||n!==void 0,i=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),a=await pt({site:i.site,range:A(e.days),minImpressions:A(e[`min-impressions`]),limit:D(e.limit)?Number(D(e.limit)):10,brandTerms:i.client?.brandTerms,includeBrand:k(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:k(e.js)?!0:void 0,rate:Gr(e),refresh:k(e.refresh)});if(t){z(a);return}if(B([[`Site`,a.site],[`Eligible pages`,W(a.summary.eligiblePages)],[`Returned pages`,W(a.summary.returnedPages)],[`Eligible queries`,W(a.summary.eligibleQueries)],[`Eligible impressions`,W(a.summary.eligibleImpressions)],[`Content issues`,W(a.summary.contentIssues)],[`Technical issues`,W(a.summary.technicalIssues)],[`Fetch failures`,W(a.summary.fetchFailures)],[`Brand queries`,a.summary.brandFiltering],[`Verification`,Ii(a)],[`Verdict`,a.summary.verdict]]),Y(`Recommended actions`,a.recommendations),Y(`Report caveats`,a.caveats),!a.items.length){process.stdout.write(`No average-position candidates matched this report.
221
+ `),process.stdout.write(`${a.ledgerSummary}\n`);return}q([`Query`,`Template`,`Pos`,`Impr`,`CTR`,`Queries`,`Fetch`,`Check`,`Action`],a.items.map(e=>[e.primaryQuery,e.template.label,e.position.toFixed(1),Math.round(e.impressions),e.ctr.toFixed(3),W(e.queryCount),ra(e.fetchDiagnostics),ia(e.contentVerification?.classification),e.recommendation.action])),J(`Top second-page actions`,a.items.map(e=>({label:e.primaryQuery,context:`${e.template.label}, pos ${Fi(e.position)}, ${W(e.impressions)} impressions`,action:e.recommendation.action}))),process.stdout.write(`${a.ledgerSummary}\n`)}}),pc=w({meta:{name:`seo-to-ai-query`,description:`Convert GSC search queries into AI-style monitoring prompts`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},"start-date":{type:`string`,description:`Exact GSC start date (YYYY-MM-DD). Use with --end-date.`},"end-date":{type:`string`,description:`Exact GSC end date (YYYY-MM-DD). Use with --start-date.`},"max-rows":{type:`string`,description:`Maximum retained GSC query rows. Defaults to 50000.`},"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},...X([`days`,`limit`,`minImpressions`,`includeBrand`,`refresh`],{days:{description:`GSC lookback within the current 16-month retention.`},limit:{description:`Maximum source queries to convert. Defaults to 25.`},minImpressions:{description:`Minimum query impressions. Defaults to 20.`},includeBrand:{description:`Include branded queries in prompt generation.`},refresh:{description:`Bypass local GSC cache.`}}),json:{type:`boolean`,default:!1}},run:async({args:t})=>{let n=P(t),r=await U({client:O(t),site:D(t.site),options:{json:n,refresh:k(t.refresh)}}),i=await e({site:r.site,days:j(t.days,`--days`),startDate:D(t[`start-date`]),endDate:D(t[`end-date`]),limit:j(t.limit,`--limit`),minImpressions:j(t[`min-impressions`],`--min-impressions`),maxRows:j(t[`max-rows`],`--max-rows`),brandTerms:[...r.client?.brandTerms??[],...M(t[`brand-terms`])??[]],includeBrand:k(t[`include-brand`]),refresh:k(t.refresh)});if(n){z(i);return}B([[`Property`,i.site],[`Status`,i.dataStatus],[`Verdict`,i.summary.verdict],[`Eligible queries`,W(i.summary.eligibleQueries)],[`Returned queries`,W(i.summary.returnedQueries)],[`Prompts`,W(i.summary.prompts)],[`GSC completeness`,i.source.completeness]]),q([`Query`,`Impr`,`Prompt`],i.items.flatMap(e=>e.prompts.map(t=>[K(e.query,42),W(e.impressions),K(t,86)]))),Y(`Report caveats`,i.caveats),Y(`Warnings`,i.warnings)}}),mc=w({meta:{name:`audit-page`,description:`Fetch one page and audit title, metadata, content, links, and schema`},args:{url:{type:`string`,required:!0,description:`URL to audit.`},site:{type:`string`,description:`Optional GSC property for page search metrics, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for extraction.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache.`}},run:async({args:e})=>{let t=O(e),n=D(e.site),r=t?await Ni({project:t,options:{json:P(e)}}):void 0,i=t||n?void 0:await Ni({options:{json:P(e)}}),a=await $e({url:D(e.url)??``,site:r?.siteUrl??n??i?.siteUrl,js:k(e.js)?!0:`auto`,refresh:k(e.refresh)});if(P(e)){z(a);return}B([[`URL`,a.url],[`Final URL`,a.page.finalUrl],[`Title`,a.page.title??`missing`],[`Meta description`,a.page.metaDescription??`missing`],[`Word count`,String(a.page.wordCount)],[`Fetch`,ra(a.fetchDiagnostics)]]),a.issues.length&&(process.stdout.write(`
118
222
  Issues
119
- `),B([`Code`,`Severity`,`Principle`,`Detail`],a.issues.map(e=>[e.code,e.severity,e.principle,e.detail])))}});function Cs(e){let t=E(e)??`mobile`;if(t!==`mobile`&&t!==`desktop`)throw new y(`INVALID_INPUT`,`Invalid --strategy. Use mobile or desktop.`);return t}function ws(e){return e?e.displayValue??String(e.value??`not measured`):`not measured`}function Ts(e){if(!e)return`not available`;let t=e.unit===`milliseconds`?`ms`:``;return`${e.p75}${t} (${e.rating})`}const Es=C({meta:{name:`perf`,description:`Audit lab performance and field Core Web Vitals`},subCommands:{audit:C({meta:{name:`audit`,description:`Run a Lighthouse/Core Web Vitals performance audit`},args:{url:{type:`string`,description:`URL to audit. Defaults to the selected project crawl URL.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},strategy:{type:`string`,default:`mobile`,description:`Audit strategy: mobile or desktop.`},"lighthouse-bin":{type:`string`,description:`Custom Lighthouse binary path. Defaults to the bundled version.`},"crux-key":{type:`string`,description:`CrUX API key. Prefer SEO_CRUX_API_KEY to avoid shell history.`},raw:{type:`boolean`,default:!1,description:`Include the full Lighthouse JSON in JSON output.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local performance report cache.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=await Qr({client:D(e),options:{json:t}}),r=E(e.url)??n?.startUrl;if(!r)throw Error(`No URL selected. Pass --url or use --project with a crawl URL.`);let i=await _e({url:r,strategy:Cs(e.strategy),lighthouseBin:E(e[`lighthouse-bin`]),cruxApiKey:E(e[`crux-key`]),refresh:O(e.refresh),includeRaw:t&&O(e.raw)});if(t){R(i);return}z([[`URL`,i.url],[`Source`,i.source],[`Strategy`,i.strategy],[`Lab score`,i.score===void 0?`unknown`:`${i.score}/100`],[`Lab grade`,i.grade],[`Data status`,i.dataStatus],[`Headline`,i.headline],[`FCP`,ws(i.metrics.firstContentfulPaint)],[`LCP`,ws(i.metrics.largestContentfulPaint)],[`TBT`,ws(i.metrics.totalBlockingTime)],[`CLS`,ws(i.metrics.cumulativeLayoutShift)],[`INP`,ws(i.metrics.interactionToNextPaint)],[`Server response`,ws(i.metrics.serverResponseTime)],[`Fallback fetch`,ws(i.metrics.fallbackFetchDuration)],[`Field data`,i.fieldData?`${i.fieldData.scope} ${i.fieldData.formFactor.toLowerCase()} (${i.fieldData.assessment.status})`:i.fieldDataStatus.status],[`Field period`,i.fieldData?.collectionPeriod?.firstDate&&i.fieldData.collectionPeriod.lastDate?`${i.fieldData.collectionPeriod.firstDate} to ${i.fieldData.collectionPeriod.lastDate}`:`not available`],[`Field LCP p75`,Ts(i.fieldData?.metrics.largestContentfulPaint)],[`Field INP p75`,Ts(i.fieldData?.metrics.interactionToNextPaint)],[`Field CLS p75`,Ts(i.fieldData?.metrics.cumulativeLayoutShift)]]),J(`Top actions`,i.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),Y(`Caveats`,i.caveats)}})}}),Ds=C({meta:{name:`diagnose`,description:`Find where Google Search performance changed`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Baseline window length in days. Defaults to 90.`},limit:{description:`Maximum rows per diagnostic section. Defaults to 10.`}}),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),r=await he({site:n.site,days:k(e.days),recentDays:k(e.recent),limit:k(e.limit),brandTerms:n.client?.brandTerms,includeBrand:O(e[`include-brand`]),refresh:O(e.refresh),progress:so(!t)});if(t){R(r);return}z([[`Property`,r.site],[`Data status`,r.dataStatus],[`Update overlap`,r.summary.updateAttribution.replaceAll(`-`,` `)],[`Significant anomalies`,String(r.summary.significantAnomalies)],[`Update matches`,String(r.summary.updateMatches)],[`Decay items`,String(r.summary.decayItems)],[`Cannibal items`,String(r.summary.cannibalItems)],[`Striking distance`,String(r.summary.strikingDistanceItems)],[`Quick wins`,String(r.summary.quickWinItems)]]),B([`Priority`,`Confidence`,`Reason`,`Action`],r.priorities.map(e=>[e.label,e.confidence,e.reason,e.action])),r.skippedSections?.length&&B([`Skipped section`,`Reason`],r.skippedSections.map(e=>[e.section,e.reason])),J(`Priority action details`,r.priorities.map(e=>({label:e.label,context:e.confidence,action:e.action})))}}),Os=C({meta:{name:`doctor`,description:`Check local auth, scopes, config, and defaults`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await Jt();if(N(e)){R(t),t.ok||(process.exitCode=1);return}Hr(`SEO doctor`,Nr(t.checks)),process.stdout.write(`
120
- `),Ur(t.checks),process.stdout.write(`\nChecked ${t.generatedAt}\n`),t.ok||(process.exitCode=1)}}),ks=e=>{let t=E(e)??`page`;if(t!==`page`&&t!==`query`&&t!==`country`&&t!==`device`)throw Error(`Invalid --dimension. Use page, query, country, or device.`);return t},As=C({meta:{name:`segment-impact`,description:`Compare GSC movement by page, query, device, or country`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},dimension:{type:`string`,default:`page`,description:`Segment by page, query, country, or device.`},...X([`days`,`limit`,`refresh`],{days:{description:`Recent window length from 1 to 240 days. Defaults to 28.`},limit:{description:`Maximum segment rows to print. Defaults to 25.`},refresh:{description:`Bypass local cache and fetch fresh GSC data.`}}),compare:{type:`string`,description:`Legacy 1-240 day comparison length. Must equal the current window.`},"start-date":{type:`string`,description:`Exact current-window start date in YYYY-MM-DD format.`},"end-date":{type:`string`,description:`Exact current-window end date in YYYY-MM-DD format.`},"max-rows":{type:`string`,description:`Maximum retained GSC rows per window. Defaults to 100000.`},"unmatched-limit":{type:`string`,description:`Maximum one-window evidence rows to return. Defaults to 25.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=ks(e.dimension),r=A(e.days,`--days`),i=A(e.compare,`--compare`),a=A(e.limit,`--limit`),o=A(e[`unmatched-limit`],`--unmatched-limit`),s=A(e[`max-rows`],`--max-rows`),c=await ht({site:(await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}})).site,dimension:n,days:r,compareDays:i,startDate:E(e[`start-date`]),endDate:E(e[`end-date`]),limit:a,unmatchedLimit:o,maxRows:s,refresh:O(e.refresh)});if(t){R(c);return}z([[`Property`,c.site],[`Dimension`,c.dimension],[`Status`,c.dataStatus],[`Before`,`${c.before.startDate} to ${c.before.endDate}`],[`After`,`${c.after.startDate} to ${c.after.endDate}`],[`Verdict`,c.summary.verdict]]),B([`Segment`,`Clicks before`,`Clicks after`,`Delta`,`Pos delta`],c.items.map(e=>[e.key,e.beforeClicks,e.afterClicks,e.clickDelta,e.positionDelta??`-`])),c.unmatchedSegments.length&&(process.stdout.write(`
223
+ `),V([`Code`,`Severity`,`Principle`,`Detail`],a.issues.map(e=>[e.code,e.severity,e.principle,e.detail])))}});function hc(e){let t=D(e)??`mobile`;if(t!==`mobile`&&t!==`desktop`)throw new b(`INVALID_INPUT`,`Invalid --strategy. Use mobile or desktop.`);return t}function gc(e){return e?e.displayValue??String(e.value??`not measured`):`not measured`}function _c(e){if(!e)return`not available`;let t=e.unit===`milliseconds`?`ms`:``;return`${e.p75}${t} (${e.rating})`}const vc=w({meta:{name:`perf`,description:`Audit lab performance and field Core Web Vitals`},subCommands:{audit:w({meta:{name:`audit`,description:`Run a Lighthouse/Core Web Vitals performance audit`},args:{url:{type:`string`,description:`URL to audit. Defaults to the selected project crawl URL.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},strategy:{type:`string`,default:`mobile`,description:`Audit strategy: mobile or desktop.`},"lighthouse-bin":{type:`string`,description:`Custom Lighthouse binary path. Defaults to the bundled version.`},"crux-key":{type:`string`,description:`CrUX API key. Prefer SEO_CRUX_API_KEY to avoid shell history.`},raw:{type:`boolean`,default:!1,description:`Include the full Lighthouse JSON in JSON output.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local performance report cache.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=await Ni({client:O(e),options:{json:t}}),r=D(e.url)??n?.startUrl;if(!r)throw Error(`No URL selected. Pass --url or use --project with a crawl URL.`);let i=await Ht({url:r,strategy:hc(e.strategy),lighthouseBin:D(e[`lighthouse-bin`]),cruxApiKey:D(e[`crux-key`]),refresh:k(e.refresh),includeRaw:t&&k(e.raw)});if(t){z(i);return}B([[`URL`,i.url],[`Source`,i.source],[`Strategy`,i.strategy],[`Lab score`,i.score===void 0?`unknown`:`${i.score}/100`],[`Lab grade`,i.grade],[`Data status`,i.dataStatus],[`Headline`,i.headline],[`FCP`,gc(i.metrics.firstContentfulPaint)],[`LCP`,gc(i.metrics.largestContentfulPaint)],[`TBT`,gc(i.metrics.totalBlockingTime)],[`CLS`,gc(i.metrics.cumulativeLayoutShift)],[`INP`,gc(i.metrics.interactionToNextPaint)],[`Server response`,gc(i.metrics.serverResponseTime)],[`Fallback fetch`,gc(i.metrics.fallbackFetchDuration)],[`Field data`,i.fieldData?`${i.fieldData.scope} ${i.fieldData.formFactor.toLowerCase()} (${i.fieldData.assessment.status})`:i.fieldDataStatus.status],[`Field period`,i.fieldData?.collectionPeriod?.firstDate&&i.fieldData.collectionPeriod.lastDate?`${i.fieldData.collectionPeriod.firstDate} to ${i.fieldData.collectionPeriod.lastDate}`:`not available`],[`Field LCP p75`,_c(i.fieldData?.metrics.largestContentfulPaint)],[`Field INP p75`,_c(i.fieldData?.metrics.interactionToNextPaint)],[`Field CLS p75`,_c(i.fieldData?.metrics.cumulativeLayoutShift)]]),J(`Top actions`,i.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),Y(`Caveats`,i.caveats)}})}}),yc=w({meta:{name:`diagnose`,description:`Find where Google Search performance changed`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Baseline window length in days. Defaults to 90.`},limit:{description:`Maximum rows per diagnostic section. Defaults to 10.`}}),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),r=await ot({site:n.site,days:A(e.days),recentDays:A(e.recent),limit:A(e.limit),brandTerms:n.client?.brandTerms,includeBrand:k(e[`include-brand`]),refresh:k(e.refresh),progress:Yo(!t)});if(t){z(r);return}B([[`Property`,r.site],[`Data status`,r.dataStatus],[`Update overlap`,r.summary.updateAttribution.replaceAll(`-`,` `)],[`Significant anomalies`,String(r.summary.significantAnomalies)],[`Update matches`,String(r.summary.updateMatches)],[`Decay items`,String(r.summary.decayItems)],[`Cannibal items`,String(r.summary.cannibalItems)],[`Striking distance`,String(r.summary.strikingDistanceItems)],[`Quick wins`,String(r.summary.quickWinItems)]]),V([`Priority`,`Confidence`,`Reason`,`Action`],r.priorities.map(e=>[e.label,e.confidence,e.reason,e.action])),r.skippedSections?.length&&V([`Skipped section`,`Reason`],r.skippedSections.map(e=>[e.section,e.reason])),J(`Priority action details`,r.priorities.map(e=>({label:e.label,context:e.confidence,action:e.action})))}}),bc=w({meta:{name:`doctor`,description:`Check local auth, scopes, config, and defaults`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await Et();if(P(e)){z(t),t.ok||(process.exitCode=1);return}Si(`SEO doctor`,pi(t.checks)),process.stdout.write(`
224
+ `),Ci(t.checks),process.stdout.write(`\nChecked ${t.generatedAt}\n`),t.ok||(process.exitCode=1)}}),xc=e=>{let t=D(e)??`page`;if(t!==`page`&&t!==`query`&&t!==`country`&&t!==`device`)throw Error(`Invalid --dimension. Use page, query, country, or device.`);return t},Sc=w({meta:{name:`segment-impact`,description:`Compare GSC movement by page, query, device, or country`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},dimension:{type:`string`,default:`page`,description:`Segment by page, query, country, or device.`},...X([`days`,`limit`,`refresh`],{days:{description:`Recent window length from 1 to 240 days. Defaults to 28.`},limit:{description:`Maximum segment rows to print. Defaults to 25.`},refresh:{description:`Bypass local cache and fetch fresh GSC data.`}}),compare:{type:`string`,description:`Legacy 1-240 day comparison length. Must equal the current window.`},"start-date":{type:`string`,description:`Exact current-window start date in YYYY-MM-DD format.`},"end-date":{type:`string`,description:`Exact current-window end date in YYYY-MM-DD format.`},"max-rows":{type:`string`,description:`Maximum retained GSC rows per window. Defaults to 100000.`},"unmatched-limit":{type:`string`,description:`Maximum one-window evidence rows to return. Defaults to 25.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=xc(e.dimension),r=j(e.days,`--days`),i=j(e.compare,`--compare`),a=j(e.limit,`--limit`),o=j(e[`unmatched-limit`],`--unmatched-limit`),s=j(e[`max-rows`],`--max-rows`),c=await Ot({site:(await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}})).site,dimension:n,days:r,compareDays:i,startDate:D(e[`start-date`]),endDate:D(e[`end-date`]),limit:a,unmatchedLimit:o,maxRows:s,refresh:k(e.refresh)});if(t){z(c);return}B([[`Property`,c.site],[`Dimension`,c.dimension],[`Status`,c.dataStatus],[`Before`,`${c.before.startDate} to ${c.before.endDate}`],[`After`,`${c.after.startDate} to ${c.after.endDate}`],[`Verdict`,c.summary.verdict]]),V([`Segment`,`Clicks before`,`Clicks after`,`Delta`,`Pos delta`],c.items.map(e=>[e.key,e.beforeClicks,e.afterClicks,e.clickDelta,e.positionDelta??`-`])),c.unmatchedSegments.length&&(process.stdout.write(`
121
225
  One-window evidence (not treated as zero)
122
- `),B([`Segment`,`Retained in`,`Clicks`,`Impressions`],c.unmatchedSegments.map(e=>[e.key,e.retainedIn,e.clicks,e.impressions]))),Y(`Warnings`,c.warnings)}});function js(e){return`${W(e)} ${e===1?`row`:`rows`}`}const Ms=C({meta:{name:`striking-distance`,description:`Find query/page rows averaging positions above 10 through 20`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},...X([`days`,`minImpressions`,`limit`,`includeBrand`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=k(e[`verify-limit`]),r=O(e[`verify-content`])===!0||n!==void 0,i=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),a=await Ve({site:i.site,days:k(e.days),minImpressions:k(e[`min-impressions`]),limit:k(e.limit),brandTerms:i.client?.brandTerms,includeBrand:O(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:O(e.js)?!0:void 0,rate:dr(e),refresh:O(e.refresh)});if(t){R(a);return}if(z([[`Site`,a.site],[`Eligible rows`,W(a.summary.eligibleRows)],[`Returned rows`,W(a.summary.returnedRows)],[`Template groups`,W(a.summary.groups)],[`Eligible impressions`,W(a.summary.eligibleImpressions)],[`Brand queries`,a.summary.brandFiltering],[`Verification`,a.verification.requested?`requested`:`off`],[`Verdict`,a.summary.verdict]]),Y(`Why this matters`,[`These rows have a GSC average position above 10 and at most 20. Treat them as candidates for investigation, not guaranteed page-two rankings.`,`Groups use all eligible rows. A shared-template label is only a candidate until recurring evidence is verified across distinct URLs.`]),Y(`Recommended actions`,a.recommendations),Y(`Report caveats`,a.caveats),a.groups.length&&(q([`Group`,`Rows`,`URLs`,`Impr`,`Avg pos`,`Scope`,`Action`],a.groups.map(e=>[K(e.label,36),W(e.rowCount),W(e.uniqueUrls),W(e.totalImpressions),ei(e.impressionWeightedPosition),e.actionScope,K(e.recommendation.action,72)])),J(`Top striking-distance group actions`,a.groups.map(e=>({label:e.label,context:`${js(e.rowCount)}, ${W(e.totalImpressions)} impressions`,action:e.recommendation.action})))),!a.items.length){process.stdout.write(`No striking-distance opportunities matched these filters.
123
- `);return}q([`Query`,`Template`,`URL`,`Impr`,`CTR`,`Pos`,`Score`,`Fetch`,`Check`,`Action`],a.items.map(e=>[K(e.query,36),K(e.template.label,24),K(e.url,48),W(e.impressions),G(e.ctr),ei(e.position),e.priority.score,Si(e.contentVerification?.fetchDiagnostics),Ci(e.contentVerification?.classification),K(e.recommendation.action,72)])),J(`Top striking-distance actions`,a.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${ei(e.position)}, ${W(e.impressions)} impressions`,action:e.recommendation.action})))}});function Ns(e){let t=e.indexed+e.notIndexed+e.unknown+e.warnings;return t?`${e.indexed}/${t} indexed`:`-`}function Ps(e){if(!e.samples.length)return`-`;let t=e.medianWordCount===void 0?`words ?`:`${W(e.medianWordCount)} words`,n=e.weakQueryCoverage?`; ${e.weakQueryCoverage} weak coverage`:``;return`${t}; ${e.usable}/${e.samples.length} usable${n}`}function Fs(e){return e===`serp-framing-review`?`wording review`:e===`body-term-review`?`literal term review`:`covered terms`}function Is(e){let t=e.staticSegments.map(e=>`/${e.value}`).join(``),n=e.variableSegments.slice(0,3).map(e=>{let t=e.examples.slice(0,3).join(`, `);return`${e.placeholder}@${e.index+1}${t?` (${t})`:``}`});return[t?`static ${t}`:`no fixed path prefix`,n.length?`variables ${n.join(`; `)}`:`no variables`].join(`; `)}function Ls(e){if(e.checkedQueries)return`${Math.round(e.impressionShare*100)}% impression fit across ${at(e.checkedQueries,`checked query/page row`)}`}function Rs(e){return e.startsWith(`theme: `)?`${e.slice(7)}-related`:e===`general`?`broad`:e}function zs(e){for(let t of e.slice(0,5)){process.stdout.write(`\n${t.signature}\n`),t.evidence.length&&process.stdout.write(` Evidence: ${t.evidence.join(`; `)}.\n`),process.stdout.write(` Shape: ${Is(t.shape)}\n`);let e=Ls(t.metrics.entityFit);e&&process.stdout.write(` Entity fit: ${e}\n`);let n=t.metrics.queryPatterns.slice(0,3).map(e=>`${Rs(e.label)} (${W(e.impressions)} impr: ${e.examples.slice(0,2).join(`; `)})`);n.length&&process.stdout.write(` Demand: ${n.join(` | `)}\n`);let r=t.metrics.topQueries.slice(0,3);if(r.length){process.stdout.write(` Top queries:
124
- `);for(let e of r)process.stdout.write(` - ${K(e.query,72)} (${W(e.impressions)} impr, pos ${ei(e.position)})\n`)}let i=t.crawl.samples.map(e=>e.queryCoverage).filter(e=>!!e).slice(0,3);if(i.length){process.stdout.write(` Sample coverage:
125
- `);for(let e of i){let t=e.missingTerms.length?` missing ${e.missingTerms.slice(0,4).join(`, `)}`:``;process.stdout.write(` - ${Fs(e.classification)}: ${K(e.query,64)} (body ${(e.bodyCoverage*100).toFixed(0)}%${t})\n`)}}let a=t.metrics.entityFit.weakExamples.slice(0,2);if(a.length){process.stdout.write(` Weak entity-fit examples:
126
- `);for(let e of a){let t=e.pathTerms.slice(0,4);process.stdout.write(` - ${K(e.query,64)} -> expected ${at(t.length,`path term`)}: ${t.join(`, `)}\n`)}}process.stdout.write(` Action: ${t.recommendation}\n`)}}const Bs=C({meta:{name:`pseo`,description:`Programmatic SEO audits that cluster URL patterns and sample template pages`},subCommands:{audit:C({meta:{name:`audit`,description:`Group GSC/sitemap URLs into pSEO templates, then sample pages for crawl and index evidence`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`limit`,`includeBrand`,`js`,`refresh`],{limit:{description:`Maximum templates to show. Defaults to 25.`},includeBrand:{description:`Include branded queries in template metrics.`},js:{description:`Force JavaScript rendering for crawl samples.`},refresh:{description:`Bypass local GSC and HTTP cache.`}}),sitemap:{type:`string`,description:`Comma-separated sitemap URLs to include in template counts.`},"crawl-samples":{type:`string`,description:`Sample URLs to fetch per detected template. This is not crawl depth.`},"inspect-samples":{type:`string`,description:`Sample URLs to check per detected template with URL Inspection.`},"max-sitemap-urls":{type:`string`,description:`Maximum discovered URLs per sitemap. Defaults to 50000.`},"minimum-template-urls":{type:`string`,description:`Minimum repeated URLs required for a template. Defaults to 3.`},"minimum-template-share":{type:`string`,description:`Minimum share of discovered URLs from 0 to 1. Defaults to 0.`},"minimum-template-impressions":{type:`string`,description:`Minimum retained page impressions for a template. Defaults to 0.`},"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude from query evidence.`},"fetch-concurrency":{type:`string`,description:`Maximum concurrent page fetches per host. Defaults to 4.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host. Defaults to 4.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds. Defaults to 1000.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=N(e),n=Lo(e),r=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),i=await ae({site:r.site,...n,brandTerms:n.brandTerms??r.client?.brandTerms,progress:so(!t)});if(t){R(i);return}if(z([[`Property`,i.site],[`Templates`,W(i.summary.templates)],[`GSC pages`,W(i.summary.gscPages)],[`Sitemap URLs`,W(i.summary.sitemapUrls)],[`Clicks`,W(i.summary.clicks)],[`Impressions`,W(i.summary.impressions)],[`Usable crawls`,`${W(i.summary.crawledUrls)}/${W(i.summary.crawlAttempts)}`],[`Inspection responses`,`${W(i.summary.inspectedUrls)}/${W(i.summary.inspectionAttempts)}`]]),Y(`Report caveats`,i.caveats),!i.templates.length){process.stdout.write(`No pSEO templates found from GSC/sitemap data.
127
- `);return}q([`Verdict`,`Template`,`URLs`,`Clicks`,`Impr`,`CTR`,`Pos`,`Index`,`Crawl`,`Action`],i.templates.map(e=>[`${e.verdict} (${e.confidence})`,K(e.signature,28),W(e.urlCount),W(e.metrics.clicks),W(e.metrics.impressions),G(e.metrics.ctr),e.metrics.position.toFixed(1),Ns(e.inspection),Ps(e.crawl),K(e.recommendation,72)])),zs(i.templates),i.warnings.length&&process.stdout.write(`Warnings: ${i.warnings.join(`; `)}\n`),ni(`seo export pseo ${r.client?`--project ${JSON.stringify(r.client.id)}`:`--site ${JSON.stringify(r.site)}`}`)}})}}),Vs={"ai-search":`AI search`,crawl:`Crawling and technical checks`,diagnosis:`Diagnosis`,experiments:`Experiments`,monitoring:`Monitoring`,opportunities:`Opportunities`,reporting:`Reporting`,setup:`Setup`,workflows:`Workflows`};function Hs(e){let t=E(e);if(t){if(!Pt.includes(t))throw new y(`INVALID_INPUT`,`Unknown report category: ${t}. Choose ${Pt.join(`, `)}.`);return t}}async function Us(e,t){let n=E(e),r=E(t);if(n&&r)throw new y(`INVALID_INPUT`,`Use either --params or --params-file, not both.`);if(!n&&!r)return{};let i=n??await En(r??``,`utf8`),a;try{a=JSON.parse(i)}catch{throw new y(`INVALID_INPUT`,`Report parameters must be valid JSON.`)}if(!a||typeof a!=`object`||Array.isArray(a))throw new y(`INVALID_INPUT`,`Report parameters must be an object.`);return a}function Ws(e){if(!e.isError)return;let t=e.structuredContent;throw new y(t?.error?.code??`INTERNAL_ERROR`,t?.error?.message??`The report could not be completed.`)}function Gs(e){if(!e||typeof e!=`object`)return[];let t=e,n=new Set(t.required??[]);return Object.entries(t.properties??{}).map(([e,t])=>{let r=Array.isArray(t.type)?t.type.join(` | `):t.type??`any`;return{name:e,type:r===`array`&&t.items?.type?`${t.items.type}[]`:t.format?`${r} (${t.format})`:r,required:n.has(e),description:t.description}})}const Ks=C({meta:{name:`reports`,description:`Discover and run the complete report catalog`},subCommands:{list:C({meta:{name:`list`,description:`List report ids available to the CLI and MCP server`},args:{category:{type:`string`,description:`Filter by category: ${Pt.join(`, `)}.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=xt(Hs(e.category));if(N(e)){R({reports:t,categories:Pt});return}Wr(t,{noun:`report`,categoryLabels:Vs}),process.stdout.write(`
128
- `),Vr({title:`Need the detail?`,body:`Describe one report to see when to use it, what it needs, and what the result can prove.`,command:`seo reports describe <id>`})}}),describe:C({meta:{name:`describe`,description:`Show the purpose and parameter schema for one report`},args:{id:{type:`positional`,required:!0,description:"Report id from `seo reports list`."},check:{type:`string`,description:`Show fix guidance for one check id from the report output.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=E(e.check);if(t){let n=ot(E(e.id)??``,t);if(N(e)){R({report:n});return}Hr(`${n.name}: ${n.check}`,n.checkFix.goal),process.stdout.write(`
129
- `),V(`Fix`,n.checkFix.fix),process.stdout.write(`
130
- `),V(`Agent prompt`,n.checkFix.prompt),process.stdout.write(`
131
- `),V(`Verify`,n.checkFix.verify),n.checkFix.resources.length>0&&(process.stdout.write(`
132
- `),Kr(`Resources`,n.checkFix.resources.map(e=>`${e.title}: ${e.url}`))),process.stdout.write(`
133
- `);return}let n=kt(E(e.id)??``);if(N(e)){R({report:n});return}Hr(n.name,n.description),process.stdout.write(`
134
- `),z([[`ID`,n.id],[`Category`,n.category],[`Outcome`,n.outcome]]),process.stdout.write(`
135
- `),Kr(`Use when`,n.useWhen),process.stdout.write(`
136
- `),Kr(`Avoid when`,n.avoidWhen),process.stdout.write(`
137
- `),Kr(`Read in order`,n.readOrder),process.stdout.write(`
138
- `),Kr(`Do not claim`,n.doNotClaim),process.stdout.write(`
139
- `),V(`Verify`,n.verify),n.related.length>0&&(process.stdout.write(`
140
- `),Kr(`Related reports`,n.related.map(e=>`${e.id}: ${e.reason}`))),process.stdout.write(`
226
+ `),V([`Segment`,`Retained in`,`Clicks`,`Impressions`],c.unmatchedSegments.map(e=>[e.key,e.retainedIn,e.clicks,e.impressions]))),Y(`Warnings`,c.warnings)}});function Cc(e){return`${W(e)} ${e===1?`row`:`rows`}`}const wc=w({meta:{name:`striking-distance`,description:`Find query/page rows averaging positions above 10 through 20`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},...X([`days`,`minImpressions`,`limit`,`includeBrand`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=A(e[`verify-limit`]),r=k(e[`verify-content`])===!0||n!==void 0,i=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),a=await p({site:i.site,days:A(e.days),minImpressions:A(e[`min-impressions`]),limit:A(e.limit),brandTerms:i.client?.brandTerms,includeBrand:k(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:k(e.js)?!0:void 0,rate:Gr(e),refresh:k(e.refresh)});if(t){z(a);return}if(B([[`Site`,a.site],[`Eligible rows`,W(a.summary.eligibleRows)],[`Returned rows`,W(a.summary.returnedRows)],[`Template groups`,W(a.summary.groups)],[`Eligible impressions`,W(a.summary.eligibleImpressions)],[`Brand queries`,a.summary.brandFiltering],[`Verification`,a.verification.requested?`requested`:`off`],[`Verdict`,a.summary.verdict]]),Y(`Why this matters`,[`These rows have a GSC average position above 10 and at most 20. Treat them as candidates for investigation, not guaranteed page-two rankings.`,`Groups use all eligible rows. A shared-template label is only a candidate until recurring evidence is verified across distinct URLs.`]),Y(`Recommended actions`,a.recommendations),Y(`Report caveats`,a.caveats),a.groups.length&&(q([`Group`,`Rows`,`URLs`,`Impr`,`Avg pos`,`Scope`,`Action`],a.groups.map(e=>[K(e.label,36),W(e.rowCount),W(e.uniqueUrls),W(e.totalImpressions),Fi(e.impressionWeightedPosition),e.actionScope,K(e.recommendation.action,72)])),J(`Top striking-distance group actions`,a.groups.map(e=>({label:e.label,context:`${Cc(e.rowCount)}, ${W(e.totalImpressions)} impressions`,action:e.recommendation.action})))),!a.items.length){process.stdout.write(`No striking-distance opportunities matched these filters.
227
+ `);return}q([`Query`,`Template`,`URL`,`Impr`,`CTR`,`Pos`,`Score`,`Fetch`,`Check`,`Action`],a.items.map(e=>[K(e.query,36),K(e.template.label,24),K(e.url,48),W(e.impressions),G(e.ctr),Fi(e.position),e.priority.score,ra(e.contentVerification?.fetchDiagnostics),ia(e.contentVerification?.classification),K(e.recommendation.action,72)])),J(`Top striking-distance actions`,a.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${Fi(e.position)}, ${W(e.impressions)} impressions`,action:e.recommendation.action})))}});function Tc(e){return e.filter(e=>e.isVerified)}function Ec(e){if(e.startsWith(`sc-domain:`))return e.slice(10).replace(/^www\./,``).toLowerCase();try{return new URL(e).hostname.replace(/^www\./,``).toLowerCase()}catch{return}}function Dc(e,t){let n=Ec(e);if(!n)return;let r=Tc(t).filter(e=>Ec(e.url)===n);return r.length===1?r[0]:void 0}async function Oc(e){let t=Tc(e.sites),n=e.explicitSite??e.savedSite;if(n){let e=t.find(e=>e.url===n);if(!e)throw new b(`PROPERTY_NOT_FOUND`,`Bing Webmaster did not return a verified site matching ${n}.`);return e.url}let r=e.projectSite?Dc(e.projectSite,t):void 0;if(r)return r.url;if(t.length===1)return t[0]?.url;if(t.length!==0){if(!R({json:e.json}))throw new b(`INVALID_INPUT`,`Several verified Bing sites are available. Pass --site to choose one.`);return H(await dr({message:`Choose a verified Bing Webmaster site`,options:t.map(e=>({value:e.url,label:e.url}))}))}}const kc={project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},site:{type:`string`,description:`Verified Bing Webmaster site URL.`}},Ac=w({meta:{name:`providers`,description:`Connect optional data providers`},subCommands:{bing:w({meta:{name:`bing`,description:`Connect and report on Bing Webmaster`},subCommands:{connect:w({meta:{name:`connect`,description:`Connect Bing Webmaster and attach a verified site`},args:{...kc,json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e);if(!R({json:t}))throw new b(`AUTH_REQUIRED`,"Run `seo providers bing connect` in a terminal. Agents and CI can set SEO_BING_API_KEY and run the report directly.");ar(`Connect Bing Webmaster`),T(`Paste the API key from Bing Webmaster Tools Settings, then API Access. The key stays on this machine.`,`API key`);let n=H(await ur({message:`Bing Webmaster API key`,validate:e=>e?.trim()?void 0:`API key is required`})),r=await new Kt({apiKey:n}).listSites(),i=await Ni({project:O(e),options:{json:t}}),a=await Oc({explicitSite:D(e.site),projectSite:i?.siteUrl,savedSite:me(i),sites:r.sites,json:t});if(!a)throw new b(`PROPERTY_NOT_FOUND`,`No verified Bing Webmaster sites were found for this API key.`);await le(y,n);let o=i?Oe(i.id,a):void 0;T(`${a}${o?` is attached to ${o.name}.`:` is ready for direct reports.`}`,`Bing connected`),lr(o?`Run seo providers bing report --project ${o.id}`:`Run seo providers bing report --site ${a}`)}}),status:w({meta:{name:`status`,description:`Show the local Bing connection`},args:{project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await _({name:y,envVar:Be}),n=await Ni({project:O(e),options:{json:P(e)}}),r={connected:!!t,credentialSource:t?.source,project:n?{id:n.id,name:n.name,site:me(n)}:void 0};if(P(e)){z(r);return}B([[`Connected`,r.connected?`yes`:`no`],[`Credential`,r.credentialSource??`missing`],[`Project`,r.project?.name??`not selected`],[`Bing site`,r.project?.site??`not attached`]])}}),disconnect:w({meta:{name:`disconnect`,description:`Remove the saved Bing Webmaster credential`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await Ue(y);let t={disconnected:!0,note:`Saved project site mappings were kept for a later reconnect.`};P(e)?z(t):process.stdout.write(`${t.note}\n`)}}),sites:w({meta:{name:`sites`,description:`List Bing Webmaster sites`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let{client:t,credentialSource:n}=await Le(),r=await t.listSites(),i={...r,credentialSource:n};if(P(e)){z(i);return}V([`Site`,`Verified`],r.sites.map(e=>[e.url,e.isVerified?`yes`:`no`]))}}),report:w({meta:{name:`report`,description:`Find Bing traffic, crawl, query, and page insights`},args:{...kc,json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=await Ni({project:O(e),options:{json:t}}),r=D(e.site)??me(n);if(!r)throw new b(`INVALID_INPUT`,`Pass --site or connect Bing Webmaster to a saved project first.`);let i=await a({site:r});if(t){z(i);return}let o=i.traffic.status===`unavailable`?void 0:i.traffic.data,s=i.crawl.status===`unavailable`?void 0:i.crawl.data,c=o?.analysis;if(B([[`Site`,i.site],[`Data status`,i.dataStatus],[`Latest 28-day clicks`,c?String(c.current.clicks):`unavailable`],[`Click change`,c?.changes.clicksPercent===null||c?.changes.clicksPercent===void 0?`unavailable`:`${c.changes.clicksPercent.toFixed(1)}%`],[`Latest 28-day impressions`,c?String(c.current.impressions):`unavailable`],[`Impression change`,c?.changes.impressionsPercent===null||c?.changes.impressionsPercent===void 0?`unavailable`:`${c.changes.impressionsPercent.toFixed(1)}%`],[`Latest crawled pages`,s?.latest?.crawledPages===void 0?`unavailable`:String(s.latest.crawledPages)],[`Latest 4xx responses`,s?.latest?.code4xx===void 0?`unavailable`:String(s.latest.code4xx)],[`Findings`,String(i.summary.findings)]]),i.findings.length){process.stdout.write(`
228
+ Review first
229
+ `);for(let e of i.findings.slice(0,5))process.stdout.write(`- ${e.title}\n ${e.verification}\n`)}for(let e of i.caveats)process.stdout.write(`\n${e}\n`)}})}})}});function jc(e){let t=e.indexed+e.notIndexed+e.unknown+e.warnings;return t?`${e.indexed}/${t} indexed`:`-`}function Mc(e){if(!e.samples.length)return`-`;let t=e.medianWordCount===void 0?`words ?`:`${W(e.medianWordCount)} words`,n=e.weakQueryCoverage?`; ${e.weakQueryCoverage} weak coverage`:``;return`${t}; ${e.usable}/${e.samples.length} usable${n}`}function Nc(e){return e===`serp-framing-review`?`wording review`:e===`body-term-review`?`literal term review`:`covered terms`}function Pc(e){let t=e.staticSegments.map(e=>`/${e.value}`).join(``),n=e.variableSegments.slice(0,3).map(e=>{let t=e.examples.slice(0,3).join(`, `);return`${e.placeholder}@${e.index+1}${t?` (${t})`:``}`});return[t?`static ${t}`:`no fixed path prefix`,n.length?`variables ${n.join(`; `)}`:`no variables`].join(`; `)}function Fc(e){if(e.checkedQueries)return`${Math.round(e.impressionShare*100)}% impression fit across ${pe(e.checkedQueries,`checked query/page row`)}`}function Ic(e){return e.startsWith(`theme: `)?`${e.slice(7)}-related`:e===`general`?`broad`:e}function Lc(e){for(let t of e.slice(0,5)){process.stdout.write(`\n${t.signature}\n`),t.evidence.length&&process.stdout.write(` Evidence: ${t.evidence.join(`; `)}.\n`),process.stdout.write(` Shape: ${Pc(t.shape)}\n`);let e=Fc(t.metrics.entityFit);e&&process.stdout.write(` Entity fit: ${e}\n`);let n=t.metrics.queryPatterns.slice(0,3).map(e=>`${Ic(e.label)} (${W(e.impressions)} impr: ${e.examples.slice(0,2).join(`; `)})`);n.length&&process.stdout.write(` Demand: ${n.join(` | `)}\n`);let r=t.metrics.topQueries.slice(0,3);if(r.length){process.stdout.write(` Top queries:
230
+ `);for(let e of r)process.stdout.write(` - ${K(e.query,72)} (${W(e.impressions)} impr, pos ${Fi(e.position)})\n`)}let i=t.crawl.samples.map(e=>e.queryCoverage).filter(e=>!!e).slice(0,3);if(i.length){process.stdout.write(` Sample coverage:
231
+ `);for(let e of i){let t=e.missingTerms.length?` missing ${e.missingTerms.slice(0,4).join(`, `)}`:``;process.stdout.write(` - ${Nc(e.classification)}: ${K(e.query,64)} (body ${(e.bodyCoverage*100).toFixed(0)}%${t})\n`)}}let a=t.metrics.entityFit.weakExamples.slice(0,2);if(a.length){process.stdout.write(` Weak entity-fit examples:
232
+ `);for(let e of a){let t=e.pathTerms.slice(0,4);process.stdout.write(` - ${K(e.query,64)} -> expected ${pe(t.length,`path term`)}: ${t.join(`, `)}\n`)}}process.stdout.write(` Action: ${t.recommendation}\n`)}}const Rc=w({meta:{name:`pseo`,description:`Programmatic SEO audits that cluster URL patterns and sample template pages`},subCommands:{audit:w({meta:{name:`audit`,description:`Group GSC/sitemap URLs into pSEO templates, then sample pages for crawl and index evidence`},args:{site:{type:`string`},project:{type:`string`,description:`Saved project id or name.`},client:{type:`string`,description:`Legacy alias for --project.`},...X([`days`,`limit`,`includeBrand`,`js`,`refresh`],{limit:{description:`Maximum templates to show. Defaults to 25.`},includeBrand:{description:`Include branded queries in template metrics.`},js:{description:`Force JavaScript rendering for crawl samples.`},refresh:{description:`Bypass local GSC and HTTP cache.`}}),sitemap:{type:`string`,description:`Comma-separated sitemap URLs to include in template counts.`},"crawl-samples":{type:`string`,description:`Sample URLs to fetch per detected template. This is not crawl depth.`},"inspect-samples":{type:`string`,description:`Sample URLs to check per detected template with URL Inspection.`},"max-sitemap-urls":{type:`string`,description:`Maximum discovered URLs per sitemap. Defaults to 50000.`},"minimum-template-urls":{type:`string`,description:`Minimum repeated URLs required for a template. Defaults to 3.`},"minimum-template-share":{type:`string`,description:`Minimum share of discovered URLs from 0 to 1. Defaults to 0.`},"minimum-template-impressions":{type:`string`,description:`Minimum retained page impressions for a template. Defaults to 0.`},"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude from query evidence.`},"fetch-concurrency":{type:`string`,description:`Maximum concurrent page fetches per host. Defaults to 4.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host. Defaults to 4.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds. Defaults to 1000.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=P(e),n=ws(e),r=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),i=await rt({site:r.site,...n,brandTerms:n.brandTerms??r.client?.brandTerms,progress:Yo(!t)});if(t){z(i);return}if(B([[`Property`,i.site],[`Templates`,W(i.summary.templates)],[`GSC pages`,W(i.summary.gscPages)],[`Sitemap URLs`,W(i.summary.sitemapUrls)],[`Clicks`,W(i.summary.clicks)],[`Impressions`,W(i.summary.impressions)],[`Usable crawls`,`${W(i.summary.crawledUrls)}/${W(i.summary.crawlAttempts)}`],[`Inspection responses`,`${W(i.summary.inspectedUrls)}/${W(i.summary.inspectionAttempts)}`]]),Y(`Report caveats`,i.caveats),!i.templates.length){process.stdout.write(`No pSEO templates found from GSC/sitemap data.
233
+ `);return}q([`Verdict`,`Template`,`URLs`,`Clicks`,`Impr`,`CTR`,`Pos`,`Index`,`Crawl`,`Action`],i.templates.map(e=>[`${e.verdict} (${e.confidence})`,K(e.signature,28),W(e.urlCount),W(e.metrics.clicks),W(e.metrics.impressions),G(e.metrics.ctr),e.metrics.position.toFixed(1),jc(e.inspection),Mc(e.crawl),K(e.recommendation,72)])),Lc(i.templates),i.warnings.length&&process.stdout.write(`Warnings: ${i.warnings.join(`; `)}\n`),Li(`seo export pseo ${r.client?`--project ${JSON.stringify(r.client.id)}`:`--site ${JSON.stringify(r.site)}`}`)}})}}),zc={"ai-search":`AI search`,crawl:`Crawling and technical checks`,diagnosis:`Diagnosis`,experiments:`Experiments`,monitoring:`Monitoring`,opportunities:`Opportunities`,reporting:`Reporting`,setup:`Setup`,workflows:`Workflows`};function Bc(e){let t=D(e);if(t){if(!$t.includes(t))throw new b(`INVALID_INPUT`,`Unknown report category: ${t}. Choose ${$t.join(`, `)}.`);return t}}async function Vc(e,t){let n=D(e),r=D(t);if(n&&r)throw new b(`INVALID_INPUT`,`Use either --params or --params-file, not both.`);if(!n&&!r)return{};let i=n??await Jn(r??``,`utf8`),a;try{a=JSON.parse(i)}catch{throw new b(`INVALID_INPUT`,`Report parameters must be valid JSON.`)}if(!a||typeof a!=`object`||Array.isArray(a))throw new b(`INVALID_INPUT`,`Report parameters must be an object.`);return a}function Hc(e){if(!e.isError)return;let t=e.structuredContent;throw new b(t?.error?.code??`INTERNAL_ERROR`,t?.error?.message??`The report could not be completed.`)}function Uc(e){if(!e||typeof e!=`object`)return[];let t=e,n=new Set(t.required??[]);return Object.entries(t.properties??{}).map(([e,t])=>{let r=Array.isArray(t.type)?t.type.join(` | `):t.type??`any`;return{name:e,type:r===`array`&&t.items?.type?`${t.items.type}[]`:t.format?`${r} (${t.format})`:r,required:n.has(e),description:t.description}})}const Wc=w({meta:{name:`reports`,description:`Discover and run the complete report catalog`},subCommands:{list:w({meta:{name:`list`,description:`List report ids available to the CLI and MCP server`},args:{category:{type:`string`,description:`Filter by category: ${$t.join(`, `)}.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Bt(Bc(e.category));if(P(e)){z({reports:t,categories:$t});return}wi(t,{noun:`report`,categoryLabels:zc}),process.stdout.write(`
234
+ `),xi({title:`Need the detail?`,body:`Describe one report to see when to use it, what it needs, and what the result can prove.`,command:`seo reports describe <id>`})}}),describe:w({meta:{name:`describe`,description:`Show the purpose and parameter schema for one report`},args:{id:{type:`positional`,required:!0,description:"Report id from `seo reports list`."},check:{type:`string`,description:`Show fix guidance for one check id from the report output.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=D(e.check);if(t){let n=Ct(D(e.id)??``,t);if(P(e)){z({report:n});return}Si(`${n.name}: ${n.check}`,n.checkFix.goal),process.stdout.write(`
235
+ `),Ei(`Fix`,n.checkFix.fix),process.stdout.write(`
236
+ `),Ei(`Agent prompt`,n.checkFix.prompt),process.stdout.write(`
237
+ `),Ei(`Verify`,n.checkFix.verify),n.checkFix.resources.length>0&&(process.stdout.write(`
238
+ `),Di(`Resources`,n.checkFix.resources.map(e=>`${e.title}: ${e.url}`))),process.stdout.write(`
239
+ `);return}let n=Jt(D(e.id)??``);if(P(e)){z({report:n});return}Si(n.name,n.description),process.stdout.write(`
240
+ `),B([[`ID`,n.id],[`Category`,n.category],[`Outcome`,n.outcome]]),process.stdout.write(`
241
+ `),Di(`Use when`,n.useWhen),process.stdout.write(`
242
+ `),Di(`Avoid when`,n.avoidWhen),process.stdout.write(`
243
+ `),Di(`Read in order`,n.readOrder),process.stdout.write(`
244
+ `),Di(`Do not claim`,n.doNotClaim),process.stdout.write(`
245
+ `),Ei(`Verify`,n.verify),n.related.length>0&&(process.stdout.write(`
246
+ `),Di(`Related reports`,n.related.map(e=>`${e.id}: ${e.reason}`))),process.stdout.write(`
141
247
  Parameters
142
- `),qr(Gs(n.inputSchema)),n.fixableChecks&&(process.stdout.write(`
143
- `),Vr({title:`Fix a failed check`,body:`Get the fix steps, an agent prompt, and spec links for one check id from the report output.`,command:`seo reports describe ${n.id} --check <check-id>`})),process.stdout.write(`
144
- `),Vr({title:`Need the exact schema?`,command:`seo reports describe ${n.id} --json`})}}),run:C({meta:{name:`run`,description:`Run one report with JSON parameters`},args:{id:{type:`positional`,required:!0,description:"Report id from `seo reports list`."},params:{type:`string`,description:`Report parameters as a JSON object.`},"params-file":{type:`string`,description:`Read report parameters from a JSON file.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await ze(E(e.id)??``,await Us(e.params,e[`params-file`]));if(Ws(t),N(e)){R(t.structuredContent??{});return}for(let e of t.content)process.stdout.write(`${e.text}\n`)}})}}),qs=C({meta:{name:`monthly-report`,description:`Generate a monthly SEO report narrative`},args:{...co,month:{type:`string`,description:`Report month as YYYY-MM. Defaults to the latest month with final GSC data.`},...X([`limit`],{limit:{description:`Maximum rows per diagnostic section. Defaults to 10.`}}),...lo},run:async({args:e})=>{let t=N(e),n=fo(e),r=await U({client:n.client,site:n.site,options:{json:t,refresh:n.refresh}}),i=await le({site:r.site,month:E(e.month),limit:k(e.limit),brandTerms:r.client?.brandTerms,...uo(e),progress:so(!t)});if(t){R(i);return}process.stdout.write(`${i.markdown}\n`);let a=r.client?`--project ${JSON.stringify(r.client.id)}`:`--site ${JSON.stringify(r.site)}`,o=E(e.month);process.stdout.write(`
145
- `),ni(`seo export monthly ${a}${o?` --month ${JSON.stringify(o)}`:``}`)}}),Js=C({meta:{name:`report-narrative`,description:`Generate a client-ready SEO narrative from diagnosis data`},args:{...co,...X([`days`,`recentDays`],{days:{description:`Diagnosis window length in days. Defaults to 90.`}}),"start-date":{type:`string`,description:`Optional report start date as YYYY-MM-DD.`},"end-date":{type:`string`,description:`Optional report end date as YYYY-MM-DD.`},...X([`limit`],{limit:{description:`Maximum rows per diagnostic section. Defaults to 10.`}}),"change-limit":{type:`string`,description:`Maximum saved changes to measure. Defaults to 5.`},...lo},run:async({args:e})=>{let t=N(e),n=fo(e),r=await U({client:n.client,site:n.site,options:{json:t,refresh:n.refresh}}),i=await pe({site:r.site,days:k(e.days),recentDays:k(e.recent),startDate:E(e[`start-date`]),endDate:E(e[`end-date`]),limit:k(e.limit),changeLimit:k(e[`change-limit`]),brandTerms:r.client?.brandTerms,...uo(e),progress:so(!t)});if(t){R(i);return}process.stdout.write(`${i.markdown}\n`);let a=r.client?`--project ${JSON.stringify(r.client.id)}`:`--site ${JSON.stringify(r.site)}`;process.stdout.write(`
146
- `),ni(`seo export narrative ${a}`)}}),Ys=C({meta:{name:`rules`,description:`List crawler rule ids and default guidance`},args:{category:{type:`string`,description:`Filter rules by category.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=E(e.category),n=ve().filter(e=>!t||e.category===t);if(N(e)){R({rules:n});return}Wr(n.map(e=>({id:e.id,category:e.category,name:`${e.title} · ${e.defaultSeverity}`})),{noun:`rule`})}}),Xs=C({meta:{name:`explain`,description:`Explain one crawler rule in plain English`},args:{rule:{type:`string`,required:!0,description:`Rule id to explain, for example missing_title.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=E(e.rule)??``,n=oe(t);if(!n)throw Error(`Unknown rule: ${t}`);if(N(e)){R(n);return}z([[`Rule`,n.id],[`Title`,n.title],[`Category`,n.category],[`Severity`,n.defaultSeverity]]),process.stdout.write(`
147
- `),V(`Why it matters`,n.whyItMatters),process.stdout.write(`
148
- `),V(`How to fix`,n.howToFix),process.stdout.write(`
149
- `),V(`Impact if ignored`,n.impactIfIgnored),process.stdout.write(`
150
- `),V(`How to verify`,n.howToVerify)}});function Zs(e){return JSON.stringify(e)}const Qs=C({meta:{name:`schedule`,description:`Print local cron entries for recurring SEO workflows`},subCommands:{cron:C({meta:{name:`cron`,description:`Print crontab lines for local recurring SEO workflows`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},url:{type:`string`,description:`Start URL for technical-watch. Defaults from the GSC property when possible.`},urls:{type:`string`,description:`Comma-separated URLs for index-watch.`},hour:{type:`string`,default:`9`,description:`Hour in local cron time. Defaults to 9.`},minute:{type:`string`,default:`0`,description:`Minute in local cron time. Defaults to 0.`},weekday:{type:`string`,description:`Weekly technical-watch day. Defaults to client setting, then Monday.`},day:{type:`string`,description:`Monthly report day. Defaults to client setting, then 1.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t}}),r=n.site,i=E(e.url)??n.client?.startUrl??yi(n.site),a=k(e.hour)??9,o=k(e.minute)??0,s=k(e.weekday)??n.client?.technicalWeekday??1,c=k(e.day)??n.client?.reportDay??1,l=n.client?`--project ${Zs(n.client.id)}`:`--site ${Zs(r)}`,u=E(e.urls)??n.client?.watchUrls.join(`,`),d=[{name:`technical-watch`,cron:`${o} ${a} * * ${s}`,command:[`seo technical-watch`,l,i?`--url ${Zs(i)}`:void 0,u?`--urls ${Zs(u)}`:void 0,`--json`].filter(Boolean).join(` `)},{name:`monthly-report`,cron:`${o} ${a} ${c} * *`,command:[`seo monthly-report`,l,`--json`].join(` `)}];if(t){R({site:r,lines:d});return}let f=Vt();z([[`Property`,r],[`Install`,`crontab -e`]]);for(let e of d)process.stdout.write(`${e.cron} seo logs prune --quiet; ${e.command} >> ${Zs(`${f.logDir}/${e.name}.log`)} 2>&1\n`)}})}});function $s(){return tc(`skills`,process.env.SEO_SKILLS_DIR)}function ec(){return tc(`evals`,process.env.SEO_EVALS_DIR)}function tc(e,t){if(t)return hn(t);let n=x(bn(import.meta.url));for(let t=0;t<6;t+=1){let t=S(n,e);if(b(S(t,`README.md`)))return t;n=x(n)}throw new y(`INTERNAL_ERROR`,`Packaged ${e} could not be found. Reinstall \`seo\` and try again.`)}function nc(e){return nn(S(e,`SKILL.md`),`utf8`).match(/^description:\s*(.+)$/m)?.[1]?.trim()??``}const rc=`claude -p`;function ic(){let e=ec();return rn(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(t=>({subject:dn(t.name,`.json`),path:S(e,t.name)})).sort((e,t)=>e.subject<t.subject?-1:+(e.subject>t.subject))}function ac(e,t){let n;try{n=nn(t,`utf8`)}catch{throw new y(`INVALID_INPUT`,`Cannot read eval file for ${e}.`)}let r;try{r=JSON.parse(n)}catch{throw new y(`INVALID_INPUT`,`Eval file ${e}.json is not valid JSON.`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new y(`INVALID_INPUT`,`Eval file ${e}.json must be an object.`);let i=r;if(i.subject!==e)throw new y(`INVALID_INPUT`,`Eval file ${e}.json must set subject to "${e}".`);if(!Array.isArray(i.evals)||i.evals.length===0)throw new y(`INVALID_INPUT`,`Eval file ${e}.json must have a non-empty evals array.`);let a=new Set;return{subject:e,evals:i.evals.map((t,n)=>{let r=t,i=`${e}.json eval ${n+1}`;if(!Number.isInteger(r?.id))throw new y(`INVALID_INPUT`,`${i}: id must be an integer.`);let o=r.id;if(a.has(o))throw new y(`INVALID_INPUT`,`${i}: duplicate id ${o}.`);if(a.add(o),typeof r.prompt!=`string`||r.prompt.trim().length===0)throw new y(`INVALID_INPUT`,`${i}: prompt must be a non-empty string.`);if(typeof r.expected_output!=`string`||r.expected_output.trim().length===0)throw new y(`INVALID_INPUT`,`${i}: expected_output must be a non-empty string.`);if(!Array.isArray(r.assertions)||r.assertions.length===0||r.assertions.some(e=>typeof e!=`string`||e.trim().length===0))throw new y(`INVALID_INPUT`,`${i}: assertions must be a non-empty array of non-empty strings.`);if(r.files!==void 0&&!Array.isArray(r.files))throw new y(`INVALID_INPUT`,`${i}: files must be an array.`);return{id:o,prompt:r.prompt,expected_output:r.expected_output,assertions:r.assertions,files:r.files??[]}})}}function oc(){let e=S($s(),`seo`,`SKILL.md`);if(!b(e))throw new y(`INTERNAL_ERROR`,"The seo router skill could not be found. Reinstall `seo` or use --no-skill.");return nn(e,`utf8`)}function sc(e){let t=[],n=``,r=!1,i=!1,a=!1;for(let o=0;o<e.length;o+=1){let s=e[o];if(i){s===`'`?i=!1:n+=s,r=!0;continue}if(a){s===`"`?a=!1:s===`\\`&&(e[o+1]===`"`||e[o+1]===`\\`)?(n+=e[o+1],o+=1):n+=s,r=!0;continue}if(s===`'`){i=!0,r=!0;continue}if(s===`"`){a=!0,r=!0;continue}if(s===`\\`){o+1<e.length&&(n+=e[o+1],o+=1,r=!0);continue}if(s===` `||s===` `||s===`
151
- `||s===`\r`){r&&=(t.push(n),n=``,!1);continue}n+=s,r=!0}if(i||a)throw new y(`INVALID_INPUT`,`Unbalanced quote in agent command.`);return r&&t.push(n),t}function cc(e,t){let n=sc(e);if(n.length===0)throw new y(`INVALID_INPUT`,`Agent command must not be empty.`);let r=n.some(e=>e.includes(`{prompt}`));return{argv:r?n.map(e=>e.split(`{prompt}`).join(t)):n,usesPlaceholder:r}}function lc(e,t){return e?`${e.trim()}\n\n---\n\nUser request:\n${t}`:t}function uc(e,t,n,r=!1){let i=[`You are judging whether an AI agent response satisfies a list of assertions.`,`Judge only against the assertions. Be strict but fair.`,``,`Original request:`,e,``,`Agent response:`,t,``,`Assertions to evaluate, in this exact order:`,`<assertions>`,n.map((e,t)=>`${t+1}. ${e}`).join(`
248
+ `),Oi(Uc(n.inputSchema)),n.fixableChecks&&(process.stdout.write(`
249
+ `),xi({title:`Fix a failed check`,body:`Get the fix steps, an agent prompt, and spec links for one check id from the report output.`,command:`seo reports describe ${n.id} --check <check-id>`})),process.stdout.write(`
250
+ `),xi({title:`Need the exact schema?`,command:`seo reports describe ${n.id} --json`})}}),run:w({meta:{name:`run`,description:`Run one report with JSON parameters`},args:{id:{type:`positional`,required:!0,description:"Report id from `seo reports list`."},params:{type:`string`,description:`Report parameters as a JSON object.`},"params-file":{type:`string`,description:`Read report parameters from a JSON file.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await tt(D(e.id)??``,await Vc(e.params,e[`params-file`]));if(Hc(t),P(e)){z(t.structuredContent??{});return}for(let e of t.content)process.stdout.write(`${e.text}\n`)}})}}),Gc={format:{type:`string`,description:`Output format: terminal or html. Defaults to terminal.`},output:{type:`string`,description:`HTML output file. A dated filename is used by default.`},view:{type:`string`,description:`HTML detail level: client or analyst. Defaults to client.`}};function Kc(e){let t=D(e.format)??`terminal`;if(t!==`terminal`&&t!==`html`)throw new b(`INVALID_INPUT`,`Choose terminal or html for --format.`);if(t===`terminal`){if(D(e.output)||D(e.view))throw new b(`INVALID_INPUT`,`Use --output and --view with --format html.`);return}if(k(e.json))throw new b(`INVALID_INPUT`,`Use either --json or --format html, not both.`);let n=D(e.view)??`client`;if(n!==`client`&&n!==`analyst`)throw new b(`INVALID_INPUT`,`Choose client or analyst for --view.`);return{output:D(e.output),view:n}}function qc(e){return e.toLowerCase().replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80)}function Jc(e){let t=(e.date??new Date).toISOString().slice(0,10),n=qc(e.projectId??e.site)||`site`;return Ln(process.cwd(),`${n}-${qc(e.reportName)}-${t}.html`)}async function Yc(e){let t=Ln(e.options.output??Jc({reportName:e.reportName,projectId:e.projectId,site:e.report.site}));return await Kn(S(t),{recursive:!0}),await er(t,kr({report:e.report,title:e.title,view:e.options.view,additionalSections:e.additionalSections}),`utf8`),t}function Xc(e){process.stdout.write(`Wrote HTML report to ${e}\n`)}const Zc=w({meta:{name:`monthly-report`,description:`Generate a monthly SEO report narrative`},args:{...Xo,month:{type:`string`,description:`Report month as YYYY-MM. Defaults to the latest month with final GSC data.`},...X([`limit`],{limit:{description:`Maximum rows per diagnostic section. Defaults to 10.`}}),...Zo,...Gc},run:async({args:e})=>{let t=P(e),n=Kc(e),r=$o(e),i=await U({client:r.client,site:r.site,options:{json:t,refresh:r.refresh}}),a=await tn({site:i.site,month:D(e.month),limit:A(e.limit),brandTerms:i.client?.brandTerms,...Qo(e),progress:Yo(!t)});if(t){z(a);return}if(n){Xc(await Yc({report:a,reportName:`monthly-report`,title:`Monthly SEO report for ${a.month}`,options:n,projectId:i.client?.id}));return}process.stdout.write(`${a.markdown}\n`);let o=i.client?`--project ${JSON.stringify(i.client.id)}`:`--site ${JSON.stringify(i.site)}`,s=D(e.month);process.stdout.write(`
251
+ `),Li(`seo export monthly ${o}${s?` --month ${JSON.stringify(s)}`:``}`)}}),Qc=w({meta:{name:`report-narrative`,description:`Generate a client-ready SEO narrative from diagnosis data`},args:{...Xo,...X([`days`,`recentDays`],{days:{description:`Diagnosis window length in days. Defaults to 90.`}}),"start-date":{type:`string`,description:`Optional report start date as YYYY-MM-DD.`},"end-date":{type:`string`,description:`Optional report end date as YYYY-MM-DD.`},...X([`limit`],{limit:{description:`Maximum rows per diagnostic section. Defaults to 10.`}}),"change-limit":{type:`string`,description:`Maximum saved changes to measure. Defaults to 5.`},...Zo,...Gc},run:async({args:e})=>{let t=P(e),n=Kc(e),r=$o(e),i=await U({client:r.client,site:r.site,options:{json:t,refresh:r.refresh}}),a=await zt({site:i.site,days:A(e.days),recentDays:A(e.recent),startDate:D(e[`start-date`]),endDate:D(e[`end-date`]),limit:A(e.limit),changeLimit:A(e[`change-limit`]),brandTerms:i.client?.brandTerms,...Qo(e),progress:Yo(!t)});if(t){z(a);return}if(n){Xc(await Yc({report:a,reportName:`narrative-report`,title:`SEO narrative report`,options:n,projectId:i.client?.id}));return}process.stdout.write(`${a.markdown}\n`);let o=i.client?`--project ${JSON.stringify(i.client.id)}`:`--site ${JSON.stringify(i.site)}`;process.stdout.write(`
252
+ `),Li(`seo export narrative ${o}`)}}),$c=w({meta:{name:`rules`,description:`List crawler rule ids and default guidance`},args:{category:{type:`string`,description:`Filter rules by category.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=D(e.category),n=Vt().filter(e=>!t||e.category===t);if(P(e)){z({rules:n});return}wi(n.map(e=>({id:e.id,category:e.category,name:`${e.title} · ${e.defaultSeverity}`})),{noun:`rule`})}}),el=w({meta:{name:`explain`,description:`Explain one crawler rule in plain English`},args:{rule:{type:`string`,required:!0,description:`Rule id to explain, for example missing_title.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=D(e.rule)??``,n=nt(t);if(!n)throw Error(`Unknown rule: ${t}`);if(P(e)){z(n);return}B([[`Rule`,n.id],[`Title`,n.title],[`Category`,n.category],[`Severity`,n.defaultSeverity]]),process.stdout.write(`
253
+ `),Ei(`Why it matters`,n.whyItMatters),process.stdout.write(`
254
+ `),Ei(`How to fix`,n.howToFix),process.stdout.write(`
255
+ `),Ei(`Impact if ignored`,n.impactIfIgnored),process.stdout.write(`
256
+ `),Ei(`How to verify`,n.howToVerify)}});function tl(e){return JSON.stringify(e)}const nl=w({meta:{name:`schedule`,description:`Print local cron entries for recurring SEO workflows`},subCommands:{cron:w({meta:{name:`cron`,description:`Print crontab lines for local recurring SEO workflows`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},url:{type:`string`,description:`Start URL for technical-watch. Defaults from the GSC property when possible.`},urls:{type:`string`,description:`Comma-separated URLs for index-watch.`},hour:{type:`string`,default:`9`,description:`Hour in local cron time. Defaults to 9.`},minute:{type:`string`,default:`0`,description:`Minute in local cron time. Defaults to 0.`},weekday:{type:`string`,description:`Weekly technical-watch day. Defaults to client setting, then Monday.`},day:{type:`string`,description:`Monthly report day. Defaults to client setting, then 1.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t}}),r=n.site,i=D(e.url)??n.client?.startUrl??ea(n.site),a=A(e.hour)??9,s=A(e.minute)??0,c=A(e.weekday)??n.client?.technicalWeekday??1,l=A(e.day)??n.client?.reportDay??1,u=n.client?`--project ${tl(n.client.id)}`:`--site ${tl(r)}`,d=D(e.urls)??n.client?.watchUrls.join(`,`),f=[{name:`technical-watch`,cron:`${s} ${a} * * ${c}`,command:[`seo technical-watch`,u,i?`--url ${tl(i)}`:void 0,d?`--urls ${tl(d)}`:void 0,`--json`].filter(Boolean).join(` `)},{name:`monthly-report`,cron:`${s} ${a} ${l} * *`,command:[`seo monthly-report`,u,`--json`].join(` `)}];if(t){z({site:r,lines:f});return}let p=o();B([[`Property`,r],[`Install`,`crontab -e`]]);for(let e of f)process.stdout.write(`${e.cron} seo logs prune --quiet; ${e.command} >> ${tl(`${p.logDir}/${e.name}.log`)} 2>&1\n`)}})}}),rl=w({meta:{name:`server-logs`,description:`Analyze local web server access logs`},subCommands:{analyze:w({meta:{name:`analyze`,description:`Stream a local access log into bounded crawler evidence`},args:{file:{type:`string`,description:`Local combined, JSONL, or NDJSON access log.`,required:!0},format:{type:`string`,description:`Input format override: combined or jsonl.`},"row-limit":{type:`string`,description:`Maximum rows to parse. Defaults to 1000000.`},"path-limit":{type:`string`,description:`Maximum crawler and path aggregates to retain. Defaults to 25000.`},limit:{type:`string`,description:`Maximum crawler path rows returned. Defaults to 100.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=D(e.file);if(!t)throw new b(`INVALID_INPUT`,`Pass --file.`);let n=D(e.format);if(n&&![`combined`,`jsonl`].includes(n))throw new b(`INVALID_INPUT`,`--format must be combined or jsonl.`);let r=on({evidence:await hn({file:t,format:n,rowLimit:j(e[`row-limit`],`--row-limit`),pathLimit:j(e[`path-limit`],`--path-limit`)}),limit:j(e.limit,`--limit`)});if(P(e)){z(r);return}B([[`Evidence`,r.dataStatus],[`Parsed requests`,W(r.summary.parsedRows)],[`Crawler requests`,W(r.summary.crawlerRows)],[`Crawler families`,W(r.crawlers.length)],[`Invalid rows`,W(r.summary.invalidRows)],[`Returned paths`,`${W(r.selection.returnedCrawlerPaths)} of ${W(r.selection.availableCrawlerPaths)}`]]),r.crawlers.length&&(process.stdout.write(`
257
+ Crawler activity
258
+ `),q([`Crawler`,`Type`,`Requests`,`4xx`,`5xx`],r.crawlers.map(e=>[e.family,e.category,String(e.requests),String(e.clientError),String(e.serverError)]))),r.crawlerPaths.length&&(process.stdout.write(`
259
+ Crawler paths
260
+ `),q([`Crawler`,`Path`,`Requests`,`4xx`,`5xx`],r.crawlerPaths.map(e=>[e.family,K(e.path,72),String(e.requests),String(e.clientError),String(e.serverError)])));for(let e of r.warnings)process.stdout.write(`\nWarning: ${e}\n`);process.stdout.write(`\nNote: ${r.caveats[0]}\n`)}})}});function il(){return ol(`skills`,process.env.SEO_SKILLS_DIR)}function al(){return ol(`evals`,process.env.SEO_EVALS_DIR)}function ol(e,t){if(t)return Ln(t);let n=S(Hn(import.meta.url));for(let t=0;t<6;t+=1){let t=C(n,e);if(x(C(t,`README.md`)))return t;n=S(n)}throw new b(`INTERNAL_ERROR`,`Packaged ${e} could not be found. Reinstall \`seo\` and try again.`)}function sl(e){return Tn(C(e,`SKILL.md`),`utf8`).match(/^description:\s*(.+)$/m)?.[1]?.trim()??``}const cl=`claude -p`;function ll(){let e=al();return En(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(t=>({subject:Nn(t.name,`.json`),path:C(e,t.name)})).sort((e,t)=>e.subject<t.subject?-1:+(e.subject>t.subject))}function ul(e,t){let n;try{n=Tn(t,`utf8`)}catch{throw new b(`INVALID_INPUT`,`Cannot read eval file for ${e}.`)}let r;try{r=JSON.parse(n)}catch{throw new b(`INVALID_INPUT`,`Eval file ${e}.json is not valid JSON.`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new b(`INVALID_INPUT`,`Eval file ${e}.json must be an object.`);let i=r;if(i.subject!==e)throw new b(`INVALID_INPUT`,`Eval file ${e}.json must set subject to "${e}".`);if(!Array.isArray(i.evals)||i.evals.length===0)throw new b(`INVALID_INPUT`,`Eval file ${e}.json must have a non-empty evals array.`);let a=new Set;return{subject:e,evals:i.evals.map((t,n)=>{let r=t,i=`${e}.json eval ${n+1}`;if(!Number.isInteger(r?.id))throw new b(`INVALID_INPUT`,`${i}: id must be an integer.`);let o=r.id;if(a.has(o))throw new b(`INVALID_INPUT`,`${i}: duplicate id ${o}.`);if(a.add(o),typeof r.prompt!=`string`||r.prompt.trim().length===0)throw new b(`INVALID_INPUT`,`${i}: prompt must be a non-empty string.`);if(typeof r.expected_output!=`string`||r.expected_output.trim().length===0)throw new b(`INVALID_INPUT`,`${i}: expected_output must be a non-empty string.`);if(!Array.isArray(r.assertions)||r.assertions.length===0||r.assertions.some(e=>typeof e!=`string`||e.trim().length===0))throw new b(`INVALID_INPUT`,`${i}: assertions must be a non-empty array of non-empty strings.`);if(r.files!==void 0&&!Array.isArray(r.files))throw new b(`INVALID_INPUT`,`${i}: files must be an array.`);return{id:o,prompt:r.prompt,expected_output:r.expected_output,assertions:r.assertions,files:r.files??[]}})}}function dl(){let e=C(il(),`seo`,`SKILL.md`);if(!x(e))throw new b(`INTERNAL_ERROR`,"The seo router skill could not be found. Reinstall `seo` or use --no-skill.");return Tn(e,`utf8`)}function fl(e){let t=[],n=``,r=!1,i=!1,a=!1;for(let o=0;o<e.length;o+=1){let s=e[o];if(i){s===`'`?i=!1:n+=s,r=!0;continue}if(a){s===`"`?a=!1:s===`\\`&&(e[o+1]===`"`||e[o+1]===`\\`)?(n+=e[o+1],o+=1):n+=s,r=!0;continue}if(s===`'`){i=!0,r=!0;continue}if(s===`"`){a=!0,r=!0;continue}if(s===`\\`){o+1<e.length&&(n+=e[o+1],o+=1,r=!0);continue}if(s===` `||s===` `||s===`
261
+ `||s===`\r`){r&&=(t.push(n),n=``,!1);continue}n+=s,r=!0}if(i||a)throw new b(`INVALID_INPUT`,`Unbalanced quote in agent command.`);return r&&t.push(n),t}function pl(e,t){let n=fl(e);if(n.length===0)throw new b(`INVALID_INPUT`,`Agent command must not be empty.`);let r=n.some(e=>e.includes(`{prompt}`));return{argv:r?n.map(e=>e.split(`{prompt}`).join(t)):n,usesPlaceholder:r}}function ml(e,t){return e?`${e.trim()}\n\n---\n\nUser request:\n${t}`:t}function hl(e,t,n,r=!1){let i=[`You are judging whether an AI agent response satisfies a list of assertions.`,`Judge only against the assertions. Be strict but fair.`,``,`Original request:`,e,``,`Agent response:`,t,``,`Assertions to evaluate, in this exact order:`,`<assertions>`,n.map((e,t)=>`${t+1}. ${e}`).join(`
152
262
  `),`</assertions>`,``,`Judge outcomes, not narration. An assertion about reading, checking, or`,`following fields or steps passes when the reply demonstrably used that`,`information or produced the result it protects, even if the reply never`,`names the field or step. Fail it only when the reply contradicts it or`,`shows the work was not done.`,``,`Reply with STRICT JSON only. No prose, no markdown, no code fence:`,`{"results":[{"assertion":"<assertion text>","pass":true,"reason":"<short reason>"}]}`,`Return exactly ${n.length} result${n.length===1?``:`s`}, one per assertion, in the same order.`].join(`
153
- `);return r?`${i}\n\nYour previous reply could not be parsed as the required JSON with one result per assertion. Reply again with STRICT JSON only, in the exact shape shown, and nothing else.`:i}function dc(e){let t=e.indexOf(`{`);if(t===-1)return;let n=0,r=!1,i=!1;for(let a=t;a<e.length;a+=1){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`)r=!0;else if(o===`{`)n+=1;else if(o===`}`&&(--n,n===0))try{return JSON.parse(e.slice(t,a+1))}catch{return}}}function fc(e,t){let n=dc(e);if(!n||typeof n!=`object`)return{error:`Judge reply did not contain a JSON object.`};let r=n.results;return Array.isArray(r)?r.length===t.length?{verdicts:t.map((e,t)=>{let n=r[t];return{assertion:e,verdict:n?.pass===!0?`pass`:`fail`,reason:typeof n?.reason==`string`&&n.reason.trim().length>0?n.reason.trim():`No reason given.`,source:`judge verdict`}})}:{error:`Judge returned ${r.length} results for ${t.length} assertions.`}:{error:`Judge reply had no results array.`}}function pc(e,t){return new Promise(n=>{let r=Date.now(),[i,...a]=e,o;try{o=vn(i,a,{stdio:[`pipe`,`pipe`,`pipe`]})}catch(e){n({stdout:``,stderr:``,code:null,timedOut:!1,spawnError:e instanceof Error?e.message:String(e),durationMs:Date.now()-r});return}let s=``,c=``,l=!1,u=!1,d,f=setTimeout(()=>{u=!0,o.kill(`SIGTERM`),d=setTimeout(()=>{try{o.kill(`SIGKILL`)}catch{}},2e3),d.unref()},t.timeoutMs),p=e=>{l||(l=!0,clearTimeout(f),d&&clearTimeout(d),n({...e,durationMs:Date.now()-r}))};o.stdout?.on(`data`,e=>{s+=e}),o.stderr?.on(`data`,e=>{c+=e}),o.on(`error`,e=>{p({stdout:s,stderr:c,code:null,timedOut:u,spawnError:e.message})}),o.on(`close`,e=>{p({stdout:s,stderr:c,code:e,timedOut:u})}),o.stdin&&(t.input===void 0?o.stdin.end():o.stdin.end(t.input))})}async function mc(e,t,n){let{argv:r,usesPlaceholder:i}=cc(e,t);return pc(r,{input:i?void 0:t,timeoutMs:n})}async function hc(e,t){let n=Date.now(),r=lc(t.skillBody,e.prompt),i=await mc(t.agent,r,t.timeoutMs),a=i.stdout.trim(),o={id:e.id,prompt:e.prompt,reply:a,agentDurationMs:i.durationMs};if(i.spawnError)return{...o,status:`errored`,error:`Agent command failed to start: ${i.spawnError}`,durationMs:Date.now()-n,assertions:gc(e.assertions)};if(i.timedOut)return{...o,status:`errored`,error:`Agent timed out after ${Math.round(t.timeoutMs/1e3)}s.`,durationMs:Date.now()-n,assertions:gc(e.assertions)};if(a.length===0)return{...o,status:`errored`,error:`Agent returned no output on stdout.`,durationMs:Date.now()-n,assertions:gc(e.assertions)};if(!t.judge)return{...o,status:`unjudged`,durationMs:Date.now()-n,assertions:gc(e.assertions)};let s=0,c=``;for(let r=0;r<2;r+=1){let i=uc(e.prompt,a,e.assertions,r>0),l=await mc(t.judge,i,t.timeoutMs);if(s+=l.durationMs,l.spawnError)return{...o,status:`errored`,error:`Judge command failed to start: ${l.spawnError}`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:gc(e.assertions)};if(l.timedOut)return{...o,status:`errored`,error:`Judge timed out after ${Math.round(t.timeoutMs/1e3)}s.`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:gc(e.assertions)};let u=fc(l.stdout,e.assertions);if(`verdicts`in u){let e=u.verdicts.some(e=>e.verdict===`fail`);return{...o,status:e?`failed`:`passed`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:u.verdicts}}c=u.error}return{...o,status:`errored`,error:`Judge output could not be parsed after a retry: ${c}`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:gc(e.assertions)}}function gc(e){return e.map(e=>({assertion:e,verdict:`unjudged`}))}async function _c(e,t,n){let r=Array(e.length),i=0,a=async()=>{for(;;){let t=i;if(i+=1,t>=e.length)return;r[t]=await n(e[t],t)}},o=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:o},()=>a())),r}function vc(e){let t={passed:0,failed:0,errored:0,unjudged:0};for(let n of e)t[n.status]+=1;return t}function yc(e){let t=[],n=E(e.subject);n&&t.push(n);let r=e._;if(Array.isArray(r))for(let e of r)typeof e==`string`&&e.length>0&&t.push(e);return[...new Set(t)]}function bc(e){let t=ic();if(e.length===0)return t;let n=new Map(t.map(e=>[e.subject,e]));return e.map(e=>{let r=n.get(e);if(!r){let n=t.map(e=>e.subject).join(`, `);throw new y(`INVALID_INPUT`,`Unknown eval subject: ${e}.${n?` Known subjects: ${n}.`:``}`)}return r})}function xc(e){let t=ic().map(e=>{let t=ac(e.subject,e.path);return{subject:e.subject,evals:t.evals.length}});if(e){R({schemaVersion:1,subjects:t});return}if(t.length===0){process.stdout.write(`No eval subjects found.
263
+ `);return r?`${i}\n\nYour previous reply could not be parsed as the required JSON with one result per assertion. Reply again with STRICT JSON only, in the exact shape shown, and nothing else.`:i}function gl(e){let t=e.indexOf(`{`);if(t===-1)return;let n=0,r=!1,i=!1;for(let a=t;a<e.length;a+=1){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`)r=!0;else if(o===`{`)n+=1;else if(o===`}`&&(--n,n===0))try{return JSON.parse(e.slice(t,a+1))}catch{return}}}function _l(e,t){let n=gl(e);if(!n||typeof n!=`object`)return{error:`Judge reply did not contain a JSON object.`};let r=n.results;return Array.isArray(r)?r.length===t.length?{verdicts:t.map((e,t)=>{let n=r[t];return{assertion:e,verdict:n?.pass===!0?`pass`:`fail`,reason:typeof n?.reason==`string`&&n.reason.trim().length>0?n.reason.trim():`No reason given.`,source:`judge verdict`}})}:{error:`Judge returned ${r.length} results for ${t.length} assertions.`}:{error:`Judge reply had no results array.`}}function vl(e,t){return new Promise(n=>{let r=Date.now(),[i,...a]=e,o;try{o=Bn(i,a,{stdio:[`pipe`,`pipe`,`pipe`]})}catch(e){n({stdout:``,stderr:``,code:null,timedOut:!1,spawnError:e instanceof Error?e.message:String(e),durationMs:Date.now()-r});return}let s=``,c=``,l=!1,u=!1,d,f=setTimeout(()=>{u=!0,o.kill(`SIGTERM`),d=setTimeout(()=>{try{o.kill(`SIGKILL`)}catch{}},2e3),d.unref()},t.timeoutMs),p=e=>{l||(l=!0,clearTimeout(f),d&&clearTimeout(d),n({...e,durationMs:Date.now()-r}))};o.stdout?.on(`data`,e=>{s+=e}),o.stderr?.on(`data`,e=>{c+=e}),o.on(`error`,e=>{p({stdout:s,stderr:c,code:null,timedOut:u,spawnError:e.message})}),o.on(`close`,e=>{p({stdout:s,stderr:c,code:e,timedOut:u})}),o.stdin&&(t.input===void 0?o.stdin.end():o.stdin.end(t.input))})}async function yl(e,t,n){let{argv:r,usesPlaceholder:i}=pl(e,t);return vl(r,{input:i?void 0:t,timeoutMs:n})}async function bl(e,t){let n=Date.now(),r=ml(t.skillBody,e.prompt),i=await yl(t.agent,r,t.timeoutMs),a=i.stdout.trim(),o={id:e.id,prompt:e.prompt,reply:a,agentDurationMs:i.durationMs};if(i.spawnError)return{...o,status:`errored`,error:`Agent command failed to start: ${i.spawnError}`,durationMs:Date.now()-n,assertions:xl(e.assertions)};if(i.timedOut)return{...o,status:`errored`,error:`Agent timed out after ${Math.round(t.timeoutMs/1e3)}s.`,durationMs:Date.now()-n,assertions:xl(e.assertions)};if(a.length===0)return{...o,status:`errored`,error:`Agent returned no output on stdout.`,durationMs:Date.now()-n,assertions:xl(e.assertions)};if(!t.judge)return{...o,status:`unjudged`,durationMs:Date.now()-n,assertions:xl(e.assertions)};let s=0,c=``;for(let r=0;r<2;r+=1){let i=hl(e.prompt,a,e.assertions,r>0),l=await yl(t.judge,i,t.timeoutMs);if(s+=l.durationMs,l.spawnError)return{...o,status:`errored`,error:`Judge command failed to start: ${l.spawnError}`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:xl(e.assertions)};if(l.timedOut)return{...o,status:`errored`,error:`Judge timed out after ${Math.round(t.timeoutMs/1e3)}s.`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:xl(e.assertions)};let u=_l(l.stdout,e.assertions);if(`verdicts`in u){let e=u.verdicts.some(e=>e.verdict===`fail`);return{...o,status:e?`failed`:`passed`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:u.verdicts}}c=u.error}return{...o,status:`errored`,error:`Judge output could not be parsed after a retry: ${c}`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:xl(e.assertions)}}function xl(e){return e.map(e=>({assertion:e,verdict:`unjudged`}))}async function Sl(e,t,n){let r=Array(e.length),i=0,a=async()=>{for(;;){let t=i;if(i+=1,t>=e.length)return;r[t]=await n(e[t],t)}},o=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:o},()=>a())),r}function Cl(e){let t={passed:0,failed:0,errored:0,unjudged:0};for(let n of e)t[n.status]+=1;return t}function wl(e){let t=[],n=D(e.subject);n&&t.push(n);let r=e._;if(Array.isArray(r))for(let e of r)typeof e==`string`&&e.length>0&&t.push(e);return[...new Set(t)]}function Tl(e){let t=ll();if(e.length===0)return t;let n=new Map(t.map(e=>[e.subject,e]));return e.map(e=>{let r=n.get(e);if(!r){let n=t.map(e=>e.subject).join(`, `);throw new b(`INVALID_INPUT`,`Unknown eval subject: ${e}.${n?` Known subjects: ${n}.`:``}`)}return r})}function El(e){let t=ll().map(e=>{let t=ul(e.subject,e.path);return{subject:e.subject,evals:t.evals.length}});if(e){z({schemaVersion:1,subjects:t});return}if(t.length===0){process.stdout.write(`No eval subjects found.
154
264
  `);return}let n=Math.max(...t.map(e=>e.subject.length));process.stdout.write(`Eval subjects
155
- `);for(let e of t){let t=e.evals===1?`eval`:`evals`;process.stdout.write(` ${e.subject.padEnd(n)} ${e.evals} ${t}\n`)}}function Sc(e){return e===`passed`?`PASS`:e===`failed`?`FAIL`:e===`errored`?`ERROR`:`UNJUDGED`}function Cc(e,t){t.judged?process.stdout.write(`Assertion verdicts below are judge verdicts, model judgments from the judge agent, not ground truth.
265
+ `);for(let e of t){let t=e.evals===1?`eval`:`evals`;process.stdout.write(` ${e.subject.padEnd(n)} ${e.evals} ${t}\n`)}}function Dl(e){return e===`passed`?`PASS`:e===`failed`?`FAIL`:e===`errored`?`ERROR`:`UNJUDGED`}function Ol(e,t){t.judged?process.stdout.write(`Assertion verdicts below are judge verdicts, model judgments from the judge agent, not ground truth.
156
266
 
157
267
  `):process.stdout.write(`Judging was skipped. Review each agent reply against the assertion checklist by hand.
158
268
 
159
- `);for(let n of e){process.stdout.write(`# ${n.subject}\n`);for(let e of n.evals){if(process.stdout.write(`\n[${Sc(e.status)}] eval ${e.id} (${e.durationMs}ms)\n`),process.stdout.write(` prompt: ${Tc(e.prompt,100)}\n`),e.error&&process.stdout.write(` error: ${e.error}\n`),!t.judged){process.stdout.write(` reply: ${Tc(e.reply,200)}\n`),process.stdout.write(` assertions to review:
160
- `);for(let t of e.assertions)process.stdout.write(` - [ ] ${t.assertion}\n`);continue}for(let t of e.assertions){let e=t.verdict===`pass`?`pass`:t.verdict===`fail`?`fail`:`unjudged`;process.stdout.write(` - ${e}: ${t.assertion}\n`),t.reason&&process.stdout.write(` judge verdict: ${t.reason}\n`)}}let e=vc(n.evals);process.stdout.write(`\nSubject ${n.subject}: ${e.passed} passed, ${e.failed} failed, ${e.errored} errored${e.unjudged?`, ${e.unjudged} unjudged`:``}.\n\n`)}let n=wc(e);process.stdout.write(`Totals: ${n.passed} passed, ${n.failed} failed, ${n.errored} errored${n.unjudged?`, ${n.unjudged} unjudged`:``} across ${n.evals} evals.\n`)}function wc(e){let t={passed:0,failed:0,errored:0,unjudged:0,evals:0};for(let n of e)t.passed+=n.passed,t.failed+=n.failed,t.errored+=n.errored,t.unjudged+=n.unjudged,t.evals+=n.evals.length;return t}function Tc(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const Ec=C({meta:{name:`eval`,description:`Run behaviour evals for the seo skill against a local agent and judge the results`},args:{subject:{type:`positional`,required:!1,description:`Eval subject (report id or job). Omit to run every subject.`},list:{type:`boolean`,default:!1,description:`List eval subjects with their eval counts and exit.`},id:{type:`string`,description:`Run one eval id within a single subject.`},agent:{type:`string`,default:rc,description:`Agent command. Use {prompt} to place the prompt in argv, otherwise it is sent on stdin.`},"judge-agent":{type:`string`,description:`Judge command. Defaults to the same command as --agent.`},judge:T(`Judge assertions with an agent.`,`Skip judging and print replies with an assertion checklist.`),skill:T(`Send the seo router skill as context before the prompt.`,`Omit the seo router skill context.`),timeout:{type:`string`,default:`300`,description:`Timeout in seconds per agent or judge call.`},concurrency:{type:`string`,default:`1`,description:`Evals to run in parallel (max 4).`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e);if(e.list===!0){xc(t);return}let n=bc(yc(e)),r=k(e.id);if(r!==void 0&&n.length!==1)throw new y(`INVALID_INPUT`,`--id needs exactly one subject. Name the subject to filter.`);let i=k(e.timeout)??300;if(!(i>0))throw new y(`INVALID_INPUT`,`--timeout must be a positive number of seconds.`);let a=Math.max(1,Math.min(4,k(e.concurrency)??1)),o=E(e.agent)??rc,s=e.judge===!1?null:E(e[`judge-agent`])??o,c=e.skill===!1?null:oc(),l={agent:o,judge:s,skillBody:c,timeoutMs:i*1e3},u=[];for(let e of n){let n=ac(e.subject,e.path).evals;if(r!==void 0&&(n=n.filter(e=>e.id===r),n.length===0))throw new y(`INVALID_INPUT`,`No eval with id ${r} in subject ${e.subject}.`);t||process.stderr.write(`Running ${n.length} eval${n.length===1?``:`s`} for ${e.subject}...\n`);let i=await _c(n,a,e=>hc(e,l)),o=vc(i);u.push({subject:e.subject,...o,evals:i})}let d=wc(u),f=d.failed>0||d.errored>0;t?R({schemaVersion:1,agent:o,judge:s,judged:s!==null,skillContext:c!==null,timeoutSeconds:i,concurrency:a,subjects:u,totals:d}):Cc(u,{judged:s!==null,agent:o,judge:s}),f&&(process.exitCode=1)}});function Dc(){let e=$s();return rn(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&b(S(e,t.name,`SKILL.md`))).map(t=>({name:t.name,description:nc(S(e,t.name)),path:S(e,t.name)})).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}function Oc(e){let t=Dc();if(!e)return t;let n=t.find(t=>t.name===e);if(!n)throw new y(`INVALID_INPUT`,`Unknown skill: ${e}.`);return[n]}const kc=C({meta:{name:`skill`,description:`Inspect the packaged SEO skill and run its evals`},subCommands:{list:C({meta:{name:`list`,description:`Show the packaged SEO skill`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=Dc();if(N(e)){R({skills:t});return}Hr(`SEO skill`,`Packaged with this CLI.`),process.stdout.write(`
161
- `);for(let e of t)z([[`Name`,e.name],[`Purpose`,`Helps agents choose and run the right SEO audit or report.`],[`Path`,e.path]]);process.stdout.write(`
162
- `),Vr({title:`Add it to an agent`,body:`Run setup to install the skill and connect your first site.`,command:`seo start`})}}),path:C({meta:{name:`path`,description:`Print a packaged agent skill path`},args:{name:{type:`positional`,description:`Skill name. Omit it for the skill directory.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=E(e.name),n=t?Oc(t)[0]?.path:$s();N(e)?R({name:t,path:n}):process.stdout.write(`${n}\n`)}}),install:C({meta:{name:`install`,description:`Install the SEO skill for coding agents`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=N(e),n=Ji({quiet:t});if(t){R(n),n.status===`failed`&&(process.exitCode=1);return}if(n.status===`failed`)throw new y(`INTERNAL_ERROR`,`Skill install failed: ${n.error}`);process.stdout.write(`SEO skill installed. Agents that support skills can discover it now.
163
- `)}}),eval:Ec}}),Ac=C({meta:{name:`privacy`,description:`Show local config, token, cache, and log storage paths`},run:async()=>{let e=Qe(),t=Mt();z(e.map(e=>[e.label,`${e.path} · ${Jr(e.sizeBytes)} · ${e.mode}`])),process.stdout.write(`
164
- `),z(Object.entries(t.counts).map(([e,t])=>[e,String(t)]))}}),jc=C({meta:{name:`reset`,description:`Delete local seo config, tokens, cache, and logs`},args:{yes:{type:`boolean`,default:!1,description:`Confirm deletion without prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Yt(),n=N(e);if(!e.yes&&!L({json:n}))throw new y(`INVALID_INPUT`,`Cannot prompt here. Pass --yes to confirm reset.`);if(!(e.yes||H(await Pn({message:`Delete config, tokens, cache, and logs?`,initialValue:!1})))){Nn(`Reset aborted.`);return}await qe(),sn(t.configDir,{recursive:!0,force:!0}),sn(t.cacheDir,{recursive:!0,force:!0}),sn(t.logDir,{recursive:!0,force:!0}),n?R({reset:!0}):process.stdout.write(`Reset complete.
165
- `)}}),Mc=C({meta:{name:`sites`,description:`List Search Console properties available to this Google login`},args:{json:{type:`boolean`,default:!1},refresh:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=await je(O(e.refresh));if(N(e)){R({sites:t});return}B([`Property`,`Permission`],t.map(e=>[e.siteUrl,e.permissionLevel??`unknown`]))}}),Nc=C({meta:{name:`updates`,description:`List official Google Search Status ranking updates`},args:{product:{type:`string`,default:`Ranking`},limit:{type:`string`,default:`10`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=await ct({product:E(e.product),limit:k(e.limit)});if(N(e)){R({updates:t});return}Gr(t.map(e=>({title:e.name,meta:[e.type,e.status,`${e.start.slice(0,10)} to ${e.end?.slice(0,10)??`present`}`]})),{empty:`No matching Google Search updates.`})}}),Pc={ci:`disabled automatically in CI or tests`,do_not_track:`disabled by DO_NOT_TRACK`,environment:`disabled by a telemetry environment variable`,local_setting:`disabled in local settings`,invalid_state:`disabled because the local state file is invalid`};function Fc(e){return{enabled:e.enabled,...e.reason?{reason:e.reason}:{},stateFile:e.stateFile,...e.state?{firstRunAt:e.state.firstRunAt,cohort:e.state.cohort,sentMilestones:e.state.sentMilestones}:{}}}function Ic(e,t){let n=Fc(e);if(t){R(n);return}z([[`Anonymous telemetry`,e.enabled?`enabled`:`disabled`],[`Reason`,e.reason?Pc[e.reason]:`local setting`],[`State file`,e.stateFile],[`Install cohort`,e.state?.cohort??`not created`]]),process.stdout.write(`
269
+ `);for(let n of e){process.stdout.write(`# ${n.subject}\n`);for(let e of n.evals){if(process.stdout.write(`\n[${Dl(e.status)}] eval ${e.id} (${e.durationMs}ms)\n`),process.stdout.write(` prompt: ${Al(e.prompt,100)}\n`),e.error&&process.stdout.write(` error: ${e.error}\n`),!t.judged){process.stdout.write(` reply: ${Al(e.reply,200)}\n`),process.stdout.write(` assertions to review:
270
+ `);for(let t of e.assertions)process.stdout.write(` - [ ] ${t.assertion}\n`);continue}for(let t of e.assertions){let e=t.verdict===`pass`?`pass`:t.verdict===`fail`?`fail`:`unjudged`;process.stdout.write(` - ${e}: ${t.assertion}\n`),t.reason&&process.stdout.write(` judge verdict: ${t.reason}\n`)}}let e=Cl(n.evals);process.stdout.write(`\nSubject ${n.subject}: ${e.passed} passed, ${e.failed} failed, ${e.errored} errored${e.unjudged?`, ${e.unjudged} unjudged`:``}.\n\n`)}let n=kl(e);process.stdout.write(`Totals: ${n.passed} passed, ${n.failed} failed, ${n.errored} errored${n.unjudged?`, ${n.unjudged} unjudged`:``} across ${n.evals} evals.\n`)}function kl(e){let t={passed:0,failed:0,errored:0,unjudged:0,evals:0};for(let n of e)t.passed+=n.passed,t.failed+=n.failed,t.errored+=n.errored,t.unjudged+=n.unjudged,t.evals+=n.evals.length;return t}function Al(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const jl=w({meta:{name:`eval`,description:`Run behaviour evals for the seo skill against a local agent and judge the results`},args:{subject:{type:`positional`,required:!1,description:`Eval subject (report id or job). Omit to run every subject.`},list:{type:`boolean`,default:!1,description:`List eval subjects with their eval counts and exit.`},id:{type:`string`,description:`Run one eval id within a single subject.`},agent:{type:`string`,default:cl,description:`Agent command. Use {prompt} to place the prompt in argv, otherwise it is sent on stdin.`},"judge-agent":{type:`string`,description:`Judge command. Defaults to the same command as --agent.`},judge:Br(`Judge assertions with an agent.`,`Skip judging and print replies with an assertion checklist.`),skill:Br(`Send the seo router skill as context before the prompt.`,`Omit the seo router skill context.`),timeout:{type:`string`,default:`300`,description:`Timeout in seconds per agent or judge call.`},concurrency:{type:`string`,default:`1`,description:`Evals to run in parallel (max 4).`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e);if(e.list===!0){El(t);return}let n=Tl(wl(e)),r=A(e.id);if(r!==void 0&&n.length!==1)throw new b(`INVALID_INPUT`,`--id needs exactly one subject. Name the subject to filter.`);let i=A(e.timeout)??300;if(!(i>0))throw new b(`INVALID_INPUT`,`--timeout must be a positive number of seconds.`);let a=Math.max(1,Math.min(4,A(e.concurrency)??1)),o=D(e.agent)??cl,s=e.judge===!1?null:D(e[`judge-agent`])??o,c=e.skill===!1?null:dl(),l={agent:o,judge:s,skillBody:c,timeoutMs:i*1e3},u=[];for(let e of n){let n=ul(e.subject,e.path).evals;if(r!==void 0&&(n=n.filter(e=>e.id===r),n.length===0))throw new b(`INVALID_INPUT`,`No eval with id ${r} in subject ${e.subject}.`);t||process.stderr.write(`Running ${n.length} eval${n.length===1?``:`s`} for ${e.subject}...\n`);let i=await Sl(n,a,e=>bl(e,l)),o=Cl(i);u.push({subject:e.subject,...o,evals:i})}let d=kl(u),f=d.failed>0||d.errored>0;t?z({schemaVersion:1,agent:o,judge:s,judged:s!==null,skillContext:c!==null,timeoutSeconds:i,concurrency:a,subjects:u,totals:d}):Ol(u,{judged:s!==null,agent:o,judge:s}),f&&(process.exitCode=1)}});function Ml(){let e=il();return En(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&x(C(e,t.name,`SKILL.md`))).map(t=>({name:t.name,description:sl(C(e,t.name)),path:C(e,t.name)})).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}function Nl(e){let t=Ml();if(!e)return t;let n=t.find(t=>t.name===e);if(!n)throw new b(`INVALID_INPUT`,`Unknown skill: ${e}.`);return[n]}const Pl=w({meta:{name:`skill`,description:`Inspect the packaged SEO skill and run its evals`},subCommands:{list:w({meta:{name:`list`,description:`Show the packaged SEO skill`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=Ml();if(P(e)){z({skills:t});return}Si(`SEO skill`,`Packaged with this CLI.`),process.stdout.write(`
271
+ `);for(let e of t)B([[`Name`,e.name],[`Purpose`,`Helps agents choose and run the right SEO audit or report.`],[`Path`,e.path]]);process.stdout.write(`
272
+ `),xi({title:`Add it to an agent`,body:`Run setup to install the skill and connect your first site.`,command:`seo start`})}}),path:w({meta:{name:`path`,description:`Print a packaged agent skill path`},args:{name:{type:`positional`,description:`Skill name. Omit it for the skill directory.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=D(e.name),n=t?Nl(t)[0]?.path:il();P(e)?z({name:t,path:n}):process.stdout.write(`${n}\n`)}}),install:w({meta:{name:`install`,description:`Install the SEO skill for coding agents`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=P(e),n=ka({quiet:t});if(t){z(n),n.status===`failed`&&(process.exitCode=1);return}if(n.status===`failed`)throw new b(`INTERNAL_ERROR`,`Skill install failed: ${n.error}`);process.stdout.write(`SEO skill installed. Agents that support skills can discover it now.
273
+ `)}}),eval:jl}}),Fl=w({meta:{name:`privacy`,description:`Show local config, token, cache, and log storage paths`},run:async()=>{let e=we(),t=At();B(e.map(e=>[e.label,`${e.path} · ${ki(e.sizeBytes)} · ${e.mode}`])),process.stdout.write(`
274
+ `),B(Object.entries(t.counts).map(([e,t])=>[e,String(t)]))}}),Il=w({meta:{name:`reset`,description:`Delete local seo config, tokens, cache, and logs`},args:{yes:{type:`boolean`,default:!1,description:`Confirm deletion without prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Ve(),n=P(e);if(!e.yes&&!R({json:n}))throw new b(`INVALID_INPUT`,`Cannot prompt here. Pass --yes to confirm reset.`);if(!(e.yes||H(await ir({message:`Delete config, tokens, cache, and logs?`,initialValue:!1})))){rr(`Reset aborted.`);return}await ve(),kn(t.configDir,{recursive:!0,force:!0}),kn(t.cacheDir,{recursive:!0,force:!0}),kn(t.logDir,{recursive:!0,force:!0}),n?z({reset:!0}):process.stdout.write(`Reset complete.
275
+ `)}}),Ll=w({meta:{name:`sites`,description:`List Search Console properties available to this Google login`},args:{json:{type:`boolean`,default:!1},refresh:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=await sn(k(e.refresh));if(P(e)){z({sites:t});return}V([`Property`,`Permission`],t.map(e=>[e.siteUrl,e.permissionLevel??`unknown`]))}}),Rl=w({meta:{name:`updates`,description:`List official Google Search Status ranking updates`},args:{product:{type:`string`,default:`Ranking`},limit:{type:`string`,default:`10`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=await ee({product:D(e.product),limit:A(e.limit)});if(P(e)){z({updates:t});return}Ti(t.map(e=>({title:e.name,meta:[e.type,e.status,`${e.start.slice(0,10)} to ${e.end?.slice(0,10)??`present`}`]})),{empty:`No matching Google Search updates.`})}}),zl={ci:`disabled automatically in CI or tests`,do_not_track:`disabled by DO_NOT_TRACK`,environment:`disabled by a telemetry environment variable`,local_setting:`disabled in local settings`,invalid_state:`disabled because the local state file is invalid`};function Bl(e){return{enabled:e.enabled,...e.reason?{reason:e.reason}:{},stateFile:e.stateFile,...e.state?{firstRunAt:e.state.firstRunAt,cohort:e.state.cohort,sentMilestones:e.state.sentMilestones}:{}}}function Vl(e,t){let n=Bl(e);if(t){z(n);return}B([[`Anonymous telemetry`,e.enabled?`enabled`:`disabled`],[`Reason`,e.reason?zl[e.reason]:`local setting`],[`State file`,e.stateFile],[`Install cohort`,e.state?.cohort??`not created`]]),process.stdout.write(`
166
276
  Only tool usage is sent. URLs, report data, Google data, and identifiers are never sent.
167
277
  `),process.stdout.write(`Details: https://seoskill.dev/telemetry
168
- `)}const Lc={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},Rc=C({meta:{name:`telemetry`,description:`Check or change anonymous usage telemetry`},subCommands:{status:C({meta:{name:`status`,description:`Show whether anonymous usage telemetry is enabled`},args:{json:Lc},run:async({args:e})=>Ic(Lt(),N(e))}),enable:C({meta:{name:`enable`,description:`Enable anonymous usage telemetry in local settings`},args:{json:Lc},run:async({args:e})=>{Ic(Ze(!0),N(e))}}),disable:C({meta:{name:`disable`,description:`Disable anonymous usage telemetry in local settings`},args:{json:Lc},run:async({args:e})=>{Ic(Ze(!1),N(e))}})}}),zc=C({meta:{name:`crawl-queue`,description:`Run a crawl and return a ranked implementation queue`},args:{crawlUrl:{type:`positional`,required:!1,description:`Start URL to crawl.`},url:{type:`string`,description:`Start URL to crawl. Optional when --project has a saved crawl URL.`},site:{type:`string`,description:`GSC property URL for joining page metrics.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},"google-analytics-property":{type:`string`,description:`Google Analytics property ID for landing-page sessions. Defaults from --project when saved.`},mode:{type:`string`,description:`Crawl mode: site, page, list, or sitemap. Defaults to site.`},urls:{type:`string`,description:`Comma-separated URLs for list mode.`},"urls-file":{type:`string`,description:`File with one URL per line for list mode.`},"max-pages":{type:`string`,description:`Maximum pages to crawl. Defaults to 500.`},"max-depth":{type:`string`,description:`Maximum click depth. Defaults to 16.`},concurrency:{type:`string`,description:`Parallel page fetches. Defaults to 8.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache and fetch fresh pages.`},include:{type:`string`,description:`Comma-separated URL patterns to include.`},exclude:{type:`string`,description:`Comma-separated URL patterns to exclude.`},limit:{type:`string`,description:`Maximum queue items to print. Defaults to 25.`},"no-sitemap":{type:`boolean`,default:!1,description:`Do not seed URLs from sitemap.xml.`},"no-robots":{type:`boolean`,default:!1,description:`Do not skip URLs disallowed by robots.txt.`},"no-external":{type:`boolean`,default:!1,description:`Do not check external links.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering when Playwright is installed.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),r=D(e),i=await Hc(e),a=Vc(e),o=E(e.site)||r||!a&&!i.length?await U({client:r,site:E(e.site),options:{json:t}}):void 0,s=a??o?.client?.startUrl??(o?.site?yi(o.site):void 0)??i[0];if(!s)throw Error(`No crawl URL selected. Pass a URL, --url, or use --project with a saved crawl URL.`);let c=await n({url:s,projectId:o?.client?.id,site:o?.site,mode:Bc(e.mode)??(i.length?`list`:void 0),urls:i,maxPages:k(e[`max-pages`]),maxDepth:k(e[`max-depth`]),concurrency:k(e.concurrency),refresh:O(e.refresh),fetchRate:dr({...e,"fetch-concurrency":e.concurrency}),include:j(e.include),exclude:j(e.exclude),googleAnalyticsPropertyId:E(e[`google-analytics-property`])??o?.client?.analytics.google?.propertyId,useSitemap:!cr(e,`sitemap`),respectRobots:!cr(e,`robots`),checkExternal:!cr(e,`external`),js:!!O(e.js),limit:k(e.limit)});if(t){R(c);return}Qo(c),B([`Rank`,`Score`,`Rule`,`Severity`,`Affected`,`Target`,`Action`],c.output.queue.map((e,t)=>[t+1,e.score,e.ruleId,e.severity,e.affectedUrls,e.target,e.action])),J(`Implementation queue details`,c.output.queue.map(e=>({label:`${e.ruleId} (${e.affectedUrls} URLs)`,context:`${e.severity}, score ${e.score}`,action:`${e.action} Verify with: ${e.verification.command}`})))}});function Bc(e){let t=E(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function Vc(e){let t=E(e.crawlUrl),n=E(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}async function Hc(e){let t=j(e.urls)??[],n=E(e[`urls-file`]);return n&&t.push(...Uc(await En(n,`utf8`))),[...new Set(t)]}function Uc(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}function Wc(e,t){let{narrative:n}=e.output,{diagnosis:r}=n;return{...e,...t?{workflow:t}:{},output:{narrative:{site:n.site,generatedAt:n.generatedAt,dataStatus:n.dataStatus,periodDays:n.periodDays,period:n.period,headline:n.headline,caveats:n.caveats,sections:n.sections,priorities:n.priorities,diagnosis:{site:r.site,generatedAt:r.generatedAt,dataStatus:r.dataStatus,summary:r.summary,skippedSections:r.skippedSections,partialReasons:r.partialReasons,priorities:r.priorities}}}}}function Gc(e){return/^[A-Za-z0-9_./:@-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function Kc(e){try{return new URL(e).origin}catch{throw new y(`INVALID_INPUT`,`Pass a valid absolute URL with --url.`)}}function Q(e,t,n){e.some(e=>e.command===t)||e.push({command:t,why:n})}function qc(e){if(!e)return[];let t=e=>{let t=e.window?` in the last ${e.window.days} days`:``,n=`for ${e.joinedPages} of ${e.totalPages} crawled URLs`;return e.status===`skipped`?`${e.label}: not connected.`:e.status===`unavailable`?`${e.label}: unavailable. ${e.warning??`No data was joined.`}`:e.status===`partial`?`${e.label}: partial data ${n}${t}. ${e.warning??``}`.trim():e.status===`none`?`${e.label}: no matching crawled URLs${t}.`:`${e.label}: joined ${n}${t}.`};return[t({label:`Search Console`,status:e.searchConsole.status,joinedPages:Math.max(e.searchConsole.joinedMetricPages,e.searchConsole.joinedQueryPages),totalPages:e.searchConsole.totalPages,window:e.searchConsole.window,warning:e.searchConsole.warning}),t({label:`Google Analytics`,status:e.analytics.status,joinedPages:e.analytics.joinedPages,totalPages:e.analytics.totalPages,window:e.analytics.window,warning:e.analytics.warning})]}function Jc(e){let t=e.report;return t?{status:e.status,...e.reason?{reason:e.reason}:{},reportId:t.id,generatedAt:t.generatedAt,crawlStatus:t.status,capped:t.summary.pageLimitReached,maxPages:t.config.maxPages,searchDataJoined:(t.dataSources?.searchConsole.joinedMetricPages??0)>0||(t.dataSources?.searchConsole.joinedQueryPages??0)>0,dataSources:t.dataSources,summary:t.summary,topFixes:Wt(t,{limit:5}),reviewObservations:s(t,{limit:5})}:{status:e.status,...e.reason?{reason:e.reason}:{}}}function Yc(e){return{ruleId:e.ruleId,title:e.title,category:e.category,severity:e.severity,recommendation:e.recommendation,count:e.count,sampleUrls:e.sampleUrls.slice(0,3),score:e.score,scoreFactors:e.scoreFactors,whyThisRanks:e.whyThisRanks,detailsCommand:`seo explain --rule ${e.ruleId}`}}function Xc(e){return`topFixes`in e?{...e,topFixes:e.topFixes.slice(0,3).map(Yc),reviewObservations:e.reviewObservations.slice(0,3).map(Yc)}:e}function Zc(e,t={}){if(!(`topFixes`in e)){process.stdout.write(`\nTechnical crawl evidence: ${e.reason??e.status}\n`);return}let n=e.status===`reused`?`saved`:`new`;if(process.stdout.write(`\nTechnical crawl evidence (${n})\n`),e.reason&&process.stdout.write(`${e.reason}\n`),e.capped&&process.stdout.write(`Coverage is capped at ${e.maxPages} pages. Run \`seo crawl\` for a broader investigation.\n`),!t.providerFree)for(let t of qc(e.dataSources))process.stdout.write(`${t}\n`);if(!e.topFixes.length){process.stdout.write(`No prioritised technical fixes were found.
278
+ `)}const Hl={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},Ul=w({meta:{name:`telemetry`,description:`Check or change anonymous usage telemetry`},subCommands:{status:w({meta:{name:`status`,description:`Show whether anonymous usage telemetry is enabled`},args:{json:Hl},run:async({args:e})=>Vl(nn(),P(e))}),enable:w({meta:{name:`enable`,description:`Enable anonymous usage telemetry in local settings`},args:{json:Hl},run:async({args:e})=>{Vl(mt(!0),P(e))}}),disable:w({meta:{name:`disable`,description:`Disable anonymous usage telemetry in local settings`},args:{json:Hl},run:async({args:e})=>{Vl(mt(!1),P(e))}})}}),Wl=w({meta:{name:`crawl-queue`,description:`Run a crawl and return a ranked implementation queue`},args:{crawlUrl:{type:`positional`,required:!1,description:`Start URL to crawl.`},url:{type:`string`,description:`Start URL to crawl. Optional when --project has a saved crawl URL.`},site:{type:`string`,description:`GSC property URL for joining page metrics.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},"google-analytics-property":{type:`string`,description:`Google Analytics property ID for landing-page sessions. Defaults from --project when saved.`},mode:{type:`string`,description:`Crawl mode: site, page, list, or sitemap. Defaults to site.`},urls:{type:`string`,description:`Comma-separated URLs for list mode.`},"urls-file":{type:`string`,description:`File with one URL per line for list mode.`},"max-pages":{type:`string`,description:`Maximum pages to crawl. Defaults to 500.`},"max-depth":{type:`string`,description:`Maximum click depth. Defaults to 16.`},concurrency:{type:`string`,description:`Parallel page fetches. Defaults to 8.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache and fetch fresh pages.`},include:{type:`string`,description:`Comma-separated URL patterns to include.`},exclude:{type:`string`,description:`Comma-separated URL patterns to exclude.`},limit:{type:`string`,description:`Maximum queue items to print. Defaults to 25.`},"no-sitemap":{type:`boolean`,default:!1,description:`Do not seed URLs from sitemap.xml.`},"no-robots":{type:`boolean`,default:!1,description:`Do not skip URLs disallowed by robots.txt.`},"no-external":{type:`boolean`,default:!1,description:`Do not check external links.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering when Playwright is installed.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=O(e),r=await ql(e),i=Kl(e),a=D(e.site)||n||!i&&!r.length?await U({client:n,site:D(e.site),options:{json:t}}):void 0,o=i??a?.client?.startUrl??(a?.site?ea(a.site):void 0)??r[0];if(!o)throw Error(`No crawl URL selected. Pass a URL, --url, or use --project with a saved crawl URL.`);let s=await Ee({url:o,projectId:a?.client?.id,site:a?.site,mode:Gl(e.mode)??(r.length?`list`:void 0),urls:r,maxPages:A(e[`max-pages`]),maxDepth:A(e[`max-depth`]),concurrency:A(e.concurrency),refresh:k(e.refresh),fetchRate:Gr({...e,"fetch-concurrency":e.concurrency}),include:M(e.include),exclude:M(e.exclude),googleAnalyticsPropertyId:D(e[`google-analytics-property`])??a?.client?.analytics.google?.propertyId,useSitemap:!Hr(e,`sitemap`),respectRobots:!Hr(e,`robots`),checkExternal:!Hr(e,`external`),js:!!k(e.js),limit:A(e.limit)});if(t){z(s);return}Ws(s),V([`Rank`,`Score`,`Rule`,`Severity`,`Affected`,`Target`,`Action`],s.output.queue.map((e,t)=>[t+1,e.score,e.ruleId,e.severity,e.affectedUrls,e.target,e.action])),J(`Implementation queue details`,s.output.queue.map(e=>({label:`${e.ruleId} (${e.affectedUrls} URLs)`,context:`${e.severity}, score ${e.score}`,action:`${e.action} Verify with: ${e.verification.command}`})))}});function Gl(e){let t=D(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function Kl(e){let t=D(e.crawlUrl),n=D(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}async function ql(e){let t=M(e.urls)??[],n=D(e[`urls-file`]);return n&&t.push(...Jl(await Jn(n,`utf8`))),[...new Set(t)]}function Jl(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}function Yl(e,t){let{narrative:n}=e.output,{diagnosis:r}=n;return{...e,...t?{workflow:t}:{},output:{narrative:{site:n.site,generatedAt:n.generatedAt,dataStatus:n.dataStatus,periodDays:n.periodDays,period:n.period,headline:n.headline,caveats:n.caveats,sections:n.sections,priorities:n.priorities,diagnosis:{site:r.site,generatedAt:r.generatedAt,dataStatus:r.dataStatus,summary:r.summary,skippedSections:r.skippedSections,partialReasons:r.partialReasons,priorities:r.priorities}}}}}function Xl(e){return/^[A-Za-z0-9_./:@-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function Zl(e){try{return new URL(e).origin}catch{throw new b(`INVALID_INPUT`,`Pass a valid absolute URL with --url.`)}}function Q(e,t,n){e.some(e=>e.command===t)||e.push({command:t,why:n})}function Ql(e){if(!e)return[];let t=e=>{let t=e.window?` in the last ${e.window.days} days`:``,n=`for ${e.joinedPages} of ${e.totalPages} crawled URLs`;return e.status===`skipped`?`${e.label}: not connected.`:e.status===`unavailable`?`${e.label}: unavailable. ${e.warning??`No data was joined.`}`:e.status===`partial`?`${e.label}: partial data ${n}${t}. ${e.warning??``}`.trim():e.status===`none`?`${e.label}: no matching crawled URLs${t}.`:`${e.label}: joined ${n}${t}.`};return[t({label:`Search Console`,status:e.searchConsole.status,joinedPages:Math.max(e.searchConsole.joinedMetricPages,e.searchConsole.joinedQueryPages),totalPages:e.searchConsole.totalPages,window:e.searchConsole.window,warning:e.searchConsole.warning}),t({label:`Google Analytics`,status:e.analytics.status,joinedPages:e.analytics.joinedPages,totalPages:e.analytics.totalPages,window:e.analytics.window,warning:e.analytics.warning})]}function $l(e){let t=e.report;return t?{status:e.status,...e.reason?{reason:e.reason}:{},reportId:t.id,generatedAt:t.generatedAt,crawlStatus:t.status,capped:t.summary.pageLimitReached,maxPages:t.config.maxPages,searchDataJoined:(t.dataSources?.searchConsole.joinedMetricPages??0)>0||(t.dataSources?.searchConsole.joinedQueryPages??0)>0,dataSources:t.dataSources,summary:t.summary,topFixes:ue(t,{limit:5}),reviewObservations:v(t,{limit:5})}:{status:e.status,...e.reason?{reason:e.reason}:{}}}function eu(e){return{ruleId:e.ruleId,title:e.title,category:e.category,severity:e.severity,recommendation:e.recommendation,count:e.count,sampleUrls:e.sampleUrls.slice(0,3),score:e.score,scoreFactors:e.scoreFactors,whyThisRanks:e.whyThisRanks,detailsCommand:`seo explain --rule ${e.ruleId}`}}function tu(e){return`topFixes`in e?{...e,topFixes:e.topFixes.slice(0,3).map(eu),reviewObservations:e.reviewObservations.slice(0,3).map(eu)}:e}function nu(e,t={}){if(!(`topFixes`in e)){process.stdout.write(`\nTechnical crawl evidence: ${e.reason??e.status}\n`);return}let n=e.status===`reused`?`saved`:`new`;if(process.stdout.write(`\nTechnical crawl evidence (${n})\n`),e.reason&&process.stdout.write(`${e.reason}\n`),e.capped&&process.stdout.write(`Coverage is capped at ${e.maxPages} pages. Run \`seo crawl\` for a broader investigation.\n`),!t.providerFree)for(let t of Ql(e.dataSources))process.stdout.write(`${t}\n`);if(!e.topFixes.length){process.stdout.write(`No prioritised technical fixes were found.
169
279
  `),e.reviewObservations.length&&process.stdout.write(`${e.reviewObservations.length} review observation${e.reviewObservations.length===1?``:`s`} need confirmation before they become implementation work.\n`);return}process.stdout.write(t.providerFree?`
170
280
  Prioritised technical fixes
171
281
  `:e.searchDataJoined?`
172
282
  Technical fixes with search value
173
283
  `:`
174
284
  Technical fixes (no Search Console data joined)
175
- `),e.searchDataJoined?B([`Score`,`Rule`,`Severity`,`Search value`,`Verify`],e.topFixes.map(e=>[e.score,e.ruleId,e.severity,`${e.scoreFactors.clicks} clicks / ${e.scoreFactors.sessions} sessions / ${e.scoreFactors.conversions} conv.`,K(e.howToVerify,72)])):B([`#`,`Rule`,`Severity`,`Affected URLs`,`Verify`],e.topFixes.map((e,t)=>[t+1,e.ruleId,e.severity,e.count,K(e.howToVerify,72)])),e.reviewObservations.length&&process.stdout.write(`\n${e.reviewObservations.length} review observation${e.reviewObservations.length===1?``:`s`} were kept out of this action queue.\n`)}function Qc(e){process.stdout.write(`
285
+ `),e.searchDataJoined?V([`Score`,`Rule`,`Severity`,`Search value`,`Verify`],e.topFixes.map(e=>[e.score,e.ruleId,e.severity,`${e.scoreFactors.clicks} clicks / ${e.scoreFactors.sessions} sessions / ${e.scoreFactors.conversions} conv.`,K(e.howToVerify,72)])):V([`#`,`Rule`,`Severity`,`Affected URLs`,`Verify`],e.topFixes.map((e,t)=>[t+1,e.ruleId,e.severity,e.count,K(e.howToVerify,72)])),e.reviewObservations.length&&process.stdout.write(`\n${e.reviewObservations.length} review observation${e.reviewObservations.length===1?``:`s`} were kept out of this action queue.\n`)}function ru(e){process.stdout.write(`
176
286
  Provider-backed sections skipped
177
- `);let t=`dataSources`in e?qc(e.dataSources):[],n=t.length?t:[`Search Console: not connected.`,`Google Analytics: not connected.`];for(let e of n)process.stdout.write(`${e}\n`);process.stdout.write("Run `seo start` when you want traffic, query, ranking, and analytics evidence added to the report.\n")}function $c(e){if(!(`topFixes`in e))return`Technical crawl evidence was ${e.status}. Search Console and Google Analytics sections were skipped because they are not connected.`;let t=e.status===`reused`?`Loaded`:`Completed`,n=e.summary.crawledUrls;return`${t} a technical crawl of ${n} ${n===1?`page`:`pages`}. Search Console and Google Analytics sections were skipped because they are not connected.`}function el(e){if(!(`topFixes`in e))return{tool:`seo_crawl`,status:`skipped`,summary:e.reason??`Technical crawl evidence was ${e.status}.`};let t=e.summary.crawledUrls;return{tool:`seo_crawl`,status:`completed`,summary:`${e.status===`reused`?`Loaded`:`Completed`} technical evidence for ${t} crawled ${t===1?`page`:`pages`}.`}}function tl(e,t={}){if(t.searchDataAvailable===!1){let e=[];return t.crawlStartUrl&&t.technicalBaselineStatus!==`created`&&t.technicalBaselineStatus!==`refreshed`&&t.technicalBaselineStatus!==`reused`?(Q(e,`seo crawl --url ${Gc(t.crawlStartUrl)} --health`,`Run the fast sitemap response and access gate before fetching page bodies.`),Q(e,`seo crawl --url ${Gc(t.crawlStartUrl)} --save`,`Create the technical crawl that this report needs before opening a page-level follow-up.`)):t.crawlStartUrl&&Q(e,`seo audit-page --url ${Gc(t.crawlStartUrl)}`,`Inspect one important page in detail after the site-level crawl.`),Q(e,`seo start`,`Connect Search Console when you want traffic, query, and ranking evidence alongside the crawl.`),e}let n=t.projectId?`--project ${Gc(t.projectId)}`:`--site ${Gc(e.site)}`,r=e.output.narrative.diagnosis,i=r.decay.rangeDays,a=[],o=new Set((r.skippedSections??[]).map(e=>e.section));Q(a,`seo refresh-priorities ${n} --days ${i} --verify-content --limit 25`,`Turn the report into a ranked action queue with content checks.`),r.decay.summary.eligibleRows>0&&Q(a,`seo decaying ${n} --days ${i} --limit 25`,`Inspect query/page declines observed in both retained-row windows.`),r.cannibalization.items.length>0&&Q(a,`seo cannibal ${n} --days ${i} --limit 25`,`Find queries split across competing URLs.`),r.quickWins.summary.eligibleRows>0&&Q(a,`seo quick-wins ${n} --days ${i} --verify-content --verify-limit 5`,`Review average-position rows below their heuristic CTR target with optional page evidence.`),r.strikingDistance.summary.eligibleRows>0&&Q(a,`seo second-page ${n} --days ${i} --verify-content --verify-limit 5`,`Work pages sitting just outside page-one rankings.`),(o.has(`traffic anomaly`)||o.has(`update correlation`))&&(Q(a,`seo quick-wins ${n} --days ${i} --min-impressions 10 --verify-content --verify-limit 5`,`Sparse GSC data: lower thresholds and look for early content wins.`),Q(a,`seo second-page ${n} --days ${i} --min-impressions 10 --verify-content --verify-limit 5`,`Sparse GSC data: inspect early second-page opportunities.`));let s=r.segments.page.items.find(e=>e.key.startsWith(`http`));return s&&Q(a,`seo audit-page --url ${Gc(s.key)}`,`Audit the biggest moved URL for title, metadata, links, and schema.`),t.crawlStartUrl&&t.technicalBaselineStatus!==`created`&&t.technicalBaselineStatus!==`refreshed`&&t.technicalBaselineStatus!==`reused`&&(Q(a,`seo crawl --url ${Gc(t.crawlStartUrl)} --health`,`Run the fast sitemap response and access gate before fetching page bodies.`),Q(a,`seo crawl --url ${Gc(t.crawlStartUrl)} ${n} --save`,`Create the first technical crawler baseline with plain-English fixes and JSON-ready issue data.`)),Q(a,`seo technical-watch ${n} --limit 50`,`Save a crawl/index baseline so future reports can flag technical drift.`),a.slice(0,6)}function nl(e){e.length&&(process.stdout.write(`
287
+ `);let t=`dataSources`in e?Ql(e.dataSources):[],n=t.length?t:[`Search Console: not connected.`,`Google Analytics: not connected.`];for(let e of n)process.stdout.write(`${e}\n`);process.stdout.write("Run `seo start` when you want traffic, query, ranking, and analytics evidence added to the report.\n")}function iu(e){let t=[],n=e.technicalCrawl;return n&&(`topFixes`in n?t.push({title:`Technical crawl evidence`,summary:`${n.summary.crawledUrls} pages were included in the ${n.status===`reused`?`saved`:`new`} crawl evidence.`,items:[...n.topFixes.map(e=>`${e.ruleId}: ${e.title}. ${e.count} affected URLs. ${e.recommendation}`),...Ql(n.dataSources)]}):t.push({title:`Technical crawl evidence`,summary:n.reason??`Technical evidence was ${n.status}.`,items:[]})),e.followups?.length&&t.push({title:`Recommended next commands`,items:e.followups.map(e=>`${e.command}: ${e.why}`)}),t}function au(e){if(!(`topFixes`in e))return`Technical crawl evidence was ${e.status}. Search Console and Google Analytics sections were skipped because they are not connected.`;let t=e.status===`reused`?`Loaded`:`Completed`,n=e.summary.crawledUrls;return`${t} a technical crawl of ${n} ${n===1?`page`:`pages`}. Search Console and Google Analytics sections were skipped because they are not connected.`}function ou(e){if(!(`topFixes`in e))return{tool:`seo_crawl`,status:`skipped`,summary:e.reason??`Technical crawl evidence was ${e.status}.`};let t=e.summary.crawledUrls;return{tool:`seo_crawl`,status:`completed`,summary:`${e.status===`reused`?`Loaded`:`Completed`} technical evidence for ${t} crawled ${t===1?`page`:`pages`}.`}}function su(e,t={}){if(t.searchDataAvailable===!1){let e=[];return t.crawlStartUrl&&t.technicalBaselineStatus!==`created`&&t.technicalBaselineStatus!==`refreshed`&&t.technicalBaselineStatus!==`reused`?(Q(e,`seo crawl --url ${Xl(t.crawlStartUrl)} --health`,`Run the fast sitemap response and access gate before fetching page bodies.`),Q(e,`seo crawl --url ${Xl(t.crawlStartUrl)} --save`,`Create the technical crawl that this report needs before opening a page-level follow-up.`)):t.crawlStartUrl&&Q(e,`seo audit-page --url ${Xl(t.crawlStartUrl)}`,`Inspect one important page in detail after the site-level crawl.`),Q(e,`seo start`,`Connect Search Console when you want traffic, query, and ranking evidence alongside the crawl.`),e}let n=t.projectId?`--project ${Xl(t.projectId)}`:`--site ${Xl(e.site)}`,r=e.output.narrative.diagnosis,i=r.decay.rangeDays,a=[],o=new Set((r.skippedSections??[]).map(e=>e.section));Q(a,`seo refresh-priorities ${n} --days ${i} --verify-content --limit 25`,`Turn the report into a ranked action queue with content checks.`),r.decay.summary.eligibleRows>0&&Q(a,`seo decaying ${n} --days ${i} --limit 25`,`Inspect query/page declines observed in both retained-row windows.`),r.cannibalization.items.length>0&&Q(a,`seo cannibal ${n} --days ${i} --limit 25`,`Find queries split across competing URLs.`),r.quickWins.summary.eligibleRows>0&&Q(a,`seo quick-wins ${n} --days ${i} --verify-content --verify-limit 5`,`Review average-position rows below their heuristic CTR target with optional page evidence.`),r.strikingDistance.summary.eligibleRows>0&&Q(a,`seo second-page ${n} --days ${i} --verify-content --verify-limit 5`,`Work pages sitting just outside page-one rankings.`),(o.has(`traffic anomaly`)||o.has(`update correlation`))&&(Q(a,`seo quick-wins ${n} --days ${i} --min-impressions 10 --verify-content --verify-limit 5`,`Sparse GSC data: lower thresholds and look for early content wins.`),Q(a,`seo second-page ${n} --days ${i} --min-impressions 10 --verify-content --verify-limit 5`,`Sparse GSC data: inspect early second-page opportunities.`));let s=r.segments.page.items.find(e=>e.key.startsWith(`http`));return s&&Q(a,`seo audit-page --url ${Xl(s.key)}`,`Audit the biggest moved URL for title, metadata, links, and schema.`),t.crawlStartUrl&&t.technicalBaselineStatus!==`created`&&t.technicalBaselineStatus!==`refreshed`&&t.technicalBaselineStatus!==`reused`&&(Q(a,`seo crawl --url ${Xl(t.crawlStartUrl)} --health`,`Run the fast sitemap response and access gate before fetching page bodies.`),Q(a,`seo crawl --url ${Xl(t.crawlStartUrl)} ${n} --save`,`Create the first technical crawler baseline with plain-English fixes and JSON-ready issue data.`)),Q(a,`seo technical-watch ${n} --limit 50`,`Save a crawl/index baseline so future reports can flag technical drift.`),a.slice(0,6)}function cu(e){e.length&&(process.stdout.write(`
178
288
  Recommended next commands
179
- `),B([`Command`,`Why`],e.map(e=>[e.command,e.why])))}function rl(e){process.stdout.write(`# Technical SEO report: ${e}\n\n`)}function il(e){return C({meta:e,args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},...e.printFollowups?{url:{type:`string`,description:`Crawl URL for a technical-only report. Search Console analyses are skipped unless you also pass --site or --project.`}}:{},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Search performance window in days. Defaults to 90.`},limit:{description:`Maximum rows per section. Defaults to 10.`}}),...e.printFollowups?{crawl:T(`Create or reuse a bounded technical crawl before the report.`,`Skip technical crawl evidence for this report.`),"crawl-max-pages":{type:`string`,description:`Maximum pages for the report crawl. Defaults to 100.`},"crawl-max-depth":{type:`string`,description:`Maximum link depth for the report crawl. Defaults to 4.`},full:{type:`boolean`,default:!1,description:`Include the full report in JSON output. Default JSON is a compact summary for agents.`}}:{},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:t})=>{let n=N(t),i=e.printFollowups&&O(t.full),a=D(t),o=E(t.site),s=e.printFollowups?E(t.url):void 0,c=!!(a||o||!s),l=c?await U({client:a,site:o,options:{json:n,refresh:O(t.refresh)}}):void 0,u=l?.site??Kc(s??``),d=await dt({site:u,days:k(t.days),recentDays:k(t.recent),limit:k(t.limit),brandTerms:l?.client?.brandTerms,includeBrand:O(t[`include-brand`]),refresh:O(t.refresh),skipSearchData:!c}),f=e.workflowName?{...d,workflow:e.workflowName}:d,p=e.printFollowups?await r({site:u,searchSite:l?.site,url:s??l?.client?.startUrl??yi(u),projectId:l?.client?.id,googleAnalyticsPropertyId:l?.client?.analytics.google?.propertyId,crawl:!cr(t,`crawl`),refresh:O(t.refresh),maxPages:k(t[`crawl-max-pages`]),maxDepth:k(t[`crawl-max-depth`])}):void 0,m=p?Jc(p):void 0,h=e.printFollowups?tl(f,{crawlStartUrl:s??l?.client?.startUrl??yi(u),projectId:l?.client?.id,technicalBaselineStatus:p?.status,searchDataAvailable:c}):void 0;if(n){let t=e.printFollowups&&!i?Wc(d,e.workflowName):f,n=!c&&m?{...t,summary:$c(m),steps:[el(m),...t.steps]}:t;R(m||h?{...n,...e.printFollowups?{detail:i?`full`:`summary`}:{},...m?{technicalCrawl:e.printFollowups&&!i?Xc(m):m}:{},...h?{nextCommands:h}:{}}:t);return}c?(process.stdout.write(`${f.output.narrative.markdown}\n\n`),Qo(f)):rl(u),m&&(Zc(m,{providerFree:!c}),c||Qc(m)),h&&nl(h)}})}const al=il({name:`diagnose-property`,description:`Find what changed in Google Search and what to inspect next`}),ol=il({name:`report`,workflowName:`report`,printFollowups:!0,description:`Run the main SEO report and recommend the next best follow-up commands`}),sl=C({meta:{name:`refresh-priorities`,description:`Agent workflow for a ranked SEO action queue`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum queue items to print. Defaults to 25.`}}),"google-analytics-property":{type:`string`,description:`Google Analytics property ID to use for analytics value. Defaults from the selected project.`},"verify-content":T(`Verify top opportunities against page title, meta, and content. Defaults to true.`,`Skip page content verification.`),"verify-limit":{type:`string`,description:`Maximum opportunity URLs to verify. Defaults to 5.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),r=await de({site:n.site,days:k(e.days),recentDays:k(e.recent),limit:k(e.limit),brandTerms:n.client?.brandTerms,includeBrand:O(e[`include-brand`]),googleAnalyticsPropertyId:E(e[`google-analytics-property`])??n.client?.analytics.google?.propertyId,verifyContent:O(e[`verify-content`]),verifyLimit:k(e[`verify-limit`]),refresh:O(e.refresh)});if(t){R(r);return}Qo(r),B([`Source`,`Category`,`Score`,`Findings`,`Template`,`Analytics`,`Target`,`Action`],r.output.queue.map(e=>[e.source,e.category,e.score,e.grouped?.count??1,e.template?.label??`-`,e.analytics?.sessions??`-`,e.target,e.action])),J(`Queue action details`,r.output.queue.map(e=>({label:e.target,context:`${e.category}, score ${e.score}`,action:e.action})))}}),cl=C({meta:{name:`technical-watch`,description:`Agent workflow for crawl-diff and index-watch monitoring`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},url:{type:`string`,description:`Start URL to crawl. Defaults from the GSC property when possible.`},urls:{type:`string`,description:`Comma-separated URLs to inspect with URL Inspection.`},sitemaps:{type:`string`,description:`Comma-separated XML sitemap URLs for quota-aware index monitoring.`},properties:{type:`string`,description:`Comma-separated GSC properties for sitemap index monitoring.`},limit:{type:`string`,description:`Maximum pages to crawl. Defaults to 50.`},"daily-limit":{type:`string`,description:`URL Inspection daily limit per property. Defaults to 2000.`},"inspect-limit":{type:`string`,description:`Maximum sitemap URLs to inspect in this run. Defaults to 100.`},"max-urls":{type:`string`,description:`Maximum sitemap URLs to load for monitoring. Defaults to 50000.`},language:{type:`string`,description:`Optional URL Inspection language code.`},"recover-links":T(`Check search-value GSC pages for broken, blocked, or poorly redirected URLs. Defaults to true.`,`Skip link recovery checks.`),"recover-days":{type:`string`,description:`GSC lookback window for link recovery. Defaults to 90.`},"recover-limit":{type:`string`,description:`Maximum search-value pages to check for link recovery. Defaults to 10.`},"recover-min-clicks":{type:`string`,description:`Minimum clicks for link recovery candidates. Defaults to 1.`},"recover-min-impressions":{type:`string`,description:`Minimum impressions for link recovery candidates. Defaults to 100.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP/GSC cache where supported.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering when Playwright is installed.`}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),r=M(e.urls),i=M(e.sitemaps),a=E(e.url)??n.client?.startUrl??yi(n.site),o=await c({site:n.site,startUrl:a,urls:r.length?r:n.client?.watchUrls,sitemaps:i.length?i:void 0,properties:M(e.properties).length?M(e.properties):void 0,limit:k(e.limit),languageCode:E(e.language),dailyLimit:k(e[`daily-limit`]),inspectLimit:k(e[`inspect-limit`]),maxUrls:k(e[`max-urls`]),refresh:O(e.refresh),js:O(e.js)?!0:`auto`,recoverLinks:O(e[`recover-links`]),recoverDays:k(e[`recover-days`]),recoverLimit:k(e[`recover-limit`]),recoverMinClicks:k(e[`recover-min-clicks`]),recoverMinImpressions:k(e[`recover-min-impressions`])});if(t){R(o);return}$o(o)}});function ll(e){return e===null?`-`:e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function ul(e){return[...e.winners.map(e=>({direction:`winner`,item:e})),...e.losers.map(e=>({direction:`loser`,item:e}))]}function dl(e,t){let n=ul(t);n.length&&(process.stdout.write(`\n${e}\n`),B([`Direction`,`Key`,`Clicks`,`Impr.`,`Position`],n.map(({direction:e,item:t})=>[e,t.key,ll(t.clickDelta),ll(t.impressionDelta),ll(t.positionDelta)])))}function fl(e){process.stdout.write(`
289
+ `),V([`Command`,`Why`],e.map(e=>[e.command,e.why])))}function lu(e){process.stdout.write(`# Technical SEO report: ${e}\n\n`)}function uu(e){return w({meta:e,args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},...e.printFollowups?{url:{type:`string`,description:`Crawl URL for a technical-only report. Search Console analyses are skipped unless you also pass --site or --project.`}}:{},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Search performance window in days. Defaults to 90.`},limit:{description:`Maximum rows per section. Defaults to 10.`}}),...e.printFollowups?{crawl:Br(`Create or reuse a bounded technical crawl before the report.`,`Skip technical crawl evidence for this report.`),"crawl-max-pages":{type:`string`,description:`Maximum pages for the report crawl. Defaults to 100.`},"crawl-max-depth":{type:`string`,description:`Maximum link depth for the report crawl. Defaults to 4.`},full:{type:`boolean`,default:!1,description:`Include the full report in JSON output. Default JSON is a compact summary for agents.`},...Gc}:{},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:t})=>{let n=P(t),r=e.printFollowups?Kc(t):void 0,i=e.printFollowups&&k(t.full),a=O(t),o=D(t.site),s=e.printFollowups?D(t.url):void 0,c=!!(a||o||!s),l=c?await U({client:a,site:o,options:{json:n,refresh:k(t.refresh)}}):void 0,u=l?.site??Zl(s??``),d=await Xe({site:u,days:A(t.days),recentDays:A(t.recent),limit:A(t.limit),brandTerms:l?.client?.brandTerms,includeBrand:k(t[`include-brand`]),refresh:k(t.refresh),skipSearchData:!c}),f=e.workflowName?{...d,workflow:e.workflowName}:d,p=e.printFollowups?await De({site:u,searchSite:l?.site,url:s??l?.client?.startUrl??ea(u),projectId:l?.client?.id,googleAnalyticsPropertyId:l?.client?.analytics.google?.propertyId,crawl:!Hr(t,`crawl`),refresh:k(t.refresh),maxPages:A(t[`crawl-max-pages`]),maxDepth:A(t[`crawl-max-depth`])}):void 0,m=p?$l(p):void 0,h=e.printFollowups?su(f,{crawlStartUrl:s??l?.client?.startUrl??ea(u),projectId:l?.client?.id,technicalBaselineStatus:p?.status,searchDataAvailable:c}):void 0;if(n){let t=e.printFollowups&&!i?Yl(d,e.workflowName):f,n=!c&&m?{...t,summary:au(m),steps:[ou(m),...t.steps]}:t;z(m||h?{...n,...e.printFollowups?{detail:i?`full`:`summary`}:{},...m?{technicalCrawl:e.printFollowups&&!i?tu(m):m}:{},...h?{nextCommands:h}:{}}:t);return}if(r){Xc(await Yc({report:f.output.narrative,reportName:`report`,title:c?`SEO report`:`Technical SEO report`,options:r,projectId:l?.client?.id,additionalSections:iu({technicalCrawl:m,followups:h})}));return}c?(process.stdout.write(`${f.output.narrative.markdown}\n\n`),Ws(f)):lu(u),m&&(nu(m,{providerFree:!c}),c||ru(m)),h&&cu(h)}})}const du=uu({name:`diagnose-property`,description:`Find what changed in Google Search and what to inspect next`}),fu=uu({name:`report`,workflowName:`report`,printFollowups:!0,description:`Run the main SEO report and recommend the next best follow-up commands`}),pu=w({meta:{name:`refresh-priorities`,description:`Agent workflow for a ranked SEO action queue`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum queue items to print. Defaults to 25.`}}),"google-analytics-property":{type:`string`,description:`Google Analytics property ID to use for analytics value. Defaults from the selected project.`},"verify-content":Br(`Verify top opportunities against page title, meta, and content. Defaults to true.`,`Skip page content verification.`),"verify-limit":{type:`string`,description:`Maximum opportunity URLs to verify. Defaults to 5.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),r=await Ke({site:n.site,days:A(e.days),recentDays:A(e.recent),limit:A(e.limit),brandTerms:n.client?.brandTerms,includeBrand:k(e[`include-brand`]),googleAnalyticsPropertyId:D(e[`google-analytics-property`])??n.client?.analytics.google?.propertyId,verifyContent:k(e[`verify-content`]),verifyLimit:A(e[`verify-limit`]),refresh:k(e.refresh)});if(t){z(r);return}Ws(r),V([`Source`,`Category`,`Score`,`Findings`,`Template`,`Analytics`,`Target`,`Action`],r.output.queue.map(e=>[e.source,e.category,e.score,e.grouped?.count??1,e.template?.label??`-`,e.analytics?.sessions??`-`,e.target,e.action])),J(`Queue action details`,r.output.queue.map(e=>({label:e.target,context:`${e.category}, score ${e.score}`,action:e.action})))}}),mu=w({meta:{name:`technical-watch`,description:`Agent workflow for crawl-diff and index-watch monitoring`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},url:{type:`string`,description:`Start URL to crawl. Defaults from the GSC property when possible.`},urls:{type:`string`,description:`Comma-separated URLs to inspect with URL Inspection.`},sitemaps:{type:`string`,description:`Comma-separated XML sitemap URLs for quota-aware index monitoring.`},properties:{type:`string`,description:`Comma-separated GSC properties for sitemap index monitoring.`},limit:{type:`string`,description:`Maximum pages to crawl. Defaults to 50.`},"daily-limit":{type:`string`,description:`URL Inspection daily limit per property. Defaults to 2000.`},"inspect-limit":{type:`string`,description:`Maximum sitemap URLs to inspect in this run. Defaults to 100.`},"max-urls":{type:`string`,description:`Maximum sitemap URLs to load for monitoring. Defaults to 50000.`},language:{type:`string`,description:`Optional URL Inspection language code.`},"recover-links":Br(`Check search-value GSC pages for broken, blocked, or poorly redirected URLs. Defaults to true.`,`Skip link recovery checks.`),"recover-days":{type:`string`,description:`GSC lookback window for link recovery. Defaults to 90.`},"recover-limit":{type:`string`,description:`Maximum search-value pages to check for link recovery. Defaults to 10.`},"recover-min-clicks":{type:`string`,description:`Minimum clicks for link recovery candidates. Defaults to 1.`},"recover-min-impressions":{type:`string`,description:`Minimum impressions for link recovery candidates. Defaults to 100.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP/GSC cache where supported.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering when Playwright is installed.`}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),r=N(e.urls),i=N(e.sitemaps),a=D(e.url)??n.client?.startUrl??ea(n.site),o=await Je({site:n.site,startUrl:a,urls:r.length?r:n.client?.watchUrls,sitemaps:i.length?i:void 0,properties:N(e.properties).length?N(e.properties):void 0,limit:A(e.limit),languageCode:D(e.language),dailyLimit:A(e[`daily-limit`]),inspectLimit:A(e[`inspect-limit`]),maxUrls:A(e[`max-urls`]),refresh:k(e.refresh),js:k(e.js)?!0:`auto`,recoverLinks:k(e[`recover-links`]),recoverDays:A(e[`recover-days`]),recoverLimit:A(e[`recover-limit`]),recoverMinClicks:A(e[`recover-min-clicks`]),recoverMinImpressions:A(e[`recover-min-impressions`])});if(t){z(o);return}Gs(o)}});function hu(e){return e===null?`-`:e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function gu(e){return[...e.winners.map(e=>({direction:`winner`,item:e})),...e.losers.map(e=>({direction:`loser`,item:e}))]}function _u(e,t){let n=gu(t);n.length&&(process.stdout.write(`\n${e}\n`),V([`Direction`,`Key`,`Clicks`,`Impr.`,`Position`],n.map(({direction:e,item:t})=>[e,t.key,hu(t.clickDelta),hu(t.impressionDelta),hu(t.positionDelta)])))}function vu(e){process.stdout.write(`
180
290
  Segment coverage
181
- `),B([`Dimension`,`Eligible`,`Returned`,`Limited`,`Result cap`,`Source cap`,`Source capped`],[`page`,`query`,`device`,`country`].map(t=>{let n=e[t].coverage;return[t,n.eligibleRows,n.returnedRows,n.limitedRows,n.resultLimit,n.sourceRowLimit,n.sourcePossiblyTruncated?`yes`:`no`]}))}function pl(e){e.length&&(process.stdout.write(`
291
+ `),V([`Dimension`,`Eligible`,`Returned`,`Limited`,`Result cap`,`Source cap`,`Source capped`],[`page`,`query`,`device`,`country`].map(t=>{let n=e[t].coverage;return[t,n.eligibleRows,n.returnedRows,n.limitedRows,n.resultLimit,n.sourceRowLimit,n.sourcePossiblyTruncated?`yes`:`no`]}))}function yu(e){e.length&&(process.stdout.write(`
182
292
  Template movement
183
- `),B([`Direction`,`Template`,`Pattern confidence`,`URLs`,`Clicks`,`Returned share`,`Common terms`],e.map(e=>[e.direction,e.signature,e.confidence,e.urlCount,ll(e.clickDelta),`${Math.round(e.movementShare*100)}%`,e.commonTerms.join(`, `)||`-`])),Y(`Template actions`,e.map(e=>e.summary)),Y(`Template evidence scope`,[`Shares use returned directional page click movement. Pattern confidence applies only to returned matched-retained page segments.`]))}const ml=C({meta:{name:`update-postmortem`,description:`Agent workflow for Google update winner/loser analysis`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum winners/losers per segment. Defaults to 20.`}}),"known-change":{type:`string`,description:`Manual site-side change to treat as a confounder, for example pruning pages or blocking traffic.`},"ignore-change-log":{type:`boolean`,default:!1,description:`Do not use saved change-log entries as confounders.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=N(e),n=await U({client:D(e),site:E(e.site),options:{json:t,refresh:O(e.refresh)}}),r=await u({site:n.site,days:k(e.days),recentDays:k(e.recent),limit:k(e.limit),brandTerms:n.client?.brandTerms,includeBrand:O(e[`include-brand`]),knownConfounders:E(e[`known-change`])?[E(e[`known-change`])??``]:void 0,includeChangeLog:!O(e[`ignore-change-log`]),refresh:O(e.refresh)});if(t){R(r);return}z([[`Workflow`,r.workflow],[`Property`,r.site],[`Summary`,r.summary],[`Causal attribution`,r.output.update.attribution.replaceAll(`-`,` `)],[`Confidence`,r.output.update.confidence],[`Known confounders`,String(r.output.update.confounders.length)]]),Y(`Recommended actions`,r.actions.map(e=>`${e.title} (${e.confidence}): ${e.action}`)),Y(`Postmortem findings`,r.output.insights.map(e=>e.summary)),Y(`Segment evidence warnings`,[...r.output.segments.page.warnings,...r.output.segments.query.warnings,...r.output.segments.device.warnings,...r.output.segments.country.warnings].filter((e,t,n)=>n.indexOf(e)===t)),pl(r.output.templateMovement),Y(`Update evidence`,r.output.update.evidence),fl(r.output.segments),dl(`Page winners and losers`,r.output.segments.page),dl(`Query winners and losers`,r.output.segments.query),dl(`Device winners and losers`,r.output.segments.device),dl(`Country winners and losers`,r.output.segments.country),ni(`seo export update-postmortem ${n.client?`--project ${JSON.stringify(n.client.id)}`:`--site ${JSON.stringify(n.site)}`}`)}});function hl(e){return e.replaceAll(`\\`,`/`).toLowerCase()}function gl(e,t){return t===`win32`?`${e}.cmd`:e}function _l(e,t=process.platform){let n=hl(e);if(!(n.includes(`/_npx/`)||n.includes(`/.npm/_npx/`)||n.includes(`/.cache/pnpm/dlx/`)||n.includes(`/.volta/`))){if(n.includes(`/.pnpm/`)||n.includes(`/pnpm/global/`))return{command:gl(`pnpm`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.bun/install/global/`))return{command:gl(`bun`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.config/yarn/global/`))return{command:gl(`yarn`,t),args:[`global`,`add`,`seo@latest`]};if(n.includes(`/node_modules/seo/`))return{command:gl(`npm`,t),args:[`install`,`--global`,`seo@latest`]}}}function vl(e,t){let n=e=>e.replace(/^v/,``).split(`-`)[0]?.split(`.`).map(e=>Number.parseInt(e,10))??[],r=n(e),i=n(t);for(let e=0;e<3;e+=1){let t=r[e]??0,n=i[e]??0;if(!Number.isFinite(t)||!Number.isFinite(n))return!1;if(n>t)return!0;if(n<t)return!1}return!1}function yl(e){return!(!e.stdinIsTty||!e.stdoutIsTty||e.env.CI||e.env.NO_UPDATE_NOTIFIER||e.env.NODE_ENV===`test`||e.env.npm_lifecycle_event||e.env.npm_execpath||e.env.TERM===`dumb`||e.argv.includes(`--json`)||e.argv.some(e=>[`--help`,`-h`,`--version`,`-v`].includes(e))||[`help`,`mcp`].includes(e.argv[0]??``))}function bl(e){if(e)try{return an(e)}catch{return e}}async function xl(e){let t=await Vn({message:`seo ${e.update.latest} is available. You have ${e.update.current}.`,options:[{value:`update`,label:`Update now`,hint:[e.command.command,...e.command.args].join(` `)},{value:`later`,label:`Later`}],initialValue:`later`});return In(t)?`later`:t}function Sl(e){return yn(e.command,e.args,{stdio:`inherit`}).status}async function Cl(e,t={}){if(!yl({argv:t.argv??process.argv.slice(2),env:t.env??process.env,stdinIsTty:t.stdinIsTty??!!process.stdin.isTTY,stdoutIsTty:t.stdoutIsTty??!!process.stdout.isTTY}))return;let n=bl(t.cliPath??process.argv[1]),r=n?_l(n,t.platform??process.platform):void 0;if(!r)return;let i=(t.createNotifier??(e=>Xn({pkg:e,shouldNotifyInNpmScript:!1})))(e).update;if(!(!i||!vl(i.current,i.latest))&&await(t.prompt??xl)({command:r,update:i})!==`later`)return(t.run??Sl)(r)===0?(Ln.success(`Updated seo to ${i.latest}. Run your command again.`),0):(Ln.error(`The update failed. Your current version is unchanged.`),1)}const wl={name:`seo`,version:t},Tl=[{title:`Start here`,commands:[[`seo start`,`Connect Google and save a project profile`],[`seo report`,`Run the main SEO report for the default project`],[`seo report --site sc-domain:example.com`,`Run without a profile`],[`seo report --url https://example.com`,`Start with a local technical report`]]},{title:`Projects`,commands:[[`seo projects list`,`List saved project profiles`],[`seo projects add`,`Create or update a project profile`],[`seo sites`,`List Search Console properties`],[`seo doctor`,`Check local auth and config`]]},{title:`Act on a report`,commands:[[`seo refresh-priorities`,`Rank the next best SEO actions`],[`seo quick-wins`,`Find ranking 4-10 low-CTR wins`],[`seo second-page`,`Investigate URLs averaging positions 10-20`],[`seo technical-watch`,`Crawl and index-monitor a site`]]},{title:`Agent and power tools`,commands:[[`seo report --json`,`Run the main report as structured JSON`],[`seo export diagnose`,`Export report data to CSV`],[`seo mcp install`,`Install SEO tools into MCP clients`],[`seo skill list`,`Show the packaged SEO skill`],[`seo reports list`,`Discover every structured report`]]}],El=[...Tl,{title:`Deeper analysis`,commands:[[`seo decaying`,`Find pages and queries losing clicks`],[`seo cannibal`,`Review queries exposed across multiple URLs`],[`seo ctr-underperformers`,`Find weak CTR by ranking position`],[`seo query-cluster`,`Cluster repeated demand themes`],[`seo page-opportunities`,`Analyze one URL for growth ideas`],[`seo content optimize`,`Build a content optimization report`],[`seo perf audit`,`Run a page performance audit`],[`seo internal-links`,`Find internal link opportunities`],[`seo community-intent`,`Find forum, review, and comparison intent`],[`seo ai-referrals`,`Find AI referral traffic in Google Analytics`],[`seo seo-to-ai-query`,`Convert searches into AI-monitor prompts`]]},{title:`Technical and data`,commands:[[`seo audit-page`,`Audit one page`],[`seo crawl --sitemap-url <url> --health`,`Run the fast sitemap gate before a full crawl`],[`seo crawl`,`Run a full crawl for page and content evidence`],[`seo agent-readiness`,`Check content-site readiness for AI agents`],[`seo ai-readiness`,`Review AI-search technical evidence`],[`seo llms audit`,`Inspect optional llms.txt presence`],[`seo entity-readiness`,`Check brand/entity signals from a saved crawl`],[`seo okf export`,`Export a saved crawl as an OKF knowledge bundle`],[`seo crawl-queue`,`Run a crawl and rank the implementation queue`],[`seo crawl-reports`,`List saved crawl reports`],[`seo rules`,`List crawler rule ids`],[`seo explain --rule missing_title`,`Explain a crawler rule`],[`seo crawl-diff`,`Compare crawl changes`],[`seo index-coverage`,`Choose pages for URL Inspection`],[`seo index-watch`,`Check URL Inspection status`],[`seo link-recover`,`Find broken search-value URLs`],[`seo redirect-trace`,`Trace redirects`],[`seo gsc-query`,`Run a raw GSC query`],[`seo url-inspect`,`Run URL Inspection`],[`seo analytics google properties`,`List Google Analytics properties`],[`seo analytics google report`,`Run a Google Analytics report`],[`seo updates`,`List official Google ranking updates`]]},{title:`Reports and ops`,commands:[[`seo monthly-report`,`Generate a monthly narrative`],[`seo report-narrative`,`Generate a client-ready narrative`],[`seo update-postmortem`,`Analyze update winners and losers`],[`seo schedule cron`,`Print cron entries`],[`seo monitoring`,`Run and review monitoring`],[`seo change-log`,`Track SEO changes`],[`seo tests`,`Create and report local SEO tests`],[`seo content-groups`,`Manage reusable page/query groups`],[`seo pseo`,`Audit programmatic SEO templates`],[`seo auth`,`Manage Google auth`],[`seo cache`,`Manage local cache`],[`seo privacy`,`Show local storage paths`],[`seo telemetry status`,`Check anonymous usage telemetry`],[`seo reset`,`Delete local SEO data`]]}];function Dl(e){Hr(`seo v${wl.version}`,`Run SEO audits, find what needs fixing, and ship the changes with your agent.`),process.stdout.write(`
184
- `),Wr(e.flatMap(e=>e.commands.map(([t,n])=>({category:e.title,id:t,name:n}))),{noun:`command`,categoryLabels:Object.fromEntries(e.map(e=>[e.title,e.title]))}),process.stdout.write(`
185
- `),V(`More help`,"Use `seo help <command>` or `seo <command> --help` for command help.","Use `seo help all` for the longer command list.")}const Ol=C({meta:{name:`seo`,version:wl.version,description:`Local-first SEO CLI and MCP server`},subCommands:{init:Vo,analytics:di,llms:Wo,auth:gi,mcp:Jo,okf:ls,doctor:Os,privacy:Ac,telemetry:Rc,reset:jc,cache:_i,logs:Go,crawl:xa,"crawl-queue":zc,"crawl-reports":Ia,client:_a,content:ya,project:va,projects:va,"change-log":Ja,tests:oo,"content-groups":Za,"crawl-diff":Yo,diagnose:Ds,"diagnose-property":al,export:Bo,"index-coverage":is,"index-watch":as,"link-recover":os,"monthly-report":qs,monitoring:rs,"report-narrative":Js,rules:Ys,explain:Xs,"refresh-priorities":sl,"redirect-trace":ss,schedule:Qs,skill:kc,start:la,setup:ca,report:ol,reports:Ks,"segment-impact":As,"striking-distance":Ms,"technical-watch":cl,"update-postmortem":ml,sites:Mc,"gsc-query":La,"url-inspect":Ra,updates:Nc,"traffic-anomaly":Ha,"update-correlate":Ua,"ai-referrals":us,"agent-readiness":ci,"ai-readiness":ai,"entity-readiness":Ga,"audit-page":Ss,"second-page":bs,cannibal:ds,"community-intent":fs,decaying:hs,"quick-wins":ys,"page-opportunities":_s,perf:Es,"internal-links":gs,"ctr-underperformers":ps,"query-cluster":vs,"seo-to-ai-query":xs,pseo:Bs},run:async()=>{process.argv.slice(2).length===0&&process.stdout.write("Use `seo start` to set up, then `seo report` for the main report.\n")}}),kl={cannibal:`cannibalisation`,crawl:`site-crawl`,"crawl-queue":`top-fixes`,decaying:`decaying-pages`,"diagnose-property":`search-performance-overview`,doctor:`setup-check`,explain:`explain-crawl-issue`,"link-recover":`link-recovery`,"monthly-report":`monthly-report`,"query-cluster":`query-clusters`,report:`search-performance-overview`,"report-narrative":`narrative-report`,rules:`crawler-rules`,"update-correlate":`update-correlation`},Al=new Set([`agent-readiness`,`ai-readiness`,`ai-referrals`,`audit-page`,`community-intent`,`crawl-diff`,`ctr-underperformers`,`entity-readiness`,`index-coverage`,`index-watch`,`internal-links`,`page-opportunities`,`quick-wins`,`redirect-trace`,`refresh-priorities`,`second-page`,`segment-impact`,`seo-to-ai-query`,`striking-distance`,`technical-watch`,`traffic-anomaly`,`update-postmortem`]),jl=new Set(xt().map(e=>e.id));function Ml(e){let[t,n,r]=e;if(t)return t===`reports`&&n===`run`?r&&jl.has(r)?r:void 0:t===`content`&&n===`optimize`?`content-optimization`:t===`change-log`&&n===`measure`?`measure-change`:t===`llms`&&n===`audit`?`llms-txt-audit`:t===`llms`&&n===`generate`?`generate-llms-txt`:t===`okf`&&n===`export`?`okf-build`:t===`okf`&&n===`validate`?`okf-validate`:t===`monitoring`&&n===`run`?`technical-watch`:t===`perf`&&n===`audit`?`performance-audit`:t===`pseo`&&n===`audit`?`pseo-audit`:t===`tests`&&n===`report`?`measure-change`:kl[t]??(Al.has(t)?t:void 0)}const $=process.argv.slice(2),Nl={agent:pt()},Pl=$[0]===`telemetry`,Fl=$[0]===`mcp`&&$[1]===`serve`;!Pl&&!Fl&&Ke(Nl);const Il=await Cl(wl,{argv:$});Il!==void 0&&process.exit(Il),($.length===0||$.length===1&&[`help`,`--help`,`-h`].includes($[0]??``))&&(Dl(Tl),process.exit(0)),$[0]===`help`&&$[1]===`all`&&(Dl(El),process.exit(0));const Ll=$[0]===`help`&&$.length>1?[...$.slice(1),`--help`]:$;Ll!==$&&(process.argv=[process.argv[0]??`node`,process.argv[1]??`seo`,...Ll]);const Rl=Ll.some(e=>[`--help`,`-h`].includes(e)),zl=$.length===1&&[`--version`,`-v`].includes($[0]??``),Bl=Rl||zl?void 0:Ml(Ll);if(Rl||zl)await Mn(Ol);else{Bl&&et(Bl,Nl);try{await jn(Ol,{rawArgs:Ll}),Bl&&gt(Bl,Nl),[`init`,`setup`,`start`].includes(Ll[0]??``)&&!Ll.includes(`--dry-run`)&&Ie(Nl)}catch(e){Bl&&rt(Bl,wt(e),Nl);let t=be(e);$.includes(`--json`)?process.stdout.write(`${JSON.stringify(Kt(t),null,2)}\n`):process.stderr.write(`Error: ${t.message}\n`),process.exitCode=t.exitCode}}export{};
293
+ `),V([`Direction`,`Template`,`Pattern confidence`,`URLs`,`Clicks`,`Returned share`,`Common terms`],e.map(e=>[e.direction,e.signature,e.confidence,e.urlCount,hu(e.clickDelta),`${Math.round(e.movementShare*100)}%`,e.commonTerms.join(`, `)||`-`])),Y(`Template actions`,e.map(e=>e.summary)),Y(`Template evidence scope`,[`Shares use returned directional page click movement. Pattern confidence applies only to returned matched-retained page segments.`]))}const bu=w({meta:{name:`update-postmortem`,description:`Agent workflow for Google update winner/loser analysis`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},client:{type:`string`,description:`Legacy alias for --project.`},project:{type:`string`,description:`Saved project id or name.`},...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum winners/losers per segment. Defaults to 20.`}}),"known-change":{type:`string`,description:`Manual site-side change to treat as a confounder, for example pruning pages or blocking traffic.`},"ignore-change-log":{type:`boolean`,default:!1,description:`Do not use saved change-log entries as confounders.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=P(e),n=await U({client:O(e),site:D(e.site),options:{json:t,refresh:k(e.refresh)}}),r=await se({site:n.site,days:A(e.days),recentDays:A(e.recent),limit:A(e.limit),brandTerms:n.client?.brandTerms,includeBrand:k(e[`include-brand`]),knownConfounders:D(e[`known-change`])?[D(e[`known-change`])??``]:void 0,includeChangeLog:!k(e[`ignore-change-log`]),refresh:k(e.refresh)});if(t){z(r);return}B([[`Workflow`,r.workflow],[`Property`,r.site],[`Summary`,r.summary],[`Causal attribution`,r.output.update.attribution.replaceAll(`-`,` `)],[`Confidence`,r.output.update.confidence],[`Known confounders`,String(r.output.update.confounders.length)]]),Y(`Recommended actions`,r.actions.map(e=>`${e.title} (${e.confidence}): ${e.action}`)),Y(`Postmortem findings`,r.output.insights.map(e=>e.summary)),Y(`Segment evidence warnings`,[...r.output.segments.page.warnings,...r.output.segments.query.warnings,...r.output.segments.device.warnings,...r.output.segments.country.warnings].filter((e,t,n)=>n.indexOf(e)===t)),yu(r.output.templateMovement),Y(`Update evidence`,r.output.update.evidence),vu(r.output.segments),_u(`Page winners and losers`,r.output.segments.page),_u(`Query winners and losers`,r.output.segments.query),_u(`Device winners and losers`,r.output.segments.device),_u(`Country winners and losers`,r.output.segments.country),Li(`seo export update-postmortem ${n.client?`--project ${JSON.stringify(n.client.id)}`:`--site ${JSON.stringify(n.site)}`}`)}});function xu(e){return e.replaceAll(`\\`,`/`).toLowerCase()}function Su(e,t){return t===`win32`?`${e}.cmd`:e}function Cu(e,t=process.platform){let n=xu(e);if(!(n.includes(`/_npx/`)||n.includes(`/.npm/_npx/`)||n.includes(`/.cache/pnpm/dlx/`)||n.includes(`/.volta/`))){if(n.includes(`/.pnpm/`)||n.includes(`/pnpm/global/`))return{command:Su(`pnpm`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.bun/install/global/`))return{command:Su(`bun`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.config/yarn/global/`))return{command:Su(`yarn`,t),args:[`global`,`add`,`seo@latest`]};if(n.includes(`/node_modules/seo/`))return{command:Su(`npm`,t),args:[`install`,`--global`,`seo@latest`]}}}function wu(e,t){let n=e=>e.replace(/^v/,``).split(`-`)[0]?.split(`.`).map(e=>Number.parseInt(e,10))??[],r=n(e),i=n(t);for(let e=0;e<3;e+=1){let t=r[e]??0,n=i[e]??0;if(!Number.isFinite(t)||!Number.isFinite(n))return!1;if(n>t)return!0;if(n<t)return!1}return!1}function Tu(e){return!(!e.stdinIsTty||!e.stdoutIsTty||e.env.CI||e.env.NO_UPDATE_NOTIFIER||e.env.NODE_ENV===`test`||e.env.npm_lifecycle_event||e.env.npm_execpath||e.env.TERM===`dumb`||e.argv.includes(`--json`)||e.argv.some(e=>[`--help`,`-h`,`--version`,`-v`].includes(e))||[`help`,`mcp`].includes(e.argv[0]??``))}function Eu(e){if(e)try{return Dn(e)}catch{return e}}async function Du(e){let t=await dr({message:`seo ${e.update.latest} is available. You have ${e.update.current}.`,options:[{value:`update`,label:`Update now`,hint:[e.command.command,...e.command.args].join(` `)},{value:`later`,label:`Later`}],initialValue:`later`});return or(t)?`later`:t}function Ou(e){return Vn(e.command,e.args,{stdio:`inherit`}).status}async function ku(e,t={}){if(!Tu({argv:t.argv??process.argv.slice(2),env:t.env??process.env,stdinIsTty:t.stdinIsTty??!!process.stdin.isTTY,stdoutIsTty:t.stdoutIsTty??!!process.stdout.isTTY}))return;let n=Eu(t.cliPath??process.argv[1]),r=n?Cu(n,t.platform??process.platform):void 0;if(!r)return;let i=(t.createNotifier??(e=>xr({pkg:e,shouldNotifyInNpmScript:!1})))(e).update;if(!(!i||!wu(i.current,i.latest))&&await(t.prompt??Du)({command:r,update:i})!==`later`)return(t.run??Ou)(r)===0?(sr.success(`Updated seo to ${i.latest}. Run your command again.`),0):(sr.error(`The update failed. Your current version is unchanged.`),1)}const Au={name:`seo`,version:pn},ju=[{title:`Start here`,commands:[[`seo start`,`Connect Google and save a project profile`],[`seo report`,`Run the main SEO report for the default project`],[`seo report --site sc-domain:example.com`,`Run without a profile`],[`seo report --url https://example.com`,`Start with a local technical report`]]},{title:`Projects`,commands:[[`seo projects list`,`List saved project profiles`],[`seo projects add`,`Create or update a project profile`],[`seo sites`,`List Search Console properties`],[`seo doctor`,`Check local auth and config`]]},{title:`Act on a report`,commands:[[`seo refresh-priorities`,`Rank the next best SEO actions`],[`seo quick-wins`,`Find ranking 4-10 low-CTR wins`],[`seo second-page`,`Investigate URLs averaging positions 10-20`],[`seo technical-watch`,`Crawl and index-monitor a site`]]},{title:`Agent and power tools`,commands:[[`seo report --json`,`Run the main report as structured JSON`],[`seo export diagnose`,`Export report data to CSV`],[`seo mcp install`,`Install SEO tools into MCP clients`],[`seo skill list`,`Show the packaged SEO skill`],[`seo reports list`,`Discover every structured report`]]}],Mu=[...ju,{title:`Deeper analysis`,commands:[[`seo decaying`,`Find pages and queries losing clicks`],[`seo cannibal`,`Review queries exposed across multiple URLs`],[`seo ctr-underperformers`,`Find weak CTR by ranking position`],[`seo query-cluster`,`Cluster repeated demand themes`],[`seo page-opportunities`,`Analyze one URL for growth ideas`],[`seo content optimize`,`Build a content optimization report`],[`seo perf audit`,`Run a page performance audit`],[`seo internal-links`,`Find internal link opportunities`],[`seo community-intent`,`Find forum, review, and comparison intent`],[`seo ai-referrals`,`Find AI referral traffic in Google Analytics`],[`seo seo-to-ai-query`,`Convert searches into AI-monitor prompts`]]},{title:`Technical and data`,commands:[[`seo audit-page`,`Audit one page`],[`seo crawl --sitemap-url <url> --health`,`Run the fast sitemap gate before a full crawl`],[`seo crawl`,`Run a full crawl for page and content evidence`],[`seo agent-readiness`,`Check content-site readiness for AI agents`],[`seo ai-readiness`,`Review AI-search technical evidence`],[`seo llms audit`,`Inspect optional llms.txt presence`],[`seo entity-readiness`,`Check brand/entity signals from a saved crawl`],[`seo okf export`,`Export a saved crawl as an OKF knowledge bundle`],[`seo crawl-queue`,`Run a crawl and rank the implementation queue`],[`seo crawl-reports`,`List saved crawl reports`],[`seo rules`,`List crawler rule ids`],[`seo explain --rule missing_title`,`Explain a crawler rule`],[`seo crawl-diff`,`Compare crawl changes`],[`seo index-coverage`,`Choose pages for URL Inspection`],[`seo index-watch`,`Check URL Inspection status`],[`seo indexnow submit`,`Notify IndexNow about changed URLs`],[`seo link-recover`,`Find broken search-value URLs`],[`seo links`,`Review bounded referring-link evidence`],[`seo server-logs analyze`,`Review crawler requests in an access log`],[`seo redirect-trace`,`Trace redirects`],[`seo gsc-query`,`Run a raw GSC query`],[`seo url-inspect`,`Run URL Inspection`],[`seo analytics google properties`,`List Google Analytics properties`],[`seo analytics google report`,`Run a Google Analytics report`],[`seo updates`,`List official Google ranking updates`]]},{title:`Reports and ops`,commands:[[`seo monthly-report`,`Generate a monthly narrative`],[`seo report-narrative`,`Generate a client-ready narrative`],[`seo update-postmortem`,`Analyze update winners and losers`],[`seo schedule cron`,`Print cron entries`],[`seo monitoring`,`Run and review monitoring`],[`seo change-log`,`Track SEO changes`],[`seo tests`,`Create and report local SEO tests`],[`seo content-groups`,`Manage reusable page/query groups`],[`seo pseo`,`Audit programmatic SEO templates`],[`seo auth`,`Manage Google auth`],[`seo providers bing`,`Connect and report on Bing Webmaster`],[`seo cache`,`Manage local cache`],[`seo privacy`,`Show local storage paths`],[`seo telemetry status`,`Check anonymous usage telemetry`],[`seo reset`,`Delete local SEO data`]]}];function Nu(e){Si(`seo v${Au.version}`,`Run SEO audits, find what needs fixing, and ship the changes with your agent.`),process.stdout.write(`
294
+ `),wi(e.flatMap(e=>e.commands.map(([t,n])=>({category:e.title,id:t,name:n}))),{noun:`command`,categoryLabels:Object.fromEntries(e.map(e=>[e.title,e.title]))}),process.stdout.write(`
295
+ `),Ei(`More help`,"Use `seo help <command>` or `seo <command> --help` for command help.","Use `seo help all` for the longer command list.")}const Pu=w({meta:{name:`seo`,version:Au.version,description:`Local-first SEO CLI and MCP server`},subCommands:{init:Ms,indexnow:js,analytics:Ki,llms:Is,auth:Zi,mcp:Bs,okf:tc,doctor:bc,privacy:Fl,telemetry:Ul,reset:Il,cache:Qi,logs:Ls,crawl:co,"crawl-queue":Wl,"crawl-reports":wo,client:Qa,content:eo,project:$a,projects:$a,providers:Ac,"change-log":Io,tests:Jo,"content-groups":zo,"crawl-diff":Vs,diagnose:yc,"diagnose-property":du,export:Ds,"index-coverage":Xs,"index-watch":Zs,"link-recover":Qs,links:Ns,"monthly-report":Zc,monitoring:Ys,"report-narrative":Qc,rules:$c,explain:el,"refresh-priorities":pu,"redirect-trace":$s,schedule:nl,"server-logs":rl,skill:Pl,start:Wa,setup:Ua,report:fu,reports:Wc,"segment-impact":Sc,"striking-distance":wc,"technical-watch":mu,"update-postmortem":bu,sites:Ll,"gsc-query":To,"url-inspect":Eo,updates:Rl,"traffic-anomaly":Ao,"update-correlate":jo,"ai-referrals":nc,"agent-readiness":Ui,"ai-readiness":Bi,"entity-readiness":No,"audit-page":mc,"second-page":fc,cannibal:rc,"community-intent":ic,decaying:sc,"quick-wins":dc,"page-opportunities":lc,perf:vc,"internal-links":cc,"ctr-underperformers":ac,"query-cluster":uc,"seo-to-ai-query":pc,pseo:Rc},run:async()=>{process.argv.slice(2).length===0&&process.stdout.write("Use `seo start` to set up, then `seo report` for the main report.\n")}}),Fu={cannibal:`cannibalisation`,crawl:`site-crawl`,"crawl-queue":`top-fixes`,decaying:`decaying-pages`,"diagnose-property":`search-performance-overview`,doctor:`setup-check`,explain:`explain-crawl-issue`,"link-recover":`link-recovery`,"monthly-report":`monthly-report`,"query-cluster":`query-clusters`,report:`search-performance-overview`,"report-narrative":`narrative-report`,rules:`crawler-rules`,"update-correlate":`update-correlation`},Iu=new Set([`agent-readiness`,`ai-readiness`,`ai-referrals`,`audit-page`,`community-intent`,`crawl-diff`,`ctr-underperformers`,`entity-readiness`,`index-coverage`,`index-watch`,`internal-links`,`link-evidence`,`page-opportunities`,`quick-wins`,`redirect-trace`,`refresh-priorities`,`second-page`,`segment-impact`,`seo-to-ai-query`,`striking-distance`,`technical-watch`,`traffic-anomaly`,`update-postmortem`]),Lu=new Set(Bt().map(e=>e.id));function Ru(e){let[t,n,r]=e;if(t)return t===`reports`&&n===`run`?r&&Lu.has(r)?r:void 0:t===`content`&&n===`optimize`?`content-optimization`:t===`change-log`&&n===`measure`?`measure-change`:t===`llms`&&n===`audit`?`llms-txt-audit`:t===`links`?`link-evidence`:t===`llms`&&n===`generate`?`generate-llms-txt`:t===`okf`&&n===`export`?`okf-build`:t===`okf`&&n===`validate`?`okf-validate`:t===`monitoring`&&n===`run`?`technical-watch`:t===`perf`&&n===`audit`?`performance-audit`:t===`pseo`&&n===`audit`?`pseo-audit`:t===`tests`&&n===`report`?`measure-change`:Fu[t]??(Iu.has(t)?t:void 0)}const $=process.argv.slice(2),zu={agent:Mt()},Bu=$[0]===`telemetry`,Vu=$[0]===`mcp`&&$[1]===`serve`;!Bu&&!Vu&&lt(zu);const Hu=await ku(Au,{argv:$});Hu!==void 0&&process.exit(Hu),($.length===0||$.length===1&&[`help`,`--help`,`-h`].includes($[0]??``))&&(Nu(ju),process.exit(0)),$[0]===`help`&&$[1]===`all`&&(Nu(Mu),process.exit(0));const Uu=$[0]===`help`&&$.length>1?[...$.slice(1),`--help`]:$;Uu!==$&&(process.argv=[process.argv[0]??`node`,process.argv[1]??`seo`,...Uu]);const Wu=Uu.some(e=>[`--help`,`-h`].includes(e)),Gu=$.length===1&&[`--version`,`-v`].includes($[0]??``),Ku=Wu||Gu?void 0:Ru(Uu);if(Wu||Gu)await nr(Pu);else{Ku&&_t(Ku,zu);try{await tr(Pu,{rawArgs:Uu}),Ku&&Ft(Ku,zu),[`init`,`setup`,`start`].includes(Uu[0]??``)&&!Uu.includes(`--dry-run`)&&Qe(zu)}catch(e){Ku&&bt(Ku,Ut(e),zu);let t=We(e);$.includes(`--json`)?process.stdout.write(`${JSON.stringify(Re(t),null,2)}\n`):process.stderr.write(`Error: ${t.message}\n`),process.exitCode=t.exitCode}}export{};
186
296
  //# sourceMappingURL=cli.js.map