seo 0.2.5 → 0.2.6

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,177 +1,180 @@
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 re,Jt as _,K as ie,Kt as ae,L as oe,Lt as se,M as ce,Mt as le,N as ue,Nt as de,O as fe,Ot as pe,P as me,Pt as he,Q as ge,Qt as _e,R as ve,Rt as ye,S 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,_t as Le,a as Re,an as ze,at as Be,b as Ve,bt as He,c as Ue,cn as v,ct as We,d as Ge,dt as Ke,en as qe,et as Je,f as Ye,ft as Xe,g as Ze,gt as Qe,h as $e,ht as et,i as tt,in as nt,it as rt,j as it,jt as at,k as ot,kt as st,l as ct,ln as lt,lt as ut,m as dt,mt as ft,nn as pt,nt as mt,on as ht,ot as gt,p as _t,pt as vt,q as yt,qt as bt,r as xt,rn as St,rt as Ct,sn as wt,st as Tt,t as Et,tn as Dt,tt as Ot,u as kt,un as At,ut as jt,v as Mt,vt as Nt,w as Pt,wt as Ft,x as It,xt as Lt,y as Rt,yt as zt,z as Bt,zt as Vt}from"./dist-oOrG0Vub.js";import{constants as Ht,copyFileSync as Ut,existsSync as y,mkdirSync as Wt,readFileSync as Gt,readdirSync as Kt,realpathSync as qt,renameSync as Jt,rmSync as Yt,statSync as Xt,writeFileSync as Zt}from"node:fs";import{homedir as Qt}from"node:os";import{basename as $t,dirname as en,isAbsolute as tn,join as b,posix as nn,relative as rn,resolve as an,win32 as on}from"node:path";import{randomUUID as sn}from"node:crypto";import{spawn as cn,spawnSync as ln}from"node:child_process";import{fileURLToPath as un}from"node:url";import{isDeepStrictEqual as dn,stripVTControlCharacters as fn}from"node:util";import{lstat as pn,mkdir as mn,mkdtemp as hn,readFile as gn,readdir as _n,rename as vn,rm as yn,writeFile as bn}from"node:fs/promises";import{defineCommand as x,runCommand as xn,runMain as Sn}from"citty";import{cancel as Cn,confirm as wn,intro as Tn,isCancel as En,log as Dn,multiselect as On,note as S,outro as kn,password as An,select as jn,text as Mn}from"@clack/prompts";import Nn from"picocolors";import Pn from"string-width";import Fn from"cli-table3";import{applyEdits as In,modify as Ln,parse as Rn,printParseErrorCode as zn}from"jsonc-parser";import Bn from"update-notifier";const C={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 Vn(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 Hn(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 Un(e){return[{filename:`postmortem-summary.csv`,headers:[...C.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:[...C.steps],rows:e.steps.map((e,t)=>({rank:t+1,tool:e.tool,status:e.status,summary:e.summary}))},{filename:`workflow-actions.csv`,headers:[...C.actions],rows:e.actions.map((e,t)=>({rank:t+1,title:e.title,confidence:e.confidence,action:e.action}))},{filename:`postmortem-findings.csv`,headers:[...C.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:[...C.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:[...C.evidence],rows:e.output.update.evidence.map((e,t)=>({rank:t+1,evidence:e}))},{filename:`postmortem-confounders.csv`,headers:[...C.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:[...C.segment],rows:Vn(e,t)})),...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}-unmatched.csv`,headers:[...C.unmatchedSegment],rows:Hn(e,t)}))]}function Wn(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 Gn(e){if(!e.startsWith(`sc-domain:`))return;let t=e.slice(10).trim().toLowerCase();if(!(!t||/[/:]/.test(t)))return t.replace(/\.$/,``)||void 0}function Kn(e,t){let n=Gn(e);return n?t===n||t.endsWith(`.${n}`)?`domain`:void 0:Wn(e)===t?`hostname`:void 0}function qn(e,t){return t.flatMap(t=>{let n=t.stream.webStreamData?.defaultUri;if(!n)return[];let r=Wn(n);if(!r)return[];let i=Kn(e,r);return i?[{...t,defaultUri:n,hostname:r,match:i}]:[]})}function Jn(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 Yn(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 w(e,t){return{type:`boolean`,default:!0,description:e,negativeDescription:t}}function T(e){return typeof e==`string`?e:void 0}function E(e){let t=T(e.project),n=T(e.client);if(t&&n&&t!==n)throw Error(`Use either --project or --client, not both.`);return t??n}function D(e){return typeof e==`boolean`?e:void 0}function Xn(e){let t=T(e.rendering);if(t!==void 0&&t!==`auto`&&t!==`on`&&t!==`off`)throw new v(`INVALID_INPUT`,`--rendering must be auto, on, or off.`);if(D(e.js)===!0&&t&&t!==`on`)throw new v(`INVALID_INPUT`,`Use either --js or --rendering on, not both with different modes.`);return t??(D(e.js)?`on`:`auto`)}function Zn(e,t){let n=D(e[t]);if(n===!1)return!0;if(n===!0)return!1;let r=D(e[Qn(t)]);if(r===!1)return!0;if(r===!0)return!1;if(D(e[`no-${t}`])===!0||D(e[`no${$n(t)}`])===!0)return!0}function Qn(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function $n(e){let t=Qn(e);return t?`${t[0]?.toUpperCase()}${t.slice(1)}`:``}function O(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 k(e,t){if(e===void 0||e===``)return;let n=O(e);if(n===void 0)throw new v(`INVALID_INPUT`,`${t} must be a number.`);return n}function A(e){if(typeof e!=`string`)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length?t:void 0}function j(e){return A(e)??[]}function er(e){let t={concurrency:O(e[`fetch-concurrency`]),intervalCap:O(e[`fetch-interval-cap`]),intervalMs:O(e[`fetch-interval-ms`])};return Object.values(t).some(e=>e!==void 0)?t:void 0}function tr(e){let t={concurrency:k(e[`fetch-concurrency`],`--fetch-concurrency`),intervalCap:k(e[`fetch-interval-cap`],`--fetch-interval-cap`),intervalMs:k(e[`fetch-interval-ms`],`--fetch-interval-ms`)};return Object.values(t).some(e=>e!==void 0)?t:void 0}function M(e){return e.json===!0}async function nr(e,t){let n=T(e),r=T(t);if(n&&r)throw Error(`Use either --body or --body-file, not both.`);if(!n&&!r)return;let i=n??await gn(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 rr(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 ir(e={}){let t=e.env??process.env,n=rr(e.columns)??rr(e.streamColumns)??rr(t.COLUMNS)??80;return Math.min(200,Math.max(40,n))}function N(e={}){let t=e.env??process.env,n=e.isTTY??!!process.stdout.isTTY,r=e.color??!!(n&&t.NO_COLOR===void 0);return{columns:ir({...e,env:t,streamColumns:e.streamColumns??process.stdout.columns}),colors:Nn.createColors(r),hasColor:r,isInteractive:n&&!t.CI}}function P(e){return Pn(fn(e))}function ar(e,t){let n=[],r=``;for(let i of e)r&&P(`${r}${i}`)>t?(n.push(r),r=i):r+=i;return r&&n.push(r),n}function or(e,t){if(!e)return[``];let n=e.trim().split(/\s+/u),r=[],i=``;for(let e of n){let n=P(e)>t?ar(e,t):[e];for(let e of n)i?P(`${i} ${e}`)<=t?i+=` ${e}`:(r.push(i),i=e):i=e}return i&&r.push(i),r.length>0?r:[``]}function F(e,t){let n=Math.max(1,t);return e.replaceAll(`\r
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 ee,H as h,Ht as te,I as ne,It as re,J as ie,Jt as ae,K as g,Kt as oe,L as se,Lt as ce,M as le,Mt as ue,N as de,Nt as fe,O as pe,Ot as me,P as he,Pt as ge,Q as _e,Qt as ve,R as ye,Rt as be,S as xe,St as Se,T as Ce,Tt as we,U as Te,Ut as Ee,V as De,Vt as Oe,W as ke,Wt as Ae,X as je,Xt as Me,Y as Ne,Yt as Pe,Z as Fe,Zt as Ie,_ as Le,_n as _,_t as Re,a as ze,an as Be,at as Ve,b as He,bt as Ue,c as We,cn as Ge,ct as Ke,d as qe,dn as Je,dt as Ye,en as Xe,et as Ze,f as Qe,fn as $e,ft as et,g as tt,gn as nt,gt as rt,h as it,hn as at,ht as ot,i as st,in as ct,it as lt,j as ut,jt as dt,k as ft,kt as pt,l as mt,ln as ht,lt as gt,m as _t,mn as vt,mt as yt,nn as bt,nt 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,xt as Kt,y as qt,yn as Jt,yt as Yt,z as Xt,zt as Zt}from"./dist-PRmi6cXV.js";import{constants as Qt,copyFileSync as $t,existsSync as v,mkdirSync as en,readFileSync as tn,readdirSync as nn,realpathSync as rn,renameSync as an,rmSync as on,statSync as sn,writeFileSync as cn}from"node:fs";import{homedir as ln}from"node:os";import{basename as un,dirname as y,isAbsolute as dn,join as b,posix as fn,relative as pn,resolve as mn,win32 as hn}from"node:path";import{randomUUID as gn}from"node:crypto";import{spawn as _n,spawnSync as vn}from"node:child_process";import{fileURLToPath as yn}from"node:url";import{isDeepStrictEqual as bn,stripVTControlCharacters as xn}from"node:util";import{lstat as Sn,mkdir as Cn,mkdtemp as wn,readFile as Tn,readdir as En,rename as Dn,rm as On,writeFile as kn}from"node:fs/promises";import{defineCommand as x,runCommand as An,runMain as jn}from"citty";import{cancel as Mn,confirm as Nn,intro as Pn,isCancel as Fn,log as In,multiselect as Ln,note as S,outro as Rn,password as zn,select as Bn,text as Vn}from"@clack/prompts";import Hn from"picocolors";import Un from"string-width";import Wn from"cli-table3";import{applyEdits as Gn,modify as Kn,parse as qn,printParseErrorCode as Jn}from"jsonc-parser";import Yn from"update-notifier";const C={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 Xn(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 Zn(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 Qn(e){return[{filename:`postmortem-summary.csv`,headers:[...C.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:[...C.steps],rows:e.steps.map((e,t)=>({rank:t+1,tool:e.tool,status:e.status,summary:e.summary}))},{filename:`workflow-actions.csv`,headers:[...C.actions],rows:e.actions.map((e,t)=>({rank:t+1,title:e.title,confidence:e.confidence,action:e.action}))},{filename:`postmortem-findings.csv`,headers:[...C.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:[...C.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:[...C.evidence],rows:e.output.update.evidence.map((e,t)=>({rank:t+1,evidence:e}))},{filename:`postmortem-confounders.csv`,headers:[...C.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:[...C.segment],rows:Xn(e,t)})),...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}-unmatched.csv`,headers:[...C.unmatchedSegment],rows:Zn(e,t)}))]}function $n(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 er(e){if(!e.startsWith(`sc-domain:`))return;let t=e.slice(10).trim().toLowerCase();if(!(!t||/[/:]/.test(t)))return t.replace(/\.$/,``)||void 0}function tr(e,t){let n=er(e);return n?t===n||t.endsWith(`.${n}`)?`domain`:void 0:$n(e)===t?`hostname`:void 0}function nr(e,t){return t.flatMap(t=>{let n=t.stream.webStreamData?.defaultUri;if(!n)return[];let r=$n(n);if(!r)return[];let i=tr(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 ir(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 w(e,t){return{type:`boolean`,default:!0,description:e,negativeDescription:t}}function T(e){return typeof e==`string`?e:void 0}function E(e){let t=T(e.project),n=T(e.client);if(t&&n&&t!==n)throw Error(`Use either --project or --client, not both.`);return t??n}function D(e){return typeof e==`boolean`?e:void 0}function ar(e){let t=T(e.rendering);if(t!==void 0&&t!==`auto`&&t!==`on`&&t!==`off`)throw new _(`INVALID_INPUT`,`--rendering must be auto, on, or off.`);if(D(e.js)===!0&&t&&t!==`on`)throw new _(`INVALID_INPUT`,`Use either --js or --rendering on, not both with different modes.`);return t??(D(e.js)?`on`:`auto`)}function or(e,t){let n=D(e[t]);if(n===!1)return!0;if(n===!0)return!1;let r=D(e[sr(t)]);if(r===!1)return!0;if(r===!0)return!1;if(D(e[`no-${t}`])===!0||D(e[`no${cr(t)}`])===!0)return!0}function sr(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function cr(e){let t=sr(e);return t?`${t[0]?.toUpperCase()}${t.slice(1)}`:``}function O(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 k(e,t){if(e===void 0||e===``)return;let n=O(e);if(n===void 0)throw new _(`INVALID_INPUT`,`${t} must be a number.`);return n}function A(e){if(typeof e!=`string`)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length?t:void 0}function j(e){return A(e)??[]}function lr(e){let t={concurrency:O(e[`fetch-concurrency`]),intervalCap:O(e[`fetch-interval-cap`]),intervalMs:O(e[`fetch-interval-ms`])};return Object.values(t).some(e=>e!==void 0)?t:void 0}function ur(e){let t={concurrency:k(e[`fetch-concurrency`],`--fetch-concurrency`),intervalCap:k(e[`fetch-interval-cap`],`--fetch-interval-cap`),intervalMs:k(e[`fetch-interval-ms`],`--fetch-interval-ms`)};return Object.values(t).some(e=>e!==void 0)?t:void 0}function M(e){return e.json===!0}async function dr(e,t){let n=T(e),r=T(t);if(n&&r)throw Error(`Use either --body or --body-file, not both.`);if(!n&&!r)return;let i=n??await Tn(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 fr(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 pr(e={}){let t=e.env??process.env,n=fr(e.columns)??fr(e.streamColumns)??fr(t.COLUMNS)??80;return Math.min(200,Math.max(40,n))}function N(e={}){let t=e.env??process.env,n=e.isTTY??!!process.stdout.isTTY,r=e.color??!!(n&&t.NO_COLOR===void 0);return{columns:pr({...e,env:t,streamColumns:e.streamColumns??process.stdout.columns}),colors:Hn.createColors(r),hasColor:r,isInteractive:n&&!t.CI}}function P(e){return Un(xn(e))}function mr(e,t){let n=[],r=``;for(let i of e)r&&P(`${r}${i}`)>t?(n.push(r),r=i):r+=i;return r&&n.push(r),n}function hr(e,t){if(!e)return[``];let n=e.trim().split(/\s+/u),r=[],i=``;for(let e of n){let n=P(e)>t?mr(e,t):[e];for(let e of n)i?P(`${i} ${e}`)<=t?i+=` ${e}`:(r.push(i),i=e):i=e}return i&&r.push(i),r.length>0?r:[``]}function F(e,t){let n=Math.max(1,t);return e.replaceAll(`\r
4
4
  `,`
5
5
  `).split(`
6
- `).flatMap(e=>or(e,n))}function sr(e,t){if(P(e)<=t)return e;let n=Math.max(1,t-P(`...`)),r=``;for(let t of e){if(P(`${r}${t}`)>n)break;r+=t}return`${r}...`}const cr={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 lr(e){return e===void 0?``:String(e)}function ur(e,t){return e.map((e,n)=>{let r=t.map(e=>lr(e[n]));return Math.min(42,Math.max(P(e),...r.map(P),4))})}function dr(e,t,n){return e.length===0||e.length>4?!1:ur(e,t).reduce((e,t)=>e+t+2,0)<=n.columns}function fr(e,t,n){let r=ur(e,t).map(e=>e+2),i=new Fn({chars:cr,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)=>F(lr(n[t]),Math.max(1,(r[t]??3)-2)).join(`
7
- `)));return i.toString()}function pr(e,t,n,r){let i=r.columns-n-2;return i<24?[r.colors.dim(e),...F(t,r.columns-2).map(e=>` ${e}`)]:F(t,i).map((t,i)=>{let a=i===0?e.padEnd(n):``.padEnd(n);return`${r.colors.dim(a)}${` `.repeat(2)}${t}`})}function mr(e,t,n,r={}){let i=Math.min(28,Math.max(...e.map(e=>P(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(...pr(a,lr(t[r]),i,n));return s.join(`
6
+ `).flatMap(e=>hr(e,n))}function gr(e,t){if(P(e)<=t)return e;let n=Math.max(1,t-P(`...`)),r=``;for(let t of e){if(P(`${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 vr(e){return e===void 0?``:String(e)}function yr(e,t){return e.map((e,n)=>{let r=t.map(e=>vr(e[n]));return Math.min(42,Math.max(P(e),...r.map(P),4))})}function br(e,t,n){return e.length===0||e.length>4?!1:yr(e,t).reduce((e,t)=>e+t+2,0)<=n.columns}function xr(e,t,n){let r=yr(e,t).map(e=>e+2),i=new Wn({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)=>F(vr(n[t]),Math.max(1,(r[t]??3)-2)).join(`
7
+ `)));return i.toString()}function Sr(e,t,n,r){let i=r.columns-n-2;return i<24?[r.colors.dim(e),...F(t,r.columns-2).map(e=>` ${e}`)]:F(t,i).map((t,i)=>{let a=i===0?e.padEnd(n):``.padEnd(n);return`${r.colors.dim(a)}${` `.repeat(2)}${t}`})}function Cr(e,t,n,r={}){let i=Math.min(28,Math.max(...e.map(e=>P(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(...Sr(a,vr(t[r]),i,n));return s.join(`
8
8
  `)}).join(`
9
9
 
10
- `)}function hr(e,t,n,r={}){return t.length===0?n.colors.dim(`No results.`):r.layout===`table`||r.layout!==`records`&&dr(e,t,n)?fr(e,t,n):mr(e,t,n,r)}function gr(e,t){if(e.length===0)return``;let n=Math.min(28,Math.max(...e.map(([e])=>P(e))));return e.flatMap(([e,r])=>{let i=pr(e,r,n,t);return i.length>0&&(i[0]=(i[0]??``).replace(e,t.colors.bold(e))),i}).join(`
11
- `)}function _r(e,t){let n=[t.colors.bold(e.title)];return e.body&&n.push(...F(e.body,t.columns)),e.command&&n.push(t.colors.cyan(sr(e.command,t.columns))),n.join(`
12
- `)}function vr(e,t,n=`${t}s`){return e===1?t:n}function yr(e,t,n){let r=` `.repeat(t);return F(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function br(e,t,n){return[t.colors.bold(e),...n?F(n,t.columns):[]].join(`
13
- `)}function xr(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(...yr(e.detail,6,t.columns)),e.fix){let n=F(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(`
10
+ `)}function wr(e,t,n,r={}){return t.length===0?n.colors.dim(`No results.`):r.layout===`table`||r.layout!==`records`&&br(e,t,n)?xr(e,t,n):Cr(e,t,n,r)}function Tr(e,t){if(e.length===0)return``;let n=Math.min(28,Math.max(...e.map(([e])=>P(e))));return e.flatMap(([e,r])=>{let i=Sr(e,r,n,t);return i.length>0&&(i[0]=(i[0]??``).replace(e,t.colors.bold(e))),i}).join(`
11
+ `)}function Er(e,t){let n=[t.colors.bold(e.title)];return e.body&&n.push(...F(e.body,t.columns)),e.command&&n.push(t.colors.cyan(gr(e.command,t.columns))),n.join(`
12
+ `)}function Dr(e,t,n=`${t}s`){return e===1?t:n}function Or(e,t,n){let r=` `.repeat(t);return F(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function kr(e,t,n){return[t.colors.bold(e),...n?F(n,t.columns):[]].join(`
13
+ `)}function Ar(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(...Or(e.detail,6,t.columns)),e.fix){let n=F(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
14
  `)}).join(`
15
15
 
16
- `)}function Sr(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} ${vr(t,`check`)} passed, ${n} ${vr(n,`warning`)}, ${r} failed.`}function Cr(e,t,n){let r=n.columns-t-2-2;return r<24||P(e.id)>t?[...yr(e.id,2,n.columns).map(e=>n.colors.cyan(e)),...yr(e.name,4,n.columns)].join(`
16
+ `)}function jr(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} ${Dr(t,`check`)} passed, ${n} ${Dr(n,`warning`)}, ${r} failed.`}function Mr(e,t,n){let r=n.columns-t-2-2;return r<24||P(e.id)>t?[...Or(e.id,2,n.columns).map(e=>n.colors.cyan(e)),...Or(e.name,4,n.columns)].join(`
17
17
  `):F(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 wr(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Tr(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} ${vr(e.length,n.noun)} across ${r.size} ${vr(r.size,`category`,`categories`)}.`,a=Math.min(30,Math.max(...e.map(e=>P(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]??wr(e);return[t.colors.bold(`${o} (${i.length})`),...i.map(e=>Cr(e,a,t))].join(`
18
+ `)}function Nr(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Pr(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} ${Dr(e.length,n.noun)} across ${r.size} ${Dr(r.size,`category`,`categories`)}.`,a=Math.min(30,Math.max(...e.map(e=>P(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]??Nr(e);return[t.colors.bold(`${o} (${i.length})`),...i.map(e=>Mr(e,a,t))].join(`
19
19
  `)})].join(`
20
20
 
21
- `)}function Er(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(...yr(e.description,2,t.columns));let r=e.meta?.filter(Boolean).join(` · `);return r&&n.push(...yr(r,2,t.columns).map(e=>t.colors.dim(e))),n.join(`
21
+ `)}function Fr(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(...Or(e.description,2,t.columns));let r=e.meta?.filter(Boolean).join(` · `);return r&&n.push(...Or(r,2,t.columns).map(e=>t.colors.dim(e))),n.join(`
22
22
  `)}).join(`
23
23
 
24
- `)}function Dr(e,t,n){let r=t.filter(e=>e.trim().length>0).flatMap(e=>F(e,n.columns));return[n.colors.bold(e),...r].join(`
25
- `)}function Or(e,t,n){let r=t.flatMap(e=>F(e,Math.max(1,n.columns-2)).map((e,t)=>`${t===0?`- `:` `}${e}`));return[n.colors.bold(e),...r].join(`
26
- `)}function kr(e,t){return e.length===0?t.colors.dim(`No parameters.`):Er(e.map(e=>({title:e.name,description:e.description,meta:[e.type,e.required?`required`:`optional`]})),t,{empty:`No parameters.`})}function I(e={}){return!!(!e.json&&process.stdin.isTTY&&process.stdout.isTTY&&!process.env.CI)}function L(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}function R(e){let t=gr(e,N());t&&process.stdout.write(`${t}\n`)}function z(e,t){process.stdout.write(`${hr(e,t,N())}\n`)}function Ar(e){process.stdout.write(`${_r(e,N())}\n`)}function jr(e,t){process.stdout.write(`${br(e,N(),t)}\n`)}function Mr(e){process.stdout.write(`${xr(e,N())}\n`)}function Nr(e,t){process.stdout.write(`${Tr(e,N(),t)}\n`)}function Pr(e,t){process.stdout.write(`${Er(e,N(),t)}\n`)}function Fr(e,...t){process.stdout.write(`${Dr(e,t,N())}\n`)}function Ir(e,t){process.stdout.write(`${Or(e,t,N())}\n`)}function Lr(e){process.stdout.write(`${kr(e,N())}\n`)}function Rr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function B(e){return typeof e==`symbol`&&process.exit(1),e}function zr(e,t){let n=t.trim().toLowerCase();return!n||e.some(e=>e.toLowerCase().includes(n))}async function Br(e){let t=e.choices;if(e.choices.length>8){let n=B(await Mn({message:e.searchMessage,placeholder:`Type part of the name or URL, or leave blank`}));if(t=e.choices.filter(t=>zr(e.searchValues(t),n)),!t.length)throw new v(`INVALID_INPUT`,e.emptyMessage)}return B(await jn({message:e.message,options:t.map(t=>{let n=e.hint?.(t);return{value:t,label:e.label(t),...n?{hint:n}:{}}})}))}async function V(e){if(e.site)return e.site;let t=pt(),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||!I())throw new v(`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 Vt(e.options?.refresh);if(!r.length)throw new v(`PROPERTY_NOT_FOUND`,`No Search Console properties found for this Google login.`);return r.length===1?r[0]?.siteUrl??``:(await Br({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 H(e){if(e.client&&e.project&&e.client!==e.project)throw new v(`INVALID_INPUT`,`Use either --project or --client, not both.`);let t=e.project??e.client;if(t){let e=Ge(t);if(!e)throw new v(`INVALID_INPUT`,`Project not found: ${t}`);return{client:e,site:e.siteUrl}}let n=Ge();return!e.site&&n?{client:n,site:n.siteUrl}:{site:await V({site:e.site,options:e.options})}}async function Vr(e){if(e.client&&e.project&&e.client!==e.project)throw new v(`INVALID_INPUT`,`Use either --project or --client, not both.`);let t=e.project??e.client;if(t){let e=Ge(t);if(!e)throw new v(`INVALID_INPUT`,`Project not found: ${t}`);return e}let n=_t();if(!n.length)return;let r=Ge();if(r)return r;if(!(e.options?.json||!I()))return Br({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 Hr(e){if(e.property)return e.property;let t=pt();if(t.analytics.google.defaultPropertyId)return t.analytics.google.defaultPropertyId;if(e.options?.json||!I())throw new v(`INVALID_INPUT`,`No Google Analytics property selected. Pass --property or run this command in a terminal to choose one.`);let n=(await h()).flatMap(e=>e.propertySummaries.map(t=>({property:Te(t.property),displayName:t.displayName??t.property,account:e.displayName??e.account})));if(!n.length)throw new v(`PROPERTY_NOT_FOUND`,`No Google Analytics properties found for this Google login.`);return n.length===1?n[0]?.property??``:(await Br({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 U(e){return Math.round(e).toLocaleString(`en-GB`)}function W(e){return e.toFixed(1)}function G(e){return`${(e*100).toFixed(1)}%`}function K(e,t=72){return sr(e,t)}function Ur(e){return e.verification?.requested?`${e.verification.verified} checked, ${e.verification.failed} failed`:`off`}function q(e,t){z(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 Wr(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 Gr(e,t={}){let n=T(e[`report-id`]);if(n){let e=Ft(n);if(!e)throw Error(`No saved crawl report found for ${n}.`);return e}let r=E(e),i=T(e.site),a=r||i?await H({client:r,site:i,options:t}):void 0,o=xe(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 Kr(e){process.stdout.write(`AI-search evidence for ${e.url}\n\n`),R([[`Assessment`,`evidence only`],[`Data`,e.dataStatus],[`Report`,e.reportId]]),process.stdout.write(`\n${e.headline}\n`),e.topActions.length&&(process.stdout.write(`
24
+ `)}function Ir(e,t,n){let r=t.filter(e=>e.trim().length>0).flatMap(e=>F(e,n.columns));return[n.colors.bold(e),...r].join(`
25
+ `)}function Lr(e,t,n){let r=t.flatMap(e=>F(e,Math.max(1,n.columns-2)).map((e,t)=>`${t===0?`- `:` `}${e}`));return[n.colors.bold(e),...r].join(`
26
+ `)}function Rr(e,t){return e.length===0?t.colors.dim(`No parameters.`):Fr(e.map(e=>({title:e.name,description:e.description,meta:[e.type,e.required?`required`:`optional`]})),t,{empty:`No parameters.`})}function I(e={}){return!!(!e.json&&process.stdin.isTTY&&process.stdout.isTTY&&!process.env.CI)}function L(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}function R(e){let t=Tr(e,N());t&&process.stdout.write(`${t}\n`)}function z(e,t){process.stdout.write(`${wr(e,t,N())}\n`)}function zr(e){process.stdout.write(`${Er(e,N())}\n`)}function Br(e,t){process.stdout.write(`${kr(e,N(),t)}\n`)}function Vr(e){process.stdout.write(`${Ar(e,N())}\n`)}function Hr(e,t){process.stdout.write(`${Pr(e,N(),t)}\n`)}function Ur(e,t){process.stdout.write(`${Fr(e,N(),t)}\n`)}function Wr(e,...t){process.stdout.write(`${Ir(e,t,N())}\n`)}function Gr(e,t){process.stdout.write(`${Lr(e,t,N())}\n`)}function Kr(e){process.stdout.write(`${Rr(e,N())}\n`)}function qr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function B(e){return typeof e==`symbol`&&process.exit(1),e}function Jr(e,t){let n=t.trim().toLowerCase();return!n||e.some(e=>e.toLowerCase().includes(n))}async function Yr(e){let t=e.choices;if(e.choices.length>8){let n=B(await Vn({message:e.searchMessage,placeholder:`Type part of the name or URL, or leave blank`}));if(t=e.choices.filter(t=>Jr(e.searchValues(t),n)),!t.length)throw new _(`INVALID_INPUT`,e.emptyMessage)}return B(await Bn({message:e.message,options:t.map(t=>{let n=e.hint?.(t);return{value:t,label:e.label(t),...n?{hint:n}:{}}})}))}async function V(e){if(e.site)return e.site;let t=Je(),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||!I())throw new _(`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 ae(e.options?.refresh);if(!r.length)throw new _(`PROPERTY_NOT_FOUND`,`No Search Console properties found for this Google login.`);return r.length===1?r[0]?.siteUrl??``:(await Yr({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 H(e){if(e.client&&e.project&&e.client!==e.project)throw new _(`INVALID_INPUT`,`Use either --project or --client, not both.`);let t=e.project??e.client;if(t){let e=He(t);if(!e)throw new _(`INVALID_INPUT`,`Project not found: ${t}`);return{client:e,site:e.siteUrl}}let n=He();return!e.site&&n?{client:n,site:n.siteUrl}:{site:await V({site:e.site,options:e.options})}}async function Xr(e){if(e.client&&e.project&&e.client!==e.project)throw new _(`INVALID_INPUT`,`Use either --project or --client, not both.`);let t=e.project??e.client;if(t){let e=He(t);if(!e)throw new _(`INVALID_INPUT`,`Project not found: ${t}`);return e}let n=xe();if(!n.length)return;let r=He();if(r)return r;if(!(e.options?.json||!I()))return Yr({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 Zr(e){if(e.property)return e.property;let t=Je();if(t.analytics.google.defaultPropertyId)return t.analytics.google.defaultPropertyId;if(e.options?.json||!I())throw new _(`INVALID_INPUT`,`No Google Analytics property selected. Pass --property or run this command in a terminal to choose one.`);let n=(await Xe()).flatMap(e=>e.propertySummaries.map(t=>({property:ve(t.property),displayName:t.displayName??t.property,account:e.displayName??e.account})));if(!n.length)throw new _(`PROPERTY_NOT_FOUND`,`No Google Analytics properties found for this Google login.`);return n.length===1?n[0]?.property??``:(await Yr({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 U(e){return Math.round(e).toLocaleString(`en-GB`)}function W(e){return e.toFixed(1)}function G(e){return`${(e*100).toFixed(1)}%`}function K(e,t=72){return gr(e,t)}function Qr(e){return e.verification?.requested?`${e.verification.verified} checked, ${e.verification.failed} failed`:`off`}function q(e,t){z(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 $r(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 ei(e,t={}){let n=T(e[`report-id`]);if(n){let e=fe(n);if(!e)throw Error(`No saved crawl report found for ${n}.`);return e}let r=E(e),i=T(e.site),a=r||i?await H({client:r,site:i,options:t}):void 0,o=dt(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 ti(e){process.stdout.write(`AI-search evidence for ${e.url}\n\n`),R([[`Assessment`,`evidence only`],[`Data`,e.dataStatus],[`Report`,e.reportId]]),process.stdout.write(`\n${e.headline}\n`),e.topActions.length&&(process.stdout.write(`
27
27
  Top actions
28
28
  `),z([`Status`,`Check`,`Action`],e.topActions.map(e=>[e.status,e.title,K(e.action,96)]))),e.botAccess.length&&(process.stdout.write(`
29
29
  Bot access
30
- `),z([`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 qr=x({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=M(e),n=r(await Gr(e,{json:t}));if(t){L(n);return}Kr(n)}});function Jr(e){let t=T(e.agentReadinessUrl),n=T(e.url);if(t&&n&&t!==n)throw Error(`Use either the positional URL or --url, not both.`);return t??n}function Yr(e){process.stdout.write(`AI agent readiness for ${e.url}\n\n`),R([[`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(`
30
+ `),z([`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 ni=x({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=M(e),n=Zt(await ei(e,{json:t}));if(t){L(n);return}ti(n)}});function ri(e){let t=T(e.agentReadinessUrl),n=T(e.url);if(t&&n&&t!==n)throw Error(`Use either the positional URL or --url, not both.`);return t??n}function ii(e){process.stdout.write(`AI agent readiness for ${e.url}\n\n`),R([[`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
31
  Profile scope
32
32
  `),z([`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
33
  What to check next
34
- `),z([`Status`,`Check`,`Action`],e.topActions.map(e=>[e.status,e.title,K(e.action,96)]))),Y(`Caveats`,e.caveats)}const Xr=x({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=M(e),n=Jr(e),r=T(e[`report-id`]);if(n&&r)throw Error(`Use either a URL or --report-id, not both.`);let i=le(n?await(async()=>{let r=E(e),i=T(e.site),a=r||i?await H({client:r,site:i,options:{json:t}}):void 0;return He({url:n,projectId:a?.client?.id,site:a?.site,maxPages:O(e[`max-pages`]),fetchRate:er(e),refresh:D(e.refresh),checkAgentDiscovery:!0,useSitemap:!0,checkExternal:!1})})():await Gr(e,{json:t}));if(t){L(i);return}Yr(i)}}),Zr=x({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 h(),n=t.flatMap(e=>e.propertySummaries.map(t=>({account:e.displayName??e.account,property:Te(t.property),displayName:t.displayName??t.property}))),r=T(e.save);if(r){let e=pt();e.analytics.google.defaultPropertyId=r,nt(e)}if(M(e)){L({accountSummaries:t,properties:n,saved:r});return}r&&process.stdout.write(`Saved default Google Analytics property ${r}.\n`),z([`Property`,`Name`,`Account`],n.map(e=>[e.property,e.displayName,e.account]))}});async function Qr(e,t={resolveClient:Vr,resolveGoogleAnalyticsProperty:Hr}){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 $r=x({meta:{name:`analytics`,description:`Read analytics data from connected providers`},subCommands:{google:x({meta:{name:`google`,description:`Read Google Analytics properties and reports`},subCommands:{properties:Zr,report:x({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=M(e),n=await Qr({property:T(e.property),project:E(e),options:{json:t}}),r=await bt(n,await nr(e.body,e[`body-file`])??{dateRanges:[{startDate:T(e[`start-date`]),endDate:T(e[`end-date`])}],dimensions:(A(e.dimensions)??[]).map(e=>({name:e})),metrics:(A(e.metrics)??[]).map(e=>({name:e})),limit:T(e.limit)},{refresh:D(e.refresh)});if(t){L(r);return}let i=ke(r);if(R([[`Property`,n],[`Rows`,String(r.rowCount??i.length)]]),i.length){let e=Object.keys(i[0]??{});z(e,i.slice(0,25).map(t=>e.map(e=>t[e]??``)))}}})}})}});function ei(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 ti(e){return e.active===`keychain`?`system keychain`:e.configured===`keychain`?`private file fallback`:`private file`}function ni(e){return e===`shared`?`SEO Skill app`:`Local OAuth config`}function ri(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`,ni(e.clientSource)],[`Expires`,Yn(e.expiresAt)]),t}const ii=x({meta:{name:`auth`,description:`Authentication commands`},subCommands:{login:x({meta:{name:`login`,description:`Run Google OAuth flow`},run:async()=>{if((await Fe()).activeMode===`service-account`)throw new v(`AUTH_CONFIG_REQUIRED`,`A service account is active from the environment. Unset its credential variable before running browser OAuth.`);let e=await je();R(ri({accountEmail:e.account_email,clientSource:e.client_source,expiresAt:e.expires_at,scope:e.scope}))}}),logout:x({meta:{name:`logout`,description:`Delete locally stored tokens`},run:async()=>{let e=await Fe();if(await t(),e.activeMode===`service-account`){process.stdout.write(`Deleted local OAuth tokens. Service account credentials remain available through the environment.
34
+ `),z([`Status`,`Check`,`Action`],e.topActions.map(e=>[e.status,e.title,K(e.action,96)]))),Y(`Caveats`,e.caveats)}const ai=x({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=M(e),n=ri(e),r=T(e[`report-id`]);if(n&&r)throw Error(`Use either a URL or --report-id, not both.`);let i=Oe(n?await(async()=>{let r=E(e),i=T(e.site),a=r||i?await H({client:r,site:i,options:{json:t}}):void 0;return pt({url:n,projectId:a?.client?.id,site:a?.site,maxPages:O(e[`max-pages`]),fetchRate:lr(e),refresh:D(e.refresh),checkAgentDiscovery:!0,useSitemap:!0,checkExternal:!1})})():await ei(e,{json:t}));if(t){L(i);return}ii(i)}}),oi=x({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 Xe(),n=t.flatMap(e=>e.propertySummaries.map(t=>({account:e.displayName??e.account,property:ve(t.property),displayName:t.displayName??t.property}))),r=T(e.save);if(r){let e=Je();e.analytics.google.defaultPropertyId=r,Tt(e)}if(M(e)){L({accountSummaries:t,properties:n,saved:r});return}r&&process.stdout.write(`Saved default Google Analytics property ${r}.\n`),z([`Property`,`Name`,`Account`],n.map(e=>[e.property,e.displayName,e.account]))}});async function si(e,t={resolveClient:Xr,resolveGoogleAnalyticsProperty:Zr}){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:Gt(n),options:e.options})}const ci=x({meta:{name:`analytics`,description:`Read analytics data from connected providers`},subCommands:{google:x({meta:{name:`google`,description:`Read Google Analytics properties and reports`},subCommands:{properties:oi,report:x({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 n=M(e),r=await si({property:T(e.property),project:E(e),options:{json:n}}),i=await bt(r,await dr(e.body,e[`body-file`])??{dateRanges:[{startDate:T(e[`start-date`]),endDate:T(e[`end-date`])}],dimensions:(A(e.dimensions)??[]).map(e=>({name:e})),metrics:(A(e.metrics)??[]).map(e=>({name:e})),limit:T(e.limit)},{refresh:D(e.refresh)});if(n){L(i);return}let a=t(i);if(R([[`Property`,r],[`Rows`,String(i.rowCount??a.length)]]),a.length){let e=Object.keys(a[0]??{});z(e,a.slice(0,25).map(t=>e.map(e=>t[e]??``)))}}})}})}});function li(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 ui(e){return e.active===`keychain`?`system keychain`:e.configured===`keychain`?`private file fallback`:`private file`}function di(e){return e===`shared`?`SEO Skill app`:`Local OAuth config`}function fi(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`,di(e.clientSource)],[`Expires`,ir(e.expiresAt)]),t}const pi=x({meta:{name:`auth`,description:`Authentication commands`},subCommands:{login:x({meta:{name:`login`,description:`Run Google OAuth flow`},run:async()=>{if((await St()).activeMode===`service-account`)throw new _(`AUTH_CONFIG_REQUIRED`,`A service account is active from the environment. Unset its credential variable before running browser OAuth.`);let e=await Be();R(fi({accountEmail:e.account_email,clientSource:e.client_source,expiresAt:e.expires_at,scope:e.scope}))}}),logout:x({meta:{name:`logout`,description:`Delete locally stored tokens`},run:async()=>{let e=await St();if(await Ge(),e.activeMode===`service-account`){process.stdout.write(`Deleted local OAuth tokens. Service account credentials remain available through the environment.
35
35
  `);return}process.stdout.write(`Deleted local OAuth tokens.
36
36
  Revoke at https://myaccount.google.com/permissions if you also want Google to forget the grant.
37
- `)}}),whoami:x({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 Fe();if(t.activeMode===`service-account`){let n={mode:`service-account`,account:t.identity??null,source:ei(t.serviceAccount.source)};if(M(e)){L(n);return}R([[`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(M(e)){L({mode:`oauth`,account:null});return}process.stdout.write(`Not logged in.
38
- `);return}if(M(e)){L({mode:`oauth`,account:n.account_email,scopes:n.scope.split(/\s+/u).filter(Boolean),clientSource:n.client_source,expiresAt:n.expires_at});return}R(ri({accountEmail:n.account_email,clientSource:n.client_source,expiresAt:n.expires_at,scope:n.scope}))}}),status:x({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 Fe(),n=t.activeMode===`oauth`?await Dt():void 0;if(M(e)){L({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`,ei(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]),R(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 Dt();R([[`Account`,t.tokens.account_email],[`Scopes`,t.tokens.scope],[`Client`,ni(t.tokens.client_source)],[`Expires`,Yn(t.tokens.expires_at)],[`Tokens file`,wt().tokensFile],[`Token storage`,ti(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:x({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 v(`INVALID_INPUT`,`Choose either --keychain or --file, not both.`);let t=e.keychain||e.file?await St(e.keychain?`keychain`:`file`):await Dt();if(M(e)){L(t);return}R([[`Configured storage`,t.configured],[`Active storage`,ti(t)],...t.reason?[[`Note`,t.reason]]:[]])}}),refresh:x({meta:{name:`refresh`,description:`Refresh the Google OAuth token`},run:async()=>{if((await Fe()).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 _e();process.stdout.write(`Refreshed. New expiry ${new Date(e.expires_at).toISOString()}.\n`)}}),"setup-client":x({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(!I({json:M(e)}))throw new v(`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.");Tn(`Local Google OAuth client`),S([`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`),ze({clientId:B(await Mn({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),clientSecret:B(await An({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}))}),kn(`Saved local OAuth config to ${wt().oauthClientFile}`)}})}}),ai=x({meta:{name:`cache`,description:`Cache helpers`},subCommands:{stats:x({meta:{name:`stats`,description:`Show local cache size and row counts`},run:async()=>{let e=Ne();R([[`DB`,e.dbPath],[`Size`,Rr(e.sizeBytes)],[`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:x({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=_(e.provider);process.stdout.write(`Removed ${t} cached rows.\n`)}})}});async function oi(e,t={}){return(await H({client:e.client,project:e.project,site:e.site,options:t})).site}function si(e){if(e.startsWith(`http://`)||e.startsWith(`https://`))return e;if(e.startsWith(`sc-domain:`))return`https://${e.slice(10)}/`}function ci(e){return e.replace(/^sc-domain:/,``).replace(/^https?:\/\//,``)}function li(e){return e.toLowerCase().replace(/^https?:\/\//,``).replace(/^sc-domain:/,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,60)}function ui(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 di(e){return e?e===`serp-framing`?`wording gap`:e===`content-gap`?`content gap`:e===`technical-check`?`technical check`:`covered`:`-`}function fi(e){let t=e.platform===`win32`?on:nn;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 pi(e={}){let t=e.home??Qt(),n=e.platform??process.platform,r=fi({home:t,platform:n,env:e.env??process.env}),i=n===`win32`?on:nn,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 mi(e,t={}){let n=t.platform??process.platform,r=t.exists??y,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=b(e,t);if(r(n))return n}for(let e of a){let t=b(en(i),e);if(r(t))return t}return e}function hi(e){return mi(e)!==e}function gi(e={}){let t=e.targets??pi(),n=e.hasCommand??hi,r=e.hasPath??y;return t.filter(e=>e.kind===`native`?e.commandNames.some(n):r(e.path)||e.detectionPaths.some(r)||e.commandNames.some(n))}const _i={insertSpaces:!0,tabSize:2,eol:`
41
- `};function vi(){return new Date().toISOString().replace(/[:.]/g,`-`)}function yi(e,t){Wt(en(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.${Date.now()}.tmp`;Zt(n,t,{encoding:`utf8`,mode:y(e)?Xt(e).mode&511:384}),Jt(n,e)}function bi(e){let t=`${e}.bak-${vi()}`,n=t,r=2;for(;y(n);)n=`${t}-${r}`,r+=1;Ut(e,n,Ht.COPYFILE_EXCL)}function xi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Si(e){if(!y(e.path))return{source:`{}
42
- `,config:{}};let t=Gt(e.path,`utf8`),n=[],r=Rn(t,n,{allowTrailingComma:!0});if(n.length>0){let t=n[0],r=t?`${zn(t.error)} at offset ${t.offset}`:`unknown parse error`;throw Error(`Cannot update ${e.path}: invalid JSONC (${r}).`)}if(!xi(r))throw Error(`Cannot update ${e.path}: config root must be an object.`);if(r.mcpServers!==void 0&&!xi(r.mcpServers))throw Error(`Cannot update ${e.path}: mcpServers must be an object.`);return{source:t,config:r}}function Ci(e){return e.includes(`mcp`)&&e.includes(`serve`)&&e.some(e=>e===`seo`||e.startsWith(`seo@`)||e===`@seo/cli`)}function wi(e,t){return typeof e.command!=`string`||t.length!==3||t[1]!==`mcp`||t[2]!==`serve`||!xi(e.env)?!1:e.env.SEO_MCP_CONFIGURED_BY===`seo`}function Ti(e){if(!xi(e)||!Array.isArray(e.args))return!1;let t=e.args.filter(e=>typeof e==`string`);return Ci(t)||wi(e,t)}function Ei(e){let t=In(e.source,Ln(e.source,[`mcpServers`,`seo`],e.value,{formattingOptions:_i}));y(e.target.path)&&bi(e.target.path),yi(e.target.path,t)}function Di(e,t){let n=ln(e,t,{encoding:`utf8`});return{status:n.status,stdout:n.stdout??``,stderr:n.stderr??``,error:n.error}}function Oi(e){let t=e.replaceAll(`\\`,`/`).toLowerCase();return t.includes(`/_npx/`)||t.includes(`/.npm/_npx/`)||t.includes(`/.cache/pnpm/dlx/`)}function ki(e){if(!e||!y(e))return;let t=qt(e);return Oi(t)?void 0:t}function Ai(e={}){let t=ki(e.cliPath??process.argv[1]);if(t)return{command:e.nodePath??process.execPath,args:[t,`mcp`,`serve`]};let n=`seo@${e.version??Ue}`;return(e.platform??process.platform)===`win32`?{command:`cmd`,args:[`/c`,`npx`,`-y`,n,`mcp`,`serve`]}:{command:`npx`,args:[`-y`,n,`mcp`,`serve`]}}function ji(e=!1,t=Ai()){let n=wt(),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 Mi(e){return e.includes(`SEO_MCP_CONFIGURED_BY`)||/args:\s+-y\s+(?:seo(?:@\S+)?|@seo\/cli)\s+mcp\s+serve\b/.test(e)}function Ni(e,t,n){let r=mi(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&&!Mi(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=wt(),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 Pi(e,t={}){let n={runCommand:t.runCommand??Di,reinstall:t.reinstall??!1,serverCommand:t.serverCommand??Ai()};if(e.kind===`native`)return Ni(e,`install`,n);let{source:r,config:i}=Si(e),a=i.mcpServers?.seo,o=ji(e.includeType,n.serverCommand);if(dn(a,o)&&!n.reinstall)return{client:e.client,path:e.path,changed:!1};if(a!==void 0&&!Ti(a))throw Error(`Cannot install SEO MCP: ${e.path} already has an unmanaged mcpServers.seo entry.`);return Ei({target:e,source:r,value:o}),{client:e.client,path:e.path,changed:!0}}function Fi(e,t={}){if(e.kind===`native`)return Ni(e,`uninstall`,{runCommand:t.runCommand??Di,reinstall:!1,serverCommand:Ai()});if(!y(e.path))return{client:e.client,path:e.path,changed:!1};let{source:n,config:r}=Si(e),i=r.mcpServers;if(i?.seo===void 0)return{client:e.client,path:e.path,changed:!1};if(!Ti(i.seo))throw Error(`Cannot uninstall SEO MCP: ${e.path} has an unmanaged mcpServers.seo entry.`);return Ei({target:e,source:n,value:void 0}),{client:e.client,path:e.path,changed:!0}}function Ii(e={}){let t=ln(`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 Li(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 Ri(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 ae(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 Fe();if(t.activeMode===`service-account`)return`service-account`;if(t.tokens)return`already-connected`;if(e[`skip-auth`])return`skipped`;if(!I({json:e.json===!0}))throw new v(`AUTH_REQUIRED`,"Not logged in. Run `seo auth login`, or pass --skip-auth to save a project profile without connecting Google.");let n=B(await jn({message:`Connect Google now?`,options:Li({sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured,canSkip:typeof e.site==`string`&&e.site.length>0})}));return n===`skip`?`skipped`:(n===`setup`&&ze({clientId:B(await Mn({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),clientSecret:B(await An({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}))}),S(`Connected as ${(await je()).account_email}. seo has read-only access and cannot change your site.`,`Google connected`),`connected`)}async function Bi(e){if(e.property)return{propertyId:e.property,selection:`explicit`,reason:`Set with --google-analytics-property.`};if(!(e.interactive??I()))return;let t=(await h().catch(()=>[])).flatMap(e=>e.propertySummaries.map(t=>({property:Te(t.property),label:t.displayName??t.property,account:e.displayName??e.account})));if(!t.length)return;let{candidates:n,complete:r}=await Ri(t),i=r?qn(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:Jn(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=B(await jn({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?Jn(t.match,e.site):t.account}))]}));if(c)return{propertyId:c.property,selection:`manual`,reason:c.match?Jn(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 Vi(e){return e[`skip-skill`]||!I({json:e.json===!0})?{status:`skipped`}:B(await wn({message:`Install the SEO skill so coding agents know how to run reports?`,initialValue:!0}))?Ii():{status:`declined`}}async function Hi(e){if(e[`skip-mcp`]||!I({json:e.json===!0}))return[];let t=gi();if(t.length===0||!B(await wn({message:`Install seo as an MCP server too?`,initialValue:!0})))return[];let n=B(await On({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 Pi(e)}catch(t){return{client:e.client,path:e.path,changed:!1,error:t instanceof Error?t.message:String(t)}}})}function Ui(e){return e.status===`installed`?`installed`:e.status===`failed`?`install failed`:`not installed`}function Wi(e){return/^[A-Za-z0-9_./:@-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function Gi(){process.stdout.write(`
43
- `),Ar({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 Ki(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 qi(e){let t=e.filter(e=>!!e.error);if(t.length!==0)return t.map(e=>`${e.client}: ${e.error}`).join(`
44
- `)}function Ji(e,t,n){if(n)return;let r=_t().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 Yi(e){let t=M(e);if(t||Tn(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?L({dryRun:!0,next:e}):(S(e.join(`
45
- `),`This setup will guide you through`),kn(`Dry run complete.`));return}ht();let n={site:T(e.site),options:{json:t,refresh:D(e.refresh)}},r=t?await V(n):void 0,i=await zi(e),a=r??await V(n),o=ci(a);if(I({json:t})&&S(`A project profile remembers the site and report defaults so future commands stay short.`,`Project profile`),!(D(e[`skip-profile`])!==!0&&(!I({json:t})||B(await wn({message:`Save this site as a project profile?`,initialValue:!0}))))){let n=await Hi(e),r=await Vi(e),o=`--site ${Wi(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){L(c);return}R([[`Project profile`,`not saved`],[`GSC property`,a],[`Auth`,i],[`MCP`,Ki(n)],[`SEO skill`,Ui(r)]]);let l=qi(n);l&&S(l,`MCP setup skipped`),r.error&&S(r.error,`SEO skill install failed`),S(s.join(`
46
- `),`Try next`),kn(`Setup complete.`),Gi();return}let s=T(e.name)??(I({json:t})?B(await Mn({message:`Project name`,placeholder:o,defaultValue:o})):o),c=T(e.id),l=c??Ji(a,s,c)?.id??li(s),u=si(a)??``,d=T(e.url)??(I({json:t})?B(await Mn({message:`Website URL to crawl`,placeholder:u||`https://example.com`,defaultValue:u})):u||void 0),f=j(e.urls).length>0?j(e.urls):[],p=await Bi({property:T(e[`google-analytics-property`]),site:a,interactive:I({json:t})}),m=p?.propertyId,h=ne({id:l,name:s,siteUrl:a}),g=j(e.brand).length>0?j(e.brand):h,ee=O(e[`report-day`])??1,te=O(e.weekday)??1,re=D(e.default)??!0,_=dt({id:l,name:s,siteUrl:a,startUrl:d,watchUrls:f,brandTerms:g,analytics:m?{google:{propertyId:m}}:void 0,reportDay:ee,technicalWeekday:te,isDefault:re}),ie=await Hi(e),ae=await Vi(e),oe=[`seo report --project ${_.id}`,`seo refresh-priorities --project ${_.id} --verify-content`,`seo technical-watch --project ${_.id}`],se={client:_,site:a,auth:i,googleAnalytics:p,mcp:ie,skill:ae,next:oe};if(t){L(se);return}R([[`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`,Ki(ie)],[`SEO skill`,Ui(ae)]]);let ce=qi(ie);ce&&S(ce,`MCP setup skipped`),ae.error&&S(ae.error,`SEO skill install failed`),S(oe.join(`
47
- `),`Try next`),kn(`Setup complete.`),Gi()}const Xi=x({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})=>Yi(e)}),Zi=x({...Xi,meta:{name:`start`,description:`Start here: connect Google, save a profile, and get the first report commands`}}),Qi=x({...Xi,meta:{name:`setup`,description:`Guided setup for one saved project profile`}}),$i=x({meta:{name:`brand`,description:`Detect and manage project brand query terms`},subCommands:{detect:x({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=M(e),n=Ge(E(e)),r=await se({site:await V({site:T(e.site)??n?.siteUrl,options:{json:t,refresh:D(e.refresh)}}),id:n?.id,name:n?.name,days:O(e.days),limit:O(e.limit),minImpressions:O(e[`min-impressions`]),refresh:D(e.refresh)}),i=D(e.save)&&n?dt({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(D(e.save)&&!n)throw Error(`Pass --project to save detected brand terms.`);if(t){L({...r,saved:i});return}R([[`Property`,r.site],[`Derived terms`,r.derivedTerms.join(`, `)],[`Suggested terms`,r.suggestedTerms.join(`, `)],[`Saved`,i?i.id:`no`]]),z([`Term`,`Score`,`Evidence`],r.candidates.map(e=>[e.term,e.score,e.evidence.map(e=>`${e.query} (${Math.round(e.clicks)} clicks)`).join(`, `)]))}})}});function ea(e){Pr(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 ta(e){R([[`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 na=x({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=M(e),n=dt({id:T(e.id),name:T(e.name),siteUrl:await V({site:T(e.site),options:{json:t}}),startUrl:T(e.url),watchUrls:j(e.urls),brandTerms:j(e.brand),analytics:T(e[`google-analytics-property`])?{google:{propertyId:T(e[`google-analytics-property`])??``}}:void 0,reportDay:O(e[`report-day`]),technicalWeekday:O(e.weekday),isDefault:D(e.default)});if(t){L(n);return}ta(n)}}),ra=x({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=$e(T(e.id)??``);if(M(e)){L(t);return}process.stdout.write(`Default project set to ${t.id}.\n`)}}),ia=x({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=T(e.id)??``,n=kt(t);if(M(e)){L({id:t,deleted:n});return}process.stdout.write(`${n?`Deleted`:`Not found`} ${t}.\n`)}}),aa=x({meta:{name:`client`,description:`Manage saved project profiles`},subCommands:{setup:Qi,brand:$i,list:x({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=_t();if(M(e)){L({clients:t});return}ea(t)}}),add:na,show:x({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=Ge(T(e.id));if(!t)throw Error(`Project not found.`);if(M(e)){L(t);return}ta(t)}}),default:ra,delete:ia}}),oa=x({...aa,meta:{name:`projects`,description:`Manage saved project profiles`}}),sa=x({meta:{name:`content`,description:`Optimize page content from real GSC queries`},subCommands:{optimize:x({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":w(`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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await de({site:n.site,url:T(e.url)??``,days:O(e.days),limit:O(e.limit),minImpressions:O(e[`min-impressions`]),brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`]),verifyContent:D(e[`verify-content`])!==!1,js:D(e.js)?!0:`auto`,refresh:D(e.refresh)});if(t){L(r);return}R([[`Property`,r.site],[`URL`,r.url],[`Score`,`${r.summary.score}/100`],[`Primary intent`,r.summary.primaryIntent],[`Primary query`,r.summary.primaryQuery??`none`],[`Queries`,U(r.summary.queries)],[`Opportunities`,U(r.summary.opportunities)],[`Estimated lift`,U(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(`
37
+ `)}}),whoami:x({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 St();if(t.activeMode===`service-account`){let n={mode:`service-account`,account:t.identity??null,source:li(t.serviceAccount.source)};if(M(e)){L(n);return}R([[`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(M(e)){L({mode:`oauth`,account:null});return}process.stdout.write(`Not logged in.
38
+ `);return}if(M(e)){L({mode:`oauth`,account:n.account_email,scopes:n.scope.split(/\s+/u).filter(Boolean),clientSource:n.client_source,expiresAt:n.expires_at});return}R(fi({accountEmail:n.account_email,clientSource:n.client_source,expiresAt:n.expires_at,scope:n.scope}))}}),status:x({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 St(),n=t.activeMode===`oauth`?await Rt():void 0;if(M(e)){L({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`,li(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]),R(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 Rt();R([[`Account`,t.tokens.account_email],[`Scopes`,t.tokens.scope],[`Client`,di(t.tokens.client_source)],[`Expires`,ir(t.tokens.expires_at)],[`Tokens file`,nt().tokensFile],[`Token storage`,ui(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:x({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 _(`INVALID_INPUT`,`Choose either --keychain or --file, not both.`);let t=e.keychain||e.file?await $e(e.keychain?`keychain`:`file`):await Rt();if(M(e)){L(t);return}R([[`Configured storage`,t.configured],[`Active storage`,ui(t)],...t.reason?[[`Note`,t.reason]]:[]])}}),refresh:x({meta:{name:`refresh`,description:`Refresh the Google OAuth token`},run:async()=>{if((await St()).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 Mt();process.stdout.write(`Refreshed. New expiry ${new Date(e.expires_at).toISOString()}.\n`)}}),"setup-client":x({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(!I({json:M(e)}))throw new _(`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.");Pn(`Local Google OAuth client`),S([`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`),vt({clientId:B(await Vn({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),clientSecret:B(await zn({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}))}),Rn(`Saved local OAuth config to ${nt().oauthClientFile}`)}})}}),mi=x({meta:{name:`cache`,description:`Cache helpers`},subCommands:{stats:x({meta:{name:`stats`,description:`Show local cache size and row counts`},run:async()=>{let e=ct();R([[`DB`,e.dbPath],[`Size`,qr(e.sizeBytes)],[`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:x({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=At(e.provider);process.stdout.write(`Removed ${t} cached rows.\n`)}})}});async function hi(e,t={}){return(await H({client:e.client,project:e.project,site:e.site,options:t})).site}function gi(e){if(e.startsWith(`http://`)||e.startsWith(`https://`))return e;if(e.startsWith(`sc-domain:`))return`https://${e.slice(10)}/`}function _i(e){return e.replace(/^sc-domain:/,``).replace(/^https?:\/\//,``)}function vi(e){return e.toLowerCase().replace(/^https?:\/\//,``).replace(/^sc-domain:/,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,60)}function yi(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 bi(e){return e?e===`serp-framing`?`wording gap`:e===`content-gap`?`content gap`:e===`technical-check`?`technical check`:`covered`:`-`}function xi(e){let t=e.platform===`win32`?hn: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 Si(e={}){let t=e.home??ln(),n=e.platform??process.platform,r=xi({home:t,platform:n,env:e.env??process.env}),i=n===`win32`?hn: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 Ci(e,t={}){let n=t.platform??process.platform,r=t.exists??v,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=b(e,t);if(r(n))return n}for(let e of a){let t=b(y(i),e);if(r(t))return t}return e}function wi(e){return Ci(e)!==e}function Ti(e={}){let t=e.targets??Si(),n=e.hasCommand??wi,r=e.hasPath??v;return t.filter(e=>e.kind===`native`?e.commandNames.some(n):r(e.path)||e.detectionPaths.some(r)||e.commandNames.some(n))}const Ei={insertSpaces:!0,tabSize:2,eol:`
41
+ `};function Di(){return new Date().toISOString().replace(/[:.]/g,`-`)}function Oi(e,t){en(y(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.${Date.now()}.tmp`;cn(n,t,{encoding:`utf8`,mode:v(e)?sn(e).mode&511:384}),an(n,e)}function ki(e){let t=`${e}.bak-${Di()}`,n=t,r=2;for(;v(n);)n=`${t}-${r}`,r+=1;$t(e,n,Qt.COPYFILE_EXCL)}function Ai(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ji(e){if(!v(e.path))return{source:`{}
42
+ `,config:{}};let t=tn(e.path,`utf8`),n=[],r=qn(t,n,{allowTrailingComma:!0});if(n.length>0){let t=n[0],r=t?`${Jn(t.error)} at offset ${t.offset}`:`unknown parse error`;throw Error(`Cannot update ${e.path}: invalid JSONC (${r}).`)}if(!Ai(r))throw Error(`Cannot update ${e.path}: config root must be an object.`);if(r.mcpServers!==void 0&&!Ai(r.mcpServers))throw Error(`Cannot update ${e.path}: mcpServers must be an object.`);return{source:t,config:r}}function Mi(e){return e.includes(`mcp`)&&e.includes(`serve`)&&e.some(e=>e===`seo`||e.startsWith(`seo@`)||e===`@seo/cli`)}function Ni(e,t){return typeof e.command!=`string`||t.length!==3||t[1]!==`mcp`||t[2]!==`serve`||!Ai(e.env)?!1:e.env.SEO_MCP_CONFIGURED_BY===`seo`}function Pi(e){if(!Ai(e)||!Array.isArray(e.args))return!1;let t=e.args.filter(e=>typeof e==`string`);return Mi(t)||Ni(e,t)}function Fi(e){let t=Gn(e.source,Kn(e.source,[`mcpServers`,`seo`],e.value,{formattingOptions:Ei}));v(e.target.path)&&ki(e.target.path),Oi(e.target.path,t)}function Ii(e,t){let n=vn(e,t,{encoding:`utf8`});return{status:n.status,stdout:n.stdout??``,stderr:n.stderr??``,error:n.error}}function Li(e){let t=e.replaceAll(`\\`,`/`).toLowerCase();return t.includes(`/_npx/`)||t.includes(`/.npm/_npx/`)||t.includes(`/.cache/pnpm/dlx/`)}function Ri(e){if(!e||!v(e))return;let t=rn(e);return Li(t)?void 0:t}function zi(e={}){let t=Ri(e.cliPath??process.argv[1]);if(t)return{command:e.nodePath??process.execPath,args:[t,`mcp`,`serve`]};let n=`seo@${e.version??Le}`;return(e.platform??process.platform)===`win32`?{command:`cmd`,args:[`/c`,`npx`,`-y`,n,`mcp`,`serve`]}:{command:`npx`,args:[`-y`,n,`mcp`,`serve`]}}function Bi(e=!1,t=zi()){let n=nt(),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 Vi(e){return e.includes(`SEO_MCP_CONFIGURED_BY`)||/args:\s+-y\s+(?:seo(?:@\S+)?|@seo\/cli)\s+mcp\s+serve\b/.test(e)}function Hi(e,t,n){let r=Ci(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&&!Vi(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=nt(),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 Ui(e,t={}){let n={runCommand:t.runCommand??Ii,reinstall:t.reinstall??!1,serverCommand:t.serverCommand??zi()};if(e.kind===`native`)return Hi(e,`install`,n);let{source:r,config:i}=ji(e),a=i.mcpServers?.seo,o=Bi(e.includeType,n.serverCommand);if(bn(a,o)&&!n.reinstall)return{client:e.client,path:e.path,changed:!1};if(a!==void 0&&!Pi(a))throw Error(`Cannot install SEO MCP: ${e.path} already has an unmanaged mcpServers.seo entry.`);return Fi({target:e,source:r,value:o}),{client:e.client,path:e.path,changed:!0}}function Wi(e,t={}){if(e.kind===`native`)return Hi(e,`uninstall`,{runCommand:t.runCommand??Ii,reinstall:!1,serverCommand:zi()});if(!v(e.path))return{client:e.client,path:e.path,changed:!1};let{source:n,config:r}=ji(e),i=r.mcpServers;if(i?.seo===void 0)return{client:e.client,path:e.path,changed:!1};if(!Pi(i.seo))throw Error(`Cannot uninstall SEO MCP: ${e.path} has an unmanaged mcpServers.seo entry.`);return Fi({target:e,source:n,value:void 0}),{client:e.client,path:e.path,changed:!0}}function Gi(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 Ki(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 qi(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 Ft(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 Ji(e){let t=await St();if(t.activeMode===`service-account`)return`service-account`;if(t.tokens)return`already-connected`;if(e[`skip-auth`])return`skipped`;if(!I({json:e.json===!0}))throw new _(`AUTH_REQUIRED`,"Not logged in. Run `seo auth login`, or pass --skip-auth to save a project profile without connecting Google.");let n=B(await Bn({message:`Connect Google now?`,options:Ki({sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured,canSkip:typeof e.site==`string`&&e.site.length>0})}));return n===`skip`?`skipped`:(n===`setup`&&vt({clientId:B(await Vn({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),clientSecret:B(await zn({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}))}),S(`Connected as ${(await Be()).account_email}. seo has read-only access and cannot change your site.`,`Google connected`),`connected`)}async function Yi(e){if(e.property)return{propertyId:e.property,selection:`explicit`,reason:`Set with --google-analytics-property.`};if(!(e.interactive??I()))return;let t=(await Xe().catch(()=>[])).flatMap(e=>e.propertySummaries.map(t=>({property:ve(t.property),label:t.displayName??t.property,account:e.displayName??e.account})));if(!t.length)return;let{candidates:n,complete:r}=await qi(t),i=r?nr(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=B(await Bn({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 Xi(e){return e[`skip-skill`]||!I({json:e.json===!0})?{status:`skipped`}:B(await Nn({message:`Install the SEO skill so coding agents know how to run reports?`,initialValue:!0}))?Gi():{status:`declined`}}async function Zi(e){if(e[`skip-mcp`]||!I({json:e.json===!0}))return[];let t=Ti();if(t.length===0||!B(await Nn({message:`Install seo as an MCP server too?`,initialValue:!0})))return[];let n=B(await Ln({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 Ui(e)}catch(t){return{client:e.client,path:e.path,changed:!1,error:t instanceof Error?t.message:String(t)}}})}function Qi(e){return e.status===`installed`?`installed`:e.status===`failed`?`install failed`:`not installed`}function $i(e){return/^[A-Za-z0-9_./:@-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function ea(){process.stdout.write(`
43
+ `),zr({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 ta(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 na(e){let t=e.filter(e=>!!e.error);if(t.length!==0)return t.map(e=>`${e.client}: ${e.error}`).join(`
44
+ `)}function ra(e,t,n){if(n)return;let r=xe().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 ia(e){let t=M(e);if(t||Pn(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?L({dryRun:!0,next:e}):(S(e.join(`
45
+ `),`This setup will guide you through`),Rn(`Dry run complete.`));return}at();let n={site:T(e.site),options:{json:t,refresh:D(e.refresh)}},r=t?await V(n):void 0,i=await Ji(e),a=r??await V(n),s=_i(a);if(I({json:t})&&S(`A project profile remembers the site and report defaults so future commands stay short.`,`Project profile`),!(D(e[`skip-profile`])!==!0&&(!I({json:t})||B(await Nn({message:`Save this site as a project profile?`,initialValue:!0}))))){let n=await Zi(e),r=await Xi(e),o=`--site ${$i(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){L(c);return}R([[`Project profile`,`not saved`],[`GSC property`,a],[`Auth`,i],[`MCP`,ta(n)],[`SEO skill`,Qi(r)]]);let l=na(n);l&&S(l,`MCP setup skipped`),r.error&&S(r.error,`SEO skill install failed`),S(s.join(`
46
+ `),`Try next`),Rn(`Setup complete.`),ea();return}let c=T(e.name)??(I({json:t})?B(await Vn({message:`Project name`,placeholder:s,defaultValue:s})):s),l=T(e.id),u=l??ra(a,c,l)?.id??vi(c),d=gi(a)??``,f=T(e.url)??(I({json:t})?B(await Vn({message:`Website URL to crawl`,placeholder:d||`https://example.com`,defaultValue:d})):d||void 0),p=j(e.urls).length>0?j(e.urls):[],m=await Yi({property:T(e[`google-analytics-property`]),site:a,interactive:I({json:t})}),h=m?.propertyId,te=ee({id:u,name:c,siteUrl:a}),ne=j(e.brand).length>0?j(e.brand):te,re=O(e[`report-day`])??1,ie=O(e.weekday)??1,ae=D(e.default)??!0,g=o({id:u,name:c,siteUrl:a,startUrl:f,watchUrls:p,brandTerms:ne,analytics:h?{google:{propertyId:h}}:void 0,reportDay:re,technicalWeekday:ie,isDefault:ae}),oe=await Zi(e),se=await Xi(e),ce=[`seo report --project ${g.id}`,`seo refresh-priorities --project ${g.id} --verify-content`,`seo technical-watch --project ${g.id}`],le={client:g,site:a,auth:i,googleAnalytics:m,mcp:oe,skill:se,next:ce};if(t){L(le);return}R([[`Project profile`,`${g.name} (${g.id})`],[`GSC property`,g.siteUrl],[`Crawl URL`,g.startUrl??`not set`],[`Watch URLs`,String(g.watchUrls.length)],[`Brand terms`,g.brandTerms.join(`, `)||`not set`],[`Google Analytics property`,g.analytics.google?.propertyId??`not connected (optional)`],...m?[[`Google Analytics selection`,m.reason]]:[],[`Auth`,i],[`MCP`,ta(oe)],[`SEO skill`,Qi(se)]]);let ue=na(oe);ue&&S(ue,`MCP setup skipped`),se.error&&S(se.error,`SEO skill install failed`),S(ce.join(`
47
+ `),`Try next`),Rn(`Setup complete.`),ea()}const aa=x({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})=>ia(e)}),oa=x({...aa,meta:{name:`start`,description:`Start here: connect Google, save a profile, and get the first report commands`}}),sa=x({...aa,meta:{name:`setup`,description:`Guided setup for one saved project profile`}}),ca=x({meta:{name:`brand`,description:`Detect and manage project brand query terms`},subCommands:{detect:x({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=M(e),n=He(E(e)),r=await oe({site:await V({site:T(e.site)??n?.siteUrl,options:{json:t,refresh:D(e.refresh)}}),id:n?.id,name:n?.name,days:O(e.days),limit:O(e.limit),minImpressions:O(e[`min-impressions`]),refresh:D(e.refresh)}),i=D(e.save)&&n?o({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(D(e.save)&&!n)throw Error(`Pass --project to save detected brand terms.`);if(t){L({...r,saved:i});return}R([[`Property`,r.site],[`Derived terms`,r.derivedTerms.join(`, `)],[`Suggested terms`,r.suggestedTerms.join(`, `)],[`Saved`,i?i.id:`no`]]),z([`Term`,`Score`,`Evidence`],r.candidates.map(e=>[e.term,e.score,e.evidence.map(e=>`${e.query} (${Math.round(e.clicks)} clicks)`).join(`, `)]))}})}});function la(e){Ur(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 ua(e){R([[`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 da=x({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=M(e),n=o({id:T(e.id),name:T(e.name),siteUrl:await V({site:T(e.site),options:{json:t}}),startUrl:T(e.url),watchUrls:j(e.urls),brandTerms:j(e.brand),analytics:T(e[`google-analytics-property`])?{google:{propertyId:T(e[`google-analytics-property`])??``}}:void 0,reportDay:O(e[`report-day`]),technicalWeekday:O(e.weekday),isDefault:D(e.default)});if(t){L(n);return}ua(n)}}),fa=x({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=Ut(T(e.id)??``);if(M(e)){L(t);return}process.stdout.write(`Default project set to ${t.id}.\n`)}}),pa=x({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=T(e.id)??``,n=qt(t);if(M(e)){L({id:t,deleted:n});return}process.stdout.write(`${n?`Deleted`:`Not found`} ${t}.\n`)}}),ma=x({meta:{name:`client`,description:`Manage saved project profiles`},subCommands:{setup:sa,brand:ca,list:x({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=xe();if(M(e)){L({clients:t});return}la(t)}}),add:da,show:x({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=He(T(e.id));if(!t)throw Error(`Project not found.`);if(M(e)){L(t);return}ua(t)}}),default:fa,delete:pa}}),ha=x({...ma,meta:{name:`projects`,description:`Manage saved project profiles`}}),ga=x({meta:{name:`content`,description:`Optimize page content from real GSC queries`},subCommands:{optimize:x({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":w(`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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await te({site:n.site,url:T(e.url)??``,days:O(e.days),limit:O(e.limit),minImpressions:O(e[`min-impressions`]),brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`]),verifyContent:D(e[`verify-content`])!==!1,js:D(e.js)?!0:`auto`,refresh:D(e.refresh)});if(t){L(r);return}R([[`Property`,r.site],[`URL`,r.url],[`Score`,`${r.summary.score}/100`],[`Primary intent`,r.summary.primaryIntent],[`Primary query`,r.summary.primaryQuery??`none`],[`Queries`,U(r.summary.queries)],[`Opportunities`,U(r.summary.opportunities)],[`Estimated lift`,U(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
48
  Suggested sections
49
49
  `),q([`Heading`,`Queries`],r.brief.sections.map(e=>[K(e.heading,48),K(e.queries.join(`, `),80)]))),r.intentMix.length&&(process.stdout.write(`
50
50
  Intent mix
51
- `),q([`Intent`,`Queries`,`Impressions`,`Clicks`],r.intentMix.map(e=>[e.intent,U(e.queries),U(e.impressions),U(e.clicks)]))),Y(`Caveats`,r.caveats)}})}}),ca={high:3,medium:2,low:1},la=x({meta:{name:`crawl`,description:`Crawl a site and run technical SEO checks`},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.`},"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, or markdown.`},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=M(e),n=pa(e.format,t),r=T(e.output),i=ma(e.csv),a=da(e.severity),o=da(e[`fail-on`]),s=E(e),c=await ha(e),l=fa(e),u=T(e.site)||s||!l&&!c.length?await H({client:s,site:T(e.site),options:{json:t}}):void 0,d=l??u?.client?.startUrl??(u?.site?si(u.site):void 0)??c[0];if(!d)throw Error(`No crawl URL selected. Pass a URL, --url, or use --project with a saved crawl URL.`);let f=await He({url:d,projectId:u?.client?.id,site:u?.site,mode:ua(e.mode)??(c.length?`list`:void 0),urls:c,maxPages:O(e[`max-pages`]),maxDepth:O(e[`max-depth`]),concurrency:O(e.concurrency),refresh:D(e.refresh),fetchRate:er({...e,"fetch-concurrency":e.concurrency}),include:A(e.include),exclude:A(e.exclude),googleAnalyticsPropertyId:T(e[`google-analytics-property`])??u?.client?.analytics.google?.propertyId,useSitemap:!Zn(e,`sitemap`),respectRobots:!Zn(e,`robots`),checkExternal:!Zn(e,`external`),js:Xn(e)}),p=D(e.save)?Ce(f):void 0,m=vt(f,{severity:a}),h=o?f.issues.some(e=>ca[e.severity]>=ca[o]):!1,g=f.status===`failed`,ee={...f,topFixes:m,reviewObservations:Xe(f,{severity:a}),...o?{failOn:o,failedThreshold:h}:{},...p?{saved:p}:{}};if(n===`json`){await _a(r,`${JSON.stringify(ee,null,2)}\n`),(g||h)&&(process.exitCode=1);return}if(n===`csv`){await _a(r,i===`pages`?jt(f):Tt(f)),(g||h)&&(process.exitCode=1);return}if(n===`html`){await _a(r,We(f,m)),(g||h)&&(process.exitCode=1);return}if(n===`markdown`){await _a(r,ut(f,m)),(g||h)&&(process.exitCode=1);return}if(r){await _a(r,Ke(f,m)),(g||h)&&(process.exitCode=1);return}process.stdout.write(Ke(f,m)),(p||o)&&(process.stdout.write(`
51
+ `),q([`Intent`,`Queries`,`Impressions`,`Clicks`],r.intentMix.map(e=>[e.intent,U(e.queries),U(e.impressions),U(e.clicks)]))),Y(`Caveats`,r.caveats)}})}}),_a={high:3,medium:2,low:1},va=x({meta:{name:`crawl`,description:`Crawl a site and run technical SEO checks`},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.`},"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, or markdown.`},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=M(e),n=Sa(e.format,t),r=T(e.output),i=Ca(e.csv),a=ba(e.severity),o=ba(e[`fail-on`]),s=E(e),c=await wa(e),l=xa(e),u=T(e.site)||s||!l&&!c.length?await H({client:s,site:T(e.site),options:{json:t}}):void 0,d=l??u?.client?.startUrl??(u?.site?gi(u.site):void 0)??c[0];if(!d)throw Error(`No crawl URL selected. Pass a URL, --url, or use --project with a saved crawl URL.`);let f=await pt({url:d,projectId:u?.client?.id,site:u?.site,mode:ya(e.mode)??(c.length?`list`:void 0),urls:c,maxPages:O(e[`max-pages`]),maxDepth:O(e[`max-depth`]),concurrency:O(e.concurrency),refresh:D(e.refresh),fetchRate:lr({...e,"fetch-concurrency":e.concurrency}),include:A(e.include),exclude:A(e.exclude),googleAnalyticsPropertyId:T(e[`google-analytics-property`])??u?.client?.analytics.google?.propertyId,useSitemap:!or(e,`sitemap`),respectRobots:!or(e,`robots`),checkExternal:!or(e,`external`),js:ar(e)}),p=D(e.save)?ge(f):void 0,m=Se(f,{severity:a}),ee=o?f.issues.some(e=>_a[e.severity]>=_a[o]):!1,h=f.status===`failed`,te={...f,topFixes:m,reviewObservations:Kt(f,{severity:a}),...o?{failOn:o,failedThreshold:ee}:{},...p?{saved:p}:{}};if(n===`json`){await Ea(r,`${JSON.stringify(te,null,2)}\n`),(h||ee)&&(process.exitCode=1);return}if(n===`csv`){await Ea(r,i===`pages`?Yt(f):rt(f)),(h||ee)&&(process.exitCode=1);return}if(n===`html`){await Ea(r,Re(f,m)),(h||ee)&&(process.exitCode=1);return}if(n===`markdown`){await Ea(r,Ht(f,m)),(h||ee)&&(process.exitCode=1);return}if(r){await Ea(r,Ue(f,m)),(h||ee)&&(process.exitCode=1);return}process.stdout.write(Ue(f,m)),(p||o)&&(process.stdout.write(`
52
52
  Run metadata
53
- `),R([[`Saved report`,p?.id??`no`],[`Fail threshold`,o??`off`]])),(g||h)&&(process.exitCode=1)}});function ua(e){let t=T(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function da(e){let t=T(e);if(t){if([`low`,`medium`,`high`].includes(t))return t;throw Error(`Severity must be one of: low, medium, high.`)}}function fa(e){let t=T(e.crawlUrl),n=T(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}function pa(e,t){let n=T(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`].includes(n))return n;throw Error(`Format must be one of: pretty, json, csv, html, markdown.`)}function ma(e){let t=T(e);if(!t)return`issues`;if([`issues`,`pages`].includes(t))return t;throw Error(`CSV table must be one of: issues, pages.`)}async function ha(e){let t=A(e.urls)??[],n=T(e[`urls-file`]);return n&&t.push(...ga(await gn(n,`utf8`))),[...new Set(t)]}function ga(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}async function _a(e,t){if(!e){process.stdout.write(t);return}await mn(en(e),{recursive:!0}),await bn(e,t),process.stdout.write(`Wrote ${e}\n`)}async function va(e,t){let n=E(e),r=T(e.site);if(!(!n&&!r))return(await H({client:n,site:r,options:{json:t}})).site}function ya(e){Pr(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 ba(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})`])}R(t),e.issueGroups.length&&(process.stdout.write(`
53
+ `),R([[`Saved report`,p?.id??`no`],[`Fail threshold`,o??`off`]])),(h||ee)&&(process.exitCode=1)}});function ya(e){let t=T(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function ba(e){let t=T(e);if(t){if([`low`,`medium`,`high`].includes(t))return t;throw Error(`Severity must be one of: low, medium, high.`)}}function xa(e){let t=T(e.crawlUrl),n=T(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}function Sa(e,t){let n=T(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`].includes(n))return n;throw Error(`Format must be one of: pretty, json, csv, html, markdown.`)}function Ca(e){let t=T(e);if(!t)return`issues`;if([`issues`,`pages`].includes(t))return t;throw Error(`CSV table must be one of: issues, pages.`)}async function wa(e){let t=A(e.urls)??[],n=T(e[`urls-file`]);return n&&t.push(...Ta(await Tn(n,`utf8`))),[...new Set(t)]}function Ta(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}async function Ea(e,t){if(!e){process.stdout.write(t);return}await Cn(y(e),{recursive:!0}),await kn(e,t),process.stdout.write(`Wrote ${e}\n`)}async function Da(e,t){let n=E(e),r=T(e.site);if(!(!n&&!r))return(await H({client:n,site:r,options:{json:t}})).site}function Oa(e){Ur(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 ka(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})`])}R(t),e.issueGroups.length&&(process.stdout.write(`
54
54
  Top issues
55
- `),z([`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 xa(e){if(R([[`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(`
55
+ `),z([`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 Aa(e){if(R([[`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
56
  Top actions
57
57
  `);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
58
  Changed pages
59
59
  `),z([`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
60
  Issue movement
61
- `),z([`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 Sa(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 Ca(e){if(e.value!==`latest`&&e.value!==`previous`)return Ft(e.value);let t=Sa(s({site:e.site,limit:20}),{value:e.value,skipId:e.skipId});return t?Ft(t.id):void 0}const wa=x({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=M(e),n=await va(e,t),r=T(e.delete),i=T(e.rerun),a=T(e.compare),o=T(e.id);if(r){let e=Lt(r);if(t){L({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`?xe(n):Ft(i);if(!e)throw Error(i===`latest`?`No saved crawl reports found.`:`No saved crawl report found for ${i}.`);let r=await He({...e.config,projectId:e.projectId,site:e.site,googleAnalyticsPropertyId:e.googleAnalyticsPropertyId}),a=Ce(r);if(t){L({...r,rerunOf:e.id,saved:a,topFixes:vt(r),reviewObservations:Xe(r)});return}process.stdout.write(`Reran crawl report ${e.id}.\n\n`),ba(r);return}if(a){let r=Ca({value:a,site:n});if(!r)throw Error(`No saved crawl report found for ${a}.`);let i=T(e.against)??`previous`,o=Ca({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=gt({before:o,after:r});if(t){L(s);return}xa(s);return}if(o||D(e.latest)){let e=o?Ft(o):xe(n);if(!e)throw Error(o?`No saved crawl report found for ${o}.`:`No saved crawl reports found.`);if(t){L(e);return}ba(e);return}let c=s({site:n,limit:O(e.limit)});if(t){L({reports:c});return}ya(c)}}),Ta=x({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 nr(e.body,e[`body-file`])??{startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),dimensions:A(e.dimensions)??[`query`,`page`],type:T(e.type)??`web`,rowLimit:O(e.limit),dataState:`final`},n=M(e),r=await oi({client:E(e),site:T(e.site)??T(t.siteUrl)},{json:n,refresh:D(e.refresh)});delete t.siteUrl;let i=await a(r,t,{refresh:D(e.refresh)}),o=O(e.limit),s=o?i.rows.slice(0,o):i.rows;if(n){L({site:r,request:t,...i,rows:s,rowsReturned:s.length});return}R([[`Property`,r],[`Rows returned`,String(s.length)],[`Rows fetched`,String(i.rowsFetched)],[`API calls`,String(i.calls)]]),z([`Keys`,`Clicks`,`Impr`,`CTR`,`Pos`],s.slice(0,25).map(e=>[e.keys.join(` | `),Math.round(e.clicks),Math.round(e.impressions),e.ctr.toFixed(3),e.position.toFixed(1)]))}}),Ea=x({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=M(e),n=await oi({client:E(e),site:T(e.site)},{json:t}),r=T(e.url);if(!r)throw Error(`Pass --url.`);let i=await De({siteUrl:n,inspectionUrl:r,languageCode:T(e.language)});if(t){L(i);return}let a=i.inspectionResult?.indexStatusResult;R([[`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`]])}}),Da={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. 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=Da[e];return[n.cli,{...n.arg,...t[e]}]}))}function Oa(e){return e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function ka(e){if(e===null)return`n/a`;let t=Math.abs(e)>=10?e.toFixed(0):e.toFixed(1);return`${e>0?`+`:``}${t}%`}const Aa=x({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=M(e),n=await we({site:await oi({client:E(e),site:T(e.site)},{json:t,refresh:D(e.refresh)}),days:O(e.days),recentDays:O(e.recent),refresh:D(e.refresh)});if(t){L(n);return}q([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`,`Significant`],n.anomalies.map(e=>[e.metric,e.direction,Oa(e.baselineMean),Oa(e.comparisonMean),ka(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])}}),ja=x({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=M(e),n=E(e),r=await oi({client:n,site:T(e.site)},{json:t,refresh:D(e.refresh)}),i=await Oe({site:r,days:O(e.days),recentDays:O(e.recent),paddingDays:O(e[`padding-days`]),knownConfounders:T(e[`known-change`])?[T(e[`known-change`])??``]:void 0,includeChangeLog:!D(e[`ignore-change-log`]),refresh:D(e.refresh)});if(t){L(i);return}R([[`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,Oa(e.baselineMean),Oa(e.comparisonMean),ka(e.percentChange),e.zScore??`n/a`])),i.overlappingUpdates.length&&(process.stdout.write(`
61
+ `),z([`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 ja(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 Ma(e){if(e.value!==`latest`&&e.value!==`previous`)return fe(e.value);let t=ja(ue({site:e.site,limit:20}),{value:e.value,skipId:e.skipId});return t?fe(t.id):void 0}const Na=x({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=M(e),n=await Da(e,t),i=T(e.delete),a=T(e.rerun),o=T(e.compare),s=T(e.id);if(i){let e=r(i);if(t){L({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`?dt(n):fe(a);if(!e)throw Error(a===`latest`?`No saved crawl reports found.`:`No saved crawl report found for ${a}.`);let r=await pt({...e.config,projectId:e.projectId,site:e.site,googleAnalyticsPropertyId:e.googleAnalyticsPropertyId}),i=ge(r);if(t){L({...r,rerunOf:e.id,saved:i,topFixes:Se(r),reviewObservations:Kt(r)});return}process.stdout.write(`Reran crawl report ${e.id}.\n\n`),ka(r);return}if(o){let r=Ma({value:o,site:n});if(!r)throw Error(`No saved crawl report found for ${o}.`);let i=T(e.against)??`previous`,a=Ma({value:i,site:r.site??n,skipId:r.id});if(!a)throw Error(`No baseline crawl report found for ${i}. Save at least two reports or pass --against <id>.`);let s=ot({before:a,after:r});if(t){L(s);return}Aa(s);return}if(s||D(e.latest)){let e=s?fe(s):dt(n);if(!e)throw Error(s?`No saved crawl report found for ${s}.`:`No saved crawl reports found.`);if(t){L(e);return}ka(e);return}let c=ue({site:n,limit:O(e.limit)});if(t){L({reports:c});return}Oa(c)}}),Pa=x({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 dr(e.body,e[`body-file`])??{startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),dimensions:A(e.dimensions)??[`query`,`page`],type:T(e.type)??`web`,rowLimit:O(e.limit),dataState:`final`},n=M(e),r=await hi({client:E(e),site:T(e.site)??T(t.siteUrl)},{json:n,refresh:D(e.refresh)});delete t.siteUrl;let i=await Pe(r,t,{refresh:D(e.refresh)}),a=O(e.limit),o=a?i.rows.slice(0,a):i.rows;if(n){L({site:r,request:t,...i,rows:o,rowsReturned:o.length});return}R([[`Property`,r],[`Rows returned`,String(o.length)],[`Rows fetched`,String(i.rowsFetched)],[`API calls`,String(i.calls)]]),z([`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)]))}}),Fa=x({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=M(e),n=await hi({client:E(e),site:T(e.site)},{json:t}),r=T(e.url);if(!r)throw Error(`Pass --url.`);let i=await Me({siteUrl:n,inspectionUrl:r,languageCode:T(e.language)});if(t){L(i);return}let a=i.inspectionResult?.indexStatusResult;R([[`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`]])}}),Ia={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. 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=Ia[e];return[n.cli,{...n.arg,...t[e]}]}))}function La(e){return e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function Ra(e){if(e===null)return`n/a`;let t=Math.abs(e)>=10?e.toFixed(0):e.toFixed(1);return`${e>0?`+`:``}${t}%`}const za=x({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=M(e),n=await _e({site:await hi({client:E(e),site:T(e.site)},{json:t,refresh:D(e.refresh)}),days:O(e.days),recentDays:O(e.recent),refresh:D(e.refresh)});if(t){L(n);return}q([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`,`Significant`],n.anomalies.map(e=>[e.metric,e.direction,La(e.baselineMean),La(e.comparisonMean),Ra(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])}}),Ba=x({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:t})=>{let n=M(t),r=E(t),i=await hi({client:r,site:T(t.site)},{json:n,refresh:D(t.refresh)}),a=await e({site:i,days:O(t.days),recentDays:O(t.recent),paddingDays:O(t[`padding-days`]),knownConfounders:T(t[`known-change`])?[T(t[`known-change`])??``]:void 0,includeChangeLog:!D(t[`ignore-change-log`]),refresh:D(t.refresh)});if(n){L(a);return}R([[`Classification`,a.classification.replaceAll(`-`,` `)],[`Causal attribution`,a.attribution.replaceAll(`-`,` `)],[`Causal confidence`,a.confidence],[`Updates matched`,String(a.overlappingUpdates.length)],[`Known confounders`,String(a.confounders.length)],[`Source`,a.source.name]]),process.stdout.write(`\n${a.summary}\n`),Y(`Evidence`,a.evidence),Y(`Report caveats`,a.caveats),Y(`Recommended next checks`,a.actions),q([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`],a.anomalies.map(e=>[e.metric,e.direction,La(e.baselineMean),La(e.comparisonMean),Ra(e.percentChange),e.zScore??`n/a`])),a.overlappingUpdates.length&&(process.stdout.write(`
62
62
  Updates
63
- `),z([`Start`,`End`,`Type`,`Name`],i.overlappingUpdates.map(e=>[e.start.slice(0,10),e.end?.slice(0,10)??`open`,e.type,e.name]))),Wr(`seo segment-impact ${n?`--project ${JSON.stringify(n)}`:`--site ${JSON.stringify(r)}`} --dimension page`)}});function Ma(e){process.stdout.write(`Entity evidence for ${e.url}\n\n`),R([[`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(`
63
+ `),z([`Start`,`End`,`Type`,`Name`],a.overlappingUpdates.map(e=>[e.start.slice(0,10),e.end?.slice(0,10)??`open`,e.type,e.name]))),$r(`seo segment-impact ${r?`--project ${JSON.stringify(r)}`:`--site ${JSON.stringify(i)}`} --dimension page`)}});function Va(e){process.stdout.write(`Entity evidence for ${e.url}\n\n`),R([[`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
64
  Schema types
65
- `),z([`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 Na=x({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=M(e),n=at(await Gr(e,{json:t}));if(t){L(n);return}Ma(n)}});function Pa(){return new Date().toISOString().slice(0,10)}function Fa(e){let t=T(e)??`page`;if(t!==`site`&&t!==`page`&&t!==`query`&&t!==`group`)throw Error(`Invalid --scope. Use site, page, query, or group.`);return t}const Ia=x({meta:{name:`change-log`,description:`Annotate SEO changes and measure before/after impact`},subCommands:{list:x({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=ie({site:T(e.site),limit:O(e.limit)});if(M(e)){L({changes:t});return}z([`ID`,`Date`,`Site`,`Scope`,`Target`,`Title`],t.map(e=>[e.id,e.changedAt,e.site,e.scope,e.target,e.title]))}}),add:x({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=M(e),n=yt({site:await V({site:T(e.site),options:{json:t}}),scope:Fa(e.scope),target:T(e.target)??``,title:T(e.title)??``,description:T(e.description),changedAt:T(e.date)??Pa()});if(t){L(n);return}R([[`ID`,n.id],[`Date`,n.changedAt],[`Site`,n.site],[`Scope`,n.scope],[`Target`,n.target],[`Title`,n.title]])}}),delete:x({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=T(e.id)??``,n=m(t);if(M(e)){L({id:t,deleted:n});return}process.stdout.write(`${n?`Deleted`:`Not found`} ${t}.\n`)}}),measure:x({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=M(e),n=T(e.id);if(!n&&(!T(e.site)||!T(e.scope)||!T(e.target)||!T(e.date)))throw Error(`Pass --id, or pass --site, --scope, --target, and --date for an ad hoc measurement.`);let r=await ve({id:n,site:n?void 0:await V({site:T(e.site),options:{json:t}}),scope:n?void 0:Fa(e.scope),target:n?void 0:T(e.target),title:T(e.title),changedAt:n?void 0:T(e.date),beforeDays:k(e.before,`--before`),afterDays:k(e.after,`--after`),refresh:D(e.refresh)});if(t){L(r);return}R([[`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]]),z([`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 La(e){let t=T(e)??`page`;if(t!==`page`&&t!==`query`)throw Error(`Invalid --dimension. Use page or query.`);return t}function Ra(e){let t=T(e)??`contains`;if(t!==`equals`&&t!==`contains`&&t!==`regex`)throw Error(`Invalid --match. Use equals, contains, or regex.`);return t}const za=x({meta:{name:`content-groups`,description:`Create and manage reusable page/query groups`},subCommands:{list:x({meta:{name:`list`,description:`List saved content groups`},args:{site:{type:`string`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=Ee(T(e.site));if(M(e)){L({groups:t});return}z([`ID`,`Site`,`Name`,`Dimension`,`Match`,`Pattern`],t.map(e=>[e.id,e.site,e.name,e.dimension,e.matchType,e.pattern]))}}),add:x({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=M(e),n=Bt({site:await V({site:T(e.site),options:{json:t}}),name:T(e.name)??``,dimension:La(e.dimension),matchType:Ra(e.match),pattern:T(e.pattern)??``});if(t){L(n);return}R([[`ID`,n.id],[`Site`,n.site],[`Name`,n.name],[`Filter`,`${n.dimension} ${n.matchType} ${n.pattern}`]])}}),delete:x({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=T(e.id)??``,n=i(t);if(M(e)){L({id:t,deleted:n});return}process.stdout.write(`${n?`Deleted`:`Not found`} ${t}.\n`)}})}});function Ba(){return new Date().toISOString().slice(0,10)}function Va(e){let t=T(e)??`page`;if(t!==`site`&&t!==`page`&&t!==`query`&&t!==`group`)throw Error(`Invalid --scope. Use site, page, query, or group.`);return t}function Ha(e){return e?Va(e):void 0}function Ua(e){return e===null?`n/a`:`${e.toFixed(1)}%`}function Wa(e){return e==null?`unavailable`:U(e)}function Ga(e,t){return e===null?`unavailable`:`${U(e)} (${Ua(t)})`}function Ka(e,t=1){return e==null?`unavailable`:e.toFixed(t)}function qa(e){R([[`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]]),z([`Metric`,`Before`,`After`,`Delta`],[[`GSC clicks`,Wa(e.before.metrics?.clicks),Wa(e.after.metrics?.clicks),Ga(e.delta.clicks,e.delta.clickPct)],[`GSC impressions`,Wa(e.before.metrics?.impressions),Wa(e.after.metrics?.impressions),Ga(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`,Ka(e.before.metrics?.position),Ka(e.after.metrics?.position),Ka(e.delta.position)]]),e.analytics&&(process.stdout.write(`
65
+ `),z([`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 Ha=x({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=M(e),n=a(await ei(e,{json:t}));if(t){L(n);return}Va(n)}});function Ua(){return new Date().toISOString().slice(0,10)}function Wa(e){let t=T(e)??`page`;if(t!==`site`&&t!==`page`&&t!==`query`&&t!==`group`)throw Error(`Invalid --scope. Use site, page, query, or group.`);return t}const Ga=x({meta:{name:`change-log`,description:`Annotate SEO changes and measure before/after impact`},subCommands:{list:x({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=It({site:T(e.site),limit:O(e.limit)});if(M(e)){L({changes:t});return}z([`ID`,`Date`,`Site`,`Scope`,`Target`,`Title`],t.map(e=>[e.id,e.changedAt,e.site,e.scope,e.target,e.title]))}}),add:x({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=M(e),n=xt({site:await V({site:T(e.site),options:{json:t}}),scope:Wa(e.scope),target:T(e.target)??``,title:T(e.title)??``,description:T(e.description),changedAt:T(e.date)??Ua()});if(t){L(n);return}R([[`ID`,n.id],[`Date`,n.changedAt],[`Site`,n.site],[`Scope`,n.scope],[`Target`,n.target],[`Title`,n.title]])}}),delete:x({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=T(e.id)??``,n=Ze(t);if(M(e)){L({id:t,deleted:n});return}process.stdout.write(`${n?`Deleted`:`Not found`} ${t}.\n`)}}),measure:x({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=M(e),n=T(e.id);if(!n&&(!T(e.site)||!T(e.scope)||!T(e.target)||!T(e.date)))throw Error(`Pass --id, or pass --site, --scope, --target, and --date for an ad hoc measurement.`);let r=await Dt({id:n,site:n?void 0:await V({site:T(e.site),options:{json:t}}),scope:n?void 0:Wa(e.scope),target:n?void 0:T(e.target),title:T(e.title),changedAt:n?void 0:T(e.date),beforeDays:k(e.before,`--before`),afterDays:k(e.after,`--after`),refresh:D(e.refresh)});if(t){L(r);return}R([[`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]]),z([`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 Ka(e){let t=T(e)??`page`;if(t!==`page`&&t!==`query`)throw Error(`Invalid --dimension. Use page or query.`);return t}function qa(e){let t=T(e)??`contains`;if(t!==`equals`&&t!==`contains`&&t!==`regex`)throw Error(`Invalid --match. Use equals, contains, or regex.`);return t}const Ja=x({meta:{name:`content-groups`,description:`Create and manage reusable page/query groups`},subCommands:{list:x({meta:{name:`list`,description:`List saved content groups`},args:{site:{type:`string`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=je(T(e.site));if(M(e)){L({groups:t});return}z([`ID`,`Site`,`Name`,`Dimension`,`Match`,`Pattern`],t.map(e=>[e.id,e.site,e.name,e.dimension,e.matchType,e.pattern]))}}),add:x({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=M(e),n=ie({site:await V({site:T(e.site),options:{json:t}}),name:T(e.name)??``,dimension:Ka(e.dimension),matchType:qa(e.match),pattern:T(e.pattern)??``});if(t){L(n);return}R([[`ID`,n.id],[`Site`,n.site],[`Name`,n.name],[`Filter`,`${n.dimension} ${n.matchType} ${n.pattern}`]])}}),delete:x({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=T(e.id)??``,n=Ne(t);if(M(e)){L({id:t,deleted:n});return}process.stdout.write(`${n?`Deleted`:`Not found`} ${t}.\n`)}})}});function Ya(){return new Date().toISOString().slice(0,10)}function Xa(e){let t=T(e)??`page`;if(t!==`site`&&t!==`page`&&t!==`query`&&t!==`group`)throw Error(`Invalid --scope. Use site, page, query, or group.`);return t}function Za(e){return e?Xa(e):void 0}function Qa(e){return e===null?`n/a`:`${e.toFixed(1)}%`}function $a(e){return e==null?`unavailable`:U(e)}function eo(e,t){return e===null?`unavailable`:`${U(e)} (${Qa(t)})`}function to(e,t=1){return e==null?`unavailable`:e.toFixed(t)}function no(e){R([[`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]]),z([`Metric`,`Before`,`After`,`Delta`],[[`GSC clicks`,$a(e.before.metrics?.clicks),$a(e.after.metrics?.clicks),eo(e.delta.clicks,e.delta.clickPct)],[`GSC impressions`,$a(e.before.metrics?.impressions),$a(e.after.metrics?.impressions),eo(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`,to(e.before.metrics?.position),to(e.after.metrics?.position),to(e.delta.position)]]),e.analytics&&(process.stdout.write(`
66
66
  Google Analytics impact
67
- `),z([`Metric`,`Before`,`After`,`Delta`],[[`Sessions`,U(e.analytics.before.metrics.sessions),U(e.analytics.after.metrics.sessions),`${U(e.analytics.delta.sessions)} (${Ua(e.analytics.delta.sessionPct)})`],[`Conversions`,U(e.analytics.before.metrics.conversions),U(e.analytics.after.metrics.conversions),`${U(e.analytics.delta.conversions)} (${Ua(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)} (${Ua(e.analytics.delta.revenuePct)})`]])),e.control&&(process.stdout.write(`
67
+ `),z([`Metric`,`Before`,`After`,`Delta`],[[`Sessions`,U(e.analytics.before.metrics.sessions),U(e.analytics.after.metrics.sessions),`${U(e.analytics.delta.sessions)} (${Qa(e.analytics.delta.sessionPct)})`],[`Conversions`,U(e.analytics.before.metrics.conversions),U(e.analytics.after.metrics.conversions),`${U(e.analytics.delta.conversions)} (${Qa(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)} (${Qa(e.analytics.delta.revenuePct)})`]])),e.control&&(process.stdout.write(`
68
68
  Control comparison
69
- `),R([[`Control`,e.control.change.title],[`Adjusted clicks`,e.control.adjusted.clickDelta===null?`n/a`:U(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 Ja=x({meta:{name:`tests`,description:`Create and report local SEO tests from Search Console and Google Analytics data`},subCommands:{list:x({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=M(e),n=E(e),r=ie({site:(n||T(e.site)?await H({client:n,site:T(e.site),options:{json:t}}):void 0)?.site,limit:O(e.limit)});if(t){L({tests:r});return}z([`ID`,`Date`,`Scope`,`Target`,`Title`],r.map(e=>[e.id,e.changedAt,e.scope,e.target,e.title]))}}),create:x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t}}),r=yt({site:n.site,scope:Va(e.scope),target:T(e.target)??``,title:T(e.title)??``,description:T(e.description),changedAt:T(e.date)??Ba()});if(t){L(r);return}R([[`ID`,r.id],[`Date`,r.changedAt],[`Project`,n.client?.name??n.site],[`Scope`,r.scope],[`Target`,r.target],[`Title`,r.title]])}}),report:x({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=M(e),n=T(e.id),r=!n||E(e)||T(e.site)?await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}):void 0,i=await ve({id:n,site:n?void 0:r?.site,scope:n?void 0:Ha(e.scope),target:n?void 0:T(e.target),title:T(e.title),changedAt:n?void 0:T(e.date),googleAnalyticsPropertyId:T(e.property)??r?.client?.analytics.google?.propertyId,controlScope:Ha(e[`control-scope`]),controlTarget:T(e[`control-target`]),controlTitle:T(e[`control-title`]),beforeDays:k(e.before,`--before`),afterDays:k(e.after,`--after`),refresh:D(e.refresh)});if(t){L(i);return}qa(i)}})}});function Ya(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 Xa={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.`}},Za={...X([`includeBrand`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}};function Qa(e){return{includeBrand:D(e[`include-brand`]),verifyContent:D(e[`verify-content`]),verifyLimit:O(e[`verify-limit`])??3,js:D(e.js)?!0:void 0,rate:er(e),refresh:D(e.refresh)}}function $a(e){return{client:E(e),site:T(e.site),refresh:D(e.refresh)}}const{json:eo,...to}=Za,no=to,ro={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 io(e){return{type:`string`,description:`Output folder. Defaults to ./seo-export/<project>-${e}-YYYY-MM-DD.`}}function ao(e){return e.toLowerCase().replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)}function oo(e){let t=new Date().toISOString().slice(0,10),n=ao(e.clientId??e.site);return an(process.cwd(),`seo-export`,`${n}-${e.report}-${t}`)}async function so(e,t){await mn(e,{recursive:!0});let n=[];for(let r of t){let t=an(e,r.filename);await bn(t,Nt(r.rows,r.headers),`utf8`),n.push(t)}return n}function co(e,t){process.stdout.write(`Wrote ${Je(t.length,`CSV file`)} to ${e}\n`);for(let e of t)process.stdout.write(`- ${e}\n`)}const lo=x({meta:{name:`diagnose`,description:`Export diagnosis tables: priorities, anomalies, movement, decay, cannibalisation, striking-distance, and quick wins.`},args:{...ro,out:io(`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 H({client:E(e),site:T(e.site)}),n=await g({site:t.site,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),brandTerms:t.client?.brandTerms,includeBrand:D(e[`include-brand`]),verifyContent:D(e[`verify-content`]),verifyLimit:O(e[`verify-limit`]),js:D(e.js)?!0:`auto`,rate:er(e),refresh:D(e.refresh),progress:Ya(!0)}),r=T(e.out)??oo({report:`diagnose`,clientId:t.client?.id,site:t.site});co(r,await so(r,ft(n)))}}),uo=`.seo-okf.json`,fo=`${JSON.stringify({generator:`seo`,format:`okf`,version:1})}\n`;function po(e,t){let n=an(e,t),r=rn(an(e),n);if(!r||r.startsWith(`..`)||tn(r))throw new v(`INVALID_INPUT`,`Unsafe OKF file path: ${t}`);return n}async function mo(e,t){for(let n of t){let t=po(e,n.path);await mn(en(t),{recursive:!0}),await bn(t,n.content)}await bn(b(e,uo),fo)}async function ho(e){let t=[];async function n(e,r=``){let i=await _n(e,{withFileTypes:!0});for(let a of i){let i=r?`${r}/${a.name}`:a.name,o=b(e,a.name);a.isDirectory()?await n(o,i):a.isFile()&&a.name.endsWith(`.md`)&&t.push({path:i,content:await gn(o,`utf8`)})}}return await n(e),t.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}async function go(e){try{let t=await pn(e);if(t.isSymbolicLink()||!t.isDirectory())throw new v(`INVALID_INPUT`,`OKF output must be a real directory: ${e}`);if(!(await _n(e)).length)return!0;try{if(await gn(b(e,uo),`utf8`)===fo)return!0}catch{}throw new v(`INVALID_INPUT`,`Refusing to replace non-empty unmanaged directory: ${e}`)}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function _o(e,t){if(!Be(t).valid)throw new v(`INVALID_INPUT`,`Generated bundle did not pass seo OKF checks and was not written.`);let n=an(e),r=en(n);await mn(r,{recursive:!0});let i=await go(n),a=await hn(b(r,`.${$t(n)}-staging-`)),o=b(r,`.${$t(n)}-backup-${sn()}`),s=!1;try{await mo(a,t);let e=Be(await ho(a));if(!e.valid)throw new v(`INTERNAL_ERROR`,`Staged OKF files failed validation after writing.`);return i&&(await vn(n,o),s=!0),await vn(a,n),s&&await yn(o,{recursive:!0,force:!0}),e}catch(e){throw await yn(a,{recursive:!0,force:!0}),s&&(await yn(n,{recursive:!0,force:!0}),await vn(o,n)),e}}async function vo(e,t){if(!e){process.stdout.write(t);return}await mn(en(e),{recursive:!0}),await bn(e,t),process.stdout.write(`Wrote ${e}\n`)}function yo(e){let t=T(e)??`okf`;if([`okf`,`markdown`,`json`].includes(t))return t;throw Error(`Format must be one of: okf, markdown, json.`)}function bo(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:r(e),entityReadiness:at(e),llmsTxt:pe(e)}}function xo(e){let t=bo(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 So=x({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=M(e),n=yo(e.format),r=n===`okf`?rt(k(e[`max-concepts`],`--max-concepts`)):void 0,i=await Gr(e,{json:t}),a=T(e.output);if(n===`okf`){let e=mt(i,{maxConcepts:r}),o=a??`./okf`,s=await _o(o,e.files);if(t){L({format:n,output:o,bundle:e,validation:s});return}process.stdout.write(`Wrote OKF bundle to ${o}\n\n`),R([[`Files`,String(e.files.length)],[`Concepts`,String(e.conceptCount)],[`Valid`,s.valid?`yes`:`no`]]);return}if(n===`json`){await vo(a,`${JSON.stringify(bo(i),null,2)}\n`);return}await vo(a,xo(i))}}),Co=x({meta:{name:`monthly`,description:`Export monthly report tables plus the underlying diagnosis detail CSVs.`},args:{...ro,out:io(`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.`}}),...no},run:async({args:e})=>{let t=await H({client:E(e),site:T(e.site),options:{refresh:D(e.refresh)}}),n=await o({site:t.site,month:T(e.month),limit:O(e.limit),brandTerms:t.client?.brandTerms,...Qa(e),progress:Ya(!0)}),r=T(e.out)??oo({report:`monthly`,clientId:t.client?.id,site:t.site});co(r,await so(r,et(n)))}}),wo=x({meta:{name:`narrative`,description:`Export report narrative tables plus the underlying diagnosis detail CSVs.`},args:{...ro,out:io(`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.`},...no},run:async({args:e})=>{let t=await H({client:E(e),site:T(e.site),options:{refresh:D(e.refresh)}}),n=await Pt({site:t.site,days:O(e.days),recentDays:O(e.recent),startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),limit:O(e.limit),changeLimit:O(e[`change-limit`]),brandTerms:t.client?.brandTerms,...Qa(e),progress:Ya(!0)}),r=T(e.out)??oo({report:`narrative`,clientId:t.client?.id,site:t.site});co(r,await so(r,et(n)))}});function To(e){return u({days:k(e.days,`--days`),sitemaps:A(e.sitemap),maxSitemapUrls:k(e[`max-sitemap-urls`],`--max-sitemap-urls`),templateLimit:k(e.limit,`--limit`),minimumTemplateUrls:k(e[`minimum-template-urls`],`--minimum-template-urls`),minimumTemplateShare:k(e[`minimum-template-share`],`--minimum-template-share`),minimumTemplateImpressions:k(e[`minimum-template-impressions`],`--minimum-template-impressions`),crawlSamples:k(e[`crawl-samples`],`--crawl-samples`),inspectSamples:k(e[`inspect-samples`],`--inspect-samples`),brandTerms:A(e[`brand-terms`]),includeBrand:D(e[`include-brand`]),js:D(e.js)?!0:`auto`,refresh:D(e.refresh),rate:tr(e)})}const Eo=x({meta:{name:`pseo`,description:`Export pSEO audit tables: templates, demand patterns, top queries, sample coverage, crawl samples, and inspection samples.`},args:{...ro,out:io(`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=To(e),n=await H({client:E(e),site:T(e.site)}),r=await c({site:n.site,...t,brandTerms:t.brandTerms??n.client?.brandTerms,progress:Ya(!0)}),i=T(e.out)??oo({report:`pseo`,clientId:n.client?.id,site:n.site});co(i,await so(i,Qe(r)))}}),Do=x({meta:{name:`refresh-priorities`,description:`Export the ranked SEO priority queue, score breakdowns, grouped findings, and diagnosis detail CSVs.`},args:{...ro,out:io(`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":w(`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 H({client:E(e),site:T(e.site),options:{refresh:D(e.refresh)}}),n=await Mt({site:t.site,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),brandTerms:t.client?.brandTerms,includeBrand:D(e[`include-brand`]),googleAnalyticsPropertyId:T(e[`google-analytics-property`])??t.client?.analytics.google?.propertyId,verifyContent:D(e[`verify-content`]),verifyLimit:O(e[`verify-limit`]),refresh:D(e.refresh)}),r=T(e.out)??oo({report:`refresh-priorities`,clientId:t.client?.id,site:t.site});co(r,await so(r,Le(n)))}}),Oo=x({meta:{name:`export`,description:`Export full report data to CSV files`},subCommands:{diagnose:lo,knowledge:So,narrative:wo,monthly:Co,"update-postmortem":x({meta:{name:`update-postmortem`,description:`Export update postmortem attribution, findings, template movement, and segment movers.`},args:{...ro,out:io(`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 H({client:E(e),site:T(e.site),options:{refresh:D(e.refresh)}}),n=await Ze({site:t.site,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),brandTerms:t.client?.brandTerms,includeBrand:D(e[`include-brand`]),knownConfounders:T(e[`known-change`])?[T(e[`known-change`])??``]:void 0,includeChangeLog:!D(e[`ignore-change-log`]),refresh:D(e.refresh)}),r=T(e.out)??oo({report:`update-postmortem`,clientId:t.client?.id,site:t.site});co(r,await so(r,Un(n)))}}),"refresh-priorities":Do,pseo:Eo}}),ko=x({...Zi,meta:{name:`init`,description:"Legacy alias for `seo start`."}});async function Ao(e,t){if(!e){process.stdout.write(t);return}await mn(en(e),{recursive:!0}),await bn(e,t),process.stdout.write(`Wrote ${e}\n`)}const jo={"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.`}},Mo=x({meta:{name:`llms`,description:`Inspect or generate optional llms.txt from saved crawl data`},subCommands:{audit:x({meta:{name:`audit`,description:`Inspect optional llms.txt presence from a saved crawl`},args:jo,run:async({args:e})=>{let t=M(e),n=pe(await Gr(e,{json:t}));if(t){L(n);return}process.stdout.write(`llms.txt audit for ${n.url}\n\n`),R([[`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(`
69
+ `),R([[`Control`,e.control.change.title],[`Adjusted clicks`,e.control.adjusted.clickDelta===null?`n/a`:U(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 ro=x({meta:{name:`tests`,description:`Create and report local SEO tests from Search Console and Google Analytics data`},subCommands:{list:x({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=M(e),n=E(e),r=It({site:(n||T(e.site)?await H({client:n,site:T(e.site),options:{json:t}}):void 0)?.site,limit:O(e.limit)});if(t){L({tests:r});return}z([`ID`,`Date`,`Scope`,`Target`,`Title`],r.map(e=>[e.id,e.changedAt,e.scope,e.target,e.title]))}}),create:x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t}}),r=xt({site:n.site,scope:Xa(e.scope),target:T(e.target)??``,title:T(e.title)??``,description:T(e.description),changedAt:T(e.date)??Ya()});if(t){L(r);return}R([[`ID`,r.id],[`Date`,r.changedAt],[`Project`,n.client?.name??n.site],[`Scope`,r.scope],[`Target`,r.target],[`Title`,r.title]])}}),report:x({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=M(e),n=T(e.id),r=!n||E(e)||T(e.site)?await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}):void 0,i=await Dt({id:n,site:n?void 0:r?.site,scope:n?void 0:Za(e.scope),target:n?void 0:T(e.target),title:T(e.title),changedAt:n?void 0:T(e.date),googleAnalyticsPropertyId:T(e.property)??r?.client?.analytics.google?.propertyId,controlScope:Za(e[`control-scope`]),controlTarget:T(e[`control-target`]),controlTitle:T(e[`control-title`]),beforeDays:k(e.before,`--before`),afterDays:k(e.after,`--after`),refresh:D(e.refresh)});if(t){L(i);return}no(i)}})}});function io(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 ao={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.`}},oo={...X([`includeBrand`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}};function so(e){return{includeBrand:D(e[`include-brand`]),verifyContent:D(e[`verify-content`]),verifyLimit:O(e[`verify-limit`])??3,js:D(e.js)?!0:void 0,rate:lr(e),refresh:D(e.refresh)}}function co(e){return{client:E(e),site:T(e.site),refresh:D(e.refresh)}}const{json:lo,...uo}=oo,fo=uo,po={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 mo(e){return{type:`string`,description:`Output folder. Defaults to ./seo-export/<project>-${e}-YYYY-MM-DD.`}}function ho(e){return e.toLowerCase().replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)}function go(e){let t=new Date().toISOString().slice(0,10),n=ho(e.clientId??e.site);return mn(process.cwd(),`seo-export`,`${n}-${e.report}-${t}`)}async function _o(e,t){await Cn(e,{recursive:!0});let n=[];for(let r of t){let t=mn(e,r.filename);await kn(t,l(r.rows,r.headers),`utf8`),n.push(t)}return n}function vo(e,t){process.stdout.write(`Wrote ${gt(t.length,`CSV file`)} to ${e}\n`);for(let e of t)process.stdout.write(`- ${e}\n`)}const yo=x({meta:{name:`diagnose`,description:`Export diagnosis tables: priorities, anomalies, movement, decay, cannibalisation, striking-distance, and quick wins.`},args:{...po,out:mo(`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 H({client:E(e),site:T(e.site)}),n=await Fe({site:t.site,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),brandTerms:t.client?.brandTerms,includeBrand:D(e[`include-brand`]),verifyContent:D(e[`verify-content`]),verifyLimit:O(e[`verify-limit`]),js:D(e.js)?!0:`auto`,rate:lr(e),refresh:D(e.refresh),progress:io(!0)}),r=T(e.out)??go({report:`diagnose`,clientId:t.client?.id,site:t.site});vo(r,await _o(r,s(n)))}}),bo=`.seo-okf.json`,xo=`${JSON.stringify({generator:`seo`,format:`okf`,version:1})}\n`;function So(e,t){let n=mn(e,t),r=pn(mn(e),n);if(!r||r.startsWith(`..`)||dn(r))throw new _(`INVALID_INPUT`,`Unsafe OKF file path: ${t}`);return n}async function Co(e,t){for(let n of t){let t=So(e,n.path);await Cn(y(t),{recursive:!0}),await kn(t,n.content)}await kn(b(e,bo),xo)}async function wo(e){let t=[];async function n(e,r=``){let i=await En(e,{withFileTypes:!0});for(let a of i){let i=r?`${r}/${a.name}`:a.name,o=b(e,a.name);a.isDirectory()?await n(o,i):a.isFile()&&a.name.endsWith(`.md`)&&t.push({path:i,content:await Tn(o,`utf8`)})}}return await n(e),t.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}async function To(e){try{let t=await Sn(e);if(t.isSymbolicLink()||!t.isDirectory())throw new _(`INVALID_INPUT`,`OKF output must be a real directory: ${e}`);if(!(await En(e)).length)return!0;try{if(await Tn(b(e,bo),`utf8`)===xo)return!0}catch{}throw new _(`INVALID_INPUT`,`Refusing to replace non-empty unmanaged directory: ${e}`)}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async function Eo(e,t){if(!yt(t).valid)throw new _(`INVALID_INPUT`,`Generated bundle did not pass seo OKF checks and was not written.`);let n=mn(e),r=y(n);await Cn(r,{recursive:!0});let i=await To(n),a=await wn(b(r,`.${un(n)}-staging-`)),o=b(r,`.${un(n)}-backup-${gn()}`),s=!1;try{await Co(a,t);let e=yt(await wo(a));if(!e.valid)throw new _(`INTERNAL_ERROR`,`Staged OKF files failed validation after writing.`);return i&&(await Dn(n,o),s=!0),await Dn(a,n),s&&await On(o,{recursive:!0,force:!0}),e}catch(e){throw await On(a,{recursive:!0,force:!0}),s&&(await On(n,{recursive:!0,force:!0}),await Dn(o,n)),e}}async function Do(e,t){if(!e){process.stdout.write(t);return}await Cn(y(e),{recursive:!0}),await kn(e,t),process.stdout.write(`Wrote ${e}\n`)}function Oo(e){let t=T(e)??`okf`;if([`okf`,`markdown`,`json`].includes(t))return t;throw Error(`Format must be one of: okf, markdown, json.`)}function ko(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:Zt(e),entityReadiness:a(e),llmsTxt:ce(e)}}function Ao(e){let t=ko(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 jo=x({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=M(e),n=Oo(e.format),r=n===`okf`?Et(k(e[`max-concepts`],`--max-concepts`)):void 0,i=await ei(e,{json:t}),a=T(e.output);if(n===`okf`){let e=Ye(i,{maxConcepts:r}),o=a??`./okf`,s=await Eo(o,e.files);if(t){L({format:n,output:o,bundle:e,validation:s});return}process.stdout.write(`Wrote OKF bundle to ${o}\n\n`),R([[`Files`,String(e.files.length)],[`Concepts`,String(e.conceptCount)],[`Valid`,s.valid?`yes`:`no`]]);return}if(n===`json`){await Do(a,`${JSON.stringify(ko(i),null,2)}\n`);return}await Do(a,Ao(i))}}),Mo=x({meta:{name:`monthly`,description:`Export monthly report tables plus the underlying diagnosis detail CSVs.`},args:{...po,out:mo(`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.`}}),...fo},run:async({args:e})=>{let t=await H({client:E(e),site:T(e.site),options:{refresh:D(e.refresh)}}),n=await le({site:t.site,month:T(e.month),limit:O(e.limit),brandTerms:t.client?.brandTerms,...so(e),progress:io(!0)}),r=T(e.out)??go({report:`monthly`,clientId:t.client?.id,site:t.site});vo(r,await _o(r,Wt(n)))}}),No=x({meta:{name:`narrative`,description:`Export report narrative tables plus the underlying diagnosis detail CSVs.`},args:{...po,out:mo(`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.`},...fo},run:async({args:e})=>{let t=await H({client:E(e),site:T(e.site),options:{refresh:D(e.refresh)}}),n=await de({site:t.site,days:O(e.days),recentDays:O(e.recent),startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),limit:O(e.limit),changeLimit:O(e[`change-limit`]),brandTerms:t.client?.brandTerms,...so(e),progress:io(!0)}),r=T(e.out)??go({report:`narrative`,clientId:t.client?.id,site:t.site});vo(r,await _o(r,Wt(n)))}});function Po(e){return f({days:k(e.days,`--days`),sitemaps:A(e.sitemap),maxSitemapUrls:k(e[`max-sitemap-urls`],`--max-sitemap-urls`),templateLimit:k(e.limit,`--limit`),minimumTemplateUrls:k(e[`minimum-template-urls`],`--minimum-template-urls`),minimumTemplateShare:k(e[`minimum-template-share`],`--minimum-template-share`),minimumTemplateImpressions:k(e[`minimum-template-impressions`],`--minimum-template-impressions`),crawlSamples:k(e[`crawl-samples`],`--crawl-samples`),inspectSamples:k(e[`inspect-samples`],`--inspect-samples`),brandTerms:A(e[`brand-terms`]),includeBrand:D(e[`include-brand`]),js:D(e.js)?!0:`auto`,refresh:D(e.refresh),rate:ur(e)})}const Fo=x({meta:{name:`pseo`,description:`Export pSEO audit tables: templates, demand patterns, top queries, sample coverage, crawl samples, and inspection samples.`},args:{...po,out:mo(`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=Po(e),n=await H({client:E(e),site:T(e.site)}),r=await ne({site:n.site,...t,brandTerms:t.brandTerms??n.client?.brandTerms,progress:io(!0)}),i=T(e.out)??go({report:`pseo`,clientId:n.client?.id,site:n.site});vo(i,await _o(i,we(r)))}}),Io=x({meta:{name:`refresh-priorities`,description:`Export the ranked SEO priority queue, score breakdowns, grouped findings, and diagnosis detail CSVs.`},args:{...po,out:mo(`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":w(`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 H({client:E(e),site:T(e.site),options:{refresh:D(e.refresh)}}),n=await c({site:t.site,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),brandTerms:t.client?.brandTerms,includeBrand:D(e[`include-brand`]),googleAnalyticsPropertyId:T(e[`google-analytics-property`])??t.client?.analytics.google?.propertyId,verifyContent:D(e[`verify-content`]),verifyLimit:O(e[`verify-limit`]),refresh:D(e.refresh)}),r=T(e.out)??go({report:`refresh-priorities`,clientId:t.client?.id,site:t.site});vo(r,await _o(r,d(n)))}}),Lo=x({meta:{name:`export`,description:`Export full report data to CSV files`},subCommands:{diagnose:yo,knowledge:jo,narrative:No,monthly:Mo,"update-postmortem":x({meta:{name:`update-postmortem`,description:`Export update postmortem attribution, findings, template movement, and segment movers.`},args:{...po,out:mo(`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 H({client:E(e),site:T(e.site),options:{refresh:D(e.refresh)}}),n=await Ce({site:t.site,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),brandTerms:t.client?.brandTerms,includeBrand:D(e[`include-brand`]),knownConfounders:T(e[`known-change`])?[T(e[`known-change`])??``]:void 0,includeChangeLog:!D(e[`ignore-change-log`]),refresh:D(e.refresh)}),r=T(e.out)??go({report:`update-postmortem`,clientId:t.client?.id,site:t.site});vo(r,await _o(r,Qn(n)))}}),"refresh-priorities":Io,pseo:Fo}}),Ro=x({...oa,meta:{name:`init`,description:"Legacy alias for `seo start`."}});async function zo(e,t){if(!e){process.stdout.write(t);return}await Cn(y(e),{recursive:!0}),await kn(e,t),process.stdout.write(`Wrote ${e}\n`)}const Bo={"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.`}},Vo=x({meta:{name:`llms`,description:`Inspect or generate optional llms.txt from saved crawl data`},subCommands:{audit:x({meta:{name:`audit`,description:`Inspect optional llms.txt presence from a saved crawl`},args:Bo,run:async({args:e})=>{let t=M(e),n=ce(await ei(e,{json:t}));if(t){L(n);return}process.stdout.write(`llms.txt audit for ${n.url}\n\n`),R([[`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
71
  Issues
72
- `),z([`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:x({meta:{name:`generate`,description:`Generate an llms.txt draft from a saved crawl`},args:{...jo,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=M(e),n=st(await Gr(e,{json:t}),{maxUrls:O(e[`max-urls`]),tokenBudget:O(e[`token-budget`]),exclude:A(e.exclude),title:T(e.title),description:T(e.description)});if(t){L(n);return}await Ao(T(e.output),n.content),T(e.output)&&R([[`URLs`,String(n.includedUrls)],[`Estimated tokens`,String(n.estimatedTokens)]])}})}}),No=[{client:`claude-desktop`,flag:`claude-desktop`},{client:`claude-code`,flag:`claude-code`},{client:`codex`,flag:`codex`},{client:`cursor`,flag:`cursor`}];function Po(e,t){return D(e.all)?t:No.filter(({flag:t})=>D(e[t])).map(({client:e})=>e)}const Fo=x({meta:{name:`mcp`,description:`MCP server helpers`},subCommands:{serve:x({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-oHPXlHac.js`);await t({test:D(e.test)})}}),install:x({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(D(e.uninstall)&&D(e.reinstall))throw new v(`INVALID_INPUT`,`Use either --uninstall or --reinstall, not both.`);let t=pi(),n=gi({targets:t}),r=M(e),i=Po(e,n.map(e=>e.client));if(i.length===0){if(!I({json:r}))throw new v(`INVALID_INPUT`,`Choose an MCP client with --claude-desktop, --claude-code, --codex, --cursor, or --all.`);let a=n.length>0?n:t;i=B(await On({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 v(`INVALID_INPUT`,`MCP setup is not supported for ${a.join(`, `)} on ${process.platform}.`);let o=t.filter(e=>i.includes(e.client)).map(t=>D(e.uninstall)?Fi(t):Pi(t,{reinstall:D(e.reinstall)}));if(r){L({operation:D(e.uninstall)?`uninstall`:`install`,results:o});return}for(let e of o)process.stdout.write(`${e.changed?`updated`:`skipped`} ${e.client} · ${e.path}\n`)}})}}),Io=x({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 te({startUrl:T(e.url)??``,site:T(e.site),limit:O(e.limit),refresh:D(e.refresh),js:D(e.js)?!0:`auto`});if(M(e)){L(t);return}if(R([[`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(`
72
+ `),z([`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:x({meta:{name:`generate`,description:`Generate an llms.txt draft from a saved crawl`},args:{...Bo,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=M(e),n=be(await ei(e,{json:t}),{maxUrls:O(e[`max-urls`]),tokenBudget:O(e[`token-budget`]),exclude:A(e.exclude),title:T(e.title),description:T(e.description)});if(t){L(n);return}await zo(T(e.output),n.content),T(e.output)&&R([[`URLs`,String(n.includedUrls)],[`Estimated tokens`,String(n.estimatedTokens)]])}})}}),Ho=[{client:`claude-desktop`,flag:`claude-desktop`},{client:`claude-code`,flag:`claude-code`},{client:`codex`,flag:`codex`},{client:`cursor`,flag:`cursor`}];function Uo(e,t){return D(e.all)?t:Ho.filter(({flag:t})=>D(e[t])).map(({client:e})=>e)}const Wo=x({meta:{name:`mcp`,description:`MCP server helpers`},subCommands:{serve:x({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-Xkhuyn70.js`);await t({test:D(e.test)})}}),install:x({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(D(e.uninstall)&&D(e.reinstall))throw new _(`INVALID_INPUT`,`Use either --uninstall or --reinstall, not both.`);let t=Si(),n=Ti({targets:t}),r=M(e),i=Uo(e,n.map(e=>e.client));if(i.length===0){if(!I({json:r}))throw new _(`INVALID_INPUT`,`Choose an MCP client with --claude-desktop, --claude-code, --codex, --cursor, or --all.`);let a=n.length>0?n:t;i=B(await Ln({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 _(`INVALID_INPUT`,`MCP setup is not supported for ${a.join(`, `)} on ${process.platform}.`);let o=t.filter(e=>i.includes(e.client)).map(t=>D(e.uninstall)?Wi(t):Ui(t,{reinstall:D(e.reinstall)}));if(r){L({operation:D(e.uninstall)?`uninstall`:`install`,results:o});return}for(let e of o)process.stdout.write(`${e.changed?`updated`:`skipped`} ${e.client} · ${e.path}\n`)}})}}),Go=x({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 m({startUrl:T(e.url)??``,site:T(e.site),limit:O(e.limit),refresh:D(e.refresh),js:D(e.js)?!0:`auto`});if(M(e)){L(t);return}if(R([[`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
73
  Recommended actions
74
74
  `),z([`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
75
  Changed URLs
76
76
  `),z([`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
77
  Warnings
78
- `);for(let e of t.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}}});function Lo(){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":w(`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 Ro(){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 zo(e){R([[`Workflow`,e.workflow],[`Property`,e.site],[`Summary`,e.summary]]),z([`Tool`,`Status`,`Summary`],e.steps.map(e=>[e.tool,e.status,e.summary])),e.actions.length&&(z([`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 Bo(e){if(zo(e),e.output.crawl?.recommendations.length&&(process.stdout.write(`
78
+ `);for(let e of t.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}}});function Ko(){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":w(`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 qo(){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 Jo(e){R([[`Workflow`,e.workflow],[`Property`,e.site],[`Summary`,e.summary]]),z([`Tool`,`Status`,`Summary`],e.steps.map(e=>[e.tool,e.status,e.summary])),e.actions.length&&(z([`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 Yo(e){if(Jo(e),e.output.crawl?.recommendations.length&&(process.stdout.write(`
79
79
  Crawl actions
80
80
  `),z([`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
81
  Index reviews, changes, and failed checks
82
82
  `),z([`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
83
  Recoverable URLs
84
- `),z([`Severity`,`Issue`,`Clicks`,`Impr`,`URL`,`Action`],e.output.recovery.items.slice(0,10).map(e=>[e.severity,e.issue,U(e.clicks),U(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}, ${U(e.clicks)} clicks at risk`,action:e.recommendation.action}))))}function Vo(e){R([[`Property`,e.site],[`Health`,e.health],[`Attention`,String(e.summary.attention)],[`Stale`,String(e.summary.stale)],[`Not run`,String(e.summary.notRun)]]),z([`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(`
84
+ `),z([`Severity`,`Issue`,`Clicks`,`Impr`,`URL`,`Action`],e.output.recovery.items.slice(0,10).map(e=>[e.severity,e.issue,U(e.clicks),U(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}, ${U(e.clicks)} clicks at risk`,action:e.recommendation.action}))))}function Xo(e){R([[`Property`,e.site],[`Health`,e.health],[`Attention`,String(e.summary.attention)],[`Stale`,String(e.summary.stale)],[`Not run`,String(e.summary.notRun)]]),z([`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
85
  Next actions
86
- `),z([`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=T(t);return n?`--${e} ${JSON.stringify(n)}`:void 0}function Ho(e,t){return D(t)?`--${e}`:void 0}function Uo(e){return D(e)===!1?`--recover-links=false`:void 0}const Wo=x({meta:{name:`monitoring`,description:`Run and review recurring technical SEO monitoring`},subCommands:{run:x({meta:{name:`run`,description:`Run crawl, index, and link recovery monitoring for a property`},args:Lo(),run:async({args:e})=>{let t=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=j(e.urls),i=j(e.sitemaps),a=T(e.url)??n.client?.startUrl??si(n.site),o=await Ie({site:n.site,startUrl:a,urls:r.length?r:n.client?.watchUrls,sitemaps:i.length?i:void 0,properties:j(e.properties).length?j(e.properties):void 0,limit:O(e.limit),languageCode:T(e.language),dailyLimit:O(e[`daily-limit`]),inspectLimit:O(e[`inspect-limit`]),maxUrls:O(e[`max-urls`]),refresh:D(e.refresh),js:D(e.js)?!0:`auto`,recoverLinks:D(e[`recover-links`]),recoverDays:O(e[`recover-days`]),recoverLimit:O(e[`recover-limit`]),recoverMinClicks:O(e[`recover-min-clicks`]),recoverMinImpressions:O(e[`recover-min-impressions`])});if(t){L(o);return}Bo(o)}}),status:x({meta:{name:`status`,description:`Show the latest saved monitoring state for a property`},args:Ro(),run:async({args:e})=>{let t=M(e),n=ot({site:(await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}})).site,staleAfterDays:O(e[`stale-days`])});if(t){L(n);return}Vo(n)}}),cron:x({meta:{name:`cron`,description:`Print a local cron line for recurring monitoring`},args:{...Lo(),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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=O(e.hour)??9,i=O(e.minute)??0,a=O(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`]),Uo(e[`recover-links`]),Ho(`refresh`,e.refresh),Ho(`js`,e.js),`--json`].filter(Boolean).join(` `),s={name:`monitoring`,cron:`${i} ${r} * * ${a}`,command:o};if(t){L({site:n.site,line:s});return}R([[`Property`,n.site],[`Install`,`crontab -e`]]),process.stdout.write(`${s.cron} ${s.command}\n`)}})}}),Go=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=j(e.sitemaps),i=await f({site:n.site,crawlReportId:T(e[`crawl-report-id`]),sitemaps:r.length?r:void 0,days:O(e.days),rowLimit:O(e[`row-limit`]),maxSitemapUrls:O(e[`max-sitemap-urls`]),itemsPerSection:O(e.limit),refresh:D(e.refresh)});if(t){L(i);return}if(R([[`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(`
86
+ `),z([`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=T(t);return n?`--${e} ${JSON.stringify(n)}`:void 0}function Zo(e,t){return D(t)?`--${e}`:void 0}function Qo(e){return D(e)===!1?`--recover-links=false`:void 0}const $o=x({meta:{name:`monitoring`,description:`Run and review recurring technical SEO monitoring`},subCommands:{run:x({meta:{name:`run`,description:`Run crawl, index, and link recovery monitoring for a property`},args:Ko(),run:async({args:e})=>{let t=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=j(e.urls),i=j(e.sitemaps),a=T(e.url)??n.client?.startUrl??gi(n.site),o=await u({site:n.site,startUrl:a,urls:r.length?r:n.client?.watchUrls,sitemaps:i.length?i:void 0,properties:j(e.properties).length?j(e.properties):void 0,limit:O(e.limit),languageCode:T(e.language),dailyLimit:O(e[`daily-limit`]),inspectLimit:O(e[`inspect-limit`]),maxUrls:O(e[`max-urls`]),refresh:D(e.refresh),js:D(e.js)?!0:`auto`,recoverLinks:D(e[`recover-links`]),recoverDays:O(e[`recover-days`]),recoverLimit:O(e[`recover-limit`]),recoverMinClicks:O(e[`recover-min-clicks`]),recoverMinImpressions:O(e[`recover-min-impressions`])});if(t){L(o);return}Yo(o)}}),status:x({meta:{name:`status`,description:`Show the latest saved monitoring state for a property`},args:qo(),run:async({args:e})=>{let t=M(e),n=ye({site:(await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}})).site,staleAfterDays:O(e[`stale-days`])});if(t){L(n);return}Xo(n)}}),cron:x({meta:{name:`cron`,description:`Print a local cron line for recurring monitoring`},args:{...Ko(),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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=O(e.hour)??9,i=O(e.minute)??0,a=O(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`]),Qo(e[`recover-links`]),Zo(`refresh`,e.refresh),Zo(`js`,e.js),`--json`].filter(Boolean).join(` `),s={name:`monitoring`,cron:`${i} ${r} * * ${a}`,command:o};if(t){L({site:n.site,line:s});return}R([[`Property`,n.site],[`Install`,`crontab -e`]]),process.stdout.write(`${s.cron} ${s.command}\n`)}})}}),es=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=j(e.sitemaps),i=await ke({site:n.site,crawlReportId:T(e[`crawl-report-id`]),sitemaps:r.length?r:void 0,days:O(e.days),rowLimit:O(e[`row-limit`]),maxSitemapUrls:O(e[`max-sitemap-urls`]),itemsPerSection:O(e.limit),refresh:D(e.refresh)});if(t){L(i);return}if(R([[`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
87
  Representative URL Inspection candidates
88
88
  `),z([`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
89
  How to read this report
90
- `);for(let e of i.caveats)process.stdout.write(`- ${e}\n`)}}}),Ko=x({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=M(e),n=j(e.urls),r=await V({site:T(e.site),options:{json:t}}),i=j(e.sitemaps);if(D(e.plan)){if(!i.length)throw Error(`Pass at least one sitemap with --sitemaps.`);let n=await me({site:r,sitemaps:i,properties:j(e.properties).length?j(e.properties):void 0,dailyLimit:O(e[`daily-limit`]),targetCycleDays:O(e[`target-days`]),maxUrls:O(e[`max-urls`])});if(t){L(n);return}if(R([[`Project site`,n.site],[`Sitemap URLs`,String(n.summary.urlCount)],[`Properties used`,String(n.summary.properties)],[`Daily capacity`,String(n.summary.dailyCapacity)],[`Estimated cycle`,Je(n.summary.estimatedCycleDays,`day`)],[`Target cycle`,Je(n.summary.targetCycleDays,`day`)],[`Suggested properties`,String(n.summary.suggestedProperties)]]),n.properties.length&&z([`Property`,`URLs`,`Cycle`,`Sample URL`],n.properties.map(e=>[e.property,e.urlCount,Je(e.cycleDays,`day`),e.sampleUrls[0]??`-`])),n.suggestions.length&&(process.stdout.write(`
90
+ `);for(let e of i.caveats)process.stdout.write(`- ${e}\n`)}}}),ts=x({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=M(e),n=j(e.urls),r=await V({site:T(e.site),options:{json:t}}),i=j(e.sitemaps);if(D(e.plan)){if(!i.length)throw Error(`Pass at least one sitemap with --sitemaps.`);let n=await Te({site:r,sitemaps:i,properties:j(e.properties).length?j(e.properties):void 0,dailyLimit:O(e[`daily-limit`]),targetCycleDays:O(e[`target-days`]),maxUrls:O(e[`max-urls`])});if(t){L(n);return}if(R([[`Project site`,n.site],[`Sitemap URLs`,String(n.summary.urlCount)],[`Properties used`,String(n.summary.properties)],[`Daily capacity`,String(n.summary.dailyCapacity)],[`Estimated cycle`,gt(n.summary.estimatedCycleDays,`day`)],[`Target cycle`,gt(n.summary.targetCycleDays,`day`)],[`Suggested properties`,String(n.summary.suggestedProperties)]]),n.properties.length&&z([`Property`,`URLs`,`Cycle`,`Sample URL`],n.properties.map(e=>[e.property,e.urlCount,gt(e.cycleDays,`day`),e.sampleUrls[0]??`-`])),n.suggestions.length&&(process.stdout.write(`
91
91
  Suggested URL-prefix properties
92
- `),z([`Property`,`URLs`,`Current property`,`Cycle`,`Reason`],n.suggestions.map(e=>[e.property,e.urlCount,e.currentProperty,Je(e.estimatedCycleDays,`day`),e.reason]))),n.warnings.length){process.stdout.write(`
92
+ `),z([`Property`,`URLs`,`Current property`,`Cycle`,`Reason`],n.suggestions.map(e=>[e.property,e.urlCount,e.currentProperty,gt(e.estimatedCycleDays,`day`),e.reason]))),n.warnings.length){process.stdout.write(`
93
93
  Warnings
94
- `);for(let e of n.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}return}if(i.length){let n=await ce({site:r,sitemaps:i,properties:j(e.properties).length?j(e.properties):void 0,dailyLimit:O(e[`daily-limit`]),inspectLimit:O(e[`inspect-limit`]),maxUrls:O(e[`max-urls`]),languageCode:T(e.language)});if(t){L(n);return}R([[`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&&z([`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(`
94
+ `);for(let e of n.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}return}if(i.length){let n=await De({site:r,sitemaps:i,properties:j(e.properties).length?j(e.properties):void 0,dailyLimit:O(e[`daily-limit`]),inspectLimit:O(e[`inspect-limit`]),maxUrls:O(e[`max-urls`]),languageCode:T(e.language)});if(t){L(n);return}R([[`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&&z([`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
95
  Index reviews, changes, and failed checks
96
96
  `),z([`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
97
  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 ue({site:r,urls:n,languageCode:T(e.language),dailyLimit:O(e[`daily-limit`])});if(t){L(a);return}R([[`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)]]),z([`Check`,`Change`,`Index state`,`Evidence`,`URL`],a.items.map(e=>[e.inspectionStatus,e.changeKind,e.indexStatus,(e.errorCode??e.issueCodes.join(`, `))||`none`,e.url]))}}),qo=x({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=M(e),r=await n({site:await oi({client:E(e),site:T(e.site)},{json:t}),days:O(e.days),limit:O(e.limit),minClicks:O(e[`min-clicks`]),minImpressions:O(e[`min-impressions`]),refresh:D(e.refresh),js:D(e.js)?!0:`auto`});if(t){L(r);return}if(R([[`Site`,r.site],[`Range`,`${r.range.startDate} to ${r.range.endDate}`],[`Checked`,U(r.summary.checked)],[`Recoverable`,U(r.summary.recoverable)],[`High severity`,U(r.summary.high)],[`Clicks at risk`,U(r.summary.clicksAtRisk)],[`Impressions at risk`,U(r.summary.impressionsAtRisk)]]),r.items.length&&(q([`Severity`,`Issue`,`Clicks`,`Impr`,`URL`,`Action`],r.items.map(e=>[e.severity,e.issue,U(e.clicks),U(e.impressions),K(e.url,56),K(e.recommendation.action,72)])),J(`Top recovery actions`,r.items.map(e=>({label:K(e.url,96),context:`${e.severity}, ${U(e.clicks)} clicks at risk`,action:e.recommendation.action})))),r.warnings.length){process.stdout.write(`
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 h({site:r,urls:n,languageCode:T(e.language),dailyLimit:O(e[`daily-limit`])});if(t){L(a);return}R([[`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)]]),z([`Check`,`Change`,`Index state`,`Evidence`,`URL`],a.items.map(e=>[e.inspectionStatus,e.changeKind,e.indexStatus,(e.errorCode??e.issueCodes.join(`, `))||`none`,e.url]))}}),ns=x({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=M(e),n=await Xt({site:await hi({client:E(e),site:T(e.site)},{json:t}),days:O(e.days),limit:O(e.limit),minClicks:O(e[`min-clicks`]),minImpressions:O(e[`min-impressions`]),refresh:D(e.refresh),js:D(e.js)?!0:`auto`});if(t){L(n);return}if(R([[`Site`,n.site],[`Range`,`${n.range.startDate} to ${n.range.endDate}`],[`Checked`,U(n.summary.checked)],[`Recoverable`,U(n.summary.recoverable)],[`High severity`,U(n.summary.high)],[`Clicks at risk`,U(n.summary.clicksAtRisk)],[`Impressions at risk`,U(n.summary.impressionsAtRisk)]]),n.items.length&&(q([`Severity`,`Issue`,`Clicks`,`Impr`,`URL`,`Action`],n.items.map(e=>[e.severity,e.issue,U(e.clicks),U(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}, ${U(e.clicks)} clicks at risk`,action:e.recommendation.action})))),n.warnings.length){process.stdout.write(`
99
99
  Warnings
100
- `);for(let e of r.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}}}),Jo=x({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 it({url:T(e.url)??``,maxHops:O(e[`max-hops`]),refresh:D(e.refresh),js:D(e.js)?!0:`auto`});if(M(e)){L(t);return}if(R([[`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`]]),z([`#`,`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(`
100
+ `);for(let e of n.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}}}),rs=x({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 i({url:T(e.url)??``,maxHops:O(e[`max-hops`]),refresh:D(e.refresh),js:D(e.js)?!0:`auto`});if(M(e)){L(t);return}if(R([[`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`]]),z([`#`,`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
101
  Final page
102
102
  `),R([[`Title`,t.finalPage.title??`-`],[`Canonical`,t.finalPage.canonical??`-`],[`Meta robots`,t.finalPage.metaRobots??`-`]])),t.warnings.length){process.stdout.write(`
103
103
  Warnings
104
- `);for(let e of t.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}}});function Yo(e,t){process.stdout.write(`OKF validation for ${e}\n\n`),R([[`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(`
104
+ `);for(let e of t.warnings.slice(0,10))process.stdout.write(`- ${e}\n`)}}});function is(e,t){process.stdout.write(`OKF validation for ${e}\n\n`),R([[`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
105
  Issues
106
- `),z([`Severity`,`Path`,`Message`],t.issues.slice(0,25).map(e=>[e.severity,e.path,e.message])))}const Xo=x({meta:{name:`okf`,description:`Export, validate, and explain OKF site knowledge bundles`},subCommands:{export:x({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=M(e),n=rt(k(e[`max-concepts`],`--max-concepts`)),r=mt(await Gr(e,{json:t}),{maxConcepts:n,title:T(e.title)}),i=T(e.output)??`./okf`,a=await _o(i,r.files);if(t){L({output:i,bundle:r,validation:a});return}process.stdout.write(`Wrote OKF bundle to ${i}\n\n`),R([[`Files`,String(r.files.length)],[`Concepts`,String(r.conceptCount)],[`Valid`,a.valid?`yes`:`no`]])}}),validate:x({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=T(e.path);if(!t)throw Error(`Pass an OKF bundle directory.`);let n=Be(await ho(t));if(n.valid||(process.exitCode=1),M(e)){L(n);return}Yo(t,n)}}),explain:x({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=T(e.path);if(!t)throw Error(`Pass an OKF bundle directory.`);let n=Ct(Be(await ho(t)));if(n.valid||(process.exitCode=1),M(e)){L(n);return}if(process.stdout.write(`${n.summary}\n\n`),R([[`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(`
106
+ `),z([`Severity`,`Path`,`Message`],t.issues.slice(0,25).map(e=>[e.severity,e.path,e.message])))}const as=x({meta:{name:`okf`,description:`Export, validate, and explain OKF site knowledge bundles`},subCommands:{export:x({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=M(e),n=Et(k(e[`max-concepts`],`--max-concepts`)),r=Ye(await ei(e,{json:t}),{maxConcepts:n,title:T(e.title)}),i=T(e.output)??`./okf`,a=await Eo(i,r.files);if(t){L({output:i,bundle:r,validation:a});return}process.stdout.write(`Wrote OKF bundle to ${i}\n\n`),R([[`Files`,String(r.files.length)],[`Concepts`,String(r.conceptCount)],[`Valid`,a.valid?`yes`:`no`]])}}),validate:x({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=T(e.path);if(!t)throw Error(`Pass an OKF bundle directory.`);let n=yt(await wo(t));if(n.valid||(process.exitCode=1),M(e)){L(n);return}is(t,n)}}),explain:x({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=T(e.path);if(!t)throw Error(`Pass an OKF bundle directory.`);let n=et(yt(await wo(t)));if(n.valid||(process.exitCode=1),M(e)){L(n);return}if(process.stdout.write(`${n.summary}\n\n`),R([[`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
107
  Next actions
108
- `);for(let e of n.nextActions)process.stdout.write(`- ${e}\n`)}}})}}),Zo=x({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=M(e),n=await Vr({client:E(e),options:{json:t}}),r=await ee({property:await Hr({property:T(e.property)??n?.analytics.google?.propertyId,options:{json:t}}),startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),maxRows:k(e[`max-rows`],`--max-rows`),resultLimit:k(e[`result-limit`],`--result-limit`),limit:k(e.limit,`--limit`),refresh:e.refresh===!0});if(t){L(r);return}if(R([[`Property`,r.property],[`Evidence`,r.dataStatus===`complete`?`Complete`:`Partial`],[`Verdict`,r.summary.verdict],[`AI sessions`,U(r.summary.sessions)],[`AI users`,r.summary.totalUsers===null?`Unavailable`:U(r.summary.totalUsers)],[`Sources`,U(r.summary.sources)],[`Landing pages`,U(r.summary.landingPages)],[`Landing-page output`,`${U(r.selection.landingPages.returnedRows)} returned / ${U(r.selection.landingPages.retainedRows)} retained`],[`Source rows`,U(r.dataSource.sourceDiscovery.returnedRows)]]),r.sources.length&&(process.stdout.write(`
108
+ `);for(let e of n.nextActions)process.stdout.write(`- ${e}\n`)}}})}}),os=x({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=M(e),n=await Xr({client:E(e),options:{json:t}}),r=await Ie({property:await Zr({property:T(e.property)??n?.analytics.google?.propertyId,options:{json:t}}),startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),maxRows:k(e[`max-rows`],`--max-rows`),resultLimit:k(e[`result-limit`],`--result-limit`),limit:k(e.limit,`--limit`),refresh:e.refresh===!0});if(t){L(r);return}if(R([[`Property`,r.property],[`Evidence`,r.dataStatus===`complete`?`Complete`:`Partial`],[`Verdict`,r.summary.verdict],[`AI sessions`,U(r.summary.sessions)],[`AI users`,r.summary.totalUsers===null?`Unavailable`:U(r.summary.totalUsers)],[`Sources`,U(r.summary.sources)],[`Landing pages`,U(r.summary.landingPages)],[`Landing-page output`,`${U(r.selection.landingPages.returnedRows)} returned / ${U(r.selection.landingPages.retainedRows)} retained`],[`Source rows`,U(r.dataSource.sourceDiscovery.returnedRows)]]),r.sources.length&&(process.stdout.write(`
109
109
  AI sources
110
110
  `),q([`Source`,`Sessions`,`Events`,`Share of AI sessions`],r.sources.map(e=>[e.label,U(e.sessions),U(e.eventCount),G(e.shareOfAiSessions)]))),r.landingPages.length&&(process.stdout.write(`
111
111
  Landing pages
112
112
  `),q([`Landing page`,`Sessions`,`Events`,`Top source`],r.landingPages.map(e=>[K(e.landingPage,64),U(e.sessions),U(e.eventCount),e.topSourceDetails.label]))),r.dataSource.partialReasons.length){process.stdout.write(`
113
113
  Evidence warnings
114
- `);for(let e of r.dataSource.partialReasons)process.stdout.write(`- ${e}\n`)}process.stdout.write(`\nNote: ${r.summary.caveat}\n`)}}),Qo=x({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=M(e),n=D(e.refresh),r=await H({client:E(e),site:T(e.site),options:{json:t,refresh:n}}),i=await ge({site:r.site,days:k(e.days,`--days`),limit:k(e.limit,`--limit`),minImpressions:k(e[`min-impressions`],`--min-impressions`),brandTerms:[...r.client?.brandTerms??[],...A(e[`brand-terms`])??[]],includeBrand:D(e[`include-brand`]),refresh:n});if(t){L(i);return}R([[`Site`,i.site],[`Status`,i.dataStatus],[`Range`,`${i.range.startDate} to ${i.range.endDate}`],[`Eligible candidates`,U(i.summary.eligibleClusters)],[`Returned candidates`,U(i.summary.returnedClusters)],[`Suppressed brand queries`,U(i.summary.suppressedQueries)],[`GSC completeness`,i.source.completeness],[`Brand queries`,D(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`:U(e.propertyImpressions),U(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])}}),$o=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await p({site:n.site,days:k(e.days,`--days`),startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),limit:k(e.limit,`--limit`),minImpressions:k(e[`min-impressions`],`--min-impressions`),maxRows:k(e[`max-rows`],`--max-rows`),brandTerms:[...n.client?.brandTerms??[],...A(e[`brand-terms`])??[]],includeBrand:D(e[`include-brand`]),refresh:D(e.refresh)});if(t){L(r);return}R([[`Property`,r.site],[`Status`,r.dataStatus],[`Verdict`,r.summary.verdict],[`Classified queries`,U(r.summary.classifiedQueries)],[`Returned queries`,U(r.summary.returnedQueries)],[`Returned impressions`,U(r.summary.returnedImpressions)],[`Returned clicks`,U(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),U(e.impressions),U(e.clicks),e.confidence,K(e.action,76)])),J(`Top community-intent actions`,r.items.map(e=>({label:e.query,context:`${e.intent}, ${U(e.impressions)} impressions`,action:e.action}))),Y(`Report caveats`,r.caveats),Y(`Warnings`,r.warnings)}}),es=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t}}),r=await Ot({site:n.site,minImpressions:O(e[`min-impressions`]),brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`])});if(t){L(r);return}R([[`Site`,r.site],[`Underperformers`,U(r.summary.underperformers)],[`Estimated click gap`,U(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),W(e.position),U(e.impressions),G(e.actualCtr),G(e.expectedCtr),U(e.clickShortfall),K(e.recommendation.action,72)])),J(`Top CTR actions`,r.items.map(e=>({label:e.query,context:`${U(e.clickShortfall)} click gap, ${G(e.actualCtr)} CTR`,action:e.recommendation.action})))}});function ts(e){return e>0?W(e):`n/a`}const ns=x({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=M(e),n=D(e.refresh),r=T(e.comparison),i=k(e.days,`--days`),a=k(e.limit,`--limit`),o=k(e[`min-drop-pct`],`--min-drop-pct`),s=k(e[`min-previous-clicks`],`--min-previous-clicks`),c=k(e[`min-click-loss`],`--min-click-loss`);if(r!==void 0&&r!==`previous-period`&&r!==`year-over-year`)throw new v(`INVALID_INPUT`,`--comparison must be previous-period or year-over-year.`);let l=await H({client:E(e),site:T(e.site),options:{json:t,refresh:n}}),u=await Pe({site:l.site,days:i,limit:a,comparison:r,brandTerms:[...l.client?.brandTerms??[],...A(e[`brand-terms`])??[]],includeBrand:D(e[`include-brand`]),minDropPct:o,minPreviousClicks:s,minClickLoss:c,refresh:n});if(t){L(u);return}R([[`Site`,u.site],[`Status`,u.dataStatus],[`Comparison`,u.comparison],[`Observed query/page declines`,U(u.summary.returnedRows)],[`Eligible declines`,U(u.summary.eligibleRows)],[`Decay clusters`,U(u.summary.groups)],[`Eligible observed click decline`,U(u.summary.observedRetainedQueryClickLoss)],[`Returned observed click decline`,U(u.summary.returnedObservedRetainedQueryClickLoss)],[`Brand queries`,u.summary.brandFiltering],[`Min drop`,`${u.filters.minDropPct}%`],[`Min previous clicks`,U(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),U(e.count),U(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:`${U(e.count)} retained rows, ${U(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(`, `),U(e.clickLoss),`${U(e.previous.clicks)} -> ${U(e.current.clicks)}`,`${U(e.previous.impressions)} -> ${U(e.current.impressions)}`,`${G(e.previous.ctr)} -> ${G(e.current.ctr)}`,`${ts(e.previous.position)} -> ${ts(e.current.position)}`,K(e.recommendation.action,64)])),J(`Top decay actions`,u.items.map(e=>({label:e.query,context:`${e.template.label}, ${U(e.clickLoss)} fewer observed clicks`,action:e.recommendation.action}))))}}),rs=x({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=M(e),n=D(e.refresh),r=k(e.days,`--days`),i=k(e.limit,`--limit`),a=k(e[`check-limit`],`--check-limit`),o=k(e[`min-impressions`],`--min-impressions`),s=tr(e),c=await H({client:E(e),site:T(e.site),options:{json:t,refresh:n}}),l=await oe({site:c.site,targetUrl:T(e.url)??``,days:r,limit:i,checkLimit:a,minImpressions:o,brandTerms:[...c.client?.brandTerms??[],...A(e[`brand-terms`])??[]],includeBrand:D(e[`include-brand`]),js:D(e.js)?!0:void 0,rate:s,refresh:n});if(t){L(l);return}R([[`Site`,l.site],[`Target`,l.targetUrl],[`Preferred target`,l.target.preferredUrl],[`Target state`,l.target.verification],[`Target queries`,U(l.summary.targetQueries)],[`Matched sources`,U(l.summary.candidateSources)],[`Attempted sources`,U(l.summary.attemptedSources)],[`Checked sources`,U(l.summary.checkedSources)],[`Review candidates`,U(l.summary.returnedSources)],[`Existing contextual links`,U(l.summary.existingLinksObserved)],[`Technical exclusions`,U(l.summary.technicalExclusions)],[`Failed checks`,U(l.summary.failedChecks)],[`Unchecked sources`,U(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),U(e.matchedQueryImpressions),e.bestMatchKind,e.linkEvidence.status,e.actionType])),J(`Top internal-link reviews`,l.items.map(e=>({label:K(e.sourceUrl,96),context:`${U(e.matchedQueryImpressions)} matched-query impressions; ${e.bestMatchKind}`,action:e.recommendation.action}))),Y(`Provider usage`,[l.ledgerSummary]))}}),is=x({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":w(`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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await he({site:n.site,url:T(e.url)??``,days:O(e.days),limit:O(e.limit),minImpressions:O(e[`min-impressions`]),brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`]),verifyContent:D(e[`verify-content`])!==!1,js:D(e.js)?!0:`auto`,refresh:D(e.refresh)});if(t){L(r);return}if(R([[`Property`,r.site],[`URL`,r.url],[`Title`,r.page?.title??`not fetched`],[`Fetch`,ui(r.page?.fetchDiagnostics)],[`Verification`,r.verification.status],[`Rows`,`${U(r.selection.returnedRows)} returned / ${U(r.selection.eligibleRows)} eligible / ${U(r.selection.sourceRows)} source`],[`Queries`,U(r.summary.queries)],[`Impressions`,U(r.summary.impressions)],[`Opportunities`,U(r.summary.opportunities)],[`CTR shortfall`,U(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.
114
+ `);for(let e of r.dataSource.partialReasons)process.stdout.write(`- ${e}\n`)}process.stdout.write(`\nNote: ${r.summary.caveat}\n`)}}),ss=x({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=M(e),n=D(e.refresh),r=await H({client:E(e),site:T(e.site),options:{json:t,refresh:n}}),i=await Nt({site:r.site,days:k(e.days,`--days`),limit:k(e.limit,`--limit`),minImpressions:k(e[`min-impressions`],`--min-impressions`),brandTerms:[...r.client?.brandTerms??[],...A(e[`brand-terms`])??[]],includeBrand:D(e[`include-brand`]),refresh:n});if(t){L(i);return}R([[`Site`,i.site],[`Status`,i.dataStatus],[`Range`,`${i.range.startDate} to ${i.range.endDate}`],[`Eligible candidates`,U(i.summary.eligibleClusters)],[`Returned candidates`,U(i.summary.returnedClusters)],[`Suppressed brand queries`,U(i.summary.suppressedQueries)],[`GSC completeness`,i.source.completeness],[`Brand queries`,D(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`:U(e.propertyImpressions),U(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])}}),cs=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await Ae({site:n.site,days:k(e.days,`--days`),startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),limit:k(e.limit,`--limit`),minImpressions:k(e[`min-impressions`],`--min-impressions`),maxRows:k(e[`max-rows`],`--max-rows`),brandTerms:[...n.client?.brandTerms??[],...A(e[`brand-terms`])??[]],includeBrand:D(e[`include-brand`]),refresh:D(e.refresh)});if(t){L(r);return}R([[`Property`,r.site],[`Status`,r.dataStatus],[`Verdict`,r.summary.verdict],[`Classified queries`,U(r.summary.classifiedQueries)],[`Returned queries`,U(r.summary.returnedQueries)],[`Returned impressions`,U(r.summary.returnedImpressions)],[`Returned clicks`,U(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),U(e.impressions),U(e.clicks),e.confidence,K(e.action,76)])),J(`Top community-intent actions`,r.items.map(e=>({label:e.query,context:`${e.intent}, ${U(e.impressions)} impressions`,action:e.action}))),Y(`Report caveats`,r.caveats),Y(`Warnings`,r.warnings)}}),ls=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t}}),r=await zt({site:n.site,minImpressions:O(e[`min-impressions`]),brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`])});if(t){L(r);return}R([[`Site`,r.site],[`Underperformers`,U(r.summary.underperformers)],[`Estimated click gap`,U(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),W(e.position),U(e.impressions),G(e.actualCtr),G(e.expectedCtr),U(e.clickShortfall),K(e.recommendation.action,72)])),J(`Top CTR actions`,r.items.map(e=>({label:e.query,context:`${U(e.clickShortfall)} click gap, ${G(e.actualCtr)} CTR`,action:e.recommendation.action})))}});function us(e){return e>0?W(e):`n/a`}const ds=x({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=M(e),n=D(e.refresh),r=T(e.comparison),i=k(e.days,`--days`),a=k(e.limit,`--limit`),o=k(e[`min-drop-pct`],`--min-drop-pct`),s=k(e[`min-previous-clicks`],`--min-previous-clicks`),c=k(e[`min-click-loss`],`--min-click-loss`);if(r!==void 0&&r!==`previous-period`&&r!==`year-over-year`)throw new _(`INVALID_INPUT`,`--comparison must be previous-period or year-over-year.`);let l=await H({client:E(e),site:T(e.site),options:{json:t,refresh:n}}),u=await Ct({site:l.site,days:i,limit:a,comparison:r,brandTerms:[...l.client?.brandTerms??[],...A(e[`brand-terms`])??[]],includeBrand:D(e[`include-brand`]),minDropPct:o,minPreviousClicks:s,minClickLoss:c,refresh:n});if(t){L(u);return}R([[`Site`,u.site],[`Status`,u.dataStatus],[`Comparison`,u.comparison],[`Observed query/page declines`,U(u.summary.returnedRows)],[`Eligible declines`,U(u.summary.eligibleRows)],[`Decay clusters`,U(u.summary.groups)],[`Eligible observed click decline`,U(u.summary.observedRetainedQueryClickLoss)],[`Returned observed click decline`,U(u.summary.returnedObservedRetainedQueryClickLoss)],[`Brand queries`,u.summary.brandFiltering],[`Min drop`,`${u.filters.minDropPct}%`],[`Min previous clicks`,U(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),U(e.count),U(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:`${U(e.count)} retained rows, ${U(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(`, `),U(e.clickLoss),`${U(e.previous.clicks)} -> ${U(e.current.clicks)}`,`${U(e.previous.impressions)} -> ${U(e.current.impressions)}`,`${G(e.previous.ctr)} -> ${G(e.current.ctr)}`,`${us(e.previous.position)} -> ${us(e.current.position)}`,K(e.recommendation.action,64)])),J(`Top decay actions`,u.items.map(e=>({label:e.query,context:`${e.template.label}, ${U(e.clickLoss)} fewer observed clicks`,action:e.recommendation.action}))))}}),fs=x({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=M(e),n=D(e.refresh),r=k(e.days,`--days`),i=k(e.limit,`--limit`),a=k(e[`check-limit`],`--check-limit`),o=k(e[`min-impressions`],`--min-impressions`),s=ur(e),c=await H({client:E(e),site:T(e.site),options:{json:t,refresh:n}}),l=await g({site:c.site,targetUrl:T(e.url)??``,days:r,limit:i,checkLimit:a,minImpressions:o,brandTerms:[...c.client?.brandTerms??[],...A(e[`brand-terms`])??[]],includeBrand:D(e[`include-brand`]),js:D(e.js)?!0:void 0,rate:s,refresh:n});if(t){L(l);return}R([[`Site`,l.site],[`Target`,l.targetUrl],[`Preferred target`,l.target.preferredUrl],[`Target state`,l.target.verification],[`Target queries`,U(l.summary.targetQueries)],[`Matched sources`,U(l.summary.candidateSources)],[`Attempted sources`,U(l.summary.attemptedSources)],[`Checked sources`,U(l.summary.checkedSources)],[`Review candidates`,U(l.summary.returnedSources)],[`Existing contextual links`,U(l.summary.existingLinksObserved)],[`Technical exclusions`,U(l.summary.technicalExclusions)],[`Failed checks`,U(l.summary.failedChecks)],[`Unchecked sources`,U(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),U(e.matchedQueryImpressions),e.bestMatchKind,e.linkEvidence.status,e.actionType])),J(`Top internal-link reviews`,l.items.map(e=>({label:K(e.sourceUrl,96),context:`${U(e.matchedQueryImpressions)} matched-query impressions; ${e.bestMatchKind}`,action:e.recommendation.action}))),Y(`Provider usage`,[l.ledgerSummary]))}}),ps=x({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":w(`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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await Ee({site:n.site,url:T(e.url)??``,days:O(e.days),limit:O(e.limit),minImpressions:O(e[`min-impressions`]),brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`]),verifyContent:D(e[`verify-content`])!==!1,js:D(e.js)?!0:`auto`,refresh:D(e.refresh)});if(t){L(r);return}if(R([[`Property`,r.site],[`URL`,r.url],[`Title`,r.page?.title??`not fetched`],[`Fetch`,yi(r.page?.fetchDiagnostics)],[`Verification`,r.verification.status],[`Rows`,`${U(r.selection.returnedRows)} returned / ${U(r.selection.eligibleRows)} eligible / ${U(r.selection.sourceRows)} source`],[`Queries`,U(r.summary.queries)],[`Impressions`,U(r.summary.impressions)],[`Opportunities`,U(r.summary.opportunities)],[`CTR shortfall`,U(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
115
  `:`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),U(e.impressions),e.estimatedCtrClickShortfall===void 0?`n/a`:U(e.estimatedCtrClickShortfall),K(e.recommendation,72)])),J(`Top page actions`,r.items.map(e=>({label:e.query,context:`${e.opportunityType}, ${U(e.impressions)} impressions`,action:e.recommendation})))}}),as=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t}}),r=await Se({site:n.site,scope:T(e.scope),brand:n.client?.brandTerms?.[0],brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`]),minImpressions:O(e[`min-impressions`]),limit:O(e.limit)});if(t){L(r);return}R([[`Site`,r.site],[`Scope`,r.scope??`all pages`],[`Clusters`,U(r.summary.clusters)],[`Queries`,U(r.summary.queries)],[`Impressions`,U(r.summary.impressions)],[`Clicks`,U(r.summary.clicks)],[`Minimum impressions`,U(r.summary.minImpressions)],[`Result limit`,U(r.summary.limit)],[`Brand queries`,r.summary.brandFiltering],[`High-opportunity clusters`,U(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,U(e.totals?.impressions??0),G(e.totals?.ctr??0),G(e.benchmark?.expectedCtr??0),e.estimatedClickLift===void 0?`-`:U(e.estimatedClickLift),K(e.recommendation??``,72)])),J(`Top cluster actions`,r.clusters.map(e=>({label:e.label,context:`${U(e.totals?.impressions??0)} impressions, ${e.estimatedClickLift===void 0?`ranking opportunity`:`${U(e.estimatedClickLift)} estimated click lift`}`,action:e.recommendation??``})))}}),os=x({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=M(e),n=O(e[`verify-limit`]),r=D(e[`verify-content`])===!0||n!==void 0,i=await H({client:E(e),site:T(e.site),options:{json:t}}),a=await Ae({site:i.site,days:O(e.days),limit:O(e.limit),minImpressions:O(e[`min-impressions`]),brandTerms:[...i.client?.brandTerms??[],...A(e[`brand-terms`])??[]],includeBrand:D(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:D(e.js)?!0:void 0,rate:er(e),refresh:D(e.refresh)});if(t){L(a);return}R([[`Site`,a.site],[`Eligible rows`,U(a.summary.eligibleRows)],[`Returned rows`,U(a.summary.returnedRows)],[`Repeated-query clusters`,U(a.summary.repeatedQueryGroups)],[`Template patterns`,U(a.summary.templatePatterns)],[`CTR click shortfall`,U(a.summary.returnedEstimatedCtrClickShortfall)],[`Brand queries`,a.summary.brandFiltering],[`Verification`,Ur(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),U(e.urlCount),U(e.rowCount),U(e.totalEstimatedCtrClickShortfall),U(e.totalImpressions),K(e.action,72)])),J(`Top template actions`,a.templateRecommendations.map(e=>({label:e.templateLabel,context:`${U(e.urlCount)} URLs, ${U(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),U(e.urlCount),U(e.rowCount),U(e.totalEstimatedCtrClickShortfall),U(e.totalImpressions),K(e.sampleUrls[0]??`-`,46),K(e.recommendation,72)])),J(`Top cluster actions`,a.groups.map(e=>({label:e.label,context:`${U(e.urlCount)} URLs, ${U(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),W(e.position),U(e.impressions),`${G(e.ctr)} / ${G(e.targetCtr)}`,U(e.estimatedCtrClickShortfall),ui(e.contentVerification?.fetchDiagnostics),di(e.contentVerification?.classification),K(e.recommendation.action,64)])),J(`Top opportunity actions`,a.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${W(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action}))))}}),ss=x({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=M(e),n=O(e[`verify-limit`]),r=D(e[`verify-content`])===!0||n!==void 0,i=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),a=await be({site:i.site,range:O(e.days),minImpressions:O(e[`min-impressions`]),limit:T(e.limit)?Number(T(e.limit)):10,brandTerms:i.client?.brandTerms,includeBrand:D(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:D(e.js)?!0:void 0,rate:er(e),refresh:D(e.refresh)});if(t){L(a);return}if(R([[`Site`,a.site],[`Eligible pages`,U(a.summary.eligiblePages)],[`Returned pages`,U(a.summary.returnedPages)],[`Eligible queries`,U(a.summary.eligibleQueries)],[`Eligible impressions`,U(a.summary.eligibleImpressions)],[`Content issues`,U(a.summary.contentIssues)],[`Technical issues`,U(a.summary.technicalIssues)],[`Fetch failures`,U(a.summary.fetchFailures)],[`Brand queries`,a.summary.brandFiltering],[`Verification`,Ur(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),U(e.queryCount),ui(e.fetchDiagnostics),di(e.contentVerification?.classification),e.recommendation.action])),J(`Top second-page actions`,a.items.map(e=>({label:e.primaryQuery,context:`${e.template.label}, pos ${W(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action}))),process.stdout.write(`${a.ledgerSummary}\n`)}}),cs=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await It({site:n.site,days:k(e.days,`--days`),startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),limit:k(e.limit,`--limit`),minImpressions:k(e[`min-impressions`],`--min-impressions`),maxRows:k(e[`max-rows`],`--max-rows`),brandTerms:[...n.client?.brandTerms??[],...A(e[`brand-terms`])??[]],includeBrand:D(e[`include-brand`]),refresh:D(e.refresh)});if(t){L(r);return}R([[`Property`,r.site],[`Status`,r.dataStatus],[`Verdict`,r.summary.verdict],[`Eligible queries`,U(r.summary.eligibleQueries)],[`Returned queries`,U(r.summary.returnedQueries)],[`Prompts`,U(r.summary.prompts)],[`GSC completeness`,r.source.completeness]]),q([`Query`,`Impr`,`Prompt`],r.items.flatMap(e=>e.prompts.map(t=>[K(e.query,42),U(e.impressions),K(t,86)]))),Y(`Report caveats`,r.caveats),Y(`Warnings`,r.warnings)}}),ls=x({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=E(e),n=T(e.site),r=t?await Vr({project:t,options:{json:M(e)}}):void 0,i=t||n?void 0:await Vr({options:{json:M(e)}}),a=await ye({url:T(e.url)??``,site:r?.siteUrl??n??i?.siteUrl,js:D(e.js)?!0:`auto`,refresh:D(e.refresh)});if(M(e)){L(a);return}R([[`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`,ui(a.fetchDiagnostics)]]),a.issues.length&&(process.stdout.write(`
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),U(e.impressions),e.estimatedCtrClickShortfall===void 0?`n/a`:U(e.estimatedCtrClickShortfall),K(e.recommendation,72)])),J(`Top page actions`,r.items.map(e=>({label:e.query,context:`${e.opportunityType}, ${U(e.impressions)} impressions`,action:e.recommendation})))}}),ms=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t}}),r=await he({site:n.site,scope:T(e.scope),brand:n.client?.brandTerms?.[0],brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`]),minImpressions:O(e[`min-impressions`]),limit:O(e.limit)});if(t){L(r);return}R([[`Site`,r.site],[`Scope`,r.scope??`all pages`],[`Clusters`,U(r.summary.clusters)],[`Queries`,U(r.summary.queries)],[`Impressions`,U(r.summary.impressions)],[`Clicks`,U(r.summary.clicks)],[`Minimum impressions`,U(r.summary.minImpressions)],[`Result limit`,U(r.summary.limit)],[`Brand queries`,r.summary.brandFiltering],[`High-opportunity clusters`,U(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,U(e.totals?.impressions??0),G(e.totals?.ctr??0),G(e.benchmark?.expectedCtr??0),e.estimatedClickLift===void 0?`-`:U(e.estimatedClickLift),K(e.recommendation??``,72)])),J(`Top cluster actions`,r.clusters.map(e=>({label:e.label,context:`${U(e.totals?.impressions??0)} impressions, ${e.estimatedClickLift===void 0?`ranking opportunity`:`${U(e.estimatedClickLift)} estimated click lift`}`,action:e.recommendation??``})))}}),hs=x({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=M(e),n=O(e[`verify-limit`]),r=D(e[`verify-content`])===!0||n!==void 0,i=await H({client:E(e),site:T(e.site),options:{json:t}}),a=await Ve({site:i.site,days:O(e.days),limit:O(e.limit),minImpressions:O(e[`min-impressions`]),brandTerms:[...i.client?.brandTerms??[],...A(e[`brand-terms`])??[]],includeBrand:D(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:D(e.js)?!0:void 0,rate:lr(e),refresh:D(e.refresh)});if(t){L(a);return}R([[`Site`,a.site],[`Eligible rows`,U(a.summary.eligibleRows)],[`Returned rows`,U(a.summary.returnedRows)],[`Repeated-query clusters`,U(a.summary.repeatedQueryGroups)],[`Template patterns`,U(a.summary.templatePatterns)],[`CTR click shortfall`,U(a.summary.returnedEstimatedCtrClickShortfall)],[`Brand queries`,a.summary.brandFiltering],[`Verification`,Qr(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),U(e.urlCount),U(e.rowCount),U(e.totalEstimatedCtrClickShortfall),U(e.totalImpressions),K(e.action,72)])),J(`Top template actions`,a.templateRecommendations.map(e=>({label:e.templateLabel,context:`${U(e.urlCount)} URLs, ${U(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),U(e.urlCount),U(e.rowCount),U(e.totalEstimatedCtrClickShortfall),U(e.totalImpressions),K(e.sampleUrls[0]??`-`,46),K(e.recommendation,72)])),J(`Top cluster actions`,a.groups.map(e=>({label:e.label,context:`${U(e.urlCount)} URLs, ${U(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),W(e.position),U(e.impressions),`${G(e.ctr)} / ${G(e.targetCtr)}`,U(e.estimatedCtrClickShortfall),yi(e.contentVerification?.fetchDiagnostics),bi(e.contentVerification?.classification),K(e.recommendation.action,64)])),J(`Top opportunity actions`,a.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${W(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action}))))}}),gs=x({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=M(e),n=O(e[`verify-limit`]),r=D(e[`verify-content`])===!0||n!==void 0,i=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),a=await ut({site:i.site,range:O(e.days),minImpressions:O(e[`min-impressions`]),limit:T(e.limit)?Number(T(e.limit)):10,brandTerms:i.client?.brandTerms,includeBrand:D(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:D(e.js)?!0:void 0,rate:lr(e),refresh:D(e.refresh)});if(t){L(a);return}if(R([[`Site`,a.site],[`Eligible pages`,U(a.summary.eligiblePages)],[`Returned pages`,U(a.summary.returnedPages)],[`Eligible queries`,U(a.summary.eligibleQueries)],[`Eligible impressions`,U(a.summary.eligibleImpressions)],[`Content issues`,U(a.summary.contentIssues)],[`Technical issues`,U(a.summary.technicalIssues)],[`Fetch failures`,U(a.summary.fetchFailures)],[`Brand queries`,a.summary.brandFiltering],[`Verification`,Qr(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),U(e.queryCount),yi(e.fetchDiagnostics),bi(e.contentVerification?.classification),e.recommendation.action])),J(`Top second-page actions`,a.items.map(e=>({label:e.primaryQuery,context:`${e.template.label}, pos ${W(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action}))),process.stdout.write(`${a.ledgerSummary}\n`)}}),_s=x({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=M(e),r=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),i=await n({site:r.site,days:k(e.days,`--days`),startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),limit:k(e.limit,`--limit`),minImpressions:k(e[`min-impressions`],`--min-impressions`),maxRows:k(e[`max-rows`],`--max-rows`),brandTerms:[...r.client?.brandTerms??[],...A(e[`brand-terms`])??[]],includeBrand:D(e[`include-brand`]),refresh:D(e.refresh)});if(t){L(i);return}R([[`Property`,i.site],[`Status`,i.dataStatus],[`Verdict`,i.summary.verdict],[`Eligible queries`,U(i.summary.eligibleQueries)],[`Returned queries`,U(i.summary.returnedQueries)],[`Prompts`,U(i.summary.prompts)],[`GSC completeness`,i.source.completeness]]),q([`Query`,`Impr`,`Prompt`],i.items.flatMap(e=>e.prompts.map(t=>[K(e.query,42),U(e.impressions),K(t,86)]))),Y(`Report caveats`,i.caveats),Y(`Warnings`,i.warnings)}}),vs=x({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=E(e),n=T(e.site),r=t?await Xr({project:t,options:{json:M(e)}}):void 0,i=t||n?void 0:await Xr({options:{json:M(e)}}),a=await Ot({url:T(e.url)??``,site:r?.siteUrl??n??i?.siteUrl,js:D(e.js)?!0:`auto`,refresh:D(e.refresh)});if(M(e)){L(a);return}R([[`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`,yi(a.fetchDiagnostics)]]),a.issues.length&&(process.stdout.write(`
118
118
  Issues
119
- `),z([`Code`,`Severity`,`Principle`,`Detail`],a.issues.map(e=>[e.code,e.severity,e.principle,e.detail])))}});function us(e){let t=T(e)??`mobile`;if(t!==`mobile`&&t!==`desktop`)throw new v(`INVALID_INPUT`,`Invalid --strategy. Use mobile or desktop.`);return t}function ds(e){return e?e.displayValue??String(e.value??`not measured`):`not measured`}function fs(e){if(!e)return`not available`;let t=e.unit===`milliseconds`?`ms`:``;return`${e.p75}${t} (${e.rating})`}const ps=x({meta:{name:`perf`,description:`Audit lab performance and field Core Web Vitals`},subCommands:{audit:x({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=M(e),n=await Vr({client:E(e),options:{json:t}}),r=T(e.url)??n?.startUrl;if(!r)throw Error(`No URL selected. Pass --url or use --project with a crawl URL.`);let i=await fe({url:r,strategy:us(e.strategy),lighthouseBin:T(e[`lighthouse-bin`]),cruxApiKey:T(e[`crux-key`]),refresh:D(e.refresh),includeRaw:t&&D(e.raw)});if(t){L(i);return}R([[`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`,ds(i.metrics.firstContentfulPaint)],[`LCP`,ds(i.metrics.largestContentfulPaint)],[`TBT`,ds(i.metrics.totalBlockingTime)],[`CLS`,ds(i.metrics.cumulativeLayoutShift)],[`INP`,ds(i.metrics.interactionToNextPaint)],[`Server response`,ds(i.metrics.serverResponseTime)],[`Fallback fetch`,ds(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`,fs(i.fieldData?.metrics.largestContentfulPaint)],[`Field INP p75`,fs(i.fieldData?.metrics.interactionToNextPaint)],[`Field CLS p75`,fs(i.fieldData?.metrics.cumulativeLayoutShift)]]),J(`Top actions`,i.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),Y(`Caveats`,i.caveats)}})}}),ms=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await g({site:n.site,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`]),refresh:D(e.refresh),progress:Ya(!t)});if(t){L(r);return}R([[`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)]]),z([`Priority`,`Confidence`,`Reason`,`Action`],r.priorities.map(e=>[e.label,e.confidence,e.reason,e.action])),r.skippedSections?.length&&z([`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})))}}),hs=x({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 ct();if(M(e)){L(t),t.ok||(process.exitCode=1);return}jr(`SEO doctor`,Sr(t.checks)),process.stdout.write(`
120
- `),Mr(t.checks),process.stdout.write(`\nChecked ${t.generatedAt}\n`),t.ok||(process.exitCode=1)}}),gs=e=>{let t=T(e)??`page`;if(t!==`page`&&t!==`query`&&t!==`country`&&t!==`device`)throw Error(`Invalid --dimension. Use page, query, country, or device.`);return t},_s=x({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:t})=>{let n=M(t),r=gs(t.dimension),i=k(t.days,`--days`),a=k(t.compare,`--compare`),o=k(t.limit,`--limit`),s=k(t[`unmatched-limit`],`--unmatched-limit`),c=k(t[`max-rows`],`--max-rows`),l=await e({site:(await H({client:E(t),site:T(t.site),options:{json:n,refresh:D(t.refresh)}})).site,dimension:r,days:i,compareDays:a,startDate:T(t[`start-date`]),endDate:T(t[`end-date`]),limit:o,unmatchedLimit:s,maxRows:c,refresh:D(t.refresh)});if(n){L(l);return}R([[`Property`,l.site],[`Dimension`,l.dimension],[`Status`,l.dataStatus],[`Before`,`${l.before.startDate} to ${l.before.endDate}`],[`After`,`${l.after.startDate} to ${l.after.endDate}`],[`Verdict`,l.summary.verdict]]),z([`Segment`,`Clicks before`,`Clicks after`,`Delta`,`Pos delta`],l.items.map(e=>[e.key,e.beforeClicks,e.afterClicks,e.clickDelta,e.positionDelta??`-`])),l.unmatchedSegments.length&&(process.stdout.write(`
119
+ `),z([`Code`,`Severity`,`Principle`,`Detail`],a.issues.map(e=>[e.code,e.severity,e.principle,e.detail])))}});function ys(e){let t=T(e)??`mobile`;if(t!==`mobile`&&t!==`desktop`)throw new _(`INVALID_INPUT`,`Invalid --strategy. Use mobile or desktop.`);return t}function bs(e){return e?e.displayValue??String(e.value??`not measured`):`not measured`}function xs(e){if(!e)return`not available`;let t=e.unit===`milliseconds`?`ms`:``;return`${e.p75}${t} (${e.rating})`}const Ss=x({meta:{name:`perf`,description:`Audit lab performance and field Core Web Vitals`},subCommands:{audit:x({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=M(e),n=await Xr({client:E(e),options:{json:t}}),r=T(e.url)??n?.startUrl;if(!r)throw Error(`No URL selected. Pass --url or use --project with a crawl URL.`);let i=await se({url:r,strategy:ys(e.strategy),lighthouseBin:T(e[`lighthouse-bin`]),cruxApiKey:T(e[`crux-key`]),refresh:D(e.refresh),includeRaw:t&&D(e.raw)});if(t){L(i);return}R([[`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`,bs(i.metrics.firstContentfulPaint)],[`LCP`,bs(i.metrics.largestContentfulPaint)],[`TBT`,bs(i.metrics.totalBlockingTime)],[`CLS`,bs(i.metrics.cumulativeLayoutShift)],[`INP`,bs(i.metrics.interactionToNextPaint)],[`Server response`,bs(i.metrics.serverResponseTime)],[`Fallback fetch`,bs(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`,xs(i.fieldData?.metrics.largestContentfulPaint)],[`Field INP p75`,xs(i.fieldData?.metrics.interactionToNextPaint)],[`Field CLS p75`,xs(i.fieldData?.metrics.cumulativeLayoutShift)]]),J(`Top actions`,i.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),Y(`Caveats`,i.caveats)}})}}),Cs=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await Fe({site:n.site,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`]),refresh:D(e.refresh),progress:io(!t)});if(t){L(r);return}R([[`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)]]),z([`Priority`,`Confidence`,`Reason`,`Action`],r.priorities.map(e=>[e.label,e.confidence,e.reason,e.action])),r.skippedSections?.length&&z([`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})))}}),ws=x({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 Bt();if(M(e)){L(t),t.ok||(process.exitCode=1);return}Br(`SEO doctor`,jr(t.checks)),process.stdout.write(`
120
+ `),Vr(t.checks),process.stdout.write(`\nChecked ${t.generatedAt}\n`),t.ok||(process.exitCode=1)}}),Ts=e=>{let t=T(e)??`page`;if(t!==`page`&&t!==`query`&&t!==`country`&&t!==`device`)throw Error(`Invalid --dimension. Use page, query, country, or device.`);return t},Es=x({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=M(e),n=Ts(e.dimension),r=k(e.days,`--days`),i=k(e.compare,`--compare`),a=k(e.limit,`--limit`),o=k(e[`unmatched-limit`],`--unmatched-limit`),s=k(e[`max-rows`],`--max-rows`),c=await Ke({site:(await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}})).site,dimension:n,days:r,compareDays:i,startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),limit:a,unmatchedLimit:o,maxRows:s,refresh:D(e.refresh)});if(t){L(c);return}R([[`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]]),z([`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
121
  One-window evidence (not treated as zero)
122
- `),z([`Segment`,`Retained in`,`Clicks`,`Impressions`],l.unmatchedSegments.map(e=>[e.key,e.retainedIn,e.clicks,e.impressions]))),Y(`Warnings`,l.warnings)}});function vs(e){return`${U(e)} ${e===1?`row`:`rows`}`}const ys=x({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=M(e),n=O(e[`verify-limit`]),r=D(e[`verify-content`])===!0||n!==void 0,i=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),a=await Me({site:i.site,days:O(e.days),minImpressions:O(e[`min-impressions`]),limit:O(e.limit),brandTerms:i.client?.brandTerms,includeBrand:D(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:D(e.js)?!0:void 0,rate:er(e),refresh:D(e.refresh)});if(t){L(a);return}if(R([[`Site`,a.site],[`Eligible rows`,U(a.summary.eligibleRows)],[`Returned rows`,U(a.summary.returnedRows)],[`Template groups`,U(a.summary.groups)],[`Eligible impressions`,U(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),U(e.rowCount),U(e.uniqueUrls),U(e.totalImpressions),W(e.impressionWeightedPosition),e.actionScope,K(e.recommendation.action,72)])),J(`Top striking-distance group actions`,a.groups.map(e=>({label:e.label,context:`${vs(e.rowCount)}, ${U(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),U(e.impressions),G(e.ctr),W(e.position),e.priority.score,ui(e.contentVerification?.fetchDiagnostics),di(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 ${W(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action})))}});function bs(e){let t=e.indexed+e.notIndexed+e.unknown+e.warnings;return t?`${e.indexed}/${t} indexed`:`-`}function xs(e){if(!e.samples.length)return`-`;let t=e.medianWordCount===void 0?`words ?`:`${U(e.medianWordCount)} words`,n=e.weakQueryCoverage?`; ${e.weakQueryCoverage} weak coverage`:``;return`${t}; ${e.usable}/${e.samples.length} usable${n}`}function Ss(e){return e===`serp-framing-review`?`wording review`:e===`body-term-review`?`literal term review`:`covered terms`}function Cs(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 ws(e){if(e.checkedQueries)return`${Math.round(e.impressionShare*100)}% impression fit across ${Je(e.checkedQueries,`checked query/page row`)}`}function Ts(e){return e.startsWith(`theme: `)?`${e.slice(7)}-related`:e===`general`?`broad`:e}function Es(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: ${Cs(t.shape)}\n`);let e=ws(t.metrics.entityFit);e&&process.stdout.write(` Entity fit: ${e}\n`);let n=t.metrics.queryPatterns.slice(0,3).map(e=>`${Ts(e.label)} (${U(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:
122
+ `),z([`Segment`,`Retained in`,`Clicks`,`Impressions`],c.unmatchedSegments.map(e=>[e.key,e.retainedIn,e.clicks,e.impressions]))),Y(`Warnings`,c.warnings)}});function Ds(e){return`${U(e)} ${e===1?`row`:`rows`}`}const Os=x({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=M(e),n=O(e[`verify-limit`]),r=D(e[`verify-content`])===!0||n!==void 0,i=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),a=await lt({site:i.site,days:O(e.days),minImpressions:O(e[`min-impressions`]),limit:O(e.limit),brandTerms:i.client?.brandTerms,includeBrand:D(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:D(e.js)?!0:void 0,rate:lr(e),refresh:D(e.refresh)});if(t){L(a);return}if(R([[`Site`,a.site],[`Eligible rows`,U(a.summary.eligibleRows)],[`Returned rows`,U(a.summary.returnedRows)],[`Template groups`,U(a.summary.groups)],[`Eligible impressions`,U(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),U(e.rowCount),U(e.uniqueUrls),U(e.totalImpressions),W(e.impressionWeightedPosition),e.actionScope,K(e.recommendation.action,72)])),J(`Top striking-distance group actions`,a.groups.map(e=>({label:e.label,context:`${Ds(e.rowCount)}, ${U(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),U(e.impressions),G(e.ctr),W(e.position),e.priority.score,yi(e.contentVerification?.fetchDiagnostics),bi(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 ${W(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action})))}});function ks(e){let t=e.indexed+e.notIndexed+e.unknown+e.warnings;return t?`${e.indexed}/${t} indexed`:`-`}function As(e){if(!e.samples.length)return`-`;let t=e.medianWordCount===void 0?`words ?`:`${U(e.medianWordCount)} words`,n=e.weakQueryCoverage?`; ${e.weakQueryCoverage} weak coverage`:``;return`${t}; ${e.usable}/${e.samples.length} usable${n}`}function js(e){return e===`serp-framing-review`?`wording review`:e===`body-term-review`?`literal term review`:`covered terms`}function Ms(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 Ns(e){if(e.checkedQueries)return`${Math.round(e.impressionShare*100)}% impression fit across ${gt(e.checkedQueries,`checked query/page row`)}`}function Ps(e){return e.startsWith(`theme: `)?`${e.slice(7)}-related`:e===`general`?`broad`:e}function Fs(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: ${Ms(t.shape)}\n`);let e=Ns(t.metrics.entityFit);e&&process.stdout.write(` Entity fit: ${e}\n`);let n=t.metrics.queryPatterns.slice(0,3).map(e=>`${Ps(e.label)} (${U(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
124
  `);for(let e of r)process.stdout.write(` - ${K(e.query,72)} (${U(e.impressions)} impr, pos ${W(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(` - ${Ss(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 ${Je(t.length,`path term`)}: ${t.join(`, `)}\n`)}}process.stdout.write(` Action: ${t.recommendation}\n`)}}const Ds=x({meta:{name:`pseo`,description:`Programmatic SEO audits that cluster URL patterns and sample template pages`},subCommands:{audit:x({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=M(e),n=To(e),r=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),i=await c({site:r.site,...n,brandTerms:n.brandTerms??r.client?.brandTerms,progress:Ya(!t)});if(t){L(i);return}if(R([[`Property`,i.site],[`Templates`,U(i.summary.templates)],[`GSC pages`,U(i.summary.gscPages)],[`Sitemap URLs`,U(i.summary.sitemapUrls)],[`Clicks`,U(i.summary.clicks)],[`Impressions`,U(i.summary.impressions)],[`Usable crawls`,`${U(i.summary.crawledUrls)}/${U(i.summary.crawlAttempts)}`],[`Inspection responses`,`${U(i.summary.inspectedUrls)}/${U(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),U(e.urlCount),U(e.metrics.clicks),U(e.metrics.impressions),G(e.metrics.ctr),e.metrics.position.toFixed(1),bs(e.inspection),xs(e.crawl),K(e.recommendation,72)])),Es(i.templates),i.warnings.length&&process.stdout.write(`Warnings: ${i.warnings.join(`; `)}\n`),Wr(`seo export pseo ${r.client?`--project ${JSON.stringify(r.client.id)}`:`--site ${JSON.stringify(r.site)}`}`)}})}}),Os={"ai-search":`AI search`,crawl:`Crawling and technical checks`,diagnosis:`Diagnosis`,experiments:`Experiments`,monitoring:`Monitoring`,opportunities:`Opportunities`,reporting:`Reporting`,setup:`Setup`,workflows:`Workflows`};function ks(e){let t=T(e);if(t){if(!Et.includes(t))throw new v(`INVALID_INPUT`,`Unknown report category: ${t}. Choose ${Et.join(`, `)}.`);return t}}async function As(e,t){let n=T(e),r=T(t);if(n&&r)throw new v(`INVALID_INPUT`,`Use either --params or --params-file, not both.`);if(!n&&!r)return{};let i=n??await gn(r??``,`utf8`),a;try{a=JSON.parse(i)}catch{throw new v(`INVALID_INPUT`,`Report parameters must be valid JSON.`)}if(!a||typeof a!=`object`||Array.isArray(a))throw new v(`INVALID_INPUT`,`Report parameters must be an object.`);return a}function js(e){if(!e.isError)return;let t=e.structuredContent;throw new v(t?.error?.code??`INTERNAL_ERROR`,t?.error?.message??`The report could not be completed.`)}function Ms(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 Ns=x({meta:{name:`reports`,description:`Discover and run the complete report catalog`},subCommands:{list:x({meta:{name:`list`,description:`List report ids available to the CLI and MCP server`},args:{category:{type:`string`,description:`Filter by category: ${Et.join(`, `)}.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Re(ks(e.category));if(M(e)){L({reports:t,categories:Et});return}Nr(t,{noun:`report`,categoryLabels:Os}),process.stdout.write(`
128
- `),Ar({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:x({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`."},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=xt(T(e.id)??``);if(M(e)){L({report:t});return}jr(t.name,t.description),process.stdout.write(`
125
+ `);for(let e of i){let t=e.missingTerms.length?` missing ${e.missingTerms.slice(0,4).join(`, `)}`:``;process.stdout.write(` - ${js(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 ${gt(t.length,`path term`)}: ${t.join(`, `)}\n`)}}process.stdout.write(` Action: ${t.recommendation}\n`)}}const Is=x({meta:{name:`pseo`,description:`Programmatic SEO audits that cluster URL patterns and sample template pages`},subCommands:{audit:x({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=M(e),n=Po(e),r=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),i=await ne({site:r.site,...n,brandTerms:n.brandTerms??r.client?.brandTerms,progress:io(!t)});if(t){L(i);return}if(R([[`Property`,i.site],[`Templates`,U(i.summary.templates)],[`GSC pages`,U(i.summary.gscPages)],[`Sitemap URLs`,U(i.summary.sitemapUrls)],[`Clicks`,U(i.summary.clicks)],[`Impressions`,U(i.summary.impressions)],[`Usable crawls`,`${U(i.summary.crawledUrls)}/${U(i.summary.crawlAttempts)}`],[`Inspection responses`,`${U(i.summary.inspectedUrls)}/${U(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),U(e.urlCount),U(e.metrics.clicks),U(e.metrics.impressions),G(e.metrics.ctr),e.metrics.position.toFixed(1),ks(e.inspection),As(e.crawl),K(e.recommendation,72)])),Fs(i.templates),i.warnings.length&&process.stdout.write(`Warnings: ${i.warnings.join(`; `)}\n`),$r(`seo export pseo ${r.client?`--project ${JSON.stringify(r.client.id)}`:`--site ${JSON.stringify(r.site)}`}`)}})}}),Ls={"ai-search":`AI search`,crawl:`Crawling and technical checks`,diagnosis:`Diagnosis`,experiments:`Experiments`,monitoring:`Monitoring`,opportunities:`Opportunities`,reporting:`Reporting`,setup:`Setup`,workflows:`Workflows`};function Rs(e){let t=T(e);if(t){if(!Pt.includes(t))throw new _(`INVALID_INPUT`,`Unknown report category: ${t}. Choose ${Pt.join(`, `)}.`);return t}}async function zs(e,t){let n=T(e),r=T(t);if(n&&r)throw new _(`INVALID_INPUT`,`Use either --params or --params-file, not both.`);if(!n&&!r)return{};let i=n??await Tn(r??``,`utf8`),a;try{a=JSON.parse(i)}catch{throw new _(`INVALID_INPUT`,`Report parameters must be valid JSON.`)}if(!a||typeof a!=`object`||Array.isArray(a))throw new _(`INVALID_INPUT`,`Report parameters must be an object.`);return a}function Bs(e){if(!e.isError)return;let t=e.structuredContent;throw new _(t?.error?.code??`INTERNAL_ERROR`,t?.error?.message??`The report could not be completed.`)}function Vs(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 Hs=x({meta:{name:`reports`,description:`Discover and run the complete report catalog`},subCommands:{list:x({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=ze(Rs(e.category));if(M(e)){L({reports:t,categories:Pt});return}Hr(t,{noun:`report`,categoryLabels:Ls}),process.stdout.write(`
128
+ `),zr({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:x({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`."},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=kt(T(e.id)??``);if(M(e)){L({report:t});return}Br(t.name,t.description),process.stdout.write(`
129
129
  `),R([[`ID`,t.id],[`Category`,t.category],[`Outcome`,t.outcome]]),process.stdout.write(`
130
- `),Ir(`Use when`,t.useWhen),process.stdout.write(`
131
- `),Ir(`Avoid when`,t.avoidWhen),process.stdout.write(`
132
- `),Ir(`Read in order`,t.readOrder),process.stdout.write(`
133
- `),Ir(`Do not claim`,t.doNotClaim),process.stdout.write(`
134
- `),Fr(`Verify`,t.verify),t.related.length>0&&(process.stdout.write(`
135
- `),Ir(`Related reports`,t.related.map(e=>`${e.id}: ${e.reason}`))),process.stdout.write(`
130
+ `),Gr(`Use when`,t.useWhen),process.stdout.write(`
131
+ `),Gr(`Avoid when`,t.avoidWhen),process.stdout.write(`
132
+ `),Gr(`Read in order`,t.readOrder),process.stdout.write(`
133
+ `),Gr(`Do not claim`,t.doNotClaim),process.stdout.write(`
134
+ `),Wr(`Verify`,t.verify),t.related.length>0&&(process.stdout.write(`
135
+ `),Gr(`Related reports`,t.related.map(e=>`${e.id}: ${e.reason}`))),process.stdout.write(`
136
136
  Parameters
137
- `),Lr(Ms(t.inputSchema)),process.stdout.write(`
138
- `),Ar({title:`Need the exact schema?`,command:`seo reports describe ${t.id} --json`})}}),run:x({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(T(e.id)??``,await As(e.params,e[`params-file`]));if(js(t),M(e)){L(t.structuredContent??{});return}for(let e of t.content)process.stdout.write(`${e.text}\n`)}})}}),Ps=x({meta:{name:`monthly-report`,description:`Generate a monthly SEO report narrative`},args:{...Xa,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.`}}),...Za},run:async({args:e})=>{let t=M(e),n=$a(e),r=await H({client:n.client,site:n.site,options:{json:t,refresh:n.refresh}}),i=await o({site:r.site,month:T(e.month),limit:O(e.limit),brandTerms:r.client?.brandTerms,...Qa(e),progress:Ya(!t)});if(t){L(i);return}process.stdout.write(`${i.markdown}\n`);let a=r.client?`--project ${JSON.stringify(r.client.id)}`:`--site ${JSON.stringify(r.site)}`,s=T(e.month);process.stdout.write(`
139
- `),Wr(`seo export monthly ${a}${s?` --month ${JSON.stringify(s)}`:``}`)}}),Fs=x({meta:{name:`report-narrative`,description:`Generate a client-ready SEO narrative from diagnosis data`},args:{...Xa,...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.`},...Za},run:async({args:e})=>{let t=M(e),n=$a(e),r=await H({client:n.client,site:n.site,options:{json:t,refresh:n.refresh}}),i=await Pt({site:r.site,days:O(e.days),recentDays:O(e.recent),startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),limit:O(e.limit),changeLimit:O(e[`change-limit`]),brandTerms:r.client?.brandTerms,...Qa(e),progress:Ya(!t)});if(t){L(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(`
140
- `),Wr(`seo export narrative ${a}`)}}),Is=x({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=T(e.category),n=l().filter(e=>!t||e.category===t);if(M(e)){L({rules:n});return}Nr(n.map(e=>({id:e.id,category:e.category,name:`${e.title} · ${e.defaultSeverity}`})),{noun:`rule`})}}),Ls=x({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=T(e.rule)??``,n=d(t);if(!n)throw Error(`Unknown rule: ${t}`);if(M(e)){L(n);return}R([[`Rule`,n.id],[`Title`,n.title],[`Category`,n.category],[`Severity`,n.defaultSeverity]]),process.stdout.write(`
141
- `),Fr(`Why it matters`,n.whyItMatters),process.stdout.write(`
142
- `),Fr(`How to fix`,n.howToFix),process.stdout.write(`
143
- `),Fr(`Impact if ignored`,n.impactIfIgnored),process.stdout.write(`
144
- `),Fr(`How to verify`,n.howToVerify)}});function Rs(e){return JSON.stringify(e)}const zs=x({meta:{name:`schedule`,description:`Print local cron entries for recurring SEO workflows`},subCommands:{cron:x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t}}),r=n.site,i=T(e.url)??n.client?.startUrl??si(n.site),a=O(e.hour)??9,o=O(e.minute)??0,s=O(e.weekday)??n.client?.technicalWeekday??1,c=O(e.day)??n.client?.reportDay??1,l=n.client?`--project ${Rs(n.client.id)}`:`--site ${Rs(r)}`,u=T(e.urls)??n.client?.watchUrls.join(`,`),d=[{name:`technical-watch`,cron:`${o} ${a} * * ${s}`,command:[`seo technical-watch`,l,i?`--url ${Rs(i)}`:void 0,u?`--urls ${Rs(u)}`:void 0,`--json`].filter(Boolean).join(` `)},{name:`monthly-report`,cron:`${o} ${a} ${c} * *`,command:[`seo monthly-report`,l,`--json`].join(` `)}];if(t){L({site:r,lines:d});return}let f=ht();R([[`Property`,r],[`Install`,`crontab -e`]]);for(let e of d)process.stdout.write(`${e.cron} ${e.command} >> ${Rs(`${f.logDir}/${e.name}.log`)} 2>&1\n`)}})}});function Bs(){return Hs(`skills`,process.env.SEO_SKILLS_DIR)}function Vs(){return Hs(`evals`,process.env.SEO_EVALS_DIR)}function Hs(e,t){if(t)return an(t);let n=en(un(import.meta.url));for(let t=0;t<6;t+=1){let t=b(n,e);if(y(b(t,`README.md`)))return t;n=en(n)}throw new v(`INTERNAL_ERROR`,`Packaged ${e} could not be found. Reinstall \`seo\` and try again.`)}function Us(e){return Gt(b(e,`SKILL.md`),`utf8`).match(/^description:\s*(.+)$/m)?.[1]?.trim()??``}const Ws=`claude -p`;function Gs(){let e=Vs();return Kt(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(t=>({subject:$t(t.name,`.json`),path:b(e,t.name)})).sort((e,t)=>e.subject<t.subject?-1:+(e.subject>t.subject))}function Ks(e,t){let n;try{n=Gt(t,`utf8`)}catch{throw new v(`INVALID_INPUT`,`Cannot read eval file for ${e}.`)}let r;try{r=JSON.parse(n)}catch{throw new v(`INVALID_INPUT`,`Eval file ${e}.json is not valid JSON.`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new v(`INVALID_INPUT`,`Eval file ${e}.json must be an object.`);let i=r;if(i.subject!==e)throw new v(`INVALID_INPUT`,`Eval file ${e}.json must set subject to "${e}".`);if(!Array.isArray(i.evals)||i.evals.length===0)throw new v(`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 v(`INVALID_INPUT`,`${i}: id must be an integer.`);let o=r.id;if(a.has(o))throw new v(`INVALID_INPUT`,`${i}: duplicate id ${o}.`);if(a.add(o),typeof r.prompt!=`string`||r.prompt.trim().length===0)throw new v(`INVALID_INPUT`,`${i}: prompt must be a non-empty string.`);if(typeof r.expected_output!=`string`||r.expected_output.trim().length===0)throw new v(`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 v(`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 v(`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 qs(){let e=b(Bs(),`seo`,`SKILL.md`);if(!y(e))throw new v(`INTERNAL_ERROR`,"The seo router skill could not be found. Reinstall `seo` or use --no-skill.");return Gt(e,`utf8`)}function Js(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===`
145
- `||s===`\r`){r&&=(t.push(n),n=``,!1);continue}n+=s,r=!0}if(i||a)throw new v(`INVALID_INPUT`,`Unbalanced quote in agent command.`);return r&&t.push(n),t}function Ys(e,t){let n=Js(e);if(n.length===0)throw new v(`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 Xs(e,t){return e?`${e.trim()}\n\n---\n\nUser request:\n${t}`:t}function Zs(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(`
137
+ `),Kr(Vs(t.inputSchema)),process.stdout.write(`
138
+ `),zr({title:`Need the exact schema?`,command:`seo reports describe ${t.id} --json`})}}),run:x({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 st(T(e.id)??``,await zs(e.params,e[`params-file`]));if(Bs(t),M(e)){L(t.structuredContent??{});return}for(let e of t.content)process.stdout.write(`${e.text}\n`)}})}}),Us=x({meta:{name:`monthly-report`,description:`Generate a monthly SEO report narrative`},args:{...ao,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.`}}),...oo},run:async({args:e})=>{let t=M(e),n=co(e),r=await H({client:n.client,site:n.site,options:{json:t,refresh:n.refresh}}),i=await le({site:r.site,month:T(e.month),limit:O(e.limit),brandTerms:r.client?.brandTerms,...so(e),progress:io(!t)});if(t){L(i);return}process.stdout.write(`${i.markdown}\n`);let a=r.client?`--project ${JSON.stringify(r.client.id)}`:`--site ${JSON.stringify(r.site)}`,o=T(e.month);process.stdout.write(`
139
+ `),$r(`seo export monthly ${a}${o?` --month ${JSON.stringify(o)}`:``}`)}}),Ws=x({meta:{name:`report-narrative`,description:`Generate a client-ready SEO narrative from diagnosis data`},args:{...ao,...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.`},...oo},run:async({args:e})=>{let t=M(e),n=co(e),r=await H({client:n.client,site:n.site,options:{json:t,refresh:n.refresh}}),i=await de({site:r.site,days:O(e.days),recentDays:O(e.recent),startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),limit:O(e.limit),changeLimit:O(e[`change-limit`]),brandTerms:r.client?.brandTerms,...so(e),progress:io(!t)});if(t){L(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(`
140
+ `),$r(`seo export narrative ${a}`)}}),Gs=x({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=T(e.category),n=re().filter(e=>!t||e.category===t);if(M(e)){L({rules:n});return}Hr(n.map(e=>({id:e.id,category:e.category,name:`${e.title} · ${e.defaultSeverity}`})),{noun:`rule`})}}),Ks=x({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=T(e.rule)??``,n=p(t);if(!n)throw Error(`Unknown rule: ${t}`);if(M(e)){L(n);return}R([[`Rule`,n.id],[`Title`,n.title],[`Category`,n.category],[`Severity`,n.defaultSeverity]]),process.stdout.write(`
141
+ `),Wr(`Why it matters`,n.whyItMatters),process.stdout.write(`
142
+ `),Wr(`How to fix`,n.howToFix),process.stdout.write(`
143
+ `),Wr(`Impact if ignored`,n.impactIfIgnored),process.stdout.write(`
144
+ `),Wr(`How to verify`,n.howToVerify)}});function qs(e){return JSON.stringify(e)}const Js=x({meta:{name:`schedule`,description:`Print local cron entries for recurring SEO workflows`},subCommands:{cron:x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t}}),r=n.site,i=T(e.url)??n.client?.startUrl??gi(n.site),a=O(e.hour)??9,o=O(e.minute)??0,s=O(e.weekday)??n.client?.technicalWeekday??1,c=O(e.day)??n.client?.reportDay??1,l=n.client?`--project ${qs(n.client.id)}`:`--site ${qs(r)}`,u=T(e.urls)??n.client?.watchUrls.join(`,`),d=[{name:`technical-watch`,cron:`${o} ${a} * * ${s}`,command:[`seo technical-watch`,l,i?`--url ${qs(i)}`:void 0,u?`--urls ${qs(u)}`:void 0,`--json`].filter(Boolean).join(` `)},{name:`monthly-report`,cron:`${o} ${a} ${c} * *`,command:[`seo monthly-report`,l,`--json`].join(` `)}];if(t){L({site:r,lines:d});return}let f=at();R([[`Property`,r],[`Install`,`crontab -e`]]);for(let e of d)process.stdout.write(`${e.cron} ${e.command} >> ${qs(`${f.logDir}/${e.name}.log`)} 2>&1\n`)}})}});function Ys(){return Zs(`skills`,process.env.SEO_SKILLS_DIR)}function Xs(){return Zs(`evals`,process.env.SEO_EVALS_DIR)}function Zs(e,t){if(t)return mn(t);let n=y(yn(import.meta.url));for(let t=0;t<6;t+=1){let t=b(n,e);if(v(b(t,`README.md`)))return t;n=y(n)}throw new _(`INTERNAL_ERROR`,`Packaged ${e} could not be found. Reinstall \`seo\` and try again.`)}function Qs(e){return tn(b(e,`SKILL.md`),`utf8`).match(/^description:\s*(.+)$/m)?.[1]?.trim()??``}const $s=`claude -p`;function ec(){let e=Xs();return nn(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(t=>({subject:un(t.name,`.json`),path:b(e,t.name)})).sort((e,t)=>e.subject<t.subject?-1:+(e.subject>t.subject))}function tc(e,t){let n;try{n=tn(t,`utf8`)}catch{throw new _(`INVALID_INPUT`,`Cannot read eval file for ${e}.`)}let r;try{r=JSON.parse(n)}catch{throw new _(`INVALID_INPUT`,`Eval file ${e}.json is not valid JSON.`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new _(`INVALID_INPUT`,`Eval file ${e}.json must be an object.`);let i=r;if(i.subject!==e)throw new _(`INVALID_INPUT`,`Eval file ${e}.json must set subject to "${e}".`);if(!Array.isArray(i.evals)||i.evals.length===0)throw new _(`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 _(`INVALID_INPUT`,`${i}: id must be an integer.`);let o=r.id;if(a.has(o))throw new _(`INVALID_INPUT`,`${i}: duplicate id ${o}.`);if(a.add(o),typeof r.prompt!=`string`||r.prompt.trim().length===0)throw new _(`INVALID_INPUT`,`${i}: prompt must be a non-empty string.`);if(typeof r.expected_output!=`string`||r.expected_output.trim().length===0)throw new _(`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 _(`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 _(`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 nc(){let e=b(Ys(),`seo`,`SKILL.md`);if(!v(e))throw new _(`INTERNAL_ERROR`,"The seo router skill could not be found. Reinstall `seo` or use --no-skill.");return tn(e,`utf8`)}function rc(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===`
145
+ `||s===`\r`){r&&=(t.push(n),n=``,!1);continue}n+=s,r=!0}if(i||a)throw new _(`INVALID_INPUT`,`Unbalanced quote in agent command.`);return r&&t.push(n),t}function ic(e,t){let n=rc(e);if(n.length===0)throw new _(`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 ac(e,t){return e?`${e.trim()}\n\n---\n\nUser request:\n${t}`:t}function oc(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(`
146
146
  `),`</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(`
147
- `);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 Qs(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 $s(e,t){let n=Qs(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 ec(e,t){return new Promise(n=>{let r=Date.now(),[i,...a]=e,o;try{o=cn(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 tc(e,t,n){let{argv:r,usesPlaceholder:i}=Ys(e,t);return ec(r,{input:i?void 0:t,timeoutMs:n})}async function nc(e,t){let n=Date.now(),r=Xs(t.skillBody,e.prompt),i=await tc(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:rc(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:rc(e.assertions)};if(a.length===0)return{...o,status:`errored`,error:`Agent returned no output on stdout.`,durationMs:Date.now()-n,assertions:rc(e.assertions)};if(!t.judge)return{...o,status:`unjudged`,durationMs:Date.now()-n,assertions:rc(e.assertions)};let s=0,c=``;for(let r=0;r<2;r+=1){let i=Zs(e.prompt,a,e.assertions,r>0),l=await tc(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:rc(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:rc(e.assertions)};let u=$s(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:rc(e.assertions)}}function rc(e){return e.map(e=>({assertion:e,verdict:`unjudged`}))}async function ic(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 ac(e){let t={passed:0,failed:0,errored:0,unjudged:0};for(let n of e)t[n.status]+=1;return t}function oc(e){let t=[],n=T(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 sc(e){let t=Gs();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 v(`INVALID_INPUT`,`Unknown eval subject: ${e}.${n?` Known subjects: ${n}.`:``}`)}return r})}function cc(e){let t=Gs().map(e=>{let t=Ks(e.subject,e.path);return{subject:e.subject,evals:t.evals.length}});if(e){L({schemaVersion:1,subjects:t});return}if(t.length===0){process.stdout.write(`No eval subjects found.
147
+ `);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 sc(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 cc(e,t){let n=sc(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 lc(e,t){return new Promise(n=>{let r=Date.now(),[i,...a]=e,o;try{o=_n(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 uc(e,t,n){let{argv:r,usesPlaceholder:i}=ic(e,t);return lc(r,{input:i?void 0:t,timeoutMs:n})}async function dc(e,t){let n=Date.now(),r=ac(t.skillBody,e.prompt),i=await uc(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:fc(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:fc(e.assertions)};if(a.length===0)return{...o,status:`errored`,error:`Agent returned no output on stdout.`,durationMs:Date.now()-n,assertions:fc(e.assertions)};if(!t.judge)return{...o,status:`unjudged`,durationMs:Date.now()-n,assertions:fc(e.assertions)};let s=0,c=``;for(let r=0;r<2;r+=1){let i=oc(e.prompt,a,e.assertions,r>0),l=await uc(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:fc(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:fc(e.assertions)};let u=cc(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:fc(e.assertions)}}function fc(e){return e.map(e=>({assertion:e,verdict:`unjudged`}))}async function pc(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 mc(e){let t={passed:0,failed:0,errored:0,unjudged:0};for(let n of e)t[n.status]+=1;return t}function hc(e){let t=[],n=T(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 gc(e){let t=ec();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 _(`INVALID_INPUT`,`Unknown eval subject: ${e}.${n?` Known subjects: ${n}.`:``}`)}return r})}function _c(e){let t=ec().map(e=>{let t=tc(e.subject,e.path);return{subject:e.subject,evals:t.evals.length}});if(e){L({schemaVersion:1,subjects:t});return}if(t.length===0){process.stdout.write(`No eval subjects found.
148
148
  `);return}let n=Math.max(...t.map(e=>e.subject.length));process.stdout.write(`Eval subjects
149
- `);for(let e of t){let t=e.evals===1?`eval`:`evals`;process.stdout.write(` ${e.subject.padEnd(n)} ${e.evals} ${t}\n`)}}function lc(e){return e===`passed`?`PASS`:e===`failed`?`FAIL`:e===`errored`?`ERROR`:`UNJUDGED`}function uc(e,t){t.judged?process.stdout.write(`Assertion verdicts below are judge verdicts, model judgments from the judge agent, not ground truth.
149
+ `);for(let e of t){let t=e.evals===1?`eval`:`evals`;process.stdout.write(` ${e.subject.padEnd(n)} ${e.evals} ${t}\n`)}}function vc(e){return e===`passed`?`PASS`:e===`failed`?`FAIL`:e===`errored`?`ERROR`:`UNJUDGED`}function yc(e,t){t.judged?process.stdout.write(`Assertion verdicts below are judge verdicts, model judgments from the judge agent, not ground truth.
150
150
 
151
151
  `):process.stdout.write(`Judging was skipped. Review each agent reply against the assertion checklist by hand.
152
152
 
153
- `);for(let n of e){process.stdout.write(`# ${n.subject}\n`);for(let e of n.evals){if(process.stdout.write(`\n[${lc(e.status)}] eval ${e.id} (${e.durationMs}ms)\n`),process.stdout.write(` prompt: ${fc(e.prompt,100)}\n`),e.error&&process.stdout.write(` error: ${e.error}\n`),!t.judged){process.stdout.write(` reply: ${fc(e.reply,200)}\n`),process.stdout.write(` assertions to review:
154
- `);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=ac(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=dc(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 dc(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 fc(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const pc=x({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:Ws,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:w(`Judge assertions with an agent.`,`Skip judging and print replies with an assertion checklist.`),skill:w(`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=M(e);if(e.list===!0){cc(t);return}let n=sc(oc(e)),r=O(e.id);if(r!==void 0&&n.length!==1)throw new v(`INVALID_INPUT`,`--id needs exactly one subject. Name the subject to filter.`);let i=O(e.timeout)??300;if(!(i>0))throw new v(`INVALID_INPUT`,`--timeout must be a positive number of seconds.`);let a=Math.max(1,Math.min(4,O(e.concurrency)??1)),o=T(e.agent)??Ws,s=e.judge===!1?null:T(e[`judge-agent`])??o,c=e.skill===!1?null:qs(),l={agent:o,judge:s,skillBody:c,timeoutMs:i*1e3},u=[];for(let e of n){let n=Ks(e.subject,e.path).evals;if(r!==void 0&&(n=n.filter(e=>e.id===r),n.length===0))throw new v(`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 ic(n,a,e=>nc(e,l)),o=ac(i);u.push({subject:e.subject,...o,evals:i})}let d=dc(u),f=d.failed>0||d.errored>0;t?L({schemaVersion:1,agent:o,judge:s,judged:s!==null,skillContext:c!==null,timeoutSeconds:i,concurrency:a,subjects:u,totals:d}):uc(u,{judged:s!==null,agent:o,judge:s}),f&&(process.exitCode=1)}});function mc(){let e=Bs();return Kt(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&y(b(e,t.name,`SKILL.md`))).map(t=>({name:t.name,description:Us(b(e,t.name)),path:b(e,t.name)})).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}function hc(e){let t=mc();if(!e)return t;let n=t.find(t=>t.name===e);if(!n)throw new v(`INVALID_INPUT`,`Unknown skill: ${e}.`);return[n]}const gc=x({meta:{name:`skill`,description:`Inspect the packaged SEO skill and run its evals`},subCommands:{list:x({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=mc();if(M(e)){L({skills:t});return}jr(`SEO skill`,`Packaged with this CLI.`),process.stdout.write(`
153
+ `);for(let n of e){process.stdout.write(`# ${n.subject}\n`);for(let e of n.evals){if(process.stdout.write(`\n[${vc(e.status)}] eval ${e.id} (${e.durationMs}ms)\n`),process.stdout.write(` prompt: ${xc(e.prompt,100)}\n`),e.error&&process.stdout.write(` error: ${e.error}\n`),!t.judged){process.stdout.write(` reply: ${xc(e.reply,200)}\n`),process.stdout.write(` assertions to review:
154
+ `);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=mc(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=bc(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 bc(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 xc(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const Sc=x({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:$s,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:w(`Judge assertions with an agent.`,`Skip judging and print replies with an assertion checklist.`),skill:w(`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=M(e);if(e.list===!0){_c(t);return}let n=gc(hc(e)),r=O(e.id);if(r!==void 0&&n.length!==1)throw new _(`INVALID_INPUT`,`--id needs exactly one subject. Name the subject to filter.`);let i=O(e.timeout)??300;if(!(i>0))throw new _(`INVALID_INPUT`,`--timeout must be a positive number of seconds.`);let a=Math.max(1,Math.min(4,O(e.concurrency)??1)),o=T(e.agent)??$s,s=e.judge===!1?null:T(e[`judge-agent`])??o,c=e.skill===!1?null:nc(),l={agent:o,judge:s,skillBody:c,timeoutMs:i*1e3},u=[];for(let e of n){let n=tc(e.subject,e.path).evals;if(r!==void 0&&(n=n.filter(e=>e.id===r),n.length===0))throw new _(`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 pc(n,a,e=>dc(e,l)),o=mc(i);u.push({subject:e.subject,...o,evals:i})}let d=bc(u),f=d.failed>0||d.errored>0;t?L({schemaVersion:1,agent:o,judge:s,judged:s!==null,skillContext:c!==null,timeoutSeconds:i,concurrency:a,subjects:u,totals:d}):yc(u,{judged:s!==null,agent:o,judge:s}),f&&(process.exitCode=1)}});function Cc(){let e=Ys();return nn(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&v(b(e,t.name,`SKILL.md`))).map(t=>({name:t.name,description:Qs(b(e,t.name)),path:b(e,t.name)})).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}function wc(e){let t=Cc();if(!e)return t;let n=t.find(t=>t.name===e);if(!n)throw new _(`INVALID_INPUT`,`Unknown skill: ${e}.`);return[n]}const Tc=x({meta:{name:`skill`,description:`Inspect the packaged SEO skill and run its evals`},subCommands:{list:x({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=Cc();if(M(e)){L({skills:t});return}Br(`SEO skill`,`Packaged with this CLI.`),process.stdout.write(`
155
155
  `);for(let e of t)R([[`Name`,e.name],[`Purpose`,`Helps agents choose and run the right SEO audit or report.`],[`Path`,e.path]]);process.stdout.write(`
156
- `),Ar({title:`Add it to an agent`,body:`Run setup to install the skill and connect your first site.`,command:`seo start`})}}),path:x({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=T(e.name),n=t?hc(t)[0]?.path:Bs();M(e)?L({name:t,path:n}):process.stdout.write(`${n}\n`)}}),install:x({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=M(e),n=Ii({quiet:t});if(t){L(n),n.status===`failed`&&(process.exitCode=1);return}if(n.status===`failed`)throw new v(`INTERNAL_ERROR`,`Skill install failed: ${n.error}`);process.stdout.write(`SEO skill installed. Agents that support skills can discover it now.
157
- `)}}),eval:pc}}),_c=x({meta:{name:`privacy`,description:`Show local config, token, cache, and log storage paths`},run:async()=>{let e=qe(),t=Ne();R(e.map(e=>[e.label,`${e.path} · ${Rr(e.sizeBytes)} · ${e.mode}`])),process.stdout.write(`
158
- `),R(Object.entries(t.counts).map(([e,t])=>[e,String(t)]))}}),vc=x({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 n=wt(),r=M(e);if(!e.yes&&!I({json:r}))throw new v(`INVALID_INPUT`,`Cannot prompt here. Pass --yes to confirm reset.`);if(!(e.yes||B(await wn({message:`Delete config, tokens, cache, and logs?`,initialValue:!1})))){Cn(`Reset aborted.`);return}await t(),Yt(n.configDir,{recursive:!0,force:!0}),Yt(n.cacheDir,{recursive:!0,force:!0}),Yt(n.logDir,{recursive:!0,force:!0}),r?L({reset:!0}):process.stdout.write(`Reset complete.
159
- `)}}),yc=x({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 Vt(D(e.refresh));if(M(e)){L({sites:t});return}z([`Property`,`Permission`],t.map(e=>[e.siteUrl,e.permissionLevel??`unknown`]))}}),bc=x({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 re({product:T(e.product),limit:O(e.limit)});if(M(e)){L({updates:t});return}Pr(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.`})}}),xc=x({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=M(e),n=E(e),r=await wc(e),i=Cc(e),a=T(e.site)||n||!i&&!r.length?await H({client:n,site:T(e.site),options:{json:t}}):void 0,o=i??a?.client?.startUrl??(a?.site?si(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 Ve({url:o,projectId:a?.client?.id,site:a?.site,mode:Sc(e.mode)??(r.length?`list`:void 0),urls:r,maxPages:O(e[`max-pages`]),maxDepth:O(e[`max-depth`]),concurrency:O(e.concurrency),refresh:D(e.refresh),fetchRate:er({...e,"fetch-concurrency":e.concurrency}),include:A(e.include),exclude:A(e.exclude),googleAnalyticsPropertyId:T(e[`google-analytics-property`])??a?.client?.analytics.google?.propertyId,useSitemap:!Zn(e,`sitemap`),respectRobots:!Zn(e,`robots`),checkExternal:!Zn(e,`external`),js:!!D(e.js),limit:O(e.limit)});if(t){L(s);return}zo(s),z([`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 Sc(e){let t=T(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function Cc(e){let t=T(e.crawlUrl),n=T(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}async function wc(e){let t=A(e.urls)??[],n=T(e[`urls-file`]);return n&&t.push(...Tc(await gn(n,`utf8`))),[...new Set(t)]}function Tc(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}function Ec(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 Dc(e){return/^[A-Za-z0-9_./:@-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function Oc(e){try{return new URL(e).origin}catch{throw new v(`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 kc(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 Ac(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:vt(t,{limit:5}),reviewObservations:Xe(t,{limit:5})}:{status:e.status,...e.reason?{reason:e.reason}:{}}}function jc(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 Mc(e){return`topFixes`in e?{...e,topFixes:e.topFixes.slice(0,3).map(jc),reviewObservations:e.reviewObservations.slice(0,3).map(jc)}:e}function Nc(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 kc(e.dataSources))process.stdout.write(`${t}\n`);if(!e.topFixes.length){process.stdout.write(`No prioritised technical fixes were found.
156
+ `),zr({title:`Add it to an agent`,body:`Run setup to install the skill and connect your first site.`,command:`seo start`})}}),path:x({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=T(e.name),n=t?wc(t)[0]?.path:Ys();M(e)?L({name:t,path:n}):process.stdout.write(`${n}\n`)}}),install:x({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=M(e),n=Gi({quiet:t});if(t){L(n),n.status===`failed`&&(process.exitCode=1);return}if(n.status===`failed`)throw new _(`INTERNAL_ERROR`,`Skill install failed: ${n.error}`);process.stdout.write(`SEO skill installed. Agents that support skills can discover it now.
157
+ `)}}),eval:Sc}}),Ec=x({meta:{name:`privacy`,description:`Show local config, token, cache, and log storage paths`},run:async()=>{let e=ht(),t=ct();R(e.map(e=>[e.label,`${e.path} · ${qr(e.sizeBytes)} · ${e.mode}`])),process.stdout.write(`
158
+ `),R(Object.entries(t.counts).map(([e,t])=>[e,String(t)]))}}),Dc=x({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=nt(),n=M(e);if(!e.yes&&!I({json:n}))throw new _(`INVALID_INPUT`,`Cannot prompt here. Pass --yes to confirm reset.`);if(!(e.yes||B(await Nn({message:`Delete config, tokens, cache, and logs?`,initialValue:!1})))){Mn(`Reset aborted.`);return}await Ge(),on(t.configDir,{recursive:!0,force:!0}),on(t.cacheDir,{recursive:!0,force:!0}),on(t.logDir,{recursive:!0,force:!0}),n?L({reset:!0}):process.stdout.write(`Reset complete.
159
+ `)}}),Oc=x({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 ae(D(e.refresh));if(M(e)){L({sites:t});return}z([`Property`,`Permission`],t.map(e=>[e.siteUrl,e.permissionLevel??`unknown`]))}}),kc=x({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 jt({product:T(e.product),limit:O(e.limit)});if(M(e)){L({updates:t});return}Ur(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.`})}}),Ac={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 jc(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 Mc(e,t){let n=jc(e);if(t){L(n);return}R([[`Anonymous telemetry`,e.enabled?`enabled`:`disabled`],[`Reason`,e.reason?Ac[e.reason]:`local setting`],[`State file`,e.stateFile],[`Install cohort`,e.state?.cohort??`not created`]]),process.stdout.write(`
160
+ Only tool usage is sent. URLs, report data, Google data, and identifiers are never sent.
161
+ `),process.stdout.write(`Details: https://seoskill.dev/telemetry
162
+ `)}const Nc={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},Pc=x({meta:{name:`telemetry`,description:`Check or change anonymous usage telemetry`},subCommands:{status:x({meta:{name:`status`,description:`Show whether anonymous usage telemetry is enabled`},args:{json:Nc},run:async({args:e})=>Mc(mt(),M(e))}),enable:x({meta:{name:`enable`,description:`Enable anonymous usage telemetry in local settings`},args:{json:Nc},run:async({args:e})=>{Mc(qe(!0),M(e))}}),disable:x({meta:{name:`disable`,description:`Disable anonymous usage telemetry in local settings`},args:{json:Nc},run:async({args:e})=>{Mc(qe(!1),M(e))}})}}),Fc=x({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=M(e),n=E(e),r=await Rc(e),i=Lc(e),a=T(e.site)||n||!i&&!r.length?await H({client:n,site:T(e.site),options:{json:t}}):void 0,o=i??a?.client?.startUrl??(a?.site?gi(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 ft({url:o,projectId:a?.client?.id,site:a?.site,mode:Ic(e.mode)??(r.length?`list`:void 0),urls:r,maxPages:O(e[`max-pages`]),maxDepth:O(e[`max-depth`]),concurrency:O(e.concurrency),refresh:D(e.refresh),fetchRate:lr({...e,"fetch-concurrency":e.concurrency}),include:A(e.include),exclude:A(e.exclude),googleAnalyticsPropertyId:T(e[`google-analytics-property`])??a?.client?.analytics.google?.propertyId,useSitemap:!or(e,`sitemap`),respectRobots:!or(e,`robots`),checkExternal:!or(e,`external`),js:!!D(e.js),limit:O(e.limit)});if(t){L(s);return}Jo(s),z([`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 Ic(e){let t=T(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function Lc(e){let t=T(e.crawlUrl),n=T(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}async function Rc(e){let t=A(e.urls)??[],n=T(e[`urls-file`]);return n&&t.push(...zc(await Tn(n,`utf8`))),[...new Set(t)]}function zc(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}function Bc(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 Vc(e){return/^[A-Za-z0-9_./:@-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`}function Hc(e){try{return new URL(e).origin}catch{throw new _(`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 Uc(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 Wc(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:Se(t,{limit:5}),reviewObservations:Kt(t,{limit:5})}:{status:e.status,...e.reason?{reason:e.reason}:{}}}function Gc(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 Kc(e){return`topFixes`in e?{...e,topFixes:e.topFixes.slice(0,3).map(Gc),reviewObservations:e.reviewObservations.slice(0,3).map(Gc)}:e}function qc(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 Uc(e.dataSources))process.stdout.write(`${t}\n`);if(!e.topFixes.length){process.stdout.write(`No prioritised technical fixes were found.
160
163
  `),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?`
161
164
  Prioritised technical fixes
162
165
  `:e.searchDataJoined?`
163
166
  Technical fixes with search value
164
167
  `:`
165
168
  Technical fixes (no Search Console data joined)
166
- `),e.searchDataJoined?z([`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)])):z([`#`,`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 Pc(e){process.stdout.write(`
169
+ `),e.searchDataJoined?z([`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)])):z([`#`,`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 Jc(e){process.stdout.write(`
167
170
  Provider-backed sections skipped
168
- `);let t=`dataSources`in e?kc(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 Fc(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 Ic(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 Lc(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 ${Dc(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 ${Dc(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 ${Dc(t.projectId)}`:`--site ${Dc(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 ${Dc(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 ${Dc(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 Rc(e){e.length&&(process.stdout.write(`
171
+ `);let t=`dataSources`in e?Uc(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 Yc(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 Xc(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 Zc(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 ${Vc(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 ${Vc(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 ${Vc(t.projectId)}`:`--site ${Vc(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 ${Vc(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 ${Vc(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 Qc(e){e.length&&(process.stdout.write(`
169
172
  Recommended next commands
170
- `),z([`Command`,`Why`],e.map(e=>[e.command,e.why])))}function zc(e){process.stdout.write(`# Technical SEO report: ${e}\n\n`)}function Bc(e){return x({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:w(`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=M(t),r=e.printFollowups&&D(t.full),i=E(t),a=T(t.site),o=e.printFollowups?T(t.url):void 0,s=!!(i||a||!o),c=s?await H({client:i,site:a,options:{json:n,refresh:D(t.refresh)}}):void 0,l=c?.site??Oc(o??``),u=await Rt({site:l,days:O(t.days),recentDays:O(t.recent),limit:O(t.limit),brandTerms:c?.client?.brandTerms,includeBrand:D(t[`include-brand`]),refresh:D(t.refresh),skipSearchData:!s}),d=e.workflowName?{...u,workflow:e.workflowName}:u,f=e.printFollowups?await zt({site:l,searchSite:c?.site,url:o??c?.client?.startUrl??si(l),projectId:c?.client?.id,googleAnalyticsPropertyId:c?.client?.analytics.google?.propertyId,crawl:!Zn(t,`crawl`),refresh:D(t.refresh),maxPages:O(t[`crawl-max-pages`]),maxDepth:O(t[`crawl-max-depth`])}):void 0,p=f?Ac(f):void 0,m=e.printFollowups?Lc(d,{crawlStartUrl:o??c?.client?.startUrl??si(l),projectId:c?.client?.id,technicalBaselineStatus:f?.status,searchDataAvailable:s}):void 0;if(n){let t=e.printFollowups&&!r?Ec(u,e.workflowName):d,n=!s&&p?{...t,summary:Fc(p),steps:[Ic(p),...t.steps]}:t;L(p||m?{...n,...e.printFollowups?{detail:r?`full`:`summary`}:{},...p?{technicalCrawl:e.printFollowups&&!r?Mc(p):p}:{},...m?{nextCommands:m}:{}}:t);return}s?(process.stdout.write(`${d.output.narrative.markdown}\n\n`),zo(d)):zc(l),p&&(Nc(p,{providerFree:!s}),s||Pc(p)),m&&Rc(m)}})}const Vc=Bc({name:`diagnose-property`,description:`Find what changed in Google Search and what to inspect next`}),Hc=Bc({name:`report`,workflowName:`report`,printFollowups:!0,description:`Run the main SEO report and recommend the next best follow-up commands`}),Uc=x({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":w(`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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await Mt({site:n.site,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`]),googleAnalyticsPropertyId:T(e[`google-analytics-property`])??n.client?.analytics.google?.propertyId,verifyContent:D(e[`verify-content`]),verifyLimit:O(e[`verify-limit`]),refresh:D(e.refresh)});if(t){L(r);return}zo(r),z([`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})))}}),Wc=x({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":w(`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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=j(e.urls),i=j(e.sitemaps),a=T(e.url)??n.client?.startUrl??si(n.site),o=await Ie({site:n.site,startUrl:a,urls:r.length?r:n.client?.watchUrls,sitemaps:i.length?i:void 0,properties:j(e.properties).length?j(e.properties):void 0,limit:O(e.limit),languageCode:T(e.language),dailyLimit:O(e[`daily-limit`]),inspectLimit:O(e[`inspect-limit`]),maxUrls:O(e[`max-urls`]),refresh:D(e.refresh),js:D(e.js)?!0:`auto`,recoverLinks:D(e[`recover-links`]),recoverDays:O(e[`recover-days`]),recoverLimit:O(e[`recover-limit`]),recoverMinClicks:O(e[`recover-min-clicks`]),recoverMinImpressions:O(e[`recover-min-impressions`])});if(t){L(o);return}Bo(o)}});function Gc(e){return e===null?`-`:e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function Kc(e){return[...e.winners.map(e=>({direction:`winner`,item:e})),...e.losers.map(e=>({direction:`loser`,item:e}))]}function qc(e,t){let n=Kc(t);n.length&&(process.stdout.write(`\n${e}\n`),z([`Direction`,`Key`,`Clicks`,`Impr.`,`Position`],n.map(({direction:e,item:t})=>[e,t.key,Gc(t.clickDelta),Gc(t.impressionDelta),Gc(t.positionDelta)])))}function Jc(e){process.stdout.write(`
173
+ `),z([`Command`,`Why`],e.map(e=>[e.command,e.why])))}function $c(e){process.stdout.write(`# Technical SEO report: ${e}\n\n`)}function el(e){return x({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:w(`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=M(t),r=e.printFollowups&&D(t.full),i=E(t),a=T(t.site),o=e.printFollowups?T(t.url):void 0,s=!!(i||a||!o),c=s?await H({client:i,site:a,options:{json:n,refresh:D(t.refresh)}}):void 0,l=c?.site??Hc(o??``),u=await pe({site:l,days:O(t.days),recentDays:O(t.recent),limit:O(t.limit),brandTerms:c?.client?.brandTerms,includeBrand:D(t[`include-brand`]),refresh:D(t.refresh),skipSearchData:!s}),d=e.workflowName?{...u,workflow:e.workflowName}:u,f=e.printFollowups?await me({site:l,searchSite:c?.site,url:o??c?.client?.startUrl??gi(l),projectId:c?.client?.id,googleAnalyticsPropertyId:c?.client?.analytics.google?.propertyId,crawl:!or(t,`crawl`),refresh:D(t.refresh),maxPages:O(t[`crawl-max-pages`]),maxDepth:O(t[`crawl-max-depth`])}):void 0,p=f?Wc(f):void 0,m=e.printFollowups?Zc(d,{crawlStartUrl:o??c?.client?.startUrl??gi(l),projectId:c?.client?.id,technicalBaselineStatus:f?.status,searchDataAvailable:s}):void 0;if(n){let t=e.printFollowups&&!r?Bc(u,e.workflowName):d,n=!s&&p?{...t,summary:Yc(p),steps:[Xc(p),...t.steps]}:t;L(p||m?{...n,...e.printFollowups?{detail:r?`full`:`summary`}:{},...p?{technicalCrawl:e.printFollowups&&!r?Kc(p):p}:{},...m?{nextCommands:m}:{}}:t);return}s?(process.stdout.write(`${d.output.narrative.markdown}\n\n`),Jo(d)):$c(l),p&&(qc(p,{providerFree:!s}),s||Jc(p)),m&&Qc(m)}})}const tl=el({name:`diagnose-property`,description:`Find what changed in Google Search and what to inspect next`}),nl=el({name:`report`,workflowName:`report`,printFollowups:!0,description:`Run the main SEO report and recommend the next best follow-up commands`}),rl=x({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":w(`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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await c({site:n.site,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`]),googleAnalyticsPropertyId:T(e[`google-analytics-property`])??n.client?.analytics.google?.propertyId,verifyContent:D(e[`verify-content`]),verifyLimit:O(e[`verify-limit`]),refresh:D(e.refresh)});if(t){L(r);return}Jo(r),z([`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})))}}),il=x({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":w(`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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=j(e.urls),i=j(e.sitemaps),a=T(e.url)??n.client?.startUrl??gi(n.site),o=await u({site:n.site,startUrl:a,urls:r.length?r:n.client?.watchUrls,sitemaps:i.length?i:void 0,properties:j(e.properties).length?j(e.properties):void 0,limit:O(e.limit),languageCode:T(e.language),dailyLimit:O(e[`daily-limit`]),inspectLimit:O(e[`inspect-limit`]),maxUrls:O(e[`max-urls`]),refresh:D(e.refresh),js:D(e.js)?!0:`auto`,recoverLinks:D(e[`recover-links`]),recoverDays:O(e[`recover-days`]),recoverLimit:O(e[`recover-limit`]),recoverMinClicks:O(e[`recover-min-clicks`]),recoverMinImpressions:O(e[`recover-min-impressions`])});if(t){L(o);return}Yo(o)}});function al(e){return e===null?`-`:e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function ol(e){return[...e.winners.map(e=>({direction:`winner`,item:e})),...e.losers.map(e=>({direction:`loser`,item:e}))]}function sl(e,t){let n=ol(t);n.length&&(process.stdout.write(`\n${e}\n`),z([`Direction`,`Key`,`Clicks`,`Impr.`,`Position`],n.map(({direction:e,item:t})=>[e,t.key,al(t.clickDelta),al(t.impressionDelta),al(t.positionDelta)])))}function cl(e){process.stdout.write(`
171
174
  Segment coverage
172
- `),z([`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 Yc(e){e.length&&(process.stdout.write(`
175
+ `),z([`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 ll(e){e.length&&(process.stdout.write(`
173
176
  Template movement
174
- `),z([`Direction`,`Template`,`Pattern confidence`,`URLs`,`Clicks`,`Returned share`,`Common terms`],e.map(e=>[e.direction,e.signature,e.confidence,e.urlCount,Gc(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 Xc=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await Ze({site:n.site,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`]),knownConfounders:T(e[`known-change`])?[T(e[`known-change`])??``]:void 0,includeChangeLog:!D(e[`ignore-change-log`]),refresh:D(e.refresh)});if(t){L(r);return}R([[`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)),Yc(r.output.templateMovement),Y(`Update evidence`,r.output.update.evidence),Jc(r.output.segments),qc(`Page winners and losers`,r.output.segments.page),qc(`Query winners and losers`,r.output.segments.query),qc(`Device winners and losers`,r.output.segments.device),qc(`Country winners and losers`,r.output.segments.country),Wr(`seo export update-postmortem ${n.client?`--project ${JSON.stringify(n.client.id)}`:`--site ${JSON.stringify(n.site)}`}`)}});function Zc(e){return e.replaceAll(`\\`,`/`).toLowerCase()}function Qc(e,t){return t===`win32`?`${e}.cmd`:e}function $c(e,t=process.platform){let n=Zc(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:Qc(`pnpm`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.bun/install/global/`))return{command:Qc(`bun`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.config/yarn/global/`))return{command:Qc(`yarn`,t),args:[`global`,`add`,`seo@latest`]};if(n.includes(`/node_modules/seo/`))return{command:Qc(`npm`,t),args:[`install`,`--global`,`seo@latest`]}}}function el(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 tl(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 nl(e){if(e)try{return qt(e)}catch{return e}}async function rl(e){let t=await jn({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 En(t)?`later`:t}function il(e){return ln(e.command,e.args,{stdio:`inherit`}).status}async function al(e,t={}){if(!tl({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=nl(t.cliPath??process.argv[1]),r=n?$c(n,t.platform??process.platform):void 0;if(!r)return;let i=(t.createNotifier??(e=>Bn({pkg:e,shouldNotifyInNpmScript:!1})))(e).update;if(!(!i||!el(i.current,i.latest))&&await(t.prompt??rl)({command:r,update:i})!==`later`)return(t.run??il)(r)===0?(Dn.success(`Updated seo to ${i.latest}. Run your command again.`),0):(Dn.error(`The update failed. Your current version is unchanged.`),1)}const ol={name:`seo`,version:Ue},sl=[{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`]]}],cl=[...sl,{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`,`Crawl a site for technical SEO issues`],[`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 reset`,`Delete local SEO data`]]}];function ll(e){jr(`seo v${ol.version}`,`Run SEO audits, find what needs fixing, and ship the changes with your agent.`),process.stdout.write(`
175
- `),Nr(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(`
176
- `),Fr(`More help`,"Use `seo help <command>` or `seo <command> --help` for command help.","Use `seo help all` for the longer command list.")}const ul=x({meta:{name:`seo`,version:ol.version,description:`Local-first SEO CLI and MCP server`},subCommands:{init:ko,analytics:$r,llms:Mo,auth:ii,mcp:Fo,okf:Xo,doctor:hs,privacy:_c,reset:vc,cache:ai,crawl:la,"crawl-queue":xc,"crawl-reports":wa,client:aa,content:sa,project:oa,projects:oa,"change-log":Ia,tests:Ja,"content-groups":za,"crawl-diff":Io,diagnose:ms,"diagnose-property":Vc,export:Oo,"index-coverage":Go,"index-watch":Ko,"link-recover":qo,"monthly-report":Ps,monitoring:Wo,"report-narrative":Fs,rules:Is,explain:Ls,"refresh-priorities":Uc,"redirect-trace":Jo,schedule:zs,skill:gc,start:Zi,setup:Xi,report:Hc,reports:Ns,"segment-impact":_s,"striking-distance":ys,"technical-watch":Wc,"update-postmortem":Xc,sites:yc,"gsc-query":Ta,"url-inspect":Ea,updates:bc,"traffic-anomaly":Aa,"update-correlate":ja,"ai-referrals":Zo,"agent-readiness":Xr,"ai-readiness":qr,"entity-readiness":Na,"audit-page":ls,"second-page":ss,cannibal:Qo,"community-intent":$o,decaying:ns,"quick-wins":os,"page-opportunities":is,perf:ps,"internal-links":rs,"ctr-underperformers":es,"query-cluster":as,"seo-to-ai-query":cs,pseo:Ds},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")}}),$=process.argv.slice(2),dl=await al(ol,{argv:$});dl!==void 0&&process.exit(dl),($.length===0||$.length===1&&[`help`,`--help`,`-h`].includes($[0]??``))&&(ll(sl),process.exit(0)),$[0]===`help`&&$[1]===`all`&&(ll(cl),process.exit(0));const fl=$[0]===`help`&&$.length>1?[...$.slice(1),`--help`]:$;fl!==$&&(process.argv=[process.argv[0]??`node`,process.argv[1]??`seo`,...fl]);const pl=fl.some(e=>[`--help`,`-h`].includes(e)),ml=$.length===1&&[`--version`,`-v`].includes($[0]??``);if(pl||ml)await Sn(ul);else try{await xn(ul,{rawArgs:fl})}catch(e){let t=At(e);$.includes(`--json`)?process.stdout.write(`${JSON.stringify(lt(t),null,2)}\n`):process.stderr.write(`Error: ${t.message}\n`),process.exitCode=t.exitCode}export{};
177
+ `),z([`Direction`,`Template`,`Pattern confidence`,`URLs`,`Clicks`,`Returned share`,`Common terms`],e.map(e=>[e.direction,e.signature,e.confidence,e.urlCount,al(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 ul=x({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=M(e),n=await H({client:E(e),site:T(e.site),options:{json:t,refresh:D(e.refresh)}}),r=await Ce({site:n.site,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),brandTerms:n.client?.brandTerms,includeBrand:D(e[`include-brand`]),knownConfounders:T(e[`known-change`])?[T(e[`known-change`])??``]:void 0,includeChangeLog:!D(e[`ignore-change-log`]),refresh:D(e.refresh)});if(t){L(r);return}R([[`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)),ll(r.output.templateMovement),Y(`Update evidence`,r.output.update.evidence),cl(r.output.segments),sl(`Page winners and losers`,r.output.segments.page),sl(`Query winners and losers`,r.output.segments.query),sl(`Device winners and losers`,r.output.segments.device),sl(`Country winners and losers`,r.output.segments.country),$r(`seo export update-postmortem ${n.client?`--project ${JSON.stringify(n.client.id)}`:`--site ${JSON.stringify(n.site)}`}`)}});function dl(e){return e.replaceAll(`\\`,`/`).toLowerCase()}function fl(e,t){return t===`win32`?`${e}.cmd`:e}function pl(e,t=process.platform){let n=dl(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:fl(`pnpm`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.bun/install/global/`))return{command:fl(`bun`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.config/yarn/global/`))return{command:fl(`yarn`,t),args:[`global`,`add`,`seo@latest`]};if(n.includes(`/node_modules/seo/`))return{command:fl(`npm`,t),args:[`install`,`--global`,`seo@latest`]}}}function ml(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 hl(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 gl(e){if(e)try{return rn(e)}catch{return e}}async function _l(e){let t=await Bn({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 Fn(t)?`later`:t}function vl(e){return vn(e.command,e.args,{stdio:`inherit`}).status}async function yl(e,t={}){if(!hl({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=gl(t.cliPath??process.argv[1]),r=n?pl(n,t.platform??process.platform):void 0;if(!r)return;let i=(t.createNotifier??(e=>Yn({pkg:e,shouldNotifyInNpmScript:!1})))(e).update;if(!(!i||!ml(i.current,i.latest))&&await(t.prompt??_l)({command:r,update:i})!==`later`)return(t.run??vl)(r)===0?(In.success(`Updated seo to ${i.latest}. Run your command again.`),0):(In.error(`The update failed. Your current version is unchanged.`),1)}const bl={name:`seo`,version:Le},xl=[{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`]]}],Sl=[...xl,{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`,`Crawl a site for technical SEO issues`],[`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 Cl(e){Br(`seo v${bl.version}`,`Run SEO audits, find what needs fixing, and ship the changes with your agent.`),process.stdout.write(`
178
+ `),Hr(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(`
179
+ `),Wr(`More help`,"Use `seo help <command>` or `seo <command> --help` for command help.","Use `seo help all` for the longer command list.")}const wl=x({meta:{name:`seo`,version:bl.version,description:`Local-first SEO CLI and MCP server`},subCommands:{init:Ro,analytics:ci,llms:Vo,auth:pi,mcp:Wo,okf:as,doctor:ws,privacy:Ec,telemetry:Pc,reset:Dc,cache:mi,crawl:va,"crawl-queue":Fc,"crawl-reports":Na,client:ma,content:ga,project:ha,projects:ha,"change-log":Ga,tests:ro,"content-groups":Ja,"crawl-diff":Go,diagnose:Cs,"diagnose-property":tl,export:Lo,"index-coverage":es,"index-watch":ts,"link-recover":ns,"monthly-report":Us,monitoring:$o,"report-narrative":Ws,rules:Gs,explain:Ks,"refresh-priorities":rl,"redirect-trace":rs,schedule:Js,skill:Tc,start:oa,setup:aa,report:nl,reports:Hs,"segment-impact":Es,"striking-distance":Os,"technical-watch":il,"update-postmortem":ul,sites:Oc,"gsc-query":Pa,"url-inspect":Fa,updates:kc,"traffic-anomaly":za,"update-correlate":Ba,"ai-referrals":os,"agent-readiness":ai,"ai-readiness":ni,"entity-readiness":Ha,"audit-page":vs,"second-page":gs,cannibal:ss,"community-intent":cs,decaying:ds,"quick-wins":hs,"page-opportunities":ps,perf:Ss,"internal-links":fs,"ctr-underperformers":ls,"query-cluster":ms,"seo-to-ai-query":_s,pseo:Is},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")}}),Tl={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`},El=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`]),Dl=new Set(ze().map(e=>e.id));function Ol(e){let[t,n,r]=e;if(t)return t===`reports`&&n===`run`?r&&Dl.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`:Tl[t]??(El.has(t)?t:void 0)}const $=process.argv.slice(2),kl={agent:We()},Al=$[0]===`telemetry`,jl=$[0]===`mcp`&&$[1]===`serve`;!Al&&!jl&&Lt(kl);const Ml=await yl(bl,{argv:$});Ml!==void 0&&process.exit(Ml),($.length===0||$.length===1&&[`help`,`--help`,`-h`].includes($[0]??``))&&(Cl(xl),process.exit(0)),$[0]===`help`&&$[1]===`all`&&(Cl(Sl),process.exit(0));const Nl=$[0]===`help`&&$.length>1?[...$.slice(1),`--help`]:$;Nl!==$&&(process.argv=[process.argv[0]??`node`,process.argv[1]??`seo`,...Nl]);const Pl=Nl.some(e=>[`--help`,`-h`].includes(e)),Fl=$.length===1&&[`--version`,`-v`].includes($[0]??``),Il=Pl||Fl?void 0:Ol(Nl);if(Pl||Fl)await jn(wl);else{Il&&it(Il,kl);try{await An(wl,{rawArgs:Nl}),Il&&wt(Il,kl),[`init`,`setup`,`start`].includes(Nl[0]??``)&&!Nl.includes(`--dry-run`)&&tt(kl)}catch(e){Il&&_t(Il,Qe(e),kl);let t=Jt(e);$.includes(`--json`)?process.stdout.write(`${JSON.stringify(Vt(t),null,2)}\n`):process.stderr.write(`Error: ${t.message}\n`),process.exitCode=t.exitCode}}export{};
177
180
  //# sourceMappingURL=cli.js.map