seo 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,126 +1,128 @@
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,An as r,At as i,B as a,Bt as o,C as s,Cn as c,Ct as l,D as u,Dn as d,Dt as f,E as ee,En as te,Et as p,F as ne,Ft as m,G as h,Gt as re,H as ie,Ht as ae,I as oe,It as se,J as ce,Jt as le,K as ue,Kt as de,L as fe,Lt as pe,M as me,Mt as he,N as ge,Nt as _e,O as ve,On as ye,Ot as be,P as xe,Pt as Se,Q as Ce,Qt as we,R as Te,Rt as Ee,S as De,Sn as Oe,St as ke,T as Ae,Tn as je,Tt as Me,U as Ne,Ut as Pe,V as Fe,Vt as Ie,W as Le,Wt as Re,X as ze,Xt as Be,Y as Ve,Yt as He,Z as Ue,Zt as We,_ as Ge,_n as Ke,_t as qe,a as Je,an as Ye,at as Xe,b as Ze,bn as Qe,bt as $e,c as et,cn as tt,ct as nt,d as rt,dn as it,dt as at,en as ot,et as st,f as ct,fn as lt,ft as ut,g as dt,gn as ft,gt as pt,h as mt,hn as ht,ht as gt,i as _t,in as vt,it as yt,j as bt,jn as xt,jt as St,k as Ct,kn as wt,kt as Tt,l as Et,ln as Dt,lt as Ot,m as kt,mn as At,mt as jt,nn as Mt,nt as Nt,o as Pt,on as Ft,ot as It,p as Lt,pn as Rt,pt as zt,q as Bt,qt as Vt,rn as Ht,rt as Ut,sn as Wt,st as Gt,t as Kt,tn as qt,tt as Jt,u as Yt,un as Xt,ut as Zt,v as Qt,vn as $t,vt as en,w as tn,wn as nn,wt as rn,x as an,xn as on,xt as sn,y as cn,yn as ln,yt as un,z as dn,zt as fn}from"./dist-DV2Z-HIp.js";import{constants as pn,copyFileSync as mn,createWriteStream as hn,existsSync as g,mkdirSync as gn,readFileSync as _n,readdirSync as vn,realpathSync as yn,renameSync as bn,statSync as xn,writeFileSync as Sn}from"node:fs";import{arch as Cn,homedir as wn,platform as Tn}from"node:os";import{basename as En,dirname as Dn,join as _,posix as On,resolve as kn,win32 as An}from"node:path";import{fileURLToPath as jn}from"node:url";import{mkdir as Mn,readFile as Nn,writeFile as Pn}from"node:fs/promises";import{isDeepStrictEqual as Fn,stripVTControlCharacters as In}from"node:util";import{spawn as Ln,spawnSync as Rn}from"node:child_process";import{defineCommand as v,runCommand as zn,runMain as Bn}from"citty";import{cancel as Vn,confirm as Hn,intro as y,isCancel as Un,log as Wn,multiselect as Gn,note as b,outro as x,password as Kn,select as qn,text as Jn}from"@clack/prompts";import Yn from"picocolors";import Xn from"string-width";import Zn from"cli-table3";import{finished as Qn}from"node:stream/promises";import{applyEdits as $n,modify as er,parse as tr,printParseErrorCode as nr}from"jsonc-parser";import rr from"update-notifier";const S={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 ir(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 ar(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 or(e){return[{filename:`postmortem-summary.csv`,headers:[...S.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:[...S.steps],rows:e.steps.map((e,t)=>({rank:t+1,tool:e.tool,status:e.status,summary:e.summary}))},{filename:`workflow-actions.csv`,headers:[...S.actions],rows:e.actions.map((e,t)=>({rank:t+1,title:e.title,confidence:e.confidence,action:e.action}))},{filename:`postmortem-findings.csv`,headers:[...S.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:[...S.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:[...S.evidence],rows:e.output.update.evidence.map((e,t)=>({rank:t+1,evidence:e}))},{filename:`postmortem-confounders.csv`,headers:[...S.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:[...S.segment],rows:ir(e,t)})),...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}-unmatched.csv`,headers:[...S.unmatchedSegment],rows:ar(e,t)}))]}function sr(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 cr(e,t){return{type:`boolean`,default:!0,description:e,negativeDescription:t}}function C(e){return typeof e==`string`?e:void 0}function w(e){return typeof e==`boolean`?e:void 0}function lr(e){let t=C(e.rendering);if(t!==void 0&&t!==`auto`&&t!==`on`&&t!==`off`)throw new d(`INVALID_INPUT`,`--rendering must be auto, on, or off.`);if(w(e.js)===!0&&t&&t!==`on`)throw new d(`INVALID_INPUT`,`Use either --js or --rendering on, not both with different modes.`);return t??(w(e.js)?`on`:`auto`)}function T(e,t){let n=w(e[t]);if(n===!1)return!0;if(n===!0)return!1;let r=w(e[ur(t)]);if(r===!1)return!0;if(r===!0)return!1;if(w(e[`no-${t}`])===!0||w(e[`no${dr(t)}`])===!0)return!0}function ur(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function dr(e){let t=ur(e);return t?`${t[0]?.toUpperCase()}${t.slice(1)}`:``}function E(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 D(e,t){if(e===void 0||e===``)return;let n=E(e);if(n===void 0)throw new d(`INVALID_INPUT`,`${t} must be a number.`);return n}function O(e){if(typeof e!=`string`)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length?t:void 0}function fr(e){return O(e)??[]}function pr(e){let t={concurrency:E(e[`fetch-concurrency`]),intervalCap:E(e[`fetch-interval-cap`]),intervalMs:E(e[`fetch-interval-ms`])};return Object.values(t).some(e=>e!==void 0)?t:void 0}function mr(e){let t={concurrency:D(e[`fetch-concurrency`],`--fetch-concurrency`),intervalCap:D(e[`fetch-interval-cap`],`--fetch-interval-cap`),intervalMs:D(e[`fetch-interval-ms`],`--fetch-interval-ms`)};return Object.values(t).some(e=>e!==void 0)?t:void 0}function k(e){return e.json===!0}async function hr(e,t){let n=C(e),r=C(t);if(n&&r)throw Error(`Use either --body or --body-file, not both.`);if(!n&&!r)return;let i=n??await Nn(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 gr(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 _r(e={}){let t=e.env??process.env,n=gr(e.columns)??gr(e.streamColumns)??gr(t.COLUMNS)??80;return Math.min(200,Math.max(40,n))}function A(e={}){let t=e.env??process.env,n=e.isTTY??!!process.stdout.isTTY,r=e.color??!!(n&&t.NO_COLOR===void 0);return{columns:_r({...e,env:t,streamColumns:e.streamColumns??process.stdout.columns}),colors:Yn.createColors(r),hasColor:r,isInteractive:n&&!t.CI}}function j(e){return Xn(In(e))}function vr(e,t){let n=[],r=``;for(let i of e)r&&j(`${r}${i}`)>t?(n.push(r),r=i):r+=i;return r&&n.push(r),n}function yr(e,t){if(!e)return[``];let n=e.trim().split(/\s+/u),r=[],i=``;for(let e of n){let n=j(e)>t?vr(e,t):[e];for(let e of n)i?j(`${i} ${e}`)<=t?i+=` ${e}`:(r.push(i),i=e):i=e}return i&&r.push(i),r.length>0?r:[``]}function M(e,t){let n=Math.max(1,t);return e.replaceAll(`\r
3
+ import{$ as e,$t as t,A as n,An as r,At as i,B as a,Bt as o,C as s,Cn as c,Ct as l,D as u,Dn as d,Dt as ee,E as te,En as ne,Et as f,F as re,Fn as p,Ft as m,G as h,Gt as ie,H as ae,Ht as oe,I as se,In as ce,It as le,J as ue,Jt as de,K as fe,Kt as pe,L as me,Ln as he,Lt as ge,M as _e,Mn as ve,Mt as ye,N as be,Nn as xe,Nt as Se,O as Ce,On as we,Ot as Te,P as Ee,Pn as De,Pt as Oe,Q as ke,Qt as Ae,R as je,Rn as Me,Rt as Ne,S as Pe,Sn as Fe,St as Ie,T as Le,Tn as Re,Tt as ze,U as Be,Ut as Ve,V as He,Vt as Ue,W as We,Wt as Ge,X as Ke,Xt as qe,Y as Je,Yt as Ye,Z as Xe,Zt as Ze,_ as Qe,_n as $e,_t as et,a as tt,an as nt,at as rt,b as it,bn as at,bt as ot,c as st,cn as ct,ct as lt,d as ut,dn as dt,dt as ft,en as pt,et as mt,f as ht,fn as gt,ft as _t,g as vt,gn as yt,gt as bt,h as xt,hn as St,ht as Ct,i as wt,in as Tt,it as Et,j as Dt,jn as Ot,jt as kt,k as At,kn as jt,kt as Mt,l as Nt,ln as Pt,lt as Ft,m as It,mn as Lt,mt as Rt,nn as zt,nt as Bt,o as Vt,on as Ht,ot as Ut,p as Wt,pn as Gt,pt as Kt,q as qt,qt as Jt,rn as Yt,rt as Xt,sn as Zt,st as Qt,t as $t,tn as en,tt as tn,u as nn,un as rn,ut as an,v as on,vn as sn,vt as cn,w as ln,wn as un,wt as dn,x as fn,xn as pn,xt as mn,y as hn,yn as gn,yt as _n,z as vn,zn as yn,zt as bn}from"./dist-CN4VawW-.js";import{arch as xn,homedir as Sn,platform as Cn}from"node:os";import{basename as wn,dirname as Tn,join as g,posix as En,resolve as Dn,win32 as On}from"node:path";import{constants as kn,copyFileSync as An,createWriteStream as jn,existsSync as _,mkdirSync as Mn,readFileSync as Nn,readdirSync as Pn,realpathSync as Fn,renameSync as In,statSync as Ln,writeFileSync as Rn}from"node:fs";import{fileURLToPath as zn}from"node:url";import{mkdir as Bn,readFile as Vn,writeFile as Hn}from"node:fs/promises";import{isDeepStrictEqual as Un,stripVTControlCharacters as Wn}from"node:util";import{spawn as Gn,spawnSync as Kn}from"node:child_process";import{defineCommand as v,runCommand as qn,runMain as Jn}from"citty";import{cancel as Yn,confirm as Xn,intro as y,isCancel as Zn,log as Qn,multiselect as $n,note as b,outro as x,password as S,select as er,text as tr}from"@clack/prompts";import nr from"picocolors";import rr from"string-width";import ir from"cli-table3";import{finished as ar}from"node:stream/promises";import{applyEdits as or,modify as sr,parse as cr,printParseErrorCode as lr}from"jsonc-parser";import ur 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 dr(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 fr(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 pr(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:dr(e,t)})),...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}-unmatched.csv`,headers:[...C.unmatchedSegment],rows:fr(e,t)}))]}function mr(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 hr(e,t){return{type:`boolean`,default:!0,description:e,negativeDescription:t}}function w(e){return typeof e==`string`?e:void 0}function T(e){return typeof e==`boolean`?e:void 0}function gr(e){let t=w(e.rendering);if(t!==void 0&&t!==`auto`&&t!==`on`&&t!==`off`)throw new p(`INVALID_INPUT`,`--rendering must be auto, on, or off.`);if(T(e.js)===!0&&t&&t!==`on`)throw new p(`INVALID_INPUT`,`Use either --js or --rendering on, not both with different modes.`);return t??(T(e.js)?`on`:`auto`)}function _r(e,t){let n=T(e[t]);if(n===!1)return!0;if(n===!0)return!1;let r=T(e[vr(t)]);if(r===!1)return!0;if(r===!0)return!1;if(T(e[`no-${t}`])===!0||T(e[`no${yr(t)}`])===!0)return!0}function vr(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function yr(e){let t=vr(e);return t?`${t[0]?.toUpperCase()}${t.slice(1)}`:``}function E(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 D(e,t){if(e===void 0||e===``)return;let n=E(e);if(n===void 0)throw new p(`INVALID_INPUT`,`${t} must be a number.`);return n}function O(e){if(typeof e!=`string`)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length?t:void 0}function br(e){return O(e)??[]}function xr(e){let t={concurrency:E(e[`fetch-concurrency`]),intervalCap:E(e[`fetch-interval-cap`]),intervalMs:E(e[`fetch-interval-ms`])};return Object.values(t).some(e=>e!==void 0)?t:void 0}function Sr(e){let t={concurrency:D(e[`fetch-concurrency`],`--fetch-concurrency`),intervalCap:D(e[`fetch-interval-cap`],`--fetch-interval-cap`),intervalMs:D(e[`fetch-interval-ms`],`--fetch-interval-ms`)};return Object.values(t).some(e=>e!==void 0)?t:void 0}function k(e){return e.json===!0}async function Cr(e,t){let n=w(e),r=w(t);if(n&&r)throw Error(`Use either --body or --body-file, not both.`);if(!n&&!r)return;let i=n??await Vn(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 wr(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 Tr(e={}){let t=e.env??process.env,n=wr(e.columns)??wr(e.streamColumns)??wr(t.COLUMNS)??80;return Math.min(200,Math.max(40,n))}function A(e={}){let t=e.env??process.env,n=e.isTTY??!!process.stdout.isTTY,r=e.color??!!(n&&t.NO_COLOR===void 0);return{columns:Tr({...e,env:t,streamColumns:e.streamColumns??process.stdout.columns}),colors:nr.createColors(r),hasColor:r,isInteractive:n&&!t.CI}}function j(e){return rr(Wn(e))}function Er(e,t){let n=[],r=``;for(let i of e)r&&j(`${r}${i}`)>t?(n.push(r),r=i):r+=i;return r&&n.push(r),n}function Dr(e,t){if(!e)return[``];let n=e.trim().split(/\s+/u),r=[],i=``;for(let e of n){let n=j(e)>t?Er(e,t):[e];for(let e of n)i?j(`${i} ${e}`)<=t?i+=` ${e}`:(r.push(i),i=e):i=e}return i&&r.push(i),r.length>0?r:[``]}function M(e,t){let n=Math.max(1,t);return e.replaceAll(`\r
4
4
  `,`
5
5
  `).split(`
6
- `).flatMap(e=>yr(e,n))}function br(e,t){if(j(e)<=t)return e;let n=Math.max(1,t-j(`...`)),r=``;for(let t of e){if(j(`${r}${t}`)>n)break;r+=t}return`${r}...`}const xr={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 Sr(e){return e===void 0?``:String(e)}function Cr(e,t){return e.map((e,n)=>{let r=t.map(e=>Sr(e[n]));return Math.min(42,Math.max(j(e),...r.map(j),4))})}function wr(e,t,n){return e.length===0||e.length>4||!e.map((e,n)=>t.every(e=>/^-?(?:\d+(?:\.\d+)?|\d+(?:\.\d+)?%)$/u.test(Sr(e[n]).trim()))).some(Boolean)?!1:Cr(e,t).reduce((e,t)=>e+t+2,0)<=n.columns}function Tr(e,t,n){if(!/(?:status|state|assessment|data|allowed)/iu.test(e))return t;let r=t.trim().toLowerCase();return[`pass`,`passed`,`completed`,`allowed`,`yes`].includes(r)?n.colors.green(t):[`warn`,`warning`,`review`,`partial`].includes(r)?n.colors.yellow(t):[`fail`,`failed`,`blocked`,`no`].includes(r)?n.colors.red(t):[`unknown`,`unavailable`].includes(r)?n.colors.blue(t):t}function Er(e,t,n){let r=Cr(e,t).map(e=>e+2),i=new Zn({chars:xr,colWidths:r,head:e.map(e=>n.colors.bold(e)),style:{border:[],head:[],"padding-left":0,"padding-right":2},wordWrap:!1});for(let a of t)i.push(e.map((e,t)=>M(Tr(e,Sr(a[t]),n),Math.max(1,(r[t]??3)-2)).join(`
7
- `)));return i.toString()}function Dr(e,t,n,r){let i=r.columns-n-2;return i<24?[r.colors.dim(e),...M(t,r.columns-2).map(e=>` ${e}`)]:M(t,i).map((t,i)=>{let a=i===0?e.padEnd(n):``.padEnd(n);return`${r.colors.dim(a)}${` `.repeat(2)}${t}`})}function Or(e,t,n,r={}){let i=Math.min(28,Math.max(...e.map(e=>j(e)),0)),a=r.rowNumbers??!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(...Dr(a,Tr(a,Sr(t[r]),n),i,n));return s.join(`
6
+ `).flatMap(e=>Dr(e,n))}function Or(e,t){if(j(e)<=t)return e;let n=Math.max(1,t-j(`...`)),r=``;for(let t of e){if(j(`${r}${t}`)>n)break;r+=t}return`${r}...`}const kr={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 Ar(e){return e===void 0?``:String(e)}function jr(e,t){return e.map((e,n)=>{let r=t.map(e=>Ar(e[n]));return Math.min(42,Math.max(j(e),...r.map(j),4))})}function Mr(e,t,n){return e.length===0||e.length>4||!e.map((e,n)=>t.every(e=>/^-?(?:\d+(?:\.\d+)?|\d+(?:\.\d+)?%)$/u.test(Ar(e[n]).trim()))).some(Boolean)?!1:jr(e,t).reduce((e,t)=>e+t+2,0)<=n.columns}function Nr(e,t,n){if(!/(?:status|state|assessment|data|allowed)/iu.test(e))return t;let r=t.trim().toLowerCase();return[`pass`,`passed`,`completed`,`allowed`,`yes`].includes(r)?n.colors.green(t):[`warn`,`warning`,`review`,`partial`].includes(r)?n.colors.yellow(t):[`fail`,`failed`,`blocked`,`no`].includes(r)?n.colors.red(t):[`unknown`,`unavailable`].includes(r)?n.colors.blue(t):t}function Pr(e,t,n){let r=jr(e,t).map(e=>e+2),i=new ir({chars:kr,colWidths:r,head:e.map(e=>n.colors.bold(e)),style:{border:[],head:[],"padding-left":0,"padding-right":2},wordWrap:!1});for(let a of t)i.push(e.map((e,t)=>M(Nr(e,Ar(a[t]),n),Math.max(1,(r[t]??3)-2)).join(`
7
+ `)));return i.toString()}function Fr(e,t,n,r){let i=r.columns-n-2;return i<24?[r.colors.dim(e),...M(t,r.columns-2).map(e=>` ${e}`)]:M(t,i).map((t,i)=>{let a=i===0?e.padEnd(n):``.padEnd(n);return`${r.colors.dim(a)}${` `.repeat(2)}${t}`})}function Ir(e,t,n,r={}){let i=Math.min(28,Math.max(...e.map(e=>j(e)),0)),a=r.rowNumbers??!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(...Fr(a,Nr(a,Ar(t[r]),n),i,n));return s.join(`
8
8
  `)}).join(`
9
9
 
10
- `)}function kr(e,t,n,r={}){return t.length===0?n.colors.dim(`No results.`):r.layout===`table`||r.layout!==`records`&&wr(e,t,n)?Er(e,t,n):Or(e,t,n,r)}function Ar(e,t){if(e.length===0)return``;let n=Math.min(28,Math.max(...e.map(([e])=>j(e))));return e.flatMap(([e,r])=>{let i=Dr(e,r,n,t);return i.length>0&&(i[0]=(i[0]??``).replace(e,t.colors.bold(e))),i}).join(`
11
- `)}function jr(e,t){let n=[t.colors.bold(e.title)];return e.body&&n.push(...M(e.body,t.columns)),e.command&&n.push(t.colors.cyan(br(e.command,t.columns))),n.join(`
12
- `)}function Mr(e,t){return e===`pass`?t.colors.green:e===`warning`?t.colors.yellow:e===`fail`?t.colors.red:e===`unknown`?t.colors.blue:e===`info`?t.colors.cyan:t.colors.dim}function Nr(e){return e===`warning`?`WARN`:e===`notApplicable`?`N/A`:e.toUpperCase()}function Pr(e,t,n){let r=` `.repeat(t);return M(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function Fr(e,t){let n=Mr(e.status,t)(`[${Nr(e.status)}]`.padEnd(10)),r=Math.max(1,t.columns-10),i=M(e.title,r).map((e,r)=>`${r===0?n:` `.repeat(10)}${t.colors.bold(e)}`);i.push(...Pr(e.explanation,10,t.columns));for(let n of e.evidence??[]){let e=M(n,Math.max(1,t.columns-20));i.push(...e.map((e,n)=>`${` `.repeat(10)}${n===0?`${t.colors.dim(`Evidence`)} `:` `}${e}`))}if(e.fix){let n=M(e.fix,Math.max(1,t.columns-15));i.push(...n.map((e,n)=>`${` `.repeat(10)}${n===0?`${t.colors.cyan(t.colors.bold(`Fix`))} `:` `}${e}`))}return i.join(`
13
- `)}function Ir(e,t){return M(e.map(e=>{let n=String(e.value),r=e.status?Mr(e.status,t)(n):t.colors.bold(n);return`${e.label} ${r}`}).join(t.colors.dim(` · `)),t.columns).join(`
14
- `)}function Lr(e,t){let n=Mr(e.status,t),r=[t.colors.bold(e.title)];e.target&&r.push(t.colors.dim(e.target)),r.push(``),r.push(`${n(Nr(e.status))} ${M(e.summary,Math.max(1,t.columns-6)).join(`
15
- `)}`),e.metrics?.length&&r.push(Ir(e.metrics,t));for(let n of e.sections.filter(e=>e.diagnostics.length>0))r.push(``,t.colors.bold(n.title)),r.push(n.diagnostics.map(e=>Fr(e,t)).join(`
10
+ `)}function Lr(e,t,n,r={}){return t.length===0?n.colors.dim(`No results.`):r.layout===`table`||r.layout!==`records`&&Mr(e,t,n)?Pr(e,t,n):Ir(e,t,n,r)}function Rr(e,t){if(e.length===0)return``;let n=Math.min(28,Math.max(...e.map(([e])=>j(e))));return e.flatMap(([e,r])=>{let i=Fr(e,r,n,t);return i.length>0&&(i[0]=(i[0]??``).replace(e,t.colors.bold(e))),i}).join(`
11
+ `)}function zr(e,t){let n=[t.colors.bold(e.title)];return e.body&&n.push(...M(e.body,t.columns)),e.command&&n.push(t.colors.cyan(Or(e.command,t.columns))),n.join(`
12
+ `)}function Br(e,t){return e===`pass`?t.colors.green:e===`warning`?t.colors.yellow:e===`fail`?t.colors.red:e===`unknown`?t.colors.blue:e===`info`?t.colors.cyan:t.colors.dim}function Vr(e){return e===`warning`?`WARN`:e===`notApplicable`?`N/A`:e.toUpperCase()}function Hr(e,t,n){let r=` `.repeat(t);return M(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function Ur(e,t){let n=Br(e.status,t)(`[${Vr(e.status)}]`.padEnd(10)),r=Math.max(1,t.columns-10),i=M(e.title,r).map((e,r)=>`${r===0?n:` `.repeat(10)}${t.colors.bold(e)}`);i.push(...Hr(e.explanation,10,t.columns));for(let n of e.evidence??[]){let e=M(n,Math.max(1,t.columns-20));i.push(...e.map((e,n)=>`${` `.repeat(10)}${n===0?`${t.colors.dim(`Evidence`)} `:` `}${e}`))}if(e.fix){let n=M(e.fix,Math.max(1,t.columns-15));i.push(...n.map((e,n)=>`${` `.repeat(10)}${n===0?`${t.colors.cyan(t.colors.bold(`Fix`))} `:` `}${e}`))}return i.join(`
13
+ `)}function Wr(e,t){return M(e.map(e=>{let n=String(e.value),r=e.status?Br(e.status,t)(n):t.colors.bold(n);return`${e.label} ${r}`}).join(t.colors.dim(` · `)),t.columns).join(`
14
+ `)}function Gr(e,t){let n=Br(e.status,t),r=[t.colors.bold(e.title)];e.target&&r.push(t.colors.dim(e.target)),r.push(``),r.push(`${n(Vr(e.status))} ${M(e.summary,Math.max(1,t.columns-6)).join(`
15
+ `)}`),e.metrics?.length&&r.push(Wr(e.metrics,t));for(let n of e.sections.filter(e=>e.diagnostics.length>0))r.push(``,t.colors.bold(n.title)),r.push(n.diagnostics.map(e=>Ur(e,t)).join(`
16
16
 
17
17
  `));if(e.notes?.length){r.push(``,t.colors.bold(`Notes`));for(let n of e.notes){let e=M(n,Math.max(1,t.columns-2));r.push(...e.map((e,t)=>`${t===0?`- `:` `}${e}`))}}return r.join(`
18
- `)}function Rr(e,t,n=`${t}s`){return e===1?t:n}function zr(e,t,n){let r=` `.repeat(t);return M(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function Br(e,t,n){return[t.colors.bold(e),...n?M(n,t.columns):[]].join(`
19
- `)}function Vr(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(...zr(e.detail,6,t.columns)),e.fix){let n=M(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(`
18
+ `)}function Kr(e,t,n=`${t}s`){return e===1?t:n}function qr(e,t,n){let r=` `.repeat(t);return M(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function Jr(e,t,n){return[t.colors.bold(e),...n?M(n,t.columns):[]].join(`
19
+ `)}function Yr(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(...qr(e.detail,6,t.columns)),e.fix){let n=M(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(`
20
20
  `)}).join(`
21
21
 
22
- `)}function Hr(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} ${Rr(t,`check`)} passed, ${n} ${Rr(n,`warning`)}, ${r} failed.`}function Ur(e,t,n){let r=n.columns-t-2-2;return r<24||j(e.id)>t?[...zr(e.id,2,n.columns).map(e=>n.colors.cyan(e)),...zr(e.name,4,n.columns)].join(`
22
+ `)}function Xr(e){let t=e.filter(e=>e.status===`pass`).length,n=e.filter(e=>e.status===`warn`).length,r=e.filter(e=>e.status===`fail`).length;return`${t} ${Kr(t,`check`)} passed, ${n} ${Kr(n,`warning`)}, ${r} failed.`}function Zr(e,t,n){let r=n.columns-t-2-2;return r<24||j(e.id)>t?[...qr(e.id,2,n.columns).map(e=>n.colors.cyan(e)),...qr(e.name,4,n.columns)].join(`
23
23
  `):M(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(`
24
- `)}function Wr(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Gr(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} ${Rr(e.length,n.noun)} across ${r.size} ${Rr(r.size,`category`,`categories`)}.`,a=Math.min(30,Math.max(...e.map(e=>j(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=>Ur(e,a,t))].join(`
24
+ `)}function Qr(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function $r(e,t,n){let r=new Map;for(let t of e){let e=r.get(t.category)??[];e.push(t),r.set(t.category,e)}let i=`${e.length} ${Kr(e.length,n.noun)} across ${r.size} ${Kr(r.size,`category`,`categories`)}.`,a=Math.min(30,Math.max(...e.map(e=>j(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]??Qr(e);return[t.colors.bold(`${o} (${i.length})`),...i.map(e=>Zr(e,a,t))].join(`
25
25
  `)})].join(`
26
26
 
27
- `)}function Kr(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(...zr(e.description,2,t.columns));let r=e.meta?.filter(Boolean).join(` · `);return r&&n.push(...zr(r,2,t.columns).map(e=>t.colors.dim(e))),n.join(`
27
+ `)}function ei(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(...qr(e.description,2,t.columns));let r=e.meta?.filter(Boolean).join(` · `);return r&&n.push(...qr(r,2,t.columns).map(e=>t.colors.dim(e))),n.join(`
28
28
  `)}).join(`
29
29
 
30
- `)}function qr(e,t,n){let r=t.filter(e=>e.trim().length>0).flatMap(e=>M(e,n.columns));return[n.colors.bold(e),...r].join(`
31
- `)}function Jr(e,t,n){let r=t.flatMap(e=>M(e,Math.max(1,n.columns-2)).map((e,t)=>`${t===0?`- `:` `}${e}`));return[n.colors.bold(e),...r].join(`
32
- `)}function Yr(e,t){return e.length===0?t.colors.dim(`No parameters.`):Kr(e.map(e=>({title:e.name,description:e.description,meta:[e.type,e.required?`required`:`optional`]})),t,{empty:`No parameters.`})}function N(e={}){return!!(!e.json&&process.stdin.isTTY&&process.stdout.isTTY&&!process.env.CI)}function P(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}function F(e){let t=Ar(e,A());t&&process.stdout.write(`${t}\n`)}function I(e,t){process.stdout.write(`${kr(e,t,A())}\n`)}function Xr(e){process.stdout.write(`${jr(e,A())}\n`)}function Zr(e,t){process.stdout.write(`${Br(e,A(),t)}\n`)}function Qr(e){process.stdout.write(`${Vr(e,A())}\n`)}function $r(e){process.stdout.write(`${Lr(e,A())}\n`)}function ei(e,t){process.stdout.write(`${Gr(e,A(),t)}\n`)}function ti(e,t){process.stdout.write(`${Kr(e,A(),t)}\n`)}function ni(e,...t){process.stdout.write(`${qr(e,t,A())}\n`)}function ri(e,t){process.stdout.write(`${Jr(e,t,A())}\n`)}function ii(e){process.stdout.write(`${Yr(e,A())}\n`)}function ai(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function L(e){return typeof e==`symbol`&&process.exit(1),e}const oi=`@seoskill/clicky-provider`;function si(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e===`provider-store`?`provider credential store`:e??`missing`}async function ci(e){let t=await m(),n=t.registry.get(`clicky`);if(n)return n;let r=t.failures.find(e=>e.id===`clicky`);if(r)throw new d(`PROVIDER_UNAVAILABLE`,`The Clicky provider package could not load: ${r.message}`);if(!N({json:e.json}))throw new d(`PROVIDER_UNAVAILABLE`,`Clicky is now an optional provider package. Run \`seo providers install ${oi} --yes\`, then run this command again.`);let i;try{i=await s(oi)}catch(e){throw new d(`PROVIDER_UNAVAILABLE`,e instanceof Error?e.message:String(e))}if(b([`${i.package}@${i.version}`,`Publisher: ${i.publisher??`not supplied by npm`}`,`Repository: ${i.repository??`not supplied by npm`}`,`Integrity: ${i.integrity}`].join(`
33
- `),`Clicky package`),b(`This package can read files, use the network, and run with the same local permissions as seo.`,`Local permissions`),!L(await Hn({message:`Install the Clicky provider package?`,initialValue:!0})))throw new d(`PROVIDER_UNAVAILABLE`,`The Clicky provider package is required for this command.`);await tn(i),t=await m();let a=t.registry.get(`clicky`);if(!a)throw new d(`PROVIDER_UNAVAILABLE`,"The Clicky provider package was installed but could not load. Run `seo providers doctor`.");return a}function li(e){if(e)return e;throw new d(`INVALID_INPUT`,`No Clicky site given. Pass --site-id with the numeric Clicky site ID.`)}async function ui(e,t){let n=await ae(t);if(n)return{siteKey:n.siteKey,source:n.source};try{let n=await pe({providerId:`clicky`,account:{siteId:t},fields:e.connection.fields});return n.sitekey?{siteKey:n.sitekey,source:`provider-store`}:{}}catch{return{}}}const di=v({meta:{name:`clicky`,description:`Connect Clicky and read bounded analytics reports`},subCommands:{connect:v({meta:{name:`connect`,description:`Validate and save a Clicky sitekey`},args:{"site-id":{type:`string`,description:`Numeric Clicky site ID.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e),r=await ci({json:t}),i=N({json:t});i&&y(`Connect Clicky`);let a=C(e[`site-id`])??(i?L(await Jn({message:`Clicky site ID`,validate:e=>/^\d{1,30}$/u.test(e?.trim()??``)?void 0:`Enter the numeric site ID from Clicky`})):void 0);if(!a)throw new d(`INVALID_INPUT`,`No Clicky site given. Pass --site-id with the numeric Clicky site ID.`);let o=await ui(r,a),s=o.siteKey??(i?L(await Kn({message:`Clicky sitekey`,validate:e=>/^[A-Za-z0-9]{12,64}$/u.test(e?.trim()??``)?void 0:`Enter the sitekey from Clicky`})):void 0);if(!s)throw new d(`AUTH_REQUIRED`,`Run this command in a terminal or set ${fn}.`);await _e({providerId:`clicky`,account:{siteId:a},credentials:{sitekey:s}});let c=o.source??await Pe(a,s);await Ee({providerId:`clicky`,account:{siteId:a},credentials:{sitekey:s}}),n(`clicky`,{siteId:a});let l={siteId:a,connected:!0,credentialSource:c};if(t){P(l);return}let u=`Connection verified. Saved in the ${si(c)}.`;i?x(u):process.stdout.write(`${u}\n`)}}),status:v({meta:{name:`status`,description:`Show the local Clicky connection`},args:{"site-id":{type:`string`,description:`Numeric Clicky site ID.`},check:{type:`boolean`,default:!1,description:`Verify the saved sitekey with Clicky.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e),n=await ci({json:t}),r=li(C(e[`site-id`])),i=await ui(n,r),a=w(e.check);a&&i.siteKey&&await _e({providerId:`clicky`,account:{siteId:r},credentials:{sitekey:i.siteKey}});let o={siteId:r,connected:!!i.siteKey,credentialSource:i.source,liveCheck:a?i.siteKey?`passed`:`unavailable`:`not-requested`};if(t){P(o);return}F([[`Site ID`,r],[`Connected`,o.connected?`yes`:`no`],[`Credential`,si(o.credentialSource)],[`Live check`,o.liveCheck]])}}),report:v({meta:{name:`report`,description:`Run a bounded Clicky analytics report`},args:{"site-id":{type:`string`,description:`Numeric Clicky site ID.`},type:{type:`string`,default:`pages-entrance`,description:`Clicky report type. Defaults to pages-entrance.`},"start-date":{type:`string`,required:!0,description:`First site calendar date in YYYY-MM-DD format.`},"end-date":{type:`string`,required:!0,description:`Last site calendar date in YYYY-MM-DD format.`},limit:{type:`string`,default:`100`,description:`Maximum retained rows. Defaults to 100 and caps at 5000.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local Clicky cache.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e),n=await ci({json:t}),r=li(C(e[`site-id`])),i=await ui(n,r),a=await bt({providerId:`clicky`,actionId:`report`,account:{siteId:r},...i.siteKey?{credentials:{sitekey:i.siteKey}}:{},params:{type:C(e.type)??`pages-entrance`,startDate:C(e[`start-date`])??``,endDate:C(e[`end-date`])??``,limit:E(e.limit)??100},refresh:w(e.refresh)});if(!a.data||typeof a.data!=`object`)throw new d(`PROVIDER_UNAVAILABLE`,`The Clicky provider returned an invalid report.`);let o={...a.data,cache:a.cache};if(t){P(o);return}F([[`Site ID`,o.siteId],[`Report`,o.type],[`Rows`,String(o.returnedRows)],[`Cache`,o.cache]]),I([`Value`,`Title`,`URL`],o.rows.slice(0,25).map(e=>[String(e.value??``),String(e.title??``),String(e.url??``)]))}}),disconnect:v({meta:{name:`disconnect`,description:`Remove a saved Clicky sitekey`},args:{"site-id":{type:`string`,description:`Numeric Clicky site ID.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e);await ci({json:t});let n=li(C(e[`site-id`]));await o(n),await se({providerId:`clicky`,account:{siteId:n}});let r=!!process.env[fn];t?P({siteId:n,savedCredentialRemoved:!0,environmentCredential:r?`active`:`missing`}):process.stdout.write(r?`Saved sitekey removed. ${fn} is still active.\n`:`Clicky is disconnected for this site.
34
- `)}})}}),fi=v({meta:{name:`properties`,description:`List Google Analytics accounts and properties`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},account:{type:`string`,description:`Saved Google account email.`}},run:async({args:e})=>{let t=await Xt(C(e.account)),n=t.flatMap(e=>e.propertySummaries.map(t=>({account:e.displayName??e.account,property:tt(t.property),displayName:t.displayName??t.property})));if(k(e)){P({accountSummaries:t,properties:n});return}I([`Property`,`Name`,`Account`],n.map(e=>[e.property,e.displayName,e.account]))}});function R(e){if(e)return e;throw new d(`INVALID_INPUT`,"No site given. Pass --site with a domain, URL or sc-domain: property. Run `seo sites` to list your Search Console properties.")}async function pi(e,t={}){let n=R(e),r=nt((await Ht(t.refresh,t.account)).map(e=>e.siteUrl),n);if(!r)throw new d(`PROPERTY_NOT_FOUND`,`This Google login has no Search Console property for ${n}. Run \`seo sites\` to list the properties it can read.`);return r}function mi(e){if(e)return e;throw new d(`INVALID_INPUT`,"No Google Analytics property given. Pass --property with the numeric property id. Run `seo analytics google properties` to list them.")}function z(e){return Math.round(e).toLocaleString(`en-GB`)}function B(e){return e.toFixed(1)}function V(e){return`${(e*100).toFixed(1)}%`}function H(e,t=72){return br(e,t)}function hi(e){return e.verification?.requested?`${e.verification.verified} checked, ${e.verification.failed} failed`:`off`}function gi(e){return{title:e.title,target:e.target,status:e.status,summary:e.summary,metrics:e.metrics,sections:(e.diagnostics??[]).map(e=>({title:e.title,diagnostics:e.items})),notes:e.notes}}function U(e){$r(gi(e))}function W(e,t){I(e,t.slice(0,25)),t.length>25&&process.stdout.write(`Showing 25 of ${t.length}. Use --json for full data.\n`)}function G(e,t,n=5){let r=t.filter(e=>e.action.trim().length>0).slice(0,n),i=_i(e,r);i&&(process.stdout.write(`
35
- `),$r(i),t.length>r.length&&process.stdout.write(`Showing ${r.length} of ${t.length}. Use --json for full data.\n`))}function _i(e,t){if(t.length)return{title:e,status:`info`,summary:`${t.length} ${t.length===1?`action`:`actions`} shown.`,sections:[{title:`Actions`,diagnostics:t.map(e=>({status:`info`,title:e.label,explanation:e.context??`Review the evidence before making changes.`,fix:e.action}))}]}}function vi(e){process.stdout.write(`\nNext: ${e}\n`)}function K(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`)}}const yi=v({meta:{name:`analytics`,description:`Read analytics data from connected providers`},subCommands:{clicky:di,google:v({meta:{name:`google`,description:`Read Google Analytics properties and reports`},subCommands:{properties:fi,report:v({meta:{name:`report`,description:`Run a Google Analytics report`},args:{property:{type:`string`,description:"Numeric Google Analytics property ID. Run `seo analytics google properties` to list them."},account:{type:`string`,description:`Saved Google account email.`},"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=k(e),n=mi(C(e.property)),r=await it(n,await hr(e.body,e[`body-file`])??{dateRanges:[{startDate:C(e[`start-date`]),endDate:C(e[`end-date`])}],dimensions:(O(e.dimensions)??[]).map(e=>({name:e})),metrics:(O(e.metrics)??[]).map(e=>({name:e})),limit:C(e.limit)},{refresh:w(e.refresh),accountEmail:C(e.account)});if(t){P(r);return}let i=Dt(r);if(U({title:`Google Analytics report`,target:n,status:`info`,summary:`${r.rowCount??i.length} rows returned for the requested dimensions and metrics.`,metrics:[{label:`Rows`,value:r.rowCount??i.length},{label:`Displayed`,value:Math.min(i.length,25)}]}),i.length){let e=Object.keys(i[0]??{});I(e,i.slice(0,25).map(t=>e.map(e=>t[e]??``)))}}})}})}});function bi(){return`Your browser will open. Choose your Google account and select all permission boxes for read-only access. Keep this terminal open and finish the browser steps within five minutes.`}async function xi(){return b(bi(),`Google sign-in`),At()}function Si(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 Ci(e){return e.active===`keychain`?`system keychain`:e.configured===`keychain`?`private file fallback`:`private file`}function wi(e){return e===`shared`?`SEO Skill app`:`Local OAuth config`}function Ti(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`,wi(e.clientSource)],[`Expires`,sr(e.expiresAt)]),t}const Ei=v({meta:{name:`auth`,description:`Authentication commands`},subCommands:{login:v({meta:{name:`login`,description:`Run Google OAuth flow`},run:async()=>{if((await ht()).activeMode===`service-account`)throw new d(`AUTH_CONFIG_REQUIRED`,`A service account is active from the environment. Unset its credential variable before running browser OAuth.`);let e=await xi();F(Ti({accountEmail:e.account_email,clientSource:e.client_source,expiresAt:e.expires_at,scope:e.scope}))}}),logout:v({meta:{name:`logout`,description:`Delete a local Google login`},args:{account:{type:`string`,description:`Delete the login for this Google account.`},all:{type:`boolean`,default:!1,description:`Delete every saved Google login.`}},run:async({args:e})=>{let t=await ht(),n=C(e.account);if(n&&e.all)throw new d(`INVALID_INPUT`,`Use either --account or --all, not both.`);let r=e.all?void 0:n??t.accounts.find(e=>e.active)?.accountEmail;if(await Ke(r),t.activeMode===`service-account`){process.stdout.write(`${e.all?`Deleted all local Google logins.`:r?`Deleted the local login for ${r}.`:`No local Google login was found.`} Service account credentials remain available through the environment.\n`);return}process.stdout.write(`${e.all?`Deleted all local Google logins.`:r?`Deleted the local login for ${r}.`:`No local Google login was found.`}\nRevoke at https://myaccount.google.com/permissions if you also want Google to forget the grant.\n`)}}),whoami:v({meta:{name:`whoami`,description:`Show the signed-in Google account`},args:{account:{type:`string`,description:`Show this saved Google account.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await ht();if(t.activeMode===`service-account`){let n={mode:`service-account`,account:t.identity??null,source:Si(t.serviceAccount.source)};if(k(e)){P(n);return}F([[`Account type`,`Service account`],[`Account`,t.identity??`Invalid configuration`],[`Credentials`,n.source],[`Access`,`Search Console and Google Analytics, read only`]]);return}let n=C(e.account),r=n?await on(n):t.tokens;if(n&&!r)throw new d(`AUTH_REQUIRED`,`Google account ${n} is not connected.`);if(!r){if(k(e)){P({mode:`oauth`,account:null});return}process.stdout.write(`Not logged in.
36
- `);return}if(k(e)){P({mode:`oauth`,account:r.account_email,scopes:r.scope.split(/\s+/u).filter(Boolean),clientSource:r.client_source,expiresAt:r.expires_at});return}F(Ti({accountEmail:r.account_email,clientSource:r.client_source,expiresAt:r.expires_at,scope:r.scope}))}}),status:v({meta:{name:`status`,description:`Show local Google auth status`},args:{account:{type:`string`,description:`Show status for this saved Google account.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await ht(),n=C(e.account),r=n?await on(n):t.tokens;if(n&&!r&&t.activeMode!==`service-account`)throw new d(`AUTH_REQUIRED`,`Google account ${n} is not connected.`);let i=t.activeMode===`oauth`?await ln():void 0;if(k(e)){P({authenticated:t.activeMode===`oauth`?!!r:t.serviceAccount.configured,mode:t.activeMode,identity:t.identity,account:t.activeMode===`oauth`?r?.account_email:void 0,scopes:t.activeMode===`oauth`?r?.scope:void 0,clientSource:t.activeMode===`oauth`?r?.client_source:void 0,expiresAt:t.activeMode===`oauth`?r?.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},accounts:t.accounts,...i?{tokenStorage:i}:{}});return}if(t.activeMode===`service-account`){let e=[[`Mode`,`service account`],[`Identity`,t.identity??`unavailable`],[`Source`,Si(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]),F(e);return}if(!r){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 a=i??await ln();F([[`Account`,r.account_email],[`Connected accounts`,String(t.accounts.length)],[`Scopes`,r.scope],[`Client`,wi(r.client_source)],[`Expires`,sr(r.expires_at)],[`Tokens file`,te().tokensFile],[`Token storage`,Ci(a)],...a.reason?[[`Storage note`,a.reason]]:[],[`OAuth mode`,t.sharedConfigured?`SEO Skill app available`:t.byoConfigured?`Local OAuth config available`:`missing`],[`Revoke at`,`https://myaccount.google.com/permissions`]])}}),storage:v({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 d(`INVALID_INPUT`,`Choose either --keychain or --file, not both.`);let t=e.keychain||e.file?await c(e.keychain?`keychain`:`file`):await ln();if(k(e)){P(t);return}F([[`Configured storage`,t.configured],[`Active storage`,Ci(t)],...t.reason?[[`Note`,t.reason]]:[]])}}),refresh:v({meta:{name:`refresh`,description:`Refresh the Google OAuth token`},args:{account:{type:`string`,description:`Refresh this saved Google account.`}},run:async({args:e})=>{if((await ht()).activeMode===`service-account`){process.stdout.write(`Service accounts request short-lived Google tokens automatically. No local refresh token is stored.
37
- `);return}let t=await ft(C(e.account));process.stdout.write(`Refreshed. New expiry ${new Date(t.expires_at).toISOString()}.\n`)}}),accounts:v({meta:{name:`accounts`,description:`List saved Google accounts`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=Qe();if(k(e)){P({accounts:t});return}if(t.length===0){process.stdout.write(`No Google accounts are connected.
38
- `);return}F(t.map(e=>[e.active?`Active account`:`Account`,e.accountEmail]))}}),use:v({meta:{name:`use`,description:`Select the default Google account`},args:{account:{type:`positional`,required:!0,description:`Saved Google account email.`}},run:({args:e})=>{let t=C(e.account);if(!t)throw new d(`INVALID_INPUT`,`Google account is required.`);Oe(t),process.stdout.write(`Default Google account: ${t}\n`)}}),"setup-client":v({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(!N({json:k(e)}))throw new d(`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.");y(`Local Google OAuth client`),b([`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(`
39
- `),`Advanced`),nn({clientId:L(await Jn({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),clientSecret:L(await Kn({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}))}),x(`Saved local OAuth config to ${te().oauthClientFile}`)}})}}),Di=[`gsc`,`google-analytics`,`dataforseo`,`ahrefs`,`clicky`,`http`];function Oi(e){if(e!==void 0){if(typeof e==`string`&&Di.includes(e))return e;throw new d(`INVALID_INPUT`,`--provider must be one of: ${Di.join(`, `)}.`)}}const ki=v({meta:{name:`cache`,description:`Cache helpers`},subCommands:{stats:v({meta:{name:`stats`,description:`Show local cache size and row counts`},run:async()=>{let e=Rt();F([[`DB`,e.dbPath],[`Size`,ai(e.sizeBytes)],[`Cached data`,`${ai(e.logicalSizeBytes)} of ${ai(e.maxSizeBytes)} automatic limit`],[`Sites`,String(e.counts.sites??0)],[`Search Console`,String(e.counts.gsc_cache??0)],[`Google Analytics`,String(e.counts.google_analytics_cache??0)],[`DataForSEO`,String(e.counts.provider_cache??0)],[`Ahrefs`,String(e.counts.ahrefs_cache??0)],[`Clicky`,String(e.counts.clicky_cache??0)],[`HTTP`,String(e.counts.http_cache??0)]])}}),clear:v({meta:{name:`clear`,description:`Clear cached API and HTTP data`},args:{provider:{type:`string`,description:`Optional cache provider: gsc, google-analytics, dataforseo, ahrefs, clicky, or http`}},run:async({args:e})=>{let t=lt(Oi(e.provider));process.stdout.write(`Removed ${t} cached rows.\n`)}})}}),Ai=v({meta:{name:`content`,description:`Optimize page content from real GSC queries`},subCommands:{optimize:v({meta:{name:`optimize`,description:`Build a content optimization report for one URL`},args:{site:{type:`string`},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":cr(`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=k(e),n=await ot({site:R(C(e.site)),url:C(e.url)??``,days:E(e.days),limit:E(e.limit),minImpressions:E(e[`min-impressions`]),includeBrand:w(e[`include-brand`]),verifyContent:w(e[`verify-content`])!==!1,js:w(e.js)?!0:`auto`,refresh:w(e.refresh)});if(t){P(n);return}U({title:`Content optimization`,target:n.url,status:`info`,summary:n.summary.verdict,metrics:[{label:`Score`,value:`${n.summary.score}/100`},{label:`Primary intent`,value:n.summary.primaryIntent},{label:`Primary query`,value:n.summary.primaryQuery??`None`},{label:`Queries`,value:z(n.summary.queries)},{label:`Opportunities`,value:z(n.summary.opportunities)},{label:`Estimated lift`,value:z(n.summary.estimatedClickLift)}]}),G(`Top actions`,n.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),n.brief.sections.length&&(process.stdout.write(`
30
+ `)}function ti(e,t,n){let r=t.filter(e=>e.trim().length>0).flatMap(e=>M(e,n.columns));return[n.colors.bold(e),...r].join(`
31
+ `)}function ni(e,t,n){let r=t.flatMap(e=>M(e,Math.max(1,n.columns-2)).map((e,t)=>`${t===0?`- `:` `}${e}`));return[n.colors.bold(e),...r].join(`
32
+ `)}function ri(e,t){return e.length===0?t.colors.dim(`No parameters.`):ei(e.map(e=>({title:e.name,description:e.description,meta:[e.type,e.required?`required`:`optional`]})),t,{empty:`No parameters.`})}function N(e={}){return!!(!e.json&&process.stdin.isTTY&&process.stdout.isTTY&&!process.env.CI)}function P(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}function F(e){let t=Rr(e,A());t&&process.stdout.write(`${t}\n`)}function I(e,t){process.stdout.write(`${Lr(e,t,A())}\n`)}function ii(e){process.stdout.write(`${zr(e,A())}\n`)}function ai(e,t){process.stdout.write(`${Jr(e,A(),t)}\n`)}function oi(e){process.stdout.write(`${Yr(e,A())}\n`)}function si(e){process.stdout.write(`${Gr(e,A())}\n`)}function ci(e,t){process.stdout.write(`${$r(e,A(),t)}\n`)}function li(e,t){process.stdout.write(`${ei(e,A(),t)}\n`)}function ui(e,...t){process.stdout.write(`${ti(e,t,A())}\n`)}function di(e,t){process.stdout.write(`${ni(e,t,A())}\n`)}function fi(e){process.stdout.write(`${ri(e,A())}\n`)}function pi(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function L(e){return typeof e==`symbol`&&process.exit(1),e}const mi=`@seoskill/clicky-provider`;function hi(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e===`provider-store`?`provider credential store`:e??`missing`}async function gi(e){let t=await kt(),n=t.registry.get(`clicky`);if(n)return n;let r=t.failures.find(e=>e.id===`clicky`);if(r)throw new p(`PROVIDER_UNAVAILABLE`,`The Clicky provider package could not load: ${r.message}`);if(!N({json:e.json}))throw new p(`PROVIDER_UNAVAILABLE`,`Clicky is now an optional provider package. Run \`seo providers install ${mi} --yes\`, then run this command again.`);let i;try{i=await s(mi)}catch(e){throw new p(`PROVIDER_UNAVAILABLE`,e instanceof Error?e.message:String(e))}if(b([`${i.package}@${i.version}`,`Publisher: ${i.publisher??`not supplied by npm`}`,`Repository: ${i.repository??`not supplied by npm`}`,`Integrity: ${i.integrity}`].join(`
33
+ `),`Clicky package`),b(`This package can read files, use the network, and run with the same local permissions as seo.`,`Local permissions`),!L(await Xn({message:`Install the Clicky provider package?`,initialValue:!0})))throw new p(`PROVIDER_UNAVAILABLE`,`The Clicky provider package is required for this command.`);await ln(i),t=await kt();let a=t.registry.get(`clicky`);if(!a)throw new p(`PROVIDER_UNAVAILABLE`,"The Clicky provider package was installed but could not load. Run `seo providers doctor`.");return a}function _i(e){if(e)return e;throw new p(`INVALID_INPUT`,`No Clicky site given. Pass --site-id with the numeric Clicky site ID.`)}async function vi(e,t){let n=await Ne(t);if(n)return{siteKey:n.siteKey,source:n.source};try{let n=await Se({providerId:`clicky`,account:{siteId:t},fields:e.connection.fields});return n.sitekey?{siteKey:n.sitekey,source:`provider-store`}:{}}catch{return{}}}const yi=v({meta:{name:`clicky`,description:`Connect Clicky and read bounded analytics reports`},subCommands:{connect:v({meta:{name:`connect`,description:`Validate and save a Clicky sitekey`},args:{"site-id":{type:`string`,description:`Numeric Clicky site ID.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e),r=await gi({json:t}),i=N({json:t});i&&y(`Connect Clicky`);let a=w(e[`site-id`])??(i?L(await tr({message:`Clicky site ID`,validate:e=>/^\d{1,30}$/u.test(e?.trim()??``)?void 0:`Enter the numeric site ID from Clicky`})):void 0);if(!a)throw new p(`INVALID_INPUT`,`No Clicky site given. Pass --site-id with the numeric Clicky site ID.`);let o=await vi(r,a),s=o.siteKey??(i?L(await S({message:`Clicky sitekey`,validate:e=>/^[A-Za-z0-9]{12,64}$/u.test(e?.trim()??``)?void 0:`Enter the sitekey from Clicky`})):void 0);if(!s)throw new p(`AUTH_REQUIRED`,`Run this command in a terminal or set ${m}.`);await Mt({providerId:`clicky`,account:{siteId:a},credentials:{sitekey:s}});let c=o.source??await bn(a,s);await Oe({providerId:`clicky`,account:{siteId:a},credentials:{sitekey:s}}),n(`clicky`,{siteId:a});let l={siteId:a,connected:!0,credentialSource:c};if(t){P(l);return}let u=`Connection verified. Saved in the ${hi(c)}.`;i?x(u):process.stdout.write(`${u}\n`)}}),status:v({meta:{name:`status`,description:`Show the local Clicky connection`},args:{"site-id":{type:`string`,description:`Numeric Clicky site ID.`},check:{type:`boolean`,default:!1,description:`Verify the saved sitekey with Clicky.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e),n=await gi({json:t}),r=_i(w(e[`site-id`])),i=await vi(n,r),a=T(e.check);a&&i.siteKey&&await Mt({providerId:`clicky`,account:{siteId:r},credentials:{sitekey:i.siteKey}});let o={siteId:r,connected:!!i.siteKey,credentialSource:i.source,liveCheck:a?i.siteKey?`passed`:`unavailable`:`not-requested`};if(t){P(o);return}F([[`Site ID`,r],[`Connected`,o.connected?`yes`:`no`],[`Credential`,hi(o.credentialSource)],[`Live check`,o.liveCheck]])}}),report:v({meta:{name:`report`,description:`Run a bounded Clicky analytics report`},args:{"site-id":{type:`string`,description:`Numeric Clicky site ID.`},type:{type:`string`,default:`pages-entrance`,description:`Clicky report type. Defaults to pages-entrance.`},"start-date":{type:`string`,required:!0,description:`First site calendar date in YYYY-MM-DD format.`},"end-date":{type:`string`,required:!0,description:`Last site calendar date in YYYY-MM-DD format.`},limit:{type:`string`,default:`100`,description:`Maximum retained rows. Defaults to 100 and caps at 5000.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local Clicky cache.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e),n=await gi({json:t}),r=_i(w(e[`site-id`])),i=await vi(n,r),a=await Dt({providerId:`clicky`,actionId:`report`,account:{siteId:r},...i.siteKey?{credentials:{sitekey:i.siteKey}}:{},params:{type:w(e.type)??`pages-entrance`,startDate:w(e[`start-date`])??``,endDate:w(e[`end-date`])??``,limit:E(e.limit)??100},refresh:T(e.refresh)});if(!a.data||typeof a.data!=`object`)throw new p(`PROVIDER_UNAVAILABLE`,`The Clicky provider returned an invalid report.`);let o={...a.data,cache:a.cache};if(t){P(o);return}F([[`Site ID`,o.siteId],[`Report`,o.type],[`Rows`,String(o.returnedRows)],[`Cache`,o.cache]]),I([`Value`,`Title`,`URL`],o.rows.slice(0,25).map(e=>[String(e.value??``),String(e.title??``),String(e.url??``)]))}}),disconnect:v({meta:{name:`disconnect`,description:`Remove a saved Clicky sitekey`},args:{"site-id":{type:`string`,description:`Numeric Clicky site ID.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e);await gi({json:t});let n=_i(w(e[`site-id`]));await le(n),await ye({providerId:`clicky`,account:{siteId:n}});let r=!!process.env[m];t?P({siteId:n,savedCredentialRemoved:!0,environmentCredential:r?`active`:`missing`}):process.stdout.write(r?`Saved sitekey removed. ${m} is still active.\n`:`Clicky is disconnected for this site.
34
+ `)}})}}),bi=v({meta:{name:`properties`,description:`List Google Analytics accounts and properties`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},account:{type:`string`,description:`Saved Google account email.`}},run:async({args:e})=>{let t=await Ht(w(e.account)),n=t.flatMap(e=>e.propertySummaries.map(t=>({account:e.displayName??e.account,property:Tt(t.property),displayName:t.displayName??t.property})));if(k(e)){P({accountSummaries:t,properties:n});return}I([`Property`,`Name`,`Account`],n.map(e=>[e.property,e.displayName,e.account]))}});function R(e){if(e)return e;throw new p(`INVALID_INPUT`,"No site given. Pass --site with a domain, URL or sc-domain: property. Run `seo sites` to list your Search Console properties.")}async function xi(e,n={}){let r=R(e),i=Ot((await t(n.refresh,n.account)).map(e=>e.siteUrl),r);if(!i)throw new p(`PROPERTY_NOT_FOUND`,`This Google login has no Search Console property for ${r}. Run \`seo sites\` to list the properties it can read.`);return i}function Si(e){if(e)return e;throw new p(`INVALID_INPUT`,"No Google Analytics property given. Pass --property with the numeric property id. Run `seo analytics google properties` to list them.")}function z(e){return Math.round(e).toLocaleString(`en-GB`)}function B(e){return e.toFixed(1)}function V(e){return`${(e*100).toFixed(1)}%`}function H(e,t=72){return Or(e,t)}function Ci(e){return e.verification?.requested?`${e.verification.verified} checked, ${e.verification.failed} failed`:`off`}function wi(e){return{title:e.title,target:e.target,status:e.status,summary:e.summary,metrics:e.metrics,sections:(e.diagnostics??[]).map(e=>({title:e.title,diagnostics:e.items})),notes:e.notes}}function U(e){si(wi(e))}function W(e,t){I(e,t.slice(0,25)),t.length>25&&process.stdout.write(`Showing 25 of ${t.length}. Use --json for full data.\n`)}function G(e,t,n=5){let r=t.filter(e=>e.action.trim().length>0).slice(0,n),i=Ti(e,r);i&&(process.stdout.write(`
35
+ `),si(i),t.length>r.length&&process.stdout.write(`Showing ${r.length} of ${t.length}. Use --json for full data.\n`))}function Ti(e,t){if(t.length)return{title:e,status:`info`,summary:`${t.length} ${t.length===1?`action`:`actions`} shown.`,sections:[{title:`Actions`,diagnostics:t.map(e=>({status:`info`,title:e.label,explanation:e.context??`Review the evidence before making changes.`,fix:e.action}))}]}}function Ei(e){process.stdout.write(`\nNext: ${e}\n`)}function K(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`)}}const Di=v({meta:{name:`analytics`,description:`Read analytics data from connected providers`},subCommands:{clicky:yi,google:v({meta:{name:`google`,description:`Read Google Analytics properties and reports`},subCommands:{properties:bi,report:v({meta:{name:`report`,description:`Run a Google Analytics report`},args:{property:{type:`string`,description:"Numeric Google Analytics property ID. Run `seo analytics google properties` to list them."},account:{type:`string`,description:`Saved Google account email.`},"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=k(e),n=Si(w(e.property)),r=await Zt(n,await Cr(e.body,e[`body-file`])??{dateRanges:[{startDate:w(e[`start-date`]),endDate:w(e[`end-date`])}],dimensions:(O(e.dimensions)??[]).map(e=>({name:e})),metrics:(O(e.metrics)??[]).map(e=>({name:e})),limit:w(e.limit)},{refresh:T(e.refresh),accountEmail:w(e.account)});if(t){P(r);return}let i=nt(r);if(U({title:`Google Analytics report`,target:n,status:`info`,summary:`${r.rowCount??i.length} rows returned for the requested dimensions and metrics.`,metrics:[{label:`Rows`,value:r.rowCount??i.length},{label:`Displayed`,value:Math.min(i.length,25)}]}),i.length){let e=Object.keys(i[0]??{});I(e,i.slice(0,25).map(t=>e.map(e=>t[e]??``)))}}})}})}});function Oi(){return`Your browser will open. Choose your Google account and select all permission boxes for read-only access. Keep this terminal open and finish the browser steps within five minutes.`}async function ki(){return b(Oi(),`Google sign-in`),rn()}function Ai(e){return e?e===`environment-json`?`SEO_GOOGLE_SERVICE_ACCOUNT_JSON`:e===`environment-file`?`SEO_GOOGLE_SERVICE_ACCOUNT_FILE`:`GOOGLE_APPLICATION_CREDENTIALS`:`invalid or conflicting configuration`}function ji(e){return e.active===`keychain`?`system keychain`:e.configured===`keychain`?`private file fallback`:`private file`}function Mi(e){return e===`shared`?`SEO Skill app`:`Local OAuth config`}function Ni(e){let t=[[`Account`,e.accountEmail]],n=new Set(e.scope.split(/\s+/u).filter(Boolean));return n.has(`https://www.googleapis.com/auth/webmasters.readonly`)?t.push([`Search Console`,`Read only`]):t.push([`Search Console`,`Not granted`]),n.has(`https://www.googleapis.com/auth/analytics.readonly`)?t.push([`Google Analytics`,`Read only`]):t.push([`Google Analytics`,`Not granted`]),t.push([`OAuth app`,Mi(e.clientSource)],[`Expires`,mr(e.expiresAt)]),t}const Pi=v({meta:{name:`auth`,description:`Authentication commands`},subCommands:{login:v({meta:{name:`login`,description:`Run Google OAuth flow`},run:async()=>{if((await dt()).activeMode===`service-account`)throw new p(`AUTH_CONFIG_REQUIRED`,`A service account is active from the environment. Unset its credential variable before running browser OAuth.`);let e=await ki();F(Ni({accountEmail:e.account_email,clientSource:e.client_source,expiresAt:e.expires_at,scope:e.scope}))}}),logout:v({meta:{name:`logout`,description:`Delete a local Google login`},args:{account:{type:`string`,description:`Delete the login for this Google account.`},all:{type:`boolean`,default:!1,description:`Delete every saved Google login.`}},run:async({args:e})=>{let t=await dt(),n=w(e.account);if(n&&e.all)throw new p(`INVALID_INPUT`,`Use either --account or --all, not both.`);let r=e.all?void 0:n??t.accounts.find(e=>e.active)?.accountEmail;if(await Gt(r),t.activeMode===`service-account`){process.stdout.write(`${e.all?`Deleted all local Google logins.`:r?`Deleted the local login for ${r}.`:`No local Google login was found.`} Service account credentials remain available through the environment.\n`);return}process.stdout.write(`${e.all?`Deleted all local Google logins.`:r?`Deleted the local login for ${r}.`:`No local Google login was found.`}\nRevoke at https://myaccount.google.com/permissions if you also want Google to forget the grant.\n`)}}),whoami:v({meta:{name:`whoami`,description:`Show the signed-in Google account`},args:{account:{type:`string`,description:`Show this saved Google account.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await dt();if(t.activeMode===`service-account`){let n={mode:`service-account`,account:t.identity??null,source:Ai(t.serviceAccount.source)};if(k(e)){P(n);return}F([[`Account type`,`Service account`],[`Account`,t.identity??`Invalid configuration`],[`Credentials`,n.source],[`Access`,`Search Console and Google Analytics, read only`]]);return}let n=w(e.account),r=n?await $e(n):t.tokens;if(n&&!r)throw new p(`AUTH_REQUIRED`,`Google account ${n} is not connected.`);if(!r){if(k(e)){P({mode:`oauth`,account:null});return}process.stdout.write(`Not logged in.
36
+ `);return}if(k(e)){P({mode:`oauth`,account:r.account_email,scopes:r.scope.split(/\s+/u).filter(Boolean),clientSource:r.client_source,expiresAt:r.expires_at});return}F(Ni({accountEmail:r.account_email,clientSource:r.client_source,expiresAt:r.expires_at,scope:r.scope}))}}),status:v({meta:{name:`status`,description:`Show local Google auth status`},args:{account:{type:`string`,description:`Show status for this saved Google account.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await dt(),n=w(e.account),i=n?await $e(n):t.tokens;if(n&&!i&&t.activeMode!==`service-account`)throw new p(`AUTH_REQUIRED`,`Google account ${n} is not connected.`);let a=t.activeMode===`oauth`?await St():void 0;if(k(e)){P({authenticated:t.activeMode===`oauth`?!!i:t.serviceAccount.configured,mode:t.activeMode,identity:t.identity,account:t.activeMode===`oauth`?i?.account_email:void 0,scopes:t.activeMode===`oauth`?i?.scope:void 0,clientSource:t.activeMode===`oauth`?i?.client_source:void 0,expiresAt:t.activeMode===`oauth`?i?.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},accounts:t.accounts,...a?{tokenStorage:a}:{}});return}if(t.activeMode===`service-account`){let e=[[`Mode`,`service account`],[`Identity`,t.identity??`unavailable`],[`Source`,Ai(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]),F(e);return}if(!i){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 o=a??await St();F([[`Account`,i.account_email],[`Connected accounts`,String(t.accounts.length)],[`Scopes`,i.scope],[`Client`,Mi(i.client_source)],[`Expires`,mr(i.expires_at)],[`Tokens file`,r().tokensFile],[`Token storage`,ji(o)],...o.reason?[[`Storage note`,o.reason]]:[],[`OAuth mode`,t.sharedConfigured?`SEO Skill app available`:t.byoConfigured?`Local OAuth config available`:`missing`],[`Revoke at`,`https://myaccount.google.com/permissions`]])}}),storage:v({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 p(`INVALID_INPUT`,`Choose either --keychain or --file, not both.`);let t=e.keychain||e.file?await gn(e.keychain?`keychain`:`file`):await St();if(k(e)){P(t);return}F([[`Configured storage`,t.configured],[`Active storage`,ji(t)],...t.reason?[[`Note`,t.reason]]:[]])}}),refresh:v({meta:{name:`refresh`,description:`Refresh the Google OAuth token`},args:{account:{type:`string`,description:`Refresh this saved Google account.`}},run:async({args:e})=>{if((await dt()).activeMode===`service-account`){process.stdout.write(`Service accounts request short-lived Google tokens automatically. No local refresh token is stored.
37
+ `);return}let t=await gt(w(e.account));process.stdout.write(`Refreshed. New expiry ${new Date(t.expires_at).toISOString()}.\n`)}}),accounts:v({meta:{name:`accounts`,description:`List saved Google accounts`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=yt();if(k(e)){P({accounts:t});return}if(t.length===0){process.stdout.write(`No Google accounts are connected.
38
+ `);return}F(t.map(e=>[e.active?`Active account`:`Account`,e.accountEmail]))}}),use:v({meta:{name:`use`,description:`Select the default Google account`},args:{account:{type:`positional`,required:!0,description:`Saved Google account email.`}},run:({args:e})=>{let t=w(e.account);if(!t)throw new p(`INVALID_INPUT`,`Google account is required.`);sn(t),process.stdout.write(`Default Google account: ${t}\n`)}}),"setup-client":v({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(!N({json:k(e)}))throw new p(`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.");y(`Local Google OAuth client`),b([`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(`
39
+ `),`Advanced`),at({clientId:L(await tr({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),clientSecret:L(await S({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}))}),x(`Saved local OAuth config to ${r().oauthClientFile}`)}})}}),Fi=[`gsc`,`google-analytics`,`dataforseo`,`ahrefs`,`clicky`,`http`];function Ii(e){if(e!==void 0){if(typeof e==`string`&&Fi.includes(e))return e;throw new p(`INVALID_INPUT`,`--provider must be one of: ${Fi.join(`, `)}.`)}}const Li=v({meta:{name:`cache`,description:`Cache helpers`},subCommands:{stats:v({meta:{name:`stats`,description:`Show local cache size and row counts`},run:async()=>{let e=Pt();F([[`DB`,e.dbPath],[`Size`,pi(e.sizeBytes)],[`Cached data`,`${pi(e.logicalSizeBytes)} of ${pi(e.maxSizeBytes)} automatic limit`],[`Sites`,String(e.counts.sites??0)],[`Search Console`,String(e.counts.gsc_cache??0)],[`Google Analytics`,String(e.counts.google_analytics_cache??0)],[`DataForSEO`,String(e.counts.provider_cache??0)],[`Ahrefs`,String(e.counts.ahrefs_cache??0)],[`Clicky`,String(e.counts.clicky_cache??0)],[`HTTP`,String(e.counts.http_cache??0)]])}}),clear:v({meta:{name:`clear`,description:`Clear cached API and HTTP data`},args:{provider:{type:`string`,description:`Optional cache provider: gsc, google-analytics, dataforseo, ahrefs, clicky, or http`}},run:async({args:e})=>{let t=ct(Ii(e.provider));process.stdout.write(`Removed ${t} cached rows.\n`)}})}}),Ri=v({meta:{name:`content`,description:`Optimize page content from real GSC queries`},subCommands:{optimize:v({meta:{name:`optimize`,description:`Build a content optimization report for one URL`},args:{site:{type:`string`},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":hr(`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=k(e),n=await qe({site:R(w(e.site)),url:w(e.url)??``,days:E(e.days),limit:E(e.limit),minImpressions:E(e[`min-impressions`]),includeBrand:T(e[`include-brand`]),verifyContent:T(e[`verify-content`])!==!1,js:T(e.js)?!0:`auto`,refresh:T(e.refresh)});if(t){P(n);return}U({title:`Content optimization`,target:n.url,status:`info`,summary:n.summary.verdict,metrics:[{label:`Score`,value:`${n.summary.score}/100`},{label:`Primary intent`,value:n.summary.primaryIntent},{label:`Primary query`,value:n.summary.primaryQuery??`None`},{label:`Queries`,value:z(n.summary.queries)},{label:`Opportunities`,value:z(n.summary.opportunities)},{label:`Estimated lift`,value:z(n.summary.estimatedClickLift)}]}),G(`Top actions`,n.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),n.brief.sections.length&&(process.stdout.write(`
40
40
  Suggested sections
41
41
  `),W([`Heading`,`Queries`],n.brief.sections.map(e=>[H(e.heading,48),H(e.queries.join(`, `),80)]))),n.intentMix.length&&(process.stdout.write(`
42
42
  Intent mix
43
- `),W([`Intent`,`Queries`,`Impressions`,`Clicks`],n.intentMix.map(e=>[e.intent,z(e.queries),z(e.impressions),z(e.clicks)]))),K(`Caveats`,n.caveats)}})}}),ji={site:`--site`,url:`--url`,section:`--section`,date:`--date`,pages:`--pages`,dimensions:`--dimensions`,detail:`--detail`,offset:`--offset`},Mi=e=>/^[\w:/.,<>@#?=&%+-]+$/.test(String(e))?String(e):`"${e}"`,Ni=(e,t)=>[`seo ${e}`,...Object.entries(t??{}).filter(([,e])=>e!==void 0).map(([e,t])=>`${ji[e]??`--${e}`} ${Mi(t??``)}`)].join(` `),Pi={account:{type:`string`,description:`Saved Google account email.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local cache and fetch fresh data.`}},Fi={"start-date":{type:`string`,description:`Optional YYYY-MM-DD.`},"end-date":{type:`string`,description:`Optional YYYY-MM-DD.`}},Ii={detail:{type:`string`,description:`summary (default), rows for the next page, or full.`},offset:{type:`string`,description:`rows only: the first row.`}};function Li(e){let t=C(e.detail)??`summary`;if(![`summary`,`rows`,`full`].includes(t))throw new d(`INVALID_INPUT`,`--detail is summary, rows or full.`);return t}function Ri(e,t){return pi(t,{refresh:w(e.refresh),account:C(e.account)})}async function q(e,t){try{let n=await t(oe({call:Ni,account:C(e.account),refresh:w(e.refresh)}));k(e)?P(n.data):process.stdout.write(`${n.text}\n`)}catch(e){throw xe(e)}}const zi=v({meta:{name:`report`,description:`The main Search Console report: overview and every section, then one section on request`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},section:{type:`string`,description:`Optional. One of ${Ut.join(`, `)}.`},...Fi,...Ii,...Pi},run:async({args:e})=>{let t=C(e.section);if(t&&!Ut.includes(t))throw new d(`INVALID_INPUT`,`--section is one of ${Ut.join(`, `)}.`);let n=C(e.site),r=t===`bing`?await Ri(e,n).catch(()=>R(n)):await Ri(e,n);await q(e,n=>yt({site:r,section:t,startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),detail:Li(e),offset:E(e.offset)},n))}}),Bi=v({meta:{name:`page`,description:`One URL: live page facts, Google index status and its queries`},args:{url:{type:`string`,description:`The page URL.`,required:!0},...Fi,...Ii,...Pi},run:async({args:t})=>{let n=C(t.url)??``;if(!/^https?:\/\/\S+$/.test(n))throw new d(`INVALID_INPUT`,`--url must be a full http(s) URL.`);let r=await Ri(t,n);await q(t,i=>e({site:r,url:n,startDate:C(t[`start-date`]),endDate:C(t[`end-date`]),detail:Li(t),offset:E(t.offset)},i))}}),Vi=v({meta:{name:`compare`,description:`Equal periods before and after a date, with the pages and queries that moved`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},date:{type:`string`,description:`YYYY-MM-DD: the first day after the change.`,required:!0},pages:{type:`string`,description:`Optional URL text, such as /blog/.`},...Pi},run:async({args:e})=>{let t=await Ri(e,C(e.site));await q(e,n=>Ue({site:t,date:C(e.date)??``,pages:C(e.pages)},n))}}),Hi=v({meta:{name:`index`,description:`Pages that lost most of their clicks, checked live and with URL Inspection`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},...Fi,...Pi},run:async({args:e})=>{let t=await Ri(e,C(e.site));await q(e,n=>Ce({site:t,startDate:C(e[`start-date`]),endDate:C(e[`end-date`])},n))}}),Ui=v({meta:{name:`data`,description:`Raw Search Console or Bing rows for any dimensions, beside the previous period`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},source:{type:`string`,description:`search_console (default) or bing. Bing takes the first dimension, query or page.`},dimensions:{type:`string`,description:`Comma-separated: ${It.join(`, `)}. Default query.`},page:{type:`string`,description:`Optional: only rows for pages whose URL contains this.`},query:{type:`string`,description:`Optional: only rows for queries that contain this.`},...Fi,...Ii,...Pi},run:async({args:e})=>{let t=O(e.dimensions)??[`query`],n=t.filter(e=>!It.includes(e));if(n.length)throw new d(`INVALID_INPUT`,`Unknown dimensions: ${n.join(`, `)}. Use ${It.join(`, `)}.`);let r=C(e.source)??`search_console`;if(![`search_console`,`bing`].includes(r))throw new d(`INVALID_INPUT`,`--source is search_console or bing.`);if(r===`bing`){let n=R(C(e.site));await q(e,r=>Xe({site:n,dimension:t[0]===`page`?`page`:`query`,startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),detail:Li(e),offset:E(e.offset)},r));return}let i=await Ri(e,C(e.site)),a=C(e.page),o=C(e.query);await q(e,n=>Gt({site:i,dimensions:t,filters:[...a?[{dimension:`page`,operator:`contains`,expression:a}]:[],...o?[{dimension:`query`,operator:`contains`,expression:o}]:[]],startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),detail:Li(e),offset:E(e.offset)},n))}}),Wi=v({meta:{name:`research`,description:`Keyword, SERP, competitor and backlink data from your DataForSEO or Ahrefs key`},args:{action:{type:`positional`,required:!0,description:st.join(`, `)},provider:{type:`string`,description:`${Jt.join(`, `)}. Default: the first one with a saved key.`},keywords:{type:`string`,description:`Comma-separated keywords.`},target:{type:`string`,description:`Domain or URL.`},country:{type:`string`,description:`Two-letter country code. Default us.`},...Ii,json:Pi.json},run:async({args:e})=>{let t=C(e.action);if(!st.includes(t))throw new d(`INVALID_INPUT`,`The action is one of ${st.join(`, `)}.`);let n=await ne(),r={dataforseo:`x-dataforseo-login`,ahrefs:`x-ahrefs-key`},i=C(e.provider)??Jt.find(e=>n.has(r[e]))??`dataforseo`;if(!Jt.includes(i))throw new d(`INVALID_INPUT`,`--provider is one of ${Jt.join(`, `)}.`);if(!n.has(r[i]))throw new d(`AUTH_CONFIG_REQUIRED`,`No ${i} key saved. Run \`seo providers ${i} connect\` first.`);let a=O(e.keywords)??[],o=C(e.target),s=C(e.country);await q(e,()=>Nt({provider:i,action:t,keywords:a,target:o,country:s,detail:Li(e),offset:E(e.offset)},n,{call:e=>Ni(`research`,{action:t,provider:i,keywords:a.join(`,`)||void 0,target:o,country:s,detail:`rows`,offset:e}).replace(`--action `,``)}))}});var Gi=class{stream;buffer=``;constructor(e){this.stream=e}async write(e){this.buffer+=e,this.buffer.length>=65536&&await this.flush()}async flush(){if(!this.buffer)return;let e=this.buffer;this.buffer=``,this.stream.write(e)||await new Promise((e,t)=>{let n=()=>{i(),e()},r=e=>{i(),t(e)},i=()=>{this.stream.off(`drain`,n),this.stream.off(`error`,r)};this.stream.once(`drain`,n),this.stream.once(`error`,r)})}};function Ki(e){return` `.repeat(e)}function qi(e){return e&&typeof e==`object`&&`toJSON`in e&&typeof e.toJSON==`function`?e.toJSON():e}async function Ji(e,t,n,r,i=!1){let a=qi(t);if(a===null)return await e.write(`null`),!0;if(typeof a==`string`||typeof a==`boolean`)return await e.write(JSON.stringify(a)),!0;if(typeof a==`number`)return await e.write(Number.isFinite(a)?String(a):`null`),!0;if(typeof a==`bigint`&&JSON.stringify(a),a===void 0||typeof a==`function`||typeof a==`symbol`)return i&&await e.write(`null`),i;if(!a||typeof a!=`object`)return!1;if(r.has(a))throw TypeError(`Converting circular structure to JSON`);r.add(a);try{if(Array.isArray(a)){if(a.length===0)return await e.write(`[]`),!0;await e.write(`[
43
+ `),W([`Intent`,`Queries`,`Impressions`,`Clicks`],n.intentMix.map(e=>[e.intent,z(e.queries),z(e.impressions),z(e.clicks)]))),K(`Caveats`,n.caveats)}})}}),zi={site:`--site`,url:`--url`,section:`--section`,date:`--date`,pages:`--pages`,dimensions:`--dimensions`,detail:`--detail`,offset:`--offset`},Bi=e=>/^[\w:/.,<>@#?=&%+-]+$/.test(String(e))?String(e):`"${e}"`,Vi=(e,t)=>[`seo ${e}`,...Object.entries(t??{}).filter(([,e])=>e!==void 0).map(([e,t])=>`${zi[e]??`--${e}`} ${Bi(t??``)}`)].join(` `),Hi={account:{type:`string`,description:`Saved Google account email.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local cache and fetch fresh data.`}},Ui={"start-date":{type:`string`,description:`Optional YYYY-MM-DD.`},"end-date":{type:`string`,description:`Optional YYYY-MM-DD.`}},Wi={detail:{type:`string`,description:`summary (default), rows for the next page, or full.`},offset:{type:`string`,description:`rows only: the first row.`}};function Gi(e){let t=w(e.detail)??`summary`;if(![`summary`,`rows`,`full`].includes(t))throw new p(`INVALID_INPUT`,`--detail is summary, rows or full.`);return t}function Ki(e,t){return xi(t,{refresh:T(e.refresh),account:w(e.account)})}async function q(e,t){try{let n=await t(se({call:Vi,account:w(e.account),refresh:T(e.refresh)}));k(e)?P(n.data):process.stdout.write(`${n.text}\n`)}catch(e){throw Ee(e)}}const qi=v({meta:{name:`report`,description:`The main Search Console report: overview and every section, then one section on request`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},section:{type:`string`,description:`Optional. One of ${Xt.join(`, `)}.`},...Ui,...Wi,...Hi},run:async({args:e})=>{let t=w(e.section);if(t&&!Xt.includes(t))throw new p(`INVALID_INPUT`,`--section is one of ${Xt.join(`, `)}.`);let n=w(e.site),r=t===`bing`?await Ki(e,n).catch(()=>R(n)):await Ki(e,n);await q(e,n=>Et({site:r,section:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:Gi(e),offset:E(e.offset)},n))}}),Ji=v({meta:{name:`page`,description:`One URL: live page facts, Google index status and its queries`},args:{url:{type:`string`,description:`The page URL.`,required:!0},...Ui,...Wi,...Hi},run:async({args:t})=>{let n=w(t.url)??``;if(!/^https?:\/\/\S+$/.test(n))throw new p(`INVALID_INPUT`,`--url must be a full http(s) URL.`);let r=await Ki(t,n);await q(t,i=>e({site:r,url:n,startDate:w(t[`start-date`]),endDate:w(t[`end-date`]),detail:Gi(t),offset:E(t.offset)},i))}}),Yi=v({meta:{name:`compare`,description:`Equal periods before and after a date, with the pages and queries that moved`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},date:{type:`string`,description:`YYYY-MM-DD: the first day after the change.`,required:!0},pages:{type:`string`,description:`Optional URL text, such as /blog/.`},...Hi},run:async({args:e})=>{let t=await Ki(e,w(e.site));await q(e,n=>Xe({site:t,date:w(e.date)??``,pages:w(e.pages)},n))}}),Xi=v({meta:{name:`index`,description:`Pages that lost most of their clicks, checked live and with URL Inspection`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},...Ui,...Hi},run:async({args:e})=>{let t=await Ki(e,w(e.site));await q(e,n=>ke({site:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`])},n))}}),Zi=v({meta:{name:`data`,description:`Raw Search Console or Bing rows for any dimensions, beside the previous period`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},source:{type:`string`,description:`search_console (default) or bing. Bing takes the first dimension, query or page.`},dimensions:{type:`string`,description:`Comma-separated: ${Ut.join(`, `)}. Default query.`},page:{type:`string`,description:`Optional: only rows for pages whose URL contains this.`},query:{type:`string`,description:`Optional: only rows for queries that contain this.`},...Ui,...Wi,...Hi},run:async({args:e})=>{let t=O(e.dimensions)??[`query`],n=t.filter(e=>!Ut.includes(e));if(n.length)throw new p(`INVALID_INPUT`,`Unknown dimensions: ${n.join(`, `)}. Use ${Ut.join(`, `)}.`);let r=w(e.source)??`search_console`;if(![`search_console`,`bing`].includes(r))throw new p(`INVALID_INPUT`,`--source is search_console or bing.`);if(r===`bing`){let n=R(w(e.site));await q(e,r=>rt({site:n,dimension:t[0]===`page`?`page`:`query`,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:Gi(e),offset:E(e.offset)},r));return}let i=await Ki(e,w(e.site)),a=w(e.page),o=w(e.query);await q(e,n=>Qt({site:i,dimensions:t,filters:[...a?[{dimension:`page`,operator:`contains`,expression:a}]:[],...o?[{dimension:`query`,operator:`contains`,expression:o}]:[]],startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:Gi(e),offset:E(e.offset)},n))}}),Qi=v({meta:{name:`research`,description:`Keyword, SERP, competitor and backlink data from your DataForSEO or Ahrefs key`},args:{action:{type:`positional`,required:!0,description:mt.join(`, `)},provider:{type:`string`,description:`${tn.join(`, `)}. Default: the first one with a saved key.`},keywords:{type:`string`,description:`Comma-separated keywords.`},target:{type:`string`,description:`Domain or URL.`},country:{type:`string`,description:`Two-letter country code. Default us.`},...Wi,json:Hi.json},run:async({args:e})=>{let t=w(e.action);if(!mt.includes(t))throw new p(`INVALID_INPUT`,`The action is one of ${mt.join(`, `)}.`);let n=await re(),r={dataforseo:`x-dataforseo-login`,ahrefs:`x-ahrefs-key`},i=w(e.provider)??tn.find(e=>n.has(r[e]))??`dataforseo`;if(!tn.includes(i))throw new p(`INVALID_INPUT`,`--provider is one of ${tn.join(`, `)}.`);if(!n.has(r[i]))throw new p(`AUTH_CONFIG_REQUIRED`,`No ${i} key. Save it at https://seoskill.dev/account#keys and run \`seo login\`, or run \`seo providers ${i} connect\` to keep it on this machine only.`);let a=O(e.keywords)??[],o=w(e.target),s=w(e.country);await q(e,()=>Bt({provider:i,action:t,keywords:a,target:o,country:s,detail:Gi(e),offset:E(e.offset)},n,{call:e=>Vi(`research`,{action:t,provider:i,keywords:a.join(`,`)||void 0,target:o,country:s,detail:`rows`,offset:e}).replace(`--action `,``)}))}});var $i=class{stream;buffer=``;constructor(e){this.stream=e}async write(e){this.buffer+=e,this.buffer.length>=65536&&await this.flush()}async flush(){if(!this.buffer)return;let e=this.buffer;this.buffer=``,this.stream.write(e)||await new Promise((e,t)=>{let n=()=>{i(),e()},r=e=>{i(),t(e)},i=()=>{this.stream.off(`drain`,n),this.stream.off(`error`,r)};this.stream.once(`drain`,n),this.stream.once(`error`,r)})}};function ea(e){return` `.repeat(e)}function ta(e){return e&&typeof e==`object`&&`toJSON`in e&&typeof e.toJSON==`function`?e.toJSON():e}async function na(e,t,n,r,i=!1){let a=ta(t);if(a===null)return await e.write(`null`),!0;if(typeof a==`string`||typeof a==`boolean`)return await e.write(JSON.stringify(a)),!0;if(typeof a==`number`)return await e.write(Number.isFinite(a)?String(a):`null`),!0;if(typeof a==`bigint`&&JSON.stringify(a),a===void 0||typeof a==`function`||typeof a==`symbol`)return i&&await e.write(`null`),i;if(!a||typeof a!=`object`)return!1;if(r.has(a))throw TypeError(`Converting circular structure to JSON`);r.add(a);try{if(Array.isArray(a)){if(a.length===0)return await e.write(`[]`),!0;await e.write(`[
44
44
  `);for(let t=0;t<a.length;t+=1)t>0&&await e.write(`,
45
- `),await e.write(Ki(n+1)),await Ji(e,a[t],n+1,r,!0);return await e.write(`\n${Ki(n)}]`),!0}let t=Object.entries(a).filter(([,e])=>{let t=qi(e);return![`undefined`,`function`,`symbol`].includes(typeof t)});if(t.length===0)return await e.write(`{}`),!0;await e.write(`{
45
+ `),await e.write(ea(n+1)),await na(e,a[t],n+1,r,!0);return await e.write(`\n${ea(n)}]`),!0}let t=Object.entries(a).filter(([,e])=>{let t=ta(e);return![`undefined`,`function`,`symbol`].includes(typeof t)});if(t.length===0)return await e.write(`{}`),!0;await e.write(`{
46
46
  `);for(let i=0;i<t.length;i+=1){let[a,o]=t[i];i>0&&await e.write(`,
47
- `),await e.write(`${Ki(n+1)}${JSON.stringify(a)}: `),await Ji(e,o,n+1,r)}return await e.write(`\n${Ki(n)}}`),!0}finally{r.delete(a)}}async function Yi(e,t){let n=new Gi(e);await Ji(n,t,0,new Set)||await n.write(`undefined`),await n.write(`
48
- `),await n.flush()}async function Xi(e,t){if(!e){await Yi(process.stdout,t);return}await Mn(Dn(e),{recursive:!0});let n=hn(e);try{await Yi(n,t),n.end(),await Qn(n)}catch(e){throw n.destroy(),e}process.stdout.write(`Wrote ${e}\n`)}function Zi(e){return e===`high`?`fail`:`warning`}function Qi(e,t=We(e)){let n=Be(e),i=e.status===`failed`||e.summary.highIssues>0?`fail`:e.status===`partial`?`unknown`:e.summary.mediumIssues>0||e.summary.lowIssues>0?`warning`:`pass`,a=e.access.samples.slice(0,5).map(e=>({status:`fail`,title:e.evidence.guidance.summary,explanation:`${e.evidence.provider} returned ${e.evidence.kind} evidence for the crawler request.`,evidence:[e.url],fix:e.evidence.guidance.recommendedAction})),o=t.slice(0,10).map(e=>({status:Zi(e.severity),title:`${e.title} on ${e.count} ${e.count===1?`URL`:`URLs`}`,explanation:r(e.ruleId)?.whyItMatters??e.whyThisRanks,evidence:e.sampleUrls.slice(0,5),fix:e.howToFix})),s=n.slice(0,10).map(e=>({status:`warning`,title:`${e.title} on ${e.count} ${e.count===1?`URL`:`URLs`}`,explanation:r(e.ruleId)?.whyItMatters??e.whyThisRanks,evidence:e.sampleUrls.slice(0,5),fix:e.howToFix}));$r({title:e.config.strategy===`health`?`Sitemap health pass`:`Site crawl`,target:e.config.url,status:i,summary:e.status===`partial`?`Partial evidence from ${e.summary.totalPages} retained pages. Review the caveats before treating missing findings as an all-clear.`:`${e.summary.totalPages} pages retained with ${e.issues.length} findings.`,metrics:[{label:`Pages`,value:e.summary.totalPages},{label:`High`,value:e.summary.highIssues,status:`fail`},{label:`Medium`,value:e.summary.mediumIssues,status:`warning`},{label:`Low`,value:e.summary.lowIssues,status:`info`},{label:`Failed fetches`,value:e.summary.failedUrls}],sections:[{title:`Access diagnostics`,diagnostics:a},{title:`Prioritised fixes`,diagnostics:o},{title:`Review before changing anything`,diagnostics:s},...!a.length&&!o.length&&!s.length?[{title:`Checks`,diagnostics:[{status:`pass`,title:`No prioritised findings were observed`,explanation:`The evaluated crawl evidence did not produce a prioritised fix or review item.`}]}]:[]],notes:[`Strategy: ${e.config.strategy}. Data: ${e.status}. Report: ${e.id}.`,...e.warnings,...e.caveats]})}const $i={"google-analytics-property":{type:`string`,description:`Google Analytics property ID for landing-page sessions.`},"clicky-site-id":{type:`string`,description:`Clicky site ID for landing-page visits.`}};function ea(e){let t=C(e[`google-analytics-property`]),n=C(e[`clicky-site-id`]);if(t&&n)throw new d(`INVALID_INPUT`,`Pass either --google-analytics-property or --clicky-site-id, not both.`);if(t)return{provider:`google`,propertyId:t};if(n)return{provider:`clicky`,siteId:Ie(n)}}function ta(e){if(e.startsWith(`http://`)||e.startsWith(`https://`))return e;if(e.startsWith(`sc-domain:`))return`https://${e.slice(10)}/`}function na(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 ra(e){return e?e===`serp-framing`?`wording gap`:e===`content-gap`?`content gap`:e===`technical-check`?`technical check`:`covered`:`-`}const ia={high:3,medium:2,low:1},aa=v({meta:{name:`crawl`,description:`Run a fast sitemap health pass or a full technical crawl`},args:{crawlUrl:{type:`positional`,required:!1,description:`Site start URL. Optional with --sitemap-url.`},url:{type:`string`,description:`Start URL to crawl. Defaults to the --site home page.`},site:{type:`string`,description:`GSC property URL for joining page metrics.`},...$i,mode:{type:`string`,description:`Crawl mode: site, page, list, or sitemap. Start with sitemap --health for large sites.`},health:{type:`boolean`,default:!1,description:`Run the uncached sitemap status and redirect pass before a full audit. No page-body analysis.`},"sitemap-url":{type:`string`,description:`Explicit sitemap URL. Selects sitemap mode when --mode is omitted.`},urls:{type:`string`,description:`Comma-separated URLs for list mode.`},"urls-file":{type:`string`,description:`File with one URL per line for list mode.`},"max-pages":{type:`string`,description:`Maximum pages to crawl, up to 10,000. Defaults to 500.`},"max-depth":{type:`string`,description:`Maximum click depth, up to 64. Defaults to 16.`},concurrency:{type:`string`,description:`Parallel page fetches, up to 16. Defaults to 8, or progressively up to 4 with --health.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache and fetch fresh pages.`},include:{type:`string`,description:`Comma-separated URL patterns to include.`},exclude:{type:`string`,description:`Comma-separated URL patterns to exclude.`},"no-sitemap":{type:`boolean`,default:!1,description:`Do not seed URLs from sitemap.xml.`},"no-robots":{type:`boolean`,default:!1,description:`Do not skip URLs disallowed by robots.txt.`},"no-external":{type:`boolean`,default:!1,description:`Do not check external links. Reserved for full link checks.`},js:{type:`boolean`,default:!1,description:`Legacy alias for --rendering on.`},rendering:{type:`string`,description:`JavaScript rendering mode: auto, on, or off. Defaults to auto.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON. Alias for --format json.`},format:{type:`string`,description:`Output format: pretty, json, csv, html, markdown, or junit. JUnit requires --health.`},output:{type:`string`,description:`Write output to this path instead of stdout.`},csv:{type:`string`,description:`CSV table to render: issues or pages. Defaults to issues.`},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=k(e),n=la(e.format,t),r=C(e.output),i=ua(e.csv),a=sa(e.severity),o=sa(e[`fail-on`]),s=await da(e),c=ca(e),l=C(e[`sitemap-url`]),u=w(e.health),f=oa(e.mode);if(n===`junit`&&!u)throw Error(`--format junit requires --health.`);if((u||l)&&f&&f!==`sitemap`)throw Error(`--health and --sitemap-url require sitemap mode.`);if(u&&T(e,`sitemap`))throw Error(`--health cannot be combined with --no-sitemap.`);if((u||l)&&s.length)throw Error(`--health and --sitemap-url cannot be combined with URL list input.`);let ee=C(e.site),te=c??(ee?ta(ee):void 0)??(l?new URL(`/`,l).toString():void 0)??s[0];if(!te)throw new d(`INVALID_INPUT`,"No crawl URL given. Pass a URL, --url or --site. Run `seo sites` to list your Search Console properties.");let p=await he({url:te,site:ee,mode:f??(u||l?`sitemap`:s.length?`list`:void 0),strategy:u?`health`:`full`,sitemapUrl:l,urls:s,maxPages:E(e[`max-pages`]),maxDepth:E(e[`max-depth`]),concurrency:E(e.concurrency),refresh:w(e.refresh),fetchRate:pr({...e,"fetch-concurrency":e.concurrency}),include:O(e.include),exclude:O(e.exclude),googleAnalyticsPropertyId:C(e[`google-analytics-property`]),analyticsConnection:ea(e),useSitemap:!T(e,`sitemap`),respectRobots:!T(e,`robots`),checkExternal:!T(e,`external`),js:lr(e)}),ne=We(p,{severity:a}),m=o?p.issues.some(e=>ia[e.severity]>=ia[o]):!1,h=p.status===`failed`,ie={...p,topFixes:ne,reviewObservations:Be(p,{severity:a}),...o?{failOn:o,failedThreshold:m}:{}};if(n===`json`){await Xi(r,ie),(h||m)&&(process.exitCode=1);return}if(n===`csv`){await pa(r,i===`pages`?le(p):Re(p)),(h||m)&&(process.exitCode=1);return}if(n===`html`){await pa(r,re(p,ne)),(h||m)&&(process.exitCode=1);return}if(n===`junit`){await pa(r,de(p)),(h||m)&&(process.exitCode=1);return}if(n===`markdown`){await pa(r,Vt(p,ne)),(h||m)&&(process.exitCode=1);return}if(r){await pa(r,He(p,ne)),(h||m)&&(process.exitCode=1);return}Qi(p,ne),o&&(process.stdout.write(`
47
+ `),await e.write(`${ea(n+1)}${JSON.stringify(a)}: `),await na(e,o,n+1,r)}return await e.write(`\n${ea(n)}}`),!0}finally{r.delete(a)}}async function ra(e,t){let n=new $i(e);await na(n,t,0,new Set)||await n.write(`undefined`),await n.write(`
48
+ `),await n.flush()}async function ia(e,t){if(!e){await ra(process.stdout,t);return}await Bn(Tn(e),{recursive:!0});let n=jn(e);try{await ra(n,t),n.end(),await ar(n)}catch(e){throw n.destroy(),e}process.stdout.write(`Wrote ${e}\n`)}function aa(e){return e===`high`?`fail`:`warning`}function oa(e,t=Jt(e)){let n=pe(e),r=e.status===`failed`||e.summary.highIssues>0?`fail`:e.status===`partial`?`unknown`:e.summary.mediumIssues>0||e.summary.lowIssues>0?`warning`:`pass`,i=e.access.samples.slice(0,5).map(e=>({status:`fail`,title:e.evidence.guidance.summary,explanation:`${e.evidence.provider} returned ${e.evidence.kind} evidence for the crawler request.`,evidence:[e.url],fix:e.evidence.guidance.recommendedAction})),a=t.slice(0,10).map(e=>({status:aa(e.severity),title:`${e.title} on ${e.count} ${e.count===1?`URL`:`URLs`}`,explanation:Me(e.ruleId)?.whyItMatters??e.whyThisRanks,evidence:e.sampleUrls.slice(0,5),fix:e.howToFix})),o=n.slice(0,10).map(e=>({status:`warning`,title:`${e.title} on ${e.count} ${e.count===1?`URL`:`URLs`}`,explanation:Me(e.ruleId)?.whyItMatters??e.whyThisRanks,evidence:e.sampleUrls.slice(0,5),fix:e.howToFix}));si({title:e.config.strategy===`health`?`Sitemap health pass`:`Site crawl`,target:e.config.url,status:r,summary:e.status===`partial`?`Partial evidence from ${e.summary.totalPages} retained pages. Review the caveats before treating missing findings as an all-clear.`:`${e.summary.totalPages} pages retained with ${e.issues.length} findings.`,metrics:[{label:`Pages`,value:e.summary.totalPages},{label:`High`,value:e.summary.highIssues,status:`fail`},{label:`Medium`,value:e.summary.mediumIssues,status:`warning`},{label:`Low`,value:e.summary.lowIssues,status:`info`},{label:`Failed fetches`,value:e.summary.failedUrls}],sections:[{title:`Access diagnostics`,diagnostics:i},{title:`Prioritised fixes`,diagnostics:a},{title:`Review before changing anything`,diagnostics:o},...!i.length&&!a.length&&!o.length?[{title:`Checks`,diagnostics:[{status:`pass`,title:`No prioritised findings were observed`,explanation:`The evaluated crawl evidence did not produce a prioritised fix or review item.`}]}]:[]],notes:[`Strategy: ${e.config.strategy}. Data: ${e.status}. Report: ${e.id}.`,...e.warnings,...e.caveats]})}const sa={"google-analytics-property":{type:`string`,description:`Google Analytics property ID for landing-page sessions.`},"clicky-site-id":{type:`string`,description:`Clicky site ID for landing-page visits.`}};function ca(e){let t=w(e[`google-analytics-property`]),n=w(e[`clicky-site-id`]);if(t&&n)throw new p(`INVALID_INPUT`,`Pass either --google-analytics-property or --clicky-site-id, not both.`);if(t)return{provider:`google`,propertyId:t};if(n)return{provider:`clicky`,siteId:ge(n)}}function la(e){if(e.startsWith(`http://`)||e.startsWith(`https://`))return e;if(e.startsWith(`sc-domain:`))return`https://${e.slice(10)}/`}function ua(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 da(e){return e?e===`serp-framing`?`wording gap`:e===`content-gap`?`content gap`:e===`technical-check`?`technical check`:`covered`:`-`}const fa={high:3,medium:2,low:1},pa=v({meta:{name:`crawl`,description:`Run a fast sitemap health pass or a full technical crawl`},args:{crawlUrl:{type:`positional`,required:!1,description:`Site start URL. Optional with --sitemap-url.`},url:{type:`string`,description:`Start URL to crawl. Defaults to the --site home page.`},site:{type:`string`,description:`GSC property URL for joining page metrics.`},...sa,mode:{type:`string`,description:`Crawl mode: site, page, list, or sitemap. Start with sitemap --health for large sites.`},health:{type:`boolean`,default:!1,description:`Run the uncached sitemap status and redirect pass before a full audit. No page-body analysis.`},"sitemap-url":{type:`string`,description:`Explicit sitemap URL. Selects sitemap mode when --mode is omitted.`},urls:{type:`string`,description:`Comma-separated URLs for list mode.`},"urls-file":{type:`string`,description:`File with one URL per line for list mode.`},"max-pages":{type:`string`,description:`Maximum pages to crawl, up to 10,000. Defaults to 500.`},"max-depth":{type:`string`,description:`Maximum click depth, up to 64. Defaults to 16.`},concurrency:{type:`string`,description:`Parallel page fetches, up to 16. Defaults to 8, or progressively up to 4 with --health.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache and fetch fresh pages.`},include:{type:`string`,description:`Comma-separated URL patterns to include.`},exclude:{type:`string`,description:`Comma-separated URL patterns to exclude.`},"no-sitemap":{type:`boolean`,default:!1,description:`Do not seed URLs from sitemap.xml.`},"no-robots":{type:`boolean`,default:!1,description:`Do not skip URLs disallowed by robots.txt.`},"no-external":{type:`boolean`,default:!1,description:`Do not check external links. Reserved for full link checks.`},js:{type:`boolean`,default:!1,description:`Legacy alias for --rendering on.`},rendering:{type:`string`,description:`JavaScript rendering mode: auto, on, or off. Defaults to auto.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON. Alias for --format json.`},format:{type:`string`,description:`Output format: pretty, json, csv, html, markdown, or junit. JUnit requires --health.`},output:{type:`string`,description:`Write output to this path instead of stdout.`},csv:{type:`string`,description:`CSV table to render: issues or pages. Defaults to issues.`},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=k(e),n=_a(e.format,t),r=w(e.output),i=va(e.csv),a=ha(e.severity),s=ha(e[`fail-on`]),c=await ya(e),l=ga(e),u=w(e[`sitemap-url`]),d=T(e.health),ee=ma(e.mode);if(n===`junit`&&!d)throw Error(`--format junit requires --health.`);if((d||u)&&ee&&ee!==`sitemap`)throw Error(`--health and --sitemap-url require sitemap mode.`);if(d&&_r(e,`sitemap`))throw Error(`--health cannot be combined with --no-sitemap.`);if((d||u)&&c.length)throw Error(`--health and --sitemap-url cannot be combined with URL list input.`);let te=w(e.site),ne=l??(te?la(te):void 0)??(u?new URL(`/`,u).toString():void 0)??c[0];if(!ne)throw new p(`INVALID_INPUT`,"No crawl URL given. Pass a URL, --url or --site. Run `seo sites` to list your Search Console properties.");let f=await Te({url:ne,site:te,mode:ee??(d||u?`sitemap`:c.length?`list`:void 0),strategy:d?`health`:`full`,sitemapUrl:u,urls:c,maxPages:E(e[`max-pages`]),maxDepth:E(e[`max-depth`]),concurrency:E(e.concurrency),refresh:T(e.refresh),fetchRate:xr({...e,"fetch-concurrency":e.concurrency}),include:O(e.include),exclude:O(e.exclude),googleAnalyticsPropertyId:w(e[`google-analytics-property`]),analyticsConnection:ca(e),useSitemap:!_r(e,`sitemap`),respectRobots:!_r(e,`robots`),checkExternal:!_r(e,`external`),js:gr(e)}),re=Jt(f,{severity:a}),m=s?f.issues.some(e=>fa[e.severity]>=fa[s]):!1,h=f.status===`failed`,ae={...f,topFixes:re,reviewObservations:pe(f,{severity:a}),...s?{failOn:s,failedThreshold:m}:{}};if(n===`json`){await ia(r,ae),(h||m)&&(process.exitCode=1);return}if(n===`csv`){await xa(r,i===`pages`?Ge(f):o(f)),(h||m)&&(process.exitCode=1);return}if(n===`html`){await xa(r,Ue(f,re)),(h||m)&&(process.exitCode=1);return}if(n===`junit`){await xa(r,oe(f)),(h||m)&&(process.exitCode=1);return}if(n===`markdown`){await xa(r,Ve(f,re)),(h||m)&&(process.exitCode=1);return}if(r){await xa(r,ie(f,re)),(h||m)&&(process.exitCode=1);return}oa(f,re),s&&(process.stdout.write(`
49
49
  Run metadata
50
- `),F([[`Fail threshold`,o]])),(h||m)&&(process.exitCode=1)}});function oa(e){let t=C(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function sa(e){let t=C(e);if(t){if([`low`,`medium`,`high`].includes(t))return t;throw Error(`Severity must be one of: low, medium, high.`)}}function ca(e){let t=C(e.crawlUrl),n=C(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}function la(e,t){let n=C(e);if(t&&n&&n!==`json`)throw Error(`Use either --json or --format, not both.`);if(!n)return t?`json`:`pretty`;if([`pretty`,`json`,`csv`,`html`,`markdown`,`junit`].includes(n))return n;throw Error(`Format must be one of: pretty, json, csv, html, markdown, junit.`)}function ua(e){let t=C(e);if(!t)return`issues`;if([`issues`,`pages`].includes(t))return t;throw Error(`CSV table must be one of: issues, pages.`)}async function da(e){let t=O(e.urls)??[],n=C(e[`urls-file`]);return n&&t.push(...fa(await Nn(n,`utf8`))),[...new Set(t)]}function fa(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}async function pa(e,t){if(!e){process.stdout.write(t);return}await Mn(Dn(e),{recursive:!0}),await Pn(e,t),process.stdout.write(`Wrote ${e}\n`)}const ma=v({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.`},account:{type:`string`,description:`Saved Google account email.`},"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 hr(e.body,e[`body-file`])??{startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),dimensions:O(e.dimensions)??[`query`,`page`],type:C(e.type)??`web`,rowLimit:E(e.limit),dataState:`final`},n=k(e),r=R(C(e.site)??C(t.siteUrl));delete t.siteUrl;let i=await vt(r,t,{refresh:w(e.refresh),accountEmail:C(e.account)}),a=E(e.limit),o=a?i.rows.slice(0,a):i.rows;if(n){P({site:r,request:t,...i,rows:o,rowsReturned:o.length});return}U({title:`Search Console query`,target:r,status:i.rowsFetched>o.length?`unknown`:`info`,summary:`${o.length} rows returned from ${i.rowsFetched} fetched rows.`,metrics:[{label:`Rows returned`,value:o.length},{label:`Rows fetched`,value:i.rowsFetched},{label:`API calls`,value:i.calls}]}),I([`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)]))}}),ha=v({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.`},account:{type:`string`,description:`Saved Google account email.`},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=k(e),n=R(C(e.site)),r=C(e.url);if(!r)throw Error(`Pass --url.`);let i=await Ye({siteUrl:n,inspectionUrl:r,accountEmail:C(e.account),languageCode:C(e.language)});if(t){P(i);return}let a=i.inspectionResult?.indexStatusResult;U({title:`URL Inspection`,target:r,status:a===void 0?`unknown`:a.verdict===`PASS`?`pass`:`warning`,summary:a===void 0?`Google did not return index status evidence for this URL.`:`${a.verdict??`Unknown`}: ${a.coverageState??`Coverage state unavailable`}.`,metrics:[{label:`Property`,value:n},{label:`Robots`,value:a?.robotsTxtState??`Unknown`},{label:`Last crawl`,value:a?.lastCrawlTime??`Unknown`},{label:`Google canonical`,value:a?.googleCanonical??`Unknown`}]})}}),ga={days:{cli:`days`,arg:{type:`string`,description:`GSC lookback window. Defaults to 28.`}},recentDays:{cli:`recent`,arg:{type:`string`,description:`Recent anomaly window in days. Defaults to 14.`}},range:{cli:`days`,arg:{type:`string`,description:`GSC lookback window. Defaults to 28.`}},limit:{cli:`limit`,arg:{type:`string`,description:`Maximum rows to return.`}},checkLimit:{cli:`check-limit`,arg:{type:`string`,description:`Maximum candidate pages to fetch and check.`}},minImpressions:{cli:`min-impressions`,arg:{type:`string`,description:`Minimum query impressions.`}},includeBrand:{cli:`include-brand`,arg:{type:`boolean`,default:!1,description:`Include branded queries in opportunity reports.`}},verifyContent:{cli:`verify-content`,arg:{type:`boolean`,default:!1,description:`Verify top opportunities against page title, meta, and content.`}},verifyLimit:{cli:`verify-limit`,arg:{type:`string`,description:`Maximum opportunity URLs to verify.`}},js:{cli:`js`,arg:{type:`boolean`,default:!1,description:`Force JavaScript rendering for verified pages.`}},fetchConcurrency:{cli:`fetch-concurrency`,arg:{type:`string`,description:`Maximum concurrent page fetches per host, up to 16. Defaults to 4.`}},fetchIntervalCap:{cli:`fetch-interval-cap`,arg:{type:`string`,description:`Maximum page fetches per interval per host. Defaults to 4.`}},fetchIntervalMs:{cli:`fetch-interval-ms`,arg:{type:`string`,description:`Fetch rate interval in milliseconds. Defaults to 1000.`}},refresh:{cli:`refresh`,arg:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh data.`}}};function J(e,t={}){return Object.fromEntries(e.map(e=>{let n=ga[e];return[n.cli,{...n.arg,...t[e]}]}))}function _a(e){return e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function va(e){if(e===null)return`n/a`;let t=Math.abs(e)>=10?e.toFixed(0):e.toFixed(1);return`${e>0?`+`:``}${t}%`}const ya=v({meta:{name:`traffic-anomaly`,description:`Detect unusual recent GSC traffic movement`},args:{site:{type:`string`},...J([`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=k(e),n=await ke({site:R(C(e.site)),days:E(e.days),recentDays:E(e.recent),refresh:w(e.refresh)});if(t){P(n);return}U({title:`Traffic anomaly report`,target:n.site,status:n.coverage?.status===`complete`?n.anomalies.some(e=>e.significant)?`warning`:`pass`:`unknown`,summary:n.anomalies.some(e=>e.significant)?`At least one recent metric moved beyond the report threshold.`:`No significant recent movement was found in the retained evidence.`,metrics:[{label:`Metrics checked`,value:n.anomalies.length},{label:`Significant`,value:n.anomalies.filter(e=>e.significant).length},{label:`Observed days`,value:n.coverage?.observedDays??`Unavailable`},{label:`Expected days`,value:n.coverage?.expectedDays??`Unavailable`}]}),W([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`,`Significant`],n.anomalies.map(e=>[e.metric,e.direction,_a(e.baselineMean),_a(e.comparisonMean),va(e.percentChange),e.zScore??`n/a`,e.significant?`yes`:`no`])),n.coverage&&K(`Evidence coverage`,[`${n.coverage.observedDays} of ${n.coverage.expectedDays} requested calendar days returned date aggregates.`,...n.coverage.caveats])}}),ba=v({meta:{name:`update-correlate`,description:`Compare traffic movement with official Google update windows`},args:{site:{type:`string`},...J([`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.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e),n=R(C(e.site)),r=await l({site:n,days:E(e.days),recentDays:E(e.recent),paddingDays:E(e[`padding-days`]),knownConfounders:C(e[`known-change`])?[C(e[`known-change`])??``]:void 0,refresh:w(e.refresh)});if(t){P(r);return}U({title:`Google update correlation`,target:r.site,status:`unknown`,summary:r.summary,metrics:[{label:`Classification`,value:r.classification.replaceAll(`-`,` `)},{label:`Attribution`,value:r.attribution.replaceAll(`-`,` `)},{label:`Confidence`,value:r.confidence},{label:`Updates matched`,value:r.overlappingUpdates.length},{label:`Known confounders`,value:r.confounders.length},{label:`Source`,value:r.source.name}]}),K(`Evidence`,r.evidence),K(`Report caveats`,r.caveats),K(`Recommended next checks`,r.actions),W([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`],r.anomalies.map(e=>[e.metric,e.direction,_a(e.baselineMean),_a(e.comparisonMean),va(e.percentChange),e.zScore??`n/a`])),r.overlappingUpdates.length&&(process.stdout.write(`
50
+ `),F([[`Fail threshold`,s]])),(h||m)&&(process.exitCode=1)}});function ma(e){let t=w(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function ha(e){let t=w(e);if(t){if([`low`,`medium`,`high`].includes(t))return t;throw Error(`Severity must be one of: low, medium, high.`)}}function ga(e){let t=w(e.crawlUrl),n=w(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}function _a(e,t){let n=w(e);if(t&&n&&n!==`json`)throw Error(`Use either --json or --format, not both.`);if(!n)return t?`json`:`pretty`;if([`pretty`,`json`,`csv`,`html`,`markdown`,`junit`].includes(n))return n;throw Error(`Format must be one of: pretty, json, csv, html, markdown, junit.`)}function va(e){let t=w(e);if(!t)return`issues`;if([`issues`,`pages`].includes(t))return t;throw Error(`CSV table must be one of: issues, pages.`)}async function ya(e){let t=O(e.urls)??[],n=w(e[`urls-file`]);return n&&t.push(...ba(await Vn(n,`utf8`))),[...new Set(t)]}function ba(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}async function xa(e,t){if(!e){process.stdout.write(t);return}await Bn(Tn(e),{recursive:!0}),await Hn(e,t),process.stdout.write(`Wrote ${e}\n`)}const Sa=v({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.`},account:{type:`string`,description:`Saved Google account email.`},"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 Cr(e.body,e[`body-file`])??{startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),dimensions:O(e.dimensions)??[`query`,`page`],type:w(e.type)??`web`,rowLimit:E(e.limit),dataState:`final`},n=k(e),r=R(w(e.site)??w(t.siteUrl));delete t.siteUrl;let i=await pt(r,t,{refresh:T(e.refresh),accountEmail:w(e.account)}),a=E(e.limit),o=a?i.rows.slice(0,a):i.rows;if(n){P({site:r,request:t,...i,rows:o,rowsReturned:o.length});return}U({title:`Search Console query`,target:r,status:i.rowsFetched>o.length?`unknown`:`info`,summary:`${o.length} rows returned from ${i.rowsFetched} fetched rows.`,metrics:[{label:`Rows returned`,value:o.length},{label:`Rows fetched`,value:i.rowsFetched},{label:`API calls`,value:i.calls}]}),I([`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)]))}}),Ca=v({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.`},account:{type:`string`,description:`Saved Google account email.`},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=k(e),n=R(w(e.site)),r=w(e.url);if(!r)throw Error(`Pass --url.`);let i=await en({siteUrl:n,inspectionUrl:r,accountEmail:w(e.account),languageCode:w(e.language)});if(t){P(i);return}let a=i.inspectionResult?.indexStatusResult;U({title:`URL Inspection`,target:r,status:a===void 0?`unknown`:a.verdict===`PASS`?`pass`:`warning`,summary:a===void 0?`Google did not return index status evidence for this URL.`:`${a.verdict??`Unknown`}: ${a.coverageState??`Coverage state unavailable`}.`,metrics:[{label:`Property`,value:n},{label:`Robots`,value:a?.robotsTxtState??`Unknown`},{label:`Last crawl`,value:a?.lastCrawlTime??`Unknown`},{label:`Google canonical`,value:a?.googleCanonical??`Unknown`}]})}}),wa={days:{cli:`days`,arg:{type:`string`,description:`GSC lookback window. Defaults to 28.`}},recentDays:{cli:`recent`,arg:{type:`string`,description:`Recent anomaly window in days. Defaults to 14.`}},range:{cli:`days`,arg:{type:`string`,description:`GSC lookback window. Defaults to 28.`}},limit:{cli:`limit`,arg:{type:`string`,description:`Maximum rows to return.`}},checkLimit:{cli:`check-limit`,arg:{type:`string`,description:`Maximum candidate pages to fetch and check.`}},minImpressions:{cli:`min-impressions`,arg:{type:`string`,description:`Minimum query impressions.`}},includeBrand:{cli:`include-brand`,arg:{type:`boolean`,default:!1,description:`Include branded queries in opportunity reports.`}},verifyContent:{cli:`verify-content`,arg:{type:`boolean`,default:!1,description:`Verify top opportunities against page title, meta, and content.`}},verifyLimit:{cli:`verify-limit`,arg:{type:`string`,description:`Maximum opportunity URLs to verify.`}},js:{cli:`js`,arg:{type:`boolean`,default:!1,description:`Force JavaScript rendering for verified pages.`}},fetchConcurrency:{cli:`fetch-concurrency`,arg:{type:`string`,description:`Maximum concurrent page fetches per host, up to 16. Defaults to 4.`}},fetchIntervalCap:{cli:`fetch-interval-cap`,arg:{type:`string`,description:`Maximum page fetches per interval per host. Defaults to 4.`}},fetchIntervalMs:{cli:`fetch-interval-ms`,arg:{type:`string`,description:`Fetch rate interval in milliseconds. Defaults to 1000.`}},refresh:{cli:`refresh`,arg:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh data.`}}};function J(e,t={}){return Object.fromEntries(e.map(e=>{let n=wa[e];return[n.cli,{...n.arg,...t[e]}]}))}function Ta(e){return e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function Ea(e){if(e===null)return`n/a`;let t=Math.abs(e)>=10?e.toFixed(0):e.toFixed(1);return`${e>0?`+`:``}${t}%`}const Da=v({meta:{name:`traffic-anomaly`,description:`Detect unusual recent GSC traffic movement`},args:{site:{type:`string`},...J([`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=k(e),n=await cn({site:R(w(e.site)),days:E(e.days),recentDays:E(e.recent),refresh:T(e.refresh)});if(t){P(n);return}U({title:`Traffic anomaly report`,target:n.site,status:n.coverage?.status===`complete`?n.anomalies.some(e=>e.significant)?`warning`:`pass`:`unknown`,summary:n.anomalies.some(e=>e.significant)?`At least one recent metric moved beyond the report threshold.`:`No significant recent movement was found in the retained evidence.`,metrics:[{label:`Metrics checked`,value:n.anomalies.length},{label:`Significant`,value:n.anomalies.filter(e=>e.significant).length},{label:`Observed days`,value:n.coverage?.observedDays??`Unavailable`},{label:`Expected days`,value:n.coverage?.expectedDays??`Unavailable`}]}),W([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`,`Significant`],n.anomalies.map(e=>[e.metric,e.direction,Ta(e.baselineMean),Ta(e.comparisonMean),Ea(e.percentChange),e.zScore??`n/a`,e.significant?`yes`:`no`])),n.coverage&&K(`Evidence coverage`,[`${n.coverage.observedDays} of ${n.coverage.expectedDays} requested calendar days returned date aggregates.`,...n.coverage.caveats])}}),Oa=v({meta:{name:`update-correlate`,description:`Compare traffic movement with official Google update windows`},args:{site:{type:`string`},...J([`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.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e),n=R(w(e.site)),r=await _n({site:n,days:E(e.days),recentDays:E(e.recent),paddingDays:E(e[`padding-days`]),knownConfounders:w(e[`known-change`])?[w(e[`known-change`])??``]:void 0,refresh:T(e.refresh)});if(t){P(r);return}U({title:`Google update correlation`,target:r.site,status:`unknown`,summary:r.summary,metrics:[{label:`Classification`,value:r.classification.replaceAll(`-`,` `)},{label:`Attribution`,value:r.attribution.replaceAll(`-`,` `)},{label:`Confidence`,value:r.confidence},{label:`Updates matched`,value:r.overlappingUpdates.length},{label:`Known confounders`,value:r.confounders.length},{label:`Source`,value:r.source.name}]}),K(`Evidence`,r.evidence),K(`Report caveats`,r.caveats),K(`Recommended next checks`,r.actions),W([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`],r.anomalies.map(e=>[e.metric,e.direction,Ta(e.baselineMean),Ta(e.comparisonMean),Ea(e.percentChange),e.zScore??`n/a`])),r.overlappingUpdates.length&&(process.stdout.write(`
51
51
  Updates
52
- `),I([`Start`,`End`,`Type`,`Name`],r.overlappingUpdates.map(e=>[e.start.slice(0,10),e.end?.slice(0,10)??`open`,e.type,e.name]))),vi(`seo segment-impact --site ${JSON.stringify(n)} --dimension page`)}}),xa={site:{type:`string`,description:`Search Console property, for example sc-domain:example.com.`}};function Sa(e){return{type:`string`,description:`Output folder. Defaults to ./seo-export/<site>-${e}-YYYY-MM-DD.`}}function Ca(e){return e.toLowerCase().replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)}function wa(e){let t=new Date().toISOString().slice(0,10),n=Ca(e.site);return kn(process.cwd(),`seo-export`,`${n}-${e.report}-${t}`)}async function Ta(e,n){await Mn(e,{recursive:!0});let r=[];for(let i of n){let n=kn(e,i.filename);await Pn(n,t(i.rows,i.headers),`utf8`),r.push(n)}return r}function Ea(e,t){process.stdout.write(`Wrote ${i(t.length,`CSV file`)} to ${e}\n`);for(let e of t)process.stdout.write(`- ${e}\n`)}const Da=v({meta:{name:`refresh-priorities`,description:`Export the ranked SEO priority queue, score breakdowns, grouped findings, and diagnosis detail CSVs.`},args:{...xa,out:Sa(`refresh-priorities`),...J([`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.`}}),...$i,"verify-content":cr(`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=R(C(e.site)),n=await zt({site:t,days:E(e.days),recentDays:E(e.recent),limit:E(e.limit),includeBrand:w(e[`include-brand`]),googleAnalyticsPropertyId:C(e[`google-analytics-property`]),analyticsConnection:ea(e),verifyContent:w(e[`verify-content`]),verifyLimit:E(e[`verify-limit`]),refresh:w(e.refresh)}),r=C(e.out)??wa({report:`refresh-priorities`,site:t});Ea(r,await Ta(r,we(n)))}}),Oa=v({meta:{name:`export`,description:`Export full report data to CSV files`},subCommands:{"update-postmortem":v({meta:{name:`update-postmortem`,description:`Export update postmortem attribution, findings, template movement, and segment movers.`},args:{...xa,out:Sa(`update-postmortem`),...J([`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.`}},run:async({args:e})=>{let t=R(C(e.site)),n=await ut({site:t,days:E(e.days),recentDays:E(e.recent),limit:E(e.limit),includeBrand:w(e[`include-brand`]),knownConfounders:C(e[`known-change`])?[C(e[`known-change`])??``]:void 0,refresh:w(e.refresh)}),r=C(e.out)??wa({report:`update-postmortem`,site:t});Ea(r,await Ta(r,or(n)))}}),"refresh-priorities":Da}});function ka(e){let t=e.platform===`win32`?An:On;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 Aa(e={}){let t=e.home??wn(),n=e.platform??process.platform,r=ka({home:t,platform:n,env:e.env??process.env}),i=n===`win32`?An:On,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 ja(e,t={}){let n=t.platform??process.platform,r=t.exists??g,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=_(e,t);if(r(n))return n}for(let e of a){let t=_(Dn(i),e);if(r(t))return t}return e}function Ma(e){return ja(e)!==e}function Na(e={}){let t=e.targets??Aa(),n=e.hasCommand??Ma,r=e.hasPath??g;return t.filter(e=>e.kind===`native`?e.commandNames.some(n):r(e.path)||e.detectionPaths.some(r)||e.commandNames.some(n))}const Pa={insertSpaces:!0,tabSize:2,eol:`
53
- `};function Fa(){return new Date().toISOString().replace(/[:.]/g,`-`)}function Ia(e,t){gn(Dn(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.${Date.now()}.tmp`;Sn(n,t,{encoding:`utf8`,mode:g(e)?xn(e).mode&511:384}),bn(n,e)}function La(e){let t=`${e}.bak-${Fa()}`,n=t,r=2;for(;g(n);)n=`${t}-${r}`,r+=1;mn(e,n,pn.COPYFILE_EXCL)}function Ra(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function za(e){if(!g(e.path))return{source:`{}
54
- `,config:{}};let t=_n(e.path,`utf8`),n=[],r=tr(t,n,{allowTrailingComma:!0});if(n.length>0){let t=n[0],r=t?`${nr(t.error)} at offset ${t.offset}`:`unknown parse error`;throw Error(`Cannot update ${e.path}: invalid JSONC (${r}).`)}if(!Ra(r))throw Error(`Cannot update ${e.path}: config root must be an object.`);if(r.mcpServers!==void 0&&!Ra(r.mcpServers))throw Error(`Cannot update ${e.path}: mcpServers must be an object.`);return{source:t,config:r}}function Ba(e){return e.includes(`mcp`)&&e.includes(`serve`)&&e.some(e=>e===`seo`||e.startsWith(`seo@`)||e===`@seo/cli`)}function Va(e,t){return typeof e.command!=`string`||t.length!==3||t[1]!==`mcp`||t[2]!==`serve`||!Ra(e.env)?!1:e.env.SEO_MCP_CONFIGURED_BY===`seo`}function Ha(e){if(!Ra(e)||!Array.isArray(e.args))return!1;let t=e.args.filter(e=>typeof e==`string`);return Ba(t)||Va(e,t)}function Ua(e){let t=$n(e.source,er(e.source,[`mcpServers`,e.name??`seo`],e.value,{formattingOptions:Pa}));g(e.target.path)&&La(e.target.path),Ia(e.target.path,t)}function Wa(e,t){let n=Rn(e,t,{encoding:`utf8`});return{status:n.status,stdout:n.stdout??``,stderr:n.stderr??``,error:n.error}}function Ga(e){let t=e.replaceAll(`\\`,`/`).toLowerCase();return t.includes(`/_npx/`)||t.includes(`/.npm/_npx/`)||t.includes(`/.cache/pnpm/dlx/`)}function Ka(e){if(!e||!g(e))return;let t=yn(e);return Ga(t)?void 0:t}function qa(e={}){let t=Ka(e.cliPath??process.argv[1]);if(t)return{command:e.nodePath??process.execPath,args:[t,`mcp`,`serve`]};let n=`seo@${e.version??Ft}`;return(e.platform??process.platform)===`win32`?{command:`cmd`,args:[`/c`,`npx`,`-y`,n,`mcp`,`serve`]}:{command:`npx`,args:[`-y`,n,`mcp`,`serve`]}}function Ja(e=!1,t=qa()){let n=te(),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 Ya(e){return e.includes(`SEO_MCP_CONFIGURED_BY`)||/args:\s+-y\s+(?:seo(?:@\S+)?|@seo\/cli)\s+mcp\s+serve\b/.test(e)}function Xa(e,t,n){let r=ja(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&&!Ya(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=te(),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 Za(e,t={}){let n={runCommand:t.runCommand??Wa,reinstall:t.reinstall??!1,serverCommand:t.serverCommand??qa()};if(e.kind===`native`)return Xa(e,`install`,n);let{source:r,config:i}=za(e),a=i.mcpServers?.seo,o=Ja(e.includeType,n.serverCommand);if(Fn(a,o)&&!n.reinstall)return{client:e.client,path:e.path,changed:!1};if(a!==void 0&&!Ha(a))throw Error(`Cannot install SEO MCP: ${e.path} already has an unmanaged mcpServers.seo entry.`);return Ua({target:e,source:r,value:o}),{client:e.client,path:e.path,changed:!0}}function Qa(e,t={}){if(e.kind===`native`)return Xa(e,`uninstall`,{runCommand:t.runCommand??Wa,reinstall:!1,serverCommand:qa()});if(!g(e.path))return{client:e.client,path:e.path,changed:!1};let{source:n,config:r}=za(e),i=r.mcpServers;if(i?.seo===void 0)return{client:e.client,path:e.path,changed:!1};if(!Ha(i.seo))throw Error(`Cannot uninstall SEO MCP: ${e.path} has an unmanaged mcpServers.seo entry.`);return Ua({target:e,source:n,value:void 0}),{client:e.client,path:e.path,changed:!0}}const $a=`https://seoskill.dev/mcp`,eo=`seoskill`;function to(e){return e.client!==`claude-desktop`}function no(e){return e.includeType?{type:`http`,url:$a}:{url:$a}}function ro(e){return Ra(e)&&e.url===`https://seoskill.dev/mcp`}function io(e,t={}){if(!to(e))throw Error(`${e.label} takes the hosted server from its Connectors settings, not its config file.`);if(e.kind===`native`){let n=t.runCommand??Wa,r=ja(e.executable),i=n(r,[`mcp`,`get`,eo]);if(i.error?.code===`ENOENT`)throw Error("Cannot add the hosted MCP server for Codex: the `codex` command is not available on PATH.");if(i.status===0){if(i.stdout.includes(`https://seoskill.dev/mcp`))return{client:e.client,path:e.path,changed:!1};throw Error(`Cannot add the hosted MCP server: ${e.path} already has a different mcp_servers.${eo} entry.`)}let a=n(r,[`mcp`,`add`,eo,`--url`,$a]);if(a.error||a.status!==0){let e=a.error?.message??a.stderr.trim()??`unknown error`;throw Error(`Cannot add the hosted MCP server for Codex: ${e}`)}return{client:e.client,path:e.path,changed:!0}}let{source:n,config:r}=za(e),i=r.mcpServers?.[eo];if(ro(i))return{client:e.client,path:e.path,changed:!1};if(i!==void 0)throw Error(`Cannot add the hosted MCP server: ${e.path} already has a different mcpServers.${eo} entry.`);return Ua({target:e,source:n,value:no(e),name:eo}),{client:e.client,path:e.path,changed:!0}}function ao(e={}){let t=Rn(`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 oo(e){let t={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 so(){let e=await xi();return b(`Connected as ${e.account_email}. seo has read-only access and cannot change your site.`,`Google connected`),{status:`connected`,accountEmail:e.account_email}}async function co(e){let t=await ht();if(t.activeMode===`service-account`)return{status:`service-account`,accountEmail:t.identity};if(!e.interactive){if(t.tokens)return{status:`already-connected`,accountEmail:t.tokens.account_email};throw new d(`AUTH_REQUIRED`,"Not signed in. Run `seo start` or `seo auth login` in a terminal.")}let n=Qe();if(n.length>0){let e=L(await qn({message:`Google account to use`,options:[...n.map(e=>({value:{type:`account`,accountEmail:e.accountEmail},label:e.accountEmail,hint:e.active?`Current default`:void 0})),{value:{type:`connect`},label:`Connect another Google account`}]}));if(e.type===`account`)return Oe(e.accountEmail),{status:`already-connected`,accountEmail:e.accountEmail};if(t.sharedConfigured||t.byoConfigured)return so()}let r=L(await qn({message:`Connect Google now?`,options:oo({sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured})}));return r===`skip`?{status:`skipped`}:(r===`setup`&&nn({clientId:L(await Jn({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),clientSecret:L(await Kn({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}))}),so())}async function lo(){return L(await Hn({message:`Install the SEO skill so your agents know how to use seo?`,initialValue:!0}))?ao():{status:`declined`}}async function uo(){let e=Na();if(e.length===0)return[];let t=L(await qn({message:`Add an MCP server to your agents?`,options:[{value:`hosted`,label:`Free hosted server (recommended)`,hint:`${$a}, your agent asks you to sign in with Google`},{value:`local`,label:`Local server`,hint:`Runs on this machine with the sign-in from this setup`},{value:`skip`,label:`Skip for now`}]}));if(t===`skip`)return[];let n=L(await Gn({message:`Which agents?`,options:e.map(e=>({value:e.client,label:e.label,hint:e.path})),initialValues:e.map(e=>e.client)})),r=e.filter(e=>n.includes(e.client)).map(e=>{let n=t===`hosted`&&to(e)?`hosted`:`local`;try{return{...n===`hosted`?io(e):Za(e),server:n}}catch(t){return{client:e.client,path:e.path,server:n,changed:!1,error:t instanceof Error?t.message:String(t)}}});return t===`hosted`&&r.some(e=>e.client===`claude-desktop`)&&b(`Claude Desktop got the local server. To use the hosted one there, open Settings, then Connectors, and add ${$a} as a custom connector.`,`Claude Desktop`),r}const fo=[`seo sites`,`seo report --site <site>`],po=[`Sign in with Google (read-only Search Console and Google Analytics).`,`Add the free hosted MCP server (${$a}) or a local one to your agents.`,`Install the SEO skill for your agents.`];function mo(e){return e.status===`skipped`?`skipped`:e.status===`service-account`?`service account${e.accountEmail?` ${e.accountEmail}`:``}`:e.accountEmail??`connected`}function ho(e){return e.status===`installed`?`installed`:e.status===`failed`?`install failed`:`not installed`}function go(e){return e.length===0?`not added`:e.map(e=>e.error?`${e.client} skipped`:`${e.client} (${e.server})`).join(`, `)}function _o(){process.stdout.write(`
55
- `),Xr({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`})}async function vo(e){let t=k(e);if(t||y(process.argv[2]===`setup`?`seo setup`:`seo start`),e[`dry-run`]){t?P({dryRun:!0,steps:po,next:fo}):(b(po.map((e,t)=>`${t+1}. ${e}`).join(`
56
- `),`Setup will`),b(fo.join(`
57
- `),`Then run`),x(`Dry run complete. Nothing was changed.`));return}je();let n=N({json:t}),r=await co({interactive:n}),i=n?await uo():[],a=n?await lo():{status:`skipped`};if(t){P({auth:r,mcp:i,skill:a,next:fo});return}F([[`Google`,mo(r)],[`MCP server`,go(i)],[`SEO skill`,ho(a)]]);let o=i.filter(e=>e.error);o.length&&b(o.map(e=>`${e.client}: ${e.error}`).join(`
52
+ `),I([`Start`,`End`,`Type`,`Name`],r.overlappingUpdates.map(e=>[e.start.slice(0,10),e.end?.slice(0,10)??`open`,e.type,e.name]))),Ei(`seo segment-impact --site ${JSON.stringify(n)} --dimension page`)}}),ka={site:{type:`string`,description:`Search Console property, for example sc-domain:example.com.`}};function Aa(e){return{type:`string`,description:`Output folder. Defaults to ./seo-export/<site>-${e}-YYYY-MM-DD.`}}function ja(e){return e.toLowerCase().replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)}function Ma(e){let t=new Date().toISOString().slice(0,10),n=ja(e.site);return Dn(process.cwd(),`seo-export`,`${n}-${e.report}-${t}`)}async function Na(e,t){await Bn(e,{recursive:!0});let n=[];for(let r of t){let t=Dn(e,r.filename);await Hn(t,Ye(r.rows,r.headers),`utf8`),n.push(t)}return n}function Pa(e,t){process.stdout.write(`Wrote ${f(t.length,`CSV file`)} to ${e}\n`);for(let e of t)process.stdout.write(`- ${e}\n`)}const Fa=v({meta:{name:`refresh-priorities`,description:`Export the ranked SEO priority queue, score breakdowns, grouped findings, and diagnosis detail CSVs.`},args:{...ka,out:Aa(`refresh-priorities`),...J([`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.`}}),...sa,"verify-content":hr(`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=R(w(e.site)),n=await Ft({site:t,days:E(e.days),recentDays:E(e.recent),limit:E(e.limit),includeBrand:T(e[`include-brand`]),googleAnalyticsPropertyId:w(e[`google-analytics-property`]),analyticsConnection:ca(e),verifyContent:T(e[`verify-content`]),verifyLimit:E(e[`verify-limit`]),refresh:T(e.refresh)}),r=w(e.out)??Ma({report:`refresh-priorities`,site:t});Pa(r,await Na(r,de(n)))}}),Ia=v({meta:{name:`export`,description:`Export full report data to CSV files`},subCommands:{"update-postmortem":v({meta:{name:`update-postmortem`,description:`Export update postmortem attribution, findings, template movement, and segment movers.`},args:{...ka,out:Aa(`update-postmortem`),...J([`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.`}},run:async({args:e})=>{let t=R(w(e.site)),n=await lt({site:t,days:E(e.days),recentDays:E(e.recent),limit:E(e.limit),includeBrand:T(e[`include-brand`]),knownConfounders:w(e[`known-change`])?[w(e[`known-change`])??``]:void 0,refresh:T(e.refresh)}),r=w(e.out)??Ma({report:`update-postmortem`,site:t});Pa(r,await Na(r,pr(n)))}}),"refresh-priorities":Fa}});function La(e){let t=e.platform===`win32`?On:En;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 Ra(e={}){let t=e.home??Sn(),n=e.platform??process.platform,r=La({home:t,platform:n,env:e.env??process.env}),i=n===`win32`?On:En,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 za(e,t={}){let n=t.platform??process.platform,r=t.exists??_,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=g(e,t);if(r(n))return n}for(let e of a){let t=g(Tn(i),e);if(r(t))return t}return e}function Ba(e){return za(e)!==e}function Va(e={}){let t=e.targets??Ra(),n=e.hasCommand??Ba,r=e.hasPath??_;return t.filter(e=>e.kind===`native`?e.commandNames.some(n):r(e.path)||e.detectionPaths.some(r)||e.commandNames.some(n))}const Ha={insertSpaces:!0,tabSize:2,eol:`
53
+ `};function Ua(){return new Date().toISOString().replace(/[:.]/g,`-`)}function Wa(e,t){Mn(Tn(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.${Date.now()}.tmp`;Rn(n,t,{encoding:`utf8`,mode:_(e)?Ln(e).mode&511:384}),In(n,e)}function Ga(e){let t=`${e}.bak-${Ua()}`,n=t,r=2;for(;_(n);)n=`${t}-${r}`,r+=1;An(e,n,kn.COPYFILE_EXCL)}function Ka(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qa(e){if(!_(e.path))return{source:`{}
54
+ `,config:{}};let t=Nn(e.path,`utf8`),n=[],r=cr(t,n,{allowTrailingComma:!0});if(n.length>0){let t=n[0],r=t?`${lr(t.error)} at offset ${t.offset}`:`unknown parse error`;throw Error(`Cannot update ${e.path}: invalid JSONC (${r}).`)}if(!Ka(r))throw Error(`Cannot update ${e.path}: config root must be an object.`);if(r.mcpServers!==void 0&&!Ka(r.mcpServers))throw Error(`Cannot update ${e.path}: mcpServers must be an object.`);return{source:t,config:r}}function Ja(e){return e.includes(`mcp`)&&e.includes(`serve`)&&e.some(e=>e===`seo`||e.startsWith(`seo@`)||e===`@seo/cli`)}function Ya(e,t){return typeof e.command!=`string`||t.length!==3||t[1]!==`mcp`||t[2]!==`serve`||!Ka(e.env)?!1:e.env.SEO_MCP_CONFIGURED_BY===`seo`}function Xa(e){if(!Ka(e)||!Array.isArray(e.args))return!1;let t=e.args.filter(e=>typeof e==`string`);return Ja(t)||Ya(e,t)}function Za(e){let t=or(e.source,sr(e.source,[`mcpServers`,e.name??`seo`],e.value,{formattingOptions:Ha}));_(e.target.path)&&Ga(e.target.path),Wa(e.target.path,t)}function Qa(e,t){let n=Kn(e,t,{encoding:`utf8`});return{status:n.status,stdout:n.stdout??``,stderr:n.stderr??``,error:n.error}}function $a(e){let t=e.replaceAll(`\\`,`/`).toLowerCase();return t.includes(`/_npx/`)||t.includes(`/.npm/_npx/`)||t.includes(`/.cache/pnpm/dlx/`)}function eo(e){if(!e||!_(e))return;let t=Fn(e);return $a(t)?void 0:t}function to(e={}){let t=eo(e.cliPath??process.argv[1]);if(t)return{command:e.nodePath??process.execPath,args:[t,`mcp`,`serve`]};let n=`seo@${e.version??zt}`;return(e.platform??process.platform)===`win32`?{command:`cmd`,args:[`/c`,`npx`,`-y`,n,`mcp`,`serve`]}:{command:`npx`,args:[`-y`,n,`mcp`,`serve`]}}function no(e=!1,t=to()){let n=r(),i={command:t.command,args:t.args,env:{SEO_CONFIG_DIR:n.configDir,SEO_MCP_CONFIGURED_BY:`seo`}};return e&&(i.type=`stdio`),i}function ro(e){return e.includes(`SEO_MCP_CONFIGURED_BY`)||/args:\s+-y\s+(?:seo(?:@\S+)?|@seo\/cli)\s+mcp\s+serve\b/.test(e)}function io(e,t,n){let i=za(e.executable),a=n.runCommand(i,[`mcp`,`get`,`seo`]);if(a.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 o=a.status===0;if(o&&!ro(a.stdout))throw Error(`Cannot ${t} SEO MCP: ${e.path} already has an unmanaged mcp_servers.seo entry.`);if(t===`install`&&o&&!n.reinstall||t===`uninstall`&&!o)return{client:e.client,path:e.path,changed:!1};if(t===`install`&&o){let e=n.runCommand(i,[`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 s=r(),c=t===`install`?[`mcp`,`add`,`seo`,`--env`,`SEO_CONFIG_DIR=${s.configDir}`,`--env`,`SEO_MCP_CONFIGURED_BY=seo`,`--`,n.serverCommand.command,...n.serverCommand.args]:[`mcp`,`remove`,`seo`],l=n.runCommand(i,c);if(l.error||l.status!==0){let e=l.error?.message??l.stderr.trim()??`unknown error`;throw Error(`Cannot ${t} SEO MCP for Codex: ${e}`)}return{client:e.client,path:e.path,changed:!0}}function ao(e,t={}){let n={runCommand:t.runCommand??Qa,reinstall:t.reinstall??!1,serverCommand:t.serverCommand??to()};if(e.kind===`native`)return io(e,`install`,n);let{source:r,config:i}=qa(e),a=i.mcpServers?.seo,o=no(e.includeType,n.serverCommand);if(Un(a,o)&&!n.reinstall)return{client:e.client,path:e.path,changed:!1};if(a!==void 0&&!Xa(a))throw Error(`Cannot install SEO MCP: ${e.path} already has an unmanaged mcpServers.seo entry.`);return Za({target:e,source:r,value:o}),{client:e.client,path:e.path,changed:!0}}function oo(e,t={}){if(e.kind===`native`)return io(e,`uninstall`,{runCommand:t.runCommand??Qa,reinstall:!1,serverCommand:to()});if(!_(e.path))return{client:e.client,path:e.path,changed:!1};let{source:n,config:r}=qa(e),i=r.mcpServers;if(i?.seo===void 0)return{client:e.client,path:e.path,changed:!1};if(!Xa(i.seo))throw Error(`Cannot uninstall SEO MCP: ${e.path} has an unmanaged mcpServers.seo entry.`);return Za({target:e,source:n,value:void 0}),{client:e.client,path:e.path,changed:!0}}const so=`https://seoskill.dev/mcp`,co=`seoskill`;function lo(e){return e.client!==`claude-desktop`}function uo(e){return e.includeType?{type:`http`,url:so}:{url:so}}function fo(e){return Ka(e)&&e.url===`https://seoskill.dev/mcp`}function po(e,t={}){if(!lo(e))throw Error(`${e.label} takes the hosted server from its Connectors settings, not its config file.`);if(e.kind===`native`){let n=t.runCommand??Qa,r=za(e.executable),i=n(r,[`mcp`,`get`,co]);if(i.error?.code===`ENOENT`)throw Error("Cannot add the hosted MCP server for Codex: the `codex` command is not available on PATH.");if(i.status===0){if(i.stdout.includes(`https://seoskill.dev/mcp`))return{client:e.client,path:e.path,changed:!1};throw Error(`Cannot add the hosted MCP server: ${e.path} already has a different mcp_servers.${co} entry.`)}let a=n(r,[`mcp`,`add`,co,`--url`,so]);if(a.error||a.status!==0){let e=a.error?.message??a.stderr.trim()??`unknown error`;throw Error(`Cannot add the hosted MCP server for Codex: ${e}`)}return{client:e.client,path:e.path,changed:!0}}let{source:n,config:r}=qa(e),i=r.mcpServers?.[co];if(fo(i))return{client:e.client,path:e.path,changed:!1};if(i!==void 0)throw Error(`Cannot add the hosted MCP server: ${e.path} already has a different mcpServers.${co} entry.`);return Za({target:e,source:n,value:uo(e),name:co}),{client:e.client,path:e.path,changed:!0}}function mo(e={}){let t=Kn(`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 ho(e){let t={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 go(){let e=await ki();return b(`Connected as ${e.account_email}. seo has read-only access and cannot change your site.`,`Google connected`),{status:`connected`,accountEmail:e.account_email}}async function _o(e){let t=await dt();if(t.activeMode===`service-account`)return{status:`service-account`,accountEmail:t.identity};if(!e.interactive){if(t.tokens)return{status:`already-connected`,accountEmail:t.tokens.account_email};throw new p(`AUTH_REQUIRED`,"Not signed in. Run `seo start` or `seo auth login` in a terminal.")}let n=yt();if(n.length>0){let e=L(await er({message:`Google account to use`,options:[...n.map(e=>({value:{type:`account`,accountEmail:e.accountEmail},label:e.accountEmail,hint:e.active?`Current default`:void 0})),{value:{type:`connect`},label:`Connect another Google account`}]}));if(e.type===`account`)return sn(e.accountEmail),{status:`already-connected`,accountEmail:e.accountEmail};if(t.sharedConfigured||t.byoConfigured)return go()}let r=L(await er({message:`Connect Google now?`,options:ho({sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured})}));return r===`skip`?{status:`skipped`}:(r===`setup`&&at({clientId:L(await tr({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),clientSecret:L(await S({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}))}),go())}async function vo(){return L(await Xn({message:`Install the SEO skill so your agents know how to use seo?`,initialValue:!0}))?mo():{status:`declined`}}async function yo(){let e=Va();if(e.length===0)return[];let t=L(await er({message:`Add an MCP server to your agents?`,options:[{value:`hosted`,label:`Free hosted server (recommended)`,hint:`${so}, your agent asks you to sign in with Google`},{value:`local`,label:`Local server`,hint:`Runs on this machine with the sign-in from this setup`},{value:`skip`,label:`Skip for now`}]}));if(t===`skip`)return[];let n=L(await $n({message:`Which agents?`,options:e.map(e=>({value:e.client,label:e.label,hint:e.path})),initialValues:e.map(e=>e.client)})),r=e.filter(e=>n.includes(e.client)).map(e=>{let n=t===`hosted`&&lo(e)?`hosted`:`local`;try{return{...n===`hosted`?po(e):ao(e),server:n}}catch(t){return{client:e.client,path:e.path,server:n,changed:!1,error:t instanceof Error?t.message:String(t)}}});return t===`hosted`&&r.some(e=>e.client===`claude-desktop`)&&b(`Claude Desktop got the local server. To use the hosted one there, open Settings, then Connectors, and add ${so} as a custom connector.`,`Claude Desktop`),r}const bo=[`seo sites`,`seo report --site <site>`],xo=[`Sign in with Google (read-only Search Console and Google Analytics).`,`Add the free hosted MCP server (${so}) or a local one to your agents.`,`Install the SEO skill for your agents.`];function So(e){return e.status===`skipped`?`skipped`:e.status===`service-account`?`service account${e.accountEmail?` ${e.accountEmail}`:``}`:e.accountEmail??`connected`}function Co(e){return e.status===`installed`?`installed`:e.status===`failed`?`install failed`:`not installed`}function wo(e){return e.length===0?`not added`:e.map(e=>e.error?`${e.client} skipped`:`${e.client} (${e.server})`).join(`, `)}function To(){process.stdout.write(`
55
+ `),ii({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`})}async function Eo(e){let t=k(e);if(t||y(process.argv[2]===`setup`?`seo setup`:`seo start`),e[`dry-run`]){t?P({dryRun:!0,steps:xo,next:bo}):(b(xo.map((e,t)=>`${t+1}. ${e}`).join(`
56
+ `),`Setup will`),b(bo.join(`
57
+ `),`Then run`),x(`Dry run complete. Nothing was changed.`));return}jt();let n=N({json:t}),r=await _o({interactive:n}),i=n?await yo():[],a=n?await vo():{status:`skipped`};if(t){P({auth:r,mcp:i,skill:a,next:bo});return}F([[`Google`,So(r)],[`MCP server`,wo(i)],[`SEO skill`,Co(a)]]);let o=i.filter(e=>e.error);o.length&&b(o.map(e=>`${e.client}: ${e.error}`).join(`
58
58
  `),`MCP setup skipped`),a.error&&b(a.error,`SEO skill install failed`),b([`seo sites list your Search Console properties`,`seo report --site <site> run the main report for one of them`].join(`
59
- `),`Try next`),x(`Setup complete.`),_o()}const yo=v({meta:{name:`setup`,description:`Sign in with Google, then add the MCP server and skill`},args:{"dry-run":{type:`boolean`,default:!1,description:`Show what setup does without changing anything.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON. Never prompts.`}},run:async({args:e})=>vo(e)}),bo=v({...yo,meta:{name:`start`,description:`Start here: sign in with Google, then add the MCP server and skill to your agents`}}),xo=v({...bo,meta:{name:`init`,description:"Legacy alias for `seo start`."}}),So=v({meta:{name:`logs`,description:`Manage local log retention`},subCommands:{prune:v({meta:{name:`prune`,description:`Rotate large logs and remove old local logs`},args:{quiet:{type:`boolean`,default:!1,description:`Do not print a result.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=me();if(k(e)){P(t);return}e.quiet||process.stdout.write(`Rotated ${t.rotated} and removed ${t.removed} log files. ${ai(t.sizeBytes)} retained.\n`)}})}}),Co=[{client:`claude-desktop`,flag:`claude-desktop`},{client:`claude-code`,flag:`claude-code`},{client:`codex`,flag:`codex`},{client:`cursor`,flag:`cursor`}];function wo(e,t){return w(e.all)?t:Co.filter(({flag:t})=>w(e[t])).map(({client:e})=>e)}const To=v({meta:{name:`mcp`,description:`MCP server helpers`},subCommands:{serve:v({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-DBHFmJmr.js`);await t({test:w(e.test)})}}),install:v({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(w(e.uninstall)&&w(e.reinstall))throw new d(`INVALID_INPUT`,`Use either --uninstall or --reinstall, not both.`);let t=Aa(),n=Na({targets:t}),r=k(e),i=wo(e,n.map(e=>e.client));if(i.length===0){if(!N({json:r}))throw new d(`INVALID_INPUT`,`Choose an MCP client with --claude-desktop, --claude-code, --codex, --cursor, or --all.`);let a=n.length>0?n:t;i=L(await Gn({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 d(`INVALID_INPUT`,`MCP setup is not supported for ${a.join(`, `)} on ${process.platform}.`);let o=t.filter(e=>i.includes(e.client)).map(t=>w(e.uninstall)?Qa(t):Za(t,{reinstall:w(e.reinstall)}));if(r){P({operation:w(e.uninstall)?`uninstall`:`install`,results:o});return}for(let e of o)process.stdout.write(`${e.changed?`updated`:`skipped`} ${e.client} · ${e.path}\n`)}})}}),Eo=v({meta:{name:`index-coverage`,description:`Find crawlable pages that deserve a closer Google index check`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},url:{type:`string`,description:`Start URL to crawl. Defaults to the home page.`},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=k(e),n=R(C(e.site)),r=fr(e.sitemaps),i=await $e({site:n,url:C(e.url),sitemaps:r.length?r:void 0,days:E(e.days),rowLimit:E(e[`row-limit`]),maxSitemapUrls:E(e[`max-sitemap-urls`]),itemsPerSection:E(e.limit),refresh:w(e.refresh)});if(t){P(i);return}U({title:`Index coverage`,target:i.site,status:i.sources.crawl.completeness===`complete`&&i.sources.searchConsole.completeness===`complete`?i.summary.crawlableCandidatesWithoutRetainedSearchVisibility>0?`warning`:`pass`:`unknown`,summary:`${i.summary.crawlableCandidatesWithoutRetainedSearchVisibility} crawlable pages need URL Inspection review.`,metrics:[{label:`Crawl report`,value:i.input.crawlReport.id},{label:`Crawl evidence`,value:i.sources.crawl.completeness},{label:`Sitemap evidence`,value:i.sources.sitemap.completeness},{label:`Search evidence`,value:i.sources.searchConsole.completeness},{label:`Search window`,value:`${i.sources.searchConsole.startDate} to ${i.sources.searchConsole.endDate}`},{label:`Search-visible pages`,value:i.summary.retainedSearchVisibleUrls},{label:`Blocked/non-indexable`,value:i.summary.blockedOrNonIndexableCrawlUrls},{label:`Sitemap only`,value:i.summary.sitemapOnlyUrls},{label:`Search Console only`,value:i.summary.searchConsoleOnlyUrls}]}),i.crawlableWithoutRetainedSearchVisibility.items.length&&(process.stdout.write(`
59
+ `),`Try next`),x(`Setup complete.`),To()}const Do=v({meta:{name:`setup`,description:`Sign in with Google, then add the MCP server and skill`},args:{"dry-run":{type:`boolean`,default:!1,description:`Show what setup does without changing anything.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON. Never prompts.`}},run:async({args:e})=>Eo(e)}),Oo=v({...Do,meta:{name:`start`,description:`Start here: sign in with Google, then add the MCP server and skill to your agents`}}),ko=v({...Oo,meta:{name:`init`,description:"Legacy alias for `seo start`."}}),Ao=e=>process.stdout.write(`${e}\n`);async function jo(){let{google:e,bing:t,keys:n}=await Fe();return{status:`linked`,google:e.map(e=>e.email),bing:t.length,keys:Object.keys(n).filter(e=>e!==`x-dataforseo-login`)}}function Mo(e){return[`Linked to your seoskill.dev account.`,`Google: ${e.google.join(`, `)||`none`}.`,`Bing: ${e.bing?`${e.bing} linked`:`not connected (add it at ${pn}/account)`}.`,`Keys: ${e.keys.length?e.keys.map(e=>e.replace(/^x-|-(key|password)$/g,``)).join(`, `):`none`}.`,`Next: seo sites, then seo report --site <site>.`].join(`
60
+ `)}const No=v({meta:{name:`login`,description:`Link this machine to your seoskill.dev account: its Google accounts, Bing and keys`},args:{json:{type:`boolean`,default:!1,description:`Print JSON.`}},run:async({args:e})=>{let t=k(e),n=async()=>{let e=await jo();t?P(e):Ao(Mo(e))};if(process.env.SEO_TOKEN?.trim()){await n();return}if(d()){let e=await Re();if(e===`linked`)return n();if(e===`pending`&&!N({json:t})){let e=d();t?P({status:`pending`,...Po(e)}):Ao(`Waiting for approval. Open ${e?.url} and click "Link this machine", then run \`seo login\` again.`);return}}else if(c()){await n();return}let r=d()??await we();if(!N({json:t})){t?P({status:`pending`,...Po(r)}):Ao([`Open this link in the person's browser and ask them to approve it:`,r.url,`Code: ${r.code}. After they approve, run \`seo login\` again.`].join(`
61
+ `));return}for(Ao(`Opening ${r.url}\nApprove code ${r.code} there. Waiting…`),await ne(r.url);d();){await new Promise(e=>setTimeout(e,3e3));let e=await Re();if(e===`linked`)return n();if(e===`expired`)break}Ao("The login expired. Run `seo login` again."),process.exitCode=1}}),Po=e=>({url:e?.url,code:e?.code}),Fo=v({meta:{name:`logout`,description:`Unlink this machine from your seoskill.dev account`},args:{json:{type:`boolean`,default:!1,description:`Print JSON.`}},run:async({args:e})=>{let t=await un();k(e)?P({unlinked:t}):Ao(t?`This machine is no longer linked to your seoskill.dev account.`:`This machine was not linked.`)}}),Io=v({meta:{name:`logs`,description:`Manage local log retention`},subCommands:{prune:v({meta:{name:`prune`,description:`Rotate large logs and remove old local logs`},args:{quiet:{type:`boolean`,default:!1,description:`Do not print a result.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=_e();if(k(e)){P(t);return}e.quiet||process.stdout.write(`Rotated ${t.rotated} and removed ${t.removed} log files. ${pi(t.sizeBytes)} retained.\n`)}})}}),Lo=[{client:`claude-desktop`,flag:`claude-desktop`},{client:`claude-code`,flag:`claude-code`},{client:`codex`,flag:`codex`},{client:`cursor`,flag:`cursor`}];function Ro(e,t){return T(e.all)?t:Lo.filter(({flag:t})=>T(e[t])).map(({client:e})=>e)}const zo=v({meta:{name:`mcp`,description:`MCP server helpers`},subCommands:{serve:v({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-BIlBtrjd.js`);await t({test:T(e.test)})}}),install:v({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(T(e.uninstall)&&T(e.reinstall))throw new p(`INVALID_INPUT`,`Use either --uninstall or --reinstall, not both.`);let t=Ra(),n=Va({targets:t}),r=k(e),i=Ro(e,n.map(e=>e.client));if(i.length===0){if(!N({json:r}))throw new p(`INVALID_INPUT`,`Choose an MCP client with --claude-desktop, --claude-code, --codex, --cursor, or --all.`);let a=n.length>0?n:t;i=L(await $n({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 p(`INVALID_INPUT`,`MCP setup is not supported for ${a.join(`, `)} on ${process.platform}.`);let o=t.filter(e=>i.includes(e.client)).map(t=>T(e.uninstall)?oo(t):ao(t,{reinstall:T(e.reinstall)}));if(r){P({operation:T(e.uninstall)?`uninstall`:`install`,results:o});return}for(let e of o)process.stdout.write(`${e.changed?`updated`:`skipped`} ${e.client} · ${e.path}\n`)}})}}),Bo=v({meta:{name:`index-coverage`,description:`Find crawlable pages that deserve a closer Google index check`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},url:{type:`string`,description:`Start URL to crawl. Defaults to the home page.`},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=k(e),n=R(w(e.site)),r=br(e.sitemaps),i=await bt({site:n,url:w(e.url),sitemaps:r.length?r:void 0,days:E(e.days),rowLimit:E(e[`row-limit`]),maxSitemapUrls:E(e[`max-sitemap-urls`]),itemsPerSection:E(e.limit),refresh:T(e.refresh)});if(t){P(i);return}U({title:`Index coverage`,target:i.site,status:i.sources.crawl.completeness===`complete`&&i.sources.searchConsole.completeness===`complete`?i.summary.crawlableCandidatesWithoutRetainedSearchVisibility>0?`warning`:`pass`:`unknown`,summary:`${i.summary.crawlableCandidatesWithoutRetainedSearchVisibility} crawlable pages need URL Inspection review.`,metrics:[{label:`Crawl report`,value:i.input.crawlReport.id},{label:`Crawl evidence`,value:i.sources.crawl.completeness},{label:`Sitemap evidence`,value:i.sources.sitemap.completeness},{label:`Search evidence`,value:i.sources.searchConsole.completeness},{label:`Search window`,value:`${i.sources.searchConsole.startDate} to ${i.sources.searchConsole.endDate}`},{label:`Search-visible pages`,value:i.summary.retainedSearchVisibleUrls},{label:`Blocked/non-indexable`,value:i.summary.blockedOrNonIndexableCrawlUrls},{label:`Sitemap only`,value:i.summary.sitemapOnlyUrls},{label:`Search Console only`,value:i.summary.searchConsoleOnlyUrls}]}),i.crawlableWithoutRetainedSearchVisibility.items.length&&(process.stdout.write(`
60
62
  Representative URL Inspection candidates
61
- `),I([`URL`,`Status`,`In sitemap`],i.crawlableWithoutRetainedSearchVisibility.items.map(e=>[H(e.url,80),e.status,e.inSitemap?`yes`:`no`]))),K(`How to read this report`,i.caveats)}}),Do=v({meta:{name:`link-recover`,description:`Find search-value URLs that are now broken, blocked, or poorly redirected`},args:{site:{type:`string`},...J([`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=k(e),n=await en({site:R(C(e.site)),days:E(e.days),limit:E(e.limit),minClicks:E(e[`min-clicks`]),minImpressions:E(e[`min-impressions`]),refresh:w(e.refresh),js:w(e.js)?!0:`auto`});if(t){P(n);return}U({title:`Link recovery`,target:n.site,status:n.warnings.length>0?`unknown`:n.summary.recoverable>0?`warning`:`pass`,summary:n.summary.recoverable>0?`${z(n.summary.recoverable)} previously visible URLs need recovery review.`:`No recoverable URLs were found in the retained evidence.`,metrics:[{label:`Range`,value:`${n.range.startDate} to ${n.range.endDate}`},{label:`Checked`,value:z(n.summary.checked)},{label:`Recoverable`,value:z(n.summary.recoverable)},{label:`High severity`,value:z(n.summary.high)},{label:`Clicks at risk`,value:z(n.summary.clicksAtRisk)},{label:`Impressions at risk`,value:z(n.summary.impressionsAtRisk)}]}),n.items.length&&(W([`Severity`,`Issue`,`Clicks`,`Impr`,`URL`,`Action`],n.items.map(e=>[e.severity,e.issue,z(e.clicks),z(e.impressions),H(e.url,56),H(e.recommendation.action,72)])),G(`Top recovery actions`,n.items.map(e=>({label:H(e.url,96),context:`${e.severity}, ${z(e.clicks)} clicks at risk`,action:e.recommendation.action})))),K(`Warnings`,n.warnings.slice(0,10))}}),Oo=v({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 un({url:C(e.url)??``,maxHops:E(e[`max-hops`]),refresh:w(e.refresh),js:w(e.js)?!0:`auto`});if(k(e)){P(t);return}U({title:`Redirect trace`,target:t.url,status:t.summary.issues.length>0?`warning`:t.summary.finalIndexable===void 0?`unknown`:`pass`,summary:t.summary.issues.length>0?t.summary.issues.join(`, `):`${t.summary.hops} redirect hops ended at HTTP ${t.summary.finalStatus}.`,metrics:[{label:`Final URL`,value:t.finalUrl},{label:`Final status`,value:t.summary.finalStatus},{label:`Indexable`,value:t.summary.finalIndexable===void 0?`Unknown`:t.summary.finalIndexable?`Yes`:`No`},{label:`Hops`,value:t.summary.hops}]}),I([`#`,`Status`,`URL`,`Next`],t.chain.map((e,t)=>[t+1,e.status,H(e.url,72),H(e.nextUrl??`-`,72)])),t.finalPage&&(process.stdout.write(`
63
+ `),I([`URL`,`Status`,`In sitemap`],i.crawlableWithoutRetainedSearchVisibility.items.map(e=>[H(e.url,80),e.status,e.inSitemap?`yes`:`no`]))),K(`How to read this report`,i.caveats)}}),Vo=v({meta:{name:`link-recover`,description:`Find search-value URLs that are now broken, blocked, or poorly redirected`},args:{site:{type:`string`},...J([`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=k(e),n=await Rt({site:R(w(e.site)),days:E(e.days),limit:E(e.limit),minClicks:E(e[`min-clicks`]),minImpressions:E(e[`min-impressions`]),refresh:T(e.refresh),js:T(e.js)?!0:`auto`});if(t){P(n);return}U({title:`Link recovery`,target:n.site,status:n.warnings.length>0?`unknown`:n.summary.recoverable>0?`warning`:`pass`,summary:n.summary.recoverable>0?`${z(n.summary.recoverable)} previously visible URLs need recovery review.`:`No recoverable URLs were found in the retained evidence.`,metrics:[{label:`Range`,value:`${n.range.startDate} to ${n.range.endDate}`},{label:`Checked`,value:z(n.summary.checked)},{label:`Recoverable`,value:z(n.summary.recoverable)},{label:`High severity`,value:z(n.summary.high)},{label:`Clicks at risk`,value:z(n.summary.clicksAtRisk)},{label:`Impressions at risk`,value:z(n.summary.impressionsAtRisk)}]}),n.items.length&&(W([`Severity`,`Issue`,`Clicks`,`Impr`,`URL`,`Action`],n.items.map(e=>[e.severity,e.issue,z(e.clicks),z(e.impressions),H(e.url,56),H(e.recommendation.action,72)])),G(`Top recovery actions`,n.items.map(e=>({label:H(e.url,96),context:`${e.severity}, ${z(e.clicks)} clicks at risk`,action:e.recommendation.action})))),K(`Warnings`,n.warnings.slice(0,10))}}),Ho=v({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 Ct({url:w(e.url)??``,maxHops:E(e[`max-hops`]),refresh:T(e.refresh),js:T(e.js)?!0:`auto`});if(k(e)){P(t);return}U({title:`Redirect trace`,target:t.url,status:t.summary.issues.length>0?`warning`:t.summary.finalIndexable===void 0?`unknown`:`pass`,summary:t.summary.issues.length>0?t.summary.issues.join(`, `):`${t.summary.hops} redirect hops ended at HTTP ${t.summary.finalStatus}.`,metrics:[{label:`Final URL`,value:t.finalUrl},{label:`Final status`,value:t.summary.finalStatus},{label:`Indexable`,value:t.summary.finalIndexable===void 0?`Unknown`:t.summary.finalIndexable?`Yes`:`No`},{label:`Hops`,value:t.summary.hops}]}),I([`#`,`Status`,`URL`,`Next`],t.chain.map((e,t)=>[t+1,e.status,H(e.url,72),H(e.nextUrl??`-`,72)])),t.finalPage&&(process.stdout.write(`
62
64
  Final page
63
- `),F([[`Title`,t.finalPage.title??`-`],[`Canonical`,t.finalPage.canonical??`-`],[`Meta robots`,t.finalPage.metaRobots??`-`]])),K(`Warnings`,t.warnings.slice(0,10))}}),ko=v({meta:{name:`ai-referrals`,description:`Find AI referral traffic detected in Google Analytics`},args:{property:{type:`string`,description:"Numeric Google Analytics property ID. Run `seo analytics google properties` to list them."},"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=k(e),n=await Wt({property:mi(C(e.property)),startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),maxRows:D(e[`max-rows`],`--max-rows`),resultLimit:D(e[`result-limit`],`--result-limit`),limit:D(e.limit,`--limit`),refresh:e.refresh===!0});if(t){P(n);return}if(U({title:`AI referral report`,target:n.property,status:n.dataStatus===`complete`?`info`:`unknown`,summary:n.summary.verdict,metrics:[{label:`Evidence`,value:n.dataStatus===`complete`?`Complete`:`Partial`,status:n.dataStatus===`complete`?`pass`:`unknown`},{label:`AI sessions`,value:z(n.summary.sessions)},{label:`AI users`,value:n.summary.totalUsers===null?`Unavailable`:z(n.summary.totalUsers)},{label:`Sources`,value:z(n.summary.sources)},{label:`Landing pages`,value:z(n.summary.landingPages)},{label:`Landing-page output`,value:`${z(n.selection.landingPages.returnedRows)} returned / ${z(n.selection.landingPages.retainedRows)} retained`},{label:`Source rows`,value:z(n.dataSource.sourceDiscovery.returnedRows)}]}),n.sources.length&&(process.stdout.write(`
65
+ `),F([[`Title`,t.finalPage.title??`-`],[`Canonical`,t.finalPage.canonical??`-`],[`Meta robots`,t.finalPage.metaRobots??`-`]])),K(`Warnings`,t.warnings.slice(0,10))}}),Uo=v({meta:{name:`ai-referrals`,description:`Find AI referral traffic detected in Google Analytics`},args:{property:{type:`string`,description:"Numeric Google Analytics property ID. Run `seo analytics google properties` to list them."},"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=k(e),n=await Yt({property:Si(w(e.property)),startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),maxRows:D(e[`max-rows`],`--max-rows`),resultLimit:D(e[`result-limit`],`--result-limit`),limit:D(e.limit,`--limit`),refresh:e.refresh===!0});if(t){P(n);return}if(U({title:`AI referral report`,target:n.property,status:n.dataStatus===`complete`?`info`:`unknown`,summary:n.summary.verdict,metrics:[{label:`Evidence`,value:n.dataStatus===`complete`?`Complete`:`Partial`,status:n.dataStatus===`complete`?`pass`:`unknown`},{label:`AI sessions`,value:z(n.summary.sessions)},{label:`AI users`,value:n.summary.totalUsers===null?`Unavailable`:z(n.summary.totalUsers)},{label:`Sources`,value:z(n.summary.sources)},{label:`Landing pages`,value:z(n.summary.landingPages)},{label:`Landing-page output`,value:`${z(n.selection.landingPages.returnedRows)} returned / ${z(n.selection.landingPages.retainedRows)} retained`},{label:`Source rows`,value:z(n.dataSource.sourceDiscovery.returnedRows)}]}),n.sources.length&&(process.stdout.write(`
64
66
  AI sources
65
67
  `),W([`Source`,`Sessions`,`Events`,`Share of AI sessions`],n.sources.map(e=>[e.label,z(e.sessions),z(e.eventCount),V(e.shareOfAiSessions)]))),n.landingPages.length&&(process.stdout.write(`
66
68
  Landing pages
67
69
  `),W([`Landing page`,`Sessions`,`Events`,`Top source`],n.landingPages.map(e=>[H(e.landingPage,64),z(e.sessions),z(e.eventCount),e.topSourceDetails.label]))),n.dataSource.partialReasons.length){process.stdout.write(`
68
70
  Evidence warnings
69
- `);for(let e of n.dataSource.partialReasons)process.stdout.write(`- ${e}\n`)}process.stdout.write(`\nNote: ${n.summary.caveat}\n`)}}),Ao=v({meta:{name:`cannibal`,description:`Find queries with material exposure across multiple URLs`},args:{site:{type:`string`},...J([`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=k(e),n=w(e.refresh),r=await be({site:R(C(e.site)),days:D(e.days,`--days`),limit:D(e.limit,`--limit`),minImpressions:D(e[`min-impressions`],`--min-impressions`),brandTerms:[...O(e[`brand-terms`])??[]],includeBrand:w(e[`include-brand`]),refresh:n});if(t){P(r);return}U({title:`Cannibalisation report`,target:r.site,status:r.dataStatus===`complete`?`info`:`unknown`,summary:r.summary.verdict,metrics:[{label:`Evidence`,value:r.dataStatus},{label:`Range`,value:`${r.range.startDate} to ${r.range.endDate}`},{label:`Eligible`,value:z(r.summary.eligibleClusters)},{label:`Returned`,value:z(r.summary.returnedClusters)},{label:`Suppressed brand queries`,value:z(r.summary.suppressedQueries)},{label:`GSC completeness`,value:r.source.completeness},{label:`Brand queries`,value:w(e[`include-brand`])?`included`:`excluded`}]}),W([`Query`,`URLs`,`Property impr`,`Exposure`,`HHI`,`Review first`],r.items.map(e=>[H(e.query,42),e.pages.length,e.propertyImpressions===void 0?`n/a`:z(e.propertyImpressions),z(e.pageExposureImpressions),e.hhi.toFixed(2),H(e.suggestedOwnerUrl,56)])),G(`Top cannibalisation actions`,r.items.map(e=>({label:e.query,context:`${e.pages.length} material URLs; first review ${H(e.suggestedOwnerUrl,64)}`,action:e.recommendation.action}))),K(`Report caveats`,r.caveats),K(`Provider usage`,[r.ledgerSummary])}}),jo=v({meta:{name:`ctr-underperformers`,description:`Find high-impression queries with weak CTR for their position`},args:{site:{type:`string`},...J([`includeBrand`,`minImpressions`],{minImpressions:{description:`Minimum query impressions. Defaults to 1 per 5,000 retained impressions, from 30 to 200.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=k(e),n=await St({site:R(C(e.site)),minImpressions:E(e[`min-impressions`]),includeBrand:w(e[`include-brand`])});if(t){P(n);return}U({title:`CTR underperformers`,target:n.site,status:n.dataStatus===`partial`?`unknown`:`info`,summary:n.summary.verdict,metrics:[{label:`Underperformers`,value:z(n.summary.underperformers)},{label:`Estimated click gap`,value:z(n.summary.estimatedClickShortfall)},{label:`Brand queries`,value:n.summary.brandFiltering},{label:`Evidence`,value:n.dataStatus},{label:`GSC completeness`,value:n.source.completeness}]}),K(`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.`]),K(`Recommended actions`,n.recommendations),K(`Report caveats`,n.caveats),W([`Query`,`URL`,`Pos`,`Impr`,`CTR`,`Expected`,`Gap`,`Action`],n.items.map(e=>[H(e.query,36),H(e.url,48),B(e.position),z(e.impressions),V(e.actualCtr),V(e.expectedCtr),z(e.clickShortfall),H(e.recommendation.action,72)])),G(`Top CTR actions`,n.items.map(e=>({label:e.query,context:`${z(e.clickShortfall)} click gap, ${V(e.actualCtr)} CTR`,action:e.recommendation.action})))}});function Mo(e){return e>0?B(e):`n/a`}const No=v({meta:{name:`decaying`,description:`Find query/page rows losing clicks between two GSC windows`},args:{site:{type:`string`},...J([`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=k(e),n=w(e.refresh),r=C(e.comparison),i=D(e.days,`--days`),a=D(e.limit,`--limit`),o=D(e[`min-drop-pct`],`--min-drop-pct`),s=D(e[`min-previous-clicks`],`--min-previous-clicks`),c=D(e[`min-click-loss`],`--min-click-loss`);if(r!==void 0&&r!==`previous-period`&&r!==`year-over-year`)throw new d(`INVALID_INPUT`,`--comparison must be previous-period or year-over-year.`);let l=await f({site:R(C(e.site)),days:i,limit:a,comparison:r,brandTerms:[...O(e[`brand-terms`])??[]],includeBrand:w(e[`include-brand`]),minDropPct:o,minPreviousClicks:s,minClickLoss:c,refresh:n});if(t){P(l);return}U({title:`Decaying pages`,target:l.site,status:l.dataStatus===`complete`?l.summary.returnedRows>0?`warning`:`pass`:`unknown`,summary:l.summary.verdict,metrics:[{label:`Evidence`,value:l.dataStatus},{label:`Comparison`,value:l.comparison},{label:`Observed declines`,value:z(l.summary.returnedRows)},{label:`Eligible declines`,value:z(l.summary.eligibleRows)},{label:`Decay clusters`,value:z(l.summary.groups)},{label:`Observed click decline`,value:z(l.summary.returnedObservedRetainedQueryClickLoss)},{label:`Eligible click decline`,value:z(l.summary.observedRetainedQueryClickLoss)},{label:`Brand queries`,value:l.summary.brandFiltering},{label:`Minimum drop`,value:`${l.filters.minDropPct}%`},{label:`Minimum previous clicks`,value:z(l.filters.minPreviousClicks)},{label:`GSC completeness`,value:l.source.completeness}]}),K(`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.`]),K(`Recommended actions`,l.recommendations),K(`Report caveats`,l.caveats),K(`Warnings`,l.warnings),l.items.length&&(l.groups.length&&(W([`Cluster`,`Rows`,`Observed loss`,`Drop`,`Sample query`,`Action`],l.groups.map(e=>[H(e.label,42),z(e.count),z(e.totalClickLoss),`${e.averageDropPct.toFixed(1)}%`,H(e.sampleQueries[0]??`-`,40),H(e.recommendation,72)])),G(`Top decay cluster actions`,l.groups.map(e=>({label:e.label,context:`${z(e.count)} retained rows, ${z(e.totalClickLoss)} observed click decline`,action:e.recommendation})))),W([`Query`,`Template`,`URL`,`Signals`,`Decline`,`Clicks`,`Impr`,`CTR`,`Pos`,`Action`],l.items.map(e=>[H(e.query,32),H(e.template.label,26),H(e.url,44),e.signals.join(`, `),z(e.clickLoss),`${z(e.previous.clicks)} -> ${z(e.current.clicks)}`,`${z(e.previous.impressions)} -> ${z(e.current.impressions)}`,`${V(e.previous.ctr)} -> ${V(e.current.ctr)}`,`${Mo(e.previous.position)} -> ${Mo(e.current.position)}`,H(e.recommendation.action,64)])),G(`Top decay actions`,l.items.map(e=>({label:e.query,context:`${e.template.label}, ${z(e.clickLoss)} fewer observed clicks`,action:e.recommendation.action}))))}}),Po=v({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.`},url:{type:`string`,required:!0,description:`Target page that should receive relevant internal links.`},...J([`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=k(e),n=w(e.refresh),r=D(e.days,`--days`),i=D(e.limit,`--limit`),a=D(e[`check-limit`],`--check-limit`),o=D(e[`min-impressions`],`--min-impressions`),s=mr(e),c=await sn({site:R(C(e.site)),targetUrl:C(e.url)??``,days:r,limit:i,checkLimit:a,minImpressions:o,brandTerms:[...O(e[`brand-terms`])??[]],includeBrand:w(e[`include-brand`]),js:w(e.js)?!0:void 0,rate:s,refresh:n});if(t){P(c);return}U({title:`Internal link opportunities`,target:c.targetUrl,status:c.summary.failedChecks>0||c.summary.uncheckedCandidates>0?`unknown`:`info`,summary:c.summary.verdict,metrics:[{label:`Target state`,value:c.target.verification},{label:`Preferred target`,value:c.target.preferredUrl},{label:`Target queries`,value:z(c.summary.targetQueries)},{label:`Matched sources`,value:z(c.summary.candidateSources)},{label:`Checked sources`,value:z(c.summary.checkedSources)},{label:`Attempted sources`,value:z(c.summary.attemptedSources)},{label:`Review candidates`,value:z(c.summary.returnedSources)},{label:`Technical exclusions`,value:z(c.summary.technicalExclusions)},{label:`Existing links`,value:z(c.summary.existingLinksObserved)},{label:`Failed checks`,value:z(c.summary.failedChecks)},{label:`Unchecked sources`,value:z(c.summary.uncheckedCandidates)},{label:`GSC completeness`,value:c.source.completeness},{label:`Brand queries`,value:c.summary.brandFiltering}]}),K(`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.`]),K(`Recommended actions`,c.recommendations),K(`Report caveats`,c.caveats),c.items.length&&(W([`Source URL`,`Matched impr`,`Match`,`Link evidence`,`Action`],c.items.map(e=>[H(e.sourceUrl,52),z(e.matchedQueryImpressions),e.bestMatchKind,e.linkEvidence.status,e.actionType])),G(`Top internal-link reviews`,c.items.map(e=>({label:H(e.sourceUrl,96),context:`${z(e.matchedQueryImpressions)} matched-query impressions; ${e.bestMatchKind}`,action:e.recommendation.action}))),K(`Provider usage`,[c.ledgerSummary]))}}),Fo=v({meta:{name:`page-opportunities`,description:`Find first-party traffic growth opportunities for one URL`},args:{site:{type:`string`},url:{type:`string`,required:!0},...J([`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":cr(`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=k(e),n=await qt({site:R(C(e.site)),url:C(e.url)??``,days:E(e.days),limit:E(e.limit),minImpressions:E(e[`min-impressions`]),includeBrand:w(e[`include-brand`]),verifyContent:w(e[`verify-content`])!==!1,js:w(e.js)?!0:`auto`,refresh:w(e.refresh)});if(t){P(n);return}if(U({title:`Page opportunities`,target:n.url,status:n.verification.status===`failed`?`unknown`:`info`,summary:n.summary.verdict,metrics:[{label:`Title`,value:n.page?.title??`Not fetched`},{label:`Fetch`,value:na(n.page?.fetchDiagnostics)},{label:`Verification`,value:n.verification.status},{label:`Rows`,value:`${z(n.selection.returnedRows)} returned / ${z(n.selection.eligibleRows)} eligible / ${z(n.selection.sourceRows)} source`},{label:`Queries`,value:z(n.summary.queries)},{label:`Impressions`,value:z(n.summary.impressions)},{label:`Opportunities`,value:z(n.summary.opportunities)},{label:`CTR shortfall`,value:z(n.summary.estimatedCtrClickShortfall)},{label:`Focus`,value:n.summary.focus},{label:`Evidence`,value:n.dataStatus}]}),K(`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.`]),K(`Recommended actions`,n.recommendations),K(`Report caveats`,n.caveats),!n.items.length){process.stdout.write(n.dataStatus===`empty`?`No GSC query rows found for this exact URL.
71
+ `);for(let e of n.dataSource.partialReasons)process.stdout.write(`- ${e}\n`)}process.stdout.write(`\nNote: ${n.summary.caveat}\n`)}}),Wo=v({meta:{name:`cannibal`,description:`Find queries with material exposure across multiple URLs`},args:{site:{type:`string`},...J([`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=k(e),n=T(e.refresh),r=await dn({site:R(w(e.site)),days:D(e.days,`--days`),limit:D(e.limit,`--limit`),minImpressions:D(e[`min-impressions`],`--min-impressions`),brandTerms:[...O(e[`brand-terms`])??[]],includeBrand:T(e[`include-brand`]),refresh:n});if(t){P(r);return}U({title:`Cannibalisation report`,target:r.site,status:r.dataStatus===`complete`?`info`:`unknown`,summary:r.summary.verdict,metrics:[{label:`Evidence`,value:r.dataStatus},{label:`Range`,value:`${r.range.startDate} to ${r.range.endDate}`},{label:`Eligible`,value:z(r.summary.eligibleClusters)},{label:`Returned`,value:z(r.summary.returnedClusters)},{label:`Suppressed brand queries`,value:z(r.summary.suppressedQueries)},{label:`GSC completeness`,value:r.source.completeness},{label:`Brand queries`,value:T(e[`include-brand`])?`included`:`excluded`}]}),W([`Query`,`URLs`,`Property impr`,`Exposure`,`HHI`,`Review first`],r.items.map(e=>[H(e.query,42),e.pages.length,e.propertyImpressions===void 0?`n/a`:z(e.propertyImpressions),z(e.pageExposureImpressions),e.hhi.toFixed(2),H(e.suggestedOwnerUrl,56)])),G(`Top cannibalisation actions`,r.items.map(e=>({label:e.query,context:`${e.pages.length} material URLs; first review ${H(e.suggestedOwnerUrl,64)}`,action:e.recommendation.action}))),K(`Report caveats`,r.caveats),K(`Provider usage`,[r.ledgerSummary])}}),Go=v({meta:{name:`ctr-underperformers`,description:`Find high-impression queries with weak CTR for their position`},args:{site:{type:`string`},...J([`includeBrand`,`minImpressions`],{minImpressions:{description:`Minimum query impressions. Defaults to 1 per 5,000 retained impressions, from 30 to 200.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=k(e),n=await ee({site:R(w(e.site)),minImpressions:E(e[`min-impressions`]),includeBrand:T(e[`include-brand`])});if(t){P(n);return}U({title:`CTR underperformers`,target:n.site,status:n.dataStatus===`partial`?`unknown`:`info`,summary:n.summary.verdict,metrics:[{label:`Underperformers`,value:z(n.summary.underperformers)},{label:`Estimated click gap`,value:z(n.summary.estimatedClickShortfall)},{label:`Brand queries`,value:n.summary.brandFiltering},{label:`Evidence`,value:n.dataStatus},{label:`GSC completeness`,value:n.source.completeness}]}),K(`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.`]),K(`Recommended actions`,n.recommendations),K(`Report caveats`,n.caveats),W([`Query`,`URL`,`Pos`,`Impr`,`CTR`,`Expected`,`Gap`,`Action`],n.items.map(e=>[H(e.query,36),H(e.url,48),B(e.position),z(e.impressions),V(e.actualCtr),V(e.expectedCtr),z(e.clickShortfall),H(e.recommendation.action,72)])),G(`Top CTR actions`,n.items.map(e=>({label:e.query,context:`${z(e.clickShortfall)} click gap, ${V(e.actualCtr)} CTR`,action:e.recommendation.action})))}});function Ko(e){return e>0?B(e):`n/a`}const qo=v({meta:{name:`decaying`,description:`Find query/page rows losing clicks between two GSC windows`},args:{site:{type:`string`},...J([`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=k(e),n=T(e.refresh),r=w(e.comparison),i=D(e.days,`--days`),a=D(e.limit,`--limit`),o=D(e[`min-drop-pct`],`--min-drop-pct`),s=D(e[`min-previous-clicks`],`--min-previous-clicks`),c=D(e[`min-click-loss`],`--min-click-loss`);if(r!==void 0&&r!==`previous-period`&&r!==`year-over-year`)throw new p(`INVALID_INPUT`,`--comparison must be previous-period or year-over-year.`);let u=await l({site:R(w(e.site)),days:i,limit:a,comparison:r,brandTerms:[...O(e[`brand-terms`])??[]],includeBrand:T(e[`include-brand`]),minDropPct:o,minPreviousClicks:s,minClickLoss:c,refresh:n});if(t){P(u);return}U({title:`Decaying pages`,target:u.site,status:u.dataStatus===`complete`?u.summary.returnedRows>0?`warning`:`pass`:`unknown`,summary:u.summary.verdict,metrics:[{label:`Evidence`,value:u.dataStatus},{label:`Comparison`,value:u.comparison},{label:`Observed declines`,value:z(u.summary.returnedRows)},{label:`Eligible declines`,value:z(u.summary.eligibleRows)},{label:`Decay clusters`,value:z(u.summary.groups)},{label:`Observed click decline`,value:z(u.summary.returnedObservedRetainedQueryClickLoss)},{label:`Eligible click decline`,value:z(u.summary.observedRetainedQueryClickLoss)},{label:`Brand queries`,value:u.summary.brandFiltering},{label:`Minimum drop`,value:`${u.filters.minDropPct}%`},{label:`Minimum previous clicks`,value:z(u.filters.minPreviousClicks)},{label:`GSC completeness`,value:u.source.completeness}]}),K(`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.`]),K(`Recommended actions`,u.recommendations),K(`Report caveats`,u.caveats),K(`Warnings`,u.warnings),u.items.length&&(u.groups.length&&(W([`Cluster`,`Rows`,`Observed loss`,`Drop`,`Sample query`,`Action`],u.groups.map(e=>[H(e.label,42),z(e.count),z(e.totalClickLoss),`${e.averageDropPct.toFixed(1)}%`,H(e.sampleQueries[0]??`-`,40),H(e.recommendation,72)])),G(`Top decay cluster actions`,u.groups.map(e=>({label:e.label,context:`${z(e.count)} retained rows, ${z(e.totalClickLoss)} observed click decline`,action:e.recommendation})))),W([`Query`,`Template`,`URL`,`Signals`,`Decline`,`Clicks`,`Impr`,`CTR`,`Pos`,`Action`],u.items.map(e=>[H(e.query,32),H(e.template.label,26),H(e.url,44),e.signals.join(`, `),z(e.clickLoss),`${z(e.previous.clicks)} -> ${z(e.current.clicks)}`,`${z(e.previous.impressions)} -> ${z(e.current.impressions)}`,`${V(e.previous.ctr)} -> ${V(e.current.ctr)}`,`${Ko(e.previous.position)} -> ${Ko(e.current.position)}`,H(e.recommendation.action,64)])),G(`Top decay actions`,u.items.map(e=>({label:e.query,context:`${e.template.label}, ${z(e.clickLoss)} fewer observed clicks`,action:e.recommendation.action}))))}}),Jo=v({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.`},url:{type:`string`,required:!0,description:`Target page that should receive relevant internal links.`},...J([`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=k(e),n=T(e.refresh),r=D(e.days,`--days`),i=D(e.limit,`--limit`),a=D(e[`check-limit`],`--check-limit`),o=D(e[`min-impressions`],`--min-impressions`),s=Sr(e),c=await et({site:R(w(e.site)),targetUrl:w(e.url)??``,days:r,limit:i,checkLimit:a,minImpressions:o,brandTerms:[...O(e[`brand-terms`])??[]],includeBrand:T(e[`include-brand`]),js:T(e.js)?!0:void 0,rate:s,refresh:n});if(t){P(c);return}U({title:`Internal link opportunities`,target:c.targetUrl,status:c.summary.failedChecks>0||c.summary.uncheckedCandidates>0?`unknown`:`info`,summary:c.summary.verdict,metrics:[{label:`Target state`,value:c.target.verification},{label:`Preferred target`,value:c.target.preferredUrl},{label:`Target queries`,value:z(c.summary.targetQueries)},{label:`Matched sources`,value:z(c.summary.candidateSources)},{label:`Checked sources`,value:z(c.summary.checkedSources)},{label:`Attempted sources`,value:z(c.summary.attemptedSources)},{label:`Review candidates`,value:z(c.summary.returnedSources)},{label:`Technical exclusions`,value:z(c.summary.technicalExclusions)},{label:`Existing links`,value:z(c.summary.existingLinksObserved)},{label:`Failed checks`,value:z(c.summary.failedChecks)},{label:`Unchecked sources`,value:z(c.summary.uncheckedCandidates)},{label:`GSC completeness`,value:c.source.completeness},{label:`Brand queries`,value:c.summary.brandFiltering}]}),K(`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.`]),K(`Recommended actions`,c.recommendations),K(`Report caveats`,c.caveats),c.items.length&&(W([`Source URL`,`Matched impr`,`Match`,`Link evidence`,`Action`],c.items.map(e=>[H(e.sourceUrl,52),z(e.matchedQueryImpressions),e.bestMatchKind,e.linkEvidence.status,e.actionType])),G(`Top internal-link reviews`,c.items.map(e=>({label:H(e.sourceUrl,96),context:`${z(e.matchedQueryImpressions)} matched-query impressions; ${e.bestMatchKind}`,action:e.recommendation.action}))),K(`Provider usage`,[c.ledgerSummary]))}}),Yo=v({meta:{name:`page-opportunities`,description:`Find first-party traffic growth opportunities for one URL`},args:{site:{type:`string`},url:{type:`string`,required:!0},...J([`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":hr(`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=k(e),n=await Ze({site:R(w(e.site)),url:w(e.url)??``,days:E(e.days),limit:E(e.limit),minImpressions:E(e[`min-impressions`]),includeBrand:T(e[`include-brand`]),verifyContent:T(e[`verify-content`])!==!1,js:T(e.js)?!0:`auto`,refresh:T(e.refresh)});if(t){P(n);return}if(U({title:`Page opportunities`,target:n.url,status:n.verification.status===`failed`?`unknown`:`info`,summary:n.summary.verdict,metrics:[{label:`Title`,value:n.page?.title??`Not fetched`},{label:`Fetch`,value:ua(n.page?.fetchDiagnostics)},{label:`Verification`,value:n.verification.status},{label:`Rows`,value:`${z(n.selection.returnedRows)} returned / ${z(n.selection.eligibleRows)} eligible / ${z(n.selection.sourceRows)} source`},{label:`Queries`,value:z(n.summary.queries)},{label:`Impressions`,value:z(n.summary.impressions)},{label:`Opportunities`,value:z(n.summary.opportunities)},{label:`CTR shortfall`,value:z(n.summary.estimatedCtrClickShortfall)},{label:`Focus`,value:n.summary.focus},{label:`Evidence`,value:n.dataStatus}]}),K(`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.`]),K(`Recommended actions`,n.recommendations),K(`Report caveats`,n.caveats),!n.items.length){process.stdout.write(n.dataStatus===`empty`?`No GSC query rows found for this exact URL.
70
72
  `:`GSC rows were found, but none met the report criteria.
71
- `);return}W([`Type`,`Query`,`Evidence`,`Pos`,`CTR`,`Expected`,`Impr`,`Shortfall`,`Action`],n.items.map(e=>[e.opportunityType,H(e.query,38),e.verification.signals.length?e.verification.signals.join(`, `):e.verification.status,e.position.toFixed(1),V(e.ctr),e.expectedCtr===void 0?`n/a`:V(e.expectedCtr),z(e.impressions),e.estimatedCtrClickShortfall===void 0?`n/a`:z(e.estimatedCtrClickShortfall),H(e.recommendation,72)])),G(`Top page actions`,n.items.map(e=>({label:e.query,context:`${e.opportunityType}, ${z(e.impressions)} impressions`,action:e.recommendation})))}}),Io=v({meta:{name:`query-cluster`,description:`Cluster GSC queries into repeated demand themes`},args:{site:{type:`string`},scope:{type:`string`},...J([`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=k(e),n=await pt({site:R(C(e.site)),scope:C(e.scope),includeBrand:w(e[`include-brand`]),minImpressions:E(e[`min-impressions`]),limit:E(e.limit)});if(t){P(n);return}U({title:`Query clusters`,target:n.site,status:`info`,summary:n.summary.verdict,metrics:[{label:`Scope`,value:n.scope??`All pages`},{label:`Clusters`,value:z(n.summary.clusters)},{label:`Queries`,value:z(n.summary.queries)},{label:`Impressions`,value:z(n.summary.impressions)},{label:`Clicks`,value:z(n.summary.clicks)},{label:`Minimum impressions`,value:z(n.summary.minImpressions)},{label:`Result limit`,value:z(n.summary.limit)},{label:`High opportunity`,value:z(n.summary.highOpportunityClusters)},{label:`Brand queries`,value:n.summary.brandFiltering}]}),K(`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.`]),K(`Recommended actions`,n.recommendations),K(`Report caveats`,n.caveats),W([`Cluster`,`Intent`,`Queries`,`Impr`,`CTR`,`Expected`,`Lift`,`Action`],n.clusters.map(e=>[H(e.label,32),e.intent,e.queries.length,z(e.totals?.impressions??0),V(e.totals?.ctr??0),V(e.benchmark?.expectedCtr??0),e.estimatedClickLift===void 0?`-`:z(e.estimatedClickLift),H(e.recommendation??``,72)])),G(`Top cluster actions`,n.clusters.map(e=>({label:e.label,context:`${z(e.totals?.impressions??0)} impressions, ${e.estimatedClickLift===void 0?`ranking opportunity`:`${z(e.estimatedClickLift)} estimated click lift`}`,action:e.recommendation??``})))}}),Lo=v({meta:{name:`quick-wins`,description:`Find high-ranking low-CTR query/page opportunities`},args:{site:{type:`string`},...J([`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=k(e),n=E(e[`verify-limit`]),r=w(e[`verify-content`])===!0||n!==void 0,i=await p({site:R(C(e.site)),days:E(e.days),limit:E(e.limit),minImpressions:E(e[`min-impressions`]),brandTerms:[...O(e[`brand-terms`])??[]],includeBrand:w(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:w(e.js)?!0:void 0,rate:pr(e),refresh:w(e.refresh)});if(t){P(i);return}U({title:`Quick wins`,target:i.site,status:i.source.possiblyTruncated?`unknown`:`info`,summary:i.summary.verdict,metrics:[{label:`Eligible rows`,value:z(i.summary.eligibleRows)},{label:`Returned rows`,value:z(i.summary.returnedRows)},{label:`Query clusters`,value:z(i.summary.repeatedQueryGroups)},{label:`Template patterns`,value:z(i.summary.templatePatterns)},{label:`CTR click shortfall`,value:z(i.summary.returnedEstimatedCtrClickShortfall)},{label:`Brand queries`,value:i.summary.brandFiltering},{label:`Evidence`,value:i.dataStatus},{label:`Verification`,value:hi(i)}]}),K(`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.`]),K(`Recommended actions`,i.recommendations),K(`Report caveats`,i.caveats),i.items.length&&(i.templateRecommendations.length&&(W([`Template`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Action`],i.templateRecommendations.map(e=>[H(e.templateLabel,34),z(e.urlCount),z(e.rowCount),z(e.totalEstimatedCtrClickShortfall),z(e.totalImpressions),H(e.action,72)])),G(`Top template actions`,i.templateRecommendations.map(e=>({label:e.templateLabel,context:`${z(e.urlCount)} URLs, ${z(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:`${e.action} ${e.evidence}`})))),i.groups.length&&(W([`Cluster`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Sample URL`,`Action`],i.groups.map(e=>[H(e.label,44),z(e.urlCount),z(e.rowCount),z(e.totalEstimatedCtrClickShortfall),z(e.totalImpressions),H(e.sampleUrls[0]??`-`,46),H(e.recommendation,72)])),G(`Top cluster actions`,i.groups.map(e=>({label:e.label,context:`${z(e.urlCount)} URLs, ${z(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:e.recommendation})))),W([`Query`,`Template`,`URL`,`Pos`,`Impr`,`CTR / target`,`Shortfall`,`Fetch`,`Check`,`Action`],i.items.map(e=>[H(e.query,36),H(e.template.label,24),H(e.url,48),B(e.position),z(e.impressions),`${V(e.ctr)} / ${V(e.targetCtr)}`,z(e.estimatedCtrClickShortfall),na(e.contentVerification?.fetchDiagnostics),ra(e.contentVerification?.classification),H(e.recommendation.action,64)])),G(`Top opportunity actions`,i.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${B(e.position)}, ${z(e.impressions)} impressions`,action:e.recommendation.action}))))}}),Ro=v({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.`},...J([`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=k(e),n=E(e[`verify-limit`]),r=w(e[`verify-content`])===!0||n!==void 0,i=await gt({site:R(C(e.site)),range:E(e.days),minImpressions:E(e[`min-impressions`]),limit:C(e.limit)?Number(C(e.limit)):10,includeBrand:w(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:w(e.js)?!0:void 0,rate:pr(e),refresh:w(e.refresh)});if(t){P(i);return}if(U({title:`Second-page opportunities`,target:i.site,status:i.source.possiblyTruncated||i.summary.fetchFailures>0?`unknown`:`info`,summary:i.summary.verdict,metrics:[{label:`Eligible pages`,value:z(i.summary.eligiblePages)},{label:`Returned pages`,value:z(i.summary.returnedPages)},{label:`Eligible queries`,value:z(i.summary.eligibleQueries)},{label:`Impressions`,value:z(i.summary.eligibleImpressions)},{label:`Content issues`,value:z(i.summary.contentIssues)},{label:`Technical issues`,value:z(i.summary.technicalIssues)},{label:`Fetch failures`,value:z(i.summary.fetchFailures)},{label:`Brand queries`,value:i.summary.brandFiltering},{label:`Evidence`,value:i.dataStatus},{label:`Verification`,value:hi(i)}]}),K(`Recommended actions`,i.recommendations),K(`Report caveats`,i.caveats),!i.items.length){process.stdout.write(`No average-position candidates matched this report.
72
- `),process.stdout.write(`${i.ledgerSummary}\n`);return}W([`Query`,`Template`,`Pos`,`Impr`,`CTR`,`Queries`,`Fetch`,`Check`,`Action`],i.items.map(e=>[e.primaryQuery,e.template.label,e.position.toFixed(1),Math.round(e.impressions),e.ctr.toFixed(3),z(e.queryCount),na(e.fetchDiagnostics),ra(e.contentVerification?.classification),e.recommendation.action])),G(`Top second-page actions`,i.items.map(e=>({label:e.primaryQuery,context:`${e.template.label}, pos ${B(e.position)}, ${z(e.impressions)} impressions`,action:e.recommendation.action}))),process.stdout.write(`${i.ledgerSummary}\n`)}}),zo=v({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.`},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=await Mt({url:C(e.url)??``,site:C(e.site),js:w(e.js)?!0:`auto`,refresh:w(e.refresh)});if(k(e)){P(t);return}U({title:`Page audit`,target:t.url,status:t.issues.some(e=>e.severity===`high`)?`fail`:t.issues.length>0?`warning`:`pass`,summary:t.issues.length>0?`${t.issues.length} ${t.issues.length===1?`issue needs`:`issues need`} review.`:`No page issues were found by the available checks.`,metrics:[{label:`Final URL`,value:t.page.finalUrl},{label:`Title`,value:t.page.title??`Missing`},{label:`Meta description`,value:t.page.metaDescription??`Missing`},{label:`Words`,value:t.page.wordCount},{label:`Fetch`,value:na(t.fetchDiagnostics)}],diagnostics:[{title:`Issues`,items:t.issues.map(e=>({status:e.severity===`high`?`fail`:`warning`,title:`${e.code}: ${e.principle}`,explanation:e.detail}))}]})}});function Bo(e){let t=C(e)??`mobile`;if(t!==`mobile`&&t!==`desktop`)throw new d(`INVALID_INPUT`,`Invalid --strategy. Use mobile or desktop.`);return t}function Y(e){return e?e.displayValue??String(e.value??`not measured`):`not measured`}function Vo(e){if(!e)return`not available`;let t=e.unit===`milliseconds`?`ms`:``;return`${e.p75}${t} (${e.rating})`}const Ho=v({meta:{name:`perf`,description:`Audit lab performance and field Core Web Vitals`},subCommands:{audit:v({meta:{name:`audit`,description:`Run a Lighthouse/Core Web Vitals performance audit`},args:{url:{type:`string`,description:`URL to audit.`},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=k(e),n=C(e.url);if(!n)throw new d(`INVALID_INPUT`,`No URL given. Pass --url.`);let r=await qe({url:n,strategy:Bo(e.strategy),lighthouseBin:C(e[`lighthouse-bin`]),cruxApiKey:C(e[`crux-key`]),refresh:w(e.refresh),includeRaw:t&&w(e.raw)});if(t){P(r);return}U({title:`Performance report`,target:r.url,status:r.dataStatus===`partial`?`unknown`:r.grade===`good`?`pass`:`warning`,summary:r.headline,metrics:[{label:`Source`,value:r.source},{label:`Strategy`,value:r.strategy},{label:`Lab score`,value:r.score===void 0?`Unknown`:`${r.score}/100`},{label:`Lab grade`,value:r.grade},{label:`Evidence`,value:r.dataStatus},{label:`FCP`,value:Y(r.metrics.firstContentfulPaint)},{label:`LCP`,value:Y(r.metrics.largestContentfulPaint)},{label:`TBT`,value:Y(r.metrics.totalBlockingTime)},{label:`CLS`,value:Y(r.metrics.cumulativeLayoutShift)},{label:`INP`,value:Y(r.metrics.interactionToNextPaint)},{label:`Server response`,value:Y(r.metrics.serverResponseTime)},{label:`Fallback fetch`,value:Y(r.metrics.fallbackFetchDuration)},{label:`Field data`,value:r.fieldData?`${r.fieldData.scope} ${r.fieldData.formFactor.toLowerCase()} (${r.fieldData.assessment.status})`:r.fieldDataStatus.status},{label:`Field LCP p75`,value:Vo(r.fieldData?.metrics.largestContentfulPaint)},{label:`Field INP p75`,value:Vo(r.fieldData?.metrics.interactionToNextPaint)},{label:`Field CLS p75`,value:Vo(r.fieldData?.metrics.cumulativeLayoutShift)},{label:`Field period`,value:r.fieldData?.collectionPeriod?.firstDate&&r.fieldData.collectionPeriod.lastDate?`${r.fieldData.collectionPeriod.firstDate} to ${r.fieldData.collectionPeriod.lastDate}`:`Unavailable`}]}),G(`Top actions`,r.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),K(`Caveats`,r.caveats)}})}}),Uo=v({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 ge();if(k(e)){P(t),t.ok||(process.exitCode=1);return}Zr(`SEO doctor`,Hr(t.checks)),process.stdout.write(`
73
- `),Qr(t.checks),process.stdout.write(`\nChecked ${t.generatedAt}\n`),t.ok||(process.exitCode=1)}}),Wo=e=>{let t=C(e)??`page`;if(t!==`page`&&t!==`query`&&t!==`country`&&t!==`device`)throw Error(`Invalid --dimension. Use page, query, country, or device.`);return t},Go=v({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.`},dimension:{type:`string`,default:`page`,description:`Segment by page, query, country, or device.`},...J([`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=k(e),n=Wo(e.dimension),r=D(e.days,`--days`),i=D(e.compare,`--compare`),a=D(e.limit,`--limit`),o=D(e[`unmatched-limit`],`--unmatched-limit`),s=D(e[`max-rows`],`--max-rows`),c=await Tt({site:R(C(e.site)),dimension:n,days:r,compareDays:i,startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),limit:a,unmatchedLimit:o,maxRows:s,refresh:w(e.refresh)});if(t){P(c);return}U({title:`Segment impact`,target:c.site,status:c.dataStatus===`complete`?`info`:`unknown`,summary:c.summary.verdict,metrics:[{label:`Dimension`,value:c.dimension},{label:`Evidence`,value:c.dataStatus},{label:`Before`,value:`${c.before.startDate} to ${c.before.endDate}`},{label:`After`,value:`${c.after.startDate} to ${c.after.endDate}`}]}),I([`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(`
73
+ `);return}W([`Type`,`Query`,`Evidence`,`Pos`,`CTR`,`Expected`,`Impr`,`Shortfall`,`Action`],n.items.map(e=>[e.opportunityType,H(e.query,38),e.verification.signals.length?e.verification.signals.join(`, `):e.verification.status,e.position.toFixed(1),V(e.ctr),e.expectedCtr===void 0?`n/a`:V(e.expectedCtr),z(e.impressions),e.estimatedCtrClickShortfall===void 0?`n/a`:z(e.estimatedCtrClickShortfall),H(e.recommendation,72)])),G(`Top page actions`,n.items.map(e=>({label:e.query,context:`${e.opportunityType}, ${z(e.impressions)} impressions`,action:e.recommendation})))}}),Xo=v({meta:{name:`query-cluster`,description:`Cluster GSC queries into repeated demand themes`},args:{site:{type:`string`},scope:{type:`string`},...J([`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=k(e),n=await _t({site:R(w(e.site)),scope:w(e.scope),includeBrand:T(e[`include-brand`]),minImpressions:E(e[`min-impressions`]),limit:E(e.limit)});if(t){P(n);return}U({title:`Query clusters`,target:n.site,status:`info`,summary:n.summary.verdict,metrics:[{label:`Scope`,value:n.scope??`All pages`},{label:`Clusters`,value:z(n.summary.clusters)},{label:`Queries`,value:z(n.summary.queries)},{label:`Impressions`,value:z(n.summary.impressions)},{label:`Clicks`,value:z(n.summary.clicks)},{label:`Minimum impressions`,value:z(n.summary.minImpressions)},{label:`Result limit`,value:z(n.summary.limit)},{label:`High opportunity`,value:z(n.summary.highOpportunityClusters)},{label:`Brand queries`,value:n.summary.brandFiltering}]}),K(`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.`]),K(`Recommended actions`,n.recommendations),K(`Report caveats`,n.caveats),W([`Cluster`,`Intent`,`Queries`,`Impr`,`CTR`,`Expected`,`Lift`,`Action`],n.clusters.map(e=>[H(e.label,32),e.intent,e.queries.length,z(e.totals?.impressions??0),V(e.totals?.ctr??0),V(e.benchmark?.expectedCtr??0),e.estimatedClickLift===void 0?`-`:z(e.estimatedClickLift),H(e.recommendation??``,72)])),G(`Top cluster actions`,n.clusters.map(e=>({label:e.label,context:`${z(e.totals?.impressions??0)} impressions, ${e.estimatedClickLift===void 0?`ranking opportunity`:`${z(e.estimatedClickLift)} estimated click lift`}`,action:e.recommendation??``})))}}),Zo=v({meta:{name:`quick-wins`,description:`Find high-ranking low-CTR query/page opportunities`},args:{site:{type:`string`},...J([`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=k(e),n=E(e[`verify-limit`]),r=T(e[`verify-content`])===!0||n!==void 0,i=await Ie({site:R(w(e.site)),days:E(e.days),limit:E(e.limit),minImpressions:E(e[`min-impressions`]),brandTerms:[...O(e[`brand-terms`])??[]],includeBrand:T(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:T(e.js)?!0:void 0,rate:xr(e),refresh:T(e.refresh)});if(t){P(i);return}U({title:`Quick wins`,target:i.site,status:i.source.possiblyTruncated?`unknown`:`info`,summary:i.summary.verdict,metrics:[{label:`Eligible rows`,value:z(i.summary.eligibleRows)},{label:`Returned rows`,value:z(i.summary.returnedRows)},{label:`Query clusters`,value:z(i.summary.repeatedQueryGroups)},{label:`Template patterns`,value:z(i.summary.templatePatterns)},{label:`CTR click shortfall`,value:z(i.summary.returnedEstimatedCtrClickShortfall)},{label:`Brand queries`,value:i.summary.brandFiltering},{label:`Evidence`,value:i.dataStatus},{label:`Verification`,value:Ci(i)}]}),K(`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.`]),K(`Recommended actions`,i.recommendations),K(`Report caveats`,i.caveats),i.items.length&&(i.templateRecommendations.length&&(W([`Template`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Action`],i.templateRecommendations.map(e=>[H(e.templateLabel,34),z(e.urlCount),z(e.rowCount),z(e.totalEstimatedCtrClickShortfall),z(e.totalImpressions),H(e.action,72)])),G(`Top template actions`,i.templateRecommendations.map(e=>({label:e.templateLabel,context:`${z(e.urlCount)} URLs, ${z(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:`${e.action} ${e.evidence}`})))),i.groups.length&&(W([`Cluster`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Sample URL`,`Action`],i.groups.map(e=>[H(e.label,44),z(e.urlCount),z(e.rowCount),z(e.totalEstimatedCtrClickShortfall),z(e.totalImpressions),H(e.sampleUrls[0]??`-`,46),H(e.recommendation,72)])),G(`Top cluster actions`,i.groups.map(e=>({label:e.label,context:`${z(e.urlCount)} URLs, ${z(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:e.recommendation})))),W([`Query`,`Template`,`URL`,`Pos`,`Impr`,`CTR / target`,`Shortfall`,`Fetch`,`Check`,`Action`],i.items.map(e=>[H(e.query,36),H(e.template.label,24),H(e.url,48),B(e.position),z(e.impressions),`${V(e.ctr)} / ${V(e.targetCtr)}`,z(e.estimatedCtrClickShortfall),ua(e.contentVerification?.fetchDiagnostics),da(e.contentVerification?.classification),H(e.recommendation.action,64)])),G(`Top opportunity actions`,i.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${B(e.position)}, ${z(e.impressions)} impressions`,action:e.recommendation.action}))))}}),Qo=v({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.`},...J([`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=k(e),n=E(e[`verify-limit`]),r=T(e[`verify-content`])===!0||n!==void 0,i=await ft({site:R(w(e.site)),range:E(e.days),minImpressions:E(e[`min-impressions`]),limit:w(e.limit)?Number(w(e.limit)):10,includeBrand:T(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:T(e.js)?!0:void 0,rate:xr(e),refresh:T(e.refresh)});if(t){P(i);return}if(U({title:`Second-page opportunities`,target:i.site,status:i.source.possiblyTruncated||i.summary.fetchFailures>0?`unknown`:`info`,summary:i.summary.verdict,metrics:[{label:`Eligible pages`,value:z(i.summary.eligiblePages)},{label:`Returned pages`,value:z(i.summary.returnedPages)},{label:`Eligible queries`,value:z(i.summary.eligibleQueries)},{label:`Impressions`,value:z(i.summary.eligibleImpressions)},{label:`Content issues`,value:z(i.summary.contentIssues)},{label:`Technical issues`,value:z(i.summary.technicalIssues)},{label:`Fetch failures`,value:z(i.summary.fetchFailures)},{label:`Brand queries`,value:i.summary.brandFiltering},{label:`Evidence`,value:i.dataStatus},{label:`Verification`,value:Ci(i)}]}),K(`Recommended actions`,i.recommendations),K(`Report caveats`,i.caveats),!i.items.length){process.stdout.write(`No average-position candidates matched this report.
74
+ `),process.stdout.write(`${i.ledgerSummary}\n`);return}W([`Query`,`Template`,`Pos`,`Impr`,`CTR`,`Queries`,`Fetch`,`Check`,`Action`],i.items.map(e=>[e.primaryQuery,e.template.label,e.position.toFixed(1),Math.round(e.impressions),e.ctr.toFixed(3),z(e.queryCount),ua(e.fetchDiagnostics),da(e.contentVerification?.classification),e.recommendation.action])),G(`Top second-page actions`,i.items.map(e=>({label:e.primaryQuery,context:`${e.template.label}, pos ${B(e.position)}, ${z(e.impressions)} impressions`,action:e.recommendation.action}))),process.stdout.write(`${i.ledgerSummary}\n`)}}),$o=v({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.`},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=await Ae({url:w(e.url)??``,site:w(e.site),js:T(e.js)?!0:`auto`,refresh:T(e.refresh)});if(k(e)){P(t);return}U({title:`Page audit`,target:t.url,status:t.issues.some(e=>e.severity===`high`)?`fail`:t.issues.length>0?`warning`:`pass`,summary:t.issues.length>0?`${t.issues.length} ${t.issues.length===1?`issue needs`:`issues need`} review.`:`No page issues were found by the available checks.`,metrics:[{label:`Final URL`,value:t.page.finalUrl},{label:`Title`,value:t.page.title??`Missing`},{label:`Meta description`,value:t.page.metaDescription??`Missing`},{label:`Words`,value:t.page.wordCount},{label:`Fetch`,value:ua(t.fetchDiagnostics)}],diagnostics:[{title:`Issues`,items:t.issues.map(e=>({status:e.severity===`high`?`fail`:`warning`,title:`${e.code}: ${e.principle}`,explanation:e.detail}))}]})}});function es(e){let t=w(e)??`mobile`;if(t!==`mobile`&&t!==`desktop`)throw new p(`INVALID_INPUT`,`Invalid --strategy. Use mobile or desktop.`);return t}function Y(e){return e?e.displayValue??String(e.value??`not measured`):`not measured`}function ts(e){if(!e)return`not available`;let t=e.unit===`milliseconds`?`ms`:``;return`${e.p75}${t} (${e.rating})`}const ns=v({meta:{name:`perf`,description:`Audit lab performance and field Core Web Vitals`},subCommands:{audit:v({meta:{name:`audit`,description:`Run a Lighthouse/Core Web Vitals performance audit`},args:{url:{type:`string`,description:`URL to audit.`},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=k(e),n=w(e.url);if(!n)throw new p(`INVALID_INPUT`,`No URL given. Pass --url.`);let r=await Kt({url:n,strategy:es(e.strategy),lighthouseBin:w(e[`lighthouse-bin`]),cruxApiKey:w(e[`crux-key`]),refresh:T(e.refresh),includeRaw:t&&T(e.raw)});if(t){P(r);return}U({title:`Performance report`,target:r.url,status:r.dataStatus===`partial`?`unknown`:r.grade===`good`?`pass`:`warning`,summary:r.headline,metrics:[{label:`Source`,value:r.source},{label:`Strategy`,value:r.strategy},{label:`Lab score`,value:r.score===void 0?`Unknown`:`${r.score}/100`},{label:`Lab grade`,value:r.grade},{label:`Evidence`,value:r.dataStatus},{label:`FCP`,value:Y(r.metrics.firstContentfulPaint)},{label:`LCP`,value:Y(r.metrics.largestContentfulPaint)},{label:`TBT`,value:Y(r.metrics.totalBlockingTime)},{label:`CLS`,value:Y(r.metrics.cumulativeLayoutShift)},{label:`INP`,value:Y(r.metrics.interactionToNextPaint)},{label:`Server response`,value:Y(r.metrics.serverResponseTime)},{label:`Fallback fetch`,value:Y(r.metrics.fallbackFetchDuration)},{label:`Field data`,value:r.fieldData?`${r.fieldData.scope} ${r.fieldData.formFactor.toLowerCase()} (${r.fieldData.assessment.status})`:r.fieldDataStatus.status},{label:`Field LCP p75`,value:ts(r.fieldData?.metrics.largestContentfulPaint)},{label:`Field INP p75`,value:ts(r.fieldData?.metrics.interactionToNextPaint)},{label:`Field CLS p75`,value:ts(r.fieldData?.metrics.cumulativeLayoutShift)},{label:`Field period`,value:r.fieldData?.collectionPeriod?.firstDate&&r.fieldData.collectionPeriod.lastDate?`${r.fieldData.collectionPeriod.firstDate} to ${r.fieldData.collectionPeriod.lastDate}`:`Unavailable`}]}),G(`Top actions`,r.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),K(`Caveats`,r.caveats)}})}}),rs=v({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 be();if(k(e)){P(t),t.ok||(process.exitCode=1);return}ai(`SEO doctor`,Xr(t.checks)),process.stdout.write(`
75
+ `),oi(t.checks),process.stdout.write(`\nChecked ${t.generatedAt}\n`),t.ok||(process.exitCode=1)}}),is=e=>{let t=w(e)??`page`;if(t!==`page`&&t!==`query`&&t!==`country`&&t!==`device`)throw Error(`Invalid --dimension. Use page, query, country, or device.`);return t},as=v({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.`},dimension:{type:`string`,default:`page`,description:`Segment by page, query, country, or device.`},...J([`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=k(e),n=is(e.dimension),r=D(e.days,`--days`),i=D(e.compare,`--compare`),a=D(e.limit,`--limit`),o=D(e[`unmatched-limit`],`--unmatched-limit`),s=D(e[`max-rows`],`--max-rows`),c=await ze({site:R(w(e.site)),dimension:n,days:r,compareDays:i,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),limit:a,unmatchedLimit:o,maxRows:s,refresh:T(e.refresh)});if(t){P(c);return}U({title:`Segment impact`,target:c.site,status:c.dataStatus===`complete`?`info`:`unknown`,summary:c.summary.verdict,metrics:[{label:`Dimension`,value:c.dimension},{label:`Evidence`,value:c.dataStatus},{label:`Before`,value:`${c.before.startDate} to ${c.before.endDate}`},{label:`After`,value:`${c.after.startDate} to ${c.after.endDate}`}]}),I([`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(`
74
76
  One-window evidence (not treated as zero)
75
- `),I([`Segment`,`Retained in`,`Clicks`,`Impressions`],c.unmatchedSegments.map(e=>[e.key,e.retainedIn,e.clicks,e.impressions]))),K(`Warnings`,c.warnings)}});function Ko(e){return`${z(e)} ${e===1?`row`:`rows`}`}const qo=v({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.`},...J([`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=k(e),n=E(e[`verify-limit`]),r=w(e[`verify-content`])===!0||n!==void 0,i=await Me({site:R(C(e.site)),days:E(e.days),minImpressions:E(e[`min-impressions`]),limit:E(e.limit),includeBrand:w(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:w(e.js)?!0:void 0,rate:pr(e),refresh:w(e.refresh)});if(t){P(i);return}if(U({title:`Striking-distance opportunities`,target:i.site,status:i.source.possiblyTruncated?`unknown`:`info`,summary:i.summary.verdict,metrics:[{label:`Eligible rows`,value:z(i.summary.eligibleRows)},{label:`Returned rows`,value:z(i.summary.returnedRows)},{label:`Template groups`,value:z(i.summary.groups)},{label:`Impressions`,value:z(i.summary.eligibleImpressions)},{label:`Brand queries`,value:i.summary.brandFiltering},{label:`Verification`,value:i.verification.requested?`Requested`:`Off`},{label:`Evidence`,value:i.dataStatus}]}),K(`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.`]),K(`Recommended actions`,i.recommendations),K(`Report caveats`,i.caveats),i.groups.length&&(W([`Group`,`Rows`,`URLs`,`Impr`,`Avg pos`,`Scope`,`Action`],i.groups.map(e=>[H(e.label,36),z(e.rowCount),z(e.uniqueUrls),z(e.totalImpressions),B(e.impressionWeightedPosition),e.actionScope,H(e.recommendation.action,72)])),G(`Top striking-distance group actions`,i.groups.map(e=>({label:e.label,context:`${Ko(e.rowCount)}, ${z(e.totalImpressions)} impressions`,action:e.recommendation.action})))),!i.items.length){process.stdout.write(`No striking-distance opportunities matched these filters.
76
- `);return}W([`Query`,`Template`,`URL`,`Impr`,`CTR`,`Pos`,`Score`,`Fetch`,`Check`,`Action`],i.items.map(e=>[H(e.query,36),H(e.template.label,24),H(e.url,48),z(e.impressions),V(e.ctr),B(e.position),e.priority.score,na(e.contentVerification?.fetchDiagnostics),ra(e.contentVerification?.classification),H(e.recommendation.action,72)])),G(`Top striking-distance actions`,i.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${B(e.position)}, ${z(e.impressions)} impressions`,action:e.recommendation.action})))}});function Jo(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e??`missing`}function Yo(e){return e===null?`unavailable`:`$${(e/1e6).toFixed(2)}`}function Xo(e){return e.limit===null?e.used===null?`not reported`:`${e.used.toLocaleString(`en-US`)} used; no key limit`:`${(e.remaining??0).toLocaleString(`en-US`)} of ${e.limit.toLocaleString(`en-US`)} remaining`}const Zo=v({meta:{name:`ahrefs`,description:`Connect Ahrefs for optional search and link data`},subCommands:{connect:v({meta:{name:`connect`,description:`Validate and save an Ahrefs API v3 key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(!N({json:k(e)}))throw new d(`AUTH_REQUIRED`,`Run \`seo providers ahrefs connect\` in a terminal. Agents and CI can set ${ue}.`);y(`Connect Ahrefs`),b(`Paste an API v3 key from Ahrefs Account settings. The validation check and Domain Rating are free; other research can consume API units.`,`API key`);let t=L(await Kn({message:`Ahrefs API v3 key`,validate:e=>e?.trim()?void 0:`API key is required`})),n=await new De({apiKey:t}).limitsAndUsage(),r=await Ve(t);b(`${n.subscription} subscription. API key units: ${Xo(n.apiKeyUnits)}.`,`Connection verified`),x(`Saved in the ${Jo(r)}. Run seo providers ahrefs status --check to verify it again.`)}}),status:v({meta:{name:`status`,description:`Show the local Ahrefs connection`},args:{check:{type:`boolean`,default:!1,description:`Verify the API key with the free account endpoint.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await ce(),n=!!e.check,r=n&&t?await new De().limitsAndUsage():void 0,i={connected:!!t,apiVersion:t?3:null,credentialSource:t?.source,liveCheck:r?{status:`passed`,subscription:r.subscription,apiKeyExpiresAt:r.apiKeyExpiresAt,usageResetsAt:r.usageResetsAt,apiKeyUnits:r.apiKeyUnits,workspaceUnits:r.workspaceUnits,observedAt:r.observedAt,requestCostUnits:r.requestCostUnits}:{status:n?`unavailable`:`not-requested`}};if(k(e)){P(i);return}F([[`Connected`,i.connected?`yes`:`no`],[`API version`,i.apiVersion?`Version 3`:`not connected`],[`Credential`,Jo(i.credentialSource)],[`Live check`,i.liveCheck.status===`passed`?`passed at ${i.liveCheck.observedAt}`:i.liveCheck.status===`unavailable`?`not available without credentials`:`not requested; pass --check to verify`],...r?[[`Subscription`,r.subscription],[`API key units`,Xo(r.apiKeyUnits)],[`Workspace units`,Xo(r.workspaceUnits)],[`Usage resets`,r.usageResetsAt],[`Key expires`,r.apiKeyExpiresAt]]:[]])}}),disconnect:v({meta:{name:`disconnect`,description:`Remove the saved Ahrefs API v3 key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await Bt();let t=!!process.env[ue]?.trim(),n={savedCredentialRemoved:!0,environmentCredential:t?`active`:`missing`,note:t?`The environment variable was not changed. Clear ${ue} to fully disconnect.`:`Ahrefs is disconnected.`};k(e)?P(n):process.stdout.write(`${n.note}\n`)}})}}),Qo="Run `seo providers bing connect` with a new API key.",$o=v({meta:{name:`bing`,description:`Connect Bing Webmaster Tools for Bing search data`},subCommands:{connect:v({meta:{name:`connect`,description:`Check and save a Bing Webmaster Tools API key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(!N({json:k(e)}))throw new d(`AUTH_REQUIRED`,`Run \`seo providers bing connect\` in a terminal. Agents and CI can set ${ie}.`);y(`Connect Bing Webmaster Tools`),b(`In Bing Webmaster Tools, open Settings, then API access, and copy the API key. Bing data is free.`,`API key`);let t=L(await Kn({message:`Bing Webmaster API key`,validate:e=>e?.trim()?void 0:`API key is required`})),n=await at(Zt({apiKey:t},{signIn:Qo})),r=await h(t);b(`${n.filter(e=>e.verified).length} verified sites.`,`Connection verified`),x(`Saved in the ${Jo(r)}.`)}}),status:v({meta:{name:`status`,description:`Show the Bing Webmaster connection`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await Le(),n=t?await at(Zt({apiKey:t.apiKey},{signIn:Qo})):null,r={connected:!!t,credentialSource:t?.source??null,sites:n?.filter(e=>e.verified).map(e=>e.url)??[]};if(k(e)){P(r);return}process.stdout.write(t?`Connected (${Jo(t.source)}). Verified sites: ${r.sites.join(`, `)||`none`}.\n`:"Not connected. Run `seo providers bing connect`.\n")}}),disconnect:v({meta:{name:`disconnect`,description:`Remove the saved Bing Webmaster API key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await Ne();let t=!!process.env[ie]?.trim(),n=t?`The saved key is removed. Clear ${ie} to fully disconnect.`:`Bing is disconnected.`;k(e)?P({removed:!0,environment:t}):process.stdout.write(`${n}\n`)}})}}),es=v({meta:{name:`dataforseo`,description:`Connect DataForSEO for optional search data`},subCommands:{connect:v({meta:{name:`connect`,description:`Validate and save DataForSEO API credentials`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(!N({json:k(e)}))throw new d(`AUTH_REQUIRED`,`Run \`seo providers dataforseo connect\` in a terminal. Agents and CI can set ${fe} and ${Te}.`);y(`Connect DataForSEO`),b(`Use the API login and API password from DataForSEO API Access. The validation call is free; later research reports can make charged requests.`,`API credentials`);let t=L(await Jn({message:`DataForSEO API login`,validate:e=>e?.trim()?void 0:`API login is required`})),n=L(await Kn({message:`DataForSEO API password`,validate:e=>e?void 0:`API password is required`})),r={login:t.trim(),password:n},i=await new an({credentials:()=>r}).userData(),a=await Fe(r);b(`${i.login} is connected with an account balance of ${Yo(i.balanceMicros)}.`,`Connection verified`),x(`Saved in the ${Jo(a)}. Run seo providers dataforseo status --check to verify it again.`)}}),status:v({meta:{name:`status`,description:`Show the local DataForSEO connection`},args:{check:{type:`boolean`,default:!1,description:`Verify credentials with the free account endpoint.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await a(),n=!!e.check,r=n&&t?await new an().userData():void 0,i={connected:!!t,credentialSource:t?.source,migratedLegacyCredentials:t?.migrated??!1,liveCheck:r?{status:`passed`,account:r.login,timezone:r.timezone,balanceMicros:r.balanceMicros,observedAt:r.observedAt,requestCostMicros:r.requestCostMicros}:{status:n?`unavailable`:`not-requested`}};if(k(e)){P(i);return}F([[`Connected`,i.connected?`yes`:`no`],[`Credential`,Jo(i.credentialSource)],[`Live check`,i.liveCheck.status===`passed`?`passed at ${i.liveCheck.observedAt}`:i.liveCheck.status===`unavailable`?`not available without credentials`:`not requested; pass --check to verify`],...r?[[`Account`,r.login],[`Balance`,Yo(r.balanceMicros)]]:[]])}}),disconnect:v({meta:{name:`disconnect`,description:`Remove saved DataForSEO credentials`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await dn();let t=!!process.env[fe]?.trim(),n=!!process.env[Te],r={savedCredentialsRemoved:!0,environmentCredentials:t&&n?`active`:t||n?`partial`:`missing`,note:t||n?`Environment variables were not changed. Clear ${fe} and ${Te} to fully disconnect.`:`DataForSEO is disconnected.`};k(e)?P(r):process.stdout.write(`${r.note}\n`)}})}});function ts(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw new d(`INVALID_INPUT`,`--account must be a JSON object.`)}if(!t||Array.isArray(t)||typeof t!=`object`)throw new d(`INVALID_INPUT`,`--account must be a JSON object.`);let n=Object.entries(t);if(n.length>20||n.some(([e,t])=>!e||e.length>64||typeof t!=`string`||t.length>4096))throw new d(`INVALID_INPUT`,`--account must contain at most 20 bounded string fields.`);return Object.fromEntries(n.map(([e,t])=>[e,t.trim()]))}function ns(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw new d(`INVALID_INPUT`,`--params must be a JSON object.`)}if(!t||Array.isArray(t)||typeof t!=`object`)throw new d(`INVALID_INPUT`,`--params must be a JSON object.`);let n=Object.entries(t);if(n.length>100||n.some(([e])=>!/^[A-Za-z][A-Za-z0-9-]{0,63}$/u.test(e))||Buffer.byteLength(e)>64*1024)throw new d(`INVALID_INPUT`,`--params must be a JSON object smaller than 64 KiB.`);return Object.fromEntries(n)}async function rs(e){let t=await m(),n=t.registry.get(e);if(n)return n;let r=t.failures.find(t=>t.id===e);throw r?new d(`INVALID_INPUT`,`Provider ${e} could not load: ${r.message}`):new d(`INVALID_INPUT`,`Provider ${e} is not installed.`)}function is(e,t){let n=new Set(e.connection.fields.filter(e=>e.kind===`account`).map(e=>e.id)),r=Object.keys(t).find(e=>!n.has(e));if(r)throw new d(`INVALID_INPUT`,`${r} is not an account field for ${e.displayName}.`);let i=e.connection.normalizeAccount?e.connection.normalizeAccount(t):{...t};if(Object.keys(i).find(e=>!n.has(e)))throw new d(`PROVIDER_UNAVAILABLE`,`${e.displayName} returned an unknown account field.`);for(let t of e.connection.fields.filter(e=>e.kind===`account`&&e.required!==!1))if(!i[t.id]?.trim())throw new d(`INVALID_INPUT`,`${t.label} is required.`);return i}async function as(){return u()}const os=v({meta:{name:`providers`,description:`Connect optional data providers`},subCommands:{list:v({meta:{name:`list`,description:`List installed provider packages`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await as();if(k(e)){P(t);return}t.installed.length>0?I([`Installed provider`,`Package`,`Version`,`Status`],t.installed.map(e=>[e.id,e.package,e.version,e.loadStatus])):process.stdout.write(`No provider extensions are installed.
77
- `)}}),describe:v({meta:{name:`describe`,description:`Describe one installed provider for an agent`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await ee(C(e.id)??``);if(k(e)){P(t);return}F([[`Provider`,t.displayName],[`Package`,`${t.package}@${t.version}`],[`Description`,t.description],[`Capabilities`,t.capabilities.map(e=>e.id).join(`, `)||`none`],[`Actions`,t.actions.map(e=>e.id).join(`, `)||`none`]])}}),install:v({meta:{name:`install`,description:`Install one provider package from npm`},args:{package:{type:`positional`,required:!0,description:`npm package name with an optional exact version.`},yes:{type:`boolean`,default:!1,description:`Approve third-party code installation without prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=C(e.package)??``,n=k(e),r=w(e.yes),i=N({json:n});if(!r&&!i)throw new d(`INVALID_INPUT`,`Provider installation runs third-party code. Review the package, then pass --yes to approve it in JSON or CI mode.`);let a;try{a=await s(t)}catch(e){throw new d(`INVALID_INPUT`,e instanceof Error?e.message:String(e))}if(!r&&(y(`Install provider package`),b([`${a.package}@${a.version}`,`Publisher: ${a.publisher??`not supplied by npm`}`,`Repository: ${a.repository??`not supplied by npm`}`,`Integrity: ${a.integrity}`].join(`
78
- `),`Package`),b(`This package can read files, use the network, and run with the same local permissions as seo. Installing it is not a security review or endorsement.`,`Third-party code`),!L(await Hn({message:`Install ${a.package}@${a.version}?`,initialValue:!1})))){x(`Provider was not installed.`);return}let o;try{o=await tn(a)}catch(e){throw new d(`PROVIDER_UNAVAILABLE`,e instanceof Error?e.message:String(e))}let c={installed:o,package:a};if(n){P(c);return}x(`Installed provider ${o.id} from ${o.package}@${o.version}.`)}}),remove:v({meta:{name:`remove`,description:`Remove one installed provider extension`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},yes:{type:`boolean`,default:!1,description:`Remove the package without prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=C(e.id)??``,n=k(e),r=w(e.yes),i=N({json:n});if(!r&&!i)throw new d(`INVALID_INPUT`,`Pass --yes to remove a provider extension in JSON or CI mode.`);if(!r&&!L(await Hn({message:`Remove provider ${t}?`,initialValue:!1})))return;let a=await Ae(t);if(!a)throw new d(`INVALID_INPUT`,`Provider ${t} is not installed.`);if(n){P({removed:a});return}process.stdout.write(`Removed ${t}.\n`)}}),connect:v({meta:{name:`connect`,description:`Validate and save one installed provider connection`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},account:{type:`string`,description:`Account fields as JSON. Secret fields must use their environment variables.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=C(e.id)??``,r=k(e),i=N({json:r}),a=await rs(t),o={...Ct(t),...ts(C(e.account))},s={};if(i){y(`Connect ${a.displayName}`),a.connection.verificationNotice&&b(a.connection.verificationNotice,`Connection check`);for(let e of a.connection.fields){if(e.kind===`account`){let t=L(await Jn({message:e.label,placeholder:e.description,initialValue:o[e.id],validate:t=>e.required!==!1&&!t?.trim()?`${e.label} is required`:void 0}));t?.trim()&&(o[e.id]=t.trim());continue}if(e.envVar&&process.env[e.envVar]?.trim())continue;let t=L(await Kn({message:e.label,validate:t=>e.required!==!1&&!t?.trim()?`${e.label} is required`:void 0}));t?.trim()&&(s[e.id]=t.trim())}}o=is(a,o);let c={...s};Object.keys(c).length===0&&(c=await pe({providerId:t,account:o,fields:a.connection.fields})),await Se({providerId:t,account:o,credentials:c}),Object.keys(s).length>0&&await Ee({providerId:t,account:o,credentials:s}),n(t,o);let l={provider:t,connected:!0,account:o,capabilities:(a.capabilities??[]).map(e=>e.id),actions:(a.actions??[]).map(e=>e.id)};r?P(l):x(`Connected ${a.displayName}. Run seo providers describe ${t} to see what it can do.`)}}),status:v({meta:{name:`status`,description:`Show one installed provider connection`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},check:{type:`boolean`,default:!1,description:`Run the provider connection check.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=C(e.id)??``,n=await rs(t),r=Ct(t),i;try{i=await pe({providerId:t,account:r,fields:n.connection.fields})}catch{i=void 0}let a=n.connection.fields.filter(e=>e.kind===`account`&&e.required!==!1).every(e=>!!r[e.id]?.trim())&&i!==void 0,o=w(e.check);if(o&&!a)throw new d(`AUTH_REQUIRED`,`Provider ${t} is not connected. Run \`seo providers connect ${t}\`.`);o&&i&&await Se({providerId:t,account:r,credentials:i});let s={provider:t,installed:!0,connected:a,account:r,capabilities:(n.capabilities??[]).map(e=>e.id),actions:(n.actions??[]).map(e=>e.id),check:o?`passed`:`not-requested`};if(k(e)){P(s);return}I([`Provider`,`Connected`,`Capabilities`,`Check`],[[n.displayName,a?`yes`:`no`,s.capabilities.join(`, `),s.check]])}}),disconnect:v({meta:{name:`disconnect`,description:`Remove one saved provider connection`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=C(e.id)??``;await rs(t),await se({providerId:t,account:Ct(t)}),ve(t);let n={provider:t,disconnected:!0,note:`Environment variables were not changed.`};k(e)?P(n):process.stdout.write(`Disconnected ${t}. ${n.note}\n`)}}),run:v({meta:{name:`run`,description:`Run one action supplied by an installed provider`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},action:{type:`positional`,required:!0,description:`Provider action id.`},account:{type:`string`,description:`Account fields as JSON. Defaults to the saved connection.`},params:{type:`string`,description:`Action parameters as a JSON object.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local provider cache.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=C(e.id)??``,n=C(e.action)??``;await rs(t),P(await bt({providerId:t,actionId:n,account:{...Ct(t),...ts(C(e.account))},params:ns(C(e.params)),refresh:w(e.refresh)}))}}),doctor:v({meta:{name:`doctor`,description:`Validate installed provider packages and entry points`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await as(),n={ok:t.installed.every(e=>e.loadStatus===`ready`),installed:t.installed};if(k(e)){P(n);return}if(n.installed.length===0){process.stdout.write(`No provider extensions are installed.
79
- `);return}I([`Provider`,`Package`,`Version`,`Status`],n.installed.map(e=>[e.id,e.package,e.version,e.error??e.loadStatus]))}}),ahrefs:Zo,bing:$o,dataforseo:es}}),ss={"ai-search":`AI search`,crawl:`Crawling and technical checks`,diagnosis:`Diagnosis`,monitoring:`Monitoring`,opportunities:`Opportunities`,reporting:`Reporting`,setup:`Setup`,workflows:`Workflows`};function cs(e){let t=C(e);if(t){if(!Kt.includes(t))throw new d(`INVALID_INPUT`,`Unknown report category: ${t}. Choose ${Kt.join(`, `)}.`);return t}}async function ls(e,t){let n=C(e),r=C(t);if(n&&r)throw new d(`INVALID_INPUT`,`Use either --params or --params-file, not both.`);if(!n&&!r)return{};let i=n??await Nn(r??``,`utf8`),a;try{a=JSON.parse(i)}catch{throw new d(`INVALID_INPUT`,`Report parameters must be valid JSON.`)}if(!a||typeof a!=`object`||Array.isArray(a))throw new d(`INVALID_INPUT`,`Report parameters must be an object.`);return a}function us(e){if(!e.isError)return;let t=e.structuredContent;throw new d(t?.error?.code??`INTERNAL_ERROR`,t?.error?.message??`The report could not be completed.`)}function ds(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 fs=v({meta:{name:`reports`,description:`Discover and run the complete report catalog`},subCommands:{list:v({meta:{name:`list`,description:`List report ids available to the CLI and MCP server`},args:{category:{type:`string`,description:`Filter by category: ${Kt.join(`, `)}.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Pt(cs(e.category));if(k(e)){P({reports:t,categories:Kt});return}ei(t,{noun:`report`,categoryLabels:ss}),process.stdout.write(`
80
- `),Xr({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:v({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=_t(C(e.id)??``);if(k(e)){P({report:t});return}Zr(t.name,t.description),process.stdout.write(`
77
+ `),I([`Segment`,`Retained in`,`Clicks`,`Impressions`],c.unmatchedSegments.map(e=>[e.key,e.retainedIn,e.clicks,e.impressions]))),K(`Warnings`,c.warnings)}});function os(e){return`${z(e)} ${e===1?`row`:`rows`}`}const ss=v({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.`},...J([`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=k(e),n=E(e[`verify-limit`]),r=T(e[`verify-content`])===!0||n!==void 0,i=await mn({site:R(w(e.site)),days:E(e.days),minImpressions:E(e[`min-impressions`]),limit:E(e.limit),includeBrand:T(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:T(e.js)?!0:void 0,rate:xr(e),refresh:T(e.refresh)});if(t){P(i);return}if(U({title:`Striking-distance opportunities`,target:i.site,status:i.source.possiblyTruncated?`unknown`:`info`,summary:i.summary.verdict,metrics:[{label:`Eligible rows`,value:z(i.summary.eligibleRows)},{label:`Returned rows`,value:z(i.summary.returnedRows)},{label:`Template groups`,value:z(i.summary.groups)},{label:`Impressions`,value:z(i.summary.eligibleImpressions)},{label:`Brand queries`,value:i.summary.brandFiltering},{label:`Verification`,value:i.verification.requested?`Requested`:`Off`},{label:`Evidence`,value:i.dataStatus}]}),K(`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.`]),K(`Recommended actions`,i.recommendations),K(`Report caveats`,i.caveats),i.groups.length&&(W([`Group`,`Rows`,`URLs`,`Impr`,`Avg pos`,`Scope`,`Action`],i.groups.map(e=>[H(e.label,36),z(e.rowCount),z(e.uniqueUrls),z(e.totalImpressions),B(e.impressionWeightedPosition),e.actionScope,H(e.recommendation.action,72)])),G(`Top striking-distance group actions`,i.groups.map(e=>({label:e.label,context:`${os(e.rowCount)}, ${z(e.totalImpressions)} impressions`,action:e.recommendation.action})))),!i.items.length){process.stdout.write(`No striking-distance opportunities matched these filters.
78
+ `);return}W([`Query`,`Template`,`URL`,`Impr`,`CTR`,`Pos`,`Score`,`Fetch`,`Check`,`Action`],i.items.map(e=>[H(e.query,36),H(e.template.label,24),H(e.url,48),z(e.impressions),V(e.ctr),B(e.position),e.priority.score,ua(e.contentVerification?.fetchDiagnostics),da(e.contentVerification?.classification),H(e.recommendation.action,72)])),G(`Top striking-distance actions`,i.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${B(e.position)}, ${z(e.impressions)} impressions`,action:e.recommendation.action})))}});function cs(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e??`missing`}function ls(e){return e===null?`unavailable`:`$${(e/1e6).toFixed(2)}`}function us(e){return e.limit===null?e.used===null?`not reported`:`${e.used.toLocaleString(`en-US`)} used; no key limit`:`${(e.remaining??0).toLocaleString(`en-US`)} of ${e.limit.toLocaleString(`en-US`)} remaining`}const ds=v({meta:{name:`ahrefs`,description:`Connect Ahrefs for optional search and link data`},subCommands:{connect:v({meta:{name:`connect`,description:`Validate and save an Ahrefs API v3 key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(!N({json:k(e)}))throw new p(`AUTH_REQUIRED`,`Run \`seo providers ahrefs connect\` in a terminal. Agents and CI can set ${fe}.`);y(`Connect Ahrefs`),b(`Paste an API v3 key from Ahrefs Account settings. The validation check and Domain Rating are free; other research can consume API units.`,`API key`);let t=L(await S({message:`Ahrefs API v3 key`,validate:e=>e?.trim()?void 0:`API key is required`})),n=await new Pe({apiKey:t}).limitsAndUsage(),r=await Je(t);b(`${n.subscription} subscription. API key units: ${us(n.apiKeyUnits)}.`,`Connection verified`),x(`Saved in the ${cs(r)}. Run seo providers ahrefs status --check to verify it again.`)}}),status:v({meta:{name:`status`,description:`Show the local Ahrefs connection`},args:{check:{type:`boolean`,default:!1,description:`Verify the API key with the free account endpoint.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await ue(),n=!!e.check,r=n&&t?await new Pe().limitsAndUsage():void 0,i={connected:!!t,apiVersion:t?3:null,credentialSource:t?.source,liveCheck:r?{status:`passed`,subscription:r.subscription,apiKeyExpiresAt:r.apiKeyExpiresAt,usageResetsAt:r.usageResetsAt,apiKeyUnits:r.apiKeyUnits,workspaceUnits:r.workspaceUnits,observedAt:r.observedAt,requestCostUnits:r.requestCostUnits}:{status:n?`unavailable`:`not-requested`}};if(k(e)){P(i);return}F([[`Connected`,i.connected?`yes`:`no`],[`API version`,i.apiVersion?`Version 3`:`not connected`],[`Credential`,cs(i.credentialSource)],[`Live check`,i.liveCheck.status===`passed`?`passed at ${i.liveCheck.observedAt}`:i.liveCheck.status===`unavailable`?`not available without credentials`:`not requested; pass --check to verify`],...r?[[`Subscription`,r.subscription],[`API key units`,us(r.apiKeyUnits)],[`Workspace units`,us(r.workspaceUnits)],[`Usage resets`,r.usageResetsAt],[`Key expires`,r.apiKeyExpiresAt]]:[]])}}),disconnect:v({meta:{name:`disconnect`,description:`Remove the saved Ahrefs API v3 key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await qt();let t=!!process.env[fe]?.trim(),n={savedCredentialRemoved:!0,environmentCredential:t?`active`:`missing`,note:t?`The environment variable was not changed. Clear ${fe} to fully disconnect.`:`Ahrefs is disconnected.`};k(e)?P(n):process.stdout.write(`${n.note}\n`)}})}}),fs="Run `seo providers bing connect` with a new API key.",ps=v({meta:{name:`bing`,description:`Connect Bing Webmaster Tools for Bing search data`},subCommands:{connect:v({meta:{name:`connect`,description:`Check and save a Bing Webmaster Tools API key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(!N({json:k(e)}))throw new p(`AUTH_REQUIRED`,`Run \`seo providers bing connect\` in a terminal. Agents and CI can set ${ae}.`);y(`Connect Bing Webmaster Tools`),b(`In Bing Webmaster Tools, open Settings, then API access, and copy the API key. Bing data is free.`,`API key`);let t=L(await S({message:`Bing Webmaster API key`,validate:e=>e?.trim()?void 0:`API key is required`})),n=await De(xe({apiKey:t},{signIn:fs})),r=await h(t);b(`${n.filter(e=>e.verified).length} verified sites.`,`Connection verified`),x(`Saved in the ${cs(r)}.`)}}),status:v({meta:{name:`status`,description:`Show the Bing Webmaster connection`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await We(),n=t?await De(xe({apiKey:t.apiKey},{signIn:fs})):null,r={connected:!!t,credentialSource:t?.source??null,sites:n?.filter(e=>e.verified).map(e=>e.url)??[]};if(k(e)){P(r);return}process.stdout.write(t?`Connected (${cs(t.source)}). Verified sites: ${r.sites.join(`, `)||`none`}.\n`:"Not connected. Run `seo providers bing connect`.\n")}}),disconnect:v({meta:{name:`disconnect`,description:`Remove the saved Bing Webmaster API key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await Be();let t=!!process.env[ae]?.trim(),n=t?`The saved key is removed. Clear ${ae} to fully disconnect.`:`Bing is disconnected.`;k(e)?P({removed:!0,environment:t}):process.stdout.write(`${n}\n`)}})}}),ms=v({meta:{name:`dataforseo`,description:`Connect DataForSEO for optional search data`},subCommands:{connect:v({meta:{name:`connect`,description:`Validate and save DataForSEO API credentials`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(!N({json:k(e)}))throw new p(`AUTH_REQUIRED`,`Run \`seo providers dataforseo connect\` in a terminal. Agents and CI can set ${me} and ${je}.`);y(`Connect DataForSEO`),b(`Use the API login and API password from DataForSEO API Access. The validation call is free; later research reports can make charged requests.`,`API credentials`);let t=L(await tr({message:`DataForSEO API login`,validate:e=>e?.trim()?void 0:`API login is required`})),n=L(await S({message:`DataForSEO API password`,validate:e=>e?void 0:`API password is required`})),r={login:t.trim(),password:n},i=await new fn({credentials:()=>r}).userData(),a=await He(r);b(`${i.login} is connected with an account balance of ${ls(i.balanceMicros)}.`,`Connection verified`),x(`Saved in the ${cs(a)}. Run seo providers dataforseo status --check to verify it again.`)}}),status:v({meta:{name:`status`,description:`Show the local DataForSEO connection`},args:{check:{type:`boolean`,default:!1,description:`Verify credentials with the free account endpoint.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await a(),n=!!e.check,r=n&&t?await new fn().userData():void 0,i={connected:!!t,credentialSource:t?.source,migratedLegacyCredentials:t?.migrated??!1,liveCheck:r?{status:`passed`,account:r.login,timezone:r.timezone,balanceMicros:r.balanceMicros,observedAt:r.observedAt,requestCostMicros:r.requestCostMicros}:{status:n?`unavailable`:`not-requested`}};if(k(e)){P(i);return}F([[`Connected`,i.connected?`yes`:`no`],[`Credential`,cs(i.credentialSource)],[`Live check`,i.liveCheck.status===`passed`?`passed at ${i.liveCheck.observedAt}`:i.liveCheck.status===`unavailable`?`not available without credentials`:`not requested; pass --check to verify`],...r?[[`Account`,r.login],[`Balance`,ls(r.balanceMicros)]]:[]])}}),disconnect:v({meta:{name:`disconnect`,description:`Remove saved DataForSEO credentials`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await vn();let t=!!process.env[me]?.trim(),n=!!process.env[je],r={savedCredentialsRemoved:!0,environmentCredentials:t&&n?`active`:t||n?`partial`:`missing`,note:t||n?`Environment variables were not changed. Clear ${me} and ${je} to fully disconnect.`:`DataForSEO is disconnected.`};k(e)?P(r):process.stdout.write(`${r.note}\n`)}})}});function hs(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw new p(`INVALID_INPUT`,`--account must be a JSON object.`)}if(!t||Array.isArray(t)||typeof t!=`object`)throw new p(`INVALID_INPUT`,`--account must be a JSON object.`);let n=Object.entries(t);if(n.length>20||n.some(([e,t])=>!e||e.length>64||typeof t!=`string`||t.length>4096))throw new p(`INVALID_INPUT`,`--account must contain at most 20 bounded string fields.`);return Object.fromEntries(n.map(([e,t])=>[e,t.trim()]))}function gs(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw new p(`INVALID_INPUT`,`--params must be a JSON object.`)}if(!t||Array.isArray(t)||typeof t!=`object`)throw new p(`INVALID_INPUT`,`--params must be a JSON object.`);let n=Object.entries(t);if(n.length>100||n.some(([e])=>!/^[A-Za-z][A-Za-z0-9-]{0,63}$/u.test(e))||Buffer.byteLength(e)>64*1024)throw new p(`INVALID_INPUT`,`--params must be a JSON object smaller than 64 KiB.`);return Object.fromEntries(n)}async function _s(e){let t=await kt(),n=t.registry.get(e);if(n)return n;let r=t.failures.find(t=>t.id===e);throw r?new p(`INVALID_INPUT`,`Provider ${e} could not load: ${r.message}`):new p(`INVALID_INPUT`,`Provider ${e} is not installed.`)}function vs(e,t){let n=new Set(e.connection.fields.filter(e=>e.kind===`account`).map(e=>e.id)),r=Object.keys(t).find(e=>!n.has(e));if(r)throw new p(`INVALID_INPUT`,`${r} is not an account field for ${e.displayName}.`);let i=e.connection.normalizeAccount?e.connection.normalizeAccount(t):{...t};if(Object.keys(i).find(e=>!n.has(e)))throw new p(`PROVIDER_UNAVAILABLE`,`${e.displayName} returned an unknown account field.`);for(let t of e.connection.fields.filter(e=>e.kind===`account`&&e.required!==!1))if(!i[t.id]?.trim())throw new p(`INVALID_INPUT`,`${t.label} is required.`);return i}async function ys(){return u()}const bs=v({meta:{name:`providers`,description:`Connect optional data providers`},subCommands:{list:v({meta:{name:`list`,description:`List installed provider packages`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await ys();if(k(e)){P(t);return}t.installed.length>0?I([`Installed provider`,`Package`,`Version`,`Status`],t.installed.map(e=>[e.id,e.package,e.version,e.loadStatus])):process.stdout.write(`No provider extensions are installed.
79
+ `)}}),describe:v({meta:{name:`describe`,description:`Describe one installed provider for an agent`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await te(w(e.id)??``);if(k(e)){P(t);return}F([[`Provider`,t.displayName],[`Package`,`${t.package}@${t.version}`],[`Description`,t.description],[`Capabilities`,t.capabilities.map(e=>e.id).join(`, `)||`none`],[`Actions`,t.actions.map(e=>e.id).join(`, `)||`none`]])}}),install:v({meta:{name:`install`,description:`Install one provider package from npm`},args:{package:{type:`positional`,required:!0,description:`npm package name with an optional exact version.`},yes:{type:`boolean`,default:!1,description:`Approve third-party code installation without prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.package)??``,n=k(e),r=T(e.yes),i=N({json:n});if(!r&&!i)throw new p(`INVALID_INPUT`,`Provider installation runs third-party code. Review the package, then pass --yes to approve it in JSON or CI mode.`);let a;try{a=await s(t)}catch(e){throw new p(`INVALID_INPUT`,e instanceof Error?e.message:String(e))}if(!r&&(y(`Install provider package`),b([`${a.package}@${a.version}`,`Publisher: ${a.publisher??`not supplied by npm`}`,`Repository: ${a.repository??`not supplied by npm`}`,`Integrity: ${a.integrity}`].join(`
80
+ `),`Package`),b(`This package can read files, use the network, and run with the same local permissions as seo. Installing it is not a security review or endorsement.`,`Third-party code`),!L(await Xn({message:`Install ${a.package}@${a.version}?`,initialValue:!1})))){x(`Provider was not installed.`);return}let o;try{o=await ln(a)}catch(e){throw new p(`PROVIDER_UNAVAILABLE`,e instanceof Error?e.message:String(e))}let c={installed:o,package:a};if(n){P(c);return}x(`Installed provider ${o.id} from ${o.package}@${o.version}.`)}}),remove:v({meta:{name:`remove`,description:`Remove one installed provider extension`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},yes:{type:`boolean`,default:!1,description:`Remove the package without prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.id)??``,n=k(e),r=T(e.yes),i=N({json:n});if(!r&&!i)throw new p(`INVALID_INPUT`,`Pass --yes to remove a provider extension in JSON or CI mode.`);if(!r&&!L(await Xn({message:`Remove provider ${t}?`,initialValue:!1})))return;let a=await Le(t);if(!a)throw new p(`INVALID_INPUT`,`Provider ${t} is not installed.`);if(n){P({removed:a});return}process.stdout.write(`Removed ${t}.\n`)}}),connect:v({meta:{name:`connect`,description:`Validate and save one installed provider connection`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},account:{type:`string`,description:`Account fields as JSON. Secret fields must use their environment variables.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.id)??``,r=k(e),a=N({json:r}),o=await _s(t),s={...At(t),...hs(w(e.account))},c={};if(a){y(`Connect ${o.displayName}`),o.connection.verificationNotice&&b(o.connection.verificationNotice,`Connection check`);for(let e of o.connection.fields){if(e.kind===`account`){let t=L(await tr({message:e.label,placeholder:e.description,initialValue:s[e.id],validate:t=>e.required!==!1&&!t?.trim()?`${e.label} is required`:void 0}));t?.trim()&&(s[e.id]=t.trim());continue}if(e.envVar&&process.env[e.envVar]?.trim())continue;let t=L(await S({message:e.label,validate:t=>e.required!==!1&&!t?.trim()?`${e.label} is required`:void 0}));t?.trim()&&(c[e.id]=t.trim())}}s=vs(o,s);let l={...c};Object.keys(l).length===0&&(l=await Se({providerId:t,account:s,fields:o.connection.fields})),await i({providerId:t,account:s,credentials:l}),Object.keys(c).length>0&&await Oe({providerId:t,account:s,credentials:c}),n(t,s);let u={provider:t,connected:!0,account:s,capabilities:(o.capabilities??[]).map(e=>e.id),actions:(o.actions??[]).map(e=>e.id)};r?P(u):x(`Connected ${o.displayName}. Run seo providers describe ${t} to see what it can do.`)}}),status:v({meta:{name:`status`,description:`Show one installed provider connection`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},check:{type:`boolean`,default:!1,description:`Run the provider connection check.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.id)??``,n=await _s(t),r=At(t),a;try{a=await Se({providerId:t,account:r,fields:n.connection.fields})}catch{a=void 0}let o=n.connection.fields.filter(e=>e.kind===`account`&&e.required!==!1).every(e=>!!r[e.id]?.trim())&&a!==void 0,s=T(e.check);if(s&&!o)throw new p(`AUTH_REQUIRED`,`Provider ${t} is not connected. Run \`seo providers connect ${t}\`.`);s&&a&&await i({providerId:t,account:r,credentials:a});let c={provider:t,installed:!0,connected:o,account:r,capabilities:(n.capabilities??[]).map(e=>e.id),actions:(n.actions??[]).map(e=>e.id),check:s?`passed`:`not-requested`};if(k(e)){P(c);return}I([`Provider`,`Connected`,`Capabilities`,`Check`],[[n.displayName,o?`yes`:`no`,c.capabilities.join(`, `),c.check]])}}),disconnect:v({meta:{name:`disconnect`,description:`Remove one saved provider connection`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.id)??``;await _s(t),await ye({providerId:t,account:At(t)}),Ce(t);let n={provider:t,disconnected:!0,note:`Environment variables were not changed.`};k(e)?P(n):process.stdout.write(`Disconnected ${t}. ${n.note}\n`)}}),run:v({meta:{name:`run`,description:`Run one action supplied by an installed provider`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},action:{type:`positional`,required:!0,description:`Provider action id.`},account:{type:`string`,description:`Account fields as JSON. Defaults to the saved connection.`},params:{type:`string`,description:`Action parameters as a JSON object.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local provider cache.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.id)??``,n=w(e.action)??``;await _s(t),P(await Dt({providerId:t,actionId:n,account:{...At(t),...hs(w(e.account))},params:gs(w(e.params)),refresh:T(e.refresh)}))}}),doctor:v({meta:{name:`doctor`,description:`Validate installed provider packages and entry points`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await ys(),n={ok:t.installed.every(e=>e.loadStatus===`ready`),installed:t.installed};if(k(e)){P(n);return}if(n.installed.length===0){process.stdout.write(`No provider extensions are installed.
81
+ `);return}I([`Provider`,`Package`,`Version`,`Status`],n.installed.map(e=>[e.id,e.package,e.version,e.error??e.loadStatus]))}}),ahrefs:ds,bing:ps,dataforseo:ms}}),xs={"ai-search":`AI search`,crawl:`Crawling and technical checks`,diagnosis:`Diagnosis`,monitoring:`Monitoring`,opportunities:`Opportunities`,reporting:`Reporting`,setup:`Setup`,workflows:`Workflows`};function Ss(e){let t=w(e);if(t){if(!$t.includes(t))throw new p(`INVALID_INPUT`,`Unknown report category: ${t}. Choose ${$t.join(`, `)}.`);return t}}async function Cs(e,t){let n=w(e),r=w(t);if(n&&r)throw new p(`INVALID_INPUT`,`Use either --params or --params-file, not both.`);if(!n&&!r)return{};let i=n??await Vn(r??``,`utf8`),a;try{a=JSON.parse(i)}catch{throw new p(`INVALID_INPUT`,`Report parameters must be valid JSON.`)}if(!a||typeof a!=`object`||Array.isArray(a))throw new p(`INVALID_INPUT`,`Report parameters must be an object.`);return a}function ws(e){if(!e.isError)return;let t=e.structuredContent;throw new p(t?.error?.code??`INTERNAL_ERROR`,t?.error?.message??`The report could not be completed.`)}function Ts(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 Es=v({meta:{name:`reports`,description:`Discover and run the complete report catalog`},subCommands:{list:v({meta:{name:`list`,description:`List report ids available to the CLI and MCP server`},args:{category:{type:`string`,description:`Filter by category: ${$t.join(`, `)}.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Vt(Ss(e.category));if(k(e)){P({reports:t,categories:$t});return}ci(t,{noun:`report`,categoryLabels:xs}),process.stdout.write(`
82
+ `),ii({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:v({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=wt(w(e.id)??``);if(k(e)){P({report:t});return}ai(t.name,t.description),process.stdout.write(`
81
83
  `),F([[`ID`,t.id],[`Category`,t.category],[`Outcome`,t.outcome]]),process.stdout.write(`
82
- `),ri(`Use when`,t.useWhen),process.stdout.write(`
83
- `),ri(`Avoid when`,t.avoidWhen),process.stdout.write(`
84
- `),ri(`Read in order`,t.readOrder),process.stdout.write(`
85
- `),ri(`Do not claim`,t.doNotClaim),process.stdout.write(`
86
- `),ni(`Verify`,t.verify),process.stdout.write(`
87
- `),Xr({title:`Implement findings`,body:t.agentWorkflow.completion,command:t.agentWorkflow.actionView.cli}),t.related.length>0&&(process.stdout.write(`
88
- `),ri(`Related reports`,t.related.map(e=>`${e.id}: ${e.reason}`))),process.stdout.write(`
84
+ `),di(`Use when`,t.useWhen),process.stdout.write(`
85
+ `),di(`Avoid when`,t.avoidWhen),process.stdout.write(`
86
+ `),di(`Read in order`,t.readOrder),process.stdout.write(`
87
+ `),di(`Do not claim`,t.doNotClaim),process.stdout.write(`
88
+ `),ui(`Verify`,t.verify),process.stdout.write(`
89
+ `),ii({title:`Implement findings`,body:t.agentWorkflow.completion,command:t.agentWorkflow.actionView.cli}),t.related.length>0&&(process.stdout.write(`
90
+ `),di(`Related reports`,t.related.map(e=>`${e.id}: ${e.reason}`))),process.stdout.write(`
89
91
  Parameters
90
- `),ii(ds(t.inputSchema)),process.stdout.write(`
91
- `),Xr({title:`Need the exact schema?`,command:`seo reports describe ${t.id} --json`})}}),run:v({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.`},"actions-only":{type:`boolean`,default:!1,description:`Return findings, verification, and retained inventories without the full report body.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await Je(C(e.id)??``,await ls(e.params,e[`params-file`]),{view:w(e[`actions-only`])?`actions`:`full`});if(us(t),k(e)){P(t.structuredContent??{});return}for(let e of t.content)process.stdout.write(`${e.text}\n`)}})}}),ps=v({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=C(e.category),n=xt().filter(e=>!t||e.category===t);if(k(e)){P({rules:n});return}ei(n.map(e=>({id:e.id,category:e.category,name:`${e.title} · ${e.defaultSeverity}`})),{noun:`rule`})}}),ms=v({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=C(e.rule)??``,n=r(t);if(!n)throw Error(`Unknown rule: ${t}`);if(k(e)){P(n);return}F([[`Rule`,n.id],[`Title`,n.title],[`Category`,n.category],[`Severity`,n.defaultSeverity]]),process.stdout.write(`
92
- `),ni(`Why it matters`,n.whyItMatters),process.stdout.write(`
93
- `),ni(`How to fix`,n.howToFix),process.stdout.write(`
94
- `),ni(`Impact if ignored`,n.impactIfIgnored),process.stdout.write(`
95
- `),ni(`How to verify`,n.howToVerify)}});function hs(){return _s(`skills`,process.env.SEO_SKILLS_DIR)}function gs(){return _s(`evals`,process.env.SEO_EVALS_DIR)}function _s(e,t){if(t)return kn(t);let n=Dn(jn(import.meta.url));for(let t=0;t<6;t+=1){let t=_(n,e);if(g(_(t,`README.md`)))return t;n=Dn(n)}throw new d(`INTERNAL_ERROR`,`Packaged ${e} could not be found. Reinstall \`seo\` and try again.`)}function vs(e){return _n(_(e,`SKILL.md`),`utf8`).match(/^description:\s*(.+)$/m)?.[1]?.trim()??``}const ys=`claude -p`;function bs(){let e=gs();return vn(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(t=>({subject:En(t.name,`.json`),path:_(e,t.name)})).sort((e,t)=>e.subject<t.subject?-1:+(e.subject>t.subject))}function xs(e,t){let n;try{n=_n(t,`utf8`)}catch{throw new d(`INVALID_INPUT`,`Cannot read eval file for ${e}.`)}let r;try{r=JSON.parse(n)}catch{throw new d(`INVALID_INPUT`,`Eval file ${e}.json is not valid JSON.`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new d(`INVALID_INPUT`,`Eval file ${e}.json must be an object.`);let i=r;if(i.subject!==e)throw new d(`INVALID_INPUT`,`Eval file ${e}.json must set subject to "${e}".`);if(!Array.isArray(i.evals)||i.evals.length===0)throw new d(`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 d(`INVALID_INPUT`,`${i}: id must be an integer.`);let o=r.id;if(a.has(o))throw new d(`INVALID_INPUT`,`${i}: duplicate id ${o}.`);if(a.add(o),typeof r.prompt!=`string`||r.prompt.trim().length===0)throw new d(`INVALID_INPUT`,`${i}: prompt must be a non-empty string.`);if(typeof r.expected_output!=`string`||r.expected_output.trim().length===0)throw new d(`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 d(`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 d(`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 Ss(){let e=_(hs(),`seo`,`SKILL.md`);if(!g(e))throw new d(`INTERNAL_ERROR`,"The seo router skill could not be found. Reinstall `seo` or use --no-skill.");return _n(e,`utf8`)}function Cs(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===`
96
- `||s===`\r`){r&&=(t.push(n),n=``,!1);continue}n+=s,r=!0}if(i||a)throw new d(`INVALID_INPUT`,`Unbalanced quote in agent command.`);return r&&t.push(n),t}function ws(e,t){let n=Cs(e);if(n.length===0)throw new d(`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 Ts(e,t){return e?`${e.trim()}\n\n---\n\nUser request:\n${t}`:t}function Es(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(`
92
+ `),fi(Ts(t.inputSchema)),process.stdout.write(`
93
+ `),ii({title:`Need the exact schema?`,command:`seo reports describe ${t.id} --json`})}}),run:v({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.`},"actions-only":{type:`boolean`,default:!1,description:`Return findings, verification, and retained inventories without the full report body.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await tt(w(e.id)??``,await Cs(e.params,e[`params-file`]),{view:T(e[`actions-only`])?`actions`:`full`});if(ws(t),k(e)){P(t.structuredContent??{});return}for(let e of t.content)process.stdout.write(`${e.text}\n`)}})}}),Ds=v({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=w(e.category),n=yn().filter(e=>!t||e.category===t);if(k(e)){P({rules:n});return}ci(n.map(e=>({id:e.id,category:e.category,name:`${e.title} · ${e.defaultSeverity}`})),{noun:`rule`})}}),Os=v({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=w(e.rule)??``,n=Me(t);if(!n)throw Error(`Unknown rule: ${t}`);if(k(e)){P(n);return}F([[`Rule`,n.id],[`Title`,n.title],[`Category`,n.category],[`Severity`,n.defaultSeverity]]),process.stdout.write(`
94
+ `),ui(`Why it matters`,n.whyItMatters),process.stdout.write(`
95
+ `),ui(`How to fix`,n.howToFix),process.stdout.write(`
96
+ `),ui(`Impact if ignored`,n.impactIfIgnored),process.stdout.write(`
97
+ `),ui(`How to verify`,n.howToVerify)}});function ks(){return js(`skills`,process.env.SEO_SKILLS_DIR)}function As(){return js(`evals`,process.env.SEO_EVALS_DIR)}function js(e,t){if(t)return Dn(t);let n=Tn(zn(import.meta.url));for(let t=0;t<6;t+=1){let t=g(n,e);if(_(g(t,`README.md`)))return t;n=Tn(n)}throw new p(`INTERNAL_ERROR`,`Packaged ${e} could not be found. Reinstall \`seo\` and try again.`)}function Ms(e){return Nn(g(e,`SKILL.md`),`utf8`).match(/^description:\s*(.+)$/m)?.[1]?.trim()??``}const Ns=`claude -p`;function Ps(){let e=As();return Pn(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(t=>({subject:wn(t.name,`.json`),path:g(e,t.name)})).sort((e,t)=>e.subject<t.subject?-1:+(e.subject>t.subject))}function Fs(e,t){let n;try{n=Nn(t,`utf8`)}catch{throw new p(`INVALID_INPUT`,`Cannot read eval file for ${e}.`)}let r;try{r=JSON.parse(n)}catch{throw new p(`INVALID_INPUT`,`Eval file ${e}.json is not valid JSON.`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new p(`INVALID_INPUT`,`Eval file ${e}.json must be an object.`);let i=r;if(i.subject!==e)throw new p(`INVALID_INPUT`,`Eval file ${e}.json must set subject to "${e}".`);if(!Array.isArray(i.evals)||i.evals.length===0)throw new p(`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 p(`INVALID_INPUT`,`${i}: id must be an integer.`);let o=r.id;if(a.has(o))throw new p(`INVALID_INPUT`,`${i}: duplicate id ${o}.`);if(a.add(o),typeof r.prompt!=`string`||r.prompt.trim().length===0)throw new p(`INVALID_INPUT`,`${i}: prompt must be a non-empty string.`);if(typeof r.expected_output!=`string`||r.expected_output.trim().length===0)throw new p(`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 p(`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 p(`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 Is(){let e=g(ks(),`seo`,`SKILL.md`);if(!_(e))throw new p(`INTERNAL_ERROR`,"The seo router skill could not be found. Reinstall `seo` or use --no-skill.");return Nn(e,`utf8`)}function Ls(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===`
98
+ `||s===`\r`){r&&=(t.push(n),n=``,!1);continue}n+=s,r=!0}if(i||a)throw new p(`INVALID_INPUT`,`Unbalanced quote in agent command.`);return r&&t.push(n),t}function Rs(e,t){let n=Ls(e);if(n.length===0)throw new p(`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 zs(e,t){return e?`${e.trim()}\n\n---\n\nUser request:\n${t}`:t}function Bs(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(`
97
99
  `),`</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(`
98
- `);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 Ds(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 Os(e,t){let n=Ds(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 ks(e,t){return new Promise(n=>{let r=Date.now(),[i,...a]=e,o;try{o=Ln(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),ee=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=>{ee({stdout:s,stderr:c,code:null,timedOut:u,spawnError:e.message})}),o.on(`close`,e=>{ee({stdout:s,stderr:c,code:e,timedOut:u})}),o.stdin&&(t.input===void 0?o.stdin.end():o.stdin.end(t.input))})}async function As(e,t,n){let{argv:r,usesPlaceholder:i}=ws(e,t);return ks(r,{input:i?void 0:t,timeoutMs:n})}async function js(e,t){let n=Date.now(),r=Ts(t.skillBody,e.prompt),i=await As(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:X(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:X(e.assertions)};if(a.length===0)return{...o,status:`errored`,error:`Agent returned no output on stdout.`,durationMs:Date.now()-n,assertions:X(e.assertions)};if(!t.judge)return{...o,status:`unjudged`,durationMs:Date.now()-n,assertions:X(e.assertions)};let s=0,c=``;for(let r=0;r<2;r+=1){let i=Es(e.prompt,a,e.assertions,r>0),l=await As(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:X(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:X(e.assertions)};let u=Os(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:X(e.assertions)}}function X(e){return e.map(e=>({assertion:e,verdict:`unjudged`}))}async function Ms(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 Ns(e){let t={passed:0,failed:0,errored:0,unjudged:0};for(let n of e)t[n.status]+=1;return t}function Ps(e){let t=[],n=C(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 Fs(e){let t=bs();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 d(`INVALID_INPUT`,`Unknown eval subject: ${e}.${n?` Known subjects: ${n}.`:``}`)}return r})}function Is(e){let t=bs().map(e=>{let t=xs(e.subject,e.path);return{subject:e.subject,evals:t.evals.length}});if(e){P({schemaVersion:1,subjects:t});return}if(t.length===0){process.stdout.write(`No eval subjects found.
100
+ `);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 Vs(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 Hs(e,t){let n=Vs(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 Us(e,t){return new Promise(n=>{let r=Date.now(),[i,...a]=e,o;try{o=Gn(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,ee=setTimeout(()=>{u=!0,o.kill(`SIGTERM`),d=setTimeout(()=>{try{o.kill(`SIGKILL`)}catch{}},2e3),d.unref()},t.timeoutMs),te=e=>{l||(l=!0,clearTimeout(ee),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=>{te({stdout:s,stderr:c,code:null,timedOut:u,spawnError:e.message})}),o.on(`close`,e=>{te({stdout:s,stderr:c,code:e,timedOut:u})}),o.stdin&&(t.input===void 0?o.stdin.end():o.stdin.end(t.input))})}async function Ws(e,t,n){let{argv:r,usesPlaceholder:i}=Rs(e,t);return Us(r,{input:i?void 0:t,timeoutMs:n})}async function Gs(e,t){let n=Date.now(),r=zs(t.skillBody,e.prompt),i=await Ws(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:X(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:X(e.assertions)};if(a.length===0)return{...o,status:`errored`,error:`Agent returned no output on stdout.`,durationMs:Date.now()-n,assertions:X(e.assertions)};if(!t.judge)return{...o,status:`unjudged`,durationMs:Date.now()-n,assertions:X(e.assertions)};let s=0,c=``;for(let r=0;r<2;r+=1){let i=Bs(e.prompt,a,e.assertions,r>0),l=await Ws(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:X(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:X(e.assertions)};let u=Hs(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:X(e.assertions)}}function X(e){return e.map(e=>({assertion:e,verdict:`unjudged`}))}async function Ks(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 qs(e){let t={passed:0,failed:0,errored:0,unjudged:0};for(let n of e)t[n.status]+=1;return t}function Js(e){let t=[],n=w(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 Ys(e){let t=Ps();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 p(`INVALID_INPUT`,`Unknown eval subject: ${e}.${n?` Known subjects: ${n}.`:``}`)}return r})}function Xs(e){let t=Ps().map(e=>{let t=Fs(e.subject,e.path);return{subject:e.subject,evals:t.evals.length}});if(e){P({schemaVersion:1,subjects:t});return}if(t.length===0){process.stdout.write(`No eval subjects found.
99
101
  `);return}let n=Math.max(...t.map(e=>e.subject.length));process.stdout.write(`Eval subjects
100
- `);for(let e of t){let t=e.evals===1?`eval`:`evals`;process.stdout.write(` ${e.subject.padEnd(n)} ${e.evals} ${t}\n`)}}function Ls(e){return e===`passed`?`PASS`:e===`failed`?`FAIL`:e===`errored`?`ERROR`:`UNJUDGED`}function Rs(e,t){t.judged?process.stdout.write(`Assertion verdicts below are judge verdicts, model judgments from the judge agent, not ground truth.
102
+ `);for(let e of t){let t=e.evals===1?`eval`:`evals`;process.stdout.write(` ${e.subject.padEnd(n)} ${e.evals} ${t}\n`)}}function Zs(e){return e===`passed`?`PASS`:e===`failed`?`FAIL`:e===`errored`?`ERROR`:`UNJUDGED`}function Qs(e,t){t.judged?process.stdout.write(`Assertion verdicts below are judge verdicts, model judgments from the judge agent, not ground truth.
101
103
 
102
104
  `):process.stdout.write(`Judging was skipped. Review each agent reply against the assertion checklist by hand.
103
105
 
104
- `);for(let n of e){process.stdout.write(`# ${n.subject}\n`);for(let e of n.evals){if(process.stdout.write(`\n[${Ls(e.status)}] eval ${e.id} (${e.durationMs}ms)\n`),process.stdout.write(` prompt: ${Bs(e.prompt,100)}\n`),e.error&&process.stdout.write(` error: ${e.error}\n`),!t.judged){process.stdout.write(` reply: ${Bs(e.reply,200)}\n`),process.stdout.write(` assertions to review:
105
- `);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=Ns(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=zs(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 zs(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 Bs(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const Vs=v({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:ys,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:cr(`Judge assertions with an agent.`,`Skip judging and print replies with an assertion checklist.`),skill:cr(`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=k(e);if(e.list===!0){Is(t);return}let n=Fs(Ps(e)),r=E(e.id);if(r!==void 0&&n.length!==1)throw new d(`INVALID_INPUT`,`--id needs exactly one subject. Name the subject to filter.`);let i=E(e.timeout)??300;if(!(i>0))throw new d(`INVALID_INPUT`,`--timeout must be a positive number of seconds.`);let a=Math.max(1,Math.min(4,E(e.concurrency)??1)),o=C(e.agent)??ys,s=e.judge===!1?null:C(e[`judge-agent`])??o,c=e.skill===!1?null:Ss(),l={agent:o,judge:s,skillBody:c,timeoutMs:i*1e3},u=[];for(let e of n){let n=xs(e.subject,e.path).evals;if(r!==void 0&&(n=n.filter(e=>e.id===r),n.length===0))throw new d(`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 Ms(n,a,e=>js(e,l)),o=Ns(i);u.push({subject:e.subject,...o,evals:i})}let f=zs(u),ee=f.failed>0||f.errored>0;t?P({schemaVersion:1,agent:o,judge:s,judged:s!==null,skillContext:c!==null,timeoutSeconds:i,concurrency:a,subjects:u,totals:f}):Rs(u,{judged:s!==null,agent:o,judge:s}),ee&&(process.exitCode=1)}});function Hs(){let e=hs();return vn(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&g(_(e,t.name,`SKILL.md`))).map(t=>({name:t.name,description:vs(_(e,t.name)),path:_(e,t.name)})).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}function Us(e){let t=Hs();if(!e)return t;let n=t.find(t=>t.name===e);if(!n)throw new d(`INVALID_INPUT`,`Unknown skill: ${e}.`);return[n]}const Ws=v({meta:{name:`skill`,description:`Inspect the packaged SEO skill and run its evals`},subCommands:{list:v({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=Hs();if(k(e)){P({skills:t});return}Zr(`SEO skill`,`Packaged with this CLI.`),process.stdout.write(`
106
+ `);for(let n of e){process.stdout.write(`# ${n.subject}\n`);for(let e of n.evals){if(process.stdout.write(`\n[${Zs(e.status)}] eval ${e.id} (${e.durationMs}ms)\n`),process.stdout.write(` prompt: ${ec(e.prompt,100)}\n`),e.error&&process.stdout.write(` error: ${e.error}\n`),!t.judged){process.stdout.write(` reply: ${ec(e.reply,200)}\n`),process.stdout.write(` assertions to review:
107
+ `);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=qs(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=$s(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 $s(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 ec(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const tc=v({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:Ns,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:hr(`Judge assertions with an agent.`,`Skip judging and print replies with an assertion checklist.`),skill:hr(`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=k(e);if(e.list===!0){Xs(t);return}let n=Ys(Js(e)),r=E(e.id);if(r!==void 0&&n.length!==1)throw new p(`INVALID_INPUT`,`--id needs exactly one subject. Name the subject to filter.`);let i=E(e.timeout)??300;if(!(i>0))throw new p(`INVALID_INPUT`,`--timeout must be a positive number of seconds.`);let a=Math.max(1,Math.min(4,E(e.concurrency)??1)),o=w(e.agent)??Ns,s=e.judge===!1?null:w(e[`judge-agent`])??o,c=e.skill===!1?null:Is(),l={agent:o,judge:s,skillBody:c,timeoutMs:i*1e3},u=[];for(let e of n){let n=Fs(e.subject,e.path).evals;if(r!==void 0&&(n=n.filter(e=>e.id===r),n.length===0))throw new p(`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 Ks(n,a,e=>Gs(e,l)),o=qs(i);u.push({subject:e.subject,...o,evals:i})}let d=$s(u),ee=d.failed>0||d.errored>0;t?P({schemaVersion:1,agent:o,judge:s,judged:s!==null,skillContext:c!==null,timeoutSeconds:i,concurrency:a,subjects:u,totals:d}):Qs(u,{judged:s!==null,agent:o,judge:s}),ee&&(process.exitCode=1)}});function nc(){let e=ks();return Pn(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&_(g(e,t.name,`SKILL.md`))).map(t=>({name:t.name,description:Ms(g(e,t.name)),path:g(e,t.name)})).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}function rc(e){let t=nc();if(!e)return t;let n=t.find(t=>t.name===e);if(!n)throw new p(`INVALID_INPUT`,`Unknown skill: ${e}.`);return[n]}const ic=v({meta:{name:`skill`,description:`Inspect the packaged SEO skill and run its evals`},subCommands:{list:v({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=nc();if(k(e)){P({skills:t});return}ai(`SEO skill`,`Packaged with this CLI.`),process.stdout.write(`
106
108
  `);for(let e of t)F([[`Name`,e.name],[`Purpose`,`Helps agents choose and run the right SEO audit or report.`],[`Path`,e.path]]);process.stdout.write(`
107
- `),Xr({title:`Add it to an agent`,body:`Run setup to install the skill and connect your first site.`,command:`seo start`})}}),path:v({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=C(e.name),n=t?Us(t)[0]?.path:hs();k(e)?P({name:t,path:n}):process.stdout.write(`${n}\n`)}}),install:v({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=k(e),n=ao({quiet:t});if(t){P(n),n.status===`failed`&&(process.exitCode=1);return}if(n.status===`failed`)throw new d(`INTERNAL_ERROR`,`Skill install failed: ${n.error}`);process.stdout.write(`SEO skill installed. Agents that support skills can discover it now.
108
- `)}}),eval:Vs}}),Gs=v({meta:{name:`privacy`,description:`Show local config, token, cache, and log storage paths`},run:async()=>{let e=$t(),t=Rt();F(e.map(e=>[e.label,`${e.path} · ${ai(e.sizeBytes)} · ${e.mode}`])),process.stdout.write(`
109
- `),F(Object.entries(t.counts).map(([e,t])=>[e,String(t)]))}}),Ks=v({meta:{name:`reset`,description:`Delete saved credentials and all local data`},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=k(e);if(!e.yes&&!N({json:t}))throw new d(`INVALID_INPUT`,`Cannot prompt here. Pass --yes to confirm reset.`);if(!(e.yes||L(await Hn({message:`Delete saved credentials and all local data?`,initialValue:!1})))){Vn(`Reset aborted.`);return}await Ze(),t?P({reset:!0}):process.stdout.write(`Reset complete.
110
- `)}}),qs=v({meta:{name:`sites`,description:`List Search Console properties available to this Google login`},args:{json:{type:`boolean`,default:!1},refresh:{type:`boolean`,default:!1},account:{type:`string`,description:`Saved Google account email.`}},run:async({args:e})=>{let t=await Ht(w(e.refresh),C(e.account));if(k(e)){P({sites:t});return}I([`Property`,`Permission`],t.map(e=>[e.siteUrl,e.permissionLevel??`unknown`]))}}),Js=v({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 rn({product:C(e.product),limit:E(e.limit)});if(k(e)){P({updates:t});return}ti(t.map(e=>({title:e.name,meta:[e.type,e.status,`${e.start.slice(0,10)} to ${e.end?.slice(0,10)??`present`}`]})),{empty:`No matching Google Search updates.`})}}),Ys={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 Xs(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 Zs(e,t){let n=Xs(e);if(t){P(n);return}F([[`Anonymous telemetry`,e.enabled?`enabled`:`disabled`],[`Reason`,e.reason?Ys[e.reason]:`local setting`],[`State file`,e.stateFile],[`Install cohort`,e.state?.cohort??`not created`]]),process.stdout.write(`
109
+ `),ii({title:`Add it to an agent`,body:`Run setup to install the skill and connect your first site.`,command:`seo start`})}}),path:v({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=w(e.name),n=t?rc(t)[0]?.path:ks();k(e)?P({name:t,path:n}):process.stdout.write(`${n}\n`)}}),install:v({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=k(e),n=mo({quiet:t});if(t){P(n),n.status===`failed`&&(process.exitCode=1);return}if(n.status===`failed`)throw new p(`INTERNAL_ERROR`,`Skill install failed: ${n.error}`);process.stdout.write(`SEO skill installed. Agents that support skills can discover it now.
110
+ `)}}),eval:tc}}),ac=v({meta:{name:`privacy`,description:`Show local config, token, cache, and log storage paths`},run:async()=>{let e=Lt(),t=Pt();F(e.map(e=>[e.label,`${e.path} · ${pi(e.sizeBytes)} · ${e.mode}`])),process.stdout.write(`
111
+ `),F(Object.entries(t.counts).map(([e,t])=>[e,String(t)]))}}),oc=v({meta:{name:`reset`,description:`Delete saved credentials and all local data`},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=k(e);if(!e.yes&&!N({json:t}))throw new p(`INVALID_INPUT`,`Cannot prompt here. Pass --yes to confirm reset.`);if(!(e.yes||L(await Xn({message:`Delete saved credentials and all local data?`,initialValue:!1})))){Yn(`Reset aborted.`);return}await it(),t?P({reset:!0}):process.stdout.write(`Reset complete.
112
+ `)}}),sc=v({meta:{name:`sites`,description:`List Search Console properties available to this Google login`},args:{json:{type:`boolean`,default:!1},refresh:{type:`boolean`,default:!1},account:{type:`string`,description:`Saved Google account email.`}},run:async({args:e})=>{let n=await t(T(e.refresh),w(e.account));if(k(e)){P({sites:n});return}I([`Property`,`Permission`],n.map(e=>[e.siteUrl,e.permissionLevel??`unknown`]))}}),cc=v({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 ot({product:w(e.product),limit:E(e.limit)});if(k(e)){P({updates:t});return}li(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.`})}}),lc={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 uc(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 dc(e,t){let n=uc(e);if(t){P(n);return}F([[`Anonymous telemetry`,e.enabled?`enabled`:`disabled`],[`Reason`,e.reason?lc[e.reason]:`local setting`],[`State file`,e.stateFile],[`Install cohort`,e.state?.cohort??`not created`]]),process.stdout.write(`
111
113
  Only tool usage is sent. URLs, report data, Google data, and identifiers are never sent.
112
114
  `),process.stdout.write(`Details: https://seoskill.dev/telemetry
113
- `)}const Qs={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},$s=v({meta:{name:`telemetry`,description:`Check or change anonymous usage telemetry`},subCommands:{status:v({meta:{name:`status`,description:`Show whether anonymous usage telemetry is enabled`},args:{json:Qs},run:async({args:e})=>Zs(Et(),k(e))}),enable:v({meta:{name:`enable`,description:`Enable anonymous usage telemetry in local settings`},args:{json:Qs},run:async({args:e})=>{Zs(ct(!0),k(e))}}),disable:v({meta:{name:`disable`,description:`Disable anonymous usage telemetry in local settings`},args:{json:Qs},run:async({args:e})=>{Zs(ct(!1),k(e))}})}});function ec(e){let t=e.toLowerCase();return[`pass`,`passed`,`complete`,`completed`,`joined`].includes(t)?`pass`:[`warn`,`warning`,`partial`,`review`].includes(t)?`warning`:[`fail`,`failed`,`error`].includes(t)?`fail`:[`unknown`,`unavailable`].includes(t)?`unknown`:`info`}function tc(e){let t=e.steps.map(e=>ec(e.status)),n=t.includes(`fail`)?`fail`:t.includes(`warning`)?`warning`:t.includes(`unknown`)?`unknown`:`pass`;$r({title:e.workflow,target:e.site,status:n,summary:e.summary,metrics:[{label:`Completed`,value:t.filter(e=>e===`pass`).length,status:`pass`},{label:`Review`,value:t.filter(e=>e===`warning`).length,status:`warning`},{label:`Unknown`,value:t.filter(e=>e===`unknown`).length,status:`unknown`}],sections:[{title:`Evidence collection`,diagnostics:e.steps.map(e=>({status:ec(e.status),title:e.tool,explanation:e.summary,evidence:[`Status: ${e.status}`]}))},{title:`Priority actions`,diagnostics:e.actions.map(e=>({status:`warning`,title:e.title,explanation:`Confidence: ${e.confidence}.`,fix:e.action}))}]})}const nc=v({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. Defaults to the --site home page.`},site:{type:`string`,description:`GSC property URL for joining page metrics.`},...$i,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=k(e),n=await ac(e),r=ic(e),i=C(e.site),a=r??(i?ta(i):void 0)??n[0];if(!a)throw new d(`INVALID_INPUT`,"No crawl URL given. Pass a URL, --url or --site. Run `seo sites` to list your Search Console properties.");let o=await jt({url:a,site:i,mode:rc(e.mode)??(n.length?`list`:void 0),urls:n,maxPages:E(e[`max-pages`]),maxDepth:E(e[`max-depth`]),concurrency:E(e.concurrency),refresh:w(e.refresh),fetchRate:pr({...e,"fetch-concurrency":e.concurrency}),include:O(e.include),exclude:O(e.exclude),googleAnalyticsPropertyId:C(e[`google-analytics-property`]),analyticsConnection:ea(e),useSitemap:!T(e,`sitemap`),respectRobots:!T(e,`robots`),checkExternal:!T(e,`external`),js:!!w(e.js),limit:E(e.limit)});if(t){P(o);return}tc(o),I([`Rank`,`Score`,`Rule`,`Severity`,`Affected`,`Target`,`Action`],o.output.queue.map((e,t)=>[t+1,e.score,e.ruleId,e.severity,e.affectedUrls,e.target,e.action])),G(`Implementation queue details`,o.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 rc(e){let t=C(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function ic(e){let t=C(e.crawlUrl),n=C(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}async function ac(e){let t=O(e.urls)??[],n=C(e[`urls-file`]);return n&&t.push(...oc(await Nn(n,`utf8`))),[...new Set(t)]}function oc(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}const sc=v({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.`},...J([`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.`}}),...$i,"verify-content":cr(`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=k(e),n=await zt({site:R(C(e.site)),days:E(e.days),recentDays:E(e.recent),limit:E(e.limit),includeBrand:w(e[`include-brand`]),googleAnalyticsPropertyId:C(e[`google-analytics-property`]),analyticsConnection:ea(e),verifyContent:w(e[`verify-content`]),verifyLimit:E(e[`verify-limit`]),refresh:w(e.refresh)});if(t){P(n);return}tc(n),I([`Source`,`Category`,`Score`,`Findings`,`Template`,`Analytics`,`Target`,`Action`],n.output.queue.map(e=>[e.source,e.category,e.score,e.grouped?.count??1,e.template?.label??`-`,e.analytics?.sessions??`-`,e.target,e.action])),G(`Queue action details`,n.output.queue.map(e=>({label:e.target,context:`${e.category}, score ${e.score}`,action:e.action})))}});function cc(e){return e===null?`-`:e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function lc(e){return[...e.winners.map(e=>({direction:`winner`,item:e})),...e.losers.map(e=>({direction:`loser`,item:e}))]}function uc(e,t){let n=lc(t);n.length&&(process.stdout.write(`\n${e}\n`),I([`Direction`,`Key`,`Clicks`,`Impr.`,`Position`],n.map(({direction:e,item:t})=>[e,t.key,cc(t.clickDelta),cc(t.impressionDelta),cc(t.positionDelta)])))}function dc(e){process.stdout.write(`
115
+ `)}const fc={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},pc=v({meta:{name:`telemetry`,description:`Check or change anonymous usage telemetry`},subCommands:{status:v({meta:{name:`status`,description:`Show whether anonymous usage telemetry is enabled`},args:{json:fc},run:async({args:e})=>dc(Nt(),k(e))}),enable:v({meta:{name:`enable`,description:`Enable anonymous usage telemetry in local settings`},args:{json:fc},run:async({args:e})=>{dc(ht(!0),k(e))}}),disable:v({meta:{name:`disable`,description:`Disable anonymous usage telemetry in local settings`},args:{json:fc},run:async({args:e})=>{dc(ht(!1),k(e))}})}});function mc(e){let t=e.toLowerCase();return[`pass`,`passed`,`complete`,`completed`,`joined`].includes(t)?`pass`:[`warn`,`warning`,`partial`,`review`].includes(t)?`warning`:[`fail`,`failed`,`error`].includes(t)?`fail`:[`unknown`,`unavailable`].includes(t)?`unknown`:`info`}function hc(e){let t=e.steps.map(e=>mc(e.status)),n=t.includes(`fail`)?`fail`:t.includes(`warning`)?`warning`:t.includes(`unknown`)?`unknown`:`pass`;si({title:e.workflow,target:e.site,status:n,summary:e.summary,metrics:[{label:`Completed`,value:t.filter(e=>e===`pass`).length,status:`pass`},{label:`Review`,value:t.filter(e=>e===`warning`).length,status:`warning`},{label:`Unknown`,value:t.filter(e=>e===`unknown`).length,status:`unknown`}],sections:[{title:`Evidence collection`,diagnostics:e.steps.map(e=>({status:mc(e.status),title:e.tool,explanation:e.summary,evidence:[`Status: ${e.status}`]}))},{title:`Priority actions`,diagnostics:e.actions.map(e=>({status:`warning`,title:e.title,explanation:`Confidence: ${e.confidence}.`,fix:e.action}))}]})}const gc=v({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. Defaults to the --site home page.`},site:{type:`string`,description:`GSC property URL for joining page metrics.`},...sa,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=k(e),n=await yc(e),r=vc(e),i=w(e.site),a=r??(i?la(i):void 0)??n[0];if(!a)throw new p(`INVALID_INPUT`,"No crawl URL given. Pass a URL, --url or --site. Run `seo sites` to list your Search Console properties.");let o=await an({url:a,site:i,mode:_c(e.mode)??(n.length?`list`:void 0),urls:n,maxPages:E(e[`max-pages`]),maxDepth:E(e[`max-depth`]),concurrency:E(e.concurrency),refresh:T(e.refresh),fetchRate:xr({...e,"fetch-concurrency":e.concurrency}),include:O(e.include),exclude:O(e.exclude),googleAnalyticsPropertyId:w(e[`google-analytics-property`]),analyticsConnection:ca(e),useSitemap:!_r(e,`sitemap`),respectRobots:!_r(e,`robots`),checkExternal:!_r(e,`external`),js:!!T(e.js),limit:E(e.limit)});if(t){P(o);return}hc(o),I([`Rank`,`Score`,`Rule`,`Severity`,`Affected`,`Target`,`Action`],o.output.queue.map((e,t)=>[t+1,e.score,e.ruleId,e.severity,e.affectedUrls,e.target,e.action])),G(`Implementation queue details`,o.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 _c(e){let t=w(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function vc(e){let t=w(e.crawlUrl),n=w(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}async function yc(e){let t=O(e.urls)??[],n=w(e[`urls-file`]);return n&&t.push(...bc(await Vn(n,`utf8`))),[...new Set(t)]}function bc(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}const xc=v({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.`},...J([`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.`}}),...sa,"verify-content":hr(`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=k(e),n=await Ft({site:R(w(e.site)),days:E(e.days),recentDays:E(e.recent),limit:E(e.limit),includeBrand:T(e[`include-brand`]),googleAnalyticsPropertyId:w(e[`google-analytics-property`]),analyticsConnection:ca(e),verifyContent:T(e[`verify-content`]),verifyLimit:E(e[`verify-limit`]),refresh:T(e.refresh)});if(t){P(n);return}hc(n),I([`Source`,`Category`,`Score`,`Findings`,`Template`,`Analytics`,`Target`,`Action`],n.output.queue.map(e=>[e.source,e.category,e.score,e.grouped?.count??1,e.template?.label??`-`,e.analytics?.sessions??`-`,e.target,e.action])),G(`Queue action details`,n.output.queue.map(e=>({label:e.target,context:`${e.category}, score ${e.score}`,action:e.action})))}});function Sc(e){return e===null?`-`:e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function Cc(e){return[...e.winners.map(e=>({direction:`winner`,item:e})),...e.losers.map(e=>({direction:`loser`,item:e}))]}function wc(e,t){let n=Cc(t);n.length&&(process.stdout.write(`\n${e}\n`),I([`Direction`,`Key`,`Clicks`,`Impr.`,`Position`],n.map(({direction:e,item:t})=>[e,t.key,Sc(t.clickDelta),Sc(t.impressionDelta),Sc(t.positionDelta)])))}function Tc(e){process.stdout.write(`
114
116
  Segment coverage
115
- `),I([`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 fc(e){e.length&&(process.stdout.write(`
117
+ `),I([`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 Ec(e){e.length&&(process.stdout.write(`
116
118
  Template movement
117
- `),I([`Direction`,`Template`,`Pattern confidence`,`URLs`,`Clicks`,`Returned share`,`Common terms`],e.map(e=>[e.direction,e.signature,e.confidence,e.urlCount,cc(e.clickDelta),`${Math.round(e.movementShare*100)}%`,e.commonTerms.join(`, `)||`-`])),K(`Template actions`,e.map(e=>e.summary)),K(`Template evidence scope`,[`Shares use returned directional page click movement. Pattern confidence applies only to returned matched-retained page segments.`]))}const pc=v({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.`},...J([`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.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e),n=R(C(e.site)),r=await ut({site:n,days:E(e.days),recentDays:E(e.recent),limit:E(e.limit),includeBrand:w(e[`include-brand`]),knownConfounders:C(e[`known-change`])?[C(e[`known-change`])??``]:void 0,refresh:w(e.refresh)});if(t){P(r);return}U({title:`Update postmortem`,target:r.site,status:`unknown`,summary:r.summary,metrics:[{label:`Attribution`,value:r.output.update.attribution.replaceAll(`-`,` `)},{label:`Confidence`,value:r.output.update.confidence},{label:`Known confounders`,value:r.output.update.confounders.length}]}),K(`Recommended actions`,r.actions.map(e=>`${e.title} (${e.confidence}): ${e.action}`)),K(`Postmortem findings`,r.output.insights.map(e=>e.summary)),K(`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)),fc(r.output.templateMovement),K(`Update evidence`,r.output.update.evidence),dc(r.output.segments),uc(`Page winners and losers`,r.output.segments.page),uc(`Query winners and losers`,r.output.segments.query),uc(`Device winners and losers`,r.output.segments.device),uc(`Country winners and losers`,r.output.segments.country),vi(`seo export update-postmortem --site ${JSON.stringify(n)}`)}}),mc=new Set([`database`,`filesystem`,`internal`,`unknown`]);function hc(e){return e.replace(/^v/,``).split(`.`)[0]||`unknown`}function gc(e){return cn(e[0])?e[0]:void 0}function _c(e,t){return rt(e)?`seo ${e}`:t?`seo ${t}`:`seo command`}function vc(e){let t=Qt(e.error);if(!mc.has(t.errorCategory))return;let n=gc(e.args),r=_c(e.report,n),i=[wt(e.error).code,t.errorCategory,t.failureReason,t.failureContext].filter(Boolean).join(` | `),a=new URL(`https://github.com/iannuttall/seo/issues/new`);return a.searchParams.set(`template`,`bug.yml`),a.searchParams.set(`title`,`bug: ${r} failed`),a.searchParams.set(`version`,e.version??Ft),a.searchParams.set(`runtime`,`Node ${hc(e.nodeVersion??process.version)} on ${e.processPlatform??Tn()} (${e.processArch??Cn()})`),a.searchParams.set(`diagnostics`,i),a.toString()}const yc={"refresh-priorities":`seo report`,"query-cluster":`seo report`,"quick-wins":`seo report --section quick-wins`,"ctr-underperformers":`seo report --section low-ctr`,"striking-distance":`seo report --section striking-distance`,"second-page":`seo report --section second-page`,decaying:`seo report --section content-decay`,cannibal:`seo report --section cannibalization`,"traffic-anomaly":`seo report --section traffic-drop`,"page-opportunities":`seo page --url <url>`,"audit-page":`seo page --url <url>`,"url-inspect":`seo page --url <url>`,"segment-impact":`seo compare --date <date>`,"update-correlate":`seo compare --date <date>`,"update-postmortem":`seo compare --date <date>`,"link-recover":`seo index`,"gsc-query":`seo data`},bc={"agent-readiness":null,"ai-readiness":null,"community-intent":null,"entity-readiness":null,llms:null,"monthly-report":`seo report`,okf:null,pseo:null,"report-narrative":`seo report`,"seo-to-ai-query":null,"server-logs":null,links:`seo research backlinks --target <domain>`,"export knowledge":null,"export monthly":`seo report --json`,"export narrative":`seo report --json`,"export pseo":null,indexnow:null,"providers semrush":`seo providers`,"providers limits":null,"providers spend":null,"providers dataforseo limits":null,"providers dataforseo spend":null,"providers ahrefs limits":null,"change-log":null,client:null,project:null,projects:null,"content-groups":null,"crawl-diff":`seo crawl`,"crawl-reports":`seo crawl`,diagnose:`seo report`,"diagnose-property":`seo report`,"export diagnose":`seo report --json`,"index-watch":`seo page --url <url>`,monitoring:`seo crawl`,schedule:null,"technical-watch":`seo crawl`,tests:`seo compare --date <date>`},Z=`It saved history between runs. Your agent keeps its own notes now.`,xc=`Commands take --site now instead of a saved project.`,Sc=`Spend is controlled in your provider account. Set limits in DataForSEO, Ahrefs or the other provider.`,Cc={"providers limits":Sc,"providers spend":Sc,"providers dataforseo limits":Sc,"providers dataforseo spend":Sc,"providers ahrefs limits":Sc,"change-log":Z,client:xc,project:xc,projects:xc,"content-groups":Z,"crawl-diff":Z,"crawl-reports":Z,diagnose:Z,"diagnose-property":Z,"export diagnose":Z,"index-watch":Z,monitoring:Z,schedule:Z,"technical-watch":Z,tests:Z},wc=new Set([`client`,`project`,`projects`]);function Tc(e){let t=e.findIndex(e=>e.startsWith(`-`)),n=t===-1?e:e.slice(0,t),r=+(n[0]===`help`);for(let e=3;e>=1;--e){let t=n.slice(r,r+e).join(` `);if(n.length-r>=e&&Object.hasOwn(bc,t))return t}return null}function Ec(e){let t=Object.hasOwn(yc,e)?yc[e]:void 0;return t?`\`seo ${e}\` is now \`${t}\`. The old name stops working in 0.4.0.`:null}function Dc(e){let t=Tc(e);if(!t)return null;let n=bc[t],r=t.split(` `)[0]??``,i=n?`Use \`${n}\` instead.`:wc.has(r)?"Run `seo sites` to list your Search Console properties.":r===`providers`?"Run `seo providers --help` for the provider commands.":"Run `seo help` for the commands.";return`\`seo ${t}\` was removed. ${Object.hasOwn(Cc,t)?Cc[t]:`SEO Skill now focuses on Search Console, analytics and keyword data.`} ${i}`}function Oc(e){let t=e.find(e=>[`--project`,`--client`].includes(e.split(`=`)[0]??``));return t?`\`${t.split(`=`)[0]}\` was removed. ${xc} Pass --site with a domain, URL or sc-domain: property, or run \`seo sites\` to list your Search Console properties.`:null}function kc(e){return e.replaceAll(`\\`,`/`).toLowerCase()}function Ac(e,t){return t===`win32`?`${e}.cmd`:e}function jc(e,t=process.platform){let n=kc(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:Ac(`pnpm`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.bun/install/global/`))return{command:Ac(`bun`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.config/yarn/global/`))return{command:Ac(`yarn`,t),args:[`global`,`add`,`seo@latest`]};if(n.includes(`/node_modules/seo/`))return{command:Ac(`npm`,t),args:[`install`,`--global`,`seo@latest`]}}}function Mc(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 Nc(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 Pc(e){if(e)try{return yn(e)}catch{return e}}async function Fc(e){let t=await qn({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 Un(t)?`later`:t}function Ic(e){return Rn(e.command,e.args,{stdio:`inherit`}).status}async function Lc(e,t={}){if(!Nc({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=Pc(t.cliPath??process.argv[1]),r=n?jc(n,t.platform??process.platform):void 0;if(!r)return;let i=(t.createNotifier??(e=>rr({pkg:e,shouldNotifyInNpmScript:!1})))(e).update;if(!(!i||!Mc(i.current,i.latest))&&await(t.prompt??Fc)({command:r,update:i})!==`later`)return(t.run??Ic)(r)===0?(Wn.success(`Updated seo to ${i.latest}. Run your command again.`),0):(Wn.error(`The update failed. Your current version is unchanged.`),1)}function Rc(e){if(!(!process.stderr.isTTY||process.env.CI)&&!(e.includes(`--json`)||e[0]===`mcp`))try{let{configDir:e,configFile:t}=te();if(!g(t))return;let n=_(e,`notices.json`),r=g(n)?JSON.parse(_n(n,`utf8`)):[];if(r.includes(`0.4`))return;process.stderr.write(`
119
+ `),I([`Direction`,`Template`,`Pattern confidence`,`URLs`,`Clicks`,`Returned share`,`Common terms`],e.map(e=>[e.direction,e.signature,e.confidence,e.urlCount,Sc(e.clickDelta),`${Math.round(e.movementShare*100)}%`,e.commonTerms.join(`, `)||`-`])),K(`Template actions`,e.map(e=>e.summary)),K(`Template evidence scope`,[`Shares use returned directional page click movement. Pattern confidence applies only to returned matched-retained page segments.`]))}const Dc=v({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.`},...J([`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.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e),n=R(w(e.site)),r=await lt({site:n,days:E(e.days),recentDays:E(e.recent),limit:E(e.limit),includeBrand:T(e[`include-brand`]),knownConfounders:w(e[`known-change`])?[w(e[`known-change`])??``]:void 0,refresh:T(e.refresh)});if(t){P(r);return}U({title:`Update postmortem`,target:r.site,status:`unknown`,summary:r.summary,metrics:[{label:`Attribution`,value:r.output.update.attribution.replaceAll(`-`,` `)},{label:`Confidence`,value:r.output.update.confidence},{label:`Known confounders`,value:r.output.update.confounders.length}]}),K(`Recommended actions`,r.actions.map(e=>`${e.title} (${e.confidence}): ${e.action}`)),K(`Postmortem findings`,r.output.insights.map(e=>e.summary)),K(`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)),Ec(r.output.templateMovement),K(`Update evidence`,r.output.update.evidence),Tc(r.output.segments),wc(`Page winners and losers`,r.output.segments.page),wc(`Query winners and losers`,r.output.segments.query),wc(`Device winners and losers`,r.output.segments.device),wc(`Country winners and losers`,r.output.segments.country),Ei(`seo export update-postmortem --site ${JSON.stringify(n)}`)}}),Oc=new Set([`database`,`filesystem`,`internal`,`unknown`]);function kc(e){return e.replace(/^v/,``).split(`.`)[0]||`unknown`}function Ac(e){return hn(e[0])?e[0]:void 0}function jc(e,t){return ut(e)?`seo ${e}`:t?`seo ${t}`:`seo command`}function Mc(e){let t=on(e.error);if(!Oc.has(t.errorCategory))return;let n=Ac(e.args),r=jc(e.report,n),i=[he(e.error).code,t.errorCategory,t.failureReason,t.failureContext].filter(Boolean).join(` | `),a=new URL(`https://github.com/iannuttall/seo/issues/new`);return a.searchParams.set(`template`,`bug.yml`),a.searchParams.set(`title`,`bug: ${r} failed`),a.searchParams.set(`version`,e.version??zt),a.searchParams.set(`runtime`,`Node ${kc(e.nodeVersion??process.version)} on ${e.processPlatform??Cn()} (${e.processArch??xn()})`),a.searchParams.set(`diagnostics`,i),a.toString()}const Nc={"refresh-priorities":`seo report`,"query-cluster":`seo report`,"quick-wins":`seo report --section quick-wins`,"ctr-underperformers":`seo report --section low-ctr`,"striking-distance":`seo report --section striking-distance`,"second-page":`seo report --section second-page`,decaying:`seo report --section content-decay`,cannibal:`seo report --section cannibalization`,"traffic-anomaly":`seo report --section traffic-drop`,"page-opportunities":`seo page --url <url>`,"audit-page":`seo page --url <url>`,"url-inspect":`seo page --url <url>`,"segment-impact":`seo compare --date <date>`,"update-correlate":`seo compare --date <date>`,"update-postmortem":`seo compare --date <date>`,"link-recover":`seo index`,"gsc-query":`seo data`},Pc={"agent-readiness":null,"ai-readiness":null,"community-intent":null,"entity-readiness":null,llms:null,"monthly-report":`seo report`,okf:null,pseo:null,"report-narrative":`seo report`,"seo-to-ai-query":null,"server-logs":null,links:`seo research backlinks --target <domain>`,"export knowledge":null,"export monthly":`seo report --json`,"export narrative":`seo report --json`,"export pseo":null,indexnow:null,"providers semrush":`seo providers`,"providers limits":null,"providers spend":null,"providers dataforseo limits":null,"providers dataforseo spend":null,"providers ahrefs limits":null,"change-log":null,client:null,project:null,projects:null,"content-groups":null,"crawl-diff":`seo crawl`,"crawl-reports":`seo crawl`,diagnose:`seo report`,"diagnose-property":`seo report`,"export diagnose":`seo report --json`,"index-watch":`seo page --url <url>`,monitoring:`seo crawl`,schedule:null,"technical-watch":`seo crawl`,tests:`seo compare --date <date>`},Z=`It saved history between runs. Your agent keeps its own notes now.`,Fc=`Commands take --site now instead of a saved project.`,Ic=`Spend is controlled in your provider account. Set limits in DataForSEO, Ahrefs or the other provider.`,Lc={"providers limits":Ic,"providers spend":Ic,"providers dataforseo limits":Ic,"providers dataforseo spend":Ic,"providers ahrefs limits":Ic,"change-log":Z,client:Fc,project:Fc,projects:Fc,"content-groups":Z,"crawl-diff":Z,"crawl-reports":Z,diagnose:Z,"diagnose-property":Z,"export diagnose":Z,"index-watch":Z,monitoring:Z,schedule:Z,"technical-watch":Z,tests:Z},Rc=new Set([`client`,`project`,`projects`]);function zc(e){let t=e.findIndex(e=>e.startsWith(`-`)),n=t===-1?e:e.slice(0,t),r=+(n[0]===`help`);for(let e=3;e>=1;--e){let t=n.slice(r,r+e).join(` `);if(n.length-r>=e&&Object.hasOwn(Pc,t))return t}return null}function Bc(e){let t=Object.hasOwn(Nc,e)?Nc[e]:void 0;return t?`\`seo ${e}\` is now \`${t}\`. The old name stops working in 0.4.0.`:null}function Vc(e){let t=zc(e);if(!t)return null;let n=Pc[t],r=t.split(` `)[0]??``,i=n?`Use \`${n}\` instead.`:Rc.has(r)?"Run `seo sites` to list your Search Console properties.":r===`providers`?"Run `seo providers --help` for the provider commands.":"Run `seo help` for the commands.";return`\`seo ${t}\` was removed. ${Object.hasOwn(Lc,t)?Lc[t]:`SEO Skill now focuses on Search Console, analytics and keyword data.`} ${i}`}function Hc(e){let t=e.find(e=>[`--project`,`--client`].includes(e.split(`=`)[0]??``));return t?`\`${t.split(`=`)[0]}\` was removed. ${Fc} Pass --site with a domain, URL or sc-domain: property, or run \`seo sites\` to list your Search Console properties.`:null}function Uc(e){return e.replaceAll(`\\`,`/`).toLowerCase()}function Wc(e,t){return t===`win32`?`${e}.cmd`:e}function Gc(e,t=process.platform){let n=Uc(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:Wc(`pnpm`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.bun/install/global/`))return{command:Wc(`bun`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.config/yarn/global/`))return{command:Wc(`yarn`,t),args:[`global`,`add`,`seo@latest`]};if(n.includes(`/node_modules/seo/`))return{command:Wc(`npm`,t),args:[`install`,`--global`,`seo@latest`]}}}function Kc(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 qc(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 Jc(e){if(e)try{return Fn(e)}catch{return e}}async function Yc(e){let t=await er({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 Zn(t)?`later`:t}function Xc(e){return Kn(e.command,e.args,{stdio:`inherit`}).status}async function Zc(e,t={}){if(!qc({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=Jc(t.cliPath??process.argv[1]),r=n?Gc(n,t.platform??process.platform):void 0;if(!r)return;let i=(t.createNotifier??(e=>ur({pkg:e,shouldNotifyInNpmScript:!1})))(e).update;if(!(!i||!Kc(i.current,i.latest))&&await(t.prompt??Yc)({command:r,update:i})!==`later`)return(t.run??Xc)(r)===0?(Qn.success(`Updated seo to ${i.latest}. Run your command again.`),0):(Qn.error(`The update failed. Your current version is unchanged.`),1)}function Qc(e){if(!(!process.stderr.isTTY||process.env.CI)&&!(e.includes(`--json`)||e[0]===`mcp`))try{let{configDir:e,configFile:t}=r();if(!_(t))return;let n=g(e,`notices.json`),i=_(n)?JSON.parse(Nn(n,`utf8`)):[];if(i.includes(`0.4`))return;process.stderr.write(`
118
120
  SEO Skill 0.4: eight commands replace the old reports, and projects are gone: every command takes --site (run \`seo sites\` to list yours). Old command names print what to use instead.
119
121
  Free hosted MCP server, nothing to install: https://seoskill.dev/docs/mcp
120
122
  To stay on the old version: npm i -g seo@0.2.41
121
123
  What changed: https://github.com/iannuttall/seo/blob/main/CHANGELOG.md
122
124
 
123
- `),Sn(n,JSON.stringify([...r,`0.4`]),{mode:384})}catch{}}const zc={name:`seo`,version:Ft},Bc=[{title:`Start here`,commands:[[`seo start`,`Sign in with Google, then add the MCP server and skill`],[`seo report`,`The main report: overview and every section`],[`seo report --section quick-wins`,`One section of the report, with live page checks`]]},{title:`Commands`,commands:[[`seo page --url <url>`,`One page: live facts, index status, queries`],[`seo compare --date <date>`,`Before and after a date`],[`seo index`,`Pages that lost most of their clicks`],[`seo research <action>`,`Keyword, SERP, competitor and backlink data from your key`],[`seo data`,`Raw Search Console or Bing rows`],[`seo crawl`,`Crawl a site and list technical issues`],[`seo internal-links`,`Pages that could link to a target page`]]},{title:`Setup`,commands:[[`seo sites`,`List Search Console properties`],[`seo mcp install`,`Add the local MCP server to your agents`],[`seo providers`,`Connect DataForSEO or Ahrefs`],[`seo doctor`,`Check local auth and config`]]}],Vc=[...Bc,{title:`More commands`,commands:[[`seo crawl-queue`,`Run a crawl and rank the fix queue`],[`seo rules`,`List crawler rule ids`],[`seo explain --rule missing_title`,`Explain a crawler rule`],[`seo redirect-trace`,`Trace redirects`],[`seo perf audit`,`Run a page performance audit`],[`seo index-coverage`,`Choose pages for URL Inspection`],[`seo ai-referrals`,`AI referral traffic in Google Analytics`],[`seo analytics google report`,`Run a Google Analytics report`],[`seo updates`,`List official Google ranking updates`],[`seo export`,`Export report data to CSV`],[`seo reports list`,`List every structured report`],[`seo skill list`,`Show the packaged SEO skill`],[`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 saved credentials and all local data`]]}];function Hc(e){Zr(`seo v${zc.version}`,`Your own Search Console, Google Analytics and Bing data, as facts for your agent.`),process.stdout.write(`
124
- `),ei(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(`
125
- `),ni(`More help`,"Use `seo help <command>` or `seo <command> --help` for command help.","Use `seo help all` for the longer command list.")}const Uc=v({meta:{name:`seo`,version:zc.version,description:`Local-first SEO CLI and MCP server`},subCommands:{init:xo,analytics:yi,auth:Ei,mcp:To,doctor:Uo,privacy:Gs,telemetry:$s,reset:Ks,cache:ki,logs:So,crawl:aa,"crawl-queue":nc,content:Ai,providers:os,export:Oa,"index-coverage":Eo,"link-recover":Do,rules:ps,explain:ms,"refresh-priorities":sc,"redirect-trace":Oo,skill:Ws,start:bo,setup:yo,report:zi,page:Bi,compare:Vi,index:Hi,data:Ui,research:Wi,reports:fs,"segment-impact":Go,"striking-distance":qo,"update-postmortem":pc,sites:qs,"gsc-query":ma,"url-inspect":ha,updates:Js,"traffic-anomaly":ya,"update-correlate":ba,"ai-referrals":ko,"audit-page":zo,"second-page":Ro,cannibal:Ao,decaying:No,"quick-wins":Lo,"page-opportunities":Fo,perf:Ho,"internal-links":Po,"ctr-underperformers":jo,"query-cluster":Io},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")}}),Wc={cannibal:`cannibalisation`,crawl:`site-crawl`,"crawl-queue":`top-fixes`,decaying:`decaying-pages`,doctor:`setup-check`,explain:`explain-crawl-issue`,"link-recover":`link-recovery`,"query-cluster":`query-clusters`,report:`search-performance-overview`,rules:`crawler-rules`,"update-correlate":`update-correlation`},Gc=new Set([`ai-referrals`,`audit-page`,`ctr-underperformers`,`index-coverage`,`internal-links`,`page-opportunities`,`quick-wins`,`redirect-trace`,`refresh-priorities`,`second-page`,`segment-impact`,`striking-distance`,`traffic-anomaly`,`update-postmortem`]),Kc=new Set(Pt().map(e=>e.id));function qc(e,t){let n=e.indexOf(t);return n>=0?e[n+1]:e.find(e=>e.startsWith(`${t}=`))?.slice(t.length+1)}function Jc(e){let[t,n,r]=e;if(t)return t in Ot?ze(t,{section:qc(e,`--section`),action:n})??void 0:t===`reports`&&n===`run`?r&&Kc.has(r)?r:void 0:t===`content`&&n===`optimize`?`content-optimization`:t===`perf`&&n===`audit`?`performance-audit`:Wc[t]??(Gc.has(t)?t:void 0)}const Q=process.argv.slice(2);Rc(Q);const Yc=Dc(Q)??Oc(Q);Yc&&(process.stderr.write(`${Yc}\n`),process.exit(2));const Xc=Ec(Q[0]??``);Xc&&!Q.some(e=>[`--help`,`-h`].includes(e))&&process.stderr.write(`${Xc}\n`);const Zc={agent:et()},Qc=Q[0]===`telemetry`,$c=Q[0]===`mcp`&&Q[1]===`serve`;!Qc&&!$c&&Yt(Zc);const el=await Lc(zc,{argv:Q});el!==void 0&&process.exit(el),(Q.length===0||Q.length===1&&[`help`,`--help`,`-h`].includes(Q[0]??``))&&(Hc(Bc),process.exit(0)),Q[0]===`help`&&Q[1]===`all`&&(Hc(Vc),process.exit(0));const $=Q[0]===`help`&&Q.length>1?[...Q.slice(1),`--help`]:Q;$!==Q&&(process.argv=[process.argv[0]??`node`,process.argv[1]??`seo`,...$]);const tl=$.some(e=>[`--help`,`-h`].includes(e)),nl=Q.length===1&&[`--version`,`-v`].includes(Q[0]??``),rl=tl||nl?void 0:Jc($);if(tl||nl)await Bn(Uc);else{rl&&dt(rl,Zc);try{await zn(Uc,{rawArgs:$}),rl&&kt(rl,Zc),[`init`,`setup`,`start`].includes($[0]??``)&&!$.includes(`--dry-run`)&&Ge(Zc)}catch(e){if(rl)mt(rl,e,Zc);else if(!Qc){let t=gc($);t&&Lt(t,e,Zc)}let t=wt(e);if(Q.includes(`--json`))process.stdout.write(`${JSON.stringify(ye(t),null,2)}\n`);else{process.stderr.write(`Error: ${t.message}\n`);let n=vc({args:$,error:e,report:rl});n&&process.stderr.write(`Report this bug: ${n}\n`)}process.exitCode=t.exitCode}}export{};
125
+ `),Rn(n,JSON.stringify([...i,`0.4`]),{mode:384})}catch{}}const $c={name:`seo`,version:zt},el=[{title:`Start here`,commands:[[`seo start`,`Sign in with Google, then add the MCP server and skill`],[`seo report`,`The main report: overview and every section`],[`seo report --section quick-wins`,`One section of the report, with live page checks`]]},{title:`Commands`,commands:[[`seo page --url <url>`,`One page: live facts, index status, queries`],[`seo compare --date <date>`,`Before and after a date`],[`seo index`,`Pages that lost most of their clicks`],[`seo research <action>`,`Keyword, SERP, competitor and backlink data from your key`],[`seo data`,`Raw Search Console or Bing rows`],[`seo crawl`,`Crawl a site and list technical issues`],[`seo internal-links`,`Pages that could link to a target page`]]},{title:`Setup`,commands:[[`seo login`,`Use your seoskill.dev account on this machine`],[`seo sites`,`List Search Console properties`],[`seo mcp install`,`Add the local MCP server to your agents`],[`seo providers`,`Connect DataForSEO or Ahrefs`],[`seo doctor`,`Check local auth and config`]]}],tl=[...el,{title:`More commands`,commands:[[`seo crawl-queue`,`Run a crawl and rank the fix queue`],[`seo rules`,`List crawler rule ids`],[`seo explain --rule missing_title`,`Explain a crawler rule`],[`seo redirect-trace`,`Trace redirects`],[`seo perf audit`,`Run a page performance audit`],[`seo index-coverage`,`Choose pages for URL Inspection`],[`seo ai-referrals`,`AI referral traffic in Google Analytics`],[`seo analytics google report`,`Run a Google Analytics report`],[`seo updates`,`List official Google ranking updates`],[`seo export`,`Export report data to CSV`],[`seo reports list`,`List every structured report`],[`seo skill list`,`Show the packaged SEO skill`],[`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 saved credentials and all local data`]]}];function nl(e){ai(`seo v${$c.version}`,`Your own Search Console, Google Analytics and Bing data, as facts for your agent.`),process.stdout.write(`
126
+ `),ci(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(`
127
+ `),ui(`More help`,"Use `seo help <command>` or `seo <command> --help` for command help.","Use `seo help all` for the longer command list.")}const rl=v({meta:{name:`seo`,version:$c.version,description:`Local-first SEO CLI and MCP server`},subCommands:{init:ko,analytics:Di,auth:Pi,mcp:zo,doctor:rs,privacy:ac,telemetry:pc,reset:oc,cache:Li,logs:Io,crawl:pa,"crawl-queue":gc,content:Ri,providers:bs,export:Ia,"index-coverage":Bo,"link-recover":Vo,rules:Ds,explain:Os,"refresh-priorities":xc,"redirect-trace":Ho,skill:ic,start:Oo,setup:Do,login:No,logout:Fo,report:qi,page:Ji,compare:Yi,index:Xi,data:Zi,research:Qi,reports:Es,"segment-impact":as,"striking-distance":ss,"update-postmortem":Dc,sites:sc,"gsc-query":Sa,"url-inspect":Ca,updates:cc,"traffic-anomaly":Da,"update-correlate":Oa,"ai-referrals":Uo,"audit-page":$o,"second-page":Qo,cannibal:Wo,decaying:qo,"quick-wins":Zo,"page-opportunities":Yo,perf:ns,"internal-links":Jo,"ctr-underperformers":Go,"query-cluster":Xo},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")}}),il={cannibal:`cannibalisation`,crawl:`site-crawl`,"crawl-queue":`top-fixes`,decaying:`decaying-pages`,doctor:`setup-check`,explain:`explain-crawl-issue`,"link-recover":`link-recovery`,"query-cluster":`query-clusters`,report:`search-performance-overview`,rules:`crawler-rules`,"update-correlate":`update-correlation`},al=new Set([`ai-referrals`,`audit-page`,`ctr-underperformers`,`index-coverage`,`internal-links`,`page-opportunities`,`quick-wins`,`redirect-trace`,`refresh-priorities`,`second-page`,`segment-impact`,`striking-distance`,`traffic-anomaly`,`update-postmortem`]),ol=new Set(Vt().map(e=>e.id));function sl(e,t){let n=e.indexOf(t);return n>=0?e[n+1]:e.find(e=>e.startsWith(`${t}=`))?.slice(t.length+1)}function cl(e){let[t,n,r]=e;if(t)return t in ve?Ke(t,{section:sl(e,`--section`),action:n})??void 0:t===`reports`&&n===`run`?r&&ol.has(r)?r:void 0:t===`content`&&n===`optimize`?`content-optimization`:t===`perf`&&n===`audit`?`performance-audit`:il[t]??(al.has(t)?t:void 0)}const Q=process.argv.slice(2);Qc(Q);const ll=Vc(Q)??Hc(Q);ll&&(process.stderr.write(`${ll}\n`),process.exit(2));const ul=Bc(Q[0]??``);ul&&!Q.some(e=>[`--help`,`-h`].includes(e))&&process.stderr.write(`${ul}\n`);const dl={agent:st()},fl=Q[0]===`telemetry`,pl=Q[0]===`mcp`&&Q[1]===`serve`;!fl&&!pl&&nn(dl);const ml=await Zc($c,{argv:Q});ml!==void 0&&process.exit(ml),(Q.length===0||Q.length===1&&[`help`,`--help`,`-h`].includes(Q[0]??``))&&(nl(el),process.exit(0)),Q[0]===`help`&&Q[1]===`all`&&(nl(tl),process.exit(0));const $=Q[0]===`help`&&Q.length>1?[...Q.slice(1),`--help`]:Q;$!==Q&&(process.argv=[process.argv[0]??`node`,process.argv[1]??`seo`,...$]);const hl=$.some(e=>[`--help`,`-h`].includes(e)),gl=Q.length===1&&[`--version`,`-v`].includes(Q[0]??``),_l=hl||gl?void 0:cl($);if(hl||gl)await Jn(rl);else{_l&&vt(_l,dl);try{await qn(rl,{rawArgs:$}),_l&&It(_l,dl),[`init`,`setup`,`start`].includes($[0]??``)&&!$.includes(`--dry-run`)&&Qe(dl)}catch(e){if(_l)xt(_l,e,dl);else if(!fl){let t=Ac($);t&&Wt(t,e,dl)}let t=he(e);if(Q.includes(`--json`))process.stdout.write(`${JSON.stringify(ce(t),null,2)}\n`);else{process.stderr.write(`Error: ${t.message}\n`);let n=Mc({args:$,error:e,report:_l});n&&process.stderr.write(`Report this bug: ${n}\n`)}process.exitCode=t.exitCode}}export{};
126
128
  //# sourceMappingURL=cli.js.map