seo 0.0.15 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/LICENSE +201 -0
  2. package/PRIVACY.md +95 -0
  3. package/README.md +338 -35
  4. package/SECURITY.md +55 -0
  5. package/TERMS.md +94 -0
  6. package/TRADEMARKS.md +27 -0
  7. package/dist/cli.js +125 -0
  8. package/dist/cli.js.map +1 -0
  9. package/dist/dist-CSY2_p-j.js +713 -0
  10. package/dist/dist-CSY2_p-j.js.map +1 -0
  11. package/dist/dist-FeAUNn9A.js +3 -0
  12. package/dist/index.d.ts +17921 -0
  13. package/dist/index.js +26769 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/mcp.d.ts +57 -0
  16. package/dist/mcp.js +26744 -0
  17. package/dist/mcp.js.map +1 -0
  18. package/dist/package-uzXzqDW6.js +23818 -0
  19. package/dist/package-uzXzqDW6.js.map +1 -0
  20. package/package.json +101 -23
  21. package/skills/README.md +81 -0
  22. package/skills/affected-urls/SKILL.md +39 -0
  23. package/skills/affected-urls/agents/openai.yaml +4 -0
  24. package/skills/ai-readiness/SKILL.md +34 -0
  25. package/skills/ai-readiness/agents/openai.yaml +4 -0
  26. package/skills/ai-referrals/SKILL.md +31 -0
  27. package/skills/ai-referrals/agents/openai.yaml +4 -0
  28. package/skills/audit-page/SKILL.md +50 -0
  29. package/skills/audit-page/agents/openai.yaml +4 -0
  30. package/skills/audit-urls/SKILL.md +39 -0
  31. package/skills/audit-urls/agents/openai.yaml +4 -0
  32. package/skills/cannibalisation/SKILL.md +31 -0
  33. package/skills/cannibalisation/agents/openai.yaml +4 -0
  34. package/skills/community-intent/SKILL.md +39 -0
  35. package/skills/community-intent/agents/openai.yaml +4 -0
  36. package/skills/compare-crawls/SKILL.md +40 -0
  37. package/skills/compare-crawls/agents/openai.yaml +4 -0
  38. package/skills/content-optimization/SKILL.md +31 -0
  39. package/skills/content-optimization/agents/openai.yaml +4 -0
  40. package/skills/crawl-diff/SKILL.md +51 -0
  41. package/skills/crawl-diff/agents/openai.yaml +4 -0
  42. package/skills/crawl-history/SKILL.md +37 -0
  43. package/skills/crawl-history/agents/openai.yaml +4 -0
  44. package/skills/crawl-report/SKILL.md +37 -0
  45. package/skills/crawl-report/agents/openai.yaml +4 -0
  46. package/skills/crawler-rules/SKILL.md +34 -0
  47. package/skills/crawler-rules/agents/openai.yaml +4 -0
  48. package/skills/ctr-underperformers/SKILL.md +31 -0
  49. package/skills/ctr-underperformers/agents/openai.yaml +4 -0
  50. package/skills/decaying-pages/SKILL.md +31 -0
  51. package/skills/decaying-pages/agents/openai.yaml +4 -0
  52. package/skills/entity-readiness/SKILL.md +34 -0
  53. package/skills/entity-readiness/agents/openai.yaml +4 -0
  54. package/skills/explain-crawl-issue/SKILL.md +32 -0
  55. package/skills/explain-crawl-issue/agents/openai.yaml +4 -0
  56. package/skills/generate-llms-txt/SKILL.md +37 -0
  57. package/skills/generate-llms-txt/agents/openai.yaml +4 -0
  58. package/skills/geo-gaps/SKILL.md +37 -0
  59. package/skills/geo-gaps/agents/openai.yaml +4 -0
  60. package/skills/index-coverage/SKILL.md +84 -0
  61. package/skills/index-coverage/agents/openai.yaml +4 -0
  62. package/skills/index-coverage-plan/SKILL.md +50 -0
  63. package/skills/index-coverage-plan/agents/openai.yaml +4 -0
  64. package/skills/index-monitor/SKILL.md +49 -0
  65. package/skills/index-monitor/agents/openai.yaml +4 -0
  66. package/skills/index-watch/SKILL.md +77 -0
  67. package/skills/index-watch/agents/openai.yaml +4 -0
  68. package/skills/internal-links/SKILL.md +31 -0
  69. package/skills/internal-links/agents/openai.yaml +4 -0
  70. package/skills/link-recovery/SKILL.md +51 -0
  71. package/skills/link-recovery/agents/openai.yaml +4 -0
  72. package/skills/llms-txt-audit/SKILL.md +34 -0
  73. package/skills/llms-txt-audit/agents/openai.yaml +4 -0
  74. package/skills/measure-change/SKILL.md +52 -0
  75. package/skills/measure-change/agents/openai.yaml +4 -0
  76. package/skills/monthly-action-plan/SKILL.md +50 -0
  77. package/skills/monthly-action-plan/agents/openai.yaml +4 -0
  78. package/skills/monthly-report/SKILL.md +50 -0
  79. package/skills/monthly-report/agents/openai.yaml +4 -0
  80. package/skills/narrative-report/SKILL.md +51 -0
  81. package/skills/narrative-report/agents/openai.yaml +4 -0
  82. package/skills/okf-build/SKILL.md +39 -0
  83. package/skills/okf-build/agents/openai.yaml +4 -0
  84. package/skills/okf-validate/SKILL.md +43 -0
  85. package/skills/okf-validate/agents/openai.yaml +4 -0
  86. package/skills/page-opportunities/SKILL.md +31 -0
  87. package/skills/page-opportunities/agents/openai.yaml +4 -0
  88. package/skills/performance/SKILL.md +50 -0
  89. package/skills/performance/agents/openai.yaml +4 -0
  90. package/skills/performance-audit/SKILL.md +31 -0
  91. package/skills/performance-audit/agents/openai.yaml +4 -0
  92. package/skills/pseo-audit/SKILL.md +103 -0
  93. package/skills/pseo-audit/agents/openai.yaml +4 -0
  94. package/skills/query-clusters/SKILL.md +31 -0
  95. package/skills/query-clusters/agents/openai.yaml +4 -0
  96. package/skills/quick-wins/SKILL.md +31 -0
  97. package/skills/quick-wins/agents/openai.yaml +4 -0
  98. package/skills/redirect-trace/SKILL.md +51 -0
  99. package/skills/redirect-trace/agents/openai.yaml +4 -0
  100. package/skills/refresh-priorities/SKILL.md +48 -0
  101. package/skills/refresh-priorities/agents/openai.yaml +4 -0
  102. package/skills/search-performance-overview/SKILL.md +48 -0
  103. package/skills/search-performance-overview/agents/openai.yaml +4 -0
  104. package/skills/second-page/SKILL.md +50 -0
  105. package/skills/second-page/agents/openai.yaml +4 -0
  106. package/skills/segment-impact/SKILL.md +50 -0
  107. package/skills/segment-impact/agents/openai.yaml +4 -0
  108. package/skills/seo/SKILL.md +74 -0
  109. package/skills/seo/agents/openai.yaml +4 -0
  110. package/skills/seo-fix-queue/SKILL.md +50 -0
  111. package/skills/seo-fix-queue/agents/openai.yaml +4 -0
  112. package/skills/seo-geo-readiness/SKILL.md +60 -0
  113. package/skills/seo-geo-readiness/agents/openai.yaml +4 -0
  114. package/skills/seo-site-audit/SKILL.md +59 -0
  115. package/skills/seo-site-audit/agents/openai.yaml +4 -0
  116. package/skills/seo-to-ai-query/SKILL.md +31 -0
  117. package/skills/seo-to-ai-query/agents/openai.yaml +4 -0
  118. package/skills/setup-check/SKILL.md +49 -0
  119. package/skills/setup-check/agents/openai.yaml +4 -0
  120. package/skills/site-crawl/SKILL.md +39 -0
  121. package/skills/site-crawl/agents/openai.yaml +4 -0
  122. package/skills/striking-distance/SKILL.md +52 -0
  123. package/skills/striking-distance/agents/openai.yaml +4 -0
  124. package/skills/technical-watch/SKILL.md +49 -0
  125. package/skills/technical-watch/agents/openai.yaml +4 -0
  126. package/skills/top-fixes/SKILL.md +38 -0
  127. package/skills/top-fixes/agents/openai.yaml +4 -0
  128. package/skills/traffic-anomaly/SKILL.md +52 -0
  129. package/skills/traffic-anomaly/agents/openai.yaml +4 -0
  130. package/skills/update-correlation/SKILL.md +51 -0
  131. package/skills/update-correlation/agents/openai.yaml +4 -0
  132. package/skills/update-postmortem/SKILL.md +49 -0
  133. package/skills/update-postmortem/agents/openai.yaml +4 -0
  134. package/.jshintrc +0 -18
  135. package/.npmignore +0 -3
  136. package/.travis.yml +0 -3
  137. package/Makefile +0 -10
  138. package/index.js +0 -2
  139. package/lib/middleware.js +0 -159
  140. package/lib/seo.js +0 -32
  141. package/test/init.js +0 -43
  142. package/test/middleware.test.js +0 -111
  143. package/test/seo-page-result.html +0 -9
  144. package/test/seo-page.html +0 -9
  145. package/test/seo-routes.js +0 -5
  146. package/test/vendor/jquery-1.11.1.min.js +0 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.js","names":["errorMessage","GOOGLE_TOKEN_ENDPOINT","authedFetch","fetch","compareText","dateValue","DEFAULT_MAX_ROWS","validIsoDate","headerValue","normalizedUrl","DefuddleConstructor","isRecord","record","absoluteHttpUrl","safeText","headerValue","absoluteUrl","fetch","percentile","parseRobots","headerValue","fetch","normalizedUrl","absoluteUrl","defaultDependencies","unique","normalizeText","defaultDateRange","normalizeText","integerOption","subtractCalendarMonths","integerOption","compareText","validRow","reportStatus","STOPWORDS","queryTerms","countPhrase","coverageSummary","benchmarkDetails","DEFAULT_MIN_IMPRESSIONS","DEFAULT_LIMIT","MAX_LIMIT","integerInRange","isHttpUrl","selectBenchmarkRows","compareText","compareItems","benchmarkDetails","selectBenchmarkRows","plural","defaultDependencies","errorMessage","unique","reportDays","reportCaveats","defaultDateRange","pct","compareText","truncate","normalizeUrl","defaultDependencies","compareText","normalizeUrl","unique","pct","matchesPattern","compareText","compareText","boundedInteger","normalizedQuery","normalizedHttpUrl","validMetrics","MAX_GSC_ROWS","plural","defaultDependencies","integerOption","defaultDateRange","plural","fixed","compareText","validMetric","verdict","DAY_MS","subtractDays","integerOption","rangeDays","subtractCalendarMonths","defaultDependencies","integerOption","parseUrl","boundedInteger","MAX_GSC_ROWS","defaultDependencies","verdict","integerOption","validRow","MAX_GSC_ROWS","defaultDependencies","verdict","integerOption","groupKey","compareText","boundedInteger","validRow","benchmarkDetails","compareText","DEFAULT_MIN_IMPRESSIONS","MAX_MIN_IMPRESSIONS","DEFAULT_LIMIT","MAX_LIMIT","boundedInteger","compareText","unique","DEFAULT_DAYS","MAX_DAYS","DEFAULT_VERIFY_LIMIT","MAX_SOURCE_ROWS","defaultDependencies","unique","applyVerification","integerOption","compareText","DEFAULT_MIN_IMPRESSIONS","MAX_MIN_IMPRESSIONS","DEFAULT_LIMIT","MAX_LIMIT","integerInRange","MAX_SOURCE_ROWS","defaultDependencies","boundedInteger","verdict","fetch","formatPercent","plural","calendarDays","defaultDateRange","defaultDateRange","defaultDependencies","defaultDependencies","MAX_GSC_ROWS","defaultDependencies","compareText","compareText","boundedInteger","validMetric","defaultDependencies","integerOption","integerOption","defaultDependencies","integerOption","integerOption","defaultDateRange","fetch","reportId","isRecord","defaultDependencies","integerOption","plural","defaultDateRange","compareText","normalizeText","normalizeText","defaultDateRange","compareText","fetch","fetch","packageJson.version","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z"],"sources":["../packages/core/dist/errors.js","../packages/core/dist/paths.js","../packages/core/dist/types/auth.js","../packages/core/dist/types/config.js","../packages/core/dist/storage/files.js","../packages/core/dist/storage/keyring.js","../packages/core/dist/storage/config.js","../packages/core/dist/storage/lock.js","../packages/core/dist/gsc/shared-client.generated.js","../packages/core/dist/gsc/auth/client-config.js","../packages/core/dist/gsc/auth/types.js","../packages/core/dist/gsc/auth/service-account.js","../packages/core/dist/gsc/auth/token-endpoint.js","../packages/core/dist/gsc/auth/authorized-client.js","../packages/core/dist/storage/database.js","../packages/core/dist/ga4/client.js","../packages/core/dist/analyze/ai-referrals-sources.js","../packages/core/dist/analyze/ai-referrals-analysis.js","../packages/core/dist/analyze/ai-referrals-query.js","../packages/core/dist/analyze/ai-referrals.js","../packages/core/dist/robots-directives.js","../packages/core/dist/extract/canonical.js","../packages/core/dist/extract/main-content.js","../packages/core/dist/extract/google-rich-results.js","../packages/core/dist/extract/structured-data.js","../packages/core/dist/extract/page-extractor.js","../packages/core/dist/fetch/http-client.js","../packages/core/dist/fetch/page-fetcher/rate-controls.js","../packages/core/dist/fetch/page-fetcher/robots.js","../packages/core/dist/fetch/page-fetcher/plain.js","../packages/core/dist/fetch/page-fetcher/browser-path.js","../packages/core/dist/fetch/page-fetcher/rendered.js","../packages/core/dist/fetch/page-fetcher/rendering-difference.js","../packages/core/dist/fetch/page-fetcher.js","../packages/core/dist/gsc/property-url.js","../packages/core/dist/gsc/client/fetch.js","../packages/core/dist/gsc/client/inspection-quota.js","../packages/core/dist/gsc/client/inspection.js","../packages/core/dist/gsc/dates.js","../packages/core/dist/gsc/client/search-analytics.js","../packages/core/dist/gsc/client/sites.js","../packages/core/dist/analyze/page-technical-signals.js","../packages/core/dist/analyze/title-width.js","../packages/core/dist/analyze/audit-page.js","../packages/core/dist/brand.js","../packages/core/dist/analyze/shared.js","../packages/core/dist/analyze/community-intent-classifier.js","../packages/core/dist/analyze/site-diagnostics/quick-wins-report-input.js","../packages/core/dist/analyze/query-opportunity-input.js","../packages/core/dist/analyze/query-opportunity-rows.js","../packages/core/dist/analyze/query-opportunity-source.js","../packages/core/dist/analyze/community-intent.js","../packages/core/dist/analyze/content-coverage.js","../packages/core/dist/analyze/opportunity-primitives.js","../packages/core/dist/analyze/page-opportunities-evidence.js","../packages/core/dist/analyze/query-quality.js","../packages/core/dist/analyze/page-opportunities-selection.js","../packages/core/dist/analyze/page-opportunities-analysis.js","../packages/core/dist/analyze/page-opportunities-presentation.js","../packages/core/dist/analyze/page-opportunities.js","../packages/core/dist/analyze/content-optimization.js","../packages/core/dist/analyze/crawler/affected-urls.js","../packages/core/dist/analyze/crawler/ai-readiness.js","../packages/core/dist/rules.js","../packages/core/dist/analyze/crawler/page-eligibility.js","../packages/core/dist/analyze/crawler/audit.js","../packages/core/dist/analyze/crawler/report.js","../packages/core/dist/analyze/crawler/report-store.js","../packages/core/dist/analyze/crawler/crawl-caveats.js","../packages/core/dist/analyze/crawler/crawl-control.js","../packages/core/dist/analyze/crawler/external-link-checks.js","../packages/core/dist/analyze/crawler/link-graph.js","../packages/core/dist/analyze/crawler/request-evidence.js","../packages/core/dist/analyze/crawler/site-crawl-providers.js","../packages/core/dist/analyze/crawler/site-crawl-data-sources.js","../packages/core/dist/analyze/monitoring/crawl-page.js","../packages/core/dist/analyze/monitoring/sitemaps.js","../packages/core/dist/analyze/workflows/analytics-value.js","../packages/core/dist/analyze/crawler/site-crawl-dependencies.js","../packages/core/dist/analyze/crawler/sitemap-discovery.js","../packages/core/dist/analyze/crawler/site-crawl.js","../packages/core/dist/analyze/crawler/entity-readiness.js","../packages/core/dist/analyze/crawler/top-fixes.js","../packages/core/dist/analyze/crawler/geo-gaps.js","../packages/core/dist/analyze/crawler/history-provenance.js","../packages/core/dist/analyze/crawler/history.js","../packages/core/dist/analyze/crawler/llms.js","../packages/core/dist/analyze/crawler/okf.js","../packages/core/dist/analyze/crawler/schemas.js","../packages/core/dist/analyze/ctr-underperformers-analysis.js","../packages/core/dist/analyze/ctr-underperformers.js","../packages/core/dist/phrasing.js","../packages/core/dist/analyze/diagnosis-priorities.js","../packages/core/dist/analyze/diagnosis-status.js","../packages/core/dist/analyze/segment-impact-rows.js","../packages/core/dist/analyze/segment-impact-analysis.js","../packages/core/dist/analyze/segment-impact-input.js","../packages/core/dist/analyze/site-diagnostics/decay-report-input.js","../packages/core/dist/analyze/segment-impact-fallback.js","../packages/core/dist/analyze/segment-impact.js","../packages/core/dist/storage/ledger.js","../packages/core/dist/analyze/page-patterns.js","../packages/core/dist/analyze/site-diagnostics/cannibal-analysis-primitives.js","../packages/core/dist/analyze/site-diagnostics/cannibal-item.js","../packages/core/dist/analyze/site-diagnostics/cannibal-analysis.js","../packages/core/dist/analyze/site-diagnostics/cannibal.js","../packages/core/dist/analyze/site-diagnostics/decay-analysis-primitives.js","../packages/core/dist/analyze/site-diagnostics/decay-analysis.js","../packages/core/dist/analyze/site-diagnostics/decaying.js","../packages/core/dist/analyze/site-diagnostics/quick-win-groups.js","../packages/core/dist/analyze/site-diagnostics/quick-wins-analysis-primitives.js","../packages/core/dist/analyze/site-diagnostics/quick-wins-analysis.js","../packages/core/dist/analyze/site-diagnostics/quick-wins-templates.js","../packages/core/dist/analyze/site-diagnostics/quick-wins.js","../packages/core/dist/analyze/striking-distance-analysis-primitives.js","../packages/core/dist/analyze/striking-distance-analysis.js","../packages/core/dist/analyze/striking-distance.js","../packages/core/dist/updates/search-status.js","../packages/core/dist/analyze/experiments/mappers.js","../packages/core/dist/analyze/experiments/change-log.js","../packages/core/dist/analyze/traffic-anomaly.js","../packages/core/dist/analyze/diagnose-property.js","../packages/core/dist/analyze/experiments/content-groups.js","../packages/core/dist/analyze/experiments/measurement/math.js","../packages/core/dist/analyze/experiments/measurement/analytics.js","../packages/core/dist/analyze/experiments/measurement/classify.js","../packages/core/dist/analyze/experiments/measurement/ga4-change-provider.js","../packages/core/dist/analyze/experiments/measurement/filters.js","../packages/core/dist/analyze/experiments/measurement/gsc-change-provider.js","../packages/core/dist/analyze/experiments/measurement/dates.js","../packages/core/dist/analyze/experiments/measurement/window.js","../packages/core/dist/analyze/experiments/measure-change.js","../packages/core/dist/analyze/internal-links-analysis-primitives.js","../packages/core/dist/analyze/internal-links-analysis.js","../packages/core/dist/analyze/internal-links-report.js","../packages/core/dist/analyze/internal-links-verification.js","../packages/core/dist/analyze/internal-links.js","../packages/core/dist/analyze/monitoring/crawl-recommendations.js","../packages/core/dist/analyze/monitoring/crawl-store.js","../packages/core/dist/analyze/monitoring/crawl-diff.js","../packages/core/dist/analyze/pseo/templates.js","../packages/core/dist/analyze/monitoring/index-coverage.js","../packages/core/dist/analyze/monitoring/index-coverage-report.js","../packages/core/dist/analyze/monitoring/index-plan.js","../packages/core/dist/analyze/monitoring/index-watch-analysis.js","../packages/core/dist/analyze/monitoring/index-watch.js","../packages/core/dist/analyze/monitoring/index-monitor.js","../packages/core/dist/analyze/monitoring/link-recover-store.js","../packages/core/dist/analyze/monitoring/redirect-trace.js","../packages/core/dist/analyze/monitoring/link-recover.js","../packages/core/dist/analyze/performance-analysis.js","../packages/core/dist/analyze/performance-crux.js","../packages/core/dist/analyze/performance-lighthouse.js","../packages/core/dist/analyze/performance.js","../packages/core/dist/analyze/pseo/query-insights.js","../packages/core/dist/analyze/pseo/row-analysis.js","../packages/core/dist/analyze/pseo/assessment.js","../packages/core/dist/analyze/pseo/analysis.js","../packages/core/dist/analyze/pseo/audit.js","../packages/core/dist/markdown.js","../packages/core/dist/analyze/pseo/presentation.js","../packages/core/dist/analyze/pseo/markdown.js","../packages/core/dist/analyze/query-cluster-primitives.js","../packages/core/dist/analyze/query-cluster-analysis.js","../packages/core/dist/analyze/query-cluster.js","../packages/core/dist/analyze/reports/dates.js","../packages/core/dist/analyze/reports/change-measurements.js","../packages/core/dist/analyze/reports/markdown.js","../packages/core/dist/analyze/reports/sections.js","../packages/core/dist/analyze/reports/narrative.js","../packages/core/dist/analyze/reports/monthly.js","../packages/core/dist/analyze/reports/presentation.js","../packages/core/dist/analyze/second-page-analysis.js","../packages/core/dist/analyze/second-page.js","../packages/core/dist/analyze/ai-monitoring-prompts.js","../packages/core/dist/analyze/seo-to-ai-query.js","../packages/core/dist/analyze/workflows/priority-scoring.js","../packages/core/dist/analyze/workflows/report.js","../packages/core/dist/analyze/workflows/diagnose-property.js","../packages/core/dist/analyze/workflows/presentation.js","../packages/core/dist/analyze/workflows/markdown.js","../packages/core/dist/analyze/workflows/monthly-report.js","../packages/core/dist/analyze/workflows/priority-grouping.js","../packages/core/dist/analyze/workflows/refresh-priorities.js","../packages/core/dist/analyze/workflows/technical-watch.js","../packages/core/dist/analyze/workflows/segments.js","../packages/core/dist/analyze/workflows/update-postmortem.js","../packages/core/dist/doctor.js","../packages/core/dist/providers/dataforseo.js","../packages/core/dist/providers/semrush/csv.js","../packages/core/dist/providers/semrush/cache.js","../packages/core/dist/providers/semrush/mappers.js","../packages/core/dist/providers/semrush.js","../packages/core/dist/providers/router.js","../packages/core/dist/runtime/interfaces.js","../packages/core/dist/version.js","../packages/mcp/src/input-schemas.ts","../packages/mcp/src/report-options.ts","../packages/mcp/src/tool-result.ts","../packages/mcp/src/ai-opportunity-tools.ts","../packages/mcp/src/fetch-rate.ts","../packages/mcp/src/crawler-tools.ts","../packages/mcp/src/diagnosis-tools.ts","../packages/mcp/src/experiment-tools.ts","../packages/mcp/src/monitoring-tools.ts","../packages/mcp/src/opportunity-tools.ts","../packages/mcp/src/pseo-tools.ts","../packages/mcp/src/report-guidance.ts","../packages/mcp/src/report-tools/audit-page.ts","../packages/mcp/src/report-tools/input.ts","../packages/mcp/src/report-tools/monthly.ts","../packages/mcp/src/report-tools/narrative.ts","../packages/mcp/src/report-tools/second-page.ts","../packages/mcp/src/report-tools.ts","../packages/mcp/src/workflow-tools.ts","../packages/mcp/src/report-registry.ts","../packages/mcp/src/reports.ts","../packages/mcp/src/discovery-tools.ts","../packages/mcp/src/index.ts"],"sourcesContent":["const errorMetadata = {\n ACCESS_DENIED: { exitCode: 4, retryable: false },\n AUTH_CONFIG_REQUIRED: { exitCode: 3, retryable: false },\n AUTH_EXPIRED: { exitCode: 3, retryable: false },\n AUTH_REQUIRED: { exitCode: 3, retryable: false },\n INSUFFICIENT_DATA: { exitCode: 6, retryable: false },\n INTERNAL_ERROR: { exitCode: 1, retryable: false },\n INVALID_INPUT: { exitCode: 2, retryable: false },\n OPTIONAL_PROVIDER_UNAVAILABLE: { exitCode: 7, retryable: true },\n PROPERTY_NOT_FOUND: { exitCode: 4, retryable: false },\n PROVIDER_UNAVAILABLE: { exitCode: 7, retryable: true },\n RATE_LIMITED: { exitCode: 5, retryable: true },\n};\nexport class SeoError extends Error {\n code;\n exitCode;\n retryable;\n constructor(code, message) {\n super(message);\n this.name = 'SeoError';\n this.code = code;\n this.exitCode = errorMetadata[code].exitCode;\n this.retryable = errorMetadata[code].retryable;\n }\n}\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : String(error);\n}\nexport function toSeoError(error) {\n if (error instanceof SeoError) {\n return error;\n }\n const message = errorMessage(error);\n if (/not logged in/i.test(message)) {\n return new SeoError('AUTH_REQUIRED', message);\n }\n if (/oauth client config.*missing|shared seo google app/i.test(message)) {\n return new SeoError('AUTH_CONFIG_REQUIRED', message);\n }\n if (/invalid_grant|refresh token.*no longer valid/i.test(message)) {\n return new SeoError('AUTH_EXPIRED', message);\n }\n if (error instanceof Error && error.name === 'CLIError') {\n return new SeoError('INVALID_INPUT', message);\n }\n return new SeoError('INTERNAL_ERROR', message);\n}\nexport function isSkippableReportError(error) {\n if (!(error instanceof SeoError)) {\n return false;\n }\n return (error.code === 'INSUFFICIENT_DATA' ||\n error.code === 'OPTIONAL_PROVIDER_UNAVAILABLE');\n}\nexport function seoErrorEnvelope(error) {\n const normalized = toSeoError(error);\n return {\n ok: false,\n error: {\n code: normalized.code,\n message: normalized.message,\n retryable: normalized.retryable,\n },\n };\n}\n//# sourceMappingURL=errors.js.map","import { existsSync, mkdirSync, renameSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nlet memoizedPaths;\nfunction defaultConfigDir(input) {\n if (input.platform === 'win32') {\n return join(input.env.APPDATA ?? join(input.home, 'AppData', 'Roaming'), 'seo', 'Config');\n }\n return join(input.env.XDG_CONFIG_HOME ?? join(input.home, '.config'), 'seo');\n}\nfunction defaultCacheDir(input) {\n if (input.platform === 'darwin') {\n return join(input.home, 'Library', 'Caches', 'seo');\n }\n if (input.platform === 'win32') {\n return join(input.env.LOCALAPPDATA ?? join(input.home, 'AppData', 'Local'), 'seo', 'Cache');\n }\n return join(input.env.XDG_CACHE_HOME ?? join(input.home, '.cache'), 'seo');\n}\nfunction defaultLogDir(input) {\n if (input.platform === 'darwin') {\n return join(input.home, 'Library', 'Logs', 'seo');\n }\n if (input.platform === 'win32') {\n return join(input.env.LOCALAPPDATA ?? join(input.home, 'AppData', 'Local'), 'seo', 'Log');\n }\n return join(input.env.XDG_STATE_HOME ?? join(input.home, '.local', 'state'), 'seo');\n}\nfunction resolvedPathOptions(input) {\n return {\n env: input.env ?? process.env,\n home: input.home ?? homedir(),\n platform: input.platform ?? process.platform,\n };\n}\nexport function resolveSeoCliPaths(input = {}) {\n const options = resolvedPathOptions(input);\n const configDir = options.env.SEO_CONFIG_DIR ?? defaultConfigDir(options);\n const cacheDir = options.env.SEO_CACHE_DIR ?? defaultCacheDir(options);\n const logDir = options.env.SEO_LOG_DIR ?? defaultLogDir(options);\n return {\n configDir,\n cacheDir,\n logDir,\n configFile: join(configDir, 'config.json'),\n tokensFile: join(configDir, 'tokens.json'),\n oauthClientFile: join(configDir, 'oauth-client.json'),\n cacheDbFile: join(cacheDir, 'cache.db'),\n };\n}\nfunction legacyMacConfigDir(input) {\n const options = resolvedPathOptions(input);\n if (options.platform !== 'darwin' ||\n options.env.SEO_CONFIG_DIR ||\n options.env.XDG_CONFIG_HOME) {\n return undefined;\n }\n return join(options.home, 'Library', 'Preferences', 'seo');\n}\nexport function migrateLegacyMacConfig(input = {}) {\n const legacyDir = legacyMacConfigDir(input);\n if (!legacyDir)\n return;\n const paths = resolveSeoCliPaths(input);\n if (!existsSync(legacyDir) || existsSync(paths.configDir))\n return;\n try {\n mkdirSync(dirname(paths.configDir), { recursive: true, mode: 0o700 });\n renameSync(legacyDir, paths.configDir);\n }\n catch (error) {\n const code = error.code;\n if (code !== 'EEXIST' && code !== 'ENOENT')\n throw error;\n }\n}\nexport function getSeoCliPaths() {\n if (memoizedPaths) {\n return memoizedPaths;\n }\n memoizedPaths = resolveSeoCliPaths();\n return memoizedPaths;\n}\nexport function ensureSeoCliDirs() {\n const paths = getSeoCliPaths();\n migrateLegacyMacConfig();\n mkdirSync(paths.configDir, { recursive: true, mode: 0o700 });\n mkdirSync(paths.cacheDir, { recursive: true, mode: 0o700 });\n mkdirSync(paths.logDir, { recursive: true, mode: 0o700 });\n return paths;\n}\nexport function fileSize(path) {\n try {\n return statSync(path).size;\n }\n catch {\n return 0;\n }\n}\n//# sourceMappingURL=paths.js.map","import { z } from 'zod';\nexport const tokenSchema = z.object({\n provider: z.literal('google'),\n account_email: z.string().email(),\n scope: z.string(),\n token_type: z.string(),\n access_token: z.string().optional(),\n refresh_token: z.string().optional(),\n expires_at: z.number().int(),\n obtained_at: z.number().int(),\n client_source: z.enum(['shared', 'byo']),\n});\n//# sourceMappingURL=auth.js.map","import { z } from 'zod';\nexport const siteSchema = z.object({\n siteUrl: z.string(),\n displayName: z.string().optional(),\n permission: z.string().optional(),\n addedAt: z.number().int().optional(),\n isDefault: z.boolean().optional(),\n});\nexport const providerPreferenceSchema = z.enum(['cheap', 'authoritative']);\nexport const clientProfileSchema = z.object({\n id: z.string(),\n name: z.string(),\n siteUrl: z.string(),\n startUrl: z.string().optional(),\n watchUrls: z.array(z.string()).default([]),\n brandTerms: z.array(z.string()).default([]),\n ga4PropertyId: z.string().optional(),\n reportDay: z.number().int().min(1).max(31).optional(),\n technicalWeekday: z.number().int().min(0).max(7).optional(),\n isDefault: z.boolean().optional(),\n createdAt: z.number().int(),\n updatedAt: z.number().int(),\n});\nexport const configSchema = z.object({\n defaultSite: z.string().optional(),\n sites: z.array(siteSchema).default([]),\n clients: z.array(clientProfileSchema).default([]),\n google: z\n .object({\n defaultGa4PropertyId: z.string().optional(),\n propertyMappings: z\n .array(z.object({\n siteUrl: z.string(),\n ga4PropertyId: z.string(),\n addedAt: z.number().int().optional(),\n }))\n .default([]),\n })\n .default({ propertyMappings: [] }),\n providers: z\n .object({\n semrushApiKey: z.string().optional(),\n dataForSeoLogin: z.string().optional(),\n dataForSeoPassword: z.string().optional(),\n prefer: providerPreferenceSchema.default('cheap'),\n })\n .default({ prefer: 'cheap' }),\n security: z\n .object({\n useKeychain: z.boolean().default(true),\n })\n .default({ useKeychain: true }),\n auth: z\n .object({\n sharedClientId: z.string().optional(),\n sharedClientSecret: z.string().optional(),\n })\n .default({}),\n});\n//# sourceMappingURL=config.js.map","import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';\nimport { dirname } from 'node:path';\nexport function ensureParentDir(path, mode = 0o700) {\n mkdirSync(dirname(path), { recursive: true, mode });\n}\nexport function readJsonFile(path) {\n try {\n return JSON.parse(readFileSync(path, 'utf8'));\n }\n catch {\n return undefined;\n }\n}\nexport function writeJsonAtomic(path, data, mode) {\n ensureParentDir(path);\n const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;\n writeFileSync(tmp, JSON.stringify(data, null, 2), { encoding: 'utf8', mode });\n chmodSync(tmp, mode);\n renameSync(tmp, path);\n chmodSync(path, mode);\n}\nexport function fileMode(path) {\n try {\n return `0${(statSync(path).mode & 0o777).toString(8)}`;\n }\n catch {\n return 'missing';\n }\n}\nexport function safeRemove(path) {\n rmSync(path, { recursive: true, force: true });\n}\n//# sourceMappingURL=files.js.map","let testKeyring;\nlet useTestKeyring = false;\nlet loadedKeyring;\nasync function resolveKeyring() {\n if (useTestKeyring && testKeyring)\n return testKeyring;\n if (!loadedKeyring) {\n loadedKeyring = import('@napi-rs/keyring/keytar.js').then((module) => module);\n }\n return loadedKeyring;\n}\nexport async function getKeyringPassword(service, account) {\n return (await resolveKeyring()).getPassword(service, account);\n}\nexport async function setKeyringPassword(service, account, password) {\n await (await resolveKeyring()).setPassword(service, account, password);\n}\nexport async function deleteKeyringPassword(service, account) {\n return (await resolveKeyring()).deletePassword(service, account);\n}\nexport function setKeyringForTests(keyring) {\n testKeyring = keyring;\n useTestKeyring = keyring !== undefined;\n}\n//# sourceMappingURL=keyring.js.map","import { chmodSync, statSync } from 'node:fs';\nimport { ensureSeoCliDirs, getSeoCliPaths } from '../paths.js';\nimport { configSchema, tokenSchema, } from '../types.js';\nimport { fileMode, readJsonFile, safeRemove, writeJsonAtomic } from './files.js';\nimport { deleteKeyringPassword, getKeyringPassword, setKeyringPassword, } from './keyring.js';\nconst KEYRING_SERVICE = 'seo';\nconst PRIVATE_FILE_MODE = 0o600;\nfunction tightenConfigPermissions(path) {\n try {\n chmodSync(path, PRIVATE_FILE_MODE);\n }\n catch (error) {\n if (error.code !== 'ENOENT') {\n throw error;\n }\n }\n}\nexport function readConfig() {\n ensureSeoCliDirs();\n const configFile = getSeoCliPaths().configFile;\n tightenConfigPermissions(configFile);\n const raw = readJsonFile(configFile);\n return configSchema.parse(raw ?? {});\n}\nexport function writeConfig(config) {\n ensureSeoCliDirs();\n writeJsonAtomic(getSeoCliPaths().configFile, configSchema.parse(config), PRIVATE_FILE_MODE);\n}\nfunction getKeyringAccount(tokens) {\n return `google:${tokens.account_email}`;\n}\nfunction tokenStorageMode(config) {\n return config.security.useKeychain ? 'keychain' : 'file';\n}\nfunction hasTokenSecrets(tokens) {\n return Boolean(tokens.access_token || tokens.refresh_token);\n}\nfunction tokenMetadata(tokens) {\n return {\n ...tokens,\n access_token: undefined,\n refresh_token: undefined,\n };\n}\nasync function readKeyringTokens(tokens) {\n const account = getKeyringAccount(tokens);\n const [accessToken, refreshToken] = await Promise.all([\n getKeyringPassword(KEYRING_SERVICE, `${account}:access`),\n getKeyringPassword(KEYRING_SERVICE, `${account}:refresh`),\n ]);\n return {\n accessToken: accessToken ?? undefined,\n refreshToken: refreshToken ?? undefined,\n };\n}\nasync function writeKeyringTokens(tokens) {\n const account = getKeyringAccount(tokens);\n if (tokens.access_token) {\n await setKeyringPassword(KEYRING_SERVICE, `${account}:access`, tokens.access_token);\n }\n else {\n await deleteKeyringPassword(KEYRING_SERVICE, `${account}:access`);\n }\n if (tokens.refresh_token) {\n await setKeyringPassword(KEYRING_SERVICE, `${account}:refresh`, tokens.refresh_token);\n }\n else {\n await deleteKeyringPassword(KEYRING_SERVICE, `${account}:refresh`);\n }\n}\nasync function deleteKeyringTokens(tokens) {\n const account = getKeyringAccount(tokens);\n await Promise.all([\n deleteKeyringPassword(KEYRING_SERVICE, `${account}:access`),\n deleteKeyringPassword(KEYRING_SERVICE, `${account}:refresh`),\n ]);\n}\nexport async function readTokens() {\n ensureSeoCliDirs();\n const raw = readJsonFile(getSeoCliPaths().tokensFile);\n if (!raw) {\n return undefined;\n }\n const parsed = tokenSchema.parse(raw);\n const config = readConfig();\n if (!config.security.useKeychain) {\n return parsed;\n }\n try {\n const keyringTokens = await readKeyringTokens(parsed);\n if (hasTokenSecrets(parsed)) {\n await writeKeyringTokens(parsed);\n writeJsonAtomic(getSeoCliPaths().tokensFile, tokenMetadata(parsed), PRIVATE_FILE_MODE);\n return parsed;\n }\n return {\n ...parsed,\n access_token: keyringTokens.accessToken,\n refresh_token: keyringTokens.refreshToken,\n };\n }\n catch {\n return parsed;\n }\n}\nexport async function writeTokens(tokens) {\n ensureSeoCliDirs();\n const parsed = tokenSchema.parse(tokens);\n const config = readConfig();\n if (config.security.useKeychain) {\n try {\n await writeKeyringTokens(parsed);\n writeJsonAtomic(getSeoCliPaths().tokensFile, tokenMetadata(parsed), PRIVATE_FILE_MODE);\n return;\n }\n catch {\n // A headless Linux host or a locked desktop keychain should not prevent\n // local OAuth from working. The private file remains the fallback.\n }\n }\n writeJsonAtomic(getSeoCliPaths().tokensFile, parsed, PRIVATE_FILE_MODE);\n}\nexport async function deleteTokens() {\n const tokens = await readTokens();\n if (tokens) {\n await deleteKeyringTokens(tokens).catch(() => undefined);\n }\n safeRemove(getSeoCliPaths().tokensFile);\n}\nexport async function getTokenStorageStatus() {\n ensureSeoCliDirs();\n const config = readConfig();\n const configured = tokenStorageMode(config);\n if (configured === 'file') {\n return { configured, active: 'file' };\n }\n const raw = readJsonFile(getSeoCliPaths().tokensFile);\n if (!raw)\n return { configured, active: 'keychain' };\n const tokens = tokenSchema.parse(raw);\n if (hasTokenSecrets(tokens)) {\n return {\n configured,\n active: 'file',\n reason: 'Private token file will move to the keychain when it is available.',\n };\n }\n try {\n await readKeyringTokens(tokens);\n return { configured, active: 'keychain' };\n }\n catch {\n return {\n configured,\n active: 'file',\n reason: 'The system keychain is unavailable, so seo is using its private file fallback.',\n };\n }\n}\nexport async function setTokenStorageMode(mode) {\n const tokens = await readTokens();\n const config = readConfig();\n writeConfig({\n ...config,\n security: { ...config.security, useKeychain: mode === 'keychain' },\n });\n if (tokens) {\n await writeTokens(tokens);\n if (mode === 'file') {\n await deleteKeyringTokens(tokens).catch(() => undefined);\n }\n }\n return getTokenStorageStatus();\n}\nexport function readOauthClient() {\n ensureSeoCliDirs();\n const raw = readJsonFile(getSeoCliPaths().oauthClientFile);\n return raw?.clientId && raw?.clientSecret ? raw : undefined;\n}\nexport function writeOauthClient(client) {\n ensureSeoCliDirs();\n writeJsonAtomic(getSeoCliPaths().oauthClientFile, client, 0o600);\n}\nexport function getPrivacySnapshot() {\n const paths = getSeoCliPaths();\n const sizeOf = (path) => {\n try {\n return statSync(path).size;\n }\n catch {\n return 0;\n }\n };\n return [\n {\n label: 'Config',\n path: paths.configFile,\n mode: fileMode(paths.configFile),\n sizeBytes: sizeOf(paths.configFile),\n },\n {\n label: 'Tokens',\n path: paths.tokensFile,\n mode: fileMode(paths.tokensFile),\n sizeBytes: sizeOf(paths.tokensFile),\n },\n {\n label: 'OAuth client',\n path: paths.oauthClientFile,\n mode: fileMode(paths.oauthClientFile),\n sizeBytes: sizeOf(paths.oauthClientFile),\n },\n {\n label: 'Cache DB',\n path: paths.cacheDbFile,\n mode: fileMode(paths.cacheDbFile),\n sizeBytes: sizeOf(paths.cacheDbFile),\n },\n ];\n}\n//# sourceMappingURL=config.js.map","import lockfile from 'proper-lockfile';\nimport { ensureParentDir } from './files.js';\nexport async function withFileLock(path, task) {\n ensureParentDir(path);\n const release = await lockfile\n .lock(path, {\n stale: 60_000,\n update: 5_000,\n retries: {\n retries: 60,\n factor: 1.2,\n minTimeout: 200,\n maxTimeout: 1_000,\n },\n realpath: false,\n })\n .catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Could not acquire local file lock for ${path}. Another seo process may still be writing auth/config state. Wait a few seconds and retry. ${message}`);\n });\n try {\n return await task();\n }\n finally {\n await release();\n }\n}\n//# sourceMappingURL=lock.js.map","export const SHARED_OAUTH_CLIENT = {\n clientId: '548418788053-q7p964rqvjiv8ooamciprku6bpu34u9d.apps.googleusercontent.com',\n clientSecret: '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',\n};\n//# sourceMappingURL=shared-client.generated.js.map","import { readConfig, readOauthClient } from '../../storage/config.js';\nimport { SHARED_OAUTH_CLIENT } from '../shared-client.generated.js';\nexport function getAuthModeStatus() {\n const byo = readOauthClient();\n return {\n sharedConfigured: Boolean(getSharedClientConfig()),\n byoConfigured: Boolean(byo?.clientId && byo?.clientSecret),\n };\n}\nfunction getSharedClientConfig() {\n const config = readConfig();\n const clientId = process.env.SEO_GOOGLE_CLIENT_ID ??\n process.env.GSC_CLIENT_ID ??\n SHARED_OAUTH_CLIENT.clientId ??\n config.auth.sharedClientId;\n const clientSecret = process.env.SEO_GOOGLE_CLIENT_SECRET ??\n process.env.GSC_CLIENT_SECRET ??\n SHARED_OAUTH_CLIENT.clientSecret ??\n config.auth.sharedClientSecret;\n if (!clientId || !clientSecret) {\n return undefined;\n }\n return { clientId, clientSecret, source: 'shared' };\n}\nexport function getClientConfig(source) {\n const byo = readOauthClient();\n if (source !== 'shared' && byo) {\n return {\n clientId: byo.clientId,\n clientSecret: byo.clientSecret,\n source: 'byo',\n };\n }\n if (source === 'byo')\n return undefined;\n return getSharedClientConfig();\n}\nexport function missingOAuthClientMessage(source) {\n return source === 'shared'\n ? 'The stored Google login uses the shared seo app, but this build is missing that OAuth client. Report this package issue at https://github.com/iannuttall/seo/issues, or use `seo auth setup-client` with your own desktop OAuth client.'\n : 'The stored Google login uses a BYO OAuth client that is no longer configured. Restore the same client with `seo auth setup-client`, or run `seo auth logout` before signing in with a different client.';\n}\n//# sourceMappingURL=client-config.js.map","export const GOOGLE_READONLY_SCOPES = [\n 'https://www.googleapis.com/auth/webmasters.readonly',\n 'https://www.googleapis.com/auth/analytics.readonly',\n];\nexport const GOOGLE_SCOPE = [...GOOGLE_READONLY_SCOPES, 'openid', 'email'].join(' ');\n//# sourceMappingURL=types.js.map","import { sign } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\nimport { SeoError } from '../../errors.js';\nimport { GOOGLE_READONLY_SCOPES, } from './types.js';\nconst GOOGLE_TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';\nconst TOKEN_BUFFER_MS = 60_000;\nfunction authConfigError(message) {\n return new SeoError('AUTH_CONFIG_REQUIRED', message);\n}\nfunction sourceLabel(source) {\n if (source === 'environment-json')\n return 'SEO_GOOGLE_SERVICE_ACCOUNT_JSON';\n if (source === 'environment-file')\n return 'SEO_GOOGLE_SERVICE_ACCOUNT_FILE';\n return 'GOOGLE_APPLICATION_CREDENTIALS';\n}\nfunction configuredEntries(environment) {\n const entries = [];\n const raw = environment.SEO_GOOGLE_SERVICE_ACCOUNT_JSON?.trim();\n if (raw)\n entries.push({ source: 'environment-json', value: raw });\n const file = environment.SEO_GOOGLE_SERVICE_ACCOUNT_FILE?.trim();\n if (file)\n entries.push({ source: 'environment-file', value: file });\n const applicationDefault = environment.GOOGLE_APPLICATION_CREDENTIALS?.trim();\n if (applicationDefault) {\n entries.push({\n source: 'application-default-file',\n value: applicationDefault,\n });\n }\n return entries;\n}\nfunction parseServiceAccount(raw, source) {\n let value;\n try {\n value = JSON.parse(raw);\n }\n catch {\n throw authConfigError(sourceLabel(source) +\n ' must contain a valid service account JSON object.');\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw authConfigError(`${sourceLabel(source)} must contain a service account JSON object.`);\n }\n const record = value;\n if (record.type !== undefined && record.type !== 'service_account') {\n throw authConfigError(sourceLabel(source) +\n ' must contain a Google service account credential.');\n }\n if (typeof record.client_email !== 'string' ||\n !record.client_email ||\n typeof record.private_key !== 'string' ||\n !record.private_key) {\n throw authConfigError(sourceLabel(source) +\n ' must include service account client_email and private_key fields.');\n }\n if (record.private_key_id !== undefined &&\n typeof record.private_key_id !== 'string') {\n throw authConfigError(`${sourceLabel(source)} has an invalid service account private_key_id.`);\n }\n return {\n clientEmail: record.client_email,\n privateKey: record.private_key,\n privateKeyId: record.private_key_id,\n source,\n };\n}\nfunction readServiceAccountFile(path, source) {\n try {\n return readFileSync(path, 'utf8');\n }\n catch {\n throw authConfigError('Could not read the service account file named by ' +\n sourceLabel(source) +\n '.');\n }\n}\nexport function getServiceAccountConfig(environment = process.env) {\n const entries = configuredEntries(environment);\n if (!entries.length)\n return undefined;\n if (entries.length > 1) {\n throw authConfigError('Set only one service account credential source: SEO_GOOGLE_SERVICE_ACCOUNT_JSON, SEO_GOOGLE_SERVICE_ACCOUNT_FILE, or GOOGLE_APPLICATION_CREDENTIALS.');\n }\n const entry = entries[0];\n if (!entry)\n return undefined;\n const raw = entry.source === 'environment-json'\n ? entry.value\n : readServiceAccountFile(entry.value, entry.source);\n return parseServiceAccount(raw, entry.source);\n}\nexport function getServiceAccountStatus(environment = process.env) {\n try {\n const config = getServiceAccountConfig(environment);\n if (!config)\n return { configured: false };\n return {\n configured: true,\n identity: config.clientEmail,\n source: config.source,\n };\n }\n catch (error) {\n const entries = configuredEntries(environment);\n return {\n configured: false,\n ...(entries.length === 1 && entries[0]\n ? { source: entries[0].source }\n : {}),\n error: error instanceof Error\n ? error.message\n : 'Service account credentials are invalid.',\n };\n }\n}\nfunction base64Url(value) {\n return Buffer.from(value).toString('base64url');\n}\nfunction signedAssertion(config, now) {\n const header = {\n alg: 'RS256',\n typ: 'JWT',\n ...(config.privateKeyId ? { kid: config.privateKeyId } : {}),\n };\n const payload = {\n iss: config.clientEmail,\n scope: GOOGLE_READONLY_SCOPES.join(' '),\n aud: GOOGLE_TOKEN_ENDPOINT,\n iat: now,\n exp: now + 3_600,\n };\n const unsigned = `${base64Url(JSON.stringify(header))}.${base64Url(JSON.stringify(payload))}`;\n try {\n return (unsigned +\n '.' +\n sign('RSA-SHA256', Buffer.from(unsigned), config.privateKey).toString('base64url'));\n }\n catch {\n throw authConfigError('The service account private key could not sign a Google access request.');\n }\n}\nasync function requestServiceAccountToken(config, fetchImpl = fetch) {\n const assertion = signedAssertion(config, Math.floor(Date.now() / 1_000));\n const response = await fetchImpl(GOOGLE_TOKEN_ENDPOINT, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n assertion,\n }),\n });\n if (!response.ok) {\n const payload = (await response.json().catch(() => undefined));\n const reason = typeof payload?.error === 'string' ? ` (${payload.error})` : '';\n if (response.status === 400 ||\n response.status === 401 ||\n response.status === 403) {\n throw authConfigError('Google rejected the service account access request with ' +\n response.status +\n reason +\n '. Check the service account, private key, and system clock.');\n }\n throw new SeoError('PROVIDER_UNAVAILABLE', 'Google token service is unavailable (' +\n response.status +\n '). Try again later.');\n }\n const payload = (await response.json());\n if (typeof payload.access_token !== 'string' ||\n !payload.access_token ||\n typeof payload.expires_in !== 'number' ||\n !Number.isFinite(payload.expires_in) ||\n payload.expires_in <= 0) {\n throw new SeoError('PROVIDER_UNAVAILABLE', 'Google token service returned an invalid service account response.');\n }\n return { accessToken: payload.access_token, expiresIn: payload.expires_in };\n}\nexport class ServiceAccountAccessTokenClient {\n config;\n fetchImpl;\n token;\n constructor(config, fetchImpl = fetch) {\n this.config = config;\n this.fetchImpl = fetchImpl;\n }\n async getAccessToken() {\n if (this.token && this.token.expiresAt - Date.now() >= TOKEN_BUFFER_MS) {\n return this.token.value;\n }\n const token = await requestServiceAccountToken(this.config, this.fetchImpl);\n this.token = {\n value: token.accessToken,\n expiresAt: Date.now() + token.expiresIn * 1_000,\n };\n return this.token.value;\n }\n}\n//# sourceMappingURL=service-account.js.map","export const GOOGLE_TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';\nexport class GoogleTokenEndpointError extends Error {\n status;\n oauthError;\n constructor(status, oauthError) {\n super(`Google token refresh failed with ${status}${oauthError ? ` (${oauthError})` : ''}.`);\n this.status = status;\n this.oauthError = oauthError;\n this.name = 'GoogleTokenEndpointError';\n }\n}\nexport async function requestGoogleAccessToken(input, fetchImpl = fetch) {\n const response = await fetchImpl(GOOGLE_TOKEN_ENDPOINT, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: input.clientConfig.clientId,\n client_secret: input.clientConfig.clientSecret,\n refresh_token: input.refreshToken,\n }),\n });\n if (!response.ok) {\n const payload = (await response.json().catch(() => undefined));\n throw new GoogleTokenEndpointError(response.status, typeof payload?.error === 'string' ? payload.error : undefined);\n }\n const payload = (await response.json());\n if (typeof payload.access_token !== 'string' ||\n !payload.access_token ||\n typeof payload.expires_in !== 'number' ||\n !Number.isFinite(payload.expires_in) ||\n payload.expires_in <= 0 ||\n (payload.refresh_token !== undefined &&\n typeof payload.refresh_token !== 'string')) {\n throw new Error('Google token refresh returned an invalid response.');\n }\n return {\n accessToken: payload.access_token,\n expiresIn: payload.expires_in,\n refreshToken: payload.refresh_token,\n };\n}\n//# sourceMappingURL=token-endpoint.js.map","import { SeoError } from '../../errors.js';\nimport { getSeoCliPaths } from '../../paths.js';\nimport { deleteTokens, readTokens, writeTokens } from '../../storage/config.js';\nimport { withFileLock } from '../../storage/lock.js';\nimport { getAuthModeStatus, getClientConfig, missingOAuthClientMessage, } from './client-config.js';\nimport { getServiceAccountConfig, getServiceAccountStatus, ServiceAccountAccessTokenClient, } from './service-account.js';\nimport { GoogleTokenEndpointError, requestGoogleAccessToken, } from './token-endpoint.js';\nconst REFRESH_BUFFER_MS = 60_000;\nfunction authRequired() {\n return new SeoError('AUTH_REQUIRED', 'Not logged in. Run `seo auth login` first.');\n}\nfunction authExpired() {\n return new SeoError('AUTH_EXPIRED', 'Google refresh token is no longer valid. Run `seo auth login` again.');\n}\nfunction needsRefresh(tokens, now) {\n return !tokens.access_token || tokens.expires_at - now < REFRESH_BUFFER_MS;\n}\nfunction requireClientConfig(tokens) {\n const clientConfig = getClientConfig(tokens.client_source);\n if (!clientConfig) {\n throw new SeoError('AUTH_CONFIG_REQUIRED', missingOAuthClientMessage(tokens.client_source));\n }\n return clientConfig;\n}\nfunction refreshRejected(error) {\n return ((error instanceof GoogleTokenEndpointError &&\n (error.status === 401 || error.oauthError === 'invalid_grant')) ||\n /invalid_grant|401/.test(error instanceof Error ? error.message : String(error)));\n}\nasync function refreshStoredToken(input) {\n return withFileLock(getSeoCliPaths().tokensFile, async () => {\n const current = await readTokens();\n if (!current)\n throw authRequired();\n const clientConfig = requireClientConfig(current);\n const now = Date.now();\n if (input.onlyIfExpiring && !needsRefresh(current, now)) {\n return current;\n }\n if (!current.refresh_token) {\n await deleteTokens();\n throw authExpired();\n }\n try {\n const refreshed = await requestGoogleAccessToken({\n clientConfig,\n refreshToken: current.refresh_token,\n });\n const next = {\n ...current,\n access_token: refreshed.accessToken,\n refresh_token: refreshed.refreshToken ?? current.refresh_token,\n expires_at: now + refreshed.expiresIn * 1_000,\n };\n await writeTokens(next);\n return next;\n }\n catch (error) {\n if (refreshRejected(error)) {\n await deleteTokens();\n throw authExpired();\n }\n throw error;\n }\n });\n}\nclass LocalGoogleAccessTokenClient {\n tokens;\n constructor(tokens) {\n this.tokens = tokens;\n }\n async getAccessToken() {\n if (needsRefresh(this.tokens, Date.now())) {\n this.tokens = await refreshStoredToken({\n onlyIfExpiring: true,\n });\n }\n if (!this.tokens.access_token)\n throw authExpired();\n return this.tokens.access_token;\n }\n}\nexport async function createAuthorizedClient() {\n let tokens = await readTokens();\n if (!tokens)\n throw authRequired();\n requireClientConfig(tokens);\n if (needsRefresh(tokens, Date.now())) {\n tokens = await refreshStoredToken({\n onlyIfExpiring: true,\n });\n }\n return {\n client: new LocalGoogleAccessTokenClient(tokens),\n tokens,\n };\n}\nexport async function refreshAuthToken() {\n return refreshStoredToken({ onlyIfExpiring: false });\n}\nexport async function createGoogleAccessTokenClient() {\n const serviceAccount = getServiceAccountConfig();\n if (serviceAccount) {\n return {\n client: new ServiceAccountAccessTokenClient(serviceAccount),\n mode: 'service-account',\n identity: serviceAccount.clientEmail,\n quotaIdentity: {\n clientId: 'service-account',\n accountEmail: serviceAccount.clientEmail,\n },\n };\n }\n const { client, tokens } = await createAuthorizedClient();\n const clientConfig = requireClientConfig(tokens);\n return {\n client,\n mode: 'oauth',\n identity: tokens.account_email,\n quotaIdentity: {\n clientId: clientConfig.clientId,\n accountEmail: tokens.account_email,\n },\n tokens,\n };\n}\nexport async function authStatus() {\n const status = getAuthModeStatus();\n const tokens = await readTokens();\n const serviceAccount = getServiceAccountStatus();\n if (serviceAccount.configured || serviceAccount.error) {\n return {\n tokens,\n configured: serviceAccount.configured,\n sharedConfigured: status.sharedConfigured,\n byoConfigured: status.byoConfigured,\n activeMode: 'service-account',\n identity: serviceAccount.identity,\n serviceAccount,\n };\n }\n return {\n tokens,\n configured: Boolean(getClientConfig(tokens?.client_source)),\n sharedConfigured: status.sharedConfigured,\n byoConfigured: status.byoConfigured,\n activeMode: tokens ? 'oauth' : 'none',\n identity: tokens?.account_email,\n serviceAccount,\n };\n}\n//# sourceMappingURL=authorized-client.js.map","import { existsSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport Database from 'better-sqlite3';\nimport { fileSize, getSeoCliPaths } from '../paths.js';\nconst CREATE_SQL = `\nCREATE TABLE IF NOT EXISTS sites (\n site_url TEXT PRIMARY KEY,\n display_name TEXT,\n permission TEXT,\n added_at INTEGER,\n is_default INTEGER DEFAULT 0\n);\n\nCREATE TABLE IF NOT EXISTS gsc_cache (\n site_url TEXT,\n query_hash TEXT,\n request_json TEXT,\n response_json TEXT,\n row_count INTEGER,\n fetched_at INTEGER,\n expires_at INTEGER,\n PRIMARY KEY(site_url, query_hash)\n) WITHOUT ROWID;\nCREATE INDEX IF NOT EXISTS idx_gsc_expires ON gsc_cache(expires_at);\n\nCREATE TABLE IF NOT EXISTS ga4_cache (\n property_id TEXT,\n query_hash TEXT,\n request_json TEXT,\n response_json TEXT,\n row_count INTEGER,\n fetched_at INTEGER,\n expires_at INTEGER,\n PRIMARY KEY(property_id, query_hash)\n) WITHOUT ROWID;\nCREATE INDEX IF NOT EXISTS idx_ga4_expires ON ga4_cache(expires_at);\n\nCREATE TABLE IF NOT EXISTS semrush_cache (\n endpoint TEXT,\n query_hash TEXT,\n request_json TEXT,\n response_json TEXT,\n credits_used INTEGER,\n fetched_at INTEGER,\n expires_at INTEGER,\n PRIMARY KEY(endpoint, query_hash)\n) WITHOUT ROWID;\n\nCREATE TABLE IF NOT EXISTS http_cache (\n url_hash TEXT PRIMARY KEY,\n url TEXT,\n status INTEGER,\n headers_json TEXT,\n body_blob BLOB,\n metadata_json TEXT,\n etag TEXT,\n fetched_at INTEGER,\n expires_at INTEGER\n);\n\nCREATE TABLE IF NOT EXISTS content_groups (\n id TEXT PRIMARY KEY,\n site_url TEXT NOT NULL,\n name TEXT NOT NULL,\n dimension TEXT NOT NULL,\n match_type TEXT NOT NULL,\n pattern TEXT NOT NULL,\n created_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_content_groups_site ON content_groups(site_url);\n\nCREATE TABLE IF NOT EXISTS seo_changes (\n id TEXT PRIMARY KEY,\n site_url TEXT NOT NULL,\n scope TEXT NOT NULL,\n target TEXT NOT NULL,\n title TEXT NOT NULL,\n description TEXT,\n changed_at TEXT NOT NULL,\n created_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_seo_changes_site ON seo_changes(site_url, changed_at);\n\nCREATE TABLE IF NOT EXISTS crawl_runs (\n id TEXT PRIMARY KEY,\n site_url TEXT NOT NULL,\n start_url TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n limit_count INTEGER NOT NULL,\n url_count INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_crawl_runs_site ON crawl_runs(site_url, start_url, created_at);\n\nCREATE TABLE IF NOT EXISTS crawl_reports (\n id TEXT PRIMARY KEY,\n config_hash TEXT NOT NULL,\n site_url TEXT,\n url TEXT NOT NULL,\n status TEXT NOT NULL,\n total_pages INTEGER NOT NULL,\n issue_count INTEGER NOT NULL,\n created_at INTEGER NOT NULL,\n report_json TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_crawl_reports_latest ON crawl_reports(created_at DESC);\nCREATE INDEX IF NOT EXISTS idx_crawl_reports_site ON crawl_reports(site_url, created_at DESC);\n\nCREATE TABLE IF NOT EXISTS crawl_pages (\n run_id TEXT NOT NULL,\n url TEXT NOT NULL,\n final_url TEXT NOT NULL,\n status INTEGER NOT NULL,\n title TEXT,\n meta_description TEXT,\n canonical TEXT,\n meta_robots TEXT,\n x_robots_tag TEXT,\n h1 TEXT,\n indexable INTEGER NOT NULL,\n word_count INTEGER NOT NULL,\n content_hash TEXT NOT NULL,\n outgoing_internal_count INTEGER NOT NULL,\n snapshot_json TEXT,\n PRIMARY KEY(run_id, url),\n FOREIGN KEY(run_id) REFERENCES crawl_runs(id) ON DELETE CASCADE\n) WITHOUT ROWID;\n\nCREATE TABLE IF NOT EXISTS crawl_recommendations (\n run_id TEXT NOT NULL,\n site_url TEXT NOT NULL,\n url TEXT NOT NULL,\n severity TEXT NOT NULL,\n category TEXT NOT NULL,\n title TEXT NOT NULL,\n action TEXT NOT NULL,\n confidence TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n PRIMARY KEY(run_id, url, category),\n FOREIGN KEY(run_id) REFERENCES crawl_runs(id) ON DELETE CASCADE\n) WITHOUT ROWID;\nCREATE INDEX IF NOT EXISTS idx_crawl_recommendations_run ON crawl_recommendations(run_id, severity);\n\nCREATE TABLE IF NOT EXISTS index_watch_snapshots (\n id TEXT PRIMARY KEY,\n site_url TEXT NOT NULL,\n root_site_url TEXT NOT NULL,\n property_site_url TEXT NOT NULL,\n url TEXT NOT NULL,\n verdict TEXT,\n coverage_state TEXT,\n indexing_state TEXT,\n robots_txt_state TEXT,\n page_fetch_state TEXT,\n google_canonical TEXT,\n user_canonical TEXT,\n last_crawl_time TEXT,\n inspection_status TEXT NOT NULL DEFAULT 'succeeded',\n error_code TEXT,\n error_message TEXT,\n inspected_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_index_watch_url ON index_watch_snapshots(site_url, url, inspected_at);\n\nCREATE TABLE IF NOT EXISTS url_inspection_quota_buckets (\n credential_key TEXT NOT NULL,\n property_site_url TEXT NOT NULL,\n quota_date TEXT NOT NULL,\n limit_count INTEGER NOT NULL,\n used_count INTEGER NOT NULL DEFAULT 0,\n reserved_count INTEGER NOT NULL DEFAULT 0,\n minute_window_start INTEGER NOT NULL,\n minute_count INTEGER NOT NULL DEFAULT 0,\n blocked_until INTEGER,\n last_429_at INTEGER,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY(credential_key, property_site_url, quota_date)\n) WITHOUT ROWID;\n\nCREATE TABLE IF NOT EXISTS url_inspection_quota_reservations (\n id TEXT PRIMARY KEY,\n credential_key TEXT NOT NULL,\n property_site_url TEXT NOT NULL,\n quota_date TEXT NOT NULL,\n count INTEGER NOT NULL,\n status TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n expires_at INTEGER NOT NULL,\n finalized_at INTEGER\n);\nCREATE INDEX IF NOT EXISTS idx_url_inspection_reservations_bucket\n ON url_inspection_quota_reservations(\n credential_key, property_site_url, quota_date, status, expires_at\n );\nCREATE INDEX IF NOT EXISTS idx_url_inspection_reservations_minute\n ON url_inspection_quota_reservations(\n credential_key, property_site_url, created_at\n );\n\nCREATE TABLE IF NOT EXISTS link_recover_runs (\n id TEXT PRIMARY KEY,\n site_url TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n start_date TEXT NOT NULL,\n end_date TEXT NOT NULL,\n days INTEGER NOT NULL,\n checked INTEGER NOT NULL,\n recoverable INTEGER NOT NULL,\n high INTEGER NOT NULL,\n medium INTEGER NOT NULL,\n low INTEGER NOT NULL,\n clicks_at_risk REAL NOT NULL,\n impressions_at_risk REAL NOT NULL,\n top_issue TEXT,\n top_url TEXT,\n top_action TEXT\n);\nCREATE INDEX IF NOT EXISTS idx_link_recover_runs_site ON link_recover_runs(site_url, created_at);\n\nCREATE TABLE IF NOT EXISTS link_recover_items (\n run_id TEXT NOT NULL,\n site_url TEXT NOT NULL,\n url TEXT NOT NULL,\n final_url TEXT NOT NULL,\n issue TEXT NOT NULL,\n issues_json TEXT NOT NULL,\n severity TEXT NOT NULL,\n clicks REAL NOT NULL,\n impressions REAL NOT NULL,\n position REAL NOT NULL,\n action TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n PRIMARY KEY(run_id, url),\n FOREIGN KEY(run_id) REFERENCES link_recover_runs(id) ON DELETE CASCADE\n) WITHOUT ROWID;\nCREATE INDEX IF NOT EXISTS idx_link_recover_items_url ON link_recover_items(site_url, url, created_at);\n\nCREATE TABLE IF NOT EXISTS performance_reports (\n id TEXT PRIMARY KEY,\n url TEXT NOT NULL,\n strategy TEXT NOT NULL,\n report_json TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n expires_at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_performance_reports_url ON performance_reports(url, strategy, created_at);\n`;\nlet db;\nfunction ensureColumn(database, table, column, definition) {\n const columns = database\n .prepare(`PRAGMA table_info(${table})`)\n .all();\n if (columns.some((item) => item.name === column))\n return;\n database.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);\n}\nfunction initDb(database) {\n database.pragma('journal_mode = WAL');\n database.pragma('synchronous = NORMAL');\n database.pragma('foreign_keys = ON');\n database.pragma('temp_store = MEMORY');\n database.pragma('mmap_size = 268435456');\n database.pragma('busy_timeout = 5000');\n const migrate = database.transaction(() => {\n database.exec(CREATE_SQL);\n ensureColumn(database, 'crawl_pages', 'snapshot_json', 'TEXT');\n ensureColumn(database, 'http_cache', 'metadata_json', 'TEXT');\n ensureColumn(database, 'index_watch_snapshots', 'root_site_url', 'TEXT');\n ensureColumn(database, 'index_watch_snapshots', 'property_site_url', 'TEXT');\n ensureColumn(database, 'index_watch_snapshots', 'error_code', 'TEXT');\n ensureColumn(database, 'index_watch_snapshots', 'error_message', 'TEXT');\n ensureColumn(database, 'index_watch_snapshots', 'inspection_status', \"TEXT NOT NULL DEFAULT 'succeeded'\");\n database.exec(`\n UPDATE index_watch_snapshots\n SET root_site_url = COALESCE(root_site_url, site_url),\n property_site_url = COALESCE(property_site_url, site_url)\n WHERE root_site_url IS NULL OR property_site_url IS NULL;\n CREATE INDEX IF NOT EXISTS idx_index_watch_root_url\n ON index_watch_snapshots(root_site_url, url, inspected_at DESC, id DESC);\n CREATE INDEX IF NOT EXISTS idx_index_watch_property_url\n ON index_watch_snapshots(property_site_url, url, inspected_at DESC, id DESC);\n `);\n });\n migrate.immediate();\n}\nexport function getDb() {\n if (db) {\n return db;\n }\n const path = getSeoCliPaths().cacheDbFile;\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n db = new Database(path);\n initDb(db);\n return db;\n}\nexport function hashKey(parts) {\n const json = JSON.stringify(parts);\n return Buffer.from(json).toString('base64url');\n}\nexport function getCacheStats() {\n const database = getDb();\n const dbPath = getSeoCliPaths().cacheDbFile;\n const counts = {\n sites: database.prepare('SELECT COUNT(*) AS count FROM sites').get(),\n gsc_cache: database\n .prepare('SELECT COUNT(*) AS count FROM gsc_cache')\n .get(),\n ga4_cache: database\n .prepare('SELECT COUNT(*) AS count FROM ga4_cache')\n .get(),\n semrush_cache: database\n .prepare('SELECT COUNT(*) AS count FROM semrush_cache')\n .get(),\n http_cache: database\n .prepare('SELECT COUNT(*) AS count FROM http_cache')\n .get(),\n };\n return {\n dbPath,\n sizeBytes: existsSync(dbPath) ? fileSize(dbPath) : 0,\n counts: Object.fromEntries(Object.entries(counts).map(([key, value]) => [key, value.count])),\n };\n}\nexport function clearCache(provider, olderThanMs) {\n const database = getDb();\n const cutoff = olderThanMs ? Date.now() - olderThanMs : undefined;\n const tables = provider === 'gsc'\n ? ['gsc_cache']\n : provider === 'ga4'\n ? ['ga4_cache']\n : provider === 'semrush'\n ? ['semrush_cache']\n : provider === 'http'\n ? ['http_cache']\n : ['gsc_cache', 'ga4_cache', 'semrush_cache', 'http_cache'];\n let removed = 0;\n for (const table of tables) {\n const sql = cutoff\n ? `DELETE FROM ${table} WHERE fetched_at < ?`\n : `DELETE FROM ${table}`;\n const info = cutoff\n ? database.prepare(sql).run(cutoff)\n : database.prepare(sql).run();\n removed += info.changes;\n }\n return removed;\n}\n//# sourceMappingURL=database.js.map","import { fetch } from 'undici';\nimport { createGoogleAccessTokenClient, } from '../gsc/auth.js';\nimport { getDb, hashKey } from '../storage/database.js';\nexport function ga4RequestCanUseCache(body) {\n return body.dateRanges.every((range) => /^\\d{4}-\\d{2}-\\d{2}$/.test(range.startDate) &&\n /^\\d{4}-\\d{2}-\\d{2}$/.test(range.endDate));\n}\nasync function authedFetch(client, url, init) {\n const accessToken = await client.getAccessToken();\n if (!accessToken) {\n throw new Error('Could not obtain Google access token.');\n }\n return fetch(url, {\n method: init?.method,\n body: init?.body,\n headers: {\n ...init?.headers,\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n });\n}\nexport async function runGa4Report(propertyId, body, opts = {}) {\n const db = getDb();\n const queryHash = hashKey([propertyId, body]);\n const cacheable = ga4RequestCanUseCache(body);\n const cached = cacheable\n ? db\n .prepare('SELECT response_json FROM ga4_cache WHERE property_id = ? AND query_hash = ? AND expires_at > ?')\n .get(propertyId, queryHash, Date.now())\n : undefined;\n if (!opts.refresh && cached?.response_json) {\n return JSON.parse(cached.response_json);\n }\n const { client } = await createGoogleAccessTokenClient();\n const response = await authedFetch(client, `https://analyticsdata.googleapis.com/v1beta/properties/${propertyId}:runReport`, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n if (!response.ok) {\n if (response.status === 403) {\n throw new Error(`GA4 report failed with 403. Check access to property ${propertyId}.`);\n }\n throw new Error(`GA4 report failed with ${response.status}.`);\n }\n const result = (await response.json());\n if (cacheable) {\n db.prepare(`INSERT OR REPLACE INTO ga4_cache\n (property_id, query_hash, request_json, response_json, row_count, fetched_at, expires_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`).run(propertyId, queryHash, JSON.stringify(body), JSON.stringify(result), result.rowCount ?? result.rows?.length ?? 0, Date.now(), Date.now() + 86_400_000);\n }\n return result;\n}\nexport async function listGa4AccountSummaries() {\n const { client } = await createGoogleAccessTokenClient();\n const response = await authedFetch(client, 'https://analyticsadmin.googleapis.com/v1beta/accountSummaries');\n if (!response.ok) {\n if (response.status === 403) {\n throw new Error('GA4 account summary fetch failed with 403. Enable the Google Analytics Admin API and check Analytics access.');\n }\n throw new Error(`GA4 account summary fetch failed with ${response.status}.`);\n }\n const json = (await response.json());\n return json.accountSummaries ?? [];\n}\nexport async function listGa4DataStreams(propertyId) {\n const { client } = await createGoogleAccessTokenClient();\n const streams = [];\n let pageToken;\n let pageCount = 0;\n do {\n if (pageCount >= 20) {\n throw new Error(`GA4 data stream discovery exceeded 20 pages for property ${propertyId}.`);\n }\n const url = new URL(`https://analyticsadmin.googleapis.com/v1beta/properties/${ga4PropertyIdFromName(propertyId)}/dataStreams`);\n url.searchParams.set('pageSize', '200');\n if (pageToken)\n url.searchParams.set('pageToken', pageToken);\n const response = await authedFetch(client, url.toString());\n if (!response.ok) {\n if (response.status === 403) {\n throw new Error(`GA4 data stream fetch failed with 403 for property ${propertyId}. Check Analytics access.`);\n }\n throw new Error(`GA4 data stream fetch failed with ${response.status} for property ${propertyId}.`);\n }\n const json = (await response.json());\n streams.push(...(json.dataStreams ?? []));\n pageToken = json.nextPageToken;\n pageCount += 1;\n } while (pageToken);\n return streams;\n}\nexport function ga4PropertyIdFromName(name) {\n return name.replace(/^properties\\//, '');\n}\nexport function ga4RowsToObjects(result) {\n const dimensions = result.dimensionHeaders?.map((header) => header.name) ?? [];\n const metrics = result.metricHeaders?.map((header) => header.name) ?? [];\n return (result.rows ?? []).map((row) => {\n const output = {};\n dimensions.forEach((name, index) => {\n output[name] = row.dimensionValues?.[index]?.value ?? '';\n });\n metrics.forEach((name, index) => {\n output[name] = row.metricValues?.[index]?.value ?? '';\n });\n return output;\n });\n}\nexport function ga4ReportQualityWarnings(result, label = 'GA4 report') {\n const warnings = [];\n if (result.metadata?.dataLossFromOtherRow) {\n warnings.push(`${label} grouped high-cardinality data into (other).`);\n }\n if (result.metadata?.subjectToThresholding) {\n warnings.push(`${label} was subject to Google Analytics thresholding.`);\n }\n const sampled = result.metadata?.samplingMetadatas?.some((sampling) => {\n const read = Number(sampling.samplesReadCount);\n const space = Number(sampling.samplingSpaceSize);\n return Number.isFinite(read) && Number.isFinite(space) && read < space;\n });\n if (sampled)\n warnings.push(`${label} was sampled by Google Analytics.`);\n return warnings;\n}\n//# sourceMappingURL=client.js.map","export const AI_REFERRAL_SOURCES_VERSION = 'ai-referral-sources@1';\nexport const AI_REFERRAL_SOURCES = [\n {\n id: 'chatgpt',\n label: 'ChatGPT',\n domains: ['chatgpt.com', 'chat.openai.com'],\n },\n { id: 'perplexity', label: 'Perplexity', domains: ['perplexity.ai'] },\n { id: 'claude', label: 'Claude', domains: ['claude.ai'] },\n {\n id: 'gemini',\n label: 'Gemini',\n domains: ['gemini.google.com', 'bard.google.com'],\n },\n {\n id: 'copilot',\n label: 'Copilot',\n domains: ['copilot.com', 'copilot.microsoft.com'],\n },\n { id: 'grok', label: 'Grok', domains: ['grok.com'] },\n { id: 'deepseek', label: 'DeepSeek', domains: ['chat.deepseek.com'] },\n { id: 'meta-ai', label: 'Meta AI', domains: ['meta.ai'] },\n { id: 'you', label: 'You.com', domains: ['you.com'] },\n { id: 'poe', label: 'Poe', domains: ['poe.com'] },\n { id: 'phind', label: 'Phind', domains: ['phind.com'] },\n {\n id: 'mistral',\n label: 'Le Chat',\n domains: ['chat.mistral.ai'],\n },\n {\n id: 'notebooklm',\n label: 'NotebookLM',\n domains: ['notebooklm.google.com'],\n },\n];\nfunction hostnameFromSource(value) {\n const normalized = value.normalize('NFKC').trim().toLowerCase();\n if (!normalized || normalized.startsWith('('))\n return undefined;\n try {\n const url = new URL(/^[a-z][a-z\\d+.-]*:\\/\\//i.test(normalized)\n ? normalized\n : `https://${normalized}`);\n return url.hostname.replace(/^www\\./, '').replace(/\\.$/, '') || undefined;\n }\n catch {\n return undefined;\n }\n}\nfunction matchesDomain(hostname, domain) {\n return hostname === domain || hostname.endsWith(`.${domain}`);\n}\nexport function aiReferralSourceForValue(value) {\n const hostname = hostnameFromSource(value);\n if (!hostname)\n return undefined;\n return AI_REFERRAL_SOURCES.find((source) => source.domains.some((domain) => matchesDomain(hostname, domain)));\n}\n//# sourceMappingURL=ai-referrals-sources.js.map","import { SeoError } from '../errors.js';\nimport { AI_REFERRAL_SOURCES_VERSION, aiReferralSourceForValue, } from './ai-referrals-sources.js';\nfunction compareText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\nfunction metric(row, name) {\n const value = row[name];\n const parsed = Number(value);\n if (value === undefined ||\n value.trim() === '' ||\n !Number.isInteger(parsed) ||\n parsed < 0) {\n throw new SeoError('PROVIDER_UNAVAILABLE', `GA4 returned an invalid ${name} value.`);\n }\n return parsed;\n}\nfunction dateValue(value) {\n if (!value || !/^\\d{8}$/.test(value)) {\n throw new SeoError('PROVIDER_UNAVAILABLE', 'GA4 returned an invalid date value.');\n }\n return `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}`;\n}\nfunction addMetrics(target, source) {\n target.sessions += source.sessions;\n target.eventCount += source.eventCount;\n}\nfunction emptyMetrics() {\n return { sessions: 0, eventCount: 0 };\n}\nfunction evidenceReasons(name, evidence) {\n if (evidence.status === 'complete' || evidence.status === 'skipped')\n return [];\n return [`${name} evidence is ${evidence.status}.`, ...evidence.warnings];\n}\nexport function analyzeAiReferralRows(input) {\n const sourceTotals = new Map();\n for (const row of input.sourceRows) {\n const definition = aiReferralSourceForValue(row.sessionSource ?? '');\n if (!definition)\n continue;\n const total = sourceTotals.get(definition.id) ?? {\n definition,\n observedSessionSources: new Set(),\n ...emptyMetrics(),\n };\n addMetrics(total, {\n sessions: metric(row, 'sessions'),\n eventCount: metric(row, 'eventCount'),\n });\n total.observedSessionSources.add(row.sessionSource ?? '');\n sourceTotals.set(definition.id, total);\n }\n const pageTotals = new Map();\n const dailyTotals = new Map();\n const detailTotal = emptyMetrics();\n for (const row of input.detailRows) {\n const definition = aiReferralSourceForValue(row.sessionSource ?? '');\n if (!definition || !sourceTotals.has(definition.id)) {\n throw new SeoError('PROVIDER_UNAVAILABLE', 'GA4 detail rows contained an unexpected session source.');\n }\n const metrics = {\n sessions: metric(row, 'sessions'),\n eventCount: metric(row, 'eventCount'),\n };\n addMetrics(detailTotal, metrics);\n const landingPage = row.landingPagePlusQueryString || '(not set)';\n const pageTotal = pageTotals.get(landingPage) ?? {\n ...emptyMetrics(),\n sources: new Map(),\n };\n addMetrics(pageTotal, metrics);\n pageTotal.sources.set(definition.id, (pageTotal.sources.get(definition.id) ?? 0) + metrics.sessions);\n pageTotals.set(landingPage, pageTotal);\n const date = dateValue(row.date);\n const dailyTotal = dailyTotals.get(date) ?? emptyMetrics();\n addMetrics(dailyTotal, metrics);\n dailyTotals.set(date, dailyTotal);\n }\n const total = [...sourceTotals.values()].reduce((sum, source) => {\n addMetrics(sum, source);\n return sum;\n }, emptyMetrics());\n const detailMismatch = (input.detail.status === 'complete' || input.detail.status === 'partial') &&\n (detailTotal.sessions !== total.sessions ||\n detailTotal.eventCount !== total.eventCount);\n const timeZones = new Set([\n input.sourceDiscovery.timeZone,\n input.detail.timeZone,\n input.totalUsersEvidence.timeZone,\n ].filter((value) => Boolean(value)));\n const partialReasons = [\n ...evidenceReasons('Source discovery', input.sourceDiscovery),\n ...evidenceReasons('Landing-page detail', input.detail),\n ...evidenceReasons('Total users', input.totalUsersEvidence),\n ...(detailMismatch\n ? [\n 'GA4 detail totals differ from source-discovery totals; landing-page and daily breakdowns are incomplete.',\n ]\n : []),\n ...(timeZones.size > 1\n ? ['GA4 queries returned inconsistent property time zones.']\n : []),\n ];\n const dataStatus = partialReasons.length ? 'partial' : 'complete';\n const generalCaveat = 'GA4 only attributes visits that arrive with a recognized session source; some AI visits appear as direct, unassigned, or another source.';\n const possiblyTruncated = input.sourceDiscovery.truncated ||\n input.detail.truncated ||\n input.totalUsersEvidence.truncated;\n const allLandingPages = [...pageTotals.entries()]\n .map(([landingPage, metrics]) => {\n const topSourceId = [...metrics.sources.entries()].sort((left, right) => right[1] - left[1] || compareText(left[0], right[0]))[0]?.[0];\n const topSource = topSourceId\n ? sourceTotals.get(topSourceId)?.definition\n : undefined;\n if (!topSource) {\n throw new SeoError('PROVIDER_UNAVAILABLE', 'Could not resolve the top AI referral source.');\n }\n return {\n landingPage,\n sessions: metrics.sessions,\n eventCount: metrics.eventCount,\n totalUsers: null,\n topSource: topSource.label,\n topSourceDetails: { id: topSource.id, label: topSource.label },\n };\n })\n .sort((left, right) => right.sessions - left.sessions ||\n compareText(left.landingPage, right.landingPage));\n const landingPages = allLandingPages.slice(0, input.resultLimit);\n const selection = {\n limit: input.resultLimit,\n retainedRows: allLandingPages.length,\n returnedRows: landingPages.length,\n omittedRows: Math.max(0, allLandingPages.length - landingPages.length),\n };\n return {\n schemaVersion: 3,\n property: input.property,\n generatedAt: input.generatedAt,\n dataStatus,\n range: input.range,\n methodology: {\n id: 'ga4-ai-referrals',\n version: 2,\n attributionDimension: 'sessionSource',\n sourceRulesVersion: AI_REFERRAL_SOURCES_VERSION,\n },\n dataSource: {\n provider: 'google-analytics-4',\n api: 'analyticsdata.v1beta.runReport',\n maxRows: input.maxRows,\n calls: input.sourceDiscovery.calls +\n input.detail.calls +\n input.totalUsersEvidence.calls,\n possiblyTruncated,\n sourceDiscovery: input.sourceDiscovery,\n detail: input.detail,\n totalUsers: input.totalUsersEvidence,\n partialReasons,\n },\n selection: { landingPages: selection },\n summary: {\n ...total,\n totalUsers: input.totalUsers,\n totalUsersStatus: input.totalUsers === null ? 'not-reported' : 'available',\n sources: sourceTotals.size,\n landingPages: pageTotals.size,\n verdict: total.sessions\n ? dataStatus === 'complete'\n ? 'Detected AI referral traffic in GA4.'\n : 'Detected AI referral traffic; partial counts and breakdowns are lower bounds.'\n : dataStatus === 'complete'\n ? 'No sessions attributed to the known AI session-source rules were detected.'\n : 'No AI-attributed sessions were found in retained GA4 data; this partial report cannot establish absence.',\n caveat: generalCaveat,\n },\n sources: [...sourceTotals.values()]\n .map((source) => ({\n id: source.definition.id,\n label: source.definition.label,\n source: source.definition.label,\n observedSessionSources: [...source.observedSessionSources].sort(compareText),\n sessions: source.sessions,\n eventCount: source.eventCount,\n totalUsers: null,\n shareOfAiSessions: total.sessions\n ? source.sessions / total.sessions\n : 0,\n share: total.sessions ? source.sessions / total.sessions : 0,\n }))\n .sort((left, right) => right.sessions - left.sessions || compareText(left.id, right.id)),\n landingPages,\n daily: [...dailyTotals.entries()]\n .map(([date, metrics]) => ({ date, ...metrics, totalUsers: null }))\n .sort((left, right) => compareText(left.date, right.date)),\n caveats: [\n generalCaveat,\n 'Attribution uses GA4 sessionSource only; landing-page text, medium text, and event referrers are never treated as referral sources.',\n 'Source totals come from a low-cardinality source query; landing-page and daily detail is queried separately for the exact observed source values.',\n 'Total users come from a separate filtered aggregate when AI sources are observed and are never summed across report rows; complete zero-session evidence implies zero users without another query.',\n ...(selection.omittedRows > 0\n ? [\n `Landing-page output returns the ${selection.returnedRows} highest-session pages from ${selection.retainedRows} retained detail rows; ${selection.omittedRows} lower-ranked pages are omitted. Increase resultLimit to inspect more.`,\n ]\n : []),\n ...partialReasons,\n ],\n };\n}\n//# sourceMappingURL=ai-referrals-analysis.js.map","import { ga4ReportQualityWarnings, ga4RowsToObjects, } from '../ga4/client.js';\nconst PAGE_SIZE = 25_000;\nexport async function fetchAiReferralRows(input) {\n const pageSize = input.pageSize ?? PAGE_SIZE;\n if (!Number.isInteger(input.maxRows) || input.maxRows < 1) {\n throw new Error('maxRows must be a positive whole number.');\n }\n if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > PAGE_SIZE) {\n throw new Error(`pageSize must be a whole number between 1 and ${PAGE_SIZE}.`);\n }\n const rows = [];\n const warnings = new Set();\n const retainedKeys = new Set();\n const dimensionNames = input.request.dimensions?.map((dimension) => dimension.name) ?? [];\n let availableRows;\n let timeZone;\n let emptyReason;\n let calls = 0;\n let lastPageSize = 0;\n let offset = 0;\n let forcedTruncation = false;\n while (offset < input.maxRows) {\n const limit = Math.min(pageSize, input.maxRows - offset);\n const result = await input.query(input.property, { ...input.request, limit, offset }, { refresh: input.refresh });\n calls += 1;\n const rawPage = ga4RowsToObjects(result);\n const page = rawPage.slice(0, limit);\n if (rawPage.length > limit) {\n forcedTruncation = true;\n warnings.add(`${input.label} returned more rows than requested.`);\n }\n lastPageSize = page.length;\n offset += page.length;\n for (const row of page) {\n const key = JSON.stringify(dimensionNames.map((name) => row[name] ?? ''));\n if (retainedKeys.has(key)) {\n warnings.add(`${input.label} returned overlapping pagination rows.`);\n continue;\n }\n retainedKeys.add(key);\n rows.push(row);\n }\n for (const warning of ga4ReportQualityWarnings(result, input.label)) {\n warnings.add(warning);\n }\n if (timeZone !== undefined &&\n result.metadata?.timeZone !== undefined &&\n timeZone !== result.metadata.timeZone) {\n warnings.add(`${input.label} time zone changed during pagination.`);\n }\n timeZone ??= result.metadata?.timeZone;\n emptyReason ??= result.metadata?.emptyReason;\n if (result.rowCount !== undefined) {\n if (availableRows !== undefined && availableRows !== result.rowCount) {\n warnings.add(`${input.label} rowCount changed during pagination.`);\n }\n availableRows = Math.max(availableRows ?? 0, result.rowCount);\n }\n if (page.length === 0)\n break;\n if (availableRows !== undefined && offset >= availableRows)\n break;\n if (page.length < limit && availableRows === undefined)\n break;\n }\n const truncated = forcedTruncation ||\n (availableRows !== undefined && availableRows > offset) ||\n (availableRows === undefined && offset >= input.maxRows && lastPageSize > 0);\n return {\n rows,\n calls,\n returnedRows: rows.length,\n ...(availableRows !== undefined ? { availableRows } : {}),\n ...(timeZone ? { timeZone } : {}),\n ...(emptyReason ? { emptyReason } : {}),\n truncated,\n warnings: [...warnings],\n };\n}\nexport function sessionSourceInListFilter(values) {\n return {\n filter: {\n fieldName: 'sessionSource',\n inListFilter: {\n values,\n caseSensitive: true,\n },\n },\n };\n}\n//# sourceMappingURL=ai-referrals-query.js.map","import { SeoError } from '../errors.js';\nimport { runGa4Report } from '../ga4/client.js';\nimport { analyzeAiReferralRows } from './ai-referrals-analysis.js';\nimport { fetchAiReferralRows, sessionSourceInListFilter, } from './ai-referrals-query.js';\nimport { aiReferralSourceForValue } from './ai-referrals-sources.js';\nexport { analyzeAiReferralRows } from './ai-referrals-analysis.js';\nexport { sessionSourceInListFilter } from './ai-referrals-query.js';\nexport { AI_REFERRAL_SOURCES, AI_REFERRAL_SOURCES_VERSION, aiReferralSourceForValue, } from './ai-referrals-sources.js';\nconst DEFAULT_MAX_ROWS = 100_000;\nconst MAX_ROWS = 100_000;\nconst DEFAULT_RESULT_LIMIT = 25;\nconst MAX_RESULT_LIMIT = 1_000;\nfunction validIsoDate(value) {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value))\n return false;\n return new Date(`${value}T00:00:00.000Z`).toISOString().slice(0, 10) === value;\n}\nfunction validRelativeDate(value) {\n return (value === 'today' || value === 'yesterday' || /^\\d+daysAgo$/.test(value));\n}\nfunction reportRange(input) {\n const startDate = input.startDate ?? '28daysAgo';\n const endDate = input.endDate ?? 'yesterday';\n const absolute = validIsoDate(startDate) && validIsoDate(endDate);\n const relative = validRelativeDate(startDate) && validRelativeDate(endDate);\n if (!absolute && !relative) {\n throw new SeoError('INVALID_INPUT', 'startDate and endDate must both be YYYY-MM-DD dates or GA4 relative dates such as 28daysAgo and yesterday.');\n }\n if (absolute && startDate > endDate) {\n throw new SeoError('INVALID_INPUT', 'startDate must be on or before endDate.');\n }\n return { startDate, endDate, kind: absolute ? 'absolute' : 'relative' };\n}\nfunction maxRows(input) {\n if (input.maxRows !== undefined &&\n input.limit !== undefined &&\n input.maxRows !== input.limit) {\n throw new SeoError('INVALID_INPUT', 'Use maxRows or the legacy limit option, not both.');\n }\n const value = input.maxRows ?? input.limit ?? DEFAULT_MAX_ROWS;\n if (!Number.isInteger(value) || value < 1 || value > MAX_ROWS) {\n throw new SeoError('INVALID_INPUT', `maxRows must be a whole number between 1 and ${MAX_ROWS}.`);\n }\n return value;\n}\nfunction resultLimit(input) {\n const value = input.resultLimit ?? DEFAULT_RESULT_LIMIT;\n if (!Number.isInteger(value) || value < 1 || value > MAX_RESULT_LIMIT) {\n throw new SeoError('INVALID_INPUT', `resultLimit must be a whole number between 1 and ${MAX_RESULT_LIMIT}.`);\n }\n return value;\n}\nfunction evidence(result) {\n return {\n status: result.truncated || result.warnings.length ? 'partial' : 'complete',\n calls: result.calls,\n returnedRows: result.returnedRows,\n ...(result.availableRows !== undefined\n ? { availableRows: result.availableRows }\n : {}),\n ...(result.timeZone ? { timeZone: result.timeZone } : {}),\n ...(result.emptyReason ? { emptyReason: result.emptyReason } : {}),\n truncated: result.truncated,\n warnings: result.warnings,\n };\n}\nfunction skippedEvidence() {\n return {\n status: 'skipped',\n calls: 0,\n returnedRows: 0,\n truncated: false,\n warnings: [],\n };\n}\nfunction unavailableEvidence(message) {\n return {\n status: 'unavailable',\n calls: 1,\n returnedRows: 0,\n truncated: false,\n warnings: [message],\n };\n}\nfunction totalUsersFromRows(rows) {\n const value = rows[0]?.totalUsers;\n if (value === undefined || value.trim() === '')\n return undefined;\n const parsed = Number(value);\n return Number.isInteger(parsed) && parsed >= 0 ? parsed : undefined;\n}\nexport async function aiReferralsReport(input, dependencies = {}) {\n const property = input.property.trim();\n if (!property)\n throw new SeoError('INVALID_INPUT', 'property is required.');\n const range = reportRange(input);\n const ga4Range = {\n startDate: range.startDate,\n endDate: range.endDate,\n };\n const retainedRows = maxRows(input);\n const selectedResultLimit = resultLimit(input);\n const query = dependencies.runGa4Report ?? runGa4Report;\n const sourceResult = await fetchAiReferralRows({\n property,\n request: {\n dateRanges: [ga4Range],\n dimensions: [{ name: 'sessionSource' }],\n metrics: [{ name: 'sessions' }, { name: 'eventCount' }],\n orderBys: [\n { dimension: { dimensionName: 'sessionSource' }, desc: false },\n ],\n },\n maxRows: retainedRows,\n refresh: input.refresh,\n label: 'AI referral source-discovery query',\n query,\n });\n const observedSources = [\n ...new Set(sourceResult.rows\n .map((row) => row.sessionSource ?? '')\n .filter((source) => aiReferralSourceForValue(source))),\n ].sort((left, right) => (left < right ? -1 : left > right ? 1 : 0));\n let detailResult;\n let usersResult;\n let detailEvidence = skippedEvidence();\n let totalUsers = null;\n let totalUsersEvidence = skippedEvidence();\n if (observedSources.length > 0) {\n const dimensionFilter = sessionSourceInListFilter(observedSources);\n try {\n detailResult = await fetchAiReferralRows({\n property,\n request: {\n dateRanges: [ga4Range],\n dimensions: [\n { name: 'date' },\n { name: 'sessionSource' },\n { name: 'landingPagePlusQueryString' },\n ],\n metrics: [{ name: 'sessions' }, { name: 'eventCount' }],\n dimensionFilter,\n orderBys: [\n { dimension: { dimensionName: 'date' }, desc: false },\n { dimension: { dimensionName: 'sessionSource' }, desc: false },\n {\n dimension: { dimensionName: 'landingPagePlusQueryString' },\n desc: false,\n },\n ],\n },\n maxRows: retainedRows,\n refresh: input.refresh,\n label: 'AI referral landing-page detail query',\n query,\n });\n detailEvidence = evidence(detailResult);\n }\n catch (error) {\n detailEvidence = unavailableEvidence(`The landing-page detail query failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n try {\n usersResult = await fetchAiReferralRows({\n property,\n request: {\n dateRanges: [ga4Range],\n metrics: [{ name: 'totalUsers' }],\n dimensionFilter,\n },\n maxRows: 1,\n refresh: input.refresh,\n label: 'AI referral total-users query',\n query,\n });\n totalUsers = totalUsersFromRows(usersResult.rows) ?? null;\n totalUsersEvidence = evidence(usersResult);\n if (totalUsers === null) {\n totalUsersEvidence = unavailableEvidence('The de-duplicated total-users query returned no valid value.');\n }\n }\n catch (error) {\n totalUsersEvidence = unavailableEvidence(`The de-duplicated total-users query failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n else if (!sourceResult.truncated && sourceResult.warnings.length === 0) {\n totalUsers = 0;\n }\n return analyzeAiReferralRows({\n property,\n generatedAt: (dependencies.now ?? (() => new Date()))().toISOString(),\n range,\n maxRows: retainedRows,\n resultLimit: selectedResultLimit,\n sourceRows: sourceResult.rows,\n detailRows: detailResult?.rows ?? [],\n totalUsers,\n sourceDiscovery: evidence(sourceResult),\n detail: detailEvidence,\n totalUsersEvidence,\n });\n}\n//# sourceMappingURL=ai-referrals.js.map","function normalizedDirective(value) {\n const directive = value.trim().toLowerCase().split(/\\s+/)[0];\n if (directive === 'none')\n return ['noindex', 'nofollow'];\n if (directive === 'noindex' ||\n directive === 'nofollow' ||\n directive === 'nosnippet') {\n return [directive];\n }\n return [];\n}\nfunction values(value) {\n if (Array.isArray(value))\n return value;\n return value ? [value] : [];\n}\nfunction metaDirectiveTokens(value) {\n return values(value).flatMap((item) => item\n .split(',')\n .map((token) => token.trim())\n .filter(Boolean));\n}\nfunction xDirectiveTokens(value, userAgent = 'googlebot') {\n const requestedAgent = userAgent.toLowerCase();\n const tokens = [];\n for (const item of values(value)) {\n let scopedAgent;\n for (const rawToken of item.split(',')) {\n const token = rawToken.trim();\n if (!token)\n continue;\n const scoped = token.match(/^([a-z][a-z0-9_-]*):\\s*(.*)$/i);\n const prefix = scoped?.[1]?.toLowerCase();\n const parameterizedDirective = prefix === 'unavailable_after' || prefix?.startsWith('max-');\n if (scoped && !parameterizedDirective) {\n scopedAgent = prefix;\n const directiveValue = scoped[2]?.trim();\n if (scopedAgent === requestedAgent && directiveValue) {\n tokens.push(directiveValue);\n }\n continue;\n }\n if (scopedAgent && scopedAgent !== requestedAgent)\n continue;\n tokens.push(token);\n }\n }\n return tokens;\n}\nexport function combineRobotsValues(value) {\n const combined = value\n .map((item) => item?.trim())\n .filter((item) => Boolean(item))\n .join(', ');\n return combined || undefined;\n}\nexport function metaRobotsDirectives(value) {\n const directives = new Set();\n for (const token of metaDirectiveTokens(value)) {\n for (const directive of normalizedDirective(token)) {\n directives.add(directive);\n }\n }\n return directives;\n}\nexport function xRobotsDirectives(value, userAgent = 'googlebot') {\n const directives = new Set();\n for (const token of xDirectiveTokens(value, userAgent)) {\n for (const directive of normalizedDirective(token)) {\n directives.add(directive);\n }\n }\n return directives;\n}\nexport function hasMetaRobotsDirective(value, directive) {\n return metaRobotsDirectives(value).has(directive);\n}\nexport function hasXRobotsDirective(value, directive) {\n return xRobotsDirectives(value).has(directive);\n}\nexport function effectiveRobotsDirectives(input) {\n return new Set([\n ...metaRobotsDirectives(input.metaRobots),\n ...xRobotsDirectives(input.xRobotsTag),\n ]);\n}\nfunction snippetEvidence(source, tokens) {\n const evidence = [];\n for (const raw of tokens) {\n const normalized = raw.trim().toLowerCase();\n if (normalized === 'nosnippet') {\n evidence.push({ source, directive: 'nosnippet', raw });\n continue;\n }\n const match = normalized.match(/^max-snippet\\s*:\\s*(-?\\d+)$/);\n if (!match)\n continue;\n const value = Number(match[1]);\n if (!Number.isSafeInteger(value) || value < -1)\n continue;\n evidence.push({ source, directive: 'max-snippet', raw, value });\n }\n return evidence;\n}\nexport function effectiveSnippetControl(input) {\n const evidence = [\n ...snippetEvidence('meta-robots', metaDirectiveTokens(input.metaRobots)),\n ...snippetEvidence('x-robots-tag', xDirectiveTokens(input.xRobotsTag)),\n ];\n const hasNoSnippet = evidence.some((item) => item.directive === 'nosnippet');\n const limits = evidence\n .filter((item) => item.directive === 'max-snippet' && item.value !== undefined)\n .map((item) => item.value);\n if (hasNoSnippet) {\n return {\n status: 'blocked',\n reason: 'nosnippet',\n maxCharacters: 0,\n evidence,\n };\n }\n if (limits.includes(0)) {\n return {\n status: 'blocked',\n reason: 'max-snippet-zero',\n maxCharacters: 0,\n evidence,\n };\n }\n const positiveLimits = limits.filter((value) => value > 0);\n if (positiveLimits.length) {\n return {\n status: 'limited',\n reason: 'max-snippet-limit',\n maxCharacters: Math.min(...positiveLimits),\n evidence,\n };\n }\n return {\n status: 'not-restricted',\n reason: 'no-restrictive-directive',\n evidence,\n };\n}\n//# sourceMappingURL=robots-directives.js.map","function headerValue(headers, name) {\n const lower = name.toLowerCase();\n return Object.entries(headers).find(([key]) => key.toLowerCase() === lower)?.[1];\n}\nfunction resolvedCandidate(source, raw, baseUrl, ignoredReason) {\n if (!raw)\n return { source, raw, ignoredReason: 'invalid-url' };\n try {\n const url = new URL(raw, baseUrl);\n if (!['http:', 'https:'].includes(url.protocol)) {\n return { source, raw, ignoredReason: 'non-http-url' };\n }\n if (url.hash) {\n return {\n source,\n raw,\n resolved: url.toString(),\n ignoredReason: 'fragment',\n };\n }\n return {\n source,\n raw,\n resolved: url.toString(),\n ...(ignoredReason ? { ignoredReason } : {}),\n };\n }\n catch {\n return { source, raw, ignoredReason: 'invalid-url' };\n }\n}\nfunction htmlCandidates($, baseUrl) {\n const candidates = [];\n $('link[rel]').each((_index, element) => {\n const rel = ($(element).attr('rel') ?? '')\n .toLowerCase()\n .split(/\\s+/)\n .filter(Boolean);\n if (!rel.includes('canonical'))\n return;\n const raw = ($(element).attr('href') ?? '').trim();\n const source = $(element).closest('head').length\n ? 'html-head'\n : 'html-body';\n const alternateQualifier = ['hreflang', 'lang', 'media', 'type'].some((attribute) => $(element).attr(attribute) !== undefined);\n candidates.push(resolvedCandidate(source, raw, baseUrl, source === 'html-body'\n ? 'outside-head'\n : alternateQualifier\n ? 'alternate-qualifier'\n : undefined));\n });\n return candidates;\n}\nfunction splitLinkHeader(value) {\n const parts = [];\n let start = 0;\n let angle = false;\n let quote;\n for (let index = 0; index < value.length; index += 1) {\n const character = value[index];\n if (quote) {\n if (character === quote && value[index - 1] !== '\\\\')\n quote = undefined;\n continue;\n }\n if (character === '\"' || character === \"'\") {\n quote = character;\n continue;\n }\n if (character === '<')\n angle = true;\n else if (character === '>')\n angle = false;\n else if (character === ',' && !angle) {\n parts.push(value.slice(start, index).trim());\n start = index + 1;\n }\n }\n parts.push(value.slice(start).trim());\n return parts.filter(Boolean);\n}\nfunction parameter(value, name) {\n const expression = new RegExp(`(?:^|;)\\\\s*${name}\\\\s*=\\\\s*(?:\"([^\"]*)\"|'([^']*)'|([^;\\\\s]+))`, 'i');\n const match = value.match(expression);\n return match?.[1] ?? match?.[2] ?? match?.[3];\n}\nfunction headerCandidates(headers, baseUrl) {\n const link = headerValue(headers, 'link');\n if (!link)\n return [];\n const candidates = [];\n for (const item of splitLinkHeader(link)) {\n const match = item.match(/^\\s*<([^>]*)>(.*)$/s);\n if (!match?.[1])\n continue;\n const rel = parameter(match[2] ?? '', 'rel')\n ?.toLowerCase()\n .split(/\\s+/)\n .filter(Boolean);\n if (!rel?.includes('canonical'))\n continue;\n const alternateQualifier = ['hreflang', 'lang', 'media', 'type'].some((name) => parameter(match[2] ?? '', name) !== undefined);\n candidates.push(resolvedCandidate('http-header', match[1], baseUrl, alternateQualifier ? 'alternate-qualifier' : undefined));\n }\n return candidates;\n}\nfunction normalizedUrl(value) {\n const url = new URL(value);\n url.hash = '';\n return url.toString();\n}\nfunction evidenceFromCandidates(candidates) {\n const eligible = candidates.filter((candidate) => candidate.resolved && !candidate.ignoredReason);\n const distinct = [\n ...new Set(eligible.map((candidate) => normalizedUrl(candidate.resolved ?? ''))),\n ];\n if (distinct.length > 1) {\n return { status: 'conflicting', candidates };\n }\n if (distinct.length === 1) {\n const selected = eligible[0];\n return {\n status: eligible.length > 1 ? 'duplicate' : 'single',\n selectedRaw: selected?.raw,\n selectedUrl: selected?.resolved,\n candidates,\n };\n }\n if (candidates.some((candidate) => candidate.source === 'html-body')) {\n return { status: 'outside-head-only', candidates };\n }\n if (candidates.length)\n return { status: 'invalid', candidates };\n return { status: 'missing', candidates };\n}\nexport function extractHttpCanonicalEvidence(headers, baseUrl) {\n return evidenceFromCandidates(headerCandidates(headers, baseUrl));\n}\nexport function extractCanonicalEvidence($, headers, baseUrl) {\n return evidenceFromCandidates([\n ...htmlCandidates($, baseUrl),\n ...headerCandidates(headers, baseUrl),\n ]);\n}\n//# sourceMappingURL=canonical.js.map","import { Readability } from '@mozilla/readability';\nimport { load } from 'cheerio';\nimport Defuddle from 'defuddle';\nimport { parseHTML } from 'linkedom';\nfunction readableError(error) {\n return error instanceof Error ? error.message : String(error);\n}\nfunction normalizedText(value) {\n const text = value?.replace(/\\s+/g, ' ').trim();\n return text || undefined;\n}\nfunction countCjkAwareWords(text) {\n let count = 0;\n let inWord = false;\n for (const character of text) {\n if (/\\p{Script=Han}|\\p{Script=Hiragana}|\\p{Script=Katakana}|\\p{Script=Hangul}/u.test(character)) {\n count += 1;\n inWord = false;\n }\n else if (/\\s/u.test(character)) {\n inWord = false;\n }\n else if (!inWord) {\n count += 1;\n inWord = true;\n }\n }\n return count;\n}\nfunction resolveDocumentUrls(document, baseUrl) {\n for (const element of document.querySelectorAll('[href], [src]')) {\n for (const attribute of ['href', 'src']) {\n const value = element.getAttribute(attribute);\n if (!value)\n continue;\n try {\n element.setAttribute(attribute, new URL(value, baseUrl).toString());\n }\n catch {\n // Leave non-URL schemes and malformed evidence unchanged.\n }\n }\n }\n}\nfunction readabilityResult(fetchResult, requested, fallbackReason, fallbackDetail) {\n const { document } = parseHTML(fetchResult.html);\n const bodyText = document.body.textContent ?? '';\n const article = new Readability(document).parse();\n const text = article?.textContent ?? bodyText;\n const fallback = requested !== 'readability';\n const diagnostics = {\n requested,\n used: 'readability',\n fallback,\n wordCountSource: 'local_cjk_aware',\n baseUrl: fetchResult.finalUrl,\n ...(fallback\n ? {\n fallbackReason,\n fallbackDetail,\n }\n : {}),\n };\n return {\n text,\n excerpt: normalizedText(article?.excerpt),\n wordCount: countCjkAwareWords(text),\n diagnostics,\n warnings: fallback && fallbackDetail\n ? [`Defuddle extraction fell back to Readability: ${fallbackDetail}`]\n : [],\n };\n}\nfunction defaultParseDefuddle(document, options) {\n const DefuddleConstructor = Defuddle;\n return new DefuddleConstructor(document, options).parse();\n}\nexport function extractMainContent(fetchResult, extractor = 'defuddle', dependencies = {}) {\n if (extractor === 'readability') {\n return readabilityResult(fetchResult, extractor);\n }\n try {\n const { document } = parseHTML(fetchResult.html);\n resolveDocumentUrls(document, fetchResult.finalUrl);\n const article = (dependencies.parseDefuddle ?? defaultParseDefuddle)(document, { url: fetchResult.finalUrl, useAsync: false });\n const text = typeof article.content === 'string'\n ? load(article.content).text()\n : (document.body.textContent ?? '');\n if (!text.trim()) {\n return readabilityResult(fetchResult, extractor, 'defuddle_empty', 'Defuddle returned no main content');\n }\n const reportedWordCount = article.wordCount;\n const hasValidWordCount = typeof reportedWordCount === 'number' &&\n Number.isFinite(reportedWordCount) &&\n reportedWordCount >= 0;\n const extractorType = normalizedText(article.extractorType);\n return {\n text,\n excerpt: normalizedText(article.description),\n wordCount: hasValidWordCount\n ? Math.floor(reportedWordCount)\n : countCjkAwareWords(text),\n diagnostics: {\n requested: extractor,\n used: 'defuddle',\n fallback: false,\n wordCountSource: hasValidWordCount ? 'defuddle' : 'local_cjk_aware',\n baseUrl: fetchResult.finalUrl,\n ...(extractorType ? { extractorType } : {}),\n },\n warnings: [],\n };\n }\n catch (error) {\n return readabilityResult(fetchResult, extractor, 'defuddle_error', readableError(error));\n }\n}\n//# sourceMappingURL=main-content.js.map","const SUPPORTED_TYPES = new Set([\n 'Article',\n 'BlogPosting',\n 'NewsArticle',\n 'Product',\n 'BreadcrumbList',\n 'FAQPage',\n]);\nconst ASSESSMENT_STATUSES = [\n 'no-required-properties',\n 'required-properties-observed',\n 'missing-required-properties',\n 'retired',\n 'not-assessed',\n];\nexport const GOOGLE_RICH_RESULT_ASSESSMENT_LIMIT = 50;\nfunction isSupportedType(value) {\n return SUPPORTED_TYPES.has(value);\n}\nconst ARTICLE_DOC = 'https://developers.google.com/search/docs/appearance/structured-data/article';\nconst PRODUCT_DOC = 'https://developers.google.com/search/docs/appearance/structured-data/product-snippet';\nconst BREADCRUMB_DOC = 'https://developers.google.com/search/docs/appearance/structured-data/breadcrumb';\nconst FAQ_DOC = 'https://developers.google.com/search/updates#removing-faq-rich-result';\nfunction hasValue(value) {\n if (typeof value === 'string')\n return value.trim().length > 0;\n if (typeof value === 'number')\n return Number.isFinite(value);\n if (typeof value === 'boolean')\n return true;\n if (Array.isArray(value))\n return value.some(hasValue);\n return Boolean(value &&\n typeof value === 'object' &&\n Object.values(value).some(hasValue));\n}\nfunction isRecord(value) {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\nfunction isNonEmptyText(value) {\n return typeof value === 'string' && value.trim().length > 0;\n}\nfunction schemaTypeName(value) {\n const trimmed = value.trim();\n if (trimmed.startsWith('schema:'))\n return trimmed.slice('schema:'.length);\n try {\n const url = new URL(trimmed);\n if (url.hostname.replace(/^www\\./, '').toLowerCase() === 'schema.org') {\n return decodeURIComponent(url.pathname.replace(/^\\/+/, ''));\n }\n }\n catch {\n // A compact Schema.org type is expected in the common case.\n }\n return trimmed;\n}\nfunction hasSchemaType(record, expected) {\n const values = Array.isArray(record['@type'])\n ? record['@type']\n : [record['@type']];\n return values.some((value) => typeof value === 'string' && expected.includes(schemaTypeName(value)));\n}\nfunction hasTypedObject(value, predicate) {\n return (Array.isArray(value) ? value : [value]).some((item) => isRecord(item) && predicate(item));\n}\nfunction isFiniteNumericValue(value) {\n if (typeof value === 'number')\n return Number.isFinite(value);\n return (typeof value === 'string' &&\n value.trim().length > 0 &&\n Number.isFinite(Number(value)));\n}\nfunction isPositiveInteger(value) {\n return typeof value === 'number' && Number.isInteger(value) && value > 0;\n}\nfunction isRatingValue(value) {\n if (isFiniteNumericValue(value))\n return true;\n if (typeof value !== 'string')\n return false;\n return /^(?:\\d+(?:\\.\\d+)?\\s*%|\\d+(?:\\.\\d+)?\\s*\\/\\s*\\d+(?:\\.\\d+)?)$/.test(value.trim());\n}\nfunction isNamedReviewAuthor(value) {\n return hasTypedObject(value, (author) => hasSchemaType(author, ['Person', 'Organization']) &&\n isNonEmptyText(author.name) &&\n author.name.trim().length < 100);\n}\nfunction isRating(value) {\n return hasTypedObject(value, (rating) => hasSchemaType(rating, ['Rating', 'AggregateRating']) &&\n isRatingValue(rating.ratingValue));\n}\nfunction isReview(value) {\n return hasTypedObject(value, (review) => hasSchemaType(review, ['Review']) &&\n isNamedReviewAuthor(review.author) &&\n isRating(review.reviewRating));\n}\nfunction isAggregateRating(value) {\n return hasTypedObject(value, (rating) => hasSchemaType(rating, ['AggregateRating']) &&\n isRatingValue(rating.ratingValue) &&\n [rating.ratingCount, rating.reviewCount].some(isPositiveInteger));\n}\nfunction isPriceSpecification(value) {\n return hasTypedObject(value, (specification) => hasSchemaType(specification, [\n 'PriceSpecification',\n 'UnitPriceSpecification',\n ]) && isFiniteNumericValue(specification.price));\n}\nfunction isOffer(value) {\n return hasTypedObject(value, (offer) => {\n if (hasSchemaType(offer, ['Offer'])) {\n return (isFiniteNumericValue(offer.price) ||\n isPriceSpecification(offer.priceSpecification));\n }\n if (hasSchemaType(offer, ['AggregateOffer'])) {\n return (isFiniteNumericValue(offer.lowPrice) &&\n isNonEmptyText(offer.priceCurrency));\n }\n return false;\n });\n}\nfunction isUrlReference(value) {\n if (!isNonEmptyText(value) || /\\s/.test(value))\n return false;\n try {\n const url = new URL(value, 'https://example.invalid/');\n return url.protocol === 'http:' || url.protocol === 'https:';\n }\n catch {\n return false;\n }\n}\nfunction isBreadcrumbTarget(value) {\n if (isUrlReference(value))\n return true;\n return isRecord(value) && isUrlReference(value['@id']);\n}\nfunction observedProperties(record) {\n return Object.keys(record)\n .filter((key) => !key.startsWith('@') && hasValue(record[key]))\n .sort();\n}\nfunction baseAssessment(input, feature, record, documentationUrl) {\n return {\n format: 'json-ld',\n block: input.block,\n path: input.path,\n schemaType: input.schemaType,\n feature,\n observedProperties: observedProperties(record),\n documentationUrl,\n };\n}\nfunction productAssessment(input, record) {\n const missing = [];\n if (!isNonEmptyText(record.name))\n missing.push('name');\n if (![\n isReview(record.review),\n isAggregateRating(record.aggregateRating),\n isOffer(record.offers),\n ].some(Boolean)) {\n missing.push('one of review, aggregateRating, or offers');\n }\n return {\n ...baseAssessment(input, 'product-snippet', record, PRODUCT_DOC),\n status: missing.length\n ? 'missing-required-properties'\n : 'required-properties-observed',\n missingRequiredProperties: missing,\n limitations: [\n 'This checks documented Product name and minimal nested Review, AggregateRating, Offer, or AggregateOffer value shapes. Recommended properties, value ranges, and feature-specific policy requirements are not fully validated.',\n 'Visible-content parity, crawlability, Search policies, and actual rich-result eligibility require Google validation.',\n ],\n };\n}\nfunction breadcrumbAssessment(input, record) {\n const rawItems = record.itemListElement;\n const items = Array.isArray(rawItems) ? rawItems : [];\n const missing = [];\n if (items.length < 2) {\n missing.push('itemListElement with at least two ListItem values');\n }\n items.forEach((value, index) => {\n if (!isRecord(value)) {\n missing.push(`itemListElement[${index}] ListItem object`);\n return;\n }\n const item = value;\n if (!hasSchemaType(item, ['ListItem'])) {\n missing.push(`itemListElement[${index}].@type ListItem`);\n }\n if (!isPositiveInteger(item.position)) {\n missing.push(`itemListElement[${index}].position`);\n }\n const target = item.item;\n const targetName = isRecord(target) ? target.name : undefined;\n if (!isNonEmptyText(item.name) && !isNonEmptyText(targetName)) {\n missing.push(`itemListElement[${index}].name`);\n }\n if ((index < items.length - 1 || target !== undefined) &&\n !isBreadcrumbTarget(target)) {\n missing.push(`itemListElement[${index}].item`);\n }\n });\n return {\n ...baseAssessment(input, 'breadcrumb', record, BREADCRUMB_DOC),\n status: missing.length\n ? 'missing-required-properties'\n : 'required-properties-observed',\n missingRequiredProperties: missing,\n limitations: [\n 'This checks ListItem typing, positive integer positions, non-empty names, and URL or @id target shapes. Visible breadcrumb parity, target crawlability, and Search policies are not verified.',\n 'Observed properties do not guarantee that Google will show a breadcrumb rich result.',\n ],\n };\n}\nfunction articleAssessment(input, record) {\n return {\n ...baseAssessment(input, 'article', record, ARTICLE_DOC),\n status: 'no-required-properties',\n missingRequiredProperties: [],\n limitations: [\n 'Google currently lists no required Article properties; author, dates, headline, and image are recommended where applicable.',\n 'Visible-content parity, image crawlability, Search policies, and actual appearance are not verified.',\n ],\n };\n}\nfunction faqAssessment(input, record) {\n return {\n ...baseAssessment(input, 'faq', record, FAQ_DOC),\n status: 'retired',\n missingRequiredProperties: [],\n limitations: [\n 'Google says the FAQ rich-result feature stopped appearing in Search on May 7, 2026 and removed its documentation in June 2026.',\n 'FAQPage can remain machine-readable Schema.org markup, but it is not a current Google rich-result opportunity.',\n ],\n };\n}\nexport function assessGoogleRichResults(input) {\n return input.nodeTypes.flatMap((schemaType) => {\n if (schemaType === 'Product') {\n return [productAssessment({ ...input, schemaType }, input.record)];\n }\n if (schemaType === 'BreadcrumbList') {\n return [breadcrumbAssessment({ ...input, schemaType }, input.record)];\n }\n if (schemaType === 'Article' ||\n schemaType === 'BlogPosting' ||\n schemaType === 'NewsArticle') {\n return [articleAssessment({ ...input, schemaType }, input.record)];\n }\n if (schemaType === 'FAQPage') {\n return [faqAssessment({ ...input, schemaType }, input.record)];\n }\n return [];\n });\n}\nexport function unassessedGoogleRichResult(input) {\n if (!isSupportedType(input.schemaType))\n return [];\n const schemaType = input.schemaType;\n const metadata = (() => {\n if (schemaType === 'Product') {\n return {\n feature: 'product-snippet',\n documentationUrl: PRODUCT_DOC,\n };\n }\n if (schemaType === 'BreadcrumbList') {\n return {\n feature: 'breadcrumb',\n documentationUrl: BREADCRUMB_DOC,\n };\n }\n if (schemaType === 'Article' ||\n schemaType === 'BlogPosting' ||\n schemaType === 'NewsArticle') {\n return { feature: 'article', documentationUrl: ARTICLE_DOC };\n }\n if (schemaType === 'FAQPage') {\n return { feature: 'faq', documentationUrl: FAQ_DOC };\n }\n return undefined;\n })();\n if (!metadata)\n return [];\n return [\n {\n format: input.format,\n path: `${input.format}:${schemaType}`,\n schemaType,\n feature: metadata.feature,\n status: 'not-assessed',\n observedProperties: [],\n missingRequiredProperties: [],\n limitations: [\n `${input.format} type evidence was detected, but property-level extraction is not available for this format.`,\n 'No rich-result completeness or eligibility conclusion was made.',\n ],\n documentationUrl: metadata.documentationUrl,\n },\n ];\n}\nfunction emptyStatusCounts() {\n return Object.fromEntries(ASSESSMENT_STATUSES.map((status) => [status, 0]));\n}\nfunction statusCounts(assessments) {\n const counts = emptyStatusCounts();\n for (const assessment of assessments)\n counts[assessment.status] += 1;\n return counts;\n}\nfunction compareCodepoints(left, right) {\n if (left === right)\n return 0;\n return left < right ? -1 : 1;\n}\nfunction assessmentSortKey(assessment) {\n return JSON.stringify([\n assessment.schemaType,\n assessment.format,\n assessment.block ?? -1,\n assessment.path,\n assessment.status,\n assessment.observedProperties,\n assessment.missingRequiredProperties,\n assessment.limitations,\n assessment.documentationUrl,\n ]);\n}\n/**\n * Bounds stored assessment detail without letting successful examples displace\n * missing-required-property evidence. Full status counts remain available when\n * even the failure set is larger than the detail limit.\n */\nexport function selectGoogleRichResultAssessments(assessments, limit = GOOGLE_RICH_RESULT_ASSESSMENT_LIMIT) {\n if (!Number.isInteger(limit) || limit < 0) {\n throw new Error('Google rich-result assessment limit must be a whole number.');\n }\n const ordered = [...assessments].sort((left, right) => {\n const leftPriority = left.status === 'missing-required-properties' ? 0 : 1;\n const rightPriority = right.status === 'missing-required-properties' ? 0 : 1;\n return (leftPriority - rightPriority ||\n compareCodepoints(assessmentSortKey(left), assessmentSortKey(right)));\n });\n const returned = ordered.slice(0, limit);\n const eligibleByStatus = statusCounts(ordered);\n const returnedByStatus = statusCounts(returned);\n const omittedByStatus = emptyStatusCounts();\n for (const status of ASSESSMENT_STATUSES) {\n omittedByStatus[status] =\n eligibleByStatus[status] - returnedByStatus[status];\n }\n return {\n assessments: returned,\n selection: {\n limit,\n eligible: ordered.length,\n returned: returned.length,\n omitted: ordered.length - returned.length,\n partial: returned.length < ordered.length,\n eligibleByStatus,\n returnedByStatus,\n omittedByStatus,\n },\n };\n}\n//# sourceMappingURL=google-rich-results.js.map","import { assessGoogleRichResults, unassessedGoogleRichResult, } from './google-rich-results.js';\nfunction schemaTypeFromIri(value) {\n try {\n const iri = new URL(value);\n const host = iri.hostname.replace(/^www\\./, '').toLowerCase();\n if (host !== 'schema.org')\n return undefined;\n const type = decodeURIComponent(iri.pathname.replace(/^\\/+/, ''));\n return /^[A-Za-z][A-Za-z0-9]*$/.test(type) ? type : undefined;\n }\n catch {\n return undefined;\n }\n}\nfunction contextFrom(parent, value) {\n const next = {\n vocab: parent.vocab,\n unresolvedContext: parent.unresolvedContext,\n prefixes: new Map(parent.prefixes),\n };\n const apply = (context) => {\n if (Array.isArray(context)) {\n for (const item of context)\n apply(item);\n return;\n }\n if (typeof context === 'string') {\n if (schemaTypeFromIri(`${context.replace(/\\/?$/, '/')}Thing`)) {\n next.vocab = context;\n next.unresolvedContext = false;\n }\n else {\n next.unresolvedContext = true;\n }\n return;\n }\n if (!context || typeof context !== 'object')\n return;\n for (const [term, definition] of Object.entries(context)) {\n if (term === '@vocab' && typeof definition === 'string') {\n next.vocab = definition;\n next.unresolvedContext = false;\n }\n else if (typeof definition === 'string') {\n next.prefixes.set(term, definition);\n }\n else if (definition &&\n typeof definition === 'object' &&\n typeof definition['@id'] === 'string') {\n next.prefixes.set(term, definition['@id'] ?? '');\n }\n }\n };\n apply(value);\n return next;\n}\nfunction normalizedSchemaType(value, context) {\n const direct = schemaTypeFromIri(value);\n if (direct)\n return { type: direct };\n const separator = value.indexOf(':');\n if (separator > 0) {\n const prefix = value.slice(0, separator);\n const suffix = value.slice(separator + 1);\n const base = context.prefixes.get(prefix);\n const expanded = base ? schemaTypeFromIri(`${base}${suffix}`) : undefined;\n return expanded ? { type: expanded } : { reason: 'unsupported-vocabulary' };\n }\n if (context.vocab) {\n const expanded = schemaTypeFromIri(`${context.vocab.replace(/\\/?$/, '/')}${value}`);\n return expanded ? { type: expanded } : { reason: 'unsupported-vocabulary' };\n }\n return {\n reason: context.unresolvedContext\n ? 'unresolved-context'\n : 'missing-schema-context',\n };\n}\nfunction usableAuthor(value) {\n if (typeof value === 'string')\n return value.trim().length > 0;\n if (Array.isArray(value))\n return value.some(usableAuthor);\n if (!value || typeof value !== 'object')\n return false;\n const record = value;\n return usableAuthor(record.name);\n}\nexport function isValidStructuredDate(value) {\n if (Array.isArray(value))\n return value.some(isValidStructuredDate);\n if (typeof value !== 'string')\n return false;\n const trimmed = value.trim();\n const datePart = trimmed.match(/^(\\d{4})-(\\d{2})-(\\d{2})/)?.[0];\n if (!datePart)\n return false;\n const parsed = new Date(trimmed);\n return (Number.isFinite(parsed.getTime()) &&\n parsed.toISOString().slice(0, 10) === datePart);\n}\nfunction parseJsonLd(blocks, baseUrl) {\n const jsonLd = [];\n const invalidJsonLdSamples = [];\n const unrecognizedJsonLdTypes = [];\n const sameAs = [];\n const invalidSameAs = [];\n const schemaTypes = new Set();\n const googleRichResults = [];\n let hasAuthor = false;\n let hasDate = false;\n const visit = (node, context, block, path) => {\n if (Array.isArray(node)) {\n node.forEach((item, index) => {\n visit(item, context, block, `${path}[${index}]`);\n });\n return;\n }\n if (!node || typeof node !== 'object')\n return;\n const record = node;\n const active = contextFrom(context, record['@context']);\n const rawTypes = Array.isArray(record['@type'])\n ? record['@type']\n : [record['@type']];\n const nodeTypes = [];\n for (const rawType of rawTypes) {\n if (typeof rawType !== 'string' || !rawType.trim())\n continue;\n const normalized = normalizedSchemaType(rawType.trim(), active);\n if (normalized.type) {\n schemaTypes.add(normalized.type);\n nodeTypes.push(normalized.type);\n }\n else if (normalized.reason) {\n unrecognizedJsonLdTypes.push({\n block,\n path: `${path}.@type`,\n value: rawType,\n reason: normalized.reason,\n });\n }\n }\n if (nodeTypes.length) {\n googleRichResults.push(...assessGoogleRichResults({ block, path, nodeTypes, record }));\n hasAuthor ||= usableAuthor(record.author);\n hasDate ||=\n isValidStructuredDate(record.datePublished) ||\n isValidStructuredDate(record.dateModified);\n const rawSameAs = Array.isArray(record.sameAs)\n ? record.sameAs\n : [record.sameAs];\n const subjectId = typeof record['@id'] === 'string'\n ? absoluteHttpUrl(record['@id'], baseUrl)\n : undefined;\n rawSameAs.forEach((value, index) => {\n if (typeof value !== 'string' || !value.trim())\n return;\n const itemPath = `${path}.sameAs${rawSameAs.length > 1 ? `[${index}]` : ''}`;\n const url = absoluteHttpUrl(value, baseUrl);\n if (url) {\n sameAs.push({\n url,\n block,\n path: itemPath,\n subjectId,\n subjectTypes: nodeTypes,\n });\n }\n else {\n invalidSameAs.push({ block, path: itemPath, value });\n }\n });\n }\n for (const [key, value] of Object.entries(record)) {\n if (key === '@context')\n continue;\n visit(value, active, block, `${path}.${key}`);\n }\n };\n blocks.forEach((block, index) => {\n try {\n const parsed = JSON.parse(block);\n jsonLd.push(parsed);\n visit(parsed, { prefixes: new Map() }, index, '$');\n }\n catch (error) {\n invalidJsonLdSamples.push({\n snippet: block.replace(/\\s+/g, ' ').trim().slice(0, 200),\n error: error instanceof Error ? error.message : String(error),\n });\n }\n });\n return {\n jsonLd,\n invalidJsonLdSamples,\n unrecognizedJsonLdTypes,\n sameAs,\n invalidSameAs,\n schemaTypes: [...schemaTypes],\n googleRichResults,\n hasAuthor,\n hasDate,\n };\n}\nfunction absoluteHttpUrl(value, baseUrl) {\n try {\n const url = new URL(value, baseUrl);\n return ['http:', 'https:'].includes(url.protocol)\n ? url.toString()\n : undefined;\n }\n catch {\n return undefined;\n }\n}\nfunction microdataTypes($) {\n const types = new Set();\n $('[itemscope][itemtype]').each((_index, element) => {\n const values = ($(element).attr('itemtype') ?? '').split(/\\s+/);\n for (const value of values) {\n const type = schemaTypeFromIri(value);\n if (type)\n types.add(type);\n }\n });\n return [...types];\n}\nfunction rdfaTypes($) {\n const types = new Set();\n $('[typeof]').each((_index, element) => {\n const active = contextFrom({ prefixes: new Map() }, $(element).closest('[vocab]').attr('vocab'));\n const prefixValue = $(element).closest('[prefix]').attr('prefix');\n if (prefixValue) {\n const pairs = [...prefixValue.matchAll(/([\\w-]+):\\s+(\\S+)/g)];\n for (const pair of pairs) {\n if (pair[1] && pair[2])\n active.prefixes.set(pair[1], pair[2]);\n }\n }\n for (const value of ($(element).attr('typeof') ?? '').split(/\\s+/)) {\n const type = normalizedSchemaType(value, active).type;\n if (type)\n types.add(type);\n }\n });\n return [...types];\n}\nfunction usableElementValue($, selector) {\n return $(selector)\n .toArray()\n .some((element) => {\n const value = $(element).attr('content') ??\n $(element).attr('datetime') ??\n $(element).text();\n return value.trim().length > 0;\n });\n}\nexport function extractStructuredData($, baseUrl) {\n const parsed = parseJsonLd($('script[type=\"application/ld+json\"]')\n .toArray()\n .map((element) => $(element).html() ?? ''), baseUrl);\n const microdata = microdataTypes($);\n const rdfa = rdfaTypes($);\n const schemaTypes = [\n ...new Set([...parsed.schemaTypes, ...microdata, ...rdfa]),\n ];\n const formats = [];\n if (parsed.schemaTypes.length)\n formats.push('json-ld');\n if (microdata.length)\n formats.push('microdata');\n if (rdfa.length)\n formats.push('rdfa');\n const googleRichResults = [\n ...parsed.googleRichResults,\n ...microdata.flatMap((schemaType) => unassessedGoogleRichResult({ format: 'microdata', schemaType })),\n ...rdfa.flatMap((schemaType) => unassessedGoogleRichResult({ format: 'rdfa', schemaType })),\n ];\n return {\n ...parsed,\n schemaTypes,\n formats,\n googleRichResults,\n hasAuthor: parsed.hasAuthor ||\n usableElementValue($, '[itemprop~=\"author\"], [property~=\"author\"]'),\n hasDate: parsed.hasDate ||\n $('[itemprop~=\"datePublished\"], [itemprop~=\"dateModified\"], [property~=\"datePublished\"], [property~=\"dateModified\"]')\n .toArray()\n .some((element) => isValidStructuredDate($(element).attr('content') ??\n $(element).attr('datetime') ??\n $(element).text())),\n };\n}\n//# sourceMappingURL=structured-data.js.map","import { load } from 'cheerio';\nimport { combineRobotsValues } from '../robots-directives.js';\nimport { extractCanonicalEvidence } from './canonical.js';\nimport { extractMainContent, } from './main-content.js';\nimport { extractStructuredData, isValidStructuredDate, } from './structured-data.js';\nfunction safeText(value) {\n const trimmed = value?.replace(/\\s+/g, ' ').trim();\n return trimmed ? trimmed : undefined;\n}\nfunction headerValue(headers, name) {\n const target = name.toLowerCase();\n return Object.entries(headers).find(([key]) => key.toLowerCase() === target)?.[1];\n}\nfunction absoluteUrl(value, base) {\n if (!value)\n return undefined;\n try {\n return new URL(value, base).toString();\n }\n catch {\n return undefined;\n }\n}\nfunction httpUrl(value, base) {\n const resolved = absoluteUrl(value, base);\n if (!resolved)\n return undefined;\n const protocol = new URL(resolved).protocol;\n return protocol === 'http:' || protocol === 'https:' ? resolved : undefined;\n}\nfunction sanitizedContentHtml(html, base) {\n const $ = load(html);\n let changed = false;\n for (const element of $('[href], [src]').toArray()) {\n for (const attribute of ['href', 'src']) {\n const value = $(element).attr(attribute);\n if (value && !absoluteUrl(value, base)) {\n $(element).removeAttr(attribute);\n changed = true;\n }\n }\n }\n return changed ? $.html() : html;\n}\nfunction numericAttribute(value) {\n if (!value)\n return undefined;\n const match = value.trim().match(/^\\d+/);\n if (!match)\n return undefined;\n const number = Number(match[0]);\n return Number.isFinite(number) && number > 0 ? number : undefined;\n}\nfunction largestSrcsetWidth(value) {\n if (!value)\n return undefined;\n const widths = value\n .split(',')\n .map((candidate) => candidate.trim().match(/\\s(\\d+)w(?:\\s|$)/)?.[1])\n .filter((width) => Boolean(width))\n .map(Number)\n .filter((width) => Number.isFinite(width) && width > 0);\n return widths.length ? Math.max(...widths) : undefined;\n}\nfunction imageDimensionsFromUrl(src) {\n const match = src.match(/(?:^|[^\\d])(\\d{3,5})[xX](\\d{3,5})(?:[^\\d]|$)/);\n if (!match)\n return undefined;\n const width = Number(match[1]);\n const height = Number(match[2]);\n if (!Number.isFinite(width) || !Number.isFinite(height))\n return undefined;\n return { width, height };\n}\nexport async function extractPage(fetchResult, extractor = 'defuddle', dependencies = {}) {\n const $ = load(fetchResult.html);\n const content = extractMainContent({\n ...fetchResult,\n html: sanitizedContentHtml(fetchResult.html, fetchResult.finalUrl),\n }, extractor, dependencies);\n const { text, excerpt } = content;\n const url = new URL(fetchResult.finalUrl);\n const canonicalEvidence = extractCanonicalEvidence($, fetchResult.headers, fetchResult.finalUrl);\n const headings = $('h1, h2, h3, h4, h5, h6')\n .toArray()\n .map((element) => ({\n level: Number.parseInt(element.tagName.slice(1), 10),\n text: $(element).text().replace(/\\s+/g, ' ').trim(),\n }))\n .filter((heading) => heading.text.length > 0);\n const links = [];\n let invalidLinkCount = 0;\n let unsupportedLinkCount = 0;\n for (const element of $('a[href]').toArray()) {\n const href = $(element).attr('href') ?? '';\n try {\n const absolute = new URL(href, fetchResult.finalUrl);\n if (!['http:', 'https:'].includes(absolute.protocol)) {\n unsupportedLinkCount += 1;\n continue;\n }\n links.push({\n href: absolute.toString(),\n text: $(element).text().replace(/\\s+/g, ' ').trim(),\n rel: ($(element).attr('rel') ?? '').split(/\\s+/).filter(Boolean),\n internal: absolute.host === url.host,\n location: $(element).closest('nav, header').length\n ? 'navigation'\n : $(element).closest('footer').length\n ? 'footer'\n : $(element).closest('main, article').length\n ? 'main-content'\n : 'other',\n });\n }\n catch {\n invalidLinkCount += 1;\n }\n }\n const hreflang = [];\n let invalidHreflangCount = 0;\n for (const element of $('link[rel~=\"alternate\"][hreflang][href]').toArray()) {\n const language = $(element).attr('hreflang') ?? '';\n const href = httpUrl($(element).attr('href'), fetchResult.finalUrl);\n if (language && href) {\n hreflang.push({ hreflang: language, href });\n }\n else {\n invalidHreflangCount += 1;\n }\n }\n const openGraph = Object.fromEntries($('meta[property^=\"og:\"]')\n .toArray()\n .map((element) => [\n $(element).attr('property') ?? '',\n $(element).attr('content') ?? '',\n ])\n .filter(([key, value]) => key && value));\n const twitter = Object.fromEntries($('meta[name^=\"twitter:\"]')\n .toArray()\n .map((element) => [\n $(element).attr('name') ?? '',\n $(element).attr('content') ?? '',\n ])\n .filter(([key, value]) => key && value));\n const structuredData = extractStructuredData($, fetchResult.finalUrl);\n const hasDate = structuredData.hasDate ||\n isValidStructuredDate($('meta[property=\"article:published_time\"]').attr('content')) ||\n isValidStructuredDate($('meta[property=\"article:modified_time\"]').attr('content')) ||\n $('article time[datetime], main time[datetime]')\n .toArray()\n .some((element) => isValidStructuredDate($(element).attr('datetime')));\n const author = safeText($('meta[name=\"author\"]').attr('content'));\n const hasAuthor = Boolean(author) ||\n structuredData.hasAuthor ||\n $('[rel~=author], .author, .byline')\n .toArray()\n .some((element) => Boolean(safeText($(element).text())));\n const semanticHtml = $('main, article').length > 0;\n const questionHeadings = headings.filter((heading) => heading.text.trimEnd().endsWith('?')).length;\n const listCount = $('ul, ol').length;\n const tableCount = $('table').length;\n const structuredBlocks = listCount + tableCount;\n const answerable = $('main p, article p, p')\n .toArray()\n .slice(0, 3)\n .some((element) => $(element)\n .text()\n .replace(/\\s+/g, ' ')\n .trim()\n .split(/\\s+/)\n .filter(Boolean).length >= 25);\n const imageElements = $('img').toArray();\n const oversizedImageCandidates = imageElements\n .map((element) => {\n const src = absoluteUrl($(element).attr('src'), fetchResult.finalUrl);\n if (!src)\n return undefined;\n const width = numericAttribute($(element).attr('width'));\n const height = numericAttribute($(element).attr('height'));\n const srcsetWidth = largestSrcsetWidth($(element).attr('srcset'));\n const filenameDimensions = imageDimensionsFromUrl(src);\n const maxDetected = Math.max(width ?? 0, height ?? 0, srcsetWidth ?? 0, filenameDimensions?.width ?? 0, filenameDimensions?.height ?? 0);\n if (maxDetected < 2000)\n return undefined;\n const detectedFrom = [\n width && width >= 2000 ? 'width' : undefined,\n height && height >= 2000 ? 'height' : undefined,\n srcsetWidth && srcsetWidth >= 2000 ? 'srcset' : undefined,\n filenameDimensions &&\n (filenameDimensions.width >= 2000 || filenameDimensions.height >= 2000)\n ? 'filename'\n : undefined,\n ]\n .filter(Boolean)\n .join(',');\n const candidateWidth = Math.max(width ?? 0, srcsetWidth ?? 0, filenameDimensions?.width ?? 0);\n const candidateHeight = Math.max(height ?? 0, filenameDimensions?.height ?? 0);\n return {\n src,\n detectedFrom,\n ...(candidateWidth > 0 ? { width: candidateWidth } : {}),\n ...(candidateHeight > 0 ? { height: candidateHeight } : {}),\n };\n })\n .filter((candidate) => Boolean(candidate));\n const mixedContentUrls = url.protocol === 'https:'\n ? [\n ...new Set($('img[src], script[src], iframe[src], source[src], video[src], audio[src], link[href]')\n .toArray()\n .map((element) => absoluteUrl($(element).attr('src') ?? $(element).attr('href'), fetchResult.finalUrl))\n .filter((value) => typeof value === 'string' &&\n new URL(value).protocol === 'http:')),\n ]\n : [];\n const metaRobots = combineRobotsValues($('meta[name]')\n .toArray()\n .filter((element) => {\n const name = $(element).attr('name')?.trim().toLowerCase();\n return name === 'robots' || name === 'googlebot';\n })\n .map((element) => $(element).attr('content')));\n return {\n url: fetchResult.url,\n finalUrl: fetchResult.finalUrl,\n title: safeText($('title').first().text()),\n metaDescription: safeText($('meta[name=\"description\"]').attr('content')),\n metaRobots,\n xRobotsTag: safeText(headerValue(fetchResult.headers, 'x-robots-tag')),\n canonical: canonicalEvidence.selectedRaw,\n canonicalEvidence,\n lang: safeText($('html').attr('lang')),\n hasViewport: Boolean($('meta[name=\"viewport\"]').attr('content')),\n headings,\n links,\n hreflang,\n jsonLd: structuredData.jsonLd,\n invalidJsonLdCount: structuredData.invalidJsonLdSamples.length,\n invalidJsonLdSamples: structuredData.invalidJsonLdSamples.slice(0, 10),\n unrecognizedJsonLdTypes: structuredData.unrecognizedJsonLdTypes.slice(0, 25),\n structuredDataFormats: structuredData.formats,\n googleRichResults: structuredData.googleRichResults,\n schemaSameAsEvidence: structuredData.sameAs,\n invalidSchemaSameAs: structuredData.invalidSameAs,\n schemaTypes: structuredData.schemaTypes,\n openGraph,\n twitter,\n author,\n hasAuthor,\n hasDate,\n imagesTotal: imageElements.length,\n imagesMissingAlt: imageElements.filter((element) => {\n const alt = $(element).attr('alt');\n return alt === undefined;\n }).length,\n oversizedImageCandidates: oversizedImageCandidates.slice(0, 25),\n mixedContentUrls,\n semanticHtml,\n questionHeadings,\n listCount,\n tableCount,\n structuredBlocks,\n answerable,\n contentText: text.replace(/\\s+/g, ' ').trim(),\n excerpt,\n wordCount: content.wordCount,\n contentExtraction: content.diagnostics,\n warnings: [\n ...fetchResult.warnings,\n ...content.warnings,\n ...(structuredData.unrecognizedJsonLdTypes.length\n ? [\n `Ignored ${structuredData.unrecognizedJsonLdTypes.length} JSON-LD @type value${structuredData.unrecognizedJsonLdTypes.length === 1 ? '' : 's'} that did not resolve to Schema.org.`,\n ]\n : []),\n ...(structuredData.invalidSameAs.length\n ? [\n `Found ${structuredData.invalidSameAs.length} invalid or non-HTTP Schema.org sameAs value${structuredData.invalidSameAs.length === 1 ? '' : 's'}.`,\n ]\n : []),\n ...(invalidLinkCount\n ? [\n `Skipped ${invalidLinkCount} malformed link URL${invalidLinkCount === 1 ? '' : 's'}.`,\n ]\n : []),\n ...(unsupportedLinkCount\n ? [\n `Excluded ${unsupportedLinkCount} non-HTTP link URL${unsupportedLinkCount === 1 ? '' : 's'} from page link evidence.`,\n ]\n : []),\n ...(invalidHreflangCount\n ? [\n `Skipped ${invalidHreflangCount} invalid or non-HTTP hreflang URL${invalidHreflangCount === 1 ? '' : 's'}.`,\n ]\n : []),\n ],\n };\n}\n//# sourceMappingURL=page-extractor.js.map","import { fetch, Headers } from 'undici';\nimport UserAgent from 'user-agents';\nexport const BROWSER_USER_AGENT = new UserAgent({\n deviceCategory: 'desktop',\n}).toString();\nexport function requestHeaders(profile) {\n if (profile === 'bot') {\n return new Headers({\n accept: 'text/plain,*/*;q=0.8',\n 'accept-language': 'en-US,en;q=0.9',\n connection: 'close',\n 'user-agent': BROWSER_USER_AGENT,\n });\n }\n return new Headers({\n accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'accept-language': 'en-US,en;q=0.9',\n connection: 'close',\n 'sec-ch-ua-mobile': '?0',\n 'sec-ch-ua-platform': '\"macOS\"',\n 'upgrade-insecure-requests': '1',\n 'user-agent': BROWSER_USER_AGENT,\n });\n}\nexport function publicHttpFetch(url, input = {}) {\n const { profile = 'browser', headers, ...init } = input;\n const base = requestHeaders(profile);\n if (headers instanceof Headers) {\n for (const [key, value] of headers.entries()) {\n base.set(key, value);\n }\n }\n else if (Array.isArray(headers)) {\n for (const [key, value] of headers) {\n base.set(key, value);\n }\n }\n else if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n if (value !== undefined) {\n base.set(key, value);\n }\n }\n }\n return fetch(url, { ...init, headers: base });\n}\n//# sourceMappingURL=http-client.js.map","import PQueue from 'p-queue';\nconst HOST_QUEUES = new Map();\nconst HOST_HEALTH = new Map();\nexport class OriginBackpressureError extends Error {\n snapshot;\n constructor(snapshot) {\n super(`Origin backpressure stopped fetches for ${snapshot.host}: ${snapshot.reason ?? 'cooldown active'}`);\n this.name = 'OriginBackpressureError';\n this.snapshot = snapshot;\n }\n}\nfunction numberEnv(name, fallback) {\n const parsed = Number(process.env[name]);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n}\nfunction healthForHost(host) {\n const existing = HOST_HEALTH.get(host);\n if (existing)\n return existing;\n const health = {\n durations: [],\n consecutiveSlow: 0,\n consecutiveBlocked: 0,\n consecutiveErrors: 0,\n cooldownUntil: 0,\n stoppedUntil: 0,\n lastDelayMs: 0,\n };\n HOST_HEALTH.set(host, health);\n return health;\n}\nfunction delay(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\nfunction percentile(values, p) {\n if (!values.length)\n return undefined;\n const sorted = [...values].sort((a, b) => a - b);\n const index = Math.min(sorted.length - 1, Math.ceil(p * sorted.length) - 1);\n return sorted[index];\n}\nfunction snapshotForHost(host, status) {\n const health = healthForHost(host);\n const recentP95Ms = percentile(health.durations, 0.95);\n const cooldown = Math.max(health.cooldownUntil, health.stoppedUntil);\n return {\n host,\n status: status ??\n (Date.now() < health.stoppedUntil\n ? 'stopped'\n : Date.now() < health.cooldownUntil\n ? 'slowed'\n : 'ok'),\n reason: health.reason,\n delayMs: health.lastDelayMs,\n cooldownUntil: cooldown > Date.now() ? new Date(cooldown).toISOString() : undefined,\n consecutiveSlow: health.consecutiveSlow,\n consecutiveBlocked: health.consecutiveBlocked,\n consecutiveErrors: health.consecutiveErrors,\n recentP95Ms,\n };\n}\nexport function normalizeRateControls(rate) {\n return {\n concurrency: rate?.concurrency ?? numberEnv('SEO_FETCH_CONCURRENCY', 4),\n intervalCap: rate?.intervalCap ?? numberEnv('SEO_FETCH_INTERVAL_CAP', 4),\n intervalMs: rate?.intervalMs ?? numberEnv('SEO_FETCH_INTERVAL_MS', 1000),\n backpressure: {\n slowMs: rate?.backpressure?.slowMs ?? numberEnv('SEO_FETCH_SLOW_MS', 8_000),\n verySlowMs: rate?.backpressure?.verySlowMs ??\n numberEnv('SEO_FETCH_VERY_SLOW_MS', 15_000),\n maxConsecutiveSlow: rate?.backpressure?.maxConsecutiveSlow ??\n numberEnv('SEO_FETCH_MAX_SLOW', 3),\n maxConsecutiveBlocked: rate?.backpressure?.maxConsecutiveBlocked ??\n numberEnv('SEO_FETCH_MAX_BLOCKED', 2),\n maxConsecutiveErrors: rate?.backpressure?.maxConsecutiveErrors ??\n numberEnv('SEO_FETCH_MAX_ERRORS', 2),\n cooldownMs: rate?.backpressure?.cooldownMs ??\n numberEnv('SEO_FETCH_COOLDOWN_MS', 30_000),\n retryAfterCapMs: rate?.backpressure?.retryAfterCapMs ??\n numberEnv('SEO_FETCH_RETRY_AFTER_CAP_MS', 30_000),\n },\n };\n}\nexport function queueForHost(host, rate) {\n const key = `${host}:${rate.concurrency}:${rate.intervalCap}:${rate.intervalMs}`;\n const existing = HOST_QUEUES.get(key);\n if (existing) {\n return existing;\n }\n const queue = new PQueue({\n concurrency: rate.concurrency,\n intervalCap: rate.intervalCap,\n interval: rate.intervalMs,\n });\n HOST_QUEUES.set(key, queue);\n return queue;\n}\nexport function rateLimitDiagnostics(host, rate) {\n return {\n host,\n concurrency: rate.concurrency,\n intervalCap: rate.intervalCap,\n intervalMs: rate.intervalMs,\n };\n}\nexport function hostBackpressureSnapshot(host) {\n return snapshotForHost(host);\n}\nexport async function waitForHostBackpressure(host, rate) {\n const health = healthForHost(host);\n const now = Date.now();\n if (health.stoppedUntil > now) {\n throw new OriginBackpressureError(snapshotForHost(host, 'stopped'));\n }\n const waitMs = Math.max(0, health.cooldownUntil - now);\n health.lastDelayMs = waitMs;\n if (waitMs > 0) {\n await delay(Math.min(waitMs, rate.backpressure.cooldownMs));\n return snapshotForHost(host, 'slowed');\n }\n return snapshotForHost(host, 'ok');\n}\nexport function retryAfterMs(value) {\n if (!value)\n return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0)\n return seconds * 1000;\n const dateMs = Date.parse(value);\n if (Number.isFinite(dateMs))\n return Math.max(0, dateMs - Date.now());\n return undefined;\n}\nexport function recordHostFetch(input) {\n const health = healthForHost(input.host);\n const cfg = input.rate.backpressure;\n health.durations.push(input.durationMs);\n if (health.durations.length > 20)\n health.durations.shift();\n const blocked = [401, 403, 429].includes(input.status);\n const errored = input.status >= 500;\n const slow = input.durationMs >= cfg.slowMs;\n health.consecutiveBlocked = blocked ? health.consecutiveBlocked + 1 : 0;\n health.consecutiveErrors = errored ? health.consecutiveErrors + 1 : 0;\n health.consecutiveSlow = slow ? health.consecutiveSlow + 1 : 0;\n if (!blocked && !errored && !slow) {\n health.reason = undefined;\n }\n const retryDelay = input.retryAfterMs === undefined\n ? 0\n : Math.min(input.retryAfterMs, cfg.retryAfterCapMs);\n if (retryDelay > 0) {\n health.reason = `origin sent Retry-After (${Math.round(retryDelay / 1000)}s)`;\n health.cooldownUntil = Math.max(health.cooldownUntil, Date.now() + retryDelay);\n }\n if (input.durationMs >= cfg.verySlowMs) {\n health.reason = `very slow response (${input.durationMs}ms)`;\n health.cooldownUntil = Math.max(health.cooldownUntil, Date.now() + cfg.cooldownMs);\n }\n if (health.consecutiveSlow >= cfg.maxConsecutiveSlow ||\n health.consecutiveBlocked >= cfg.maxConsecutiveBlocked ||\n health.consecutiveErrors >= cfg.maxConsecutiveErrors) {\n health.reason =\n health.consecutiveBlocked >= cfg.maxConsecutiveBlocked\n ? `${health.consecutiveBlocked} consecutive blocked responses`\n : health.consecutiveErrors >= cfg.maxConsecutiveErrors\n ? `${health.consecutiveErrors} consecutive error responses`\n : `${health.consecutiveSlow} consecutive slow responses`;\n health.stoppedUntil = Date.now() + cfg.cooldownMs;\n }\n return snapshotForHost(input.host);\n}\n//# sourceMappingURL=rate-controls.js.map","import robotsParserModule from 'robots-parser';\nimport { getDb, hashKey } from '../../storage/database.js';\nimport { BROWSER_USER_AGENT, publicHttpFetch } from '../http-client.js';\nexport class RobotsAccessError extends Error {\n reason;\n evidence;\n constructor(reason, evidence) {\n super(reason === 'robots-disallowed'\n ? `robots.txt disallows ${evidence.url}`\n : `robots.txt access decision is deferred for ${evidence.url}`);\n this.reason = reason;\n this.evidence = evidence;\n this.name = 'RobotsAccessError';\n }\n}\nfunction parseRobots(robotsUrl, text) {\n return robotsParserModule(robotsUrl, text);\n}\nfunction cacheableStatus(status) {\n return ((status >= 200 && status < 300) ||\n (status >= 400 && status < 500 && status !== 429));\n}\nfunction resultFromResponse(input) {\n if (input.status >= 200 && input.status < 300) {\n const parsed = parseRobots(input.robotsUrl, input.text);\n const lineNumber = parsed.getMatchingLineNumber?.(input.targetUrl, BROWSER_USER_AGENT);\n const matchedLine = lineNumber\n ? input.text.split(/\\r?\\n/)[lineNumber - 1]?.trim()\n : undefined;\n return {\n allowed: parsed.isAllowed(input.targetUrl, BROWSER_USER_AGENT) ?? true,\n availability: 'available',\n status: input.status,\n cache: input.cache,\n url: input.robotsUrl,\n ...(matchedLine ? { matchedLine } : {}),\n };\n }\n if (input.status >= 400 && input.status < 500 && input.status !== 429) {\n return {\n allowed: true,\n availability: [401, 403].includes(input.status)\n ? 'access-blocked'\n : 'absent',\n status: input.status,\n cache: input.cache,\n url: input.robotsUrl,\n };\n }\n return {\n allowed: null,\n availability: input.status === 429 ? 'rate-limited' : 'unreachable',\n status: input.status,\n error: `robots.txt returned HTTP ${input.status}.`,\n cache: input.cache,\n url: input.robotsUrl,\n };\n}\nexport async function fetchRobots(origin, targetUrl = origin, refresh = false) {\n const db = getDb();\n const robotsUrl = new URL('/robots.txt', origin).toString();\n const key = hashKey(['robots', robotsUrl]);\n const cached = db\n .prepare('SELECT status, body_blob, expires_at FROM http_cache WHERE url_hash = ?')\n .get(key);\n if (!refresh &&\n cached?.body_blob &&\n cached.status !== undefined &&\n cacheableStatus(cached.status) &&\n cached.expires_at &&\n cached.expires_at > Date.now()) {\n return resultFromResponse({\n robotsUrl,\n targetUrl,\n status: cached.status,\n text: cached.body_blob.toString('utf8'),\n cache: 'hit',\n });\n }\n try {\n const response = await publicHttpFetch(robotsUrl, {\n profile: 'bot',\n });\n const text = await response.text();\n const result = resultFromResponse({\n robotsUrl,\n targetUrl,\n status: response.status,\n text,\n cache: refresh ? 'bypass' : 'miss',\n });\n if (cacheableStatus(response.status)) {\n db.prepare(`INSERT OR REPLACE INTO http_cache\n (url_hash, url, status, headers_json, body_blob, etag, fetched_at, expires_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(key, robotsUrl, response.status, '{}', Buffer.from(text), null, Date.now(), Date.now() + 86_400_000);\n }\n return result;\n }\n catch (error) {\n return {\n allowed: null,\n availability: 'unreachable',\n error: error instanceof Error ? error.message : String(error),\n cache: refresh ? 'bypass' : 'miss',\n url: robotsUrl,\n };\n }\n}\n//# sourceMappingURL=robots.js.map","import pRetry, { AbortError } from 'p-retry';\nimport { getDb, hashKey } from '../../storage/database.js';\nimport { publicHttpFetch } from '../http-client.js';\nimport { hostBackpressureSnapshot, rateLimitDiagnostics, recordHostFetch, retryAfterMs, waitForHostBackpressure, } from './rate-controls.js';\nimport { fetchRobots, RobotsAccessError } from './robots.js';\nfunction pageRobotsEvidence(robots) {\n return {\n url: robots.url,\n allowed: robots.allowed,\n availability: robots.availability,\n status: robots.status,\n error: robots.error,\n matchedLine: robots.matchedLine,\n };\n}\nfunction diagnosticRobotsEvidence(robots) {\n return {\n url: robots.url,\n cache: robots.cache,\n allowed: robots.allowed,\n availability: robots.availability,\n status: robots.status,\n error: robots.error,\n };\n}\nexport function encodePageFetchCacheEvidence(result) {\n return JSON.stringify({\n finalUrl: result.finalUrl,\n blocked: result.diagnostics.blocked,\n robotsTxt: result.robotsTxt,\n diagnosticsRobotsTxt: result.diagnostics.robotsTxt,\n redirectChain: result.diagnostics.redirectChain,\n warnings: result.warnings,\n });\n}\nexport function decodePageFetchCacheEvidence(value) {\n if (!value)\n return undefined;\n try {\n const parsed = JSON.parse(value);\n if (typeof parsed.finalUrl !== 'string' ||\n typeof parsed.blocked !== 'boolean' ||\n !Array.isArray(parsed.warnings)) {\n return undefined;\n }\n return parsed;\n }\n catch {\n return undefined;\n }\n}\nasync function fetchWithRedirectChain(url, signal) {\n const redirectChain = [];\n let currentUrl = url;\n for (let redirectCount = 0; redirectCount <= 10; redirectCount += 1) {\n const response = await publicHttpFetch(currentUrl, {\n redirect: 'manual',\n signal,\n });\n const location = response.headers.get('location');\n if (response.status < 300 || response.status >= 400 || !location) {\n return { response, redirectChain };\n }\n const nextUrl = new URL(location, currentUrl).toString();\n redirectChain.push({\n url: currentUrl,\n status: response.status,\n location: nextUrl,\n });\n await response.body?.cancel().catch(() => undefined);\n currentUrl = nextUrl;\n }\n throw new Error(`Too many redirects for ${url}`);\n}\nexport async function fetchPlain(url, refresh = false, timeoutMs = 20_000, rate, signal, respectRobots = false) {\n const startedAt = Date.now();\n const db = getDb();\n const key = hashKey(['page', url]);\n const host = new URL(url).host;\n let robots = respectRobots\n ? await fetchRobots(new URL(url).origin, url, refresh)\n : undefined;\n if (robots && robots.allowed !== true) {\n throw new RobotsAccessError(robots.allowed === false ? 'robots-disallowed' : 'robots-deferred', robots);\n }\n const cached = db\n .prepare('SELECT status, headers_json, body_blob, metadata_json, expires_at FROM http_cache WHERE url_hash = ? AND expires_at > ?')\n .get(key, Date.now());\n if (!refresh && cached) {\n const evidence = decodePageFetchCacheEvidence(cached.metadata_json);\n return {\n url,\n finalUrl: evidence?.finalUrl ?? url,\n status: cached.status,\n headers: JSON.parse(cached.headers_json),\n html: cached.body_blob.toString('utf8'),\n usedJs: false,\n diagnostics: {\n source: 'cache',\n cache: 'hit',\n fetched: false,\n rendered: false,\n blocked: evidence?.blocked ?? [401, 403, 429].includes(cached.status),\n durationMs: Date.now() - startedAt,\n retries: 0,\n rateLimit: {\n ...rateLimitDiagnostics(host, rate),\n },\n backpressure: hostBackpressureSnapshot(host),\n robotsTxt: robots\n ? diagnosticRobotsEvidence(robots)\n : evidence?.diagnosticsRobotsTxt\n ? { ...evidence.diagnosticsRobotsTxt, cache: 'hit' }\n : undefined,\n redirectChain: evidence?.redirectChain,\n },\n warnings: evidence?.warnings ?? [\n 'Cached page predates redirect and robots diagnostics. Rerun with refresh before making technical decisions.',\n ],\n robotsTxt: robots ? pageRobotsEvidence(robots) : evidence?.robotsTxt,\n };\n }\n robots ??= await fetchRobots(new URL(url).origin, url, refresh);\n const beforeFetch = await waitForHostBackpressure(host, rate);\n let attempts = 0;\n const response = await pRetry(async () => {\n attempts += 1;\n const controller = new AbortController();\n const abort = () => controller.abort();\n const timer = setTimeout(abort, timeoutMs);\n if (signal?.aborted) {\n controller.abort();\n }\n else {\n signal?.addEventListener('abort', abort, { once: true });\n }\n try {\n return await fetchWithRedirectChain(url, controller.signal);\n }\n catch (error) {\n if (error instanceof Error && /4\\d\\d/.test(error.message)) {\n throw new AbortError(error);\n }\n throw error;\n }\n finally {\n clearTimeout(timer);\n signal?.removeEventListener('abort', abort);\n }\n }, { retries: 2 });\n const html = await response.response.text();\n const headerMap = Object.fromEntries(response.response.headers.entries());\n const durationMs = Date.now() - startedAt;\n const backpressure = recordHostFetch({\n host,\n status: response.response.status,\n durationMs,\n retryAfterMs: retryAfterMs(response.response.headers.get('retry-after')),\n rate,\n });\n const result = {\n url,\n finalUrl: response.response.url,\n status: response.response.status,\n headers: headerMap,\n html,\n usedJs: false,\n diagnostics: {\n source: 'network',\n cache: refresh ? 'bypass' : 'miss',\n fetched: true,\n rendered: false,\n blocked: robots.allowed === false ||\n [401, 403, 429].includes(response.response.status),\n durationMs,\n retries: Math.max(0, attempts - 1),\n rateLimit: {\n ...rateLimitDiagnostics(host, rate),\n },\n backpressure: backpressure.status === 'ok' && beforeFetch.status !== 'ok'\n ? beforeFetch\n : backpressure,\n robotsTxt: diagnosticRobotsEvidence(robots),\n redirectChain: response.redirectChain,\n },\n warnings: robots.allowed === null\n ? [\n `robots.txt availability is unknown${robots.status ? ` after HTTP ${robots.status}` : ''}; this fetch does not prove crawler access is allowed.`,\n ]\n : [],\n robotsTxt: pageRobotsEvidence(robots),\n };\n db.prepare(`INSERT OR REPLACE INTO http_cache\n (url_hash, url, status, headers_json, body_blob, metadata_json, etag, fetched_at, expires_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(key, url, response.response.status, JSON.stringify(headerMap), Buffer.from(html), encodePageFetchCacheEvidence(result), response.response.headers.get('etag'), Date.now(), Date.now() + 3_600_000);\n return result;\n}\n//# sourceMappingURL=plain.js.map","import { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nexport const PLAYWRIGHT_CORE_VERSION = '1.61.1';\nfunction systemBrowserCandidates(input) {\n const macApplications = [\n '/Applications',\n join(input.homeDirectory, 'Applications'),\n ];\n if (input.platform === 'darwin') {\n return macApplications.flatMap((directory) => [\n {\n path: join(directory, 'Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome'),\n source: 'system',\n product: 'Google Chrome',\n },\n {\n path: join(directory, 'Google Chrome Beta.app', 'Contents', 'MacOS', 'Google Chrome Beta'),\n source: 'system',\n product: 'Google Chrome Beta',\n },\n {\n path: join(directory, 'Chromium.app', 'Contents', 'MacOS', 'Chromium'),\n source: 'system',\n product: 'Chromium',\n },\n ]);\n }\n if (input.platform === 'win32') {\n const roots = [\n input.environment.LOCALAPPDATA,\n input.environment.PROGRAMFILES,\n input.environment['PROGRAMFILES(X86)'],\n ].filter((value) => Boolean(value));\n return roots.flatMap((root) => [\n {\n path: join(root, 'Google', 'Chrome', 'Application', 'chrome.exe'),\n source: 'system',\n product: 'Google Chrome',\n },\n {\n path: join(root, 'Chromium', 'Application', 'chrome.exe'),\n source: 'system',\n product: 'Chromium',\n },\n ]);\n }\n return [\n '/usr/bin/google-chrome-stable',\n '/usr/bin/google-chrome',\n '/usr/bin/chromium',\n '/usr/bin/chromium-browser',\n '/snap/bin/chromium',\n ].map((path) => ({\n path,\n source: 'system',\n product: path.includes('google-chrome') ? 'Google Chrome' : 'Chromium',\n }));\n}\n/**\n * Resolve a browser without downloading one during normal package installation.\n * The explicit path wins so CI and managed workstations can select their own\n * supported browser deterministically.\n */\nexport function resolveBrowserExecutable(playwrightExecutablePath, dependencies = {}) {\n const environment = dependencies.environment ?? process.env;\n const fileExists = dependencies.fileExists ?? existsSync;\n const configuredPath = environment.SEO_BROWSER_EXECUTABLE_PATH?.trim();\n if (configuredPath) {\n if (fileExists(configuredPath)) {\n return {\n status: 'available',\n browser: {\n path: configuredPath,\n source: 'environment',\n product: 'Configured Chromium browser',\n },\n };\n }\n return { status: 'invalid-environment-path', path: configuredPath };\n }\n if (fileExists(playwrightExecutablePath)) {\n return {\n status: 'available',\n browser: {\n path: playwrightExecutablePath,\n source: 'playwright-cache',\n product: 'Playwright Chromium',\n },\n };\n }\n const candidates = systemBrowserCandidates({\n platform: dependencies.platform ?? process.platform,\n homeDirectory: dependencies.homeDirectory ?? homedir(),\n environment,\n });\n const browser = candidates.find((candidate) => fileExists(candidate.path));\n return browser ? { status: 'available', browser } : { status: 'unavailable' };\n}\nexport function browserInstallCommand() {\n return `npx --yes playwright@${PLAYWRIGHT_CORE_VERSION} install chromium`;\n}\nexport function browserUnavailableMessage(resolution) {\n if (resolution.status === 'invalid-environment-path') {\n return 'SEO_BROWSER_EXECUTABLE_PATH does not point to a readable Chromium browser.';\n }\n return [\n 'JavaScript rendering needs a local Chrome or Chromium browser.',\n `Install one, or run \\`${browserInstallCommand()}\\`.`,\n 'Set SEO_BROWSER_EXECUTABLE_PATH to use a managed browser executable.',\n ].join(' ');\n}\n//# sourceMappingURL=browser-path.js.map","import PQueue from 'p-queue';\nimport { chromium } from 'playwright-core';\nimport { BROWSER_USER_AGENT } from '../http-client.js';\nimport { browserUnavailableMessage, resolveBrowserExecutable, } from './browser-path.js';\nimport { rateLimitDiagnostics, recordHostFetch, retryAfterMs, waitForHostBackpressure, } from './rate-controls.js';\nconst DEFAULT_RENDER_TIMEOUT_MS = 20_000;\nconst NETWORK_IDLE_TIMEOUT_MS = 3_000;\nconst MAX_RENDER_CONTEXTS = 4;\nconst MAX_RENDER_DIAGNOSTICS = 20;\nexport class JavaScriptRenderingError extends Error {\n kind;\n constructor(message, kind) {\n super(message);\n this.kind = kind;\n this.name = 'JavaScriptRenderingError';\n }\n}\nfunction safeDiagnosticUrl(value) {\n try {\n const url = new URL(value);\n url.search = '';\n url.hash = '';\n return url.toString();\n }\n catch {\n return value.slice(0, 300);\n }\n}\nfunction safeDiagnosticText(value) {\n return value\n .replace(/https?:\\/\\/[^\\s\"')]+/gi, (url) => safeDiagnosticUrl(url))\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 500);\n}\nfunction pushDiagnostic(values, value) {\n if (values.length >= MAX_RENDER_DIAGNOSTICS)\n return;\n const safeValue = safeDiagnosticText(value);\n if (safeValue && !values.includes(safeValue))\n values.push(safeValue);\n}\nfunction securityObservation(message) {\n const safeMessage = safeDiagnosticText(message);\n if (/content security policy|\\bcsp\\b/i.test(safeMessage)) {\n return { kind: 'content-security-policy', message: safeMessage };\n }\n if (/\\bcors\\b|cross-origin/i.test(safeMessage)) {\n return { kind: 'cors', message: safeMessage };\n }\n if (/mixed content/i.test(safeMessage)) {\n return { kind: 'mixed-content', message: safeMessage };\n }\n return undefined;\n}\nfunction createPageDiagnostics(page) {\n const consoleErrors = [];\n const pageErrors = [];\n const failedRequests = [];\n const securityObservations = [];\n const addSecurityObservation = (message) => {\n if (securityObservations.length >= MAX_RENDER_DIAGNOSTICS)\n return;\n const observation = securityObservation(message);\n if (observation &&\n !securityObservations.some((existing) => existing.kind === observation.kind &&\n existing.message === observation.message)) {\n securityObservations.push(observation);\n }\n };\n page.on('console', (message) => {\n if (message.type() !== 'error')\n return;\n const text = message.text();\n pushDiagnostic(consoleErrors, text);\n addSecurityObservation(text);\n });\n page.on('pageerror', (error) => {\n pushDiagnostic(pageErrors, error.message);\n addSecurityObservation(error.message);\n });\n page.on('requestfailed', (request) => {\n if (failedRequests.length >= MAX_RENDER_DIAGNOSTICS)\n return;\n const failure = request.failure()?.errorText ?? 'Request failed.';\n const item = {\n url: safeDiagnosticUrl(request.url()),\n resourceType: request.resourceType(),\n error: safeDiagnosticText(failure),\n };\n if (!failedRequests.some((existing) => existing.url === item.url &&\n existing.resourceType === item.resourceType &&\n existing.error === item.error)) {\n failedRequests.push(item);\n }\n addSecurityObservation(failure);\n });\n return {\n consoleErrors,\n pageErrors,\n failedRequests,\n securityObservations,\n };\n}\nfunction launchFailureMessage(error) {\n const detail = error instanceof Error ? error.message : String(error);\n if (/executable doesn't exist|browser.*not found/i.test(detail)) {\n return [\n 'JavaScript rendering could not start the selected local browser.',\n 'Check SEO_BROWSER_EXECUTABLE_PATH or install Chromium with the command in `seo` output.',\n ].join(' ');\n }\n return 'JavaScript rendering could not start the selected local browser.';\n}\nasync function launchBrowser() {\n const resolution = resolveBrowserExecutable(chromium.executablePath());\n if (resolution.status !== 'available') {\n throw new JavaScriptRenderingError(browserUnavailableMessage(resolution), 'browser-unavailable');\n }\n try {\n const browser = await chromium.launch({\n headless: true,\n executablePath: resolution.browser.path,\n });\n return { browser, executable: resolution.browser };\n }\n catch (error) {\n throw new JavaScriptRenderingError(launchFailureMessage(error), 'browser-unavailable');\n }\n}\nasync function renderPage(input) {\n const startedAt = Date.now();\n const host = new URL(input.url).host;\n const beforeFetch = await waitForHostBackpressure(host, input.rate);\n const timeoutMs = input.timeoutMs ?? DEFAULT_RENDER_TIMEOUT_MS;\n const context = await input.browser.browser.newContext({\n userAgent: BROWSER_USER_AGENT,\n viewport: { width: 1440, height: 900 },\n locale: 'en-US',\n });\n let page;\n let aborted = Boolean(input.signal?.aborted);\n const abort = () => {\n aborted = true;\n void page?.close().catch(() => undefined);\n };\n if (input.signal?.aborted)\n abort();\n else\n input.signal?.addEventListener('abort', abort, { once: true });\n try {\n page = await context.newPage();\n const renderDiagnostics = createPageDiagnostics(page);\n const response = await page.goto(input.url, {\n waitUntil: 'domcontentloaded',\n timeout: timeoutMs,\n });\n if (aborted) {\n throw new JavaScriptRenderingError('JavaScript rendering was aborted.', 'navigation-failed');\n }\n let networkIdleReached = true;\n await page\n .waitForLoadState('networkidle', {\n timeout: Math.min(NETWORK_IDLE_TIMEOUT_MS, timeoutMs),\n })\n .catch(() => {\n networkIdleReached = false;\n });\n const html = await page.content();\n const status = response?.status() ?? 200;\n const durationMs = Date.now() - startedAt;\n const backpressure = recordHostFetch({\n host,\n status,\n durationMs,\n retryAfterMs: retryAfterMs(response?.headers()['retry-after']),\n rate: input.rate,\n });\n return {\n url: input.url,\n finalUrl: page.url(),\n status,\n headers: response?.headers() ?? {},\n html,\n usedJs: true,\n diagnostics: {\n source: 'rendered',\n cache: 'bypass',\n fetched: true,\n rendered: true,\n blocked: [401, 403, 429].includes(status),\n durationMs,\n retries: 0,\n rateLimit: rateLimitDiagnostics(host, input.rate),\n backpressure: backpressure.status === 'ok' && beforeFetch.status !== 'ok'\n ? beforeFetch\n : backpressure,\n rendering: {\n mode: 'on',\n status: 'rendered',\n browser: {\n source: input.browser.executable.source,\n product: input.browser.executable.product,\n version: input.browser.browser.version(),\n },\n navigation: {\n waitUntil: 'domcontentloaded',\n networkIdleTimeoutMs: Math.min(NETWORK_IDLE_TIMEOUT_MS, timeoutMs),\n networkIdleReached,\n },\n ...renderDiagnostics,\n },\n },\n warnings: networkIdleReached\n ? []\n : [\n `Rendered page did not reach network idle within ${Math.min(NETWORK_IDLE_TIMEOUT_MS, timeoutMs)}ms; captured DOM after DOMContentLoaded.`,\n ],\n };\n }\n catch (error) {\n if (error instanceof JavaScriptRenderingError)\n throw error;\n if (aborted) {\n throw new JavaScriptRenderingError('JavaScript rendering was aborted.', 'navigation-failed');\n }\n throw new JavaScriptRenderingError('JavaScript rendering could not load this page.', 'navigation-failed');\n }\n finally {\n input.signal?.removeEventListener('abort', abort);\n await context.close().catch(() => undefined);\n }\n}\n/**\n * One renderer owns one browser process and a bounded number of isolated\n * contexts. Create it once for a crawl, then close it after the crawl exits.\n */\nexport function createPageRenderer(input = {}) {\n const queue = new PQueue({\n concurrency: Math.max(1, Math.min(input.concurrency ?? MAX_RENDER_CONTEXTS, MAX_RENDER_CONTEXTS)),\n });\n let launched;\n const browser = () => {\n launched ??= launchBrowser();\n return launched;\n };\n return {\n render: (url, rate, options) => queue.add(async () => renderPage({\n browser: await browser(),\n url,\n rate,\n timeoutMs: options.timeoutMs,\n signal: options.signal,\n })),\n close: async () => {\n await queue.onIdle();\n const current = await launched?.catch(() => undefined);\n await current?.browser.close().catch(() => undefined);\n },\n };\n}\nexport function looksLikeSpa(html) {\n const lower = html.toLowerCase();\n return (/<div[^>]+id=\"root\"[^>]*>\\s*<\\/div>/.test(lower) ||\n /<div[^>]+id=\"__next\"[^>]*>\\s*<\\/div>/.test(lower) ||\n /<app-root[^>]*>\\s*<\\/app-root>/.test(lower) ||\n /enable javascript/i.test(lower));\n}\n/** @deprecated Prefer a shared renderer created with createPageRenderer. */\nexport async function fetchWithPlaywright(url, rate) {\n const renderer = createPageRenderer();\n try {\n return await renderer.render(url, rate, {});\n }\n finally {\n await renderer.close();\n }\n}\n//# sourceMappingURL=rendered.js.map","import { createHash } from 'node:crypto';\nimport { load } from 'cheerio';\nimport { extractCanonicalEvidence } from '../../extract/canonical.js';\nimport { extractStructuredData } from '../../extract/structured-data.js';\nconst MAX_HEADINGS = 50;\nconst MAX_TEXT_VALUE_LENGTH = 500;\nfunction safeText(value) {\n const normalized = value?.replace(/\\s+/g, ' ').trim();\n return normalized ? normalized.slice(0, MAX_TEXT_VALUE_LENGTH) : undefined;\n}\nfunction headerValue(headers, name) {\n const expected = name.toLowerCase();\n return Object.entries(headers).find(([key]) => key.toLowerCase() === expected)?.[1];\n}\nfunction normalizedDirectiveValue(values) {\n const directives = values\n .flatMap((value) => value?.split(',') ?? [])\n .map((value) => value.replace(/\\s+/g, ' ').trim().toLowerCase())\n .filter(Boolean)\n .sort();\n return directives.length ? directives.join(', ') : undefined;\n}\nfunction metaValue($, name) {\n const expected = name.toLowerCase();\n const element = $('meta')\n .toArray()\n .find((candidate) => $(candidate).attr('name')?.toLowerCase() === expected);\n return safeText(element ? $(element).attr('content') : undefined);\n}\nfunction fingerprint(value) {\n return createHash('sha256').update(value).digest('hex').slice(0, 16);\n}\nfunction textObservation($) {\n const text = $('body')\n .clone()\n .find('script, style, noscript, template')\n .remove()\n .end()\n .text()\n .replace(/\\s+/g, ' ')\n .trim();\n const words = text.match(/[\\p{L}\\p{N}][\\p{L}\\p{M}\\p{N}'’_-]*/gu) ?? [];\n return {\n characters: text.length,\n wordCount: words.length,\n fingerprint: fingerprint(text),\n };\n}\nfunction linksObservation($, finalUrl) {\n const host = new URL(finalUrl).host;\n const urls = new Set();\n let internal = 0;\n let external = 0;\n for (const element of $('a[href]').toArray()) {\n const href = $(element).attr('href') ?? '';\n try {\n const url = new URL(href, finalUrl);\n if (!['http:', 'https:'].includes(url.protocol))\n continue;\n urls.add(url.toString());\n if (url.host === host)\n internal += 1;\n else\n external += 1;\n }\n catch {\n // Invalid hrefs are excluded from the comparison just as crawl links are.\n }\n }\n return {\n total: internal + external,\n internal,\n external,\n fingerprint: fingerprint([...urls].sort().join('\\n')),\n };\n}\nexport function renderingDocumentSnapshot(result) {\n const $ = load(result.html);\n const canonical = extractCanonicalEvidence($, result.headers, result.finalUrl);\n const structuredData = extractStructuredData($, result.finalUrl);\n const metaRobots = normalizedDirectiveValue([metaValue($, 'robots')]);\n const googlebotRobots = normalizedDirectiveValue([metaValue($, 'googlebot')]);\n const httpRobots = normalizedDirectiveValue([\n headerValue(result.headers, 'x-robots-tag'),\n ]);\n const headings = $('h1, h2, h3, h4, h5, h6')\n .toArray()\n .map((element) => ({\n level: Number.parseInt(element.tagName.slice(1), 10),\n text: safeText($(element).text()),\n }))\n .filter((heading) => Number.isFinite(heading.level) && Boolean(heading.text))\n .slice(0, MAX_HEADINGS);\n return {\n title: safeText($('title').first().text()),\n metaDescription: metaValue($, 'description'),\n canonical: {\n status: canonical.status,\n ...(canonical.selectedUrl ? { url: canonical.selectedUrl } : {}),\n },\n robots: {\n ...(metaRobots ? { meta: metaRobots } : {}),\n ...(googlebotRobots ? { googlebot: googlebotRobots } : {}),\n ...(httpRobots ? { http: httpRobots } : {}),\n },\n headings,\n links: linksObservation($, result.finalUrl),\n content: textObservation($),\n structuredData: {\n blocks: $('script[type=\"application/ld+json\"]').length,\n formats: [...structuredData.formats].sort(),\n schemaTypes: [...structuredData.schemaTypes].sort(),\n },\n };\n}\nexport function renderingDocumentDifference(raw, rendered) {\n const rawDocument = renderingDocumentSnapshot(raw);\n const renderedDocument = renderingDocumentSnapshot(rendered);\n const fields = [\n 'title',\n 'metaDescription',\n 'canonical',\n 'robots',\n 'headings',\n 'links',\n 'content',\n 'structuredData',\n ];\n const changed = fields.filter((field) => JSON.stringify(rawDocument[field]) !==\n JSON.stringify(renderedDocument[field]));\n return { raw: rawDocument, rendered: renderedDocument, changed };\n}\n//# sourceMappingURL=rendering-difference.js.map","import { fetchPlain } from './page-fetcher/plain.js';\nimport { normalizeRateControls, queueForHost, } from './page-fetcher/rate-controls.js';\nimport { createPageRenderer, JavaScriptRenderingError, looksLikeSpa, } from './page-fetcher/rendered.js';\nimport { renderingDocumentDifference } from './page-fetcher/rendering-difference.js';\nexport { createPageRenderer } from './page-fetcher/rendered.js';\nexport function normalizeJavaScriptRenderingMode(input) {\n if (input === true)\n return 'on';\n if (input === false)\n return 'off';\n return input ?? 'auto';\n}\nfunction rawObservation(result) {\n return {\n source: result.diagnostics.source === 'cache' ? 'cache' : 'network',\n cache: result.diagnostics.cache,\n url: result.url,\n finalUrl: result.finalUrl,\n status: result.status,\n };\n}\nfunction withRenderingState(result, mode, status, input = {}) {\n return {\n ...result,\n diagnostics: {\n ...result.diagnostics,\n rendering: {\n mode,\n status,\n raw: rawObservation(result),\n ...(input.error ? { error: input.error } : {}),\n },\n },\n warnings: [...result.warnings, ...(input.warnings ?? [])],\n };\n}\nfunction renderingFallback(result, mode, error) {\n const unavailable = error instanceof JavaScriptRenderingError &&\n error.kind === 'browser-unavailable';\n const message = error instanceof Error ? error.message : 'JavaScript rendering failed.';\n return withRenderingState(result, mode, unavailable ? 'unavailable' : 'failed', {\n error: message,\n warnings: [\n `${mode === 'on' ? 'JavaScript rendering was requested' : 'JavaScript rendering was attempted'} but ${unavailable ? 'is unavailable' : 'failed'}. This result uses raw HTTP HTML only, so client-rendered content, metadata, and links may be incomplete. ${message}`,\n ],\n });\n}\nexport async function fetchPage(url, opts = {}, dependencies = {}) {\n const renderingMode = normalizeJavaScriptRenderingMode(opts.js);\n const plainFetch = dependencies.fetchPlain ?? fetchPlain;\n const makeRenderer = dependencies.createPageRenderer ?? createPageRenderer;\n const rate = normalizeRateControls(opts.rate);\n const queue = queueForHost(new URL(url).host, rate);\n return (await queue.add(async () => {\n const first = await plainFetch(url, opts.refresh, opts.timeoutMs, rate, opts.signal, opts.respectRobots);\n const shouldRetryJs = renderingMode === 'on' ||\n (renderingMode === 'auto' && looksLikeSpa(first.html));\n if (!shouldRetryJs || opts.signal?.aborted) {\n return withRenderingState(first, renderingMode, opts.signal?.aborted\n ? 'skipped'\n : renderingMode === 'off'\n ? 'not-requested'\n : 'not-needed');\n }\n const ownsRenderer = !opts.renderer;\n const renderer = opts.renderer ?? makeRenderer();\n try {\n const rendered = await renderer.render(url, rate, {\n timeoutMs: opts.timeoutMs,\n signal: opts.signal,\n });\n return {\n ...rendered,\n diagnostics: {\n ...rendered.diagnostics,\n robotsTxt: first.diagnostics.robotsTxt,\n redirectChain: first.diagnostics.redirectChain,\n rendering: {\n ...rendered.diagnostics.rendering,\n mode: renderingMode,\n status: 'rendered',\n raw: rawObservation(first),\n documentDifference: renderingDocumentDifference(first, rendered),\n },\n },\n warnings: [...first.warnings, ...rendered.warnings],\n };\n }\n catch (error) {\n return renderingFallback(first, renderingMode, error);\n }\n finally {\n if (ownsRenderer)\n await renderer.close();\n }\n }));\n}\n//# sourceMappingURL=page-fetcher.js.map","import { SeoError } from '../errors.js';\nfunction invalid(message) {\n throw new SeoError('INVALID_INPUT', message);\n}\nexport function normalizeHttpUrl(value) {\n let url;\n try {\n url = new URL(value.trim());\n }\n catch {\n return invalid(`Invalid URL: ${value}`);\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return invalid('The report URL must use http:// or https://.');\n }\n if (url.username || url.password) {\n return invalid('The report URL must not contain embedded credentials.');\n }\n url.hash = '';\n return url.toString();\n}\nexport function assertUrlMatchesGscProperty(property, value) {\n const url = normalizeHttpUrl(value);\n const parsed = new URL(url);\n if (property.startsWith('sc-domain:')) {\n const domain = property.slice('sc-domain:'.length).trim().toLowerCase();\n if (!domain || /[/:]/.test(domain)) {\n return invalid(`Invalid Search Console domain property: ${property}`);\n }\n const hostname = parsed.hostname.toLowerCase();\n if (hostname !== domain && !hostname.endsWith(`.${domain}`)) {\n return invalid(`${url} is outside the Search Console property ${property}.`);\n }\n return url;\n }\n const prefix = normalizeHttpUrl(property);\n if (!url.startsWith(prefix)) {\n return invalid(`${url} is outside the Search Console property ${property}.`);\n }\n return url;\n}\n//# sourceMappingURL=property-url.js.map","import { fetch } from 'undici';\nimport { SeoError } from '../../errors.js';\nimport { createGoogleAccessTokenClient, } from '../auth.js';\nexport async function authedFetch(client, url, init) {\n const accessToken = await client.getAccessToken();\n if (!accessToken) {\n throw new SeoError('AUTH_EXPIRED', 'Could not obtain a Google access token. Run `seo auth login` again.');\n }\n return fetch(url, {\n method: init?.method,\n body: init?.body,\n headers: {\n ...init?.headers,\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n });\n}\nexport async function getAuthorized() {\n return createGoogleAccessTokenClient();\n}\n//# sourceMappingURL=fetch.js.map","import { randomUUID } from 'node:crypto';\nimport { SeoError } from '../../errors.js';\nimport { getDb } from '../../storage/database.js';\nexport const URL_INSPECTION_DAILY_LIMIT = 2_000;\nexport const URL_INSPECTION_MINUTE_LIMIT = 600;\nconst RESERVATION_TTL_MS = 5 * 60_000;\nexport class UrlInspectionQuotaError extends SeoError {\n property;\n requestSent;\n resetAt;\n used;\n limit;\n constructor(input) {\n super('RATE_LIMITED', `URL Inspection ${input.reason ?? 'daily'} quota is blocked for ${input.property}. Retry after ${input.resetAt}.`);\n this.name = 'UrlInspectionQuotaError';\n this.property = input.property;\n this.requestSent = input.requestSent ?? false;\n this.resetAt = input.resetAt;\n this.used = input.used;\n this.limit = input.limit;\n }\n}\nexport function urlInspectionQuotaDate(now) {\n return now.toISOString().slice(0, 10);\n}\nexport function urlInspectionQuotaResetAt(now) {\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1));\n}\nfunction boundedLimit(value) {\n const limit = value ?? URL_INSPECTION_DAILY_LIMIT;\n if (!Number.isInteger(limit) || limit < 1 || limit > 2_000) {\n throw new SeoError('INVALID_INPUT', 'URL Inspection daily limit must be an integer from 1 to 2000.');\n }\n return limit;\n}\nfunction reconcileExpiredReservations(input) {\n const expired = input.database\n .prepare(`SELECT COALESCE(SUM(count), 0) AS count\n FROM url_inspection_quota_reservations\n WHERE credential_key = ? AND property_site_url = ? AND quota_date = ?\n AND status = 'reserved' AND expires_at <= ?`)\n .get(input.credentialKey, input.property, input.quotaDate, input.now);\n if (!expired.count)\n return;\n input.database\n .prepare(`UPDATE url_inspection_quota_reservations\n SET status = 'abandoned', finalized_at = ?\n WHERE credential_key = ? AND property_site_url = ? AND quota_date = ?\n AND status = 'reserved' AND expires_at <= ?`)\n .run(input.now, input.credentialKey, input.property, input.quotaDate, input.now);\n input.database\n .prepare(`UPDATE url_inspection_quota_buckets\n SET used_count = MIN(limit_count, used_count + ?),\n reserved_count = MAX(0, reserved_count - ?),\n updated_at = ?\n WHERE credential_key = ? AND property_site_url = ? AND quota_date = ?`)\n .run(expired.count, expired.count, input.now, input.credentialKey, input.property, input.quotaDate);\n}\nfunction pruneOldQuotaRows(database, now) {\n const reservationCutoff = now - 2 * 86_400_000;\n const bucketCutoff = new Date(now - 7 * 86_400_000).toISOString().slice(0, 10);\n database\n .prepare(`DELETE FROM url_inspection_quota_reservations\n WHERE expires_at < ?`)\n .run(reservationCutoff);\n database\n .prepare(`DELETE FROM url_inspection_quota_buckets\n WHERE quota_date < ? AND COALESCE(blocked_until, 0) <= ?`)\n .run(bucketCutoff, now);\n}\nexport function reserveUrlInspectionQuota(input) {\n const database = input.database ?? getDb();\n const now = input.now ?? new Date();\n const nowMs = now.getTime();\n const requestedLimit = boundedLimit(input.limit);\n const quotaDate = urlInspectionQuotaDate(now);\n const resetAt = urlInspectionQuotaResetAt(now);\n const reserve = database.transaction(() => {\n pruneOldQuotaRows(database, nowMs);\n database\n .prepare(`INSERT INTO url_inspection_quota_buckets\n (credential_key, property_site_url, quota_date, limit_count,\n minute_window_start, updated_at)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT(credential_key, property_site_url, quota_date)\n DO UPDATE SET limit_count = MIN(limit_count, excluded.limit_count),\n updated_at = excluded.updated_at`)\n .run(input.credentialKey, input.property, quotaDate, requestedLimit, nowMs, nowMs);\n reconcileExpiredReservations({\n database,\n credentialKey: input.credentialKey,\n property: input.property,\n quotaDate,\n now: nowMs,\n });\n const bucket = database\n .prepare(`SELECT * FROM url_inspection_quota_buckets\n WHERE credential_key = ? AND property_site_url = ? AND quota_date = ?`)\n .get(input.credentialKey, input.property, quotaDate);\n const priorBlocked = database\n .prepare(`SELECT MAX(blocked_until) AS blocked_until\n FROM url_inspection_quota_buckets\n WHERE credential_key = ? AND property_site_url = ?\n AND blocked_until > ?`)\n .get(input.credentialKey, input.property, nowMs);\n const blockedUntil = Math.max(bucket.blocked_until ?? 0, priorBlocked.blocked_until ?? 0);\n if (blockedUntil > nowMs ||\n bucket.used_count + bucket.reserved_count >= bucket.limit_count) {\n return {\n error: new UrlInspectionQuotaError({\n property: input.property,\n resetAt: new Date(blockedUntil > nowMs ? blockedUntil : resetAt.getTime()).toISOString(),\n used: bucket.used_count,\n limit: bucket.limit_count,\n reason: 'daily',\n }),\n };\n }\n const rollingMinute = database\n .prepare(`SELECT COALESCE(SUM(count), 0) AS count,\n MIN(created_at) AS earliest_created_at\n FROM url_inspection_quota_reservations\n WHERE credential_key = ? AND property_site_url = ?\n AND created_at > ? AND status != 'released'`)\n .get(input.credentialKey, input.property, nowMs - 60_000);\n if (rollingMinute.count >= URL_INSPECTION_MINUTE_LIMIT) {\n return {\n error: new UrlInspectionQuotaError({\n property: input.property,\n resetAt: new Date((rollingMinute.earliest_created_at ?? nowMs) + 60_000).toISOString(),\n used: rollingMinute.count,\n limit: URL_INSPECTION_MINUTE_LIMIT,\n reason: 'minute',\n }),\n };\n }\n const id = randomUUID();\n database\n .prepare(`INSERT INTO url_inspection_quota_reservations\n (id, credential_key, property_site_url, quota_date, count, status,\n created_at, expires_at)\n VALUES (?, ?, ?, ?, 1, 'reserved', ?, ?)`)\n .run(id, input.credentialKey, input.property, quotaDate, nowMs, nowMs + RESERVATION_TTL_MS);\n database\n .prepare(`UPDATE url_inspection_quota_buckets\n SET reserved_count = reserved_count + 1,\n minute_count = minute_count + 1,\n updated_at = ?\n WHERE credential_key = ? AND property_site_url = ? AND quota_date = ?`)\n .run(nowMs, input.credentialKey, input.property, quotaDate);\n return {\n reservation: {\n id,\n credentialKey: input.credentialKey,\n property: input.property,\n quotaDate,\n count: 1,\n limit: bucket.limit_count,\n used: bucket.used_count,\n reserved: bucket.reserved_count + 1,\n resetAt: resetAt.toISOString(),\n },\n };\n });\n const result = reserve.immediate();\n if ('error' in result)\n throw result.error;\n return result.reservation;\n}\nexport function finalizeUrlInspectionQuota(input) {\n const database = input.database ?? getDb();\n const now = input.now ?? new Date();\n const finalize = database.transaction(() => {\n const row = database\n .prepare('SELECT count, status FROM url_inspection_quota_reservations WHERE id = ?')\n .get(input.reservation.id);\n if (row?.status !== 'reserved')\n return;\n const nextStatus = input.outcome === 'consumed'\n ? 'consumed'\n : input.outcome === 'exhausted'\n ? 'exhausted'\n : 'released';\n database\n .prepare(`UPDATE url_inspection_quota_reservations\n SET status = ?, finalized_at = ?\n WHERE id = ? AND status = 'reserved'`)\n .run(nextStatus, now.getTime(), input.reservation.id);\n const consumed = input.outcome === 'released' ? 0 : row.count;\n const exhausted = input.outcome === 'exhausted';\n const dailyExhausted = exhausted && !input.blockedUntil;\n database\n .prepare(`UPDATE url_inspection_quota_buckets\n SET used_count = CASE WHEN ? = 1 THEN limit_count\n ELSE MIN(limit_count, used_count + ?) END,\n reserved_count = MAX(0, reserved_count - ?),\n minute_count = MAX(0, minute_count - ?),\n blocked_until = CASE WHEN ? = 1 THEN ? ELSE blocked_until END,\n last_429_at = CASE WHEN ? = 1 THEN ? ELSE last_429_at END,\n updated_at = ?\n WHERE credential_key = ? AND property_site_url = ? AND quota_date = ?`)\n .run(dailyExhausted ? 1 : 0, consumed, row.count, input.outcome === 'released' ? row.count : 0, exhausted ? 1 : 0, (input.blockedUntil ?? new Date(input.reservation.resetAt)).getTime(), exhausted ? 1 : 0, now.getTime(), now.getTime(), input.reservation.credentialKey, input.reservation.property, input.reservation.quotaDate);\n });\n finalize.immediate();\n}\n//# sourceMappingURL=inspection-quota.js.map","import { createHash } from 'node:crypto';\nimport { SeoError } from '../../errors.js';\nimport { assertUrlMatchesGscProperty } from '../property-url.js';\nimport { authedFetch, getAuthorized } from './fetch.js';\nimport { finalizeUrlInspectionQuota, reserveUrlInspectionQuota, UrlInspectionQuotaError, } from './inspection-quota.js';\nfunction credentialKey(input) {\n return createHash('sha256')\n .update(`${input.clientId}\\n${input.accountEmail.toLowerCase()}`)\n .digest('base64url');\n}\nfunction retryAfter(response, now) {\n const value = response.headers.get('retry-after');\n if (!value)\n return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) {\n return new Date(now.getTime() + seconds * 1_000);\n }\n const timestamp = Date.parse(value);\n return Number.isFinite(timestamp) ? new Date(timestamp) : undefined;\n}\nfunction inspectionResponseError(response, input) {\n if (response.status === 401) {\n return new SeoError('AUTH_EXPIRED', 'Google rejected the access token. Run `seo auth login` again.');\n }\n if (response.status === 403) {\n return new SeoError('ACCESS_DENIED', `Google Search Console denied URL Inspection access to ${input.siteUrl}. Check the selected account and property permissions.`);\n }\n if (response.status === 404) {\n return new SeoError('PROPERTY_NOT_FOUND', `Google Search Console could not inspect URLs under ${input.siteUrl}. Check the property value and account access.`);\n }\n if (response.status >= 500) {\n return new SeoError('PROVIDER_UNAVAILABLE', `Google URL Inspection is unavailable (${response.status}). Try again later.`);\n }\n return new SeoError('PROVIDER_UNAVAILABLE', `URL Inspection failed with ${response.status}.`);\n}\nexport async function inspectUrl(input) {\n const inspectionUrl = assertUrlMatchesGscProperty(input.siteUrl, input.inspectionUrl);\n const { client, quotaIdentity } = await getAuthorized();\n const reservation = reserveUrlInspectionQuota({\n credentialKey: credentialKey(quotaIdentity),\n property: input.siteUrl,\n limit: input.quotaLimit,\n });\n let response;\n try {\n response = await authedFetch(client, 'https://searchconsole.googleapis.com/v1/urlInspection/index:inspect', {\n method: 'POST',\n body: JSON.stringify({\n siteUrl: input.siteUrl,\n inspectionUrl,\n ...(input.languageCode ? { languageCode: input.languageCode } : {}),\n }),\n });\n }\n catch (error) {\n finalizeUrlInspectionQuota({ reservation, outcome: 'consumed' });\n if (error instanceof SeoError)\n throw error;\n throw new SeoError('PROVIDER_UNAVAILABLE', `URL Inspection request failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (response.status === 429) {\n const now = new Date();\n const blockedUntil = retryAfter(response, now);\n finalizeUrlInspectionQuota({\n reservation,\n outcome: 'exhausted',\n blockedUntil,\n now,\n });\n throw new UrlInspectionQuotaError({\n property: input.siteUrl,\n resetAt: (blockedUntil ?? new Date(reservation.resetAt)).toISOString(),\n used: reservation.used + reservation.count,\n limit: reservation.limit,\n reason: 'provider',\n requestSent: true,\n });\n }\n finalizeUrlInspectionQuota({ reservation, outcome: 'consumed' });\n if (!response.ok)\n throw inspectionResponseError(response, input);\n return (await response.json());\n}\n//# sourceMappingURL=inspection.js.map","export const GSC_TIME_ZONE = 'America/Los_Angeles';\nexport const GSC_FINAL_DATA_LAG_DAYS = 4;\nfunction dateInTimeZone(now, timeZone) {\n const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', {\n timeZone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n })\n .formatToParts(now)\n .map((part) => [part.type, part.value]));\n return new Date(Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day)));\n}\nexport function shiftIsoDate(date, days) {\n const value = new Date(`${date}T00:00:00.000Z`);\n value.setUTCDate(value.getUTCDate() + days);\n return value.toISOString().slice(0, 10);\n}\nexport function latestFinalGscDate(now = new Date()) {\n const pacificToday = dateInTimeZone(now, GSC_TIME_ZONE);\n pacificToday.setUTCDate(pacificToday.getUTCDate() - GSC_FINAL_DATA_LAG_DAYS);\n return pacificToday.toISOString().slice(0, 10);\n}\nexport function finalGscDateRange(days = 28, now = new Date()) {\n const endDate = latestFinalGscDate(now);\n return {\n startDate: shiftIsoDate(endDate, -(days - 1)),\n endDate,\n };\n}\n//# sourceMappingURL=dates.js.map","import { SeoError } from '../../errors.js';\nimport { getDb, hashKey } from '../../storage/database.js';\nimport { finalGscDateRange } from '../dates.js';\nimport { authedFetch, getAuthorized } from './fetch.js';\nfunction searchDateRange(days) {\n return finalGscDateRange(days);\n}\nfunction resolveSearchDateWindow(input = 28) {\n return typeof input === 'number' ? searchDateRange(input) : input;\n}\nexport async function querySearchAnalytics(site, body, opts = {}) {\n const { client } = await getAuthorized();\n const db = getDb();\n const queryHash = hashKey([site, body]);\n const cached = db\n .prepare('SELECT response_json, row_count FROM gsc_cache WHERE site_url = ? AND query_hash = ? AND expires_at > ?')\n .get(site, queryHash, Date.now());\n if (!opts.refresh && cached?.response_json) {\n const rows = JSON.parse(cached.response_json);\n return { rows, calls: 0, rowsFetched: cached.row_count ?? rows.length };\n }\n const encodedSite = encodeURIComponent(site);\n const allRows = [];\n const { maxRows: requestedMaxRows, ...apiBody } = body;\n const maxRows = requestedMaxRows ?? body.rowLimit;\n let startRow = 0;\n let calls = 0;\n while (true) {\n const remainingRows = typeof maxRows === 'number' ? maxRows - allRows.length : undefined;\n if (typeof remainingRows === 'number' && remainingRows <= 0) {\n break;\n }\n const rowLimit = Math.min(apiBody.rowLimit ?? 25_000, remainingRows ?? 25_000, 25_000);\n const requestBody = {\n ...apiBody,\n rowLimit,\n startRow,\n dataState: apiBody.dataState ?? 'final',\n dimensions: apiBody.dimensions ?? ['query', 'page'],\n type: apiBody.type ?? 'web',\n aggregationType: apiBody.aggregationType ?? 'auto',\n };\n const response = await authedFetch(client, `https://www.googleapis.com/webmasters/v3/sites/${encodedSite}/searchAnalytics/query`, {\n method: 'POST',\n body: JSON.stringify(requestBody),\n });\n calls += 1;\n if (!response.ok) {\n if (response.status === 429) {\n throw new SeoError('RATE_LIMITED', 'GSC rate limit hit. Back off for 15 minutes.');\n }\n if (response.status === 401) {\n throw new SeoError('AUTH_EXPIRED', 'Google rejected the access token. Run `seo auth login` again.');\n }\n if (response.status === 403) {\n throw new SeoError('ACCESS_DENIED', `Google Search Console denied access to ${site}. Check the selected Google account and property permissions.`);\n }\n if (response.status === 404) {\n throw new SeoError('PROPERTY_NOT_FOUND', `Google Search Console could not find ${site}. Check the property value and account access.`);\n }\n if (response.status >= 500) {\n throw new SeoError('PROVIDER_UNAVAILABLE', `Google Search Console is unavailable (${response.status}). Try again later.`);\n }\n throw new SeoError('PROVIDER_UNAVAILABLE', `GSC query failed with ${response.status}.`);\n }\n const json = (await response.json());\n const rows = json.rows ?? [];\n allRows.push(...rows);\n if (rows.length < rowLimit ||\n (typeof maxRows === 'number' && allRows.length >= maxRows)) {\n break;\n }\n startRow += rowLimit;\n }\n db.prepare(`INSERT OR REPLACE INTO gsc_cache\n (site_url, query_hash, request_json, response_json, row_count, fetched_at, expires_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`).run(site, queryHash, JSON.stringify(body), JSON.stringify(allRows), allRows.length, Date.now(), Date.now() + 86_400_000);\n return { rows: allRows, calls, rowsFetched: allRows.length };\n}\nexport async function queryPageMetrics(site, pageUrl, days = 28) {\n const { startDate, endDate } = searchDateRange(days);\n const result = await querySearchAnalytics(site, {\n startDate,\n endDate,\n dimensions: ['page'],\n dimensionFilterGroups: [\n {\n groupType: 'and',\n filters: [\n { dimension: 'page', operator: 'equals', expression: pageUrl },\n ],\n },\n ],\n });\n return result.rows[0]\n ? {\n clicks: result.rows[0].clicks,\n impressions: result.rows[0].impressions,\n ctr: result.rows[0].ctr,\n position: result.rows[0].position,\n }\n : undefined;\n}\nexport async function queryPagesMetrics(site, pageUrls, days = 28) {\n return (await queryPagesMetricsBatch(site, pageUrls, days)).values;\n}\nexport async function queryPagesMetricsBatch(site, pageUrls, range = 28) {\n const wanted = new Set(pageUrls);\n const retainedRowLimit = 25_000;\n if (!wanted.size) {\n return {\n values: new Map(),\n returnedRows: 0,\n retainedRowLimit,\n retainedRowLimitReached: false,\n };\n }\n const { startDate, endDate } = resolveSearchDateWindow(range);\n const result = await querySearchAnalytics(site, {\n startDate,\n endDate,\n dimensions: ['page'],\n rowLimit: retainedRowLimit,\n maxRows: retainedRowLimit,\n });\n const metrics = new Map();\n for (const row of result.rows) {\n const pageUrl = row.keys[0];\n if (!pageUrl || !wanted.has(pageUrl))\n continue;\n metrics.set(pageUrl, {\n clicks: row.clicks,\n impressions: row.impressions,\n ctr: row.ctr,\n position: row.position,\n });\n }\n return {\n values: metrics,\n returnedRows: result.rowsFetched,\n retainedRowLimit,\n retainedRowLimitReached: result.rowsFetched >= retainedRowLimit,\n };\n}\nexport async function queryPageTopQuery(site, pageUrl, days = 28) {\n const { startDate, endDate } = searchDateRange(days);\n const result = await querySearchAnalytics(site, {\n startDate,\n endDate,\n dimensions: ['query'],\n dimensionFilterGroups: [\n {\n groupType: 'and',\n filters: [\n { dimension: 'page', operator: 'equals', expression: pageUrl },\n ],\n },\n ],\n rowLimit: 10,\n });\n const row = result.rows[0];\n const query = row?.keys[0];\n return row && query\n ? {\n query,\n clicks: row.clicks,\n impressions: row.impressions,\n ctr: row.ctr,\n position: row.position,\n }\n : undefined;\n}\nexport async function queryPagesTopQueries(site, pageUrls, days = 28) {\n return (await queryPagesTopQueriesBatch(site, pageUrls, days)).values;\n}\nexport async function queryPagesTopQueriesBatch(site, pageUrls, range = 28) {\n const wanted = new Set(pageUrls);\n const retainedRowLimit = 25_000;\n if (!wanted.size) {\n return {\n values: new Map(),\n returnedRows: 0,\n retainedRowLimit,\n retainedRowLimitReached: false,\n };\n }\n const { startDate, endDate } = resolveSearchDateWindow(range);\n const result = await querySearchAnalytics(site, {\n startDate,\n endDate,\n dimensions: ['page', 'query'],\n rowLimit: retainedRowLimit,\n maxRows: retainedRowLimit,\n });\n const topQueries = new Map();\n for (const row of result.rows) {\n const pageUrl = row.keys[0];\n const query = row.keys[1];\n if (!pageUrl || !query || !wanted.has(pageUrl) || topQueries.has(pageUrl)) {\n continue;\n }\n topQueries.set(pageUrl, {\n query,\n clicks: row.clicks,\n impressions: row.impressions,\n ctr: row.ctr,\n position: row.position,\n });\n }\n return {\n values: topQueries,\n returnedRows: result.rowsFetched,\n retainedRowLimit,\n retainedRowLimitReached: result.rowsFetched >= retainedRowLimit,\n };\n}\n//# sourceMappingURL=search-analytics.js.map","import { getDb } from '../../storage/database.js';\nimport { authedFetch, getAuthorized } from './fetch.js';\nexport async function listSites(_refresh = false) {\n const { client } = await getAuthorized();\n const response = await authedFetch(client, 'https://www.googleapis.com/webmasters/v3/sites');\n if (!response.ok) {\n throw new Error(`GSC site list failed with ${response.status}.`);\n }\n const json = (await response.json());\n const entries = json.siteEntry ?? [];\n const db = getDb();\n const insert = db.prepare('INSERT OR REPLACE INTO sites (site_url, display_name, permission, added_at, is_default) VALUES (?, ?, ?, ?, COALESCE((SELECT is_default FROM sites WHERE site_url = ?), 0))');\n for (const site of entries) {\n insert.run(site.siteUrl, site.siteUrl, site.permissionLevel ?? null, Date.now(), site.siteUrl);\n }\n return entries;\n}\n//# sourceMappingURL=sites.js.map","import { hasMetaRobotsDirective, hasXRobotsDirective, } from '../robots-directives.js';\nfunction normalizedUrl(value) {\n try {\n const parsed = new URL(value);\n parsed.hash = '';\n if (parsed.pathname !== '/') {\n parsed.pathname = parsed.pathname.replace(/\\/$/, '');\n }\n return parsed.toString();\n }\n catch {\n return value.trim().replace(/\\/$/, '');\n }\n}\nexport function samePageUrl(left, right) {\n return normalizedUrl(left) === normalizedUrl(right);\n}\nfunction absoluteUrl(value, base) {\n try {\n return new URL(value, base).toString();\n }\n catch {\n return value;\n }\n}\nexport function pageTechnicalSignals(input) {\n const signals = [];\n if (input.httpStatus !== undefined &&\n (input.httpStatus < 200 || input.httpStatus > 299)) {\n signals.push('http-non-2xx');\n }\n if (input.httpStatus === 204 || input.httpStatus === 205) {\n signals.push('http-no-content');\n }\n if (input.fetchDiagnostics?.blocked)\n signals.push('blocked');\n if (input.fetchDiagnostics &&\n !input.fetchDiagnostics.fetched &&\n input.fetchDiagnostics.source !== 'cache') {\n signals.push('fetch-incomplete');\n }\n if ((input.fetchDiagnostics?.redirectChain?.length ?? 0) > 0 ||\n (input.page && !samePageUrl(input.url, input.page.finalUrl))) {\n signals.push('redirected');\n }\n if (hasMetaRobotsDirective(input.page?.metaRobots, 'noindex')) {\n signals.push('meta-noindex');\n }\n if (hasXRobotsDirective(input.page?.xRobotsTag, 'noindex')) {\n signals.push('x-robots-noindex');\n }\n if (input.page?.canonical &&\n !samePageUrl(input.page.finalUrl, absoluteUrl(input.page.canonical, input.page.finalUrl))) {\n signals.push('canonical-mismatch');\n }\n return signals;\n}\n//# sourceMappingURL=page-technical-signals.js.map","export const SERP_TITLE_REFERENCE_WIDTH_PX = 580;\nexport const SERP_TITLE_WIDTH_PROFILE = {\n id: 'arial-20-v1',\n fontFamily: 'Arial',\n fontSizePixels: 20,\n fontWeight: 400,\n};\n// Independently measured Arial 20px regular glyph advances, rounded to 0.1px.\nconst WIDTH_GROUPS = [\n [\"'\", 3.8],\n ['ijl', 4.4],\n ['|', 5.2],\n [' !,;:./\\\\[]ftI', 5.6],\n ['-(){}\\u0060r', 6.7],\n ['\"', 7.1],\n ['*', 7.8],\n ['^', 9.4],\n ['cJksvxyz', 10],\n ['?_#$0123456789abdeghnopquL', 11.1],\n ['+<=>~', 11.7],\n ['FTZ', 12.2],\n ['&ABEKPRSVXY', 13.3],\n ['CDHNUw', 14.4],\n ['GOQ', 15.6],\n ['mM', 16.7],\n ['%', 17.8],\n ['W', 18.9],\n ['@', 20.3],\n];\nconst ASCII_WIDTHS = new Map(WIDTH_GROUPS.flatMap(([characters, width]) => [...characters].map((character) => [character, width])));\nconst COMMON_UNICODE_WIDTHS = new Map([\n ['\\u00a0', 5.6],\n ['‘', 4.4],\n ['’', 4.4],\n ['“', 7.1],\n ['”', 7.1],\n ['–', 11.1],\n ['\\u2014', 20],\n ['…', 16.7],\n ['•', 7],\n]);\nconst KERNING_ADJUSTMENTS = new Map([\n ['AV', -1.5],\n ['VA', -1.5],\n ['AW', -0.7],\n ['WA', -0.7],\n ['To', -2.2],\n ['Ta', -2.2],\n ['Te', -2.2],\n ['Ty', -1.1],\n ['Yo', -1.8],\n ['LT', -1.5],\n ['FA', -1.1],\n ['PA', -1.5],\n ['We', -0.4],\n]);\nconst segmenter = new Intl.Segmenter('und', { granularity: 'grapheme' });\nfunction lowerConfidence(current, next) {\n const order = { high: 0, medium: 1, low: 2 };\n return order[next] > order[current] ? next : current;\n}\nfunction graphemeWidth(grapheme) {\n const direct = ASCII_WIDTHS.get(grapheme);\n if (direct !== undefined) {\n return { confidence: 'high', kerningCharacter: grapheme, width: direct };\n }\n const commonUnicode = COMMON_UNICODE_WIDTHS.get(grapheme);\n if (commonUnicode !== undefined) {\n return { confidence: 'high', width: commonUnicode };\n }\n if (/^[\\p{Mark}\\p{Format}]+$/u.test(grapheme)) {\n return { confidence: 'high', width: 0 };\n }\n const decomposed = grapheme.normalize('NFD');\n const base = [...decomposed].find((character) => !/\\p{Mark}/u.test(character));\n const latinWidth = base ? ASCII_WIDTHS.get(base) : undefined;\n if (latinWidth !== undefined &&\n /^\\p{Script=Latin}\\p{Mark}*$/u.test(decomposed)) {\n return { confidence: 'high', kerningCharacter: base, width: latinWidth };\n }\n if (/\\p{Extended_Pictographic}|\\p{Emoji_Presentation}|\\p{Regional_Indicator}|\\u20e3/u.test(grapheme)) {\n return { confidence: 'medium', width: 23 };\n }\n if (/^[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}\\p{Mark}]+$/u.test(grapheme)) {\n return { confidence: 'medium', width: 20 };\n }\n if (/^\\p{Script=Latin}\\p{Mark}*$/u.test(decomposed)) {\n return { confidence: 'medium', width: 11.1 };\n }\n return { confidence: 'low', width: 11.1 };\n}\nexport function estimateSerpTitleWidth(title) {\n const normalized = title.trim().replace(/\\s+/gu, ' ');\n const graphemes = [...segmenter.segment(normalized)].map((segment) => segment.segment);\n const fallbackGraphemes = [];\n let confidence = 'high';\n let previousKerningCharacter;\n let width = 0;\n for (const grapheme of graphemes) {\n const measured = graphemeWidth(grapheme);\n confidence = lowerConfidence(confidence, measured.confidence);\n if (measured.confidence === 'low' &&\n !fallbackGraphemes.includes(grapheme)) {\n fallbackGraphemes.push(grapheme);\n }\n if (previousKerningCharacter && measured.kerningCharacter) {\n width +=\n KERNING_ADJUSTMENTS.get(`${previousKerningCharacter}${measured.kerningCharacter}`) ?? 0;\n }\n width += measured.width;\n previousKerningCharacter = measured.kerningCharacter;\n }\n const estimatedPixels = Math.round(width * 10) / 10;\n return {\n estimatedPixels,\n referencePixels: SERP_TITLE_REFERENCE_WIDTH_PX,\n status: estimatedPixels > SERP_TITLE_REFERENCE_WIDTH_PX\n ? 'over-reference'\n : estimatedPixels >= SERP_TITLE_REFERENCE_WIDTH_PX - 30\n ? 'near-reference'\n : 'within-reference',\n confidence,\n profile: SERP_TITLE_WIDTH_PROFILE,\n graphemeCount: graphemes.length,\n fallbackGraphemes: fallbackGraphemes.slice(0, 10),\n };\n}\n//# sourceMappingURL=title-width.js.map","import { extractPage } from '../extract/page-extractor.js';\nimport { fetchPage } from '../fetch/page-fetcher.js';\nimport { queryPageMetrics } from '../gsc/client.js';\nimport { samePageUrl } from './page-technical-signals.js';\nimport { estimateSerpTitleWidth } from './title-width.js';\nexport const AUDIT_PAGE_RULE_IDS = [\n 'missing_title',\n 'title_too_wide',\n 'h1_missing',\n 'canonical_invalid',\n 'canonical_conflict',\n 'canonical_multiple',\n 'canonical_outside_head',\n 'canonical_mismatch',\n];\nconst defaultDependencies = {\n fetchPage,\n queryPageMetrics,\n now: () => new Date(),\n};\nfunction buildRecommendations(report) {\n const recommendations = [];\n const page = report.page;\n if (!page.title) {\n recommendations.push({\n principle: 'C.2',\n evidenceRef: 'The HTML document has no title element.',\n action: 'Add a concise, descriptive title that identifies this page.',\n effort: 'S',\n confidence: 'high',\n });\n }\n if (page.headings.every((heading) => heading.level !== 1)) {\n recommendations.push({\n principle: 'C.4',\n evidenceRef: 'The extracted document has no H1 heading.',\n action: 'Add a descriptive H1 for the page’s main visible topic.',\n effort: 'S',\n confidence: 'high',\n });\n }\n if (!page.canonical &&\n (!page.canonicalEvidence || page.canonicalEvidence.status === 'missing')) {\n recommendations.push({\n principle: 'C.7',\n evidenceRef: 'No canonical link tag detected.',\n action: 'If duplicate or parameter variants exist, declare the preferred canonical URL consistently; otherwise no change is required.',\n effort: 'S',\n confidence: 'medium',\n });\n }\n return recommendations;\n}\nexport async function auditPage(input, dependencies = defaultDependencies) {\n const fetched = await dependencies.fetchPage(input.url, {\n js: input.js,\n refresh: input.refresh,\n });\n const page = await extractPage(fetched, input.extractor);\n const h1s = page.headings.filter((heading) => heading.level === 1);\n const issues = [];\n if (!page.title) {\n issues.push({\n code: 'missing_title',\n title: 'Title missing',\n detail: 'No <title> element was found.',\n principle: 'C.2',\n evidenceRef: 'HTML document has no <title> element.',\n severity: 'high',\n });\n }\n if (page.title) {\n const titleWidth = estimateSerpTitleWidth(page.title);\n if (titleWidth.status === 'over-reference') {\n issues.push({\n code: 'title_too_wide',\n title: 'Title may truncate on some devices',\n detail: `Estimated title width ${titleWidth.estimatedPixels}px exceeds the ${titleWidth.referencePixels}px review reference.`,\n principle: 'C.3',\n evidenceRef: `Title width estimate: ${titleWidth.estimatedPixels}px using ${titleWidth.profile.id} (${titleWidth.confidence} confidence).`,\n severity: 'low',\n });\n }\n }\n if (h1s.length === 0) {\n issues.push({\n code: 'h1_missing',\n title: 'Missing H1',\n detail: 'No H1 element was found.',\n principle: 'C.4',\n evidenceRef: 'Detected 0 H1 elements.',\n severity: 'low',\n });\n }\n const canonicalEvidence = page.canonicalEvidence;\n if (canonicalEvidence?.status === 'conflicting') {\n const targets = [\n ...new Set(canonicalEvidence.candidates.flatMap((candidate) => candidate.resolved && !candidate.ignoredReason\n ? [candidate.resolved]\n : [])),\n ];\n issues.push({\n code: 'canonical_conflict',\n title: 'Canonical declarations conflict',\n detail: `Canonical declarations identify ${targets.length} different targets.`,\n principle: 'C.7',\n evidenceRef: `Canonical targets: ${targets.join(', ')}.`,\n severity: 'high',\n });\n }\n else if (canonicalEvidence?.status === 'duplicate') {\n issues.push({\n code: 'canonical_multiple',\n title: 'Canonical is declared more than once',\n detail: 'Multiple eligible declarations identify the same target; keep one canonical method.',\n principle: 'C.7',\n evidenceRef: `${canonicalEvidence.candidates.length} canonical declarations were found for ${canonicalEvidence.selectedUrl}.`,\n severity: 'low',\n });\n }\n else if (canonicalEvidence?.status === 'outside-head-only') {\n issues.push({\n code: 'canonical_outside_head',\n title: 'Canonical appears outside the document head',\n detail: 'Google only accepts HTML canonical link elements in the head.',\n principle: 'C.7',\n evidenceRef: `Ignored canonical value ${canonicalEvidence.candidates[0]?.raw ?? '(empty)'}.`,\n severity: 'medium',\n });\n }\n else if (canonicalEvidence?.status === 'invalid') {\n const raw = canonicalEvidence.candidates[0]?.raw ?? '(empty)';\n issues.push({\n code: 'canonical_invalid',\n title: 'Canonical URL is invalid',\n detail: 'The canonical link does not resolve to an HTTP or HTTPS URL.',\n principle: 'C.7',\n evidenceRef: `Canonical value ${raw} is not a valid HTTP or HTTPS URL.`,\n severity: 'high',\n });\n }\n else if (page.canonical) {\n let canonicalUrl;\n try {\n const resolved = new URL(page.canonical, page.finalUrl);\n if (['http:', 'https:'].includes(resolved.protocol)) {\n canonicalUrl = resolved.toString();\n }\n }\n catch {\n // Report invalid canonical evidence below.\n }\n if (!canonicalUrl) {\n issues.push({\n code: 'canonical_invalid',\n title: 'Canonical URL is invalid',\n detail: 'The canonical link does not resolve to an HTTP or HTTPS URL.',\n principle: 'C.7',\n evidenceRef: `Canonical value ${page.canonical} is not a valid HTTP or HTTPS URL.`,\n severity: 'high',\n });\n }\n else if (!samePageUrl(canonicalUrl, page.finalUrl)) {\n issues.push({\n code: 'canonical_mismatch',\n title: 'Canonical differs from final URL',\n detail: `Canonical points to ${canonicalUrl}, fetched final URL is ${page.finalUrl}.`,\n principle: 'C.7',\n evidenceRef: `Canonical ${canonicalUrl} differs from final URL ${page.finalUrl}.`,\n severity: 'medium',\n });\n }\n }\n const metrics = input.site\n ? await dependencies.queryPageMetrics(input.site, input.url)\n : undefined;\n const report = {\n url: input.url,\n fetchedAt: dependencies.now().toISOString(),\n page,\n fetchDiagnostics: fetched.diagnostics,\n metrics,\n issues,\n recommendations: [],\n warnings: page.warnings,\n };\n report.recommendations = buildRecommendations(report);\n return report;\n}\n//# sourceMappingURL=audit-page.js.map","import { querySearchAnalytics } from './gsc/client.js';\nimport { finalGscDateRange } from './gsc/dates.js';\nconst COUNTRY_CODE_SECOND_LEVELS = new Set([\n 'ac',\n 'co',\n 'com',\n 'edu',\n 'gov',\n 'net',\n 'org',\n]);\nfunction normalizeBrandText(value) {\n return value\n .normalize('NFKC')\n .replace(/([a-z])([A-Z])/g, '$1 $2')\n .toLowerCase()\n .replace(/^https?:\\/\\//, '')\n .replace(/^sc-domain:/, '')\n .replace(/[^\\p{L}\\p{N}]+/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\nfunction domainStem(siteUrl) {\n const value = siteUrl.replace(/^sc-domain:/, '').replace(/^https?:\\/\\//, '');\n const host = value.split('/')[0];\n if (!host)\n return undefined;\n const parts = host.split('.').filter(Boolean);\n if (!parts.length)\n return undefined;\n const last = parts.at(-1) ?? '';\n const secondLast = parts.at(-2) ?? '';\n const suffixDepth = last.length === 2 && COUNTRY_CODE_SECOND_LEVELS.has(secondLast) ? 2 : 1;\n return parts.at(-(suffixDepth + 1)) ?? parts[0];\n}\nfunction unique(values) {\n return [...new Set(values.map(normalizeBrandText).filter(Boolean))];\n}\nfunction tokenStem(token) {\n return token.length > 3 && token.endsWith('s') ? token.slice(0, -1) : token;\n}\nfunction tokensMatch(a, b) {\n return a === b || tokenStem(a) === tokenStem(b);\n}\nfunction includesTokenSequence(queryTokens, termTokens) {\n if (!termTokens.length || termTokens.length > queryTokens.length)\n return false;\n for (let index = 0; index <= queryTokens.length - termTokens.length; index++) {\n if (termTokens.every((termToken, offset) => tokensMatch(queryTokens[index + offset] ?? '', termToken))) {\n return true;\n }\n }\n return false;\n}\nexport function deriveBrandTerms(input) {\n const stem = domainStem(input.siteUrl);\n const candidates = [input.name, input.id, stem]\n .filter((value) => Boolean(value))\n .flatMap((value) => {\n const normalized = normalizeBrandText(value);\n const compact = normalized.replace(/\\s+/g, '');\n return [normalized, compact];\n });\n return unique(candidates);\n}\nexport function isBrandQuery(query, brandTerms) {\n const normalized = normalizeBrandText(query);\n if (!normalized || !brandTerms.length)\n return false;\n const queryTokens = normalized.split(' ');\n const compactQuery = normalized.replace(/\\s+/g, '');\n return brandTerms.some((term) => {\n const normalizedTerm = normalizeBrandText(term);\n if (!normalizedTerm)\n return false;\n const compactTerm = normalizedTerm.replace(/\\s+/g, '');\n const compactTermLength = [...compactTerm].length;\n const compactMatches = (compactTermLength >= 6 ||\n (/[^\\p{ASCII}]/u.test(compactTerm) && compactTermLength >= 2)) &&\n compactQuery.includes(compactTerm);\n const termTokens = normalizedTerm.split(' ');\n if (termTokens.length === 1) {\n return (queryTokens.some((queryToken) => tokensMatch(queryToken, normalizedTerm)) || compactMatches);\n }\n return includesTokenSequence(queryTokens, termTokens) || compactMatches;\n });\n}\nexport function shouldExcludeBrandQuery(input) {\n if (input.includeBrand)\n return false;\n const terms = input.brandTerms?.length\n ? input.brandTerms\n : deriveBrandTerms({ siteUrl: input.siteUrl });\n return isBrandQuery(input.query, terms);\n}\nfunction defaultDateRange(days = 28) {\n return finalGscDateRange(days);\n}\nfunction addCandidate(candidates, term, evidence) {\n const normalized = normalizeBrandText(term);\n if (!normalized)\n return;\n const existing = candidates.get(normalized) ?? {\n term: normalized,\n score: 0,\n evidence: [],\n };\n existing.score +=\n evidence.clicks * 2 +\n evidence.impressions * evidence.ctr +\n Math.max(0, 5 - evidence.position) * 10;\n existing.evidence.push(evidence);\n candidates.set(normalized, existing);\n}\nfunction isExactBrandVariant(query, terms) {\n const normalizedQuery = normalizeBrandText(query);\n const compactQuery = normalizedQuery.replace(/\\s+/g, '');\n return terms.some((term) => {\n const normalizedTerm = normalizeBrandText(term);\n const compactTerm = normalizedTerm.replace(/\\s+/g, '');\n return normalizedQuery === normalizedTerm || compactQuery === compactTerm;\n });\n}\nexport async function detectBrandTerms(input) {\n const derivedTerms = deriveBrandTerms({\n id: input.id,\n name: input.name,\n siteUrl: input.site,\n });\n const range = defaultDateRange(input.days ?? 28);\n const { rows } = await querySearchAnalytics(input.site, {\n ...range,\n dimensions: ['query'],\n type: 'web',\n dataState: 'final',\n }, { refresh: input.refresh });\n const minImpressions = input.minImpressions ?? 10;\n const candidates = new Map();\n for (const row of rows) {\n const query = row.keys[0] ?? '';\n if (row.impressions < minImpressions ||\n row.position > 3 ||\n row.ctr < 0.1 ||\n !isBrandQuery(query, derivedTerms)) {\n continue;\n }\n const evidence = {\n query,\n clicks: row.clicks,\n impressions: row.impressions,\n ctr: row.ctr,\n position: row.position,\n };\n const normalizedQuery = normalizeBrandText(query);\n const queryTokens = normalizedQuery.split(' ');\n if (queryTokens.length <= 4 &&\n (isExactBrandVariant(query, derivedTerms) || query.includes('.'))) {\n addCandidate(candidates, normalizedQuery, evidence);\n }\n for (const term of derivedTerms) {\n if (isBrandQuery(query, [term])) {\n addCandidate(candidates, term, evidence);\n }\n }\n }\n const ranked = [...candidates.values()]\n .map((candidate) => ({\n ...candidate,\n score: Number(candidate.score.toFixed(2)),\n evidence: candidate.evidence\n .sort((a, b) => b.clicks - a.clicks)\n .slice(0, 3),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, input.limit ?? 10);\n return {\n site: input.site,\n generatedAt: new Date().toISOString(),\n derivedTerms,\n suggestedTerms: ranked.length\n ? ranked.map((candidate) => candidate.term)\n : derivedTerms,\n candidates: ranked,\n };\n}\n//# sourceMappingURL=brand.js.map","import { isBrandQuery } from '../brand.js';\nimport { querySearchAnalytics } from '../gsc/client.js';\nimport { finalGscDateRange } from '../gsc/dates.js';\nexport const CTR_BASELINE = {\n 1: 0.27,\n 2: 0.15,\n 3: 0.1,\n 4: 0.07,\n 5: 0.05,\n 6: 0.035,\n 7: 0.025,\n 8: 0.02,\n 9: 0.015,\n 10: 0.012,\n};\nexport function normalizeText(value) {\n return value\n .normalize('NFKD')\n .replace(/\\p{Diacritic}/gu, '')\n .replace(/[’']/g, \"'\")\n .toLowerCase()\n .replace(/\\s+/g, ' ')\n .trim();\n}\nexport function unicodeTokens(value) {\n const normalized = normalizeText(value);\n if (typeof Intl !== 'undefined' && 'Segmenter' in Intl) {\n const segmenter = new Intl.Segmenter('und', { granularity: 'word' });\n return [...segmenter.segment(normalized)]\n .filter((part) => part.isWordLike)\n .map((part) => part.segment.trim())\n .filter((token) => token.length > 1);\n }\n return (normalized.match(/[\\p{L}\\p{N}]+/gu) ?? []).filter((token) => token.length > 1);\n}\nexport function tokenize(value) {\n return unicodeTokens(value);\n}\nexport function jaccard(a, b) {\n const setA = new Set(a);\n const setB = new Set(b);\n const intersection = [...setA].filter((token) => setB.has(token));\n const union = new Set([...setA, ...setB]);\n return union.size === 0 ? 0 : intersection.length / union.size;\n}\nexport function defaultDateRange(days = 28, now = new Date()) {\n return finalGscDateRange(days, now);\n}\nexport function looksLikeBrand(query, brandTerms = []) {\n return isBrandQuery(query, brandTerms);\n}\nexport async function fetchSiteQueryPageRows(site, days = 28, refresh = false, filters = []) {\n const range = defaultDateRange(days);\n return querySearchAnalytics(site, {\n ...range,\n dimensions: ['query', 'page'],\n type: 'web',\n dataState: 'final',\n dimensionFilterGroups: filters,\n }, { refresh });\n}\n//# sourceMappingURL=shared.js.map","import { normalizeText } from './shared.js';\nconst INTENT_PATTERNS = [\n {\n intent: 'forum/reddit',\n patterns: [\n { regex: /\\breddit\\b/, label: 'reddit' },\n { regex: /\\bforums?\\b/, label: 'forum' },\n ],\n action: 'Retrieve the page or pages associated with this query. If relevant pages lack practical first-party detail, add evidence, examples, and limitations without imitating forum posts.',\n },\n {\n intent: 'comparison',\n patterns: [\n { regex: /\\S+\\s+vs\\.?\\s+\\S+/, label: 'vs' },\n { regex: /\\S+\\s+versus\\s+\\S+/, label: 'versus' },\n {\n regex: /\\balternatives?\\s+to\\b|\\balternatives?\\s*$/,\n label: 'alternative comparison',\n },\n ],\n action: 'Retrieve the page or pages associated with this query. If relevant pages do not satisfy comparison intent, explain criteria, tradeoffs, alternatives, and which situations fit each option.',\n },\n {\n intent: 'reviews',\n patterns: [\n { regex: /\\breviews?\\b/, label: 'review' },\n { regex: /\\bcomplaints?\\b/, label: 'complaint' },\n { regex: /\\bworth\\s+it\\b/, label: 'worth it' },\n ],\n action: 'Retrieve the page or pages associated with this query. If relevant pages do not satisfy review intent, add original evidence, pros, cons, limitations, and suitable alternatives.',\n },\n {\n intent: 'experience',\n patterns: [\n { regex: /\\bfirst[ -]?hand\\b/, label: 'first-hand' },\n { regex: /\\bmy\\s+experience(?:\\s+with)?\\b/, label: 'my experience' },\n { regex: /\\bexperience\\s+with\\b/, label: 'experience with' },\n { regex: /\\bpeople\\s+say\\b/, label: 'people say' },\n { regex: /\\breal\\s+users?\\b/, label: 'real user' },\n { regex: /\\buser\\s+opinions?\\b/, label: 'user opinion' },\n ],\n action: 'Retrieve the page or pages associated with this query. If relevant pages do not satisfy experience-seeking intent, add genuine first-party examples, methodology, and clearly stated limitations.',\n },\n {\n intent: 'recommendation',\n patterns: [\n { regex: /\\bbest\\b/, label: 'best' },\n {\n regex: /\\brecommend(?:ed|ation|ations|ing)?\\b/,\n label: 'recommendation',\n },\n { regex: /\\btop\\s+\\d+\\b/, label: 'ranked list' },\n ],\n action: 'Retrieve the page or pages associated with this query. If relevant pages do not satisfy recommendation intent, make selection criteria, evidence, tradeoffs, and use-case fit explicit.',\n },\n];\nexport function classifyCommunityIntent(query) {\n const normalized = normalizeText(query);\n const matches = INTENT_PATTERNS.map((pattern) => ({\n pattern,\n terms: pattern.patterns\n .filter(({ regex }) => regex.test(normalized))\n .map(({ label }) => label),\n })).filter(({ terms }) => terms.length > 0);\n const primary = matches[0];\n if (!primary)\n return undefined;\n return {\n intent: primary.pattern.intent,\n signals: matches.map(({ pattern }) => pattern.intent),\n matchedTerms: matches.flatMap(({ terms }) => terms),\n confidence: 'low',\n method: 'query-language-heuristic',\n action: primary.pattern.action,\n };\n}\n//# sourceMappingURL=community-intent-classifier.js.map","import { SeoError } from '../../errors.js';\nimport { finalGscDateRange } from '../../gsc/dates.js';\nexport function integerOption(input) {\n if (input.value === undefined)\n return input.fallback;\n if (!Number.isInteger(input.value) ||\n input.value < input.minimum ||\n input.value > input.maximum) {\n throw new SeoError('INVALID_INPUT', `${input.label} must be a whole number between ${input.minimum} and ${input.maximum}.`);\n }\n return input.value;\n}\nexport function defaultDateRange(days, now) {\n return finalGscDateRange(days, now);\n}\nexport function explicitDateRange(input, maximumDays) {\n if (!input.startDate && !input.endDate)\n return undefined;\n if (!input.startDate || !input.endDate) {\n throw new SeoError('INVALID_INPUT', 'Start date and end date must be provided together.');\n }\n const pattern = /^\\d{4}-\\d{2}-\\d{2}$/;\n const start = new Date(`${input.startDate}T00:00:00.000Z`);\n const end = new Date(`${input.endDate}T00:00:00.000Z`);\n if (!pattern.test(input.startDate) ||\n !pattern.test(input.endDate) ||\n Number.isNaN(start.getTime()) ||\n Number.isNaN(end.getTime()) ||\n start.toISOString().slice(0, 10) !== input.startDate ||\n end.toISOString().slice(0, 10) !== input.endDate ||\n start > end) {\n throw new SeoError('INVALID_INPUT', 'Start date and end date must be valid YYYY-MM-DD values in ascending order.');\n }\n const days = Math.floor((end.getTime() - start.getTime()) / 86_400_000) + 1;\n if (days > maximumDays) {\n throw new SeoError('INVALID_INPUT', `Date range must not exceed ${maximumDays} days.`);\n }\n return {\n range: { startDate: input.startDate, endDate: input.endDate },\n days,\n };\n}\n//# sourceMappingURL=quick-wins-report-input.js.map","import { SeoError } from '../errors.js';\nimport { defaultDateRange, explicitDateRange, integerOption, } from './site-diagnostics/quick-wins-report-input.js';\nfunction subtractCalendarMonths(value, months) {\n const source = new Date(`${value}T00:00:00.000Z`);\n const first = new Date(Date.UTC(source.getUTCFullYear(), source.getUTCMonth() - months, 1));\n const lastDay = new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth() + 1, 0)).getUTCDate();\n first.setUTCDate(Math.min(source.getUTCDate(), lastDay));\n return first.toISOString().slice(0, 10);\n}\nexport function resolveQueryOpportunityInput(input, now) {\n if (!input.site.trim()) {\n throw new SeoError('INVALID_INPUT', 'site must not be empty.');\n }\n const days = integerOption({\n value: input.days,\n fallback: 28,\n minimum: 1,\n maximum: 548,\n label: 'days',\n });\n const explicit = explicitDateRange(input, 548);\n if (explicit && input.days !== undefined) {\n throw new SeoError('INVALID_INPUT', 'Use either days or an explicit startDate/endDate range, not both.');\n }\n const range = explicit?.range ?? defaultDateRange(days, now);\n const latestFinalDate = defaultDateRange(1, now).endDate;\n const pacificToday = new Date(`${latestFinalDate}T00:00:00.000Z`);\n pacificToday.setUTCDate(pacificToday.getUTCDate() + 4);\n const earliestDate = subtractCalendarMonths(pacificToday.toISOString().slice(0, 10), 16);\n if (range.endDate > latestFinalDate) {\n throw new SeoError('INVALID_INPUT', `endDate must be on or before the latest finalized GSC date, ${latestFinalDate}.`);\n }\n if (range.startDate < earliestDate) {\n throw new SeoError('INVALID_INPUT', `startDate must be on or after ${earliestDate}, the current 16-month GSC retention boundary.`);\n }\n return {\n days: explicit?.days ?? days,\n range,\n availableDateWindow: { earliestDate, latestFinalDate },\n limit: integerOption({\n value: input.limit,\n fallback: 25,\n minimum: 1,\n maximum: 100,\n label: 'limit',\n }),\n minImpressions: integerOption({\n value: input.minImpressions,\n fallback: 20,\n minimum: 0,\n maximum: 1_000_000_000,\n label: 'minImpressions',\n }),\n maxRows: integerOption({\n value: input.maxRows,\n fallback: 50_000,\n minimum: 1,\n maximum: 50_000,\n label: 'maxRows',\n }),\n };\n}\n//# sourceMappingURL=query-opportunity-input.js.map","function compareText(left, right) {\n const leftPoints = [...left].map((value) => value.codePointAt(0) ?? 0);\n const rightPoints = [...right].map((value) => value.codePointAt(0) ?? 0);\n for (let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index++) {\n const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);\n if (difference !== 0)\n return difference;\n }\n return leftPoints.length - rightPoints.length;\n}\nexport function compareQueryOpportunityRows(left, right) {\n return (right.impressions - left.impressions ||\n right.clicks - left.clicks ||\n left.position - right.position ||\n compareText(left.query, right.query));\n}\nfunction validRow(row, query) {\n return (row.keys.length === 1 &&\n Boolean(query) &&\n Number.isFinite(row.clicks) &&\n Number.isFinite(row.impressions) &&\n Number.isFinite(row.ctr) &&\n Number.isFinite(row.position) &&\n row.clicks >= 0 &&\n row.impressions > 0 &&\n row.clicks <= row.impressions &&\n row.ctr >= 0 &&\n row.ctr <= 1 &&\n row.position > 0);\n}\nfunction signature(row) {\n return `${row.clicks}\\u0000${row.impressions}\\u0000${row.ctr}\\u0000${row.position}`;\n}\nexport function normalizeQueryOpportunityRows(rows, selection) {\n const grouped = new Map();\n for (const row of rows) {\n const query = row.keys[0]?.trim() ?? '';\n if (!validRow(row, query)) {\n selection.invalidRows++;\n continue;\n }\n const group = grouped.get(query) ?? [];\n group.push(row);\n grouped.set(query, group);\n }\n const normalized = [];\n for (const [query, group] of grouped) {\n const signatures = new Set(group.map(signature));\n if (signatures.size > 1) {\n selection.conflictingRows += group.length;\n continue;\n }\n selection.duplicateRows += group.length - 1;\n const row = group[0];\n if (!row)\n continue;\n normalized.push({\n query,\n clicks: row.clicks,\n impressions: row.impressions,\n ctr: row.ctr,\n position: row.position,\n });\n }\n return normalized;\n}\n//# sourceMappingURL=query-opportunity-rows.js.map","import { shouldExcludeBrandQuery } from '../brand.js';\nimport { querySearchAnalytics } from '../gsc/client.js';\nimport { resolveQueryOpportunityInput } from './query-opportunity-input.js';\nimport { compareQueryOpportunityRows, normalizeQueryOpportunityRows, } from './query-opportunity-rows.js';\nexport const defaultQueryOpportunityDependencies = {\n searchAnalytics: querySearchAnalytics,\n now: () => new Date(),\n};\nexport async function queryOpportunityEvidence(input, dependencies = defaultQueryOpportunityDependencies) {\n const now = dependencies.now();\n const resolved = resolveQueryOpportunityInput(input, now);\n const result = await dependencies.searchAnalytics(input.site, {\n ...resolved.range,\n dimensions: ['query'],\n type: 'web',\n dataState: 'final',\n aggregationType: 'auto',\n maxRows: resolved.maxRows,\n }, { refresh: input.refresh });\n const selection = {\n sourceRows: result.rows.length,\n invalidRows: 0,\n duplicateRows: 0,\n conflictingRows: 0,\n brandRows: 0,\n belowMinimumRows: 0,\n eligibleRows: 0,\n };\n const rows = normalizeQueryOpportunityRows(result.rows, selection)\n .filter((row) => {\n if (row.impressions < resolved.minImpressions) {\n selection.belowMinimumRows++;\n return false;\n }\n if (shouldExcludeBrandQuery({\n query: row.query,\n siteUrl: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n })) {\n selection.brandRows++;\n return false;\n }\n return true;\n })\n .sort(compareQueryOpportunityRows);\n selection.eligibleRows = rows.length;\n const possiblyTruncated = result.rowsFetched >= resolved.maxRows;\n const warnings = [];\n if (possiblyTruncated) {\n warnings.push(`GSC reached the ${resolved.maxRows}-row retention cap. Lower-click queries may be missing.`);\n }\n if (selection.invalidRows > 0) {\n warnings.push(`${selection.invalidRows} malformed GSC rows were excluded.`);\n }\n if (selection.conflictingRows > 0) {\n warnings.push(`${selection.conflictingRows} conflicting duplicate GSC rows were excluded.`);\n }\n return {\n site: input.site,\n generatedAt: now.toISOString(),\n rangeDays: resolved.days,\n dateRange: resolved.range,\n filters: {\n limit: resolved.limit,\n minImpressions: resolved.minImpressions,\n maxRows: resolved.maxRows,\n },\n source: {\n provider: 'google-search-console',\n dimensions: ['query'],\n searchType: 'web',\n dataState: 'final',\n aggregationType: 'auto',\n rowsFetched: result.rowsFetched,\n calls: result.calls,\n maxRows: resolved.maxRows,\n possiblyTruncated,\n completeness: possiblyTruncated\n ? 'possibly-truncated'\n : 'retained-query-rows-only',\n availableDateWindow: {\n ...resolved.availableDateWindow,\n basis: 'rolling-16-month-retention-with-finalization-lag',\n },\n },\n selection,\n rows,\n warnings,\n caveats: [\n 'Search Console exposes retained top query rows and does not guarantee every query.',\n 'Clicks, impressions, CTR, and position are observed GSC metrics; classifications and generated prompts are heuristics.',\n ],\n };\n}\n//# sourceMappingURL=query-opportunity-source.js.map","import { classifyCommunityIntent, } from './community-intent-classifier.js';\nimport { defaultQueryOpportunityDependencies, queryOpportunityEvidence, } from './query-opportunity-source.js';\nexport * from './community-intent-classifier.js';\nfunction reportStatus(input) {\n if (input.sourceRows === 0)\n return 'empty';\n if (input.partial)\n return 'partial';\n return input.classifiedRows === 0 ? 'filtered' : 'available';\n}\nexport async function communityIntentReport(input, dependencies = defaultQueryOpportunityDependencies) {\n const evidence = await queryOpportunityEvidence(input, dependencies);\n const classified = evidence.rows.flatMap((row) => {\n const classification = classifyCommunityIntent(row.query);\n return classification ? [{ row, classification }] : [];\n });\n const items = classified\n .slice(0, evidence.filters.limit)\n .map(({ row, classification }) => ({\n ...row,\n intent: classification.intent,\n signals: classification.signals,\n matchedTerms: classification.matchedTerms,\n confidence: classification.confidence,\n evidenceScope: 'retained-gsc-query-language',\n action: classification.action,\n }));\n const partial = evidence.source.possiblyTruncated ||\n evidence.selection.invalidRows > 0 ||\n evidence.selection.conflictingRows > 0;\n const dataStatus = reportStatus({\n sourceRows: evidence.selection.sourceRows,\n classifiedRows: classified.length,\n partial,\n });\n const verdict = dataStatus === 'empty'\n ? 'GSC returned no retained query rows for this range.'\n : dataStatus === 'partial' && classified.length === 0\n ? 'No matching intent language appeared in the retained rows, but incomplete source evidence makes that negative inconclusive.'\n : dataStatus === 'partial'\n ? `Partial evidence: ${classified.length} retained queries matched explicit intent language, but incomplete source rows may omit other queries.`\n : dataStatus === 'filtered'\n ? `No retained ${input.includeBrand ? '' : 'non-brand '}queries met both the thresholds and the explicit intent-language rules.`\n : `${classified.length} retained queries matched explicit community, comparison, review, experience, or recommendation language; treat each as a review hypothesis.`;\n return {\n schemaVersion: 2,\n site: evidence.site,\n generatedAt: evidence.generatedAt,\n rangeDays: evidence.rangeDays,\n dateRange: evidence.dateRange,\n dataStatus,\n source: evidence.source,\n filters: {\n ...evidence.filters,\n brandFiltering: input.includeBrand ? 'included' : 'excluded',\n },\n methodology: {\n id: 'gsc_community_intent_query_heuristic',\n version: 2,\n classificationUnit: 'retained-query-row',\n classificationType: 'language-heuristic',\n classificationLanguage: 'english-patterns',\n pageContentVerified: false,\n estimatedTrafficLift: false,\n },\n selection: {\n ...evidence.selection,\n unclassifiedRows: evidence.rows.length - classified.length,\n classifiedRows: classified.length,\n returnedRows: items.length,\n limitedRows: classified.length - items.length,\n },\n summary: {\n classifiedQueries: classified.length,\n returnedQueries: items.length,\n returnedImpressions: items.reduce((sum, item) => sum + item.impressions, 0),\n returnedClicks: items.reduce((sum, item) => sum + item.clicks, 0),\n verdict,\n },\n items,\n warnings: evidence.warnings,\n caveats: [\n ...evidence.caveats,\n 'Intent labels come from explicit query-language patterns, not SERP, page-content, or audience research.',\n 'Classification patterns are English-only; non-English queries remain in source counts but may not be classified.',\n 'Review the ranking page and live search results before changing content.',\n ],\n };\n}\n//# sourceMappingURL=community-intent.js.map","import { extractPage } from '../extract/page-extractor.js';\nimport { fetchPage } from '../fetch/page-fetcher.js';\nimport { pageTechnicalSignals, } from './page-technical-signals.js';\nconst STOPWORDS = new Set([\n 'a',\n 'an',\n 'and',\n 'are',\n 'as',\n 'at',\n 'be',\n 'by',\n 'for',\n 'from',\n 'how',\n 'in',\n 'is',\n 'of',\n 'on',\n 'or',\n 'the',\n 'to',\n 'with',\n]);\nexport function normalizeForCoverage(value) {\n return value\n .normalize('NFKD')\n .replace(/\\p{Diacritic}/gu, '')\n .replace(/([\\p{L}\\p{N}])[’']([\\p{L}\\p{N}])/gu, '$1$2')\n .toLowerCase()\n .replace(/&/g, ' and ')\n .replace(/[^\\p{L}\\p{N}]+/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\nfunction hasNonAscii(value) {\n return [...value].some((character) => (character.codePointAt(0) ?? 0) > 127);\n}\nfunction queryTerms(query) {\n const tokens = normalizeForCoverage(query)\n .split(' ')\n .filter((token) => token.length > 1 || hasNonAscii(token));\n const meaningful = tokens.filter((token) => (token.length > 2 || hasNonAscii(token)) && !STOPWORDS.has(token));\n return [...new Set(meaningful.length ? meaningful : tokens)];\n}\nfunction countPhrase(query, text) {\n const normalizedQuery = normalizeForCoverage(query);\n const normalizedText = normalizeForCoverage(text);\n if (!normalizedQuery || !normalizedText)\n return 0;\n const pattern = new RegExp(`(?:^|\\\\s)${normalizedQuery.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}(?=\\\\s|$)`, 'g');\n return [...normalizedText.matchAll(pattern)].length;\n}\nexport function measureCoverage(query, text = '') {\n const terms = queryTerms(query);\n const normalizedText = normalizeForCoverage(text);\n const matchedTerms = terms.filter((term) => normalizedText\n .split(' ')\n .some((token) => token === term || token.startsWith(term)));\n const missingTerms = terms.filter((term) => !matchedTerms.includes(term));\n return {\n phraseCount: countPhrase(query, text),\n matchedTerms,\n missingTerms,\n termCoverage: terms.length ? matchedTerms.length / terms.length : 0,\n };\n}\nfunction displayQuery(coverage) {\n const query = coverage.query.trim();\n if (query.length <= 80)\n return query;\n const focus = coverage.queryTerms.slice(0, 7).join(' ');\n return focus || `${query.slice(0, 77)}...`;\n}\nfunction missingFieldNames(coverage) {\n const fields = [];\n if (coverage.fields.title.termCoverage < 0.8)\n fields.push('title');\n if (coverage.fields.h1.termCoverage < 0.8)\n fields.push('H1');\n if (coverage.fields.metaDescription.termCoverage < 0.8) {\n fields.push('meta description');\n }\n return fields;\n}\nfunction subjectVerb(count) {\n return count === 1 ? 'does' : 'do';\n}\nfunction gapScore(input) {\n let score = 0;\n if (input.title.termCoverage < 0.8)\n score += 3;\n if (input.h1.termCoverage < 0.8)\n score += 1;\n if (input.metaDescription.termCoverage < 0.8)\n score += 1;\n if (input.mainContent.termCoverage < 0.8)\n score += 5;\n return score;\n}\nexport function contentCoverageType(fields) {\n if (fields.mainContent.termCoverage < 0.8)\n return 'content-gap';\n if (fields.title.termCoverage < 0.8 ||\n fields.metaDescription.termCoverage < 0.8 ||\n fields.h1.termCoverage < 0.8) {\n return 'serp-framing';\n }\n return 'covered';\n}\nfunction classification(input) {\n const signals = [...input.technicalSignals];\n if (input.fields.title.phraseCount === 0) {\n signals.push('exact-phrase-missing');\n }\n if (input.fields.title.termCoverage < 0.8)\n signals.push('title-gap');\n if (input.fields.metaDescription.termCoverage < 0.8) {\n signals.push('meta-description-gap');\n }\n if (input.fields.h1.termCoverage < 0.8)\n signals.push('h1-gap');\n if (input.fields.mainContent.termCoverage < 0.8)\n signals.push('body-gap');\n if (input.technicalSignals.length > 0) {\n return { classification: 'technical-check', signals };\n }\n return { classification: contentCoverageType(input.fields), signals };\n}\nexport function contentCoverageRecommendation(coverage) {\n const focus = displayQuery(coverage);\n if (coverage.status === 'failed') {\n return 'I could not fetch or read the page, so do not change the content yet. Check the fetch error, blocking, or rendering issue first, then rerun this report.';\n }\n if (coverage.classification === 'technical-check') {\n return coverage.signals.includes('redirected') && coverage.finalUrl\n ? `This GSC URL resolves to ${coverage.finalUrl}. Confirm that this is the page Google should rank for \"${focus}\" before editing titles or copy.`\n : `Check whether this URL is indexable, canonical, and fetchable before editing copy for \"${focus}\". If the page has a technical issue, fix that first.`;\n }\n if (coverage.classification === 'content-gap') {\n const missing = coverage.fields.mainContent.missingTerms.slice(0, 4);\n return missing.length\n ? `The page ranks for \"${focus}\" but the main content does not clearly cover: ${missing.join(', ')}. Add a short, useful section or intro sentence that answers that angle directly.`\n : `The page ranks for \"${focus}\" but the main content does not clearly answer that angle. Add a short section that covers it directly.`;\n }\n if (coverage.classification === 'serp-framing') {\n const fields = missingFieldNames(coverage);\n const targetFields = fields.length ? fields.join(', ') : 'title and meta';\n return `The main content covers the important terms for \"${focus}\", but the ${targetFields} ${subjectVerb(fields.length)} not make that exact search angle clear enough. Test clearer wording there before rewriting the body.`;\n }\n return `The page already covers \"${focus}\". Do not add more copy for this query; test the title/meta, improve internal links, or check whether the SERP format is limiting clicks.`;\n}\nfunction coverageSummary(coverage) {\n if (coverage.status === 'failed') {\n return 'Content verification failed.';\n }\n if (coverage.classification === 'technical-check') {\n return coverage.signals.includes('redirected') && coverage.finalUrl\n ? `GSC URL resolves to ${coverage.finalUrl}; verify the canonical target first.`\n : 'Fetch diagnostics show a technical check is needed before judging content.';\n }\n if (coverage.classification === 'covered') {\n return 'The page covers the query across the main on-page signals.';\n }\n const title = coverage.fields.title.phraseCount > 0;\n const h1 = coverage.fields.h1.phraseCount > 0;\n const body = coverage.fields.mainContent.phraseCount > 0;\n const bodyTerms = Math.round(coverage.fields.mainContent.termCoverage * 100);\n if (title && h1 && body) {\n return 'Exact query appears in title, H1, and main content.';\n }\n if (bodyTerms >= 100) {\n return 'Main content covers every meaningful query term, but exact SERP wording may be weak.';\n }\n return `Main content covers ${bodyTerms}% of meaningful query terms.`;\n}\nexport function queryContentCoverageFromPage(input) {\n const fields = queryContentFieldsFromPage(input.query, input.page);\n const technicalSignals = pageTechnicalSignals({\n url: input.url,\n page: input.page,\n fetchDiagnostics: input.fetchDiagnostics,\n httpStatus: input.httpStatus,\n });\n const classified = classification({\n technicalSignals,\n fields,\n });\n const coverage = {\n verifiedAt: input.verifiedAt ?? new Date().toISOString(),\n query: input.query,\n url: input.url,\n finalUrl: input.page.finalUrl,\n status: 'verified',\n httpStatus: input.httpStatus,\n warnings: [...new Set([...(input.warnings ?? []), ...input.page.warnings])],\n wordCount: input.page.wordCount,\n fetchDiagnostics: input.fetchDiagnostics,\n contentGapScore: gapScore(fields),\n queryTerms: queryTerms(input.query),\n fields,\n classification: classified.classification,\n signals: classified.signals,\n recommendation: '',\n summary: '',\n };\n return {\n ...coverage,\n recommendation: contentCoverageRecommendation(coverage),\n summary: coverageSummary(coverage),\n };\n}\nexport function queryContentFieldsFromPage(query, page) {\n return {\n title: measureCoverage(query, page.title),\n h1: measureCoverage(query, page.headings\n .filter((heading) => heading.level === 1)\n .map((heading) => heading.text)\n .join(' ')),\n metaDescription: measureCoverage(query, page.metaDescription),\n mainContent: measureCoverage(query, page.contentText),\n };\n}\nexport async function verifyQueryContent(input) {\n let fetched;\n try {\n fetched = await (input.fetch ?? fetchPage)(input.url, {\n js: input.js ?? 'auto',\n refresh: input.refresh,\n rate: input.rate,\n });\n const page = await (input.extract ?? extractPage)(fetched, 'defuddle');\n return queryContentCoverageFromPage({\n query: input.query,\n url: input.url,\n page,\n fetchDiagnostics: fetched.diagnostics,\n httpStatus: fetched.status,\n warnings: fetched.warnings,\n verifiedAt: input.verifiedAt,\n });\n }\n catch (error) {\n const technicalSignals = pageTechnicalSignals({\n url: input.url,\n fetchDiagnostics: fetched?.diagnostics,\n httpStatus: fetched?.status,\n });\n return {\n verifiedAt: input.verifiedAt ?? new Date().toISOString(),\n query: input.query,\n url: input.url,\n status: 'failed',\n error: error instanceof Error ? error.message : String(error),\n httpStatus: fetched?.status,\n warnings: fetched?.warnings ?? [],\n wordCount: undefined,\n fetchDiagnostics: fetched?.diagnostics,\n contentGapScore: 0,\n queryTerms: queryTerms(input.query),\n fields: {\n title: measureCoverage(input.query),\n h1: measureCoverage(input.query),\n metaDescription: measureCoverage(input.query),\n mainContent: measureCoverage(input.query),\n },\n classification: 'fetch-failed',\n signals: technicalSignals,\n recommendation: 'Verification failed; inspect fetch diagnostics before making content calls.',\n summary: 'Content verification failed.',\n };\n }\n}\n//# sourceMappingURL=content-coverage.js.map","import { samePageUrl } from './page-technical-signals.js';\nimport { CTR_BASELINE, unicodeTokens } from './shared.js';\nexport { unicodeTokens } from './shared.js';\nconst MIN_BENCHMARK_URL_IMPRESSIONS = 30;\nconst MIN_BENCHMARK_IMPRESSIONS = 1000;\nconst MIN_BENCHMARK_URL_SAMPLES = 5;\nconst MIN_POSITIVE_URL_SAMPLES = 3;\nconst SITE_BENCHMARK_FLOOR_MULTIPLIER = 0.5;\nconst SITE_BENCHMARK_CAP_MULTIPLIER = 1.5;\nexport function roundedPosition(position) {\n return Math.max(1, Math.min(10, Math.round(position)));\n}\nexport function expectedCtrForPosition(position) {\n return CTR_BASELINE[roundedPosition(position)] ?? 0.01;\n}\nfunction percentile(values, percentileValue) {\n if (values.length === 0)\n return undefined;\n const sorted = [...values].sort((a, b) => a - b);\n const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil((percentileValue / 100) * sorted.length) - 1));\n return sorted[index];\n}\nfunction bucketBenchmark(input) {\n const peerRows = input.rows.filter((row) => !input.excludedRows?.has(row));\n const impressions = peerRows.reduce((sum, row) => sum + row.impressions, 0);\n const byUrl = new Map();\n for (const row of peerRows) {\n const key = row.keys?.[1] || `${row.keys?.[0] ?? 'query'}:${row.position}`;\n const current = byUrl.get(key) ?? { clicks: 0, impressions: 0 };\n current.clicks += row.clicks;\n current.impressions += row.impressions;\n byUrl.set(key, current);\n }\n const qualifiedSamples = [...byUrl.values()].filter((sample) => sample.impressions >= MIN_BENCHMARK_URL_IMPRESSIONS);\n const urlCtrSamples = qualifiedSamples.map((sample) => sample.clicks / sample.impressions);\n const positiveUrlCtrSamples = urlCtrSamples.filter((ctr) => ctr > 0);\n const qualifiedImpressions = qualifiedSamples.reduce((sum, sample) => sum + sample.impressions, 0);\n const hasEnoughSiteData = qualifiedImpressions >= MIN_BENCHMARK_IMPRESSIONS &&\n urlCtrSamples.length >= MIN_BENCHMARK_URL_SAMPLES &&\n positiveUrlCtrSamples.length >= MIN_POSITIVE_URL_SAMPLES;\n const fallbackCtr = expectedCtrForPosition(input.position);\n const samplePopulation = input.samplePopulation ?? 'positive_url_samples';\n const percentileSamples = samplePopulation === 'all_qualified_url_samples'\n ? urlCtrSamples\n : positiveUrlCtrSamples;\n const rawSiteCtr = hasEnoughSiteData\n ? percentile(percentileSamples, 75)\n : undefined;\n const floorCtr = fallbackCtr * SITE_BENCHMARK_FLOOR_MULTIPLIER;\n const capCtr = fallbackCtr * SITE_BENCHMARK_CAP_MULTIPLIER;\n const hasSiteCtr = rawSiteCtr !== undefined;\n const ctr = hasSiteCtr\n ? Math.max(floorCtr, Math.min(rawSiteCtr, capCtr))\n : fallbackCtr;\n const adjustment = hasSiteCtr && rawSiteCtr < floorCtr\n ? '_floored'\n : hasSiteCtr && rawSiteCtr > capCtr\n ? '_capped'\n : '';\n const source = hasSiteCtr\n ? `site_gsc_position_bucket_robust_p75${samplePopulation === 'all_qualified_url_samples' ? '_all_samples' : ''}${input.sourceSuffix ?? ''}${adjustment}`\n : (input.fallbackSource ?? 'default_position_curve');\n return {\n ctr: Number(ctr.toFixed(4)),\n source,\n samplePopulation,\n rows: peerRows.length,\n impressions,\n qualifiedImpressions,\n urlSamples: urlCtrSamples.length,\n positiveUrlSamples: positiveUrlCtrSamples.length,\n };\n}\nfunction smoothMonotonicBenchmarks(input) {\n const byPosition = {};\n let previousCtr = Number.POSITIVE_INFINITY;\n for (const position of Object.keys(CTR_BASELINE).map(Number)) {\n const benchmark = input[position] ?? bucketBenchmark({ rows: [], position });\n const ctr = Math.min(benchmark.ctr, previousCtr);\n const smoothed = ctr < benchmark.ctr;\n previousCtr = ctr;\n byPosition[String(position)] = {\n ...benchmark,\n ctr: Number(ctr.toFixed(4)),\n source: smoothed\n ? `${benchmark.source}_monotonic_smoothed`\n : benchmark.source,\n };\n }\n return byPosition;\n}\nexport function createCtrBenchmarkContext(rows, options = {}) {\n const buckets = new Map();\n for (const row of rows) {\n const position = roundedPosition(row.position);\n buckets.set(position, [...(buckets.get(position) ?? []), row]);\n }\n const raw = {};\n for (const position of Object.keys(CTR_BASELINE).map(Number)) {\n raw[position] = bucketBenchmark({\n rows: buckets.get(position) ?? [],\n position,\n samplePopulation: options.samplePopulation,\n fallbackSource: options.fallbackSource,\n });\n }\n const byPosition = smoothMonotonicBenchmarks(raw);\n function benchmarkForRow(row, excludedRows, sourceSuffix) {\n const position = roundedPosition(row.position);\n const excludedSet = new Set(excludedRows);\n const rowRaw = {};\n for (const bucketPosition of Object.keys(CTR_BASELINE).map(Number)) {\n rowRaw[bucketPosition] = bucketBenchmark({\n rows: buckets.get(bucketPosition) ?? [],\n position: bucketPosition,\n excludedRows: excludedSet,\n sourceSuffix,\n samplePopulation: options.samplePopulation,\n fallbackSource: options.fallbackSource,\n });\n }\n return (smoothMonotonicBenchmarks(rowRaw)[String(position)] ??\n byPosition[String(position)] ??\n bucketBenchmark({ rows: [], position }));\n }\n return {\n byPosition,\n forRow(row) {\n return benchmarkForRow(row, [row], '_leave_one_out');\n },\n forUrl(row) {\n const url = row.keys?.[1];\n const excludedRows = url\n ? rows.filter((candidate) => samePageUrl(candidate.keys?.[1] ?? '', url))\n : [row];\n return benchmarkForRow(row, excludedRows, '_leave_target_url_out');\n },\n forAggregate(row, excludedRows = []) {\n return benchmarkForRow(row, excludedRows, excludedRows.length ? '_leave_group_out' : undefined);\n },\n };\n}\nexport function queryFieldCoverage(query, input) {\n const tokens = unicodeTokens(query).filter((token) => token.length > 2);\n if (query.trim() && tokens.length === 0) {\n return {\n evaluated: false,\n reason: 'coverage_not_evaluated_for_script',\n queryTokens: tokens,\n inTitle: false,\n inMetaDescription: false,\n inH1: false,\n inOpeningCopy: false,\n };\n }\n const hasToken = (value) => {\n const haystack = new Set(unicodeTokens(value ?? ''));\n return tokens.length > 0 && tokens.some((token) => haystack.has(token));\n };\n return {\n evaluated: true,\n queryTokens: tokens,\n inTitle: hasToken(input.title),\n inMetaDescription: hasToken(input.meta),\n inH1: hasToken(input.h1),\n inOpeningCopy: hasToken(input.opening),\n };\n}\nexport function pageEvidenceRecommendation(input) {\n if (!input.coverage.evaluated) {\n return 'Coverage was not evaluated for this query script, so do not infer a title, meta, H1, or copy gap from token matching alone. Use manual SERP and page review before editing.';\n }\n const missing = [\n !input.coverage.inTitle ? 'title' : undefined,\n !input.coverage.inMetaDescription ? 'meta description' : undefined,\n !input.coverage.inH1 ? 'H1' : undefined,\n !input.coverage.inOpeningCopy ? 'opening copy' : undefined,\n ].filter((field) => Boolean(field));\n return missing.length\n ? `Check ${missing.join(', ')} first. The page ranks already, but the main SERP-facing fields do not clearly reflect \"${input.query}\".`\n : 'The query already appears in the main extracted fields. Avoid a blind rewrite; compare SERP intent, snippets, and competing titles before changing the page.';\n}\nexport function queryOpportunityRecommendation(input) {\n const percent = (value) => `${(value * 100).toFixed(value >= 0.1 ? 1 : 2)}%`;\n const rounded = roundedPosition(input.position);\n return {\n title: `Review SERP framing for \"${input.query}\".`,\n reason: `The page already ranks around position ${rounded}, but CTR is ${percent(input.ctr)} against an expected ${percent(input.expectedCtr)} for that position.`,\n expectedImpact: `About ${Math.round(input.estimatedClickLift)} extra clicks in the selected GSC window if CTR reaches the benchmark.`,\n };\n}\n//# sourceMappingURL=opportunity-primitives.js.map","import { contentCoverageType, queryContentFieldsFromPage, } from './content-coverage.js';\nimport { pageTechnicalSignals } from './page-technical-signals.js';\nexport { pageTechnicalSignals as technicalPageSignals };\nexport function verificationFor(input) {\n const signals = pageTechnicalSignals(input);\n if (signals.length > 0) {\n return {\n status: 'technical-check',\n reason: 'Fetch or indexability evidence needs checking before making an on-page recommendation.',\n signals,\n httpStatus: input.httpStatus,\n };\n }\n if (!input.page) {\n return {\n status: 'unverified',\n reason: input.fetchDiagnostics?.fetched\n ? 'The page was fetched, but extracted content was not available for verification.'\n : 'On-page content was not verified for this analysis.',\n signals: [],\n httpStatus: input.httpStatus,\n };\n }\n return {\n status: 'verified',\n reason: 'The recommendation uses extracted on-page evidence.',\n signals: [],\n httpStatus: input.httpStatus,\n fields: queryContentFieldsFromPage(input.query, input.page),\n };\n}\nexport function opportunityType(input) {\n if (input.verification.status === 'technical-check')\n return 'technical-check';\n if (input.verification.status === 'verified' && input.verification.fields) {\n const coverageType = contentCoverageType(input.verification.fields);\n if (coverageType !== 'covered')\n return coverageType;\n }\n if (input.position > 10)\n return 'ranking';\n if (input.expectedCtr !== undefined && input.ctr < input.expectedCtr * 0.65) {\n return 'ctr';\n }\n return input.verification.status === 'verified' ? 'covered' : 'unverified';\n}\nexport function recommendationFor(input) {\n if (input.type === 'technical-check') {\n return `Check fetchability, indexability, redirects, and canonical signals for this URL before changing content for \"${input.query}\".`;\n }\n if (input.type === 'unverified') {\n const signal = input.position > 10\n ? 'GSC shows the query outside page one.'\n : 'GSC shows page-one visibility.';\n return `${signal} Verify the live page and current SERP intent before deciding whether content, internal links, or snippet wording needs work.`;\n }\n if (input.type === 'content-gap') {\n return `The extracted copy does not clearly cover the main terms in \"${input.query}\". Confirm the search intent, then improve the existing answer if the query belongs on this page.`;\n }\n if (input.type === 'serp-framing') {\n return `The extracted body covers \"${input.query}\", but the title, meta description, or H1 does not reflect it clearly. Check the live SERP before testing more precise framing.`;\n }\n if (input.type === 'ranking') {\n return 'This query ranks outside page one, so no CTR lift is claimed. Check intent fit, content quality, internal links, and competing pages before choosing an edit.';\n }\n if (input.type === 'ctr') {\n return 'This page-one query is below its directional CTR benchmark. Review the live SERP, then test title and meta-description framing without assuming the body needs rewriting.';\n }\n return `The extracted page covers \"${input.query}\" and its CTR is not materially below the benchmark. Avoid a blind rewrite; monitor the query and inspect the SERP for format changes.`;\n}\nexport function benchmarkDetails(benchmark, excludedTargetRows) {\n if (!benchmark) {\n return {\n applicable: false,\n source: 'not_applicable_outside_page_one',\n peerRows: 0,\n peerImpressions: 0,\n qualifiedPeerImpressions: 0,\n urlSamples: 0,\n positiveUrlSamples: 0,\n excludedTargetRows,\n };\n }\n return {\n applicable: true,\n expectedCtr: benchmark.ctr,\n source: benchmark.source,\n peerRows: benchmark.rows,\n peerImpressions: benchmark.impressions,\n qualifiedPeerImpressions: benchmark.qualifiedImpressions,\n urlSamples: benchmark.urlSamples,\n positiveUrlSamples: benchmark.positiveUrlSamples,\n excludedTargetRows,\n };\n}\n//# sourceMappingURL=page-opportunities-evidence.js.map","import { tokenize } from './shared.js';\nfunction hasLetter(value) {\n return /\\p{L}/u.test(value);\n}\nfunction hasDigit(value) {\n return /\\d/.test(value);\n}\nfunction looksLikeSearchOperatorDump(query) {\n const lower = query.toLowerCase();\n const operatorCount = (lower.match(/(?:^|\\s)-?(?:site|filetype):/g) ?? [])\n .length;\n return (query.length > 120 &&\n (lower.includes('x_keyword_search') ||\n lower.includes('min_faves') ||\n lower.includes('filter:') ||\n lower.includes(' since:') ||\n lower.includes(' until:') ||\n operatorCount >= 3));\n}\nfunction looksLikeSearchOperatorQuery(query) {\n const lower = query.toLowerCase();\n return /(?:^|\\s)-?(?:site|filetype|inurl|intitle|intext):\\S+/.test(lower);\n}\nfunction looksLikeInternalSnippet(query) {\n const lower = query.toLowerCase();\n return lower.includes('ranking/') || /\\bmoved up\\b/.test(lower);\n}\nfunction looksLikeDomainQuery(query) {\n return /^[a-z0-9][a-z0-9.-]*\\.[a-z]{2,}$/i.test(query.trim());\n}\nexport function isSearchArtifactQuery(query) {\n const tokens = tokenize(query);\n if (!tokens.length)\n return true;\n return (looksLikeSearchOperatorQuery(query) ||\n looksLikeSearchOperatorDump(query) ||\n looksLikeInternalSnippet(query) ||\n looksLikeDomainQuery(query));\n}\nexport function isLowActionabilityQuery(query) {\n const tokens = tokenize(query);\n if (!tokens.length || !hasLetter(query))\n return true;\n if (isSearchArtifactQuery(query))\n return true;\n const letterTokens = tokens.filter(hasLetter);\n if (tokens.length === 1 && hasDigit(tokens[0] ?? ''))\n return true;\n if (letterTokens.length <= 1 && tokens.some(hasDigit))\n return true;\n return false;\n}\n//# sourceMappingURL=query-quality.js.map","import { shouldExcludeBrandQuery } from '../brand.js';\nimport { samePageUrl } from './page-technical-signals.js';\nimport { isLowActionabilityQuery } from './query-quality.js';\nconst DEFAULT_MIN_IMPRESSIONS = 10;\nconst DEFAULT_LIMIT = 25;\nconst MAX_LIMIT = 100;\nfunction integerInRange(value, fallback, minimum, maximum) {\n if (value === undefined || !Number.isFinite(value))\n return fallback;\n return Math.min(maximum, Math.max(minimum, Math.floor(value)));\n}\nfunction isHttpUrl(value) {\n try {\n const parsed = new URL(value);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n }\n catch {\n return false;\n }\n}\nfunction hasValidMetrics(row) {\n return (Number.isFinite(row.clicks) &&\n Number.isFinite(row.impressions) &&\n Number.isFinite(row.ctr) &&\n Number.isFinite(row.position) &&\n row.clicks >= 0 &&\n row.impressions > 0 &&\n row.clicks <= row.impressions &&\n row.ctr >= 0 &&\n row.ctr <= 1 &&\n row.position > 0);\n}\nfunction isBrandRow(input) {\n return shouldExcludeBrandQuery({\n query: input.query,\n siteUrl: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n}\nexport function normalizePageOpportunityOptions(input) {\n return {\n minImpressions: integerInRange(input.minImpressions, DEFAULT_MIN_IMPRESSIONS, 1, Number.MAX_SAFE_INTEGER),\n limit: integerInRange(input.limit, DEFAULT_LIMIT, 1, MAX_LIMIT),\n };\n}\nexport function selectTargetRows(input) {\n const selection = {\n sourceRows: input.rows.length,\n invalidRows: 0,\n wrongPageRows: 0,\n belowMinimumRows: 0,\n lowActionabilityRows: 0,\n brandRows: 0,\n eligibleRows: 0,\n returnedRows: 0,\n limitedRows: 0,\n };\n const eligibleRows = [];\n for (const row of input.rows) {\n const query = row.keys[0]?.trim() ?? '';\n const page = row.keys[1] ?? '';\n if (row.keys.length < 2 ||\n !query ||\n !isHttpUrl(page) ||\n !hasValidMetrics(row)) {\n selection.invalidRows++;\n continue;\n }\n if (!samePageUrl(page, input.url)) {\n selection.wrongPageRows++;\n continue;\n }\n if (row.impressions < input.minImpressions) {\n selection.belowMinimumRows++;\n continue;\n }\n if (isLowActionabilityQuery(query)) {\n selection.lowActionabilityRows++;\n continue;\n }\n if (isBrandRow({\n query,\n site: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n })) {\n selection.brandRows++;\n continue;\n }\n selection.eligibleRows++;\n eligibleRows.push(row);\n }\n return { eligibleRows, selection };\n}\nexport function selectBenchmarkRows(input) {\n return input.rows.filter((row) => {\n const query = row.keys[0]?.trim() ?? '';\n return (row.keys.length >= 2 &&\n isHttpUrl(row.keys[1] ?? '') &&\n hasValidMetrics(row) &&\n row.position >= 1 &&\n row.position <= 10 &&\n Boolean(query) &&\n !isLowActionabilityQuery(query) &&\n !isBrandRow({\n query,\n site: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n }));\n });\n}\n//# sourceMappingURL=page-opportunities-selection.js.map","import { createCtrBenchmarkContext } from './opportunity-primitives.js';\nimport { benchmarkDetails, opportunityType, recommendationFor, verificationFor, } from './page-opportunities-evidence.js';\nimport { normalizePageOpportunityOptions, selectBenchmarkRows, selectTargetRows, } from './page-opportunities-selection.js';\nimport { samePageUrl } from './page-technical-signals.js';\nexport { technicalPageSignals } from './page-opportunities-evidence.js';\nfunction compareText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\nfunction compareItems(left, right) {\n return ((right.estimatedCtrClickShortfall ?? -1) -\n (left.estimatedCtrClickShortfall ?? -1) ||\n right.impressions - left.impressions ||\n left.position - right.position ||\n compareText(left.query, right.query) ||\n compareText(left.url, right.url));\n}\nfunction analyzeRow(input) {\n const query = input.row.keys[0]?.trim() ?? '';\n const pageOne = input.row.position >= 1 && input.row.position <= 10;\n const benchmark = pageOne\n ? input.benchmarkContext.forAggregate(input.row, input.excludedTargetRows)\n : undefined;\n const expectedClicks = benchmark\n ? Number((benchmark.ctr * input.row.impressions).toFixed(2))\n : undefined;\n const estimatedCtrClickShortfall = benchmark\n ? Number(Math.max(0, benchmark.ctr * input.row.impressions - input.row.clicks).toFixed(2))\n : undefined;\n const verification = verificationFor({\n query,\n url: input.reportInput.url,\n page: input.reportInput.page,\n fetchDiagnostics: input.reportInput.fetchDiagnostics,\n httpStatus: input.reportInput.httpStatus,\n });\n const type = opportunityType({\n position: input.row.position,\n ctr: input.row.ctr,\n expectedCtr: benchmark?.ctr,\n verification,\n });\n return {\n query,\n url: input.row.keys[1] ?? input.reportInput.url,\n clicks: input.row.clicks,\n impressions: input.row.impressions,\n ctr: input.row.ctr,\n position: input.row.position,\n expectedCtr: benchmark?.ctr,\n expectedClicks,\n estimatedCtrClickShortfall,\n estimatedClickLift: estimatedCtrClickShortfall,\n opportunityType: type,\n benchmark: benchmarkDetails(benchmark, input.excludedTargetRows.length),\n verification,\n recommendation: recommendationFor({\n query,\n position: input.row.position,\n type,\n }),\n };\n}\nexport function analyzePageOpportunitiesFromRows(input) {\n const { minImpressions, limit } = normalizePageOpportunityOptions(input);\n const { eligibleRows, selection } = selectTargetRows({\n rows: input.targetRows,\n site: input.site,\n url: input.url,\n minImpressions,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n const benchmarkRows = selectBenchmarkRows({\n rows: input.benchmarkRows,\n site: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n const excludedTargetRows = benchmarkRows.filter((row) => samePageUrl(row.keys[1] ?? '', input.url));\n const benchmarkContext = createCtrBenchmarkContext(benchmarkRows);\n const items = eligibleRows\n .map((row) => analyzeRow({\n row,\n reportInput: input,\n benchmarkContext,\n excludedTargetRows,\n }))\n .sort(compareItems)\n .slice(0, limit);\n const estimatedCtrClickShortfall = Number(items\n .reduce((sum, item) => sum + (item.estimatedCtrClickShortfall ?? 0), 0)\n .toFixed(2));\n return {\n site: input.site,\n url: input.url,\n minImpressions,\n limit,\n httpStatus: input.httpStatus,\n dataStatus: input.targetRows.length === 0\n ? 'empty'\n : eligibleRows.length === 0\n ? 'filtered'\n : 'available',\n sourceRows: input.targetRows.length,\n eligibleRows: eligibleRows.length,\n returnedRows: items.length,\n benchmarkSourceRows: input.benchmarkRows.length,\n benchmarkEligibleRows: benchmarkRows.length,\n excludedTargetBenchmarkRows: excludedTargetRows.length,\n selection: {\n ...selection,\n returnedRows: items.length,\n limitedRows: Math.max(0, eligibleRows.length - items.length),\n },\n items,\n summary: {\n clicks: items.reduce((sum, item) => sum + item.clicks, 0),\n impressions: items.reduce((sum, item) => sum + item.impressions, 0),\n opportunities: items.filter((item) => item.opportunityType !== 'covered' &&\n item.opportunityType !== 'unverified').length,\n estimatedCtrClickShortfall,\n estimatedClickLift: estimatedCtrClickShortfall,\n },\n };\n}\n//# sourceMappingURL=page-opportunities-analysis.js.map","const focusPriority = [\n 'technical-check',\n 'content-gap',\n 'serp-framing',\n 'ranking',\n 'ctr',\n 'unverified',\n 'covered',\n];\nconst actionPriority = new Map(focusPriority.map((type, index) => [type, index]));\nfunction plural(count, singular, pluralLabel) {\n return count === 1 ? singular : pluralLabel;\n}\nfunction actionable(item) {\n return (item.opportunityType !== 'covered' && item.opportunityType !== 'unverified');\n}\nfunction compareActions(left, right) {\n return ((actionPriority.get(left.opportunityType) ?? 99) -\n (actionPriority.get(right.opportunityType) ?? 99) ||\n (right.estimatedCtrClickShortfall ?? -1) -\n (left.estimatedCtrClickShortfall ?? -1) ||\n right.impressions - left.impressions ||\n (left.query < right.query ? -1 : left.query > right.query ? 1 : 0));\n}\nexport function pageOpportunityFocus(items) {\n if (!items.length)\n return 'no-data';\n if (items.some((item) => item.opportunityType === 'technical-check')) {\n return 'technical-check';\n }\n const counts = new Map();\n for (const item of items) {\n counts.set(item.opportunityType, (counts.get(item.opportunityType) ?? 0) + 1);\n }\n return ([...counts.entries()].sort(([leftType, leftCount], [rightType, rightCount]) => rightCount - leftCount ||\n (actionPriority.get(leftType) ?? 99) -\n (actionPriority.get(rightType) ?? 99))[0]?.[0] ?? 'no-data');\n}\nfunction filteredReason(selection) {\n const reasons = [\n selection.belowMinimumRows\n ? `${selection.belowMinimumRows} below the impression threshold`\n : undefined,\n selection.brandRows ? `${selection.brandRows} branded` : undefined,\n selection.lowActionabilityRows\n ? `${selection.lowActionabilityRows} low-actionability`\n : undefined,\n selection.invalidRows ? `${selection.invalidRows} invalid` : undefined,\n selection.wrongPageRows\n ? `${selection.wrongPageRows} for another URL`\n : undefined,\n ].filter((reason) => Boolean(reason));\n return reasons.length ? ` Rows removed: ${reasons.join(', ')}.` : '';\n}\nexport function pageOpportunityVerdict(input) {\n const { analysis, focus } = input;\n if (analysis.dataStatus === 'empty') {\n return 'No GSC query rows were found for this exact URL in the selected window.';\n }\n if (analysis.dataStatus === 'filtered') {\n return `GSC returned rows for this URL, but none met the report criteria.${filteredReason(analysis.selection)}`;\n }\n if (focus === 'technical-check') {\n return 'Technical fetch or indexability evidence needs checking before content or snippet changes.';\n }\n if (focus === 'unverified') {\n return 'GSC visibility exists, but the page was not verified and no specific change is justified yet.';\n }\n if (focus === 'covered') {\n return 'The verified page covers the sampled queries and CTR is not materially below its directional benchmark.';\n }\n const count = analysis.summary.opportunities;\n const prefix = `${count} ${plural(count, 'actionable observation', 'actionable observations')} found.`;\n if (focus === 'content-gap') {\n return `${prefix} Verified body coverage is the main issue; confirm intent before expanding the page.`;\n }\n if (focus === 'serp-framing') {\n return `${prefix} The body is relevant, but its title, meta description, or H1 framing is weak.`;\n }\n if (focus === 'ranking') {\n return `${prefix} Most upside requires stronger relevance or authority; no CTR-only lift is claimed for page-two queries.`;\n }\n return `${prefix} The page-one CTR shortfall is about ${analysis.summary.estimatedCtrClickShortfall.toFixed(0)} clicks against the directional benchmark.`;\n}\nexport function pageOpportunityRecommendations(analysis) {\n const actions = analysis.items.filter(actionable).sort(compareActions);\n const top = actions[0];\n if (!top) {\n if (analysis.items.some((item) => item.opportunityType === 'unverified')) {\n return [\n 'Verify the live page and current SERP before turning these GSC observations into an editing brief.',\n ];\n }\n return analysis.items.length\n ? [\n 'Avoid an unnecessary rewrite. Monitor the queries and inspect current SERP formats before changing the page.',\n ]\n : [\n 'No page-level action is justified from this result. Lower the impression threshold only when long-tail inspection is useful.',\n ];\n }\n const recommendations = [`Start with \"${top.query}\". ${top.recommendation}`];\n const technical = actions.filter((item) => item.opportunityType === 'technical-check').length;\n if (technical) {\n recommendations.push(`Resolve the technical evidence affecting ${technical} ${plural(technical, 'row', 'rows')} before content work.`);\n }\n const gaps = actions.filter((item) => item.opportunityType === 'content-gap').length;\n if (gaps >= 3) {\n recommendations.push(`Group the ${gaps} verified content gaps into useful sections rather than adding one thin paragraph per query.`);\n }\n return recommendations;\n}\n//# sourceMappingURL=page-opportunities-presentation.js.map","import { SeoError } from '../errors.js';\nimport { extractPage } from '../extract/page-extractor.js';\nimport { fetchPage } from '../fetch/page-fetcher.js';\nimport { querySearchAnalytics } from '../gsc/client.js';\nimport { assertUrlMatchesGscProperty } from '../gsc/property-url.js';\nimport { analyzePageOpportunitiesFromRows, } from './page-opportunities-analysis.js';\nimport { pageOpportunityFocus, pageOpportunityRecommendations, pageOpportunityVerdict, } from './page-opportunities-presentation.js';\nimport { defaultDateRange } from './shared.js';\nexport * from './page-opportunities-analysis.js';\nconst MAX_BENCHMARK_ROWS = 100_000;\nconst defaultDependencies = {\n searchAnalytics: querySearchAnalytics,\n fetch: fetchPage,\n extract: extractPage,\n now: () => new Date(),\n};\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : String(error);\n}\nfunction unique(values) {\n return [...new Set(values.filter(Boolean))];\n}\nfunction reportDays(value) {\n if (value === undefined)\n return 28;\n if (!Number.isInteger(value) || value < 1 || value > 548) {\n throw new SeoError('INVALID_INPUT', 'Days must be a whole number between 1 and 548.');\n }\n return value;\n}\nasync function verifyPage(input) {\n const warnings = [];\n let fetched;\n try {\n fetched = await input.dependencies.fetch(input.url, {\n js: input.js ?? 'auto',\n refresh: input.refresh,\n });\n warnings.push(...fetched.warnings);\n }\n catch (error) {\n const reason = `Page fetch failed: ${errorMessage(error)}`;\n return {\n verification: { status: 'failed', reason },\n warnings: [reason],\n };\n }\n try {\n const page = await input.dependencies.extract(fetched);\n warnings.push(...page.warnings);\n return {\n fetched,\n page,\n verification: {\n status: 'verified',\n reason: 'The live page was fetched and extracted for on-page checks.',\n },\n warnings: unique(warnings),\n };\n }\n catch (error) {\n const reason = `Page extraction failed: ${errorMessage(error)}`;\n return {\n fetched,\n verification: { status: 'failed', reason },\n warnings: unique([...warnings, reason]),\n };\n }\n}\nfunction reportCaveats(input) {\n const { analysis, reportInput, range } = input;\n return [\n `Date window: ${range.startDate} to ${range.endDate}, using final GSC data where available.`,\n `Selection: ${analysis.selection.sourceRows} exact-URL rows, ${analysis.selection.eligibleRows} eligible, ${analysis.selection.returnedRows} returned.`,\n `Minimum query impressions: ${analysis.minImpressions}.`,\n `Brand filtering: ${reportInput.includeBrand ? 'brand queries included' : 'brand queries excluded when detected or configured'}.`,\n `Content verification: ${input.verification.status} (${input.verification.reason})`,\n 'CTR benchmarks are directional. GSC query data omits anonymized queries and does not explain SERP features or intent changes.',\n input.benchmarkTruncated\n ? `The site-wide benchmark reached its ${MAX_BENCHMARK_ROWS.toLocaleString('en-US')}-row cap, so provenance is complete but the peer sample is truncated.`\n : '',\n ].filter(Boolean);\n}\nexport async function pageOpportunitiesReport(input, dependencies = defaultDependencies) {\n const url = assertUrlMatchesGscProperty(input.site, input.url);\n const days = reportDays(input.days);\n const range = defaultDateRange(days);\n const targetResult = await dependencies.searchAnalytics(input.site, {\n ...range,\n dimensions: ['query', 'page'],\n type: 'web',\n dataState: 'final',\n dimensionFilterGroups: [\n {\n groupType: 'and',\n filters: [{ dimension: 'page', operator: 'equals', expression: url }],\n },\n ],\n }, { refresh: input.refresh });\n const preliminary = analyzePageOpportunitiesFromRows({\n targetRows: targetResult.rows,\n benchmarkRows: [],\n site: input.site,\n url,\n minImpressions: input.minImpressions,\n limit: input.limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n const shouldVerify = (input.verifyContent ?? true) && preliminary.eligibleRows > 0;\n const verificationPromise = shouldVerify\n ? verifyPage({\n url,\n refresh: input.refresh,\n js: input.js,\n dependencies,\n })\n : Promise.resolve({\n verification: {\n status: 'skipped',\n reason: preliminary.eligibleRows === 0\n ? 'No eligible query rows required page verification.'\n : 'Page verification was disabled.',\n },\n warnings: [],\n });\n const benchmarkPromise = preliminary.eligibleRows > 0\n ? dependencies.searchAnalytics(input.site, {\n ...range,\n dimensions: ['query', 'page'],\n type: 'web',\n dataState: 'final',\n maxRows: MAX_BENCHMARK_ROWS,\n }, { refresh: input.refresh })\n : Promise.resolve({ rows: [], calls: 0, rowsFetched: 0 });\n const [verified, benchmarkResult] = await Promise.all([\n verificationPromise,\n benchmarkPromise,\n ]);\n const analysis = analyzePageOpportunitiesFromRows({\n targetRows: targetResult.rows,\n benchmarkRows: benchmarkResult.rows,\n site: input.site,\n url,\n minImpressions: input.minImpressions,\n limit: input.limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n page: verified.page,\n fetchDiagnostics: verified.fetched?.diagnostics,\n httpStatus: verified.fetched?.status,\n });\n const focus = pageOpportunityFocus(analysis.items);\n const verdict = pageOpportunityVerdict({ analysis, focus });\n const benchmarkTruncated = benchmarkResult.rowsFetched >= MAX_BENCHMARK_ROWS;\n return {\n site: input.site,\n url,\n generatedAt: dependencies.now().toISOString(),\n range,\n rangeDays: days,\n source: {\n provider: 'google-search-console',\n dimensions: ['query', 'page'],\n searchType: 'web',\n dataState: 'final',\n targetRowsFetched: targetResult.rowsFetched,\n targetCalls: targetResult.calls,\n },\n dataStatus: analysis.dataStatus,\n selection: analysis.selection,\n verification: verified.verification,\n benchmark: {\n sourceRows: analysis.benchmarkSourceRows,\n eligibleRows: analysis.benchmarkEligibleRows,\n excludedTargetRows: analysis.excludedTargetBenchmarkRows,\n rowsFetched: benchmarkResult.rowsFetched,\n calls: benchmarkResult.calls,\n maxRows: MAX_BENCHMARK_ROWS,\n possiblyTruncated: benchmarkTruncated,\n },\n page: verified.page && verified.fetched\n ? {\n finalUrl: verified.page.finalUrl,\n status: verified.fetched.status,\n title: verified.page.title,\n h1: verified.page.headings.find((heading) => heading.level === 1)\n ?.text,\n wordCount: verified.page.wordCount,\n fetchDiagnostics: verified.fetched.diagnostics,\n }\n : undefined,\n summary: {\n queries: analysis.returnedRows,\n clicks: analysis.summary.clicks,\n impressions: analysis.summary.impressions,\n opportunities: analysis.summary.opportunities,\n estimatedCtrClickShortfall: analysis.summary.estimatedCtrClickShortfall,\n estimatedClickLift: analysis.summary.estimatedCtrClickShortfall,\n verdict,\n focus,\n },\n items: analysis.items,\n warnings: verified.warnings,\n caveats: reportCaveats({\n reportInput: input,\n analysis,\n range,\n benchmarkTruncated,\n verification: verified.verification,\n }),\n recommendations: pageOpportunityRecommendations(analysis),\n };\n}\n//# sourceMappingURL=page-opportunities.js.map","import { pageOpportunitiesReport } from './page-opportunities.js';\nfunction intentFor(query) {\n const value = query.toLowerCase();\n if (/\\b(vs|versus|alternative|alternatives|compare|comparison|best)\\b/.test(value)) {\n return 'comparison';\n }\n if (/\\b(price|pricing|cost|buy|deal|coupon|review|reviews)\\b/.test(value)) {\n return 'commercial';\n }\n if (/\\b(how|steps|guide|tutorial|setup|fix|create|make)\\b/.test(value)) {\n return 'how-to';\n }\n if (/\\b(what is|meaning|definition|explained|why)\\b/.test(value)) {\n return 'definition';\n }\n if (/\\b(near me|city|state|county|postcode|zip|london|new york)\\b/.test(value)) {\n return 'local';\n }\n if (/\\b(login|sign in|app|dashboard|support)\\b/.test(value)) {\n return 'navigational';\n }\n return 'general';\n}\nfunction score(report) {\n if (!report.items.length)\n return 0;\n const actionableRatio = report.summary.opportunities / report.items.length;\n const coveragePenalty = report.items.filter((item) => item.opportunityType === 'content-gap')\n .length * 8;\n const framingPenalty = report.items.filter((item) => item.opportunityType === 'serp-framing')\n .length * 5;\n const ctrPenalty = report.items.filter((item) => item.opportunityType === 'ctr').length * 4;\n return Math.max(0, Math.min(100, Math.round(100 -\n actionableRatio * 40 -\n coveragePenalty -\n framingPenalty -\n ctrPenalty)));\n}\nfunction titleCase(value) {\n return value\n .split(/\\s+/)\n .filter(Boolean)\n .map((word) => `${word[0]?.toUpperCase() ?? ''}${word.slice(1)}`)\n .join(' ');\n}\nfunction ctrShortfall(item) {\n return item.estimatedCtrClickShortfall ?? item.estimatedClickLift ?? 0;\n}\nfunction sectionHeading(intent, query) {\n if (intent === 'comparison')\n return `${titleCase(query)}: what to choose`;\n if (intent === 'how-to')\n return `How to ${query.replace(/^how to\\s+/i, '')}`;\n if (intent === 'definition')\n return `${titleCase(query)}, in plain English`;\n if (intent === 'commercial')\n return `${titleCase(query)}: costs and trade-offs`;\n return titleCase(query);\n}\nfunction intentMix(report) {\n const groups = new Map();\n for (const item of report.items) {\n const intent = intentFor(item.query);\n const current = groups.get(intent) ?? {\n queries: 0,\n impressions: 0,\n clicks: 0,\n };\n current.queries += 1;\n current.impressions += item.impressions;\n current.clicks += item.clicks;\n groups.set(intent, current);\n }\n return [...groups.entries()]\n .map(([intent, values]) => ({ intent, ...values }))\n .sort((a, b) => b.impressions - a.impressions);\n}\nfunction brief(report) {\n const actionable = report.items\n .filter((item) => item.opportunityType !== 'covered' &&\n item.opportunityType !== 'technical-check' &&\n item.opportunityType !== 'unverified')\n .sort((a, b) => ctrShortfall(b) - ctrShortfall(a));\n const primary = actionable[0];\n const bodyCandidates = actionable.filter((item) => item.verification.status === 'verified' &&\n (item.opportunityType === 'content-gap' ||\n item.opportunityType === 'ranking'));\n const sections = bodyCandidates.slice(0, 5).map((item) => {\n const intent = intentFor(item.query);\n return {\n heading: sectionHeading(intent, item.query),\n why: item.recommendation,\n queries: [\n item.query,\n ...bodyCandidates\n .filter((candidate) => candidate.query !== item.query &&\n intentFor(candidate.query) === intent)\n .slice(0, 3)\n .map((candidate) => candidate.query),\n ],\n };\n });\n return {\n titleAngle: primary\n ? `Make the title clearly promise the \"${primary.query}\" answer.`\n : undefined,\n h1Angle: primary\n ? `Keep the H1 aligned with the page topic, then use subheadings for \"${primary.query}\" variants.`\n : undefined,\n metaAngle: primary\n ? `Use the meta description to state the outcome, trade-off, or direct answer searchers get.`\n : undefined,\n sections,\n internalLinkAnchors: bodyCandidates\n .slice(0, 8)\n .map((item) => item.query)\n .filter((query, index, values) => values.indexOf(query) === index),\n };\n}\nfunction topActions(report) {\n const technical = report.items.filter((item) => item.opportunityType === 'technical-check');\n const unverified = report.items.filter((item) => item.opportunityType === 'unverified');\n const gaps = report.items.filter((item) => item.opportunityType === 'content-gap');\n const framing = report.items.filter((item) => item.opportunityType === 'serp-framing' || item.opportunityType === 'ctr');\n const ranking = report.items.filter((item) => item.opportunityType === 'ranking');\n const actions = [];\n if (technical.length) {\n actions.push({\n title: 'Resolve technical evidence first',\n plainEnglish: `${technical.length} query observation is attached to a URL with conflicting fetch or indexability evidence.`,\n action: 'Check status, redirects, robots directives, noindex, and canonical signals before producing a content brief.',\n queries: technical.slice(0, 8).map((item) => item.query),\n });\n }\n if (gaps.length) {\n actions.push({\n title: 'Add missing answer coverage',\n plainEnglish: `${gaps.length} query angle needs clearer body coverage.`,\n action: 'Add one useful section that directly answers the grouped query angles. Do not add one thin paragraph per query.',\n queries: gaps.slice(0, 8).map((item) => item.query),\n });\n }\n if (framing.length) {\n actions.push({\n title: 'Tighten the SERP framing',\n plainEnglish: `${framing.length} query angle looks covered but under-framed in title, H1, or meta copy.`,\n action: 'Test clearer title/meta wording before rewriting the body. Keep the promise specific and human.',\n queries: framing.slice(0, 8).map((item) => item.query),\n });\n }\n if (ranking.length) {\n actions.push({\n title: 'Strengthen relevance and links',\n plainEnglish: `${ranking.length} query angle is still too low for a simple CTR change.`,\n action: 'Improve the relevant answer block and add internal links from pages that already cover related demand.',\n queries: ranking.slice(0, 8).map((item) => item.query),\n });\n }\n if (!actions.length) {\n if (unverified.length) {\n actions.push({\n title: 'Verify the page before editing',\n plainEnglish: 'GSC visibility exists, but live content evidence was not available.',\n action: 'Fetch and inspect the live page and current SERP before turning these observations into a content brief.',\n queries: unverified.slice(0, 8).map((item) => item.query),\n });\n return actions;\n }\n actions.push({\n title: 'Avoid unnecessary content expansion',\n plainEnglish: 'The sampled queries look mostly covered. More copy may dilute the page.',\n action: 'Review title/meta tests, internal links, and SERP format before adding new sections.',\n queries: report.items.slice(0, 5).map((item) => item.query),\n });\n }\n return actions;\n}\nexport function contentOptimizationFromPageOpportunities(sourceReport) {\n const mix = intentMix(sourceReport);\n const primaryIntent = mix[0]?.intent ?? 'general';\n const primaryQuery = sourceReport.items\n .filter((item) => item.opportunityType !== 'covered' &&\n item.opportunityType !== 'technical-check' &&\n item.opportunityType !== 'unverified')\n .sort((a, b) => ctrShortfall(b) - ctrShortfall(a))[0]?.query ??\n sourceReport.items[0]?.query;\n return {\n site: sourceReport.site,\n url: sourceReport.url,\n generatedAt: sourceReport.generatedAt,\n sourceReport,\n summary: {\n score: score(sourceReport),\n primaryIntent,\n primaryQuery,\n queries: sourceReport.summary.queries,\n opportunities: sourceReport.summary.opportunities,\n estimatedClickLift: sourceReport.summary.estimatedClickLift,\n verdict: sourceReport.summary.verdict,\n },\n intentMix: mix,\n brief: brief(sourceReport),\n topActions: topActions(sourceReport),\n caveats: sourceReport.caveats,\n };\n}\nexport async function contentOptimizationReport(input) {\n return contentOptimizationFromPageOpportunities(await pageOpportunitiesReport(input));\n}\n//# sourceMappingURL=content-optimization.js.map","const severityRank = {\n high: 3,\n medium: 2,\n low: 1,\n};\nexport function affectedUrls(report, filters = {}) {\n return selectAffectedUrls(report, filters).affectedUrls;\n}\nexport function selectAffectedUrls(report, filters = {}) {\n const pagesByUrl = new Map(report.pages.flatMap((page) => [\n [page.url, page],\n [page.finalUrl, page],\n ]));\n const matches = report.issues\n .filter((issue) => matchesFilters(issue, filters))\n .map((issue) => {\n const page = pagesByUrl.get(issue.url);\n return {\n url: issue.url,\n ruleId: issue.ruleId,\n title: issue.title,\n category: issue.category,\n severity: issue.severity,\n detail: issue.detail,\n evidence: issue.evidence,\n clicks: issue.searchMetrics?.clicks ?? page?.searchMetrics?.clicks ?? 0,\n impressions: issue.searchMetrics?.impressions ??\n page?.searchMetrics?.impressions ??\n 0,\n sessions: page?.analytics?.sessions ?? 0,\n };\n })\n .sort((a, b) => severityRank[b.severity] - severityRank[a.severity] ||\n b.clicks - a.clicks ||\n b.impressions - a.impressions ||\n b.sessions - a.sessions ||\n a.url.localeCompare(b.url));\n const limit = filters.limit ?? 100;\n const selected = matches.slice(0, limit);\n return {\n affectedUrls: selected,\n selection: {\n totalMatchedRows: matches.length,\n returnedRows: selected.length,\n limit,\n truncated: selected.length < matches.length,\n },\n };\n}\nfunction matchesFilters(issue, filters) {\n if (filters.ruleId && issue.ruleId !== filters.ruleId)\n return false;\n if (filters.category && issue.category !== filters.category)\n return false;\n if (filters.severity && issue.severity !== filters.severity)\n return false;\n return true;\n}\n//# sourceMappingURL=affected-urls.js.map","import { effectiveSnippetControl } from '../../robots-directives.js';\nfunction pct(part, total) {\n if (total <= 0)\n return 0;\n return Math.round((part / total) * 100);\n}\nfunction scoreFromPercent(value, maxScore) {\n return Math.round((Math.max(0, Math.min(100, value)) / 100) * maxScore);\n}\nfunction status(score, maxScore) {\n if (maxScore === 0)\n return 'info';\n const ratio = maxScore ? score / maxScore : 0;\n if (ratio >= 0.85)\n return 'pass';\n if (ratio >= 0.5)\n return 'warning';\n return 'fail';\n}\nfunction section(id, title, checks) {\n return { id, title, checks };\n}\nfunction check(input) {\n const { score, maxScore, ...output } = input;\n const evaluated = input.evaluated ?? true;\n return {\n ...output,\n evaluated,\n status: evaluated ? status(score, maxScore) : 'unknown',\n };\n}\nfunction indexablePages(report) {\n return report.pages.filter((page) => page.indexable && page.status < 400);\n}\nfunction sampleUrls(pages, predicate) {\n return pages\n .filter(predicate)\n .slice(0, 10)\n .map((page) => page.finalUrl);\n}\nexport function aiReadiness(report) {\n const pages = indexablePages(report);\n const pageCount = pages.length;\n const hasIndexablePages = pageCount > 0;\n const pageLimitReached = report.summary.pageLimitReached;\n const robotsTxt = report.ai?.robotsTxt;\n const botAccess = robotsTxt?.botAccess ?? [];\n const blockedBots = botAccess.filter((bot) => bot.allowed === false);\n const unknownBots = botAccess.filter((bot) => bot.allowed === null);\n const robotsUnavailable = robotsTxt?.availability === 'rate-limited' ||\n robotsTxt?.availability === 'unreachable';\n const hasRobotsEvidence = robotsTxt !== undefined;\n const hasBotAccessEvidence = hasRobotsEvidence && botAccess.length > 0;\n const botAccessEvaluated = hasBotAccessEvidence && !robotsUnavailable;\n const sitemapEvaluated = hasRobotsEvidence && !robotsUnavailable;\n const robotsEvidenceIncomplete = robotsUnavailable || !hasRobotsEvidence || !hasBotAccessEvidence;\n const declaredBots = botAccess.filter((bot) => bot.declared || bot.coveredByWildcard);\n const detectedResources = report.ai?.agentResources?.filter((resource) => resource.exists);\n const jsonLdPages = report.pages.filter((page) => page.structuredDataFormats?.includes('json-ld') ||\n (page.invalidJsonLdCount ?? 0) > 0);\n const invalidJsonLdPages = jsonLdPages.filter((page) => (page.invalidJsonLdCount ?? 0) > 0);\n const answerablePages = pages.filter((page) => page.geo?.answerable);\n const semanticPages = pages.filter((page) => page.geo?.semanticHtml);\n const titlePages = pages.filter((page) => page.title && page.h1);\n const metaPages = pages.filter((page) => page.metaDescription);\n const langPages = pages.filter((page) => page.lang);\n const entityPages = pages.filter((page) => page.schemaTypes?.some((type) => /^(Organization|LocalBusiness|Person|Product|WebSite)$/i.test(type)) ||\n (page.schemaSameAs?.length ?? 0) > 0 ||\n (page.socialProfileLinks?.length ?? 0) > 0);\n const snippetControls = pages.map((page) => ({\n url: page.finalUrl,\n control: effectiveSnippetControl({\n metaRobots: page.metaRobots,\n xRobotsTag: page.xRobotsTag,\n }),\n }));\n const restrictedSnippets = snippetControls.filter(({ control }) => control.status !== 'not-restricted');\n const blockedSnippets = restrictedSnippets.filter(({ control }) => control.status === 'blocked');\n const limitedSnippets = restrictedSnippets.filter(({ control }) => control.status === 'limited');\n const sections = [\n section('agent-access', 'Agent access', [\n check({\n id: 'robots-ai-bots',\n section: 'agent-access',\n maxScore: 20,\n evaluated: botAccessEvaluated,\n score: robotsUnavailable\n ? 0\n : botAccess.length\n ? blockedBots.length\n ? scoreFromPercent(pct(botAccess.length - blockedBots.length, botAccess.length), 20)\n : 20\n : 8,\n title: robotsUnavailable\n ? 'robots.txt crawler-policy evidence is unavailable'\n : !hasBotAccessEvidence\n ? 'robots.txt crawler-policy evidence was not collected'\n : blockedBots.length\n ? 'robots.txt blocks selected crawler tokens at the start URL'\n : 'robots.txt allows selected crawler tokens at the start URL',\n plainEnglish: robotsUnavailable\n ? 'The robots.txt request failed, so this report cannot say whether selected crawler tokens are allowed at the start URL.'\n : !hasBotAccessEvidence\n ? 'This crawl does not include per-bot robots.txt policy data for the start URL.'\n : blockedBots.length\n ? `robots.txt policy blocks ${blockedBots.length} selected crawler ${blockedBots.length === 1 ? 'token' : 'tokens'} at the start URL.`\n : 'robots.txt policy does not block the selected crawler tokens at the start URL. This does not verify actual or site-wide fetchability.',\n action: robotsUnavailable\n ? 'Restore a stable robots.txt response, then rerun this report before making crawler-policy claims.'\n : !hasBotAccessEvidence\n ? 'Rerun the crawl with top-level per-bot robots.txt evidence before making crawler-policy claims.'\n : blockedBots.length\n ? 'Only block AI crawlers intentionally. If discovery matters, remove accidental Disallow rules for the blocked user agents.'\n : 'Keep robots.txt explicit and intentional so humans and agents can see what is allowed.',\n evidence: {\n blockedBots,\n unknownBots,\n declaredBots: declaredBots.length,\n availability: robotsTxt?.availability,\n status: robotsTxt?.status,\n error: robotsTxt?.error,\n scope: 'start-url-robots-policy',\n startUrl: report.config.url,\n },\n }),\n check({\n id: 'robots-sitemap',\n section: 'agent-access',\n maxScore: 0,\n evaluated: sitemapEvaluated,\n score: 0,\n title: sitemapEvaluated\n ? 'robots.txt sitemap declarations were checked'\n : 'robots.txt sitemap declarations were not evaluated',\n plainEnglish: robotsUnavailable\n ? 'The robots.txt response was unavailable, so sitemap declarations could not be checked.'\n : !hasRobotsEvidence\n ? 'This crawl does not include top-level robots.txt evidence, so sitemap declarations could not be checked.'\n : robotsTxt.sitemapUrls.length\n ? 'robots.txt declares at least one sitemap URL.'\n : 'robots.txt does not declare a sitemap URL.',\n action: robotsUnavailable\n ? 'Restore robots.txt availability and rerun before evaluating sitemap declarations.'\n : !hasRobotsEvidence\n ? 'Rerun the crawl with top-level robots.txt evidence before evaluating sitemap declarations.'\n : 'Add a Sitemap line to robots.txt so crawlers can discover the full index quickly.',\n evidence: { sitemapUrls: robotsTxt?.sitemapUrls ?? [] },\n }),\n check({\n id: 'agent-resources',\n section: 'agent-access',\n maxScore: 0,\n score: 0,\n title: 'Agent descriptor files are discoverable',\n plainEnglish: detectedResources?.length\n ? `${detectedResources.length} machine-readable agent resource was found.`\n : 'No OpenAPI, MCP, ai-plugin, or agent descriptor file was found at the common locations.',\n action: 'Publish useful descriptors only when they are real: OpenAPI for APIs, MCP metadata for tools, or agent.json for site capabilities.',\n evidence: { resources: report.ai?.agentResources ?? [] },\n }),\n ]),\n section('machine-readable', 'Machine-readable signals', [\n check({\n id: 'llms-txt',\n section: 'machine-readable',\n maxScore: 0,\n score: 0,\n title: 'llms.txt is optional',\n plainEnglish: report.ai?.llmsTxt?.exists\n ? 'An optional llms.txt file was found. Google says it has no positive or negative Search impact.'\n : 'No llms.txt file was found. Google says the file is not needed for Search and does not affect visibility.',\n action: 'No SEO action is required. Generate one only for a specific agent or service that consumes it.',\n evidence: {\n llmsTxt: report.ai?.llmsTxt,\n googleSearchImpact: 'none',\n guidanceUrl: 'https://developers.google.com/search/updates#clarifying-guidance-on-llms-txt-files',\n },\n }),\n check({\n id: 'valid-json-ld',\n section: 'machine-readable',\n maxScore: 8,\n evaluated: jsonLdPages.length > 0,\n score: invalidJsonLdPages.length ? 3 : 8,\n title: jsonLdPages.length\n ? 'Observed JSON-LD parses cleanly'\n : 'JSON-LD syntax was not evaluated',\n plainEnglish: jsonLdPages.length\n ? invalidJsonLdPages.length\n ? `${invalidJsonLdPages.length} evaluated page contains invalid JSON-LD.`\n : 'The JSON-LD observed on evaluated pages parsed cleanly.'\n : 'No JSON-LD was observed, so this report cannot make a syntax claim.',\n action: invalidJsonLdPages.length\n ? 'Fix invalid JSON-LD before relying on its structured-data claims.'\n : 'Use structured data only where it accurately represents the visible page and a supported use case.',\n urls: invalidJsonLdPages.slice(0, 10).map((page) => page.finalUrl),\n }),\n ]),\n section('content-clarity', 'Content clarity', [\n check({\n id: 'answerable-content',\n section: 'content-clarity',\n maxScore: 0,\n evaluated: hasIndexablePages,\n score: 0,\n title: 'Short opening paragraphs are an unscored observation',\n plainEnglish: hasIndexablePages\n ? `${pct(answerablePages.length, pageCount)}% of indexable pages have at least one 25-word paragraph near the start. This does not establish content quality, citation likelihood, or Google AI eligibility.`\n : 'No indexable 2xx pages were available, so opening-paragraph coverage was not evaluated.',\n action: 'Write for the reader and the page intent. Do not create artificial answer blocks or chunk content solely for AI Search.',\n urls: sampleUrls(pages, (page) => !page.geo?.answerable),\n evidence: {\n observedPages: answerablePages.length,\n evaluatedPages: pageCount,\n heuristic: 'one-of-first-three-paragraphs-has-at-least-25-words',\n googleSearchImpact: 'not-established',\n guidanceUrl: 'https://developers.google.com/search/docs/fundamentals/ai-optimization-guide',\n },\n }),\n check({\n id: 'semantic-html',\n section: 'content-clarity',\n maxScore: 0,\n evaluated: hasIndexablePages,\n score: 0,\n title: 'Semantic HTML coverage observed',\n plainEnglish: hasIndexablePages\n ? `${pct(semanticPages.length, pageCount)}% of indexable pages use semantic structure.`\n : 'No indexable 2xx pages were available, so semantic HTML coverage was not evaluated.',\n action: 'Use real headings, lists, tables, nav, main, article, and section elements instead of layout-only divs.',\n }),\n check({\n id: 'titles-headings-meta',\n section: 'content-clarity',\n maxScore: 0,\n evaluated: hasIndexablePages,\n score: 0,\n title: 'Title, H1, and description coverage observed',\n plainEnglish: hasIndexablePages\n ? `${pct(titlePages.length, pageCount)}% of indexable pages have title/H1 coverage and ${pct(metaPages.length, pageCount)}% have meta descriptions.`\n : 'No indexable 2xx pages were available, so title, H1, and description coverage was not evaluated.',\n action: 'Write a unique title and descriptive H1. Add a useful meta description when a summary would help searchers understand the page.',\n }),\n check({\n id: 'language',\n section: 'content-clarity',\n maxScore: 0,\n evaluated: hasIndexablePages,\n score: 0,\n title: 'HTML language declaration coverage observed',\n plainEnglish: hasIndexablePages\n ? `${pct(langPages.length, pageCount)}% of indexable pages declare a language.`\n : 'No indexable 2xx pages were available, so language declaration coverage was not evaluated.',\n action: 'Set the html lang attribute so crawlers and assistive tech understand the page language.',\n }),\n ]),\n section('entity-signals', 'Entity signals', [\n check({\n id: 'entity-schema',\n section: 'entity-signals',\n maxScore: 0,\n evaluated: hasIndexablePages,\n score: 0,\n title: 'Entity-signal coverage observed',\n plainEnglish: hasIndexablePages\n ? `${pct(entityPages.length, pageCount)}% of indexable pages include entity signals such as Organization, Person, Product, sameAs, or social profile links.`\n : 'No indexable 2xx pages were available, so entity-signal coverage was not evaluated.',\n action: 'Make the homepage and key pages explicit about the brand, product, people, and official profiles using accurate schema and links.',\n urls: sampleUrls(pages, (page) => !entityPages.includes(page)),\n }),\n check({\n id: 'authors-dates',\n section: 'entity-signals',\n maxScore: 0,\n score: 0,\n title: 'People and dates are visible where they matter',\n plainEnglish: 'Author and date signals help agents judge freshness and accountability.',\n action: 'Add visible authors, reviewed dates, and updated dates to content where trust and freshness matter.',\n }),\n ]),\n section('technical-ux', 'Technical UX', [\n check({\n id: 'snippet-controls',\n section: 'technical-ux',\n maxScore: 0,\n evaluated: hasIndexablePages,\n score: 0,\n title: !hasIndexablePages\n ? 'Snippet controls were not evaluated'\n : restrictedSnippets.length\n ? 'Page-level snippet restrictions observed'\n : 'No page-level snippet restriction detected',\n plainEnglish: !hasIndexablePages\n ? 'No indexable 2xx pages were available, so snippet controls were not evaluated.'\n : restrictedSnippets.length\n ? `${blockedSnippets.length} indexable ${blockedSnippets.length === 1 ? 'page has' : 'pages have'} snippets blocked and ${limitedSnippets.length} ${limitedSnippets.length === 1 ? 'has' : 'have'} a positive max-snippet limit.`\n : 'No nosnippet or restrictive max-snippet directive was detected on the evaluated indexable pages.',\n action: restrictedSnippets.length\n ? 'Confirm each restriction is intentional. Do not remove publisher controls solely to satisfy this report.'\n : 'No action is required. This observation does not guarantee that Google will select or show a snippet.',\n urls: restrictedSnippets.slice(0, 10).map(({ url }) => url),\n evidence: {\n evaluatedPages: pages.length,\n blockedPages: blockedSnippets.length,\n limitedPages: limitedSnippets.length,\n restrictions: restrictedSnippets.slice(0, 10),\n },\n }),\n check({\n id: 'https-viewport-readable',\n section: 'technical-ux',\n maxScore: 0,\n score: 0,\n title: 'Pages are secure, mobile-ready, and readable from HTML',\n plainEnglish: 'Agents need stable HTML content, not just a visual page that works in one browser session.',\n action: 'Serve HTTPS, include viewport metadata, and make important copy available in the initial HTML or rendered output.',\n }),\n check({\n id: 'status-indexability',\n section: 'technical-ux',\n maxScore: 12,\n evaluated: report.pages.length > 0,\n score: scoreFromPercent(pct(pages.length, report.pages.length || 1), 12),\n title: report.pages.length\n ? 'Crawled-page indexability observed'\n : 'Crawled-page indexability was not evaluated',\n plainEnglish: report.pages.length\n ? `${pct(pages.length, report.pages.length)}% of crawled pages are indexable 2xx pages.`\n : 'No crawled pages were available, so status and indexability were not evaluated.',\n action: 'Fix 4xx/5xx pages, accidental noindex, and blocked internal URLs before expanding AI discovery work.',\n }),\n ]),\n section('crawl-completeness', 'Crawl completeness', [\n check({\n id: 'crawl-depth',\n section: 'crawl-completeness',\n maxScore: 8,\n score: pageLimitReached ? 3 : 8,\n title: pageLimitReached\n ? 'The crawl hit the page cap'\n : 'The crawl finished without hitting the page cap',\n plainEnglish: pageLimitReached\n ? `The crawl stopped at maxPages (${report.config.maxPages}), so the report may under-sample the site.`\n : 'The crawl did not hit the configured page cap.',\n action: 'Raise --max-pages or crawl from sitemap mode when you need a complete site inventory.',\n }),\n check({\n id: 'internal-link-discovery',\n section: 'crawl-completeness',\n maxScore: 0,\n score: 0,\n title: 'Internal links expose more of the site',\n plainEnglish: 'A healthy crawl should discover important pages through internal links, not only through a seed URL.',\n action: 'Link important pages from navigational, hub, or contextual links so crawlers can find them naturally.',\n }),\n ]),\n ];\n const checks = sections.flatMap((item) => item.checks);\n const dataStatus = report.status === 'completed' && !robotsEvidenceIncomplete\n ? 'complete'\n : 'partial';\n const topActions = checks\n .filter((item) => item.evaluated &&\n (item.status === 'warning' || item.status === 'fail') &&\n [\n 'robots-ai-bots',\n 'valid-json-ld',\n 'status-indexability',\n 'crawl-depth',\n ].includes(item.id))\n .sort((a, b) => Number(b.status === 'fail') - Number(a.status === 'fail') ||\n a.id.localeCompare(b.id))\n .slice(0, 8);\n return {\n reportId: report.id,\n url: report.config.url,\n generatedAt: report.generatedAt,\n dataStatus,\n assessment: 'evidence-only',\n headline: dataStatus === 'partial'\n ? 'AI-search evidence is incomplete. Fix the collection gaps before drawing site-wide conclusions.'\n : topActions.length\n ? `${topActions.length} evidence-backed technical ${topActions.length === 1 ? 'action remains' : 'actions remain'}. Optional observations are not treated as ranking or citation factors.`\n : 'No evidence-backed technical action was found in this crawl. This is not a visibility or citation verdict.',\n sections,\n checks,\n topActions,\n botAccess,\n agentResources: report.ai?.agentResources ?? [],\n caveats: [\n ...report.caveats,\n 'This report deliberately has no aggregate readiness score. Google documents no separate technical requirements for its generative AI Search features.',\n 'llms.txt is treated as optional agent-discovery metadata, not a Google Search ranking or visibility factor.',\n 'Paragraph length and placement are observations only. Google does not require content chunking or special answer blocks for generative AI features.',\n 'Snippet controls reflect page-level publisher directives only. No detected restriction does not guarantee selection, visibility, or a displayed snippet.',\n ...(robotsTxt\n ? robotsUnavailable\n ? [\n 'robots.txt was unavailable, so crawler access and sitemap declaration checks are inconclusive.',\n ]\n : !hasBotAccessEvidence\n ? [\n 'robots.txt was collected without per-bot policy evidence, so the crawler-policy check is inconclusive.',\n ]\n : []\n : [\n 'This crawl report does not include top-level robots.txt AI bot data.',\n ]),\n 'robots.txt checks describe policy for the configured start URL only. They do not verify actual crawler requests or site-wide access.',\n ],\n };\n}\n//# sourceMappingURL=ai-readiness.js.map","// biome-ignore-all lint/style/noExcessiveLinesPerFile: central rule guidance registry for CLI and MCP parity.\nconst RULE_DEFINITIONS = [\n {\n id: 'missing_title',\n title: 'Title missing',\n category: 'metadata',\n defaultSeverity: 'high',\n whyItMatters: 'The title is the main search-result headline and one of the clearest page-topic signals. Without it, search engines invent a label and users get a weaker reason to click.',\n howToFix: 'Add one descriptive title that names the page topic and matches the main query intent. Keep it useful for humans first.',\n impactIfIgnored: 'The page can look vague in search results, earn lower CTR, and send weaker relevance signals.',\n howToVerify: 'Re-run `seo audit-page --url <url>` and confirm the title is present in the page audit output.',\n agentHints: {\n evidenceFields: ['page.title'],\n suggestedCommands: ['seo audit-page --url <url> --json'],\n },\n },\n {\n id: 'title_too_wide',\n title: 'Title may truncate on some devices',\n category: 'metadata',\n defaultSeverity: 'low',\n whyItMatters: 'Google has no fixed title length limit, but title links are truncated to fit the available device width. Important wording placed late may not always display.',\n howToFix: 'Review the title rather than shortening it blindly. Put the clearest page-specific wording first and remove filler only when meaning is preserved.',\n impactIfIgnored: 'Some result layouts may truncate later words. This is a display estimate, not an indexing or ranking defect.',\n howToVerify: 'Re-run the audit and review estimatedPixels, referencePixels, confidence, and profile. Confirm the important wording appears early.',\n agentHints: {\n evidenceFields: [\n 'page.title',\n 'issue.evidence.estimatedPixels',\n 'issue.evidence.referencePixels',\n 'issue.evidence.confidence',\n 'issue.evidence.profile',\n ],\n suggestedCommands: ['seo audit-page --url <url> --json'],\n },\n },\n {\n id: 'title_duplicate',\n title: 'Duplicate title',\n category: 'metadata',\n defaultSeverity: 'medium',\n whyItMatters: 'When multiple pages share the same title, search engines and users get a weaker signal about which page is the right result.',\n howToFix: 'Rewrite each title so it reflects the specific page, including the unique entity, intent, location, product, or angle.',\n impactIfIgnored: 'Search engines may pick the wrong page to rank, and users may see repetitive snippets that do not explain the difference.',\n howToVerify: 'Re-run the crawl and confirm this title appears on only one indexable URL.',\n agentHints: {\n evidenceFields: [\n 'page.title',\n 'issue.evidence.duplicateCount',\n 'issue.evidence.sampleUrls',\n ],\n suggestedCommands: ['seo crawl <url> --json'],\n },\n },\n {\n id: 'h1_missing',\n title: 'Missing H1',\n category: 'headings',\n defaultSeverity: 'low',\n whyItMatters: 'A descriptive main heading helps readers and assistive technology identify the page topic and navigate its content.',\n howToFix: 'Add one clear H1 near the top of the main content. Make it describe the specific page, not just a generic section label.',\n impactIfIgnored: 'The visible document outline may be less clear to readers and assistive technology.',\n howToVerify: 'Re-run the crawl and confirm an H1 describes the page’s main visible topic.',\n agentHints: {\n evidenceFields: ['page.h1', 'page.h1Count'],\n suggestedCommands: ['seo crawl <url> --max-pages 1 --json'],\n },\n },\n {\n id: 'canonical_invalid',\n title: 'Canonical URL is invalid',\n category: 'canonical',\n defaultSeverity: 'high',\n whyItMatters: 'A malformed or non-HTTP canonical cannot identify a valid preferred page and may be ignored by search engines.',\n howToFix: 'Replace it with one absolute HTTP or HTTPS URL for the intended preferred page.',\n impactIfIgnored: 'Search engines receive unusable consolidation evidence and may choose a different canonical on their own.',\n howToVerify: 'Re-run the page audit and confirm the canonical resolves to the intended HTTP or HTTPS URL.',\n agentHints: {\n evidenceFields: [\n 'page.canonical',\n 'page.canonicalRaw',\n 'issue.evidence.canonicalRaw',\n ],\n suggestedCommands: ['seo audit-page --url <url> --json'],\n },\n },\n {\n id: 'canonical_conflict',\n title: 'Canonical declarations conflict',\n category: 'canonical',\n defaultSeverity: 'high',\n whyItMatters: 'Different canonical targets in HTML or HTTP headers give search engines contradictory consolidation signals.',\n howToFix: 'Choose one preferred absolute URL and make every canonical declaration agree, or remove the extra declaration source.',\n impactIfIgnored: 'Search engines may ignore the declarations or select a different canonical than the site intended.',\n howToVerify: 'Re-run the crawl and confirm canonicalStatus is single with one intended target.',\n agentHints: {\n evidenceFields: ['page.canonicalCandidates', 'page.canonicalStatus'],\n suggestedCommands: ['seo crawl <url> --max-pages 1 --json'],\n },\n },\n {\n id: 'canonical_multiple',\n title: 'Canonical declared more than once',\n category: 'canonical',\n defaultSeverity: 'low',\n whyItMatters: 'Repeated canonical declarations are error-prone even when they currently point to the same URL.',\n howToFix: 'Keep one canonical method per response where practical. If HTML and HTTP headers are both required, keep their targets identical.',\n impactIfIgnored: 'A future template or header change can create a hidden canonical conflict.',\n howToVerify: 'Re-run the crawl and confirm canonicalStatus is single.',\n agentHints: {\n evidenceFields: ['page.canonicalCandidates', 'page.canonicalStatus'],\n suggestedCommands: ['seo crawl <url> --max-pages 1 --json'],\n },\n },\n {\n id: 'canonical_outside_head',\n title: 'Canonical appears outside the HTML head',\n category: 'canonical',\n defaultSeverity: 'medium',\n whyItMatters: 'Google only accepts an HTML canonical link element in the document head.',\n howToFix: 'Move the canonical link element into a valid head section and keep one absolute preferred URL.',\n impactIfIgnored: 'The body declaration may be ignored, leaving the page without the intended canonical signal.',\n howToVerify: 'Re-run the crawl and confirm the canonical candidate source is html-head.',\n agentHints: {\n evidenceFields: ['page.canonicalCandidates', 'page.canonicalStatus'],\n suggestedCommands: ['seo crawl <url> --max-pages 1 --json'],\n },\n },\n {\n id: 'canonical_mismatch',\n title: 'Canonical differs from final URL',\n category: 'canonical',\n defaultSeverity: 'medium',\n whyItMatters: 'A canonical pointing somewhere else tells search engines that another URL may be the preferred page. That is useful when intentional and risky when accidental.',\n howToFix: 'If this page should rank, make the canonical self-referencing. If another URL is preferred, make sure internal links and redirects also point there.',\n impactIfIgnored: 'Search engines may consolidate signals into the wrong URL or drop this URL from search results.',\n howToVerify: 'Re-run the page audit and confirm the canonical matches the fetched final URL, or inspect the preferred target instead.',\n agentHints: {\n evidenceFields: ['page.canonical', 'page.finalUrl'],\n suggestedCommands: ['seo audit-page --url <url> --json'],\n },\n },\n {\n id: 'canonical_non_absolute',\n title: 'Canonical uses a relative URL',\n category: 'canonical',\n defaultSeverity: 'low',\n whyItMatters: 'Search engines can usually resolve relative canonicals, but absolute canonical URLs are clearer and less fragile across mirrors, previews, and rendered variants.',\n howToFix: 'Use a full https URL in the canonical tag, including protocol, host, and path.',\n impactIfIgnored: 'Canonical signals are easier to misread when pages are copied, proxied, or rendered from alternate origins.',\n howToVerify: 'Re-run the crawl and confirm canonicalRaw starts with http:// or https://.',\n agentHints: {\n evidenceFields: ['page.canonicalRaw', 'page.canonical'],\n suggestedCommands: ['seo crawl <url> --max-pages 1 --json'],\n },\n },\n {\n id: 'canonical_chain',\n title: 'Canonical chain',\n category: 'canonical',\n defaultSeverity: 'medium',\n whyItMatters: 'A canonical that points to another URL which then canonicalizes again creates an indirect consolidation path.',\n howToFix: 'Point the first page directly at the final preferred URL, or make the intermediate canonical target self-referencing.',\n impactIfIgnored: 'Search engines may ignore or reinterpret the canonical path, especially at scale.',\n howToVerify: 'Re-run the crawl and confirm the canonical target is self-referencing.',\n agentHints: {\n evidenceFields: [\n 'page.canonical',\n 'issue.evidence.nextCanonical',\n 'issue.evidence.chain',\n ],\n suggestedCommands: ['seo crawl <url> --json'],\n },\n },\n {\n id: 'connection_error',\n title: 'Connection error',\n category: 'response',\n defaultSeverity: 'high',\n whyItMatters: 'A URL that cannot be fetched is invisible to users, search crawlers, and AI agents. It may be a DNS, TLS, timeout, firewall, or server availability problem.',\n howToFix: 'Check DNS, TLS certificates, firewall/CDN rules, server logs, and timeout behavior. Make the URL return a stable 2xx response or one direct redirect to the replacement.',\n impactIfIgnored: 'The page cannot be crawled, ranked, or cited while the connection failure remains.',\n howToVerify: 'Re-run the crawl and confirm the URL returns a normal HTTP status instead of status 0.',\n },\n {\n id: 'client_error',\n title: 'Client error',\n category: 'response',\n defaultSeverity: 'high',\n whyItMatters: 'A 4xx URL is a dead end for users and search engines. Internal links to 4xx pages waste crawl attention and leak authority.',\n howToFix: 'Restore the page, update links to the correct URL, or add one direct 301 to the best replacement.',\n impactIfIgnored: 'Users hit broken pages and search engines may drop the URL or reduce trust in nearby internal links.',\n howToVerify: 'Re-run the crawl and confirm the URL returns a 2xx status or redirects once to a useful replacement.',\n },\n {\n id: 'server_error',\n title: 'Server error',\n category: 'response',\n defaultSeverity: 'high',\n whyItMatters: 'A 5xx means the server failed to deliver the page. Persistent 5xx errors can slow crawling and remove pages from search.',\n howToFix: 'Check application logs, hosting health, upstream services, and cache/CDN rules. Return 200 when fixed, or 503 only for planned maintenance.',\n impactIfIgnored: 'Search engines may crawl less often and users cannot reach the affected pages.',\n howToVerify: 'Re-run the crawl and confirm the affected URL no longer returns a 5xx status.',\n },\n {\n id: 'redirected_url',\n title: 'URL redirects',\n category: 'response',\n defaultSeverity: 'low',\n whyItMatters: 'This crawl reached the page through a redirect. A direct redirect can be intentional. It becomes worth fixing when internal links, canonicals, or sitemap entries still point to the old URL.',\n howToFix: 'Check why the old URL was requested. Update internal links, canonicals, and sitemap entries to the final URL when appropriate. Keep one direct 301 when the old URL must remain supported.',\n impactIfIgnored: 'An avoidable redirect adds a request and can turn into a chain later. An intentional direct redirect needs no change.',\n howToVerify: 'Re-run the crawl and confirm the requested URL is the same as the final URL, or that the redirect is intentional.',\n agentHints: {\n evidenceFields: ['page.url', 'page.finalUrl', 'page.status'],\n suggestedCommands: ['seo redirect-trace --url <url> --json'],\n },\n },\n {\n id: 'redirect_chain',\n title: 'Redirect chain',\n category: 'response',\n defaultSeverity: 'medium',\n whyItMatters: 'Multiple redirect hops slow users and crawlers, and each hop is another place a migration can break.',\n howToFix: 'Point internal links, canonicals, and sitemap URLs directly at the final destination. Keep only one necessary 301 from old URLs.',\n impactIfIgnored: 'Pages load slower, crawl paths are less clear, and future redirects can turn into loops or dead ends.',\n howToVerify: 'Re-run the crawl and confirm fetchDiagnostics.redirectChain has zero or one hop.',\n },\n {\n id: 'slow_response',\n title: 'Slow response in this crawl',\n category: 'response',\n defaultSeverity: 'low',\n whyItMatters: 'The crawler observed a slow HTML response. One request is a diagnostic sample, not a field performance verdict, but repeated slow responses are worth investigating.',\n howToFix: 'Repeat the check and use the performance report before changing anything. If the delay persists, check server timing, cache headers, database queries, CDN caching, and origin health.',\n impactIfIgnored: 'Persistent slow HTML can delay users and crawlers. A one-off slow sample may be network or origin variance.',\n howToVerify: 'Re-run the crawl and compare repeated response times. Use field data where available for a user-experience decision.',\n },\n {\n id: 'large_html',\n title: 'Large HTML response',\n category: 'performance',\n defaultSeverity: 'low',\n whyItMatters: 'Large HTML takes longer to download and parse before the browser can even start the rest of the page.',\n howToFix: 'Trim duplicated markup, remove heavy inline data, split non-critical content, and move large scripts or styles out of the HTML response.',\n impactIfIgnored: 'Pages can feel slow on mobile connections and crawlers spend more time processing each URL.',\n howToVerify: 'Re-run the crawl and confirm sizeBytes is below the large HTML threshold for normal pages.',\n agentHints: {\n evidenceFields: ['page.sizeBytes', 'issue.evidence.thresholdBytes'],\n suggestedCommands: ['seo crawl <url> --json'],\n },\n },\n {\n id: 'no_compression',\n title: 'No text compression',\n category: 'performance',\n defaultSeverity: 'low',\n whyItMatters: 'HTML without gzip or brotli sends more bytes than necessary and slows every first page load.',\n howToFix: 'Enable gzip or brotli for HTML and other text responses at the server, CDN, or reverse proxy.',\n impactIfIgnored: 'Users download more data, pages load slower, and the origin may spend more bandwidth than needed.',\n howToVerify: 'Re-run the crawl and confirm compression is br or gzip for sizeable HTML responses.',\n agentHints: {\n evidenceFields: [\n 'page.compression',\n 'page.sizeBytes',\n 'issue.evidence.thresholdBytes',\n ],\n suggestedCommands: ['seo crawl <url> --json'],\n },\n },\n {\n id: 'http_not_secure',\n title: 'Page is not served over HTTPS',\n category: 'security',\n defaultSeverity: 'medium',\n whyItMatters: 'HTTPS is a baseline trust signal. Browsers label HTTP pages as not secure, and users can be intercepted or downgraded.',\n howToFix: 'Install TLS, serve the page on HTTPS, and redirect the HTTP URL to the HTTPS version with a permanent redirect.',\n impactIfIgnored: 'Users see trust warnings, conversions suffer, and search quality signals are weaker.',\n howToVerify: 'Re-run the crawl and confirm finalUrl starts with https:// and isHttps is true.',\n },\n {\n id: 'mixed_content',\n title: 'Mixed content',\n category: 'security',\n defaultSeverity: 'medium',\n whyItMatters: 'An HTTPS page that loads HTTP resources can trigger browser warnings or blocked images, scripts, fonts, or media.',\n howToFix: 'Change insecure resource URLs to HTTPS, update CDN origins, or remove resources that are no longer available securely.',\n impactIfIgnored: 'Parts of the page may break, users lose trust, and the security guarantee of HTTPS is weakened.',\n howToVerify: 'Re-run the crawl and confirm mixedContentCount is zero.',\n agentHints: {\n evidenceFields: [\n 'page.mixedContentSamples',\n 'issue.evidence.mixedContentSamples',\n ],\n suggestedCommands: ['seo crawl <url> --json'],\n },\n },\n {\n id: 'hsts_missing',\n title: 'HSTS header missing',\n category: 'security',\n defaultSeverity: 'low',\n whyItMatters: 'HSTS tells browsers to keep using HTTPS, which reduces downgrade risk after the first secure visit.',\n howToFix: 'Send a Strict-Transport-Security header with a suitable max-age once the whole site is stable on HTTPS.',\n impactIfIgnored: 'Repeat visitors have a larger downgrade window if a network or link tries to send them to HTTP.',\n howToVerify: 'Re-run the crawl and confirm hasHsts is true for HTTPS pages.',\n },\n {\n id: 'broken_internal_link',\n title: 'Broken internal link',\n category: 'links',\n defaultSeverity: 'high',\n whyItMatters: 'Internal links that land on broken URLs waste crawl paths, frustrate users, and leak authority inside the site.',\n howToFix: 'Update every internal link to the working destination, restore the missing page, or add one direct 301 to the best replacement.',\n impactIfIgnored: 'Users hit dead ends and search engines keep discovering broken URLs from your own pages.',\n howToVerify: 'Re-run the crawl and confirm the linked URL no longer returns a broken status.',\n },\n {\n id: 'broken_external_link',\n title: 'Broken external link',\n category: 'links',\n defaultSeverity: 'medium',\n whyItMatters: 'External links are part of the page experience and source trail. Broken references make content feel stale and less trustworthy.',\n howToFix: 'Replace the link with a working source, update the URL, or remove the reference if it no longer supports the page.',\n impactIfIgnored: 'Readers and agents following citations hit dead ends, which weakens trust in the content.',\n howToVerify: 'Re-run the crawl with external checks enabled and confirm the external link no longer appears in externalLinkChecks as broken.',\n },\n {\n id: 'orphan_page',\n title: 'No observed internal links',\n category: 'links',\n defaultSeverity: 'low',\n whyItMatters: 'This crawl did not find an internal link to the page. That is worth checking, but a partial crawl cannot prove that the page is a true sitewide orphan.',\n howToFix: 'Check the page in a complete crawl and in the sitemap. If it is meant to be discovered, add a relevant link from a hub, navigation path, related page, or template.',\n impactIfIgnored: 'A genuinely unlinked page can be hard for users and crawlers to find. A page omitted by the crawl needs no change yet.',\n howToVerify: 'Re-run a complete crawl from the same site entry point and confirm an observed internal link reaches the page.',\n },\n {\n id: 'deep_page',\n title: 'Deep crawl path',\n category: 'links',\n defaultSeverity: 'low',\n whyItMatters: 'This crawl reached the page several links away from its start URL. A capped crawl or a non-homepage start URL does not prove the shortest sitewide path.',\n howToFix: 'Check whether the page is important and whether a shorter user path makes sense. Add a link from a closer hub, category page, related content block, or navigation path only when it helps users.',\n impactIfIgnored: 'A genuinely deep important page can be harder to reach. Treat this as a crawl-path review, not a sitewide architecture verdict.',\n howToVerify: 'Re-run a complete crawl from the same start URL and confirm crawlDepth changed after a justified link update.',\n },\n {\n id: 'weak_internal_links_to_valuable_page',\n title: 'Review internal links to a valuable page',\n category: 'links',\n defaultSeverity: 'low',\n whyItMatters: 'The page has observed search or analytics value but few inlinks within this crawl. It is a review cue, not proof that the page lacks enough internal authority.',\n howToFix: \"Check the page's role and current navigation first. Add contextual links from relevant hubs, templates, or related pages only when they help users reach it.\",\n impactIfIgnored: 'A valuable page may be harder to find if it is genuinely underlinked. Do not treat the observed count as a ranking forecast.',\n howToVerify: 'Re-run the same crawl after a justified link change and confirm the observed inlink count changed.',\n },\n {\n id: 'missing_meta_description',\n title: 'Meta description missing',\n category: 'metadata',\n defaultSeverity: 'medium',\n whyItMatters: 'The meta description is often used as search-result copy. Without it, search engines choose their own snippet.',\n howToFix: 'Write a concise, unique description that explains the page value and matches the main search intent.',\n impactIfIgnored: 'Search snippets may be generic or less persuasive, especially on pages that already rank.',\n howToVerify: 'Re-run the crawl and confirm the page has a meta description.',\n },\n {\n id: 'meta_description_duplicate',\n title: 'Duplicate meta description',\n category: 'metadata',\n defaultSeverity: 'medium',\n whyItMatters: 'Repeated descriptions make different pages look interchangeable and can weaken snippet quality across a section.',\n howToFix: 'Write a distinct description for each page that explains what is unique about that URL.',\n impactIfIgnored: 'Search snippets stay generic, and search engines may rewrite them or struggle to distinguish similar pages.',\n howToVerify: 'Re-run the crawl and confirm this description appears on only one URL.',\n agentHints: {\n evidenceFields: [\n 'page.metaDescription',\n 'issue.evidence.duplicateCount',\n 'issue.evidence.sampleUrls',\n ],\n suggestedCommands: ['seo crawl <url> --json'],\n },\n },\n {\n id: 'canonical_missing',\n title: 'No canonical declared',\n category: 'canonical',\n defaultSeverity: 'low',\n whyItMatters: 'The page did not declare a canonical. That is often fine for a unique URL. It matters when parameter, protocol, pagination, or duplicate-content variants need a preferred URL.',\n howToFix: 'First check whether equivalent URL variants exist. Add a self-referencing canonical only when the site uses canonical tags as part of a deliberate duplicate-URL strategy.',\n impactIfIgnored: 'A unique page may need no action. If duplicate variants exist, search engines can choose a different preferred URL.',\n howToVerify: 'Re-run the crawl and confirm the canonical field is present and points to the preferred URL.',\n },\n {\n id: 'noindex',\n title: 'Noindex found',\n category: 'indexability',\n defaultSeverity: 'medium',\n whyItMatters: 'Noindex tells search engines not to show the page in search results. It is useful when intentional and risky when accidental.',\n howToFix: 'Remove the noindex directive if the page should rank. Leave it in place only for intentionally private or low-value pages.',\n impactIfIgnored: 'The page cannot earn organic search traffic while the noindex directive remains.',\n howToVerify: 'Re-run the crawl or URL Inspection and confirm no effective meta robots or X-Robots-Tag noindex remains, including the equivalent none directive.',\n },\n {\n id: 'nofollow',\n title: 'Nofollow found',\n category: 'indexability',\n defaultSeverity: 'low',\n whyItMatters: 'Nofollow asks crawlers not to follow links from the page. On important pages, that can block discovery and weaken internal authority flow.',\n howToFix: 'Remove nofollow from meta robots or X-Robots-Tag unless the page is intentionally isolated from link discovery.',\n impactIfIgnored: 'Internal links on the page may pass weaker discovery and authority signals.',\n howToVerify: 'Re-run the crawl and confirm the effective meta robots and X-Robots-Tag rules no longer block following, including through the equivalent none directive.',\n agentHints: {\n evidenceFields: ['page.metaRobots', 'page.xRobotsTag'],\n suggestedCommands: ['seo crawl <url> --max-pages 1 --json'],\n },\n },\n {\n id: 'x_robots_noindex',\n title: 'X-Robots-Tag noindex',\n category: 'indexability',\n defaultSeverity: 'medium',\n whyItMatters: 'An X-Robots-Tag noindex header can remove a page from search even when the HTML looks indexable.',\n howToFix: 'Remove the noindex directive from server, CDN, or framework response headers if the page should rank.',\n impactIfIgnored: 'The page remains excluded from search results while the header is present.',\n howToVerify: 'Re-run the crawl and confirm the effective X-Robots-Tag rules no longer block indexing, including through the equivalent none directive.',\n agentHints: {\n evidenceFields: ['page.xRobotsTag', 'page.responseHeaders'],\n suggestedCommands: ['seo crawl <url> --max-pages 1 --json'],\n },\n },\n {\n id: 'robots_blocked',\n title: 'Blocked by robots.txt',\n category: 'indexability',\n defaultSeverity: 'medium',\n whyItMatters: 'Robots.txt blocking prevents crawlers from fetching the URL. If accidental, search engines and AI systems cannot evaluate the page content.',\n howToFix: 'Update robots.txt so important public pages are allowed, or leave the block in place only for intentionally private or low-value paths.',\n impactIfIgnored: 'The page may stay uncrawled, stale, or missing from search and AI retrieval systems.',\n howToVerify: 'Re-run the crawl and confirm robotsTxt.allowed is true for the URL.',\n agentHints: {\n evidenceFields: ['page.robotsTxt'],\n suggestedCommands: ['seo crawl <url> --json'],\n },\n },\n {\n id: 'canonicalized_page',\n title: 'Canonicalized page',\n category: 'indexability',\n defaultSeverity: 'low',\n whyItMatters: 'A canonicalized page tells search engines another URL should receive the ranking signals. That is fine when intentional and risky when accidental.',\n howToFix: 'If this URL should rank, make the canonical self-referencing. If another URL is preferred, make internal links and sitemap entries point to that preferred URL.',\n impactIfIgnored: 'The page may be excluded from search in favor of the canonical target.',\n howToVerify: 'Re-run the crawl and confirm the canonical target matches the intended indexable URL.',\n agentHints: {\n evidenceFields: ['page.canonical', 'page.finalUrl', 'page.indexability'],\n suggestedCommands: ['seo crawl <url> --max-pages 1 --json'],\n },\n },\n {\n id: 'duplicate_content',\n title: 'Duplicate content',\n category: 'content',\n defaultSeverity: 'medium',\n whyItMatters: 'Pages with the same main content force search engines to choose a winner and can split internal signals across duplicates.',\n howToFix: 'Consolidate duplicate pages with redirects or canonicals, or make each page meaningfully different for its own intent.',\n impactIfIgnored: 'The wrong URL may rank, similar pages may underperform, and AI systems may cite a less useful duplicate.',\n howToVerify: 'Re-run the crawl and confirm the duplicate mainContentHash appears on only one URL.',\n agentHints: {\n evidenceFields: [\n 'page.mainContentHash',\n 'issue.evidence.duplicateCount',\n 'issue.evidence.sampleUrls',\n ],\n suggestedCommands: ['seo crawl <url> --json'],\n },\n },\n {\n id: 'query_coverage_missing',\n title: 'Review top-query text coverage',\n category: 'content',\n defaultSeverity: 'low',\n whyItMatters: 'The top reported query has terms that were not found in the title, description, H1, or retained content sample. Exact terms alone do not prove relevance, and the sample cannot assess every section or useful synonym.',\n howToFix: 'Read the page and the search results before changing copy. Add or clarify wording only when it makes the page answer the query better. Do not force exact terms into a page that already serves the intent.',\n impactIfIgnored: 'Use this as a review prompt. It does not predict rankings, clicks, or a need to rewrite the page.',\n howToVerify: 'Re-run the crawl with the same GSC property and review the query, sampled text, and any deliberate wording changes together.',\n agentHints: {\n evidenceFields: [\n 'page.topQuery',\n 'issue.evidence.missingTerms',\n 'issue.evidence.coverage',\n ],\n suggestedCommands: ['seo crawl <url> --project <id> --json'],\n },\n },\n {\n id: 'image_missing_alt',\n title: 'Images lack alt attributes',\n category: 'images',\n defaultSeverity: 'medium',\n whyItMatters: 'An image with no alt attribute gives screen readers no declared text alternative. A deliberately empty alt attribute is valid for decorative images and is not included here.',\n howToFix: 'Add concise alt text to meaningful images that currently have no alt attribute. Keep alt=\"\" on decorative images.',\n impactIfIgnored: 'People using screen readers may miss the purpose of a meaningful image, and search engines have less image context.',\n howToVerify: 'Re-run the crawl and confirm imagesMissingAlt is zero. Decorative images can keep an empty alt attribute.',\n },\n {\n id: 'image_oversized_candidate',\n title: 'Oversized image candidates',\n category: 'images',\n defaultSeverity: 'low',\n whyItMatters: 'Very large images can slow pages down, especially when the browser only needs a small rendered size.',\n howToFix: 'Resize the source image, add responsive srcset sizes, and serve modern compressed formats such as WebP or AVIF where supported.',\n impactIfIgnored: 'Users may download more image data than needed, which hurts load speed and wastes bandwidth.',\n howToVerify: 'Re-run the crawl and confirm oversizedImageCandidates is empty, then spot-check the page in a browser performance trace if the image is important.',\n agentHints: {\n evidenceFields: [\n 'page.oversizedImageCandidates',\n 'issue.evidence.thresholdPx',\n 'issue.evidence.candidates',\n ],\n suggestedCommands: ['seo crawl <url> --max-pages 10 --json'],\n },\n },\n {\n id: 'viewport_missing',\n title: 'Viewport missing',\n category: 'mobile',\n defaultSeverity: 'medium',\n whyItMatters: 'The viewport tag lets mobile browsers render responsive layouts correctly.',\n howToFix: 'Add `<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">` to the document head.',\n impactIfIgnored: 'Mobile users may get a zoomed-out desktop page and mobile-first search quality can suffer.',\n howToVerify: 'Re-run the crawl and confirm hasViewport is true.',\n },\n {\n id: 'lang_missing',\n title: 'Language missing',\n category: 'international',\n defaultSeverity: 'low',\n whyItMatters: 'The html lang attribute helps browsers, screen readers, search engines, and translators understand the page language.',\n howToFix: 'Set the language on the root html element, for example `<html lang=\"en\">`.',\n impactIfIgnored: 'Accessibility and language targeting signals are weaker.',\n howToVerify: 'Re-run the crawl and confirm the lang field is populated.',\n },\n {\n id: 'hreflang_invalid',\n title: 'Malformed hreflang values',\n category: 'international',\n defaultSeverity: 'low',\n whyItMatters: 'These hreflang values do not match the basic language or language-region shape. This check does not validate every officially supported language or region code.',\n howToFix: 'Use a supported language or language-region code such as en, en-gb, fr-ca, or x-default. Check the current Google hreflang documentation before changing a locale set.',\n impactIfIgnored: 'Search engines may ignore malformed annotations and show a less relevant regional page.',\n howToVerify: 'Re-run the crawl and confirm no hreflang values are marked malformed. Validate the full locale set against Google documentation.',\n agentHints: {\n evidenceFields: ['page.hreflang', 'issue.evidence.malformed'],\n suggestedCommands: ['seo crawl <url> --json'],\n },\n },\n {\n id: 'hreflang_duplicate',\n title: 'Repeated hreflang values',\n category: 'international',\n defaultSeverity: 'low',\n whyItMatters: 'Repeated hreflang declarations make a locale set harder to review. They only conflict when the same language code points to different URLs.',\n howToFix: 'Keep one hreflang declaration per language code. If repeated codes point to different URLs, decide which page is the intended locale target.',\n impactIfIgnored: 'Conflicting duplicate targets may be ignored. Identical repeats are usually cleanup work, not a search emergency.',\n howToVerify: 'Re-run the crawl and confirm each hreflang code appears only once per page.',\n agentHints: {\n evidenceFields: ['page.hreflang', 'issue.evidence.duplicateCodes'],\n suggestedCommands: ['seo crawl <url> --json'],\n },\n },\n {\n id: 'hreflang_incomplete',\n title: 'Hreflang missing self reference',\n category: 'international',\n defaultSeverity: 'low',\n whyItMatters: 'A page that declares hreflang should include an alternate that points back to its own final URL. An x-default entry does not replace that self reference.',\n howToFix: \"Add one hreflang entry that points to this page's final URL. Keep x-default as an additional fallback only where it is useful.\",\n impactIfIgnored: 'Search engines may treat the hreflang set as incomplete and show a less relevant language variant.',\n howToVerify: 'Re-run the crawl and confirm one hreflang href matches the fetched final URL.',\n agentHints: {\n evidenceFields: ['page.lang', 'page.hreflang'],\n suggestedCommands: ['seo crawl <url> --json'],\n },\n },\n {\n id: 'jsonld_invalid',\n title: 'Invalid JSON-LD',\n category: 'structured-data',\n defaultSeverity: 'medium',\n whyItMatters: 'Broken JSON-LD can make structured data unreadable even when the right schema was intended.',\n howToFix: 'Fix the JSON syntax in each application/ld+json script. Validate quotes, commas, braces, and any server-rendered values inserted into the block.',\n impactIfIgnored: 'Consumers cannot reliably read the invalid block, and Google cannot use unreadable markup for supported Search features.',\n howToVerify: 'Re-run the crawl and confirm invalidJsonLdCount is zero, then validate the page with a structured data tester.',\n agentHints: {\n evidenceFields: [\n 'page.invalidJsonLdSamples',\n 'issue.evidence.invalidJsonLdSamples',\n ],\n suggestedCommands: ['seo crawl <url> --max-pages 1 --json'],\n },\n },\n {\n id: 'rich_result_required_fields_missing',\n title: 'Required rich-result properties are missing',\n category: 'structured-data',\n defaultSeverity: 'medium',\n whyItMatters: 'Schema.org vocabulary and valid JSON syntax do not make markup eligible for a Google rich result when documented required properties are absent.',\n howToFix: 'Add the missing properties only when they accurately represent visible page content. Follow the linked Google feature documentation and validate the result.',\n impactIfIgnored: 'Google can understand some of the markup while still treating the item as ineligible for that enhanced Search feature.',\n howToVerify: 'Re-run the crawl, review googleRichResults, and confirm no supported item reports missing-required-properties. Then use Google’s Rich Results Test.',\n agentHints: {\n evidenceFields: ['page.googleRichResults', 'issue.evidence.assessments'],\n suggestedCommands: ['seo crawl <url> --max-pages 1 --json'],\n },\n },\n {\n id: 'og_title_missing',\n title: 'Open Graph title missing',\n category: 'social',\n defaultSeverity: 'low',\n whyItMatters: 'Open Graph tags control how pages appear in social feeds, chat previews, and many sharing surfaces.',\n howToFix: 'Add an og:title that matches the page title or a share-friendly version of it.',\n impactIfIgnored: 'Shared links can look generic, reducing clicks from social and messaging apps.',\n howToVerify: 'Re-run the crawl and confirm openGraphTitle is present.',\n },\n {\n id: 'og_description_missing',\n title: 'Open Graph description missing',\n category: 'social',\n defaultSeverity: 'low',\n whyItMatters: 'The Open Graph description is often the short pitch shown when a page is shared in chat, Slack, social feeds, and link previews.',\n howToFix: 'Add an og:description that briefly explains why the page is worth opening.',\n impactIfIgnored: 'Shared links can appear vague or empty, which reduces clicks from discovery surfaces.',\n howToVerify: 'Re-run the crawl and confirm openGraphDescription is present.',\n },\n {\n id: 'og_image_missing',\n title: 'Open Graph image missing',\n category: 'social',\n defaultSeverity: 'low',\n whyItMatters: 'An Open Graph image helps shared links stand out and makes previews feel trustworthy and complete.',\n howToFix: 'Add an og:image URL with a representative image that crawlers can fetch over HTTPS.',\n impactIfIgnored: 'Shared links may render without a visual preview, reducing click appeal.',\n howToVerify: 'Re-run the crawl and confirm openGraphImage is present.',\n },\n {\n id: 'twitter_card_missing',\n title: 'No Twitter card declared',\n category: 'social',\n defaultSeverity: 'low',\n whyItMatters: 'A Twitter card tells X which preview format to use. X can sometimes fall back to Open Graph metadata, so this is a sharing observation, not a search issue.',\n howToFix: 'Add twitter:card and matching metadata only when you need a specific X preview. Keep Open Graph metadata accurate either way.',\n impactIfIgnored: 'X may use fallback metadata or a simple link preview. Organic rankings are not affected.',\n howToVerify: 'Re-run the crawl and confirm twitterCard is present if a specific X preview is required.',\n },\n];\nconst RULE_RECOMMENDATIONS = {\n title_too_wide: 'review',\n canonical_missing: 'review',\n canonical_multiple: 'review',\n canonical_mismatch: 'review',\n canonical_non_absolute: 'review',\n canonicalized_page: 'review',\n noindex: 'review',\n nofollow: 'review',\n x_robots_noindex: 'review',\n robots_blocked: 'review',\n orphan_page: 'review',\n redirected_url: 'review',\n slow_response: 'review',\n image_oversized_candidate: 'review',\n hsts_missing: 'review',\n og_title_missing: 'review',\n og_description_missing: 'review',\n og_image_missing: 'review',\n twitter_card_missing: 'review',\n};\nconst RULES_BY_ID = new Map(RULE_DEFINITIONS.map((rule) => [\n rule.id,\n {\n ...rule,\n recommendation: RULE_RECOMMENDATIONS[rule.id] ?? 'fix',\n },\n]));\nexport function listRules() {\n return [...RULES_BY_ID.values()];\n}\nexport function explainRule(ruleId) {\n return RULES_BY_ID.get(ruleId);\n}\nexport function recommendationForRule(ruleId) {\n return explainRule(ruleId)?.recommendation ?? 'fix';\n}\nexport function hasRule(ruleId) {\n return RULES_BY_ID.has(ruleId);\n}\n//# sourceMappingURL=rules.js.map","function comparableUrl(value) {\n if (!value)\n return undefined;\n try {\n const url = new URL(value);\n url.hash = '';\n return url.toString();\n }\n catch {\n return value;\n }\n}\nexport function isRedirectedPage(page) {\n const requested = comparableUrl(page.url);\n const final = comparableUrl(page.finalUrl);\n return Boolean(requested && final && requested !== final);\n}\nexport function isSuccessfulResponse(page) {\n return page.status >= 200 && page.status < 300;\n}\nexport function isHtmlPage(page) {\n return /^\\s*(?:text\\/html|application\\/xhtml\\+xml)\\b/i.test(page.contentType ?? '');\n}\nexport function isAuditableHtmlPage(page) {\n const contentAuditAllowed = page.contentAuditAllowed ??\n (!page.blocked && page.robotsTxt?.allowed !== false);\n return (isSuccessfulResponse(page) &&\n isHtmlPage(page) &&\n !isRedirectedPage(page) &&\n contentAuditAllowed);\n}\n//# sourceMappingURL=page-eligibility.js.map","import { hasMetaRobotsDirective, hasXRobotsDirective, } from '../../robots-directives.js';\nimport { explainRule } from '../../rules.js';\nimport { estimateSerpTitleWidth } from '../title-width.js';\nimport { isAuditableHtmlPage, isHtmlPage, isRedirectedPage, } from './page-eligibility.js';\nfunction sameUrl(a, b) {\n if (!a || !b)\n return false;\n try {\n const left = new URL(a);\n const right = new URL(b);\n left.hash = '';\n right.hash = '';\n return left.toString() === right.toString();\n }\n catch {\n return a === b;\n }\n}\nfunction absoluteHttpUrl(value) {\n try {\n const url = new URL(value ?? '');\n return url.protocol === 'http:' || url.protocol === 'https:';\n }\n catch {\n return false;\n }\n}\nfunction urlKey(value) {\n if (!value)\n return undefined;\n try {\n const url = new URL(value);\n url.hash = '';\n return url.toString();\n }\n catch {\n return undefined;\n }\n}\nconst SLOW_RESPONSE_MS = 2_000;\nconst LARGE_HTML_BYTES = 2 * 1024 * 1024;\nconst COMPRESSION_MIN_BYTES = 4 * 1024;\nconst DEEP_PAGE_DEPTH = 4;\nconst WEAK_VALUABLE_INLINKS = 1;\nconst QUERY_COVERAGE_MIN_IMPRESSIONS = 50;\nconst QUERY_COVERAGE_MIN = 0.6;\nconst OVERSIZED_IMAGE_CANDIDATE_LIMIT = 2000;\nfunction issue(ruleId, page, detail, evidence) {\n const rule = explainRule(ruleId);\n if (!rule) {\n throw new Error(`Missing rule guidance for ${ruleId}`);\n }\n return {\n ruleId,\n title: rule.title,\n category: rule.category,\n severity: rule.defaultSeverity,\n url: page.url,\n detail,\n evidence,\n searchMetrics: page.searchMetrics,\n };\n}\nfunction requestIssue(ruleId, request, detail, evidence) {\n const rule = explainRule(ruleId);\n if (!rule) {\n throw new Error(`Missing rule guidance for ${ruleId}`);\n }\n return {\n ruleId,\n title: rule.title,\n category: rule.category,\n severity: rule.defaultSeverity,\n url: request.requestedUrl,\n detail,\n evidence,\n };\n}\nfunction isBrokenLinkStatus(status) {\n return (status === 0 || status === 404 || status === 410 || (status ?? 0) >= 500);\n}\nfunction hasRecognizableHreflangFormat(value) {\n const normalized = value.trim().toLowerCase();\n return (normalized === 'x-default' ||\n /^[a-z]{2}(?:-[a-z]{4})?(?:-[a-z]{2})?$/.test(normalized));\n}\nfunction isValuablePage(page) {\n return ((page.searchMetrics?.clicks ?? 0) > 0 ||\n (page.searchMetrics?.impressions ?? 0) >= 100 ||\n (page.analytics?.sessions ?? 0) >= 25);\n}\nfunction normalizedMetadata(value) {\n const normalized = value?.trim().replace(/\\s+/g, ' ').toLowerCase();\n return normalized || undefined;\n}\nfunction metadataDuplicates(pages, read) {\n const counts = new Map();\n for (const page of pages) {\n if (!isAuditableHtmlPage(page))\n continue;\n const raw = read(page)?.trim();\n const key = normalizedMetadata(raw);\n if (!key || !raw)\n continue;\n const existing = counts.get(key) ?? { count: 0, sampleUrls: [], value: raw };\n existing.count += 1;\n if (existing.sampleUrls.length < 10)\n existing.sampleUrls.push(page.url);\n counts.set(key, existing);\n }\n return new Map([...counts].filter(([, value]) => value.count > 1));\n}\nfunction contentDuplicates(pages) {\n const counts = new Map();\n for (const page of pages) {\n if (!isAuditableHtmlPage(page))\n continue;\n if (page.wordCount < 20 || !page.mainContentHash)\n continue;\n const existing = counts.get(page.mainContentHash) ?? {\n count: 0,\n sampleUrls: [],\n };\n existing.count += 1;\n if (existing.sampleUrls.length < 10)\n existing.sampleUrls.push(page.url);\n counts.set(page.mainContentHash, existing);\n }\n return new Map([...counts].filter(([, value]) => value.count > 1));\n}\nconst QUERY_STOP_WORDS = new Set([\n 'a',\n 'an',\n 'and',\n 'are',\n 'for',\n 'from',\n 'how',\n 'in',\n 'is',\n 'of',\n 'on',\n 'or',\n 'the',\n 'to',\n 'vs',\n 'what',\n 'with',\n]);\nfunction queryTerms(query) {\n return [\n ...new Set(query\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((term) => term.length > 2 && !QUERY_STOP_WORDS.has(term))),\n ];\n}\nfunction queryCoverage(page) {\n const query = page.topQuery?.query;\n if (!query ||\n (page.topQuery?.impressions ?? 0) < QUERY_COVERAGE_MIN_IMPRESSIONS) {\n return undefined;\n }\n const terms = queryTerms(query);\n if (!terms.length)\n return undefined;\n const haystack = [\n page.title,\n page.metaDescription,\n page.h1,\n page.contentSample,\n ]\n .filter(Boolean)\n .join(' ')\n .toLowerCase();\n const matchedTerms = terms.filter((term) => haystack.includes(term));\n const missingTerms = terms.filter((term) => !haystack.includes(term));\n return {\n query,\n matchedTerms,\n missingTerms,\n coverage: matchedTerms.length / terms.length,\n };\n}\nexport function auditCrawlRequests(requests) {\n const issues = [];\n for (const request of requests) {\n if (request.outcome === 'failure') {\n if (request.failureKind === 'aborted')\n continue;\n issues.push(requestIssue('connection_error', request, request.error, {\n outcome: request.outcome,\n failureKind: request.failureKind,\n durationMs: request.durationMs,\n error: request.error,\n }));\n continue;\n }\n if (request.outcome === 'skipped')\n continue;\n const redirectChain = request.redirectChain ?? [];\n const redirected = redirectChain.length > 0 ||\n !sameUrl(request.requestedUrl, request.finalUrl);\n if (redirected) {\n issues.push(requestIssue('redirected_url', request, request.finalUrl ? `Final URL: ${request.finalUrl}` : undefined, {\n requestedUrl: request.requestedUrl,\n finalUrl: request.finalUrl,\n status: redirectChain[0]?.status,\n finalStatus: request.status,\n }));\n }\n if (redirectChain.length > 1) {\n issues.push(requestIssue('redirect_chain', request, `${redirectChain.length} hops`, {\n redirectChain,\n hops: redirectChain.length,\n }));\n }\n }\n return issues;\n}\nexport function auditCrawlPages(pages, opts = {}) {\n const issues = [];\n const duplicateTitles = metadataDuplicates(pages, (page) => page.title);\n const duplicateDescriptions = metadataDuplicates(pages, (page) => page.metaDescription);\n const duplicateContent = contentDuplicates(pages);\n const pageByUrl = new Map();\n for (const page of pages) {\n if (!isAuditableHtmlPage(page))\n continue;\n for (const value of [page.url, page.finalUrl]) {\n const key = urlKey(value);\n if (key)\n pageByUrl.set(key, page);\n }\n }\n for (const page of pages) {\n if (page.status === 0) {\n issues.push(issue('connection_error', page, page.error, {\n status: page.status,\n error: page.error,\n }));\n continue;\n }\n if (page.status >= 500) {\n issues.push(issue('server_error', page, String(page.status), {\n status: page.status,\n }));\n if ((page.internalInlinkCount ?? 0) > 0) {\n issues.push(issue('broken_internal_link', page, String(page.status), {\n status: page.status,\n internalInlinkCount: page.internalInlinkCount,\n }));\n }\n continue;\n }\n if (page.status >= 400) {\n issues.push(issue('client_error', page, String(page.status), {\n status: page.status,\n }));\n if (isBrokenLinkStatus(page.status) &&\n (page.internalInlinkCount ?? 0) > 0) {\n issues.push(issue('broken_internal_link', page, String(page.status), {\n status: page.status,\n internalInlinkCount: page.internalInlinkCount,\n }));\n }\n continue;\n }\n if (page.status >= 300) {\n issues.push(issue('redirected_url', page, `Status ${page.status}`, {\n requestedUrl: page.url,\n finalUrl: page.finalUrl,\n status: page.status,\n }));\n continue;\n }\n if (page.status < 200)\n continue;\n const redirected = isRedirectedPage(page);\n if (redirected) {\n issues.push(issue('redirected_url', page, `Final URL: ${page.finalUrl}`, {\n requestedUrl: page.url,\n finalUrl: page.finalUrl,\n status: page.status,\n }));\n }\n const redirectChain = page.fetchDiagnostics?.redirectChain ?? [];\n if (redirectChain.length > 1) {\n issues.push(issue('redirect_chain', page, `${redirectChain.length} hops`, {\n redirectChain,\n hops: redirectChain.length,\n }));\n }\n if ((page.responseTimeMs ?? 0) > SLOW_RESPONSE_MS) {\n issues.push(issue('slow_response', page, `${page.responseTimeMs}ms`, {\n responseTimeMs: page.responseTimeMs,\n thresholdMs: SLOW_RESPONSE_MS,\n }));\n }\n if (redirected)\n continue;\n if (isHtmlPage(page) && (page.sizeBytes ?? 0) > LARGE_HTML_BYTES) {\n issues.push(issue('large_html', page, `${Math.round((page.sizeBytes ?? 0) / 1024)} KB`, {\n sizeBytes: page.sizeBytes,\n thresholdBytes: LARGE_HTML_BYTES,\n }));\n }\n if (isHtmlPage(page) &&\n !page.compression &&\n (page.sizeBytes ?? 0) > COMPRESSION_MIN_BYTES) {\n issues.push(issue('no_compression', page, undefined, {\n sizeBytes: page.sizeBytes,\n thresholdBytes: COMPRESSION_MIN_BYTES,\n compression: page.compression,\n }));\n }\n if (page.isHttps === false) {\n issues.push(issue('http_not_secure', page, undefined, {\n finalUrl: page.finalUrl,\n }));\n }\n else if (page.isHttps === true) {\n if ((page.mixedContentCount ?? 0) > 0) {\n issues.push(issue('mixed_content', page, `${page.mixedContentCount} insecure resources`, {\n mixedContentCount: page.mixedContentCount,\n mixedContentSamples: page.mixedContentSamples,\n }));\n }\n if (page.hasHsts === false) {\n issues.push(issue('hsts_missing', page, undefined, {\n header: 'strict-transport-security',\n }));\n }\n }\n for (const link of page.externalLinkChecks ?? []) {\n if (!isBrokenLinkStatus(link.status))\n continue;\n issues.push(issue('broken_external_link', page, link.url, {\n url: link.url,\n status: link.status,\n error: link.error,\n }));\n }\n if (page.indexable &&\n (page.internalInlinkCount ?? 0) === 0 &&\n !sameUrl(page.url, opts.startUrl)) {\n issues.push(issue('orphan_page', page, 'No internal inlinks', {\n internalInlinkCount: page.internalInlinkCount ?? 0,\n }));\n }\n if ((page.crawlDepth ?? 0) > DEEP_PAGE_DEPTH) {\n issues.push(issue('deep_page', page, `Depth ${page.crawlDepth}`, {\n crawlDepth: page.crawlDepth,\n threshold: DEEP_PAGE_DEPTH,\n }));\n }\n if (page.indexable &&\n isValuablePage(page) &&\n (page.internalInlinkCount ?? 0) <= WEAK_VALUABLE_INLINKS) {\n issues.push(issue('weak_internal_links_to_valuable_page', page, `${page.internalInlinkCount ?? 0} internal inlinks`, {\n internalInlinkCount: page.internalInlinkCount ?? 0,\n searchMetrics: page.searchMetrics,\n analytics: page.analytics,\n }));\n }\n if (page.robotsTxt?.allowed === false) {\n issues.push(issue('robots_blocked', page, page.robotsTxt.matchedLine, {\n robotsTxt: page.robotsTxt,\n }));\n }\n const xRobotsNoindex = hasXRobotsDirective(page.xRobotsTag, 'noindex');\n if (xRobotsNoindex) {\n issues.push(issue('x_robots_noindex', page, page.xRobotsTag, {\n xRobotsTag: page.xRobotsTag,\n }));\n }\n const xRobotsNofollow = hasXRobotsDirective(page.xRobotsTag, 'nofollow');\n if (xRobotsNofollow) {\n issues.push(issue('nofollow', page, page.xRobotsTag, {\n xRobotsTag: page.xRobotsTag,\n }));\n }\n if (!isAuditableHtmlPage(page))\n continue;\n const title = page.title?.trim();\n const titleWidth = title ? estimateSerpTitleWidth(title) : undefined;\n const duplicateTitle = duplicateTitles.get(normalizedMetadata(title) ?? '');\n if (!title) {\n issues.push(issue('missing_title', page));\n }\n else if (titleWidth?.status === 'over-reference') {\n issues.push(issue('title_too_wide', page, `${titleWidth.estimatedPixels}px`, {\n title,\n ...titleWidth,\n }));\n }\n if (title && duplicateTitle) {\n issues.push(issue('title_duplicate', page, duplicateTitle.value, {\n title,\n duplicateCount: duplicateTitle.count,\n sampleUrls: duplicateTitle.sampleUrls,\n }));\n }\n const metaDescription = page.metaDescription?.trim();\n const duplicateDescription = duplicateDescriptions.get(normalizedMetadata(metaDescription) ?? '');\n if (!metaDescription) {\n issues.push(issue('missing_meta_description', page));\n }\n if (metaDescription && duplicateDescription) {\n issues.push(issue('meta_description_duplicate', page, duplicateDescription.value, {\n metaDescription,\n duplicateCount: duplicateDescription.count,\n sampleUrls: duplicateDescription.sampleUrls,\n }));\n }\n const h1Count = page.h1Count ?? (page.h1 ? 1 : 0);\n if (h1Count === 0) {\n issues.push(issue('h1_missing', page, 'No H1 found', {\n h1Count,\n }));\n }\n if (page.canonicalStatus === 'conflicting') {\n issues.push(issue('canonical_conflict', page, undefined, {\n candidates: page.canonicalCandidates,\n }));\n }\n else if (page.canonicalStatus === 'duplicate') {\n issues.push(issue('canonical_multiple', page, page.canonical, {\n canonical: page.canonical,\n candidates: page.canonicalCandidates,\n }));\n }\n else if (page.canonicalStatus === 'outside-head-only') {\n issues.push(issue('canonical_outside_head', page, page.canonicalRaw, {\n candidates: page.canonicalCandidates,\n }));\n }\n if (!page.canonical &&\n !['conflicting', 'outside-head-only'].includes(page.canonicalStatus ?? '')) {\n issues.push(page.canonicalRaw\n ? issue('canonical_invalid', page, page.canonicalRaw, {\n canonicalRaw: page.canonicalRaw,\n })\n : issue('canonical_missing', page));\n }\n else {\n if (page.canonicalRaw && !absoluteHttpUrl(page.canonicalRaw)) {\n issues.push(issue('canonical_non_absolute', page, page.canonicalRaw, {\n canonicalRaw: page.canonicalRaw,\n canonical: page.canonical,\n }));\n }\n const canonicalTarget = pageByUrl.get(urlKey(page.canonical) ?? '');\n if (canonicalTarget?.canonical &&\n !sameUrl(canonicalTarget.canonical, page.canonical)) {\n issues.push(issue('canonical_chain', page, page.canonical, {\n canonical: page.canonical,\n nextCanonical: canonicalTarget.canonical,\n chain: [page.finalUrl, page.canonical, canonicalTarget.canonical],\n }));\n }\n }\n const metaNoindex = hasMetaRobotsDirective(page.metaRobots, 'noindex');\n if (metaNoindex) {\n issues.push(issue('noindex', page, page.indexability, {\n metaRobots: page.metaRobots,\n }));\n }\n if (hasMetaRobotsDirective(page.metaRobots, 'nofollow') &&\n !xRobotsNofollow) {\n issues.push(issue('nofollow', page, page.metaRobots, {\n metaRobots: page.metaRobots,\n }));\n }\n const canonicalized = page.canonical &&\n !sameUrl(page.canonical, page.finalUrl) &&\n (page.declaredIndexability === 'canonical-hint-other' ||\n (page.declaredIndexability === undefined &&\n /canonical/i.test(page.indexability ?? '')));\n if (canonicalized) {\n issues.push(issue('canonicalized_page', page, page.canonical, {\n canonical: page.canonical,\n finalUrl: page.finalUrl,\n indexability: page.indexability,\n }));\n }\n else if (page.canonical && !sameUrl(page.canonical, page.finalUrl)) {\n issues.push(issue('canonical_mismatch', page, page.canonical, {\n canonical: page.canonical,\n finalUrl: page.finalUrl,\n }));\n }\n const contentDuplicate = page.mainContentHash\n ? duplicateContent.get(page.mainContentHash)\n : undefined;\n if (contentDuplicate) {\n issues.push(issue('duplicate_content', page, 'Duplicate main content', {\n mainContentHash: page.mainContentHash,\n duplicateCount: contentDuplicate.count,\n sampleUrls: contentDuplicate.sampleUrls,\n }));\n }\n const coverage = queryCoverage(page);\n if (coverage && coverage.coverage < QUERY_COVERAGE_MIN) {\n issues.push(issue('query_coverage_missing', page, coverage.query, {\n query: coverage.query,\n impressions: page.topQuery?.impressions,\n matchedTerms: coverage.matchedTerms,\n missingTerms: coverage.missingTerms,\n coverage: coverage.coverage,\n threshold: QUERY_COVERAGE_MIN,\n }));\n }\n if ((page.imagesMissingAlt ?? 0) > 0) {\n issues.push(issue('image_missing_alt', page, `${page.imagesMissingAlt} of ${page.imagesTotal ?? 0} images`, {\n imagesTotal: page.imagesTotal,\n imagesMissingAlt: page.imagesMissingAlt,\n }));\n }\n if (page.oversizedImageCandidates?.length) {\n issues.push(issue('image_oversized_candidate', page, `${page.oversizedImageCandidates.length} image candidate${page.oversizedImageCandidates.length === 1 ? '' : 's'}`, {\n thresholdPx: OVERSIZED_IMAGE_CANDIDATE_LIMIT,\n candidates: page.oversizedImageCandidates.slice(0, 10),\n }));\n }\n if (!page.hasViewport) {\n issues.push(issue('viewport_missing', page));\n }\n if (!page.lang) {\n issues.push(issue('lang_missing', page));\n }\n const hreflang = page.hreflang ?? [];\n if (hreflang.length) {\n const malformed = hreflang.filter((item) => !hasRecognizableHreflangFormat(item.hreflang));\n if (malformed.length) {\n issues.push(issue('hreflang_invalid', page, `${malformed.length} malformed`, {\n malformed,\n }));\n }\n const duplicateCodes = [\n ...new Set(hreflang\n .map((item) => item.hreflang.trim().toLowerCase())\n .filter((code, index, values) => values.indexOf(code) !== index)),\n ];\n if (duplicateCodes.length) {\n issues.push(issue('hreflang_duplicate', page, duplicateCodes.join(', '), {\n duplicateCodes,\n }));\n }\n const hasSelfReference = hreflang.some((item) => sameUrl(item.href, page.finalUrl));\n if (!hasSelfReference) {\n issues.push(issue('hreflang_incomplete', page, page.lang, {\n lang: page.lang,\n finalUrl: page.finalUrl,\n hreflang,\n }));\n }\n }\n if ((page.invalidJsonLdCount ?? 0) > 0) {\n issues.push(issue('jsonld_invalid', page, `${page.invalidJsonLdCount} invalid`, {\n invalidJsonLdCount: page.invalidJsonLdCount,\n invalidJsonLdSamples: page.invalidJsonLdSamples,\n }));\n }\n const incompleteRichResults = (page.googleRichResults ?? []).filter((assessment) => assessment.status === 'missing-required-properties');\n const selectedIncompleteCount = page.googleRichResultsSelection?.eligibleByStatus['missing-required-properties'] ?? 0;\n const incompleteRichResultCount = Math.max(incompleteRichResults.length, selectedIncompleteCount);\n if (incompleteRichResultCount) {\n const details = incompleteRichResults.map((assessment) => `${assessment.schemaType}: ${assessment.missingRequiredProperties.join(', ')}`);\n const omittedDetails = incompleteRichResultCount - details.length;\n issues.push(issue('rich_result_required_fields_missing', page, [\n ...details,\n ...(omittedDetails > 0\n ? [\n `${omittedDetails} more incomplete assessment${omittedDetails === 1 ? '' : 's'} omitted from bounded detail`,\n ]\n : []),\n ].join('; '), {\n assessments: incompleteRichResults,\n ...(page.googleRichResultsSelection\n ? { selection: page.googleRichResultsSelection }\n : {}),\n }));\n }\n if (!page.openGraphTitle) {\n issues.push(issue('og_title_missing', page));\n }\n if (!page.openGraphDescription) {\n issues.push(issue('og_description_missing', page));\n }\n if (!page.openGraphImage) {\n issues.push(issue('og_image_missing', page));\n }\n if (!page.twitterCard) {\n issues.push(issue('twitter_card_missing', page));\n }\n }\n return issues;\n}\n//# sourceMappingURL=audit.js.map","import { createHash, randomUUID } from 'node:crypto';\nimport { normalizeJavaScriptRenderingMode, } from '../../fetch/page-fetcher.js';\nimport { auditCrawlPages, auditCrawlRequests } from './audit.js';\nconst SENSITIVE_FIELD_NAMES = new Set([\n 'authorization',\n 'cookie',\n 'proxy-authorization',\n 'set-cookie',\n 'www-authenticate',\n 'x-api-key',\n 'api-key',\n 'access-token',\n 'refresh-token',\n]);\nconst SENSITIVE_PARAM_PATTERN = /^(access_?token|auth|api_?key|client_?secret|code|jwt|key|password|refresh_?token|secret|session|sig|signature|token)$/i;\nfunction uniqueSorted(values = []) {\n return [...new Set(values.filter(Boolean))].sort();\n}\nfunction normalizeFetchRate(input) {\n return {\n concurrency: input.fetchRate?.concurrency ?? input.concurrency ?? 8,\n ...(input.fetchRate?.intervalCap !== undefined\n ? { intervalCap: input.fetchRate.intervalCap }\n : {}),\n ...(input.fetchRate?.intervalMs !== undefined\n ? { intervalMs: input.fetchRate.intervalMs }\n : {}),\n ...(input.fetchRate?.backpressure\n ? { backpressure: input.fetchRate.backpressure }\n : {}),\n };\n}\nexport function normalizeCrawlConfig(input) {\n return {\n url: new URL(input.url).toString(),\n mode: input.mode ?? 'site',\n urls: uniqueSorted(input.urls ?? []),\n maxPages: input.maxPages ?? 500,\n maxDepth: input.maxDepth ?? 16,\n concurrency: input.concurrency ?? 8,\n timeoutMs: input.timeoutMs ?? 20_000,\n include: uniqueSorted(input.include ?? []),\n exclude: uniqueSorted(input.exclude ?? []),\n respectRobots: input.respectRobots ?? true,\n useSitemap: input.useSitemap ?? true,\n checkExternal: input.checkExternal ?? true,\n js: normalizeJavaScriptRenderingMode(input.js),\n refresh: input.refresh ?? false,\n fetchRate: normalizeFetchRate(input),\n };\n}\nexport function crawlConfigHash(config) {\n const normalized = normalizeCrawlConfig(config);\n return createHash('sha256')\n .update(JSON.stringify(normalized))\n .digest('hex')\n .slice(0, 16);\n}\nexport function crawlDefinitionId(input) {\n const normalized = {\n config: normalizeCrawlConfig(input.config),\n site: input.site ?? null,\n ga4PropertyId: input.ga4PropertyId ?? null,\n };\n const hash = createHash('sha256')\n .update(JSON.stringify(normalized))\n .digest('hex')\n .slice(0, 20);\n return `crawl_def_${hash}`;\n}\nexport function crawlRunId() {\n return `crawl_${randomUUID().replaceAll('-', '')}`;\n}\nexport function groupCrawlIssues(issues) {\n const groups = new Map();\n for (const issue of issues) {\n const existing = groups.get(issue.ruleId) ?? {\n ruleId: issue.ruleId,\n title: issue.title,\n category: issue.category,\n severity: issue.severity,\n count: 0,\n sampleUrls: [],\n };\n existing.count += 1;\n if (existing.sampleUrls.length < 10) {\n existing.sampleUrls.push(issue.url);\n }\n groups.set(issue.ruleId, existing);\n }\n const severityRank = {\n high: 3,\n medium: 2,\n low: 1,\n };\n return [...groups.values()].sort((a, b) => severityRank[b.severity] - severityRank[a.severity] || b.count - a.count);\n}\nfunction isSensitiveFieldName(key) {\n const lower = key.toLowerCase();\n return (SENSITIVE_FIELD_NAMES.has(lower) ||\n SENSITIVE_PARAM_PATTERN.test(lower.replace(/-/g, '_')));\n}\nfunction sanitizeUrlString(value) {\n try {\n const url = new URL(value);\n for (const key of [...url.searchParams.keys()]) {\n if (SENSITIVE_PARAM_PATTERN.test(key)) {\n url.searchParams.set(key, '[redacted]');\n }\n }\n return url.toString();\n }\n catch {\n return value;\n }\n}\nfunction sanitizeTenantString(value) {\n return value\n .replace(/https?:\\/\\/[^\\s\"'<>`]+/g, (match) => sanitizeUrlString(match))\n .replace(/\\b(access_?token|api_?key|auth|client_?secret|jwt|password|refresh_?token|secret|session|signature|token)(\\s*[=:]\\s*)[^\\s,;&]+/gi, (_match, key, separator) => `${key}${separator}[redacted]`)\n .replace(/\\b[A-Za-z]:\\\\[^\\s\"'<>`]+/g, '[local-path]')\n .replace(/\\/(?:Users|home|tmp|var\\/folders)\\/[^\\s\"'<>`]+/g, '[local-path]');\n}\nfunction sanitizeTenantValue(value, key) {\n if (key && isSensitiveFieldName(key))\n return '[redacted]';\n if (typeof value === 'string')\n return sanitizeTenantString(value);\n if (Array.isArray(value))\n return value.map((item) => sanitizeTenantValue(item));\n if (!value || typeof value !== 'object')\n return value;\n return Object.fromEntries(Object.entries(value).map(([entryKey, entry]) => [entryKey, sanitizeTenantValue(entry, entryKey)]));\n}\nfunction sanitizeCrawlConfig(config) {\n return sanitizeTenantValue(config);\n}\nfunction sanitizePages(pages) {\n return sanitizeTenantValue(pages).map(({ seoScore: _seoScore, geoScore: _geoScore, ...page }) => page);\n}\nfunction sanitizeIssues(issues) {\n return sanitizeTenantValue(issues);\n}\nfunction sanitizeMessages(values = []) {\n return values.map((value) => sanitizeTenantString(value));\n}\nfunction compareText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\nfunction sortPages(pages) {\n return [...pages].sort((left, right) => compareText(left.url, right.url));\n}\nfunction sortRequests(requests) {\n return [...requests].sort((left, right) => {\n const byUrl = compareText(left.requestedUrl, right.requestedUrl);\n if (byUrl)\n return byUrl;\n const byOutcome = compareText(left.outcome, right.outcome);\n if (byOutcome)\n return byOutcome;\n const leftDetail = left.outcome === 'response'\n ? `${left.status}:${left.finalUrl}`\n : left.outcome === 'skipped'\n ? left.reason\n : `${left.failureKind}:${left.error}`;\n const rightDetail = right.outcome === 'response'\n ? `${right.status}:${right.finalUrl}`\n : right.outcome === 'skipped'\n ? right.reason\n : `${right.failureKind}:${right.error}`;\n return compareText(leftDetail, rightDetail);\n });\n}\nexport function summarizeCrawlReport(input) {\n const byStatus = {};\n const requestByStatus = {};\n const byCategory = {};\n let responseMs = 0;\n let responseCount = 0;\n for (const page of input.pages) {\n byStatus[String(page.status)] = (byStatus[String(page.status)] ?? 0) + 1;\n if (typeof page.responseTimeMs === 'number') {\n responseMs += page.responseTimeMs;\n responseCount += 1;\n }\n }\n const requests = input.requests ?? [];\n const failedRequests = requests.filter((request) => request.outcome === 'failure' && request.failureKind !== 'aborted');\n const abortedRequests = requests.filter((request) => request.outcome === 'failure' && request.failureKind === 'aborted');\n let requestMs = 0;\n let requestMsCount = 0;\n for (const request of requests) {\n const status = request.outcome === 'response'\n ? String(request.status)\n : request.outcome === 'skipped'\n ? request.reason\n : request.failureKind === 'aborted'\n ? 'aborted'\n : 'no-response';\n requestByStatus[status] = (requestByStatus[status] ?? 0) + 1;\n if (typeof request.durationMs === 'number') {\n requestMs += request.durationMs;\n requestMsCount += 1;\n }\n }\n for (const issue of input.issues) {\n byCategory[issue.category] = (byCategory[issue.category] ?? 0) + 1;\n }\n return {\n totalPages: input.pages.length,\n indexablePages: input.pages.filter((page) => page.indexable).length,\n nonIndexablePages: input.pages.filter((page) => !page.indexable).length,\n statusErrors: input.pages.filter((page) => page.status === 0 || page.status >= 400).length,\n ...crawlRunStats(input.pages, input.stats),\n attemptedRequests: input.requestEvidenceStatus === 'unavailable' ? 0 : requests.length,\n responseRequests: requests.filter((request) => request.outcome === 'response').length,\n failedRequests: failedRequests.length,\n abortedRequests: abortedRequests.length,\n extractionFailures: requests.filter((request) => request.outcome === 'response' && request.extraction === 'failed').length,\n requestByStatus,\n avgRequestMs: requestMsCount\n ? Math.round(requestMs / requestMsCount)\n : undefined,\n highIssues: input.issues.filter((issue) => issue.severity === 'high')\n .length,\n mediumIssues: input.issues.filter((issue) => issue.severity === 'medium')\n .length,\n lowIssues: input.issues.filter((issue) => issue.severity === 'low').length,\n avgResponseMs: responseCount\n ? Math.round(responseMs / responseCount)\n : undefined,\n byStatus,\n byCategory,\n };\n}\nfunction crawlRunStats(pages, stats = {}) {\n const discovered = new Set();\n let observedInternalLinks = 0;\n for (const page of pages) {\n discovered.add(page.url);\n for (const url of page.sampleInternalLinks ?? [])\n discovered.add(url);\n for (const url of page.sampleExternalLinks ?? [])\n discovered.add(url);\n observedInternalLinks += page.outgoingInternalCount;\n }\n return {\n discoveredUrls: stats.discoveredUrls ?? discovered.size,\n queuedUrls: stats.queuedUrls ?? pages.length,\n crawledUrls: stats.crawledUrls ?? pages.length,\n skippedUrls: stats.skippedUrls ?? 0,\n failedUrls: stats.failedUrls ??\n pages.filter((page) => page.status === 0 || page.status >= 400).length,\n observedInternalLinks: stats.observedInternalLinks ?? observedInternalLinks,\n pageLimitReached: stats.pageLimitReached ?? false,\n };\n}\nfunction normalizeLinkUrl(value) {\n try {\n const url = new URL(value);\n url.hash = '';\n return url.toString();\n }\n catch {\n return undefined;\n }\n}\nfunction deriveInternalLinkAuthority(pages, linkGraph) {\n const hasLinkGraph = linkGraph && Object.keys(linkGraph).length > 0;\n const hasStoredScores = pages.some((page) => page.internalInlinkCount !== undefined ||\n page.internalLinkAuthorityScore !== undefined);\n if (!hasLinkGraph && hasStoredScores) {\n return pages.map((page) => ({\n ...page,\n internalInlinkCount: page.internalInlinkCount ?? 0,\n internalLinkAuthorityScore: page.internalLinkAuthorityScore ?? 0,\n }));\n }\n const pageByUrl = new Map();\n for (const page of pages) {\n for (const value of [page.url, page.finalUrl]) {\n const normalized = normalizeLinkUrl(value);\n if (normalized)\n pageByUrl.set(normalized, page.url);\n }\n }\n const inlinks = new Map();\n for (const page of pages)\n inlinks.set(page.url, 0);\n for (const page of pages) {\n const targets = hasLinkGraph\n ? (linkGraph?.[page.url] ?? linkGraph?.[page.finalUrl] ?? [])\n : (page.sampleInternalLinks ?? []);\n const linkedPages = new Set();\n for (const target of targets) {\n const normalized = normalizeLinkUrl(target);\n const linkedPage = normalized ? pageByUrl.get(normalized) : undefined;\n if (!linkedPage || linkedPage === page.url)\n continue;\n linkedPages.add(linkedPage);\n }\n for (const linkedPage of linkedPages) {\n inlinks.set(linkedPage, (inlinks.get(linkedPage) ?? 0) + 1);\n }\n }\n const maxInlinks = Math.max(0, ...inlinks.values());\n return pages.map((page) => {\n const internalInlinkCount = inlinks.get(page.url) ?? 0;\n return {\n ...page,\n internalInlinkCount,\n internalLinkAuthorityScore: maxInlinks\n ? Math.round((internalInlinkCount / maxInlinks) * 100)\n : 0,\n };\n });\n}\nexport function createCrawlReport(input) {\n const config = sanitizeCrawlConfig(normalizeCrawlConfig(input.config));\n const definitionId = crawlDefinitionId({\n config,\n site: input.site,\n ga4PropertyId: input.ga4PropertyId,\n });\n const pagesWithLinks = deriveInternalLinkAuthority(input.pages ?? [], input.linkGraph);\n const safePagesWithLinks = sortPages(sanitizePages(pagesWithLinks));\n const requests = sortRequests(sanitizeTenantValue(input.requests ?? []));\n const requestEvidenceStatus = input.requestEvidenceStatus ??\n (input.requests ? 'available' : 'unavailable');\n if (requestEvidenceStatus === 'unavailable' && requests.length > 0) {\n throw new Error('Unavailable request evidence cannot include request observations.');\n }\n const issues = input.issues ?? [\n ...auditCrawlRequests(requests),\n ...auditCrawlPages(safePagesWithLinks, { startUrl: config.url }),\n ];\n const safeIssues = sanitizeIssues(issues);\n const pages = safePagesWithLinks;\n return {\n id: input.id ?? crawlRunId(),\n definitionId,\n projectId: input.projectId,\n site: input.site,\n ga4PropertyId: input.ga4PropertyId,\n generatedAt: input.generatedAt ?? new Date().toISOString(),\n status: input.status ?? 'completed',\n configHash: crawlConfigHash(config),\n config,\n summary: summarizeCrawlReport({\n pages,\n requests,\n requestEvidenceStatus,\n issues: safeIssues,\n stats: input.stats,\n }),\n requestEvidenceStatus,\n requests,\n pages,\n issues: safeIssues,\n issueGroups: groupCrawlIssues(safeIssues),\n ...(input.dataSources\n ? {\n dataSources: sanitizeTenantValue(input.dataSources),\n }\n : {}),\n ...(input.ai\n ? { ai: sanitizeTenantValue(input.ai) }\n : {}),\n ...(input.sitemapDiscovery\n ? {\n sitemapDiscovery: sanitizeTenantValue(input.sitemapDiscovery),\n }\n : {}),\n ...(input.externalLinkVerification\n ? {\n externalLinkVerification: sanitizeTenantValue(input.externalLinkVerification),\n }\n : {}),\n warnings: sanitizeMessages(input.warnings).sort(compareText),\n caveats: sanitizeMessages(input.caveats).sort(compareText),\n };\n}\nexport function normalizeLoadedCrawlReport(report) {\n const requestEvidenceStatus = report.requestEvidenceStatus ??\n (Object.hasOwn(report, 'requests') ? 'available' : 'unavailable');\n const issues = sanitizeIssues(report.issues ?? []);\n const requests = sortRequests((sanitizeTenantValue(report.requests ?? []) ??\n []));\n const pages = sortPages(sanitizePages(deriveInternalLinkAuthority(report.pages ?? [])));\n return {\n ...sanitizeTenantValue(report),\n requestEvidenceStatus,\n requests,\n definitionId: report.definitionId ??\n crawlDefinitionId({\n config: report.config,\n site: report.site,\n ga4PropertyId: report.ga4PropertyId,\n }),\n summary: summarizeCrawlReport({\n pages,\n requests,\n requestEvidenceStatus,\n issues,\n stats: report.summary,\n }),\n pages,\n issues,\n issueGroups: groupCrawlIssues(issues),\n warnings: sanitizeMessages(report.warnings).sort(compareText),\n caveats: sanitizeMessages(report.caveats).sort(compareText),\n };\n}\n//# sourceMappingURL=report.js.map","import { getDb } from '../../storage/database.js';\nimport { normalizeLoadedCrawlReport } from './report.js';\nexport const CRAWL_REPORT_STORAGE_VERSION = 5;\nfunction toMeta(row) {\n return {\n id: row.id,\n configHash: row.config_hash,\n site: row.site_url ?? undefined,\n url: row.url,\n status: row.status,\n totalPages: row.total_pages,\n issueCount: row.issue_count,\n createdAt: new Date(row.created_at).toISOString(),\n storageVersion: storageVersionFromJson(row.report_json),\n };\n}\nfunction storageEnvelope(report) {\n const tenant = {};\n if (report.projectId)\n tenant.projectId = report.projectId;\n if (report.site)\n tenant.site = report.site;\n return {\n kind: 'seo.crawl_report',\n version: CRAWL_REPORT_STORAGE_VERSION,\n savedAt: new Date().toISOString(),\n ...(tenant.projectId || tenant.site ? { tenant } : {}),\n report,\n };\n}\nfunction storageVersionFromJson(value) {\n try {\n const parsed = JSON.parse(value);\n return parsed.kind === 'seo.crawl_report' &&\n typeof parsed.version === 'number'\n ? parsed.version\n : 0;\n }\n catch {\n return 0;\n }\n}\nfunction reportFromJson(value) {\n const parsed = JSON.parse(value);\n if (parsed &&\n typeof parsed === 'object' &&\n 'kind' in parsed &&\n parsed.kind === 'seo.crawl_report' &&\n 'report' in parsed) {\n return normalizeLoadedCrawlReport(parsed.report);\n }\n return normalizeLoadedCrawlReport(parsed);\n}\nfunction saveCrawlReportToSqlite(report) {\n const result = getDb()\n .prepare(`INSERT INTO crawl_reports\n (id, config_hash, site_url, url, status, total_pages, issue_count, created_at, report_json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO NOTHING`)\n .run(report.id, report.configHash, report.site ?? null, report.config.url, report.status, report.summary.totalPages, report.issues.length, Date.parse(report.generatedAt), JSON.stringify(storageEnvelope(report)));\n if (result.changes === 0) {\n const existing = getDb()\n .prepare('SELECT * FROM crawl_reports WHERE id = ?')\n .get(report.id);\n if (existing)\n return toMeta(existing);\n }\n return {\n id: report.id,\n configHash: report.configHash,\n site: report.site,\n url: report.config.url,\n status: report.status,\n totalPages: report.summary.totalPages,\n issueCount: report.issues.length,\n createdAt: report.generatedAt,\n storageVersion: CRAWL_REPORT_STORAGE_VERSION,\n };\n}\nfunction listCrawlReportsFromSqlite(input = {}) {\n const limit = input.limit ?? 20;\n const rows = input.site\n ? getDb()\n .prepare(`SELECT * FROM crawl_reports\n WHERE site_url = ?\n ORDER BY created_at DESC, id DESC\n LIMIT ?`)\n .all(input.site, limit)\n : getDb()\n .prepare(`SELECT * FROM crawl_reports\n ORDER BY created_at DESC, id DESC\n LIMIT ?`)\n .all(limit);\n return rows.map(toMeta);\n}\nfunction loadCrawlReportFromSqlite(id) {\n const row = getDb()\n .prepare('SELECT report_json FROM crawl_reports WHERE id = ?')\n .get(id);\n if (!row)\n return undefined;\n return reportFromJson(row.report_json);\n}\nfunction deleteCrawlReportFromSqlite(id) {\n const result = getDb()\n .prepare('DELETE FROM crawl_reports WHERE id = ?')\n .run(id);\n return result.changes > 0;\n}\nfunction latestCrawlReportFromSqlite(site) {\n const row = site\n ? getDb()\n .prepare(`SELECT report_json FROM crawl_reports\n WHERE site_url = ?\n ORDER BY created_at DESC, id DESC\n LIMIT 1`)\n .get(site)\n : getDb()\n .prepare(`SELECT report_json FROM crawl_reports\n ORDER BY created_at DESC, id DESC\n LIMIT 1`)\n .get();\n if (!row)\n return undefined;\n return reportFromJson(row.report_json);\n}\nexport const sqliteCrawlReportStore = {\n save: saveCrawlReportToSqlite,\n list: listCrawlReportsFromSqlite,\n load: loadCrawlReportFromSqlite,\n delete: deleteCrawlReportFromSqlite,\n latest: latestCrawlReportFromSqlite,\n};\nexport const crawlReportStore = sqliteCrawlReportStore;\nexport function saveCrawlReport(report, store = crawlReportStore) {\n return store.save(report);\n}\nexport function listCrawlReports(input = {}, store = crawlReportStore) {\n return store.list(input);\n}\nexport function loadCrawlReport(id, store = crawlReportStore) {\n return store.load(id);\n}\nexport function deleteCrawlReport(id, store = crawlReportStore) {\n return store.delete(id);\n}\nexport function latestCrawlReport(site, store = crawlReportStore) {\n return store.latest(site);\n}\n//# sourceMappingURL=report-store.js.map","export function crawlCaveats(input) {\n const caveats = input.cancelled\n ? ['Crawl cancelled before all queued URLs finished.']\n : input.pageLimitReached\n ? [`Stopped after reaching maxPages (${input.maxPages}).`]\n : [];\n if (input.queueSafetySkippedUrls > 0) {\n caveats.push(`Left ${input.queueSafetySkippedUrls} eligible same-origin URLs unqueued to keep this crawl bounded. Increase --max-pages to inspect more.`);\n }\n if (input.originBackpressureSkippedUrls > 0) {\n caveats.push(`Stopped ${input.originBackpressureSkippedUrls} queued URL${input.originBackpressureSkippedUrls === 1 ? '' : 's'} because the origin stayed slow. This is incomplete crawl evidence, not a failed URL check.`);\n }\n return caveats;\n}\n//# sourceMappingURL=crawl-caveats.js.map","export const CRAWL_CANCELLED = Symbol('crawl-cancelled');\nexport function abortController(input) {\n const controller = new AbortController();\n const abort = () => controller.abort();\n const timer = setTimeout(abort, Math.min(input.timeoutMs, 5_000));\n if (input.signal?.aborted) {\n controller.abort();\n }\n else {\n input.signal?.addEventListener('abort', abort, { once: true });\n }\n return {\n signal: controller.signal,\n cleanup: () => {\n clearTimeout(timer);\n input.signal?.removeEventListener('abort', abort);\n },\n };\n}\nexport function cancellationRace(signal) {\n if (signal.aborted)\n return Promise.resolve(CRAWL_CANCELLED);\n return new Promise((resolve) => {\n signal.addEventListener('abort', () => resolve(CRAWL_CANCELLED), {\n once: true,\n });\n });\n}\n//# sourceMappingURL=crawl-control.js.map","import { abortController } from './crawl-control.js';\nconst EXTERNAL_LINK_SELECTION_LIMIT = 200;\nfunction stableHash(value) {\n let hash = 2_166_136_261;\n for (const character of value) {\n hash = Math.imul(hash ^ (character.codePointAt(0) ?? 0), 16_777_619);\n }\n return hash >>> 0;\n}\nfunction compareStable(left, right) {\n const leftHash = stableHash(left);\n const rightHash = stableHash(right);\n if (leftHash !== rightHash)\n return leftHash - rightHash;\n return left < right ? -1 : left > right ? 1 : 0;\n}\nfunction collectCandidates(pages) {\n const sourcesByUrl = new Map();\n let discoveredLinkOccurrences = 0;\n let retainedLinkOccurrences = 0;\n for (const page of pages) {\n const retained = [...new Set(page.sampleExternalLinks ?? [])];\n discoveredLinkOccurrences += page.outgoingExternalCount ?? retained.length;\n retainedLinkOccurrences += retained.length;\n for (const url of retained) {\n let sourcePages = sourcesByUrl.get(url);\n if (!sourcePages) {\n sourcePages = new Set();\n sourcesByUrl.set(url, sourcePages);\n }\n sourcePages.add(page.url);\n }\n }\n return {\n candidates: [...sourcesByUrl]\n .map(([url, sourcePages]) => ({\n url,\n sourcePages: [...sourcePages].sort(),\n }))\n .sort((left, right) => compareStable(left.url, right.url)),\n discoveredLinkOccurrences,\n retainedLinkOccurrences,\n };\n}\nfunction selectCandidateUrls(candidates, limit) {\n const urlsBySource = new Map();\n for (const candidate of candidates) {\n for (const sourcePage of candidate.sourcePages) {\n const urls = urlsBySource.get(sourcePage) ?? [];\n urls.push(candidate.url);\n urlsBySource.set(sourcePage, urls);\n }\n }\n for (const urls of urlsBySource.values())\n urls.sort(compareStable);\n const sourcePages = [...urlsBySource.keys()].sort(compareStable);\n const cursors = new Map(sourcePages.map((sourcePage) => [sourcePage, 0]));\n const selected = new Set();\n while (selected.size < limit) {\n let selectedThisRound = false;\n for (const sourcePage of sourcePages) {\n const urls = urlsBySource.get(sourcePage) ?? [];\n let cursor = cursors.get(sourcePage) ?? 0;\n while (cursor < urls.length) {\n const candidate = urls[cursor];\n if (!candidate || !selected.has(candidate))\n break;\n cursor += 1;\n }\n cursors.set(sourcePage, cursor + 1);\n const url = urls[cursor];\n if (!url)\n continue;\n selected.add(url);\n selectedThisRound = true;\n if (selected.size === limit)\n break;\n }\n if (!selectedThisRound)\n break;\n }\n return [...selected];\n}\nasync function checkExternalLink(url, timeoutMs, fetch, signal) {\n const controller = abortController({ timeoutMs, signal });\n try {\n const response = await fetch(url, {\n method: 'HEAD',\n redirect: 'follow',\n signal: controller.signal,\n });\n await response.body?.cancel().catch(() => undefined);\n return { url, status: response.status };\n }\n catch (error) {\n return {\n url,\n status: 0,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n finally {\n controller.cleanup();\n }\n}\nexport async function verifyExternalLinks(input) {\n const { candidates, discoveredLinkOccurrences, retainedLinkOccurrences } = collectCandidates(input.pages);\n const urls = input.signal?.aborted\n ? []\n : selectCandidateUrls(candidates, EXTERNAL_LINK_SELECTION_LIMIT);\n const checks = new Map();\n for (let index = 0; index < urls.length; index += 8) {\n if (input.signal?.aborted)\n break;\n const batch = urls.slice(index, index + 8);\n const results = await Promise.all(batch.map((url) => checkExternalLink(url, input.timeoutMs, input.fetch, input.signal)));\n for (const result of results)\n checks.set(result.url, result);\n }\n for (const page of input.pages) {\n const pageChecks = (page.sampleExternalLinks ?? [])\n .map((url) => checks.get(url))\n .filter((value) => Boolean(value));\n if (pageChecks.length)\n page.externalLinkChecks = pageChecks;\n }\n const fetchedUrls = [...checks.values()].filter((check) => typeof check.status === 'number' && check.status > 0).length;\n const failedUrls = checks.size - fetchedUrls;\n const deferredUrls = candidates.length - checks.size;\n const warnings = [];\n if (discoveredLinkOccurrences > retainedLinkOccurrences) {\n warnings.push(`Retained ${retainedLinkOccurrences} sampled external link occurrence${retainedLinkOccurrences === 1 ? '' : 's'} from ${discoveredLinkOccurrences} observed occurrence${discoveredLinkOccurrences === 1 ? '' : 's'}.`);\n }\n if (candidates.length > urls.length) {\n warnings.push(`Selected ${urls.length} of ${candidates.length} retained external URLs using the ${EXTERNAL_LINK_SELECTION_LIMIT}-URL verification limit.`);\n }\n if (checks.size < urls.length) {\n warnings.push(`Stopped before checking ${urls.length - checks.size} selected external URL${urls.length - checks.size === 1 ? '' : 's'}.`);\n }\n if (failedUrls) {\n warnings.push(`${failedUrls} external URL request${failedUrls === 1 ? '' : 's'} failed before a response was received.`);\n }\n return {\n dataStatus: discoveredLinkOccurrences > retainedLinkOccurrences ||\n deferredUrls > 0 ||\n failedUrls > 0\n ? 'partial'\n : 'complete',\n discoveredLinkOccurrences,\n retainedUrls: candidates.length,\n selectedUrls: urls.length,\n fetchedUrls,\n failedUrls,\n deferredUrls,\n limit: EXTERNAL_LINK_SELECTION_LIMIT,\n warnings,\n };\n}\n//# sourceMappingURL=external-link-checks.js.map","function resolveFetchedAlias(url, aliases) {\n const visited = new Set();\n let current = url;\n while (!visited.has(current)) {\n visited.add(current);\n const next = aliases.get(current);\n if (!next)\n return current;\n current = next;\n }\n return current;\n}\nexport function resolveLinkGraphAliases(linkGraph, aliases) {\n const resolved = {};\n for (const [source, targets] of Object.entries(linkGraph)) {\n const resolvedSource = resolveFetchedAlias(source, aliases);\n let resolvedTargets = resolved[resolvedSource];\n if (!resolvedTargets) {\n resolvedTargets = new Set();\n resolved[resolvedSource] = resolvedTargets;\n }\n for (const target of targets) {\n resolvedTargets.add(resolveFetchedAlias(target, aliases));\n }\n }\n return Object.fromEntries(Object.entries(resolved).map(([source, targets]) => [\n source,\n [...targets].sort((left, right) => left < right ? -1 : left > right ? 1 : 0),\n ]));\n}\n//# sourceMappingURL=link-graph.js.map","export function observationFromPage(requestedUrl, page) {\n const observation = {\n requestedUrl,\n outcome: 'response',\n finalUrl: page.finalUrl,\n status: page.status,\n contentType: page.contentType,\n durationMs: page.responseTimeMs,\n redirectChain: page.fetchDiagnostics?.redirectChain,\n };\n if (page.extractionStatus === 'failed') {\n return {\n ...observation,\n extraction: 'failed',\n extractionError: page.extractionError ??\n 'Content extraction failed without a recorded error.',\n };\n }\n return {\n ...observation,\n extraction: page.extractionStatus ?? 'complete',\n };\n}\n//# sourceMappingURL=request-evidence.js.map","import { defaultDateRange } from '../site-diagnostics/quick-wins-report-input.js';\nexport function crawlMetricsWindow(now) {\n return { ...defaultDateRange(28, now), days: 28 };\n}\nexport async function joinAnalytics(input) {\n let analytics;\n try {\n analytics = await input.fetchLandingPageValues({\n propertyId: input.propertyId,\n startDate: input.window.startDate,\n endDate: input.window.endDate,\n limit: input.limit,\n });\n }\n catch (error) {\n const warning = `GA4 metrics unavailable: ${error instanceof Error ? error.message : String(error)}`;\n input.warnings.push(warning);\n return {\n status: 'unavailable',\n window: input.window,\n totalPages: input.pages.length,\n queriedPages: input.pages.length,\n joinedPages: 0,\n retainedRowLimit: input.limit,\n warning,\n };\n }\n if (analytics.warning) {\n const warning = `GA4 metrics unavailable: ${analytics.warning}`;\n input.warnings.push(warning);\n return {\n status: 'unavailable',\n window: input.window,\n totalPages: input.pages.length,\n queriedPages: input.pages.length,\n joinedPages: 0,\n returnedRows: analytics.source?.returnedRows,\n availableRows: analytics.source?.availableRows,\n retainedRowLimit: analytics.source?.retainedRowLimit ?? input.limit,\n ...(analytics.source\n ? {\n retainedRowLimitReached: analytics.source.retainedRowLimitReached,\n }\n : {}),\n warning,\n };\n }\n let joinedPages = 0;\n for (const page of input.pages) {\n const value = input.landingValueForUrl(analytics.values, page.finalUrl);\n if (!value)\n continue;\n page.analytics = value;\n joinedPages += 1;\n }\n const sourceQualityKnown = analytics.source?.dataStatus !== undefined;\n const retainedRowLimitReached = analytics.source?.retainedRowLimitReached;\n const qualityWarnings = analytics.source?.qualityWarnings ?? [];\n const warning = !sourceQualityKnown\n ? `GA4 metrics joined for ${joinedPages} of ${input.pages.length} crawled pages, but the provider did not expose row completeness; missing page metrics are not reliable zero-traffic evidence.`\n : retainedRowLimitReached\n ? `GA4 retained-row limit reached; missing page metrics are not reliable zero-traffic evidence.`\n : qualityWarnings.length\n ? `${qualityWarnings.join(' ')} Missing page metrics and relative analytics value are partial evidence.`\n : input.pages.length && joinedPages === 0\n ? 'GA4 metrics joined for 0 crawled pages.'\n : undefined;\n if (warning)\n input.warnings.push(warning);\n return {\n status: !sourceQualityKnown || analytics.source?.dataStatus === 'partial'\n ? 'partial'\n : joinedPages\n ? 'joined'\n : 'none',\n window: input.window,\n totalPages: input.pages.length,\n queriedPages: input.pages.length,\n joinedPages,\n returnedRows: analytics.source?.returnedRows,\n availableRows: analytics.source?.availableRows,\n retainedRowLimit: analytics.source?.retainedRowLimit ?? input.limit,\n ...(retainedRowLimitReached !== undefined\n ? { retainedRowLimitReached }\n : {}),\n ...(warning ? { warning } : {}),\n };\n}\nexport async function joinSearchMetrics(input) {\n const pages = [...input.pages]\n .sort((left, right) => left.finalUrl < right.finalUrl\n ? -1\n : left.finalUrl > right.finalUrl\n ? 1\n : left.url < right.url\n ? -1\n : left.url > right.url\n ? 1\n : 0)\n .slice(0, input.limit);\n const pageLimitReached = pages.length < input.pages.length;\n const range = {\n startDate: input.window.startDate,\n endDate: input.window.endDate,\n };\n let joinedMetricPages = 0;\n let joinedQueryPages = 0;\n let metricBatch;\n let queryBatch;\n const retentionUnknown = Boolean((input.queryPagesMetrics && !input.queryPagesMetricsBatch) ||\n (input.queryPagesTopQueries && !input.queryPagesTopQueriesBatch));\n const explicitWindow = Boolean(input.queryPagesMetricsBatch || input.queryPagesTopQueriesBatch);\n const hasBulkMetricsProvider = Boolean(input.queryPagesMetricsBatch || input.queryPagesMetrics);\n const hasBulkQueryProvider = Boolean(input.queryPagesTopQueriesBatch || input.queryPagesTopQueries);\n const bulkProviderIncomplete = (hasBulkMetricsProvider || hasBulkQueryProvider) &&\n hasBulkMetricsProvider !== hasBulkQueryProvider;\n const bulkErrors = [];\n try {\n if (input.queryPagesMetricsBatch ||\n input.queryPagesTopQueriesBatch ||\n input.queryPagesMetrics ||\n input.queryPagesTopQueries) {\n const pageUrls = pages.map((page) => page.finalUrl);\n try {\n metricBatch = input.queryPagesMetricsBatch\n ? await input.queryPagesMetricsBatch(input.site, pageUrls, range)\n : input.queryPagesMetrics\n ? {\n values: await input.queryPagesMetrics(input.site, pageUrls, input.window.days),\n }\n : undefined;\n }\n catch (error) {\n bulkErrors.push(`page metrics failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n try {\n queryBatch = input.queryPagesTopQueriesBatch\n ? await input.queryPagesTopQueriesBatch(input.site, pageUrls, range)\n : input.queryPagesTopQueries\n ? {\n values: await input.queryPagesTopQueries(input.site, pageUrls, input.window.days),\n }\n : undefined;\n }\n catch (error) {\n bulkErrors.push(`top queries failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n for (const page of pages) {\n const metrics = metricBatch?.values.get(page.finalUrl);\n if (metrics) {\n page.searchMetrics = metrics;\n joinedMetricPages += 1;\n }\n const topQuery = queryBatch?.values.get(page.finalUrl);\n if (topQuery) {\n page.topQuery = topQuery;\n joinedQueryPages += 1;\n }\n }\n }\n else {\n for (const page of pages) {\n const metrics = await input.queryPageMetrics(input.site, page.finalUrl, input.window.days);\n if (metrics) {\n page.searchMetrics = metrics;\n joinedMetricPages += 1;\n }\n const topQuery = await input.queryPageTopQuery(input.site, page.finalUrl, input.window.days);\n if (topQuery) {\n page.topQuery = topQuery;\n joinedQueryPages += 1;\n }\n }\n }\n }\n catch (error) {\n const warning = `GSC metrics unavailable: ${error instanceof Error ? error.message : String(error)}`;\n input.warnings.push(warning);\n return {\n status: joinedMetricPages || joinedQueryPages ? 'partial' : 'unavailable',\n ...(explicitWindow ? { window: input.window } : {}),\n totalPages: input.pages.length,\n queriedPages: pages.length,\n joinedMetricPages,\n joinedQueryPages,\n pageLimit: input.limit,\n pageLimitReached,\n metricRowsReturned: metricBatch?.returnedRows,\n queryRowsReturned: queryBatch?.returnedRows,\n retainedRowLimit: metricBatch?.retainedRowLimit ?? queryBatch?.retainedRowLimit,\n warning,\n };\n }\n if (bulkErrors.length > 0) {\n const warning = `GSC metrics partially unavailable: ${bulkErrors.join('; ')}`;\n input.warnings.push(warning);\n return {\n status: joinedMetricPages || joinedQueryPages ? 'partial' : 'unavailable',\n ...(explicitWindow ? { window: input.window } : {}),\n totalPages: input.pages.length,\n queriedPages: pages.length,\n joinedMetricPages,\n joinedQueryPages,\n pageLimit: input.limit,\n pageLimitReached,\n metricRowsReturned: metricBatch?.returnedRows,\n queryRowsReturned: queryBatch?.returnedRows,\n retainedRowLimit: metricBatch?.retainedRowLimit ?? queryBatch?.retainedRowLimit,\n warning,\n };\n }\n const retainedRowLimitReached = Boolean(metricBatch?.retainedRowLimitReached || queryBatch?.retainedRowLimitReached);\n const joinedPages = pages.filter((page) => page.searchMetrics || page.topQuery).length;\n const partial = pageLimitReached ||\n retainedRowLimitReached ||\n retentionUnknown ||\n bulkProviderIncomplete ||\n !explicitWindow;\n const warning = bulkProviderIncomplete\n ? 'GSC provider did not supply both page metrics and top-query evidence; missing evidence is not a reliable zero.'\n : retentionUnknown && !explicitWindow\n ? 'GSC legacy provider did not expose retained-row completeness or an exact date window; missing evidence is not a reliable zero.'\n : retentionUnknown\n ? 'GSC provider did not expose retained-row completeness; missing page metrics and queries are not reliable zero-visibility evidence.'\n : !explicitWindow\n ? `GSC metrics joined for ${joinedPages} of ${pages.length} crawled pages through a legacy relative-day provider; exact queried dates are not verifiable.`\n : retainedRowLimitReached\n ? 'GSC retained-row limit reached; missing page metrics and queries are not reliable zero-visibility evidence.'\n : pageLimitReached\n ? `GSC metrics queried for ${pages.length} of ${input.pages.length} crawled pages because the page limit was reached.`\n : joinedPages < pages.length\n ? `GSC metrics joined for ${joinedPages} of ${pages.length} crawled pages.`\n : undefined;\n if (warning)\n input.warnings.push(warning);\n return {\n status: partial\n ? 'partial'\n : joinedMetricPages || joinedQueryPages\n ? 'joined'\n : 'none',\n ...(explicitWindow ? { window: input.window } : {}),\n totalPages: input.pages.length,\n queriedPages: pages.length,\n joinedMetricPages,\n joinedQueryPages,\n pageLimit: input.limit,\n pageLimitReached,\n metricRowsReturned: metricBatch?.returnedRows,\n queryRowsReturned: queryBatch?.returnedRows,\n retainedRowLimit: metricBatch?.retainedRowLimit ?? queryBatch?.retainedRowLimit,\n ...(retentionUnknown ? {} : { retainedRowLimitReached }),\n ...(warning ? { warning } : {}),\n };\n}\n//# sourceMappingURL=site-crawl-providers.js.map","import { crawlMetricsWindow, joinAnalytics, joinSearchMetrics, } from './site-crawl-providers.js';\nexport function crawlProviderLimits(input) {\n const normalize = (value, fallback, label) => {\n const limit = value ?? fallback;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new Error(`${label} must be a positive whole number.`);\n }\n return limit;\n };\n return {\n searchMetricsLimit: normalize(input.searchMetricsLimit, 5000, 'searchMetricsLimit'),\n analyticsLimit: normalize(input.analyticsLimit, 5000, 'analyticsLimit'),\n };\n}\nexport async function crawlDataSources(input) {\n const window = crawlMetricsWindow(input.now());\n const dataSources = {\n searchConsole: {\n status: 'skipped',\n totalPages: input.pages.length,\n queriedPages: 0,\n joinedMetricPages: 0,\n joinedQueryPages: 0,\n pageLimit: input.searchMetricsLimit,\n pageLimitReached: false,\n retainedRowLimitReached: false,\n warning: input.cancelled\n ? 'Search Console join skipped because the crawl was cancelled.'\n : 'Search Console join skipped because no property was selected.',\n },\n analytics: {\n status: 'skipped',\n totalPages: input.pages.length,\n queriedPages: 0,\n joinedPages: 0,\n retainedRowLimit: input.analyticsLimit,\n retainedRowLimitReached: false,\n warning: input.cancelled\n ? 'GA4 join skipped because the crawl was cancelled.'\n : 'GA4 join skipped because no property was selected.',\n },\n };\n if (!input.cancelled && input.site) {\n dataSources.searchConsole = await joinSearchMetrics({\n site: input.site,\n pages: input.pages,\n warnings: input.warnings,\n limit: input.searchMetricsLimit,\n window,\n queryPageMetrics: input.queryPageMetrics,\n queryPageTopQuery: input.queryPageTopQuery,\n queryPagesMetrics: input.queryPagesMetrics,\n queryPagesTopQueries: input.queryPagesTopQueries,\n queryPagesMetricsBatch: input.queryPagesMetricsBatch,\n queryPagesTopQueriesBatch: input.queryPagesTopQueriesBatch,\n });\n }\n if (!input.cancelled && input.ga4PropertyId) {\n dataSources.analytics = await joinAnalytics({\n propertyId: input.ga4PropertyId,\n pages: input.pages,\n warnings: input.warnings,\n limit: input.analyticsLimit,\n window,\n fetchLandingPageValues: input.fetchLandingPageValues,\n landingValueForUrl: input.landingValueForUrl,\n });\n }\n return dataSources;\n}\n//# sourceMappingURL=site-crawl-data-sources.js.map","import { createHash } from 'node:crypto';\nimport { extractHttpCanonicalEvidence } from '../../extract/canonical.js';\nimport { selectGoogleRichResultAssessments } from '../../extract/google-rich-results.js';\nimport { extractPage } from '../../extract/page-extractor.js';\nimport { OriginBackpressureError } from '../../fetch/page-fetcher/rate-controls.js';\nimport { RobotsAccessError } from '../../fetch/page-fetcher/robots.js';\nimport { fetchPage } from '../../fetch/page-fetcher.js';\nimport { hasMetaRobotsDirective, hasXRobotsDirective, } from '../../robots-directives.js';\nfunction sameOriginUrl(href, base) {\n try {\n const url = new URL(href, base);\n url.hash = '';\n if (url.origin !== base.origin)\n return undefined;\n if (!['http:', 'https:'].includes(url.protocol))\n return undefined;\n return url.toString();\n }\n catch {\n return undefined;\n }\n}\nfunction resolvedUrl(href, base) {\n if (!href)\n return undefined;\n try {\n const url = new URL(href, base);\n return ['http:', 'https:'].includes(url.protocol)\n ? url.toString()\n : undefined;\n }\n catch {\n return undefined;\n }\n}\nfunction hashText(value) {\n return createHash('sha256').update(value).digest('hex');\n}\nfunction headerValue(headers, name) {\n const lower = name.toLowerCase();\n return (headers[name] ??\n headers[lower] ??\n Object.entries(headers).find(([key]) => key.toLowerCase() === lower)?.[1]);\n}\nfunction safeResponseHeaders(headers) {\n const blocked = new Set([\n 'authorization',\n 'cookie',\n 'proxy-authorization',\n 'set-cookie',\n 'www-authenticate',\n ]);\n return Object.fromEntries(Object.entries(headers).filter(([key]) => !blocked.has(key.toLowerCase())));\n}\nfunction truncate(value, max) {\n return value.length > max ? value.slice(0, max).trimEnd() : value;\n}\nfunction anchorSamples(links, internal) {\n const seen = new Set();\n const samples = [];\n for (const link of links) {\n if (link.internal !== internal)\n continue;\n const text = truncate(link.text.replace(/\\s+/g, ' ').trim(), 120);\n if (!text)\n continue;\n const key = `${link.href}\\n${text}`;\n if (seen.has(key))\n continue;\n seen.add(key);\n samples.push({ href: link.href, text });\n if (samples.length >= 25)\n break;\n }\n return samples;\n}\nfunction socialProfileLinks(links) {\n const hosts = [\n 'facebook.com',\n 'instagram.com',\n 'linkedin.com',\n 'pinterest.com',\n 'tiktok.com',\n 'twitter.com',\n 'x.com',\n 'youtube.com',\n ];\n const profiles = new Set();\n for (const link of links) {\n if (link.internal)\n continue;\n try {\n const url = new URL(link.href);\n const host = url.hostname.replace(/^www\\./, '').toLowerCase();\n if (hosts.some((value) => host === value || host.endsWith(`.${value}`))) {\n url.hash = '';\n profiles.add(url.toString());\n }\n }\n catch {\n // Ignore malformed outgoing links.\n }\n }\n return [...profiles].slice(0, 50);\n}\nfunction sameDocumentUrl(left, right) {\n if (!left || !right)\n return false;\n try {\n const a = new URL(left);\n const b = new URL(right);\n a.hash = '';\n b.hash = '';\n return a.toString() === b.toString();\n }\n catch {\n return left === right;\n }\n}\nfunction isHtmlContentType(value) {\n return /^\\s*(?:text\\/html|application\\/xhtml\\+xml)\\b/i.test(value ?? '');\n}\nfunction fetchFailureKind(error, signal) {\n const record = error;\n const code = String(record?.code ?? record?.cause?.code ?? '').toUpperCase();\n const message = error instanceof Error ? error.message : String(error);\n if (signal?.aborted)\n return 'aborted';\n if (/TOO MANY REDIRECTS/i.test(message))\n return 'redirect-limit';\n if (['ENOTFOUND', 'EAI_AGAIN', 'EAI_FAIL'].includes(code))\n return 'dns';\n if (code.includes('CERT') ||\n code.includes('TLS') ||\n code.includes('SSL') ||\n /CERTIFICATE|\\bTLS\\b|\\bSSL\\b/i.test(message)) {\n return 'tls';\n }\n if (code === 'ETIMEDOUT' ||\n /TIMED?\\s*OUT|TIMEOUT|ABORT(?:ED|ERROR)/i.test(message)) {\n return 'timeout';\n }\n return 'unknown';\n}\nfunction responseObservation(requestedUrl, fetched, extraction, extractionError) {\n const observation = {\n requestedUrl,\n outcome: 'response',\n finalUrl: fetched.finalUrl,\n status: fetched.status,\n contentType: headerValue(fetched.headers, 'content-type'),\n durationMs: fetched.diagnostics.durationMs,\n redirectChain: fetched.diagnostics.redirectChain,\n };\n if (extraction === 'failed') {\n if (!extractionError) {\n throw new Error('Failed extraction observations require an error.');\n }\n return { ...observation, extraction, extractionError };\n }\n return { ...observation, extraction };\n}\nfunction unextractedPage(fetched, contentType) {\n const xRobotsTag = headerValue(fetched.headers, 'x-robots-tag');\n const canonicalEvidence = extractHttpCanonicalEvidence(fetched.headers, fetched.finalUrl);\n const noindex = hasXRobotsDirective(xRobotsTag, 'noindex');\n const knownNonHtml = Boolean(contentType);\n return {\n url: fetched.finalUrl,\n finalUrl: fetched.finalUrl,\n status: fetched.status,\n contentType,\n responseHeaders: safeResponseHeaders(fetched.headers),\n responseTimeMs: fetched.diagnostics.durationMs,\n sizeBytes: Buffer.byteLength(fetched.html),\n usedJs: fetched.usedJs,\n fetchSource: fetched.diagnostics.source,\n cacheState: fetched.diagnostics.cache,\n fetchDiagnostics: fetched.diagnostics,\n blocked: fetched.diagnostics.blocked,\n robotsTxt: fetched.robotsTxt,\n xRobotsTag,\n canonical: canonicalEvidence.selectedUrl,\n canonicalRaw: canonicalEvidence.selectedRaw ?? canonicalEvidence.candidates[0]?.raw,\n canonicalStatus: canonicalEvidence.status,\n canonicalCandidates: canonicalEvidence.candidates,\n indexable: fetched.status >= 200 && fetched.status < 300 && !noindex,\n indexability: noindex\n ? 'X-Robots-Tag noindex'\n : knownNonHtml\n ? 'Non-HTML response'\n : 'Unknown response media type',\n declaredIndexability: noindex\n ? 'noindex'\n : knownNonHtml\n ? 'not-html'\n : 'unknown',\n extractionStatus: knownNonHtml ? 'not-applicable' : 'unknown-media-type',\n wordCount: 0,\n contentHash: hashText(fetched.html),\n outgoingInternalCount: 0,\n outgoingExternalCount: 0,\n isHttps: new URL(fetched.finalUrl).protocol === 'https:',\n hasHsts: Boolean(headerValue(fetched.headers, 'strict-transport-security')),\n compression: headerValue(fetched.headers, 'content-encoding'),\n };\n}\nfunction indexabilityReason(page) {\n if (page.status < 200 || page.status >= 300)\n return `Status ${page.status}`;\n if (hasMetaRobotsDirective(page.metaRobots, 'noindex')) {\n return 'Meta robots noindex';\n }\n if (hasXRobotsDirective(page.xRobotsTag, 'noindex')) {\n return 'X-Robots-Tag noindex';\n }\n return undefined;\n}\nexport async function crawlOne(url, opts = {}) {\n const startedAt = Date.now();\n let fetched;\n try {\n fetched = await fetchPage(url, opts);\n }\n catch (error) {\n if (error instanceof OriginBackpressureError) {\n return {\n request: {\n requestedUrl: url,\n outcome: 'skipped',\n reason: 'origin-backpressure',\n error: error.message,\n extraction: 'not-applicable',\n },\n urls: [],\n };\n }\n if (error instanceof RobotsAccessError) {\n return {\n request: {\n requestedUrl: url,\n outcome: 'skipped',\n reason: error.reason,\n robotsTxt: {\n url: error.evidence.url,\n allowed: error.evidence.allowed,\n availability: error.evidence.availability,\n status: error.evidence.status,\n error: error.evidence.error,\n matchedLine: error.evidence.matchedLine,\n },\n extraction: 'not-applicable',\n },\n urls: [],\n };\n }\n const message = error instanceof Error ? error.message : String(error);\n return {\n request: {\n requestedUrl: url,\n outcome: 'failure',\n durationMs: Date.now() - startedAt,\n failureKind: fetchFailureKind(error, opts.signal),\n error: message,\n extraction: 'not-applicable',\n },\n urls: [],\n warning: `${url}: ${message}`,\n };\n }\n const contentType = headerValue(fetched.headers, 'content-type');\n if (!isHtmlContentType(contentType)) {\n const extraction = contentType\n ? 'not-applicable'\n : 'unknown-media-type';\n return {\n request: responseObservation(url, fetched, extraction),\n page: unextractedPage(fetched, contentType),\n urls: [],\n };\n }\n try {\n const extracted = await extractPage(fetched);\n const base = new URL(extracted.finalUrl);\n const internalLinks = extracted.links\n .map((link) => sameOriginUrl(link.href, base))\n .filter((value) => Boolean(value));\n const externalLinks = extracted.links\n .filter((link) => !link.internal)\n .map((link) => link.href)\n .filter((href) => /^https?:\\/\\//.test(href));\n const h1 = extracted.headings.find((heading) => heading.level === 1)?.text;\n const uniqueInternalLinks = [...new Set(internalLinks)];\n const uniqueExternalLinks = [...new Set(externalLinks)];\n const canonical = extracted.canonicalEvidence?.selectedUrl ??\n resolvedUrl(extracted.canonical, extracted.finalUrl);\n const richResults = selectGoogleRichResultAssessments(extracted.googleRichResults ?? []);\n const page = {\n url: extracted.finalUrl,\n finalUrl: extracted.finalUrl,\n status: fetched.status,\n contentType,\n responseHeaders: safeResponseHeaders(fetched.headers),\n responseTimeMs: fetched.diagnostics.durationMs,\n sizeBytes: Buffer.byteLength(fetched.html),\n usedJs: fetched.usedJs,\n fetchSource: fetched.diagnostics.source,\n cacheState: fetched.diagnostics.cache,\n fetchDiagnostics: fetched.diagnostics,\n blocked: fetched.diagnostics.blocked,\n robotsTxt: fetched.robotsTxt,\n title: extracted.title,\n metaDescription: extracted.metaDescription,\n canonical,\n canonicalRaw: extracted.canonicalEvidence?.selectedRaw ??\n extracted.canonicalEvidence?.candidates[0]?.raw ??\n extracted.canonical,\n canonicalStatus: extracted.canonicalEvidence?.status,\n canonicalCandidates: extracted.canonicalEvidence?.candidates,\n metaRobots: extracted.metaRobots,\n xRobotsTag: extracted.xRobotsTag,\n h1,\n h1Count: extracted.headings.filter((heading) => heading.level === 1)\n .length,\n h2Count: extracted.headings.filter((heading) => heading.level === 2)\n .length,\n h3Count: extracted.headings.filter((heading) => heading.level === 3)\n .length,\n indexable: false,\n extractionStatus: 'complete',\n wordCount: extracted.wordCount,\n contentExtraction: extracted.contentExtraction,\n warnings: [\n ...extracted.warnings,\n ...(extracted.canonicalEvidence?.status === 'invalid' ||\n (extracted.canonical && !canonical)\n ? ['Ignored a malformed canonical URL.']\n : []),\n ...(extracted.canonicalEvidence?.status === 'conflicting'\n ? ['Found conflicting canonical declarations.']\n : []),\n ...(extracted.canonicalEvidence?.status === 'outside-head-only'\n ? [\n 'Ignored canonical link elements outside the document head because Google does not accept them.',\n ]\n : []),\n ],\n contentHash: hashText([\n extracted.title,\n extracted.metaDescription,\n h1,\n extracted.canonical,\n extracted.contentText,\n ].join('\\n')),\n mainContentHash: hashText(extracted.contentText),\n textRatio: fetched.html.length\n ? Math.min(1, extracted.contentText.length / fetched.html.length)\n : undefined,\n contentSample: truncate(extracted.contentText, 300),\n lang: extracted.lang,\n hasViewport: extracted.hasViewport,\n isHttps: new URL(extracted.finalUrl).protocol === 'https:',\n hasHsts: Boolean(headerValue(fetched.headers, 'strict-transport-security')),\n compression: headerValue(fetched.headers, 'content-encoding'),\n hreflang: extracted.hreflang,\n mixedContentCount: extracted.mixedContentUrls.length,\n mixedContentSamples: extracted.mixedContentUrls.slice(0, 25),\n imagesTotal: extracted.imagesTotal,\n imagesMissingAlt: extracted.imagesMissingAlt,\n oversizedImageCandidates: extracted.oversizedImageCandidates,\n outgoingInternalCount: uniqueInternalLinks.length,\n outgoingExternalCount: uniqueExternalLinks.length,\n sampleInternalLinks: uniqueInternalLinks.slice(0, 25),\n sampleExternalLinks: uniqueExternalLinks.slice(0, 25),\n internalAnchorSamples: anchorSamples(extracted.links, true),\n externalAnchorSamples: anchorSamples(extracted.links, false),\n schemaTypes: extracted.schemaTypes,\n structuredDataFormats: extracted.structuredDataFormats ?? [],\n googleRichResults: richResults.assessments,\n googleRichResultsSelection: richResults.selection,\n schemaSameAs: [\n ...new Set((extracted.schemaSameAsEvidence ?? []).map((evidence) => evidence.url)),\n ].slice(0, 50),\n schemaSameAsEvidence: (extracted.schemaSameAsEvidence ?? []).slice(0, 50),\n invalidSchemaSameAs: (extracted.invalidSchemaSameAs ?? []).slice(0, 25),\n socialProfileLinks: socialProfileLinks(extracted.links),\n invalidJsonLdCount: extracted.invalidJsonLdCount,\n invalidJsonLdSamples: extracted.invalidJsonLdSamples,\n unrecognizedJsonLdTypes: extracted.unrecognizedJsonLdTypes ?? [],\n openGraphTitle: extracted.openGraph['og:title'],\n openGraphDescription: extracted.openGraph['og:description'],\n openGraphImage: extracted.openGraph['og:image'],\n twitterCard: extracted.twitter['twitter:card'],\n author: extracted.author,\n hasDate: extracted.hasDate,\n geo: {\n semanticHtml: extracted.semanticHtml,\n structuredData: (extracted.structuredDataFormats?.length ?? 0) > 0,\n hasAuthor: extracted.hasAuthor,\n hasDate: extracted.hasDate,\n questionHeadings: extracted.questionHeadings,\n listCount: extracted.listCount,\n tableCount: extracted.tableCount,\n structuredBlocks: extracted.structuredBlocks,\n answerable: extracted.answerable,\n hasFaqSchema: extracted.schemaTypes.includes('FAQPage'),\n hasQapageSchema: extracted.schemaTypes.includes('QAPage'),\n },\n };\n page.indexability = indexabilityReason(page);\n page.indexable = !page.indexability;\n page.declaredIndexability =\n hasMetaRobotsDirective(page.metaRobots, 'noindex') ||\n hasXRobotsDirective(page.xRobotsTag, 'noindex')\n ? 'noindex'\n : page.robotsTxt?.allowed === false\n ? 'robots-blocked'\n : page.canonicalStatus === 'conflicting'\n ? 'canonical-conflict'\n : page.canonical && !sameDocumentUrl(page.canonical, page.finalUrl)\n ? 'canonical-hint-other'\n : 'indexable-candidate';\n return {\n request: responseObservation(url, fetched, 'complete'),\n page,\n urls: uniqueInternalLinks,\n };\n }\n catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n request: responseObservation(url, fetched, 'failed', message),\n urls: [],\n warning: `${url}: content extraction failed: ${message}`,\n };\n }\n}\n//# sourceMappingURL=crawl-page.js.map","import { gunzipSync } from 'node:zlib';\nimport { load } from 'cheerio';\nimport { publicHttpFetch } from '../../fetch/http-client.js';\nconst INVALID_LOC_SAMPLE_LIMIT = 10;\nconst LASTMOD_SAMPLE_LIMIT = 10;\nconst MAX_SITEMAP_BYTES = 52_428_800;\nconst LASTMOD_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.\\d+)?)?(Z|[+-]\\d{2}:\\d{2}))?$/;\nfunction normalizeUrl(value) {\n try {\n const parsed = new URL(value.trim());\n return ['http:', 'https:'].includes(parsed.protocol)\n ? parsed.toString()\n : undefined;\n }\n catch {\n return undefined;\n }\n}\nfunction positiveInteger(value, name) {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new Error(`${name} must be a positive integer.`);\n }\n return value;\n}\nfunction parseSitemapLastmod(value) {\n const match = LASTMOD_PATTERN.exec(value);\n if (!match)\n return undefined;\n const [, yearText, monthText, dayText, hourText, minuteText, secondText, timeZone,] = match;\n const year = Number(yearText);\n const month = Number(monthText);\n const day = Number(dayText);\n const hour = hourText === undefined ? 0 : Number(hourText);\n const minute = minuteText === undefined ? 0 : Number(minuteText);\n const second = secondText === undefined ? 0 : Number(secondText);\n const daysInMonth = month === 2\n ? year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)\n ? 29\n : 28\n : [4, 6, 9, 11].includes(month)\n ? 30\n : 31;\n const offset = timeZone?.match(/^([+-])(\\d{2}):(\\d{2})$/);\n if (month < 1 ||\n month > 12 ||\n day < 1 ||\n day > daysInMonth ||\n hour > 23 ||\n minute > 59 ||\n second > 59 ||\n (offset && (Number(offset[2]) > 23 || Number(offset[3]) > 59))) {\n return undefined;\n }\n const parsed = hourText ? new Date(value) : new Date(`${value}T00:00:00Z`);\n return Number.isNaN(parsed.getTime()) ? undefined : parsed;\n}\nfunction isGzip(bytes) {\n return bytes[0] === 0x1f && bytes[1] === 0x8b;\n}\nfunction contentTypeLooksXml(contentType, compression) {\n if (!contentType)\n return true;\n const mime = contentType.split(';', 1)[0]?.trim().toLowerCase();\n return Boolean(mime &&\n (compression === 'gzip'\n ? mime === 'application/gzip' || mime === 'application/x-gzip'\n : mime === 'application/xml' ||\n mime === 'text/xml' ||\n mime.endsWith('+xml')));\n}\nasync function responseBytes(response) {\n const declaredLength = Number(response.headers.get('content-length'));\n if (Number.isFinite(declaredLength) && declaredLength > MAX_SITEMAP_BYTES) {\n throw new Error(`The response exceeds the ${MAX_SITEMAP_BYTES}-byte sitemap limit.`);\n }\n const reader = response.body?.getReader();\n if (!reader)\n return new Uint8Array();\n const chunks = [];\n let total = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n break;\n total += value.byteLength;\n if (total > MAX_SITEMAP_BYTES) {\n await reader.cancel();\n throw new Error(`The response exceeds the ${MAX_SITEMAP_BYTES}-byte sitemap limit.`);\n }\n chunks.push(value);\n }\n }\n finally {\n reader.releaseLock();\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\nfunction xmlRoot(xml) {\n const tags = [];\n let rootName;\n let cursor = 0;\n while (cursor < xml.length) {\n const start = xml.indexOf('<', cursor);\n if (start === -1)\n break;\n if (xml.startsWith('<!--', start)) {\n const end = xml.indexOf('-->', start + 4);\n if (end === -1)\n return { error: 'an unclosed XML comment' };\n cursor = end + 3;\n continue;\n }\n if (xml.startsWith('<![CDATA[', start)) {\n const end = xml.indexOf(']]>', start + 9);\n if (end === -1)\n return { error: 'an unclosed CDATA section' };\n cursor = end + 3;\n continue;\n }\n if (xml.startsWith('<?', start)) {\n const end = xml.indexOf('?>', start + 2);\n if (end === -1)\n return { error: 'an unclosed processing instruction' };\n cursor = end + 2;\n continue;\n }\n let end = start + 1;\n let quote;\n while (end < xml.length) {\n const character = xml[end];\n if (quote) {\n if (character === quote)\n quote = undefined;\n }\n else if (character === '\"' || character === \"'\") {\n quote = character;\n }\n else if (character === '>') {\n break;\n }\n end += 1;\n }\n if (end >= xml.length || quote)\n return { error: 'an unclosed XML tag' };\n const content = xml.slice(start + 1, end).trim();\n cursor = end + 1;\n if (!content || content.startsWith('!'))\n continue;\n if (content.startsWith('/')) {\n const name = content.slice(1).trim();\n const expected = tags.pop();\n if (!expected || name !== expected) {\n return { error: `a mismatched closing tag </${name}>` };\n }\n continue;\n }\n const name = content.match(/^([A-Za-z_][A-Za-z0-9_.:-]*)/);\n if (!name?.[1])\n return { error: 'an invalid XML tag name' };\n if (tags.length === 0) {\n if (rootName)\n return { error: 'more than one XML root element' };\n rootName = name[1];\n }\n const selfClosing = /\\/$/.test(content);\n if (!selfClosing)\n tags.push(name[1]);\n }\n if (tags.length > 0) {\n return { error: `an unclosed <${tags.at(-1)}> tag` };\n }\n if (rootName === 'urlset' || rootName === 'sitemapindex') {\n return { root: rootName };\n }\n return {\n error: `expected a <urlset> or <sitemapindex> root${rootName ? `, found <${rootName}>` : ''}`,\n };\n}\nasync function fetchSitemapXml(sitemapUrl) {\n try {\n const response = await publicHttpFetch(sitemapUrl, { profile: 'browser' });\n const contentType = response.headers.get('content-type') ?? undefined;\n const finalUrl = normalizeUrl(response.url);\n const redirectEvidence = response.redirected && finalUrl\n ? { finalUrl, redirected: true }\n : {};\n if (!response.ok) {\n return {\n document: {\n url: sitemapUrl,\n ...redirectEvidence,\n dataStatus: 'unavailable',\n status: response.status,\n contentType,\n compression: 'none',\n warning: `Sitemap fetch failed for ${sitemapUrl}: HTTP ${response.status}.`,\n },\n };\n }\n let bytes;\n try {\n bytes = await responseBytes(response);\n }\n catch (error) {\n return {\n document: {\n url: sitemapUrl,\n ...redirectEvidence,\n dataStatus: 'partial',\n status: response.status,\n contentType,\n compression: 'none',\n warning: `Could not read sitemap data: ${error instanceof Error ? error.message : String(error)}`,\n },\n };\n }\n const compression = isGzip(bytes) ? 'gzip' : 'none';\n let xmlBytes = bytes;\n if (compression === 'gzip') {\n try {\n xmlBytes = gunzipSync(bytes, { maxOutputLength: MAX_SITEMAP_BYTES });\n }\n catch (error) {\n return {\n document: {\n url: sitemapUrl,\n ...redirectEvidence,\n dataStatus: 'partial',\n status: response.status,\n contentType,\n compression,\n bytes: bytes.byteLength,\n warning: `Could not decompress sitemap gzip data: ${error instanceof Error ? error.message : String(error)}`,\n },\n };\n }\n }\n const xml = new TextDecoder().decode(xmlBytes);\n const validated = xmlRoot(xml);\n const contentTypeWarning = contentTypeLooksXml(contentType, compression)\n ? undefined\n : `Sitemap returned content type ${contentType ?? 'unknown'}, not an XML type.`;\n if ('error' in validated) {\n return {\n document: {\n url: sitemapUrl,\n ...redirectEvidence,\n dataStatus: 'partial',\n status: response.status,\n contentType,\n compression,\n bytes: bytes.byteLength,\n uncompressedBytes: xmlBytes.byteLength,\n warning: `Sitemap XML is invalid: ${validated.error}.`,\n },\n };\n }\n return {\n document: {\n url: sitemapUrl,\n ...redirectEvidence,\n dataStatus: contentTypeWarning ? 'partial' : 'complete',\n status: response.status,\n contentType,\n compression,\n bytes: bytes.byteLength,\n uncompressedBytes: xmlBytes.byteLength,\n root: validated.root,\n ...(contentTypeWarning ? { warning: contentTypeWarning } : {}),\n },\n xml,\n };\n }\n catch (error) {\n return {\n document: {\n url: sitemapUrl,\n dataStatus: 'unavailable',\n compression: 'none',\n warning: `Sitemap fetch failed for ${sitemapUrl}: ${error instanceof Error ? error.message : String(error)}`,\n },\n };\n }\n}\nexport function boundedSitemapInventory(results, limit) {\n const inventoryLimit = positiveInteger(limit, 'limit');\n const uniqueUrls = [...new Set(results.flatMap((result) => result.urls))];\n const sourceTruncated = results.some((result) => result.truncation.possiblyTruncated);\n const inventoryLimitExceeded = uniqueUrls.length > inventoryLimit;\n return {\n urls: uniqueUrls.slice(0, inventoryLimit),\n truncation: {\n possiblyTruncated: sourceTruncated || inventoryLimitExceeded,\n sourceTruncated,\n inventoryLimitExceeded,\n omittedUrlsAtLeast: Math.max(0, uniqueUrls.length - inventoryLimit),\n limit: inventoryLimit,\n },\n };\n}\nexport async function fetchSitemapUrls(input) {\n const warnings = [];\n const urls = [];\n const seenUrls = new Set();\n const nestedSitemaps = [];\n const discoveredSitemaps = new Set();\n const scheduledSitemaps = new Set();\n const invalidLocSamples = [];\n const malformedLastmodSamples = [];\n const futureLastmodSamples = [];\n const documents = [];\n const queue = [];\n const limit = positiveInteger(input.limit ?? 50_000, 'limit');\n const maxNested = positiveInteger(input.maxNested ?? 50, 'maxNested');\n const rootSitemap = normalizeUrl(input.sitemapUrl);\n if (!rootSitemap) {\n throw new Error('sitemapUrl must be an absolute HTTP or HTTPS URL.');\n }\n scheduledSitemaps.add(rootSitemap);\n queue.push(rootSitemap);\n let sitemapsFetched = 0;\n let urlLocs = 0;\n let sitemapLocs = 0;\n let duplicateUrlLocs = 0;\n let duplicateSitemapLocs = 0;\n let invalidLocCount = 0;\n let lastmodsObserved = 0;\n let parseableLastmods = 0;\n let malformedLastmodCount = 0;\n let futureLastmodCount = 0;\n let omittedUrlsAtLeast = 0;\n let urlLimitExceeded = false;\n let nestedSitemapLimitExceeded = false;\n function recordInvalidLoc(input) {\n invalidLocCount += 1;\n if (invalidLocSamples.length < INVALID_LOC_SAMPLE_LIMIT) {\n invalidLocSamples.push(input);\n }\n }\n function recordLastmod(input) {\n lastmodsObserved += 1;\n const parsed = parseSitemapLastmod(input.value);\n if (!parsed) {\n malformedLastmodCount += 1;\n if (malformedLastmodSamples.length < LASTMOD_SAMPLE_LIMIT) {\n malformedLastmodSamples.push(input);\n }\n return;\n }\n parseableLastmods += 1;\n if (parsed.getTime() > Date.now()) {\n futureLastmodCount += 1;\n if (futureLastmodSamples.length < LASTMOD_SAMPLE_LIMIT) {\n futureLastmodSamples.push(input);\n }\n }\n }\n while (queue.length) {\n const sitemapUrl = queue.shift();\n if (!sitemapUrl)\n continue;\n const fetched = await fetchSitemapXml(sitemapUrl);\n documents.push(fetched.document);\n if (fetched.document.warning)\n warnings.push(fetched.document.warning);\n if (fetched.document.dataStatus !== 'unavailable')\n sitemapsFetched += 1;\n if (!fetched.xml || !fetched.document.root)\n continue;\n const $ = load(fetched.xml, { xmlMode: true });\n const urlEntrySelector = fetched.document.root === 'urlset' ? 'urlset > url' : '';\n $(urlEntrySelector).each((_, element) => {\n urlLocs += 1;\n const entry = $(element);\n const value = entry.children('loc').first().text().trim();\n const lastmod = entry.children('lastmod').first();\n if (lastmod.length) {\n recordLastmod({\n sitemapUrl,\n kind: 'url',\n loc: value,\n value: lastmod.text().trim(),\n });\n }\n const url = normalizeUrl(value);\n if (!url) {\n recordInvalidLoc({ sitemapUrl, kind: 'url', value });\n return;\n }\n if (seenUrls.has(url)) {\n duplicateUrlLocs += 1;\n return;\n }\n seenUrls.add(url);\n if (urls.length < limit) {\n urls.push(url);\n return;\n }\n urlLimitExceeded = true;\n omittedUrlsAtLeast += 1;\n });\n const sitemapEntrySelector = fetched.document.root === 'sitemapindex' ? 'sitemapindex > sitemap' : '';\n $(sitemapEntrySelector).each((_, element) => {\n sitemapLocs += 1;\n const entry = $(element);\n const value = entry.children('loc').first().text().trim();\n const lastmod = entry.children('lastmod').first();\n if (lastmod.length) {\n recordLastmod({\n sitemapUrl,\n kind: 'sitemap',\n loc: value,\n value: lastmod.text().trim(),\n });\n }\n const child = normalizeUrl(value);\n if (!child) {\n recordInvalidLoc({ sitemapUrl, kind: 'sitemap', value });\n return;\n }\n if (discoveredSitemaps.has(child) || scheduledSitemaps.has(child)) {\n duplicateSitemapLocs += 1;\n return;\n }\n discoveredSitemaps.add(child);\n nestedSitemaps.push(child);\n if (scheduledSitemaps.size < maxNested) {\n scheduledSitemaps.add(child);\n queue.push(child);\n }\n else {\n nestedSitemapLimitExceeded = true;\n }\n });\n }\n const unprocessedSitemaps = nestedSitemaps.filter((sitemap) => !scheduledSitemaps.has(sitemap)).length;\n const possiblyTruncated = urlLimitExceeded || nestedSitemapLimitExceeded || unprocessedSitemaps > 0;\n if (invalidLocCount) {\n warnings.push(`Ignored ${invalidLocCount} invalid sitemap <loc> ${invalidLocCount === 1 ? 'entry' : 'entries'}.`);\n }\n if (possiblyTruncated) {\n warnings.push('Sitemap discovery exceeded a configured URL or sitemap boundary; the returned inventory is incomplete.');\n }\n return {\n sitemapUrl: rootSitemap,\n dataStatus: warnings.length || invalidLocCount || possiblyTruncated\n ? 'partial'\n : 'complete',\n urls,\n nestedSitemaps,\n source: {\n sitemapsFetched,\n urlLocs,\n sitemapLocs,\n duplicateUrlLocs,\n duplicateSitemapLocs,\n invalidLocs: {\n count: invalidLocCount,\n samples: invalidLocSamples,\n },\n lastmods: {\n trust: 'unverified',\n observed: lastmodsObserved,\n parseable: parseableLastmods,\n malformed: {\n count: malformedLastmodCount,\n samples: malformedLastmodSamples,\n },\n future: {\n count: futureLastmodCount,\n samples: futureLastmodSamples,\n },\n },\n documents,\n },\n truncation: {\n possiblyTruncated,\n urlLimitExceeded,\n nestedSitemapLimitExceeded,\n omittedUrlsAtLeast,\n unprocessedSitemaps,\n limits: {\n urls: limit,\n sitemaps: maxNested,\n },\n },\n warnings,\n };\n}\n//# sourceMappingURL=sitemaps.js.map","import { ga4ReportQualityWarnings, ga4RowsToObjects, runGa4Report, } from '../../ga4/client.js';\nconst defaultDependencies = { runGa4Report };\nfunction normalizePath(value) {\n if (!value || value === '(not set)')\n return '';\n const [path = ''] = value.split('?');\n return path.replace(/\\/$/, '') || '/';\n}\nfunction urlPath(url) {\n try {\n return normalizePath(new URL(url).pathname);\n }\n catch {\n return '';\n }\n}\nfunction compareText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\nexport function landingPageValuesFromRows(rows) {\n const orderedRows = [...rows].sort((left, right) => {\n const leftPath = normalizePath(left.landingPagePlusQueryString ?? '');\n const rightPath = normalizePath(right.landingPagePlusQueryString ?? '');\n return (compareText(leftPath, rightPath) ||\n compareText(left.landingPagePlusQueryString ?? '', right.landingPagePlusQueryString ?? '') ||\n compareText(left.sessions ?? '', right.sessions ?? '') ||\n compareText(left.totalUsers ?? '', right.totalUsers ?? '') ||\n compareText(left.conversions ?? '', right.conversions ?? ''));\n });\n const values = new Map();\n for (const row of orderedRows) {\n const path = normalizePath(row.landingPagePlusQueryString ?? '');\n if (!path)\n continue;\n const existing = values.get(path) ?? {\n sessions: 0,\n totalUsers: 0,\n conversions: 0,\n };\n values.set(path, {\n sessions: existing.sessions + Number(row.sessions ?? 0),\n totalUsers: existing.totalUsers + Number(row.totalUsers ?? 0),\n conversions: existing.conversions + Number(row.conversions ?? 0),\n });\n }\n return values;\n}\nexport function landingValueForUrl(values, url) {\n return values.get(urlPath(url));\n}\nexport function landingPageValuesCanRank(source) {\n return source?.dataStatus === 'complete';\n}\nexport function landingPageRankingPolicy(input) {\n if (!input.propertyId)\n return { canRank: false, warnings: [] };\n const warningSuffix = 'Observed landing-page values remain visible but do not affect priority scores.';\n const warnings = [\n ...(input.warning ? [`GA4: ${input.warning}`] : []),\n ...(input.source?.retainedRowLimitReached\n ? [`GA4: the retained-row limit was reached. ${warningSuffix}`]\n : []),\n ...(input.source?.qualityWarnings?.map((warning) => `${warning} ${warningSuffix}`) ?? []),\n ];\n if (!input.source?.dataStatus && !input.warning) {\n warnings.push(`GA4: landing-page completeness was not reported. ${warningSuffix}`);\n }\n return {\n canRank: !input.warning &&\n warnings.length === 0 &&\n landingPageValuesCanRank(input.source),\n warnings,\n };\n}\nexport async function fetchLandingPageValues(input, dependencies = defaultDependencies) {\n const retainedRowLimit = input.limit ?? 5000;\n if (!input.propertyId) {\n return {\n values: new Map(),\n source: {\n dataStatus: 'complete',\n returnedRows: 0,\n retainedRowLimit,\n retainedRowLimitReached: false,\n qualityWarnings: [],\n },\n };\n }\n try {\n const result = await dependencies.runGa4Report(input.propertyId, {\n dateRanges: [{ startDate: input.startDate, endDate: input.endDate }],\n dimensions: [{ name: 'landingPagePlusQueryString' }],\n metrics: [\n { name: 'sessions' },\n { name: 'totalUsers' },\n { name: 'conversions' },\n ],\n orderBys: [{ metric: { metricName: 'sessions' }, desc: true }],\n limit: retainedRowLimit,\n });\n const rows = ga4RowsToObjects(result);\n const values = landingPageValuesFromRows(rows);\n const availableRows = result.rowCount;\n const retainedRowLimitReached = (availableRows !== undefined && availableRows > rows.length) ||\n rows.length >= retainedRowLimit;\n const qualityWarnings = ga4ReportQualityWarnings(result, 'GA4 landing-page report');\n return {\n values,\n source: {\n dataStatus: retainedRowLimitReached || qualityWarnings.length\n ? 'partial'\n : 'complete',\n returnedRows: rows.length,\n ...(availableRows !== undefined ? { availableRows } : {}),\n retainedRowLimit,\n retainedRowLimitReached,\n qualityWarnings,\n },\n };\n }\n catch (error) {\n return {\n values: new Map(),\n source: {\n dataStatus: 'partial',\n returnedRows: 0,\n retainedRowLimit,\n retainedRowLimitReached: false,\n qualityWarnings: [],\n },\n warning: error instanceof Error ? error.message : String(error),\n };\n }\n}\n//# sourceMappingURL=analytics-value.js.map","import { publicHttpFetch } from '../../fetch/http-client.js';\nimport { queryPageMetrics, queryPagesMetrics, queryPagesMetricsBatch, queryPagesTopQueries, queryPagesTopQueriesBatch, queryPageTopQuery, } from '../../gsc/client.js';\nimport { crawlOne } from '../monitoring/crawl-page.js';\nimport { fetchSitemapUrls } from '../monitoring/sitemaps.js';\nimport { fetchLandingPageValues, landingValueForUrl, } from '../workflows/analytics-value.js';\nexport function resolveCrawlSiteDependencies(dependencies = {}) {\n const hasInjectedPerPageSearchProvider = Boolean(dependencies.queryPageMetrics || dependencies.queryPageTopQuery);\n const hasInjectedLegacyBulkSearchProvider = Boolean(dependencies.queryPagesMetrics || dependencies.queryPagesTopQueries);\n const hasInjectedBatchSearchProvider = Boolean(dependencies.queryPagesMetricsBatch ||\n dependencies.queryPagesTopQueriesBatch);\n const injectedMode = hasInjectedBatchSearchProvider\n ? 'batch'\n : hasInjectedLegacyBulkSearchProvider\n ? 'legacy-bulk'\n : hasInjectedPerPageSearchProvider\n ? 'per-page'\n : undefined;\n const emptyPageMetrics = async () => undefined;\n const emptyPageTopQuery = async () => undefined;\n return {\n fetchPage: dependencies.fetchPage ?? crawlOne,\n fetchSitemapUrls: dependencies.fetchSitemapUrls ?? fetchSitemapUrls,\n fetch: dependencies.fetch ?? publicHttpFetch,\n queryPageMetrics: (injectedMode === 'per-page'\n ? dependencies.queryPageMetrics\n : undefined) ?? (injectedMode ? emptyPageMetrics : queryPageMetrics),\n queryPageTopQuery: (injectedMode === 'per-page'\n ? dependencies.queryPageTopQuery\n : undefined) ?? (injectedMode ? emptyPageTopQuery : queryPageTopQuery),\n queryPagesMetrics: injectedMode === 'legacy-bulk'\n ? dependencies.queryPagesMetrics\n : injectedMode\n ? undefined\n : queryPagesMetrics,\n queryPagesTopQueries: injectedMode === 'legacy-bulk'\n ? dependencies.queryPagesTopQueries\n : injectedMode\n ? undefined\n : queryPagesTopQueries,\n queryPagesMetricsBatch: injectedMode === 'batch'\n ? dependencies.queryPagesMetricsBatch\n : injectedMode\n ? undefined\n : queryPagesMetricsBatch,\n queryPagesTopQueriesBatch: injectedMode === 'batch'\n ? dependencies.queryPagesTopQueriesBatch\n : injectedMode\n ? undefined\n : queryPagesTopQueriesBatch,\n fetchLandingPageValues: dependencies.fetchLandingPageValues ?? fetchLandingPageValues,\n landingValueForUrl: dependencies.landingValueForUrl ?? landingValueForUrl,\n now: dependencies.now ?? (() => new Date()),\n };\n}\n//# sourceMappingURL=site-crawl-dependencies.js.map","const MAX_SITEMAP_ROOTS = 20;\nfunction isSameOrigin(url, origin) {\n try {\n return new URL(url).origin === origin;\n }\n catch {\n return false;\n }\n}\nfunction sitemapRootUrls(input) {\n const origin = new URL(input.url).origin;\n const declared = input.declaredSitemapUrls.filter((url) => isSameOrigin(url, origin));\n const ignored = input.declaredSitemapUrls.length - declared.length;\n if (ignored > 0) {\n input.warnings.push(`Ignored ${ignored} robots.txt sitemap declaration${ignored === 1 ? '' : 's'} outside the crawl origin.`);\n }\n const unique = [...new Set(declared)].map((url) => ({\n url,\n source: 'robots-txt',\n }));\n if (unique.length > MAX_SITEMAP_ROOTS) {\n input.warnings.push(`Used the first ${MAX_SITEMAP_ROOTS} robots.txt sitemap declarations to keep discovery bounded.`);\n }\n if (unique.length > 0)\n return unique.slice(0, MAX_SITEMAP_ROOTS);\n return [\n {\n url: new URL('/sitemap.xml', input.url).toString(),\n source: 'default-path',\n },\n ];\n}\nfunction sitemapDiscoveryStatus(roots) {\n if (!roots.some((root) => root.dataStatus !== 'unavailable')) {\n return 'unavailable';\n }\n return roots.every((root) => root.dataStatus === 'complete')\n ? 'complete'\n : 'partial';\n}\nexport async function sitemapSeeds(input) {\n const roots = [];\n const urls = new Set();\n const rootUrls = sitemapRootUrls(input);\n for (const root of rootUrls) {\n const sitemap = await input.fetchSitemapUrls({\n sitemapUrl: root.url,\n limit: input.maxPages,\n });\n input.warnings.push(...sitemap.warnings);\n for (const url of sitemap.urls)\n urls.add(url);\n roots.push({\n url: sitemap.sitemapUrl,\n source: root.source,\n dataStatus: sitemap.source.sitemapsFetched > 0 ? sitemap.dataStatus : 'unavailable',\n urlsReturned: sitemap.urls.length,\n sitemapsFetched: sitemap.source.sitemapsFetched,\n lastmods: sitemap.source.lastmods,\n documents: sitemap.source.documents,\n possiblyTruncated: sitemap.truncation.possiblyTruncated,\n warnings: sitemap.warnings,\n });\n }\n if (urls.size === 0 &&\n rootUrls.some((root) => root.source === 'robots-txt')) {\n const fallbackUrl = new URL('/sitemap.xml', input.url).toString();\n if (!roots.some((root) => root.url === fallbackUrl)) {\n input.warnings.push('No robots.txt sitemap declaration returned URLs, so the crawler also tried /sitemap.xml.');\n const sitemap = await input.fetchSitemapUrls({\n sitemapUrl: fallbackUrl,\n limit: input.maxPages,\n });\n input.warnings.push(...sitemap.warnings);\n for (const url of sitemap.urls)\n urls.add(url);\n roots.push({\n url: sitemap.sitemapUrl,\n source: 'default-path',\n dataStatus: sitemap.source.sitemapsFetched > 0\n ? sitemap.dataStatus\n : 'unavailable',\n urlsReturned: sitemap.urls.length,\n sitemapsFetched: sitemap.source.sitemapsFetched,\n lastmods: sitemap.source.lastmods,\n documents: sitemap.source.documents,\n possiblyTruncated: sitemap.truncation.possiblyTruncated,\n warnings: sitemap.warnings,\n });\n }\n }\n return {\n urls: [...urls],\n discovery: {\n dataStatus: sitemapDiscoveryStatus(roots),\n urlsReturned: urls.size,\n roots,\n },\n };\n}\n//# sourceMappingURL=sitemap-discovery.js.map","import robotsParserModule from 'robots-parser';\nimport { createPageRenderer } from '../../fetch/page-fetcher.js';\nimport { crawlCaveats } from './crawl-caveats.js';\nimport { abortController, CRAWL_CANCELLED, cancellationRace, } from './crawl-control.js';\nimport { verifyExternalLinks } from './external-link-checks.js';\nimport { resolveLinkGraphAliases } from './link-graph.js';\nimport { createCrawlReport, normalizeCrawlConfig } from './report.js';\nimport { observationFromPage } from './request-evidence.js';\nimport { crawlDataSources, crawlProviderLimits, } from './site-crawl-data-sources.js';\nimport { resolveCrawlSiteDependencies, } from './site-crawl-dependencies.js';\nimport { sitemapSeeds } from './sitemap-discovery.js';\nconst AI_BOT_USER_AGENTS = [\n 'GPTBot',\n 'OAI-SearchBot',\n 'ChatGPT-User',\n 'ClaudeBot',\n 'PerplexityBot',\n 'Google-Extended',\n 'CCBot',\n 'Applebot',\n 'Bingbot',\n];\nconst AGENT_RESOURCE_PATHS = [\n '/.well-known/agent.json',\n '/agent.json',\n '/.well-known/mcp.json',\n '/.well-known/ai-plugin.json',\n '/.well-known/openapi.json',\n '/openapi.json',\n];\nfunction normalizeUrl(value, base) {\n try {\n const url = base ? new URL(value, base) : new URL(value);\n url.hash = '';\n if (!['http:', 'https:'].includes(url.protocol))\n return undefined;\n return url.toString();\n }\n catch {\n return undefined;\n }\n}\nfunction sameOrigin(url, origin) {\n try {\n return new URL(url).origin === origin;\n }\n catch {\n return false;\n }\n}\nfunction isLikelyAsset(url) {\n const path = new URL(url).pathname.toLowerCase();\n return /\\.(avif|bmp|css|csv|dmg|eot|gif|gz|ico|jpeg|jpg|js|json|map|mov|mp3|mp4|ogg|otf|pdf|png|svg|tar|ttf|wav|webm|webp|woff|woff2|zip)$/.test(path);\n}\nfunction globMatch(pattern, value) {\n if (!pattern.includes('*'))\n return value.includes(pattern);\n const parts = pattern.split('*');\n let position = 0;\n for (const part of parts) {\n if (!part)\n continue;\n const found = value.slice(position).indexOf(part);\n if (found === -1)\n return false;\n position += found + part.length;\n }\n return true;\n}\nfunction passesFilters(url, include, exclude) {\n return ((!include.length || include.some((pattern) => globMatch(pattern, url))) &&\n !exclude.some((pattern) => globMatch(pattern, url)));\n}\nasync function checkLlmsTxt(input) {\n const llmsUrl = new URL('/llms.txt', input.url).toString();\n const controller = abortController({\n timeoutMs: input.timeoutMs,\n signal: input.signal,\n });\n try {\n const response = await input.fetch(llmsUrl, {\n profile: 'bot',\n redirect: 'follow',\n signal: controller.signal,\n });\n const contentType = response.headers.get('content-type') ?? '';\n const exists = response.status >= 200 &&\n response.status < 300 &&\n !/\\btext\\/html\\b/i.test(contentType);\n await response.body?.cancel().catch(() => undefined);\n return {\n url: response.url || llmsUrl,\n exists,\n status: response.status,\n };\n }\n catch {\n return { url: llmsUrl, exists: false };\n }\n finally {\n controller.cleanup();\n }\n}\nfunction parseRobots(robotsUrl, text) {\n return robotsParserModule(robotsUrl, text);\n}\nfunction declaredUserAgents(text) {\n const declared = new Set();\n for (const match of text.matchAll(/^\\s*user-agent\\s*:\\s*(.+?)\\s*$/gim)) {\n const value = match[1]?.trim().toLowerCase();\n if (value)\n declared.add(value);\n }\n return declared;\n}\nfunction sitemapUrlsFromRobots(text) {\n const urls = new Set();\n for (const match of text.matchAll(/^\\s*sitemap\\s*:\\s*(\\S+)\\s*$/gim)) {\n const value = match[1]?.trim();\n if (!value)\n continue;\n try {\n urls.add(new URL(value).toString());\n }\n catch {\n // Ignore malformed sitemap declarations.\n }\n }\n return [...urls];\n}\nasync function checkRobotsAiAccess(input) {\n const robotsUrl = new URL('/robots.txt', input.url).toString();\n const controller = abortController({\n timeoutMs: input.timeoutMs,\n signal: input.signal,\n });\n try {\n const response = await input.fetch(robotsUrl, {\n profile: 'bot',\n redirect: 'follow',\n signal: controller.signal,\n });\n const text = await response.text();\n const available = response.status >= 200 && response.status < 300;\n const absent = response.status >= 400 && response.status < 500 && response.status !== 429;\n const availability = available\n ? 'available'\n : [401, 403].includes(response.status)\n ? 'access-blocked'\n : response.status === 429\n ? 'rate-limited'\n : absent\n ? 'absent'\n : 'unreachable';\n const exists = available;\n const declared = exists ? declaredUserAgents(text) : new Set();\n const parsed = parseRobots(robotsUrl, exists ? text : '');\n return {\n url: response.url || robotsUrl,\n exists,\n availability,\n status: response.status,\n ...(['rate-limited', 'unreachable'].includes(availability)\n ? { error: `robots.txt returned HTTP ${response.status}.` }\n : {}),\n sitemapUrls: exists ? sitemapUrlsFromRobots(text) : [],\n botAccess: AI_BOT_USER_AGENTS.map((userAgent) => {\n const lower = userAgent.toLowerCase();\n return {\n userAgent,\n allowed: availability === 'rate-limited' || availability === 'unreachable'\n ? null\n : (parsed.isAllowed(input.url, userAgent) ?? true),\n declared: declared.has(lower),\n coveredByWildcard: declared.has('*'),\n };\n }),\n };\n }\n catch (error) {\n return {\n url: robotsUrl,\n exists: false,\n availability: 'unreachable',\n error: error instanceof Error ? error.message : String(error),\n sitemapUrls: [],\n botAccess: AI_BOT_USER_AGENTS.map((userAgent) => ({\n userAgent,\n allowed: null,\n declared: false,\n coveredByWildcard: false,\n })),\n };\n }\n finally {\n controller.cleanup();\n }\n}\nasync function checkAgentResource(input) {\n const url = new URL(input.path, input.baseUrl).toString();\n const controller = abortController({\n timeoutMs: input.timeoutMs,\n signal: input.signal,\n });\n try {\n const response = await input.fetch(url, {\n profile: 'bot',\n redirect: 'follow',\n signal: controller.signal,\n });\n const contentType = response.headers.get('content-type') ?? '';\n const text = await response.text();\n const exists = response.status >= 200 && response.status < 300;\n let validJson;\n if (exists && /\\bjson\\b/i.test(contentType)) {\n try {\n JSON.parse(text);\n validJson = true;\n }\n catch {\n validJson = false;\n }\n }\n return {\n url: response.url || url,\n exists,\n status: response.status,\n contentType,\n ...(validJson === undefined ? {} : { validJson }),\n };\n }\n catch {\n return { url, exists: false };\n }\n finally {\n controller.cleanup();\n }\n}\nasync function checkAgentResources(input) {\n const resources = [];\n for (const path of AGENT_RESOURCE_PATHS) {\n if (input.signal?.aborted)\n break;\n resources.push(await checkAgentResource({\n baseUrl: input.url,\n path,\n timeoutMs: input.timeoutMs,\n fetch: input.fetch,\n signal: input.signal,\n }));\n }\n return resources;\n}\nexport async function crawlSite(input, dependencies) {\n const deps = resolveCrawlSiteDependencies(dependencies);\n const config = normalizeCrawlConfig(input);\n const { searchMetricsLimit, analyticsLimit } = crawlProviderLimits(input);\n const signal = input.signal;\n let cancelled = Boolean(signal?.aborted);\n const isCancelled = () => cancelled || Boolean(signal?.aborted);\n const site = input.site;\n const origin = new URL(config.url).origin;\n const warnings = [];\n const queue = [];\n const visited = new Set();\n const queued = new Set();\n const discovered = new Set();\n const linkGraph = {};\n const fetchedAliases = new Map();\n const pages = [];\n const requests = [];\n const documentIndexes = new Map();\n const inFlight = new Set();\n const followLinks = config.mode === 'site';\n let queuedUrls = 0;\n let skippedUrls = 0;\n let robotsDeferredUrls = 0;\n let originBackpressureSkippedUrls = 0;\n let queueSafetySkippedUrls = 0;\n let failedUrls = 0;\n let observedInternalLinks = 0;\n let sitemapDiscovery;\n let externalLinkVerification;\n let statusEventChain = Promise.resolve();\n const emitStatus = (phase, event = {}) => {\n if (!input.onStatus)\n return;\n const statusEvent = {\n type: 'crawl_status',\n phase,\n generatedAt: deps.now().toISOString(),\n discoveredUrls: discovered.size,\n queuedUrls,\n pendingUrls: queue.length,\n inFlightUrls: inFlight.size,\n crawledUrls: pages.length,\n skippedUrls,\n failedUrls,\n observedInternalLinks,\n maxPages: config.maxPages,\n ...event,\n };\n statusEventChain = statusEventChain\n .then(() => input.onStatus?.(statusEvent))\n .catch(() => undefined);\n };\n const flushStatusEvents = async () => {\n await statusEventChain;\n };\n const renderer = config.js === 'off'\n ? undefined\n : createPageRenderer({ concurrency: config.concurrency });\n try {\n emitStatus('started', {\n url: config.url,\n message: `Started crawl for ${config.url}.`,\n });\n const aiSignals = isCancelled()\n ? undefined\n : await Promise.all([\n checkLlmsTxt({\n url: config.url,\n timeoutMs: config.timeoutMs,\n fetch: deps.fetch,\n signal,\n }),\n checkRobotsAiAccess({\n url: config.url,\n timeoutMs: config.timeoutMs,\n fetch: deps.fetch,\n signal,\n }),\n checkAgentResources({\n url: config.url,\n timeoutMs: config.timeoutMs,\n fetch: deps.fetch,\n signal,\n }),\n ]);\n const llmsTxt = aiSignals?.[0] ??\n {\n url: new URL('/llms.txt', config.url).toString(),\n exists: false,\n };\n const robotsTxt = aiSignals?.[1];\n const agentResources = aiSignals?.[2];\n cancelled = isCancelled();\n const enqueue = (value, depth) => {\n const normalized = normalizeUrl(value, config.url);\n if (!normalized) {\n skippedUrls += 1;\n emitStatus('url_skipped', {\n url: value,\n depth,\n reason: 'invalid_url',\n });\n return;\n }\n discovered.add(normalized);\n if (visited.has(normalized))\n return;\n if (queued.has(normalized)) {\n const existing = queue.find((item) => item.url === normalized);\n if (existing && depth < existing.depth)\n existing.depth = depth;\n queue.sort((left, right) => left.depth - right.depth ||\n (left.url < right.url ? -1 : left.url > right.url ? 1 : 0));\n return;\n }\n if (!sameOrigin(normalized, origin)) {\n skippedUrls += 1;\n emitStatus('url_skipped', {\n url: normalized,\n depth,\n reason: 'off_origin',\n });\n return;\n }\n if (isLikelyAsset(normalized)) {\n skippedUrls += 1;\n emitStatus('url_skipped', {\n url: normalized,\n depth,\n reason: 'asset_url',\n });\n return;\n }\n if (!passesFilters(normalized, config.include, config.exclude)) {\n skippedUrls += 1;\n emitStatus('url_skipped', {\n url: normalized,\n depth,\n reason: 'filtered_url',\n });\n return;\n }\n if (queue.length + visited.size + inFlight.size >= config.maxPages * 5) {\n skippedUrls += 1;\n queueSafetySkippedUrls += 1;\n emitStatus('url_skipped', {\n url: normalized,\n depth,\n reason: 'queue_safety_limit',\n });\n return;\n }\n queued.add(normalized);\n queuedUrls += 1;\n queue.push({ url: normalized, depth });\n queue.sort((left, right) => left.depth - right.depth ||\n (left.url < right.url ? -1 : left.url > right.url ? 1 : 0));\n emitStatus('url_queued', { url: normalized, depth });\n };\n if (config.mode !== 'sitemap') {\n const seeds = config.mode === 'list' ? config.urls : [config.url];\n for (const seed of seeds) {\n enqueue(seed, 0);\n }\n }\n if (!isCancelled() &&\n config.useSitemap &&\n (config.mode === 'site' || config.mode === 'sitemap')) {\n const sitemap = await sitemapSeeds({\n url: config.url,\n maxPages: config.maxPages,\n declaredSitemapUrls: robotsTxt?.sitemapUrls ?? [],\n warnings,\n fetchSitemapUrls: deps.fetchSitemapUrls,\n });\n for (const url of sitemap.urls) {\n enqueue(url, 0);\n }\n sitemapDiscovery = sitemap.discovery;\n }\n const nextQueueItem = () => {\n while (queue.length) {\n const item = queue.shift();\n if (!item)\n continue;\n const normalized = normalizeUrl(item.url, config.url);\n if (!normalized)\n continue;\n if (visited.has(normalized))\n continue;\n visited.add(normalized);\n return { url: normalized, depth: item.depth };\n }\n return undefined;\n };\n const startTask = (item) => {\n let task;\n task = {\n ...item,\n promise: deps\n .fetchPage(item.url, {\n js: config.js,\n refresh: config.refresh,\n timeoutMs: config.timeoutMs,\n rate: config.fetchRate,\n signal,\n respectRobots: config.respectRobots,\n renderer,\n })\n .then((result) => ({\n task,\n result,\n }))\n .catch((error) => ({\n task,\n result: {\n request: {\n requestedUrl: item.url,\n outcome: 'failure',\n failureKind: 'unknown',\n error: error instanceof Error ? error.message : String(error),\n extraction: 'not-applicable',\n },\n urls: [],\n warning: `${item.url}: ${error instanceof Error ? error.message : String(error)}`,\n },\n })),\n };\n inFlight.add(task);\n emitStatus('page_started', { url: item.url, depth: item.depth });\n };\n while (!isCancelled() &&\n (queue.length || inFlight.size) &&\n pages.length < config.maxPages) {\n while (!isCancelled() &&\n inFlight.size < config.concurrency &&\n pages.length + inFlight.size < config.maxPages) {\n const item = nextQueueItem();\n if (!item)\n break;\n startTask(item);\n }\n if (!inFlight.size)\n break;\n const next = await Promise.race([\n ...[...inFlight].map((item) => item.promise),\n ...(signal ? [cancellationRace(signal)] : []),\n ]);\n if (next === CRAWL_CANCELLED) {\n cancelled = true;\n break;\n }\n const { task, result } = next;\n inFlight.delete(task);\n const request = result.request ??\n (result.page\n ? observationFromPage(task.url, result.page)\n : {\n requestedUrl: task.url,\n outcome: 'failure',\n failureKind: 'unknown',\n error: result.warning ?? 'Crawler returned no page snapshot.',\n extraction: 'not-applicable',\n });\n requests.push(request);\n if (request.outcome === 'skipped') {\n skippedUrls += 1;\n if (request.reason === 'robots-deferred') {\n robotsDeferredUrls += 1;\n warnings.push(`${task.url}: crawl deferred because robots.txt availability is unknown.`);\n }\n if (request.reason === 'origin-backpressure') {\n originBackpressureSkippedUrls += 1;\n }\n emitStatus('page_skipped', {\n url: task.url,\n depth: task.depth,\n reason: request.reason,\n });\n continue;\n }\n if (result.warning) {\n warnings.push(result.warning);\n failedUrls += 1;\n emitStatus('page_failed', {\n url: task.url,\n depth: task.depth,\n reason: result.warning,\n });\n continue;\n }\n if (!result.page) {\n failedUrls += 1;\n emitStatus('page_failed', {\n url: task.url,\n depth: task.depth,\n reason: 'missing_page_snapshot',\n });\n continue;\n }\n const page = result.page;\n const finalUrl = normalizeUrl(page.finalUrl, config.url);\n if (!finalUrl) {\n failedUrls += 1;\n warnings.push(`${task.url}: invalid final URL ${page.finalUrl}`);\n emitStatus('page_failed', {\n url: task.url,\n depth: task.depth,\n reason: 'invalid_final_url',\n });\n continue;\n }\n page.url = finalUrl;\n page.finalUrl = finalUrl;\n page.crawlDepth = task.depth;\n const requestedUrl = normalizeUrl(task.url, config.url);\n if (requestedUrl && requestedUrl !== finalUrl) {\n fetchedAliases.set(requestedUrl, finalUrl);\n }\n page.contentAuditAllowed =\n !config.respectRobots || page.robotsTxt?.allowed !== false;\n const storeDocument = (urls) => {\n const sourceRequest = normalizeUrl(task.url, config.url) ?? task.url;\n const directlyRequested = sourceRequest === finalUrl;\n const normalizedLinks = urls\n .map((url) => normalizeUrl(url, finalUrl))\n .filter((url) => Boolean(url));\n const syncLinkEvidence = (target, links) => {\n const sortedLinks = [...links].sort((left, right) => left < right ? -1 : left > right ? 1 : 0);\n target.outgoingInternalCount = sortedLinks.length;\n target.sampleInternalLinks = sortedLinks.slice(0, 25);\n };\n const existing = documentIndexes.get(finalUrl);\n if (existing) {\n const links = new Set([...existing.links, ...normalizedLinks]);\n const minDepth = Math.min(existing.minDepth, task.depth);\n const replace = (!existing.directlyRequested && directlyRequested) ||\n (existing.directlyRequested === directlyRequested &&\n sourceRequest < existing.sourceRequest);\n if (replace) {\n page.crawlDepth = minDepth;\n pages[existing.index] = page;\n }\n else {\n const existingPage = pages[existing.index];\n if (existingPage)\n existingPage.crawlDepth = minDepth;\n }\n const retainedPage = pages[existing.index];\n if (retainedPage)\n syncLinkEvidence(retainedPage, links);\n observedInternalLinks += links.size - existing.links.size;\n documentIndexes.set(finalUrl, {\n ...existing,\n directlyRequested: existing.directlyRequested || directlyRequested,\n sourceRequest: replace ? sourceRequest : existing.sourceRequest,\n links,\n minDepth,\n });\n linkGraph[finalUrl] = [...links].sort((left, right) => left < right ? -1 : left > right ? 1 : 0);\n }\n else {\n const links = new Set(normalizedLinks);\n syncLinkEvidence(page, links);\n pages.push(page);\n observedInternalLinks += links.size;\n documentIndexes.set(finalUrl, {\n index: pages.length - 1,\n directlyRequested,\n sourceRequest,\n links,\n minDepth: task.depth,\n });\n linkGraph[finalUrl] = [...links].sort((left, right) => left < right ? -1 : left > right ? 1 : 0);\n }\n };\n if (config.respectRobots && page.robotsTxt?.allowed === false) {\n page.blocked = true;\n page.contentAuditAllowed = false;\n page.indexable = false;\n page.indexability = 'Robots.txt disallowed';\n page.declaredIndexability = 'robots-blocked';\n storeDocument([]);\n warnings.push(`${page.url}: skipped because robots.txt disallows it`);\n skippedUrls += 1;\n emitStatus('page_skipped', {\n url: page.url,\n depth: task.depth,\n statusCode: page.status,\n reason: 'robots_txt_disallowed',\n });\n continue;\n }\n storeDocument(result.urls);\n emitStatus('page_completed', {\n url: task.url,\n depth: task.depth,\n statusCode: page.status,\n });\n if (followLinks && task.depth < config.maxDepth) {\n for (const url of result.urls) {\n enqueue(url, task.depth + 1);\n }\n }\n }\n const resolvedLinkGraph = resolveLinkGraphAliases(linkGraph, fetchedAliases);\n const pageIndexes = new Map(pages.map((page, index) => [page.url, index]));\n const depths = pages.map((page) => page.crawlDepth ?? 0);\n for (let pass = 0; pass < pages.length; pass += 1) {\n let changed = false;\n for (const [sourceUrl, targets] of Object.entries(resolvedLinkGraph)) {\n const sourceIndex = pageIndexes.get(sourceUrl);\n if (sourceIndex === undefined)\n continue;\n for (const target of targets) {\n const targetIndex = pageIndexes.get(target);\n if (targetIndex === undefined)\n continue;\n const nextDepth = (depths[sourceIndex] ?? 0) + 1;\n if (nextDepth >= (depths[targetIndex] ?? Number.POSITIVE_INFINITY)) {\n continue;\n }\n depths[targetIndex] = nextDepth;\n changed = true;\n }\n }\n if (!changed)\n break;\n }\n for (const [index, page] of pages.entries()) {\n page.crawlDepth = depths[index];\n }\n cancelled = isCancelled();\n if (cancelled) {\n warnings.push('Crawl cancelled; returning a partial report.');\n emitStatus('cancelled', {\n url: config.url,\n message: 'Crawl cancelled; returning a partial report.',\n });\n }\n const pageLimitReached = pages.length >= config.maxPages && (queue.length > 0 || inFlight.size > 0);\n const sitemapEvidencePartial = sitemapDiscovery?.dataStatus === 'partial';\n const partial = cancelled ||\n failedUrls > 0 ||\n pageLimitReached ||\n robotsDeferredUrls > 0 ||\n originBackpressureSkippedUrls > 0 ||\n queueSafetySkippedUrls > 0 ||\n queue.length > 0 ||\n inFlight.size > 0 ||\n sitemapEvidencePartial;\n const failed = !cancelled &&\n pages.length === 0 &&\n requests.length > 0 &&\n requests.every((request) => request.outcome === 'failure');\n const requestEvidenceStatus = cancelled && inFlight.size > 0 ? 'partial' : 'available';\n const dataSources = await crawlDataSources({\n cancelled,\n site,\n ga4PropertyId: input.ga4PropertyId,\n pages,\n warnings,\n searchMetricsLimit,\n analyticsLimit,\n now: deps.now,\n queryPageMetrics: deps.queryPageMetrics,\n queryPageTopQuery: deps.queryPageTopQuery,\n queryPagesMetrics: deps.queryPagesMetrics,\n queryPagesTopQueries: deps.queryPagesTopQueries,\n queryPagesMetricsBatch: deps.queryPagesMetricsBatch,\n queryPagesTopQueriesBatch: deps.queryPagesTopQueriesBatch,\n fetchLandingPageValues: deps.fetchLandingPageValues,\n landingValueForUrl: deps.landingValueForUrl,\n });\n const sourceEvidencePartial = [\n dataSources.searchConsole.status,\n dataSources.analytics.status,\n ].some((status) => status === 'partial' || status === 'unavailable');\n const reportStatus = failed\n ? 'failed'\n : partial || sourceEvidencePartial\n ? 'partial'\n : 'completed';\n if (!cancelled && config.checkExternal) {\n emitStatus('external_links_started', {\n url: config.url,\n message: 'Started external link checks.',\n });\n externalLinkVerification = await verifyExternalLinks({\n pages,\n timeoutMs: config.timeoutMs,\n fetch: deps.fetch,\n signal,\n });\n warnings.push(...externalLinkVerification.warnings);\n emitStatus('external_links_completed', {\n url: config.url,\n message: 'Finished external link checks.',\n });\n }\n for (const page of pages) {\n if (!page.geo)\n continue;\n page.geo = {\n ...page.geo,\n hasLlmsTxt: llmsTxt.exists,\n llmsTxtUrl: llmsTxt.url,\n llmsTxtStatus: llmsTxt.status,\n };\n }\n const report = createCrawlReport({\n config,\n projectId: input.projectId,\n site,\n ga4PropertyId: input.ga4PropertyId,\n dataSources,\n pages,\n requests,\n requestEvidenceStatus,\n linkGraph: resolvedLinkGraph,\n ai: {\n llmsTxt,\n ...(robotsTxt ? { robotsTxt } : {}),\n ...(agentResources ? { agentResources } : {}),\n },\n ...(sitemapDiscovery ? { sitemapDiscovery } : {}),\n ...(externalLinkVerification ? { externalLinkVerification } : {}),\n status: reportStatus,\n warnings,\n caveats: crawlCaveats({\n cancelled,\n pageLimitReached,\n maxPages: config.maxPages,\n queueSafetySkippedUrls,\n originBackpressureSkippedUrls,\n }),\n stats: {\n discoveredUrls: discovered.size,\n queuedUrls,\n crawledUrls: pages.length,\n skippedUrls,\n failedUrls,\n observedInternalLinks,\n pageLimitReached,\n },\n });\n emitStatus('completed', {\n url: config.url,\n reportId: report.id,\n reportStatus: report.status,\n message: `Crawl ${report.status} with ${report.summary.totalPages} crawled pages.`,\n });\n await flushStatusEvents();\n return report;\n }\n finally {\n await renderer?.close();\n }\n}\n//# sourceMappingURL=site-crawl.js.map","function unique(values) {\n return [...new Set(values.filter((value) => Boolean(value)))];\n}\nfunction pct(part, total) {\n return total ? Math.round((part / total) * 100) : 0;\n}\nexport function entityReadiness(report) {\n const pages = report.pages.filter((page) => page.indexable && page.status < 400);\n const total = pages.length || 1;\n const schemaTypes = {};\n for (const page of pages) {\n for (const type of page.schemaTypes ?? []) {\n schemaTypes[type] = (schemaTypes[type] ?? 0) + 1;\n }\n }\n const entitySchemaPages = pages.filter((page) => page.schemaTypes?.some((type) => /^(Organization|LocalBusiness|Person|Product|WebSite)$/i.test(type)));\n const sameAsEvidence = pages\n .flatMap((page) => page.schemaSameAsEvidence ?? [])\n .filter((evidence) => evidence.subjectTypes.some((type) => /^(Organization|LocalBusiness|Person)$/i.test(type)));\n const siteSameAsEvidence = sameAsEvidence.filter((evidence) => evidence.subjectTypes.some((type) => /^(Organization|LocalBusiness)$/i.test(type)));\n const sameAs = unique(sameAsEvidence.map((evidence) => evidence.url));\n const sameAsByType = {};\n for (const evidence of sameAsEvidence) {\n for (const type of evidence.subjectTypes) {\n if (!/^(Organization|LocalBusiness|Person)$/i.test(type))\n continue;\n sameAsByType[type] = unique([...(sameAsByType[type] ?? []), evidence.url]);\n }\n }\n const socialProfiles = unique(pages.flatMap((page) => page.socialProfileLinks ?? []));\n const authors = unique(pages.map((page) => page.author));\n const authorPages = pages.filter((page) => page.author || page.geo?.hasAuthor);\n const datePages = pages.filter((page) => page.hasDate || page.geo?.hasDate);\n const titlePages = pages.filter((page) => page.title && page.h1);\n const evidenceChecks = [\n {\n coverage: pct(entitySchemaPages.length, total),\n check: {\n id: 'entity-schema',\n title: 'Entity schema is present',\n plainEnglish: `${pct(entitySchemaPages.length, total)}% of evaluated indexable pages include Organization, LocalBusiness, Person, Product, or WebSite schema.`,\n action: 'Add accurate entity schema to the homepage and key product, author, organization, and local pages.',\n evidence: { schemaTypes },\n urls: pages\n .filter((page) => !entitySchemaPages.includes(page))\n .slice(0, 10)\n .map((page) => page.finalUrl),\n },\n },\n {\n coverage: siteSameAsEvidence.length ? 100 : 0,\n check: {\n id: 'same-as',\n title: 'Site entity profiles are connected',\n plainEnglish: siteSameAsEvidence.length\n ? 'The crawl found sameAs links attached to Organization or LocalBusiness structured data.'\n : sameAs.length\n ? 'The crawl found Person sameAs links, but no Organization or LocalBusiness profile evidence for the site entity.'\n : socialProfiles.length\n ? 'The crawl found social-domain links, but they are not enough to prove official profile ownership.'\n : 'The crawl did not find entity-scoped sameAs evidence.',\n action: 'Connect official profiles with sameAs on Organization, Person, or LocalBusiness schema. Use only profiles you control.',\n evidence: {\n sameAs,\n siteSameAs: unique(siteSameAsEvidence.map((evidence) => evidence.url)),\n sameAsEvidence,\n unclassifiedSocialLinks: socialProfiles,\n },\n },\n },\n {\n coverage: Math.round((pct(authorPages.length, total) + pct(datePages.length, total)) / 2),\n check: {\n id: 'authority-freshness',\n title: 'Author and date signals observed',\n plainEnglish: `${pct(authorPages.length, total)}% of evaluated indexable pages expose an author signal and ${pct(datePages.length, total)}% expose a date signal.`,\n action: 'For editorial content, identify authors and show accurate published or modified dates when that information is useful to readers.',\n evidence: {\n authorCoverage: pct(authorPages.length, total),\n dateCoverage: pct(datePages.length, total),\n authors,\n },\n },\n },\n {\n coverage: pct(titlePages.length, total),\n check: {\n id: 'entity-naming',\n title: 'Title and H1 coverage observed',\n plainEnglish: `${pct(titlePages.length, total)}% of evaluated indexable pages have both a title and H1.`,\n action: 'Review pages missing either signal. Keep brand, product, and person names accurate wherever they appear.',\n },\n },\n ];\n const checks = evidenceChecks.map(({ coverage, check }) => ({\n ...check,\n status: 'info',\n evidence: { ...check.evidence, observedCoveragePercent: coverage },\n }));\n const dataStatus = report.status === 'completed' && pages.length > 0\n ? 'complete'\n : 'partial';\n return {\n reportId: report.id,\n url: report.config.url,\n generatedAt: report.generatedAt,\n dataStatus,\n evaluatedPages: pages.length,\n crawlPages: report.pages.length,\n assessment: 'evidence-only',\n headline: dataStatus === 'partial'\n ? 'Entity evidence is incomplete; treat these findings as scoped to the evaluated pages, not the whole site.'\n : 'Entity signals are reported as observations, not a ranking, visibility, or machine-understanding score.',\n caveats: [\n ...report.caveats,\n 'This report deliberately has no aggregate entity score. Add schema, authors, dates, and sameAs only where they accurately fit the page and a documented use case.',\n ...(dataStatus === 'partial'\n ? [\n `Entity coverage is based on ${pages.length} evaluated indexable page${pages.length === 1 ? '' : 's'} from a ${report.status} crawl.`,\n ]\n : []),\n ...(socialProfiles.length && !sameAs.length\n ? [\n 'Social-domain links are unclassified navigation evidence, not proof that the linked profiles are official.',\n ]\n : []),\n ],\n checks,\n entities: {\n schemaTypes,\n sameAs,\n sameAsByType,\n socialProfiles,\n authors,\n },\n };\n}\n//# sourceMappingURL=entity-readiness.js.map","import { explainRule, recommendationForRule, } from '../../rules.js';\nconst SEVERITY_SCORE = {\n high: 5000,\n medium: 1200,\n low: 100,\n};\nconst EFFORT_BY_CATEGORY = {\n canonical: 'medium',\n content: 'high',\n geo: 'medium',\n headings: 'low',\n images: 'medium',\n indexability: 'medium',\n international: 'low',\n metadata: 'low',\n mobile: 'low',\n response: 'medium',\n security: 'medium',\n social: 'low',\n 'structured-data': 'medium',\n};\nconst EFFORT_SCORE = {\n low: 60,\n medium: 30,\n high: 0,\n};\nconst AFFECTED_URL_WEIGHT = {\n high: 25,\n medium: 15,\n low: 2,\n};\nconst VALUE_WEIGHT = {\n high: 1,\n medium: 0.75,\n low: 0.15,\n};\nfunction matchesPattern(pattern, value) {\n if (!pattern.includes('*'))\n return value.includes(pattern);\n const parts = pattern.split('*');\n let position = 0;\n for (const part of parts) {\n if (!part)\n continue;\n const found = value.slice(position).indexOf(part);\n if (found === -1)\n return false;\n position += found + part.length;\n }\n return true;\n}\nfunction filteredIssues(report, filters) {\n if (filters.projectId && report.projectId !== filters.projectId)\n return [];\n return report.issues.filter((issue) => {\n if (filters.category && issue.category !== filters.category)\n return false;\n if (filters.severity && issue.severity !== filters.severity)\n return false;\n if (filters.url && !matchesPattern(filters.url, issue.url))\n return false;\n if ((filters.recommendation ?? 'fix') !== recommendationForRule(issue.ruleId)) {\n return false;\n }\n return true;\n });\n}\nfunction groupIssues(issues) {\n const groups = new Map();\n for (const issue of issues) {\n const existing = groups.get(issue.ruleId) ?? {\n ruleId: issue.ruleId,\n title: issue.title,\n category: issue.category,\n severity: issue.severity,\n count: 0,\n sampleUrls: [],\n };\n existing.count += 1;\n if (existing.sampleUrls.length < 10)\n existing.sampleUrls.push(issue.url);\n groups.set(issue.ruleId, existing);\n }\n return [...groups.values()];\n}\nfunction searchValueForGroup(report, urls) {\n const wanted = new Set(urls);\n const pages = report.pages.filter((page) => wanted.has(page.url) || wanted.has(page.finalUrl));\n const metrics = pages\n .map((page) => page.searchMetrics)\n .filter((item) => Boolean(item));\n const clicks = metrics.reduce((sum, item) => sum + item.clicks, 0);\n const impressions = metrics.reduce((sum, item) => sum + item.impressions, 0);\n const sessions = pages.reduce((sum, page) => sum + (page.analytics?.sessions ?? 0), 0);\n const totalUsers = pages.reduce((sum, page) => sum + (page.analytics?.totalUsers ?? 0), 0);\n const conversions = pages.reduce((sum, page) => sum + (page.analytics?.conversions ?? 0), 0);\n const avgPosition = metrics.length\n ? metrics.reduce((sum, item) => sum + item.position, 0) / metrics.length\n : undefined;\n return {\n searchVisibleUrls: metrics.length,\n clicks,\n impressions,\n sessions,\n totalUsers,\n conversions,\n avgPosition,\n };\n}\nfunction whyThisRanks(input, recommendation, searchStatus) {\n const visibility = input.searchVisibleUrls\n ? `${input.searchVisibleUrls} affected URLs have GSC visibility (${input.clicks} clicks, ${input.impressions} impressions).`\n : searchStatus && !['joined', 'none'].includes(searchStatus)\n ? `No joined GSC visibility is available for these affected URLs; Search Console evidence is ${searchStatus}.`\n : 'No affected URL has joined GSC visibility yet.';\n const analytics = input.sessions\n ? ` GA4 adds ${input.sessions} sessions and ${input.conversions} conversions from affected landing pages.`\n : '';\n const priority = recommendation === 'review'\n ? 'This is a review observation. Confirm it before scheduling implementation work.'\n : `This ranks as a fix. Severity is ${input.severity}; ${input.affectedUrls} URL${input.affectedUrls === 1 ? ' is' : 's are'} affected; estimated effort is ${input.effort}.`;\n return `${visibility}${analytics} ${priority}`;\n}\nfunction verificationCommand(report, severity) {\n return `seo crawl ${report.config.url} --severity ${severity} --max-pages ${Math.min(report.config.maxPages, 100)}`;\n}\nexport function topFixes(report, filters = {}) {\n const groups = groupIssues(filteredIssues(report, filters));\n const fixes = groups.map((group) => {\n const search = searchValueForGroup(report, group.sampleUrls);\n const effort = EFFORT_BY_CATEGORY[group.category] ?? 'medium';\n const scoreFactors = {\n severity: SEVERITY_SCORE[group.severity],\n affectedUrls: group.count,\n searchVisibleUrls: search.searchVisibleUrls,\n clicks: search.clicks,\n impressions: search.impressions,\n sessions: search.sessions,\n totalUsers: search.totalUsers,\n conversions: search.conversions,\n avgPosition: search.avgPosition,\n effort,\n effortScore: EFFORT_SCORE[effort],\n };\n const valueWeight = VALUE_WEIGHT[group.severity];\n const score = scoreFactors.severity +\n scoreFactors.affectedUrls * AFFECTED_URL_WEIGHT[group.severity] +\n scoreFactors.searchVisibleUrls * 100 * valueWeight +\n scoreFactors.clicks * 20 * valueWeight +\n (Math.min(scoreFactors.impressions, 10_000) / 25) * valueWeight +\n scoreFactors.sessions * 2 * valueWeight +\n scoreFactors.conversions * 100 * valueWeight +\n scoreFactors.effortScore;\n const rule = explainRule(group.ruleId);\n const recommendation = recommendationForRule(group.ruleId);\n return {\n ...group,\n recommendation,\n score: Math.round(score),\n scoreFactors,\n whyThisRanks: whyThisRanks(scoreFactors, recommendation, report.dataSources?.searchConsole.status),\n howToFix: rule?.howToFix ?? '',\n howToVerify: rule?.howToVerify ?? '',\n verification: {\n command: verificationCommand(report, group.severity),\n expected: rule?.howToVerify ?? '',\n },\n };\n });\n return fixes\n .sort((a, b) => b.score - a.score ||\n SEVERITY_SCORE[b.severity] - SEVERITY_SCORE[a.severity] ||\n b.count - a.count ||\n a.ruleId.localeCompare(b.ruleId))\n .slice(0, filters.limit ?? 10);\n}\nexport function reviewObservations(report, filters = {}) {\n return topFixes(report, { ...filters, recommendation: 'review' });\n}\n//# sourceMappingURL=top-fixes.js.map","import { effectiveSnippetControl, } from '../../robots-directives.js';\nconst ELIGIBILITY_RULES = new Set([\n 'connection_error',\n 'client_error',\n 'server_error',\n 'robots_blocked',\n 'noindex',\n 'x_robots_noindex',\n 'canonicalized_page',\n]);\nfunction matchingGeoGaps(report) {\n const eligibilityIssuesByUrl = new Map();\n for (const issue of report.issues) {\n if (!ELIGIBILITY_RULES.has(issue.ruleId))\n continue;\n const issues = eligibilityIssuesByUrl.get(issue.url) ?? [];\n issues.push({\n ruleId: issue.ruleId,\n title: issue.title,\n severity: issue.severity,\n });\n eligibilityIssuesByUrl.set(issue.url, issues);\n }\n return report.pages\n .map((page) => {\n const geo = page.geo ?? {\n semanticHtml: false,\n structuredData: false,\n hasAuthor: false,\n hasDate: false,\n questionHeadings: 0,\n structuredBlocks: 0,\n answerable: false,\n };\n const snippetEligibility = effectiveSnippetControl({\n metaRobots: page.metaRobots,\n xRobotsTag: page.xRobotsTag,\n });\n return {\n url: page.finalUrl,\n issueCount: eligibilityIssuesByUrl.get(page.url)?.length ?? 0,\n issues: eligibilityIssuesByUrl.get(page.url) ?? [],\n searchEligibility: {\n successfulHtmlResponse: page.status >= 200 &&\n page.status < 300 &&\n page.contentType?.toLowerCase().includes('text/html') === true,\n crawlAllowed: page.robotsTxt?.allowed ?? null,\n indexableCandidate: page.indexable,\n declaredIndexability: page.declaredIndexability,\n indexability: page.indexability,\n snippetEligibility,\n },\n observations: {\n semanticHtml: geo.semanticHtml,\n structuredData: geo.structuredData,\n hasAuthor: geo.hasAuthor,\n hasDate: geo.hasDate,\n questionHeadings: geo.questionHeadings,\n structuredBlocks: geo.structuredBlocks,\n answerable: geo.answerable,\n },\n };\n })\n .filter((gap) => gap.issueCount > 0 ||\n !gap.searchEligibility.successfulHtmlResponse ||\n gap.searchEligibility.crawlAllowed === false ||\n !gap.searchEligibility.indexableCandidate ||\n gap.searchEligibility.snippetEligibility.status !== 'not-restricted')\n .sort((a, b) => b.issueCount - a.issueCount || a.url.localeCompare(b.url));\n}\nfunction partialReasons(report) {\n const reasons = [];\n if (report.pages.length === 0)\n reasons.push('no-pages-evaluated');\n if (report.status !== 'completed')\n reasons.push('crawl-not-complete');\n if (report.requestEvidenceStatus === 'partial') {\n reasons.push('request-evidence-partial');\n }\n if (report.requestEvidenceStatus === 'unavailable') {\n reasons.push('request-evidence-unavailable');\n }\n if (report.summary.pageLimitReached)\n reasons.push('page-limit-reached');\n if (report.summary.skippedUrls > 0)\n reasons.push('skipped-urls');\n if (report.summary.failedRequests > 0)\n reasons.push('failed-requests');\n if (report.summary.extractionFailures > 0) {\n reasons.push('extraction-failures');\n }\n return reasons;\n}\nexport function geoGapsReport(report, filters = {}) {\n const matches = matchingGeoGaps(report);\n const limit = filters.limit ?? 50;\n const eligibilityGaps = matches.slice(0, limit);\n const reasons = partialReasons(report);\n const truncated = eligibilityGaps.length < matches.length;\n const dataStatus = report.pages.length\n ? reasons.length\n ? 'partial'\n : 'complete'\n : 'unavailable';\n return {\n schemaVersion: 1,\n dataStatus,\n source: {\n provider: 'seo-crawl',\n reportId: report.id,\n definitionId: report.definitionId,\n generatedAt: report.generatedAt,\n startUrl: report.config.url,\n crawlStatus: report.status,\n requestEvidenceStatus: report.requestEvidenceStatus,\n configuredMaxPages: report.config.maxPages,\n pageLimitReached: report.summary.pageLimitReached,\n discoveredUrls: report.summary.discoveredUrls,\n queuedUrls: report.summary.queuedUrls,\n crawledUrls: report.summary.crawledUrls,\n skippedUrls: report.summary.skippedUrls,\n failedRequests: report.summary.failedRequests,\n extractionFailures: report.summary.extractionFailures,\n partialReasons: reasons,\n },\n selection: {\n evaluatedPages: report.pages.length,\n totalMatchedPages: matches.length,\n returnedPages: eligibilityGaps.length,\n limit,\n truncated,\n },\n eligibilityGaps,\n warnings: report.warnings,\n caveats: [\n ...report.caveats,\n ...(truncated\n ? [\n `${matches.length - eligibilityGaps.length} matched pages were omitted by the output limit.`,\n ]\n : []),\n 'No detected restriction among evaluated pages does not prove indexing, selection, visibility, or citation.',\n ],\n };\n}\nexport function geoGaps(report, filters = {}) {\n return geoGapsReport(report, filters).eligibilityGaps;\n}\n//# sourceMappingURL=geo-gaps.js.map","function snapshotCaps(report) {\n return {\n maxPages: report.config.maxPages,\n maxDepth: report.config.maxDepth,\n timeoutMs: report.config.timeoutMs,\n searchConsolePageLimit: report.dataSources?.searchConsole.pageLimit,\n searchConsoleRetainedRowLimit: report.dataSources?.searchConsole.retainedRowLimit,\n analyticsRetainedRowLimit: report.dataSources?.analytics.retainedRowLimit,\n };\n}\nfunction requestScope(report) {\n return {\n startUrl: report.config.url,\n mode: report.config.mode,\n explicitUrls: report.config.urls,\n include: report.config.include,\n exclude: report.config.exclude,\n respectRobots: report.config.respectRobots,\n useSitemap: report.config.useSitemap,\n checkExternal: report.config.checkExternal,\n js: report.config.js,\n };\n}\nfunction sourceTruncated(report) {\n return Boolean(report.dataSources?.searchConsole.pageLimitReached ||\n report.dataSources?.searchConsole.retainedRowLimitReached ||\n report.dataSources?.analytics.retainedRowLimitReached);\n}\nfunction completenessReasons(report) {\n const reasons = [];\n if (report.status !== 'completed') {\n reasons.push(`report-status-${report.status}`);\n }\n if (report.summary.pageLimitReached)\n reasons.push('crawl-page-limit-reached');\n if (report.requestEvidenceStatus !== 'available') {\n reasons.push(`request-evidence-${report.requestEvidenceStatus}`);\n }\n if (report.summary.skippedUrls > 0)\n reasons.push('urls-skipped');\n if (report.summary.failedRequests > 0)\n reasons.push('requests-failed');\n if (report.summary.abortedRequests > 0)\n reasons.push('requests-aborted');\n if (report.summary.extractionFailures > 0) {\n reasons.push('document-extraction-failed');\n }\n if (report.dataSources?.searchConsole.pageLimitReached) {\n reasons.push('search-console-page-limit-reached');\n }\n if (report.dataSources?.searchConsole.retainedRowLimitReached) {\n reasons.push('search-console-row-limit-reached');\n }\n if (report.dataSources?.analytics.retainedRowLimitReached) {\n reasons.push('analytics-row-limit-reached');\n }\n if (report.dataSources?.searchConsole.status === 'partial' ||\n report.dataSources?.searchConsole.status === 'unavailable') {\n reasons.push(`search-console-${report.dataSources.searchConsole.status}`);\n }\n if (report.dataSources?.analytics.status === 'partial' ||\n report.dataSources?.analytics.status === 'unavailable') {\n reasons.push(`analytics-${report.dataSources.analytics.status}`);\n }\n return reasons;\n}\nfunction snapshotCompleteness(report) {\n const reasons = completenessReasons(report);\n return {\n status: report.status === 'failed'\n ? 'failed'\n : reasons.length\n ? 'partial'\n : 'complete',\n truncated: report.summary.pageLimitReached || sourceTruncated(report),\n reasons,\n requestEvidenceStatus: report.requestEvidenceStatus,\n pageLimitReached: report.summary.pageLimitReached,\n skippedUrls: report.summary.skippedUrls,\n failedRequests: report.summary.failedRequests,\n abortedRequests: report.summary.abortedRequests,\n extractionFailures: report.summary.extractionFailures,\n dataSources: report.dataSources,\n };\n}\nfunction snapshotInput(report) {\n const completeness = snapshotCompleteness(report);\n return {\n id: report.id,\n definitionId: report.definitionId,\n generatedAt: report.generatedAt,\n projectId: report.projectId,\n site: report.site,\n ga4PropertyId: report.ga4PropertyId,\n url: report.config.url,\n status: report.status,\n configHash: report.configHash,\n config: report.config,\n caps: snapshotCaps(report),\n requestScope: requestScope(report),\n requestEvidenceStatus: report.requestEvidenceStatus,\n dataSources: report.dataSources,\n warnings: report.warnings,\n caveats: report.caveats,\n completeness,\n summary: report.summary,\n };\n}\nfunction sameValue(left, right) {\n return JSON.stringify(left) === JSON.stringify(right);\n}\nfunction comparisonCaveats(input) {\n const caveats = [];\n if (!input.comparability.sameSite) {\n caveats.push('The reports use different site properties.');\n }\n if (!input.comparability.sameRequestScope) {\n caveats.push('The reports use different crawl request scopes; added and removed pages may reflect scope changes.');\n }\n if (!input.comparability.sameCaps) {\n caveats.push('The reports use different crawl or provider caps; compare retained coverage before interpreting deltas.');\n }\n if (!input.comparability.sameConfigHash &&\n input.comparability.sameRequestScope &&\n input.comparability.sameCaps) {\n caveats.push('The crawl configurations differ outside request scope and caps; inspect both config objects before attribution.');\n }\n if (!input.comparability.sameDefinitionId) {\n caveats.push('The reports use different crawl definitions; do not attribute every delta to the site or a release.');\n }\n if (input.before.completeness.status !== 'complete') {\n caveats.push(`The baseline report is ${input.before.completeness.status}: ${input.before.completeness.reasons.join(', ')}.`);\n }\n if (input.after.completeness.status !== 'complete') {\n caveats.push(`The newer report is ${input.after.completeness.status}: ${input.after.completeness.reasons.join(', ')}.`);\n }\n if (input.before.completeness.truncated ||\n input.after.completeness.truncated) {\n caveats.push('At least one report was truncated; page and issue deltas describe retained evidence only.');\n }\n if (input.after.generatedAt <= input.before.generatedAt) {\n caveats.push('The report labelled after is not newer than the report labelled before.');\n }\n if (input.before.warnings.length ||\n input.after.warnings.length ||\n input.before.caveats.length ||\n input.after.caveats.length) {\n caveats.push('One or both saved reports contain source warnings or caveats; inspect them before acting.');\n }\n return caveats;\n}\nexport function crawlComparisonMetadata(input) {\n const before = snapshotInput(input.before);\n const after = snapshotInput(input.after);\n const baseComparability = {\n sameDefinitionId: before.definitionId === after.definitionId,\n sameConfigHash: before.configHash === after.configHash,\n sameSite: before.site === after.site,\n sameStartUrl: before.url === after.url,\n sameMode: before.config.mode === after.config.mode,\n sameRequestScope: sameValue(before.requestScope, after.requestScope),\n sameCaps: sameValue(before.caps, after.caps),\n };\n const inputsMatch = Object.values(baseComparability).every(Boolean);\n const evidenceComplete = before.completeness.status === 'complete' &&\n after.completeness.status === 'complete';\n const comparability = {\n status: inputsMatch && evidenceComplete ? 'comparable' : 'review-required',\n ...baseComparability,\n };\n const status = before.completeness.status === 'failed' ||\n after.completeness.status === 'failed'\n ? 'failed'\n : before.completeness.status === 'partial' ||\n after.completeness.status === 'partial'\n ? 'partial'\n : 'complete';\n return {\n before,\n after,\n comparability,\n completeness: {\n status,\n truncated: before.completeness.truncated || after.completeness.truncated,\n before: before.completeness,\n after: after.completeness,\n },\n caveats: comparisonCaveats({ before, after, comparability }),\n };\n}\n//# sourceMappingURL=history-provenance.js.map","import { crawlComparisonMetadata, } from './history-provenance.js';\nfunction pagePick(page) {\n return {\n url: page.url,\n finalUrl: page.finalUrl,\n status: page.status,\n title: page.title,\n metaDescription: page.metaDescription,\n canonical: page.canonical,\n h1: page.h1,\n indexable: page.indexable,\n wordCount: page.wordCount,\n };\n}\nfunction statusBecameError(before, after) {\n return (before?.status ?? 200) < 400 && (after?.status ?? 200) >= 400;\n}\nfunction statusWasFixed(before, after) {\n return (before?.status ?? 200) >= 400 && (after?.status ?? 500) < 400;\n}\nfunction comparePage(before, after) {\n const changes = [];\n if (before.finalUrl !== after.finalUrl)\n changes.push('final_url');\n if (before.status !== after.status)\n changes.push('status');\n if (before.title !== after.title)\n changes.push('title');\n if (before.metaDescription !== after.metaDescription) {\n changes.push('meta_description');\n }\n if (before.canonical !== after.canonical)\n changes.push('canonical');\n if (before.h1 !== after.h1)\n changes.push('h1');\n if (before.indexable !== after.indexable)\n changes.push('indexability');\n if (before.contentHash !== after.contentHash)\n changes.push('content');\n if (before.wordCount !== after.wordCount)\n changes.push('word_count');\n return changes;\n}\nfunction pageChanges(beforeReport, afterReport) {\n const before = new Map(beforeReport.pages.map((page) => [page.url, page]));\n const after = new Map(afterReport.pages.map((page) => [page.url, page]));\n const changes = [];\n for (const [url, page] of after) {\n const previous = before.get(url);\n if (!previous) {\n changes.push({\n url,\n kind: 'added',\n changes: ['url_added'],\n after: pagePick(page),\n });\n continue;\n }\n const fields = comparePage(previous, page);\n if (fields.length) {\n changes.push({\n url,\n kind: 'changed',\n changes: fields,\n before: pagePick(previous),\n after: pagePick(page),\n });\n }\n }\n for (const [url, page] of before) {\n if (!after.has(url)) {\n changes.push({\n url,\n kind: 'removed',\n changes: ['url_removed'],\n before: pagePick(page),\n });\n }\n }\n return changes.sort((a, b) => {\n const rank = { changed: 0, added: 1, removed: 2 };\n return rank[a.kind] - rank[b.kind] || a.url.localeCompare(b.url);\n });\n}\nfunction issueMap(groups) {\n return new Map(groups.map((group) => [group.ruleId, group]));\n}\nfunction issueChanges(beforeReport, afterReport) {\n const before = issueMap(beforeReport.issueGroups);\n const after = issueMap(afterReport.issueGroups);\n const ruleIds = new Set([...before.keys(), ...after.keys()]);\n const changes = [];\n for (const ruleId of ruleIds) {\n const oldGroup = before.get(ruleId);\n const newGroup = after.get(ruleId);\n const oldCount = oldGroup?.count ?? 0;\n const newCount = newGroup?.count ?? 0;\n if (oldCount === newCount)\n continue;\n const group = newGroup ?? oldGroup;\n if (!group)\n continue;\n changes.push({\n ruleId,\n title: group.title,\n severity: group.severity,\n category: group.category,\n before: oldCount,\n after: newCount,\n delta: newCount - oldCount,\n });\n }\n return changes.sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta) || a.ruleId.localeCompare(b.ruleId));\n}\nfunction headline(summary) {\n if (summary.addedPages === 0 &&\n summary.removedPages === 0 &&\n summary.changedPages === 0 &&\n summary.issueDelta === 0) {\n return 'No material crawl changes were found between these saved reports.';\n }\n if (summary.newStatusErrors > 0 ||\n summary.issueGroupsWorse > summary.issueGroupsBetter) {\n return 'The newer crawl has regressions that should be reviewed before more SEO work.';\n }\n if (summary.fixedStatusErrors > 0 ||\n summary.issueGroupsBetter > summary.issueGroupsWorse) {\n return 'The newer crawl looks healthier, with some technical issues reduced or fixed.';\n }\n return 'The newer crawl changed, but the overall technical picture is broadly similar.';\n}\nfunction actions(input) {\n const actions = [];\n const newErrors = input.changes.filter((item) => statusBecameError(item.before, item.after));\n if (newErrors.length) {\n actions.push({\n title: 'New status errors appeared',\n plainEnglish: `${newErrors.length} URL now returns a 4xx or 5xx status when it did not before.`,\n action: 'Check deploys, redirects, routing, and canonical URL changes before changing content.',\n urls: newErrors.slice(0, 10).map((item) => item.url),\n });\n }\n const indexability = input.changes.filter((item) => item.changes.includes('indexability'));\n if (indexability.length) {\n actions.push({\n title: 'Indexability changed',\n plainEnglish: `${indexability.length} URL changed indexability state.`,\n action: 'Confirm noindex, robots, canonical, auth, and rendering changes were intentional.',\n urls: indexability.slice(0, 10).map((item) => item.url),\n });\n }\n const worseIssues = input.issues.filter((item) => item.delta > 0);\n if (worseIssues.length) {\n const issue = worseIssues[0];\n actions.push({\n title: issue?.title ?? 'Crawl issues increased',\n plainEnglish: `${issue?.ruleId ?? 'A rule'} increased by ${issue?.delta ?? 0} affected pages.`,\n action: 'Review the affected rule and compare changed templates before shipping more pages.',\n });\n }\n const titleChanges = input.changes.filter((item) => item.changes.includes('title'));\n if (titleChanges.length) {\n actions.push({\n title: 'Titles changed',\n plainEnglish: `${titleChanges.length} page title changed between snapshots.`,\n action: 'Compare title changes against top GSC queries before treating traffic movement as content decay.',\n urls: titleChanges.slice(0, 10).map((item) => item.url),\n });\n }\n if (!actions.length && input.summary.changedPages > 0) {\n actions.push({\n title: 'Review changed pages',\n plainEnglish: `${input.summary.changedPages} page changed without an obvious technical regression.`,\n action: 'Use the JSON output to inspect changed fields, then decide whether to annotate the change as an SEO test.',\n });\n }\n return actions;\n}\nexport function compareCrawlReports(input) {\n const metadata = crawlComparisonMetadata(input);\n const changes = pageChanges(input.before, input.after);\n const issues = issueChanges(input.before, input.after);\n const summary = {\n pageDelta: input.after.summary.totalPages - input.before.summary.totalPages,\n issueDelta: input.after.issues.length - input.before.issues.length,\n addedPages: changes.filter((item) => item.kind === 'added').length,\n removedPages: changes.filter((item) => item.kind === 'removed').length,\n changedPages: changes.filter((item) => item.kind === 'changed').length,\n newStatusErrors: changes.filter((item) => statusBecameError(item.before, item.after)).length,\n fixedStatusErrors: changes.filter((item) => statusWasFixed(item.before, item.after)).length,\n indexabilityFlips: changes.filter((item) => item.changes.includes('indexability')).length,\n titleChanges: changes.filter((item) => item.changes.includes('title'))\n .length,\n contentChanges: changes.filter((item) => item.changes.includes('content'))\n .length,\n issueGroupsWorse: issues.filter((item) => item.delta > 0).length,\n issueGroupsBetter: issues.filter((item) => item.delta < 0).length,\n };\n return {\n schemaVersion: 1,\n ...metadata,\n summary,\n headline: headline(summary),\n topActions: actions({ changes, issues, summary }),\n pageChanges: changes,\n issueChanges: issues,\n };\n}\n//# sourceMappingURL=history.js.map","function estimatedTokens(value) {\n return Math.ceil(value.length / 4);\n}\nfunction originHost(url) {\n return new URL(url).hostname.replace(/^www\\./, '');\n}\nfunction cleanTitle(page) {\n return (page.title ?? page.h1 ?? (new URL(page.finalUrl).pathname || page.finalUrl));\n}\nfunction sectionForPage(page) {\n const path = new URL(page.finalUrl).pathname.toLowerCase();\n if (/\\/(docs|documentation|guide|guides|help|kb|learn)\\b/.test(path)) {\n return 'Docs and guides';\n }\n if (/\\/(blog|articles|news|resources)\\b/.test(path))\n return 'Articles';\n if (/\\/(product|products|features|tools|solutions)\\b/.test(path)) {\n return 'Products and tools';\n }\n if (/\\/(pricing|plans)\\b/.test(path))\n return 'Pricing';\n if (/\\/(about|company|team|contact)\\b/.test(path))\n return 'Company';\n return 'Core pages';\n}\nfunction defaultExclude(url) {\n return /\\/(login|logout|cart|checkout|account|admin|wp-admin|search|tag|privacy|terms|cookie|legal)\\b/i.test(new URL(url).pathname);\n}\nfunction matchesPattern(value, patterns = []) {\n return patterns.some((pattern) => {\n if (!pattern.includes('*'))\n return value.includes(pattern);\n const parts = pattern.split('*');\n let cursor = 0;\n for (const part of parts) {\n if (!part)\n continue;\n const found = value.slice(cursor).indexOf(part);\n if (found === -1)\n return false;\n cursor += found + part.length;\n }\n return true;\n });\n}\nfunction candidatePages(report, options = {}) {\n return report.pages\n .filter((page) => page.indexable && page.status < 400)\n .filter((page) => !defaultExclude(page.finalUrl))\n .filter((page) => !matchesPattern(page.finalUrl, options.exclude))\n .sort((a, b) => (b.internalLinkAuthorityScore ?? 0) -\n (a.internalLinkAuthorityScore ?? 0) ||\n (b.wordCount ?? 0) - (a.wordCount ?? 0) ||\n a.finalUrl.localeCompare(b.finalUrl));\n}\nexport function auditLlmsTxt(report) {\n const llmsTxt = report.ai?.llmsTxt;\n const pages = candidatePages(report);\n const issues = [];\n if (pages.length < 3) {\n issues.push({\n id: 'thin-llms-inventory',\n severity: 'low',\n title: 'The crawl has a small llms.txt inventory',\n plainEnglish: 'There are very few indexable candidate pages to include in llms.txt.',\n action: 'If you choose to generate the optional file, run a deeper crawl or sitemap crawl first.',\n evidence: { candidatePages: pages.length },\n });\n }\n return {\n reportId: report.id,\n url: report.config.url,\n exists: Boolean(llmsTxt?.exists),\n llmsTxtUrl: llmsTxt?.url ?? new URL('/llms.txt', report.config.url).toString(),\n status: llmsTxt?.status,\n optional: true,\n googleSearchImpact: 'none',\n guidanceUrl: 'https://developers.google.com/search/updates#clarifying-guidance-on-llms-txt-files',\n headline: llmsTxt?.exists\n ? 'An optional llms.txt file is present. It has no Google Search visibility impact.'\n : 'No llms.txt file was found. This is not an SEO issue and requires no action.',\n issues,\n recommendedPages: pages.slice(0, 25).map((page) => ({\n url: page.finalUrl,\n title: page.title,\n section: sectionForPage(page),\n reason: (page.internalLinkAuthorityScore ?? 0) > 0\n ? 'High internal link authority in this crawl.'\n : 'Indexable page with useful content signals.',\n })),\n };\n}\nexport function generateLlmsTxt(report, options = {}) {\n const maxUrls = options.maxUrls ?? 250;\n const tokenBudget = options.tokenBudget ?? 12_000;\n const title = options.title ?? originHost(report.config.url);\n const description = options.description ??\n `Curated entry points for agents reading ${originHost(report.config.url)}.`;\n const pages = candidatePages(report, options).slice(0, maxUrls);\n const sections = new Map();\n for (const page of pages) {\n const section = sectionForPage(page);\n sections.set(section, [...(sections.get(section) ?? []), page]);\n }\n const lines = [`# ${title}`, '', `> ${description}`, ''];\n let includedUrls = 0;\n const counts = {};\n for (const [sectionName, sectionPages] of sections) {\n const sectionLines = [`## ${sectionName}`, ''];\n let sectionCount = 0;\n for (const page of sectionPages) {\n const title = cleanTitle(page).replace(/\\]/g, '\\\\]');\n const note = page.metaDescription\n ? ` - ${page.metaDescription.replace(/\\s+/g, ' ').slice(0, 160)}`\n : '';\n const line = `- [${title}](${page.finalUrl})${note}`;\n const projected = [...lines, ...sectionLines, line, ''].join('\\n');\n if (estimatedTokens(projected) > tokenBudget && includedUrls > 0)\n break;\n sectionLines.push(line);\n sectionCount += 1;\n includedUrls += 1;\n }\n if (!sectionCount)\n break;\n sectionLines.push('');\n lines.push(...sectionLines);\n counts[sectionName] = sectionCount;\n if (sectionCount < sectionPages.length)\n break;\n }\n lines.push('## Notes', '', '- Optional metadata for agents and services that explicitly support llms.txt.', '- [Google Search guidance](https://developers.google.com/search/updates#clarifying-guidance-on-llms-txt-files) says llms.txt does not affect visibility or rankings.', `- Generated from crawl report ${report.id}.`, `- Crawl generated at ${report.generatedAt}.`);\n if (report.caveats.length) {\n lines.push(...report.caveats.map((caveat) => `- Caveat: ${caveat}`));\n }\n const content = `${lines.join('\\n')}\\n`;\n return {\n content,\n includedUrls,\n estimatedTokens: estimatedTokens(content),\n sections: counts,\n };\n}\n//# sourceMappingURL=llms.js.map","import { createHash } from 'node:crypto';\nimport { SeoError } from '../../errors.js';\nexport const OKF_DEFAULT_CONCEPTS = 500;\nexport const OKF_MAX_CONCEPTS = 5_000;\nfunction compareText(left, right) {\n const leftPoints = [...left].map((value) => value.codePointAt(0) ?? 0);\n const rightPoints = [...right].map((value) => value.codePointAt(0) ?? 0);\n for (let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index++) {\n const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);\n if (difference)\n return difference;\n }\n return leftPoints.length - rightPoints.length;\n}\nfunction conceptPath(value) {\n const cleaned = value\n .toLowerCase()\n .replace(/^https?:\\/\\//, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n const readable = cleaned.slice(0, 62) || 'page';\n const identity = createHash('sha256').update(value).digest('hex').slice(0, 12);\n return `concepts/${readable}-${identity}.md`;\n}\nfunction frontmatter(values) {\n const lines = ['---'];\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined)\n continue;\n if (Array.isArray(value)) {\n if (!value.length)\n continue;\n lines.push(`${key}:`);\n for (const item of value)\n lines.push(` - ${JSON.stringify(item)}`);\n }\n else {\n lines.push(`${key}: ${JSON.stringify(value)}`);\n }\n }\n lines.push('---', '');\n return lines.join('\\n');\n}\nfunction singleLine(value) {\n return [...value]\n .map((character) => {\n const codePoint = character.codePointAt(0) ?? 0;\n return codePoint < 32 || codePoint === 127 ? ' ' : character;\n })\n .join('')\n .replace(/\\s+/g, ' ')\n .trim();\n}\nfunction pageTitle(page) {\n return singleLine(page.title ?? page.h1 ?? (new URL(page.finalUrl).pathname || page.finalUrl));\n}\nfunction pageType(page) {\n const path = new URL(page.finalUrl).pathname.toLowerCase();\n if (page.schemaTypes?.includes('Article') ||\n /\\/(blog|article|news)\\b/.test(path)) {\n return 'article';\n }\n if (page.schemaTypes?.some((type) => /Product|Service|SoftwareApplication/i.test(type))) {\n return 'product';\n }\n if (/\\/(about|company|team|contact)\\b/.test(path))\n return 'organization';\n return 'webpage';\n}\nfunction conceptFile(page) {\n const title = pageTitle(page);\n const body = [\n frontmatter({\n type: pageType(page),\n title,\n url: page.finalUrl,\n status: page.status,\n indexable: page.indexable,\n canonical: page.canonical,\n schemaTypes: page.schemaTypes,\n sameAs: page.schemaSameAs,\n }),\n `# ${title}`,\n '',\n page.metaDescription\n ? `Summary: ${singleLine(page.metaDescription)}`\n : undefined,\n page.contentSample\n ? `Extract: ${singleLine(page.contentSample)}`\n : undefined,\n '',\n '## Signals',\n '',\n `- URL: ${page.finalUrl}`,\n `- Status: ${page.status}`,\n `- Indexable: ${page.indexable ? 'yes' : 'no'}`,\n `- Word count: ${page.wordCount}`,\n `- Structured data: ${(page.schemaTypes ?? []).join(', ') || 'none detected'}`,\n `- Internal inlinks: ${page.internalInlinkCount ?? 0}`,\n '',\n '# Citations',\n '',\n `- [Source page](<${page.finalUrl}>)`,\n '',\n ].filter((line) => line !== undefined);\n return {\n path: conceptPath(page.finalUrl),\n content: body.join('\\n'),\n };\n}\nexport function okfConceptLimit(value) {\n if (value === undefined)\n return OKF_DEFAULT_CONCEPTS;\n if (!Number.isInteger(value) || value < 1 || value > OKF_MAX_CONCEPTS) {\n throw new SeoError('INVALID_INPUT', `maxConcepts must be a whole number between 1 and ${OKF_MAX_CONCEPTS}.`);\n }\n return value;\n}\nfunction okfTitle(value, report) {\n const title = singleLine(value ?? new URL(report.config.url).hostname.replace(/^www\\./, ''));\n if (!title || title.length > 200) {\n throw new SeoError('INVALID_INPUT', 'OKF title must contain 1 to 200 characters on one line.');\n }\n return title;\n}\nfunction selectedOkfPages(report, requestedLimit) {\n const limit = okfConceptLimit(requestedLimit);\n const eligible = report.pages\n .filter((page) => page.indexable &&\n page.status >= 200 &&\n page.status < 300 &&\n !page.blocked &&\n !page.error)\n .sort((left, right) => (right.searchMetrics?.clicks ?? 0) -\n (left.searchMetrics?.clicks ?? 0) ||\n (right.searchMetrics?.impressions ?? 0) -\n (left.searchMetrics?.impressions ?? 0) ||\n (right.internalLinkAuthorityScore ?? 0) -\n (left.internalLinkAuthorityScore ?? 0) ||\n (right.internalInlinkCount ?? 0) - (left.internalInlinkCount ?? 0) ||\n compareText(left.finalUrl, right.finalUrl));\n const unique = new Map();\n for (const page of eligible) {\n if (!unique.has(page.finalUrl))\n unique.set(page.finalUrl, page);\n }\n const uniquePages = [...unique.values()];\n return {\n pages: uniquePages.slice(0, limit),\n sourcePages: report.pages.length,\n eligiblePages: uniquePages.length,\n duplicateFinalUrls: eligible.length - uniquePages.length,\n limit,\n };\n}\nexport function buildOkfBundle(report, options = {}) {\n const title = okfTitle(options.title, report);\n const selected = selectedOkfPages(report, options.maxConcepts);\n const pages = selected.pages;\n const generatedCaveats = [\n ...report.caveats,\n ...(report.status !== 'completed'\n ? [\n `Source crawl status is ${report.status}; the bundle may not represent the complete site inventory.`,\n ]\n : []),\n ...(selected.duplicateFinalUrls\n ? [\n `${selected.duplicateFinalUrls} duplicate final URL${selected.duplicateFinalUrls === 1 ? ' was' : 's were'} deduplicated before concept export.`,\n ]\n : []),\n ...(selected.eligiblePages > pages.length\n ? [\n `OKF selected ${pages.length} of ${selected.eligiblePages} eligible 2xx indexable pages using observed search clicks, impressions, internal authority, inlinks, and a stable URL tie-break.`,\n ]\n : []),\n ];\n const concepts = pages.map(conceptFile);\n const files = [\n {\n path: 'index.md',\n content: [\n frontmatter({ okf: '0.1', type: 'index', title }),\n `# ${title}`,\n '',\n `Source crawl: ${report.id}`,\n `Generated from: ${report.config.url}`,\n '',\n '## Contents',\n '',\n '- [Concepts](concepts/index.md)',\n '- [Inventory](inventory/pages.md)',\n '- [Graph](graph/links.md)',\n '- [Caveats](caveats.md)',\n '- [Log](log.md)',\n '',\n ].join('\\n'),\n },\n {\n path: 'log.md',\n content: [\n '# Log',\n '',\n `- ${report.generatedAt}: Generated OKF bundle from crawl report ${report.id}.`,\n '',\n ].join('\\n'),\n },\n {\n path: 'concepts/index.md',\n content: [\n '# Concepts',\n '',\n ...concepts.map((file) => `- [${file.path.replace(/^concepts\\//, '')}](${file.path.replace(/^concepts\\//, '')})`),\n '',\n ].join('\\n'),\n },\n {\n path: 'inventory/pages.md',\n content: [\n frontmatter({ type: 'inventory', title: 'Selected concept pages' }),\n '# Selected Concept Pages',\n '',\n '| URL | Status | Indexable | Title |',\n '| --- | ---: | --- | --- |',\n ...pages.map((page) => `| ${page.finalUrl} | ${page.status} | ${page.indexable ? 'yes' : 'no'} | ${singleLine(page.title ?? '').replace(/\\|/g, '\\\\|')} |`),\n '',\n '# Citations',\n '',\n `- [Crawl start URL](${report.config.url})`,\n '',\n ].join('\\n'),\n },\n {\n path: 'graph/links.md',\n content: [\n frontmatter({ type: 'graph', title: 'Internal link graph' }),\n '# Internal Link Graph',\n '',\n ...pages.flatMap((page) => [\n `## ${pageTitle(page)}`,\n '',\n `Source: ${page.finalUrl}`,\n '',\n ...(page.sampleInternalLinks ?? [])\n .slice(0, 25)\n .map((url) => `- ${url}`),\n '',\n ]),\n '# Citations',\n '',\n `- [Crawl start URL](${report.config.url})`,\n '',\n ].join('\\n'),\n },\n {\n path: 'caveats.md',\n content: [\n frontmatter({ type: 'caveats', title: 'Caveats' }),\n '# Caveats',\n '',\n ...(generatedCaveats.length\n ? generatedCaveats\n : ['No crawl caveats were reported.']).map((caveat) => `- ${caveat}`),\n ...(report.warnings.length\n ? [\n '',\n '## Warnings',\n '',\n ...report.warnings.map((warning) => `- ${warning}`),\n ]\n : []),\n '',\n '# Citations',\n '',\n `- [Crawl start URL](${report.config.url})`,\n '',\n ].join('\\n'),\n },\n ...concepts,\n ];\n return {\n schemaVersion: 1,\n reportId: report.id,\n sourceUrl: report.config.url,\n generatedAt: report.generatedAt,\n crawlStatus: report.status,\n rootTitle: title,\n files,\n conceptCount: concepts.length,\n selection: {\n sourcePages: selected.sourcePages,\n eligiblePages: selected.eligiblePages,\n duplicateFinalUrls: selected.duplicateFinalUrls,\n selectedPages: pages.length,\n limitedPages: selected.eligiblePages - pages.length,\n limit: selected.limit,\n order: 'search-clicks-impressions-internal-authority-inlinks-url',\n },\n caveats: generatedCaveats,\n warnings: report.warnings,\n };\n}\nfunction hasFrontmatter(content) {\n return /^---\\n[\\s\\S]+?\\n---\\n/.test(content);\n}\nfunction frontmatterHasType(content) {\n const match = content.match(/^---\\n([\\s\\S]+?)\\n---\\n/);\n return Boolean(match?.[1]?.match(/^type:\\s*.+$/m));\n}\nfunction frontmatterString(content, key) {\n const match = content.match(new RegExp(`^${key}:\\\\s*(.+)$`, 'm'))?.[1];\n if (!match)\n return undefined;\n try {\n const value = JSON.parse(match);\n return typeof value === 'string' ? value : undefined;\n }\n catch {\n return undefined;\n }\n}\nfunction isReserved(path) {\n return (path.endsWith('/index.md') ||\n path === 'index.md' ||\n path.endsWith('/log.md') ||\n path === 'log.md');\n}\nexport function validateOkfFiles(files) {\n const issues = [];\n const pathCounts = new Map();\n for (const file of files) {\n pathCounts.set(file.path, (pathCounts.get(file.path) ?? 0) + 1);\n if (!file.path ||\n file.path.startsWith('/') ||\n file.path.split('/').some((part) => part === '..' || part === '')) {\n issues.push({\n path: file.path || '(empty)',\n severity: 'error',\n message: 'File paths must be safe relative paths.',\n });\n }\n }\n for (const [path, count] of pathCounts) {\n if (count > 1) {\n issues.push({\n path,\n severity: 'error',\n message: `File path is duplicated ${count} times.`,\n });\n }\n }\n const byPath = new Map(files.map((file) => [file.path, file]));\n const requiredPaths = [\n 'index.md',\n 'log.md',\n 'concepts/index.md',\n 'inventory/pages.md',\n 'graph/links.md',\n 'caveats.md',\n ];\n for (const path of requiredPaths) {\n if (byPath.has(path))\n continue;\n issues.push({\n path,\n severity: 'error',\n message: 'Required seo OKF bundle file is missing.',\n });\n }\n const root = byPath.get('index.md');\n if (root &&\n (frontmatterString(root.content, 'okf') !== '0.1' ||\n frontmatterString(root.content, 'type') !== 'index')) {\n issues.push({\n path: 'index.md',\n severity: 'error',\n message: 'Root frontmatter must declare okf \"0.1\" and type \"index\".',\n });\n }\n for (const file of files.filter((item) => item.path.endsWith('.md'))) {\n if (!file.content.trim()) {\n issues.push({\n path: file.path,\n severity: 'error',\n message: 'Markdown files must not be empty.',\n });\n }\n if (!isReserved(file.path)) {\n if (!hasFrontmatter(file.content)) {\n issues.push({\n path: file.path,\n severity: 'error',\n message: 'Concept files need YAML frontmatter.',\n });\n }\n else if (!frontmatterHasType(file.content)) {\n issues.push({\n path: file.path,\n severity: 'error',\n message: 'Concept frontmatter needs a non-empty type field.',\n });\n }\n if (file.path.startsWith('concepts/')) {\n const url = frontmatterString(file.content, 'url');\n let validUrl = false;\n try {\n validUrl = Boolean(url && ['http:', 'https:'].includes(new URL(url).protocol));\n }\n catch {\n validUrl = false;\n }\n if (!validUrl) {\n issues.push({\n path: file.path,\n severity: 'error',\n message: 'Concept frontmatter needs a valid HTTP(S) url.',\n });\n }\n }\n if (!/\\n# Citations\\n/i.test(file.content)) {\n issues.push({\n path: file.path,\n severity: 'warning',\n message: 'Files with claims should include a # Citations section.',\n });\n }\n }\n }\n const conceptIndex = byPath.get('concepts/index.md')?.content ?? '';\n for (const file of files.filter((item) => item.path.startsWith('concepts/') && !isReserved(item.path))) {\n const relative = file.path.replace(/^concepts\\//, '');\n if (!conceptIndex.includes(`](${relative})`)) {\n issues.push({\n path: file.path,\n severity: 'error',\n message: 'Concept is missing from concepts/index.md.',\n });\n }\n }\n const concepts = files.filter((file) => file.path.startsWith('concepts/') && !isReserved(file.path)).length;\n return {\n valid: !issues.some((issue) => issue.severity === 'error'),\n files: files.length,\n concepts,\n issues,\n };\n}\nexport function explainOkfValidation(validation) {\n const errors = validation.issues.filter((issue) => issue.severity === 'error');\n const warnings = validation.issues.filter((issue) => issue.severity === 'warning');\n return {\n title: 'OKF bundle',\n valid: validation.valid,\n summary: validation.valid\n ? `This bundle passes seo OKF checks with ${validation.concepts} concept files.`\n : `This OKF bundle has ${errors.length} validation error${errors.length === 1 ? '' : 's'}.`,\n files: validation.files,\n concepts: validation.concepts,\n errors: errors.length,\n warnings: warnings.length,\n nextActions: validation.valid\n ? [\n 'Review concept quality and publish the bundle where agents can fetch it.',\n ]\n : errors.slice(0, 5).map((issue) => `${issue.path}: ${issue.message}`),\n };\n}\n//# sourceMappingURL=okf.js.map","import { z } from 'zod';\nimport { listRules } from '../../rules.js';\nexport const crawlerRuleSeveritySchema = z.enum(['low', 'medium', 'high']);\nexport const crawlerRuleRecommendationSchema = z.enum(['fix', 'review']);\nexport const crawlerRuleCategorySchema = z.enum([\n 'canonical',\n 'content',\n 'response',\n 'headings',\n 'images',\n 'indexability',\n 'international',\n 'links',\n 'metadata',\n 'mobile',\n 'performance',\n 'security',\n 'social',\n 'structured-data',\n 'geo',\n]);\nexport const crawlerRuleIdSchema = z.enum(listRules().map((rule) => rule.id));\nexport const crawlerRuleInfoSchema = z.object({\n id: crawlerRuleIdSchema,\n title: z.string(),\n category: crawlerRuleCategorySchema,\n defaultSeverity: crawlerRuleSeveritySchema,\n recommendation: crawlerRuleRecommendationSchema,\n whyItMatters: z.string(),\n howToFix: z.string(),\n impactIfIgnored: z.string(),\n howToVerify: z.string(),\n agentHints: z\n .object({\n evidenceFields: z.array(z.string()).optional(),\n suggestedCommands: z.array(z.string()).optional(),\n })\n .optional(),\n});\nconst searchMetricsSchema = z.object({\n clicks: z.number(),\n impressions: z.number(),\n ctr: z.number(),\n position: z.number(),\n});\nconst analyticsSchema = z.object({\n sessions: z.number(),\n totalUsers: z.number(),\n conversions: z.number(),\n});\nconst geoSignalsSchema = z.object({\n semanticHtml: z.boolean(),\n structuredData: z.boolean(),\n hasAuthor: z.boolean(),\n hasDate: z.boolean(),\n questionHeadings: z.number().int(),\n listCount: z.number().int().optional(),\n tableCount: z.number().int().optional(),\n structuredBlocks: z.number().int(),\n answerable: z.boolean(),\n hasFaqSchema: z.boolean().optional(),\n hasQapageSchema: z.boolean().optional(),\n hasLlmsTxt: z.boolean().optional(),\n llmsTxtUrl: z.string().url().optional(),\n llmsTxtStatus: z.number().int().optional(),\n});\nconst googleRichResultAssessmentStatusSchema = z.enum([\n 'no-required-properties',\n 'required-properties-observed',\n 'missing-required-properties',\n 'retired',\n 'not-assessed',\n]);\nconst googleRichResultStatusCountsSchema = z.object({\n 'no-required-properties': z.number().int().nonnegative(),\n 'required-properties-observed': z.number().int().nonnegative(),\n 'missing-required-properties': z.number().int().nonnegative(),\n retired: z.number().int().nonnegative(),\n 'not-assessed': z.number().int().nonnegative(),\n});\nconst googleRichResultAssessmentSchema = z.object({\n format: z.enum(['json-ld', 'microdata', 'rdfa']),\n block: z.number().int().nonnegative().optional(),\n path: z.string(),\n schemaType: z.enum([\n 'Article',\n 'BlogPosting',\n 'NewsArticle',\n 'Product',\n 'BreadcrumbList',\n 'FAQPage',\n ]),\n feature: z.enum(['article', 'product-snippet', 'breadcrumb', 'faq']),\n status: googleRichResultAssessmentStatusSchema,\n observedProperties: z.array(z.string()),\n missingRequiredProperties: z.array(z.string()),\n limitations: z.array(z.string()),\n documentationUrl: z.string().url(),\n});\nconst canonicalStatusSchema = z.enum([\n 'missing',\n 'single',\n 'duplicate',\n 'conflicting',\n 'outside-head-only',\n 'invalid',\n]);\nconst renderingDocumentSnapshotSchema = z.object({\n title: z.string().optional(),\n metaDescription: z.string().optional(),\n canonical: z.object({\n status: canonicalStatusSchema,\n url: z.string().url().optional(),\n }),\n robots: z.object({\n meta: z.string().optional(),\n googlebot: z.string().optional(),\n http: z.string().optional(),\n }),\n headings: z.array(z.object({ level: z.number().int(), text: z.string() })),\n links: z.object({\n total: z.number().int().nonnegative(),\n internal: z.number().int().nonnegative(),\n external: z.number().int().nonnegative(),\n fingerprint: z.string(),\n }),\n content: z.object({\n characters: z.number().int().nonnegative(),\n wordCount: z.number().int().nonnegative(),\n fingerprint: z.string(),\n }),\n structuredData: z.object({\n blocks: z.number().int().nonnegative(),\n formats: z.array(z.enum(['json-ld', 'microdata', 'rdfa'])),\n schemaTypes: z.array(z.string()),\n }),\n});\nconst renderingDocumentDifferenceSchema = z.object({\n raw: renderingDocumentSnapshotSchema,\n rendered: renderingDocumentSnapshotSchema,\n changed: z.array(z.enum([\n 'title',\n 'metaDescription',\n 'canonical',\n 'robots',\n 'headings',\n 'links',\n 'content',\n 'structuredData',\n ])),\n});\nexport const crawlPageSnapshotSchema = z.object({\n url: z.string().url(),\n finalUrl: z.string().url(),\n status: z.number().int(),\n contentType: z.string().optional(),\n responseHeaders: z.record(z.string(), z.string()).optional(),\n responseTimeMs: z.number().optional(),\n sizeBytes: z.number().int().optional(),\n usedJs: z.boolean().optional(),\n fetchSource: z.enum(['cache', 'network', 'rendered']).optional(),\n cacheState: z.enum(['hit', 'miss', 'bypass']).optional(),\n fetchDiagnostics: z\n .object({\n source: z.enum(['cache', 'network', 'rendered']),\n cache: z.enum(['hit', 'miss', 'bypass']),\n fetched: z.boolean(),\n rendered: z.boolean(),\n blocked: z.boolean(),\n durationMs: z.number(),\n retries: z.number().int(),\n rateLimit: z.object({\n host: z.string(),\n concurrency: z.number().int(),\n intervalCap: z.number().int(),\n intervalMs: z.number().int(),\n }),\n backpressure: z\n .object({\n host: z.string(),\n status: z.enum(['ok', 'slowed', 'stopped']),\n reason: z.string().optional(),\n delayMs: z.number(),\n cooldownUntil: z.string().optional(),\n consecutiveSlow: z.number().int(),\n consecutiveBlocked: z.number().int(),\n consecutiveErrors: z.number().int(),\n recentP95Ms: z.number().optional(),\n })\n .optional(),\n robotsTxt: z\n .object({\n url: z.string().url(),\n cache: z.enum(['hit', 'miss', 'bypass']),\n allowed: z.boolean().nullable(),\n availability: z.enum([\n 'available',\n 'absent',\n 'access-blocked',\n 'rate-limited',\n 'unreachable',\n ]),\n status: z.number().int().optional(),\n error: z.string().optional(),\n })\n .optional(),\n redirectChain: z\n .array(z.object({\n url: z.string().url(),\n status: z.number().int(),\n location: z.string().url().optional(),\n }))\n .optional(),\n rendering: z\n .object({\n mode: z.enum(['auto', 'on', 'off']),\n status: z.enum([\n 'not-requested',\n 'not-needed',\n 'skipped',\n 'rendered',\n 'unavailable',\n 'failed',\n ]),\n raw: z\n .object({\n source: z.enum(['cache', 'network']),\n cache: z.enum(['hit', 'miss', 'bypass']),\n url: z.string().url(),\n finalUrl: z.string().url(),\n status: z.number().int(),\n })\n .optional(),\n documentDifference: renderingDocumentDifferenceSchema.optional(),\n browser: z\n .object({\n source: z.enum(['environment', 'playwright-cache', 'system']),\n product: z.string(),\n version: z.string().optional(),\n })\n .optional(),\n navigation: z\n .object({\n waitUntil: z.literal('domcontentloaded'),\n networkIdleTimeoutMs: z.number().int().nonnegative(),\n networkIdleReached: z.boolean(),\n })\n .optional(),\n consoleErrors: z.array(z.string()).optional(),\n pageErrors: z.array(z.string()).optional(),\n failedRequests: z\n .array(z.object({\n url: z.string(),\n resourceType: z.string(),\n error: z.string(),\n }))\n .optional(),\n securityObservations: z\n .array(z.object({\n kind: z.enum([\n 'content-security-policy',\n 'cors',\n 'mixed-content',\n ]),\n message: z.string(),\n }))\n .optional(),\n error: z.string().optional(),\n })\n .optional(),\n })\n .optional(),\n blocked: z.boolean().optional(),\n contentAuditAllowed: z.boolean().optional(),\n crawlDepth: z.number().int().optional(),\n error: z.string().optional(),\n robotsTxt: z\n .object({\n url: z.string().url(),\n allowed: z.boolean().nullable(),\n availability: z.enum([\n 'available',\n 'absent',\n 'access-blocked',\n 'rate-limited',\n 'unreachable',\n ]),\n status: z.number().int().optional(),\n error: z.string().optional(),\n matchedLine: z.string().optional(),\n })\n .optional(),\n title: z.string().optional(),\n metaDescription: z.string().optional(),\n canonical: z.string().url().optional(),\n canonicalRaw: z.string().optional(),\n canonicalStatus: z\n .enum([\n 'missing',\n 'single',\n 'duplicate',\n 'conflicting',\n 'outside-head-only',\n 'invalid',\n ])\n .optional(),\n canonicalCandidates: z\n .array(z.object({\n source: z.enum(['html-head', 'html-body', 'http-header']),\n raw: z.string(),\n resolved: z.string().url().optional(),\n ignoredReason: z\n .enum([\n 'outside-head',\n 'alternate-qualifier',\n 'fragment',\n 'invalid-url',\n 'non-http-url',\n ])\n .optional(),\n }))\n .optional(),\n metaRobots: z.string().optional(),\n xRobotsTag: z.string().optional(),\n h1: z.string().optional(),\n h1Count: z.number().int().optional(),\n h2Count: z.number().int().optional(),\n h3Count: z.number().int().optional(),\n indexable: z.boolean(),\n indexability: z.string().optional(),\n declaredIndexability: z\n .enum([\n 'indexable-candidate',\n 'noindex',\n 'robots-blocked',\n 'canonical-conflict',\n 'canonical-hint-other',\n 'not-html',\n 'unknown',\n ])\n .optional(),\n extractionStatus: z\n .enum(['complete', 'failed', 'not-applicable', 'unknown-media-type'])\n .optional(),\n extractionError: z.string().optional(),\n wordCount: z.number().int(),\n contentExtraction: z\n .object({\n requested: z.enum(['defuddle', 'readability']),\n used: z.enum(['defuddle', 'readability']),\n fallback: z.boolean(),\n fallbackReason: z.enum(['defuddle_error', 'defuddle_empty']).optional(),\n fallbackDetail: z.string().optional(),\n wordCountSource: z.enum(['defuddle', 'local_cjk_aware']),\n baseUrl: z.string().url(),\n extractorType: z.string().optional(),\n })\n .optional(),\n warnings: z.array(z.string()).optional(),\n contentHash: z.string(),\n mainContentHash: z.string().optional(),\n textRatio: z.number().min(0).max(1).optional(),\n contentSample: z.string().optional(),\n lang: z.string().optional(),\n hasViewport: z.boolean().optional(),\n isHttps: z.boolean().optional(),\n hasHsts: z.boolean().optional(),\n compression: z.string().optional(),\n hreflang: z\n .array(z.object({ hreflang: z.string(), href: z.string().url() }))\n .optional(),\n mixedContentCount: z.number().int().optional(),\n mixedContentSamples: z.array(z.string().url()).optional(),\n imagesTotal: z.number().int().optional(),\n imagesMissingAlt: z.number().int().optional(),\n oversizedImageCandidates: z\n .array(z.object({\n src: z.string().url(),\n width: z.number().int().optional(),\n height: z.number().int().optional(),\n detectedFrom: z.string(),\n }))\n .optional(),\n outgoingInternalCount: z.number().int(),\n outgoingExternalCount: z.number().int().optional(),\n internalInlinkCount: z.number().int().optional(),\n internalLinkAuthorityScore: z.number().int().min(0).max(100).optional(),\n sampleInternalLinks: z.array(z.string().url()).optional(),\n sampleExternalLinks: z.array(z.string().url()).optional(),\n internalAnchorSamples: z\n .array(z.object({ href: z.string().url(), text: z.string() }))\n .optional(),\n externalAnchorSamples: z\n .array(z.object({ href: z.string().url(), text: z.string() }))\n .optional(),\n externalLinkChecks: z\n .array(z.object({\n url: z.string().url(),\n status: z.number().int().optional(),\n error: z.string().optional(),\n }))\n .optional(),\n schemaTypes: z.array(z.string()).optional(),\n structuredDataFormats: z\n .array(z.enum(['json-ld', 'microdata', 'rdfa']))\n .optional(),\n googleRichResults: z.array(googleRichResultAssessmentSchema).optional(),\n googleRichResultsSelection: z\n .object({\n limit: z.number().int().nonnegative(),\n eligible: z.number().int().nonnegative(),\n returned: z.number().int().nonnegative(),\n omitted: z.number().int().nonnegative(),\n partial: z.boolean(),\n eligibleByStatus: googleRichResultStatusCountsSchema,\n returnedByStatus: googleRichResultStatusCountsSchema,\n omittedByStatus: googleRichResultStatusCountsSchema,\n })\n .optional(),\n schemaSameAs: z.array(z.string().url()).optional(),\n schemaSameAsEvidence: z\n .array(z.object({\n url: z.string().url(),\n block: z.number().int().nonnegative(),\n path: z.string(),\n subjectId: z.string().url().optional(),\n subjectTypes: z.array(z.string()),\n }))\n .optional(),\n invalidSchemaSameAs: z\n .array(z.object({\n block: z.number().int().nonnegative(),\n path: z.string(),\n value: z.string(),\n }))\n .optional(),\n socialProfileLinks: z.array(z.string().url()).optional(),\n invalidJsonLdCount: z.number().int().optional(),\n invalidJsonLdSamples: z\n .array(z.object({ snippet: z.string(), error: z.string() }))\n .optional(),\n unrecognizedJsonLdTypes: z\n .array(z.object({\n block: z.number().int().nonnegative(),\n path: z.string(),\n value: z.string(),\n reason: z.enum([\n 'missing-schema-context',\n 'unresolved-context',\n 'unsupported-vocabulary',\n ]),\n }))\n .optional(),\n openGraphTitle: z.string().optional(),\n openGraphDescription: z.string().optional(),\n openGraphImage: z.string().optional(),\n twitterCard: z.string().optional(),\n author: z.string().optional(),\n hasDate: z.boolean().optional(),\n geo: geoSignalsSchema.optional(),\n searchMetrics: searchMetricsSchema.optional(),\n topQuery: searchMetricsSchema.extend({ query: z.string() }).optional(),\n analytics: analyticsSchema.optional(),\n});\nconst crawlResponseObservationBaseSchema = z.object({\n requestedUrl: z.string().url(),\n outcome: z.literal('response'),\n finalUrl: z.string().url(),\n status: z.number().int(),\n contentType: z.string().optional(),\n durationMs: z.number().optional(),\n redirectChain: z\n .array(z.object({\n url: z.string().url(),\n status: z.number().int(),\n location: z.string().url().optional(),\n }))\n .optional(),\n});\nexport const crawlRequestObservationSchema = z.union([\n crawlResponseObservationBaseSchema.extend({\n extraction: z.enum(['complete', 'not-applicable', 'unknown-media-type']),\n }),\n crawlResponseObservationBaseSchema.extend({\n extraction: z.literal('failed'),\n extractionError: z.string(),\n }),\n z.object({\n requestedUrl: z.string().url(),\n outcome: z.literal('skipped'),\n durationMs: z.number().optional(),\n reason: z.enum(['robots-disallowed', 'robots-deferred']),\n robotsTxt: z.object({\n url: z.string().url(),\n allowed: z.boolean().nullable(),\n availability: z.enum([\n 'available',\n 'absent',\n 'access-blocked',\n 'rate-limited',\n 'unreachable',\n ]),\n status: z.number().int().optional(),\n error: z.string().optional(),\n matchedLine: z.string().optional(),\n }),\n extraction: z.literal('not-applicable'),\n }),\n z.object({\n requestedUrl: z.string().url(),\n outcome: z.literal('skipped'),\n durationMs: z.number().optional(),\n reason: z.literal('origin-backpressure'),\n error: z.string(),\n extraction: z.literal('not-applicable'),\n }),\n z.object({\n requestedUrl: z.string().url(),\n outcome: z.literal('failure'),\n durationMs: z.number().optional(),\n failureKind: z.enum([\n 'dns',\n 'tls',\n 'timeout',\n 'redirect-limit',\n 'aborted',\n 'unknown',\n ]),\n error: z.string(),\n extraction: z.literal('not-applicable'),\n }),\n]);\nexport const crawlIssueSchema = z.object({\n ruleId: crawlerRuleIdSchema,\n title: z.string(),\n category: crawlerRuleCategorySchema,\n severity: crawlerRuleSeveritySchema,\n url: z.string().url(),\n detail: z.string().optional(),\n evidence: z.record(z.string(), z.unknown()).optional(),\n searchMetrics: searchMetricsSchema.optional(),\n});\nexport const crawlIssueGroupSchema = z.object({\n ruleId: crawlerRuleIdSchema,\n title: z.string(),\n category: crawlerRuleCategorySchema,\n severity: crawlerRuleSeveritySchema,\n count: z.number().int(),\n sampleUrls: z.array(z.string().url()),\n});\nconst crawlAiSignalsSchema = z.object({\n robotsTxt: z\n .object({\n url: z.string().url(),\n exists: z.boolean(),\n availability: z.enum([\n 'available',\n 'absent',\n 'access-blocked',\n 'rate-limited',\n 'unreachable',\n ]),\n status: z.number().int().optional(),\n error: z.string().optional(),\n sitemapUrls: z.array(z.string().url()),\n botAccess: z.array(z.object({\n userAgent: z.string(),\n allowed: z.boolean().nullable(),\n declared: z.boolean(),\n coveredByWildcard: z.boolean(),\n })),\n })\n .optional(),\n llmsTxt: z\n .object({\n url: z.string().url(),\n exists: z.boolean(),\n status: z.number().int().optional(),\n })\n .optional(),\n agentResources: z\n .array(z.object({\n url: z.string().url(),\n exists: z.boolean(),\n status: z.number().int().optional(),\n contentType: z.string().optional(),\n validJson: z.boolean().optional(),\n }))\n .optional(),\n});\nexport const crawlTopFixSchema = crawlIssueGroupSchema.extend({\n recommendation: crawlerRuleRecommendationSchema,\n score: z.number(),\n scoreFactors: z.object({\n severity: z.number(),\n affectedUrls: z.number().int(),\n searchVisibleUrls: z.number().int(),\n clicks: z.number(),\n impressions: z.number(),\n sessions: z.number(),\n totalUsers: z.number(),\n conversions: z.number(),\n avgPosition: z.number().optional(),\n effort: z.enum(['low', 'medium', 'high']),\n effortScore: z.number(),\n }),\n whyThisRanks: z.string(),\n howToFix: z.string(),\n howToVerify: z.string(),\n verification: z.object({\n command: z.string(),\n expected: z.string(),\n }),\n});\nconst crawlSitemapDiscoverySchema = z.object({\n dataStatus: z.enum(['complete', 'partial', 'unavailable']),\n urlsReturned: z.number().int().nonnegative(),\n roots: z.array(z.object({\n url: z.string().url(),\n source: z.enum(['robots-txt', 'default-path']),\n dataStatus: z.enum(['complete', 'partial', 'unavailable']),\n urlsReturned: z.number().int().nonnegative(),\n sitemapsFetched: z.number().int().nonnegative(),\n lastmods: z.object({\n trust: z.literal('unverified'),\n observed: z.number().int().nonnegative(),\n parseable: z.number().int().nonnegative(),\n malformed: z.object({\n count: z.number().int().nonnegative(),\n samples: z.array(z.object({\n sitemapUrl: z.string().url(),\n kind: z.enum(['url', 'sitemap']),\n loc: z.string(),\n value: z.string(),\n })),\n }),\n future: z.object({\n count: z.number().int().nonnegative(),\n samples: z.array(z.object({\n sitemapUrl: z.string().url(),\n kind: z.enum(['url', 'sitemap']),\n loc: z.string(),\n value: z.string(),\n })),\n }),\n }),\n documents: z.array(z.object({\n url: z.string().url(),\n finalUrl: z.string().url().optional(),\n redirected: z.literal(true).optional(),\n dataStatus: z.enum(['complete', 'partial', 'unavailable']),\n status: z.number().int().optional(),\n contentType: z.string().optional(),\n compression: z.enum(['gzip', 'none']),\n bytes: z.number().int().nonnegative().optional(),\n uncompressedBytes: z.number().int().nonnegative().optional(),\n root: z.enum(['urlset', 'sitemapindex']).optional(),\n warning: z.string().optional(),\n })),\n possiblyTruncated: z.boolean(),\n warnings: z.array(z.string()),\n })),\n});\nconst crawlExternalLinkVerificationSchema = z.object({\n dataStatus: z.enum(['complete', 'partial', 'unavailable']),\n discoveredLinkOccurrences: z.number().int().nonnegative(),\n retainedUrls: z.number().int().nonnegative(),\n selectedUrls: z.number().int().nonnegative(),\n fetchedUrls: z.number().int().nonnegative(),\n failedUrls: z.number().int().nonnegative(),\n deferredUrls: z.number().int().nonnegative(),\n limit: z.number().int().positive(),\n warnings: z.array(z.string()),\n});\nexport const crawlConfigSchema = z.object({\n url: z.string().url(),\n mode: z.enum(['site', 'page', 'list', 'sitemap']),\n urls: z.array(z.string().url()),\n maxPages: z.number().int(),\n maxDepth: z.number().int(),\n concurrency: z.number().int(),\n timeoutMs: z.number().int(),\n include: z.array(z.string()),\n exclude: z.array(z.string()),\n respectRobots: z.boolean(),\n useSitemap: z.boolean(),\n checkExternal: z.boolean(),\n js: z.union([z.enum(['auto', 'on', 'off']), z.boolean()]),\n refresh: z.boolean(),\n fetchRate: z.object({\n concurrency: z.number().int(),\n intervalCap: z.number().int().optional(),\n intervalMs: z.number().int().optional(),\n backpressure: z\n .object({\n slowMs: z.number().int().optional(),\n verySlowMs: z.number().int().optional(),\n maxConsecutiveSlow: z.number().int().optional(),\n maxConsecutiveBlocked: z.number().int().optional(),\n maxConsecutiveErrors: z.number().int().optional(),\n cooldownMs: z.number().int().optional(),\n retryAfterCapMs: z.number().int().optional(),\n })\n .optional(),\n }),\n});\nexport const crawlReportSummarySchema = z.object({\n totalPages: z.number().int(),\n indexablePages: z.number().int(),\n nonIndexablePages: z.number().int(),\n statusErrors: z.number().int(),\n discoveredUrls: z.number().int(),\n queuedUrls: z.number().int(),\n crawledUrls: z.number().int(),\n skippedUrls: z.number().int(),\n failedUrls: z.number().int(),\n observedInternalLinks: z.number().int(),\n pageLimitReached: z.boolean().default(false),\n attemptedRequests: z.number().int(),\n responseRequests: z.number().int(),\n failedRequests: z.number().int(),\n abortedRequests: z.number().int(),\n extractionFailures: z.number().int(),\n requestByStatus: z.record(z.string(), z.number().int()),\n avgRequestMs: z.number().int().optional(),\n highIssues: z.number().int(),\n mediumIssues: z.number().int(),\n lowIssues: z.number().int(),\n avgResponseMs: z.number().int().optional(),\n byStatus: z.record(z.string(), z.number().int()),\n byCategory: z.record(z.string(), z.number().int()),\n});\nconst crawlDataSourceStatusSchema = z.enum([\n 'joined',\n 'partial',\n 'none',\n 'skipped',\n 'unavailable',\n]);\nconst crawlDataSourceWindowSchema = z.object({\n startDate: z.string().date(),\n endDate: z.string().date(),\n days: z.number().int().positive(),\n});\nconst crawlSearchDataSourceSchema = z.object({\n status: crawlDataSourceStatusSchema,\n window: crawlDataSourceWindowSchema.optional(),\n totalPages: z.number().int().nonnegative(),\n queriedPages: z.number().int().nonnegative(),\n joinedMetricPages: z.number().int().nonnegative(),\n joinedQueryPages: z.number().int().nonnegative(),\n pageLimit: z.number().int().positive(),\n pageLimitReached: z.boolean(),\n metricRowsReturned: z.number().int().nonnegative().optional(),\n queryRowsReturned: z.number().int().nonnegative().optional(),\n retainedRowLimit: z.number().int().positive().optional(),\n retainedRowLimitReached: z.boolean().optional(),\n warning: z.string().optional(),\n});\nconst crawlAnalyticsDataSourceSchema = z.object({\n status: crawlDataSourceStatusSchema,\n window: crawlDataSourceWindowSchema.optional(),\n totalPages: z.number().int().nonnegative(),\n queriedPages: z.number().int().nonnegative(),\n joinedPages: z.number().int().nonnegative(),\n returnedRows: z.number().int().nonnegative().optional(),\n availableRows: z.number().int().nonnegative().optional(),\n retainedRowLimit: z.number().int().positive().optional(),\n retainedRowLimitReached: z.boolean().optional(),\n warning: z.string().optional(),\n});\nconst crawlReportDataSourcesSchema = z.object({\n searchConsole: crawlSearchDataSourceSchema,\n analytics: crawlAnalyticsDataSourceSchema,\n});\nconst crawlReportBaseSchema = z.object({\n id: z.string(),\n definitionId: z.string(),\n projectId: z.string().optional(),\n site: z.string().optional(),\n ga4PropertyId: z.string().optional(),\n generatedAt: z.string().datetime(),\n status: z.enum(['completed', 'partial', 'failed']),\n configHash: z.string(),\n config: crawlConfigSchema,\n summary: crawlReportSummarySchema,\n pages: z.array(crawlPageSnapshotSchema),\n issues: z.array(crawlIssueSchema),\n issueGroups: z.array(crawlIssueGroupSchema),\n dataSources: crawlReportDataSourcesSchema.optional(),\n ai: crawlAiSignalsSchema.optional(),\n sitemapDiscovery: crawlSitemapDiscoverySchema.optional(),\n externalLinkVerification: crawlExternalLinkVerificationSchema.optional(),\n warnings: z.array(z.string()),\n caveats: z.array(z.string()),\n});\nexport const crawlReportSchema = z.discriminatedUnion('requestEvidenceStatus', [\n crawlReportBaseSchema.extend({\n requestEvidenceStatus: z.literal('available'),\n requests: z.array(crawlRequestObservationSchema),\n }),\n crawlReportBaseSchema.extend({\n requestEvidenceStatus: z.literal('partial'),\n requests: z.array(crawlRequestObservationSchema),\n }),\n crawlReportBaseSchema.extend({\n requestEvidenceStatus: z.literal('unavailable'),\n requests: z.array(crawlRequestObservationSchema).max(0),\n }),\n]);\nexport const crawlerSchemas = {\n crawlReport: crawlReportSchema,\n issueGroup: crawlIssueGroupSchema,\n topFix: crawlTopFixSchema,\n ruleInfo: crawlerRuleInfoSchema,\n requestObservation: crawlRequestObservationSchema,\n pageSnapshot: crawlPageSnapshotSchema,\n};\nexport const crawlerJsonSchemas = {\n crawlReport: z.toJSONSchema(crawlReportSchema),\n issueGroup: z.toJSONSchema(crawlIssueGroupSchema),\n topFix: z.toJSONSchema(crawlTopFixSchema),\n ruleInfo: z.toJSONSchema(crawlerRuleInfoSchema),\n requestObservation: z.toJSONSchema(crawlRequestObservationSchema),\n pageSnapshot: z.toJSONSchema(crawlPageSnapshotSchema),\n};\n//# sourceMappingURL=schemas.js.map","import { shouldExcludeBrandQuery } from '../brand.js';\nimport { createCtrBenchmarkContext, roundedPosition, } from './opportunity-primitives.js';\nimport { isLowActionabilityQuery } from './query-quality.js';\nexport const CTR_DEFAULT_MIN_IMPRESSIONS = 200;\nexport const CTR_MAX_MIN_IMPRESSIONS = 1_000_000_000;\nexport const CTR_DEFAULT_LIMIT = 25;\nexport const CTR_MAX_LIMIT = 100;\nfunction compareText(left, right) {\n const leftPoints = [...left].map((value) => value.codePointAt(0) ?? 0);\n const rightPoints = [...right].map((value) => value.codePointAt(0) ?? 0);\n for (let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index++) {\n const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);\n if (difference !== 0)\n return difference;\n }\n return leftPoints.length - rightPoints.length;\n}\nfunction boundedInteger(value, fallback, minimum, maximum) {\n if (value === undefined || !Number.isFinite(value))\n return fallback;\n return Math.min(maximum, Math.max(minimum, Math.floor(value)));\n}\nfunction normalizedQuery(value) {\n return value.normalize('NFKC').toLowerCase().replace(/\\s+/g, ' ').trim();\n}\nfunction normalizedHttpUrl(value) {\n try {\n const url = new URL(value);\n if (url.protocol !== 'http:' && url.protocol !== 'https:')\n return undefined;\n url.hash = '';\n return url.toString();\n }\n catch {\n return undefined;\n }\n}\nfunction validMetrics(row) {\n return (Number.isFinite(row.clicks) &&\n row.clicks >= 0 &&\n Number.isFinite(row.impressions) &&\n row.impressions > 0 &&\n row.clicks <= row.impressions &&\n Number.isFinite(row.ctr) &&\n row.ctr >= 0 &&\n row.ctr <= 1 &&\n Number.isFinite(row.position) &&\n row.position > 0);\n}\nfunction aggregateCtrRows(rows, selection) {\n const groups = new Map();\n for (const row of rows) {\n const query = row.keys[0]?.trim() ?? '';\n const url = normalizedHttpUrl(row.keys[1]?.trim() ?? '');\n if (row.keys.length !== 2 || !query || !url || !validMetrics(row)) {\n selection.invalidRows++;\n continue;\n }\n selection.validRows++;\n const key = `${normalizedQuery(query)}\\u0000${url}`;\n const group = groups.get(key) ?? {\n query,\n url,\n clicks: 0,\n impressions: 0,\n weightedPosition: 0,\n sourceRows: 0,\n };\n if (compareText(query, group.query) < 0)\n group.query = query;\n group.clicks += row.clicks;\n group.impressions += row.impressions;\n group.weightedPosition += row.position * row.impressions;\n group.sourceRows++;\n groups.set(key, group);\n }\n const aggregated = [...groups.values()].map((group) => ({\n keys: [group.query, group.url],\n clicks: group.clicks,\n impressions: group.impressions,\n ctr: group.clicks / group.impressions,\n position: group.weightedPosition / group.impressions,\n sourceRows: group.sourceRows,\n }));\n selection.duplicateRows = aggregated.reduce((count, row) => count + row.sourceRows - 1, 0);\n selection.aggregatedRows = aggregated.length;\n return aggregated;\n}\nfunction initialSelection(sourceRows) {\n return {\n sourceRows,\n invalidRows: 0,\n validRows: 0,\n duplicateRows: 0,\n aggregatedRows: 0,\n outsidePageOneRows: 0,\n lowActionabilityRows: 0,\n brandRows: 0,\n benchmarkRows: 0,\n belowMinimumRows: 0,\n evaluatedRows: 0,\n eligibleUnderperformers: 0,\n returnedUnderperformers: 0,\n limitedUnderperformers: 0,\n };\n}\nexport function analyzeCtrUnderperformersFromRows(input) {\n const minImpressions = boundedInteger(input.minImpressions, CTR_DEFAULT_MIN_IMPRESSIONS, 1, CTR_MAX_MIN_IMPRESSIONS);\n const limit = boundedInteger(input.limit, CTR_DEFAULT_LIMIT, 1, CTR_MAX_LIMIT);\n const selection = initialSelection(input.rows.length);\n const aggregatedRows = aggregateCtrRows(input.rows, selection);\n const benchmarkRows = aggregatedRows.filter((row) => {\n const query = row.keys[0] ?? '';\n if (row.position < 1 || row.position > 10) {\n selection.outsidePageOneRows++;\n return false;\n }\n if (isLowActionabilityQuery(query)) {\n selection.lowActionabilityRows++;\n return false;\n }\n if (shouldExcludeBrandQuery({\n query,\n siteUrl: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n })) {\n selection.brandRows++;\n return false;\n }\n return true;\n });\n selection.benchmarkRows = benchmarkRows.length;\n const benchmarkContext = createCtrBenchmarkContext(benchmarkRows);\n const evaluatedRows = benchmarkRows.filter((row) => {\n if (row.impressions < minImpressions) {\n selection.belowMinimumRows++;\n return false;\n }\n return true;\n });\n selection.evaluatedRows = evaluatedRows.length;\n const eligibleItems = evaluatedRows\n .map((row) => {\n const rounded = roundedPosition(row.position);\n const benchmark = benchmarkContext.forUrl(row);\n const expectedClicks = benchmark.ctr * row.impressions;\n const clickShortfall = Math.max(0, expectedClicks - row.clicks);\n return {\n query: row.keys[0] ?? '',\n url: row.keys[1] ?? '',\n position: row.position,\n impressions: row.impressions,\n actualCtr: row.ctr,\n expectedCtr: benchmark.ctr,\n clicks: row.clicks,\n expectedClicks,\n clickShortfall,\n benchmark: {\n expectedCtr: benchmark.ctr,\n source: benchmark.source,\n peerRows: benchmark.rows,\n peerImpressions: benchmark.impressions,\n qualifiedPeerImpressions: benchmark.qualifiedImpressions,\n urlSamples: benchmark.urlSamples,\n positiveUrlSamples: benchmark.positiveUrlSamples,\n },\n recommendation: {\n principle: 'C.3',\n evidenceRef: `Query \"${row.keys[0]}\" has observed CTR ${row.ctr.toFixed(3)} versus a heuristic ${benchmark.ctr.toFixed(3)} benchmark at average position ${rounded}, producing a calculated ${clickShortfall.toFixed(0)}-click shortfall for this window.`,\n action: `Review the live SERP, query intent, displayed snippet, title, and meta description for \"${row.keys[0]}\". Test SERP copy only when that review finds a mismatch; the CTR gap alone does not identify the cause.`,\n effort: 'S',\n confidence: 'low',\n },\n };\n })\n .filter((item) => item.actualCtr < item.expectedCtr * 0.6)\n .sort((left, right) => right.clickShortfall - left.clickShortfall ||\n compareText(left.query, right.query) ||\n compareText(left.url, right.url));\n const items = eligibleItems.slice(0, limit);\n selection.eligibleUnderperformers = eligibleItems.length;\n selection.returnedUnderperformers = items.length;\n selection.limitedUnderperformers = eligibleItems.length - items.length;\n return {\n items,\n totalClickShortfall: eligibleItems.reduce((sum, item) => sum + item.clickShortfall, 0),\n returnedClickShortfall: items.reduce((sum, item) => sum + item.clickShortfall, 0),\n minImpressions,\n limit,\n selection,\n };\n}\n//# sourceMappingURL=ctr-underperformers-analysis.js.map","import { querySearchAnalytics } from '../gsc/client.js';\nimport { analyzeCtrUnderperformersFromRows, CTR_DEFAULT_LIMIT, CTR_DEFAULT_MIN_IMPRESSIONS, CTR_MAX_LIMIT, CTR_MAX_MIN_IMPRESSIONS, } from './ctr-underperformers-analysis.js';\nimport { defaultDateRange } from './shared.js';\nimport { integerOption } from './site-diagnostics/quick-wins-report-input.js';\nexport * from './ctr-underperformers-analysis.js';\nconst MAX_GSC_ROWS = 100_000;\nfunction plural(count, singular, pluralLabel = `${singular}s`) {\n return count === 1 ? singular : pluralLabel;\n}\nconst defaultDependencies = {\n searchAnalytics: querySearchAnalytics,\n now: () => new Date(),\n};\nexport async function ctrUnderperformersReport(input, dependencies = defaultDependencies) {\n const minImpressions = integerOption({\n value: input.minImpressions,\n fallback: CTR_DEFAULT_MIN_IMPRESSIONS,\n minimum: 1,\n maximum: CTR_MAX_MIN_IMPRESSIONS,\n label: 'minImpressions',\n });\n const limit = integerOption({\n value: input.limit,\n fallback: CTR_DEFAULT_LIMIT,\n minimum: 1,\n maximum: CTR_MAX_LIMIT,\n label: 'limit',\n });\n const now = dependencies.now();\n const range = defaultDateRange(28, now);\n const source = await dependencies.searchAnalytics(input.site, {\n ...range,\n dimensions: ['query', 'page'],\n type: 'web',\n dataState: 'final',\n maxRows: MAX_GSC_ROWS,\n }, { refresh: input.refresh });\n const { items, totalClickShortfall, returnedClickShortfall, selection } = analyzeCtrUnderperformersFromRows({\n rows: source.rows,\n site: input.site,\n minImpressions,\n limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n const top = items[0];\n const possiblyTruncated = source.rowsFetched >= MAX_GSC_ROWS;\n const partialValidation = selection.invalidRows > 0;\n const dataStatus = selection.sourceRows === 0\n ? 'empty'\n : possiblyTruncated || partialValidation\n ? 'partial'\n : selection.eligibleUnderperformers === 0\n ? 'filtered'\n : 'complete';\n const completeness = possiblyTruncated && partialValidation\n ? 'partial-and-possibly-truncated'\n : possiblyTruncated\n ? 'possibly-truncated'\n : partialValidation\n ? 'partial'\n : 'complete';\n return {\n schemaVersion: 1,\n site: input.site,\n range,\n generatedAt: now.toISOString(),\n dataStatus,\n source: {\n provider: 'google-search-console',\n dimensions: ['query', 'page'],\n searchType: 'web',\n dataState: 'final',\n rowsFetched: source.rowsFetched,\n calls: source.calls,\n maxRows: MAX_GSC_ROWS,\n possiblyTruncated,\n completeness,\n validation: {\n retainedRows: selection.validRows,\n invalidRows: selection.invalidRows,\n aggregatedRows: selection.aggregatedRows,\n duplicateRows: selection.duplicateRows,\n },\n },\n selection,\n summary: {\n underperformers: selection.eligibleUnderperformers,\n returnedUnderperformers: selection.returnedUnderperformers,\n estimatedClickShortfall: totalClickShortfall,\n returnedClickShortfall,\n minImpressions,\n limit,\n brandFiltering: input.includeBrand ? 'included' : 'excluded',\n verdict: top\n ? `${selection.eligibleUnderperformers} CTR ${plural(selection.eligibleUnderperformers, 'underperformer')} found in retained rows, with a calculated heuristic shortfall of ${totalClickShortfall.toFixed(0)} clicks for this window. Start review with \"${top.query}\" because it has the largest gap.`\n : dataStatus === 'partial'\n ? 'No material CTR underperformers remained in the validated retained rows, but partial evidence prevents an all-clear.'\n : 'No high-impression page-one queries in the retained rows are materially below the heuristic CTR benchmark.',\n },\n items,\n caveats: [\n `Date window: ${range.startDate} to ${range.endDate} (28 days), using final GSC data where available.`,\n `Brand queries: ${input.includeBrand ? 'included' : 'excluded'}.`,\n `Only queries ranking position 1-10 with at least ${minImpressions} impressions were checked.`,\n 'Expected CTR uses a robust site-aware position benchmark when enough peer data exists, otherwise the fallback position curve.',\n 'CTR benchmarks and calculated click shortfalls are directional heuristics, not forecasts or proof that clicks are available. Validate the search intent and live SERP before editing.',\n ...(selection.invalidRows\n ? [\n `${selection.invalidRows} invalid provider ${plural(selection.invalidRows, 'row')} ${selection.invalidRows === 1 ? 'was' : 'were'} excluded, so this report is partial.`,\n ]\n : []),\n ...(selection.duplicateRows\n ? [\n `${selection.duplicateRows} repeated query/page ${plural(selection.duplicateRows, 'row')} ${selection.duplicateRows === 1 ? 'was' : 'were'} aggregated before CTR and average position were calculated.`,\n ]\n : []),\n ...(possiblyTruncated\n ? [\n `The retained-row limit of ${MAX_GSC_ROWS} was reached, so lower-ranked source rows may be absent.`,\n ]\n : []),\n ...(selection.limitedUnderperformers\n ? [\n `${selection.limitedUnderperformers} eligible ${plural(selection.limitedUnderperformers, 'underperformer')} ${selection.limitedUnderperformers === 1 ? 'was' : 'were'} omitted by the output limit.`,\n ]\n : []),\n ],\n recommendations: top\n ? [\n `Review the live SERP and displayed snippet for \"${top.query}\" first. Test the title or meta description only if the observed framing does not match the query intent.`,\n 'Prioritise rows with high impressions and clear intent, but treat the benchmark gap as a hypothesis rather than a diagnosed copy defect.',\n 'After changing SERP copy, annotate the change and compare the next full 28-day period before making more edits.',\n ]\n : dataStatus === 'partial'\n ? [\n 'No CTR-only action is recommended from the validated retained rows. Refresh or inspect the provider evidence before treating this as an all-clear.',\n ]\n : [\n 'No CTR-only action is recommended from this report. Use striking-distance or page-opportunities if you want more growth ideas.',\n ],\n };\n}\n//# sourceMappingURL=ctr-underperformers.js.map","export function plural(count, singular, pluralLabel = `${singular}s`) {\n return count === 1 ? singular : pluralLabel;\n}\nexport function countLabel(count, singular, pluralLabel = `${singular}s`) {\n return `${count.toLocaleString('en-GB')} ${plural(count, singular, pluralLabel)}`;\n}\n//# sourceMappingURL=phrasing.js.map","import { countLabel } from '../phrasing.js';\nfunction topDelta(report) {\n const top = report.items[0];\n if (!top)\n return 'No segment movement found.';\n const direction = top.clickDelta < 0 ? 'lost' : 'gained';\n return `${top.key} ${direction} ${Math.abs(top.clickDelta)} clicks.`;\n}\nexport function buildDiagnosisPriorities(input) {\n const priorities = [];\n const hasSignificantAnomaly = input.anomaly.anomalies.some((anomaly) => anomaly.significant);\n if (hasSignificantAnomaly && input.update.overlappingUpdates.length) {\n priorities.push({\n label: 'Review movement during update overlap',\n reason: `${countLabel(input.update.overlappingUpdates.length, 'official update window')} ${input.update.overlappingUpdates.length === 1 ? 'overlaps' : 'overlap'} the significant movement comparison window.`,\n action: 'Do not assume the update caused the movement. First compare winning and losing templates, then test site changes, indexability, intent, and SERP changes as separate explanations.',\n confidence: 'low',\n });\n }\n const largestPage = input.page.items[0];\n if (largestPage) {\n priorities.push({\n label: 'Investigate largest page movement',\n reason: topDelta(input.page),\n action: 'Open the page and check the queries that moved, whether the URL is still canonical/indexable, and whether the title, H1, or body changed recently.',\n confidence: input.page.dataStatus === 'partial'\n ? 'low'\n : Math.abs(largestPage.clickDelta) > 50\n ? 'high'\n : 'medium',\n });\n }\n if (input.decay.selection.eligibleRows) {\n const topGroup = input.decay.groups[0];\n priorities.push({\n label: 'Refresh decaying content',\n reason: topGroup\n ? `${input.decay.selection.eligibleRows} observed retained query/page declines found; ${topGroup.label} declined by ${topGroup.totalClickLoss.toFixed(0)} clicks.`\n : `${input.decay.selection.eligibleRows} observed retained query/page declines found.`,\n action: topGroup\n ? topGroup.recommendation\n : 'Start with declines that continued outside the update window. Check indexability first, then ranking and CTR causes.',\n confidence: input.decay.dataStatus === 'partial' ? 'low' : 'medium',\n });\n }\n if (input.cannibal.items.length) {\n priorities.push({\n label: 'Review multi-URL query candidates',\n reason: `${input.cannibal.selection.eligibleClusters} multi-URL query candidates found.`,\n action: 'Confirm whether each URL set satisfies the same intent and inspect technical state. Consolidate only verified duplicate or same-intent pages; otherwise clarify the distinction.',\n confidence: 'low',\n });\n }\n const topQuickWin = input.quickWins.items[0];\n if (topQuickWin) {\n const incompleteEvidence = input.quickWins.source.possiblyTruncated ||\n (input.quickWins.verification.requested &&\n input.quickWins.verification.failed > 0);\n priorities.push({\n label: 'Review CTR-target opportunity',\n reason: `${countLabel(input.quickWins.items.length, 'returned query/page candidate')} fell below ${input.quickWins.items.length === 1 ? 'its' : 'their'} deterministic, versioned heuristic CTR target.`,\n action: topQuickWin.recommendation.action,\n confidence: incompleteEvidence\n ? 'low'\n : topQuickWin.recommendation.confidence,\n });\n }\n if (input.striking.items.length) {\n const top = input.striking.items[0];\n priorities.push({\n label: 'Investigate striking-distance candidates',\n reason: `${input.striking.items.length} query/page rows have an average GSC position above 10 and at most 20.`,\n action: top?.recommendation.action ??\n 'Check technical state, query coverage, competing URLs, and relevant internal links before choosing a change.',\n confidence: input.striking.source.possiblyTruncated\n ? 'low'\n : (top?.recommendation.confidence ?? 'low'),\n });\n }\n return priorities.slice(0, 6);\n}\n//# sourceMappingURL=diagnosis-priorities.js.map","export function diagnosisPartialReasons(report) {\n const skippedSections = new Set(report.skippedSections?.map((section) => section.section));\n const segmentReasons = ['page', 'query', 'device', 'country'].flatMap((dimension) => {\n const segment = report.segments[dimension];\n if (segment.dataStatus === 'complete' ||\n skippedSections.has(`${dimension} movement segments`)) {\n return [];\n }\n return [\n {\n section: `${dimension} movement segments`,\n reason: `${segment.summary.verdict} Inspect its retained-row source evidence and warnings.`,\n },\n ];\n });\n return [\n ...(report.anomaly.coverage?.status === 'partial'\n ? [\n {\n section: 'traffic anomaly',\n reason: report.anomaly.coverage.caveats.join(' ') ||\n 'The requested Search Console calendar window has incomplete daily evidence.',\n },\n ]\n : []),\n ...segmentReasons,\n ...(report.decay.dataStatus === 'partial'\n ? [\n {\n section: 'decay analysis',\n reason: 'The decay comparison used incomplete source evidence; inspect its source completeness, warnings, and caveats.',\n },\n ]\n : []),\n ...(report.cannibalization.dataStatus === 'partial'\n ? [\n {\n section: 'cannibalisation analysis',\n reason: 'The multi-URL query analysis used incomplete source evidence; inspect its source completeness and caveats.',\n },\n ]\n : []),\n ...(report.strikingDistance.source.possiblyTruncated\n ? [\n {\n section: 'striking-distance opportunities',\n reason: 'The retained Search Console response reached its row cap, so additional candidates may exist.',\n },\n ]\n : []),\n ...(report.strikingDistance.verification.requested &&\n report.strikingDistance.verification.failed > 0\n ? [\n {\n section: 'striking-distance content verification',\n reason: `${report.strikingDistance.verification.failed} of ${report.strikingDistance.verification.attempted} attempted candidate verifications failed, so page evidence is incomplete.`,\n },\n ]\n : []),\n ...(report.quickWins.source.possiblyTruncated\n ? [\n {\n section: 'quick-win opportunities',\n reason: 'The retained Search Console response reached its row cap, so benchmarks and candidates may be incomplete.',\n },\n ]\n : []),\n ...(report.quickWins.verification.requested &&\n report.quickWins.verification.failed > 0\n ? [\n {\n section: 'quick-win content verification',\n reason: `${report.quickWins.verification.failed} of ${report.quickWins.verification.attemptedRows} attempted candidate verifications failed, so page evidence is incomplete.`,\n },\n ]\n : []),\n ];\n}\nexport function diagnosisDataStatus(input) {\n if (input.criticalStatuses.length > 0 &&\n input.criticalStatuses.every((status) => status === 'skipped')) {\n return 'unavailable';\n }\n return input.skippedSections || input.partialReasons ? 'partial' : 'complete';\n}\n//# sourceMappingURL=diagnosis-status.js.map","function fixed(value) {\n return Number(value.toFixed(3));\n}\nfunction compareText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\nfunction validMetric(value) {\n return Number.isFinite(value) && value >= 0;\n}\nfunction validCount(value) {\n return Number.isInteger(value) && value >= 0;\n}\nfunction retainedRows(rows) {\n const retained = new Map();\n const conflicted = new Set();\n let invalidRows = 0;\n let duplicateRows = 0;\n let conflictingRows = 0;\n for (const row of rows) {\n const key = row.keys[0];\n if (row.keys.length !== 1 ||\n !key?.trim() ||\n !validCount(row.clicks) ||\n !validCount(row.impressions) ||\n !validMetric(row.position) ||\n (row.impressions > 0 && row.position <= 0)) {\n invalidRows += 1;\n continue;\n }\n const value = {\n key,\n clicks: row.clicks,\n impressions: row.impressions,\n position: row.impressions > 0 ? fixed(row.position) : null,\n };\n const existing = retained.get(key);\n if (existing) {\n if (existing.clicks === value.clicks &&\n existing.impressions === value.impressions &&\n existing.position === value.position) {\n duplicateRows += 1;\n }\n else {\n conflictingRows += 1;\n retained.delete(key);\n conflicted.add(key);\n }\n continue;\n }\n if (!conflicted.has(key))\n retained.set(key, value);\n }\n return { rows: retained, invalidRows, duplicateRows, conflictingRows };\n}\nfunction impactItem(before, after) {\n const positionDelta = before.position === null || after.position === null\n ? null\n : fixed(after.position - before.position);\n return {\n key: before.key,\n evidenceScope: 'matched-retained-segment',\n beforeClicks: before.clicks,\n afterClicks: after.clicks,\n clickDelta: fixed(after.clicks - before.clicks),\n beforeImpressions: before.impressions,\n afterImpressions: after.impressions,\n impressionDelta: fixed(after.impressions - before.impressions),\n beforePosition: before.position,\n afterPosition: after.position,\n positionDelta,\n };\n}\nfunction unmatchedRow(row, retainedIn) {\n return {\n ...row,\n retainedIn,\n reason: 'not-retained-in-other-window',\n };\n}\nexport function compareRetainedSegmentRows(input) {\n const before = retainedRows(input.beforeRows);\n const after = retainedRows(input.afterRows);\n const matched = [];\n const unmatched = [];\n for (const [key, row] of before.rows) {\n const afterRow = after.rows.get(key);\n if (afterRow)\n matched.push(impactItem(row, afterRow));\n else\n unmatched.push(unmatchedRow(row, 'before'));\n }\n for (const [key, row] of after.rows) {\n if (!before.rows.has(key))\n unmatched.push(unmatchedRow(row, 'after'));\n }\n matched.sort((left, right) => Math.abs(right.clickDelta) - Math.abs(left.clickDelta) ||\n compareText(left.key, right.key));\n unmatched.sort((left, right) => right.clicks - left.clicks ||\n compareText(left.retainedIn, right.retainedIn) ||\n compareText(left.key, right.key));\n return { before, after, matched, unmatched };\n}\n//# sourceMappingURL=segment-impact-rows.js.map","import { SeoError } from '../errors.js';\nimport { compareRetainedSegmentRows } from './segment-impact-rows.js';\nfunction verdict(input) {\n if (input.status === 'empty') {\n return 'Search Console returned no retained segment rows for either window.';\n }\n if (!input.matchedRows) {\n return 'No segment was retained in both windows, so no movement delta was inferred.';\n }\n const suffix = input.unmatchedRows\n ? ` ${input.unmatchedRows} one-window rows were kept as unmatched evidence and not converted to zero.`\n : '';\n return `${input.returnedRows} of ${input.matchedRows} matched retained segments returned.${suffix}`;\n}\nexport function analyzeSegmentRows(input) {\n if (!Number.isInteger(input.beforeDays) ||\n !Number.isInteger(input.afterDays) ||\n input.beforeDays < 1 ||\n input.afterDays < 1) {\n throw new SeoError('INVALID_INPUT', 'Segment ranges must contain days.');\n }\n if (input.beforeDays !== input.afterDays) {\n throw new SeoError('INVALID_INPUT', 'Segment impact requires adjacent equal-length comparison windows.');\n }\n const { before, after, matched, unmatched } = compareRetainedSegmentRows(input);\n const beforeRowsFetched = input.beforeRowsFetched ?? input.beforeRows.length;\n const afterRowsFetched = input.afterRowsFetched ?? input.afterRows.length;\n const beforeTruncated = beforeRowsFetched >= input.maxRows;\n const afterTruncated = afterRowsFetched >= input.maxRows;\n const unmatchedBeforeRows = unmatched.filter((row) => row.retainedIn === 'before').length;\n const unmatchedAfterRows = unmatched.length - unmatchedBeforeRows;\n const selection = {\n beforeSourceRows: input.beforeRows.length,\n afterSourceRows: input.afterRows.length,\n beforeInvalidRows: before.invalidRows,\n afterInvalidRows: after.invalidRows,\n beforeDuplicateRows: before.duplicateRows,\n afterDuplicateRows: after.duplicateRows,\n beforeConflictingRows: before.conflictingRows,\n afterConflictingRows: after.conflictingRows,\n matchedRows: matched.length,\n unmatchedBeforeRows,\n unmatchedAfterRows,\n returnedRows: Math.min(matched.length, input.limit),\n limitedRows: Math.max(0, matched.length - input.limit),\n returnedUnmatchedRows: Math.min(unmatched.length, input.unmatchedLimit),\n limitedUnmatchedRows: Math.max(0, unmatched.length - input.unmatchedLimit),\n };\n const hasPartialEvidence = beforeTruncated ||\n afterTruncated ||\n before.invalidRows > 0 ||\n after.invalidRows > 0 ||\n before.duplicateRows > 0 ||\n after.duplicateRows > 0 ||\n before.conflictingRows > 0 ||\n after.conflictingRows > 0 ||\n unmatched.length > 0 ||\n beforeRowsFetched === 0 ||\n afterRowsFetched === 0;\n const dataStatus = beforeRowsFetched === 0 && afterRowsFetched === 0\n ? 'empty'\n : beforeRowsFetched === 0 ||\n afterRowsFetched === 0 ||\n matched.length === 0\n ? 'unavailable'\n : hasPartialEvidence\n ? 'partial'\n : 'complete';\n const warnings = [\n ...(beforeTruncated || afterTruncated\n ? [\n `At least one GSC window reached the ${input.maxRows.toLocaleString('en-GB')}-row safety cap. Results may be truncated.`,\n ]\n : []),\n ...(unmatched.length\n ? [\n `${unmatched.length} segments appeared in only one retained response. They are not treated as zero traffic or ranked as winners or losers.`,\n ]\n : []),\n ...(before.invalidRows || after.invalidRows\n ? [\n `${before.invalidRows} before and ${after.invalidRows} after rows had invalid dimensions or metrics and were excluded.`,\n ]\n : []),\n ...(before.duplicateRows || after.duplicateRows\n ? [\n `${before.duplicateRows} before and ${after.duplicateRows} after identical duplicate segment rows were deduplicated.`,\n ]\n : []),\n ...(before.conflictingRows || after.conflictingRows\n ? [\n `${before.conflictingRows} before and ${after.conflictingRows} after conflicting duplicate segment rows were excluded.`,\n ]\n : []),\n ];\n return {\n schemaVersion: 2,\n site: input.site,\n dimension: input.dimension,\n before: input.before,\n after: input.after,\n rangeDays: { before: input.beforeDays, after: input.afterDays },\n generatedAt: input.generatedAt,\n dataStatus,\n source: {\n provider: 'google-search-console',\n dimension: input.dimension,\n aggregationType: 'auto',\n searchType: 'web',\n dataState: 'final',\n before: {\n rowsFetched: beforeRowsFetched,\n calls: input.beforeCalls ?? 0,\n maxRows: input.maxRows,\n possiblyTruncated: beforeTruncated,\n },\n after: {\n rowsFetched: afterRowsFetched,\n calls: input.afterCalls ?? 0,\n maxRows: input.maxRows,\n possiblyTruncated: afterTruncated,\n },\n completeness: beforeTruncated || afterTruncated\n ? 'possibly-truncated'\n : 'retained-rows-only',\n },\n methodology: {\n id: 'gsc_matched_retained_segment_impact',\n version: 2,\n missingRowsTreatedAsZero: false,\n equalLengthAdjacentWindows: true,\n clickDeltaBasis: 'after-minus-before',\n positionDeltaDefinition: 'after-minus-before-positive-is-worse',\n causeLanguage: 'signals-not-attribution',\n },\n filters: {\n limit: input.limit,\n unmatchedLimit: input.unmatchedLimit,\n maxRows: input.maxRows,\n },\n selection,\n summary: {\n matchedRows: matched.length,\n returnedRows: selection.returnedRows,\n unmatchedRows: unmatched.length,\n verdict: verdict({\n status: dataStatus,\n matchedRows: matched.length,\n returnedRows: selection.returnedRows,\n unmatchedRows: unmatched.length,\n }),\n },\n items: matched.slice(0, input.limit),\n unmatchedSegments: unmatched.slice(0, input.unmatchedLimit),\n warnings,\n caveats: [\n 'Only segments retained in both GSC responses receive movement deltas. Search Console can omit anonymized and lower-volume rows, so one-window absence is not proof of zero traffic.',\n 'Average position is impression-weighted provider data and is only compared when both retained rows have impressions.',\n 'Search Console segment data is observational. Movement can guide investigation but does not establish the cause of a ranking, demand, or CTR change.',\n ],\n };\n}\n//# sourceMappingURL=segment-impact-analysis.js.map","import { SeoError } from '../errors.js';\nimport { defaultDateRange, explicitDateRange, integerOption, } from './site-diagnostics/quick-wins-report-input.js';\nconst DAY_MS = 86_400_000;\nconst MAX_WINDOW_DAYS = 240;\nfunction subtractDays(value, days) {\n const date = new Date(`${value}T00:00:00.000Z`);\n date.setUTCDate(date.getUTCDate() - days);\n return date.toISOString().slice(0, 10);\n}\nexport function segmentRangeDays(range) {\n return (Math.floor((Date.parse(`${range.endDate}T00:00:00.000Z`) -\n Date.parse(`${range.startDate}T00:00:00.000Z`)) /\n DAY_MS) + 1);\n}\nexport function segmentComparisonRange(after, compareDays) {\n const endDate = subtractDays(after.startDate, 1);\n return {\n startDate: subtractDays(endDate, compareDays - 1),\n endDate,\n };\n}\nexport function validateSegmentRanges(input) {\n const before = explicitDateRange(input.before, MAX_WINDOW_DAYS);\n const after = explicitDateRange(input.after, MAX_WINDOW_DAYS);\n if (!before || !after) {\n throw new SeoError('INVALID_INPUT', 'Both segment ranges are required.');\n }\n if (subtractDays(input.after.startDate, 1) !== input.before.endDate) {\n throw new SeoError('INVALID_INPUT', 'Segment comparison windows must be adjacent.');\n }\n if (before.days !== after.days) {\n throw new SeoError('INVALID_INPUT', 'Segment comparison windows must have equal lengths.');\n }\n return { beforeDays: before.days, afterDays: after.days };\n}\nexport function resolveSegmentRanges(input) {\n const days = integerOption({\n value: input.days,\n fallback: 28,\n minimum: 1,\n maximum: MAX_WINDOW_DAYS,\n label: 'days',\n });\n const explicit = explicitDateRange(input, MAX_WINDOW_DAYS);\n const after = explicit?.range ?? defaultDateRange(days, input.now);\n const compareDays = integerOption({\n value: input.compareDays,\n fallback: segmentRangeDays(after),\n minimum: 1,\n maximum: MAX_WINDOW_DAYS,\n label: 'compareDays',\n });\n const afterDays = segmentRangeDays(after);\n if (compareDays !== afterDays) {\n throw new SeoError('INVALID_INPUT', `compareDays must equal the ${afterDays}-day current window. Segment impact requires adjacent equal-length periods.`);\n }\n return { before: segmentComparisonRange(after, compareDays), after };\n}\nexport function validateSegmentSite(site) {\n if (!site.trim()) {\n throw new SeoError('INVALID_INPUT', 'site must not be empty.');\n }\n}\n//# sourceMappingURL=segment-impact-input.js.map","import { SeoError } from '../../errors.js';\nimport { defaultDateRange } from './quick-wins-report-input.js';\nexport function decayNumberOption(input) {\n const value = input.value ?? input.fallback;\n if (!Number.isFinite(value) ||\n value < input.minimum ||\n value > input.maximum) {\n throw new SeoError('INVALID_INPUT', `${input.label} must be between ${input.minimum} and ${input.maximum}.`);\n }\n return value;\n}\nfunction rangeDays(range) {\n return (Math.floor((new Date(`${range.endDate}T00:00:00.000Z`).getTime() -\n new Date(`${range.startDate}T00:00:00.000Z`).getTime()) /\n 86_400_000) + 1);\n}\nfunction dateString(date) {\n return date.toISOString().slice(0, 10);\n}\nfunction subtractDays(value, days) {\n const date = new Date(`${value}T00:00:00.000Z`);\n date.setUTCDate(date.getUTCDate() - days);\n return dateString(date);\n}\nfunction priorYearDate(value) {\n const source = new Date(`${value}T00:00:00.000Z`);\n const year = source.getUTCFullYear() - 1;\n const month = source.getUTCMonth();\n const day = source.getUTCDate();\n const candidate = new Date(Date.UTC(year, month, day));\n if (candidate.getUTCMonth() !== month) {\n return dateString(new Date(Date.UTC(year, month + 1, 0)));\n }\n return dateString(candidate);\n}\nfunction subtractCalendarMonths(date, months) {\n const day = date.getUTCDate();\n const target = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() - months, 1));\n const lastDay = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate();\n target.setUTCDate(Math.min(day, lastDay));\n return dateString(target);\n}\nexport function validateDecayRanges(input) {\n const latestFinalDate = defaultDateRange(1, input.now).endDate;\n if (input.current.endDate > latestFinalDate) {\n throw new SeoError('INVALID_INPUT', `Decay end date must be ${latestFinalDate} or earlier so both GSC windows use final data.`);\n }\n const pacificToday = new Date(`${latestFinalDate}T00:00:00.000Z`);\n pacificToday.setUTCDate(pacificToday.getUTCDate() + 4);\n const retentionStart = subtractCalendarMonths(pacificToday, 16);\n if (input.previous.startDate < retentionStart) {\n throw new SeoError('INVALID_INPUT', `Comparison range starts before Search Console's rolling 16-month API history (${retentionStart}). Choose a shorter range or use previously stored data.`);\n }\n}\nexport function decayComparisonRange(current, comparison = 'previous-period') {\n const days = rangeDays(current);\n if (comparison === 'year-over-year') {\n const endDate = priorYearDate(current.endDate);\n return { startDate: subtractDays(endDate, days - 1), endDate };\n }\n const endDate = subtractDays(current.startDate, 1);\n return { startDate: subtractDays(endDate, days - 1), endDate };\n}\n//# sourceMappingURL=decay-report-input.js.map","import { segmentComparisonRange, segmentRangeDays, } from './segment-impact-input.js';\nexport function unavailableSegmentImpactReport(input) {\n const days = segmentRangeDays(input.after);\n const before = segmentComparisonRange(input.after, days);\n return {\n schemaVersion: 2,\n site: input.site,\n dimension: input.dimension,\n before,\n after: input.after,\n rangeDays: { before: days, after: days },\n generatedAt: input.generatedAt ?? new Date().toISOString(),\n dataStatus: 'unavailable',\n source: {\n provider: 'google-search-console',\n dimension: input.dimension,\n aggregationType: 'auto',\n searchType: 'web',\n dataState: 'final',\n before: {\n rowsFetched: 0,\n calls: 0,\n maxRows: 100_000,\n possiblyTruncated: false,\n },\n after: {\n rowsFetched: 0,\n calls: 0,\n maxRows: 100_000,\n possiblyTruncated: false,\n },\n completeness: 'unavailable',\n },\n methodology: {\n id: 'gsc_matched_retained_segment_impact',\n version: 2,\n missingRowsTreatedAsZero: false,\n equalLengthAdjacentWindows: true,\n clickDeltaBasis: 'after-minus-before',\n positionDeltaDefinition: 'after-minus-before-positive-is-worse',\n causeLanguage: 'signals-not-attribution',\n },\n filters: { limit: 0, unmatchedLimit: 0, maxRows: 100_000 },\n selection: {\n beforeSourceRows: 0,\n afterSourceRows: 0,\n beforeInvalidRows: 0,\n afterInvalidRows: 0,\n beforeDuplicateRows: 0,\n afterDuplicateRows: 0,\n beforeConflictingRows: 0,\n afterConflictingRows: 0,\n matchedRows: 0,\n unmatchedBeforeRows: 0,\n unmatchedAfterRows: 0,\n returnedRows: 0,\n limitedRows: 0,\n returnedUnmatchedRows: 0,\n limitedUnmatchedRows: 0,\n },\n summary: {\n matchedRows: 0,\n returnedRows: 0,\n unmatchedRows: 0,\n verdict: 'Segment movement could not be compared for this run.',\n },\n items: [],\n unmatchedSegments: [],\n warnings: [input.reason],\n caveats: [\n 'No segment movement conclusion was produced because the provider evidence was unavailable.',\n ],\n };\n}\n//# sourceMappingURL=segment-impact-fallback.js.map","import { querySearchAnalytics } from '../gsc/client.js';\nimport { analyzeSegmentRows } from './segment-impact-analysis.js';\nimport { resolveSegmentRanges, segmentRangeDays, validateSegmentRanges, validateSegmentSite, } from './segment-impact-input.js';\nimport { validateDecayRanges } from './site-diagnostics/decay-report-input.js';\nimport { integerOption } from './site-diagnostics/quick-wins-report-input.js';\nexport { analyzeSegmentRows } from './segment-impact-analysis.js';\nexport { unavailableSegmentImpactReport } from './segment-impact-fallback.js';\nexport { resolveSegmentRanges, segmentComparisonRange, segmentRangeDays, } from './segment-impact-input.js';\nconst DEFAULT_MAX_ROWS = 100_000;\nconst defaultDependencies = {\n searchAnalytics: querySearchAnalytics,\n now: () => new Date(),\n};\nexport function compareSegmentRows(input) {\n validateSegmentSite(input.site);\n const limit = integerOption({\n value: input.limit,\n fallback: 25,\n minimum: 1,\n maximum: 100,\n label: 'limit',\n });\n const unmatchedLimit = integerOption({\n value: input.unmatchedLimit,\n fallback: 25,\n minimum: 0,\n maximum: 100,\n label: 'unmatchedLimit',\n });\n const maxRows = integerOption({\n value: input.maxRows,\n fallback: DEFAULT_MAX_ROWS,\n minimum: 1,\n maximum: 250_000,\n label: 'maxRows',\n });\n const rangeDays = validateSegmentRanges({\n before: input.before,\n after: input.after,\n });\n return analyzeSegmentRows({\n ...input,\n ...rangeDays,\n limit,\n unmatchedLimit,\n maxRows,\n generatedAt: input.generatedAt ?? new Date().toISOString(),\n });\n}\nexport async function segmentImpact(input, dependencies = defaultDependencies) {\n validateSegmentSite(input.site);\n const now = dependencies.now();\n const ranges = resolveSegmentRanges({ ...input, now });\n validateDecayRanges({\n current: ranges.after,\n previous: ranges.before,\n now,\n });\n const limit = integerOption({\n value: input.limit,\n fallback: 25,\n minimum: 1,\n maximum: 100,\n label: 'limit',\n });\n const unmatchedLimit = integerOption({\n value: input.unmatchedLimit,\n fallback: 25,\n minimum: 0,\n maximum: 100,\n label: 'unmatchedLimit',\n });\n const maxRows = integerOption({\n value: input.maxRows,\n fallback: DEFAULT_MAX_ROWS,\n minimum: 1,\n maximum: 250_000,\n label: 'maxRows',\n });\n const dimension = input.dimension ?? 'page';\n const request = {\n dimensions: [dimension],\n type: 'web',\n dataState: 'final',\n aggregationType: 'auto',\n maxRows,\n };\n const [beforeResult, afterResult] = await Promise.all([\n dependencies.searchAnalytics(input.site, { ...ranges.before, ...request }, { refresh: input.refresh }),\n dependencies.searchAnalytics(input.site, { ...ranges.after, ...request }, { refresh: input.refresh }),\n ]);\n return analyzeSegmentRows({\n site: input.site,\n dimension,\n before: ranges.before,\n after: ranges.after,\n beforeDays: segmentRangeDays(ranges.before),\n afterDays: segmentRangeDays(ranges.after),\n beforeRows: beforeResult.rows,\n afterRows: afterResult.rows,\n beforeRowsFetched: beforeResult.rowsFetched,\n afterRowsFetched: afterResult.rowsFetched,\n beforeCalls: beforeResult.calls,\n afterCalls: afterResult.calls,\n limit,\n unmatchedLimit,\n maxRows,\n generatedAt: now.toISOString(),\n });\n}\n//# sourceMappingURL=segment-impact.js.map","export class SessionLedger {\n entries = new Map();\n gscCalls = 0;\n gscRows = 0;\n addUsage(usage) {\n const current = this.entries.get(usage.provider);\n if (!current) {\n this.entries.set(usage.provider, { ...usage });\n return;\n }\n current.units += usage.units;\n current.calls += usage.calls;\n current.cacheHits = (current.cacheHits ?? 0) + (usage.cacheHits ?? 0);\n current.estimatedUsd =\n (current.estimatedUsd ?? 0) + (usage.estimatedUsd ?? 0);\n }\n addGsc(calls, rows) {\n this.gscCalls += calls;\n this.gscRows += rows;\n }\n summary() {\n const providerBits = [...this.entries.values()].map((entry) => {\n const money = entry.estimatedUsd\n ? ` (~$${entry.estimatedUsd.toFixed(2)})`\n : '';\n const cacheHits = entry.cacheHits\n ? ` · Cache hits: ${entry.cacheHits}`\n : '';\n return `${entry.provider}: ${entry.calls} calls, ${entry.units} ${entry.unitLabel}${money}${cacheHits}`;\n });\n providerBits.push(`GSC: ${this.gscCalls} calls, ${this.gscRows} rows`);\n return providerBits.join(' · ');\n }\n}\n//# sourceMappingURL=ledger.js.map","const LOCAL_QUERY_TERMS = [\n 'near me',\n 'today',\n 'tonight',\n 'calendar',\n 'schedule',\n 'time',\n 'times',\n 'high tide',\n 'low tide',\n 'tide chart',\n 'tide times',\n 'salary in',\n 'average salary',\n];\nconst GENERIC_TEMPLATE_TERMS = [\n 'last name',\n 'surname',\n 'meaning',\n 'origin',\n 'popularity',\n 'how rare',\n 'my last name',\n 'salary',\n 'wage',\n 'pay',\n 'tide',\n];\nfunction parseUrl(url) {\n try {\n return new URL(url);\n }\n catch {\n return undefined;\n }\n}\nfunction normalizeText(value) {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\nfunction pathParts(url) {\n return (parseUrl(url)?.pathname ?? '')\n .split('/')\n .map((part) => part.trim())\n .filter(Boolean);\n}\nexport function detectPageTemplate(url) {\n const parts = pathParts(url);\n const path = `/${parts.join('/')}/`;\n if (path.includes('/last-names/') && path.endsWith('-surname-popularity/')) {\n return {\n id: 'surname-entity',\n label: 'Surname entity page',\n confidence: 'high',\n };\n }\n if (path.includes('/last-names/')) {\n return {\n id: 'last-name-list',\n label: 'Last-name list page',\n confidence: 'high',\n };\n }\n if (path.includes('/first-names/') &&\n path.endsWith('-meaning-and-history/')) {\n return {\n id: 'first-name-entity',\n label: 'First-name entity page',\n confidence: 'high',\n };\n }\n if (path.includes('/first-names/')) {\n return {\n id: 'first-name-list',\n label: 'First-name list page',\n confidence: 'high',\n };\n }\n if (/\\/average-[a-z0-9-]+-salary-in-[a-z0-9-]+\\//.test(path)) {\n const locationDepth = parts.length >= 2 ? 'city' : 'country';\n return {\n id: `${locationDepth}-salary`,\n label: `${locationDepth === 'city' ? 'City' : 'Country'} salary page`,\n confidence: 'high',\n };\n }\n if (path.includes('/salary-calculator/')) {\n return {\n id: 'salary-calculator',\n label: 'Salary calculator page',\n confidence: 'high',\n };\n }\n if (parts.length >= 3 &&\n /\\b(tide|tides|harbour|harbor|marina|beach)\\b/.test(normalizeText(path))) {\n return {\n id: 'location-schedule',\n label: 'Location schedule page',\n confidence: 'medium',\n };\n }\n if (path.startsWith('/tools/')) {\n return { id: 'tool-page', label: 'Tool page', confidence: 'medium' };\n }\n if (path.startsWith('/alternatives/')) {\n return {\n id: 'alternative-page',\n label: 'Alternative page',\n confidence: 'medium',\n };\n }\n if (path.startsWith('/compare/')) {\n return {\n id: 'comparison-page',\n label: 'Comparison page',\n confidence: 'medium',\n };\n }\n return { id: 'other', label: 'Other page', confidence: 'low' };\n}\nexport function summarizeTemplates(items, limit = 5) {\n const byTemplate = new Map();\n for (const item of items) {\n const template = item.template ?? detectPageTemplate(item.url ?? '');\n const existing = byTemplate.get(template.id) ?? {\n id: template.id,\n label: template.label,\n count: 0,\n sampleUrls: [],\n };\n existing.count += 1;\n if (item.url && existing.sampleUrls.length < 3) {\n existing.sampleUrls.push(item.url);\n }\n byTemplate.set(template.id, existing);\n }\n return [...byTemplate.values()]\n .sort((a, b) => b.count - a.count)\n .slice(0, limit);\n}\nexport function isQuotedQuery(query) {\n return /[\"“”]/.test(query);\n}\nexport function isLikelyLocalOrEntityIntent(query) {\n const normalized = normalizeText(query);\n return LOCAL_QUERY_TERMS.some((term) => normalized.includes(term));\n}\nexport function isLikelyGenericTemplateQuery(query) {\n const normalized = normalizeText(query);\n return GENERIC_TEMPLATE_TERMS.some((term) => normalized.includes(term));\n}\nexport function dominantTemplate(rows) {\n const counts = new Map();\n for (const row of rows) {\n const template = detectPageTemplate(row.keys[1] ?? '');\n const existing = counts.get(template.id) ?? { template, count: 0 };\n existing.count += 1;\n counts.set(template.id, existing);\n }\n const top = [...counts.values()].sort((a, b) => b.count - a.count)[0];\n if (!top) {\n return { template: detectPageTemplate(''), share: 0 };\n }\n return { template: top.template, share: top.count / rows.length };\n}\nexport function templateFamilyId(template) {\n if (template.id.endsWith('-salary'))\n return 'salary-page';\n return template.id;\n}\nfunction templateFamilyLabel(template) {\n if (template.id.endsWith('-salary')) {\n return 'Salary page';\n }\n return template.label;\n}\nexport function dominantTemplateFamily(rows) {\n const counts = new Map();\n for (const row of rows) {\n const template = detectPageTemplate(row.keys[1] ?? '');\n const id = templateFamilyId(template);\n const existing = counts.get(id) ?? {\n id,\n label: templateFamilyLabel(template),\n count: 0,\n share: 0,\n template,\n };\n existing.count += 1;\n counts.set(id, existing);\n }\n const top = [...counts.values()].sort((a, b) => b.count - a.count)[0];\n if (!top) {\n return {\n id: 'other',\n label: 'Other page',\n count: 0,\n share: 0,\n template: detectPageTemplate(''),\n };\n }\n return { ...top, share: top.count / rows.length };\n}\n//# sourceMappingURL=page-patterns.js.map","export function compareCannibalText(left, right) {\n const leftPoints = [...left].map((value) => value.codePointAt(0) ?? 0);\n const rightPoints = [...right].map((value) => value.codePointAt(0) ?? 0);\n for (let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index++) {\n const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);\n if (difference)\n return difference;\n }\n return leftPoints.length - rightPoints.length;\n}\nexport function normalizeCannibalQuery(value) {\n return value.normalize('NFKC').toLowerCase().replace(/\\s+/g, ' ').trim();\n}\nexport function normalizeCannibalUrl(value) {\n try {\n const url = new URL(value);\n if (url.protocol !== 'http:' && url.protocol !== 'https:')\n return undefined;\n url.hash = '';\n return url.toString();\n }\n catch {\n return undefined;\n }\n}\nfunction validMetrics(row) {\n return (Number.isFinite(row.clicks) &&\n row.clicks >= 0 &&\n Number.isFinite(row.impressions) &&\n row.impressions > 0 &&\n row.clicks <= row.impressions &&\n Number.isFinite(row.ctr) &&\n row.ctr >= 0 &&\n row.ctr <= 1 &&\n Number.isFinite(row.position) &&\n row.position > 0);\n}\nexport function validCannibalRow(row, query, url) {\n return Boolean(query && url) && validMetrics(row);\n}\nexport function validCannibalPropertyRow(row, query) {\n return Boolean(query) && validMetrics(row);\n}\nexport function addCannibalRow(group, url, row) {\n const current = group.pages.get(url);\n const clicks = (current?.clicks ?? 0) + row.clicks;\n const impressions = (current?.impressions ?? 0) + row.impressions;\n const weightedPosition = (current?.position ?? 0) * (current?.impressions ?? 0) +\n row.position * row.impressions;\n group.pages.set(url, {\n url,\n clicks,\n impressions,\n ctr: clicks / impressions,\n position: weightedPosition / impressions,\n });\n}\n//# sourceMappingURL=cannibal-analysis-primitives.js.map","import { dominantTemplate, dominantTemplateFamily, isLikelyLocalOrEntityIntent, isQuotedQuery, } from '../page-patterns.js';\nimport { compareCannibalText } from './cannibal-analysis-primitives.js';\nexport function cannibalReviewContext(query, rows) {\n const context = [];\n if (isQuotedQuery(query))\n context.push('quoted-query');\n const family = dominantTemplateFamily(rows);\n const sameFamily = family.share >= 0.8 && family.id !== 'other';\n if (sameFamily)\n context.push('same-template-family');\n if (sameFamily && isLikelyLocalOrEntityIntent(query)) {\n context.push('local-or-entity-intent');\n }\n return context;\n}\nexport function cannibalBrandEvidence(query) {\n return `Query \"${query}\" was excluded as branded.`;\n}\nexport function cannibalTemplateRow(page, query) {\n return {\n keys: [query, page.url],\n clicks: page.clicks,\n impressions: page.impressions,\n ctr: page.ctr,\n position: page.position,\n };\n}\nfunction comparePages(left, right) {\n return (right.clicks - left.clicks ||\n right.impressions - left.impressions ||\n left.position - right.position ||\n compareCannibalText(left.url, right.url));\n}\nexport function createCannibalItem(input) {\n const { query, pages } = input;\n const materialClicks = pages.reduce((sum, page) => sum + page.clicks, 0);\n const materialImpressions = pages.reduce((sum, page) => sum + page.impressions, 0);\n const owner = [...pages].sort(comparePages)[0];\n const hhi = pages.reduce((sum, page) => sum + page.impressionShare ** 2, 0);\n const largestPageShare = Math.max(...pages.map((page) => page.impressionShare));\n const secondaryExposureShare = 1 - largestPageShare;\n const demandImpressions = input.propertyImpressions ?? input.pageExposureImpressions;\n const template = dominantTemplate(pages.map((page) => cannibalTemplateRow(page, query)));\n const suggestedOwnerUrl = owner?.url ?? pages[0]?.url ?? '';\n return {\n query,\n pages: [...pages].sort((left, right) => right.impressionShare - left.impressionShare ||\n comparePages(left, right)),\n pageCount: pages.length,\n materialPageClicks: Number(materialClicks.toFixed(3)),\n materialPageExposureImpressions: Number(materialImpressions.toFixed(3)),\n pageExposureImpressions: Number(input.pageExposureImpressions.toFixed(3)),\n propertyImpressions: input.propertyImpressions,\n observedPageExposureRatio: input.propertyImpressions && input.propertyImpressions > 0\n ? Number((input.pageExposureImpressions / input.propertyImpressions).toFixed(4))\n : undefined,\n additionalUrlExposures: input.propertyImpressions === undefined\n ? undefined\n : Number(Math.max(0, input.pageExposureImpressions - input.propertyImpressions).toFixed(3)),\n hhi: Number(hhi.toFixed(4)),\n splitScore: Number((1 - hhi).toFixed(4)),\n largestPageShare: Number(largestPageShare.toFixed(4)),\n secondaryExposureShare: Number(secondaryExposureShare.toFixed(4)),\n reviewContext: input.context,\n suggestedOwnerUrl,\n ownerSelection: {\n method: 'clicks_then_impressions_then_position',\n confidence: 'low',\n requiresIntentReview: true,\n },\n priority: {\n method: 'demand_impressions_x_secondary_exposure',\n score: Number((demandImpressions * secondaryExposureShare).toFixed(3)),\n demandImpressions: Number(demandImpressions.toFixed(3)),\n secondaryExposureShare: Number(secondaryExposureShare.toFixed(4)),\n heuristic: true,\n estimatedClickLift: false,\n },\n template: template.share >= 0.8 ? template.template : undefined,\n recommendation: {\n principle: 'C.6',\n evidenceRef: `GSC retained ${pages.length} material URLs for \"${query}\" across ${input.pageExposureImpressions.toFixed(0)} page exposures${input.propertyImpressions === undefined ? '' : ` and ${input.propertyImpressions.toFixed(0)} property impressions`}; the largest material URL share was ${(largestPageShare * 100).toFixed(1)}%.`,\n action: `Compare the intent and technical state of these URLs. If they satisfy the same intent, choose a preferred page and align internal links, canonicals, and on-page focus. If they satisfy different intents, keep them separate and clarify the distinction. Treat ${suggestedOwnerUrl} only as the first review candidate based on observed clicks, impressions, and position.`,\n effort: 'M',\n confidence: 'low',\n },\n };\n}\nexport function compareCannibalItems(left, right) {\n return (right.priority.score - left.priority.score ||\n right.priority.demandImpressions - left.priority.demandImpressions ||\n compareCannibalText(left.query, right.query));\n}\n//# sourceMappingURL=cannibal-item.js.map","import { shouldExcludeBrandQuery } from '../../brand.js';\nimport { detectPageTemplate, summarizeTemplates } from '../page-patterns.js';\nimport { isLowActionabilityQuery } from '../query-quality.js';\nimport { addCannibalRow, compareCannibalText, normalizeCannibalQuery, normalizeCannibalUrl, validCannibalPropertyRow, validCannibalRow, } from './cannibal-analysis-primitives.js';\nimport { cannibalBrandEvidence, cannibalReviewContext, cannibalTemplateRow, compareCannibalItems, createCannibalItem, } from './cannibal-item.js';\nconst MINIMUM_PAGE_SHARE = 0.1;\nconst MINIMUM_PAGE_IMPRESSIONS = 10;\nconst MAXIMUM_DOMINANT_SHARE = 0.8;\nconst MAX_SUPPRESSIONS = 100;\nfunction boundedInteger(value, fallback, minimum, maximum) {\n if (value === undefined || !Number.isFinite(value))\n return fallback;\n return Math.min(maximum, Math.max(minimum, Math.floor(value)));\n}\nexport function analyzeCannibalRows(input) {\n const minImpressions = boundedInteger(input.minImpressions, 50, 0, 1_000_000_000);\n const limit = boundedInteger(input.limit, 25, 1, 100);\n const selection = {\n sourceRows: input.rows.length,\n invalidRows: 0,\n validRows: 0,\n propertySourceRows: input.propertyRows?.length ?? 0,\n propertyInvalidRows: 0,\n propertyQueryGroups: 0,\n queryGroups: 0,\n lowActionabilityQueries: 0,\n brandQueries: 0,\n belowMinimumQueries: 0,\n singlePageQueries: 0,\n incidentalPages: 0,\n dominantQueries: 0,\n missingPropertyQueries: 0,\n suppressedQueries: 0,\n eligibleClusters: 0,\n returnedClusters: 0,\n limitedClusters: 0,\n returnedSuppressions: 0,\n limitedSuppressions: 0,\n };\n const groups = new Map();\n const propertyImpressions = new Map();\n for (const row of input.propertyRows ?? []) {\n const query = row.keys[0]?.trim() ?? '';\n if (!validCannibalPropertyRow(row, query)) {\n selection.propertyInvalidRows++;\n continue;\n }\n const key = normalizeCannibalQuery(query);\n propertyImpressions.set(key, (propertyImpressions.get(key) ?? 0) + row.impressions);\n }\n selection.propertyQueryGroups = propertyImpressions.size;\n for (const row of input.rows) {\n const query = row.keys[0]?.trim() ?? '';\n const url = normalizeCannibalUrl(row.keys[1]?.trim() ?? '');\n if (!validCannibalRow(row, query, url)) {\n selection.invalidRows++;\n continue;\n }\n const key = normalizeCannibalQuery(query);\n const group = groups.get(key) ?? { query, pages: new Map() };\n if (compareCannibalText(query, group.query) < 0)\n group.query = query;\n addCannibalRow(group, url ?? '', row);\n groups.set(key, group);\n selection.validRows++;\n }\n selection.queryGroups = groups.size;\n const items = [];\n const allSuppressed = [];\n for (const [queryKey, group] of groups.entries()) {\n const totalImpressions = [...group.pages.values()].reduce((sum, page) => sum + page.impressions, 0);\n const propertyDemand = propertyImpressions.get(queryKey);\n if (isLowActionabilityQuery(group.query)) {\n selection.lowActionabilityQueries++;\n continue;\n }\n if (shouldExcludeBrandQuery({\n query: group.query,\n siteUrl: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n })) {\n selection.brandQueries++;\n if (group.pages.size >= 2) {\n allSuppressed.push({\n query: group.query,\n reason: 'brand_query',\n urlCount: group.pages.size,\n evidenceRef: cannibalBrandEvidence(group.query),\n });\n }\n continue;\n }\n if ((propertyDemand ?? totalImpressions) < minImpressions) {\n selection.belowMinimumQueries++;\n continue;\n }\n if (group.pages.size < 2) {\n selection.singlePageQueries++;\n continue;\n }\n const pages = [...group.pages.values()].map((page) => ({\n ...page,\n clicks: Number(page.clicks.toFixed(3)),\n impressions: Number(page.impressions.toFixed(3)),\n ctr: Number(page.ctr.toFixed(4)),\n position: Number(page.position.toFixed(2)),\n impressionShare: Number((page.impressions / totalImpressions).toFixed(4)),\n template: detectPageTemplate(page.url),\n }));\n const retainedMaterialPages = pages.filter((page) => page.impressions >= MINIMUM_PAGE_IMPRESSIONS &&\n page.impressionShare >= MINIMUM_PAGE_SHARE);\n selection.incidentalPages += pages.length - retainedMaterialPages.length;\n if (retainedMaterialPages.length < 2) {\n selection.dominantQueries++;\n continue;\n }\n const materialImpressions = retainedMaterialPages.reduce((sum, page) => sum + page.impressions, 0);\n const materialPages = retainedMaterialPages.map((page) => ({\n ...page,\n impressionShare: Number((page.impressions / materialImpressions).toFixed(4)),\n }));\n const largestShare = Math.max(...materialPages.map((page) => page.impressionShare));\n if (largestShare > MAXIMUM_DOMINANT_SHARE) {\n selection.dominantQueries++;\n continue;\n }\n const templateRows = materialPages.map((page) => cannibalTemplateRow(page, group.query));\n if (propertyDemand === undefined)\n selection.missingPropertyQueries++;\n items.push(createCannibalItem({\n query: group.query,\n pages: materialPages,\n pageExposureImpressions: totalImpressions,\n propertyImpressions: propertyDemand,\n context: cannibalReviewContext(group.query, templateRows),\n }));\n }\n const eligibleItems = items.sort(compareCannibalItems);\n const returnedItems = eligibleItems.slice(0, limit);\n const orderedSuppressions = allSuppressed.sort((left, right) => compareCannibalText(left.query, right.query) ||\n compareCannibalText(left.reason, right.reason));\n const suppressed = orderedSuppressions.slice(0, MAX_SUPPRESSIONS);\n selection.suppressedQueries = allSuppressed.length;\n selection.eligibleClusters = eligibleItems.length;\n selection.returnedClusters = returnedItems.length;\n selection.limitedClusters = eligibleItems.length - returnedItems.length;\n selection.returnedSuppressions = suppressed.length;\n selection.limitedSuppressions = allSuppressed.length - suppressed.length;\n return {\n filters: {\n minImpressions,\n limit,\n brand: input.includeBrand ? 'included' : 'excluded',\n },\n selection,\n items: returnedItems,\n suppressed,\n suppressionSummary: allSuppressed.reduce((summary, item) => {\n summary[item.reason] = (summary[item.reason] ?? 0) + 1;\n return summary;\n }, {}),\n templates: summarizeTemplates(returnedItems.flatMap((item) => item.pages)),\n };\n}\nexport const CANNIBAL_MINIMUM_PAGE_SHARE = MINIMUM_PAGE_SHARE;\nexport const CANNIBAL_MAXIMUM_DOMINANT_SHARE = MAXIMUM_DOMINANT_SHARE;\n//# sourceMappingURL=cannibal-analysis.js.map","import { querySearchAnalytics } from '../../gsc/client.js';\nimport { SessionLedger } from '../../storage/ledger.js';\nimport { analyzeCannibalRows } from './cannibal-analysis.js';\nimport { defaultDateRange, explicitDateRange, integerOption, } from './quick-wins-report-input.js';\nexport * from './cannibal-analysis.js';\nconst MAX_GSC_ROWS = 100_000;\nconst defaultDependencies = {\n searchAnalytics: querySearchAnalytics,\n now: () => new Date(),\n};\nfunction verdict(input) {\n if (input.status === 'empty') {\n return 'Search Console returned no retained query/page rows for this window.';\n }\n if (!input.eligible) {\n if (input.status === 'partial') {\n return 'No material multi-URL query candidates remained in the validated retained rows, but partial evidence prevents an all-clear.';\n }\n return 'No material multi-URL query candidates remained after validation and filtering.';\n }\n const result = `${input.returned} of ${input.eligible} multi-URL query candidate${input.eligible === 1 ? '' : 's'} returned for intent and technical review.`;\n return input.status === 'partial'\n ? `${result} Provider evidence is partial.`\n : result;\n}\nexport async function cannibalReport(input, dependencies = defaultDependencies) {\n const days = integerOption({\n value: input.days,\n fallback: 28,\n minimum: 1,\n maximum: 548,\n label: 'days',\n });\n const limit = integerOption({\n value: input.limit,\n fallback: 25,\n minimum: 1,\n maximum: 100,\n label: 'limit',\n });\n const minImpressions = integerOption({\n value: input.minImpressions,\n fallback: 50,\n minimum: 0,\n maximum: 1_000_000_000,\n label: 'minImpressions',\n });\n const now = dependencies.now();\n const explicit = explicitDateRange(input, 548);\n const range = explicit?.range ?? defaultDateRange(days, now);\n const rangeDays = explicit?.days ?? days;\n const requestBase = {\n ...range,\n type: 'web',\n dataState: 'final',\n maxRows: MAX_GSC_ROWS,\n };\n const [pageExposure, propertyDemand] = await Promise.all([\n dependencies.searchAnalytics(input.site, {\n ...requestBase,\n dimensions: ['query', 'page'],\n aggregationType: 'auto',\n }, { refresh: input.refresh }),\n dependencies.searchAnalytics(input.site, {\n ...requestBase,\n dimensions: ['query'],\n aggregationType: 'byProperty',\n }, { refresh: input.refresh }),\n ]);\n const ledger = new SessionLedger();\n ledger.addGsc(pageExposure.calls, pageExposure.rowsFetched);\n ledger.addGsc(propertyDemand.calls, propertyDemand.rowsFetched);\n const analysis = analyzeCannibalRows({\n site: input.site,\n rows: pageExposure.rows,\n propertyRows: propertyDemand.rows,\n minImpressions,\n limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n const pageTruncated = pageExposure.rowsFetched >= MAX_GSC_ROWS;\n const propertyTruncated = propertyDemand.rowsFetched >= MAX_GSC_ROWS;\n const possiblyTruncated = pageTruncated || propertyTruncated;\n const invalidRows = analysis.selection.invalidRows + analysis.selection.propertyInvalidRows;\n const partialValidation = invalidRows > 0;\n const completeness = possiblyTruncated && partialValidation\n ? 'partial-and-possibly-truncated'\n : possiblyTruncated\n ? 'possibly-truncated'\n : partialValidation\n ? 'partial'\n : 'complete';\n const dataStatus = analysis.selection.sourceRows === 0\n ? 'empty'\n : possiblyTruncated ||\n partialValidation ||\n analysis.selection.missingPropertyQueries > 0\n ? 'partial'\n : analysis.selection.eligibleClusters === 0\n ? 'filtered'\n : 'complete';\n return {\n schemaVersion: 1,\n site: input.site,\n generatedAt: now.toISOString(),\n range,\n rangeDays,\n dataStatus,\n source: {\n provider: 'google-search-console',\n searchType: 'web',\n dataState: 'final',\n pageExposure: {\n dimensions: ['query', 'page'],\n aggregationType: 'auto',\n rowsFetched: pageExposure.rowsFetched,\n validation: {\n retainedRows: analysis.selection.validRows,\n invalidRows: analysis.selection.invalidRows,\n },\n calls: pageExposure.calls,\n maxRows: MAX_GSC_ROWS,\n possiblyTruncated: pageTruncated,\n },\n propertyDemand: {\n dimensions: ['query'],\n aggregationType: 'byProperty',\n rowsFetched: propertyDemand.rowsFetched,\n validation: {\n retainedRows: analysis.selection.propertySourceRows -\n analysis.selection.propertyInvalidRows,\n invalidRows: analysis.selection.propertyInvalidRows,\n },\n calls: propertyDemand.calls,\n maxRows: MAX_GSC_ROWS,\n possiblyTruncated: propertyTruncated,\n },\n completeness,\n },\n methodology: {\n id: 'gsc_url_overlap_v2',\n version: 2,\n minimumPageImpressions: 10,\n minimumPageImpressionShare: 0.1,\n maximumDominantPageShare: 0.8,\n matching: 'normalized_exact_query',\n finding: 'url-overlap-candidate',\n requiresIntentReview: true,\n },\n verification: {\n status: 'not-requested',\n technicalStateChecked: false,\n searchIntentChecked: false,\n },\n filters: analysis.filters,\n selection: analysis.selection,\n summary: {\n eligibleClusters: analysis.selection.eligibleClusters,\n returnedClusters: analysis.selection.returnedClusters,\n suppressedQueries: analysis.selection.suppressedQueries,\n brandFiltering: input.includeBrand ? 'included' : 'excluded',\n verdict: verdict({\n status: dataStatus,\n eligible: analysis.selection.eligibleClusters,\n returned: analysis.selection.returnedClusters,\n }),\n },\n templates: analysis.templates,\n suppressed: analysis.suppressed,\n suppressionSummary: analysis.suppressionSummary,\n items: analysis.items,\n caveats: [\n `Date window: ${range.startDate} to ${range.endDate} (${rangeDays} days), using final GSC data where available.`,\n 'This report finds queries with material exposure across multiple URLs. It does not prove that the URLs satisfy the same intent or that consolidation is correct.',\n 'Page exposure impressions can count more than one URL for a property impression. Property-level query impressions are reported separately instead of calling page exposure split demand.',\n 'Search Console retains top rows and omits anonymized queries, so absent rows are not proof of absent traffic.',\n ...(partialValidation\n ? [\n `${analysis.selection.invalidRows} invalid page-exposure row${analysis.selection.invalidRows === 1 ? '' : 's'} and ${analysis.selection.propertyInvalidRows} invalid property-demand row${analysis.selection.propertyInvalidRows === 1 ? '' : 's'} were excluded. Findings use validated retained rows only.`,\n ]\n : []),\n 'The suggested owner is only a deterministic review starting point based on clicks, impressions, and position. Verify intent, indexability, redirects, and canonicals before changing URLs.',\n ],\n recommendations: analysis.items.length\n ? [\n 'Review the highest-exposure candidates first. Confirm whether URLs serve the same intent and inspect technical state before changing canonicals, redirects, or content.',\n ]\n : partialValidation\n ? [\n 'No URL-overlap action is recommended from the validated retained rows. Inspect or refresh the provider data before treating this result as an all-clear.',\n ]\n : [\n 'No URL-overlap action is recommended from the retained rows and current filters.',\n ],\n ledgerSummary: ledger.summary(),\n };\n}\n//# sourceMappingURL=cannibal.js.map","import { detectPageTemplate } from '../page-patterns.js';\nexport function compareDecayText(left, right) {\n const leftPoints = [...left].map((value) => value.codePointAt(0) ?? 0);\n const rightPoints = [...right].map((value) => value.codePointAt(0) ?? 0);\n for (let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index++) {\n const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);\n if (difference)\n return difference;\n }\n return leftPoints.length - rightPoints.length;\n}\nexport function normalizeDecayQuery(value) {\n return value.normalize('NFKC').toLowerCase().replace(/\\s+/g, ' ').trim();\n}\nfunction normalizeUrl(value) {\n try {\n const url = new URL(value);\n if (url.protocol !== 'http:' && url.protocol !== 'https:')\n return undefined;\n url.hash = '';\n return url.toString();\n }\n catch {\n return undefined;\n }\n}\nfunction validRow(row, query, url) {\n return (Boolean(query && url) &&\n Number.isFinite(row.clicks) &&\n row.clicks >= 0 &&\n Number.isFinite(row.impressions) &&\n row.impressions > 0 &&\n row.clicks <= row.impressions &&\n Number.isFinite(row.ctr) &&\n row.ctr >= 0 &&\n row.ctr <= 1 &&\n Number.isFinite(row.position) &&\n row.position > 0);\n}\nexport function aggregateDecayRows(rows) {\n const grouped = new Map();\n let invalid = 0;\n for (const row of rows) {\n const query = row.keys[0]?.trim() ?? '';\n const url = normalizeUrl(row.keys[1]?.trim() ?? '');\n if (!validRow(row, query, url)) {\n invalid++;\n continue;\n }\n const key = `${normalizeDecayQuery(query)}\\u0000${url}`;\n const current = grouped.get(key);\n const clicks = (current?.clicks ?? 0) + row.clicks;\n const impressions = (current?.impressions ?? 0) + row.impressions;\n const position = ((current?.position ?? 0) * (current?.impressions ?? 0) +\n row.position * row.impressions) /\n impressions;\n grouped.set(key, {\n keys: [\n current && compareDecayText(current.keys[0], query) < 0\n ? current.keys[0]\n : query,\n url ?? '',\n ],\n clicks,\n impressions,\n ctr: clicks / impressions,\n position,\n });\n }\n return { rows: [...grouped.values()], invalid };\n}\nexport function decayMetrics(row) {\n return {\n clicks: Number(row.clicks.toFixed(3)),\n impressions: Number(row.impressions.toFixed(3)),\n ctr: Number(row.ctr.toFixed(4)),\n position: Number(row.position.toFixed(2)),\n };\n}\nexport function decayTemplate(url) {\n const detected = detectPageTemplate(url);\n if (detected.id !== 'other')\n return detected;\n const firstSegment = new URL(url).pathname.split('/').filter(Boolean)[0];\n return firstSegment\n ? {\n id: `path:${firstSegment}`,\n label: `/${firstSegment}/ pages`,\n confidence: 'low',\n }\n : { id: 'path:root', label: 'Homepage', confidence: 'high' };\n}\nexport function classifyDecay(current, previous) {\n const signals = ['click_decline'];\n if (current.position > previous.position + 1)\n signals.push('position_decline');\n if (current.impressions >= previous.impressions * 0.9 &&\n current.ctr < previous.ctr * 0.8) {\n signals.push('ctr_decline');\n }\n if (current.impressions < previous.impressions * 0.9)\n signals.push('impression_decline');\n const diagnosis = signals.includes('position_decline')\n ? 'lost_position'\n : signals.includes('ctr_decline')\n ? 'lost_ctr'\n : signals.includes('impression_decline')\n ? 'lost_impressions'\n : 'lost_clicks';\n return { diagnosis, signals };\n}\nexport function decayRecommendation(item) {\n const action = item.diagnosis === 'lost_position'\n ? 'Check indexability, canonical state, competing URLs, SERP intent, content changes, and internal links before refreshing the page.'\n : item.diagnosis === 'lost_ctr'\n ? 'Inspect the live SERP and query intent, then review title and meta framing before changing page content.'\n : item.diagnosis === 'lost_impressions'\n ? 'Check seasonality, query demand, SERP features, page indexability, and URL shifts before attributing this to content quality.'\n : 'Clicks declined without one strong position, CTR, or impression signal. Segment by device, country, and search appearance before choosing a fix.';\n return {\n principle: item.diagnosis === 'lost_ctr' ? 'C.3' : 'C.8',\n evidenceRef: `Retained GSC row for \"${item.query}\" on ${item.url}: ${item.previous.clicks.toFixed(1)} to ${item.current.clicks.toFixed(1)} clicks (${item.dropPct.toFixed(1)}% decline). Signals: ${item.signals.join(', ')}.`,\n action,\n effort: item.diagnosis === 'lost_ctr' ? 'S' : 'M',\n confidence: 'medium',\n };\n}\nexport function groupDecayItems(items) {\n const groups = new Map();\n for (const item of items) {\n const id = `${item.template.id}:${item.diagnosis}`;\n const state = groups.get(id) ?? {\n group: {\n id,\n label: `${item.template.label} - ${item.diagnosis.replaceAll('_', ' ')}`,\n diagnosis: item.diagnosis,\n template: item.template,\n count: 0,\n urlCount: 0,\n totalClickLoss: 0,\n totalPreviousClicks: 0,\n averageDropPct: 0,\n sampleQueries: [],\n sampleUrls: [],\n recommendation: '',\n },\n urls: new Set(),\n };\n const { group } = state;\n group.count++;\n group.totalClickLoss += item.clickLoss;\n group.totalPreviousClicks += item.previous.clicks;\n state.urls.add(item.url);\n if (!group.sampleQueries.includes(item.query) &&\n group.sampleQueries.length < 5)\n group.sampleQueries.push(item.query);\n if (!group.sampleUrls.includes(item.url) && group.sampleUrls.length < 3)\n group.sampleUrls.push(item.url);\n groups.set(id, state);\n }\n return [...groups.values()]\n .map(({ group, urls }) => ({\n ...group,\n urlCount: urls.size,\n totalClickLoss: Number(group.totalClickLoss.toFixed(3)),\n totalPreviousClicks: Number(group.totalPreviousClicks.toFixed(3)),\n averageDropPct: Number(((group.totalClickLoss / group.totalPreviousClicks) * 100).toFixed(1)),\n recommendation: `Review the shared ${group.template.label} pattern, but verify technical state, seasonality, and SERP intent before applying one change across ${group.count} retained query/page findings.`,\n }))\n .sort((left, right) => right.totalClickLoss - left.totalClickLoss ||\n compareDecayText(left.id, right.id));\n}\nexport function boundedDecayNumber(value, fallback, min, max) {\n if (value === undefined || !Number.isFinite(value))\n return fallback;\n return Math.min(max, Math.max(min, value));\n}\n//# sourceMappingURL=decay-analysis-primitives.js.map","import { shouldExcludeBrandQuery } from '../../brand.js';\nimport { summarizeTemplates } from '../page-patterns.js';\nimport { isSearchArtifactQuery } from '../query-quality.js';\nimport { aggregateDecayRows, boundedDecayNumber, classifyDecay, compareDecayText, decayMetrics, decayRecommendation, decayTemplate, groupDecayItems, normalizeDecayQuery, } from './decay-analysis-primitives.js';\nexport function analyzeDecay(input) {\n const minDropPct = boundedDecayNumber(input.minDropPct, 20, 0, 100);\n const minPreviousClicks = boundedDecayNumber(input.minPreviousClicks, 2, 0, 1_000_000_000);\n const minClickLoss = boundedDecayNumber(input.minClickLoss, 1, 0, 1_000_000_000);\n const limit = Math.floor(boundedDecayNumber(input.limit, 25, 1, 100));\n const current = aggregateDecayRows(input.currentRows);\n const previous = aggregateDecayRows(input.previousRows);\n const selection = {\n currentSourceRows: input.currentRows.length,\n previousSourceRows: input.previousRows.length,\n currentInvalidRows: current.invalid,\n previousInvalidRows: previous.invalid,\n currentAggregatedRows: current.rows.length,\n previousAggregatedRows: previous.rows.length,\n lowEvidenceRows: 0,\n lowActionabilityRows: 0,\n brandRows: 0,\n currentRowNotRetained: 0,\n urlShiftRows: 0,\n belowClickLossRows: 0,\n belowDropRows: 0,\n eligibleRows: 0,\n returnedRows: 0,\n limitedRows: 0,\n eligibleGroups: 0,\n returnedGroups: 0,\n limitedGroups: 0,\n };\n const currentByKey = new Map(current.rows.map((row) => [\n `${normalizeDecayQuery(row.keys[0])}\\u0000${row.keys[1]}`,\n row,\n ]));\n const currentUrlsByQuery = new Map();\n for (const row of current.rows) {\n const key = normalizeDecayQuery(row.keys[0]);\n const urls = currentUrlsByQuery.get(key) ?? new Set();\n urls.add(row.keys[1]);\n currentUrlsByQuery.set(key, urls);\n }\n const items = [];\n for (const previousRow of previous.rows) {\n const query = previousRow.keys[0];\n const url = previousRow.keys[1];\n if (previousRow.clicks <= 0 || previousRow.clicks < minPreviousClicks) {\n selection.lowEvidenceRows++;\n continue;\n }\n if (isSearchArtifactQuery(query)) {\n selection.lowActionabilityRows++;\n continue;\n }\n if (shouldExcludeBrandQuery({\n query,\n siteUrl: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n })) {\n selection.brandRows++;\n continue;\n }\n const key = `${normalizeDecayQuery(query)}\\u0000${url}`;\n const currentRow = currentByKey.get(key);\n if (!currentRow) {\n const currentUrls = currentUrlsByQuery.get(normalizeDecayQuery(query));\n if (currentUrls?.size)\n selection.urlShiftRows++;\n else\n selection.currentRowNotRetained++;\n continue;\n }\n const clickLoss = previousRow.clicks - currentRow.clicks;\n if (clickLoss <= 0 || clickLoss < minClickLoss) {\n selection.belowClickLossRows++;\n continue;\n }\n const dropPct = (clickLoss / previousRow.clicks) * 100;\n if (dropPct < minDropPct) {\n selection.belowDropRows++;\n continue;\n }\n const classification = classifyDecay(currentRow, previousRow);\n const base = {\n query,\n url,\n template: decayTemplate(url),\n clickLoss: Number(clickLoss.toFixed(3)),\n dropPct: Number(dropPct.toFixed(1)),\n current: decayMetrics(currentRow),\n previous: decayMetrics(previousRow),\n diagnosis: classification.diagnosis,\n signals: classification.signals,\n evidenceScope: 'retained-query-page-row',\n };\n items.push({ ...base, recommendation: decayRecommendation(base) });\n }\n const eligible = items.sort((left, right) => right.clickLoss - left.clickLoss ||\n right.previous.clicks - left.previous.clicks ||\n compareDecayText(left.query, right.query) ||\n compareDecayText(left.url, right.url));\n const returned = eligible.slice(0, limit);\n const eligibleObservedRetainedQueryClickLoss = Number(eligible.reduce((sum, item) => sum + item.clickLoss, 0).toFixed(3));\n const returnedObservedRetainedQueryClickLoss = Number(returned.reduce((sum, item) => sum + item.clickLoss, 0).toFixed(3));\n selection.eligibleRows = eligible.length;\n selection.returnedRows = returned.length;\n selection.limitedRows = eligible.length - returned.length;\n const eligibleGroups = groupDecayItems(eligible);\n const groups = eligibleGroups.slice(0, 100);\n selection.eligibleGroups = eligibleGroups.length;\n selection.returnedGroups = groups.length;\n selection.limitedGroups = eligibleGroups.length - groups.length;\n return {\n selection,\n totals: {\n eligibleObservedRetainedQueryClickLoss,\n returnedObservedRetainedQueryClickLoss,\n },\n items: returned,\n groups,\n templates: summarizeTemplates(returned),\n };\n}\n//# sourceMappingURL=decay-analysis.js.map","import { SeoError } from '../../errors.js';\nimport { querySearchAnalytics } from '../../gsc/client.js';\nimport { SessionLedger } from '../../storage/ledger.js';\nimport { analyzeDecay } from './decay-analysis.js';\nimport { decayComparisonRange, decayNumberOption, validateDecayRanges, } from './decay-report-input.js';\nimport { defaultDateRange, explicitDateRange, integerOption, } from './quick-wins-report-input.js';\nexport { decayComparisonRange } from './decay-report-input.js';\nconst MAX_GSC_ROWS = 100_000;\nconst defaultDependencies = {\n searchAnalytics: querySearchAnalytics,\n now: () => new Date(),\n};\nfunction verdict(report) {\n if (report.dataStatus === 'empty')\n return 'Search Console returned no retained query/page rows for either comparison window.';\n if (report.dataStatus === 'partial' &&\n report.selection.currentAggregatedRows === 0) {\n return 'The current retained-row window is empty, so no query/page losses were inferred.';\n }\n if (report.dataStatus === 'partial' &&\n report.selection.previousAggregatedRows === 0) {\n return 'The comparison retained-row window is empty, so query/page decay could not be measured.';\n }\n if (!report.selection.eligibleRows) {\n return 'No observed retained query/page declines matched the report filters.';\n }\n return `${report.selection.returnedRows} of ${report.selection.eligibleRows} observed retained query/page declines returned for review.`;\n}\nexport async function decayingReport(input, dependencies = defaultDependencies) {\n if (input.comparison !== undefined &&\n input.comparison !== 'previous-period' &&\n input.comparison !== 'year-over-year') {\n throw new SeoError('INVALID_INPUT', 'comparison must be previous-period or year-over-year.');\n }\n if (input.brandTerms &&\n (input.brandTerms.length > 20 ||\n input.brandTerms.some((term) => !term.trim() || term.trim().length > 200))) {\n throw new SeoError('INVALID_INPUT', 'brandTerms must contain at most 20 non-empty terms of 200 characters or fewer.');\n }\n const days = integerOption({\n value: input.days,\n fallback: 28,\n minimum: 1,\n maximum: 548,\n label: 'days',\n });\n const limit = integerOption({\n value: input.limit,\n fallback: 25,\n minimum: 1,\n maximum: 100,\n label: 'limit',\n });\n const minDropPct = decayNumberOption({\n value: input.minDropPct,\n fallback: 20,\n minimum: 0,\n maximum: 100,\n label: 'minDropPct',\n });\n const minPreviousClicks = decayNumberOption({\n value: input.minPreviousClicks,\n fallback: 2,\n minimum: 0,\n maximum: 1_000_000_000,\n label: 'minPreviousClicks',\n });\n const minClickLoss = decayNumberOption({\n value: input.minClickLoss,\n fallback: 1,\n minimum: 0,\n maximum: 1_000_000_000,\n label: 'minClickLoss',\n });\n const now = dependencies.now();\n const explicit = explicitDateRange(input, 548);\n const currentRange = explicit?.range ?? defaultDateRange(days, now);\n const comparison = input.comparison ?? 'previous-period';\n const previousRange = decayComparisonRange(currentRange, comparison);\n validateDecayRanges({\n current: currentRange,\n previous: previousRange,\n now,\n });\n const request = {\n dimensions: ['query', 'page'],\n aggregationType: 'auto',\n type: 'web',\n dataState: 'final',\n maxRows: MAX_GSC_ROWS,\n };\n const [current, previous] = await Promise.all([\n dependencies.searchAnalytics(input.site, { ...request, ...currentRange }, { refresh: input.refresh }),\n dependencies.searchAnalytics(input.site, { ...request, ...previousRange }, { refresh: input.refresh }),\n ]);\n const ledger = new SessionLedger();\n ledger.addGsc(current.calls, current.rowsFetched);\n ledger.addGsc(previous.calls, previous.rowsFetched);\n const analysis = analyzeDecay({\n site: input.site,\n currentRows: current.rows,\n previousRows: previous.rows,\n minDropPct,\n minPreviousClicks,\n minClickLoss,\n limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n const currentTruncated = current.rowsFetched >= MAX_GSC_ROWS;\n const previousTruncated = previous.rowsFetched >= MAX_GSC_ROWS;\n const possiblyTruncated = currentTruncated || previousTruncated;\n const dataStatus = current.rowsFetched === 0 && previous.rowsFetched === 0\n ? 'empty'\n : current.rowsFetched === 0 ||\n previous.rowsFetched === 0 ||\n possiblyTruncated ||\n analysis.selection.currentInvalidRows > 0 ||\n analysis.selection.previousInvalidRows > 0 ||\n analysis.selection.currentRowNotRetained > 0\n ? 'partial'\n : analysis.selection.eligibleRows === 0\n ? 'filtered'\n : 'complete';\n const reportBase = { dataStatus, selection: analysis.selection };\n return {\n schemaVersion: 1,\n site: input.site,\n generatedAt: now.toISOString(),\n comparison,\n ranges: { current: currentRange, previous: previousRange },\n rangeDays: explicit?.days ?? days,\n dataStatus,\n source: {\n provider: 'google-search-console',\n dimensions: ['query', 'page'],\n aggregationType: 'auto',\n searchType: 'web',\n dataState: 'final',\n current: {\n rowsFetched: current.rowsFetched,\n calls: current.calls,\n maxRows: MAX_GSC_ROWS,\n possiblyTruncated: currentTruncated,\n },\n previous: {\n rowsFetched: previous.rowsFetched,\n calls: previous.calls,\n maxRows: MAX_GSC_ROWS,\n possiblyTruncated: previousTruncated,\n },\n completeness: possiblyTruncated\n ? 'possibly-truncated'\n : 'retained-query-rows-only',\n },\n methodology: {\n id: 'gsc_retained_query_page_decay_v2',\n version: 2,\n gscHistoryMonths: 16,\n missingRowsTreatedAsZero: false,\n urlShiftsExcluded: true,\n causeLanguage: 'signals-not-attribution',\n },\n filters: {\n minDropPct,\n minPreviousClicks,\n minClickLoss,\n limit,\n brand: input.includeBrand ? 'included' : 'excluded',\n },\n selection: analysis.selection,\n summary: {\n eligibleRows: analysis.selection.eligibleRows,\n returnedRows: analysis.selection.returnedRows,\n groups: analysis.selection.eligibleGroups,\n observedRetainedQueryClickLoss: analysis.totals.eligibleObservedRetainedQueryClickLoss,\n returnedObservedRetainedQueryClickLoss: analysis.totals.returnedObservedRetainedQueryClickLoss,\n brandFiltering: input.includeBrand ? 'included' : 'excluded',\n verdict: verdict(reportBase),\n },\n caveats: [\n `Current window: ${currentRange.startDate} to ${currentRange.endDate}; comparison: ${previousRange.startDate} to ${previousRange.endDate}.`,\n 'Only declines observed in retained GSC query/page rows are counted. Missing current rows are reported in selection and never converted to zero traffic.',\n 'Queries retained on a different current URL are counted as URL shifts and excluded from content-decay actions.',\n 'Search Console API history is limited to a rolling 16 months. Ranges outside that horizon are rejected instead of compared partially.',\n 'Search Console omits anonymized and lower-volume rows and does not guarantee every row. Signals do not establish cause.',\n ],\n recommendations: analysis.groups.length\n ? analysis.groups.slice(0, 5).map((group) => group.recommendation)\n : [\n 'No content-decay action is recommended from the observed retained rows.',\n ],\n items: analysis.items,\n groups: analysis.groups,\n templates: analysis.templates,\n ledgerSummary: ledger.summary(),\n warnings: [\n ...(possiblyTruncated\n ? [\n 'At least one GSC window reached the 100,000-row safety cap. Results may be truncated.',\n ]\n : []),\n ...(analysis.selection.currentRowNotRetained\n ? [\n `${analysis.selection.currentRowNotRetained} previous query/page rows were not retained in the current response and were excluded rather than treated as zero.`,\n ]\n : []),\n ...(analysis.selection.currentInvalidRows ||\n analysis.selection.previousInvalidRows\n ? [\n `${analysis.selection.currentInvalidRows} current and ${analysis.selection.previousInvalidRows} comparison rows had invalid dimensions or metrics and were excluded.`,\n ]\n : []),\n ...(previous.rowsFetched === 0 && current.rowsFetched > 0\n ? [\n 'The comparison window returned no retained query/page rows, so decay could not be measured.',\n ]\n : []),\n ...(analysis.selection.urlShiftRows\n ? [\n `${analysis.selection.urlShiftRows} previous query/page rows now appear under another URL and were excluded from content-decay actions.`,\n ]\n : []),\n ],\n };\n}\n//# sourceMappingURL=decaying.js.map","function normalizedQuery(value) {\n return value\n .normalize('NFKC')\n .toLocaleLowerCase('und')\n .replace(/\\s+/gu, ' ')\n .trim();\n}\nfunction groupKey(item) {\n return `${item.template.id}:${normalizedQuery(item.query)}`;\n}\nfunction compareText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\nfunction groupAction(input) {\n if (input.technicalUrls > 0) {\n return `${input.technicalUrls} of ${input.group.urlCount} affected URLs have verified technical evidence. Fix those HTTP, indexability, redirect, or canonical issues before testing shared search-framing changes.`;\n }\n return `${input.group.urlCount} distinct ${input.group.template.label.toLowerCase()} URLs share the query pattern \"${input.group.query}\". Compare their live search results and verified page evidence before testing a shared title, snippet, or heading change.`;\n}\nexport function groupQuickWins(items) {\n const groups = new Map();\n for (const item of items) {\n const key = groupKey(item);\n groups.set(key, [...(groups.get(key) ?? []), item]);\n }\n return [...groups.entries()]\n .map(([id, groupItems]) => {\n const first = groupItems[0];\n if (!first || first.template.confidence === 'low')\n return undefined;\n const urls = [...new Set(groupItems.map((item) => item.url))];\n if (urls.length < 2)\n return undefined;\n const technicalUrls = new Set(groupItems\n .filter((item) => item.contentVerification?.classification === 'technical-check')\n .map((item) => item.url)).size;\n const group = {\n id,\n label: `${first.template.label} - ${first.query}`,\n query: first.query,\n template: first.template,\n rowCount: groupItems.length,\n urlCount: urls.length,\n totalEstimatedCtrClickShortfall: Number(groupItems\n .reduce((sum, item) => sum + item.estimatedCtrClickShortfall, 0)\n .toFixed(2)),\n totalImpressions: Number(groupItems\n .reduce((sum, item) => sum + item.impressions, 0)\n .toFixed(0)),\n sampleUrls: urls.slice(0, 3),\n recommendation: '',\n };\n group.recommendation = groupAction({ group, technicalUrls });\n return group;\n })\n .filter((group) => group !== undefined)\n .sort((left, right) => right.totalEstimatedCtrClickShortfall -\n left.totalEstimatedCtrClickShortfall ||\n right.totalImpressions - left.totalImpressions ||\n compareText(left.id, right.id));\n}\n//# sourceMappingURL=quick-win-groups.js.map","import { shouldExcludeBrandQuery } from '../../brand.js';\nimport { detectPageTemplate } from '../page-patterns.js';\nimport { isLowActionabilityQuery } from '../query-quality.js';\nexport function boundedInteger(value, fallback, minimum, maximum) {\n if (value === undefined || !Number.isFinite(value))\n return fallback;\n return Math.min(maximum, Math.max(minimum, Math.floor(value)));\n}\nfunction validHttpUrl(value) {\n try {\n const url = new URL(value);\n return url.protocol === 'http:' || url.protocol === 'https:';\n }\n catch {\n return false;\n }\n}\nfunction validRow(row, query, url) {\n return (row.keys.length >= 2 &&\n Boolean(query) &&\n validHttpUrl(url) &&\n Number.isFinite(row.clicks) &&\n row.clicks >= 0 &&\n Number.isFinite(row.impressions) &&\n row.impressions > 0 &&\n row.clicks <= row.impressions &&\n Number.isFinite(row.ctr) &&\n row.ctr >= 0 &&\n row.ctr <= 1 &&\n Number.isFinite(row.position) &&\n row.position >= 1);\n}\nexport function selectBenchmarkRows(input) {\n const selection = {\n sourceRows: input.rows.length,\n invalidRows: 0,\n outsideBenchmarkPositionRows: 0,\n lowActionabilityRows: 0,\n brandRows: 0,\n benchmarkRows: 0,\n outsideCandidatePositionRows: 0,\n belowMinimumRows: 0,\n atOrAboveTargetRows: 0,\n eligibleRows: 0,\n returnedRows: 0,\n limitedRows: 0,\n };\n const rows = [];\n for (const row of input.rows) {\n const query = row.keys[0]?.trim() ?? '';\n const url = row.keys[1]?.trim() ?? '';\n if (!validRow(row, query, url)) {\n selection.invalidRows++;\n }\n else if (row.position > 10) {\n selection.outsideBenchmarkPositionRows++;\n }\n else if (isLowActionabilityQuery(query)) {\n selection.lowActionabilityRows++;\n }\n else if (shouldExcludeBrandQuery({\n query,\n siteUrl: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n })) {\n selection.brandRows++;\n }\n else {\n rows.push({ ...row, keys: [query, url] });\n selection.benchmarkRows++;\n }\n }\n return { rows, selection };\n}\nfunction benchmarkDetails(input) {\n return {\n targetCtr: input.benchmark.ctr,\n source: input.benchmark.source,\n samplePopulation: 'all_qualified_url_samples',\n peerRows: input.benchmark.rows,\n peerImpressions: input.benchmark.impressions,\n qualifiedPeerImpressions: input.benchmark.qualifiedImpressions,\n urlSamples: input.benchmark.urlSamples,\n positiveUrlSamples: input.benchmark.positiveUrlSamples,\n excludedTargetRows: input.excludedTargetRows,\n leaveOut: 'target_url',\n confidence: input.benchmark.source.startsWith('site_gsc_')\n ? 'site-data'\n : 'fallback',\n heuristic: true,\n };\n}\nexport function quickWinItem(input) {\n const query = input.row.keys[0] ?? '';\n const url = input.row.keys[1] ?? '';\n const estimatedCtrClickShortfall = Number((Math.max(0, input.benchmark.ctr - input.row.ctr) * input.row.impressions).toFixed(2));\n const benchmark = benchmarkDetails({\n benchmark: input.benchmark,\n excludedTargetRows: input.excludedTargetRows,\n });\n return {\n query,\n url,\n template: detectPageTemplate(url),\n position: input.row.position,\n clicks: input.row.clicks,\n impressions: input.row.impressions,\n ctr: input.row.ctr,\n targetCtr: input.benchmark.ctr,\n benchmark,\n estimatedCtrClickShortfall,\n priority: {\n method: 'impressions_x_target_ctr_shortfall',\n score: estimatedCtrClickShortfall,\n heuristic: true,\n estimatedClickLift: false,\n },\n finding: 'ctr-target-shortfall',\n recommendation: {\n principle: 'C.3',\n evidenceRef: `GSC average position is ${input.row.position.toFixed(1)} with ${input.row.impressions} impressions and CTR ${input.row.ctr.toFixed(4)} versus a heuristic target of ${input.benchmark.ctr.toFixed(4)} from ${benchmark.source}.`,\n action: 'Inspect the live search result, query intent, title, snippet, device/country mix, and page evidence before choosing an edit.',\n effort: 'S',\n confidence: 'low',\n impactEstimate: `${estimatedCtrClickShortfall.toFixed(2)} calculated CTR click shortfall in this window if observed CTR matched the heuristic target; this is not a traffic forecast.`,\n },\n };\n}\nfunction compareText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\nexport function compareQuickWinItems(left, right) {\n return (right.estimatedCtrClickShortfall - left.estimatedCtrClickShortfall ||\n right.impressions - left.impressions ||\n compareText(left.query, right.query) ||\n compareText(left.url, right.url));\n}\nexport function roundedSum(values) {\n return Number(values.reduce((sum, value) => sum + value, 0).toFixed(2));\n}\n//# sourceMappingURL=quick-wins-analysis-primitives.js.map","import { createCtrBenchmarkContext } from '../opportunity-primitives.js';\nimport { samePageUrl } from '../page-technical-signals.js';\nimport { CTR_BASELINE } from '../shared.js';\nimport { boundedInteger, compareQuickWinItems, quickWinItem, roundedSum, selectBenchmarkRows, } from './quick-wins-analysis-primitives.js';\nconst DEFAULT_MIN_IMPRESSIONS = 200;\nconst MAX_MIN_IMPRESSIONS = 1_000_000_000;\nconst DEFAULT_LIMIT = 25;\nconst MAX_LIMIT = 100;\nconst FALLBACK_SOURCE = 'builtin_position_ctr_curve_v1';\nexport function analyzeQuickWinsFromRows(input) {\n const minImpressions = boundedInteger(input.minImpressions, DEFAULT_MIN_IMPRESSIONS, 0, MAX_MIN_IMPRESSIONS);\n const limit = boundedInteger(input.limit, DEFAULT_LIMIT, 1, MAX_LIMIT);\n const selected = selectBenchmarkRows(input);\n const benchmarkContext = createCtrBenchmarkContext(selected.rows, {\n samplePopulation: 'all_qualified_url_samples',\n fallbackSource: FALLBACK_SOURCE,\n });\n const eligibleItems = [];\n for (const row of selected.rows) {\n if (row.position < 4) {\n selected.selection.outsideCandidatePositionRows++;\n continue;\n }\n if (row.impressions < minImpressions) {\n selected.selection.belowMinimumRows++;\n continue;\n }\n const targetUrl = row.keys[1] ?? '';\n const excludedTargetRows = selected.rows.filter((candidate) => samePageUrl(candidate.keys[1] ?? '', targetUrl)).length;\n const benchmark = benchmarkContext.forUrl(row);\n if (row.ctr >= benchmark.ctr) {\n selected.selection.atOrAboveTargetRows++;\n continue;\n }\n eligibleItems.push(quickWinItem({ row, benchmark, excludedTargetRows }));\n selected.selection.eligibleRows++;\n }\n eligibleItems.sort(compareQuickWinItems);\n const items = eligibleItems.slice(0, limit);\n selected.selection.returnedRows = items.length;\n selected.selection.limitedRows = eligibleItems.length - items.length;\n return {\n site: input.site,\n minImpressions,\n limit,\n dataStatus: input.rows.length === 0\n ? 'empty'\n : eligibleItems.length === 0\n ? 'filtered'\n : 'available',\n selection: selected.selection,\n methodology: {\n id: 'gsc_quick_wins_v2',\n source: 'google_search_console_query_page_rows',\n position: {\n metric: 'gsc_average_position',\n minimumInclusive: 4,\n maximumInclusive: 10,\n },\n benchmark: {\n method: 'position_bucket_url_p75_v2',\n samplePopulation: 'all_qualified_url_samples',\n leaveOut: 'target_url',\n minimumUrlImpressions: 30,\n minimumQualifiedImpressions: 1000,\n minimumUrlSamples: 5,\n minimumPositiveUrlSamples: 3,\n fallback: {\n id: 'seo_builtin_position_ctr',\n version: 1,\n kind: 'built_in_heuristic',\n curve: Object.fromEntries(Object.entries(CTR_BASELINE).map(([position, ctr]) => [\n position,\n ctr,\n ])),\n },\n heuristic: true,\n },\n priority: {\n method: 'impressions_x_target_ctr_shortfall',\n formula: 'impressions * max(0, target CTR - observed CTR)',\n heuristic: true,\n estimatedClickLift: false,\n },\n },\n provenance: {\n inputScope: 'provided_rows',\n selectionOrder: [\n 'valid_row',\n 'benchmark_position',\n 'query_quality',\n 'brand',\n 'candidate_position',\n 'minimum_impressions',\n 'target_ctr_shortfall',\n 'limit',\n ],\n selection: selected.selection,\n },\n summary: {\n eligibleRows: eligibleItems.length,\n returnedRows: items.length,\n eligibleImpressions: roundedSum(eligibleItems.map((item) => item.impressions)),\n returnedImpressions: roundedSum(items.map((item) => item.impressions)),\n eligibleEstimatedCtrClickShortfall: roundedSum(eligibleItems.map((item) => item.estimatedCtrClickShortfall)),\n returnedEstimatedCtrClickShortfall: roundedSum(items.map((item) => item.estimatedCtrClickShortfall)),\n uniqueEligibleUrls: new Set(eligibleItems.map((item) => item.url)).size,\n uniqueEligibleQueries: new Set(eligibleItems.map((item) => item.query))\n .size,\n },\n items,\n eligibleItems,\n benchmarkByPosition: benchmarkContext.byPosition,\n };\n}\n//# sourceMappingURL=quick-wins-analysis.js.map","function compareText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\nfunction unique(values) {\n return [...new Set(values.filter(Boolean))];\n}\nexport function quickWinTemplateRecommendations(items) {\n const byTemplate = new Map();\n for (const item of items) {\n byTemplate.set(item.template.id, [\n ...(byTemplate.get(item.template.id) ?? []),\n item,\n ]);\n }\n return [...byTemplate.entries()]\n .map(([templateId, templateItems]) => {\n const first = templateItems[0];\n if (!first || first.template.confidence === 'low')\n return undefined;\n const urls = [...new Set(templateItems.map((item) => item.url))];\n if (urls.length < 2)\n return undefined;\n const technicalUrls = new Set(templateItems\n .filter((item) => item.contentVerification?.classification === 'technical-check')\n .map((item) => item.url)).size;\n const queries = unique(templateItems.map((item) => item.query)).slice(0, 3);\n return {\n templateId,\n templateLabel: first.template.label,\n rowCount: templateItems.length,\n urlCount: urls.length,\n totalEstimatedCtrClickShortfall: Number(templateItems\n .reduce((sum, item) => sum + item.estimatedCtrClickShortfall, 0)\n .toFixed(2)),\n totalImpressions: Number(templateItems\n .reduce((sum, item) => sum + item.impressions, 0)\n .toFixed(0)),\n action: technicalUrls > 0\n ? `Fix verified technical issues on ${technicalUrls} affected URLs before testing shared template changes.`\n : `Compare live results and verified page evidence for ${urls.length} affected URLs before testing a shared title, snippet, or heading change.`,\n evidence: `${templateItems.length} eligible rows across ${urls.length} distinct URLs share this recognised template. Example queries: ${queries.join('; ')}.`,\n };\n })\n .filter((item) => item !== undefined)\n .sort((left, right) => right.totalEstimatedCtrClickShortfall -\n left.totalEstimatedCtrClickShortfall ||\n right.totalImpressions - left.totalImpressions ||\n compareText(left.templateId, right.templateId));\n}\nexport function quickWinTemplateSummaries(items) {\n const templates = new Map();\n for (const item of items) {\n const current = templates.get(item.template.id) ?? {\n label: item.template.label,\n rows: 0,\n urls: new Set(),\n };\n current.rows++;\n current.urls.add(item.url);\n templates.set(item.template.id, current);\n }\n return [...templates.entries()]\n .map(([id, item]) => ({\n id,\n label: item.label,\n rowCount: item.rows,\n urlCount: item.urls.size,\n sampleUrls: [...item.urls].sort(compareText).slice(0, 3),\n }))\n .sort((left, right) => right.urlCount - left.urlCount ||\n right.rowCount - left.rowCount ||\n compareText(left.id, right.id))\n .slice(0, 5);\n}\n//# sourceMappingURL=quick-wins-templates.js.map","import { extractPage } from '../../extract/page-extractor.js';\nimport { fetchPage } from '../../fetch/page-fetcher.js';\nimport { querySearchAnalytics } from '../../gsc/client.js';\nimport { SessionLedger } from '../../storage/ledger.js';\nimport { contentCoverageRecommendation, verifyQueryContent, } from '../content-coverage.js';\nimport { groupQuickWins } from './quick-win-groups.js';\nimport { analyzeQuickWinsFromRows } from './quick-wins-analysis.js';\nimport { defaultDateRange, explicitDateRange, integerOption, } from './quick-wins-report-input.js';\nimport { quickWinTemplateRecommendations, quickWinTemplateSummaries, } from './quick-wins-templates.js';\nexport * from './quick-wins-analysis.js';\nconst DEFAULT_DAYS = 28;\nconst MAX_DAYS = 548;\nconst DEFAULT_VERIFY_LIMIT = 5;\nconst MAX_VERIFY_LIMIT = 100;\nconst MAX_SOURCE_ROWS = 100_000;\nconst defaultDependencies = {\n searchAnalytics: querySearchAnalytics,\n fetch: fetchPage,\n extract: extractPage,\n now: () => new Date(),\n};\nfunction unique(values) {\n return [...new Set(values.filter(Boolean))];\n}\nfunction applyVerification(item, coverage) {\n item.contentVerification = coverage;\n item.finding = coverage.classification;\n item.recommendation = {\n ...item.recommendation,\n action: contentCoverageRecommendation(coverage),\n confidence: coverage.status === 'verified' && coverage.classification !== 'covered'\n ? 'medium'\n : 'low',\n evidenceRef: `${item.recommendation.evidenceRef} ${coverage.summary}`,\n };\n}\nexport async function quickWinsReport(input, dependencies = defaultDependencies) {\n const explicitRange = explicitDateRange(input, MAX_DAYS);\n const days = explicitRange?.days ??\n integerOption({\n value: input.days,\n fallback: DEFAULT_DAYS,\n minimum: 1,\n maximum: MAX_DAYS,\n label: 'Days',\n });\n const verifyLimit = integerOption({\n value: input.verifyLimit,\n fallback: DEFAULT_VERIFY_LIMIT,\n minimum: 0,\n maximum: MAX_VERIFY_LIMIT,\n label: 'Verification limit',\n });\n const generatedAt = dependencies.now().toISOString();\n const range = explicitRange?.range ?? defaultDateRange(days, new Date(generatedAt));\n const source = await dependencies.searchAnalytics(input.site, {\n ...range,\n dimensions: ['query', 'page'],\n type: 'web',\n dataState: 'final',\n maxRows: MAX_SOURCE_ROWS,\n }, { refresh: input.refresh });\n const ledger = new SessionLedger();\n ledger.addGsc(source.calls, source.rowsFetched);\n const analysis = analyzeQuickWinsFromRows({\n rows: source.rows,\n site: input.site,\n minImpressions: input.minImpressions,\n limit: input.limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n const verificationRequested = input.verifyContent === true || input.verifyLimit !== undefined;\n const verificationItems = verificationRequested\n ? analysis.items.slice(0, verifyLimit)\n : [];\n const fetches = new Map();\n const cachedFetch = (url, options) => {\n const existing = fetches.get(url);\n if (existing)\n return existing;\n const request = dependencies.fetch(url, options);\n fetches.set(url, request);\n return request;\n };\n for (const item of verificationItems) {\n const coverage = await verifyQueryContent({\n query: item.query,\n url: item.url,\n js: input.js,\n refresh: input.refresh,\n rate: input.rate,\n verifiedAt: generatedAt,\n fetch: cachedFetch,\n extract: dependencies.extract,\n });\n applyVerification(item, coverage);\n }\n const groups = groupQuickWins(analysis.eligibleItems);\n const templates = quickWinTemplateSummaries(analysis.eligibleItems);\n const templateActions = quickWinTemplateRecommendations(analysis.eligibleItems);\n const verified = verificationItems.filter((item) => item.contentVerification?.status === 'verified').length;\n const failed = verificationItems.filter((item) => item.contentVerification?.status === 'failed').length;\n const technical = verificationItems.filter((item) => item.contentVerification?.classification === 'technical-check').length;\n const recommendations = unique([\n ...templateActions.slice(0, 3).map((item) => item.action),\n ...groups.slice(0, 3).map((item) => item.recommendation),\n analysis.items[0]?.recommendation.action ?? '',\n ]).slice(0, 5);\n const warnings = verificationItems.flatMap((item) => {\n const coverage = item.contentVerification;\n if (!coverage)\n return [];\n return [\n ...(coverage.warnings ?? []).map((message) => ({\n stage: 'verification',\n url: item.url,\n code: 'page-warning',\n message,\n })),\n ...(coverage.error\n ? [\n {\n stage: 'verification',\n url: item.url,\n code: 'verification-failed',\n message: coverage.error,\n },\n ]\n : []),\n ];\n });\n return {\n site: input.site,\n generatedAt,\n range,\n rangeDays: days,\n source: {\n provider: 'google-search-console',\n dimensions: ['query', 'page'],\n searchType: 'web',\n dataState: 'final',\n rowsFetched: source.rowsFetched,\n calls: source.calls,\n maxRows: MAX_SOURCE_ROWS,\n possiblyTruncated: source.rowsFetched >= MAX_SOURCE_ROWS,\n completeness: 'retained-query-rows-only',\n },\n dataStatus: analysis.dataStatus,\n selection: analysis.selection,\n methodology: analysis.methodology,\n provenance: {\n ...analysis.provenance,\n verification: {\n optional: true,\n population: 'returned_rows_in_priority_order',\n fetchDeduplication: 'exact_url',\n },\n },\n benchmark: {\n method: analysis.methodology.benchmark.method,\n peerRows: analysis.selection.benchmarkRows,\n byPosition: analysis.benchmarkByPosition,\n },\n verification: verificationRequested\n ? {\n requested: true,\n limit: verifyLimit,\n attemptedRows: verificationItems.length,\n attemptedUrls: fetches.size,\n verified,\n technical,\n failed,\n }\n : {\n requested: false,\n attemptedRows: 0,\n attemptedUrls: 0,\n verified: 0,\n technical: 0,\n failed: 0,\n },\n summary: {\n ...analysis.summary,\n repeatedQueryGroups: groups.length,\n templatePatterns: templateActions.length,\n brandFiltering: input.includeBrand ? 'included' : 'excluded',\n verdict: analysis.dataStatus === 'empty'\n ? 'Search Console returned no retained query/page rows for this date window.'\n : analysis.dataStatus === 'filtered'\n ? 'No retained rows met the quick-win report criteria.'\n : `${analysis.summary.eligibleRows} eligible CTR-target rows found; ${analysis.summary.returnedRows} returned for review.`,\n },\n caveats: [\n `Date window: ${range.startDate} to ${range.endDate}, using final GSC data where available.`,\n `Selection: ${analysis.selection.sourceRows} source rows, ${analysis.selection.benchmarkRows} benchmark rows, ${analysis.selection.eligibleRows} eligible rows, ${analysis.selection.returnedRows} returned.`,\n 'Position is GSC average position across impressions; a value from 4 to 10 does not mean the URL ranked on page one for every impression.',\n 'Target CTR is a deterministic site-peer or versioned built-in heuristic. The calculated CTR click shortfall is for prioritisation and is not a traffic forecast.',\n 'Search Analytics exposes top retained query rows only. Anonymized and lower-value queries can be absent even after pagination is exhausted.',\n source.rowsFetched >= MAX_SOURCE_ROWS\n ? `The report reached its ${MAX_SOURCE_ROWS.toLocaleString('en-US')}-row safety cap.`\n : '',\n verificationRequested\n ? `Page evidence was checked for ${verificationItems.length} returned rows across ${fetches.size} distinct URLs.`\n : 'Page evidence was not requested; CTR shortfalls do not establish why CTR differs.',\n ].filter(Boolean),\n recommendations: recommendations.length\n ? recommendations\n : [\n analysis.dataStatus === 'empty'\n ? 'Choose a longer window only if this property should have Search Console data.'\n : 'Adjust the minimum impressions only if you intentionally want a broader, lower-confidence review.',\n ],\n templates,\n templateRecommendations: templateActions,\n groups,\n items: analysis.items,\n ledgerSummary: ledger.summary(),\n warnings,\n };\n}\n//# sourceMappingURL=quick-wins.js.map","import { shouldExcludeBrandQuery } from '../brand.js';\nimport { detectPageTemplate } from './page-patterns.js';\nfunction compareText(left, right) {\n const leftPoints = [...left].map((character) => character.codePointAt(0) ?? 0);\n const rightPoints = [...right].map((character) => character.codePointAt(0) ?? 0);\n const length = Math.min(leftPoints.length, rightPoints.length);\n for (let index = 0; index < length; index++) {\n const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);\n if (difference !== 0)\n return difference;\n }\n return leftPoints.length - rightPoints.length;\n}\nfunction isHttpUrl(value) {\n try {\n const parsed = new URL(value);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n }\n catch {\n return false;\n }\n}\nexport function isValidStrikingDistanceRow(row, query, url) {\n return (Boolean(query) &&\n isHttpUrl(url) &&\n Number.isFinite(row.clicks) &&\n Number.isFinite(row.impressions) &&\n Number.isFinite(row.ctr) &&\n Number.isFinite(row.position) &&\n row.clicks >= 0 &&\n row.impressions > 0 &&\n row.clicks <= row.impressions &&\n row.ctr >= 0 &&\n row.ctr <= 1 &&\n row.position > 0);\n}\nexport function isStrikingDistanceBrandRow(input) {\n return shouldExcludeBrandQuery({\n query: input.query,\n siteUrl: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n}\nfunction itemRecommendation(input) {\n return {\n type: 'investigate-ranking',\n confidence: 'low',\n evidence: `GSC reports ${input.impressions} impressions at average position ${input.position.toFixed(2)} for \"${input.query}\" on ${input.url}.`,\n action: `Inspect indexability, canonical state, current query coverage, competing URLs, and relevant internal links for ${input.url} before choosing a change.`,\n };\n}\nexport function strikingDistanceItem(row) {\n const query = row.keys[0]?.trim() ?? '';\n const url = row.keys[1]?.trim() ?? '';\n const proximity = Number(Math.min(1, Math.max(0.1, (21 - row.position) / 10)).toFixed(4));\n return {\n query,\n url,\n template: detectPageTemplate(url),\n clicks: Number(row.clicks.toFixed(3)),\n impressions: Number(row.impressions.toFixed(3)),\n ctr: Number(row.ctr.toFixed(4)),\n position: Number(row.position.toFixed(2)),\n priority: {\n method: 'impressions_x_position_proximity',\n score: Number((row.impressions * proximity).toFixed(2)),\n demandImpressions: Number(row.impressions.toFixed(3)),\n positionProximity: proximity,\n heuristic: true,\n estimatedClickLift: false,\n },\n recommendation: itemRecommendation({\n query,\n url,\n impressions: row.impressions,\n position: row.position,\n }),\n };\n}\nexport function compareStrikingDistanceItems(left, right) {\n return (right.priority.score - left.priority.score ||\n right.impressions - left.impressions ||\n left.position - right.position ||\n compareText(left.query, right.query) ||\n compareText(left.url, right.url));\n}\nexport function groupStrikingDistanceItems(items) {\n const grouped = new Map();\n for (const item of items) {\n const existing = grouped.get(item.template.id) ?? [];\n existing.push(item);\n grouped.set(item.template.id, existing);\n }\n return [...grouped.entries()]\n .map(([id, members]) => {\n const first = members[0];\n if (!first)\n return undefined;\n const urls = [...new Set(members.map((item) => item.url))];\n const queries = [...new Set(members.map((item) => item.query))];\n const totalImpressions = members.reduce((sum, item) => sum + item.impressions, 0);\n const shared = first.template.confidence !== 'low' && urls.length >= 2;\n const evidence = `${members.length} eligible query/page rows represent ${urls.length} unique URLs and ${queries.length} unique queries.`;\n return {\n id,\n label: first.template.label,\n template: first.template,\n rowCount: members.length,\n uniqueUrls: urls.length,\n uniqueQueries: queries.length,\n totalImpressions: Number(totalImpressions.toFixed(3)),\n bestPosition: Math.min(...members.map((item) => item.position)),\n impressionWeightedPosition: Number((members.reduce((sum, item) => sum + item.position * item.impressions, 0) / totalImpressions).toFixed(2)),\n sampleQueries: queries.slice(0, 5),\n sampleUrls: urls.slice(0, 3),\n actionScope: shared ? 'shared-template-candidate' : 'page-level-review',\n recommendation: {\n type: 'investigate-ranking',\n confidence: 'low',\n evidence,\n action: shared\n ? `Review the sampled ${first.template.label.toLowerCase()} URLs for a recurring technical, content, or internal-link pattern before changing the shared template.`\n : `Review these URLs individually; the current evidence does not support a shared-template change.`,\n },\n };\n })\n .filter((group) => group !== undefined)\n .sort((left, right) => right.totalImpressions - left.totalImpressions ||\n right.uniqueUrls - left.uniqueUrls ||\n compareText(left.id, right.id));\n}\n//# sourceMappingURL=striking-distance-analysis-primitives.js.map","import { isLowActionabilityQuery } from './query-quality.js';\nimport { compareStrikingDistanceItems, groupStrikingDistanceItems, isStrikingDistanceBrandRow, isValidStrikingDistanceRow, strikingDistanceItem, } from './striking-distance-analysis-primitives.js';\nconst DEFAULT_MIN_IMPRESSIONS = 100;\nconst MAX_MIN_IMPRESSIONS = 1_000_000_000;\nconst DEFAULT_LIMIT = 25;\nconst MAX_LIMIT = 100;\nfunction integerInRange(value, fallback, minimum, maximum) {\n if (value === undefined || !Number.isFinite(value))\n return fallback;\n return Math.min(maximum, Math.max(minimum, Math.floor(value)));\n}\nfunction selectRows(input) {\n const selection = {\n sourceRows: input.rows.length,\n invalidRows: 0,\n outsidePositionRows: 0,\n belowMinimumRows: 0,\n lowActionabilityRows: 0,\n brandRows: 0,\n eligibleRows: 0,\n returnedRows: 0,\n limitedRows: 0,\n };\n const rows = [];\n for (const row of input.rows) {\n const query = row.keys[0]?.trim() ?? '';\n const url = row.keys[1]?.trim() ?? '';\n if (!isValidStrikingDistanceRow(row, query, url)) {\n selection.invalidRows++;\n }\n else if (row.position <= 10 || row.position > 20) {\n selection.outsidePositionRows++;\n }\n else if (row.impressions < input.minImpressions) {\n selection.belowMinimumRows++;\n }\n else if (isLowActionabilityQuery(query)) {\n selection.lowActionabilityRows++;\n }\n else if (isStrikingDistanceBrandRow({\n query,\n site: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n })) {\n selection.brandRows++;\n }\n else {\n rows.push(row);\n selection.eligibleRows++;\n }\n }\n return { rows, selection };\n}\nexport function analyzeStrikingDistanceRows(input) {\n const minImpressions = integerInRange(input.minImpressions, DEFAULT_MIN_IMPRESSIONS, 0, MAX_MIN_IMPRESSIONS);\n const limit = integerInRange(input.limit, DEFAULT_LIMIT, 1, MAX_LIMIT);\n const selected = selectRows({ ...input, minImpressions });\n const eligibleItems = selected.rows\n .map(strikingDistanceItem)\n .sort(compareStrikingDistanceItems);\n const items = eligibleItems.slice(0, limit);\n selected.selection.returnedRows = items.length;\n selected.selection.limitedRows = eligibleItems.length - items.length;\n const groups = groupStrikingDistanceItems(eligibleItems);\n const eligibleImpressions = eligibleItems.reduce((sum, item) => sum + item.impressions, 0);\n const returnedImpressions = items.reduce((sum, item) => sum + item.impressions, 0);\n const dataStatus = input.rows.length === 0\n ? 'empty'\n : eligibleItems.length === 0\n ? 'filtered'\n : 'available';\n return {\n site: input.site,\n minImpressions,\n limit,\n dataStatus,\n selection: selected.selection,\n methodology: {\n id: 'gsc_striking_distance_v2',\n source: 'google_search_console_query_page_rows',\n position: { minimumExclusive: 10, maximumInclusive: 20 },\n ctrEligibilityFilter: false,\n priority: {\n method: 'impressions_x_position_proximity',\n formula: 'impressions * clamp((21 - position) / 10, 0.1, 1)',\n heuristic: true,\n estimatedClickLift: false,\n },\n grouping: {\n population: 'all_eligible_rows_before_limit',\n sharedTemplateMinimumUniqueUrls: 2,\n lowConfidenceTemplatesAreShared: false,\n },\n },\n provenance: {\n inputScope: 'provided_rows',\n selectionOrder: [\n 'valid_row',\n 'position',\n 'minimum_impressions',\n 'query_quality',\n 'brand',\n ],\n selection: selected.selection,\n },\n summary: {\n eligibleRows: eligibleItems.length,\n returnedRows: items.length,\n eligibleImpressions: Number(eligibleImpressions.toFixed(3)),\n returnedImpressions: Number(returnedImpressions.toFixed(3)),\n uniqueEligibleUrls: new Set(eligibleItems.map((item) => item.url)).size,\n uniqueEligibleQueries: new Set(eligibleItems.map((item) => item.query))\n .size,\n groups: groups.length,\n },\n groups,\n items,\n };\n}\n//# sourceMappingURL=striking-distance-analysis.js.map","import { SeoError } from '../errors.js';\nimport { querySearchAnalytics } from '../gsc/client.js';\nimport { finalGscDateRange } from '../gsc/dates.js';\nimport { contentCoverageRecommendation, verifyQueryContent, } from './content-coverage.js';\nimport { analyzeStrikingDistanceRows, } from './striking-distance-analysis.js';\nexport * from './striking-distance-analysis.js';\nconst DEFAULT_DAYS = 28;\nconst MAX_DAYS = 548;\nconst DEFAULT_VERIFY_LIMIT = 5;\nconst MAX_SOURCE_ROWS = 100_000;\nconst defaultDependencies = {\n searchAnalytics: querySearchAnalytics,\n verifyContent: verifyQueryContent,\n now: () => new Date(),\n};\nfunction boundedInteger(value, fallback, minimum, maximum) {\n if (value === undefined || !Number.isFinite(value))\n return fallback;\n return Math.min(maximum, Math.max(minimum, Math.floor(value)));\n}\nfunction reportDays(value) {\n if (value === undefined)\n return DEFAULT_DAYS;\n if (!Number.isInteger(value) || value < 1 || value > MAX_DAYS) {\n throw new SeoError('INVALID_INPUT', `Days must be a whole number between 1 and ${MAX_DAYS}.`);\n }\n return value;\n}\nfunction dateRange(days, now) {\n return finalGscDateRange(days, now);\n}\nfunction verifiedRecommendation(coverage) {\n if (coverage.status === 'failed') {\n return {\n type: 'verification-failed',\n confidence: 'low',\n evidence: coverage.error ?? 'The page could not be verified.',\n action: contentCoverageRecommendation(coverage),\n };\n }\n if (coverage.classification === 'technical-check') {\n return {\n type: 'fix-technical',\n confidence: 'medium',\n evidence: `Verified technical signals: ${coverage.signals.join(', ')}.`,\n action: contentCoverageRecommendation(coverage),\n };\n }\n return {\n type: coverage.classification === 'covered'\n ? 'investigate-ranking'\n : 'review-page-evidence',\n confidence: 'low',\n evidence: coverage.summary,\n action: contentCoverageRecommendation(coverage),\n };\n}\nfunction templatesFromGroups(groups) {\n return groups.slice(0, 5).map((group) => ({\n id: group.id,\n label: group.label,\n count: group.rowCount,\n sampleUrls: group.sampleUrls,\n }));\n}\nfunction verdict(analysis) {\n if (analysis.dataStatus === 'empty') {\n return 'Search Console returned no retained query/page rows for this date window.';\n }\n if (analysis.dataStatus === 'filtered') {\n return 'No retained query/page rows met the report filters.';\n }\n return `${analysis.summary.eligibleRows} eligible query/page rows found; ${analysis.summary.returnedRows} returned for review.`;\n}\nexport async function strikingDistance(input, dependencies = defaultDependencies) {\n const days = reportDays(input.days);\n const generatedAt = dependencies.now().toISOString();\n const range = dateRange(days, new Date(generatedAt));\n const result = await dependencies.searchAnalytics(input.site, {\n ...range,\n dimensions: ['query', 'page'],\n type: 'web',\n dataState: 'final',\n maxRows: MAX_SOURCE_ROWS,\n }, { refresh: input.refresh });\n const analysis = analyzeStrikingDistanceRows({\n rows: result.rows,\n site: input.site,\n minImpressions: input.minImpressions,\n limit: input.limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n const verifyLimit = boundedInteger(input.verifyLimit, DEFAULT_VERIFY_LIMIT, 0, analysis.limit);\n const verificationRequested = input.verifyContent === true || input.verifyLimit !== undefined;\n const attempted = verificationRequested\n ? Math.min(verifyLimit, analysis.items.length)\n : 0;\n const items = await Promise.all(analysis.items.map(async (item, index) => {\n if (index >= attempted)\n return item;\n const contentVerification = await dependencies.verifyContent({\n query: item.query,\n url: item.url,\n js: input.js,\n refresh: input.refresh,\n rate: input.rate,\n verifiedAt: generatedAt,\n });\n return {\n ...item,\n contentVerification,\n recommendation: verifiedRecommendation(contentVerification),\n };\n }));\n const verifiedItems = items\n .slice(0, attempted)\n .map((item) => item.contentVerification)\n .filter((coverage) => Boolean(coverage));\n const possiblyTruncated = result.rowsFetched >= MAX_SOURCE_ROWS;\n return {\n site: input.site,\n generatedAt,\n range,\n rangeDays: days,\n source: {\n provider: 'google-search-console',\n dimensions: ['query', 'page'],\n searchType: 'web',\n dataState: 'final',\n rowsFetched: result.rowsFetched,\n calls: result.calls,\n maxRows: MAX_SOURCE_ROWS,\n possiblyTruncated,\n completeness: 'retained-query-rows-only',\n },\n dataStatus: analysis.dataStatus,\n selection: analysis.selection,\n methodology: analysis.methodology,\n verification: verificationRequested\n ? {\n requested: true,\n limit: verifyLimit,\n attempted,\n verified: verifiedItems.filter((item) => item.status === 'verified')\n .length,\n technical: verifiedItems.filter((item) => item.classification === 'technical-check').length,\n failed: verifiedItems.filter((item) => item.status === 'failed')\n .length,\n }\n : {\n requested: false,\n attempted: 0,\n verified: 0,\n technical: 0,\n failed: 0,\n },\n items,\n templates: templatesFromGroups(analysis.groups),\n groups: analysis.groups,\n summary: {\n ...analysis.summary,\n brandFiltering: input.includeBrand ? 'included' : 'excluded',\n verdict: verdict(analysis),\n },\n caveats: [\n `Date window: ${range.startDate} to ${range.endDate}, using final GSC data where available.`,\n `Selection: ${analysis.selection.sourceRows} source rows, ${analysis.selection.eligibleRows} eligible, ${analysis.selection.returnedRows} returned.`,\n \"Position is GSC average position for the property's topmost result per impression; it does not prove a URL ranked on a literal second results page every time.\",\n 'Search Analytics exposes retained query rows only. Anonymized and lower-value queries can be absent even when pagination is exhausted.',\n 'Priority is a demand-and-position heuristic, not an estimated click lift or proof that a change will improve rankings.',\n `Content verification: ${verificationRequested ? `${attempted} ${attempted === 1 ? 'row' : 'rows'} attempted` : 'not run'}.`,\n possiblyTruncated\n ? `The report reached its ${MAX_SOURCE_ROWS.toLocaleString('en-US')}-row safety cap.`\n : '',\n ].filter(Boolean),\n recommendations: analysis.groups.length\n ? analysis.groups.slice(0, 5).map((group) => group.recommendation.action)\n : [\n 'No action is recommended from this report. Lower the minimum impressions or widen the date window if you need long-tail inspection.',\n ],\n };\n}\n//# sourceMappingURL=striking-distance.js.map","import { fetch } from 'undici';\nimport { SeoError } from '../errors.js';\nconst INCIDENTS_URL = 'https://status.search.google.com/incidents.json';\nfunction classifyUpdate(name, product) {\n const lower = `${name} ${product}`.toLowerCase();\n if (lower.includes('core'))\n return 'core';\n if (lower.includes('spam'))\n return 'spam';\n if (lower.includes('discover'))\n return 'discover';\n if (lower.includes('ranking'))\n return 'ranking';\n if (lower.includes('index'))\n return 'indexing';\n if (lower.includes('serving'))\n return 'serving';\n return 'other';\n}\nexport async function fetchSearchStatusIncidents() {\n const response = await fetch(INCIDENTS_URL);\n if (!response.ok) {\n throw new SeoError('OPTIONAL_PROVIDER_UNAVAILABLE', `Google Search Status fetch failed with ${response.status}.`);\n }\n return (await response.json());\n}\nexport async function listSearchUpdates(input = {}) {\n const incidents = await fetchSearchStatusIncidents();\n const product = input.product?.toLowerCase();\n return incidents\n .filter((incident) => !product || incident.service_name.toLowerCase() === product)\n .map((incident) => {\n const status = incident.end\n ? 'complete'\n : incident.status_impact === 'SERVICE_INFORMATION'\n ? 'rolling-out'\n : 'incident';\n return {\n id: incident.id,\n name: incident.external_desc,\n type: classifyUpdate(incident.external_desc, incident.service_name),\n product: incident.service_name,\n start: incident.begin,\n end: incident.end,\n status,\n sourceUrl: `https://status.search.google.com/${incident.uri}`,\n };\n })\n .slice(0, input.limit ?? 25);\n}\nexport function findOverlappingSearchUpdates(input) {\n const paddingMs = (input.paddingDays ?? 3) * 86_400_000;\n const windowStart = new Date(input.startDate).getTime() - paddingMs;\n const windowEnd = new Date(input.endDate).getTime() + paddingMs;\n return input.updates.filter((update) => {\n const updateStart = new Date(update.start).getTime();\n const updateEnd = update.end ? new Date(update.end).getTime() : Date.now();\n return updateStart <= windowEnd && updateEnd >= windowStart;\n });\n}\n//# sourceMappingURL=search-status.js.map","function toIsoDate(value) {\n return new Date(value).toISOString();\n}\nexport function groupFromRow(row) {\n return {\n id: row.id,\n site: row.site_url,\n name: row.name,\n dimension: row.dimension,\n matchType: row.match_type,\n pattern: row.pattern,\n createdAt: toIsoDate(row.created_at),\n };\n}\nexport function changeFromRow(row) {\n return {\n id: row.id,\n site: row.site_url,\n scope: row.scope,\n target: row.target,\n title: row.title,\n description: row.description ?? undefined,\n changedAt: row.changed_at,\n createdAt: toIsoDate(row.created_at),\n };\n}\n//# sourceMappingURL=mappers.js.map","import { randomUUID } from 'node:crypto';\nimport { getDb } from '../../storage/database.js';\nimport { changeFromRow } from './mappers.js';\nexport function recordChange(input) {\n const change = {\n id: randomUUID(),\n site: input.site,\n scope: input.scope,\n target: input.target,\n title: input.title,\n description: input.description,\n changedAt: input.changedAt,\n createdAt: new Date().toISOString(),\n };\n getDb()\n .prepare(`INSERT INTO seo_changes\n (id, site_url, scope, target, title, description, changed_at, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)\n .run(change.id, change.site, change.scope, change.target, change.title, change.description ?? null, change.changedAt, Date.parse(change.createdAt));\n return change;\n}\nexport function listChanges(input = {}) {\n const limit = input.limit ?? 25;\n const rows = input.site\n ? getDb()\n .prepare('SELECT * FROM seo_changes WHERE site_url = ? ORDER BY changed_at DESC, created_at DESC LIMIT ?')\n .all(input.site, limit)\n : getDb()\n .prepare('SELECT * FROM seo_changes ORDER BY changed_at DESC, created_at DESC LIMIT ?')\n .all(limit);\n return rows.map(changeFromRow);\n}\nexport function getChange(id) {\n const row = getDb()\n .prepare('SELECT * FROM seo_changes WHERE id = ?')\n .get(id);\n return row ? changeFromRow(row) : undefined;\n}\nexport function deleteChange(id) {\n return (getDb().prepare('DELETE FROM seo_changes WHERE id = ?').run(id).changes > 0);\n}\n//# sourceMappingURL=change-log.js.map","import { SeoError } from '../errors.js';\nimport { querySearchAnalytics } from '../gsc/client.js';\nimport { shiftIsoDate } from '../gsc/dates.js';\nimport { findOverlappingSearchUpdates, listSearchUpdates, } from '../updates/search-status.js';\nimport { listChanges } from './experiments/change-log.js';\nimport { defaultDateRange } from './shared.js';\nfunction mean(values) {\n return (values.reduce((sum, value) => sum + value, 0) / Math.max(1, values.length));\n}\nfunction standardDeviation(values) {\n const average = mean(values);\n const variance = mean(values.map((value) => (value - average) ** 2));\n return Math.sqrt(variance);\n}\nfunction toFixedNumber(value, digits = 3) {\n return Number(value.toFixed(digits));\n}\nfunction percentChange(baseline, comparison) {\n if (!baseline)\n return comparison ? null : 0;\n return ((comparison - baseline) / baseline) * 100;\n}\nfunction formatPercent(value) {\n const rounded = Math.abs(value) >= 10 ? value.toFixed(0) : value.toFixed(1);\n return `${rounded}%`;\n}\nfunction formatMetric(metric) {\n return metric === 'clicks' ? 'Clicks' : 'Impressions';\n}\nfunction anomalyEvidence(anomaly) {\n const direction = anomaly.direction === 'drop' ? 'fell' : 'rose';\n const change = anomaly.percentChange === null\n ? null\n : anomaly.direction === 'drop'\n ? Math.abs(anomaly.percentChange)\n : anomaly.percentChange;\n const changePhrase = change === null\n ? 'from a zero baseline; percentage change is undefined'\n : `${formatPercent(change)} vs baseline`;\n if (anomaly.direction === 'normal') {\n return `${formatMetric(anomaly.metric)} changed ${changePhrase} (${anomaly.baselineMean.toLocaleString('en-GB')} -> ${anomaly.comparisonMean.toLocaleString('en-GB')} per observed day${anomaly.zScore === null ? '; the baseline had no observed variance' : `, z ${anomaly.zScore}`}).`;\n }\n return `${formatMetric(anomaly.metric)} ${direction} ${changePhrase} (${anomaly.baselineMean.toLocaleString('en-GB')} -> ${anomaly.comparisonMean.toLocaleString('en-GB')} per observed day${anomaly.zScore === null ? '; outside the flat observed baseline' : `, z ${anomaly.zScore}`}).`;\n}\nfunction plural(count, singular, pluralLabel = `${singular}s`) {\n return count === 1 ? singular : pluralLabel;\n}\nfunction strongestSignal(anomalies) {\n return [...anomalies].sort((a, b) => {\n if (a.significant !== b.significant)\n return a.significant ? -1 : 1;\n const zDifference = Math.abs(b.zScore ?? 0) - Math.abs(a.zScore ?? 0);\n if (zDifference)\n return zDifference;\n const changeDifference = Math.abs(b.percentChange ?? 0) - Math.abs(a.percentChange ?? 0);\n if (changeDifference)\n return changeDifference;\n return a.metric < b.metric ? -1 : a.metric > b.metric ? 1 : 0;\n })[0];\n}\nfunction dateMs(value) {\n return new Date(value).getTime();\n}\nfunction changesInWindow(input) {\n if (!input.startDate || !input.endDate)\n return [];\n const paddingMs = input.paddingDays * 86_400_000;\n const start = dateMs(input.startDate) - paddingMs;\n const end = dateMs(input.endDate) + paddingMs;\n return input.changes.filter((change) => {\n const changedAt = dateMs(change.changedAt);\n return changedAt >= start && changedAt <= end;\n });\n}\nfunction movementIsLarge(anomalies) {\n const significant = anomalies.filter((anomaly) => anomaly.significant);\n if (significant.length < 2)\n return false;\n const directions = new Set(significant.map((anomaly) => anomaly.direction));\n if (directions.size !== 1 || directions.has('normal'))\n return false;\n const clicks = significant.find((anomaly) => anomaly.metric === 'clicks');\n const impressions = significant.find((anomaly) => anomaly.metric === 'impressions');\n if (!clicks || !impressions)\n return false;\n if (clicks.percentChange === null || impressions.percentChange === null) {\n return false;\n }\n const clickChange = Math.abs(clicks.percentChange);\n const impressionChange = Math.abs(impressions.percentChange);\n const strongestZ = Math.max(...significant.map((item) => Math.abs(item.zScore ?? 0)));\n const outsideFlatBaseline = significant.some((item) => item.significanceMethod === 'outside-flat-baseline');\n return ((strongestZ >= 3 || outsideFlatBaseline) &&\n Math.min(clickChange, impressionChange) >= 45 &&\n Math.max(clickChange, impressionChange) >= 60);\n}\nfunction confounderTitle(confounder) {\n const date = confounder.date ? `${confounder.date}: ` : '';\n const scope = confounder.scope ? `${confounder.scope} ` : '';\n return `${date}${scope}${confounder.title}`;\n}\nexport function interpretUpdateCorrelation(input) {\n const significant = input.anomalies.filter((anomaly) => anomaly.significant);\n const strongest = strongestSignal(input.anomalies);\n const updateNames = input.overlappingUpdates.map((update) => update.name);\n const hasUpdate = input.overlappingUpdates.length > 0;\n const confounders = input.confounders ?? [];\n const hasConfounders = confounders.length > 0;\n const largeMovement = movementIsLarge(input.anomalies);\n const classification = significant.length > 0 && hasUpdate\n ? 'significant-movement-with-update-overlap'\n : hasUpdate\n ? 'update-overlap-without-significant-movement'\n : 'no-update-overlap';\n const direction = strongest?.direction ?? 'normal';\n const movement = direction === 'drop'\n ? largeMovement\n ? 'collapsed'\n : 'dropped'\n : direction === 'spike'\n ? largeMovement\n ? 'surged'\n : 'grew'\n : 'did not move enough to call an anomaly';\n const attribution = 'not-established';\n const confidence = 'none';\n const knownChangePhrase = confounders.length === 1\n ? '1 known site change also overlaps'\n : `${confounders.length} known site changes also overlap`;\n const summary = significant.length && hasUpdate\n ? `${input.site} ${movement} during a period that overlaps ${updateNames.join(', ')}.${hasConfounders ? ` ${knownChangePhrase} this window.` : ''} The overlap is timing context and does not establish what caused the movement.`\n : hasUpdate\n ? `${input.site} overlaps ${updateNames.join(', ')}, but no significant GSC movement was detected in this window.`\n : `${input.site} had no official Google Ranking update overlap in the recent comparison window.`;\n const actions = significant.length && hasUpdate && hasConfounders\n ? [\n 'Start with the overlapping site changes. Test whether pruning, blocking, redirects, deploys, or tracking changes explain the observed movement.',\n 'Run segment-impact for page and query and compare affected sections against the saved change targets.',\n 'Compare changed and unchanged sections, then record which explanation the segment evidence supports.',\n ]\n : significant.length && hasUpdate\n ? [\n 'Run update-postmortem and segment-impact next to find the winning or losing templates, queries, countries, and devices without assuming a cause.',\n direction === 'drop'\n ? 'For a collapse, avoid broad rewrites first. Identify the templates that lost impressions, then check indexability, intent fit, and SERP changes.'\n : 'For a surge, document the winning templates and reinforce them with internal links before changing pages that improved.',\n 'Add any missed deploy, pruning, blocking, or content changes to change-log so later comparisons include that evidence.',\n ]\n : hasUpdate\n ? [\n 'No significant movement was detected in this comparison. Keep the overlap as context and avoid an update-impact conclusion.',\n ]\n : [\n 'If traffic moved, investigate site changes, seasonality, indexing, and segment-level movement before looking for update causes.',\n ];\n return {\n classification,\n attribution,\n confidence,\n confounders,\n summary,\n evidence: [\n ...input.anomalies.map(anomalyEvidence),\n hasUpdate\n ? `${input.overlappingUpdates.length} official Google Ranking update ${plural(input.overlappingUpdates.length, 'window')} overlapped the comparison period: ${updateNames.join(', ')}.`\n : 'No official Google Ranking update windows overlapped the comparison period.',\n largeMovement\n ? 'Both clicks and impressions moved sharply in the same direction.'\n : 'Clicks and impressions did not both meet the sharp-movement evidence threshold.',\n hasConfounders\n ? `Known overlapping site changes: ${confounders.map(confounderTitle).join('; ')}.`\n : 'No saved or manually supplied overlapping site changes were found.',\n ],\n caveats: [\n `GSC window: ${input.days} days; recent comparison window: ${input.recentDays} days.`,\n `Update overlap padding: ${input.paddingDays} ${plural(input.paddingDays, 'day')} either side of the comparison window.`,\n input.refresh\n ? 'Data freshness: cache bypassed for GSC data.'\n : 'Data freshness: local GSC cache may have been used.',\n 'Source: official Google Search Status Dashboard Ranking incidents only; third-party volatility and unconfirmed chatter are not included.',\n 'An update-window overlap cannot establish causation, even when movement is large and no known site change was recorded.',\n 'Attribution remains not established. Use segment-impact and update-postmortem to describe which templates or intents moved, then test possible explanations separately.',\n ],\n actions,\n source: {\n name: 'Google Search Status Dashboard incidents feed',\n url: 'https://status.search.google.com/incidents.json',\n product: 'Ranking',\n },\n };\n}\nfunction validIsoDate(value) {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(value))\n return false;\n const parsed = new Date(`${value}T00:00:00.000Z`);\n return (!Number.isNaN(parsed.getTime()) &&\n parsed.toISOString().slice(0, 10) === value);\n}\nfunction calendarDays(start, end) {\n const startMs = Date.parse(`${start}T00:00:00.000Z`);\n const endMs = Date.parse(`${end}T00:00:00.000Z`);\n return Math.floor((endMs - startMs) / 86_400_000) + 1;\n}\nfunction validMetricRow(row) {\n return (row.keys.length === 1 &&\n Number.isFinite(row.clicks) &&\n row.clicks >= 0 &&\n Number.isFinite(row.impressions) &&\n row.impressions >= 0);\n}\nfunction aggregateDailyRows(input) {\n const byDate = new Map();\n let invalidRows = 0;\n let duplicateRows = 0;\n for (const row of input.rows) {\n const date = row.keys[0];\n if (!date ||\n !validIsoDate(date) ||\n date < input.startDate ||\n date > input.endDate ||\n !validMetricRow(row)) {\n invalidRows += 1;\n continue;\n }\n const existing = byDate.get(date);\n if (existing) {\n duplicateRows += 1;\n existing.clicks += row.clicks;\n existing.impressions += row.impressions;\n continue;\n }\n byDate.set(date, { ...row, keys: [date] });\n }\n return {\n rows: [...byDate.values()].sort((a, b) => {\n const aDate = a.keys[0] ?? '';\n const bDate = b.keys[0] ?? '';\n return aDate < bDate ? -1 : aDate > bDate ? 1 : 0;\n }),\n invalidRows,\n duplicateRows,\n };\n}\nexport function analyzeTrafficAnomalyRows(input) {\n if (!validIsoDate(input.startDate) ||\n !validIsoDate(input.endDate) ||\n input.startDate > input.endDate) {\n throw new SeoError('INVALID_INPUT', 'Pass a valid Search Console date range.');\n }\n if (!Number.isInteger(input.recentDays) || input.recentDays < 1) {\n throw new SeoError('INVALID_INPUT', 'recentDays must be a positive integer.');\n }\n const expectedDays = calendarDays(input.startDate, input.endDate);\n const comparisonStart = shiftIsoDate(input.endDate, -(input.recentDays - 1));\n const baselineEnd = shiftIsoDate(comparisonStart, -1);\n const baselineExpectedDays = calendarDays(input.startDate, baselineEnd);\n if (comparisonStart < input.startDate || baselineExpectedDays < 14) {\n throw new SeoError('INSUFFICIENT_DATA', 'The requested calendar range does not contain at least 14 baseline days before the comparison window.');\n }\n const aggregated = aggregateDailyRows({\n rows: input.rows,\n startDate: input.startDate,\n endDate: input.endDate,\n });\n const baselineRows = aggregated.rows.filter((row) => (row.keys[0] ?? '') <= baselineEnd);\n const comparisonRows = aggregated.rows.filter((row) => (row.keys[0] ?? '') >= comparisonStart);\n if (baselineRows.length < 14 || comparisonRows.length < 3) {\n throw new SeoError('INSUFFICIENT_DATA', `Not enough observed daily GSC data for anomaly detection (${baselineRows.length} baseline days and ${comparisonRows.length} comparison days).`);\n }\n const metrics = ['clicks', 'impressions'];\n const anomalies = metrics.map((metric) => {\n const baselineValues = baselineRows.map((row) => row[metric]);\n const comparisonValues = comparisonRows.map((row) => row[metric]);\n const baselineMean = mean(baselineValues);\n const comparisonMean = mean(comparisonValues);\n const baselineTotal = baselineValues.reduce((sum, value) => sum + value, 0);\n const comparisonTotal = comparisonValues.reduce((sum, value) => sum + value, 0);\n const stdDev = standardDeviation(baselineValues);\n const standardError = stdDev / Math.sqrt(comparisonValues.length);\n const zScore = standardError > 0 ? (comparisonMean - baselineMean) / standardError : null;\n const outsideFlatBaseline = zScore === null && comparisonMean !== baselineMean;\n const significant = outsideFlatBaseline || (zScore !== null && Math.abs(zScore) >= 2);\n const direction = significant\n ? comparisonMean < baselineMean\n ? 'drop'\n : 'spike'\n : 'normal';\n const relativeChange = percentChange(baselineMean, comparisonMean);\n return {\n site: input.site,\n metric,\n baselineStart: input.startDate,\n baselineEnd,\n comparisonStart,\n comparisonEnd: input.endDate,\n baselineMean: toFixedNumber(baselineMean),\n comparisonMean: toFixedNumber(comparisonMean),\n baselineTotal: toFixedNumber(baselineTotal),\n comparisonTotal: toFixedNumber(comparisonTotal),\n percentChange: relativeChange === null ? null : toFixedNumber(relativeChange),\n zScore: zScore === null ? null : toFixedNumber(zScore),\n significanceMethod: significant\n ? outsideFlatBaseline\n ? 'outside-flat-baseline'\n : 'z-score'\n : 'none',\n direction,\n significant,\n };\n });\n const baselineMissingDays = baselineExpectedDays - baselineRows.length;\n const comparisonMissingDays = input.recentDays - comparisonRows.length;\n const missingDays = expectedDays - aggregated.rows.length;\n const caveats = [\n ...(missingDays > 0\n ? [\n `${missingDays} requested calendar ${plural(missingDays, 'day')} had no returned date aggregate and ${missingDays === 1 ? 'was' : 'were'} not filled with zeros.`,\n ]\n : []),\n ...(aggregated.invalidRows > 0\n ? [\n `${aggregated.invalidRows} invalid provider ${plural(aggregated.invalidRows, 'row')} ${aggregated.invalidRows === 1 ? 'was' : 'were'} excluded.`,\n ]\n : []),\n ...(aggregated.duplicateRows > 0\n ? [\n `${aggregated.duplicateRows} duplicate date ${plural(aggregated.duplicateRows, 'row')} ${aggregated.duplicateRows === 1 ? 'was' : 'were'} aggregated before analysis.`,\n ]\n : []),\n ];\n return {\n anomalies,\n coverage: {\n status: missingDays > 0 || aggregated.invalidRows > 0 ? 'partial' : 'complete',\n requestedStart: input.startDate,\n requestedEnd: input.endDate,\n returnedRows: input.rows.length,\n observedDays: aggregated.rows.length,\n invalidRows: aggregated.invalidRows,\n duplicateRows: aggregated.duplicateRows,\n expectedDays,\n missingDays,\n baseline: {\n start: input.startDate,\n end: baselineEnd,\n expectedDays: baselineExpectedDays,\n observedDays: baselineRows.length,\n missingDays: baselineMissingDays,\n },\n comparison: {\n start: comparisonStart,\n end: input.endDate,\n expectedDays: input.recentDays,\n observedDays: comparisonRows.length,\n missingDays: comparisonMissingDays,\n },\n caveats,\n },\n };\n}\nexport async function trafficAnomaly(input) {\n const days = input.days ?? 90;\n const recentDays = input.recentDays ?? 7;\n if ((input.startDate && !input.endDate) ||\n (!input.startDate && input.endDate)) {\n throw new SeoError('INVALID_INPUT', 'Pass both startDate and endDate, or neither.');\n }\n const range = input.startDate && input.endDate\n ? { startDate: input.startDate, endDate: input.endDate }\n : defaultDateRange(days);\n const result = await querySearchAnalytics(input.site, {\n ...range,\n dimensions: ['date'],\n type: 'web',\n dataState: 'final',\n }, { refresh: input.refresh });\n const analyzed = analyzeTrafficAnomalyRows({\n site: input.site,\n rows: result.rows,\n startDate: range.startDate,\n endDate: range.endDate,\n recentDays,\n });\n return {\n site: input.site,\n generatedAt: new Date().toISOString(),\n anomalies: analyzed.anomalies,\n rows: result.rows.length,\n coverage: analyzed.coverage,\n };\n}\nexport async function updateCorrelation(input) {\n const days = input.days ?? 90;\n const recentDays = input.recentDays ?? 7;\n const paddingDays = input.paddingDays ?? 3;\n const anomalies = input.trafficAnomalies ?? (await trafficAnomaly(input)).anomalies;\n const comparisonStart = anomalies[0]?.comparisonStart;\n const comparisonEnd = anomalies[0]?.comparisonEnd;\n const updates = await listSearchUpdates({ product: 'Ranking', limit: 50 });\n const overlappingUpdates = comparisonStart && comparisonEnd\n ? findOverlappingSearchUpdates({\n updates,\n startDate: comparisonStart,\n endDate: comparisonEnd,\n paddingDays,\n })\n : [];\n const savedConfounders = input.includeChangeLog === false\n ? []\n : changesInWindow({\n changes: listChanges({ site: input.site, limit: 100 }),\n startDate: comparisonStart,\n endDate: comparisonEnd,\n paddingDays,\n }).map((change) => ({\n source: 'change-log',\n title: change.title,\n date: change.changedAt,\n scope: change.scope,\n target: change.target,\n description: change.description,\n }));\n const manualConfounders = (input.knownConfounders ?? []).map((title) => ({\n source: 'manual',\n title,\n }));\n const confounders = [...savedConfounders, ...manualConfounders];\n return {\n site: input.site,\n generatedAt: new Date().toISOString(),\n anomalies,\n overlappingUpdates,\n ...interpretUpdateCorrelation({\n site: input.site,\n anomalies,\n overlappingUpdates,\n confounders,\n days,\n recentDays,\n paddingDays,\n refresh: input.refresh,\n }),\n };\n}\n//# sourceMappingURL=traffic-anomaly.js.map","import { isSkippableReportError } from '../errors.js';\nimport { buildDiagnosisPriorities } from './diagnosis-priorities.js';\nimport { diagnosisDataStatus, diagnosisPartialReasons, } from './diagnosis-status.js';\nimport { segmentImpact, segmentRangeDays, unavailableSegmentImpactReport, } from './segment-impact.js';\nimport { defaultDateRange } from './shared.js';\nimport { analyzeCannibalRows, analyzeDecay, analyzeQuickWinsFromRows, cannibalReport, decayComparisonRange, decayingReport, quickWinsReport, } from './site-diagnostics.js';\nimport { analyzeStrikingDistanceRows, strikingDistance, } from './striking-distance.js';\nimport { trafficAnomaly, updateCorrelation, } from './traffic-anomaly.js';\nfunction errorReason(error) {\n return error instanceof Error ? error.message : String(error);\n}\nfunction fallbackRange(input) {\n return input.startDate && input.endDate\n ? { startDate: input.startDate, endDate: input.endDate }\n : defaultDateRange(input.days ?? 28);\n}\nfunction emptyAnomaly(input) {\n return {\n site: input.site,\n generatedAt: new Date().toISOString(),\n anomalies: [],\n rows: 0,\n };\n}\nfunction emptyUpdateCorrelation(input, unavailable) {\n const sparseDataReason = 'The traffic anomaly section was skipped or returned no daily rows.';\n const reason = unavailable\n ? `Update correlation was unavailable: ${unavailable.reason}`\n : sparseDataReason;\n return {\n site: input.site,\n generatedAt: new Date().toISOString(),\n anomalies: [],\n overlappingUpdates: [],\n classification: 'insufficient-data',\n attribution: 'not-established',\n confidence: 'none',\n confounders: [],\n summary: unavailable\n ? `${input.site} update correlation was unavailable for this run.`\n : `${input.site} does not have enough daily GSC data for update correlation yet.`,\n evidence: [reason],\n caveats: [\n `GSC window: ${input.days ?? 90} days; recent comparison window: ${input.recentDays ?? 7} days.`,\n ...(unavailable\n ? ['No update-correlation conclusion was produced.']\n : [\n 'New or sparse properties need more daily GSC data before update correlation is useful.',\n ]),\n ],\n actions: [\n unavailable?.source === 'search-status'\n ? 'Retry update correlation when the Search Status provider is available; use the canonical traffic anomalies and other report evidence in the meantime.'\n : unavailable?.source === 'traffic-anomaly'\n ? 'Restore traffic anomaly evidence, then retry update correlation; use other report evidence in the meantime.'\n : 'Use quick wins, second-page opportunities, page audit, and technical checks until enough daily GSC data exists.',\n ],\n source: {\n name: 'Google Search Status Dashboard incidents feed',\n url: 'https://status.search.google.com/incidents.json',\n product: 'Ranking',\n },\n };\n}\nfunction emptySegment(input, reason = 'Segment evidence was unavailable.') {\n const after = fallbackRange(input);\n return unavailableSegmentImpactReport({\n site: input.site,\n dimension: input.dimension,\n after,\n reason,\n });\n}\nfunction segmentWindowUnavailableReason(input) {\n const days = segmentRangeDays(fallbackRange(input));\n return days > 240\n ? `The ${days}-day diagnosis window is too long for an adjacent segment comparison inside Search Console's rolling 16-month API history. Use 240 days or fewer for segment movement.`\n : undefined;\n}\nfunction emptyDecay(input) {\n const current = fallbackRange(input);\n const previous = decayComparisonRange(current);\n const analysis = analyzeDecay({\n site: input.site,\n currentRows: [],\n previousRows: [],\n limit: input.limit,\n includeBrand: input.includeBrand,\n });\n return {\n schemaVersion: 1,\n site: input.site,\n generatedAt: new Date().toISOString(),\n comparison: 'previous-period',\n ranges: { current, previous },\n rangeDays: Math.floor((new Date(`${current.endDate}T00:00:00.000Z`).getTime() -\n new Date(`${current.startDate}T00:00:00.000Z`).getTime()) /\n 86_400_000) + 1,\n dataStatus: 'unavailable',\n source: {\n provider: 'google-search-console',\n dimensions: ['query', 'page'],\n aggregationType: 'auto',\n searchType: 'web',\n dataState: 'final',\n current: {\n rowsFetched: 0,\n calls: 0,\n maxRows: 100_000,\n possiblyTruncated: false,\n },\n previous: {\n rowsFetched: 0,\n calls: 0,\n maxRows: 100_000,\n possiblyTruncated: false,\n },\n completeness: 'unavailable',\n },\n methodology: {\n id: 'gsc_retained_query_page_decay_v2',\n version: 2,\n gscHistoryMonths: 16,\n missingRowsTreatedAsZero: false,\n urlShiftsExcluded: true,\n causeLanguage: 'signals-not-attribution',\n },\n filters: {\n minDropPct: 20,\n minPreviousClicks: 2,\n minClickLoss: 1,\n limit: input.limit ?? 25,\n brand: input.includeBrand ? 'included' : 'excluded',\n },\n selection: analysis.selection,\n summary: {\n eligibleRows: 0,\n returnedRows: 0,\n groups: 0,\n observedRetainedQueryClickLoss: 0,\n returnedObservedRetainedQueryClickLoss: 0,\n brandFiltering: input.includeBrand ? 'included' : 'excluded',\n verdict: 'Decay analysis was skipped.',\n },\n caveats: [\n 'Decay analysis was skipped because required GSC data was unavailable.',\n ],\n recommendations: [\n 'Run this section again after the property has enough query/page history.',\n ],\n items: analysis.items,\n groups: analysis.groups,\n templates: analysis.templates,\n ledgerSummary: 'GSC: 0 calls, 0 rows.',\n warnings: [],\n };\n}\nfunction emptyCannibal(input) {\n const range = fallbackRange(input);\n const rangeDays = Math.floor((new Date(`${range.endDate}T00:00:00.000Z`).getTime() -\n new Date(`${range.startDate}T00:00:00.000Z`).getTime()) /\n 86_400_000) + 1;\n const analysis = analyzeCannibalRows({ site: input.site, rows: [] });\n return {\n schemaVersion: 1,\n site: input.site,\n generatedAt: new Date().toISOString(),\n range,\n rangeDays,\n dataStatus: 'unavailable',\n source: {\n provider: 'google-search-console',\n searchType: 'web',\n dataState: 'final',\n pageExposure: {\n dimensions: ['query', 'page'],\n aggregationType: 'auto',\n rowsFetched: 0,\n validation: { retainedRows: 0, invalidRows: 0 },\n calls: 0,\n maxRows: 100_000,\n possiblyTruncated: false,\n },\n propertyDemand: {\n dimensions: ['query'],\n aggregationType: 'byProperty',\n rowsFetched: 0,\n validation: { retainedRows: 0, invalidRows: 0 },\n calls: 0,\n maxRows: 100_000,\n possiblyTruncated: false,\n },\n completeness: 'unavailable',\n },\n methodology: {\n id: 'gsc_url_overlap_v2',\n version: 2,\n minimumPageImpressions: 10,\n minimumPageImpressionShare: 0.1,\n maximumDominantPageShare: 0.8,\n matching: 'normalized_exact_query',\n finding: 'url-overlap-candidate',\n requiresIntentReview: true,\n },\n verification: {\n status: 'not-requested',\n technicalStateChecked: false,\n searchIntentChecked: false,\n },\n filters: analysis.filters,\n selection: analysis.selection,\n summary: {\n eligibleClusters: 0,\n returnedClusters: 0,\n suppressedQueries: 0,\n brandFiltering: 'excluded',\n verdict: 'Multi-URL query analysis was unavailable.',\n },\n templates: [],\n suppressed: [],\n suppressionSummary: {},\n items: [],\n caveats: [\n 'Multi-URL query analysis was skipped because required GSC data was unavailable.',\n ],\n recommendations: [\n 'Run this section again after Search Console query/page data is available.',\n ],\n ledgerSummary: 'GSC: 0 calls, 0 rows.',\n };\n}\nfunction emptyStriking(input) {\n const analysis = analyzeStrikingDistanceRows({ rows: [], site: input.site });\n return {\n site: input.site,\n generatedAt: new Date().toISOString(),\n range: defaultDateRange(input.days ?? 28),\n rangeDays: input.days ?? 28,\n source: {\n provider: 'google-search-console',\n dimensions: ['query', 'page'],\n searchType: 'web',\n dataState: 'final',\n rowsFetched: 0,\n calls: 0,\n maxRows: 100_000,\n possiblyTruncated: false,\n completeness: 'retained-query-rows-only',\n },\n dataStatus: analysis.dataStatus,\n selection: analysis.selection,\n methodology: analysis.methodology,\n verification: {\n requested: false,\n attempted: 0,\n verified: 0,\n technical: 0,\n failed: 0,\n },\n items: [],\n templates: [],\n groups: [],\n summary: {\n ...analysis.summary,\n brandFiltering: 'excluded',\n verdict: 'Striking-distance analysis was skipped.',\n },\n caveats: [\n 'Striking-distance analysis was skipped because required GSC data was unavailable.',\n ],\n recommendations: [\n 'Run this section again after the property has enough query/page history.',\n ],\n };\n}\nfunction emptyQuickWins(input) {\n const analysis = analyzeQuickWinsFromRows({ rows: [], site: input.site });\n const range = fallbackRange(input);\n return {\n site: input.site,\n generatedAt: new Date().toISOString(),\n range,\n rangeDays: input.days ?? 28,\n source: {\n provider: 'google-search-console',\n dimensions: ['query', 'page'],\n searchType: 'web',\n dataState: 'final',\n rowsFetched: 0,\n calls: 0,\n maxRows: 100_000,\n possiblyTruncated: false,\n completeness: 'retained-query-rows-only',\n },\n dataStatus: analysis.dataStatus,\n selection: analysis.selection,\n methodology: analysis.methodology,\n provenance: {\n ...analysis.provenance,\n verification: {\n optional: true,\n population: 'returned_rows_in_priority_order',\n fetchDeduplication: 'exact_url',\n },\n },\n benchmark: {\n method: analysis.methodology.benchmark.method,\n peerRows: 0,\n byPosition: analysis.benchmarkByPosition,\n },\n verification: {\n requested: false,\n attemptedRows: 0,\n attemptedUrls: 0,\n verified: 0,\n technical: 0,\n failed: 0,\n },\n summary: {\n ...analysis.summary,\n repeatedQueryGroups: 0,\n templatePatterns: 0,\n brandFiltering: 'excluded',\n verdict: 'Quick-win analysis was skipped.',\n },\n caveats: [\n 'Quick-win analysis was skipped because required GSC data was unavailable.',\n ],\n recommendations: [\n 'Run this section again after the property has enough query/page history.',\n ],\n templates: [],\n templateRecommendations: [],\n groups: [],\n items: [],\n ledgerSummary: 'No provider calls recorded.',\n warnings: [],\n };\n}\nconst defaultDependencies = {\n trafficAnomaly,\n updateCorrelation,\n segmentImpact,\n decayingReport,\n cannibalReport,\n strikingDistance,\n quickWinsReport,\n};\nexport async function diagnoseProperty(input, dependencies = {}) {\n const providers = { ...defaultDependencies, ...dependencies };\n const limit = input.limit ?? 10;\n const track = async (label, run, fallback) => {\n input.progress?.(`Running ${label}`);\n try {\n const result = await run();\n input.progress?.(`Finished ${label}`);\n return { status: 'completed', value: result };\n }\n catch (error) {\n if (!isSkippableReportError(error)) {\n throw error;\n }\n const reason = errorReason(error);\n input.progress?.(`Skipped ${label}: ${reason}`);\n return {\n status: 'skipped',\n value: fallback(error),\n skipped: { section: label, reason },\n };\n }\n };\n const skipped = (label, value, reason) => {\n input.progress?.(`Skipped ${label}: ${reason}`);\n return {\n status: 'skipped',\n value,\n skipped: { section: label, reason },\n };\n };\n const searchDataSkipReason = input.skipSearchData\n ? 'Search Console data was skipped because no Search Console property was selected.'\n : undefined;\n const searchDataTask = (label, fallback, run) => searchDataSkipReason\n ? Promise.resolve(skipped(label, fallback(), searchDataSkipReason))\n : track(label, run, fallback);\n const anomalyResult = await searchDataTask('traffic anomaly', () => emptyAnomaly(input), () => providers.trafficAnomaly(input));\n const updateTask = searchDataSkipReason\n ? Promise.resolve(skipped('update correlation', emptyUpdateCorrelation(input, {\n reason: searchDataSkipReason,\n source: 'traffic-anomaly',\n }), searchDataSkipReason))\n : anomalyResult.status === 'skipped'\n ? Promise.resolve(skipped('update correlation', emptyUpdateCorrelation(input, {\n reason: `Traffic anomaly evidence was unavailable: ${anomalyResult.skipped.reason}`,\n source: 'traffic-anomaly',\n }), `Traffic anomaly evidence was unavailable: ${anomalyResult.skipped.reason}`))\n : track('update correlation', () => providers.updateCorrelation({\n ...input,\n trafficAnomalies: anomalyResult.value.anomalies,\n }), (error) => emptyUpdateCorrelation(input, {\n reason: errorReason(error),\n source: 'search-status',\n }));\n const segmentUnavailable = segmentWindowUnavailableReason(input);\n const segmentTask = (label, dimension) => searchDataSkipReason\n ? Promise.resolve(skipped(label, emptySegment({ ...input, dimension }, searchDataSkipReason), searchDataSkipReason))\n : segmentUnavailable\n ? Promise.resolve(skipped(label, emptySegment({ ...input, dimension }, segmentUnavailable), segmentUnavailable))\n : searchDataTask(label, (error) => emptySegment({ ...input, dimension }, errorReason(error)), () => providers.segmentImpact({ ...input, dimension, limit }));\n const [updateResult, pageResult, queryResult, deviceResult, countryResult, decayResult, cannibalResult, strikingResult, quickWinsResult,] = await Promise.all([\n updateTask,\n segmentTask('page movement segments', 'page'),\n segmentTask('query movement segments', 'query'),\n segmentTask('device movement segments', 'device'),\n segmentTask('country movement segments', 'country'),\n searchDataTask('decay analysis', () => emptyDecay({ ...input, limit }), () => providers.decayingReport({\n site: input.site,\n days: input.days,\n startDate: input.startDate,\n endDate: input.endDate,\n limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n refresh: input.refresh,\n })),\n searchDataTask('cannibalisation analysis', () => emptyCannibal(input), () => providers.cannibalReport({\n site: input.site,\n days: input.days,\n startDate: input.startDate,\n endDate: input.endDate,\n limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n refresh: input.refresh,\n })),\n searchDataTask('striking-distance opportunities', () => emptyStriking(input), () => providers.strikingDistance({ ...input, limit })),\n searchDataTask('quick-win opportunities', () => emptyQuickWins(input), () => providers.quickWinsReport({\n site: input.site,\n days: input.days,\n startDate: input.startDate,\n endDate: input.endDate,\n limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n verifyContent: input.verifyContent,\n verifyLimit: input.verifyLimit,\n js: input.js,\n rate: input.rate,\n refresh: input.refresh,\n })),\n ]);\n input.progress?.('Building priority list');\n const anomaly = anomalyResult.value;\n const update = updateResult.value;\n const page = pageResult.value;\n const query = queryResult.value;\n const device = deviceResult.value;\n const country = countryResult.value;\n const decay = decayResult.value;\n const cannibal = cannibalResult.value;\n const striking = strikingResult.value;\n const quickWins = quickWinsResult.value;\n const sectionResults = [\n anomalyResult,\n updateResult,\n pageResult,\n queryResult,\n deviceResult,\n countryResult,\n decayResult,\n cannibalResult,\n strikingResult,\n quickWinsResult,\n ];\n const skippedSections = sectionResults.flatMap((result) => result.status === 'skipped' ? [result.skipped] : []);\n const priorities = buildDiagnosisPriorities({\n anomaly,\n update,\n page,\n decay,\n cannibal,\n striking,\n quickWins,\n });\n const partialReasons = diagnosisPartialReasons({\n skippedSections,\n anomaly,\n segments: { page, query, device, country },\n decay,\n cannibalization: cannibal,\n strikingDistance: striking,\n quickWins,\n });\n const criticalResults = [\n anomalyResult,\n updateResult,\n pageResult,\n decayResult,\n cannibalResult,\n strikingResult,\n quickWinsResult,\n ];\n const dataStatus = diagnosisDataStatus({\n criticalStatuses: criticalResults.map((result) => result.status),\n skippedSections: skippedSections.length,\n partialReasons: partialReasons.length,\n });\n const updateAttributionStatus = updateResult.status === 'skipped' ? 'unavailable' : 'available';\n return {\n site: input.site,\n generatedAt: new Date().toISOString(),\n dataStatus,\n summary: {\n updateAttribution: updateAttributionStatus === 'available'\n ? update.classification\n : 'unavailable',\n updateAttributionStatus,\n classification: update.classification,\n significantAnomalies: anomaly.anomalies.filter((item) => item.significant)\n .length,\n updateMatches: update.overlappingUpdates.length,\n largestPageMovements: page.items.length,\n decayItems: decay.selection.eligibleRows,\n cannibalItems: cannibal.selection.eligibleClusters,\n strikingDistanceItems: striking.items.length,\n quickWinItems: quickWins.items.length,\n },\n skippedSections,\n partialReasons,\n priorities,\n anomaly,\n updateCorrelation: update,\n segments: { page, query, device, country },\n decay,\n cannibalization: cannibal,\n strikingDistance: striking,\n quickWins,\n };\n}\n//# sourceMappingURL=diagnose-property.js.map","import { randomUUID } from 'node:crypto';\nimport { getDb } from '../../storage/database.js';\nimport { groupFromRow } from './mappers.js';\nexport function createContentGroup(input) {\n const group = {\n id: randomUUID(),\n site: input.site,\n name: input.name,\n dimension: input.dimension ?? 'page',\n matchType: input.matchType ?? 'contains',\n pattern: input.pattern,\n createdAt: new Date().toISOString(),\n };\n getDb()\n .prepare(`INSERT INTO content_groups\n (id, site_url, name, dimension, match_type, pattern, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`)\n .run(group.id, group.site, group.name, group.dimension, group.matchType, group.pattern, Date.parse(group.createdAt));\n return group;\n}\nexport function listContentGroups(site) {\n const sql = site\n ? 'SELECT * FROM content_groups WHERE site_url = ? ORDER BY created_at DESC'\n : 'SELECT * FROM content_groups ORDER BY created_at DESC';\n const rows = site\n ? getDb().prepare(sql).all(site)\n : getDb().prepare(sql).all();\n return rows.map(groupFromRow);\n}\nexport function getContentGroup(id) {\n const row = getDb()\n .prepare('SELECT * FROM content_groups WHERE id = ?')\n .get(id);\n return row ? groupFromRow(row) : undefined;\n}\nexport function deleteContentGroup(id) {\n return (getDb().prepare('DELETE FROM content_groups WHERE id = ?').run(id).changes >\n 0);\n}\n//# sourceMappingURL=content-groups.js.map","export function pct(after, before) {\n if (before === 0)\n return after === 0 ? 0 : null;\n return Number((((after - before) / before) * 100).toFixed(2));\n}\nexport function fixed(value, digits = 3) {\n return Number(value.toFixed(digits));\n}\nexport function summarizeRows(rows) {\n const clicks = rows.reduce((sum, row) => sum + row.clicks, 0);\n const impressions = rows.reduce((sum, row) => sum + row.impressions, 0);\n const ctr = impressions > 0 ? clicks / impressions : 0;\n const position = impressions > 0\n ? rows.reduce((sum, row) => sum + row.position * row.impressions, 0) /\n impressions\n : 0;\n return {\n clicks: fixed(clicks),\n impressions: fixed(impressions),\n ctr: fixed(ctr, 4),\n position: fixed(position),\n };\n}\n//# sourceMappingURL=math.js.map","import { fixed, pct } from './math.js';\nfunction pathFromTarget(value) {\n try {\n const url = new URL(value);\n return `${url.pathname}${url.search}`;\n }\n catch {\n return value;\n }\n}\nfunction stringMatchType(matchType) {\n if (matchType === 'regex')\n return 'PARTIAL_REGEXP';\n if (matchType === 'equals')\n return 'EXACT';\n return 'CONTAINS';\n}\nexport function ga4LandingPageFilterForChange(change, group) {\n if (change.scope === 'site')\n return undefined;\n if (change.scope === 'query')\n return undefined;\n if (change.scope === 'group') {\n if (group?.dimension !== 'page')\n return undefined;\n return {\n filter: {\n fieldName: 'landingPagePlusQueryString',\n stringFilter: {\n matchType: stringMatchType(group.matchType),\n value: pathFromTarget(group.pattern),\n caseSensitive: false,\n },\n },\n };\n }\n return {\n filter: {\n fieldName: 'landingPagePlusQueryString',\n stringFilter: {\n matchType: 'EXACT',\n value: pathFromTarget(change.target),\n caseSensitive: false,\n },\n },\n };\n}\nexport function summarizeGa4Rows(rows) {\n return rows.reduce((sum, row) => ({\n sessions: fixed(sum.sessions + (Number(row.sessions) || 0)),\n engagedSessions: fixed(sum.engagedSessions + (Number(row.engagedSessions) || 0)),\n conversions: fixed(sum.conversions + (Number(row.conversions) || 0)),\n totalRevenue: fixed(sum.totalRevenue + (Number(row.totalRevenue) || 0)),\n }), {\n sessions: 0,\n engagedSessions: 0,\n conversions: 0,\n totalRevenue: 0,\n });\n}\nexport function analyticsDelta(input) {\n return {\n sessions: fixed(input.after.sessions - input.before.sessions),\n sessionPct: pct(input.after.sessions, input.before.sessions),\n engagedSessions: fixed(input.after.engagedSessions - input.before.engagedSessions),\n engagedSessionPct: pct(input.after.engagedSessions, input.before.engagedSessions),\n conversions: fixed(input.after.conversions - input.before.conversions),\n conversionPct: pct(input.after.conversions, input.before.conversions),\n totalRevenue: fixed(input.after.totalRevenue - input.before.totalRevenue),\n revenuePct: pct(input.after.totalRevenue, input.before.totalRevenue),\n };\n}\n//# sourceMappingURL=analytics.js.map","export function classify(input) {\n const totalImpressions = input.before.impressions + input.after.impressions;\n if (totalImpressions < 100) {\n return {\n verdict: 'not-enough-data',\n confidence: 'low',\n note: 'The comparison windows have fewer than 100 impressions total.',\n };\n }\n const betterPosition = input.positionDelta < -0.5;\n const worsePosition = input.positionDelta > 0.5;\n if (input.clickPct === null &&\n input.before.clicks === 0 &&\n input.after.clicks > 0 &&\n input.after.ctr > input.before.ctr) {\n return {\n verdict: 'positive',\n confidence: 'low',\n note: 'Clicks and CTR increased from a zero-click baseline. Treat the direction as early evidence because percentage growth is undefined.',\n };\n }\n const pctValue = input.clickPct ?? 0;\n const positive = input.clickDelta > 0 && (pctValue >= 10 || betterPosition);\n const negative = input.clickDelta < 0 && (pctValue <= -10 || worsePosition);\n const confidence = Math.abs(input.clickDelta) >= 50 && Math.abs(pctValue) >= 30\n ? 'high'\n : Math.abs(input.clickDelta) >= 10 && Math.abs(pctValue) >= 10\n ? 'medium'\n : 'low';\n if (positive) {\n return {\n verdict: 'positive',\n confidence,\n note: 'Clicks improved after the change. Confirm with segment breakdown before rolling out widely.',\n };\n }\n if (negative) {\n return {\n verdict: 'negative',\n confidence,\n note: 'Clicks declined after the change. Check query mix, ranking movement, and indexability before reverting.',\n };\n }\n if (betterPosition || worsePosition) {\n return {\n verdict: 'mixed',\n confidence,\n note: 'Ranking movement and click movement disagree. Inspect SERP layout, CTR, and query demand.',\n };\n }\n return {\n verdict: 'flat',\n confidence,\n note: 'No material movement detected in this window.',\n };\n}\n//# sourceMappingURL=classify.js.map","import { ga4ReportQualityWarnings, ga4RowsToObjects, } from '../../../ga4/client.js';\nimport { analyticsDelta, summarizeGa4Rows } from './analytics.js';\nasync function queryGa4Metrics(input) {\n const result = await input.ga4Report(input.propertyId, {\n dateRanges: [input.window],\n dimensions: [{ name: 'date' }],\n metrics: [\n { name: 'sessions' },\n { name: 'engagedSessions' },\n { name: 'conversions' },\n { name: 'totalRevenue' },\n ],\n ...(input.filter ? { dimensionFilter: input.filter } : {}),\n limit: 10_000,\n }, { refresh: input.refresh });\n const rows = ga4RowsToObjects(result);\n return {\n metrics: summarizeGa4Rows(rows),\n source: {\n rows: rows.length,\n rowCount: result.rowCount ?? rows.length,\n timeZone: result.metadata?.timeZone,\n currencyCode: result.metadata?.currencyCode,\n },\n warnings: ga4ReportQualityWarnings(result, input.label),\n };\n}\nexport async function queryGa4ChangeWindows(input) {\n const [before, after] = await Promise.all([\n queryGa4Metrics({\n ...input,\n window: input.before,\n label: 'GA4 before window',\n }),\n queryGa4Metrics({\n ...input,\n window: input.after,\n label: 'GA4 after window',\n }),\n ]);\n const metadataWarnings = [];\n if (before.source.timeZone &&\n after.source.timeZone &&\n before.source.timeZone !== after.source.timeZone) {\n metadataWarnings.push('GA4 returned different property timezones across the two windows.');\n }\n if (before.source.currencyCode &&\n after.source.currencyCode &&\n before.source.currencyCode !== after.source.currencyCode) {\n metadataWarnings.push('GA4 returned different currency codes across the two windows.');\n }\n return {\n report: {\n propertyId: input.propertyId,\n before: { ...input.before, metrics: before.metrics },\n after: { ...input.after, metrics: after.metrics },\n delta: analyticsDelta({ before: before.metrics, after: after.metrics }),\n note: 'GA4 attribution is landing-page based. Query-level tests use GSC only.',\n },\n source: { before: before.source, after: after.source },\n warnings: [\n ...new Set([...before.warnings, ...after.warnings, ...metadataWarnings]),\n ],\n };\n}\n//# sourceMappingURL=ga4-change-provider.js.map","function groupOperator(matchType) {\n return matchType === 'regex'\n ? 'includingRegex'\n : matchType === 'contains'\n ? 'contains'\n : 'equals';\n}\nexport function filterForChange(change, group) {\n if (change.scope === 'site')\n return undefined;\n const dimension = change.scope === 'group' ? group?.dimension : change.scope;\n const expression = change.scope === 'group' ? group?.pattern : change.target;\n if (!dimension || !expression)\n return undefined;\n const operator = change.scope === 'group' && group\n ? groupOperator(group.matchType)\n : 'equals';\n return [\n {\n groupType: 'and',\n filters: [{ dimension, operator, expression }],\n },\n ];\n}\n//# sourceMappingURL=filters.js.map","import { filterForChange } from './filters.js';\nimport { fixed, pct, summarizeRows } from './math.js';\nfunction validDateRow(row, window) {\n const date = row.keys[0];\n if (!date)\n return false;\n const parsed = new Date(`${date}T00:00:00.000Z`);\n return (row.keys.length === 1 &&\n /^\\d{4}-\\d{2}-\\d{2}$/.test(date) &&\n !Number.isNaN(parsed.getTime()) &&\n parsed.toISOString().slice(0, 10) === date &&\n date >= window.startDate &&\n date <= window.endDate &&\n [row.clicks, row.impressions, row.ctr, row.position].every(Number.isFinite) &&\n row.clicks >= 0 &&\n row.impressions >= 0 &&\n row.clicks <= row.impressions &&\n row.ctr >= 0 &&\n row.ctr <= 1 &&\n (row.impressions === 0 ? row.position >= 0 : row.position >= 1));\n}\nfunction retainedDateRows(rows, window) {\n const byDate = new Map();\n const conflicts = new Set();\n let invalidRows = 0;\n let duplicateRows = 0;\n for (const row of rows) {\n if (!validDateRow(row, window)) {\n invalidRows += 1;\n continue;\n }\n const date = row.keys[0] ?? '';\n if (conflicts.has(date)) {\n invalidRows += 1;\n continue;\n }\n const previous = byDate.get(date);\n if (!previous) {\n byDate.set(date, row);\n continue;\n }\n const same = previous.clicks === row.clicks &&\n previous.impressions === row.impressions &&\n previous.ctr === row.ctr &&\n previous.position === row.position;\n if (same) {\n duplicateRows += 1;\n continue;\n }\n byDate.delete(date);\n conflicts.add(date);\n invalidRows += 2;\n }\n return {\n rows: [...byDate.values()].sort((left, right) => {\n const leftDate = left.keys[0] ?? '';\n const rightDate = right.keys[0] ?? '';\n return leftDate < rightDate ? -1 : leftDate > rightDate ? 1 : 0;\n }),\n invalidRows,\n duplicateRows,\n };\n}\nasync function queryGscMetrics(input) {\n const result = await input.searchAnalytics(input.site, {\n ...input.window,\n dimensions: ['date'],\n type: 'web',\n dataState: 'final',\n dimensionFilterGroups: input.filters,\n }, { refresh: input.refresh });\n const retained = retainedDateRows(result.rows, input.window);\n return {\n metrics: summarizeRows(retained.rows),\n source: {\n calls: result.calls,\n rowsFetched: result.rowsFetched,\n returnedRows: retained.rows.length,\n invalidRows: retained.invalidRows,\n duplicateRows: retained.duplicateRows,\n },\n };\n}\nfunction metricDelta(input) {\n return {\n clicks: fixed(input.after.clicks - input.before.clicks),\n clickPct: pct(input.after.clicks, input.before.clicks),\n impressions: fixed(input.after.impressions - input.before.impressions),\n impressionPct: pct(input.after.impressions, input.before.impressions),\n ctr: fixed(input.after.ctr - input.before.ctr, 4),\n position: input.before.impressions > 0 && input.after.impressions > 0\n ? fixed(input.after.position - input.before.position)\n : null,\n };\n}\nexport async function queryGscChangeWindows(input) {\n const filters = filterForChange(input.change, input.group);\n const retainedQueryEvidence = input.change.scope === 'query' || input.group?.dimension === 'query';\n const [before, after] = await Promise.all([\n queryGscMetrics({\n site: input.change.site,\n window: input.before,\n filters,\n refresh: input.refresh,\n searchAnalytics: input.searchAnalytics,\n }),\n queryGscMetrics({\n site: input.change.site,\n window: input.after,\n filters,\n refresh: input.refresh,\n searchAnalytics: input.searchAnalytics,\n }),\n ]);\n const warnings = [];\n const invalidRows = before.source.invalidRows + after.source.invalidRows;\n if (invalidRows) {\n warnings.push(`Excluded ${invalidRows} invalid or conflicting Search Console date rows.`);\n }\n if (retainedQueryEvidence) {\n warnings.push('Query-scoped Search Console evidence contains retained query data and can omit anonymized queries.');\n }\n const unusableBefore = before.source.rowsFetched > 0 &&\n before.source.returnedRows === 0 &&\n before.source.invalidRows > 0;\n const unusableAfter = after.source.rowsFetched > 0 &&\n after.source.returnedRows === 0 &&\n after.source.invalidRows > 0;\n const comparable = !unusableBefore &&\n !unusableAfter &&\n (!retainedQueryEvidence ||\n (before.source.returnedRows > 0 && after.source.returnedRows > 0));\n if (!comparable) {\n warnings.push(retainedQueryEvidence\n ? 'A query-scoped window returned no retained rows; absence was not converted into zero movement.'\n : 'A Search Console window contained provider rows but none were valid; the window was not converted into zero movement.');\n }\n const beforeMetrics = unusableBefore ||\n (retainedQueryEvidence && before.source.returnedRows === 0)\n ? null\n : before.metrics;\n const afterMetrics = unusableAfter || (retainedQueryEvidence && after.source.returnedRows === 0)\n ? null\n : after.metrics;\n return {\n before: { ...input.before, metrics: beforeMetrics },\n after: { ...input.after, metrics: afterMetrics },\n delta: beforeMetrics && afterMetrics\n ? metricDelta({ before: beforeMetrics, after: afterMetrics })\n : {\n clicks: null,\n clickPct: null,\n impressions: null,\n impressionPct: null,\n ctr: null,\n position: null,\n },\n status: retainedQueryEvidence || invalidRows > 0 ? 'partial' : 'complete',\n completeness: retainedQueryEvidence\n ? 'retained-query-date-aggregates'\n : 'date-aggregates',\n comparable,\n warnings,\n source: { before: before.source, after: after.source },\n };\n}\n//# sourceMappingURL=gsc-change-provider.js.map","import { latestFinalGscDate } from '../../../gsc/dates.js';\nexport function dateShift(date, days) {\n const value = new Date(`${date}T00:00:00.000Z`);\n value.setUTCDate(value.getUTCDate() + days);\n return value.toISOString().slice(0, 10);\n}\nexport function latestGscDate(now = new Date()) {\n return latestFinalGscDate(now);\n}\n//# sourceMappingURL=dates.js.map","import { SeoError } from '../../../errors.js';\nimport { defaultDateRange } from '../../site-diagnostics/quick-wins-report-input.js';\nimport { dateShift } from './dates.js';\nconst DAY_MS = 86_400_000;\nfunction exactDate(value, label) {\n const pattern = /^\\d{4}-\\d{2}-\\d{2}$/;\n const parsed = new Date(`${value}T00:00:00.000Z`);\n if (!pattern.test(value) ||\n Number.isNaN(parsed.getTime()) ||\n parsed.toISOString().slice(0, 10) !== value) {\n throw new SeoError('INVALID_INPUT', `${label} must be a valid YYYY-MM-DD date.`);\n }\n return value;\n}\nfunction boundedDays(value, fallback, label) {\n const resolved = value ?? fallback;\n if (!Number.isInteger(resolved) || resolved < 1 || resolved > 548) {\n throw new SeoError('INVALID_INPUT', `${label} must be a whole number between 1 and 548.`);\n }\n return resolved;\n}\nfunction calendarDays(startDate, endDate) {\n const start = new Date(`${startDate}T00:00:00.000Z`).getTime();\n const end = new Date(`${endDate}T00:00:00.000Z`).getTime();\n return Math.floor((end - start) / DAY_MS) + 1;\n}\nfunction subtractCalendarMonths(value, months) {\n const source = new Date(`${value}T00:00:00.000Z`);\n const first = new Date(Date.UTC(source.getUTCFullYear(), source.getUTCMonth() - months, 1));\n const lastDay = new Date(Date.UTC(first.getUTCFullYear(), first.getUTCMonth() + 1, 0)).getUTCDate();\n first.setUTCDate(Math.min(source.getUTCDate(), lastDay));\n return first.toISOString().slice(0, 10);\n}\nexport function measurementWindow(input) {\n const changedAt = exactDate(input.changedAt, 'changedAt');\n const beforeDays = boundedDays(input.beforeDays, 28, 'beforeDays');\n const afterDays = boundedDays(input.afterDays, beforeDays, 'afterDays');\n if (beforeDays !== afterDays) {\n throw new SeoError('INVALID_INPUT', 'beforeDays and afterDays must match so raw totals use equal calendar windows.');\n }\n const latestFinalDate = defaultDateRange(1, input.now).endDate;\n const pacificToday = dateShift(latestFinalDate, 4);\n const earliestDate = subtractCalendarMonths(pacificToday, 16);\n if (changedAt > latestFinalDate) {\n throw new SeoError('INSUFFICIENT_DATA', `changedAt must be on or before the latest finalized GSC date, ${latestFinalDate}.`);\n }\n const desiredAfterEnd = dateShift(changedAt, afterDays - 1);\n const afterEnd = desiredAfterEnd > latestFinalDate ? latestFinalDate : desiredAfterEnd;\n const effectiveDays = calendarDays(changedAt, afterEnd);\n const beforeEnd = dateShift(changedAt, -1);\n const beforeStart = dateShift(beforeEnd, -(effectiveDays - 1));\n if (beforeStart < earliestDate) {\n throw new SeoError('INVALID_INPUT', `The equal before window starts before ${earliestDate}, the current 16-month GSC retention boundary.`);\n }\n return {\n before: { startDate: beforeStart, endDate: beforeEnd },\n after: { startDate: changedAt, endDate: afterEnd },\n requestedDays: beforeDays,\n effectiveDays,\n afterWindowTruncated: effectiveDays < afterDays,\n availableDateWindow: { earliestDate, latestFinalDate },\n };\n}\n//# sourceMappingURL=window.js.map","import { SeoError } from '../../errors.js';\nimport { runGa4Report } from '../../ga4/client.js';\nimport { querySearchAnalytics } from '../../gsc/client.js';\nimport { getChange } from './change-log.js';\nimport { getContentGroup } from './content-groups.js';\nimport { ga4LandingPageFilterForChange } from './measurement/analytics.js';\nimport { classify } from './measurement/classify.js';\nimport { queryGa4ChangeWindows } from './measurement/ga4-change-provider.js';\nimport { queryGscChangeWindows } from './measurement/gsc-change-provider.js';\nimport { fixed } from './measurement/math.js';\nimport { measurementWindow } from './measurement/window.js';\nconst defaultDependencies = {\n searchAnalytics: querySearchAnalytics,\n ga4Report: runGa4Report,\n contentGroup: getContentGroup,\n now: () => new Date(),\n};\nfunction resolveContentGroup(change, contentGroup) {\n if (change.scope !== 'group')\n return undefined;\n const group = contentGroup(change.target);\n if (!group) {\n throw new SeoError('INVALID_INPUT', `Content group ${change.target} was not found.`);\n }\n if (group.site !== change.site) {\n throw new SeoError('INVALID_INPUT', `Content group ${change.target} belongs to ${group.site}, not ${change.site}.`);\n }\n return group;\n}\nfunction counterfactualDelta(input) {\n if (input.controlBefore <= 0)\n return null;\n const expectedAfter = input.treatmentBefore * (input.controlAfter / input.controlBefore);\n return fixed(input.treatmentAfter - expectedAfter);\n}\nexport async function measureChange(input, dependencies = defaultDependencies) {\n const now = dependencies.now();\n const stored = input.id ? getChange(input.id) : undefined;\n const change = stored ??\n {\n id: 'adhoc',\n site: input.site,\n scope: input.scope,\n target: input.target,\n title: input.title ?? 'Ad hoc change measurement',\n changedAt: input.changedAt,\n createdAt: now.toISOString(),\n };\n if (!change.site?.trim() ||\n !change.scope ||\n !change.target?.trim() ||\n !change.changedAt) {\n throw new SeoError('INVALID_INPUT', 'Pass a change id, or provide site, scope, target, and changedAt.');\n }\n if (Boolean(input.controlScope) !== Boolean(input.controlTarget?.trim())) {\n throw new SeoError('INVALID_INPUT', 'controlScope and controlTarget must be provided together.');\n }\n const window = measurementWindow({\n changedAt: change.changedAt,\n beforeDays: input.beforeDays,\n afterDays: input.afterDays,\n now,\n });\n const { before, after } = window;\n const group = resolveContentGroup(change, dependencies.contentGroup);\n const controlChange = input.controlScope && input.controlTarget\n ? {\n id: 'control',\n site: change.site,\n scope: input.controlScope,\n target: input.controlTarget,\n title: input.controlTitle ?? 'Control group',\n changedAt: change.changedAt,\n createdAt: now.toISOString(),\n }\n : undefined;\n const controlGroup = controlChange\n ? resolveContentGroup(controlChange, dependencies.contentGroup)\n : undefined;\n const measured = await queryGscChangeWindows({\n change,\n before,\n after,\n group,\n refresh: input.refresh,\n searchAnalytics: dependencies.searchAnalytics,\n });\n const control = controlChange\n ? await queryGscChangeWindows({\n change: controlChange,\n before,\n after,\n group: controlGroup,\n refresh: input.refresh,\n searchAnalytics: dependencies.searchAnalytics,\n })\n : undefined;\n const clickPct = measured.delta.clickPct;\n const shortWindow = window.effectiveDays < 7;\n const unavailableReason = window.afterWindowTruncated\n ? `Only ${window.effectiveDays} of ${window.requestedDays} requested finalized after-days are available.`\n : !measured.comparable\n ? 'A Search Console window has no comparable metrics.'\n : shortWindow\n ? `Only ${window.effectiveDays} finalized day${window.effectiveDays === 1 ? '' : 's'} are available in each window.`\n : undefined;\n const classified = measured.before.metrics &&\n measured.after.metrics &&\n measured.delta.clicks !== null &&\n measured.delta.position !== null\n ? classify({\n before: measured.before.metrics,\n after: measured.after.metrics,\n clickPct,\n clickDelta: measured.delta.clicks,\n positionDelta: measured.delta.position,\n })\n : {\n verdict: 'not-enough-data',\n confidence: 'low',\n note: 'Comparable Search Console metrics are unavailable.',\n };\n const verdict = unavailableReason\n ? {\n verdict: 'not-enough-data',\n confidence: 'low',\n note: `${unavailableReason} The equal-window metrics are provisional and no directional verdict was assigned.`,\n }\n : measured.status === 'partial' && classified.confidence === 'high'\n ? {\n ...classified,\n confidence: 'medium',\n note: `${classified.note} Confidence is capped because Search Console evidence is partial.`,\n }\n : classified;\n const ga4Filter = ga4LandingPageFilterForChange(change, group);\n const queryDimension = change.scope === 'query' || group?.dimension === 'query';\n const analytics = input.ga4PropertyId && !queryDimension\n ? await queryGa4ChangeWindows({\n propertyId: input.ga4PropertyId,\n before,\n after,\n filter: ga4Filter,\n refresh: input.refresh,\n ga4Report: dependencies.ga4Report,\n })\n : undefined;\n const warnings = [\n ...measured.warnings,\n ...(control?.warnings.map((warning) => `Control: ${warning}`) ?? []),\n ...(analytics?.warnings ?? []),\n ];\n const dataStatus = window.afterWindowTruncated ||\n measured.status === 'partial' ||\n control?.status === 'partial' ||\n analytics?.warnings.length\n ? 'partial'\n : 'complete';\n return {\n schemaVersion: 1,\n methodology: 'equal-finalized-calendar-windows-v1',\n dataStatus,\n change,\n window: {\n requestedDays: window.requestedDays,\n effectiveDays: window.effectiveDays,\n afterWindowTruncated: window.afterWindowTruncated,\n gscTimezone: 'America/Los_Angeles',\n availableDateWindow: window.availableDateWindow,\n },\n source: {\n searchAnalytics: {\n status: measured.status,\n completeness: measured.completeness,\n dimensions: ['date'],\n searchType: 'web',\n dataState: 'final',\n before: measured.source.before,\n after: measured.source.after,\n ...(control\n ? {\n control: {\n status: control.status,\n completeness: control.completeness,\n before: control.source.before,\n after: control.source.after,\n },\n }\n : {}),\n warnings: [\n ...measured.warnings,\n ...(control?.warnings.map((warning) => `Control: ${warning}`) ?? []),\n ],\n },\n ...(analytics\n ? {\n analytics: {\n status: analytics.warnings.length\n ? 'partial'\n : 'complete',\n before: analytics.source.before,\n after: analytics.source.after,\n warnings: analytics.warnings,\n },\n }\n : {}),\n },\n before: measured.before,\n after: measured.after,\n delta: measured.delta,\n ...(analytics ? { analytics: analytics.report } : {}),\n ...(control && controlChange\n ? {\n control: {\n change: controlChange,\n before: control.before,\n after: control.after,\n delta: control.delta,\n adjusted: {\n methodology: 'control-ratio-counterfactual-v1',\n clickDelta: control.comparable &&\n measured.before.metrics &&\n measured.after.metrics &&\n control.before.metrics &&\n control.after.metrics\n ? counterfactualDelta({\n treatmentBefore: measured.before.metrics.clicks,\n treatmentAfter: measured.after.metrics.clicks,\n controlBefore: control.before.metrics.clicks,\n controlAfter: control.after.metrics.clicks,\n })\n : null,\n clickPctPoints: measured.delta.clickPct === null ||\n control.delta.clickPct === null\n ? null\n : fixed(measured.delta.clickPct - control.delta.clickPct),\n impressionDelta: control.comparable &&\n measured.before.metrics &&\n measured.after.metrics &&\n control.before.metrics &&\n control.after.metrics\n ? counterfactualDelta({\n treatmentBefore: measured.before.metrics.impressions,\n treatmentAfter: measured.after.metrics.impressions,\n controlBefore: control.before.metrics.impressions,\n controlAfter: control.after.metrics.impressions,\n })\n : null,\n impressionPctPoints: measured.delta.impressionPct === null ||\n control.delta.impressionPct === null\n ? null\n : fixed(measured.delta.impressionPct -\n control.delta.impressionPct),\n },\n note: 'Adjusted deltas compare the observed treatment result with a control-ratio counterfactual. Controls reduce some shared noise but do not prove causality.',\n },\n }\n : {}),\n ...verdict,\n warnings,\n caveats: [\n `Compared ${window.effectiveDays} finalized Search Console calendar days before and after the change in America/Los_Angeles time.`,\n 'Search Console position is impression-weighted average position; before/after timing and controls do not prove causality.',\n ...(window.afterWindowTruncated\n ? [\n `The requested ${window.requestedDays}-day after window is incomplete, so this run is partial and has no directional verdict.`,\n ]\n : []),\n ...(shortWindow\n ? [\n 'Fewer than 7 finalized days per window is too short for a directional verdict.',\n ]\n : []),\n ...(measured.completeness === 'retained-query-date-aggregates'\n ? [\n 'Query-scoped Search Console data can omit anonymized queries; an absent retained row is not zero traffic.',\n ]\n : []),\n ...(analytics\n ? [\n `GA4 attribution uses landing pages and the GA4 property timezone${analytics.source.before.timeZone ? ` (${analytics.source.before.timeZone})` : ''}; its day boundaries may differ from Search Console Pacific dates.`,\n ]\n : []),\n ],\n };\n}\n//# sourceMappingURL=measure-change.js.map","const STOPWORDS = new Set([\n 'a',\n 'an',\n 'and',\n 'are',\n 'at',\n 'best',\n 'by',\n 'for',\n 'free',\n 'from',\n 'guide',\n 'how',\n 'in',\n 'is',\n 'of',\n 'on',\n 'online',\n 'or',\n 'page',\n 'seo',\n 'site',\n 'the',\n 'to',\n 'tool',\n 'use',\n 'website',\n 'what',\n 'when',\n 'where',\n 'which',\n 'with',\n]);\nexport function compareInternalLinkText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\nexport function normalizeInternalLinkQuery(value) {\n return value\n .normalize('NFKC')\n .replace(/[’']/g, \"'\")\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}']+/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\nexport function normalizeInternalLinkUrl(value) {\n try {\n const url = new URL(value);\n if (url.protocol !== 'http:' && url.protocol !== 'https:')\n return undefined;\n url.hash = '';\n return url.toString();\n }\n catch {\n return undefined;\n }\n}\nexport function validInternalLinkRow(row) {\n const [query, page] = row.keys;\n return Boolean(normalizeInternalLinkQuery(query ?? '') &&\n normalizeInternalLinkUrl(page ?? '') &&\n Number.isFinite(row.clicks) &&\n row.clicks >= 0 &&\n Number.isFinite(row.impressions) &&\n row.impressions > 0 &&\n row.clicks <= row.impressions &&\n Number.isFinite(row.ctr) &&\n row.ctr >= 0 &&\n row.ctr <= 1 &&\n Number.isFinite(row.position) &&\n row.position > 0);\n}\nexport function internalLinkTokens(query) {\n const normalized = normalizeInternalLinkQuery(query);\n const tokens = typeof Intl !== 'undefined' && 'Segmenter' in Intl\n ? [\n ...new Intl.Segmenter('und', { granularity: 'word' }).segment(normalized),\n ]\n .filter((part) => part.isWordLike)\n .map((part) => part.segment)\n : (normalized.match(/[\\p{L}\\p{N}]+/gu) ?? []);\n return [\n ...new Set(tokens.filter((token) => !STOPWORDS.has(token) &&\n !/^\\p{N}+$/u.test(token) &&\n ([...token].length > 1 || /[^\\p{ASCII}]/u.test(token)))),\n ];\n}\nexport function createInternalLinkLexicalScorer(queries) {\n const tokenCache = new Map();\n const tokensFor = (query) => {\n const key = normalizeInternalLinkQuery(query);\n const cached = tokenCache.get(key);\n if (cached)\n return cached;\n const tokens = internalLinkTokens(query);\n tokenCache.set(key, tokens);\n return tokens;\n };\n const documents = [\n ...new Set(queries.map(normalizeInternalLinkQuery).filter(Boolean)),\n ].map(tokensFor);\n const documentFrequency = new Map();\n for (const document of documents) {\n for (const token of new Set(document)) {\n documentFrequency.set(token, (documentFrequency.get(token) ?? 0) + 1);\n }\n }\n const documentCount = Math.max(1, documents.length);\n const frequencyLimit = Math.max(3, Math.ceil(documentCount * 0.1));\n const weight = (token) => Math.log((documentCount + 1) / ((documentFrequency.get(token) ?? 0) + 1)) +\n 1;\n const informative = (tokens) => tokens.filter((token) => (documentFrequency.get(token) ?? 0) <= frequencyLimit);\n return (sourceQuery, targetQuery) => {\n const source = informative(tokensFor(sourceQuery));\n const target = informative(tokensFor(targetQuery));\n if (source.length < 2 || target.length < 2)\n return undefined;\n const targetSet = new Set(target);\n const sharedTerms = source\n .filter((token) => targetSet.has(token))\n .sort(compareInternalLinkText);\n if (sharedTerms.length < 2)\n return undefined;\n const union = new Set([...source, ...target]);\n const sharedWeight = sharedTerms.reduce((sum, token) => sum + weight(token), 0);\n const targetWeight = target.reduce((sum, token) => sum + weight(token), 0);\n const sourceWeight = source.reduce((sum, token) => sum + weight(token), 0);\n const unionWeight = [...union].reduce((sum, token) => sum + weight(token), 0);\n const targetCoverage = sharedWeight / targetWeight;\n const sourceCoverage = sharedWeight / sourceWeight;\n const weightedJaccard = sharedWeight / unionWeight;\n const score = weightedJaccard * 0.5 + targetCoverage * 0.25 + sourceCoverage * 0.25;\n if (targetCoverage < 2 / 3 ||\n sourceCoverage < 2 / 3 ||\n weightedJaccard < 0.6 ||\n score < 0.72) {\n return undefined;\n }\n return {\n score: Number(score.toFixed(4)),\n weightedJaccard: Number(weightedJaccard.toFixed(4)),\n targetCoverage: Number(targetCoverage.toFixed(4)),\n sourceCoverage: Number(sourceCoverage.toFixed(4)),\n sharedTerms,\n };\n };\n}\n//# sourceMappingURL=internal-links-analysis-primitives.js.map","import { shouldExcludeBrandQuery } from '../brand.js';\nimport { compareInternalLinkText, createInternalLinkLexicalScorer, internalLinkTokens, normalizeInternalLinkQuery, normalizeInternalLinkUrl, validInternalLinkRow, } from './internal-links-analysis-primitives.js';\nimport { isLowActionabilityQuery } from './query-quality.js';\nconst LEXICAL_TARGET_LIMIT = 50;\nexport const INTERNAL_LINK_LEXICAL_TARGET_LIMIT = LEXICAL_TARGET_LIMIT;\nexport const INTERNAL_LINK_MATCH_EVIDENCE_LIMIT = 10;\nfunction exclusion(input) {\n if (input.impressions < input.minImpressions)\n return 'low-impressions';\n if (isLowActionabilityQuery(input.query))\n return 'low-actionability';\n if (shouldExcludeBrandQuery({\n query: input.query,\n siteUrl: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n })) {\n return 'brand';\n }\n return undefined;\n}\nfunction mergeQuery(map, key, query, row) {\n const current = map.get(key) ?? { query, clicks: 0, impressions: 0 };\n current.clicks += row.clicks;\n current.impressions += row.impressions;\n if (compareInternalLinkText(query, current.query) < 0)\n current.query = query;\n map.set(key, current);\n}\nfunction bestMatch(input) {\n const sourceKey = normalizeInternalLinkQuery(input.source.query);\n const exact = input.exactTargets.get(sourceKey);\n if (exact) {\n return {\n sourceQuery: input.source.query,\n targetQuery: exact.query,\n kind: 'exact-query',\n relevanceScore: 1,\n impressions: input.source.impressions,\n sharedTerms: internalLinkTokens(input.source.query),\n };\n }\n const lexicalMatches = input.lexicalTargets.flatMap((target) => {\n const score = input.scoreLexical(input.source.query, target.query);\n return score\n ? [\n {\n sourceQuery: input.source.query,\n targetQuery: target.query,\n kind: 'lexical-review',\n relevanceScore: score.score,\n impressions: input.source.impressions,\n sharedTerms: score.sharedTerms,\n },\n ]\n : [];\n });\n return lexicalMatches.sort((left, right) => right.relevanceScore - left.relevanceScore ||\n compareInternalLinkText(left.targetQuery, right.targetQuery))[0];\n}\nfunction candidatesFromMatches(matchesByUrl) {\n return [...matchesByUrl.entries()]\n .map(([sourceUrl, matches]) => {\n const ordered = [...matches].sort((left, right) => (left.kind === right.kind\n ? 0\n : left.kind === 'exact-query'\n ? -1\n : 1) ||\n right.impressions - left.impressions ||\n right.relevanceScore - left.relevanceScore ||\n compareInternalLinkText(left.sourceQuery, right.sourceQuery));\n return {\n sourceUrl,\n matchedQueryImpressions: ordered.reduce((sum, match) => sum + match.impressions, 0),\n matchedQueries: ordered.length,\n exactQueryMatches: ordered.filter((match) => match.kind === 'exact-query').length,\n bestRelevanceScore: Math.max(...ordered.map((match) => match.relevanceScore)),\n bestMatchKind: ordered.some((match) => match.kind === 'exact-query')\n ? 'exact-query'\n : 'lexical-review',\n matches: ordered.slice(0, INTERNAL_LINK_MATCH_EVIDENCE_LIMIT),\n };\n })\n .sort((left, right) => right.exactQueryMatches - left.exactQueryMatches ||\n right.matchedQueryImpressions - left.matchedQueryImpressions ||\n right.bestRelevanceScore - left.bestRelevanceScore ||\n compareInternalLinkText(left.sourceUrl, right.sourceUrl));\n}\nexport function analyzeInternalLinksFromRows(input) {\n const aliases = new Set(input.targetAliases\n .map(normalizeInternalLinkUrl)\n .filter((url) => Boolean(url)));\n const count = new Map();\n const increment = (key) => {\n count.set(key, (count.get(key) ?? 0) + 1);\n };\n const targetMap = new Map();\n let targetValidRows = 0;\n for (const row of input.targetRows) {\n if (!validInternalLinkRow(row)) {\n increment('targetInvalidRows');\n continue;\n }\n targetValidRows += 1;\n const query = row.keys[0] ?? '';\n const page = normalizeInternalLinkUrl(row.keys[1] ?? '');\n if (!page || !aliases.has(page)) {\n increment('targetUrlMismatchRows');\n continue;\n }\n mergeQuery(targetMap, normalizeInternalLinkQuery(query), query, row);\n }\n const allTargets = [...targetMap.values()]\n .filter((target) => {\n const reason = exclusion({\n ...target,\n site: input.site,\n minImpressions: input.minImpressions,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n if (reason === 'low-impressions')\n increment('targetLowImpressionQueries');\n if (reason === 'low-actionability')\n increment('targetLowActionabilityQueries');\n if (reason === 'brand')\n increment('targetBrandQueries');\n return !reason;\n })\n .sort((left, right) => right.impressions - left.impressions ||\n right.clicks - left.clicks ||\n compareInternalLinkText(left.query, right.query));\n const lexicalTargets = allTargets.slice(0, LEXICAL_TARGET_LIMIT);\n const exactTargets = new Map(allTargets.map((target) => [\n normalizeInternalLinkQuery(target.query),\n target,\n ]));\n const sourceMap = new Map();\n let sourceValidRows = 0;\n for (const row of input.sourceRows) {\n if (!validInternalLinkRow(row)) {\n increment('sourceInvalidRows');\n continue;\n }\n sourceValidRows += 1;\n const query = row.keys[0] ?? '';\n const page = normalizeInternalLinkUrl(row.keys[1] ?? '');\n if (!page)\n continue;\n if (aliases.has(page)) {\n increment('sourceTargetAliasRows');\n continue;\n }\n const key = `${page}\\u0000${normalizeInternalLinkQuery(query)}`;\n const current = sourceMap.get(key) ?? {\n page,\n query,\n clicks: 0,\n impressions: 0,\n };\n current.clicks += row.clicks;\n current.impressions += row.impressions;\n if (compareInternalLinkText(query, current.query) < 0)\n current.query = query;\n sourceMap.set(key, current);\n }\n const eligibleSources = [...sourceMap.values()].filter((source) => {\n const reason = exclusion({\n ...source,\n site: input.site,\n minImpressions: input.minImpressions,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n if (reason === 'low-impressions')\n increment('sourceLowImpressionQueries');\n if (reason === 'low-actionability')\n increment('sourceLowActionabilityQueries');\n if (reason === 'brand')\n increment('sourceBrandQueries');\n return !reason;\n });\n const scoreLexical = createInternalLinkLexicalScorer([\n ...allTargets.map((target) => target.query),\n ...eligibleSources.map((source) => source.query),\n ]);\n const matchesByUrl = new Map();\n let candidateQueries = 0;\n for (const source of eligibleSources) {\n const match = bestMatch({\n source,\n exactTargets,\n lexicalTargets,\n scoreLexical,\n });\n if (!match) {\n increment('sourceUnmatchedQueries');\n continue;\n }\n candidateQueries += 1;\n const matches = matchesByUrl.get(source.page) ?? [];\n matches.push(match);\n matchesByUrl.set(source.page, matches);\n }\n const candidates = candidatesFromMatches(matchesByUrl);\n const value = (key) => count.get(key) ?? 0;\n return {\n targetQueries: lexicalTargets,\n candidates,\n selection: {\n targetSourceRows: input.targetRows.length,\n targetValidRows,\n targetInvalidRows: value('targetInvalidRows'),\n targetUrlMismatchRows: value('targetUrlMismatchRows'),\n targetLowImpressionQueries: value('targetLowImpressionQueries'),\n targetLowActionabilityQueries: value('targetLowActionabilityQueries'),\n targetBrandQueries: value('targetBrandQueries'),\n targetEligibleQueries: allTargets.length,\n selectedLexicalTargetQueries: lexicalTargets.length,\n sourceRows: input.sourceRows.length,\n sourceValidRows,\n sourceInvalidRows: value('sourceInvalidRows'),\n sourceTargetAliasRows: value('sourceTargetAliasRows'),\n sourceLowImpressionQueries: value('sourceLowImpressionQueries'),\n sourceLowActionabilityQueries: value('sourceLowActionabilityQueries'),\n sourceBrandQueries: value('sourceBrandQueries'),\n sourceUnmatchedQueries: value('sourceUnmatchedQueries'),\n candidateQueries,\n candidateUrls: candidates.length,\n },\n };\n}\n//# sourceMappingURL=internal-links-analysis.js.map","import { SeoError } from '../errors.js';\nimport { finalGscDateRange } from '../gsc/dates.js';\nexport function internalLinksIntegerOption(input) {\n const value = input.value ?? input.fallback;\n if (!Number.isInteger(value) ||\n value < input.minimum ||\n value > input.maximum) {\n throw new SeoError('INVALID_INPUT', `${input.label} must be a whole number between ${input.minimum} and ${input.maximum}.`);\n }\n return value;\n}\nexport function internalLinksNumberOption(input) {\n const value = input.value ?? input.fallback;\n if (!Number.isFinite(value) ||\n value < input.minimum ||\n value > input.maximum) {\n throw new SeoError('INVALID_INPUT', `${input.label} must be between ${input.minimum} and ${input.maximum}.`);\n }\n return value;\n}\nexport function internalLinksReportRange(days, now) {\n return finalGscDateRange(days, now);\n}\nexport function completeInternalLinksSelection(analysis, runtime) {\n return { ...analysis.selection, ...runtime };\n}\nexport function internalLinksVerdict(input) {\n if (input.dataStatus === 'target-technical-issue') {\n return 'The target has a technical issue. Resolve it before adding internal links.';\n }\n if (input.dataStatus === 'empty') {\n return 'Search Console returned no retained query/page rows for the target URL aliases in this window.';\n }\n if (input.dataStatus === 'source-empty') {\n return 'Search Console returned no retained source query/page rows in this window. This does not prove that no relevant source page exists.';\n }\n if (input.dataStatus === 'filtered') {\n return 'Target demand exists, but no precision-matched source candidates passed the report filters.';\n }\n if (input.returned) {\n return `${input.returned} internal-link review candidate${input.returned === 1 ? '' : 's'} remained after ${input.attempted} verification attempt${input.attempted === 1 ? '' : 's'}; ${input.checked} of ${input.candidates} matched source pages were successfully checked.`;\n }\n if (input.dataStatus === 'partial') {\n if (input.candidates === 0 && input.attempted === 0) {\n return 'Internal-link candidates could not be evaluated because required target, provider, or row evidence was incomplete.';\n }\n return `No missing contextual link was confirmed among ${input.checked} successfully checked source page${input.checked === 1 ? '' : 's'}; evidence remains incomplete with ${input.failed} failed check${input.failed === 1 ? '' : 's'} and ${input.unchecked} unattempted candidate${input.unchecked === 1 ? '' : 's'}.`;\n }\n return `No missing contextual link was confirmed among ${input.checked} successfully checked source page${input.checked === 1 ? '' : 's'}.`;\n}\nexport function uniqueInternalLinksWarnings(warnings) {\n return [\n ...new Map(warnings.map((warning) => [\n `${warning.stage}\\u0000${warning.url}\\u0000${warning.code}\\u0000${warning.message}`,\n warning,\n ])).values(),\n ];\n}\n//# sourceMappingURL=internal-links-report.js.map","import { assertUrlMatchesGscProperty } from '../gsc/property-url.js';\nimport { pageTechnicalSignals } from './page-technical-signals.js';\nexport const INTERNAL_LINK_OBSERVED_EVIDENCE_LIMIT = 20;\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : String(error);\n}\nfunction acceptedAlias(site, value) {\n if (!value)\n return undefined;\n try {\n return assertUrlMatchesGscProperty(site, value);\n }\n catch {\n return undefined;\n }\n}\nfunction withoutFragment(value) {\n const url = new URL(value);\n url.hash = '';\n return url.toString();\n}\nfunction sameObservedUrl(left, right) {\n try {\n return withoutFragment(left) === withoutFragment(right);\n }\n catch {\n return false;\n }\n}\nfunction absoluteCanonical(page) {\n if (!page.canonical)\n return undefined;\n try {\n return new URL(page.canonical, page.finalUrl).toString();\n }\n catch {\n return undefined;\n }\n}\nexport async function verifyInternalLinkTarget(input) {\n let fetched;\n try {\n fetched = await input.dependencies.fetch(input.targetUrl, {\n js: input.js ?? 'auto',\n refresh: input.refresh,\n rate: input.rate,\n });\n }\n catch (error) {\n return {\n requestedUrl: input.targetUrl,\n preferredUrl: input.targetUrl,\n aliases: [input.targetUrl],\n verification: 'failed',\n technicalSignals: [],\n warnings: [\n {\n stage: 'target-fetch',\n url: input.targetUrl,\n code: 'fetch-failed',\n message: errorMessage(error),\n },\n ],\n };\n }\n let page;\n try {\n page = await input.dependencies.extract(fetched);\n }\n catch (error) {\n return {\n requestedUrl: input.targetUrl,\n preferredUrl: input.targetUrl,\n finalUrl: fetched.finalUrl,\n status: fetched.status,\n aliases: [input.targetUrl],\n verification: 'failed',\n technicalSignals: [],\n fetchDiagnostics: fetched.diagnostics,\n warnings: [\n {\n stage: 'target-extract',\n url: input.targetUrl,\n code: 'extract-failed',\n message: errorMessage(error),\n },\n ],\n };\n }\n const canonical = absoluteCanonical(page);\n const acceptedFinal = acceptedAlias(input.site, page.finalUrl);\n const acceptedCanonical = acceptedAlias(input.site, canonical);\n const aliases = [input.targetUrl, acceptedFinal, acceptedCanonical]\n .filter((url) => Boolean(url))\n .map(withoutFragment);\n const uniqueAliases = [...new Set(aliases)];\n const signals = pageTechnicalSignals({\n url: input.targetUrl,\n page,\n fetchDiagnostics: fetched.diagnostics,\n httpStatus: fetched.status,\n });\n const fatalSignals = signals.filter((signal) => signal !== 'redirected' || !acceptedFinal);\n const warnings = page.warnings.map((message) => ({\n stage: 'target-extract',\n url: input.targetUrl,\n code: 'extractor-warning',\n message,\n }));\n return {\n requestedUrl: input.targetUrl,\n preferredUrl: acceptedFinal ?? input.targetUrl,\n finalUrl: page.finalUrl,\n canonical,\n status: fetched.status,\n aliases: uniqueAliases,\n verification: fatalSignals.length ? 'technical-issue' : 'verified',\n technicalSignals: signals,\n fetchDiagnostics: fetched.diagnostics,\n warnings,\n };\n}\nfunction linksToAliases(page, aliases) {\n return page.links.filter((link) => aliases.some((alias) => sameObservedUrl(link.href, alias)));\n}\nfunction priority(candidate) {\n const score = Math.round(candidate.exactQueryMatches * 100 +\n Math.log10(candidate.matchedQueryImpressions + 1) * 10 +\n candidate.bestRelevanceScore * 10);\n return {\n score,\n heuristic: true,\n components: {\n exactQueryMatches: candidate.exactQueryMatches,\n matchedQueryImpressions: candidate.matchedQueryImpressions,\n relevanceScore: candidate.bestRelevanceScore,\n },\n };\n}\nexport async function verifyInternalLinkCandidate(input) {\n try {\n assertUrlMatchesGscProperty(input.site, input.candidate.sourceUrl);\n }\n catch (error) {\n return {\n exclusion: 'failed',\n warnings: [\n {\n stage: 'source-fetch',\n url: input.candidate.sourceUrl,\n code: 'fetch-failed',\n message: errorMessage(error),\n },\n ],\n };\n }\n let fetched;\n try {\n fetched = await input.dependencies.fetch(input.candidate.sourceUrl, {\n js: input.js ?? 'auto',\n refresh: input.refresh,\n rate: input.rate,\n });\n }\n catch (error) {\n return {\n exclusion: 'failed',\n warnings: [\n {\n stage: 'source-fetch',\n url: input.candidate.sourceUrl,\n code: 'fetch-failed',\n message: errorMessage(error),\n },\n ],\n };\n }\n let page;\n try {\n page = await input.dependencies.extract(fetched);\n }\n catch (error) {\n return {\n exclusion: 'failed',\n warnings: [\n {\n stage: 'source-extract',\n url: input.candidate.sourceUrl,\n code: 'extract-failed',\n message: errorMessage(error),\n },\n ],\n };\n }\n const warnings = page.warnings.map((message) => ({\n stage: 'source-extract',\n url: input.candidate.sourceUrl,\n code: 'extractor-warning',\n message,\n }));\n if (input.target.aliases.some((alias) => sameObservedUrl(page.finalUrl, alias))) {\n return { exclusion: 'self-alias', warnings };\n }\n const technicalSignals = pageTechnicalSignals({\n url: input.candidate.sourceUrl,\n page,\n fetchDiagnostics: fetched.diagnostics,\n httpStatus: fetched.status,\n });\n if (technicalSignals.length) {\n return { exclusion: 'technical', warnings };\n }\n const observed = linksToAliases(page, input.target.aliases).map((link) => ({\n href: link.href,\n text: link.text,\n rel: link.rel,\n location: link.location,\n }));\n const contextual = observed.filter((link) => link.location === 'main-content');\n const preferredContextual = contextual.some((link) => sameObservedUrl(link.href, input.target.preferredUrl));\n if (preferredContextual)\n return { exclusion: 'existing-link', warnings };\n const aliasContextual = contextual.length > 0;\n const linkStatus = aliasContextual\n ? 'alias-contextual'\n : observed.length\n ? 'non-contextual-only'\n : 'missing';\n const confidence = input.candidate.bestMatchKind === 'exact-query' &&\n !page.contentExtraction.fallback\n ? 'medium'\n : 'low';\n const actionType = aliasContextual\n ? 'review-alias-link'\n : 'review-contextual-link';\n const evidenceRef = aliasContextual\n ? `A main-content link points to a non-preferred target alias; the preferred target is ${input.target.preferredUrl}.`\n : `${input.candidate.sourceUrl} matched ${input.candidate.matchedQueries} retained GSC query row${input.candidate.matchedQueries === 1 ? '' : 's'}, and no main-content link to the preferred target was observed in the fetched HTML.`;\n const action = aliasContextual\n ? `Review the existing contextual link and update it to the preferred target ${input.target.preferredUrl} if the redirect or old alias is not intentional.`\n : `Review whether this source page and ${input.target.preferredUrl} serve complementary intent. If the link would help a reader, add a natural main-content link without forcing exact-match anchor text.`;\n return {\n item: {\n ...input.candidate,\n finalUrl: page.finalUrl,\n status: fetched.status,\n technicalSignals,\n fetchDiagnostics: fetched.diagnostics,\n pageWarnings: page.warnings,\n actionType,\n linkEvidence: {\n status: linkStatus,\n observedCount: observed.length,\n observedLimit: INTERNAL_LINK_OBSERVED_EVIDENCE_LIMIT,\n limitedCount: Math.max(0, observed.length - INTERNAL_LINK_OBSERVED_EVIDENCE_LIMIT),\n observed: observed.slice(0, INTERNAL_LINK_OBSERVED_EVIDENCE_LIMIT),\n },\n confidence,\n priority: priority(input.candidate),\n recommendation: {\n principle: 'C.6',\n evidenceRef,\n action,\n effort: 'S',\n confidence,\n },\n },\n warnings,\n };\n}\n//# sourceMappingURL=internal-links-verification.js.map","import { extractPage } from '../extract/page-extractor.js';\nimport { fetchPage } from '../fetch/page-fetcher.js';\nimport { querySearchAnalytics } from '../gsc/client.js';\nimport { assertUrlMatchesGscProperty } from '../gsc/property-url.js';\nimport { SessionLedger } from '../storage/ledger.js';\nimport { analyzeInternalLinksFromRows, INTERNAL_LINK_LEXICAL_TARGET_LIMIT, INTERNAL_LINK_MATCH_EVIDENCE_LIMIT, } from './internal-links-analysis.js';\nimport { completeInternalLinksSelection, internalLinksIntegerOption, internalLinksNumberOption, internalLinksReportRange, internalLinksVerdict, uniqueInternalLinksWarnings, } from './internal-links-report.js';\nimport { INTERNAL_LINK_OBSERVED_EVIDENCE_LIMIT, verifyInternalLinkCandidate, verifyInternalLinkTarget, } from './internal-links-verification.js';\nexport * from './internal-links-analysis.js';\nconst MAX_GSC_ROWS = 100_000;\nconst defaultDependencies = {\n searchAnalytics: querySearchAnalytics,\n fetch: fetchPage,\n extract: extractPage,\n now: () => new Date(),\n};\nexport async function internalLinksReport(input, dependencies = defaultDependencies) {\n const targetPage = new URL(assertUrlMatchesGscProperty(input.site, input.targetUrl));\n targetPage.hash = '';\n const targetUrl = targetPage.toString();\n const days = internalLinksIntegerOption({\n value: input.days,\n fallback: 28,\n minimum: 1,\n maximum: 548,\n label: 'days',\n });\n const limit = internalLinksIntegerOption({\n value: input.limit,\n fallback: 20,\n minimum: 1,\n maximum: 100,\n label: 'limit',\n });\n const checkLimit = internalLinksIntegerOption({\n value: input.checkLimit,\n fallback: Math.max(limit, 40),\n minimum: 1,\n maximum: 200,\n label: 'checkLimit',\n });\n const minImpressions = internalLinksNumberOption({\n value: input.minImpressions,\n fallback: 1,\n minimum: 0,\n maximum: 1_000_000_000,\n label: 'minImpressions',\n });\n const now = dependencies.now();\n const range = internalLinksReportRange(days, now);\n const ledger = new SessionLedger();\n const target = await verifyInternalLinkTarget({\n site: input.site,\n targetUrl,\n js: input.js,\n refresh: input.refresh,\n rate: input.rate,\n dependencies,\n });\n const targetRequests = await Promise.all(target.aliases.map(async (alias) => {\n const result = await dependencies.searchAnalytics(input.site, {\n ...range,\n dimensions: ['query', 'page'],\n type: 'web',\n dataState: 'final',\n maxRows: MAX_GSC_ROWS,\n dimensionFilterGroups: [\n {\n groupType: 'and',\n filters: [\n { dimension: 'page', operator: 'equals', expression: alias },\n ],\n },\n ],\n }, { refresh: input.refresh });\n ledger.addGsc(result.calls, result.rowsFetched);\n return { alias, result };\n }));\n const targetRows = targetRequests.flatMap(({ result }) => result.rows);\n const preliminary = analyzeInternalLinksFromRows({\n targetRows,\n sourceRows: [],\n site: input.site,\n targetAliases: target.aliases,\n minImpressions,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n const queryCandidates = target.verification === 'verified' &&\n preliminary.selection.targetEligibleQueries > 0;\n const sourceResult = queryCandidates\n ? await dependencies.searchAnalytics(input.site, {\n ...range,\n dimensions: ['query', 'page'],\n type: 'web',\n dataState: 'final',\n maxRows: MAX_GSC_ROWS,\n }, { refresh: input.refresh })\n : { rows: [], calls: 0, rowsFetched: 0 };\n ledger.addGsc(sourceResult.calls, sourceResult.rowsFetched);\n const analysis = analyzeInternalLinksFromRows({\n targetRows,\n sourceRows: sourceResult.rows,\n site: input.site,\n targetAliases: target.aliases,\n minImpressions,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n const items = [];\n const warnings = [...target.warnings];\n let attemptedSources = 0;\n let checkedSources = 0;\n let existingLinkExclusions = 0;\n let technicalExclusions = 0;\n let selfAliasExclusions = 0;\n let failedChecks = 0;\n for (const candidate of analysis.candidates) {\n if (attemptedSources >= checkLimit || items.length >= limit)\n break;\n attemptedSources += 1;\n const verified = await verifyInternalLinkCandidate({\n site: input.site,\n candidate,\n target,\n js: input.js,\n refresh: input.refresh,\n rate: input.rate,\n dependencies,\n });\n warnings.push(...verified.warnings);\n if (verified.item)\n items.push(verified.item);\n if (verified.exclusion === 'existing-link')\n existingLinkExclusions += 1;\n if (verified.exclusion === 'technical')\n technicalExclusions += 1;\n if (verified.exclusion === 'self-alias')\n selfAliasExclusions += 1;\n if (verified.exclusion === 'failed')\n failedChecks += 1;\n else\n checkedSources += 1;\n }\n const uncheckedCandidates = Math.max(0, analysis.candidates.length - attemptedSources);\n const targetTruncated = targetRequests.some(({ result }) => result.rowsFetched >= MAX_GSC_ROWS);\n const sourceTruncated = sourceResult.rowsFetched >= MAX_GSC_ROWS;\n const invalidRows = analysis.selection.targetInvalidRows + analysis.selection.sourceInvalidRows;\n const structuredWarnings = uniqueInternalLinksWarnings(warnings);\n const dataStatus = target.verification === 'technical-issue'\n ? 'target-technical-issue'\n : target.verification === 'failed'\n ? 'partial'\n : targetRows.length === 0\n ? 'empty'\n : targetTruncated || sourceTruncated || invalidRows > 0\n ? 'partial'\n : queryCandidates && sourceResult.rows.length === 0\n ? 'source-empty'\n : analysis.selection.targetEligibleQueries === 0 ||\n analysis.candidates.length === 0\n ? 'filtered'\n : failedChecks > 0 || uncheckedCandidates > 0\n ? 'partial'\n : 'complete';\n const selection = completeInternalLinksSelection(analysis, {\n attemptedSources,\n checkedSources,\n returnedSources: items.length,\n existingLinkExclusions,\n technicalExclusions,\n selfAliasExclusions,\n failedChecks,\n uncheckedCandidates,\n });\n const summaryVerdict = internalLinksVerdict({\n dataStatus,\n returned: items.length,\n attempted: attemptedSources,\n checked: checkedSources,\n candidates: analysis.candidates.length,\n failed: failedChecks,\n unchecked: uncheckedCandidates,\n });\n return {\n site: input.site,\n targetUrl,\n generatedAt: now.toISOString(),\n range,\n rangeDays: days,\n dataStatus,\n source: {\n provider: 'google-search-console',\n dimensions: ['query', 'page'],\n searchType: 'web',\n dataState: 'final',\n target: {\n pageFilters: targetRequests.map(({ alias }) => alias),\n requests: targetRequests.map(({ alias, result }) => ({\n pageFilter: alias,\n rowsFetched: result.rowsFetched,\n calls: result.calls,\n possiblyTruncated: result.rowsFetched >= MAX_GSC_ROWS,\n })),\n rowsFetched: targetRequests.reduce((sum, { result }) => sum + result.rowsFetched, 0),\n calls: targetRequests.reduce((sum, { result }) => sum + result.calls, 0),\n maxRowsPerRequest: MAX_GSC_ROWS,\n possiblyTruncated: targetTruncated,\n },\n candidates: {\n queried: queryCandidates,\n rowsFetched: sourceResult.rowsFetched,\n calls: sourceResult.calls,\n maxRows: MAX_GSC_ROWS,\n possiblyTruncated: sourceTruncated,\n },\n completeness: !queryCandidates\n ? 'not-queried'\n : targetTruncated || sourceTruncated\n ? 'possibly-truncated'\n : 'retained-rows-only',\n },\n methodology: {\n id: 'gsc_internal_link_candidates',\n version: 3,\n lexicalTargetLimit: INTERNAL_LINK_LEXICAL_TARGET_LIMIT,\n matchedQueryEvidenceLimit: INTERNAL_LINK_MATCH_EVIDENCE_LIMIT,\n observedLinkEvidenceLimit: INTERNAL_LINK_OBSERVED_EVIDENCE_LIMIT,\n matching: 'pairwise_exact_then_precision_lexical',\n ranking: 'exact_matches_then_matched_query_impressions_then_relevance',\n contextualPlacementVerified: true,\n },\n filters: {\n minImpressions,\n resultLimit: limit,\n checkLimit,\n maxGscRowsPerRequest: MAX_GSC_ROWS,\n },\n target: {\n requestedUrl: target.requestedUrl,\n preferredUrl: target.preferredUrl,\n finalUrl: target.finalUrl,\n canonical: target.canonical,\n status: target.status,\n aliases: target.aliases,\n verification: target.verification,\n technicalSignals: target.technicalSignals,\n fetchDiagnostics: target.fetchDiagnostics,\n queries: analysis.targetQueries,\n },\n selection,\n summary: {\n targetQueries: analysis.selection.targetEligibleQueries,\n candidateSources: analysis.candidates.length,\n attemptedSources,\n checkedSources,\n returnedSources: items.length,\n existingLinksObserved: existingLinkExclusions,\n technicalExclusions,\n failedChecks,\n uncheckedCandidates,\n matchedQueryImpressions: items.reduce((sum, item) => sum + item.matchedQueryImpressions, 0),\n brandFiltering: input.includeBrand ? 'included' : 'excluded',\n verdict: summaryVerdict,\n },\n items,\n warnings: structuredWarnings,\n caveats: [\n `Date window: ${range.startDate} to ${range.endDate} (${days} days), using final GSC data where available.`,\n `Selection: ${analysis.selection.targetEligibleQueries} eligible target queries, ${analysis.selection.candidateUrls} matched source pages, ${attemptedSources} attempted, ${checkedSources} successfully checked, ${items.length} returned.`,\n `Minimum retained query impressions: ${minImpressions}. Brand queries were ${input.includeBrand ? 'included' : 'excluded when detected or configured'}.`,\n 'GSC query rows omit anonymized queries and lower-volume rows. A 100,000-row cap is reported separately when reached.',\n 'Exact query overlap is medium-confidence affinity evidence; lexical matches are low-confidence review evidence. Neither predicts traffic lift or link equity.',\n 'The fetch checks HTML link placement, but it cannot prove editorial relevance. Review intent and reader usefulness before adding a link.',\n uncheckedCandidates\n ? `${uncheckedCandidates} matched source page${uncheckedCandidates === 1 ? ' was' : 's were'} not checked because the output or check limit was reached.`\n : '',\n failedChecks\n ? `${failedChecks} source verification attempt${failedChecks === 1 ? '' : 's'} failed. Failed fetches or extraction attempts are not counted as checked pages and do not support a missing-link conclusion.`\n : '',\n ].filter(Boolean),\n recommendations: target.verification !== 'verified'\n ? [\n 'Resolve the target fetch, indexability, redirect, or canonical issue before adding internal links.',\n ]\n : items.length\n ? [\n 'Review exact-query candidates first, then lexical candidates. Add or update a contextual link only when it helps a reader move between complementary intents.',\n ]\n : [\n 'No ready-to-apply link action was confirmed among the checked sources. Review completeness and unchecked counts before treating this as a site-wide absence.',\n ],\n ledgerSummary: ledger.summary(),\n };\n}\n//# sourceMappingURL=internal-links.js.map","import { hasMetaRobotsDirective, hasXRobotsDirective, } from '../../robots-directives.js';\nfunction statusMovedToError(item) {\n return (item.kind !== 'removed' &&\n (item.after?.status ?? 0) >= 400 &&\n (item.before?.status ?? 200) < 400);\n}\nfunction statusRecovered(item) {\n return (item.kind === 'changed' &&\n (item.before?.status ?? 200) >= 400 &&\n (item.after?.status ?? 0) < 400);\n}\nfunction indexabilityLost(item) {\n return (item.kind === 'changed' &&\n item.before?.indexable === true &&\n item.after?.indexable === false);\n}\nfunction canonicalChangedAway(item) {\n return (item.kind === 'changed' &&\n item.changes.includes('canonical') &&\n Boolean(item.after?.canonical) &&\n item.after?.canonical !== item.after?.finalUrl);\n}\nexport function recommendCrawlDiffItem(item) {\n if (statusMovedToError(item)) {\n return {\n severity: 'high',\n category: 'status',\n title: 'Search-visible URL now returns an error',\n action: 'This URL used to be crawlable and now returns an error. Restore it if the page should still exist, or add one direct 301 to the closest live replacement before doing any content work.',\n confidence: 'high',\n };\n }\n if (item.kind === 'removed') {\n return {\n severity: 'high',\n category: 'inventory',\n title: 'Previously crawled URL disappeared',\n action: 'This URL was in the previous crawl but is missing now. Confirm whether removal was intentional; if it had search traffic or links, restore it or redirect it to the best replacement.',\n confidence: 'medium',\n };\n }\n if (indexabilityLost(item)) {\n const noindex = hasMetaRobotsDirective(item.after?.metaRobots, 'noindex') ||\n hasXRobotsDirective(item.after?.xRobotsTag, 'noindex');\n return {\n severity: 'high',\n category: 'indexability',\n title: 'URL became non-indexable',\n action: noindex\n ? 'This URL now has a noindex signal. Remove it if accidental, or mark this as intentional so it does not keep appearing as a risk.'\n : 'This URL used to be indexable and now is not. Check robots, canonical, status, and rendered HTML to find what changed.',\n confidence: noindex ? 'high' : 'medium',\n };\n }\n if (canonicalChangedAway(item)) {\n return {\n severity: 'medium',\n category: 'canonical',\n title: 'Canonical changed away from the final URL',\n action: 'Google may treat a different URL as the preferred page now. If that is not intentional, restore the self-canonical or redirect directly to the preferred URL.',\n confidence: 'high',\n };\n }\n if (item.changes.includes('title') || item.changes.includes('h1')) {\n return {\n severity: 'medium',\n category: 'metadata',\n title: 'Primary SERP/on-page targeting changed',\n action: 'The title or H1 changed. Compare the old and new wording against the top GSC queries for this URL before blaming traffic movement on content decay.',\n confidence: 'medium',\n };\n }\n if (item.changes.includes('meta_description')) {\n return {\n severity: 'low',\n category: 'metadata',\n title: 'Meta description changed',\n action: 'The meta description changed. Check CTR for this URL before spending time on more copy edits.',\n confidence: 'medium',\n };\n }\n if (item.changes.includes('content')) {\n return {\n severity: 'low',\n category: 'content',\n title: 'Main content changed',\n action: 'Main content changed. If traffic moved after this crawl, compare the changed section against the queries this URL ranks for.',\n confidence: 'medium',\n };\n }\n if (statusRecovered(item)) {\n return {\n severity: 'low',\n category: 'status',\n title: 'URL recovered from an error status',\n action: 'The URL is no longer returning an error. Keep monitoring it and run URL Inspection if it was previously deindexed.',\n confidence: 'medium',\n };\n }\n return undefined;\n}\nexport function attachCrawlRecommendations(items) {\n return items.map((item) => ({\n ...item,\n recommendation: recommendCrawlDiffItem(item),\n }));\n}\nexport function topCrawlRecommendations(items) {\n const priority = { high: 3, medium: 2, low: 1 };\n return items\n .filter((item) => item.recommendation)\n .map((item) => ({\n ...item.recommendation,\n url: item.url,\n }))\n .sort((a, b) => priority[b.severity] - priority[a.severity]);\n}\n//# sourceMappingURL=crawl-recommendations.js.map","import { getDb } from '../../storage/database.js';\nfunction toRun(row) {\n return {\n id: row.id,\n site: row.site_url,\n startUrl: row.start_url,\n createdAt: new Date(row.created_at).toISOString(),\n limit: row.limit_count,\n urlCount: row.url_count,\n };\n}\nfunction parseSnapshot(value) {\n if (!value)\n return {};\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === 'object' ? parsed : {};\n }\n catch {\n return {};\n }\n}\nfunction toPage(row) {\n const legacy = {\n url: row.url,\n finalUrl: row.final_url,\n status: row.status,\n title: row.title ?? undefined,\n metaDescription: row.meta_description ?? undefined,\n canonical: row.canonical ?? undefined,\n metaRobots: row.meta_robots ?? undefined,\n xRobotsTag: row.x_robots_tag ?? undefined,\n h1: row.h1 ?? undefined,\n indexable: row.indexable === 1,\n wordCount: row.word_count,\n contentHash: row.content_hash,\n outgoingInternalCount: row.outgoing_internal_count,\n };\n return {\n ...legacy,\n ...parseSnapshot(row.snapshot_json),\n url: row.url,\n finalUrl: row.final_url,\n status: row.status,\n indexable: row.indexable === 1,\n contentHash: row.content_hash,\n outgoingInternalCount: row.outgoing_internal_count,\n };\n}\nexport function getPreviousRun(input) {\n const row = getDb()\n .prepare(`SELECT * FROM crawl_runs\n WHERE site_url = ? AND start_url = ? AND id != ?\n ORDER BY created_at DESC LIMIT 1`)\n .get(input.site, input.startUrl, input.currentRunId);\n return row ? toRun(row) : undefined;\n}\nexport function getRunPages(runId) {\n const rows = getDb()\n .prepare('SELECT * FROM crawl_pages WHERE run_id = ?')\n .all(runId);\n return new Map(rows.map((row) => [row.url, toPage(row)]));\n}\nexport function insertCrawlRun(run, pages, recommendations = []) {\n const db = getDb();\n db.prepare(`INSERT INTO crawl_runs\n (id, site_url, start_url, created_at, limit_count, url_count)\n VALUES (?, ?, ?, ?, ?, ?)`).run(run.id, run.site, run.startUrl, Date.parse(run.createdAt), run.limit, pages.length);\n const insertPage = db.prepare(`INSERT INTO crawl_pages\n (run_id, url, final_url, status, title, meta_description, canonical,\n meta_robots, x_robots_tag, h1, indexable, word_count, content_hash,\n outgoing_internal_count, snapshot_json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);\n const insertRecommendation = db.prepare(`INSERT INTO crawl_recommendations\n (run_id, site_url, url, severity, category, title, action, confidence, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);\n const createdAt = Date.parse(run.createdAt);\n const transaction = db.transaction(() => {\n for (const page of pages) {\n insertPage.run(run.id, page.url, page.finalUrl, page.status, page.title ?? null, page.metaDescription ?? null, page.canonical ?? null, page.metaRobots ?? null, page.xRobotsTag ?? null, page.h1 ?? null, page.indexable ? 1 : 0, page.wordCount, page.contentHash, page.outgoingInternalCount, JSON.stringify(page));\n }\n for (const recommendation of recommendations) {\n insertRecommendation.run(run.id, run.site, recommendation.url, recommendation.severity, recommendation.category, recommendation.title, recommendation.action, recommendation.confidence, createdAt);\n }\n });\n transaction();\n}\nexport function latestCrawlSummaries(site, limit = 5) {\n const rows = getDb()\n .prepare(`WITH page_counts AS (\n SELECT\n run_id,\n COALESCE(SUM(CASE WHEN status >= 400 THEN 1 ELSE 0 END), 0) AS status_errors,\n COALESCE(SUM(CASE WHEN indexable = 0 THEN 1 ELSE 0 END), 0) AS non_indexable\n FROM crawl_pages\n GROUP BY run_id\n ),\n recommendation_counts AS (\n SELECT\n run_id,\n COUNT(*) AS recommendation_count,\n COALESCE(SUM(CASE WHEN severity = 'high' THEN 1 ELSE 0 END), 0) AS high_recommendation_count\n FROM crawl_recommendations\n GROUP BY run_id\n ),\n recommendation_rank AS (\n SELECT\n crawl_recommendations.*,\n ROW_NUMBER() OVER (\n PARTITION BY run_id\n ORDER BY\n CASE severity WHEN 'high' THEN 3 WHEN 'medium' THEN 2 ELSE 1 END DESC,\n created_at DESC\n ) AS rank\n FROM crawl_recommendations\n )\n SELECT\n crawl_runs.*,\n COALESCE(page_counts.status_errors, 0) AS status_errors,\n COALESCE(page_counts.non_indexable, 0) AS non_indexable,\n COALESCE(recommendation_counts.recommendation_count, 0) AS recommendation_count,\n COALESCE(recommendation_counts.high_recommendation_count, 0) AS high_recommendation_count,\n top.url AS top_recommendation_url,\n top.title AS top_recommendation_title,\n top.action AS top_recommendation_action,\n top.severity AS top_recommendation_severity\n FROM crawl_runs\n LEFT JOIN page_counts ON page_counts.run_id = crawl_runs.id\n LEFT JOIN recommendation_counts ON recommendation_counts.run_id = crawl_runs.id\n LEFT JOIN recommendation_rank top ON top.run_id = crawl_runs.id AND top.rank = 1\n WHERE crawl_runs.site_url = ?\n GROUP BY crawl_runs.id\n ORDER BY crawl_runs.created_at DESC\n LIMIT ?`)\n .all(site, limit);\n return rows.map((row) => ({\n ...toRun(row),\n statusErrors: row.status_errors,\n nonIndexable: row.non_indexable,\n recommendations: row.recommendation_count,\n highPriorityRecommendations: row.high_recommendation_count,\n topRecommendation: row.top_recommendation_url\n ? {\n url: row.top_recommendation_url,\n title: row.top_recommendation_title ?? '',\n action: row.top_recommendation_action ?? '',\n severity: row.top_recommendation_severity ?? 'medium',\n }\n : undefined,\n }));\n}\n//# sourceMappingURL=crawl-store.js.map","import { randomUUID } from 'node:crypto';\nimport { crawlOne } from './crawl-page.js';\nimport { attachCrawlRecommendations, topCrawlRecommendations, } from './crawl-recommendations.js';\nimport { getPreviousRun, getRunPages, insertCrawlRun } from './crawl-store.js';\nexport function compareCrawlPages(input) {\n const current = new Map(input.current.map((page) => [page.url, page]));\n const previous = new Map(input.previous.map((page) => [page.url, page]));\n const items = [];\n for (const [url, page] of current.entries()) {\n const before = previous.get(url);\n if (!before) {\n items.push({ url, kind: 'added', changes: ['url_added'], after: page });\n continue;\n }\n const changes = [];\n if (before.status !== page.status)\n changes.push('status');\n if (before.title !== page.title)\n changes.push('title');\n if (before.metaDescription !== page.metaDescription) {\n changes.push('meta_description');\n }\n if (before.canonical !== page.canonical)\n changes.push('canonical');\n if (before.h1 !== page.h1)\n changes.push('h1');\n if (before.indexable !== page.indexable)\n changes.push('indexability');\n if (before.contentHash !== page.contentHash)\n changes.push('content');\n if (changes.length) {\n items.push({ url, kind: 'changed', changes, before, after: page });\n }\n }\n for (const [url, page] of previous.entries()) {\n if (!current.has(url)) {\n items.push({\n url,\n kind: 'removed',\n changes: ['url_removed'],\n before: page,\n });\n }\n }\n return items;\n}\nexport async function crawlDiff(input) {\n const startUrl = new URL(input.startUrl).toString();\n const site = input.site ?? new URL(startUrl).origin;\n const limit = input.limit ?? 50;\n const queue = [startUrl];\n const seen = new Set();\n const pages = [];\n const warnings = [];\n while (queue.length && pages.length < limit) {\n const url = queue.shift();\n if (!url || seen.has(url))\n continue;\n seen.add(url);\n const result = await crawlOne(url, {\n refresh: input.refresh,\n js: input.js ?? 'auto',\n });\n if (result.warning)\n warnings.push(result.warning);\n if (result.page)\n pages.push(result.page);\n for (const next of result.urls) {\n if (!seen.has(next) && queue.length + pages.length < limit * 3) {\n queue.push(next);\n }\n }\n }\n const run = {\n id: randomUUID(),\n site,\n startUrl,\n createdAt: new Date().toISOString(),\n limit,\n urlCount: pages.length,\n };\n const previousRun = getPreviousRun({ site, startUrl, currentRunId: run.id });\n const previousPages = previousRun\n ? [...getRunPages(previousRun.id).values()]\n : [];\n const items = previousRun\n ? attachCrawlRecommendations(compareCrawlPages({ current: pages, previous: previousPages }))\n : [];\n const recommendations = topCrawlRecommendations(items);\n insertCrawlRun(run, pages, recommendations);\n return {\n run,\n previousRun,\n summary: {\n crawled: pages.length,\n added: items.filter((item) => item.kind === 'added').length,\n removed: items.filter((item) => item.kind === 'removed').length,\n changed: items.filter((item) => item.kind === 'changed').length,\n newErrors: items.filter((item) => item.kind !== 'removed' &&\n (item.after?.status ?? 0) >= 400 &&\n (item.before?.status ?? 200) < 400).length,\n indexabilityFlips: items.filter((item) => item.changes.includes('indexability')).length,\n highPriorityRecommendations: recommendations.filter((item) => item.severity === 'high').length,\n },\n recommendations,\n items,\n warnings,\n };\n}\n//# sourceMappingURL=crawl-diff.js.map","const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst DATE_RE = /^\\d{4}-\\d{2}-\\d{2}$/;\nfunction compareText(left, right) {\n const leftPoints = [...left].map((value) => value.codePointAt(0) ?? 0);\n const rightPoints = [...right].map((value) => value.codePointAt(0) ?? 0);\n for (let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index++) {\n const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);\n if (difference)\n return difference;\n }\n return leftPoints.length - rightPoints.length;\n}\nexport function parsePseoPath(url) {\n const decode = (part) => {\n try {\n return decodeURIComponent(part);\n }\n catch {\n return part;\n }\n };\n try {\n return new URL(url).pathname.split('/').filter(Boolean).map(decode);\n }\n catch {\n return url.split('?')[0]?.split('/').filter(Boolean).map(decode) ?? [];\n }\n}\nfunction placeholder(segment) {\n if (/^\\d+$/.test(segment))\n return ':num';\n if (UUID_RE.test(segment))\n return ':id';\n if (DATE_RE.test(segment))\n return ':date';\n if (/^[\\p{L}\\p{N}]+(?:-[\\p{L}\\p{N}]+)+$/u.test(segment))\n return ':slug';\n if (segment.length >= 12 && /^[\\p{L}\\p{N}]+$/u.test(segment))\n return ':slug';\n return undefined;\n}\nexport function inferPseoTemplate(url) {\n const parts = parsePseoPath(url);\n if (!parts.length)\n return '/';\n const normalized = parts.map((part, index) => {\n const token = placeholder(part);\n if (token) {\n if (index === 0 && token === ':slug')\n return part.toLowerCase();\n return token;\n }\n return part.toLowerCase();\n });\n return `/${normalized.join('/')}`;\n}\nfunction broadTemplate(url) {\n const parts = parsePseoPath(url);\n if (!parts.length)\n return '/';\n const [first, ...rest] = parts;\n if (!first)\n return '/';\n if (!rest.length)\n return `/${placeholder(first) ?? first.toLowerCase()}`;\n return `/${first.toLowerCase()}/${rest\n .map((part) => placeholder(part) ?? ':value')\n .join('/')}`;\n}\nfunction valueTokens(values) {\n const counts = new Map();\n for (const value of values) {\n const tokens = value\n .normalize('NFKC')\n .toLowerCase()\n .match(/[\\p{L}\\p{N}]+/gu) ?? [];\n for (const token of tokens.filter((item) => item.length > 1 || /[^\\p{ASCII}]/u.test(item))) {\n counts.set(token, (counts.get(token) ?? 0) + 1);\n }\n }\n return [...counts.entries()]\n .sort((a, b) => b[1] - a[1] || compareText(a[0], b[0]))\n .slice(0, 8)\n .map(([token]) => token);\n}\nfunction templateShape(signature, urls) {\n const signatureParts = signature.split('/').filter(Boolean);\n const pathRows = urls.map(parsePseoPath);\n const depth = Math.max(signatureParts.length, ...pathRows.map((row) => row.length));\n const staticSegments = [];\n const variableSegments = [];\n for (let index = 0; index < depth; index += 1) {\n const signaturePart = signatureParts[index] ?? ':missing';\n const values = pathRows\n .map((row) => row[index]?.toLowerCase())\n .filter((value) => Boolean(value));\n const distinctValues = [...new Set(values)];\n const isVariable = signaturePart.startsWith(':') || distinctValues.length > 1;\n if (isVariable) {\n variableSegments.push({\n index,\n placeholder: signaturePart.startsWith(':') ? signaturePart : ':value',\n distinctValues: distinctValues.length,\n examples: distinctValues.slice(0, 5),\n tokenExamples: valueTokens(distinctValues),\n });\n }\n else if (signaturePart) {\n staticSegments.push({\n index,\n value: signaturePart,\n });\n }\n }\n return {\n depth,\n staticSegments,\n variableSegments,\n };\n}\nexport function templateForUrl(url, clusters) {\n const primary = inferPseoTemplate(url);\n if (clusters.some((cluster) => cluster.signature === primary))\n return primary;\n const broad = broadTemplate(url);\n if (clusters.some((cluster) => cluster.signature === broad))\n return broad;\n return primary;\n}\nfunction collectClusters(urls, signatures) {\n const bySignature = new Map();\n for (const url of urls) {\n const signature = signatures.get(url);\n if (!signature)\n continue;\n const existing = bySignature.get(signature) ?? [];\n existing.push(url);\n bySignature.set(signature, existing);\n }\n return bySignature;\n}\nexport function clusterPseoTemplates(urls, opts = {}) {\n const uniqueUrls = [...new Set(urls)].sort(compareText);\n const minUrls = opts.minUrls ?? 3;\n const minShare = opts.minShare ?? 0.01;\n const sampleSize = opts.sampleSize ?? 5;\n const primarySignatures = new Map(uniqueUrls.map((url) => [url, inferPseoTemplate(url)]));\n const primary = collectClusters(uniqueUrls, primarySignatures);\n const primaryQualifiers = new Set([...primary.entries()]\n .filter(([, clusterUrls]) => clusterUrls.length >= minUrls &&\n clusterUrls.length / uniqueUrls.length >= minShare)\n .map(([signature]) => signature));\n const finalSignatures = new Map();\n for (const url of uniqueUrls) {\n const primarySignature = primarySignatures.get(url) ?? '/';\n finalSignatures.set(url, primaryQualifiers.has(primarySignature)\n ? primarySignature\n : broadTemplate(url));\n }\n return [...collectClusters(uniqueUrls, finalSignatures).entries()]\n .map(([signature, clusterUrls]) => ({\n id: signature,\n signature,\n shape: templateShape(signature, clusterUrls),\n urlCount: clusterUrls.length,\n share: uniqueUrls.length ? clusterUrls.length / uniqueUrls.length : 0,\n sampleUrls: clusterUrls.sort(compareText).slice(0, sampleSize),\n }))\n .filter((cluster) => cluster.urlCount >= minUrls && cluster.share >= minShare)\n .sort((a, b) => b.urlCount - a.urlCount || compareText(a.signature, b.signature))\n .slice(0, opts.limit ?? 50);\n}\n//# sourceMappingURL=templates.js.map","import { clusterPseoTemplates, } from '../pseo/templates.js';\nconst DEFAULT_ITEMS_PER_SECTION = 100;\nconst MAX_ITEMS_PER_SECTION = 1_000;\nconst DEFAULT_TEMPLATE_LIMIT = 50;\nconst MAX_TEMPLATE_LIMIT = 200;\nconst DEFAULT_TEMPLATE_SAMPLES = 5;\nconst MAX_TEMPLATE_SAMPLES = 25;\nconst DEFAULT_TEMPLATE_MIN_URLS = 3;\nconst DEFAULT_TEMPLATE_MIN_SHARE = 0.01;\nfunction compareText(left, right) {\n const leftPoints = [...left].map((value) => value.codePointAt(0) ?? 0);\n const rightPoints = [...right].map((value) => value.codePointAt(0) ?? 0);\n for (let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index += 1) {\n const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);\n if (difference)\n return difference;\n }\n return leftPoints.length - rightPoints.length;\n}\nfunction boundedInteger(value, fallback, maximum) {\n if (value === undefined || !Number.isFinite(value))\n return fallback;\n return Math.min(maximum, Math.max(1, Math.trunc(value)));\n}\nfunction normalizedUrl(value) {\n try {\n const url = new URL(value.trim());\n if (!['http:', 'https:'].includes(url.protocol))\n return undefined;\n if (url.username || url.password)\n return undefined;\n url.hash = '';\n return url.toString();\n }\n catch {\n return undefined;\n }\n}\nfunction isString(value) {\n return value !== undefined;\n}\nfunction sourceEvidence(input) {\n return {\n ...input,\n duplicateUrls: input.validUrls - input.uniqueUrls,\n invalidUrls: input.rowsReceived - input.validUrls,\n };\n}\nfunction crawlInput(input) {\n const report = 'report' in input ? input.report : undefined;\n const pages = report?.pages ?? ('pages' in input ? input.pages : []);\n const urls = pages.map((page) => normalizedUrl(page.url)).filter(isString);\n const uniqueUrls = new Set(urls);\n const rowLimit = report?.config.maxPages ??\n ('rowLimit' in input ? input.rowLimit : undefined);\n const rowLimitReached = report?.summary.pageLimitReached ??\n ('rowLimitReached' in input ? input.rowLimitReached : undefined);\n const completeness = report\n ? report.summary.pageLimitReached\n ? 'truncated'\n : report.status === 'completed'\n ? 'complete'\n : report.status === 'partial'\n ? 'partial'\n : 'unknown'\n : 'completeness' in input\n ? input.completeness\n : 'unknown';\n return {\n pages,\n evidence: sourceEvidence({\n completeness,\n rowsReceived: pages.length,\n validUrls: urls.length,\n uniqueUrls: uniqueUrls.size,\n rowLimit,\n rowLimitReached,\n }),\n };\n}\nfunction normalizedInventory(input) {\n if (!input) {\n return {\n urls: new Set(),\n evidence: sourceEvidence({\n completeness: 'unavailable',\n rowsReceived: 0,\n validUrls: 0,\n uniqueUrls: 0,\n }),\n };\n }\n const normalized = input.urls.map(normalizedUrl).filter(isString);\n const urls = new Set(normalized);\n return {\n urls,\n evidence: sourceEvidence({\n completeness: input.completeness,\n rowsReceived: input.urls.length,\n validUrls: normalized.length,\n uniqueUrls: urls.size,\n rowLimit: input.rowLimit,\n rowLimitReached: input.rowLimitReached,\n }),\n };\n}\nfunction validMetric(value) {\n return Number.isFinite(value) && value >= 0;\n}\nfunction searchConsoleInput(input) {\n if (!input) {\n return {\n metrics: new Map(),\n evidence: {\n ...sourceEvidence({\n completeness: 'unavailable',\n rowsReceived: 0,\n validUrls: 0,\n uniqueUrls: 0,\n }),\n semantics: 'retained-search-analytics-page-rows',\n invalidMetricRows: 0,\n zeroImpressionRows: 0,\n },\n };\n }\n const pageKeyIndex = input.pageKeyIndex ?? 0;\n const metrics = new Map();\n const retainedRows = [];\n let invalidUrls = 0;\n let invalidMetricRows = 0;\n let zeroImpressionRows = 0;\n for (const row of input.rows) {\n const url = normalizedUrl(row.keys[pageKeyIndex] ?? '');\n if (!url) {\n invalidUrls += 1;\n continue;\n }\n if (!validMetric(row.clicks) ||\n !validMetric(row.impressions) ||\n !validMetric(row.position) ||\n row.clicks > row.impressions) {\n invalidMetricRows += 1;\n continue;\n }\n if (row.impressions === 0) {\n zeroImpressionRows += 1;\n continue;\n }\n retainedRows.push({ url, row });\n }\n retainedRows.sort((left, right) => compareText(left.url, right.url) ||\n left.row.clicks - right.row.clicks ||\n left.row.impressions - right.row.impressions ||\n left.row.position - right.row.position ||\n compareText(JSON.stringify(left.row.keys), JSON.stringify(right.row.keys)));\n for (const { url, row } of retainedRows) {\n const existing = metrics.get(url) ?? {\n clicks: 0,\n impressions: 0,\n weightedPosition: 0,\n sourceRows: 0,\n };\n existing.clicks += row.clicks;\n existing.impressions += row.impressions;\n existing.weightedPosition += row.position * row.impressions;\n existing.sourceRows += 1;\n metrics.set(url, existing);\n }\n const retainedMetricRows = input.rows.length - invalidUrls - invalidMetricRows - zeroImpressionRows;\n return {\n metrics,\n evidence: {\n semantics: 'retained-search-analytics-page-rows',\n completeness: input.completeness,\n rowsReceived: input.rows.length,\n validUrls: retainedMetricRows,\n uniqueUrls: metrics.size,\n duplicateUrls: retainedMetricRows - metrics.size,\n invalidUrls,\n rowLimit: input.rowLimit,\n rowLimitReached: input.completeness === 'truncated',\n startDate: input.startDate,\n endDate: input.endDate,\n pageKeyIndex,\n invalidMetricRows,\n zeroImpressionRows,\n },\n };\n}\nfunction controlReasons(page) {\n const reasons = new Set();\n if (page.error || page.blocked)\n reasons.add('crawl-fetch-error');\n if (page.status < 200 || page.status >= 300)\n reasons.add('http-status');\n if (page.robotsTxt?.allowed === false ||\n page.declaredIndexability === 'robots-blocked') {\n reasons.add('robots-blocked');\n }\n if (page.declaredIndexability === 'noindex')\n reasons.add('noindex');\n if (page.declaredIndexability === 'canonical-conflict')\n reasons.add('canonical-conflict');\n if (page.declaredIndexability === 'canonical-hint-other')\n reasons.add('canonical-hint-other');\n if (page.declaredIndexability === 'not-html')\n reasons.add('not-html');\n if (!page.indexable && reasons.size === 0)\n reasons.add('crawler-marked-non-indexable');\n if (reasons.size === 0)\n reasons.add('unknown');\n return [...reasons].sort(compareText);\n}\nfunction boundedSection(items, limit) {\n const retained = items.slice(0, limit);\n return {\n count: items.length,\n returned: retained.length,\n omitted: items.length - retained.length,\n items: retained,\n };\n}\nfunction sourceMembership(input) {\n return {\n crawl: input.crawlUrls.has(input.url),\n sitemap: input.sitemapUrls.has(input.url),\n searchConsole: input.searchUrls.has(input.url),\n };\n}\nfunction caveats(input) {\n const items = [\n 'Retained Search Console page rows show search visibility during the selected date range. They are not a complete index inventory and do not prove current indexing.',\n 'A crawlable URL absent from the retained Search Console export is not proven unindexed. It may have had no retained impressions, may be outside the export limit, or may need URL Inspection.',\n \"Use URL Inspection when you need Google's current indexed verdict for a specific URL. This report does not infer that verdict from crawl, sitemap, or Search Analytics data.\",\n 'Repeated URL templates are grouped for review only. A cluster does not diagnose content quality, duplication, or index coverage.',\n ];\n if (input.searchConsole.completeness === 'unavailable') {\n items.push('Search Console data was unavailable, so absence-from-search comparisons are not available.');\n }\n else if (input.searchConsole.completeness !== 'complete') {\n items.push('The Search Console source is not complete. Missing URLs are especially unsafe to interpret as absent from search.');\n }\n if (input.crawl.completeness !== 'complete') {\n items.push('The crawl source is not complete. Crawl counts and cross-source comparisons cover only retained pages.');\n }\n if (input.sitemap.completeness === 'unavailable') {\n items.push('No sitemap inventory was supplied. Sitemap-only and sitemap membership findings are unavailable.');\n }\n else if (input.sitemap.completeness !== 'complete') {\n items.push('The sitemap source is not complete. Sitemap-only counts cover only retained URLs.');\n }\n if (input.sitemap.completeness !== 'unavailable') {\n items.push('Sitemap inclusion is a discovery hint. It does not prove that Google crawled or indexed a URL.');\n }\n if (input.searchConsole.zeroImpressionRows > 0) {\n items.push('Rows with zero impressions were excluded from retained search visibility instead of treating them as a separate indexing state.');\n }\n if (input.controlledWithVisibility > 0) {\n items.push('Some currently blocked or non-indexable crawl URLs also had retained search visibility. The crawl observation and historical date-range visibility describe different evidence and can coexist.');\n }\n return items;\n}\nexport function analyzeIndexCoverageSignals(input) {\n const itemLimit = boundedInteger(input.limits?.itemsPerSection, DEFAULT_ITEMS_PER_SECTION, MAX_ITEMS_PER_SECTION);\n const clusterLimit = boundedInteger(input.limits?.templateClusters, DEFAULT_TEMPLATE_LIMIT, MAX_TEMPLATE_LIMIT);\n const clusterSamples = boundedInteger(input.limits?.templateSamples, DEFAULT_TEMPLATE_SAMPLES, MAX_TEMPLATE_SAMPLES);\n const minUrls = boundedInteger(input.templateThresholds?.minUrls, DEFAULT_TEMPLATE_MIN_URLS, Number.MAX_SAFE_INTEGER);\n const requestedMinShare = input.templateThresholds?.minShare;\n const minShare = Number.isFinite(requestedMinShare)\n ? Math.min(1, Math.max(0, requestedMinShare ?? DEFAULT_TEMPLATE_MIN_SHARE))\n : DEFAULT_TEMPLATE_MIN_SHARE;\n const crawl = crawlInput(input.crawl);\n const sitemap = normalizedInventory(input.sitemap);\n const search = searchConsoleInput(input.searchConsole);\n const searchUrls = new Set(search.metrics.keys());\n const hasSearchConsole = search.evidence.completeness !== 'unavailable';\n const pageByUrl = new Map();\n for (const page of crawl.pages) {\n const url = normalizedUrl(page.url);\n if (!url)\n continue;\n const existing = pageByUrl.get(url);\n if (!existing ||\n compareText(JSON.stringify(page), JSON.stringify(existing)) < 0) {\n pageByUrl.set(url, page);\n }\n }\n const crawlUrls = new Set(pageByUrl.keys());\n const retainedSearchVisibility = [...search.metrics.entries()]\n .map(([url, metrics]) => ({\n url,\n clicks: metrics.clicks,\n impressions: metrics.impressions,\n ctr: metrics.impressions ? metrics.clicks / metrics.impressions : 0,\n position: metrics.impressions\n ? metrics.weightedPosition / metrics.impressions\n : 0,\n sourceRows: metrics.sourceRows,\n sources: sourceMembership({\n url,\n crawlUrls,\n sitemapUrls: sitemap.urls,\n searchUrls,\n }),\n crawlIndexable: pageByUrl.get(url)?.indexable,\n }))\n .sort((left, right) => right.clicks - left.clicks ||\n right.impressions - left.impressions ||\n compareText(left.url, right.url));\n const crawlable = [...pageByUrl.entries()]\n .filter(([url, page]) => hasSearchConsole && page.indexable && !searchUrls.has(url))\n .map(([url, page]) => ({\n url,\n status: page.status,\n declaredIndexability: page.declaredIndexability,\n inSitemap: sitemap.urls.has(url),\n }))\n .sort((left, right) => compareText(left.url, right.url));\n const controlled = [...pageByUrl.entries()]\n .filter(([, page]) => !page.indexable)\n .map(([url, page]) => ({\n url,\n status: page.status,\n declaredIndexability: page.declaredIndexability,\n reasons: controlReasons(page),\n inSitemap: sitemap.urls.has(url),\n hasRetainedSearchVisibility: searchUrls.has(url),\n }))\n .sort((left, right) => compareText(left.url, right.url));\n const sitemapOnly = [...sitemap.urls]\n .filter((url) => !crawlUrls.has(url) && !searchUrls.has(url))\n .sort(compareText)\n .map((url) => ({\n url,\n sources: sourceMembership({\n url,\n crawlUrls,\n sitemapUrls: sitemap.urls,\n searchUrls,\n }),\n }));\n const searchConsoleOnly = [...searchUrls]\n .filter((url) => !crawlUrls.has(url) && !sitemap.urls.has(url))\n .sort(compareText)\n .map((url) => ({\n url,\n sources: sourceMembership({\n url,\n crawlUrls,\n sitemapUrls: sitemap.urls,\n searchUrls,\n }),\n }));\n const allUrls = new Set([...crawlUrls, ...sitemap.urls, ...searchUrls]);\n const allClusters = clusterPseoTemplates(crawlable.map((item) => item.url), {\n minUrls,\n minShare,\n limit: Number.MAX_SAFE_INTEGER,\n sampleSize: clusterSamples,\n });\n const clusters = allClusters.slice(0, clusterLimit);\n const controlledWithVisibility = controlled.filter((item) => item.hasRetainedSearchVisibility).length;\n return {\n schemaVersion: 1,\n generatedAt: input.generatedAt,\n limits: {\n itemsPerSection: itemLimit,\n templateClusters: clusterLimit,\n templateSamples: clusterSamples,\n },\n summary: {\n uniqueUrlsAcrossSources: allUrls.size,\n retainedSearchVisibleUrls: retainedSearchVisibility.length,\n crawlableCandidatesWithoutRetainedSearchVisibility: crawlable.length,\n blockedOrNonIndexableCrawlUrls: controlled.length,\n sitemapOnlyUrls: sitemapOnly.length,\n searchConsoleOnlyUrls: searchConsoleOnly.length,\n repeatedTemplateClustersForReview: allClusters.length,\n },\n sources: {\n crawl: {\n ...crawl.evidence,\n semantics: 'local-crawl-page-snapshots',\n },\n sitemap: {\n ...sitemap.evidence,\n semantics: 'submitted-discovery-hints',\n },\n searchConsole: search.evidence,\n },\n retainedSearchVisibility: boundedSection(retainedSearchVisibility, itemLimit),\n crawlableWithoutRetainedSearchVisibility: boundedSection(crawlable, itemLimit),\n blockedOrNonIndexable: boundedSection(controlled, itemLimit),\n sitemapOnly: boundedSection(sitemapOnly, itemLimit),\n searchConsoleOnly: boundedSection(searchConsoleOnly, itemLimit),\n templateReview: {\n scope: 'crawlable-without-retained-search-visibility',\n eligibleUrlCount: crawlable.length,\n count: allClusters.length,\n returned: clusters.length,\n omitted: allClusters.length - clusters.length,\n thresholds: { minUrls, minShare },\n clusters,\n },\n caveats: caveats({\n crawl: crawl.evidence,\n sitemap: sitemap.evidence,\n searchConsole: search.evidence,\n controlledWithVisibility,\n }),\n };\n}\n//# sourceMappingURL=index-coverage.js.map","import { SeoError } from '../../errors.js';\nimport { querySearchAnalytics } from '../../gsc/client.js';\nimport { finalGscDateRange } from '../../gsc/dates.js';\nimport { latestCrawlReport, loadCrawlReport } from '../crawler/report-store.js';\nimport { integerOption } from '../site-diagnostics/quick-wins-report-input.js';\nimport { analyzeIndexCoverageSignals, } from './index-coverage.js';\nimport { boundedSitemapInventory, fetchSitemapUrls, } from './sitemaps.js';\nconst MAX_SITEMAP_DOCUMENTS = 20;\nconst MAX_SEARCH_ROWS = 250_000;\nconst MAX_SITEMAP_URLS = 250_000;\nconst defaultDependencies = {\n loadCrawl: loadCrawlReport,\n latestCrawl: latestCrawlReport,\n searchAnalytics: querySearchAnalytics,\n fetchSitemap: fetchSitemapUrls,\n now: () => new Date(),\n};\nfunction selectedCrawl(input, dependencies) {\n const report = input.crawlReportId\n ? dependencies.loadCrawl(input.crawlReportId)\n : dependencies.latestCrawl(input.site);\n if (!report) {\n throw new SeoError('INVALID_INPUT', input.crawlReportId\n ? `No saved crawl report found for ${input.crawlReportId}.`\n : `No saved crawl report found for ${input.site}. Run a site crawl first or pass crawlReportId.`);\n }\n if (report.site && report.site !== input.site) {\n throw new SeoError('INVALID_INPUT', `Crawl report ${report.id} belongs to ${report.site}, not ${input.site}.`);\n }\n return report;\n}\nfunction sitemapDocuments(input) {\n if (input.explicit?.length) {\n return { source: 'explicit', urls: [...new Set(input.explicit)] };\n }\n const robots = input.report.ai?.robotsTxt;\n if (robots?.availability === 'available' && robots.sitemapUrls.length) {\n return {\n source: 'crawl-robots',\n urls: [...new Set(robots.sitemapUrls)],\n };\n }\n return { source: 'unavailable', urls: [] };\n}\nfunction sitemapCompleteness(input) {\n if (input.inventoryTruncated)\n return 'truncated';\n return input.results.every((result) => result.dataStatus === 'complete')\n ? 'complete'\n : 'partial';\n}\nexport async function indexCoverageSignals(input, dependencies = defaultDependencies) {\n const days = integerOption({\n value: input.days,\n fallback: 90,\n minimum: 1,\n maximum: 548,\n label: 'days',\n });\n const rowLimit = integerOption({\n value: input.rowLimit,\n fallback: 100_000,\n minimum: 1,\n maximum: MAX_SEARCH_ROWS,\n label: 'rowLimit',\n });\n const maxSitemapUrls = integerOption({\n value: input.maxSitemapUrls,\n fallback: 100_000,\n minimum: 1,\n maximum: MAX_SITEMAP_URLS,\n label: 'maxSitemapUrls',\n });\n const report = selectedCrawl(input, dependencies);\n const documents = sitemapDocuments({\n explicit: input.sitemaps,\n report,\n });\n if (documents.urls.length > MAX_SITEMAP_DOCUMENTS) {\n throw new SeoError('INVALID_INPUT', `Pass at most ${MAX_SITEMAP_DOCUMENTS} sitemap URLs.`);\n }\n const now = dependencies.now();\n const range = finalGscDateRange(days, now);\n const [search, fetchedSitemaps] = await Promise.all([\n dependencies.searchAnalytics(input.site, {\n ...range,\n dimensions: ['page'],\n type: 'web',\n dataState: 'final',\n maxRows: rowLimit,\n }, { refresh: input.refresh }),\n Promise.all(documents.urls.map((sitemapUrl) => dependencies.fetchSitemap({\n sitemapUrl,\n limit: maxSitemapUrls,\n }))),\n ]);\n const sitemapInventory = fetchedSitemaps.length\n ? boundedSitemapInventory(fetchedSitemaps, maxSitemapUrls)\n : undefined;\n const searchTruncated = search.rows.length >= rowLimit;\n const analysis = analyzeIndexCoverageSignals({\n generatedAt: now.toISOString(),\n crawl: { report },\n ...(sitemapInventory\n ? {\n sitemap: {\n urls: sitemapInventory.urls,\n completeness: sitemapCompleteness({\n results: fetchedSitemaps,\n inventoryTruncated: sitemapInventory.truncation.possiblyTruncated,\n }),\n rowLimit: maxSitemapUrls,\n rowLimitReached: sitemapInventory.truncation.inventoryLimitExceeded,\n },\n }\n : {}),\n searchConsole: {\n rows: search.rows,\n ...range,\n rowLimit,\n completeness: searchTruncated ? 'truncated' : 'complete',\n pageKeyIndex: 0,\n },\n limits: {\n itemsPerSection: input.itemsPerSection,\n templateClusters: input.templateClusters,\n templateSamples: input.templateSamples,\n },\n });\n return {\n ...analysis,\n site: input.site,\n input: {\n crawlReport: {\n id: report.id,\n generatedAt: report.generatedAt,\n status: report.status,\n mode: report.config.mode,\n startUrl: report.config.url,\n },\n sitemapDocuments: {\n ...documents,\n warnings: fetchedSitemaps.flatMap((result) => result.warnings),\n },\n searchConsole: {\n days,\n rowLimit,\n calls: search.calls,\n rowsFetched: search.rowsFetched,\n },\n },\n };\n}\n//# sourceMappingURL=index-coverage-report.js.map","import { SeoError } from '../../errors.js';\nimport { listSites } from '../../gsc/client.js';\nimport { assertUrlMatchesGscProperty, normalizeHttpUrl, } from '../../gsc/property-url.js';\nimport { integerOption } from '../site-diagnostics/quick-wins-report-input.js';\nimport { boundedSitemapInventory, fetchSitemapUrls } from './sitemaps.js';\nfunction parseUrl(value) {\n try {\n return new URL(value);\n }\n catch {\n return undefined;\n }\n}\nfunction originFromSite(site) {\n if (site.startsWith('sc-domain:'))\n return undefined;\n const parsed = parseUrl(site);\n return parsed ? parsed.origin : undefined;\n}\nexport function propertyMatchesUrl(property, url) {\n try {\n assertUrlMatchesGscProperty(property, url);\n return true;\n }\n catch {\n return false;\n }\n}\nfunction mostSpecificProperty(url, properties) {\n const matching = properties\n .filter((property) => propertyMatchesUrl(property, url))\n .sort((a, b) => {\n if (a.startsWith('sc-domain:') && !b.startsWith('sc-domain:'))\n return 1;\n if (!a.startsWith('sc-domain:') && b.startsWith('sc-domain:'))\n return -1;\n return b.length - a.length || a.localeCompare(b);\n });\n return matching[0];\n}\nfunction propertyBelongsToSite(property, site) {\n if (site.startsWith('sc-domain:')) {\n const domain = site.slice('sc-domain:'.length).toLowerCase();\n if (property.startsWith('sc-domain:')) {\n const propertyDomain = property.slice('sc-domain:'.length).toLowerCase();\n return propertyDomain === domain || propertyDomain.endsWith(`.${domain}`);\n }\n const host = parseUrl(property)?.hostname.toLowerCase();\n return host === domain || Boolean(host?.endsWith(`.${domain}`));\n }\n if (property.startsWith('sc-domain:')) {\n const root = parseUrl(site);\n const domain = property.slice('sc-domain:'.length).toLowerCase();\n return Boolean(root &&\n (root.hostname.toLowerCase() === domain ||\n root.hostname.toLowerCase().endsWith(`.${domain}`)));\n }\n try {\n const root = assertUrlMatchesGscProperty(site, property);\n return root === new URL(property).toString();\n }\n catch {\n return false;\n }\n}\nfunction relevantPropertiesForSite(site, accountProperties) {\n return [...new Set([site, ...accountProperties])].filter((property) => propertyBelongsToSite(property, site));\n}\nexport function allocateIndexUrlsToProperties(input) {\n const urls = [\n ...new Set(input.urls.map((url) => assertUrlMatchesGscProperty(input.site, url))),\n ];\n const properties = relevantPropertiesForSite(input.site, input.accountProperties);\n const urlsByProperty = new Map();\n for (const url of urls) {\n const property = mostSpecificProperty(url, properties);\n if (!property)\n continue;\n const existing = urlsByProperty.get(property) ?? [];\n existing.push(url);\n urlsByProperty.set(property, existing);\n }\n return [...urlsByProperty.entries()]\n .map(([property, propertyUrls]) => ({\n property,\n urls: propertyUrls,\n }))\n .sort((a, b) => b.urls.length - a.urls.length);\n}\nfunction cycleDays(urlCount, dailyLimit) {\n if (urlCount <= 0)\n return 0;\n return Math.ceil(urlCount / dailyLimit);\n}\nfunction subdirectoryProperty(url) {\n const parsed = parseUrl(url);\n if (!parsed)\n return undefined;\n const firstSegment = parsed.pathname.split('/').filter(Boolean)[0];\n if (!firstSegment)\n return undefined;\n return `${parsed.origin}/${firstSegment}/`;\n}\nfunction propertyOrigin(property, fallbackSite) {\n return originFromSite(property) ?? originFromSite(fallbackSite);\n}\nfunction suggestedProperties(input) {\n const suggestions = [];\n const maxUrlsPerBucket = input.dailyLimit * input.targetCycleDays;\n for (const property of input.properties) {\n if (property.urlCount <= maxUrlsPerBucket)\n continue;\n const urls = input.urlsByProperty.get(property.property) ?? [];\n const byDirectory = new Map();\n for (const url of urls) {\n const suggested = subdirectoryProperty(url);\n if (!suggested)\n continue;\n if (input.existingProperties.some((item) => item === suggested))\n continue;\n const propertyOriginUrl = propertyOrigin(property.property, input.site);\n if (propertyOriginUrl && !suggested.startsWith(propertyOriginUrl))\n continue;\n const existing = byDirectory.get(suggested) ?? [];\n existing.push(url);\n byDirectory.set(suggested, existing);\n }\n for (const [suggested, directoryUrls] of [...byDirectory.entries()].sort((a, b) => b[1].length - a[1].length)) {\n if (directoryUrls.length < Math.min(100, maxUrlsPerBucket))\n continue;\n suggestions.push({\n property: suggested,\n urlCount: directoryUrls.length,\n currentProperty: property.property,\n estimatedCycleDays: cycleDays(directoryUrls.length, input.dailyLimit),\n sampleUrls: directoryUrls.slice(0, 3),\n reason: `${directoryUrls.length} URLs share this folder. A URL-prefix property would give it a separate daily inspection bucket.`,\n });\n if (suggestions.length >= input.limit)\n return suggestions;\n }\n }\n return suggestions;\n}\nexport async function indexCoveragePlan(input) {\n if (!input.sitemaps.length || input.sitemaps.length > 20) {\n throw new SeoError('INVALID_INPUT', 'Pass between 1 and 20 sitemap URLs.');\n }\n const maxUrls = integerOption({\n value: input.maxUrls,\n fallback: 50_000,\n minimum: 1,\n maximum: 250_000,\n label: 'maxUrls',\n });\n const warnings = [];\n const sitemaps = input.sitemaps.map(normalizeHttpUrl);\n const sitemapResults = await Promise.all(sitemaps.map((sitemapUrl) => fetchSitemapUrls({ sitemapUrl, limit: maxUrls })));\n const inventory = boundedSitemapInventory(sitemapResults, maxUrls);\n const urls = inventory.urls;\n warnings.push(...sitemapResults.flatMap((result) => result.warnings));\n if (inventory.truncation.possiblyTruncated) {\n warnings.push('Sitemap discovery exceeded a configured URL or nested-sitemap boundary; coverage planning may be incomplete.');\n }\n const accountProperties = input.properties\n ? [...input.properties]\n : await listSites(input.refresh).then((sites) => sites.map((site) => site.siteUrl));\n return planIndexCoverageFromUrls({\n site: input.site,\n urls,\n sitemaps,\n accountProperties,\n dailyLimit: input.dailyLimit,\n targetCycleDays: input.targetCycleDays,\n suggestionLimit: input.suggestionLimit,\n warnings,\n });\n}\nexport function planIndexCoverageFromUrls(input) {\n const dailyLimit = integerOption({\n value: input.dailyLimit,\n fallback: 2_000,\n minimum: 1,\n maximum: 2_000,\n label: 'dailyLimit',\n });\n const targetCycleDays = integerOption({\n value: input.targetCycleDays,\n fallback: 1,\n minimum: 1,\n maximum: 365,\n label: 'targetCycleDays',\n });\n const suggestionLimit = integerOption({\n value: input.suggestionLimit,\n fallback: 10,\n minimum: 0,\n maximum: 100,\n label: 'suggestionLimit',\n });\n const warnings = [...(input.warnings ?? [])];\n const urls = [];\n for (const value of [...new Set(input.urls)]) {\n try {\n urls.push(assertUrlMatchesGscProperty(input.site, value));\n }\n catch (error) {\n warnings.push(error instanceof Error ? error.message : String(error));\n }\n }\n const allocations = allocateIndexUrlsToProperties({\n site: input.site,\n urls,\n accountProperties: input.accountProperties,\n });\n const urlsByProperty = new Map(allocations.map((allocation) => [allocation.property, allocation.urls]));\n const propertyPlans = allocations\n .map((allocation) => ({\n property: allocation.property,\n urlCount: allocation.urls.length,\n dailyLimit,\n cycleDays: cycleDays(allocation.urls.length, dailyLimit),\n sampleUrls: allocation.urls.slice(0, 3),\n }))\n .sort((a, b) => b.urlCount - a.urlCount);\n const dailyCapacity = propertyPlans.length * dailyLimit;\n const estimatedCycleDays = cycleDays(urls.length, dailyCapacity || dailyLimit);\n const suggestions = suggestedProperties({\n properties: propertyPlans,\n urlsByProperty,\n existingProperties: input.accountProperties,\n site: input.site,\n dailyLimit,\n targetCycleDays,\n limit: suggestionLimit,\n });\n return {\n site: input.site,\n generatedAt: new Date().toISOString(),\n summary: {\n sitemapUrls: input.sitemaps?.length ?? 0,\n urlCount: urls.length,\n properties: propertyPlans.length,\n dailyCapacity,\n estimatedCycleDays,\n targetCycleDays,\n suggestedProperties: suggestions.length,\n },\n properties: propertyPlans,\n suggestions,\n warnings,\n };\n}\n//# sourceMappingURL=index-plan.js.map","const STATUS_FIELDS = [\n 'verdict',\n 'indexingState',\n 'robotsTxtState',\n 'pageFetchState',\n 'googleCanonical',\n 'userCanonical',\n];\nfunction indexStatus(verdict) {\n if (verdict === 'PASS')\n return 'indexed';\n if (verdict === 'NEUTRAL')\n return 'excluded';\n if (verdict === 'FAIL')\n return 'invalid';\n return 'unknown';\n}\nfunction canonicalKey(value) {\n if (!value)\n return undefined;\n try {\n const url = new URL(value);\n url.hash = '';\n return url.toString();\n }\n catch {\n return value;\n }\n}\nexport function indexWatchIssueCodes(status) {\n const issues = [];\n if (status.verdict === 'FAIL')\n issues.push('verdict_invalid');\n if (status.verdict === 'NEUTRAL')\n issues.push('verdict_excluded');\n if (status.robotsTxtState === 'DISALLOWED') {\n issues.push('robots_disallowed');\n }\n if (status.indexingState === 'BLOCKED_BY_META_TAG') {\n issues.push('indexing_blocked_meta');\n }\n if (status.indexingState === 'BLOCKED_BY_HTTP_HEADER') {\n issues.push('indexing_blocked_header');\n }\n if (status.pageFetchState &&\n !['PAGE_FETCH_STATE_UNSPECIFIED', 'SUCCESSFUL'].includes(status.pageFetchState)) {\n issues.push('page_fetch_failed');\n }\n if (status.googleCanonical &&\n status.userCanonical &&\n canonicalKey(status.googleCanonical) !== canonicalKey(status.userCanonical)) {\n issues.push('canonical_mismatch');\n }\n return issues;\n}\nfunction changesFromPrevious(previous, current) {\n if (!previous)\n return [];\n return STATUS_FIELDS.flatMap((field) => {\n const before = previous[field];\n const after = current[field];\n const equal = field === 'googleCanonical' || field === 'userCanonical'\n ? canonicalKey(before) === canonicalKey(after)\n : before === after;\n return equal ? [] : [{ field, before, after }];\n });\n}\nfunction changeKind(input) {\n if (!input.previous)\n return 'baseline';\n if (!input.changes.length)\n return 'unchanged';\n const previousIssue = indexWatchIssueCodes(input.previous).length > 0;\n if (!previousIssue && input.currentIssue)\n return 'regression';\n if (previousIssue && !input.currentIssue)\n return 'recovery';\n return 'changed';\n}\nexport function indexWatchItemFromInspection(input) {\n const status = input.result.inspectionResult?.indexStatusResult;\n const item = {\n rootSite: input.rootSite,\n property: input.property,\n url: input.url,\n inspectedAt: input.inspectedAt,\n inspectionStatus: 'succeeded',\n requestSent: true,\n indexStatus: indexStatus(status?.verdict),\n verdict: status?.verdict,\n coverageState: status?.coverageState,\n indexingState: status?.indexingState,\n robotsTxtState: status?.robotsTxtState,\n pageFetchState: status?.pageFetchState,\n googleCanonical: status?.googleCanonical,\n userCanonical: status?.userCanonical,\n lastCrawlTime: status?.lastCrawlTime,\n previous: input.previous,\n issueCodes: [],\n currentIssue: false,\n severity: 'none',\n changes: [],\n changeKind: 'baseline',\n changed: false,\n regression: false,\n recovery: false,\n alert: false,\n };\n item.issueCodes = indexWatchIssueCodes(item);\n item.currentIssue = item.issueCodes.length > 0;\n item.severity = item.issueCodes.some((issue) => [\n 'verdict_invalid',\n 'robots_disallowed',\n 'indexing_blocked_meta',\n 'indexing_blocked_header',\n 'page_fetch_failed',\n ].includes(issue))\n ? 'high'\n : item.currentIssue\n ? 'medium'\n : 'none';\n item.changes = changesFromPrevious(input.previous, item);\n item.changeKind = changeKind({\n previous: input.previous,\n changes: item.changes,\n currentIssue: item.currentIssue,\n });\n item.changed = item.changes.length > 0;\n item.regression = item.changeKind === 'regression';\n item.recovery = item.changeKind === 'recovery';\n item.alert =\n item.regression || (item.changeKind === 'baseline' && item.currentIssue);\n return item;\n}\nexport function indexWatchFailureItem(input) {\n return {\n rootSite: input.rootSite,\n property: input.property,\n url: input.url,\n inspectedAt: input.inspectedAt,\n inspectionStatus: input.deferred\n ? 'deferred'\n : input.quotaBlocked\n ? 'quota-blocked'\n : 'failed',\n requestSent: input.requestSent ?? true,\n indexStatus: 'unknown',\n issueCodes: [\n input.quotaBlocked ? 'inspection_quota_blocked' : 'inspection_failed',\n ],\n currentIssue: false,\n severity: 'none',\n changes: [],\n changeKind: 'not-comparable',\n changed: false,\n regression: false,\n recovery: false,\n alert: false,\n errorCode: input.errorCode,\n errorMessage: input.errorMessage,\n retryAt: input.retryAt,\n };\n}\n//# sourceMappingURL=index-watch-analysis.js.map","import { randomUUID } from 'node:crypto';\nimport { SeoError, toSeoError } from '../../errors.js';\nimport { UrlInspectionQuotaError } from '../../gsc/client/inspection-quota.js';\nimport { inspectUrl, } from '../../gsc/client.js';\nimport { assertUrlMatchesGscProperty } from '../../gsc/property-url.js';\nimport { getDb } from '../../storage/database.js';\nimport { integerOption } from '../site-diagnostics/quick-wins-report-input.js';\nimport { indexWatchFailureItem, indexWatchIssueCodes, indexWatchItemFromInspection, } from './index-watch-analysis.js';\nconst MAX_DIRECT_INSPECTIONS = 100;\nfunction previousFromRow(row) {\n if (!row.inspected_at)\n return undefined;\n return {\n inspectedAt: new Date(row.inspected_at).toISOString(),\n verdict: row.verdict ?? undefined,\n coverageState: row.coverage_state ?? undefined,\n indexingState: row.indexing_state ?? undefined,\n robotsTxtState: row.robots_txt_state ?? undefined,\n pageFetchState: row.page_fetch_state ?? undefined,\n googleCanonical: row.google_canonical ?? undefined,\n userCanonical: row.user_canonical ?? undefined,\n lastCrawlTime: row.last_crawl_time ?? undefined,\n };\n}\nconst sqliteIndexWatchStore = {\n latest(rootSite, url) {\n const row = getDb()\n .prepare(`SELECT *\n FROM index_watch_snapshots\n WHERE root_site_url = ? AND url = ? AND error_code IS NULL\n ORDER BY inspected_at DESC, id DESC\n LIMIT 1`)\n .get(rootSite, url);\n return row ? previousFromRow(row) : undefined;\n },\n insert(item) {\n getDb()\n .prepare(`INSERT INTO index_watch_snapshots\n (id, site_url, root_site_url, property_site_url, url, verdict,\n coverage_state, indexing_state, robots_txt_state, page_fetch_state,\n google_canonical, user_canonical, last_crawl_time, inspection_status,\n error_code, error_message, inspected_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n .run(randomUUID(), item.property, item.rootSite, item.property, item.url, item.verdict ?? null, item.coverageState ?? null, item.indexingState ?? null, item.robotsTxtState ?? null, item.pageFetchState ?? null, item.googleCanonical ?? null, item.userCanonical ?? null, item.lastCrawlTime ?? null, item.inspectionStatus, item.errorCode ?? null, item.errorMessage ?? null, Date.parse(item.inspectedAt));\n },\n};\nconst defaultDependencies = {\n inspectUrl,\n now: () => new Date(),\n store: sqliteIndexWatchStore,\n};\nfunction validateLanguageCode(value) {\n const code = value?.trim();\n if (!code)\n return undefined;\n if (code.length > 35 || !/^[A-Za-z0-9-]+$/.test(code)) {\n throw new SeoError('INVALID_INPUT', 'languageCode must be a valid BCP 47 tag.');\n }\n return code;\n}\nfunction normalizedUrls(property, urls) {\n if (!urls.length) {\n throw new SeoError('INVALID_INPUT', 'Pass at least one URL to inspect.');\n }\n if (urls.length > MAX_DIRECT_INSPECTIONS) {\n throw new SeoError('INVALID_INPUT', `Direct index watch accepts at most ${MAX_DIRECT_INSPECTIONS} URLs per run.`);\n }\n return [\n ...new Set(urls.map((url) => assertUrlMatchesGscProperty(property, url))),\n ];\n}\nfunction failureCode(error) {\n return error instanceof SeoError\n ? error.code.toLowerCase()\n : 'inspection_failed';\n}\nfunction isFatalBatchError(error) {\n return ['AUTH_CONFIG_REQUIRED', 'AUTH_EXPIRED', 'AUTH_REQUIRED'].includes(error.code);\n}\nexport async function indexWatch(input, dependencies = defaultDependencies) {\n const languageCode = validateLanguageCode(input.languageCode);\n const dailyLimit = integerOption({\n value: input.dailyLimit,\n fallback: 2_000,\n minimum: 1,\n maximum: 2_000,\n label: 'dailyLimit',\n });\n const urls = normalizedUrls(input.site, input.urls);\n const rootSite = input.rootSite ?? input.site;\n const items = [];\n const warnings = [];\n for (const [index, url] of urls.entries()) {\n const inspectedAt = dependencies.now().toISOString();\n try {\n const result = await dependencies.inspectUrl({\n siteUrl: input.site,\n inspectionUrl: url,\n languageCode,\n quotaLimit: dailyLimit,\n });\n const item = indexWatchItemFromInspection({\n rootSite,\n property: input.site,\n url,\n inspectedAt,\n result,\n previous: dependencies.store.latest(rootSite, url),\n });\n dependencies.store.insert(item);\n items.push(item);\n }\n catch (error) {\n const normalized = toSeoError(error);\n if (isFatalBatchError(normalized))\n throw normalized;\n const propertyError = ['ACCESS_DENIED', 'PROPERTY_NOT_FOUND'].includes(normalized.code);\n if (propertyError && !input.continueOnPropertyError)\n throw normalized;\n const quotaBlocked = normalized.code === 'RATE_LIMITED';\n const requestSent = normalized instanceof UrlInspectionQuotaError\n ? normalized.requestSent\n : true;\n const retryAt = normalized instanceof UrlInspectionQuotaError\n ? normalized.resetAt\n : undefined;\n const item = indexWatchFailureItem({\n rootSite,\n property: input.site,\n url,\n inspectedAt,\n errorCode: failureCode(normalized),\n errorMessage: normalized.message,\n quotaBlocked,\n requestSent,\n retryAt,\n });\n dependencies.store.insert(item);\n items.push(item);\n warnings.push(`${url}: ${normalized.message}`);\n if (quotaBlocked || propertyError) {\n for (const blockedUrl of urls.slice(index + 1)) {\n const blocked = indexWatchFailureItem({\n rootSite,\n property: input.site,\n url: blockedUrl,\n inspectedAt: dependencies.now().toISOString(),\n errorCode: quotaBlocked\n ? 'rate_limited'\n : normalized.code.toLowerCase(),\n errorMessage: quotaBlocked\n ? 'URL Inspection quota is blocked for this property; no request was sent.'\n : `URL Inspection stopped for this property after ${normalized.code}; no request was sent.`,\n quotaBlocked,\n deferred: true,\n requestSent: false,\n retryAt,\n });\n items.push(blocked);\n }\n break;\n }\n }\n }\n const inspected = items.filter((item) => item.inspectionStatus === 'succeeded').length;\n const failed = items.filter((item) => item.inspectionStatus === 'failed').length;\n const quotaBlocked = items.filter((item) => item.inspectionStatus === 'quota-blocked').length;\n const deferred = items.filter((item) => item.inspectionStatus === 'deferred').length;\n const currentIssues = items.filter((item) => item.currentIssue).length;\n return {\n schemaVersion: 1,\n methodology: 'index-watch-v2',\n site: rootSite,\n generatedAt: dependencies.now().toISOString(),\n dataStatus: failed || quotaBlocked || deferred ? 'partial' : 'complete',\n source: {\n type: 'url-inspection-indexed-snapshot',\n property: input.site,\n dailyLimit,\n languageCode,\n },\n summary: {\n requested: input.urls.length,\n unique: urls.length,\n attempted: items.filter((item) => item.requestSent).length,\n inspected,\n failed,\n quotaBlocked,\n deferred,\n currentIssues,\n changed: items.filter((item) => item.changed).length,\n regressions: items.filter((item) => item.regression).length,\n recoveries: items.filter((item) => item.recovery).length,\n alerts: items.filter((item) => item.alert).length,\n },\n caveats: [\n \"URL Inspection reports Google's indexed snapshot for one URL, not a live test of the current page.\",\n 'PASS, NEUTRAL, and FAIL map to indexed, excluded, and invalid. Translated coverage text is display evidence only.',\n 'An excluded URL or canonical difference may be intentional. Issue codes mean review the URL against its intended state, not that every URL is defective.',\n 'The local quota ledger uses a conservative UTC-day safety cap and cannot see URL Inspection calls made by other machines or Google clients.',\n ],\n warnings,\n items,\n };\n}\nexport function latestIndexWatchSummary(site) {\n const rows = getDb()\n .prepare(`WITH attempts AS (\n SELECT snapshot.*,\n ROW_NUMBER() OVER (\n PARTITION BY url\n ORDER BY inspected_at DESC, id DESC\n ) AS attempt_rank\n FROM index_watch_snapshots snapshot\n WHERE root_site_url = ?\n ), successes AS (\n SELECT snapshot.*,\n ROW_NUMBER() OVER (\n PARTITION BY url\n ORDER BY inspected_at DESC, id DESC\n ) AS success_rank\n FROM index_watch_snapshots snapshot\n WHERE root_site_url = ?\n AND inspection_status = 'succeeded'\n AND error_code IS NULL\n )\n SELECT\n attempts.url,\n attempts.inspected_at AS attempt_inspected_at,\n attempts.error_code AS latest_error_code,\n successes.inspected_at AS success_inspected_at,\n successes.verdict,\n successes.indexing_state,\n successes.robots_txt_state,\n successes.page_fetch_state,\n successes.google_canonical,\n successes.user_canonical\n FROM attempts\n LEFT JOIN successes\n ON successes.url = attempts.url AND successes.success_rank = 1\n WHERE attempts.attempt_rank = 1`)\n .all(site, site);\n const timestamps = rows\n .map((row) => row.success_inspected_at)\n .filter((value) => Boolean(value));\n const earliestTimestamp = timestamps.reduce((earliest, timestamp) => Math.min(earliest, timestamp), Number.POSITIVE_INFINITY);\n const successful = rows.filter((row) => Boolean(row.success_inspected_at));\n const issues = successful.map((row) => indexWatchIssueCodes({\n verdict: row.verdict ?? undefined,\n indexingState: row.indexing_state ?? undefined,\n robotsTxtState: row.robots_txt_state ?? undefined,\n pageFetchState: row.page_fetch_state ?? undefined,\n googleCanonical: row.google_canonical ?? undefined,\n userCanonical: row.user_canonical ?? undefined,\n }));\n return {\n inspectedUrls: rows.length,\n earliestInspectedAt: timestamps.length\n ? new Date(earliestTimestamp).toISOString()\n : undefined,\n latestInspectedAt: rows.length\n ? new Date(Math.max(...rows.map((row) => row.attempt_inspected_at ?? 0))).toISOString()\n : undefined,\n currentIssues: issues.filter((codes) => codes.length > 0).length,\n failed: rows.filter((row) => Boolean(row.latest_error_code)).length,\n nonPass: successful.filter((row) => row.verdict && row.verdict !== 'PASS')\n .length,\n blocked: issues.filter((codes) => codes.some((code) => [\n 'indexing_blocked_header',\n 'indexing_blocked_meta',\n 'page_fetch_failed',\n 'robots_disallowed',\n ].includes(code))).length,\n };\n}\n//# sourceMappingURL=index-watch.js.map","import { SeoError } from '../../errors.js';\nimport { listSites } from '../../gsc/client.js';\nimport { assertUrlMatchesGscProperty, normalizeHttpUrl, } from '../../gsc/property-url.js';\nimport { getDb } from '../../storage/database.js';\nimport { integerOption } from '../site-diagnostics/quick-wins-report-input.js';\nimport { allocateIndexUrlsToProperties } from './index-plan.js';\nimport { indexWatch } from './index-watch.js';\nimport { boundedSitemapInventory, fetchSitemapUrls } from './sitemaps.js';\nfunction latestInspectionStates(rootSite, urls) {\n if (!urls.length)\n return new Map();\n const latest = new Map();\n const chunkSize = 500;\n for (let index = 0; index < urls.length; index += chunkSize) {\n const chunk = urls.slice(index, index + chunkSize);\n const placeholders = chunk.map(() => '?').join(', ');\n const rows = getDb()\n .prepare(`WITH ranked AS (\n SELECT url, inspected_at, inspection_status, error_code,\n MAX(CASE\n WHEN inspection_status = 'succeeded' AND error_code IS NULL\n THEN inspected_at\n END) OVER (PARTITION BY url) AS latest_success_at,\n ROW_NUMBER() OVER (\n PARTITION BY url ORDER BY inspected_at DESC, id DESC\n ) AS attempt_rank\n FROM index_watch_snapshots\n WHERE root_site_url = ? AND url IN (${placeholders})\n )\n SELECT * FROM ranked WHERE attempt_rank = 1`)\n .all(rootSite, ...chunk);\n for (const row of rows) {\n latest.set(row.url, {\n latestAttemptAt: row.inspected_at ?? undefined,\n latestSuccessAt: row.latest_success_at ?? undefined,\n latestAttemptSucceeded: row.inspection_status === 'succeeded' && !row.error_code,\n });\n }\n }\n return latest;\n}\nfunction dueUrlsForProperty(rootSite, urls, limit, dueBefore, retryBefore) {\n const latest = latestInspectionStates(rootSite, urls);\n const counts = {\n neverAttempted: 0,\n neverSucceeded: 0,\n retryWaiting: 0,\n fresh: 0,\n stale: 0,\n };\n const dueUrls = [];\n for (const url of urls) {\n const state = latest.get(url);\n if (!state) {\n counts.neverAttempted += 1;\n dueUrls.push({ url, dueReason: 'never-attempted' });\n continue;\n }\n if (!state.latestAttemptSucceeded &&\n state.latestAttemptAt &&\n state.latestAttemptAt > retryBefore) {\n counts.retryWaiting += 1;\n continue;\n }\n if (!state.latestSuccessAt) {\n counts.neverSucceeded += 1;\n dueUrls.push({ url, dueReason: 'never-succeeded' });\n continue;\n }\n if (state.latestSuccessAt <= dueBefore) {\n counts.stale += 1;\n dueUrls.push({\n url,\n lastInspectedAt: state.latestSuccessAt,\n dueReason: 'stale',\n });\n continue;\n }\n counts.fresh += 1;\n }\n return {\n counts,\n dueUrls: dueUrls\n .sort((a, b) => (a.lastInspectedAt ?? 0) - (b.lastInspectedAt ?? 0) ||\n (a.url < b.url ? -1 : a.url > b.url ? 1 : 0))\n .slice(0, limit),\n };\n}\nexport function planDueIndexUrls(input) {\n const dailyLimit = integerOption({\n value: input.dailyLimit,\n fallback: 2_000,\n minimum: 1,\n maximum: 2_000,\n label: 'dailyLimit',\n });\n const inspectLimit = integerOption({\n value: input.inspectLimit,\n fallback: Math.min(dailyLimit, 100),\n minimum: 1,\n maximum: 100,\n label: 'inspectLimit',\n });\n const staleAfterDays = integerOption({\n value: input.staleAfterDays,\n fallback: 1,\n minimum: 1,\n maximum: 365,\n label: 'staleAfterDays',\n });\n const failureRetryHours = integerOption({\n value: input.failureRetryHours,\n fallback: 24,\n minimum: 1,\n maximum: 168,\n label: 'failureRetryHours',\n });\n const now = (input.now ?? new Date()).getTime();\n const dueBefore = now - staleAfterDays * 86_400_000;\n const retryBefore = now - failureRetryHours * 3_600_000;\n const allocations = allocateIndexUrlsToProperties({\n site: input.site,\n urls: input.urls,\n accountProperties: input.accountProperties,\n });\n const dueByProperty = allocations.map((allocation) => {\n const due = dueUrlsForProperty(input.site, allocation.urls, dailyLimit, dueBefore, retryBefore);\n return { allocation, ...due, cursor: 0 };\n });\n const selected = [];\n let remaining = inspectLimit;\n const firstPassLimit = Math.max(1, Math.floor(inspectLimit / Math.max(1, dueByProperty.length)));\n for (const item of dueByProperty) {\n if (remaining <= 0)\n break;\n const propertyLimit = Math.min(firstPassLimit, remaining);\n const dueUrls = item.dueUrls.slice(0, propertyLimit);\n item.cursor = dueUrls.length;\n selected.push(...withProperty(item.allocation.property, dueUrls));\n remaining -= dueUrls.length;\n }\n for (const item of dueByProperty) {\n if (remaining <= 0)\n break;\n const dueUrls = item.dueUrls.slice(item.cursor, item.cursor + remaining);\n selected.push(...withProperty(item.allocation.property, dueUrls));\n remaining -= dueUrls.length;\n }\n const counts = dueByProperty.reduce((total, item) => ({\n neverAttempted: total.neverAttempted + item.counts.neverAttempted,\n neverSucceeded: total.neverSucceeded + item.counts.neverSucceeded,\n retryWaiting: total.retryWaiting + item.counts.retryWaiting,\n fresh: total.fresh + item.counts.fresh,\n stale: total.stale + item.counts.stale,\n }), {\n neverAttempted: 0,\n neverSucceeded: 0,\n retryWaiting: 0,\n fresh: 0,\n stale: 0,\n });\n const due = counts.neverAttempted + counts.neverSucceeded + counts.stale;\n return {\n selected,\n summary: {\n ...counts,\n due,\n unselectedDue: Math.max(0, due - selected.length),\n },\n };\n}\nexport function selectDueIndexUrls(input) {\n return planDueIndexUrls(input).selected;\n}\nfunction withProperty(property, urls) {\n return urls.map((dueUrl) => ({\n ...dueUrl,\n property,\n }));\n}\nexport async function indexMonitor(input) {\n const staleAfterDays = 1;\n const failureRetryHours = 24;\n if (!input.sitemaps.length || input.sitemaps.length > 20) {\n throw new SeoError('INVALID_INPUT', 'Pass between 1 and 20 sitemap URLs.');\n }\n const sitemaps = input.sitemaps.map(normalizeHttpUrl);\n const dailyLimit = integerOption({\n value: input.dailyLimit,\n fallback: 2_000,\n minimum: 1,\n maximum: 2_000,\n label: 'dailyLimit',\n });\n const inspectLimit = integerOption({\n value: input.inspectLimit,\n fallback: Math.min(dailyLimit, 100),\n minimum: 1,\n maximum: 100,\n label: 'inspectLimit',\n });\n const maxUrls = integerOption({\n value: input.maxUrls,\n fallback: 50_000,\n minimum: 1,\n maximum: 250_000,\n label: 'maxUrls',\n });\n const sitemapResults = await Promise.all(sitemaps.map((sitemapUrl) => fetchSitemapUrls({ sitemapUrl, limit: maxUrls })));\n const inventory = boundedSitemapInventory(sitemapResults, maxUrls);\n const discoveredUrls = inventory.urls;\n const warnings = sitemapResults.flatMap((result) => result.warnings);\n const inventoryUrls = [];\n let invalidUrls = 0;\n for (const url of discoveredUrls) {\n try {\n inventoryUrls.push(assertUrlMatchesGscProperty(input.site, url));\n }\n catch (error) {\n invalidUrls += 1;\n warnings.push(error instanceof Error ? error.message : String(error));\n }\n }\n const possiblyTruncated = inventory.truncation.possiblyTruncated;\n if (possiblyTruncated) {\n warnings.push('Sitemap discovery exceeded a configured URL or nested-sitemap boundary; inventory and skipped counts may be incomplete.');\n }\n const accountProperties = input.properties\n ? [...input.properties]\n : await listSites(input.refresh).then((sites) => sites.map((site) => site.siteUrl));\n const allocations = allocateIndexUrlsToProperties({\n site: input.site,\n urls: inventoryUrls,\n accountProperties,\n });\n const selection = planDueIndexUrls({\n site: input.site,\n urls: inventoryUrls,\n accountProperties,\n dailyLimit,\n inspectLimit,\n staleAfterDays,\n failureRetryHours,\n });\n const selected = selection.selected;\n const selectedByProperty = new Map();\n for (const selectedUrl of selected) {\n const existing = selectedByProperty.get(selectedUrl.property) ?? [];\n existing.push(selectedUrl.url);\n selectedByProperty.set(selectedUrl.property, existing);\n }\n const items = [];\n const properties = [];\n for (const allocation of allocations) {\n const urls = selectedByProperty.get(allocation.property) ?? [];\n if (!urls.length) {\n properties.push({\n property: allocation.property,\n inventoryUrls: allocation.urls.length,\n selectedUrls: 0,\n attempted: 0,\n inspected: 0,\n failed: 0,\n quotaBlocked: 0,\n deferred: 0,\n currentIssues: 0,\n changed: 0,\n regressions: 0,\n recoveries: 0,\n alerts: 0,\n sampleUrls: allocation.urls.slice(0, 3),\n });\n continue;\n }\n const report = await indexWatch({\n site: allocation.property,\n rootSite: input.site,\n urls,\n languageCode: input.languageCode,\n dailyLimit,\n continueOnPropertyError: true,\n });\n items.push(...report.items);\n warnings.push(...report.warnings);\n properties.push({\n property: allocation.property,\n inventoryUrls: allocation.urls.length,\n selectedUrls: urls.length,\n attempted: report.summary.attempted,\n inspected: report.summary.inspected,\n failed: report.summary.failed,\n quotaBlocked: report.summary.quotaBlocked,\n deferred: report.summary.deferred,\n currentIssues: report.summary.currentIssues,\n changed: report.summary.changed,\n regressions: report.summary.regressions,\n recoveries: report.summary.recoveries,\n alerts: report.summary.alerts,\n sampleUrls: urls.slice(0, 3),\n });\n }\n return {\n schemaVersion: 1,\n methodology: 'index-monitor-v2',\n site: input.site,\n generatedAt: new Date().toISOString(),\n dataStatus: possiblyTruncated ||\n warnings.length > 0 ||\n items.some((item) => item.inspectionStatus !== 'succeeded')\n ? 'partial'\n : 'complete',\n source: {\n type: 'sitemap-url-inspection-indexed-snapshot',\n sitemaps,\n maxUrls,\n dailyLimit,\n inspectLimit,\n staleAfterDays,\n failureRetryHours,\n possiblyTruncated,\n inventoryLimitExceeded: inventory.truncation.inventoryLimitExceeded,\n omittedUrlsAtLeast: inventory.truncation.omittedUrlsAtLeast,\n discoveredUrls: discoveredUrls.length,\n invalidUrls,\n },\n summary: {\n inventoryUrls: inventoryUrls.length,\n properties: allocations.length,\n dailyCapacity: allocations.length * dailyLimit,\n neverAttempted: selection.summary.neverAttempted,\n neverSucceeded: selection.summary.neverSucceeded,\n retryWaiting: selection.summary.retryWaiting,\n fresh: selection.summary.fresh,\n stale: selection.summary.stale,\n due: selection.summary.due,\n selected: selected.length,\n unselectedDue: selection.summary.unselectedDue,\n attempted: items.filter((item) => item.requestSent).length,\n inspected: items.filter((item) => item.inspectionStatus === 'succeeded')\n .length,\n failed: items.filter((item) => item.inspectionStatus === 'failed').length,\n quotaBlocked: items.filter((item) => item.inspectionStatus === 'quota-blocked').length,\n deferred: items.filter((item) => item.inspectionStatus === 'deferred')\n .length,\n currentIssues: items.filter((item) => item.currentIssue).length,\n changed: items.filter((item) => item.changed).length,\n regressions: items.filter((item) => item.regression).length,\n recoveries: items.filter((item) => item.recovery).length,\n alerts: items.filter((item) => item.alert).length,\n skipped: Math.max(0, inventoryUrls.length - selected.length),\n },\n properties,\n items,\n caveats: [\n \"URL Inspection reports Google's indexed snapshot for one URL, not a live test of the current page.\",\n 'Due URLs are never-attempted, never-successful, or at least one day past their latest successful inspection. Failed attempts wait 24 hours before retry.',\n 'Selected URLs are a bounded oldest-first sample across matching Search Console properties; current issue counts describe the selected results, not every sitemap URL.',\n 'Excluded and canonical-difference issue codes require review against the intended URL state and are not automatically defects.',\n 'The local quota ledger uses a conservative UTC-day safety cap and cannot see URL Inspection calls made by other machines or Google clients.',\n ],\n warnings,\n };\n}\n//# sourceMappingURL=index-monitor.js.map","import { randomUUID } from 'node:crypto';\nimport { getDb } from '../../storage/database.js';\nfunction toSummary(row) {\n return {\n id: row.id,\n site: row.site_url,\n createdAt: new Date(row.created_at).toISOString(),\n range: {\n startDate: row.start_date,\n endDate: row.end_date,\n days: row.days,\n },\n checked: row.checked,\n recoverable: row.recoverable,\n high: row.high,\n medium: row.medium,\n low: row.low,\n clicksAtRisk: row.clicks_at_risk,\n impressionsAtRisk: row.impressions_at_risk,\n topIssue: row.top_issue ?? undefined,\n topUrl: row.top_url ?? undefined,\n topAction: row.top_action ?? undefined,\n repeatedUrls: row.repeated_urls ?? 0,\n repeatedTopUrl: row.repeated_top_url ?? undefined,\n };\n}\nexport function insertLinkRecoverRun(report) {\n const top = report.items[0];\n const id = randomUUID();\n const db = getDb();\n const insertRun = db.prepare(`INSERT INTO link_recover_runs\n (id, site_url, created_at, start_date, end_date, days, checked,\n recoverable, high, medium, low, clicks_at_risk, impressions_at_risk,\n top_issue, top_url, top_action)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);\n const insertItem = db.prepare(`INSERT INTO link_recover_items\n (run_id, site_url, url, final_url, issue, issues_json, severity,\n clicks, impressions, position, action, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);\n const createdAt = Date.parse(report.generatedAt);\n db.transaction(() => {\n insertRun.run(id, report.site, createdAt, report.range.startDate, report.range.endDate, report.range.days, report.summary.checked, report.summary.recoverable, report.summary.high, report.summary.medium, report.summary.low, report.summary.clicksAtRisk, report.summary.impressionsAtRisk, top?.issue ?? null, top?.url ?? null, top?.recommendation.action ?? null);\n for (const item of report.items) {\n insertItem.run(id, report.site, item.url, item.finalUrl, item.issue, JSON.stringify(item.issues), item.severity, item.clicks, item.impressions, item.position, item.recommendation.action, createdAt);\n }\n })();\n return id;\n}\nexport function latestLinkRecoverSummary(site) {\n const row = getDb()\n .prepare(`SELECT *\n FROM link_recover_runs\n WHERE site_url = ?\n ORDER BY created_at DESC\n LIMIT 1`)\n .get(site);\n if (!row)\n return undefined;\n const repeated = getRepeatedLinkRecoverUrls(site, 5);\n return toSummary({\n ...row,\n repeated_urls: repeated.length,\n repeated_top_url: repeated[0]?.url,\n });\n}\nexport function getRepeatedLinkRecoverUrls(site, runLimit = 5) {\n const db = getDb();\n const runs = db\n .prepare(`SELECT id\n FROM link_recover_runs\n WHERE site_url = ?\n ORDER BY created_at DESC\n LIMIT ?`)\n .all(site, runLimit);\n if (runs.length < 2)\n return [];\n const placeholders = runs.map(() => '?').join(', ');\n const rows = db\n .prepare(`SELECT url, COUNT(DISTINCT run_id) AS seen_count\n FROM link_recover_items\n WHERE site_url = ? AND run_id IN (${placeholders})\n GROUP BY url\n HAVING seen_count >= 2\n ORDER BY seen_count DESC, MAX(created_at) DESC`)\n .all(site, ...runs.map((run) => run.id));\n return rows.map((row) => ({\n url: row.url,\n seenCount: row.seen_count,\n }));\n}\n//# sourceMappingURL=link-recover-store.js.map","import { publicHttpFetch } from '../../fetch/http-client.js';\nimport { crawlOne } from './crawl-page.js';\nfunction resolveNextUrl(location, baseUrl) {\n try {\n const next = new URL(location, baseUrl);\n next.hash = '';\n return next.toString();\n }\n catch {\n return undefined;\n }\n}\nfunction redirectIssue(input) {\n const issues = [];\n const finalStatus = input.chain.at(-1)?.status ?? 0;\n const redirectWithoutLocation = input.chain.some((step) => step.status >= 300 && step.status < 400 && !step.location);\n if (input.stoppedForLoop)\n issues.push('redirect-loop');\n if (input.stoppedForLimit)\n issues.push('too-many-redirects');\n if (redirectWithoutLocation)\n issues.push('redirect-without-location');\n if (finalStatus >= 400 && finalStatus < 500)\n issues.push('final-4xx');\n if (finalStatus >= 500)\n issues.push('final-5xx');\n if (input.finalIndexable === false)\n issues.push('non-indexable-final');\n if (input.canonical && input.canonical !== input.finalUrl) {\n issues.push('canonical-mismatch');\n }\n return [...new Set(issues)];\n}\nexport async function redirectTrace(input) {\n const maxHops = input.maxHops ?? 10;\n const warnings = [];\n const chain = [];\n const seen = new Set();\n let currentUrl = new URL(input.url).toString();\n let stoppedForLoop = false;\n let stoppedForLimit = false;\n for (let hop = 0; hop <= maxHops; hop += 1) {\n if (seen.has(currentUrl)) {\n stoppedForLoop = true;\n break;\n }\n seen.add(currentUrl);\n const startedAt = Date.now();\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), input.timeoutMs ?? 20_000);\n try {\n const response = await publicHttpFetch(currentUrl, {\n redirect: 'manual',\n signal: controller.signal,\n });\n const location = response.headers.get('location') ?? undefined;\n const nextUrl = location\n ? resolveNextUrl(location, currentUrl)\n : undefined;\n chain.push({\n url: currentUrl,\n status: response.status,\n location,\n nextUrl,\n durationMs: Date.now() - startedAt,\n });\n if (response.status < 300 || response.status >= 400)\n break;\n if (!nextUrl)\n break;\n currentUrl = nextUrl;\n }\n catch (error) {\n warnings.push(`${currentUrl}: ${error instanceof Error ? error.message : String(error)}`);\n break;\n }\n finally {\n clearTimeout(timer);\n }\n }\n const lastStep = chain.at(-1);\n if (lastStep &&\n lastStep.status >= 300 &&\n lastStep.status < 400 &&\n chain.length > maxHops) {\n stoppedForLimit = true;\n }\n const finalUrl = lastStep?.nextUrl ?? lastStep?.url ?? currentUrl;\n const final = await crawlOne(finalUrl, {\n refresh: input.refresh,\n js: input.js ?? 'auto',\n });\n if (final.warning)\n warnings.push(final.warning);\n const finalPage = final.page\n ? {\n title: final.page.title,\n canonical: final.page.canonical,\n metaRobots: final.page.metaRobots,\n xRobotsTag: final.page.xRobotsTag,\n indexable: final.page.indexable,\n }\n : undefined;\n const issues = redirectIssue({\n chain,\n finalIndexable: finalPage?.indexable,\n canonical: finalPage?.canonical,\n finalUrl,\n stoppedForLoop,\n stoppedForLimit,\n });\n return {\n url: input.url,\n finalUrl,\n generatedAt: new Date().toISOString(),\n summary: {\n hops: Math.max(0, chain.length - 1),\n finalStatus: final.page?.status ?? chain.at(-1)?.status ?? 0,\n finalIndexable: finalPage?.indexable,\n issues,\n },\n chain,\n finalPage,\n warnings,\n };\n}\n//# sourceMappingURL=redirect-trace.js.map","import { querySearchAnalytics } from '../../gsc/client.js';\nimport { defaultDateRange } from '../shared.js';\nimport { insertLinkRecoverRun } from './link-recover-store.js';\nimport { redirectTrace, } from './redirect-trace.js';\nfunction primaryIssue(issues) {\n const priority = [\n 'final-5xx',\n 'final-4xx',\n 'redirect-loop',\n 'too-many-redirects',\n 'non-indexable-final',\n 'canonical-mismatch',\n 'redirect-without-location',\n ];\n return (priority.find((issue) => issues.includes(issue)) ?? issues[0] ?? 'final-4xx');\n}\nfunction issueSeverity(issue, metrics) {\n if (issue === 'final-5xx' || issue === 'final-4xx') {\n return metrics.clicks >= 10 || metrics.impressions >= 500\n ? 'high'\n : 'medium';\n }\n if (issue === 'redirect-loop' || issue === 'too-many-redirects') {\n return 'high';\n }\n if (issue === 'non-indexable-final') {\n return metrics.clicks >= 5 || metrics.impressions >= 250 ? 'high' : 'medium';\n }\n return metrics.clicks >= 10 || metrics.impressions >= 500 ? 'medium' : 'low';\n}\nexport function linkRecoverRecommendation(input) {\n const impactEstimate = `${Math.round(input.clicks).toLocaleString('en-GB')} clicks and ${Math.round(input.impressions).toLocaleString('en-GB')} impressions in the checked period.`;\n if (input.issue === 'final-4xx') {\n return {\n principle: 'Search-value URLs should not resolve to dead pages.',\n evidenceRef: input.url,\n action: 'This search-visible URL now lands on a dead page. Restore the page if it should exist, or add one direct 301 redirect to the closest live replacement.',\n effort: 'S',\n confidence: 'high',\n impactEstimate,\n };\n }\n if (input.issue === 'final-5xx') {\n return {\n principle: 'Server errors on search-visible URLs waste existing demand.',\n evidenceRef: input.url,\n action: 'This search-visible URL ends in a server error. Fix the server response first, then rerun URL Inspection once it returns a stable 200 or an intentional 301.',\n effort: 'S',\n confidence: 'high',\n impactEstimate,\n };\n }\n if (input.issue === 'redirect-loop' ||\n input.issue === 'too-many-redirects' ||\n input.issue === 'redirect-without-location') {\n return {\n principle: 'Redirect chains must resolve cleanly to a crawlable target.',\n evidenceRef: input.url,\n action: 'The redirect path is broken. Replace the chain with one direct 301 from the old URL to the intended live destination.',\n effort: 'M',\n confidence: 'high',\n impactEstimate,\n };\n }\n if (input.issue === 'non-indexable-final') {\n return {\n principle: 'Recovered search-value URLs need an indexable final target.',\n evidenceRef: input.finalUrl,\n action: 'The final destination is not indexable. Remove accidental noindex/robots blocking, or redirect the old URL to an indexable equivalent.',\n effort: 'S',\n confidence: 'high',\n impactEstimate,\n };\n }\n return {\n principle: 'Canonicals should reinforce the final URL selected by redirects.',\n evidenceRef: input.finalUrl,\n action: 'The redirect target and canonical target disagree. Make the canonical match the final destination, or redirect the original URL directly to the canonical page.',\n effort: 'S',\n confidence: 'medium',\n impactEstimate,\n };\n}\nfunction rowMetrics(row) {\n return {\n url: row.keys[0] ?? '',\n clicks: row.clicks,\n impressions: row.impressions,\n position: row.position,\n };\n}\nexport async function linkRecover(input) {\n const days = input.days ?? 90;\n const range = defaultDateRange(days);\n const result = await querySearchAnalytics(input.site, {\n ...range,\n dimensions: ['page'],\n type: 'web',\n dataState: 'final',\n }, { refresh: input.refresh });\n const minClicks = input.minClicks ?? 1;\n const minImpressions = input.minImpressions ?? 100;\n const candidates = result.rows\n .map(rowMetrics)\n .filter((row) => row.url &&\n (row.clicks >= minClicks || row.impressions >= minImpressions))\n .sort((a, b) => b.clicks - a.clicks || b.impressions - a.impressions)\n .slice(0, input.limit ?? 50);\n const items = [];\n const warnings = [];\n for (const candidate of candidates) {\n const trace = await redirectTrace({\n url: candidate.url,\n refresh: input.refresh,\n js: input.js ?? 'auto',\n });\n warnings.push(...trace.warnings);\n if (!trace.summary.issues.length)\n continue;\n const issue = primaryIssue(trace.summary.issues);\n const severity = issueSeverity(issue, candidate);\n items.push({\n url: candidate.url,\n finalUrl: trace.finalUrl,\n clicks: candidate.clicks,\n impressions: candidate.impressions,\n position: candidate.position,\n issue,\n issues: trace.summary.issues,\n severity,\n trace: {\n summary: trace.summary,\n chain: trace.chain,\n finalPage: trace.finalPage,\n warnings: trace.warnings,\n },\n recommendation: linkRecoverRecommendation({\n issue,\n url: candidate.url,\n finalUrl: trace.finalUrl,\n clicks: candidate.clicks,\n impressions: candidate.impressions,\n }),\n });\n }\n const report = {\n site: input.site,\n generatedAt: new Date().toISOString(),\n range: {\n ...range,\n days,\n },\n summary: {\n checked: candidates.length,\n recoverable: items.length,\n high: items.filter((item) => item.severity === 'high').length,\n medium: items.filter((item) => item.severity === 'medium').length,\n low: items.filter((item) => item.severity === 'low').length,\n clicksAtRisk: items.reduce((sum, item) => sum + item.clicks, 0),\n impressionsAtRisk: items.reduce((sum, item) => sum + item.impressions, 0),\n },\n items,\n warnings: [...new Set(warnings)].slice(0, 50),\n };\n insertLinkRecoverRun(report);\n return report;\n}\n//# sourceMappingURL=link-recover.js.map","const FIELD_THRESHOLDS = {\n CLS: { good: 0.1, poor: 0.25, unit: 'score' },\n INP: { good: 200, poor: 500, unit: 'milliseconds' },\n LCP: { good: 2_500, poor: 4_000, unit: 'milliseconds' },\n};\nfunction numericP75(value) {\n if (typeof value === 'number' && Number.isFinite(value))\n return value;\n if (typeof value !== 'string' || value.trim() === '')\n return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n}\nexport function fieldMetric(name, rawMetric) {\n const p75 = numericP75(rawMetric?.percentiles\n ?.p75);\n if (p75 === undefined || p75 < 0)\n return undefined;\n const threshold = FIELD_THRESHOLDS[name];\n return {\n p75,\n unit: threshold.unit,\n rating: p75 <= threshold.good\n ? 'good'\n : p75 <= threshold.poor\n ? 'needs-work'\n : 'poor',\n };\n}\nexport function parseCruxFieldData(input) {\n const rawMetrics = input.record.metrics ?? {};\n const metrics = {\n cumulativeLayoutShift: fieldMetric('CLS', rawMetrics.cumulative_layout_shift),\n interactionToNextPaint: fieldMetric('INP', rawMetrics.interaction_to_next_paint),\n largestContentfulPaint: fieldMetric('LCP', rawMetrics.largest_contentful_paint),\n };\n const entries = [\n ['CLS', metrics.cumulativeLayoutShift],\n ['INP', metrics.interactionToNextPaint],\n ['LCP', metrics.largestContentfulPaint],\n ];\n const available = entries.filter((entry) => entry[1] !== undefined);\n const missingMetrics = entries\n .filter((entry) => entry[1] === undefined)\n .map((entry) => entry[0]);\n const ratings = available.map((entry) => entry[1]?.rating);\n const assessment = missingMetrics.length\n ? 'incomplete'\n : ratings.includes('poor')\n ? 'poor'\n : ratings.includes('needs-work')\n ? 'needs-work'\n : 'good';\n return {\n source: 'crux',\n status: 'available',\n scope: input.record.key?.url ? 'url' : 'origin',\n formFactor: input.requestedFormFactor,\n url: input.record.key?.url,\n origin: input.record.key?.origin,\n collectionPeriod: {\n firstDate: dateValue(input.record.collectionPeriod?.firstDate),\n lastDate: dateValue(input.record.collectionPeriod?.lastDate),\n },\n metrics,\n rawMetrics,\n assessment: {\n status: assessment,\n availableMetrics: available.length,\n missingMetrics,\n },\n };\n}\nfunction dateValue(value) {\n if (!value?.year || !value.month || !value.day)\n return undefined;\n return `${String(value.year).padStart(4, '0')}-${String(value.month).padStart(2, '0')}-${String(value.day).padStart(2, '0')}`;\n}\nexport function labMetric(input) {\n if (!input.audit)\n return undefined;\n const value = typeof input.audit.numericValue === 'number' &&\n Number.isFinite(input.audit.numericValue)\n ? Math.round(input.audit.numericValue * 1_000) / 1_000\n : undefined;\n return {\n value,\n displayValue: input.audit.displayValue,\n score: typeof input.audit.score === 'number' ? input.audit.score : undefined,\n rating: typeof input.audit.score === 'number'\n ? input.audit.score >= 0.9\n ? 'good'\n : input.audit.score >= 0.5\n ? 'needs-work'\n : 'poor'\n : value === undefined\n ? 'unknown'\n : input.rating?.(value),\n source: 'lighthouse-lab',\n };\n}\nexport function ratingAt(value, good, poor) {\n return value <= good ? 'good' : value <= poor ? 'needs-work' : 'poor';\n}\nfunction metricAction(input) {\n return {\n title: input.title,\n plainEnglish: `${input.metric} is ${input.display} (${input.source}).`,\n action: input.action,\n evidence: {\n metric: input.metric,\n value: input.value,\n source: input.source,\n },\n };\n}\nfunction needsReview(metric) {\n return (typeof metric?.value === 'number' &&\n (metric.rating === 'needs-work' || metric.rating === 'poor'));\n}\nexport function performanceActions(report) {\n const actions = [];\n if (report.fallbackEvidence?.blocked) {\n actions.push({\n title: 'Resolve crawl access first',\n plainEnglish: 'The fallback fetch was blocked, so it cannot support a page performance conclusion.',\n action: 'Check robots and local fetch access, then rerun Lighthouse before reviewing performance.',\n evidence: report.fallbackEvidence,\n });\n return actions;\n }\n if (report.fallbackEvidence &&\n (report.fallbackEvidence.httpStatus < 200 ||\n report.fallbackEvidence.httpStatus >= 300)) {\n actions.push({\n title: 'Fix the page response first',\n plainEnglish: `The fallback fetch returned HTTP ${report.fallbackEvidence.httpStatus}.`,\n action: 'Resolve the HTTP response before drawing any performance conclusion for this URL.',\n evidence: report.fallbackEvidence,\n });\n return actions;\n }\n const field = report.fieldData?.metrics;\n const fieldLcp = field?.largestContentfulPaint;\n if (fieldLcp && fieldLcp.rating !== 'good') {\n actions.push(metricAction({\n title: 'Improve the largest visible content',\n metric: 'LCP p75',\n value: fieldLcp.p75,\n display: `${fieldLcp.p75}ms`,\n source: `CrUX ${report.fieldData?.scope} ${report.fieldData?.formFactor}`,\n action: 'Optimize the LCP resource and server path, then verify the change in field data.',\n }));\n }\n const labLcp = report.metrics.largestContentfulPaint;\n if (needsReview(labLcp) && (!fieldLcp || fieldLcp.rating === 'good')) {\n actions.push(metricAction({\n title: fieldLcp\n ? 'Investigate the current lab LCP regression'\n : 'Improve the largest visible content',\n metric: 'Lighthouse LCP',\n value: labLcp.value,\n display: labLcp.displayValue ?? `${labLcp.value}ms`,\n source: 'Lighthouse lab run',\n action: 'Optimize the LCP resource, render path, and HTML delivery, then repeat controlled lab runs.',\n }));\n }\n const fieldInp = field?.interactionToNextPaint;\n if (fieldInp && fieldInp.rating !== 'good') {\n actions.push(metricAction({\n title: 'Improve interaction responsiveness',\n metric: 'INP p75',\n value: fieldInp.p75,\n display: `${fieldInp.p75}ms`,\n source: `CrUX ${report.fieldData?.scope} ${report.fieldData?.formFactor}`,\n action: 'Reduce long interaction tasks and rendering work, then verify the change in field data.',\n }));\n }\n const labTbt = report.metrics.totalBlockingTime;\n if (needsReview(labTbt)) {\n actions.push(metricAction({\n title: 'Reduce main-thread blocking',\n metric: 'Lighthouse TBT',\n value: labTbt.value,\n display: labTbt.displayValue ?? `${labTbt.value}ms`,\n source: 'Lighthouse lab diagnostic, not field INP',\n action: 'Defer non-critical JavaScript, split long tasks, and repeat controlled lab runs.',\n }));\n }\n const fieldCls = field?.cumulativeLayoutShift;\n if (fieldCls && fieldCls.rating !== 'good') {\n actions.push(metricAction({\n title: 'Reduce layout shifts',\n metric: 'CLS p75',\n value: fieldCls.p75,\n display: String(fieldCls.p75),\n source: `CrUX ${report.fieldData?.scope} ${report.fieldData?.formFactor}`,\n action: 'Reserve stable layout space and identify shifts across the full page lifecycle.',\n }));\n }\n const labCls = report.metrics.cumulativeLayoutShift;\n if (needsReview(labCls) && (!fieldCls || fieldCls.rating === 'good')) {\n actions.push(metricAction({\n title: fieldCls\n ? 'Investigate the current lab layout shift'\n : 'Reduce layout shifts',\n metric: 'Lighthouse CLS',\n value: labCls.value,\n display: labCls.displayValue ?? String(labCls.value),\n source: 'Lighthouse lab run',\n action: 'Reserve dimensions for images, ads, embeds, banners, and late-loading UI.',\n }));\n }\n const serverResponseTime = report.metrics.serverResponseTime;\n if (needsReview(serverResponseTime)) {\n actions.push(metricAction({\n title: 'Reduce Lighthouse server response time',\n metric: 'Lighthouse server response time',\n value: serverResponseTime.value,\n display: serverResponseTime.displayValue ?? `${serverResponseTime.value}ms`,\n source: 'Lighthouse lab diagnostic',\n action: 'Check origin work and HTML caching, then validate with repeat lab runs and separate field TTFB data.',\n }));\n }\n for (const insight of (report.labInsights ?? [])\n .filter((item) => (item.estimatedSavingsMs ?? 0) > 0)\n .slice(0, 3)) {\n actions.push({\n title: `Review Lighthouse insight: ${insight.title}`,\n plainEnglish: `Lighthouse estimates about ${Math.round(insight.estimatedSavingsMs ?? 0)}ms of potential savings for ${insight.title}.`,\n action: 'Inspect the returned evidence, fix the measured bottleneck, and confirm it with repeat controlled lab runs.',\n evidence: {\n insightId: insight.id,\n estimatedSavingsMs: insight.estimatedSavingsMs,\n },\n });\n }\n if (!actions.length &&\n report.labDataStatus?.status === 'unavailable' &&\n !report.fieldData) {\n actions.push({\n title: 'Collect performance evidence',\n plainEnglish: 'No Lighthouse lab metrics or CrUX field Core Web Vitals were available.',\n action: 'Restore the local Lighthouse browser runtime or configure CrUX, then rerun before making performance claims.',\n });\n }\n if (!actions.length) {\n actions.push({\n title: 'Keep monitoring performance',\n plainEnglish: 'No measured lab or field metric crossed its review threshold.',\n action: 'Re-run after deploys and avoid generalizing this single URL and measurement window to the whole site.',\n });\n }\n return actions;\n}\n//# sourceMappingURL=performance-analysis.js.map","import pRetry from 'p-retry';\nimport { fetch } from 'undici';\nimport { parseCruxFieldData } from './performance-analysis.js';\nconst CRUX_METRICS = [\n 'cumulative_layout_shift',\n 'interaction_to_next_paint',\n 'largest_contentful_paint',\n];\nexport async function fetchCruxFieldData(input) {\n const checkedUrl = input.url;\n const checkedOrigin = new URL(input.url).origin;\n const formFactor = input.strategy === 'desktop' ? 'DESKTOP' : 'PHONE';\n if (!input.apiKey) {\n return {\n status: {\n provider: 'crux',\n status: 'not_configured',\n reason: 'Chrome UX Report field data is not configured.',\n checkedUrl,\n checkedOrigin,\n formFactor,\n },\n caveat: 'Field Core Web Vitals were not checked in this run.',\n };\n }\n const fetchImpl = input.fetchImpl ?? fetch;\n const endpoint = `https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=${encodeURIComponent(input.apiKey)}`;\n async function query(body) {\n return pRetry(async () => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), input.timeoutMs ?? 10_000);\n try {\n const response = await fetchImpl(endpoint, {\n method: 'POST',\n body: JSON.stringify({\n ...body,\n formFactor,\n metrics: CRUX_METRICS,\n }),\n headers: { 'content-type': 'application/json' },\n signal: controller.signal,\n });\n const json = (await response.json().catch(() => ({})));\n if (response.status === 404)\n return { response, json };\n if (response.status === 429 || response.status >= 500) {\n throw new Error(`CrUX transient HTTP ${response.status}`);\n }\n if (!response.ok)\n return { response, json };\n if (!json.record) {\n throw new Error('CrUX returned no record.');\n }\n return { response, json };\n }\n finally {\n clearTimeout(timer);\n }\n }, { retries: 2, minTimeout: 250, factor: 2 });\n }\n try {\n const attempts = [\n { scope: 'url', body: { url: checkedUrl } },\n { scope: 'origin', body: { origin: checkedOrigin } },\n ];\n let lastStatus;\n for (const attempt of attempts) {\n const { response, json } = await query(attempt.body);\n lastStatus = response.status;\n if (response.ok && json.record) {\n const fieldData = parseCruxFieldData({\n record: json.record,\n requestedFormFactor: formFactor,\n });\n return {\n fieldData,\n status: {\n provider: 'crux',\n status: 'available',\n reason: `Chrome UX Report ${attempt.scope}-level field data was available.`,\n checkedUrl,\n checkedOrigin,\n formFactor,\n httpStatus: response.status,\n },\n caveat: `CrUX ${attempt.scope}-level ${formFactor.toLowerCase()} field data covers a rolling collection period; it is not the Lighthouse run.`,\n };\n }\n if (!response.ok && response.status !== 404) {\n return {\n status: {\n provider: 'crux',\n status: 'request_failed',\n reason: 'Chrome UX Report field data could not be fetched.',\n checkedUrl,\n checkedOrigin,\n formFactor,\n httpStatus: response.status,\n },\n caveat: 'Chrome UX Report field data could not be fetched right now.',\n };\n }\n }\n return {\n status: {\n provider: 'crux',\n status: 'unavailable_no_coverage',\n reason: 'Chrome UX Report does not have enough field data for this URL or origin.',\n checkedUrl,\n checkedOrigin,\n formFactor,\n httpStatus: lastStatus,\n },\n caveat: 'Chrome UX Report does not have enough device-specific field data for this URL or origin.',\n };\n }\n catch {\n return {\n status: {\n provider: 'crux',\n status: 'request_failed',\n reason: 'Chrome UX Report field data could not be fetched.',\n checkedUrl,\n checkedOrigin,\n formFactor,\n },\n caveat: 'Chrome UX Report field data could not be fetched right now.',\n };\n }\n}\n//# sourceMappingURL=performance-crux.js.map","import { execFile } from 'node:child_process';\nimport { fileURLToPath } from 'node:url';\nimport { promisify } from 'node:util';\nimport { chromium } from 'playwright-core';\nimport { resolveBrowserExecutable } from '../fetch/page-fetcher/browser-path.js';\nimport { labMetric, ratingAt } from './performance-analysis.js';\nconst execFileAsync = promisify(execFile);\nconst INSIGHT_BYTE_BUDGET = 24_000;\nfunction compactRecord(value) {\n if (!value || typeof value !== 'object')\n return {};\n return Object.fromEntries(Object.entries(value)\n .filter((entry) => {\n const item = entry[1];\n return (typeof item === 'number' ||\n typeof item === 'boolean' ||\n (typeof item === 'string' && item.length <= 160));\n })\n .slice(0, 4));\n}\nfunction labInsights(audits) {\n const candidates = Object.entries(audits)\n .filter(([id, audit]) => {\n const insight = id.endsWith('-insight');\n const opportunity = (audit.details?.overallSavingsMs ?? 0) > 0;\n return (insight || opportunity) && audit.score !== 1;\n })\n .map(([id, audit]) => {\n const evidence = [\n compactRecord(audit.details?.debugData),\n ...(audit.details?.items ?? []).slice(0, 2).map(compactRecord),\n ].filter((item) => Object.keys(item).length > 0);\n return {\n id,\n title: audit.title ?? id,\n displayValue: audit.displayValue,\n score: audit.score,\n estimatedSavingsMs: audit.details?.overallSavingsMs,\n evidence,\n };\n })\n .sort((a, b) => (b.estimatedSavingsMs ?? 0) - (a.estimatedSavingsMs ?? 0) ||\n a.id.localeCompare(b.id))\n .slice(0, 8);\n const selected = [];\n for (const candidate of candidates) {\n if (Buffer.byteLength(JSON.stringify([...selected, candidate]), 'utf8') >\n INSIGHT_BYTE_BUDGET) {\n break;\n }\n selected.push(candidate);\n }\n return selected;\n}\nfunction responseAudit(audits) {\n const legacy = audits['server-response-time'];\n if (legacy?.numericValue !== undefined)\n return legacy;\n const insight = audits['document-latency-insight'];\n const responseTime = insight?.details?.debugData?.serverResponseTime;\n return typeof responseTime === 'number'\n ? {\n numericValue: responseTime,\n displayValue: `${Math.round(responseTime)} ms`,\n score: insight?.score,\n }\n : undefined;\n}\nfunction defaultLighthouseCommand() {\n const cli = fileURLToPath(import.meta.resolve('lighthouse/cli/index.js'));\n return { bin: process.execPath, prefixArgs: [cli] };\n}\nfunction lighthouseEnvironment() {\n const resolution = resolveBrowserExecutable(chromium.executablePath());\n if (resolution.status !== 'available')\n return process.env;\n return { ...process.env, CHROME_PATH: resolution.browser.path };\n}\nclass LighthouseRunError extends Error {\n failureCode;\n constructor(failureCode) {\n super(failureCode);\n this.failureCode = failureCode;\n }\n}\nfunction classifyExternalFailure(error) {\n const value = error;\n const message = value?.message?.toLowerCase() ?? '';\n if (value?.code === 'ENOENT' || message.includes('cannot find package')) {\n return 'binary_missing';\n }\n if (value?.code === 'ETIMEDOUT' ||\n value?.killed ||\n value?.signal === 'SIGTERM' ||\n message.includes('timed out')) {\n return 'timeout';\n }\n if (message.includes('chrome') &&\n (message.includes('not found') ||\n message.includes('no usable') ||\n message.includes('install'))) {\n return 'chrome_missing';\n }\n if (error instanceof SyntaxError)\n return 'invalid_result';\n return 'run_failed';\n}\nexport function classifyLighthouseFailure(error) {\n const failureCode = error instanceof LighthouseRunError\n ? error.failureCode\n : classifyExternalFailure(error);\n const reasons = {\n binary_missing: 'The Lighthouse runtime could not be found. Reinstall seo or remove the custom binary override.',\n chrome_missing: 'Lighthouse could not find a compatible local Chrome browser.',\n invalid_result: 'Lighthouse completed without a usable navigation performance result.',\n run_failed: 'Lighthouse could not complete the navigation lab run.',\n timeout: 'Lighthouse exceeded the bounded lab-run timeout.',\n };\n return { failureCode, reason: reasons[failureCode] };\n}\nexport async function runLighthouse(input) {\n const command = input.lighthouseBin\n ? { bin: input.lighthouseBin, prefixArgs: [] }\n : defaultLighthouseCommand();\n const { stdout } = await execFileAsync(command.bin, [\n ...command.prefixArgs,\n input.url,\n '--quiet',\n '--output=json',\n '--output-path=stdout',\n '--only-categories=performance',\n `--preset=${input.strategy === 'desktop' ? 'desktop' : 'perf'}`,\n '--chrome-flags=--headless=new',\n ], {\n env: lighthouseEnvironment(),\n timeout: input.timeoutMs ?? 120_000,\n maxBuffer: 30 * 1024 * 1024,\n });\n const jsonStart = stdout.indexOf('{');\n if (jsonStart < 0)\n throw new LighthouseRunError('invalid_result');\n const parsed = JSON.parse(stdout.slice(jsonStart));\n const audits = parsed.audits ?? {};\n const categoryScore = parsed.categories?.performance?.score;\n const score = typeof categoryScore === 'number'\n ? Math.round(categoryScore * 100)\n : undefined;\n const hasEssentialMetric = [\n 'first-contentful-paint',\n 'largest-contentful-paint',\n 'total-blocking-time',\n 'cumulative-layout-shift',\n ].some((id) => typeof audits[id]?.numericValue === 'number');\n if (!hasEssentialMetric) {\n throw new LighthouseRunError('invalid_result');\n }\n const report = {\n schemaVersion: 1,\n methodology: 'performance-v2',\n dataStatus: 'complete',\n id: input.id,\n url: input.url,\n finalUrl: parsed.finalUrl,\n strategy: input.strategy,\n generatedAt: input.generatedAt,\n cache: { status: 'miss', ttlHours: 24 },\n source: 'lighthouse',\n score,\n grade: score === undefined\n ? 'unknown'\n : score >= 90\n ? 'good'\n : score >= 50\n ? 'needs-work'\n : 'poor',\n headline: score === undefined\n ? 'Lighthouse ran, but no lab performance score was returned.'\n : `Lighthouse lab performance score is ${score}/100.`,\n metrics: {\n firstContentfulPaint: labMetric({\n audit: audits['first-contentful-paint'],\n rating: (value) => ratingAt(value, 1_800, 3_000),\n }),\n largestContentfulPaint: labMetric({\n audit: audits['largest-contentful-paint'],\n rating: (value) => ratingAt(value, 2_500, 4_000),\n }),\n totalBlockingTime: labMetric({\n audit: audits['total-blocking-time'],\n rating: (value) => ratingAt(value, 200, 600),\n }),\n cumulativeLayoutShift: labMetric({\n audit: audits['cumulative-layout-shift'],\n rating: (value) => ratingAt(value, 0.1, 0.25),\n }),\n interactionToNextPaint: labMetric({\n audit: audits['interaction-to-next-paint'],\n rating: (value) => ratingAt(value, 200, 500),\n }),\n speedIndex: labMetric({ audit: audits['speed-index'] }),\n serverResponseTime: labMetric({\n audit: responseAudit(audits),\n rating: (value) => ratingAt(value, 600, 600),\n }),\n },\n labInsights: labInsights(audits),\n labDataStatus: {\n provider: 'lighthouse',\n status: 'available',\n reason: `Lighthouse ${parsed.lighthouseVersion ?? 'unknown version'} completed a ${input.strategy} navigation lab run.`,\n },\n fieldDataStatus: {\n provider: 'crux',\n status: 'not_configured',\n reason: 'Field Core Web Vitals were not checked yet.',\n checkedUrl: input.url,\n checkedOrigin: new URL(input.url).origin,\n formFactor: input.strategy === 'desktop' ? 'DESKTOP' : 'PHONE',\n },\n caveats: [\n 'Lighthouse is one controlled lab run; its score and timings can vary between runs and are not field Core Web Vitals.',\n 'Navigation Lighthouse uses Total Blocking Time as a lab responsiveness diagnostic; field INP comes from CrUX when available.',\n ],\n topActions: [],\n ...(input.includeRaw ? { raw: parsed } : {}),\n };\n if (parsed.runWarnings?.length) {\n report.caveats.push(`Lighthouse returned ${parsed.runWarnings.length} run warning${parsed.runWarnings.length === 1 ? '' : 's'}; inspect the compact lab insights or rerun before relying on the score.`);\n report.dataStatus = 'partial';\n }\n if (score === undefined) {\n report.dataStatus = 'partial';\n report.caveats.push('Lighthouse returned usable lab metrics without a numeric performance category score.');\n }\n return report;\n}\n//# sourceMappingURL=performance-lighthouse.js.map","import { createHash } from 'node:crypto';\nimport { fetchPage } from '../fetch/page-fetcher.js';\nimport { normalizeHttpUrl } from '../gsc/property-url.js';\nimport { getDb } from '../storage/database.js';\nimport { performanceActions } from './performance-analysis.js';\nimport { fetchCruxFieldData } from './performance-crux.js';\nimport { classifyLighthouseFailure, runLighthouse, } from './performance-lighthouse.js';\nexport * from './performance-crux.js';\nexport * from './performance-types.js';\nconst CACHE_TTL_MS = 86_400_000;\nfunction reportId(input) {\n return `perf_${createHash('sha256')\n .update(JSON.stringify({ methodology: 'performance-v2', ...input }))\n .digest('hex')\n .slice(0, 20)}`;\n}\nfunction cacheGet(id, now) {\n const row = getDb()\n .prepare('SELECT report_json FROM performance_reports WHERE id = ? AND expires_at > ?')\n .get(id, now);\n if (!row?.report_json)\n return undefined;\n try {\n const report = JSON.parse(row.report_json);\n return isStoredPerformanceReport(report) &&\n performanceReportIsCacheable({ report })\n ? report\n : undefined;\n }\n catch {\n return undefined;\n }\n}\nfunction cacheSet(report, now) {\n const stored = { ...report, raw: undefined };\n getDb()\n .prepare(`INSERT OR REPLACE INTO performance_reports\n (id, url, strategy, report_json, created_at, expires_at)\n VALUES (?, ?, ?, ?, ?, ?)`)\n .run(report.id, report.url, report.strategy, JSON.stringify(stored), Date.parse(report.generatedAt), now + CACHE_TTL_MS);\n}\nasync function fallbackReport(input) {\n const fetched = await fetchPage(input.url, {\n js: false,\n refresh: true,\n });\n const responseTime = fetched.diagnostics.durationMs;\n const report = {\n schemaVersion: 1,\n methodology: 'performance-v2',\n dataStatus: 'partial',\n id: input.id,\n url: input.url,\n finalUrl: fetched.finalUrl,\n strategy: input.strategy,\n generatedAt: input.generatedAt,\n cache: { status: input.cacheStatus, ttlHours: 24 },\n source: 'fetch-fallback',\n grade: 'unknown',\n headline: 'Lighthouse lab data was unavailable; fallback evidence is unscored HTTP transport data.',\n metrics: {\n fallbackFetchDuration: {\n value: responseTime,\n displayValue: `${responseTime}ms`,\n source: 'fetch-fallback',\n },\n },\n labInsights: [],\n labDataStatus: {\n provider: 'lighthouse',\n status: 'unavailable',\n reason: input.lighthouseFailure.reason,\n failureCode: input.lighthouseFailure.failureCode,\n },\n fallbackEvidence: {\n requestedUrl: input.url,\n finalUrl: fetched.finalUrl,\n httpStatus: fetched.status,\n blocked: fetched.diagnostics.blocked,\n redirectCount: fetched.diagnostics.redirectChain?.length ?? 0,\n },\n fieldDataStatus: {\n provider: 'crux',\n status: 'not_configured',\n reason: 'Field Core Web Vitals were not checked yet.',\n checkedUrl: input.url,\n checkedOrigin: new URL(input.url).origin,\n formFactor: input.strategy === 'desktop' ? 'DESKTOP' : 'PHONE',\n },\n caveats: [\n 'Fallback response duration includes the complete local fetch workflow and is not TTFB, Lighthouse, or Core Web Vitals.',\n 'Fallback mode does not measure JavaScript execution, LCP, CLS, TBT, or INP and never receives a performance score.',\n ...fetched.warnings,\n ],\n topActions: [],\n };\n return { ...report, topActions: performanceActions(report) };\n}\nfunction fieldHeadline(report) {\n const field = report.fieldData;\n if (!field)\n return report.headline;\n const scope = `${field.formFactor.toLowerCase()} ${field.scope}-level`;\n if (field.assessment.status === 'incomplete') {\n return `CrUX ${scope} field data is incomplete (${field.assessment.availableMetrics}/3 Core Web Vitals); ${report.headline}`;\n }\n return `CrUX ${scope} Core Web Vitals are ${field.assessment.status}; ${report.headline}`;\n}\nfunction isRecord(value) {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\nfunction isStoredPerformanceReport(value) {\n if (!isRecord(value))\n return false;\n const cache = value.cache;\n const fieldDataStatus = value.fieldDataStatus;\n const labDataStatus = value.labDataStatus;\n return (value.schemaVersion === 1 &&\n value.methodology === 'performance-v2' &&\n (value.dataStatus === 'complete' || value.dataStatus === 'partial') &&\n typeof value.id === 'string' &&\n typeof value.url === 'string' &&\n (value.strategy === 'mobile' || value.strategy === 'desktop') &&\n typeof value.generatedAt === 'string' &&\n isRecord(cache) &&\n typeof cache.ttlHours === 'number' &&\n (value.source === 'lighthouse' || value.source === 'fetch-fallback') &&\n typeof value.headline === 'string' &&\n isRecord(value.metrics) &&\n Array.isArray(value.labInsights) &&\n isRecord(labDataStatus) &&\n (labDataStatus.status === 'available' ||\n labDataStatus.status === 'unavailable') &&\n isRecord(fieldDataStatus) &&\n [\n 'not_configured',\n 'available',\n 'unavailable_no_coverage',\n 'request_failed',\n ].includes(String(fieldDataStatus.status)) &&\n Array.isArray(value.topActions) &&\n Array.isArray(value.caveats));\n}\nexport function performanceReportIsCacheable(input) {\n const { report } = input;\n return (!input.includeRaw &&\n !input.customLighthouse &&\n !input.customCrux &&\n report.dataStatus === 'complete' &&\n report.source === 'lighthouse' &&\n report.labDataStatus.status === 'available' &&\n report.fieldDataStatus.status !== 'request_failed' &&\n (report.fieldDataStatus.status !== 'available' ||\n (report.fieldData?.status === 'available' &&\n report.fieldData.assessment.status !== 'incomplete')) &&\n report.raw === undefined);\n}\nexport async function performanceAudit(input) {\n const strategy = input.strategy ?? 'mobile';\n const url = normalizeHttpUrl(input.url);\n const cruxApiKey = input.cruxApiKey ?? process.env.SEO_CRUX_API_KEY ?? process.env.CRUX_API_KEY;\n const id = reportId({\n url,\n strategy,\n fieldDataEnabled: Boolean(cruxApiKey),\n });\n const now = input.now?.() ?? new Date();\n const bypassCache = Boolean(input.refresh || input.includeRaw || input.lighthouseBin || input.cruxFetch);\n if (!bypassCache) {\n const cached = cacheGet(id, now.getTime());\n if (cached) {\n return { ...cached, cache: { ...cached.cache, status: 'hit' } };\n }\n }\n const generatedAt = now.toISOString();\n const cacheStatus = bypassCache ? 'bypass' : 'miss';\n let report;\n try {\n report = await runLighthouse({\n id,\n url,\n strategy,\n lighthouseBin: input.lighthouseBin,\n timeoutMs: input.timeoutMs,\n generatedAt,\n includeRaw: input.includeRaw,\n });\n report.cache.status = cacheStatus;\n }\n catch (error) {\n report = await fallbackReport({\n id,\n url,\n strategy,\n generatedAt,\n cacheStatus,\n lighthouseFailure: classifyLighthouseFailure(error),\n });\n }\n const fieldData = await fetchCruxFieldData({\n url,\n strategy,\n apiKey: cruxApiKey,\n fetchImpl: input.cruxFetch,\n timeoutMs: input.cruxTimeoutMs,\n });\n report = {\n ...report,\n ...(fieldData.fieldData ? { fieldData: fieldData.fieldData } : {}),\n fieldDataStatus: fieldData.status,\n caveats: [...new Set([...report.caveats, fieldData.caveat])],\n };\n report = {\n ...report,\n dataStatus: report.labDataStatus.status === 'unavailable' ||\n fieldData.status.status === 'request_failed' ||\n fieldData.fieldData?.assessment.status === 'incomplete'\n ? 'partial'\n : report.dataStatus,\n headline: fieldHeadline(report),\n topActions: performanceActions(report),\n };\n const cacheable = performanceReportIsCacheable({\n report,\n customCrux: Boolean(input.cruxFetch),\n customLighthouse: Boolean(input.lighthouseBin),\n includeRaw: Boolean(input.includeRaw),\n });\n if (cacheable)\n cacheSet(report, now.getTime());\n return report;\n}\n//# sourceMappingURL=performance.js.map","const QUERY_STOPWORDS = new Set([\n 'a',\n 'an',\n 'and',\n 'are',\n 'best',\n 'for',\n 'first',\n 'from',\n 'how',\n 'in',\n 'is',\n 'last',\n 'letter',\n 'letters',\n 'name',\n 'names',\n 'of',\n 'on',\n 'or',\n 'start',\n 'starts',\n 'starting',\n 'that',\n 'the',\n 'to',\n 'vs',\n 'with',\n]);\nconst THEME_STOPWORDS = new Set([\n ...QUERY_STOPWORDS,\n 'about',\n 'after',\n 'all',\n 'at',\n 'be',\n 'by',\n 'can',\n 'chart',\n 'check',\n 'day',\n 'days',\n 'did',\n 'do',\n 'does',\n 'each',\n 'ever',\n 'find',\n 'free',\n 'get',\n 'high',\n 'hour',\n 'hours',\n 'into',\n 'low',\n 'made',\n 'make',\n 'makes',\n 'many',\n 'month',\n 'months',\n 'much',\n 'near',\n 'new',\n 'page',\n 'pages',\n 'per',\n 'search',\n 'show',\n 'site',\n 'sites',\n 'than',\n 'they',\n 'this',\n 'time',\n 'times',\n 'today',\n 'tool',\n 'tools',\n 'top',\n 'what',\n 'when',\n 'where',\n 'year',\n 'years',\n 'you',\n 'your',\n]);\nexport function normalizePseoText(value) {\n return value\n .normalize('NFKC')\n .replace(/([\\p{L}\\p{N}])[’']([\\p{L}\\p{N}])/gu, '$1$2')\n .toLowerCase()\n .replace(/&/g, ' and ')\n .replace(/[^\\p{L}\\p{N}]+/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n}\nfunction isUsefulQueryTerm(term) {\n return term.length > 1 || /^\\d$/u.test(term) || /[^\\p{ASCII}]/u.test(term);\n}\nexport function pseoQueryTerms(query) {\n const terms = normalizePseoText(query)\n .split(' ')\n .filter((term) => isUsefulQueryTerm(term) && !QUERY_STOPWORDS.has(term));\n return [...new Set(terms)];\n}\nexport function canonicalPseoTerm(term) {\n if (!/^[a-z]+$/i.test(term))\n return term;\n if (['surname', 'surnames'].includes(term))\n return 'name';\n if (['beginning', 'begins', 'started'].includes(term))\n return 'start';\n if (/(as|is|ss|us)$/.test(term))\n return term;\n if (term.length > 4 && term.endsWith('ies')) {\n return `${term.slice(0, -3)}y`;\n }\n if (term.length > 4 && term.endsWith('xes'))\n return term.slice(0, -2);\n if (term.length > 4 && term.endsWith('es'))\n return term.slice(0, -1);\n if (term.length > 4 && term.endsWith('s'))\n return term.slice(0, -1);\n return term;\n}\nexport function pseoQueryThemeTerms(query) {\n return normalizePseoText(query)\n .split(' ')\n .filter((term) => isUsefulQueryTerm(term) && !THEME_STOPWORDS.has(term));\n}\nfunction queryPatternLabel(query) {\n const normalized = normalizePseoText(query);\n if (/\\b(vs|versus|compare|comparison)\\b/.test(normalized)) {\n return 'comparison';\n }\n if (/\\balternative|alternatives\\b/.test(normalized))\n return 'alternatives';\n if (/\\bwithout (account|login|signing|sign in)\\b/.test(normalized)) {\n return 'no-login modifier';\n }\n if (/\\b(export|download|save|convert)\\b/.test(normalized)) {\n return 'workflow/action';\n }\n if (/\\bmeaning|origin|history\\b/.test(normalized))\n return 'meaning/origin';\n if (/\\brare|rarity|popular|popularity\\b/.test(normalized)) {\n return 'rarity/popularity';\n }\n if (/\\bhow many|number of|people with|people have\\b/.test(normalized)) {\n return 'count/statistic';\n }\n if (/\\b(starting with|starts with|start with|beginning with|letter)\\b/.test(normalized)) {\n return 'list/facet';\n }\n if (/\\b(price|pricing|cost|fee)\\b/.test(normalized))\n return 'pricing';\n if (/\\breview|reviews|reddit|forum|community\\b/.test(normalized)) {\n return 'reviews/community';\n }\n if (/\\bguide|docs|documentation|api\\b/.test(normalized)) {\n return 'docs/how-to';\n }\n return 'general';\n}\nfunction queryThemeCandidates(query) {\n const terms = pseoQueryThemeTerms(query).map(canonicalPseoTerm);\n const candidates = [];\n for (const size of [3, 2]) {\n for (let index = 0; index <= terms.length - size; index += 1) {\n candidates.push(terms.slice(index, index + size).join(' '));\n }\n }\n candidates.push(...terms);\n return [...new Set(candidates)];\n}\nfunction learnedQueryThemeLabels(rows) {\n const phraseStats = new Map();\n const queryCandidates = new Map();\n const rowsByQuery = new Map();\n for (const row of rows) {\n rowsByQuery.set(row.query, (rowsByQuery.get(row.query) ?? 0) + row.impressions);\n }\n for (const [query, impressions] of rowsByQuery) {\n const candidates = queryThemeCandidates(query);\n queryCandidates.set(query, candidates);\n for (const candidate of candidates) {\n const existing = phraseStats.get(candidate) ?? {\n queryCount: 0,\n impressions: 0,\n };\n existing.queryCount += 1;\n existing.impressions += impressions;\n phraseStats.set(candidate, existing);\n }\n }\n const totalImpressions = [...rowsByQuery.values()].reduce((sum, impressions) => sum + impressions, 0);\n const scoredPhrases = [...phraseStats.entries()]\n .filter(([, stats]) => stats.queryCount >= 2)\n .filter(([phrase, stats]) => phrase.includes(' ') || stats.impressions >= totalImpressions * 0.05)\n .sort((a, b) => {\n const impressions = b[1].impressions - a[1].impressions;\n if (impressions)\n return impressions;\n return b[0].length - a[0].length;\n });\n const labels = new Map();\n for (const [query, candidates] of queryCandidates) {\n const match = scoredPhrases.find(([phrase]) => candidates.includes(phrase));\n if (match)\n labels.set(query, `theme: ${match[0]}`);\n }\n return labels;\n}\nexport function pseoQueryPatterns(rows) {\n const patterns = new Map();\n const patternQueries = new Map();\n const learnedThemes = learnedQueryThemeLabels(rows);\n for (const row of rows) {\n const intentLabel = queryPatternLabel(row.query);\n const label = intentLabel === 'general'\n ? (learnedThemes.get(row.query) ?? intentLabel)\n : intentLabel;\n const existing = patterns.get(label) ?? {\n label,\n queryCount: 0,\n clicks: 0,\n impressions: 0,\n examples: [],\n };\n const queries = patternQueries.get(label) ?? new Set();\n queries.add(row.query);\n patternQueries.set(label, queries);\n existing.queryCount = queries.size;\n existing.clicks += row.clicks;\n existing.impressions += row.impressions;\n if (existing.examples.length < 3 &&\n !existing.examples.includes(row.query)) {\n existing.examples.push(row.query);\n }\n patterns.set(label, existing);\n }\n return [...patterns.values()]\n .sort((a, b) => b.impressions - a.impressions)\n .slice(0, 5);\n}\n//# sourceMappingURL=query-insights.js.map","import { canonicalPseoTerm, normalizePseoText, pseoQueryPatterns, pseoQueryTerms, pseoQueryThemeTerms, } from './query-insights.js';\nimport { parsePseoPath } from './templates.js';\nexport function comparePseoText(left, right) {\n const leftPoints = [...left].map((value) => value.codePointAt(0) ?? 0);\n const rightPoints = [...right].map((value) => value.codePointAt(0) ?? 0);\n for (let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index++) {\n const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);\n if (difference)\n return difference;\n }\n return leftPoints.length - rightPoints.length;\n}\nexport function validPseoHttpUrl(value) {\n try {\n return ['http:', 'https:'].includes(new URL(value).protocol);\n }\n catch {\n return false;\n }\n}\nfunction validMetric(value, minimum = 0) {\n return Number.isFinite(value) && value >= minimum;\n}\nexport function validPseoQueryPageRow(row) {\n return (Boolean(row.query.trim()) &&\n validPseoHttpUrl(row.page) &&\n validMetric(row.clicks) &&\n validMetric(row.impressions) &&\n row.clicks <= row.impressions &&\n validMetric(row.position, 1));\n}\nexport function validPseoPageRow(row) {\n return (validPseoHttpUrl(row.page) &&\n validMetric(row.clicks) &&\n validMetric(row.impressions) &&\n row.clicks <= row.impressions &&\n validMetric(row.position, 1));\n}\nfunction weightedPosition(rows) {\n const impressions = rows.reduce((sum, row) => sum + row.impressions, 0);\n if (!impressions)\n return 0;\n return (rows.reduce((sum, row) => sum + row.position * row.impressions, 0) /\n impressions);\n}\nexport function aggregatePseoPageRows(rows) {\n const pages = new Map();\n for (const row of rows) {\n const previous = pages.get(row.page);\n pages.set(row.page, {\n page: row.page,\n clicks: (previous?.clicks ?? 0) + row.clicks,\n impressions: (previous?.impressions ?? 0) + row.impressions,\n position: previous ? weightedPosition([previous, row]) : row.position,\n });\n }\n return [...pages.values()];\n}\nexport function aggregatePseoQueryPageRows(rows) {\n const pairs = new Map();\n for (const row of rows) {\n const key = `${row.query}\\u0000${row.page}`;\n const previous = pairs.get(key);\n pairs.set(key, {\n query: row.query,\n page: row.page,\n clicks: (previous?.clicks ?? 0) + row.clicks,\n impressions: (previous?.impressions ?? 0) + row.impressions,\n position: previous ? weightedPosition([previous, row]) : row.position,\n });\n }\n return [...pairs.values()];\n}\nfunction termCoverage(query, text) {\n const terms = pseoQueryTerms(query).map(canonicalPseoTerm);\n if (!terms.length)\n return { coverage: 0, missingTerms: [] };\n const textTerms = new Set(pseoQueryTerms(normalizePseoText(text ?? '')).map(canonicalPseoTerm));\n const matched = terms.filter((term) => textTerms.has(term));\n return {\n coverage: matched.length / terms.length,\n missingTerms: terms.filter((term) => !textTerms.has(term)),\n };\n}\nexport function pseoQueryCoverage(input) {\n const title = termCoverage(input.query, input.title);\n const h1 = termCoverage(input.query, input.h1);\n const body = termCoverage(input.query, input.body);\n const classification = body.coverage < 0.75\n ? 'body-term-review'\n : title.coverage < 0.75 || h1.coverage < 0.75\n ? 'serp-framing-review'\n : 'covered';\n return {\n method: 'literal-query-term-presence-v1',\n heuristic: true,\n query: input.query,\n classification,\n titleCoverage: title.coverage,\n h1Coverage: h1.coverage,\n bodyCoverage: body.coverage,\n missingTerms: body.missingTerms.slice(0, 8),\n };\n}\nfunction pathVariableTerms(url, cluster) {\n const parts = parsePseoPath(url);\n const terms = cluster.shape.variableSegments.flatMap((segment) => {\n const value = parts[segment.index];\n return value ? pseoQueryThemeTerms(value) : [];\n });\n return [...new Set(terms.map(canonicalPseoTerm))];\n}\nfunction entityFitForRows(rows, cluster) {\n let checkedQueries = 0;\n let matchedQueries = 0;\n let checkedImpressions = 0;\n let matchedImpressions = 0;\n const weakExamples = [];\n for (const row of rows) {\n const pathTerms = pathVariableTerms(row.page, cluster);\n if (!pathTerms.length)\n continue;\n const queryTerms = new Set(pseoQueryTerms(row.query).map(canonicalPseoTerm));\n checkedQueries += 1;\n checkedImpressions += row.impressions;\n if (pathTerms.some((term) => queryTerms.has(term))) {\n matchedQueries += 1;\n matchedImpressions += row.impressions;\n }\n else {\n weakExamples.push({\n url: row.page,\n query: row.query,\n pathTerms: pathTerms.slice(0, 6),\n impressions: row.impressions,\n });\n }\n }\n return {\n method: 'any-path-variable-term-v1',\n heuristic: true,\n checkedQueries,\n matchedQueries,\n impressionShare: checkedImpressions\n ? matchedImpressions / checkedImpressions\n : 0,\n weakExamples: weakExamples\n .sort((left, right) => right.impressions - left.impressions ||\n comparePseoText(left.query, right.query) ||\n comparePseoText(left.url, right.url))\n .slice(0, 5),\n };\n}\nexport function pseoMetricsForRows(input) {\n const clicks = input.pageRows.reduce((sum, row) => sum + row.clicks, 0);\n const impressions = input.pageRows.reduce((sum, row) => sum + row.impressions, 0);\n const byQuery = new Map();\n for (const row of input.queryRows) {\n const previous = byQuery.get(row.query);\n byQuery.set(row.query, {\n query: row.query,\n clicks: (previous?.clicks ?? 0) + row.clicks,\n impressions: (previous?.impressions ?? 0) + row.impressions,\n position: previous ? weightedPosition([previous, row]) : row.position,\n });\n }\n return {\n clicks,\n impressions,\n ctr: impressions ? clicks / impressions : 0,\n position: weightedPosition(input.pageRows),\n impressionsPerUrl: input.cluster.urlCount\n ? impressions / input.cluster.urlCount\n : 0,\n clicksPerUrl: input.cluster.urlCount ? clicks / input.cluster.urlCount : 0,\n retainedQueryImpressions: input.queryRows.reduce((sum, row) => sum + row.impressions, 0),\n queryCount: byQuery.size,\n pageCountWithGsc: input.pageRows.length,\n zeroClickImpressions: input.pageRows\n .filter((row) => row.clicks === 0)\n .reduce((sum, row) => sum + row.impressions, 0),\n entityFit: entityFitForRows(input.queryRows, input.cluster),\n queryPatterns: pseoQueryPatterns(input.queryRows),\n topQueries: [...byQuery.values()]\n .sort((left, right) => right.impressions - left.impressions ||\n right.clicks - left.clicks ||\n comparePseoText(left.query, right.query))\n .slice(0, 5),\n };\n}\n//# sourceMappingURL=row-analysis.js.map","import { countLabel } from '../../phrasing.js';\nimport { normalizePseoText } from './query-insights.js';\nimport { comparePseoText } from './row-analysis.js';\nfunction median(values) {\n if (!values.length)\n return undefined;\n const sorted = [...values].sort((left, right) => left - right);\n const middle = Math.floor(sorted.length / 2);\n if (sorted.length % 2)\n return sorted[middle];\n return ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2;\n}\nfunction duplicateAffectedCount(values) {\n const counts = new Map();\n for (const value of values) {\n const normalized = normalizePseoText(value ?? '');\n if (normalized)\n counts.set(normalized, (counts.get(normalized) ?? 0) + 1);\n }\n return [...counts.values()].reduce((sum, count) => sum + (count > 1 ? count : 0), 0);\n}\nexport function pseoIndexStatus(verdict) {\n if (verdict === 'PASS')\n return 'indexed';\n if (verdict === 'NEUTRAL')\n return 'excluded';\n if (verdict === 'FAIL')\n return 'invalid';\n return 'unknown';\n}\nexport function selectedPseoSampleUrls(urls, pageRows, limit) {\n if (!limit)\n return [];\n const demand = new Map(pageRows.map((row) => [row.page, row]));\n const ranked = [...urls].sort((left, right) => {\n const leftRow = demand.get(left);\n const rightRow = demand.get(right);\n return ((rightRow?.clicks ?? 0) - (leftRow?.clicks ?? 0) ||\n (rightRow?.impressions ?? 0) - (leftRow?.impressions ?? 0) ||\n comparePseoText(left, right));\n });\n const indexes = [0, ranked.length - 1, Math.floor((ranked.length - 1) / 2)];\n const selected = [];\n for (const index of indexes) {\n const url = ranked[index];\n if (url && !selected.includes(url))\n selected.push(url);\n if (selected.length >= limit)\n return selected;\n }\n for (const url of ranked) {\n if (!selected.includes(url))\n selected.push(url);\n if (selected.length >= limit)\n break;\n }\n return selected;\n}\nexport function summarizePseoCrawl(samples, requested) {\n const succeeded = samples.filter((sample) => sample.technicalStatus !== 'fetch-error').length;\n const usableSamples = samples.filter((sample) => ['ok', 'redirected'].includes(sample.technicalStatus));\n const wordCounts = usableSamples\n .map((sample) => sample.wordCount)\n .filter((value) => value !== undefined);\n const middle = median(wordCounts);\n return {\n requested,\n attempted: samples.length,\n succeeded,\n failed: samples.length - succeeded,\n usable: usableSamples.length,\n samples,\n wordCount: wordCounts.length && middle !== undefined\n ? {\n min: Math.min(...wordCounts),\n median: middle,\n max: Math.max(...wordCounts),\n }\n : undefined,\n medianWordCount: middle,\n weakQueryCoverage: usableSamples.filter((sample) => sample.queryCoverage?.classification === 'body-term-review').length,\n duplicateTitles: duplicateAffectedCount(usableSamples.map((sample) => sample.title)),\n duplicateMetaDescriptions: duplicateAffectedCount(usableSamples.map((sample) => sample.metaDescription)),\n blockedOrFailed: samples.filter((sample) => !['ok', 'redirected'].includes(sample.technicalStatus)).length,\n };\n}\nexport function summarizePseoInspection(samples, requested) {\n const successful = samples.filter((sample) => !sample.warning);\n const indexed = successful.filter((sample) => sample.indexStatus === 'indexed').length;\n const notIndexed = successful.filter((sample) => ['excluded', 'invalid'].includes(sample.indexStatus)).length;\n return {\n requested,\n attempted: samples.length,\n succeeded: successful.length,\n failed: samples.length - successful.length,\n samples,\n indexed,\n notIndexed,\n unknown: successful.length - indexed - notIndexed,\n warnings: samples.length - successful.length,\n };\n}\nexport function assessPseoTemplate(template) {\n const conclusive = template.inspection.indexed + template.inspection.notIndexed;\n if (template.inspection.notIndexed) {\n if (conclusive === 1 ||\n template.inspection.notIndexed / conclusive >= 0.5) {\n return {\n verdict: 'index-risk',\n confidence: conclusive >= 2 ? 'medium' : 'low',\n };\n }\n }\n if (template.crawl.blockedOrFailed) {\n if (template.crawl.attempted === 1 ||\n template.crawl.blockedOrFailed / template.crawl.attempted >= 0.5) {\n return {\n verdict: 'crawl-risk',\n confidence: template.crawl.attempted >= 2 ? 'medium' : 'low',\n };\n }\n }\n if (template.crawl.usable >= 3 &&\n (template.crawl.weakQueryCoverage / template.crawl.usable >= 0.5 ||\n template.crawl.duplicateTitles >= 2 ||\n template.crawl.duplicateMetaDescriptions >= 2)) {\n return { verdict: 'content-review', confidence: 'medium' };\n }\n if (template.metrics.impressions > 0 &&\n (template.metrics.position > 8 ||\n (template.metrics.position <= 10 && template.metrics.ctr < 0.01) ||\n (template.metrics.entityFit.checkedQueries >= 10 &&\n template.metrics.entityFit.impressionShare < 0.35))) {\n return { verdict: 'opportunity', confidence: 'low' };\n }\n if (conclusive >= 2 &&\n template.inspection.indexed === conclusive &&\n template.crawl.usable >= 2 &&\n template.crawl.blockedOrFailed === 0) {\n return { verdict: 'healthy', confidence: 'medium' };\n }\n if (template.metrics.impressions > 0) {\n return { verdict: 'inconclusive', confidence: 'low' };\n }\n return { verdict: 'no-data', confidence: 'low' };\n}\nexport function pseoTemplateEvidence(template) {\n const evidence = [];\n if (template.metrics.impressions) {\n evidence.push(`${Math.round(template.metrics.impressions).toLocaleString('en-GB')} impressions from ${countLabel(template.metrics.pageCountWithGsc, 'retained GSC page row')}`);\n }\n if (template.inspection.attempted) {\n const untested = Math.max(0, template.population.discoveredUrls - template.inspection.attempted);\n evidence.push(`${template.inspection.indexed}/${template.inspection.attempted} sampled URLs returned exact PASS verdicts; ${untested} discovered URLs were not inspected`);\n }\n if (template.crawl.attempted) {\n const untested = Math.max(0, template.population.discoveredUrls - template.crawl.attempted);\n evidence.push(`${template.crawl.usable}/${template.crawl.attempted} sampled URLs returned usable 2xx crawl evidence; ${untested} discovered URLs were not sampled`);\n }\n if (template.crawl.weakQueryCoverage) {\n evidence.push(`${countLabel(template.crawl.weakQueryCoverage, 'usable sample')} need literal query-term review`);\n }\n if (template.crawl.duplicateTitles) {\n evidence.push(`${countLabel(template.crawl.duplicateTitles, 'sampled URL')} share duplicate titles`);\n }\n return evidence;\n}\nexport function pseoTemplateRecommendation(template) {\n if (template.verdict === 'index-risk') {\n return `${countLabel(template.inspection.notIndexed, 'inspected URL')} returned an exact excluded or invalid verdict as of Google's last indexed crawl. Review their robots/noindex, canonical, fetch, and sitemap evidence; do not generalise the result to ${countLabel(template.population.untestedUrls, 'untested URL')}.`;\n }\n if (template.verdict === 'crawl-risk') {\n return `${countLabel(template.crawl.blockedOrFailed, 'sampled URL')} returned objective HTTP, robots, noindex, canonical, or fetch failures. Fix those sampled URLs first, then rerun before assessing content.`;\n }\n if (template.verdict === 'content-review') {\n return `Review the sampled pages for distinct utility and intent fit. Literal term coverage and repeated metadata are heuristics, not proof that pages need more words or violate Google's policies.`;\n }\n if (template.verdict === 'opportunity') {\n return `Retained GSC page rows show search visibility but weak average position, CTR, or entity-fit heuristics. Inspect the top queries and sampled pages before changing this template.`;\n }\n if (template.verdict === 'healthy') {\n return `No material issue was found in the bounded crawl and URL Inspection samples. Keep monitoring; this is sample evidence, not a guarantee for every URL.`;\n }\n if (template.verdict === 'inconclusive') {\n return `Retained GSC rows show search visibility, but technical sampling is not strong enough for a health verdict. Add bounded crawl and URL Inspection samples.`;\n }\n return `No retained page-level Search Analytics evidence was found for this discovered template. That is not proof of zero demand or low quality; inspect representative URLs and canonical attribution.`;\n}\n//# sourceMappingURL=assessment.js.map","import { deriveBrandTerms, shouldExcludeBrandQuery } from '../../brand.js';\nimport { isLowActionabilityQuery } from '../query-quality.js';\nimport { assessPseoTemplate, pseoTemplateEvidence, pseoTemplateRecommendation, selectedPseoSampleUrls, summarizePseoCrawl, summarizePseoInspection, } from './assessment.js';\nimport { aggregatePseoPageRows, aggregatePseoQueryPageRows, comparePseoText, pseoMetricsForRows, validPseoHttpUrl, validPseoPageRow, validPseoQueryPageRow, } from './row-analysis.js';\nimport { clusterPseoTemplates, templateForUrl } from './templates.js';\nexport { pseoIndexStatus } from './assessment.js';\nexport { pseoQueryCoverage } from './row-analysis.js';\nconst SAMPLE_SELECTION = 'page-demand-stratified-url-v1';\nconst TEMPLATE_ORDER = 'page-impressions-clicks-url-count-signature-v1';\nfunction retainedQueryRows(input) {\n const invalid = input.queryPageRows.filter((row) => !validPseoQueryPageRow(row)).length;\n const valid = input.queryPageRows.filter(validPseoQueryPageRow);\n const lowActionability = valid.filter((row) => isLowActionabilityQuery(row.query)).length;\n const actionable = valid.filter((row) => !isLowActionabilityQuery(row.query));\n const classified = actionable.map((row) => ({\n row,\n isBrand: shouldExcludeBrandQuery({\n query: row.query,\n siteUrl: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n }),\n }));\n return {\n rows: aggregatePseoQueryPageRows(classified.filter((item) => !item.isBrand).map((item) => item.row)),\n invalid,\n lowActionability,\n brand: classified.filter((item) => item.isBrand).length,\n };\n}\nfunction groupRowsByTemplate(rows, clusters) {\n const grouped = new Map();\n for (const row of rows) {\n const signature = templateForUrl(row.page, clusters);\n grouped.set(signature, [...(grouped.get(signature) ?? []), row]);\n }\n return grouped;\n}\nfunction buildTemplates(input) {\n const clusters = clusterPseoTemplates(input.allUrls, {\n minUrls: input.dataset.minimumTemplateUrls,\n minShare: input.dataset.minimumTemplateShare,\n limit: Math.max(1, input.allUrls.length),\n sampleSize: 0,\n });\n const urlsByTemplate = new Map();\n for (const url of input.allUrls) {\n const signature = templateForUrl(url, clusters);\n urlsByTemplate.set(signature, [\n ...(urlsByTemplate.get(signature) ?? []),\n url,\n ]);\n }\n const pageRowsByTemplate = groupRowsByTemplate(input.pageRows, clusters);\n const queryRowsByTemplate = groupRowsByTemplate(input.queryRows, clusters);\n const ranked = clusters\n .map((cluster) => {\n const pageRows = pageRowsByTemplate.get(cluster.signature) ?? [];\n const queryRows = queryRowsByTemplate.get(cluster.signature) ?? [];\n return {\n cluster,\n urls: urlsByTemplate.get(cluster.signature) ?? [],\n pageRows,\n metrics: pseoMetricsForRows({ pageRows, queryRows, cluster }),\n };\n })\n .filter((item) => item.metrics.impressions >= input.dataset.minimumTemplateImpressions)\n .sort((left, right) => right.metrics.impressions - left.metrics.impressions ||\n right.metrics.clicks - left.metrics.clicks ||\n right.cluster.urlCount - left.cluster.urlCount ||\n comparePseoText(left.cluster.signature, right.cluster.signature));\n const crawlsByUrl = new Map((input.dataset.crawlSamples ?? []).map((sample) => [sample.url, sample]));\n const inspectionsByUrl = new Map((input.dataset.inspectionSamples ?? []).map((sample) => [\n sample.url,\n sample,\n ]));\n const templates = ranked\n .slice(0, input.dataset.templateLimit)\n .map((item) => {\n const sampleLimit = Math.max(input.dataset.crawlSamplesPerTemplate, input.dataset.inspectionSamplesPerTemplate);\n const sampleUrls = selectedPseoSampleUrls(item.urls, item.pageRows, sampleLimit);\n const crawl = summarizePseoCrawl(sampleUrls\n .slice(0, input.dataset.crawlSamplesPerTemplate)\n .map((url) => crawlsByUrl.get(url))\n .filter((sample) => Boolean(sample)), input.dataset.crawlSamplesPerTemplate);\n const inspection = summarizePseoInspection(sampleUrls\n .slice(0, input.dataset.inspectionSamplesPerTemplate)\n .map((url) => inspectionsByUrl.get(url))\n .filter((sample) => Boolean(sample)), input.dataset.inspectionSamplesPerTemplate);\n const base = {\n ...item.cluster,\n sampleUrls,\n population: {\n discoveredUrls: item.cluster.urlCount,\n gscVisibleUrls: item.pageRows.length,\n untestedUrls: Math.max(0, item.cluster.urlCount -\n Math.max(crawl.attempted, inspection.attempted)),\n sampleSelection: SAMPLE_SELECTION,\n },\n metrics: item.metrics,\n crawl,\n inspection,\n evidence: [],\n verdict: 'inconclusive',\n confidence: 'low',\n recommendation: '',\n };\n const assessed = { ...base, ...assessPseoTemplate(base) };\n return {\n ...assessed,\n evidence: pseoTemplateEvidence(assessed),\n recommendation: pseoTemplateRecommendation(assessed),\n };\n });\n return { templates, eligibleTemplates: ranked.length };\n}\nexport function buildPseoAuditReportFromRows(input) {\n const querySelection = retainedQueryRows(input);\n const invalidPageRows = input.pageRows.filter((row) => !validPseoPageRow(row)).length;\n const pageRows = aggregatePseoPageRows(input.pageRows.filter(validPseoPageRow));\n const sitemapUrls = [...new Set(input.sitemapUrls ?? [])]\n .filter(validPseoHttpUrl)\n .sort(comparePseoText);\n const allUrls = [\n ...new Set([\n ...sitemapUrls,\n ...pageRows.map((row) => row.page),\n ...querySelection.rows.map((row) => row.page),\n ]),\n ].sort(comparePseoText);\n const { templates, eligibleTemplates } = buildTemplates({\n dataset: input,\n allUrls,\n pageRows,\n queryRows: querySelection.rows,\n });\n const warnings = [...new Set(input.warnings ?? [])];\n const pageRowsPossiblyTruncated = input.pageRowsFetched >= input.maxRowsPerRequest;\n const queryPageRowsPossiblyTruncated = input.queryPageRowsFetched >= input.maxRowsPerRequest;\n const crawlAttempts = templates.reduce((sum, template) => sum + template.crawl.attempted, 0);\n const crawledUrls = templates.reduce((sum, template) => sum + template.crawl.usable, 0);\n const inspectionAttempts = templates.reduce((sum, template) => sum + template.inspection.attempted, 0);\n const inspectedUrls = templates.reduce((sum, template) => sum + template.inspection.succeeded, 0);\n const hasInput = input.queryPageRows.length > 0 ||\n input.pageRows.length > 0 ||\n sitemapUrls.length > 0;\n const hasPartialEvidence = pageRowsPossiblyTruncated ||\n queryPageRowsPossiblyTruncated ||\n querySelection.invalid > 0 ||\n invalidPageRows > 0 ||\n warnings.length > 0 ||\n crawlAttempts > crawledUrls ||\n inspectionAttempts > inspectedUrls;\n const dataStatus = !hasInput\n ? 'empty'\n : !allUrls.length\n ? 'filtered'\n : hasPartialEvidence\n ? 'partial'\n : 'complete';\n const brandTerms = input.brandTerms?.length\n ? input.brandTerms\n : deriveBrandTerms({ siteUrl: input.site });\n return {\n schemaVersion: 1,\n methodology: 'pseo-audit-v2',\n site: input.site,\n generatedAt: input.generatedAt,\n rangeDays: input.days,\n range: input.range,\n dataStatus,\n source: {\n searchAnalytics: {\n pageRows: input.pageRowsFetched,\n queryPageRows: input.queryPageRowsFetched,\n maxRowsPerRequest: input.maxRowsPerRequest,\n pageRowsPossiblyTruncated,\n queryPageRowsPossiblyTruncated,\n dimensions: { page: ['page'], queryPage: ['query', 'page'] },\n searchType: 'web',\n dataState: 'final',\n aggregation: 'auto',\n },\n sitemaps: {\n requested: input.sitemapsRequested,\n discoveredUrls: sitemapUrls.length,\n maxUrlsPerSitemap: input.maxUrlsPerSitemap,\n },\n },\n selection: {\n inputQueryPageRows: input.queryPageRows.length,\n invalidQueryPageRows: querySelection.invalid,\n lowActionabilityRows: querySelection.lowActionability,\n brandRows: querySelection.brand,\n retainedQueryPageRows: querySelection.rows.length,\n inputPageRows: input.pageRows.length,\n invalidPageRows,\n retainedPageRows: pageRows.length,\n discoveredUrls: allUrls.length,\n eligibleTemplates,\n returnedTemplates: templates.length,\n templateLimit: input.templateLimit,\n minimumTemplateUrls: input.minimumTemplateUrls,\n minimumTemplateShare: input.minimumTemplateShare,\n minimumTemplateImpressions: input.minimumTemplateImpressions,\n templateOrder: TEMPLATE_ORDER,\n },\n summary: {\n sitemapUrls: sitemapUrls.length,\n gscPages: pageRows.length,\n templates: templates.length,\n clicks: pageRows.reduce((sum, row) => sum + row.clicks, 0),\n impressions: pageRows.reduce((sum, row) => sum + row.impressions, 0),\n crawlAttempts,\n crawledUrls,\n crawlFailures: crawlAttempts - crawledUrls,\n inspectionAttempts,\n inspectedUrls,\n inspectionFailures: inspectionAttempts - inspectedUrls,\n },\n caveats: [\n ...(input.caveats ?? []),\n `Search Analytics range: ${input.range.startDate} through ${input.range.endDate}, using finalized web data.`,\n 'Clicks, impressions, CTR, and position use retained page-dimension rows; Search Console does not guarantee every row or complete totals.',\n 'Query patterns and examples use retained query/page rows, which omit anonymized and lower-ranked data.',\n `Brand queries: ${input.includeBrand ? 'included' : `excluded using ${brandTerms.join(', ') || 'no terms'}`}.`,\n `Template detection requires at least ${input.minimumTemplateUrls} URLs and ${(input.minimumTemplateShare * 100).toFixed(2)}% of discovered URLs.`,\n `Samples use ${SAMPLE_SELECTION}; observations apply to sampled URLs, not every URL in a template.`,\n \"URL Inspection reports Google's indexed snapshot for a specific URL; an exact PASS verdict does not guarantee current search appearance.\",\n 'Word counts are descriptive only. This report has no preferred or minimum word-count rule.',\n 'Literal term coverage and path entity fit are review heuristics, not Google ranking factors or scaled-content policy verdicts.',\n ],\n templates,\n warnings,\n };\n}\nexport function pseoSampleUrls(report) {\n return {\n crawl: report.templates.flatMap((template) => template.sampleUrls.slice(0, template.crawl.requested)),\n inspection: report.templates.flatMap((template) => template.sampleUrls.slice(0, template.inspection.requested)),\n };\n}\n//# sourceMappingURL=analysis.js.map","import { shouldExcludeBrandQuery } from '../../brand.js';\nimport { SeoError } from '../../errors.js';\nimport { extractPage } from '../../extract/page-extractor.js';\nimport { fetchPage } from '../../fetch/page-fetcher.js';\nimport { inspectUrl } from '../../gsc/client/inspection.js';\nimport { querySearchAnalytics } from '../../gsc/client.js';\nimport { countLabel } from '../../phrasing.js';\nimport { effectiveRobotsDirectives } from '../../robots-directives.js';\nimport { fetchSitemapUrls } from '../monitoring/sitemaps.js';\nimport { isLowActionabilityQuery } from '../query-quality.js';\nimport { defaultDateRange, integerOption, } from '../site-diagnostics/quick-wins-report-input.js';\nimport { buildPseoAuditReportFromRows, pseoIndexStatus, pseoQueryCoverage, pseoSampleUrls, } from './analysis.js';\nexport { buildPseoAuditReportFromRows, pseoIndexStatus } from './analysis.js';\nconst MAX_GSC_ROWS = 50_000;\nconst DEFAULT_SITEMAP_URLS = 50_000;\nconst defaultDependencies = {\n searchAnalytics: querySearchAnalytics,\n fetchPage,\n inspectUrl,\n fetchSitemapUrls,\n now: () => new Date(),\n};\nfunction numericOption(input) {\n const value = input.value ?? input.fallback;\n if (!Number.isFinite(value) ||\n value < input.minimum ||\n value > input.maximum) {\n throw new SeoError('INVALID_INPUT', `${input.label} must be between ${input.minimum} and ${input.maximum}.`);\n }\n return value;\n}\nexport function pseoAuditOptions(input) {\n const days = integerOption({\n value: input.days,\n fallback: 28,\n minimum: 1,\n maximum: 548,\n label: 'days',\n });\n const templateLimit = integerOption({\n value: input.templateLimit,\n fallback: 25,\n minimum: 1,\n maximum: 100,\n label: 'templateLimit',\n });\n const minimumTemplateUrls = integerOption({\n value: input.minimumTemplateUrls,\n fallback: 3,\n minimum: 2,\n maximum: 100,\n label: 'minimumTemplateUrls',\n });\n const crawlSamples = integerOption({\n value: input.crawlSamples,\n fallback: 0,\n minimum: 0,\n maximum: 10,\n label: 'crawlSamples',\n });\n const inspectSamples = integerOption({\n value: input.inspectSamples,\n fallback: 0,\n minimum: 0,\n maximum: 10,\n label: 'inspectSamples',\n });\n const maxSitemapUrls = integerOption({\n value: input.maxSitemapUrls,\n fallback: DEFAULT_SITEMAP_URLS,\n minimum: 1,\n maximum: 100_000,\n label: 'maxSitemapUrls',\n });\n const minimumTemplateImpressions = numericOption({\n value: input.minimumTemplateImpressions,\n fallback: 0,\n minimum: 0,\n maximum: 1_000_000_000,\n label: 'minimumTemplateImpressions',\n });\n const minimumTemplateShare = numericOption({\n value: input.minimumTemplateShare,\n fallback: 0,\n minimum: 0,\n maximum: 1,\n label: 'minimumTemplateShare',\n });\n if ((input.sitemaps?.length ?? 0) > 20) {\n throw new SeoError('INVALID_INPUT', 'sitemaps must contain at most 20 URLs.');\n }\n for (const sitemap of input.sitemaps ?? []) {\n try {\n if (!['http:', 'https:'].includes(new URL(sitemap).protocol))\n throw new Error();\n }\n catch {\n throw new SeoError('INVALID_INPUT', `Invalid sitemap URL: ${sitemap}`);\n }\n }\n if (input.brandTerms &&\n (input.brandTerms.length > 20 ||\n input.brandTerms.some((term) => !term.trim() || term.length > 200))) {\n throw new SeoError('INVALID_INPUT', 'brandTerms must contain at most 20 non-empty terms of 200 characters or fewer.');\n }\n return {\n ...input,\n days,\n templateLimit,\n minimumTemplateUrls,\n minimumTemplateShare,\n minimumTemplateImpressions,\n crawlSamples,\n inspectSamples,\n maxSitemapUrls,\n };\n}\nfunction topQueryByUrl(rows, input) {\n const best = new Map();\n for (const row of rows) {\n if (isLowActionabilityQuery(row.query) ||\n shouldExcludeBrandQuery({\n query: row.query,\n siteUrl: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n })) {\n continue;\n }\n const score = row.impressions + row.clicks * 10;\n const previous = best.get(row.page);\n if (!previous || score > previous.score) {\n best.set(row.page, { query: row.query, score });\n }\n }\n return new Map([...best].map(([url, value]) => [url, value.query]));\n}\nfunction absoluteUrl(value, base) {\n if (!value)\n return undefined;\n try {\n const url = new URL(value, base);\n url.hash = '';\n return url.toString();\n }\n catch {\n return undefined;\n }\n}\nfunction crawlTechnicalStatus(input) {\n if (input.fetched.diagnostics.blocked ||\n input.fetched.robotsTxt?.allowed === false) {\n return 'blocked';\n }\n if (input.fetched.status < 200 || input.fetched.status >= 300) {\n return 'http-error';\n }\n if (effectiveRobotsDirectives(input).has('noindex')) {\n return 'noindex';\n }\n const canonical = absoluteUrl(input.canonical, input.fetched.finalUrl);\n const finalUrl = absoluteUrl(input.fetched.finalUrl, input.fetched.finalUrl);\n if (canonical && finalUrl && canonical !== finalUrl) {\n return 'canonical-mismatch';\n }\n if (input.requestedUrl !== input.fetched.finalUrl ||\n (input.fetched.diagnostics.redirectChain?.length ?? 0) > 0) {\n return 'redirected';\n }\n return 'ok';\n}\nasync function crawlSample(input) {\n try {\n const fetched = await input.fetch(input.url, {\n refresh: input.refresh,\n js: input.js ?? 'auto',\n rate: input.rate,\n });\n const page = await extractPage(fetched);\n const h1 = page.headings.find((heading) => heading.level === 1)?.text;\n const technicalStatus = crawlTechnicalStatus({\n requestedUrl: input.url,\n fetched,\n canonical: page.canonical,\n metaRobots: page.metaRobots,\n xRobotsTag: page.xRobotsTag,\n });\n return {\n url: input.url,\n finalUrl: page.finalUrl,\n status: fetched.status,\n title: page.title,\n h1,\n metaDescription: page.metaDescription,\n metaRobots: page.metaRobots,\n xRobotsTag: page.xRobotsTag,\n canonical: absoluteUrl(page.canonical, page.finalUrl),\n wordCount: page.wordCount,\n technicalStatus,\n queryCoverage: input.topQuery && ['ok', 'redirected'].includes(technicalStatus)\n ? pseoQueryCoverage({\n query: input.topQuery,\n title: page.title,\n h1,\n body: page.contentText,\n })\n : undefined,\n fetchDiagnostics: fetched.diagnostics,\n warnings: [...fetched.warnings, ...page.warnings],\n };\n }\n catch (error) {\n const warning = error instanceof Error ? error.message : String(error);\n return {\n url: input.url,\n technicalStatus: 'fetch-error',\n warnings: [warning],\n warning,\n };\n }\n}\nfunction inspectionSample(url, result) {\n const status = result.inspectionResult?.indexStatusResult;\n return {\n url,\n indexStatus: pseoIndexStatus(status?.verdict),\n verdict: status?.verdict,\n coverageState: status?.coverageState,\n indexingState: status?.indexingState,\n robotsTxtState: status?.robotsTxtState,\n pageFetchState: status?.pageFetchState,\n lastCrawlTime: status?.lastCrawlTime,\n userCanonical: status?.userCanonical,\n googleCanonical: status?.googleCanonical,\n };\n}\nasync function inspectSample(input) {\n try {\n return inspectionSample(input.url, await input.inspect({ siteUrl: input.site, inspectionUrl: input.url }));\n }\n catch (error) {\n return {\n url: input.url,\n indexStatus: 'unknown',\n warning: error instanceof Error ? error.message : String(error),\n };\n }\n}\nexport async function pseoAuditReport(input, dependencies = defaultDependencies) {\n const options = pseoAuditOptions(input);\n const now = dependencies.now();\n const generatedAt = now.toISOString();\n const range = defaultDateRange(options.days, now);\n const warnings = [];\n input.progress?.('Fetching sitemap URLs');\n const sitemapResults = await Promise.all((input.sitemaps ?? []).map((sitemapUrl) => dependencies.fetchSitemapUrls({\n sitemapUrl,\n limit: options.maxSitemapUrls,\n })));\n const sitemapUrls = sitemapResults.flatMap((result) => {\n warnings.push(...result.warnings);\n return result.urls;\n });\n const request = {\n ...range,\n type: 'web',\n dataState: 'final',\n aggregationType: 'auto',\n maxRows: MAX_GSC_ROWS,\n };\n input.progress?.(`Fetching ${options.days} days of GSC page and query/page rows`);\n const [pageResponse, queryPageResponse] = await Promise.all([\n dependencies.searchAnalytics(input.site, { ...request, dimensions: ['page'] }, { refresh: input.refresh }),\n dependencies.searchAnalytics(input.site, { ...request, dimensions: ['query', 'page'] }, { refresh: input.refresh }),\n ]);\n const pageRows = pageResponse.rows.map((row) => ({\n page: row.keys[0] ?? '',\n clicks: row.clicks,\n impressions: row.impressions,\n position: row.position,\n }));\n const queryPageRows = queryPageResponse.rows.map((row) => ({\n query: row.keys[0] ?? '',\n page: row.keys[1] ?? '',\n clicks: row.clicks,\n impressions: row.impressions,\n position: row.position,\n }));\n const build = (evidence) => buildPseoAuditReportFromRows({\n site: input.site,\n generatedAt,\n range,\n days: options.days,\n queryPageRows,\n pageRows,\n sitemapUrls,\n crawlSamples: evidence?.crawl,\n inspectionSamples: evidence?.inspection,\n templateLimit: options.templateLimit,\n minimumTemplateUrls: options.minimumTemplateUrls,\n minimumTemplateShare: options.minimumTemplateShare,\n minimumTemplateImpressions: options.minimumTemplateImpressions,\n crawlSamplesPerTemplate: options.crawlSamples,\n inspectionSamplesPerTemplate: options.inspectSamples,\n maxRowsPerRequest: MAX_GSC_ROWS,\n pageRowsFetched: pageResponse.rowsFetched,\n queryPageRowsFetched: queryPageResponse.rowsFetched,\n sitemapsRequested: input.sitemaps?.length ?? 0,\n maxUrlsPerSitemap: options.maxSitemapUrls,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n warnings,\n caveats: [\n `Data freshness: ${input.refresh ? 'fresh fetch requested; caches bypassed where supported' : 'local cache allowed; use --refresh to bypass cached provider and HTTP data'}.`,\n input.sitemaps?.length\n ? `Sitemaps: ${countLabel(input.sitemaps.length, 'sitemap URL')} requested.`\n : 'Sitemaps: none provided; template discovery used retained GSC page rows.',\n ],\n });\n const initial = build();\n const sampleUrls = pseoSampleUrls(initial);\n const topQueries = topQueryByUrl(queryPageRows, input);\n const crawl = [];\n for (const [index, url] of sampleUrls.crawl.entries()) {\n input.progress?.(`Crawling pSEO sample ${index + 1}/${sampleUrls.crawl.length}`);\n crawl.push(await crawlSample({\n url,\n topQuery: topQueries.get(url),\n refresh: input.refresh,\n js: input.js,\n rate: input.rate,\n fetch: dependencies.fetchPage,\n }));\n }\n const inspection = [];\n for (const [index, url] of sampleUrls.inspection.entries()) {\n input.progress?.(`Inspecting pSEO sample ${index + 1}/${sampleUrls.inspection.length}`);\n inspection.push(await inspectSample({\n site: input.site,\n url,\n inspect: dependencies.inspectUrl,\n }));\n }\n input.progress?.('Scoring pSEO template evidence');\n return build({ crawl, inspection });\n}\n//# sourceMappingURL=audit.js.map","function tableCell(value) {\n return String(value ?? '-')\n .replaceAll('\\n', ' ')\n .replaceAll('|', '\\\\|');\n}\nfunction truncate(value, maxLength = 120) {\n const text = tableCell(value).trim();\n if (text.length <= maxLength)\n return text;\n return `${text.slice(0, maxLength - 1)}...`;\n}\nexport function renderPresentationTablesMarkdown(tables) {\n return tables.flatMap((table) => {\n const headers = table.columns.map((column) => tableCell(column.label));\n const dividers = table.columns.map((column) => column.type === 'number' ? '---:' : '---');\n return [\n `## ${table.title}`,\n '',\n `| ${headers.join(' | ')} |`,\n `| ${dividers.join(' | ')} |`,\n ...table.rows.map((row) => [\n '',\n ...table.columns.map((column) => truncate(row[column.key])),\n '',\n ].join(' | ')),\n '',\n ];\n });\n}\n//# sourceMappingURL=markdown.js.map","function inspectionLabel(template) {\n const total = template.inspection.indexed +\n template.inspection.notIndexed +\n template.inspection.unknown +\n template.inspection.warnings;\n if (!total)\n return 'not checked';\n return `${template.inspection.indexed}/${total} indexed`;\n}\nfunction crawlLabel(template) {\n if (!template.crawl.attempted)\n return 'not crawled';\n return `${template.crawl.usable}/${template.crawl.attempted} usable`;\n}\nexport function pseoPresentation(report) {\n const charts = report.templates.length\n ? [\n {\n id: 'template_impressions',\n title: 'Template Impressions',\n type: 'bar',\n tableId: 'pseo_templates',\n xKey: 'rank',\n yKey: 'impressions',\n },\n {\n id: 'template_clicks',\n title: 'Template Clicks',\n type: 'bar',\n tableId: 'pseo_templates',\n xKey: 'rank',\n yKey: 'clicks',\n },\n ]\n : [];\n return {\n tables: [\n {\n id: 'pseo_summary',\n title: 'pSEO Summary',\n columns: [\n { key: 'metric', label: 'Metric' },\n { key: 'value', label: 'Value', type: 'number' },\n ],\n rows: [\n { metric: 'templates', value: report.summary.templates },\n { metric: 'gsc_pages', value: report.summary.gscPages },\n { metric: 'sitemap_urls', value: report.summary.sitemapUrls },\n { metric: 'clicks', value: report.summary.clicks },\n { metric: 'impressions', value: report.summary.impressions },\n { metric: 'crawled_urls', value: report.summary.crawledUrls },\n { metric: 'crawl_attempts', value: report.summary.crawlAttempts },\n { metric: 'inspected_urls', value: report.summary.inspectedUrls },\n {\n metric: 'inspection_attempts',\n value: report.summary.inspectionAttempts,\n },\n ],\n },\n {\n id: 'pseo_templates',\n title: 'pSEO Templates',\n columns: [\n { key: 'rank', label: 'Rank', type: 'number' },\n { key: 'template', label: 'Template' },\n { key: 'verdict', label: 'Verdict' },\n { key: 'confidence', label: 'Confidence' },\n { key: 'urls', label: 'URLs', type: 'number' },\n { key: 'clicks', label: 'Clicks', type: 'number' },\n { key: 'impressions', label: 'Impressions', type: 'number' },\n { key: 'ctr', label: 'CTR', type: 'number' },\n { key: 'position', label: 'Position', type: 'number' },\n { key: 'index', label: 'Index' },\n { key: 'crawl', label: 'Crawl' },\n { key: 'recommendation', label: 'Recommendation' },\n ],\n rows: report.templates.map((template, index) => ({\n rank: index + 1,\n template: template.signature,\n verdict: template.verdict,\n confidence: template.confidence,\n urls: template.urlCount,\n clicks: template.metrics.clicks,\n impressions: template.metrics.impressions,\n ctr: Number(template.metrics.ctr.toFixed(3)),\n position: Number(template.metrics.position.toFixed(1)),\n index: inspectionLabel(template),\n crawl: crawlLabel(template),\n recommendation: template.recommendation,\n })),\n },\n ],\n charts,\n };\n}\n//# sourceMappingURL=presentation.js.map","import { renderPresentationTablesMarkdown } from '../../markdown.js';\nimport { countLabel } from '../../phrasing.js';\nimport { pseoPresentation } from './presentation.js';\nexport function renderPseoMarkdown(report) {\n const presentation = pseoPresentation(report);\n const lines = [\n `# pSEO audit: ${report.site}`,\n '',\n `Generated: ${report.generatedAt}`,\n `Window: ${report.rangeDays} days`,\n '',\n `${countLabel(report.summary.templates, 'template')} audited from ${countLabel(report.summary.gscPages, 'GSC page')}.`,\n '',\n ];\n if (report.caveats.length) {\n lines.push('## Report Caveats', '');\n lines.push(...report.caveats.map((caveat) => `- ${caveat}`), '');\n }\n lines.push(...renderPresentationTablesMarkdown(presentation.tables));\n if (report.warnings.length) {\n lines.push('## Warnings', '');\n lines.push(...report.warnings.map((warning) => `- ${warning}`));\n }\n return lines.join('\\n').trim();\n}\n//# sourceMappingURL=markdown.js.map","import { jaccard, tokenize } from './shared.js';\nconst CLUSTER_THRESHOLD = 0.5;\nconst MAX_TOKEN_BUCKET = 250;\nconst MAX_TOKEN_SHARE = 0.08;\nconst IGNORED_CLUSTER_TOKENS = new Set([\n 'and',\n 'are',\n 'best',\n 'can',\n 'for',\n 'from',\n 'how',\n 'near',\n 'the',\n 'to',\n 'vs',\n 'what',\n 'when',\n 'where',\n 'with',\n 'your',\n]);\nexport function compareQueryClusterText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\nexport function queryClusterTokens(query) {\n return tokenize(query).filter((token) => !IGNORED_CLUSTER_TOKENS.has(token));\n}\nexport function aggregateQueryClusterRows(rows) {\n const byQuery = new Map();\n for (const row of rows) {\n const current = byQuery.get(row.query) ?? {\n query: row.query,\n impressions: 0,\n clicks: 0,\n weightedPosition: 0,\n tokens: new Set(),\n pages: new Map(),\n };\n current.impressions += row.impressions;\n current.clicks += row.clicks;\n current.weightedPosition += row.position * row.impressions;\n for (const token of row.tokens)\n current.tokens.add(token);\n const page = current.pages.get(row.page) ?? {\n url: row.page,\n impressions: 0,\n clicks: 0,\n };\n page.impressions += row.impressions;\n page.clicks += row.clicks;\n if (page.url)\n current.pages.set(page.url, page);\n byQuery.set(row.query, current);\n }\n return [...byQuery.values()]\n .map((row) => ({\n query: row.query,\n impressions: row.impressions,\n clicks: row.clicks,\n position: row.impressions ? row.weightedPosition / row.impressions : 0,\n tokens: [...row.tokens].sort(),\n pages: [...row.pages.values()].sort((a, b) => b.impressions - a.impressions ||\n compareQueryClusterText(a.url, b.url)),\n }))\n .sort((a, b) => b.impressions - a.impressions ||\n compareQueryClusterText(a.query, b.query));\n}\nexport function clusterQueryRows(rows) {\n if (rows.length <= 1)\n return rows.map((row) => [row]);\n const normalizedRows = rows.map((row) => ({\n ...row,\n tokens: queryClusterTokens(row.query),\n }));\n const tokenBuckets = new Map();\n for (const [index, row] of normalizedRows.entries()) {\n for (const token of row.tokens) {\n const bucket = tokenBuckets.get(token) ?? [];\n bucket.push(index);\n tokenBuckets.set(token, bucket);\n }\n }\n const maxBucketSize = Math.max(20, Math.min(MAX_TOKEN_BUCKET, Math.floor(rows.length * MAX_TOKEN_SHARE)));\n const assigned = new Set();\n const groups = [];\n const seedIds = normalizedRows\n .map((row, index) => ({\n index,\n impressions: row.impressions,\n query: row.query,\n }))\n .sort((a, b) => b.impressions - a.impressions ||\n compareQueryClusterText(a.query, b.query));\n for (const seed of seedIds) {\n if (assigned.has(seed.index))\n continue;\n const seedRow = normalizedRows[seed.index];\n if (!seedRow)\n continue;\n const candidateIds = new Set();\n for (const token of seedRow.tokens) {\n const bucket = tokenBuckets.get(token);\n if (!bucket || bucket.length > maxBucketSize)\n continue;\n for (const candidateId of bucket) {\n if (candidateId !== seed.index && !assigned.has(candidateId)) {\n candidateIds.add(candidateId);\n }\n }\n }\n const group = [seedRow];\n assigned.add(seed.index);\n const sortedCandidateIds = [...candidateIds].sort((left, right) => {\n const leftRow = normalizedRows[left];\n const rightRow = normalizedRows[right];\n if (!leftRow || !rightRow)\n return left - right;\n return (rightRow.impressions - leftRow.impressions ||\n compareQueryClusterText(leftRow.query, rightRow.query));\n });\n for (const candidateId of sortedCandidateIds) {\n const candidate = normalizedRows[candidateId];\n if (!candidate)\n continue;\n if (jaccard(seedRow.tokens, candidate.tokens) >= CLUSTER_THRESHOLD) {\n group.push(candidate);\n assigned.add(candidateId);\n }\n }\n groups.push(group);\n }\n return groups;\n}\n//# sourceMappingURL=query-cluster-primitives.js.map","import { createCtrBenchmarkContext, } from './opportunity-primitives.js';\nimport { clusterPseoTemplates } from './pseo/templates.js';\nimport { clusterQueryRows, compareQueryClusterText, } from './query-cluster-primitives.js';\nimport { tokenize } from './shared.js';\nfunction quotedLabel(label) {\n return label.includes('\"') ? `'${label}'` : `\"${label}\"`;\n}\nfunction classifyIntent(query, brand) {\n const tokens = new Set(tokenize(query));\n const brandTokens = brand ? tokenize(brand) : [];\n if (brandTokens.length && brandTokens.every((token) => tokens.has(token))) {\n return 'navigational';\n }\n if (tokens.has('buy') ||\n tokens.has('price') ||\n (tokens.has('near') && tokens.has('me'))) {\n return 'transactional';\n }\n if (['vs', 'review', 'best', 'top', 'compare'].some((token) => tokens.has(token))) {\n return 'commercial';\n }\n if (['how', 'what', 'why', 'guide'].some((token) => tokens.has(token))) {\n return 'informational';\n }\n return 'mixed';\n}\nfunction clusterTotals(cluster) {\n const totals = cluster.queries.reduce((sum, query) => ({\n impressions: sum.impressions + query.impressions,\n clicks: sum.clicks + query.clicks,\n weightedPosition: sum.weightedPosition + query.position * query.impressions,\n }), { impressions: 0, clicks: 0, weightedPosition: 0 });\n return {\n impressions: totals.impressions,\n clicks: totals.clicks,\n averagePosition: totals.impressions\n ? totals.weightedPosition / totals.impressions\n : 0,\n ctr: totals.impressions ? totals.clicks / totals.impressions : 0,\n };\n}\nfunction opportunityScore(input) {\n if (input.queries <= 1 || input.impressions < 50)\n return 0;\n return input.position > 10\n ? Number((input.impressions * 0.03).toFixed(2))\n : (input.estimatedClickLift ?? 0);\n}\nfunction clusterRecommendation(input) {\n const clusterName = quotedLabel(input.label);\n if (input.template &&\n input.template.urlCount >= 3 &&\n input.template.share >= 0.6) {\n const pageText = input.topPage && input.template.urlCount > 1\n ? ` Start with ${input.topPage.url}.`\n : '';\n const action = input.template.urlCount > 1\n ? `This is template-level demand, not a one-off page edit. Tighten the shared title/H1/intro/schema/internal-link rules so each page makes the entity and query angle clear. If ${clusterName} is broader than one entity, route it to a better hub/list page instead of letting several template URLs compete.`\n : 'Improve the shared title, H1, intro, schema, and internal-link pattern, then spot-check the highest-impression URL.';\n return `${clusterName} maps mostly to ${input.template.signature} (${input.template.urlCount} URLs). ${action}${pageText}`;\n }\n if (input.queries === 1) {\n return input.topPage\n ? `This is a single-query cluster. Inspect ${input.topPage.url} before making a template or hub decision.`\n : 'This is a single-query cluster. Use it as supporting detail, not as a content hub or template decision by itself.';\n }\n if (input.impressions >= 500 && input.clicks === 0) {\n return input.topPage\n ? `This ${clusterName} cluster has search demand but no clicks. Check ${input.topPage.url}; if it is the right target, make the exact intent obvious in the title, H1, intro, and internal links.`\n : `This ${clusterName} cluster has search demand but no clicks. Check whether the ranking page actually answers the cluster intent, then improve the section/title or create a stronger dedicated page if intent is distinct.`;\n }\n if (input.position > 10) {\n return input.topPage\n ? `This ${clusterName} cluster is mostly outside page one. Strengthen ${input.topPage.url} around this exact intent and add internal links from related pages before treating it as a CTR problem.`\n : `This ${clusterName} cluster is mostly outside page one. Tighten the page section around the shared intent and add internal links from related pages before treating this as a CTR problem.`;\n }\n if (input.clicks / Math.max(1, input.impressions) < input.expectedCtr) {\n return `This ${clusterName} cluster ranks below its CTR benchmark. Review SERP framing around the dominant intent (${input.intent}) before expanding content.`;\n }\n return `This ${clusterName} cluster already gets clicks. Use it to refine page structure, FAQs, and internal anchors rather than creating duplicate pages.`;\n}\nfunction clusterSummary(input) {\n return `${input.queries} queries, ${input.impressions.toFixed(0)} impressions, ${input.clicks.toFixed(0)} clicks, average position ${input.position.toFixed(1)}.`;\n}\nfunction clusterLabel(rows) {\n return ([...rows].sort((a, b) => b.impressions - a.impressions ||\n compareQueryClusterText(a.query, b.query))[0]?.query ?? '');\n}\nfunction clusterPages(rows) {\n const byPage = new Map();\n for (const row of rows) {\n for (const page of row.pages) {\n const current = byPage.get(page.url) ?? {\n url: page.url,\n impressions: 0,\n clicks: 0,\n };\n current.impressions += page.impressions;\n current.clicks += page.clicks;\n byPage.set(page.url, current);\n }\n }\n return [...byPage.values()].sort((a, b) => b.impressions - a.impressions || compareQueryClusterText(a.url, b.url));\n}\nfunction clusterTemplate(pages) {\n const urls = pages.map((page) => page.url);\n const [template] = clusterPseoTemplates(urls, {\n minUrls: 3,\n minShare: 0.6,\n limit: 1,\n });\n return template\n ? {\n signature: template.signature,\n urlCount: template.urlCount,\n share: template.share,\n sampleUrls: template.sampleUrls,\n }\n : undefined;\n}\nfunction benchmarkDetails(benchmark) {\n return {\n expectedCtr: benchmark.ctr,\n source: benchmark.source,\n peerRows: benchmark.rows,\n peerImpressions: benchmark.impressions,\n qualifiedPeerImpressions: benchmark.qualifiedImpressions,\n urlSamples: benchmark.urlSamples,\n positiveUrlSamples: benchmark.positiveUrlSamples,\n };\n}\nfunction boundedInteger(input) {\n const value = Number.isFinite(input.value)\n ? (input.value ?? 0)\n : input.fallback;\n return Math.min(input.maximum ?? Number.POSITIVE_INFINITY, Math.max(1, Math.floor(value)));\n}\nexport function analyzeQueryClustersFromRows(input) {\n const minImpressions = boundedInteger({\n value: input.minImpressions,\n fallback: 25,\n });\n const limit = boundedInteger({\n value: input.limit,\n fallback: 25,\n maximum: 100,\n });\n const benchmarkRows = input.rows\n .filter((row) => row.position >= 1 &&\n row.position <= 10 &&\n row.impressions > 0 &&\n Boolean(row.pages[0]?.url))\n .map((row) => ({\n keys: [row.query, row.pages[0]?.url ?? ''],\n clicks: row.clicks,\n impressions: row.impressions,\n ctr: row.clicks / row.impressions,\n position: row.position,\n }));\n const benchmarkRowsByQuery = new Map(benchmarkRows.map((row) => [row.keys[0] ?? '', row]));\n const benchmarkContext = createCtrBenchmarkContext(benchmarkRows);\n const clusters = [];\n const candidateRows = input.rows.filter((row) => row.impressions >= minImpressions);\n for (const clusterRows of clusterQueryRows(candidateRows)) {\n const label = clusterLabel(clusterRows);\n const intents = new Set(clusterRows.map((row) => classifyIntent(row.query, input.brand)));\n const [intent] = intents;\n const clusterIntent = intents.size === 1 && intent ? intent : 'mixed';\n const totals = clusterTotals({ queries: clusterRows });\n const pages = clusterPages(clusterRows);\n const topPages = pages.slice(0, 5);\n const excludedRows = clusterRows\n .map((row) => benchmarkRowsByQuery.get(row.query))\n .filter((row) => Boolean(row));\n const benchmark = benchmarkContext.forAggregate({\n keys: [label, topPages[0]?.url ?? ''],\n clicks: totals.clicks,\n impressions: totals.impressions,\n ctr: totals.ctr,\n position: totals.averagePosition,\n }, excludedRows);\n const estimatedClickLift = totals.averagePosition <= 10\n ? Number((Math.max(0, benchmark.ctr - totals.ctr) * totals.impressions).toFixed(2))\n : undefined;\n const template = clusterTemplate(pages);\n clusters.push({\n label,\n intent: clusterIntent,\n queries: clusterRows\n .map((row) => ({\n query: row.query,\n impressions: row.impressions,\n clicks: row.clicks,\n position: row.position,\n }))\n .sort((a, b) => b.impressions - a.impressions ||\n compareQueryClusterText(a.query, b.query)),\n topPages,\n template,\n totals,\n benchmark: benchmarkDetails(benchmark),\n ...(estimatedClickLift === undefined ? {} : { estimatedClickLift }),\n opportunityScore: opportunityScore({\n queries: clusterRows.length,\n impressions: totals.impressions,\n position: totals.averagePosition,\n estimatedClickLift,\n }),\n summary: clusterSummary({\n label,\n queries: clusterRows.length,\n impressions: totals.impressions,\n clicks: totals.clicks,\n position: totals.averagePosition,\n }),\n recommendation: clusterRecommendation({\n label,\n intent: clusterIntent,\n queries: clusterRows.length,\n impressions: totals.impressions,\n clicks: totals.clicks,\n position: totals.averagePosition,\n expectedCtr: benchmark.ctr,\n topPage: topPages[0],\n template,\n }),\n });\n }\n const sortedClusters = clusters\n .filter((cluster) => cluster.queries.length >= 2 ||\n (cluster.totals?.impressions ?? 0) >= minImpressions * 3)\n .sort((a, b) => (b.opportunityScore ?? 0) - (a.opportunityScore ?? 0) ||\n (b.totals?.impressions ?? 0) - (a.totals?.impressions ?? 0) ||\n b.queries.length - a.queries.length ||\n compareQueryClusterText(a.label, b.label))\n .slice(0, limit);\n const totals = sortedClusters.reduce((sum, cluster) => ({\n queries: sum.queries + cluster.queries.length,\n impressions: sum.impressions + (cluster.totals?.impressions ?? 0),\n clicks: sum.clicks + (cluster.totals?.clicks ?? 0),\n }), { queries: 0, impressions: 0, clicks: 0 });\n const highOpportunityClusters = sortedClusters.filter((cluster) => {\n const clusterTotal = cluster.totals;\n return Boolean(clusterTotal &&\n (cluster.opportunityScore ?? 0) > 0 &&\n cluster.queries.length > 1 &&\n clusterTotal.impressions >= 100);\n }).length;\n return {\n clusters: sortedClusters,\n totals,\n highOpportunityClusters,\n minImpressions,\n limit,\n };\n}\n//# sourceMappingURL=query-cluster-analysis.js.map","import { shouldExcludeBrandQuery } from '../brand.js';\nimport { querySearchAnalytics } from '../gsc/client.js';\nimport { analyzeQueryClustersFromRows } from './query-cluster-analysis.js';\nimport { aggregateQueryClusterRows, queryClusterTokens, } from './query-cluster-primitives.js';\nimport { isLowActionabilityQuery } from './query-quality.js';\nimport { defaultDateRange } from './shared.js';\nexport { analyzeQueryClustersFromRows } from './query-cluster-analysis.js';\nexport { clusterQueryRows, queryClusterTokens, } from './query-cluster-primitives.js';\nfunction plural(count, singular, pluralLabel = `${singular}s`) {\n return count === 1 ? singular : pluralLabel;\n}\nfunction reportVerdict(input) {\n if (!input.clusters.length) {\n return 'No query clusters were generated for this scope.';\n }\n if (input.highOpportunityClusters > 0) {\n const verb = input.highOpportunityClusters === 1 ? 'has' : 'have';\n return `${input.highOpportunityClusters} ${plural(input.highOpportunityClusters, 'cluster')} ${verb} enough demand and weak enough performance to review first.`;\n }\n return 'No obvious high-opportunity clusters were found. Use this report for content structure and intent mapping rather than urgent fixes.';\n}\nexport async function queryClusterReport(input) {\n const range = defaultDateRange(28);\n const filters = input.scope\n ? [\n {\n groupType: 'and',\n filters: [\n {\n dimension: 'page',\n operator: 'contains',\n expression: input.scope,\n },\n ],\n },\n ]\n : undefined;\n const { rows } = await querySearchAnalytics(input.site, {\n ...range,\n dimensions: ['query', 'page'],\n type: 'web',\n dataState: 'final',\n dimensionFilterGroups: filters,\n }, { refresh: input.refresh });\n const queryRows = aggregateQueryClusterRows(rows\n .map((row) => ({\n query: row.keys[0] ?? '',\n impressions: row.impressions,\n clicks: row.clicks,\n position: row.position,\n tokens: queryClusterTokens(row.keys[0] ?? ''),\n page: row.keys[1] ?? '',\n }))\n .filter((row) => row.query &&\n !isLowActionabilityQuery(row.query) &&\n !shouldExcludeBrandQuery({\n query: row.query,\n siteUrl: input.site,\n brandTerms: input.brandTerms ?? (input.brand ? [input.brand] : undefined),\n includeBrand: input.includeBrand,\n })));\n const { clusters, totals, highOpportunityClusters, minImpressions, limit } = analyzeQueryClustersFromRows({\n rows: queryRows,\n brand: input.brand,\n minImpressions: input.minImpressions,\n limit: input.limit,\n });\n return {\n site: input.site,\n scope: input.scope,\n range,\n generatedAt: new Date().toISOString(),\n summary: {\n clusters: clusters.length,\n queries: totals.queries,\n impressions: totals.impressions,\n clicks: totals.clicks,\n highOpportunityClusters,\n minImpressions,\n limit,\n brandFiltering: input.includeBrand ? 'included' : 'excluded',\n verdict: reportVerdict({\n clusters,\n highOpportunityClusters,\n }),\n },\n clusters,\n caveats: [\n `Date window: ${range.startDate} to ${range.endDate} (28 days), using final GSC data where available.`,\n input.scope\n ? `Scope: only pages containing \"${input.scope}\" were included.`\n : 'Scope: all pages in the selected GSC property were included.',\n input.brand\n ? `Brand filtering: ${input.includeBrand ? 'brand queries included' : `brand queries excluded using ${input.brandTerms?.length ? input.brandTerms.join(', ') : input.brand}`}.`\n : 'Brand intent detection used only query language because no brand term was supplied.',\n 'Clusters are token-overlap groups. Review the top queries before creating, merging, or deleting pages.',\n `Query threshold: at least ${minImpressions} impressions per query; low-volume singletons are omitted and output is capped at ${limit} clusters.`,\n 'Expected CTR is a heuristic using a leave-cluster-out site benchmark when enough peer URL data exists, otherwise the default position curve. Page-two clusters do not claim CTR-only click lift.',\n ],\n recommendations: clusters\n .filter((cluster) => cluster.recommendation)\n .slice(0, 5)\n .map((cluster) => cluster.recommendation ?? ''),\n };\n}\n//# sourceMappingURL=query-cluster.js.map","import { latestFinalGscDate } from '../../gsc/dates.js';\nexport function rangeDays(range) {\n const start = Date.parse(`${range.startDate}T00:00:00Z`);\n const end = Date.parse(`${range.endDate}T00:00:00Z`);\n return Math.floor((end - start) / 86_400_000) + 1;\n}\nexport function finalGscDate(now = new Date()) {\n return latestFinalGscDate(now);\n}\nexport function monthRange(month, now = new Date()) {\n if (!/^\\d{4}-\\d{2}$/.test(month)) {\n throw new Error('Pass --month as YYYY-MM.');\n }\n const start = new Date(`${month}-01T00:00:00Z`);\n if (Number.isNaN(start.getTime())) {\n throw new Error('Pass --month as YYYY-MM.');\n }\n const end = new Date(start);\n end.setUTCMonth(end.getUTCMonth() + 1);\n end.setUTCDate(0);\n const endDate = end.toISOString().slice(0, 10);\n const availableEndDate = finalGscDate(now);\n const cappedEndDate = endDate < availableEndDate ? endDate : availableEndDate;\n const startDate = start.toISOString().slice(0, 10);\n if (cappedEndDate < startDate) {\n throw new Error(`Final GSC data is only available through ${availableEndDate}. Choose an earlier month.`);\n }\n return { startDate, endDate: cappedEndDate };\n}\n//# sourceMappingURL=dates.js.map","import { toSeoError } from '../../errors.js';\nimport { measureChange } from '../experiments.js';\nexport async function measureSavedChanges(changes, options = {}) {\n const measure = options.measure ?? measureChange;\n return Promise.all(changes.map(async (change) => {\n try {\n const measurement = await measure({\n id: change.id,\n refresh: options.refresh,\n });\n return {\n status: 'measured',\n dataStatus: measurement.dataStatus,\n change,\n measurement,\n };\n }\n catch (error) {\n const normalized = toSeoError(error);\n return {\n status: 'failed',\n dataStatus: 'unavailable',\n change,\n error: {\n code: normalized.code,\n message: normalized.message,\n retryable: normalized.retryable,\n },\n };\n }\n }));\n}\nfunction partialReason(measurement) {\n return (measurement.warnings[0] ??\n measurement.caveats.find((caveat) => /incomplete|partial|truncated/i.test(caveat)) ??\n 'The requested window or source evidence was incomplete; inspect the structured measurement for provenance.');\n}\nexport function changeMeasurementCaveats(attempts) {\n return attempts.flatMap((attempt) => {\n if (attempt.status === 'failed') {\n return [\n `Unavailable saved change measurement \"${attempt.change.title}\": ${attempt.error.message.replace(/[.!?]+$/, '')} (${attempt.error.code}).`,\n ];\n }\n if (attempt.dataStatus === 'partial') {\n return [\n `Partial saved change measurement \"${attempt.change.title}\": ${partialReason(attempt.measurement).replace(/[.!?]+$/, '')}.`,\n ];\n }\n return [];\n });\n}\nexport function narrativeDataStatus(diagnosisStatus, attempts) {\n if (diagnosisStatus === 'complete' &&\n attempts.some((attempt) => attempt.dataStatus !== 'complete')) {\n return 'partial';\n }\n return diagnosisStatus;\n}\n//# sourceMappingURL=change-measurements.js.map","export function renderMarkdown(report) {\n const lines = [`# SEO report: ${report.site}`, '', report.headline, ''];\n lines.push(`Period: ${report.period.startDate} to ${report.period.endDate}`);\n lines.push('');\n if (report.caveats.length) {\n lines.push('## Report Caveats');\n for (const caveat of report.caveats) {\n lines.push(`- ${caveat}`);\n }\n lines.push('');\n }\n for (const section of report.sections) {\n lines.push(`## ${section.title}`);\n for (const bullet of section.bullets) {\n lines.push(`- ${bullet}`);\n }\n lines.push('');\n }\n lines.push('## Priorities');\n for (const priority of report.priorities) {\n lines.push(`- ${priority.title} (${priority.confidence}): ${priority.action}`);\n }\n return lines.join('\\n');\n}\n//# sourceMappingURL=markdown.js.map","import { countLabel } from '../../phrasing.js';\nfunction skippedReason(report, section) {\n return report.skippedSections?.find((item) => item.section === section)\n ?.reason;\n}\nfunction unavailablePhrase(report, section, label) {\n return skippedReason(report, section) ? `${label} unavailable` : undefined;\n}\nexport function diagnosisAvailabilityCaveats(report) {\n const groupedCaveats = (prefix, sections) => {\n const byReason = new Map();\n for (const section of sections) {\n const items = byReason.get(section.reason) ?? [];\n items.push(section.section);\n byReason.set(section.reason, items);\n }\n return [...byReason.entries()].map(([reason, items]) => items.length === 1\n ? `${prefix} ${items[0]}: ${reason.replace(/[.!?]+$/, '')}.`\n : `${prefix} ${items.length} sections: ${reason.replace(/[.!?]+$/, '')}.`);\n };\n return [\n ...groupedCaveats('Skipped', report.skippedSections ?? []),\n ...groupedCaveats('Partial', report.partialReasons ?? []),\n ];\n}\nexport function movementLine(report) {\n if (skippedReason(report, 'traffic anomaly')) {\n return 'Traffic anomaly detection was not available for this run.';\n }\n const anomaly = report.anomaly.anomalies.find((item) => item.significant);\n if (!anomaly) {\n return 'No significant traffic anomaly signal was detected.';\n }\n const direction = anomaly.direction === 'spike'\n ? 'spiked'\n : anomaly.direction === 'drop'\n ? 'dropped'\n : anomaly.direction;\n return `Average daily ${anomaly.metric} ${direction} from ${anomaly.baselineMean.toFixed(1)} to ${anomaly.comparisonMean.toFixed(1)}.`;\n}\nfunction countPhrase(count, singular, pluralLabel = `${singular}s`) {\n if (count === 0)\n return `no ${pluralLabel}`;\n return `${count} ${plural(count, singular, pluralLabel)}`;\n}\nexport function headlineLine(report) {\n const parts = [\n unavailablePhrase(report, 'traffic anomaly', 'traffic anomaly analysis') ??\n countPhrase(report.summary.significantAnomalies, 'significant anomaly signal'),\n unavailablePhrase(report, 'decay analysis', 'content decay analysis') ??\n countPhrase(report.summary.decayItems, 'observed retained query/page decline'),\n unavailablePhrase(report, 'striking-distance opportunities', 'striking-distance analysis') ??\n countPhrase(report.summary.strikingDistanceItems, 'striking-distance opportunity', 'striking-distance opportunities'),\n unavailablePhrase(report, 'quick-win opportunities', 'quick-win analysis') ?? countPhrase(report.summary.quickWinItems, 'quick-win candidate'),\n ];\n if (report.summary.cannibalItems ||\n skippedReason(report, 'cannibalisation analysis')) {\n parts.push(unavailablePhrase(report, 'cannibalisation analysis', 'multi-URL query analysis') ??\n countPhrase(report.summary.cannibalItems, 'multi-URL query candidate'));\n }\n const prefix = report.dataStatus === 'partial'\n ? 'Partial diagnosis; '\n : report.dataStatus === 'unavailable'\n ? 'Diagnosis unavailable; '\n : '';\n return `${prefix}${parts.join('; ')}.`;\n}\nexport function topSegmentLine(report) {\n if (skippedReason(report, 'page movement segments')) {\n return 'Page movement comparison was not available for this run.';\n }\n const segment = report.segments.page;\n if (segment.dataStatus === 'empty') {\n return 'Search Console returned no retained page rows for either movement window.';\n }\n if (segment.dataStatus === 'unavailable') {\n return 'No page was retained in both movement windows, so page movement could not be compared.';\n }\n const page = segment.items[0];\n if (!page)\n return 'No matched retained page movement stood out.';\n const direction = page.clickDelta < 0 ? 'lost' : 'gained';\n return `${page.key} ${direction} ${Math.abs(page.clickDelta)} clicks compared with the previous window.`;\n}\nexport function updateAttributionLine(report) {\n if (report.summary.updateAttributionStatus === 'unavailable') {\n return 'Update correlation was not available for this run.';\n }\n const overlapCount = report.updateCorrelation.overlappingUpdates.length;\n const significant = report.anomaly.anomalies.some((anomaly) => anomaly.significant);\n if (!overlapCount) {\n return 'No official Google update window overlapped the comparison window.';\n }\n if (!significant) {\n return `${countLabel(overlapCount, 'official Google update window')} overlapped the comparison window, but no significant movement was detected.`;\n }\n return `${countLabel(overlapCount, 'official Google update window')} overlapped the significant movement comparison window. This timing does not establish that the update caused the movement.`;\n}\nexport function changeLine(measurement) {\n const status = measurement.dataStatus === 'partial' ? 'partial; ' : '';\n if (measurement.delta.clicks === null) {\n return `${measurement.change.title}: ${status}${measurement.verdict}; comparable click movement is unavailable.`;\n }\n const pct = measurement.delta.clickPct === null\n ? ''\n : ` (${measurement.delta.clickPct}%)`;\n return `${measurement.change.title}: ${status}${measurement.verdict}, ${measurement.delta.clicks} clicks${pct}.`;\n}\nexport function changeMeasurementLine(attempt) {\n if (attempt.status === 'failed') {\n return `${attempt.change.title}: measurement unavailable (${attempt.error.code}); ${attempt.error.message.replace(/[.!?]+$/, '')}.`;\n }\n return changeLine(attempt.measurement);\n}\nexport function monitoringBullets(report) {\n const bullets = [];\n const crawl = report.monitoring.crawlRuns[0];\n const recovery = report.monitoring.linkRecover;\n if (crawl) {\n bullets.push(`Latest crawl checked ${countLabel(crawl.urlCount, 'URL')} with ${countLabel(crawl.statusErrors, 'status error')}, ${countLabel(crawl.nonIndexable, 'non-indexable page')}, and ${countLabel(crawl.highPriorityRecommendations, 'high-priority crawl action')}.`);\n if (crawl.topRecommendation) {\n bullets.push(`Top crawl action: ${crawl.topRecommendation.url}. ${crawl.topRecommendation.action}`);\n }\n if ((crawl.statusErrors || crawl.nonIndexable) && !recovery) {\n bullets.push('Run link-recover before content work if those URLs have GSC search value; recoverable 4xx, noindex, and canonical issues can look like content decay.');\n }\n }\n else {\n bullets.push('No crawl-diff run is saved yet.');\n }\n const watch = report.monitoring.indexWatch;\n if (watch.inspectedUrls) {\n bullets.push(`Index watch tracks ${countLabel(watch.inspectedUrls, 'URL')}; ${countLabel(watch.currentIssues, 'current indexing review')} and ${countLabel(watch.failed, 'failed inspection')}.`);\n if (watch.currentIssues || watch.failed) {\n bullets.push(`Index watch currently has ${countLabel(watch.blocked, 'exact blocked state')}; inspect stable verdict, robots, indexing, fetch, and canonical evidence before changing copy.`);\n }\n }\n else {\n bullets.push('No index-watch snapshot is saved yet.');\n }\n if (recovery) {\n bullets.push(`Latest link-recover checked ${countLabel(recovery.checked, 'search-value URL')}; ${countLabel(recovery.recoverable, 'recoverable issue')}, ${recovery.high} high severity, ${recovery.clicksAtRisk.toFixed(0)} clicks at risk.`);\n if (recovery.topUrl && recovery.topAction) {\n bullets.push(`Top recovery target: ${recovery.topUrl}. ${recovery.topAction}`);\n }\n if (recovery.repeatedUrls) {\n bullets.push(`${countLabel(recovery.repeatedUrls, 'recoverable URL')} appeared in multiple recent link-recover runs${recovery.repeatedTopUrl ? `; first repeat: ${recovery.repeatedTopUrl}` : ''}.`);\n }\n }\n else {\n bullets.push('No link-recover run is saved yet.');\n }\n return bullets;\n}\nexport function verificationFetchLine(report) {\n const verified = report.quickWins.items\n .map((item) => item.contentVerification?.fetchDiagnostics)\n .filter((item) => item !== undefined);\n if (!verified.length)\n return null;\n const blocked = verified.filter((item) => item.blocked).length;\n const rendered = verified.filter((item) => item.rendered).length;\n const cached = verified.filter((item) => item.cache === 'hit').length;\n const fetched = verified.filter((item) => item.fetched && item.cache !== 'hit' && !item.rendered).length;\n return `Verified-page fetch status: ${cached} cached, ${fetched} fetched, ${rendered} rendered, ${blocked} blocked.`;\n}\nexport function gapCountLine(report) {\n const gaps = report.quickWins.items.filter((item) => item.contentVerification?.classification === 'content-gap').length;\n const framing = report.quickWins.items.filter((item) => item.contentVerification?.classification === 'serp-framing').length;\n return `${gaps} ${gaps === 1 ? 'shows' : 'show'} true content gaps; ${framing} look more like SERP/title/H1 framing gaps.`;\n}\nexport function templateOpportunityLine(report) {\n const template = report.quickWins.templates[0];\n if (!template || template.urlCount < 2) {\n return 'No dominant opportunity template stood out.';\n }\n if (template.id === 'other') {\n return `${template.urlCount} quick-win URLs sit outside a recognised reusable template. Triage them individually, then create a content group only if they share real page structure.`;\n }\n return `${template.urlCount} distinct quick-win URLs sit in the ${template.label} template. Compare their technical and page evidence before choosing a shared change.`;\n}\nfunction decayDiagnosisLabel(diagnosis) {\n if (diagnosis === 'lost_ctr')\n return 'CTR dropped while rankings held';\n if (diagnosis === 'lost_position')\n return 'average position worsened';\n if (diagnosis === 'lost_impressions')\n return 'impressions dropped';\n if (diagnosis === 'lost_clicks')\n return 'clicks dropped without one dominant signal';\n return diagnosis.replaceAll('_', ' ');\n}\nfunction plural(count, singular, pluralLabel = `${singular}s`) {\n return count === 1 ? singular : pluralLabel;\n}\nexport function decayClusterLine(report) {\n const group = report.decay.groups[0];\n if (!group)\n return 'No material decay cluster stood out.';\n const diagnosis = decayDiagnosisLabel(group.diagnosis);\n const samples = group.sampleQueries.slice(0, 2).join('; ');\n return `Top decay cluster: ${group.count} ${plural(group.count, 'finding')} in the ${group.template.label} template (${diagnosis}), ${group.totalClickLoss.toFixed(0)} fewer observed clicks across rows retained in both windows. Action: ${group.recommendation}${samples ? ` Example queries: ${samples}.` : ''}`;\n}\nexport function cannibalSuppressionLine(report) {\n const suppressed = report.cannibalization.selection.suppressedQueries;\n if (!suppressed)\n return 'No branded multi-URL query candidates were excluded.';\n const reasons = Object.entries(report.cannibalization.suppressionSummary)\n .map(([reason, count]) => `${count} ${reason.replace(/_/g, ' ')}`)\n .join(', ');\n return `${suppressed} branded multi-URL query candidates were excluded (${reasons}).`;\n}\nexport function contentOpportunityBullets(report) {\n const bullets = [];\n const unavailableSections = [\n ['decay analysis', 'content decay'],\n ['cannibalisation analysis', 'multi-URL query'],\n ['striking-distance opportunities', 'striking-distance'],\n ['quick-win opportunities', 'quick-win'],\n ]\n .filter(([section]) => skippedReason(report, section))\n .map(([, label]) => label);\n if (unavailableSections.length) {\n bullets.push(`Could not assess ${unavailableSections.join(', ')} opportunities in this run; see report caveats.`);\n }\n if (report.summary.decayItems) {\n const top = report.decay.items[0];\n bullets.push(top\n ? `${report.summary.decayItems} observed retained query/page ${plural(report.summary.decayItems, 'decline')} need review. Start with \"${top.query}\" on ${top.url}; it had ${top.clickLoss.toFixed(0)} fewer clicks.`\n : `${report.summary.decayItems} observed retained query/page ${plural(report.summary.decayItems, 'decline')} need review.`);\n bullets.push(decayClusterLine(report));\n }\n if (report.summary.cannibalItems) {\n const top = report.cannibalization.items[0];\n bullets.push(top\n ? `${report.summary.cannibalItems} multi-URL query ${plural(report.summary.cannibalItems, 'candidate')} need intent and technical review. Start with \"${top.query}\" and decide whether ${top.pages.length} ranking URLs answer the same intent.`\n : `${report.summary.cannibalItems} multi-URL query ${plural(report.summary.cannibalItems, 'candidate')} need intent and technical review.`);\n }\n if (report.cannibalization.selection.suppressedQueries) {\n bullets.push(cannibalSuppressionLine(report));\n }\n if (report.summary.strikingDistanceItems) {\n const top = report.strikingDistance.items[0];\n bullets.push(top\n ? `${report.summary.strikingDistanceItems} query/page ${plural(report.summary.strikingDistanceItems, 'candidate')} have an average GSC position above 10 and at most 20. Start by investigating \"${top.query}\" on ${top.url}; it averages position ${top.position.toFixed(1)} with ${top.impressions.toFixed(0)} impressions.`\n : `${report.summary.strikingDistanceItems} query/page ${plural(report.summary.strikingDistanceItems, 'candidate')} have an average GSC position above 10 and at most 20.`);\n }\n if (!skippedReason(report, 'quick-win opportunities') &&\n report.summary.quickWinItems) {\n const top = report.quickWins.items[0];\n bullets.push(top\n ? `${report.summary.quickWinItems} retained query/page ${plural(report.summary.quickWinItems, 'candidate')} fell below a site-peer or versioned heuristic CTR target. Start with \"${top.query}\" on ${top.url}; it had ${top.impressions.toFixed(0)} impressions at average position ${top.position.toFixed(1)}.`\n : `${report.summary.quickWinItems} CTR-target ${plural(report.summary.quickWinItems, 'candidate')} need review.`);\n }\n const templateLine = templateOpportunityLine(report);\n if (!templateLine.startsWith('No dominant')) {\n bullets.push(templateLine);\n }\n if (report.quickWins.verification.requested) {\n bullets.push(`Verified content for ${report.quickWins.verification.verified} of ${report.quickWins.items.length} quick-win candidates; ${gapCountLine(report)}`);\n const fetchLine = verificationFetchLine(report);\n if (fetchLine)\n bullets.push(fetchLine);\n }\n if (!bullets.length) {\n bullets.push('No material content opportunity stood out in this window. Keep monitoring, but do not force content edits from this report alone.');\n }\n return bullets;\n}\n//# sourceMappingURL=sections.js.map","import { countLabel } from '../../phrasing.js';\nimport { diagnoseProperty } from '../diagnose-property.js';\nimport { listChanges } from '../experiments.js';\nimport { latestCrawlSummaries, latestIndexWatchSummary, latestLinkRecoverSummary, } from '../monitoring.js';\nimport { changeMeasurementCaveats, measureSavedChanges, narrativeDataStatus, } from './change-measurements.js';\nimport { rangeDays } from './dates.js';\nimport { renderMarkdown } from './markdown.js';\nimport { changeMeasurementLine, contentOpportunityBullets, diagnosisAvailabilityCaveats, headlineLine, monitoringBullets, movementLine, topSegmentLine, updateAttributionLine, } from './sections.js';\nfunction reportCaveats(input) {\n return [\n `Date window: ${input.period.startDate} to ${input.period.endDate}.`,\n `Brand queries: ${input.includeBrand\n ? 'included'\n : input.brandTerms?.length\n ? 'excluded where saved brand terms matched'\n : 'no saved brand terms, so no brand filter was applied'}.`,\n `Data freshness: ${input.refresh ? 'fresh fetch requested; local cache bypassed where supported' : 'local cache allowed; rerun with --refresh to bypass cached GSC/HTTP data'}.`,\n input.skipSearchData\n ? 'Search Console: skipped because no property was selected. Run `seo start` to add performance evidence.'\n : 'Search Console: included where the selected property returned usable data.',\n 'GA4: not included in this narrative; use refresh-priorities when GA4 value should influence prioritisation.',\n input.skipSearchData\n ? 'Content verification: not run because Search Console did not provide page candidates for this report.'\n : input.verifyContent\n ? `Content verification: checked ${input.verified} of ${countLabel(input.quickWinCount, 'quick-win candidate')}, limit ${input.verifyLimit ?? 3}.`\n : 'Content verification: not run; recommendations are based on GSC/query data unless stated otherwise.',\n ];\n}\nexport async function reportNarrative(input) {\n const periodDays = input.days ?? 90;\n if ((input.startDate && !input.endDate) ||\n (!input.startDate && input.endDate)) {\n throw new Error('Pass both startDate and endDate, or neither.');\n }\n const period = input.startDate && input.endDate\n ? { startDate: input.startDate, endDate: input.endDate }\n : undefined;\n input.progress?.('Running diagnosis primitives');\n const diagnosis = await diagnoseProperty({\n site: input.site,\n days: period ? rangeDays(period) : periodDays,\n recentDays: input.recentDays,\n startDate: period?.startDate,\n endDate: period?.endDate,\n limit: input.limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n verifyContent: input.verifyContent,\n verifyLimit: input.verifyLimit,\n js: input.js,\n rate: input.rate,\n refresh: input.refresh,\n skipSearchData: input.skipSearchData,\n progress: input.progress,\n });\n input.progress?.('Measuring saved changes');\n const changes = listChanges({\n site: input.site,\n limit: input.changeLimit ?? 5,\n });\n const changeMeasurementAttempts = await measureSavedChanges(changes, {\n refresh: input.refresh,\n });\n const changeMeasurements = changeMeasurementAttempts.flatMap((attempt) => attempt.status === 'measured' ? [attempt.measurement] : []);\n const monitoring = {\n crawlRuns: latestCrawlSummaries(input.site),\n indexWatch: latestIndexWatchSummary(input.site),\n linkRecover: latestLinkRecoverSummary(input.site),\n };\n input.progress?.('Rendering narrative');\n const diagnosisPeriod = period ?? {\n startDate: diagnosis.anomaly.anomalies[0]?.baselineStart ??\n diagnosis.quickWins.range.startDate,\n endDate: diagnosis.anomaly.anomalies[0]?.comparisonEnd ??\n diagnosis.quickWins.range.endDate,\n };\n const report = {\n site: input.site,\n generatedAt: new Date().toISOString(),\n dataStatus: narrativeDataStatus(diagnosis.dataStatus, changeMeasurementAttempts),\n periodDays: period ? rangeDays(period) : periodDays,\n period: diagnosisPeriod,\n headline: headlineLine(diagnosis),\n caveats: [\n ...reportCaveats({\n period: diagnosisPeriod,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n refresh: input.refresh,\n verifyContent: input.verifyContent,\n verifyLimit: input.verifyLimit,\n verified: diagnosis.quickWins.verification.verified,\n quickWinCount: diagnosis.quickWins.items.length,\n skipSearchData: input.skipSearchData,\n }),\n ...diagnosisAvailabilityCaveats(diagnosis),\n ...changeMeasurementCaveats(changeMeasurementAttempts),\n ],\n sections: [\n {\n title: 'Performance',\n bullets: [\n movementLine(diagnosis),\n topSegmentLine(diagnosis),\n updateAttributionLine(diagnosis),\n ],\n },\n {\n title: 'Content Opportunities',\n bullets: contentOpportunityBullets(diagnosis),\n },\n {\n title: 'Change Measurements',\n bullets: changeMeasurementAttempts.length\n ? changeMeasurementAttempts.map(changeMeasurementLine)\n : ['No measured changes are saved for this property yet.'],\n },\n {\n title: 'Technical Monitoring',\n bullets: monitoringBullets({ monitoring }),\n },\n ],\n priorities: diagnosis.priorities.map((priority) => ({\n title: priority.label,\n confidence: priority.confidence,\n action: priority.action,\n })),\n diagnosis,\n changeMeasurements,\n changeMeasurementAttempts,\n monitoring,\n };\n return { ...report, markdown: renderMarkdown(report) };\n}\n//# sourceMappingURL=narrative.js.map","import { finalGscDate, monthRange, rangeDays } from './dates.js';\nimport { reportNarrative } from './narrative.js';\nexport async function monthlyReport(input) {\n const month = input.month ?? finalGscDate().slice(0, 7);\n const period = monthRange(month);\n input.progress?.(`Preparing monthly period ${month}`);\n const report = await reportNarrative({\n site: input.site,\n startDate: period.startDate,\n endDate: period.endDate,\n recentDays: Math.min(14, Math.max(3, rangeDays(period))),\n limit: input.limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n verifyContent: input.verifyContent,\n verifyLimit: input.verifyLimit,\n js: input.js,\n rate: input.rate,\n refresh: input.refresh,\n progress: input.progress,\n });\n return {\n ...report,\n month,\n markdown: report.markdown.replace(`# SEO report: ${input.site}`, `# Monthly SEO report (${month}): ${input.site}`),\n };\n}\n//# sourceMappingURL=monthly.js.map","export function reportPresentation(report) {\n return {\n tables: [\n {\n id: 'report_caveats',\n title: 'Report Caveats',\n columns: [{ key: 'caveat', label: 'Caveat' }],\n rows: report.caveats.map((caveat) => ({ caveat })),\n },\n {\n id: 'report_sections',\n title: 'Report Sections',\n columns: [\n { key: 'section', label: 'Section' },\n { key: 'finding', label: 'Finding' },\n ],\n rows: report.sections.flatMap((section) => section.bullets.map((finding) => ({\n section: section.title,\n finding,\n }))),\n },\n {\n id: 'report_priorities',\n title: 'Report Priorities',\n columns: [\n { key: 'priority', label: 'Priority', type: 'number' },\n { key: 'title', label: 'Title' },\n { key: 'confidence', label: 'Confidence' },\n { key: 'action', label: 'Action' },\n ],\n rows: report.priorities.map((priority, index) => ({\n priority: index + 1,\n title: priority.title,\n confidence: priority.confidence,\n action: priority.action,\n })),\n },\n ],\n charts: [],\n };\n}\n//# sourceMappingURL=presentation.js.map","import { shouldExcludeBrandQuery } from '../brand.js';\nimport { detectPageTemplate } from './page-patterns.js';\nconst DEFAULT_MIN_IMPRESSIONS = 50;\nconst MAX_MIN_IMPRESSIONS = 1_000_000_000;\nconst DEFAULT_LIMIT = 10;\nconst MAX_LIMIT = 100;\nfunction integerInRange(value, fallback, minimum, maximum) {\n if (value === undefined || !Number.isFinite(value))\n return fallback;\n return Math.min(maximum, Math.max(minimum, Math.floor(value)));\n}\nfunction compareText(left, right) {\n const leftPoints = [...left].map((character) => character.codePointAt(0) ?? 0);\n const rightPoints = [...right].map((character) => character.codePointAt(0) ?? 0);\n for (let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index++) {\n const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);\n if (difference !== 0)\n return difference;\n }\n return leftPoints.length - rightPoints.length;\n}\nfunction normalizedHttpUrl(value) {\n try {\n const url = new URL(value);\n if (url.protocol !== 'http:' && url.protocol !== 'https:')\n return undefined;\n url.hash = '';\n return url.toString();\n }\n catch {\n return undefined;\n }\n}\nfunction validRow(row, query, url) {\n return (Boolean(query && url) &&\n Number.isFinite(row.clicks) &&\n Number.isFinite(row.impressions) &&\n Number.isFinite(row.ctr) &&\n Number.isFinite(row.position) &&\n row.clicks >= 0 &&\n row.impressions > 0 &&\n row.clicks <= row.impressions &&\n row.ctr >= 0 &&\n row.ctr <= 1 &&\n row.position > 0);\n}\nfunction queryFromRow(row) {\n return {\n query: row.keys[0]?.trim() ?? '',\n clicks: Number(row.clicks.toFixed(3)),\n impressions: Number(row.impressions.toFixed(3)),\n ctr: Number(row.ctr.toFixed(4)),\n position: Number(row.position.toFixed(2)),\n };\n}\nfunction compareQueries(left, right) {\n return (right.impressions - left.impressions ||\n left.position - right.position ||\n right.clicks - left.clicks ||\n compareText(left.query, right.query));\n}\nfunction recommendation(input) {\n return {\n type: 'investigate-ranking',\n confidence: 'low',\n evidence: `GSC reports ${input.impressions} eligible impressions at an impression-weighted average position of ${input.position.toFixed(2)} for ${input.url}.`,\n action: `Inspect indexability, canonical state, query coverage, competing URLs, and relevant internal links for ${input.url} before choosing a change. Start with \"${input.primaryQuery}\" as the highest-impression query in this page group.`,\n };\n}\nfunction pageItem(url, rows) {\n const queries = rows.map(queryFromRow).sort(compareQueries);\n const impressions = queries.reduce((sum, query) => sum + query.impressions, 0);\n const clicks = queries.reduce((sum, query) => sum + query.clicks, 0);\n const position = queries.reduce((sum, query) => sum + query.position * query.impressions, 0) / impressions;\n const proximity = Math.min(1, Math.max(0.1, (21 - position) / 10));\n const primaryQuery = queries[0]?.query ?? '';\n const nextRecommendation = recommendation({\n url,\n primaryQuery,\n impressions,\n position,\n });\n return {\n url,\n primaryQuery,\n template: detectPageTemplate(url),\n queries,\n queryCount: queries.length,\n clicks: Number(clicks.toFixed(3)),\n impressions: Number(impressions.toFixed(3)),\n ctr: Number((clicks / impressions).toFixed(4)),\n position: Number(position.toFixed(2)),\n priority: {\n method: 'impressions_x_position_proximity',\n score: Number((impressions * proximity).toFixed(2)),\n demandImpressions: Number(impressions.toFixed(3)),\n positionProximity: Number(proximity.toFixed(4)),\n heuristic: true,\n estimatedClickLift: false,\n },\n finding: 'unverified',\n recommendation: nextRecommendation,\n };\n}\nfunction compareItems(left, right) {\n return (right.priority.score - left.priority.score ||\n right.impressions - left.impressions ||\n left.position - right.position ||\n compareText(left.url, right.url));\n}\nexport function analyzeSecondPageRows(input) {\n const minImpressions = integerInRange(input.minImpressions, DEFAULT_MIN_IMPRESSIONS, 0, MAX_MIN_IMPRESSIONS);\n const limit = integerInRange(input.limit, DEFAULT_LIMIT, 1, MAX_LIMIT);\n const selection = {\n sourceRows: input.rows.length,\n invalidRows: 0,\n outsidePositionRows: 0,\n brandRows: 0,\n eligibleRows: 0,\n sourcePages: 0,\n belowMinimumPages: 0,\n eligiblePages: 0,\n returnedPages: 0,\n limitedPages: 0,\n };\n const grouped = new Map();\n for (const row of input.rows) {\n const query = row.keys[0]?.trim() ?? '';\n const url = normalizedHttpUrl(row.keys[1]?.trim() ?? '');\n if (!validRow(row, query, url)) {\n selection.invalidRows++;\n }\n else if (row.position <= 10 || row.position > 20) {\n selection.outsidePositionRows++;\n }\n else if (shouldExcludeBrandQuery({\n query,\n siteUrl: input.site,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n })) {\n selection.brandRows++;\n }\n else {\n const rows = grouped.get(url ?? '') ?? [];\n rows.push({ ...row, keys: [query, url ?? ''] });\n grouped.set(url ?? '', rows);\n selection.eligibleRows++;\n }\n }\n selection.sourcePages = grouped.size;\n const aggregated = [...grouped.entries()].map(([url, rows]) => pageItem(url, rows));\n const eligibleItems = aggregated\n .filter((item) => {\n if (item.impressions >= minImpressions)\n return true;\n selection.belowMinimumPages++;\n return false;\n })\n .sort(compareItems);\n const items = eligibleItems.slice(0, limit);\n selection.eligiblePages = eligibleItems.length;\n selection.returnedPages = items.length;\n selection.limitedPages = eligibleItems.length - items.length;\n const eligibleClicks = eligibleItems.reduce((sum, item) => sum + item.clicks, 0);\n const eligibleImpressions = eligibleItems.reduce((sum, item) => sum + item.impressions, 0);\n const returnedClicks = items.reduce((sum, item) => sum + item.clicks, 0);\n const returnedImpressions = items.reduce((sum, item) => sum + item.impressions, 0);\n return {\n site: input.site,\n minImpressions,\n limit,\n dataStatus: input.rows.length === 0\n ? 'empty'\n : eligibleItems.length === 0\n ? 'filtered'\n : 'available',\n selection,\n methodology: {\n id: 'gsc_second_page_v2',\n source: 'google_search_console_query_page_rows',\n position: {\n metric: 'gsc_average_position',\n minimumExclusive: 10,\n maximumInclusive: 20,\n appliedAt: 'query_page_row',\n },\n aggregation: {\n unit: 'page',\n minimumImpressionsAppliedAt: 'eligible_page_aggregate',\n ctr: 'sum_clicks_divided_by_sum_impressions',\n position: 'impression_weighted_query_page_position',\n queries: 'all_eligible_queries_retained',\n },\n priority: {\n method: 'impressions_x_position_proximity',\n formula: 'page impressions * clamp((21 - weighted position) / 10, 0.1, 1)',\n heuristic: true,\n estimatedClickLift: false,\n },\n },\n provenance: {\n inputScope: 'provided_rows',\n selectionOrder: [\n 'valid_row',\n 'position',\n 'brand',\n 'page_aggregation',\n 'minimum_page_impressions',\n 'priority',\n 'limit',\n ],\n selection,\n },\n summary: {\n eligiblePages: eligibleItems.length,\n returnedPages: items.length,\n eligibleTemplates: new Set(eligibleItems.map((item) => item.template.id))\n .size,\n returnedTemplates: new Set(items.map((item) => item.template.id)).size,\n eligibleQueries: eligibleItems.reduce((sum, item) => sum + item.queryCount, 0),\n returnedQueries: items.reduce((sum, item) => sum + item.queryCount, 0),\n eligibleClicks: Number(eligibleClicks.toFixed(3)),\n eligibleImpressions: Number(eligibleImpressions.toFixed(3)),\n returnedClicks: Number(returnedClicks.toFixed(3)),\n returnedImpressions: Number(returnedImpressions.toFixed(3)),\n },\n items,\n };\n}\n//# sourceMappingURL=second-page-analysis.js.map","import { SeoError } from '../errors.js';\nimport { extractPage } from '../extract/page-extractor.js';\nimport { fetchPage } from '../fetch/page-fetcher.js';\nimport { querySearchAnalytics } from '../gsc/client.js';\nimport { finalGscDateRange } from '../gsc/dates.js';\nimport { SessionLedger } from '../storage/ledger.js';\nimport { contentCoverageRecommendation, verifyQueryContent, } from './content-coverage.js';\nimport { analyzeSecondPageRows, } from './second-page-analysis.js';\nexport * from './second-page-analysis.js';\nconst MAX_SOURCE_ROWS = 100_000;\nconst defaultDependencies = {\n searchAnalytics: querySearchAnalytics,\n fetch: fetchPage,\n extract: extractPage,\n now: () => new Date(),\n};\nfunction integerOption(input) {\n if (input.value === undefined)\n return input.fallback;\n if (!Number.isInteger(input.value) ||\n input.value < input.minimum ||\n input.value > input.maximum) {\n throw new SeoError('INVALID_INPUT', `${input.label} must be a whole number between ${input.minimum} and ${input.maximum}.`);\n }\n return input.value;\n}\nfunction unique(values) {\n return [...new Set(values.filter(Boolean))];\n}\nfunction uniqueWarnings(warnings) {\n return [\n ...new Map(warnings.map((warning) => [\n `${warning.stage}\\u0000${warning.url}\\u0000${warning.code}\\u0000${warning.message}`,\n warning,\n ])).values(),\n ];\n}\nfunction reportDateRange(days, now) {\n return finalGscDateRange(days, now);\n}\nfunction findingFor(coverage) {\n const evidence = coverage.error ?? coverage.summary;\n if (coverage.status === 'failed') {\n return {\n type: 'inspect-fetch',\n confidence: 'medium',\n evidence,\n action: contentCoverageRecommendation(coverage),\n };\n }\n if (coverage.classification === 'technical-check') {\n return {\n type: 'fix-technical',\n confidence: 'medium',\n evidence,\n action: contentCoverageRecommendation(coverage),\n };\n }\n if (coverage.classification === 'content-gap') {\n return {\n type: 'fix-content-gap',\n confidence: 'medium',\n evidence,\n action: contentCoverageRecommendation(coverage),\n };\n }\n if (coverage.classification === 'serp-framing') {\n return {\n type: 'improve-serp-framing',\n confidence: 'medium',\n evidence,\n action: contentCoverageRecommendation(coverage),\n };\n }\n return {\n type: 'investigate-ranking',\n confidence: 'low',\n evidence,\n action: `The page covers \"${coverage.query}\". Inspect internal links, competing URLs, intent alignment, and the search results before changing copy.`,\n };\n}\nfunction applyVerification(item, coverage) {\n const recommendation = findingFor(coverage);\n item.contentVerification = coverage;\n item.fetchDiagnostics = coverage.fetchDiagnostics;\n item.finding = recommendation.type;\n item.recommendation = recommendation;\n}\nfunction verdict(report) {\n if (report.dataStatus === 'empty') {\n return 'Google Search Console returned no retained query/page rows for this window.';\n }\n if (report.dataStatus === 'filtered') {\n return 'No pages met the position, brand, and minimum-impression criteria.';\n }\n if (report.technical > 0) {\n return `${report.eligible} eligible average-position pages found; ${report.technical} returned pages have verified technical issues to fix before content changes.`;\n }\n if (report.failed > 0) {\n return `${report.eligible} eligible average-position pages found; ${report.failed} returned pages could not be verified and need a fetch check before content changes.`;\n }\n if (report.content > 0) {\n return `${report.eligible} eligible average-position pages found; ${report.content} returned pages have verified content or search-framing gaps.`;\n }\n return `${report.eligible} eligible average-position pages found; ${report.returned} are returned in priority order for investigation.`;\n}\nfunction reportRecommendations(items) {\n const first = items[0];\n if (!first) {\n return [\n 'Widen the date window or lower the minimum page impressions only if you need to inspect smaller opportunities.',\n ];\n }\n return unique([\n first.recommendation.action,\n 'Review page-level query groups before creating another URL; several queries may already map to the same ranking page.',\n 'Treat the priority score as a triage heuristic, not an estimated traffic lift.',\n ]);\n}\nexport async function secondPage(input, dependencies = defaultDependencies) {\n const days = integerOption({\n value: input.range,\n fallback: 28,\n minimum: 1,\n maximum: 548,\n label: 'Days',\n });\n const verifyLimit = integerOption({\n value: input.verifyLimit,\n fallback: 5,\n minimum: 0,\n maximum: 100,\n label: 'Verification limit',\n });\n const now = dependencies.now();\n const range = reportDateRange(days, now);\n const result = await dependencies.searchAnalytics(input.site, {\n ...range,\n dimensions: ['query', 'page'],\n type: 'web',\n dataState: 'final',\n maxRows: MAX_SOURCE_ROWS,\n }, { refresh: input.refresh });\n const ledger = new SessionLedger();\n ledger.addGsc(result.calls, result.rowsFetched);\n const analysis = analyzeSecondPageRows({\n rows: result.rows,\n site: input.site,\n minImpressions: input.minImpressions,\n limit: input.limit,\n brandTerms: input.brandTerms,\n includeBrand: input.includeBrand,\n });\n const generatedAt = now.toISOString();\n const warnings = [];\n const verificationRequested = input.verifyContent === true || input.verifyLimit !== undefined;\n const verificationItems = verificationRequested\n ? analysis.items.slice(0, verifyLimit)\n : [];\n for (const item of verificationItems) {\n const coverage = await verifyQueryContent({\n query: item.primaryQuery,\n url: item.url,\n js: input.js,\n refresh: input.refresh,\n rate: input.rate,\n verifiedAt: generatedAt,\n fetch: dependencies.fetch,\n extract: dependencies.extract,\n });\n applyVerification(item, coverage);\n warnings.push(...(coverage.warnings ?? []).map((message) => ({\n stage: 'verification',\n url: item.url,\n code: 'page-warning',\n message,\n })));\n if (coverage.error) {\n warnings.push({\n stage: 'verification',\n url: item.url,\n code: 'verification-failed',\n message: coverage.error,\n });\n }\n }\n const verified = verificationItems.filter((item) => item.contentVerification?.status === 'verified').length;\n const failed = verificationItems.filter((item) => item.contentVerification?.status === 'failed').length;\n const technicalIssues = verificationItems.filter((item) => item.finding === 'fix-technical').length;\n const contentIssues = verificationItems.filter((item) => ['fix-content-gap', 'improve-serp-framing'].includes(item.finding)).length;\n return {\n site: input.site,\n range: days,\n dateRange: range,\n generatedAt,\n source: {\n provider: 'google-search-console',\n dimensions: ['query', 'page'],\n searchType: 'web',\n dataState: 'final',\n rowsFetched: result.rowsFetched,\n calls: result.calls,\n maxRows: MAX_SOURCE_ROWS,\n possiblyTruncated: result.rowsFetched >= MAX_SOURCE_ROWS,\n completeness: 'retained-query-rows-only',\n },\n dataStatus: analysis.dataStatus,\n selection: analysis.selection,\n methodology: analysis.methodology,\n provenance: {\n ...analysis.provenance,\n verification: {\n optional: true,\n population: 'returned_pages_in_priority_order',\n },\n },\n summary: {\n ...analysis.summary,\n contentIssues,\n technicalIssues,\n fetchFailures: failed,\n brandFiltering: input.includeBrand ? 'included' : 'excluded',\n verdict: verdict({\n dataStatus: analysis.dataStatus,\n eligible: analysis.summary.eligiblePages,\n returned: analysis.summary.returnedPages,\n technical: technicalIssues,\n failed,\n content: contentIssues,\n }),\n },\n verification: verificationRequested\n ? {\n requested: true,\n limit: verifyLimit,\n attempted: verificationItems.length,\n verified,\n failed,\n technicalChecks: technicalIssues,\n }\n : { requested: false, attempted: 0, verified: 0, failed: 0 },\n items: analysis.items,\n caveats: [\n `Date window: ${range.startDate} to ${range.endDate}, using final GSC data where available.`,\n `Selection: ${analysis.selection.sourceRows} source rows, ${analysis.selection.eligibleRows} eligible query/page rows, ${analysis.selection.eligiblePages} eligible page groups, ${analysis.selection.returnedPages} returned.`,\n `Positions use GSC average position per query/page row and must be greater than 10 and at most 20. Page position is impression-weighted across retained queries.`,\n `Minimum impressions (${analysis.minImpressions}) are applied after eligible rows are aggregated by page.`,\n verificationRequested\n ? `Content verification was attempted for the first ${verificationItems.length} returned pages in priority order.`\n : 'Content verification was not requested; unverified items are investigation prompts, not content findings.',\n 'Priority is a deterministic demand-and-position heuristic. It is not an estimated click or ranking lift.',\n 'Search Analytics exposes retained query rows only. Anonymized and lower-value queries can be absent even when pagination is exhausted.',\n result.rowsFetched >= MAX_SOURCE_ROWS\n ? `The report reached its ${MAX_SOURCE_ROWS.toLocaleString('en-US')}-row safety cap.`\n : '',\n ].filter(Boolean),\n recommendations: reportRecommendations(analysis.items),\n ledgerSummary: ledger.summary(),\n warnings: uniqueWarnings(warnings),\n };\n}\n//# sourceMappingURL=second-page.js.map","import { normalizeText } from './shared.js';\nconst QUESTION_START = /^(?:how|what|why|when|where|who|which|can|could|do|does|is|are|should|would)\\b/i;\nconst LEADING_QUESTION = /^(?:(?:how\\s+(?:many|much)|what|which|who|why|when|where)\\s+(?:do|does|did|is|are|can|could|should|would)?|how\\s+to|can|could|do|does|did|is|are|should|would)\\s+/i;\nconst LEADING_CHOICE = /^how\\s+(?:(?:do|can|should|would)\\s+(?:i|we|you|someone)\\s+|to\\s+)(?:choose|find|pick|use|compare)\\s+/i;\nconst LEADING_DECISION = /^(?:can|could|do|does|did|should|would)\\s+(?:i|we|you|someone|they|he|she)\\s+(?:use|choose|buy|get|try|consider|pick|find|hire)\\s+/i;\nconst COMMERCIAL_TERM = /\\b(?:best|vs|versus|reviews?|worth|alternatives?)\\b/;\nconst PRICE_TERM = /\\b(?:price|cost|salary|rate|fee|fees)\\b/;\nconst REVIEW_TERM = /\\b(?:review|reviews|worth)\\b/;\nfunction compactQuery(query) {\n return query.normalize('NFC').replace(/\\s+/g, ' ').trim();\n}\nfunction querySubject(query) {\n const compact = compactQuery(query);\n const subject = compact\n .replace(LEADING_CHOICE, '')\n .replace(LEADING_DECISION, '')\n .replace(LEADING_QUESTION, '')\n .replace(/^(?:the\\s+)?(?:best|top\\s+\\d+)\\s+/i, '')\n .replace(/^(?:reviews?)(?:\\s+(?:of|for))?\\s+/i, '')\n .replace(/\\s+(?:reviews?|worth\\s+it)$/i, '')\n .replace(/[?.!]+$/, '')\n .trim();\n return subject || compact.replace(/[?.!]+$/, '');\n}\nfunction comparisonParts(query) {\n const parts = compactQuery(query)\n .replace(/[?.!]+$/, '')\n .split(/\\s+(?:vs\\.?|versus)\\s+/i)\n .map((part) => part.trim());\n return parts.length === 2 && parts[0] && parts[1]\n ? [parts[0], parts[1]]\n : undefined;\n}\nexport function aiPromptsForQuery(query) {\n const compact = compactQuery(query);\n if (!compact)\n return [];\n const normalized = normalizeText(compact);\n const subject = querySubject(compact);\n const comparison = comparisonParts(compact);\n const prompts = new Set();\n if (QUESTION_START.test(compact)) {\n prompts.add(`${compact.replace(/[?.!]+$/, '')}?`);\n }\n prompts.add(`What should someone know about ${subject}?`);\n prompts.add(`Explain ${subject}, including key facts and caveats.`);\n if (/\\bbest\\b/.test(normalized)) {\n prompts.add(`Which ${subject} options are strongest for different needs, and why?`);\n }\n if (comparison) {\n prompts.add(`Compare ${comparison[0]} and ${comparison[1]}, including tradeoffs and use-case fit.`);\n }\n if (PRICE_TERM.test(normalized)) {\n prompts.add(`What factors determine ${subject}?`);\n }\n if (REVIEW_TERM.test(normalized)) {\n prompts.add(`Is ${subject} worth considering? Include evidence, pros, cons, and alternatives.`);\n }\n prompts.add(COMMERCIAL_TERM.test(normalized)\n ? `What criteria should someone use to evaluate ${subject}?`\n : `What evidence or data supports claims about ${subject}?`);\n return [...prompts].slice(0, 5);\n}\n//# sourceMappingURL=ai-monitoring-prompts.js.map","import { aiPromptsForQuery } from './ai-monitoring-prompts.js';\nimport { defaultQueryOpportunityDependencies, queryOpportunityEvidence, } from './query-opportunity-source.js';\nexport * from './ai-monitoring-prompts.js';\nfunction reportStatus(input) {\n if (input.sourceRows === 0)\n return 'empty';\n if (input.partial)\n return 'partial';\n return input.eligibleRows === 0 ? 'filtered' : 'available';\n}\nexport async function seoToAiQueryReport(input, dependencies = defaultQueryOpportunityDependencies) {\n const evidence = await queryOpportunityEvidence(input, dependencies);\n const rows = evidence.rows.slice(0, evidence.filters.limit);\n const items = rows.map((row) => ({\n ...row,\n evidenceScope: 'retained-gsc-query',\n prompts: aiPromptsForQuery(row.query),\n }));\n const partial = evidence.source.possiblyTruncated ||\n evidence.selection.invalidRows > 0 ||\n evidence.selection.conflictingRows > 0;\n const dataStatus = reportStatus({\n sourceRows: evidence.selection.sourceRows,\n eligibleRows: evidence.selection.eligibleRows,\n partial,\n });\n const verdict = dataStatus === 'empty'\n ? 'GSC returned no retained query rows for this range.'\n : dataStatus === 'partial' && items.length === 0\n ? 'No prompt candidates survived the retained rows and filters, but incomplete source evidence makes that negative inconclusive.'\n : dataStatus === 'partial'\n ? `Partial evidence: ${items.length} retained GSC queries were converted into prompt suggestions, but incomplete source rows may omit other queries.`\n : dataStatus === 'filtered'\n ? `No retained ${input.includeBrand ? '' : 'non-brand '}queries met the minimum-impression threshold.`\n : `${items.length} retained GSC queries were converted into deterministic monitoring-prompt suggestions; these are not observed AI prompts.`;\n return {\n schemaVersion: 2,\n site: evidence.site,\n generatedAt: evidence.generatedAt,\n rangeDays: evidence.rangeDays,\n dateRange: evidence.dateRange,\n dataStatus,\n source: evidence.source,\n filters: {\n ...evidence.filters,\n brandFiltering: input.includeBrand ? 'included' : 'excluded',\n },\n methodology: {\n id: 'gsc_query_to_ai_monitoring_prompt',\n version: 2,\n sourceUnit: 'retained-query-row',\n promptType: 'deterministic-template-heuristic',\n observedAiPromptData: false,\n estimatedTrafficLift: false,\n },\n selection: {\n ...evidence.selection,\n returnedRows: items.length,\n limitedRows: evidence.selection.eligibleRows - items.length,\n },\n summary: {\n eligibleQueries: evidence.selection.eligibleRows,\n returnedQueries: items.length,\n prompts: items.reduce((sum, item) => sum + item.prompts.length, 0),\n verdict,\n },\n items,\n warnings: evidence.warnings,\n caveats: [\n ...evidence.caveats,\n 'Generated prompts are deterministic monitoring suggestions derived from GSC query wording, not evidence of demand in any AI product.',\n ],\n };\n}\n//# sourceMappingURL=seo-to-ai-query.js.map","const SOURCE_WEIGHT = {\n decay: 1.25,\n 'quick-win': 1.15,\n 'striking-distance': 1,\n cannibalization: 0.9,\n diagnosis: 0.75,\n template: 1.35,\n crawl: 1.3,\n};\nconst CONFIDENCE_WEIGHT = {\n high: 1.2,\n medium: 1,\n low: 0.7,\n};\nconst EFFORT_WEIGHT = {\n S: 1.15,\n M: 1,\n L: 0.8,\n};\nconst VERIFICATION_WEIGHT = {\n 'technical-check': 1.25,\n 'content-gap': 1.2,\n 'serp-framing': 1.1,\n covered: 0.85,\n 'fetch-failed': 0.7,\n};\nfunction boundedLogScore(value) {\n if (!Number.isFinite(value) || value <= 0)\n return 0;\n return Math.min(100, Math.log1p(value) * 12);\n}\nfunction templateLeverage(count = 1) {\n if (count <= 1)\n return 1;\n return Math.min(1.6, 1 + Math.log1p(count - 1) / 8);\n}\nfunction analyticsBoost(sessions = 0) {\n if (sessions <= 0)\n return 1;\n return Math.min(1.35, 1 + Math.log1p(sessions) / 30);\n}\nexport function priorityCategory(source, verification) {\n if (verification === 'technical-check')\n return 'technical';\n if (verification === 'content-gap')\n return 'content';\n if (verification === 'serp-framing' || verification === 'covered') {\n return 'serp';\n }\n if (source === 'cannibalization')\n return 'authority';\n if (source === 'template')\n return 'strategy';\n if (source === 'diagnosis')\n return 'strategy';\n if (source === 'crawl')\n return 'technical';\n return source === 'decay' ? 'content' : 'serp';\n}\nexport function scorePriority(input) {\n const impact = boundedLogScore(input.impact);\n const source = SOURCE_WEIGHT[input.source];\n const confidence = CONFIDENCE_WEIGHT[input.confidence];\n const effort = EFFORT_WEIGHT[input.effort ?? 'M'];\n const verification = input.verification\n ? VERIFICATION_WEIGHT[input.verification]\n : 1;\n const template = templateLeverage(input.templateCount);\n const analytics = analyticsBoost(input.analyticsSessions);\n const final = impact * source * confidence * effort * verification * template;\n return {\n impact: Number(impact.toFixed(2)),\n source: Number(source.toFixed(2)),\n confidence: Number(confidence.toFixed(2)),\n effort: Number(effort.toFixed(2)),\n verification: Number(verification.toFixed(2)),\n template: Number(template.toFixed(2)),\n analytics: Number(analytics.toFixed(2)),\n final: Number(final.toFixed(2)),\n };\n}\n//# sourceMappingURL=priority-scoring.js.map","export function workflowReport(input) {\n return {\n workflow: input.workflow,\n site: input.site,\n generatedAt: new Date().toISOString(),\n summary: input.summary,\n steps: input.steps,\n actions: input.actions,\n output: input.output,\n };\n}\n//# sourceMappingURL=report.js.map","import { reportNarrative } from '../reports.js';\nimport { workflowReport } from './report.js';\nexport async function diagnosePropertyWorkflow(input) {\n const narrative = await reportNarrative(input);\n const skippedCount = narrative.diagnosis.skippedSections?.length ?? 0;\n const stepSummary = narrative.dataStatus === 'complete'\n ? 'Generated diagnosis, movement, change, and monitoring narrative.'\n : skippedCount\n ? `Generated ${narrative.dataStatus === 'unavailable' ? 'an' : 'a'} ${narrative.dataStatus} diagnosis; ${skippedCount} sections were unavailable.`\n : 'Generated a partial diagnosis because one or more source datasets were incomplete.';\n return workflowReport({\n workflow: 'diagnose-property',\n site: input.site,\n summary: narrative.headline,\n steps: [\n {\n tool: 'seo_report_narrative',\n status: 'completed',\n summary: stepSummary,\n },\n ],\n actions: narrative.priorities.map((priority) => ({\n title: priority.title,\n action: priority.action,\n confidence: priority.confidence,\n })),\n output: { narrative },\n });\n}\n//# sourceMappingURL=diagnose-property.js.map","function isRecord(value) {\n return typeof value === 'object' && value !== null;\n}\nfunction priorityQueue(output) {\n if (!isRecord(output))\n return [];\n const queue = output.queue;\n if (!Array.isArray(queue))\n return [];\n return queue.filter((item) => isRecord(item));\n}\nfunction stepsTable(report) {\n if (!report.steps.length)\n return undefined;\n return {\n id: 'steps',\n title: 'Steps',\n columns: [\n { key: 'tool', label: 'Tool' },\n { key: 'status', label: 'Status' },\n { key: 'summary', label: 'Summary' },\n ],\n rows: report.steps.map((step) => ({\n tool: step.tool,\n status: step.status,\n summary: step.summary,\n })),\n };\n}\nfunction actionsTable(report) {\n if (!report.actions.length)\n return undefined;\n return {\n id: 'recommended_actions',\n title: 'Recommended Actions',\n columns: [\n { key: 'priority', label: 'Priority', type: 'number' },\n { key: 'title', label: 'Title' },\n { key: 'confidence', label: 'Confidence' },\n { key: 'action', label: 'Action' },\n ],\n rows: report.actions.map((action, index) => ({\n priority: index + 1,\n title: action.title,\n confidence: action.confidence,\n action: action.action,\n })),\n };\n}\nfunction queueTable(queue, limit) {\n if (!queue.length)\n return undefined;\n return {\n id: 'priority_queue',\n title: 'Priority Queue',\n columns: [\n { key: 'rank', label: 'Rank', type: 'number' },\n { key: 'source', label: 'Source' },\n { key: 'category', label: 'Category' },\n { key: 'score', label: 'Score', type: 'number' },\n { key: 'confidence', label: 'Confidence' },\n { key: 'target', label: 'Target', type: 'url' },\n { key: 'action', label: 'Action' },\n ],\n rows: queue.slice(0, limit).map((item, index) => ({\n rank: index + 1,\n source: item.source,\n category: item.category,\n score: Number(item.score.toFixed(1)),\n confidence: item.confidence,\n target: item.target,\n action: item.action,\n })),\n };\n}\nexport function workflowPresentation(report, options = {}) {\n const queue = priorityQueue(report.output);\n const tables = [\n stepsTable(report),\n actionsTable(report),\n queueTable(queue, options.queueLimit ?? 10),\n ].filter((table) => Boolean(table));\n const charts = queue.length\n ? [\n {\n id: 'priority_scores',\n title: 'Priority Scores',\n type: 'bar',\n tableId: 'priority_queue',\n xKey: 'rank',\n yKey: 'score',\n },\n ]\n : [];\n return { tables, charts };\n}\n//# sourceMappingURL=presentation.js.map","import { renderPresentationTablesMarkdown } from '../../markdown.js';\nimport { workflowPresentation } from './presentation.js';\nexport function renderWorkflowMarkdown(report, options = {}) {\n const presentation = workflowPresentation(report, options);\n const lines = [\n `# ${report.workflow}`,\n '',\n `Property: ${report.site}`,\n `Generated: ${report.generatedAt}`,\n '',\n report.summary,\n '',\n ...renderPresentationTablesMarkdown(presentation.tables),\n ];\n return lines.join('\\n').trim();\n}\n//# sourceMappingURL=markdown.js.map","import { monthlyReport } from '../reports.js';\nimport { workflowReport } from './report.js';\nexport async function monthlyReportWorkflow(input) {\n const report = await monthlyReport(input);\n return workflowReport({\n workflow: 'monthly-report',\n site: input.site,\n summary: `Monthly report generated for ${report.month}. ${report.headline}`,\n steps: [\n {\n tool: 'seo_monthly_report',\n status: 'completed',\n summary: `Generated report for ${report.period.startDate} to ${report.period.endDate}.`,\n },\n ],\n actions: report.priorities,\n output: { report },\n });\n}\n//# sourceMappingURL=monthly-report.js.map","import { normalizeText } from '../shared.js';\nconst GROUPABLE_SOURCES = new Set([\n 'quick-win',\n 'striking-distance',\n]);\nfunction queueTemplateFamilyId(template) {\n if (!template)\n return 'no-template';\n if (template.id.endsWith('-salary'))\n return 'salary-page';\n return template.id;\n}\nfunction groupKey(item) {\n if (!GROUPABLE_SOURCES.has(item.source))\n return undefined;\n if (item.grouped)\n return undefined;\n const templateId = queueTemplateFamilyId(item.template);\n return [\n item.source,\n item.category,\n templateId,\n normalizeText(item.title),\n ].join('|');\n}\nfunction targetGroupKey(item) {\n if (!GROUPABLE_SOURCES.has(item.source))\n return undefined;\n if (item.grouped)\n return undefined;\n const templateId = queueTemplateFamilyId(item.template);\n return [\n item.source,\n item.category,\n templateId,\n normalizeText(item.target),\n ].join('|');\n}\nfunction groupedAction(items) {\n const first = items[0];\n if (!first)\n return '';\n const targetCount = new Set(items.map((item) => item.target)).size;\n if (targetCount <= 1 && items.length <= 1)\n return first.action;\n if (targetCount <= 1) {\n return `${items.length} findings point at this URL. Start with the highest-impact issue first: ${first.action}`;\n }\n return `${targetCount} URLs have the same issue. Apply this action across the affected pages: ${first.action}`;\n}\nfunction groupedEvidence(items) {\n const totalImpact = items.reduce((sum, item) => sum + item.impact, 0);\n const actionCount = new Set(items.map((item) => item.action)).size;\n const topTargets = items\n .slice(0, 3)\n .map((item) => item.target)\n .join(', ');\n const actionNote = actionCount > 1\n ? ` ${actionCount} action variants are preserved in grouped findings.`\n : '';\n return `Grouped ${items.length} matching findings; total impact ${totalImpact.toFixed(2)}.${actionNote} Top targets: ${topTargets}.`;\n}\nfunction groupedItem(items) {\n const sorted = [...items].sort((a, b) => b.score - a.score);\n const first = sorted[0];\n if (!first) {\n throw new Error('Cannot group an empty priority list.');\n }\n const totalImpact = sorted.reduce((sum, item) => sum + item.impact, 0);\n const totalScore = sorted.reduce((sum, item) => sum + item.score, 0);\n const score = Number(Math.min(first.score * (1 + Math.log1p(sorted.length - 1) / 8), 300).toFixed(2));\n return {\n ...first,\n score,\n impact: Number(totalImpact.toFixed(2)),\n action: groupedAction(sorted),\n evidence: groupedEvidence(sorted),\n grouped: {\n count: sorted.length,\n totalImpact: Number(totalImpact.toFixed(2)),\n totalScore: Number(totalScore.toFixed(2)),\n findings: sorted.map((item) => ({\n source: item.source,\n title: item.title,\n target: item.target,\n category: item.category,\n score: item.score,\n impact: item.impact,\n impactKind: item.impactKind,\n confidence: item.confidence,\n template: item.template,\n analytics: item.analytics,\n action: item.action,\n evidence: item.evidence,\n })),\n },\n };\n}\nfunction groupBy(items, keyFor) {\n const grouped = new Map();\n const passthrough = [];\n for (const item of items) {\n const key = keyFor(item);\n if (!key) {\n passthrough.push(item);\n continue;\n }\n const group = grouped.get(key) ?? [];\n group.push(item);\n grouped.set(key, group);\n }\n return [\n ...passthrough,\n ...[...grouped.values()].flatMap((items) => items.length > 1 ? [groupedItem(items)] : items),\n ];\n}\nexport function groupPriorityQueue(items) {\n const targetGrouped = groupBy(items, targetGroupKey);\n const queryGrouped = groupBy(targetGrouped, groupKey);\n return queryGrouped.sort((a, b) => b.score - a.score);\n}\n//# sourceMappingURL=priority-grouping.js.map","import { diagnoseProperty } from '../diagnose-property.js';\nimport { defaultDateRange } from '../shared.js';\nimport { fetchLandingPageValues, landingPageRankingPolicy, landingValueForUrl, } from './analytics-value.js';\nimport { groupPriorityQueue } from './priority-grouping.js';\nimport { priorityCategory, scorePriority } from './priority-scoring.js';\nimport { workflowReport } from './report.js';\nfunction templateCount(input) {\n const template = input.templates?.find((item) => item.id === input.id);\n return template?.urlCount ?? template?.count;\n}\nfunction priorityFromDraft(draft, analyticsCanRank) {\n const breakdown = scorePriority({\n source: draft.source,\n impact: draft.impact,\n confidence: draft.confidence,\n effort: draft.effort,\n verification: draft.verification,\n templateCount: draft.template?.count,\n analyticsSessions: analyticsCanRank ? draft.analytics?.sessions : undefined,\n });\n return {\n ...draft,\n category: priorityCategory(draft.source, draft.verification),\n score: breakdown.final,\n scoreBreakdown: breakdown,\n };\n}\nexport function decayClusterDrafts(input) {\n return input.groups\n .filter((item) => item.count >= 3 || item.totalClickLoss >= 10)\n .map((group) => ({\n source: 'decay',\n title: `${group.label} cluster`,\n target: group.sampleUrls[0] ?? input.site,\n impact: group.totalClickLoss,\n impactKind: 'observed_retained_query_clicks',\n confidence: 'medium',\n effort: group.diagnosis === 'lost_ctr' ? 'S' : 'M',\n template: {\n id: group.template.id,\n label: group.template.label,\n count: group.count,\n },\n action: group.recommendation,\n evidence: `${group.count} matching query/page rows retained in both windows had ${group.totalClickLoss.toFixed(0)} fewer clicks. Examples: ${group.sampleQueries.slice(0, 3).join('; ')}.`,\n }));\n}\nexport async function refreshPrioritiesWorkflow(input) {\n const diagnosis = await diagnoseProperty({\n ...input,\n verifyContent: input.verifyContent ?? true,\n verifyLimit: input.verifyLimit ?? Math.min(input.limit ?? 5, 5),\n });\n const range = defaultDateRange(input.days ?? 28);\n const analytics = await fetchLandingPageValues({\n propertyId: input.ga4PropertyId,\n startDate: range.startDate,\n endDate: range.endDate,\n });\n const analyticsPolicy = landingPageRankingPolicy({\n propertyId: input.ga4PropertyId,\n source: analytics.source,\n warning: analytics.warning,\n });\n const warnings = analyticsPolicy.warnings;\n const drafts = [];\n const opportunityCandidateLimit = Math.max(input.limit ?? 25, 25);\n for (const item of diagnosis.strikingDistance.items) {\n const templateItems = templateCount({\n templates: diagnosis.strikingDistance.templates,\n id: item.template.id,\n });\n const landingValue = landingValueForUrl(analytics.values, item.url);\n drafts.push({\n source: 'striking-distance',\n title: item.query,\n target: item.url,\n impact: item.priority.score,\n impactKind: 'heuristic_priority_score',\n confidence: item.recommendation.confidence,\n verification: item.contentVerification?.classification,\n template: {\n id: item.template.id,\n label: item.template.label,\n count: templateItems ?? 1,\n },\n analytics: landingValue,\n action: item.recommendation.action,\n evidence: item.recommendation.evidence,\n });\n }\n for (const item of diagnosis.quickWins.items.slice(0, opportunityCandidateLimit)) {\n const templateItems = templateCount({\n templates: diagnosis.quickWins.templates,\n id: item.template.id,\n });\n const landingValue = landingValueForUrl(analytics.values, item.url);\n drafts.push({\n source: 'quick-win',\n title: item.query,\n target: item.url,\n impact: Number(item.estimatedCtrClickShortfall.toFixed(2)),\n impactKind: 'heuristic_ctr_click_shortfall',\n confidence: item.recommendation.confidence,\n effort: item.recommendation.effort,\n verification: item.contentVerification?.classification,\n template: {\n id: item.template.id,\n label: item.template.label,\n count: templateItems ?? 1,\n },\n analytics: landingValue,\n action: item.recommendation.action,\n evidence: item.recommendation.evidenceRef,\n });\n }\n for (const item of diagnosis.decay.items) {\n const templateItems = templateCount({\n templates: diagnosis.decay.templates,\n id: item.template.id,\n });\n const landingValue = landingValueForUrl(analytics.values, item.url);\n drafts.push({\n source: 'decay',\n title: item.query,\n target: item.url,\n impact: item.clickLoss,\n impactKind: 'observed_retained_query_clicks',\n confidence: item.recommendation.confidence,\n effort: item.recommendation.effort,\n template: {\n id: item.template.id,\n label: item.template.label,\n count: templateItems ?? 1,\n },\n analytics: landingValue,\n action: item.recommendation.action,\n evidence: item.recommendation.evidenceRef,\n });\n }\n drafts.push(...decayClusterDrafts({\n groups: diagnosis.decay.groups,\n site: input.site,\n }));\n for (const item of diagnosis.cannibalization.items) {\n drafts.push({\n source: 'cannibalization',\n title: item.query,\n target: item.suggestedOwnerUrl,\n impact: item.priority.score,\n impactKind: 'heuristic_multi_url_exposure',\n confidence: item.recommendation.confidence,\n effort: item.recommendation.effort,\n template: item.template\n ? {\n id: item.template.id,\n label: item.template.label,\n count: item.pages.length,\n }\n : undefined,\n action: item.recommendation.action,\n evidence: item.recommendation.evidenceRef,\n });\n }\n for (const item of diagnosis.priorities) {\n drafts.push({\n source: 'diagnosis',\n title: item.label,\n target: input.site,\n impact: item.confidence === 'high'\n ? 150\n : item.confidence === 'medium'\n ? 75\n : 25,\n impactKind: 'ordinal',\n confidence: item.confidence,\n action: item.action,\n evidence: item.reason,\n });\n }\n for (const template of diagnosis.quickWins.templateRecommendations) {\n drafts.push({\n source: 'template',\n title: `${template.templateLabel} opportunity template`,\n target: `${template.templateLabel} template (${template.urlCount} URLs)`,\n impact: template.totalEstimatedCtrClickShortfall,\n impactKind: 'heuristic_ctr_click_shortfall',\n confidence: 'medium',\n effort: 'M',\n template: {\n id: template.templateId,\n label: template.templateLabel,\n count: template.urlCount,\n },\n action: template.action,\n evidence: template.evidence,\n });\n }\n const ranked = groupPriorityQueue(drafts\n .map((draft) => priorityFromDraft(draft, analyticsPolicy.canRank))\n .filter((item) => item.score > 0)\n .sort((a, b) => b.score - a.score)).slice(0, input.limit ?? 25);\n return workflowReport({\n workflow: 'refresh-priorities',\n site: input.site,\n summary: `${ranked.length} ranked SEO priorities refreshed.`,\n steps: [\n {\n tool: 'seo_diagnose_property',\n status: 'completed',\n summary: 'Combined diagnosis, decay, striking-distance, quick-win, and cannibalisation signals.',\n },\n ],\n actions: ranked.slice(0, 5).map((item) => ({\n title: item.title,\n action: item.action,\n confidence: item.confidence,\n })),\n output: {\n queue: ranked,\n warnings,\n diagnosis,\n analyticsSource: analytics.source,\n analyticsRankingEligible: analyticsPolicy.canRank,\n analyticsRankingApplied: ranked.some((item) => item.scoreBreakdown.analytics > 1),\n },\n });\n}\n//# sourceMappingURL=refresh-priorities.js.map","import { countLabel } from '../../phrasing.js';\nimport { crawlDiff, indexMonitor, indexWatch, linkRecover, } from '../monitoring.js';\nimport { workflowReport } from './report.js';\nfunction indexSummary(index) {\n return {\n inspected: index?.summary.inspected ?? 0,\n alerts: index?.summary.alerts ?? 0,\n currentIssues: index?.summary.currentIssues ?? 0,\n failed: index?.summary.failed ?? 0,\n quotaBlocked: index?.summary.quotaBlocked ?? 0,\n deferred: index?.summary.deferred ?? 0,\n };\n}\nexport async function technicalWatchWorkflow(input) {\n const recoverLinks = input.recoverLinks ?? true;\n const hasIndexInput = Boolean(input.urls?.length || input.sitemaps?.length);\n if (!input.startUrl && !hasIndexInput && !recoverLinks) {\n throw new Error('Pass startUrl, urls, sitemaps, or enable link recovery for technical-watch.');\n }\n const [crawl, index, recovery] = await Promise.all([\n input.startUrl\n ? crawlDiff({\n site: input.site,\n startUrl: input.startUrl,\n limit: input.limit,\n refresh: input.refresh,\n js: input.js,\n })\n : undefined,\n input.sitemaps?.length\n ? indexMonitor({\n site: input.site,\n sitemaps: input.sitemaps,\n properties: input.properties,\n dailyLimit: input.dailyLimit,\n inspectLimit: input.inspectLimit,\n maxUrls: input.maxUrls,\n languageCode: input.languageCode,\n refresh: input.refresh,\n })\n : input.urls?.length\n ? indexWatch({\n site: input.site,\n urls: input.urls,\n languageCode: input.languageCode,\n dailyLimit: input.dailyLimit,\n })\n : undefined,\n recoverLinks\n ? linkRecover({\n site: input.site,\n days: input.recoverDays,\n limit: input.recoverLimit ?? 10,\n minClicks: input.recoverMinClicks,\n minImpressions: input.recoverMinImpressions,\n refresh: input.refresh,\n js: input.js,\n })\n : undefined,\n ]);\n const indexCounts = indexSummary(index);\n const findingCount = (crawl?.summary.highPriorityRecommendations ?? 0) +\n indexCounts.currentIssues +\n (recovery?.summary.high ?? 0) +\n (recovery?.summary.medium ?? 0);\n const incompleteChecks = indexCounts.failed + indexCounts.quotaBlocked + indexCounts.deferred;\n const actions = [];\n if (recovery?.items[0]) {\n actions.push({\n title: 'Recover search-value URL',\n action: recovery.items[0].recommendation.action,\n confidence: recovery.items[0].recommendation.confidence,\n });\n }\n if (findingCount > 0) {\n actions.push({\n title: 'Triage technical findings',\n action: 'Prioritize current index issues, crawl actions, and recoverable search-value URLs before content work.',\n confidence: 'high',\n });\n }\n if (incompleteChecks > 0) {\n actions.push({\n title: 'Complete URL Inspection coverage',\n action: 'Retry failed or deferred URL Inspection checks after resolving access, provider, or quota errors. Do not treat incomplete checks as SEO defects.',\n confidence: 'high',\n });\n }\n if (!actions.length) {\n actions.push({\n title: 'No material technical finding',\n action: 'Keep the saved crawl and index snapshots; repeat the recovery check on the next run.',\n confidence: 'medium',\n });\n }\n return workflowReport({\n workflow: 'technical-watch',\n site: input.site,\n summary: `${countLabel(findingCount, 'material technical finding')}; ${countLabel(incompleteChecks, 'incomplete URL Inspection check')}.`,\n steps: [\n {\n tool: 'seo_crawl_diff',\n status: crawl ? 'completed' : 'skipped',\n summary: crawl\n ? `Crawled ${countLabel(crawl.summary.crawled, 'URL')}; ${crawl.summary.changed} changed, ${countLabel(crawl.summary.highPriorityRecommendations, 'high-priority crawl action')}.`\n : 'No start URL passed.',\n },\n {\n tool: input.sitemaps?.length ? 'seo_index_monitor' : 'seo_index_watch',\n status: index ? 'completed' : 'skipped',\n summary: index\n ? `Inspected ${countLabel(indexCounts.inspected, 'selected URL')}; ${countLabel(indexCounts.currentIssues, 'current review in selected results')}, ${countLabel(indexCounts.alerts, 'new alert')}, ${countLabel(indexCounts.failed, 'failed check')}, ${indexCounts.quotaBlocked + indexCounts.deferred} quota-blocked or deferred.`\n : 'No inspection URLs or sitemaps passed.',\n },\n {\n tool: 'seo_link_recover',\n status: recovery ? 'completed' : 'skipped',\n summary: recovery\n ? `Checked ${countLabel(recovery.summary.checked, 'search-value URL')}; ${countLabel(recovery.summary.recoverable, 'recoverable issue')}, ${recovery.summary.high} high severity.`\n : 'Link recovery disabled.',\n },\n ],\n actions,\n output: { crawl, index, recovery },\n });\n}\n//# sourceMappingURL=technical-watch.js.map","function compareText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\nexport function splitSegments(report) {\n const winners = report.items\n .filter((item) => item.clickDelta > 0)\n .sort((a, b) => b.clickDelta - a.clickDelta || compareText(a.key, b.key));\n const losers = report.items\n .filter((item) => item.clickDelta < 0)\n .sort((a, b) => a.clickDelta - b.clickDelta || compareText(a.key, b.key));\n const movedRows = winners.length + losers.length;\n return {\n dataStatus: report.dataStatus,\n coverage: {\n evidenceScope: 'matched-retained-segments',\n eligibleRows: report.selection.matchedRows,\n returnedRows: report.selection.returnedRows,\n limitedRows: report.selection.limitedRows,\n resultLimit: report.filters.limit,\n sourceRowLimit: report.filters.maxRows,\n movedRows,\n unchangedRows: Math.max(0, report.selection.returnedRows - movedRows),\n sourcePossiblyTruncated: report.source.before.possiblyTruncated ||\n report.source.after.possiblyTruncated,\n },\n summary: report.summary,\n unmatchedSegments: report.unmatchedSegments,\n warnings: report.warnings,\n winners,\n losers,\n };\n}\n//# sourceMappingURL=segments.js.map","import { clusterPseoTemplates, templateForUrl, } from '../pseo/templates.js';\nimport { segmentImpact } from '../segment-impact.js';\nimport { updateCorrelation } from '../traffic-anomaly.js';\nimport { workflowReport } from './report.js';\nimport { splitSegments } from './segments.js';\nfunction formatMagnitude(value) {\n return Math.abs(value).toLocaleString('en-GB');\n}\nfunction formatPercent(value) {\n return `${Math.round(value * 100)}%`;\n}\nfunction compareText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\nfunction coverageSummary(coverage) {\n return `${coverage.returnedRows} of ${coverage.eligibleRows} eligible matched retained rows returned under result limit ${coverage.resultLimit}${coverage.sourcePossiblyTruncated ? `; at least one source window reached the ${coverage.sourceRowLimit}-row source limit` : ''}`;\n}\nfunction directionLabel(item) {\n if (item.clickDelta > 0)\n return 'gained';\n if (item.clickDelta < 0)\n return 'lost';\n return 'held flat';\n}\nfunction segmentLabel(dimension, item) {\n if (dimension === 'page')\n return item.key.replace(/^https?:\\/\\//, '');\n return item.key;\n}\nfunction insightForSegment(dimension, segment) {\n if (segment.dataStatus === 'unavailable' || segment.dataStatus === 'empty') {\n return {\n dimension,\n dataStatus: segment.dataStatus,\n coverage: segment.coverage,\n unmatchedRows: segment.summary.unmatchedRows,\n summary: `${dimension}: no matched retained segment movement was available. ${segment.summary.verdict} Scope: ${coverageSummary(segment.coverage)}.`,\n };\n }\n const evidenceSuffix = segment.dataStatus === 'partial'\n ? ` Evidence is partial; ${segment.summary.unmatchedRows} one-window rows were not treated as zero.`\n : '';\n const coverageSuffix = ` Scope: ${coverageSummary(segment.coverage)}.`;\n const winner = segment.winners[0];\n const loser = segment.losers[0];\n if (winner && loser) {\n return {\n dimension,\n dataStatus: segment.dataStatus,\n coverage: segment.coverage,\n unmatchedRows: segment.summary.unmatchedRows,\n winner,\n loser,\n summary: `${dimension}: top winner ${segmentLabel(dimension, winner)} ${directionLabel(winner)} ${formatMagnitude(winner.clickDelta)} clicks; top loser ${segmentLabel(dimension, loser)} ${directionLabel(loser)} ${formatMagnitude(loser.clickDelta)} clicks.${evidenceSuffix}${coverageSuffix}`,\n };\n }\n if (winner) {\n return {\n dimension,\n dataStatus: segment.dataStatus,\n coverage: segment.coverage,\n unmatchedRows: segment.summary.unmatchedRows,\n winner,\n summary: `${dimension}: top winner ${segmentLabel(dimension, winner)} ${directionLabel(winner)} ${formatMagnitude(winner.clickDelta)} clicks; no material loser appeared in the returned segment rows.${evidenceSuffix}${coverageSuffix}`,\n };\n }\n if (loser) {\n return {\n dimension,\n dataStatus: segment.dataStatus,\n coverage: segment.coverage,\n unmatchedRows: segment.summary.unmatchedRows,\n loser,\n summary: `${dimension}: top loser ${segmentLabel(dimension, loser)} ${directionLabel(loser)} ${formatMagnitude(loser.clickDelta)} clicks; no material winner appeared in the returned segment rows.${evidenceSuffix}${coverageSuffix}`,\n };\n }\n return {\n dimension,\n dataStatus: segment.dataStatus,\n coverage: segment.coverage,\n unmatchedRows: segment.summary.unmatchedRows,\n summary: `${dimension}: no material winner or loser appeared in the returned matched retained segment rows.${evidenceSuffix}${coverageSuffix}`,\n };\n}\nfunction buildSummary(input) {\n const page = input.insights.find((item) => item.dimension === 'page');\n const query = input.insights.find((item) => item.dimension === 'query');\n const pageMovement = page?.dataStatus === 'empty' || page?.dataStatus === 'unavailable'\n ? 'page segment evidence unavailable'\n : page?.winner\n ? `top returned page gained ${formatMagnitude(page.winner.clickDelta)} clicks`\n : page?.loser\n ? `top returned page lost ${formatMagnitude(page.loser.clickDelta)} clicks`\n : 'no material page movement found in returned rows';\n const queryMovement = query?.dataStatus === 'empty' || query?.dataStatus === 'unavailable'\n ? 'query segment evidence unavailable'\n : query?.winner\n ? `top returned query gained ${formatMagnitude(query.winner.clickDelta)} clicks`\n : query?.loser\n ? `top returned query lost ${formatMagnitude(query.loser.clickDelta)} clicks`\n : 'no material query movement found in returned rows';\n return `Cause not established; ${pageMovement}; ${queryMovement}.`;\n}\nfunction buildActions(input) {\n const actions = [];\n const pageWinners = input.segments.page.winners.length;\n const pageLosers = input.segments.page.losers.length;\n const queryWinners = input.segments.query.winners.length;\n const queryLosers = input.segments.query.losers.length;\n const topTemplate = input.templateMovement[0];\n if (topTemplate) {\n actions.push({\n title: `${topTemplate.direction === 'winner' ? 'Protect' : 'Fix'} ${topTemplate.signature}`,\n action: topTemplate.direction === 'winner'\n ? `${topTemplate.signature} is a repeated winning URL pattern across ${topTemplate.urlCount} URLs in the returned matched-retained page subset. Preserve the shared title/H1/content/internal-link pattern before making broad edits.`\n : `${topTemplate.signature} is a repeated losing URL pattern across ${topTemplate.urlCount} URLs in the returned matched-retained page subset. Check indexability, canonical/robots state, internal links, and whether the shared template still matches search intent.`,\n confidence: topTemplate.confidence,\n });\n }\n if (input.update.confounders.length > 0) {\n actions.push({\n title: 'Test overlapping site changes first',\n action: 'Start with the known overlapping changes, then compare changed sections against unchanged sections. Keep the Google update window as timing context, not a cause.',\n confidence: 'medium',\n });\n }\n else if (input.update.classification === 'significant-movement-with-update-overlap') {\n actions.push({\n title: 'Map movement by template',\n action: 'Group the top page and query movers into templates or content types. Preserve winning patterns and investigate losing templates, but do not treat timing overlap as proof of an update effect.',\n confidence: 'medium',\n });\n }\n else {\n actions.push({\n title: 'Treat this as exploratory',\n action: 'Use the segment splits as a triage view, but do not over-attribute the movement to a Google update yet.',\n confidence: 'low',\n });\n }\n if (pageWinners > 0 && pageLosers === 0) {\n actions.push({\n title: 'Protect the winning pages',\n action: 'The returned page split contains positive movers and no negative movers. Check those pages for common query intent, title/H1 pattern, internal links, and template shape before making broad edits.',\n confidence: 'medium',\n });\n }\n if (pageLosers > 0 || queryLosers > 0) {\n actions.push({\n title: 'Triage the largest losers first',\n action: 'For losing pages and queries, check whether impressions dropped, average position worsened, or CTR fell. That separates ranking/index loss from snippet or SERP layout issues.',\n confidence: 'medium',\n });\n }\n if (queryWinners > 0 && queryLosers === 0) {\n actions.push({\n title: 'Expand winning query angles',\n action: 'The returned query split contains positive movers and no negative movers. Use that query wording to improve internal anchors and supporting copy on related pages.',\n confidence: 'medium',\n });\n }\n return actions;\n}\nfunction sameDirectionItems(items, direction) {\n return items.filter((item) => direction === 'winner' ? item.clickDelta > 0 : item.clickDelta < 0);\n}\nfunction movementRows(input) {\n const grouped = new Map();\n for (const item of input.items) {\n const signature = templateForUrl(item.key, input.clusters);\n if (signature === '/')\n continue;\n const cluster = input.clusters.find((item) => item.signature === signature);\n const existing = grouped.get(signature) ?? {\n cluster,\n signature,\n items: [],\n clickDelta: 0,\n impressionDelta: 0,\n };\n existing.items.push(item);\n existing.clickDelta += item.clickDelta;\n existing.impressionDelta += item.impressionDelta;\n grouped.set(signature, existing);\n }\n return [...grouped.values()];\n}\nfunction clusterCommonTerms(cluster) {\n if (!cluster)\n return [];\n return [\n ...new Set(cluster.shape.variableSegments.flatMap((segment) => segment.tokenExamples)),\n ].slice(0, 6);\n}\nfunction templateMovementForDirection(input) {\n const rows = movementRows({\n items: sameDirectionItems(input.items, input.direction),\n clusters: input.clusters,\n });\n return rows\n .map((row) => {\n const movement = Math.abs(row.clickDelta);\n const movementShare = input.totalMovement\n ? movement / input.totalMovement\n : 0;\n if (row.items.length < 3 || movementShare < 0.2)\n return undefined;\n const confidence = row.items.length >= 10 &&\n movementShare >= 0.35 &&\n input.segmentCoverage.limitedRows === 0 &&\n !input.segmentCoverage.sourcePossiblyTruncated\n ? 'high'\n : 'medium';\n const directionWord = input.direction === 'winner' ? 'gained' : 'lost';\n const commonTerms = clusterCommonTerms(row.cluster);\n const termText = commonTerms.length\n ? ` Common URL terms: ${commonTerms.join(', ')}.`\n : '';\n return {\n signature: row.signature,\n direction: input.direction,\n confidence,\n urlCount: row.items.length,\n clickDelta: Number(row.clickDelta.toFixed(3)),\n impressionDelta: Number(row.impressionDelta.toFixed(3)),\n movementShare: Number(movementShare.toFixed(3)),\n movementShareScope: 'returned-directional-page-click-movement',\n confidenceScope: 'pattern-within-returned-matched-retained-page-segments',\n segmentCoverage: input.segmentCoverage,\n commonTerms,\n sampleUrls: row.items.slice(0, 5).map((item) => item.key),\n summary: `${row.signature} ${directionWord} ${formatMagnitude(row.clickDelta)} clicks across ${row.items.length} moved URLs (${formatPercent(movementShare)} of returned ${input.direction} page click movement). Coverage: ${input.segmentCoverage.returnedRows} of ${input.segmentCoverage.eligibleRows} eligible matched retained page rows returned under result limit ${input.segmentCoverage.resultLimit}.${termText}`,\n };\n })\n .filter((item) => Boolean(item))\n .sort((a, b) => Math.abs(b.clickDelta) - Math.abs(a.clickDelta) ||\n b.urlCount - a.urlCount ||\n compareText(a.signature, b.signature));\n}\nexport function inferTemplateMovement(pageSegment) {\n const movedPages = [...pageSegment.winners, ...pageSegment.losers]\n .filter((item) => item.key.startsWith('http'))\n .filter((item) => Math.abs(item.clickDelta) > 0)\n .sort((left, right) => Math.abs(right.clickDelta) - Math.abs(left.clickDelta) ||\n compareText(left.key, right.key));\n if (movedPages.length < 6)\n return [];\n const clusters = clusterPseoTemplates(movedPages.map((item) => item.key), { minUrls: 3, minShare: 0.15, limit: 20 }).filter((cluster) => cluster.signature !== '/' && cluster.urlCount >= 3);\n if (!clusters.length)\n return [];\n const winnerMovement = pageSegment.winners.reduce((sum, item) => sum + Math.max(0, item.clickDelta), 0);\n const loserMovement = Math.abs(pageSegment.losers.reduce((sum, item) => sum + Math.min(0, item.clickDelta), 0));\n return [\n ...templateMovementForDirection({\n direction: 'winner',\n items: movedPages,\n clusters,\n totalMovement: winnerMovement,\n segmentCoverage: pageSegment.coverage,\n }),\n ...templateMovementForDirection({\n direction: 'loser',\n items: movedPages,\n clusters,\n totalMovement: loserMovement,\n segmentCoverage: pageSegment.coverage,\n }),\n ].slice(0, 6);\n}\nexport async function updatePostmortemWorkflow(input, dependencies = {}) {\n const limit = input.limit ?? 20;\n const runUpdateCorrelation = dependencies.updateCorrelation ?? updateCorrelation;\n const runSegmentImpact = dependencies.segmentImpact ?? segmentImpact;\n const [update, page, query, device, country] = await Promise.all([\n runUpdateCorrelation(input),\n runSegmentImpact({ ...input, dimension: 'page', limit }),\n runSegmentImpact({ ...input, dimension: 'query', limit }),\n runSegmentImpact({ ...input, dimension: 'device', limit }),\n runSegmentImpact({ ...input, dimension: 'country', limit }),\n ]);\n const segments = {\n page: splitSegments(page),\n query: splitSegments(query),\n device: splitSegments(device),\n country: splitSegments(country),\n };\n const insights = [\n insightForSegment('page', segments.page),\n insightForSegment('query', segments.query),\n insightForSegment('device', segments.device),\n insightForSegment('country', segments.country),\n ];\n const templateMovement = inferTemplateMovement(segments.page);\n const segmentStepStatus = [\n segments.page,\n segments.query,\n segments.device,\n segments.country,\n ].every((segment) => segment.dataStatus === 'empty' || segment.dataStatus === 'unavailable')\n ? 'skipped'\n : 'completed';\n return workflowReport({\n workflow: 'update-postmortem',\n site: input.site,\n summary: buildSummary({ update, insights }),\n steps: [\n {\n tool: 'seo_update_correlate',\n status: 'completed',\n summary: `Cause not established. ${update.summary}`,\n },\n {\n tool: 'seo_segment_impact',\n status: segmentStepStatus,\n summary: insights.map((insight) => insight.summary).join(' '),\n },\n ],\n actions: buildActions({ update, segments, templateMovement }),\n output: { update, insights, templateMovement, segments },\n });\n}\n//# sourceMappingURL=update-postmortem.js.map","import { existsSync } from 'node:fs';\nimport { getAuthModeStatus, getClientConfig, getServiceAccountStatus, } from './gsc/auth.js';\nimport { getSeoCliPaths } from './paths.js';\nimport { readConfig, readOauthClient, readTokens } from './storage/config.js';\nconst REQUIRED_SCOPES = [\n 'https://www.googleapis.com/auth/webmasters.readonly',\n 'https://www.googleapis.com/auth/analytics.readonly',\n];\nexport async function runDoctor() {\n const paths = getSeoCliPaths();\n const config = readConfig();\n const authMode = getAuthModeStatus();\n const serviceAccount = getServiceAccountStatus();\n const tokens = await readTokens();\n const oauthClient = readOauthClient();\n const tokenClientConfigured = tokens\n ? Boolean(getClientConfig(tokens.client_source))\n : undefined;\n const checks = [];\n checks.push({\n id: 'config-dir',\n label: 'Config directory',\n status: existsSync(paths.configDir) ? 'pass' : 'warn',\n detail: paths.configDir,\n fix: existsSync(paths.configDir)\n ? undefined\n : 'Run `seo start` or `seo auth setup-client`.',\n });\n checks.push({\n id: 'oauth-client',\n label: 'Google credentials',\n status: serviceAccount.configured\n ? 'pass'\n : tokenClientConfigured === false\n ? 'fail'\n : serviceAccount.error\n ? 'fail'\n : authMode.sharedConfigured || authMode.byoConfigured\n ? 'pass'\n : 'fail',\n detail: serviceAccount.configured\n ? `Service account configured for ${serviceAccount.identity}.`\n : tokenClientConfigured === false\n ? `Stored Google login uses the ${tokens?.client_source === 'shared' ? 'shared seo app' : 'BYO client'}, but that client is not configured.`\n : serviceAccount.error\n ? serviceAccount.error\n : authMode.sharedConfigured\n ? 'Shared client configured.'\n : authMode.byoConfigured\n ? `BYO client configured at ${paths.oauthClientFile}.`\n : 'No shared or BYO Google OAuth client configured.',\n fix: serviceAccount.configured\n ? undefined\n : tokenClientConfigured === false\n ? tokens?.client_source === 'shared'\n ? 'Reinstall `seo`. If the shared client is still missing, report it at https://github.com/iannuttall/seo/issues.'\n : 'Restore the same client with `seo auth setup-client`, or run `seo auth logout` before signing in with a different client.'\n : serviceAccount.error\n ? 'Set one valid service account credential source, then run `seo doctor` again.'\n : authMode.sharedConfigured || authMode.byoConfigured\n ? undefined\n : 'Run `seo auth setup-client` or set SEO_GOOGLE_CLIENT_ID and SEO_GOOGLE_CLIENT_SECRET.',\n });\n checks.push({\n id: 'oauth-client-file',\n label: 'BYO OAuth file',\n status: oauthClient ? 'pass' : 'warn',\n detail: oauthClient\n ? paths.oauthClientFile\n : 'No BYO OAuth client file. This is fine if using a shared client.',\n });\n checks.push({\n id: 'google-login',\n label: 'Google login',\n status: serviceAccount.configured || tokens ? 'pass' : 'fail',\n detail: serviceAccount.configured\n ? `Using service account ${serviceAccount.identity}.`\n : tokens\n ? `Signed in as ${tokens.account_email}.`\n : 'No Google token found.',\n fix: serviceAccount.configured || tokens\n ? undefined\n : 'Run `seo auth login`, or configure a service account for CI.',\n });\n const grantedScopes = new Set(tokens?.scope.split(/\\s+/).filter(Boolean) ?? []);\n for (const scope of REQUIRED_SCOPES) {\n checks.push({\n id: `scope:${scope}`,\n label: scope.endsWith('webmasters.readonly') ? 'GSC scope' : 'GA4 scope',\n status: serviceAccount.configured || (tokens && grantedScopes.has(scope))\n ? 'pass'\n : tokens\n ? 'fail'\n : 'warn',\n detail: serviceAccount.configured\n ? `${scope} requested by the service account.`\n : tokens\n ? grantedScopes.has(scope)\n ? scope\n : `Missing ${scope}.`\n : 'Cannot inspect scopes until login is complete.',\n fix: !serviceAccount.configured && tokens && !grantedScopes.has(scope)\n ? 'Run `seo auth logout` then `seo auth login`.'\n : undefined,\n });\n }\n checks.push({\n id: 'default-site',\n label: 'Saved GSC property',\n status: 'pass',\n detail: config.defaultSite ??\n 'No saved default. Human CLI commands will prompt; agents can pass --site.',\n });\n checks.push({\n id: 'default-ga4',\n label: 'Saved GA4 property',\n status: 'pass',\n detail: config.google.defaultGa4PropertyId ??\n 'No saved default. Human CLI commands will prompt; agents can pass --property.',\n });\n const ok = checks.every((check) => check.status !== 'fail');\n return {\n ok,\n generatedAt: new Date().toISOString(),\n checks,\n };\n}\n//# sourceMappingURL=doctor.js.map","import { fetch } from 'undici';\nimport { readConfig } from '../storage/config.js';\nexport class DataForSeoProvider {\n name = 'dataforseo';\n capabilities = {\n overview: true,\n };\n getAuthHeader() {\n const config = readConfig();\n const login = config.providers.dataForSeoLogin;\n const password = config.providers.dataForSeoPassword;\n if (!login || !password) {\n throw new Error('DataForSEO credentials missing. Add login and password to config.json.');\n }\n return `Basic ${Buffer.from(`${login}:${password}`).toString('base64')}`;\n }\n async keywordOverview(phrase, opts = {}) {\n const response = await fetch('https://api.dataforseo.com/v3/dataforseo_labs/google/keyword_overview/live', {\n method: 'POST',\n headers: {\n authorization: this.getAuthHeader(),\n 'content-type': 'application/json',\n },\n body: JSON.stringify([\n {\n keyword: phrase,\n language_code: 'en',\n location_code: 2840,\n },\n ]),\n });\n if (!response.ok) {\n throw new Error(`DataForSEO request failed with ${response.status}.`);\n }\n const json = (await response.json());\n const row = json.tasks?.[0]?.result?.[0];\n return {\n data: {\n phrase: row?.keyword ?? phrase,\n volume: row?.search_volume,\n competition: row?.competition,\n cpc: row?.cpc,\n difficulty: row?.keyword_difficulty,\n },\n usage: {\n provider: 'DataForSEO',\n units: 1,\n unitLabel: 'tasks',\n estimatedUsd: json.cost,\n calls: 1,\n },\n warnings: opts.database\n ? ['DataForSEO overview currently ignores the database option.']\n : undefined,\n };\n }\n}\n//# sourceMappingURL=dataforseo.js.map","export function parseSemicolonCsv(text) {\n return text\n .trim()\n .split('\\n')\n .map((line) => line.split(';').map((cell) => cell.replace(/^\"|\"$/g, '').trim()));\n}\n//# sourceMappingURL=csv.js.map","import { fetch } from 'undici';\nimport { readConfig } from '../../storage/config.js';\nimport { getDb, hashKey } from '../../storage/database.js';\nimport { parseSemicolonCsv } from './csv.js';\nconst BASE_URL = 'https://api.semrush.com/';\nfunction estimateUsd(units) {\n return (units / 1000) * 0.05;\n}\nexport async function cachedSemrushCall(endpoint, params, map, ttlMs, creditsPerLine, refresh = false) {\n const config = readConfig();\n const apiKey = config.providers.semrushApiKey;\n if (!apiKey) {\n throw new Error('Semrush API key missing. Add it to config.json first.');\n }\n const requestParams = Object.fromEntries(Object.entries({ ...params, key: apiKey, type: endpoint }).filter(([, value]) => value !== undefined));\n const db = getDb();\n const queryHash = hashKey([endpoint, requestParams]);\n const cached = db\n .prepare('SELECT response_json, credits_used FROM semrush_cache WHERE endpoint = ? AND query_hash = ? AND expires_at > ?')\n .get(endpoint, queryHash, Date.now());\n if (!refresh && cached?.response_json) {\n return {\n data: JSON.parse(cached.response_json),\n usage: {\n provider: 'Semrush',\n units: cached.credits_used ?? 0,\n unitLabel: 'units',\n estimatedUsd: estimateUsd(cached.credits_used ?? 0),\n calls: 1,\n cacheHits: 1,\n },\n cached: true,\n };\n }\n const url = new URL(BASE_URL);\n url.search = new URLSearchParams(requestParams).toString();\n const response = await fetch(url);\n const text = await response.text();\n if (!response.ok || text.startsWith('ERROR ::')) {\n throw new Error(text || `Semrush request failed with ${response.status}.`);\n }\n const rows = parseSemicolonCsv(text);\n const data = map(rows);\n const credits = Math.max(0, rows.length - 1) * creditsPerLine;\n db.prepare(`INSERT OR REPLACE INTO semrush_cache\n (endpoint, query_hash, request_json, response_json, credits_used, fetched_at, expires_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`).run(endpoint, queryHash, JSON.stringify(requestParams), JSON.stringify(data), credits, Date.now(), Date.now() + ttlMs);\n return {\n data,\n usage: {\n provider: 'Semrush',\n units: credits,\n unitLabel: 'units',\n estimatedUsd: estimateUsd(credits),\n calls: 1,\n },\n };\n}\n//# sourceMappingURL=cache.js.map","export function mapOverview(rows) {\n const [header, first] = rows;\n if (!header || !first) {\n return { phrase: '' };\n }\n const record = Object.fromEntries(header.map((key, index) => [key, first[index]]));\n return {\n phrase: record.Ph ?? '',\n volume: Number(record.Nq ?? 0) || undefined,\n cpc: Number(record.Cp ?? 0) || undefined,\n competition: Number(record.Co ?? 0) || undefined,\n difficulty: Number(record.Kd ?? 0) || undefined,\n results: Number(record.Nr ?? 0) || undefined,\n };\n}\nexport function mapKeywordRows(rows) {\n const [header, ...body] = rows;\n if (!header) {\n return [];\n }\n return body.map((row) => {\n const record = Object.fromEntries(header.map((key, index) => [key, row[index]]));\n return {\n phrase: record.Ph ?? '',\n volume: Number(record.Nq ?? 0) || undefined,\n difficulty: Number(record.Kd ?? 0) || undefined,\n cpc: Number(record.Cp ?? 0) || undefined,\n competition: Number(record.Co ?? 0) || undefined,\n url: record.Ur,\n domain: record.Dn,\n position: Number(record.Po ?? 0) || undefined,\n };\n });\n}\n//# sourceMappingURL=mappers.js.map","import { cachedSemrushCall } from './semrush/cache.js';\nimport { mapKeywordRows, mapOverview } from './semrush/mappers.js';\nexport class SemrushProvider {\n name = 'semrush';\n capabilities = {\n overview: true,\n batchOverview: true,\n related: true,\n broadMatch: true,\n questions: true,\n difficulty: true,\n urlKeywords: true,\n domainKeywords: true,\n maxBatchSize: 100,\n };\n async keywordOverview(phrase, opts = {}) {\n return cachedSemrushCall('phrase_this', {\n phrase,\n database: opts.database ?? 'us',\n export_columns: 'Ph,Nq,Cp,Co,Nr,Td,Kd',\n }, mapOverview, 7 * 86_400_000, 10, opts.refresh);\n }\n async batchKeywordOverview(phrases, opts = {}) {\n return cachedSemrushCall('phrase_these', {\n phrase: phrases.join(';'),\n database: opts.database ?? 'us',\n export_columns: 'Ph,Nq,Cp,Co,Nr,Td,Kd',\n }, (rows) => mapKeywordRows(rows).map((row) => ({ ...row, phrase: row.phrase })), 7 * 86_400_000, 10, opts.refresh);\n }\n async relatedKeywords(phrase, opts = {}) {\n return cachedSemrushCall('phrase_related', {\n phrase,\n database: opts.database ?? 'us',\n display_limit: 20,\n export_columns: 'Ph,Nq,Kd,Cp,Co',\n }, mapKeywordRows, 14 * 86_400_000, 40, opts.refresh);\n }\n async questions(phrase, opts = {}) {\n return cachedSemrushCall('phrase_questions', {\n phrase,\n database: opts.database ?? 'us',\n display_limit: 20,\n export_columns: 'Ph,Nq,Kd,Cp,Co',\n }, mapKeywordRows, 14 * 86_400_000, 40, opts.refresh);\n }\n async keywordDifficulty(phrases, opts = {}) {\n return cachedSemrushCall('phrase_kdi', {\n phrase: phrases.join(';'),\n database: opts.database ?? 'us',\n export_columns: 'Ph,Kd',\n }, (rows) => mapKeywordRows(rows).map((row) => ({\n phrase: row.phrase,\n kd: row.difficulty ?? 0,\n })), 7 * 86_400_000, 50, opts.refresh);\n }\n async domainKeywords(domain, opts = {}) {\n return cachedSemrushCall('domain_organic', {\n domain,\n database: opts.database ?? 'us',\n display_limit: 100,\n export_columns: 'Ph,Nq,Cp,Co,Kd,Po,Ur,Dn',\n }, mapKeywordRows, 7 * 86_400_000, 10, opts.refresh);\n }\n async urlKeywords(url, opts = {}) {\n return cachedSemrushCall('url_organic', {\n url,\n database: opts.database ?? 'us',\n display_limit: 100,\n export_columns: 'Ph,Nq,Cp,Co,Kd,Po,Ur,Dn',\n }, mapKeywordRows, 7 * 86_400_000, 10, opts.refresh);\n }\n}\n//# sourceMappingURL=semrush.js.map","import { readConfig } from '../storage/config.js';\nimport { DataForSeoProvider } from './dataforseo.js';\nimport { SemrushProvider } from './semrush.js';\nexport function getKeywordProvider(prefer) {\n const config = readConfig();\n const chosen = prefer ?? config.providers.prefer;\n if (chosen === 'authoritative' && config.providers.semrushApiKey) {\n return new SemrushProvider();\n }\n if (chosen === 'cheap' &&\n config.providers.dataForSeoLogin &&\n config.providers.dataForSeoPassword) {\n return new DataForSeoProvider();\n }\n if (config.providers.semrushApiKey) {\n return new SemrushProvider();\n }\n if (config.providers.dataForSeoLogin && config.providers.dataForSeoPassword) {\n return new DataForSeoProvider();\n }\n return undefined;\n}\n//# sourceMappingURL=router.js.map","import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { SHARED_OAUTH_CLIENT } from '../gsc/shared-client.generated.js';\nimport { deleteTokens, readConfig, readOauthClient, readTokens, writeTokens, } from '../storage/config.js';\nexport class LocalCredentialsProvider {\n getGoogleOAuthClient() {\n const byo = readOauthClient();\n if (byo) {\n return {\n clientId: byo.clientId,\n clientSecret: byo.clientSecret,\n source: 'byo',\n };\n }\n const config = readConfig();\n const clientId = process.env.SEO_GOOGLE_CLIENT_ID ??\n process.env.GSC_CLIENT_ID ??\n SHARED_OAUTH_CLIENT.clientId ??\n config.auth.sharedClientId;\n const clientSecret = process.env.SEO_GOOGLE_CLIENT_SECRET ??\n process.env.GSC_CLIENT_SECRET ??\n SHARED_OAUTH_CLIENT.clientSecret ??\n config.auth.sharedClientSecret;\n if (!clientId || !clientSecret) {\n return undefined;\n }\n return { clientId, clientSecret, source: 'shared' };\n }\n readGoogleTokens() {\n return readTokens();\n }\n writeGoogleTokens(tokens) {\n return writeTokens(tokens);\n }\n deleteGoogleTokens() {\n return deleteTokens();\n }\n}\nexport class JsonFileStorageAdapter {\n filePath;\n constructor(filePath) {\n this.filePath = filePath;\n }\n async get(key) {\n const data = await this.readAll();\n return data[key];\n }\n async put(key, value) {\n const data = await this.readAll();\n data[key] = value;\n await this.writeAll(data);\n }\n async delete(key) {\n const data = await this.readAll();\n delete data[key];\n await this.writeAll(data);\n }\n async readAll() {\n try {\n return JSON.parse(await readFile(this.filePath, 'utf8'));\n }\n catch {\n return {};\n }\n }\n async writeAll(data) {\n await mkdir(dirname(this.filePath), { recursive: true, mode: 0o700 });\n const tmpPath = `${this.filePath}.tmp`;\n await writeFile(tmpPath, `${JSON.stringify(data, null, 2)}\\n`, {\n mode: 0o600,\n });\n await rename(tmpPath, this.filePath);\n await rm(tmpPath, { force: true });\n }\n}\nexport const localCredentialsProvider = new LocalCredentialsProvider();\n//# sourceMappingURL=interfaces.js.map","import packageJson from '../../../package.json' with { type: 'json' };\nexport const SEO_VERSION = packageJson.version;\n//# sourceMappingURL=version.js.map","import * as z from 'zod/v4'\n\nexport const calendarDateSchema = z.iso.date('Use a YYYY-MM-DD date.')\n\nexport const calendarMonthSchema = z\n .string()\n .regex(/^\\d{4}-(?:0[1-9]|1[0-2])$/, 'Use a YYYY-MM month.')\n\nexport function resolveJsOption(\n input: boolean | undefined,\n defaultValue: 'auto' | undefined,\n): boolean | 'auto' | undefined {\n return input === undefined ? defaultValue : input\n}\n","import * as z from 'zod/v4'\n\n// Shared report option metadata used by MCP tools. The parity check keeps this\n// aligned with scripts/report-surface-catalog.mjs.\nconst REPORT_OPTIONS = {\n site: { mcp: 'site', schema: z.string() },\n days: { mcp: 'days', schema: z.number().optional() },\n recentDays: { mcp: 'recentDays', schema: z.number().optional() },\n range: { mcp: 'range', schema: z.number().optional() },\n limit: { mcp: 'limit', schema: z.number().optional() },\n checkLimit: { mcp: 'checkLimit', schema: z.number().optional() },\n minImpressions: { mcp: 'minImpressions', schema: z.number().optional() },\n includeBrand: { mcp: 'includeBrand', schema: z.boolean().optional() },\n verifyContent: { mcp: 'verifyContent', schema: z.boolean().optional() },\n verifyLimit: { mcp: 'verifyLimit', schema: z.number().optional() },\n js: { mcp: 'js', schema: z.boolean().optional() },\n fetchConcurrency: { mcp: 'fetchConcurrency', schema: z.number().optional() },\n fetchIntervalCap: { mcp: 'fetchIntervalCap', schema: z.number().optional() },\n fetchIntervalMs: { mcp: 'fetchIntervalMs', schema: z.number().optional() },\n refresh: { mcp: 'refresh', schema: z.boolean().optional() },\n} as const\n\ntype ReportOptionKey = keyof typeof REPORT_OPTIONS\n\nexport function mcpReportInputSchema<\n const T extends readonly ReportOptionKey[],\n>(\n keys: T,\n): {\n [K in T[number] as (typeof REPORT_OPTIONS)[K]['mcp']]: (typeof REPORT_OPTIONS)[K]['schema']\n} {\n return Object.fromEntries(\n keys.map((key) => {\n const option = REPORT_OPTIONS[key]\n return [option.mcp, option.schema]\n }),\n ) as {\n [K in T[number] as (typeof REPORT_OPTIONS)[K]['mcp']]: (typeof REPORT_OPTIONS)[K]['schema']\n }\n}\n","import { seoErrorEnvelope } from '@seo/core'\n\nexport type ToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n isError?: boolean\n}\n\nexport function summarize(data: unknown): string {\n return JSON.stringify(data, null, 2)\n}\n\nexport function toolError(error: unknown): ToolResult {\n const envelope = seoErrorEnvelope(error)\n return {\n content: [{ type: 'text', text: `Error: ${envelope.error.message}` }],\n structuredContent: envelope,\n isError: true,\n }\n}\n\nexport function toolSuccess(\n summaryText: string,\n structuredContent: unknown,\n options: { markdown?: string } = {},\n): ToolResult {\n return {\n content: [{ type: 'text', text: options.markdown ?? summaryText }],\n structuredContent: structuredContent as Record<string, unknown>,\n }\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n aiReferralsReport,\n communityIntentReport,\n contentOptimizationReport,\n countLabel,\n pageOpportunitiesReport,\n performanceAudit,\n SeoError,\n seoToAiQueryReport,\n} from '@seo/core'\nimport * as z from 'zod/v4'\nimport { calendarDateSchema, resolveJsOption } from './input-schemas.js'\nimport { mcpReportInputSchema } from './report-options.js'\nimport { toolError, toolSuccess } from './tool-result.js'\n\nconst ga4DateSchema = z\n .union([\n calendarDateSchema,\n z.string().regex(/^(?:today|yesterday|\\d+daysAgo)$/),\n ])\n .describe('Use YYYY-MM-DD or a GA4 relative date.')\n\nconst queryOpportunitySchema = {\n site: z.string().trim().min(1),\n days: z.number().int().min(1).max(548).optional(),\n startDate: calendarDateSchema.optional(),\n endDate: calendarDateSchema.optional(),\n limit: z.number().int().min(1).max(100).optional(),\n minImpressions: z.number().int().min(0).max(1_000_000_000).optional(),\n maxRows: z.number().int().min(1).max(50_000).optional(),\n brandTerms: z.array(z.string().trim().min(1)).max(100).optional(),\n includeBrand: z.boolean().optional(),\n refresh: z.boolean().optional(),\n} as const\n\nexport function registerAiOpportunityTools(\n server: McpServer,\n dependencies: {\n aiReferralsReport?: typeof aiReferralsReport\n contentOptimizationReport?: typeof contentOptimizationReport\n pageOpportunitiesReport?: typeof pageOpportunitiesReport\n seoToAiQueryReport?: typeof seoToAiQueryReport\n communityIntentReport?: typeof communityIntentReport\n } = {},\n): void {\n server.registerTool(\n 'seo_ai_referrals',\n {\n description:\n 'Find AI referral traffic detected in GA4. maxRows bounds retained provider rows; resultLimit bounds returned landing pages.',\n inputSchema: {\n property: z.string().trim().min(1),\n startDate: ga4DateSchema.optional(),\n endDate: ga4DateSchema.optional(),\n maxRows: z\n .number()\n .int()\n .min(1)\n .max(100_000)\n .describe(\n 'Maximum retained GA4 rows. If limit is also supplied, both values must match.',\n )\n .optional(),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100_000)\n .describe(\n 'Legacy alias for maxRows. If maxRows is also supplied, both values must match.',\n )\n .optional(),\n resultLimit: z\n .number()\n .int()\n .min(1)\n .max(1_000)\n .describe('Maximum ranked landing pages returned. Defaults to 25.')\n .optional(),\n refresh: z.boolean().optional(),\n },\n },\n async ({\n property,\n startDate,\n endDate,\n maxRows,\n limit,\n resultLimit,\n refresh,\n }) => {\n try {\n if (maxRows !== undefined && limit !== undefined && maxRows !== limit) {\n throw new SeoError(\n 'INVALID_INPUT',\n 'maxRows and the legacy limit option must match when both are provided.',\n )\n }\n const result = await (\n dependencies.aiReferralsReport ?? aiReferralsReport\n )({\n property,\n startDate,\n endDate,\n maxRows,\n limit,\n resultLimit,\n refresh,\n })\n return toolSuccess(\n `${countLabel(result.summary.sessions, 'AI referral session')} detected across ${countLabel(result.summary.sources, 'source')}; evidence is ${result.dataStatus}.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_page_opportunities',\n {\n description:\n 'Find first-party traffic growth opportunities for one URL from GSC and page content',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'limit',\n 'minImpressions',\n 'includeBrand',\n 'verifyContent',\n 'refresh',\n 'js',\n ]),\n days: z.number().int().min(1).max(548).optional(),\n limit: z.number().int().min(1).max(100).optional(),\n minImpressions: z.number().int().positive().optional(),\n url: z.string().url(),\n },\n },\n async ({\n site,\n url,\n days,\n limit,\n minImpressions,\n includeBrand,\n verifyContent,\n refresh,\n js,\n }) => {\n try {\n const result = await (\n dependencies.pageOpportunitiesReport ?? pageOpportunitiesReport\n )({\n site,\n url,\n days,\n limit,\n minImpressions,\n includeBrand,\n verifyContent,\n refresh,\n js: resolveJsOption(js, 'auto'),\n })\n return toolSuccess(result.summary.verdict, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_content_optimization',\n {\n description:\n 'Build a content optimization brief for one URL from first-party GSC queries and page content checks',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'limit',\n 'minImpressions',\n 'includeBrand',\n 'verifyContent',\n 'refresh',\n 'js',\n ]),\n days: z.number().int().min(1).max(548).optional(),\n limit: z.number().int().min(1).max(100).optional(),\n minImpressions: z.number().int().positive().optional(),\n url: z.string().url(),\n },\n },\n async ({\n site,\n url,\n days,\n limit,\n minImpressions,\n includeBrand,\n verifyContent,\n refresh,\n js,\n }) => {\n try {\n const result = await (\n dependencies.contentOptimizationReport ?? contentOptimizationReport\n )({\n site,\n url,\n days,\n limit,\n minImpressions,\n includeBrand,\n verifyContent,\n refresh,\n js: resolveJsOption(js, 'auto'),\n })\n return toolSuccess(result.summary.verdict, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_performance_audit',\n {\n description:\n 'Run a local Lighthouse lab audit and optional device-specific CrUX field Core Web Vitals. Configure CrUX with SEO_CRUX_API_KEY.',\n inputSchema: {\n url: z.string().url(),\n strategy: z.enum(['mobile', 'desktop']).optional(),\n refresh: z.boolean().optional(),\n },\n },\n async ({ url, strategy, refresh }) => {\n try {\n const result = await performanceAudit({\n url,\n strategy,\n refresh,\n })\n return toolSuccess(result.headline, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_to_ai_query',\n {\n description:\n 'Convert retained GSC queries into deterministic AI monitoring-prompt suggestions with source completeness and heuristic caveats',\n inputSchema: queryOpportunitySchema,\n },\n async ({\n site,\n days,\n startDate,\n endDate,\n limit,\n minImpressions,\n maxRows,\n brandTerms,\n includeBrand,\n refresh,\n }) => {\n try {\n const result = await (\n dependencies.seoToAiQueryReport ?? seoToAiQueryReport\n )({\n site,\n days,\n startDate,\n endDate,\n limit,\n minImpressions,\n maxRows,\n brandTerms,\n includeBrand,\n refresh,\n })\n return toolSuccess(\n `${countLabel(result.summary.prompts, 'monitoring-prompt suggestion')} generated from ${countLabel(result.summary.returnedQueries, 'retained GSC query')}; evidence is ${result.dataStatus}.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_community_intent',\n {\n description:\n 'Classify explicit forum, review, comparison, experience, and recommendation language in retained GSC queries as review hypotheses',\n inputSchema: queryOpportunitySchema,\n },\n async ({\n site,\n days,\n startDate,\n endDate,\n limit,\n minImpressions,\n maxRows,\n brandTerms,\n includeBrand,\n refresh,\n }) => {\n try {\n const result = await (\n dependencies.communityIntentReport ?? communityIntentReport\n )({\n site,\n days,\n startDate,\n endDate,\n limit,\n minImpressions,\n maxRows,\n brandTerms,\n includeBrand,\n refresh,\n })\n return toolSuccess(\n `Evidence status: ${result.dataStatus}. ${result.summary.verdict}`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n}\n","export function fetchRateInput(input: {\n fetchConcurrency?: number\n fetchIntervalCap?: number\n fetchIntervalMs?: number\n}) {\n if (\n input.fetchConcurrency === undefined &&\n input.fetchIntervalCap === undefined &&\n input.fetchIntervalMs === undefined\n ) {\n return undefined\n }\n return {\n concurrency: input.fetchConcurrency,\n intervalCap: input.fetchIntervalCap,\n intervalMs: input.fetchIntervalMs,\n }\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n aiReadiness,\n auditLlmsTxt,\n buildOkfBundle,\n compareCrawlReports,\n crawlerRuleCategorySchema,\n crawlSite,\n entityReadiness,\n explainOkfValidation,\n explainRule,\n generateLlmsTxt,\n geoGapsReport,\n latestCrawlReport,\n listCrawlReports,\n listRules,\n loadCrawlReport,\n reviewObservations,\n saveCrawlReport,\n selectAffectedUrls,\n topFixes,\n validateOkfFiles,\n} from '@seo/core'\nimport * as z from 'zod/v4'\nimport { fetchRateInput } from './fetch-rate.js'\nimport { toolError, toolSuccess } from './tool-result.js'\n\nfunction compactCrawlResult(\n report: Awaited<ReturnType<typeof crawlSite>>,\n opts: { includePages?: boolean; includeIssues?: boolean } = {},\n) {\n const requestHeadline =\n report.requestEvidenceStatus === 'available'\n ? `Processed ${report.requests.length} URL requests into ${report.summary.totalPages} unique documents.`\n : report.requestEvidenceStatus === 'partial'\n ? `Observed ${report.requests.length} URL requests and retained ${report.summary.totalPages} unique documents; some started requests were still in flight when the crawl stopped.`\n : `Loaded ${report.summary.totalPages} unique documents; request evidence is unavailable for this legacy report.`\n const payload: Record<string, unknown> = {\n id: report.id,\n definitionId: report.definitionId,\n headline: `${requestHeadline} Found ${report.summary.highIssues} high, ${report.summary.mediumIssues} medium, and ${report.summary.lowIssues} low issues.`,\n status: report.status,\n requestEvidenceStatus: report.requestEvidenceStatus,\n configHash: report.configHash,\n summary: report.summary,\n dataSources: report.dataSources,\n ai: report.ai\n ? {\n robotsTxt: report.ai.robotsTxt,\n llmsTxt: report.ai.llmsTxt,\n agentResources: report.ai.agentResources,\n }\n : undefined,\n topFixes: topFixes(report, { limit: 10 }),\n reviewObservations: reviewObservations(report, { limit: 10 }),\n warnings: report.warnings,\n caveats: report.caveats,\n }\n if (opts.includeIssues) payload.issues = report.issues\n if (opts.includePages) {\n payload.requests = report.requests\n payload.pages = report.pages\n }\n return payload\n}\n\nfunction resolveSavedReportAlias(input: {\n value?: string\n site?: string\n skipId?: string\n}) {\n if (!input.value || input.value === 'latest' || input.value === 'previous') {\n const reports = listCrawlReports({ site: input.site, limit: 20 }).filter(\n (report) => report.id !== input.skipId,\n )\n const meta = input.value === 'previous' ? reports[1] : reports[0]\n return meta ? loadCrawlReport(meta.id) : undefined\n }\n return loadCrawlReport(input.value)\n}\n\nexport function registerCrawlerTools(server: McpServer): void {\n server.registerTool(\n 'seo_crawl_site',\n {\n description:\n 'Crawl a site and run technical SEO checks. The compact result separates prioritised fixes from review observations. Set includePages/includeIssues for raw data.',\n inputSchema: {\n url: z.string().url(),\n site: z.string().optional(),\n ga4PropertyId: z.string().optional(),\n maxPages: z.number().int().positive().optional(),\n maxDepth: z.number().int().nonnegative().optional(),\n concurrency: z.number().int().positive().optional(),\n fetchIntervalCap: z.number().int().positive().optional(),\n fetchIntervalMs: z.number().int().positive().optional(),\n refresh: z.boolean().optional(),\n include: z.array(z.string()).optional(),\n exclude: z.array(z.string()).optional(),\n useSitemap: z.boolean().optional(),\n respectRobots: z.boolean().optional(),\n js: z.boolean().optional(),\n includePages: z.boolean().optional(),\n includeIssues: z.boolean().optional(),\n saveReport: z.boolean().optional(),\n },\n },\n async ({\n url,\n site,\n ga4PropertyId,\n maxPages,\n maxDepth,\n concurrency,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n include,\n exclude,\n useSitemap,\n respectRobots,\n js,\n includePages,\n includeIssues,\n saveReport,\n }) => {\n try {\n const report = await crawlSite({\n url,\n site,\n ga4PropertyId,\n maxPages,\n maxDepth,\n concurrency,\n refresh,\n fetchRate: fetchRateInput({\n fetchConcurrency: concurrency,\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n include,\n exclude,\n useSitemap,\n respectRobots,\n js: Boolean(js),\n })\n const saved = saveReport ? saveCrawlReport(report) : undefined\n return toolSuccess(\n `Crawl complete for ${url}. Found ${report.issues.length} issues across ${report.summary.totalPages} pages.`,\n {\n ...compactCrawlResult(report, { includePages, includeIssues }),\n ...(saved ? { saved } : {}),\n },\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_audit_urls',\n {\n description:\n 'Audit an explicit list of URLs with technical SEO checks. The compact result separates prioritised fixes from review observations. Set includePages/includeIssues for raw data.',\n inputSchema: {\n urls: z.array(z.string().url()).min(1),\n site: z.string().optional(),\n ga4PropertyId: z.string().optional(),\n maxPages: z.number().int().positive().optional(),\n concurrency: z.number().int().positive().optional(),\n fetchIntervalCap: z.number().int().positive().optional(),\n fetchIntervalMs: z.number().int().positive().optional(),\n refresh: z.boolean().optional(),\n includePages: z.boolean().optional(),\n includeIssues: z.boolean().optional(),\n saveReport: z.boolean().optional(),\n },\n },\n async ({\n urls,\n site,\n ga4PropertyId,\n maxPages,\n concurrency,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n includePages,\n includeIssues,\n saveReport,\n }) => {\n try {\n const report = await crawlSite({\n url: urls[0] ?? '',\n urls,\n mode: 'list',\n site,\n ga4PropertyId,\n maxPages: maxPages ?? urls.length,\n concurrency,\n refresh,\n fetchRate: fetchRateInput({\n fetchConcurrency: concurrency,\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n useSitemap: false,\n })\n const saved = saveReport ? saveCrawlReport(report) : undefined\n return toolSuccess(\n `URL audit complete. Found ${report.issues.length} issues across ${report.summary.totalPages} pages.`,\n {\n ...compactCrawlResult(report, { includePages, includeIssues }),\n ...(saved ? { saved } : {}),\n },\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_top_fixes',\n {\n description:\n 'Return top technical SEO fixes for a URL by running a compact crawl.',\n inputSchema: {\n url: z.string().url().optional(),\n reportId: z.string().optional(),\n site: z.string().optional(),\n maxPages: z.number().int().positive().optional(),\n maxDepth: z.number().int().nonnegative().optional(),\n fetchIntervalCap: z.number().int().positive().optional(),\n fetchIntervalMs: z.number().int().positive().optional(),\n refresh: z.boolean().optional(),\n category: z.string().optional(),\n limit: z.number().int().min(1).max(1_000).optional(),\n },\n },\n async ({\n url,\n reportId,\n site,\n maxPages,\n maxDepth,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n category,\n limit,\n }) => {\n try {\n const report = url\n ? await crawlSite({\n url,\n site,\n maxPages,\n maxDepth,\n refresh,\n fetchRate: fetchRateInput({\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n })\n : reportId\n ? loadCrawlReport(reportId)\n : latestCrawlReport(site)\n if (!report) {\n return toolError(\n 'No crawl report found. Pass url, reportId, or run seo_crawl_site with saveReport first.',\n )\n }\n const groups = topFixes(report, { category, limit })\n return toolSuccess(\n `Found ${groups.length} top fix groups for ${report.config.url}.`,\n {\n url: report.config.url,\n reportId: report.id,\n summary: report.summary,\n dataSources: report.dataSources,\n topFixes: groups,\n warnings: report.warnings,\n caveats: report.caveats,\n },\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_explain_issue',\n {\n description:\n 'Explain a crawler rule in plain English: why it matters, how to fix it, and how to verify it.',\n inputSchema: {\n ruleId: z.string(),\n },\n },\n async ({ ruleId }) => {\n const rule = explainRule(ruleId)\n if (!rule) {\n return toolError(`Unknown rule: ${ruleId}`)\n }\n return toolSuccess(`Rule guidance for ${ruleId}.`, rule)\n },\n )\n\n server.registerTool(\n 'seo_list_rules',\n {\n description:\n 'List crawler rule ids and guidance metadata. Use this before the explain-crawl-issue report when you need valid rule ids.',\n inputSchema: {\n category: crawlerRuleCategorySchema.optional(),\n },\n },\n async ({ category }) => {\n const rules = listRules().filter((rule) =>\n category ? rule.category === category : true,\n )\n return toolSuccess(`Found ${rules.length} crawler rules.`, {\n rules,\n })\n },\n )\n\n server.registerTool(\n 'seo_affected_urls',\n {\n description:\n 'Return affected URLs for a saved or freshly crawled report, filtered by rule, category, or severity.',\n inputSchema: {\n url: z.string().url().optional(),\n reportId: z.string().optional(),\n site: z.string().optional(),\n ruleId: z.string().optional(),\n category: z.string().optional(),\n severity: z.string().optional(),\n maxPages: z.number().int().positive().optional(),\n fetchIntervalCap: z.number().int().positive().optional(),\n fetchIntervalMs: z.number().int().positive().optional(),\n refresh: z.boolean().optional(),\n limit: z.number().int().positive().optional(),\n },\n },\n async ({\n url,\n reportId,\n site,\n ruleId,\n category,\n severity,\n maxPages,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n limit,\n }) => {\n try {\n const report = url\n ? await crawlSite({\n url,\n site,\n maxPages,\n refresh,\n fetchRate: fetchRateInput({\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n })\n : reportId\n ? loadCrawlReport(reportId)\n : latestCrawlReport(site)\n if (!report) {\n return toolError(\n 'No crawl report found. Pass url, reportId, or run seo_crawl_site with saveReport first.',\n )\n }\n const result = selectAffectedUrls(report, {\n ruleId,\n category,\n severity,\n limit,\n })\n return toolSuccess(\n `Returned ${result.selection.returnedRows} of ${result.selection.totalMatchedRows} affected URLs for ${report.config.url}.`,\n {\n url: report.config.url,\n reportId: report.id,\n dataSources: report.dataSources,\n affectedUrls: result.affectedUrls,\n selection: result.selection,\n warnings: report.warnings,\n caveats: report.caveats,\n },\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_geo_gaps',\n {\n description:\n 'Return crawl, indexability, and page-level snippet controls for Google AI Search eligibility, with optional page observations kept separate. No detected restriction does not guarantee selection or visibility.',\n inputSchema: {\n url: z.string().url().optional(),\n reportId: z.string().optional(),\n site: z.string().optional(),\n maxPages: z.number().int().positive().optional(),\n fetchIntervalCap: z.number().int().positive().optional(),\n fetchIntervalMs: z.number().int().positive().optional(),\n refresh: z.boolean().optional(),\n limit: z.number().int().positive().optional(),\n },\n },\n async ({\n url,\n reportId,\n site,\n maxPages,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n limit,\n }) => {\n try {\n const report = url\n ? await crawlSite({\n url,\n site,\n maxPages,\n refresh,\n fetchRate: fetchRateInput({\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n })\n : reportId\n ? loadCrawlReport(reportId)\n : latestCrawlReport(site)\n if (!report) {\n return toolError(\n 'No crawl report found. Pass url, reportId, or run seo_crawl_site with saveReport first.',\n )\n }\n const gaps = geoGapsReport(report, { limit })\n return toolSuccess(\n `Returned ${gaps.selection.returnedPages} of ${gaps.selection.totalMatchedPages} AI Search technical eligibility gap pages for ${report.config.url}; evidence is ${gaps.dataStatus}.`,\n {\n url: report.config.url,\n reportId: report.id,\n ...gaps,\n },\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_ai_readiness',\n {\n description:\n 'Return AI-search technical evidence and optional observations without an aggregate score or citation prediction.',\n inputSchema: {\n url: z.string().url().optional(),\n reportId: z.string().optional(),\n site: z.string().optional(),\n maxPages: z.number().int().positive().optional(),\n fetchIntervalCap: z.number().int().positive().optional(),\n fetchIntervalMs: z.number().int().positive().optional(),\n refresh: z.boolean().optional(),\n },\n },\n async ({\n url,\n reportId,\n site,\n maxPages,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n }) => {\n try {\n const report = url\n ? await crawlSite({\n url,\n site,\n maxPages,\n refresh,\n fetchRate: fetchRateInput({\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n })\n : reportId\n ? loadCrawlReport(reportId)\n : latestCrawlReport(site)\n if (!report) {\n return toolError(\n 'No crawl report found. Pass url, reportId, or run seo_crawl_site with saveReport first.',\n )\n }\n const readiness = aiReadiness(report)\n return toolSuccess(readiness.headline, readiness)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_llms_txt_audit',\n {\n description:\n 'Inspect optional llms.txt presence from a saved or freshly crawled report and return current Google guidance plus candidate pages.',\n inputSchema: {\n url: z.string().url().optional(),\n reportId: z.string().optional(),\n site: z.string().optional(),\n maxPages: z.number().int().positive().optional(),\n fetchIntervalCap: z.number().int().positive().optional(),\n fetchIntervalMs: z.number().int().positive().optional(),\n refresh: z.boolean().optional(),\n },\n },\n async ({\n url,\n reportId,\n site,\n maxPages,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n }) => {\n try {\n const report = url\n ? await crawlSite({\n url,\n site,\n maxPages,\n refresh,\n fetchRate: fetchRateInput({\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n })\n : reportId\n ? loadCrawlReport(reportId)\n : latestCrawlReport(site)\n if (!report) {\n return toolError(\n 'No crawl report found. Pass url, reportId, or run seo_crawl_site with saveReport first.',\n )\n }\n const audit = auditLlmsTxt(report)\n return toolSuccess(audit.headline, audit)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_llms_txt_generate',\n {\n description:\n 'Generate an llms.txt draft from a saved or freshly crawled report. Returns content and metadata.',\n inputSchema: {\n url: z.string().url().optional(),\n reportId: z.string().optional(),\n site: z.string().optional(),\n maxPages: z.number().int().positive().optional(),\n maxUrls: z.number().int().positive().optional(),\n tokenBudget: z.number().int().positive().optional(),\n exclude: z.array(z.string()).optional(),\n title: z.string().optional(),\n description: z.string().optional(),\n fetchIntervalCap: z.number().int().positive().optional(),\n fetchIntervalMs: z.number().int().positive().optional(),\n refresh: z.boolean().optional(),\n },\n },\n async ({\n url,\n reportId,\n site,\n maxPages,\n maxUrls,\n tokenBudget,\n exclude,\n title,\n description,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n }) => {\n try {\n const report = url\n ? await crawlSite({\n url,\n site,\n maxPages,\n refresh,\n fetchRate: fetchRateInput({\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n })\n : reportId\n ? loadCrawlReport(reportId)\n : latestCrawlReport(site)\n if (!report) {\n return toolError(\n 'No crawl report found. Pass url, reportId, or run seo_crawl_site with saveReport first.',\n )\n }\n const generated = generateLlmsTxt(report, {\n maxUrls,\n tokenBudget,\n exclude,\n title,\n description,\n })\n return toolSuccess(\n `Generated llms.txt with ${generated.includedUrls} URLs.`,\n generated,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_entity_readiness',\n {\n description:\n 'Check schema, sameAs, social profile, author/date, and naming signals from a saved or freshly crawled report.',\n inputSchema: {\n url: z.string().url().optional(),\n reportId: z.string().optional(),\n site: z.string().optional(),\n maxPages: z.number().int().positive().optional(),\n fetchIntervalCap: z.number().int().positive().optional(),\n fetchIntervalMs: z.number().int().positive().optional(),\n refresh: z.boolean().optional(),\n },\n },\n async ({\n url,\n reportId,\n site,\n maxPages,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n }) => {\n try {\n const report = url\n ? await crawlSite({\n url,\n site,\n maxPages,\n refresh,\n fetchRate: fetchRateInput({\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n })\n : reportId\n ? loadCrawlReport(reportId)\n : latestCrawlReport(site)\n if (!report) {\n return toolError(\n 'No crawl report found. Pass url, reportId, or run seo_crawl_site with saveReport first.',\n )\n }\n const readiness = entityReadiness(report)\n return toolSuccess(readiness.headline, readiness)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_okf_build',\n {\n description:\n 'Build a compact OKF site knowledge manifest from a saved or freshly crawled report. Set includeFiles for bounded inline markdown.',\n inputSchema: {\n url: z.string().url().optional(),\n reportId: z.string().optional(),\n site: z.string().optional(),\n maxPages: z.number().int().positive().optional(),\n maxConcepts: z.number().int().min(1).max(100).optional(),\n includeFiles: z.boolean().optional(),\n title: z.string().min(1).max(200).optional(),\n fetchIntervalCap: z.number().int().positive().optional(),\n fetchIntervalMs: z.number().int().positive().optional(),\n refresh: z.boolean().optional(),\n },\n },\n async ({\n url,\n reportId,\n site,\n maxPages,\n maxConcepts,\n includeFiles,\n title,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n }) => {\n try {\n const report = url\n ? await crawlSite({\n url,\n site,\n maxPages,\n refresh,\n fetchRate: fetchRateInput({\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n })\n : reportId\n ? loadCrawlReport(reportId)\n : latestCrawlReport(site)\n if (!report) {\n return toolError(\n 'No crawl report found. Pass url, reportId, or run seo_crawl_site with saveReport first.',\n )\n }\n const bundle = buildOkfBundle(report, {\n maxConcepts: maxConcepts ?? (includeFiles ? 25 : 100),\n title,\n })\n const validation = validateOkfFiles(bundle.files)\n const { files, ...manifest } = bundle\n return toolSuccess(\n `Built OKF bundle with ${bundle.conceptCount} concepts.`,\n {\n manifest: {\n ...manifest,\n filePaths: files.map((file) => file.path),\n },\n ...(includeFiles ? { files } : {}),\n validation,\n },\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_okf_validate',\n {\n description:\n 'Validate OKF markdown files supplied by an agent. Use the okf-build report to generate files from a crawl.',\n inputSchema: {\n files: z\n .array(\n z.object({\n path: z.string().min(1).max(512),\n content: z.string().max(2_000_000),\n }),\n )\n .min(1)\n .max(5_006),\n },\n },\n async ({ files }) => {\n const validation = validateOkfFiles(files)\n return toolSuccess(\n validation.valid\n ? 'Bundle passes seo OKF checks.'\n : 'Bundle has seo OKF issues.',\n {\n validation,\n explanation: explainOkfValidation(validation),\n },\n )\n },\n )\n\n server.registerTool(\n 'seo_get_crawl_report',\n {\n description:\n 'Return a saved crawl report by id, or the latest saved report for an optional site. Compact by default.',\n inputSchema: {\n id: z.string().optional(),\n site: z.string().optional(),\n includePages: z.boolean().optional(),\n includeIssues: z.boolean().optional(),\n },\n },\n async ({ id, site, includePages, includeIssues }) => {\n try {\n const report = id ? loadCrawlReport(id) : latestCrawlReport(site)\n if (!report) {\n return toolError(\n id\n ? `No saved crawl report found for ${id}.`\n : 'No saved crawl reports found.',\n )\n }\n return toolSuccess(`Saved crawl report ${report.id}.`, {\n ...compactCrawlResult(report, { includePages, includeIssues }),\n url: report.config.url,\n site: report.site,\n generatedAt: report.generatedAt,\n })\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_list_crawl_reports',\n {\n description:\n 'List saved crawl report metadata, optionally filtered by GSC site/property.',\n inputSchema: {\n site: z.string().optional(),\n limit: z.number().int().positive().optional(),\n },\n },\n async ({ site, limit }) => {\n try {\n const reports = listCrawlReports({ site, limit })\n return toolSuccess(`Found ${reports.length} saved crawl reports.`, {\n reports,\n })\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_compare_crawl_reports',\n {\n description:\n 'Compare two saved crawl reports and return page, issue, score, and plain-English change summaries.',\n inputSchema: {\n after: z.string().optional(),\n before: z.string().optional(),\n site: z.string().optional(),\n },\n },\n async ({ after, before, site }) => {\n try {\n const afterReport = resolveSavedReportAlias({\n value: after ?? 'latest',\n site,\n })\n if (!afterReport) {\n return toolError('No newer crawl report found.')\n }\n const beforeReport = resolveSavedReportAlias({\n value: before ?? 'previous',\n site: afterReport.site ?? site,\n skipId: afterReport.id,\n })\n if (!beforeReport) {\n return toolError(\n 'No baseline crawl report found. Save at least two reports or pass before.',\n )\n }\n const diff = compareCrawlReports({\n before: beforeReport,\n after: afterReport,\n })\n return toolSuccess(diff.headline, diff)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n diagnoseProperty,\n runDoctor,\n segmentImpact,\n strikingDistance,\n trafficAnomaly,\n updateCorrelation,\n} from '@seo/core'\nimport * as z from 'zod/v4'\nimport { fetchRateInput } from './fetch-rate.js'\nimport { calendarDateSchema, resolveJsOption } from './input-schemas.js'\nimport { mcpReportInputSchema } from './report-options.js'\nimport { toolError, toolSuccess } from './tool-result.js'\n\ntype StrikingDistanceToolInput = {\n site: string\n days?: number\n minImpressions?: number\n limit?: number\n verifyContent?: boolean\n verifyLimit?: number\n includeBrand?: boolean\n brandTerms?: string[]\n js?: boolean\n fetchConcurrency?: number\n fetchIntervalCap?: number\n fetchIntervalMs?: number\n refresh?: boolean\n}\n\nexport function registerDiagnosisTools(\n server: McpServer,\n dependencies: { segmentImpact?: typeof segmentImpact } = {},\n): void {\n server.registerTool(\n 'seo_doctor',\n {\n description: 'Check local auth, scopes, config, and defaults',\n inputSchema: {},\n },\n async () => {\n try {\n const result = await runDoctor()\n return toolSuccess(\n result.ok\n ? 'Local seo setup is ready.'\n : 'Local seo setup needs attention.',\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_diagnose_property',\n {\n description:\n 'Run end-to-end property diagnosis across anomaly, update, segment, decay, cannibalisation, and opportunity signals',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'recentDays',\n 'limit',\n 'includeBrand',\n 'refresh',\n ]),\n },\n },\n async ({ site, days, recentDays, limit, includeBrand, refresh }) => {\n try {\n const result = await diagnoseProperty({\n site,\n days,\n recentDays,\n limit,\n includeBrand,\n refresh,\n })\n return toolSuccess(\n `Diagnosis ${result.dataStatus}. Update attribution: ${result.summary.updateAttribution}.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_segment_impact',\n {\n description:\n 'Compare matched retained GSC segments across adjacent equal-length periods without treating missing rows as zero',\n inputSchema: {\n site: z.string().trim().min(1),\n days: z.number().int().min(1).max(240).optional(),\n limit: z.number().int().min(1).max(100).optional(),\n refresh: z.boolean().optional(),\n dimension: z.enum(['page', 'query', 'country', 'device']).optional(),\n compareDays: z.number().int().min(1).max(240).optional(),\n startDate: calendarDateSchema.optional(),\n endDate: calendarDateSchema.optional(),\n maxRows: z.number().int().min(1).max(250_000).optional(),\n unmatchedLimit: z.number().int().min(0).max(100).optional(),\n },\n },\n async ({\n site,\n dimension,\n days,\n compareDays,\n startDate,\n endDate,\n limit,\n maxRows,\n unmatchedLimit,\n refresh,\n }) => {\n try {\n const result = await (dependencies.segmentImpact ?? segmentImpact)({\n site,\n dimension,\n days,\n compareDays,\n startDate,\n endDate,\n limit,\n maxRows,\n unmatchedLimit,\n refresh,\n })\n return toolSuccess(result.summary.verdict, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_striking_distance',\n {\n description: 'Find position 11-20 query/page opportunities from GSC',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'minImpressions',\n 'limit',\n 'verifyContent',\n 'verifyLimit',\n 'includeBrand',\n 'js',\n 'fetchConcurrency',\n 'fetchIntervalCap',\n 'fetchIntervalMs',\n 'refresh',\n ]),\n days: z.number().int().min(1).max(548).optional(),\n minImpressions: z.number().int().min(0).max(1_000_000_000).optional(),\n limit: z.number().int().min(1).max(100).optional(),\n verifyLimit: z.number().int().min(0).max(100).optional(),\n brandTerms: z\n .array(z.string().trim().min(1).max(200))\n .max(20)\n .optional(),\n fetchConcurrency: z.number().int().min(1).max(16).optional(),\n fetchIntervalCap: z.number().int().min(1).max(60).optional(),\n fetchIntervalMs: z.number().int().min(100).max(60_000).optional(),\n },\n },\n async ({\n site,\n days,\n minImpressions,\n limit,\n verifyContent,\n verifyLimit,\n includeBrand,\n brandTerms,\n js,\n fetchConcurrency,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n }: StrikingDistanceToolInput) => {\n try {\n const result = await strikingDistance({\n site,\n days,\n minImpressions,\n limit,\n verifyContent,\n verifyLimit,\n includeBrand,\n brandTerms,\n js: resolveJsOption(js, undefined),\n rate: fetchRateInput({\n fetchConcurrency,\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n refresh,\n })\n return toolSuccess(result.summary.verdict, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_traffic_anomaly',\n {\n description:\n 'Detect statistically significant recent GSC traffic movement',\n inputSchema: {\n ...mcpReportInputSchema(['site', 'days', 'recentDays', 'refresh']),\n },\n },\n async ({ site, days, recentDays, refresh }) => {\n try {\n const result = await trafficAnomaly({ site, days, recentDays, refresh })\n return toolSuccess(\n `${result.anomalies.filter((item) => item.significant).length} significant anomalies found.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_update_correlate',\n {\n description:\n 'Overlay recent traffic anomalies against official Google ranking update windows',\n inputSchema: {\n ...mcpReportInputSchema(['site', 'days', 'recentDays', 'refresh']),\n paddingDays: z.number().optional(),\n },\n },\n async ({ site, days, recentDays, paddingDays, refresh }) => {\n try {\n const result = await updateCorrelation({\n site,\n days,\n recentDays,\n paddingDays,\n refresh,\n })\n return toolSuccess(`Classification: ${result.classification}.`, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n createContentGroup,\n deleteChange,\n deleteContentGroup,\n listChanges,\n listContentGroups,\n measureChange,\n recordChange,\n} from '@seo/core'\nimport * as z from 'zod/v4'\nimport { calendarDateSchema } from './input-schemas.js'\nimport { toolError, toolSuccess } from './tool-result.js'\n\nexport function registerExperimentTools(server: McpServer): void {\n server.registerTool(\n 'seo_content_groups',\n {\n description: 'List, create, or delete reusable page/query groups',\n inputSchema: {\n action: z.enum(['list', 'add', 'delete']),\n site: z.string().optional(),\n id: z.string().optional(),\n name: z.string().optional(),\n dimension: z.enum(['page', 'query']).optional(),\n matchType: z.enum(['equals', 'contains', 'regex']).optional(),\n pattern: z.string().optional(),\n },\n },\n async ({ action, site, id, name, dimension, matchType, pattern }) => {\n try {\n if (action === 'list') {\n const groups = listContentGroups(site)\n return toolSuccess(`${groups.length} content groups found.`, {\n groups,\n })\n }\n if (action === 'delete') {\n if (!id) throw new Error('Pass id to delete a content group.')\n const deleted = deleteContentGroup(id)\n return toolSuccess(\n deleted ? 'Content group deleted.' : 'Not found.',\n {\n id,\n deleted,\n },\n )\n }\n if (!site || !name || !pattern) {\n throw new Error(\n 'Pass site, name, and pattern to add a content group.',\n )\n }\n const group = createContentGroup({\n site,\n name,\n dimension,\n matchType,\n pattern,\n })\n return toolSuccess(`Content group created: ${group.name}.`, group)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_change_log',\n {\n description: 'List or record SEO annotations and site changes',\n inputSchema: {\n action: z.enum(['list', 'add', 'delete']),\n site: z.string().optional(),\n id: z.string().optional(),\n limit: z.number().optional(),\n scope: z.enum(['site', 'page', 'query', 'group']).optional(),\n target: z.string().optional(),\n title: z.string().optional(),\n description: z.string().optional(),\n changedAt: z.string().optional(),\n },\n },\n async ({\n action,\n site,\n id,\n limit,\n scope,\n target,\n title,\n description,\n changedAt,\n }) => {\n try {\n if (action === 'list') {\n const changes = listChanges({ site, limit })\n return toolSuccess(`${changes.length} changes found.`, { changes })\n }\n if (action === 'delete') {\n if (!id) throw new Error('Pass id to delete a change.')\n const deleted = deleteChange(id)\n return toolSuccess(deleted ? 'Change deleted.' : 'Not found.', {\n id,\n deleted,\n })\n }\n if (!site || !scope || !target || !title) {\n throw new Error(\n 'Pass site, scope, target, and title to add a change.',\n )\n }\n const change = recordChange({\n site,\n scope,\n target,\n title,\n description,\n changedAt: changedAt ?? new Date().toISOString().slice(0, 10),\n })\n return toolSuccess(`Change recorded: ${change.title}.`, change)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_measure_change',\n {\n description:\n 'Measure a saved or ad hoc SEO change with equal finalized GSC windows and optional GA4/control evidence',\n inputSchema: {\n id: z.string().min(1).optional(),\n site: z.string().min(1).optional(),\n scope: z.enum(['site', 'page', 'query', 'group']).optional(),\n target: z.string().min(1).optional(),\n title: z.string().min(1).optional(),\n changedAt: calendarDateSchema.optional(),\n ga4PropertyId: z.string().min(1).optional(),\n controlScope: z.enum(['site', 'page', 'query', 'group']).optional(),\n controlTarget: z.string().min(1).optional(),\n controlTitle: z.string().min(1).optional(),\n beforeDays: z.number().int().min(1).max(548).optional(),\n afterDays: z.number().int().min(1).max(548).optional(),\n refresh: z.boolean().optional(),\n },\n },\n async ({\n id,\n site,\n scope,\n target,\n title,\n changedAt,\n ga4PropertyId,\n controlScope,\n controlTarget,\n controlTitle,\n beforeDays,\n afterDays,\n refresh,\n }) => {\n try {\n const result = await measureChange({\n id,\n site,\n scope,\n target,\n title,\n changedAt,\n ga4PropertyId,\n controlScope,\n controlTarget,\n controlTitle,\n beforeDays,\n afterDays,\n refresh,\n })\n return toolSuccess(\n `Measurement ${result.dataStatus}. Verdict: ${result.verdict}. Compared ${result.window.effectiveDays}/${result.window.requestedDays} finalized days.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n crawlDiff,\n indexCoveragePlan,\n indexCoverageSignals,\n indexMonitor,\n indexWatch,\n linkRecover,\n redirectTrace,\n} from '@seo/core'\nimport * as z from 'zod/v4'\nimport { resolveJsOption } from './input-schemas.js'\nimport { mcpReportInputSchema } from './report-options.js'\nimport { toolError, toolSuccess } from './tool-result.js'\n\nexport function registerMonitoringTools(server: McpServer): void {\n server.registerTool(\n 'seo_crawl_diff',\n {\n description:\n 'Crawl a bounded same-origin URL set and compare technical/page changes with the previous run',\n inputSchema: {\n startUrl: z.string().url(),\n site: z.string().optional(),\n limit: z.number().optional(),\n refresh: z.boolean().optional(),\n js: z.boolean().optional(),\n },\n },\n async ({ startUrl, site, limit, refresh, js }) => {\n try {\n const result = await crawlDiff({\n startUrl,\n site,\n limit,\n refresh,\n js: resolveJsOption(js, 'auto'),\n })\n return toolSuccess(\n `Crawled ${result.summary.crawled} URLs. ${result.summary.changed} changed vs previous run.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_index_watch',\n {\n description:\n \"Inspect a bounded URL set against Google's indexed snapshot and separate current issues, regressions, recoveries, and operational failures\",\n inputSchema: {\n site: z.string(),\n urls: z.array(z.string().url()).min(1).max(100),\n languageCode: z.string().min(1).max(35).optional(),\n dailyLimit: z.number().int().min(1).max(2_000).optional(),\n },\n },\n async ({ site, urls, languageCode, dailyLimit }) => {\n try {\n const result = await indexWatch({\n site,\n urls,\n languageCode,\n dailyLimit,\n })\n return toolSuccess(\n `Inspected ${result.summary.inspected} URLs. ${result.summary.currentIssues} current reviews, ${result.summary.regressions} regressions, ${result.summary.failed} failed, ${result.summary.quotaBlocked} quota-blocked, ${result.summary.deferred} deferred.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_index_coverage_plan',\n {\n description:\n 'Plan sitemap URL allocation across GSC properties and suggest URL-prefix properties for better URL Inspection coverage',\n inputSchema: {\n site: z.string(),\n sitemaps: z.array(z.string().url()).min(1).max(20),\n properties: z.array(z.string()).optional(),\n dailyLimit: z.number().int().min(1).max(2_000).optional(),\n targetCycleDays: z.number().int().min(1).max(365).optional(),\n maxUrls: z.number().int().min(1).max(250_000).optional(),\n },\n },\n async ({\n site,\n sitemaps,\n properties,\n dailyLimit,\n targetCycleDays,\n maxUrls,\n }) => {\n try {\n const result = await indexCoveragePlan({\n site,\n sitemaps,\n properties,\n dailyLimit,\n targetCycleDays,\n maxUrls,\n })\n return toolSuccess(\n `Planned ${result.summary.urlCount} sitemap URLs across ${result.summary.properties} properties. ${result.summary.suggestedProperties} suggested properties.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_index_coverage',\n {\n description:\n 'Compare a saved crawl and sitemap with Search Console page results, then choose representative URLs for URL Inspection',\n inputSchema: {\n site: z.string().min(1),\n crawlReportId: z.string().min(1).optional(),\n sitemaps: z.array(z.string().url()).min(1).max(20).optional(),\n days: z.number().int().min(1).max(548).optional(),\n rowLimit: z.number().int().min(1).max(250_000).optional(),\n maxSitemapUrls: z.number().int().min(1).max(250_000).optional(),\n itemsPerSection: z.number().int().min(1).max(1_000).optional(),\n templateClusters: z.number().int().min(1).max(200).optional(),\n templateSamples: z.number().int().min(1).max(25).optional(),\n refresh: z.boolean().optional(),\n },\n },\n async ({\n site,\n crawlReportId,\n sitemaps,\n days,\n rowLimit,\n maxSitemapUrls,\n itemsPerSection,\n templateClusters,\n templateSamples,\n refresh,\n }) => {\n try {\n const result = await indexCoverageSignals({\n site,\n crawlReportId,\n sitemaps,\n days,\n rowLimit,\n maxSitemapUrls,\n itemsPerSection,\n templateClusters,\n templateSamples,\n refresh,\n })\n return toolSuccess(\n `${result.summary.retainedSearchVisibleUrls} URLs appeared in the returned Search Console data. ${result.summary.crawlableCandidatesWithoutRetainedSearchVisibility} crawlable URLs need evidence review before choosing representative URL Inspection checks.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_index_monitor',\n {\n description:\n \"Run bounded, locally quota-enforced URL Inspection monitoring from XML sitemaps and store Google's indexed snapshots\",\n inputSchema: {\n site: z.string(),\n sitemaps: z.array(z.string().url()).min(1).max(20),\n properties: z.array(z.string()).optional(),\n dailyLimit: z.number().int().min(1).max(2_000).optional(),\n inspectLimit: z.number().int().min(1).max(100).optional(),\n maxUrls: z.number().int().min(1).max(250_000).optional(),\n languageCode: z.string().min(1).max(35).optional(),\n },\n },\n async ({\n site,\n sitemaps,\n properties,\n dailyLimit,\n inspectLimit,\n maxUrls,\n languageCode,\n }) => {\n try {\n const result = await indexMonitor({\n site,\n sitemaps,\n properties,\n dailyLimit,\n inspectLimit,\n maxUrls,\n languageCode,\n })\n return toolSuccess(\n `Inventory ${result.summary.inventoryUrls}; ${result.summary.due} due, ${result.summary.selected} selected, ${result.summary.inspected} inspected, ${result.summary.unselectedDue} due but not selected. ${result.summary.currentIssues} current reviews in selected results, ${result.summary.regressions} regressions, ${result.summary.failed} failed, ${result.summary.quotaBlocked} quota-blocked, ${result.summary.deferred} deferred.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_redirect_trace',\n {\n description:\n 'Trace redirects and report final indexability/canonical issues for a URL',\n inputSchema: {\n url: z.string().url(),\n maxHops: z.number().optional(),\n refresh: z.boolean().optional(),\n js: z.boolean().optional(),\n },\n },\n async ({ url, maxHops, refresh, js }) => {\n try {\n const result = await redirectTrace({\n url,\n maxHops,\n refresh,\n js: resolveJsOption(js, 'auto'),\n })\n return toolSuccess(\n `Traced ${result.summary.hops} hops. Final status ${result.summary.finalStatus}. ${result.summary.issues.length} issues.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_link_recover',\n {\n description:\n 'Find GSC search-value URLs that are now broken, blocked, or poorly redirected',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'limit',\n 'minImpressions',\n 'refresh',\n 'js',\n ]),\n minClicks: z.number().optional(),\n },\n },\n async ({ site, days, limit, minClicks, minImpressions, refresh, js }) => {\n try {\n const result = await linkRecover({\n site,\n days,\n limit,\n minClicks,\n minImpressions,\n refresh,\n js: resolveJsOption(js, 'auto'),\n })\n return toolSuccess(\n `Checked ${result.summary.checked} search-value URLs. ${result.summary.recoverable} recoverable issues.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n cannibalReport,\n ctrUnderperformersReport,\n decayingReport,\n getKeywordProvider,\n internalLinksReport,\n queryClusterReport,\n quickWinsReport,\n} from '@seo/core'\nimport * as z from 'zod/v4'\nimport { fetchRateInput } from './fetch-rate.js'\nimport { resolveJsOption } from './input-schemas.js'\nimport { mcpReportInputSchema } from './report-options.js'\nimport { summarize, toolError, toolSuccess } from './tool-result.js'\n\ntype QuickWinsToolInput = {\n site: string\n days?: number\n limit?: number\n minImpressions?: number\n brandTerms?: string[]\n verifyContent?: boolean\n verifyLimit?: number\n includeBrand?: boolean\n js?: boolean\n fetchConcurrency?: number\n fetchIntervalCap?: number\n fetchIntervalMs?: number\n refresh?: boolean\n}\n\ntype InternalLinksToolInput = {\n site: string\n targetUrl: string\n days?: number\n limit?: number\n checkLimit?: number\n minImpressions?: number\n brandTerms?: string[]\n includeBrand?: boolean\n js?: boolean\n fetchConcurrency?: number\n fetchIntervalCap?: number\n fetchIntervalMs?: number\n refresh?: boolean\n}\n\nexport function registerOpportunityTools(\n server: McpServer,\n dependencies: {\n ctrUnderperformersReport?: typeof ctrUnderperformersReport\n internalLinksReport?: typeof internalLinksReport\n queryClusterReport?: typeof queryClusterReport\n quickWinsReport?: typeof quickWinsReport\n } = {},\n): void {\n server.registerTool(\n 'seo_cannibal',\n {\n description:\n 'Find multi-URL query exposure candidates for intent and technical review',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'limit',\n 'minImpressions',\n 'includeBrand',\n 'refresh',\n ]),\n days: z.number().int().min(1).max(548).optional(),\n limit: z.number().int().min(1).max(100).optional(),\n minImpressions: z.number().int().min(0).max(1_000_000_000).optional(),\n brandTerms: z\n .array(z.string().trim().min(1).max(200))\n .max(20)\n .optional(),\n },\n },\n async ({\n site,\n days,\n limit,\n minImpressions,\n brandTerms,\n includeBrand,\n refresh,\n }) => {\n try {\n const result = await cannibalReport({\n site,\n days,\n limit,\n minImpressions,\n brandTerms,\n includeBrand,\n refresh,\n })\n return toolSuccess(result.summary.verdict, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_decaying',\n {\n description:\n 'Find query/page click declines observed in both retained GSC windows and investigation signals',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'limit',\n 'includeBrand',\n 'refresh',\n ]),\n days: z.number().int().min(1).max(548).optional(),\n limit: z.number().int().min(1).max(100).optional(),\n comparison: z.enum(['previous-period', 'year-over-year']).optional(),\n minDropPct: z.number().min(0).max(100).optional(),\n minPreviousClicks: z.number().min(0).max(1_000_000_000).optional(),\n minClickLoss: z.number().min(0).max(1_000_000_000).optional(),\n brandTerms: z\n .array(z.string().trim().min(1).max(200))\n .max(20)\n .optional(),\n },\n },\n async ({\n site,\n days,\n limit,\n comparison,\n minDropPct,\n minPreviousClicks,\n minClickLoss,\n brandTerms,\n includeBrand,\n refresh,\n }) => {\n try {\n const result = await decayingReport({\n site,\n days,\n limit,\n comparison,\n minDropPct,\n minPreviousClicks,\n minClickLoss,\n brandTerms,\n includeBrand,\n refresh,\n })\n return toolSuccess(result.summary.verdict, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_quick_wins',\n {\n description: 'Find quick-win CTR/position opportunities',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'limit',\n 'minImpressions',\n 'verifyContent',\n 'verifyLimit',\n 'includeBrand',\n 'js',\n 'fetchConcurrency',\n 'fetchIntervalCap',\n 'fetchIntervalMs',\n 'refresh',\n ]),\n days: z.number().int().min(1).max(548).optional(),\n limit: z.number().int().min(1).max(100).optional(),\n minImpressions: z.number().int().min(0).max(1_000_000_000).optional(),\n verifyLimit: z.number().int().min(0).max(100).optional(),\n brandTerms: z\n .array(z.string().trim().min(1).max(200))\n .max(20)\n .optional(),\n fetchConcurrency: z.number().int().min(1).max(16).optional(),\n fetchIntervalCap: z.number().int().min(1).max(60).optional(),\n fetchIntervalMs: z.number().int().min(100).max(60_000).optional(),\n },\n },\n async ({\n site,\n days,\n limit,\n minImpressions,\n brandTerms,\n verifyContent,\n verifyLimit,\n includeBrand,\n js,\n fetchConcurrency,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n }: QuickWinsToolInput) => {\n try {\n const result = await (dependencies.quickWinsReport ?? quickWinsReport)({\n site,\n days,\n limit,\n minImpressions,\n brandTerms,\n verifyContent,\n verifyLimit,\n includeBrand,\n js: resolveJsOption(js, undefined),\n rate: fetchRateInput({\n fetchConcurrency,\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n refresh,\n })\n return toolSuccess(result.summary.verdict, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_internal_links',\n {\n description:\n 'Find verified internal-link review candidates for a target URL',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'limit',\n 'checkLimit',\n 'minImpressions',\n 'includeBrand',\n 'js',\n 'fetchConcurrency',\n 'fetchIntervalCap',\n 'fetchIntervalMs',\n 'refresh',\n ]),\n targetUrl: z\n .string()\n .url()\n .refine((value) => /^https?:\\/\\//.test(value), 'Use an HTTP(S) URL.'),\n days: z.number().int().min(1).max(548).optional(),\n limit: z.number().int().min(1).max(100).optional(),\n checkLimit: z.number().int().min(1).max(200).optional(),\n minImpressions: z.number().min(0).max(1_000_000_000).optional(),\n brandTerms: z\n .array(z.string().trim().min(1).max(200))\n .max(20)\n .optional(),\n fetchConcurrency: z.number().int().min(1).max(16).optional(),\n fetchIntervalCap: z.number().int().min(1).max(60).optional(),\n fetchIntervalMs: z.number().int().min(100).max(60_000).optional(),\n },\n },\n async ({\n site,\n targetUrl,\n days,\n limit,\n checkLimit,\n minImpressions,\n brandTerms,\n includeBrand,\n js,\n fetchConcurrency,\n fetchIntervalCap,\n fetchIntervalMs,\n refresh,\n }: InternalLinksToolInput) => {\n try {\n const result = await (\n dependencies.internalLinksReport ?? internalLinksReport\n )({\n site,\n targetUrl,\n days,\n limit,\n checkLimit,\n minImpressions,\n brandTerms,\n includeBrand,\n js: resolveJsOption(js, undefined),\n rate: fetchRateInput({\n fetchConcurrency,\n fetchIntervalCap,\n fetchIntervalMs,\n }),\n refresh,\n })\n return toolSuccess(result.summary.verdict, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_ctr_underperformers',\n {\n description:\n 'Find high-impression queries underperforming CTR expectations',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'minImpressions',\n 'limit',\n 'includeBrand',\n 'refresh',\n ]),\n site: z.string().trim().min(1),\n minImpressions: z.number().int().min(1).max(1_000_000_000).optional(),\n limit: z.number().int().min(1).max(100).optional(),\n brandTerms: z\n .array(z.string().trim().min(1).max(200))\n .max(20)\n .optional(),\n },\n },\n async ({\n site,\n minImpressions,\n limit,\n brandTerms,\n includeBrand,\n refresh,\n }) => {\n try {\n const result = await (\n dependencies.ctrUnderperformersReport ?? ctrUnderperformersReport\n )({\n site,\n minImpressions,\n limit,\n brandTerms,\n includeBrand,\n refresh,\n })\n return toolSuccess(result.summary.verdict, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_query_cluster',\n {\n description: 'Cluster queries by token overlap',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'includeBrand',\n 'minImpressions',\n 'limit',\n 'refresh',\n ]),\n site: z.string().trim().min(1),\n scope: z.string().trim().min(1).max(2_000).optional(),\n minImpressions: z.number().int().min(1).max(1_000_000_000).optional(),\n limit: z.number().int().min(1).max(100).optional(),\n brandTerms: z\n .array(z.string().trim().min(1).max(200))\n .max(20)\n .optional(),\n },\n },\n async ({\n site,\n scope,\n brandTerms,\n includeBrand,\n minImpressions,\n limit,\n refresh,\n }) => {\n try {\n const result = await (\n dependencies.queryClusterReport ?? queryClusterReport\n )({\n site,\n scope,\n brand: brandTerms?.[0],\n brandTerms,\n includeBrand,\n minImpressions,\n limit,\n refresh,\n })\n return toolSuccess(result.summary.verdict, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'semrush_call',\n {\n description:\n 'Raw-ish Semrush passthrough for supported keyword endpoints',\n inputSchema: {\n endpoint: z.enum(['phrase_this', 'phrase_related', 'phrase_questions']),\n phrase: z.string(),\n },\n },\n async ({ endpoint, phrase }) => {\n try {\n const provider = getKeywordProvider('authoritative')\n if (!provider) {\n throw new Error('No keyword provider configured.')\n }\n\n const result =\n endpoint === 'phrase_this'\n ? await provider.keywordOverview(phrase)\n : endpoint === 'phrase_related'\n ? await provider.relatedKeywords?.(phrase)\n : await provider.questions?.(phrase)\n\n if (!result) {\n throw new Error(\n `Endpoint ${endpoint} is not supported by the active provider.`,\n )\n }\n\n return toolSuccess(summarize(result.data), result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n countLabel,\n pseoAuditReport,\n pseoPresentation,\n renderPseoMarkdown,\n} from '@seo/core'\nimport * as z from 'zod/v4'\nimport { resolveJsOption } from './input-schemas.js'\nimport { toolError, toolSuccess } from './tool-result.js'\n\nexport function compactPseoReport(\n result: Awaited<ReturnType<typeof pseoAuditReport>>,\n) {\n return {\n schemaVersion: result.schemaVersion,\n methodology: result.methodology,\n site: result.site,\n generatedAt: result.generatedAt,\n range: result.range,\n dataStatus: result.dataStatus,\n summary: result.summary,\n source: result.source,\n selection: result.selection,\n caveats: result.caveats,\n warnings: result.warnings,\n templates: result.templates.map((template) => ({\n signature: template.signature,\n urlCount: template.urlCount,\n sampleUrls: template.sampleUrls,\n population: template.population,\n verdict: template.verdict,\n confidence: template.confidence,\n metrics: template.metrics,\n crawl: {\n requested: template.crawl.requested,\n attempted: template.crawl.attempted,\n usable: template.crawl.usable,\n blockedOrFailed: template.crawl.blockedOrFailed,\n },\n inspection: {\n requested: template.inspection.requested,\n attempted: template.inspection.attempted,\n indexed: template.inspection.indexed,\n notIndexed: template.inspection.notIndexed,\n unknown: template.inspection.unknown,\n },\n evidence: template.evidence,\n recommendation: template.recommendation,\n })),\n }\n}\n\nexport function registerPseoTools(server: McpServer): void {\n server.registerTool(\n 'seo_pseo_audit',\n {\n description:\n 'Audit pSEO templates with first-party GSC, optional crawl, and optional URL Inspection evidence',\n inputSchema: {\n site: z.string().min(1),\n days: z.number().int().min(1).max(548).optional(),\n sitemaps: z.array(z.string().url()).max(20).optional(),\n maxSitemapUrls: z.number().int().min(1).max(100_000).optional(),\n templateLimit: z.number().int().min(1).max(100).optional(),\n minimumTemplateUrls: z.number().int().min(2).max(100).optional(),\n minimumTemplateShare: z.number().min(0).max(1).optional(),\n minimumTemplateImpressions: z\n .number()\n .min(0)\n .max(1_000_000_000)\n .optional(),\n crawlSamples: z.number().int().min(0).max(10).optional(),\n inspectSamples: z.number().int().min(0).max(10).optional(),\n brandTerms: z.array(z.string().min(1).max(200)).max(20).optional(),\n includeBrand: z.boolean().optional(),\n refresh: z.boolean().optional(),\n js: z.boolean().optional(),\n fetchConcurrency: z.number().int().min(1).max(20).optional(),\n fetchIntervalCap: z.number().int().min(1).max(100).optional(),\n fetchIntervalMs: z.number().int().min(100).max(60_000).optional(),\n detail: z.enum(['summary', 'full']).optional(),\n },\n },\n async ({\n site,\n days,\n sitemaps,\n templateLimit,\n maxSitemapUrls,\n minimumTemplateUrls,\n minimumTemplateShare,\n minimumTemplateImpressions,\n crawlSamples,\n inspectSamples,\n brandTerms,\n includeBrand,\n refresh,\n js,\n fetchConcurrency,\n fetchIntervalCap,\n fetchIntervalMs,\n detail,\n }) => {\n try {\n const result = await pseoAuditReport({\n site,\n days,\n sitemaps,\n maxSitemapUrls,\n templateLimit,\n minimumTemplateUrls,\n minimumTemplateShare,\n minimumTemplateImpressions,\n crawlSamples,\n inspectSamples,\n brandTerms,\n includeBrand,\n refresh,\n js: resolveJsOption(js, 'auto'),\n rate: {\n concurrency: fetchConcurrency,\n intervalCap: fetchIntervalCap,\n intervalMs: fetchIntervalMs,\n },\n })\n const full = detail === 'full'\n return toolSuccess(\n `${countLabel(result.summary.templates, 'pSEO template')} audited from ${countLabel(result.summary.gscPages, 'GSC page')}.`,\n full\n ? { report: result, presentation: pseoPresentation(result) }\n : { report: compactPseoReport(result) },\n full ? { markdown: renderPseoMarkdown(result) } : undefined,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n}\n","export type ReportGuidance = {\n name: string\n description: string\n useWhen:\n | readonly [string]\n | readonly [string, string]\n | readonly [string, string, string]\n avoidWhen: readonly [string] | readonly [string, string]\n outcome: string\n}\n\nexport const REPORT_GUIDANCE = {\n 'affected-urls': {\n name: 'URLs affected by a crawl issue',\n description:\n 'Open the exact pages behind a crawl finding so you can review or fix the right URLs.',\n useWhen: [\n 'A crawl summary shows an issue that needs a closer look.',\n 'You need the affected URLs for one rule, category, or severity.',\n ],\n avoidWhen: [\n 'You have not run or selected a crawl yet.',\n 'You need an overview of the most important crawl findings first.',\n ],\n outcome:\n 'A focused list of affected URLs with the evidence for each match.',\n },\n 'ai-readiness': {\n name: 'AI search technical readiness',\n description:\n 'Check whether crawl, index, or snippet controls could block pages from Google AI search features.',\n useWhen: [\n 'You want to check technical access before investigating AI search visibility.',\n 'You need page-level evidence for robots, indexability, or snippet restrictions.',\n ],\n avoidWhen: [\n 'You want a visibility score or a prediction of AI citations.',\n 'You need evidence of visits from AI products.',\n ],\n outcome: 'A technical blocker list with affected pages and clear limits.',\n },\n 'ai-referrals': {\n name: 'AI referral traffic',\n description:\n 'Find visits from known AI products in GA4 and see a ranked, bounded set of landing pages that received them.',\n useWhen: [\n 'You want measured AI referral traffic from GA4.',\n 'You need the landing pages and sources behind those visits.',\n ],\n avoidWhen: [\n 'GA4 is not connected or does not track the site.',\n 'You want to measure citations or unclicked mentions inside AI answers.',\n ],\n outcome:\n 'A source and landing-page breakdown of identifiable AI referrals.',\n },\n 'audit-page': {\n name: 'Single-page SEO audit',\n description:\n 'Check one URL for response, indexability, metadata, headings, links, and page content evidence.',\n useWhen: [\n 'One page needs a technical review before you change it.',\n 'A broader report points to a specific URL.',\n ],\n avoidWhen: [\n 'You need to discover issues across a whole site.',\n 'The page requires a logged-in browser session.',\n ],\n outcome:\n 'A page-level audit that separates observed evidence from review advice.',\n },\n 'audit-urls': {\n name: 'Selected URL audit',\n description:\n 'Audit a specific list of pages without crawling the rest of the site.',\n useWhen: [\n 'You already know which URLs need checking.',\n 'You want a repeatable pre-release or post-release check for key pages.',\n ],\n avoidWhen: [\n 'You need the crawler to discover pages for you.',\n 'You only need a deep review of one page.',\n ],\n outcome: 'Consistent technical checks for each supplied URL.',\n },\n cannibalisation: {\n name: 'Query and URL overlap',\n description:\n 'Find search queries that appear across several URLs and decide whether the overlap needs attention.',\n useWhen: [\n 'Several pages may be competing for the same search intent.',\n 'You want query-level evidence before merging or redirecting pages.',\n ],\n avoidWhen: [\n 'You plan to treat every multi-URL query as a problem.',\n 'The site has too little Search Console data for meaningful overlap.',\n ],\n outcome:\n 'A ranked review list of queries, URLs, and their share of search exposure.',\n },\n 'community-intent': {\n name: 'Community and review intent',\n description:\n 'Find Search Console queries that explicitly ask for reviews, comparisons, recommendations, or real experience.',\n useWhen: [\n 'You want to see where searchers ask for proof, opinions, or comparisons.',\n 'You are planning content that answers community-style questions.',\n ],\n avoidWhen: [\n 'You want the tool to guess intent without explicit query wording.',\n 'You need proof that a new page will rank.',\n ],\n outcome:\n 'A review list of real queries grouped by the intent language they contain.',\n },\n 'compare-crawls': {\n name: 'Compare saved crawls',\n description:\n 'Compare two saved crawl snapshots to see which pages and technical findings changed.',\n useWhen: [\n 'You want to check what changed after a release or migration.',\n 'You need evidence that a technical fix appeared in a later crawl.',\n ],\n avoidWhen: [\n 'The two crawls used materially different scope or settings.',\n 'You have only one saved crawl.',\n ],\n outcome:\n 'A before-and-after view of added, removed, fixed, and new findings.',\n },\n 'content-optimization': {\n name: 'Search-led content brief',\n description:\n 'Turn a page and its Search Console queries into a practical brief for improving relevance and coverage.',\n useWhen: [\n 'An existing page has search demand but needs a clearer improvement plan.',\n 'You want first-party query evidence beside the current page content.',\n ],\n avoidWhen: [\n 'The URL has no useful Search Console history.',\n 'You want generated copy or a traffic forecast.',\n ],\n outcome:\n 'A page brief with query evidence, content checks, and specific review points.',\n },\n 'crawl-diff': {\n name: 'Monitor crawl changes',\n description:\n 'Crawl a site and compare it with the previous matching run to catch technical changes.',\n useWhen: [\n 'You want a repeatable technical check after deployments.',\n 'You need newly introduced or resolved crawl findings.',\n ],\n avoidWhen: [\n 'There is no comparable earlier crawl.',\n 'You need to compare two specific saved crawl IDs.',\n ],\n outcome:\n 'A fresh crawl plus a clear list of technical changes since the previous run.',\n },\n 'crawl-history': {\n name: 'Saved crawl history',\n description:\n 'List local crawl snapshots so you can choose the right report by site and date.',\n useWhen: [\n 'You need to find a crawl ID for review or comparison.',\n 'You want to confirm which crawl snapshots exist locally.',\n ],\n avoidWhen: [\n 'You need the findings inside a crawl rather than its saved metadata.',\n ],\n outcome:\n 'A compact list of saved crawls with IDs, sites, dates, and scope.',\n },\n 'crawl-report': {\n name: 'Open a saved crawl',\n description:\n 'Load a saved crawl by ID, or open the latest local crawl for a site.',\n useWhen: [\n 'You already know which saved crawl you want to inspect.',\n 'Another report asks for crawl evidence by report ID.',\n ],\n avoidWhen: [\n 'You need to create a new crawl.',\n 'You only need a filtered list for one issue.',\n ],\n outcome: 'The selected crawl summary with optional page and issue detail.',\n },\n 'crawler-rules': {\n name: 'Crawler rule catalog',\n description:\n 'Find the available technical check IDs and the evidence each crawler rule looks for.',\n useWhen: [\n 'You need a valid rule ID for another crawl report.',\n 'You want to see which technical checks are available by category.',\n ],\n avoidWhen: ['You need affected pages or live crawl results.'],\n outcome: 'A searchable catalog of crawler rules, severity, and guidance.',\n },\n 'ctr-underperformers': {\n name: 'CTR underperformers',\n description:\n 'Find high-impression queries whose click-through rate trails comparable queries at similar positions.',\n useWhen: [\n 'You want title or snippet review candidates backed by Search Console data.',\n 'You need to compare CTR fairly across similar average positions.',\n ],\n avoidWhen: [\n 'You want a promised click uplift.',\n 'The comparison groups have too little data.',\n ],\n outcome:\n 'A ranked list of query and page pairs with CTR comparison evidence.',\n },\n 'decaying-pages': {\n name: 'Pages losing search clicks',\n description:\n 'Find pages and queries with meaningful click declines across comparable Search Console periods.',\n useWhen: [\n 'You want to investigate a sustained organic search decline.',\n 'You need the pages and queries behind lost clicks.',\n ],\n avoidWhen: [\n 'The newer period is incomplete or not comparable.',\n 'You want to assume every decline is caused by old content.',\n ],\n outcome:\n 'A ranked investigation list with before-and-after search evidence.',\n },\n 'entity-readiness': {\n name: 'Entity signal review',\n description:\n 'Check names, authors, dates, structured data, and profile links that help identify who created a page.',\n useWhen: [\n 'You want to review publisher, organization, or author signals across crawled pages.',\n 'You need examples of missing or inconsistent entity evidence.',\n ],\n avoidWhen: [\n 'You want a knowledge graph or ranking guarantee.',\n 'You have not saved or supplied a crawl.',\n ],\n outcome:\n 'Page-level entity observations with examples that need human review.',\n },\n 'explain-crawl-issue': {\n name: 'Explain a crawl issue',\n description:\n 'Explain what one crawler rule means, why it may matter, and how to verify a fix.',\n useWhen: [\n 'A crawl returned a rule ID you do not recognize.',\n 'You need implementation and verification guidance before creating work.',\n ],\n avoidWhen: [\n 'You need the URLs affected by the rule.',\n 'You have not selected a valid crawler rule ID.',\n ],\n outcome:\n 'A plain-English rule explanation with fix and verification steps.',\n },\n 'generate-llms-txt': {\n name: 'Generate an llms.txt draft',\n description:\n 'Create a concise llms.txt draft from selected public pages in a crawl report.',\n useWhen: [\n 'You want a human-reviewed navigation file for useful public pages.',\n 'You have a current crawl that identifies suitable canonical URLs.',\n ],\n avoidWhen: [\n 'You expect the file to improve rankings, indexing, or AI citations.',\n 'The source crawl is old, partial, or aimed at the wrong site section.',\n ],\n outcome:\n 'An editable llms.txt draft with source and size limits kept visible.',\n },\n 'geo-gaps': {\n name: 'Google AI search controls',\n description:\n 'Find crawl, index, and snippet settings that could restrict pages in Google AI search features.',\n useWhen: [\n 'You want to find technical restrictions that apply to Google AI search.',\n 'You need affected pages for a crawl, index, or preview control.',\n ],\n avoidWhen: [\n 'You want a generic AI visibility score.',\n 'You need referral traffic or citation monitoring.',\n ],\n outcome:\n 'A focused list of technical restrictions and the pages where they appear.',\n },\n 'index-coverage-plan': {\n name: 'URL Inspection coverage plan',\n description:\n 'Choose which sitemap URLs and Search Console properties should use limited URL Inspection checks.',\n useWhen: [\n 'A large site needs a practical sampling plan for URL Inspection.',\n 'You want to spread checks across useful URL-prefix properties.',\n ],\n avoidWhen: [\n 'You need current Google index results rather than a plan.',\n 'You want complete coverage beyond the available quota.',\n ],\n outcome: 'A quota-aware list of URLs and properties to inspect next.',\n },\n 'index-coverage': {\n name: 'Index coverage signals',\n description:\n 'Compare the pages your site exposes with pages that had Google Search visibility, then choose representative URLs for URL Inspection.',\n useWhen: [\n 'You need to find crawlable pages that did not appear in the Search Console results returned for the selected period.',\n 'You want a focused review list before spending URL Inspection quota.',\n ],\n avoidWhen: [\n 'You need proof that a URL is indexed or excluded. Use URL Inspection for that URL.',\n 'You do not have a saved crawl for the selected site.',\n ],\n outcome:\n 'Cross-source URL groups with clear evidence limits and a representative review queue for URL Inspection.',\n },\n 'index-monitor': {\n name: 'Collect index snapshots',\n description:\n 'Check selected sitemap URLs with Google URL Inspection and save the results locally for later comparison.',\n useWhen: [\n 'You want current Google index evidence for a controlled URL set.',\n 'You need repeatable snapshots for future monitoring.',\n ],\n avoidWhen: [\n 'You expect every URL in a large site to be checked at once.',\n 'You only need to review previously saved snapshots.',\n ],\n outcome:\n 'Saved URL Inspection results with quota skips and provider failures separated.',\n },\n 'index-watch': {\n name: 'Review index changes',\n description:\n 'Compare current Google index evidence with saved snapshots to find regressions and recoveries.',\n useWhen: [\n 'You want to see which monitored URLs changed index state.',\n 'You need to separate page issues from quota or provider failures.',\n ],\n avoidWhen: [\n 'No earlier index snapshots exist.',\n 'You want a complete index count for the whole site.',\n ],\n outcome:\n 'A review queue of current issues, regressions, recoveries, and failed checks.',\n },\n 'internal-links': {\n name: 'Internal link opportunities',\n description:\n 'Find relevant pages that could add a useful internal link to a target URL.',\n useWhen: [\n 'A target page needs stronger internal discovery or contextual links.',\n 'You want candidate source pages checked against their current content.',\n ],\n avoidWhen: [\n 'You want links added automatically.',\n 'The target and candidate pages do not share a clear topic or user need.',\n ],\n outcome:\n 'Verified source-page candidates with query and page evidence for review.',\n },\n 'link-recovery': {\n name: 'Recover broken search-value URLs',\n description:\n 'Find URLs that previously earned search clicks but now fail, redirect poorly, or block indexing.',\n useWhen: [\n 'You suspect valuable URLs broke during a migration or release.',\n 'You want to prioritize technical recovery using Search Console evidence.',\n ],\n avoidWhen: [\n 'You want a backlink report.',\n 'You have no Search Console page history for the site.',\n ],\n outcome:\n 'A ranked recovery list with current URL checks and prior search value.',\n },\n 'llms-txt-audit': {\n name: 'Audit llms.txt',\n description:\n 'Check whether llms.txt exists, whether its links work, and how well it reflects useful public pages.',\n useWhen: [\n 'The site publishes llms.txt and you want to verify it.',\n 'You are deciding whether a concise navigation file would help agents.',\n ],\n avoidWhen: [\n 'You expect llms.txt to improve Google rankings or indexing.',\n 'You need to generate a new draft rather than audit the current file.',\n ],\n outcome:\n 'File, link, and page coverage findings with no visibility claims.',\n },\n 'measure-change': {\n name: 'Measure an SEO change',\n description:\n 'Compare equal Search Console periods before and after a known site change.',\n useWhen: [\n 'A release, migration, or content change has a clear date.',\n 'Both comparison periods contain final and comparable data.',\n ],\n avoidWhen: [\n 'The after period is incomplete.',\n 'You need proof that the change caused the movement.',\n ],\n outcome:\n 'A before-and-after search comparison with confounders and data limits shown.',\n },\n 'monthly-action-plan': {\n name: 'Monthly SEO action plan',\n description:\n 'Review a calendar month of search performance and turn the evidence into next actions.',\n useWhen: [\n 'You need a recurring monthly review with clear priorities.',\n 'The selected month has final Search Console data.',\n ],\n avoidWhen: [\n 'You only need a client-ready summary without an action queue.',\n 'The month is still incomplete.',\n ],\n outcome: 'A monthly performance summary followed by a focused action plan.',\n },\n 'monthly-report': {\n name: 'Monthly SEO report',\n description:\n 'Turn one calendar month of search evidence into a concise report for clients or teams.',\n useWhen: [\n 'You need a readable monthly summary of organic search performance.',\n 'The selected month has final Search Console data.',\n ],\n avoidWhen: [\n 'You need a rolling period rather than a calendar month.',\n 'You want a detailed technical site audit.',\n ],\n outcome:\n 'A clear monthly narrative with wins, losses, caveats, and next steps.',\n },\n 'narrative-report': {\n name: 'Client-ready SEO narrative',\n description:\n 'Turn search, change, and monitoring evidence into a readable update without hiding caveats.',\n useWhen: [\n 'You need to explain recent SEO performance to a client or team.',\n 'You want one narrative built from several available evidence sources.',\n ],\n avoidWhen: [\n 'You need raw rows for further analysis.',\n 'You want unsupported forecasts or causal claims.',\n ],\n outcome:\n 'A concise written report with evidence, limits, and practical next steps.',\n },\n 'okf-build': {\n name: 'Build site knowledge for agents',\n description:\n 'Create a compact, cited site knowledge pack from public pages in a crawl.',\n useWhen: [\n 'An agent needs reliable site facts with links back to source pages.',\n 'You want a portable knowledge pack from selected crawl content.',\n ],\n avoidWhen: [\n 'The crawl contains private, stale, or irrelevant pages.',\n 'You want the tool to invent missing facts.',\n ],\n outcome: 'An OKF manifest and optional markdown files with source links.',\n },\n 'okf-validate': {\n name: 'Validate a site knowledge pack',\n description:\n 'Check supplied OKF markdown files for structure, references, and broken links before use.',\n useWhen: [\n 'You created or edited an OKF pack and want to check it.',\n 'An agent needs to verify files before loading them.',\n ],\n avoidWhen: ['You need to build the pack from a crawl first.'],\n outcome: 'A validation result with exact file, reference, and link errors.',\n },\n 'page-opportunities': {\n name: 'Opportunities for one page',\n description:\n 'Find Search Console queries and page evidence that point to useful improvements for one URL.',\n useWhen: [\n 'You want to improve an existing page using its own search demand.',\n 'You need query themes and page checks in one result.',\n ],\n avoidWhen: [\n 'The page has no useful Search Console data.',\n 'You want a guaranteed traffic gain.',\n ],\n outcome:\n 'A ranked page improvement list tied to real queries and current content.',\n },\n 'performance-audit': {\n name: 'Page performance audit',\n description:\n 'Run Lighthouse lab checks and add CrUX field Core Web Vitals when that data is available.',\n useWhen: [\n 'You need actionable performance diagnostics for a page.',\n 'You want lab findings kept separate from real-user field data.',\n ],\n avoidWhen: [\n 'You want Lighthouse scores presented as field Core Web Vitals.',\n 'The page cannot be fetched from the local machine.',\n ],\n outcome:\n 'Lab diagnostics plus clearly labelled field metrics when available.',\n },\n 'pseo-audit': {\n name: 'Programmatic SEO audit',\n description:\n 'Review repeated page templates using search demand, crawl evidence, and optional Google index checks.',\n useWhen: [\n 'A site publishes many pages from repeatable templates.',\n 'You need to compare template groups before expanding or pruning them.',\n ],\n avoidWhen: [\n 'You want every repeated path labelled as spam or thin content.',\n 'There are too few pages to compare as a template group.',\n ],\n outcome:\n 'Template-level demand, quality, and index evidence with representative URLs.',\n },\n 'query-clusters': {\n name: 'Search query clusters',\n description:\n 'Group related Search Console queries so repeated demand themes are easier to review.',\n useWhen: [\n 'A large query list needs a clearer topic structure.',\n 'You want to find repeated wording within a site section.',\n ],\n avoidWhen: [\n 'You need semantic or intent classification beyond shared query terms.',\n 'You want clusters turned into new pages automatically.',\n ],\n outcome: 'Stable query groups with the search demand behind each theme.',\n },\n 'quick-wins': {\n name: 'Page-one CTR opportunities',\n description:\n 'Find page-one query and URL pairs whose CTR deserves a closer look.',\n useWhen: [\n 'You want high-impression title and snippet review candidates.',\n 'You need page-one opportunities ranked from Search Console data.',\n ],\n avoidWhen: [\n 'You want a promised click gain.',\n 'You plan to treat a CTR heuristic as a Google requirement.',\n ],\n outcome:\n 'A ranked review queue with CTR, position, impressions, and comparison evidence.',\n },\n 'redirect-trace': {\n name: 'Redirect trace',\n description:\n 'Follow every redirect hop and check the final page, indexability, and canonical signals.',\n useWhen: [\n 'A URL redirects unexpectedly or through several hops.',\n 'You need to verify the final destination after a migration.',\n ],\n avoidWhen: [\n 'You need to discover redirect issues across a whole site.',\n 'The URL requires a signed-in browser session.',\n ],\n outcome: 'The complete redirect chain with final response and page checks.',\n },\n 'refresh-priorities': {\n name: 'Content refresh priorities',\n description:\n 'Combine search declines and near-term opportunities into a ranked content review queue.',\n useWhen: [\n 'You need to decide which existing pages to review first.',\n 'You want several Search Console signals ranked in one queue.',\n ],\n avoidWhen: [\n 'You need a technical crawl plan.',\n 'You want the ranking treated as a traffic forecast.',\n ],\n outcome:\n 'A focused list of pages and queries to investigate next, with reasons.',\n },\n 'search-performance-overview': {\n name: 'Search performance overview',\n description:\n 'Find where Google Search performance changed and choose the next focused report to inspect it.',\n useWhen: [\n 'You are starting an investigation and do not yet know which pages or queries moved.',\n 'You want one view of declines, gains, overlap, and near-term opportunities.',\n ],\n avoidWhen: [\n 'You already know the exact question and can run a focused report.',\n 'You need a technical crawl without Search Console analysis.',\n ],\n outcome:\n 'A clear search performance summary with a short list of next reports.',\n },\n 'second-page': {\n name: 'Second-page opportunities',\n description:\n 'Find URLs averaging positions 11 to 20 and see the queries behind each opportunity.',\n useWhen: [\n 'You want existing pages that may deserve closer review near page one.',\n 'You need page-level evidence across all matching queries.',\n ],\n avoidWhen: [\n 'You want average position treated as a fixed rank.',\n 'You need proof that a change will move the page to page one.',\n ],\n outcome:\n 'A ranked URL list with query, click, impression, and position evidence.',\n },\n 'segment-impact': {\n name: 'Search impact by segment',\n description:\n 'Compare page or query groups across equal periods to find which parts of a site moved.',\n useWhen: [\n 'A traffic change may be concentrated in one directory, page type, or query group.',\n 'You need to separate broad movement from a local segment issue.',\n ],\n avoidWhen: [\n 'The periods are incomplete or not comparable.',\n 'Missing Search Console rows would be mistaken for zero activity.',\n ],\n outcome:\n 'A segment comparison showing where clicks and impressions changed.',\n },\n 'seo-to-ai-query': {\n name: 'AI monitoring prompt ideas',\n description:\n 'Turn real Search Console query wording into a repeatable set of prompts for external AI monitoring.',\n useWhen: [\n 'You need prompt ideas grounded in the way people already find the site.',\n 'You want a stable prompt set for manual or third-party monitoring.',\n ],\n avoidWhen: [\n 'You want proof of demand inside AI products.',\n 'You want citation or visibility results from this report.',\n ],\n outcome:\n 'A prompt set linked back to its source queries and search metrics.',\n },\n 'setup-check': {\n name: 'Check local setup',\n description:\n 'Check Google login, scopes, local configuration, and saved defaults before running reports.',\n useWhen: [\n 'Authentication or site selection is failing.',\n 'You want to verify the local setup before investigating report errors.',\n ],\n avoidWhen: ['You need SEO findings rather than a setup check.'],\n outcome: 'A local setup status with the exact problems that need fixing.',\n },\n 'site-crawl': {\n name: 'Technical SEO site crawl',\n description:\n 'Crawl a site, check technical SEO signals, and save a local baseline for follow-up reports.',\n useWhen: [\n 'You need to discover technical issues across linked pages.',\n 'You want a crawl snapshot for later filtering or comparison.',\n ],\n avoidWhen: [\n 'You only need to check one page or a known URL list.',\n 'Important content requires browser rendering that is not enabled.',\n ],\n outcome:\n 'A crawl summary with page evidence, technical findings, and saved report ID.',\n },\n 'striking-distance': {\n name: 'Queries near page one',\n description:\n 'Find Search Console query and page pairs averaging positions 11 to 20.',\n useWhen: [\n 'You want existing search demand close to page one.',\n 'You need a compact list of queries and URLs for content review.',\n ],\n avoidWhen: [\n 'You want average position treated as an exact daily rank.',\n 'You need a promised ranking or click gain.',\n ],\n outcome:\n 'A ranked list of near-page-one query and URL pairs with search evidence.',\n },\n 'technical-watch': {\n name: 'Technical SEO watch',\n description:\n 'Run crawl and index checks together to catch technical regressions on a schedule.',\n useWhen: [\n 'You want recurring checks after releases or site changes.',\n 'You need crawl changes and selected Google index checks in one run.',\n ],\n avoidWhen: [\n 'You have not chosen any crawl, index, or link recovery input.',\n 'You need a one-off deep audit rather than ongoing monitoring.',\n ],\n outcome:\n 'A combined technical change report with failures and skipped checks kept separate.',\n },\n 'top-fixes': {\n name: 'Top technical SEO fixes',\n description:\n 'Turn crawl findings into a short, ranked queue of technical issues to investigate first.',\n useWhen: [\n 'A crawl contains too many findings to review at once.',\n 'You need representative URLs and reasons for the highest priorities.',\n ],\n avoidWhen: [\n 'You need every affected URL for one rule.',\n 'You plan to treat rank as proof of business impact.',\n ],\n outcome:\n 'A focused technical fix queue with issue evidence and example URLs.',\n },\n 'traffic-anomaly': {\n name: 'Unusual search traffic changes',\n description:\n \"Find recent clicks or impressions that moved beyond the site's normal Search Console pattern.\",\n useWhen: [\n 'You want an early signal of an unusual search change.',\n 'You need to know whether recent movement stands out from normal variation.',\n ],\n avoidWhen: [\n 'There is too little history for a useful baseline.',\n 'You want the report to identify the cause of the change.',\n ],\n outcome:\n 'A statistical movement signal with the dates, baseline, and limits shown.',\n },\n 'update-correlation': {\n name: 'Google update correlation',\n description:\n 'Compare search movement dates with official Google ranking update windows.',\n useWhen: [\n 'A traffic change overlaps a confirmed Google ranking update.',\n 'You need a timeline before investigating affected pages and queries.',\n ],\n avoidWhen: [\n 'You want overlap presented as proof of causation.',\n 'The traffic window does not cover the update dates.',\n ],\n outcome:\n 'A traffic and update timeline with overlaps clearly labelled as correlation.',\n },\n 'update-postmortem': {\n name: 'Google update impact review',\n description:\n 'Find the pages and queries that gained or lost around a confirmed Google ranking update.',\n useWhen: [\n 'You need winners and losers around a known update window.',\n 'You want to compare affected segments and known site changes.',\n ],\n avoidWhen: [\n 'You want the report to claim the update caused every change.',\n 'The comparison periods are incomplete or contain major unrecorded changes.',\n ],\n outcome:\n 'A post-update review of winners, losers, confounders, and next checks.',\n },\n} as const satisfies Record<string, ReportGuidance>\n\nexport function getReportGuidance(id: string): ReportGuidance | undefined {\n return (REPORT_GUIDANCE as Record<string, ReportGuidance>)[id]\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { auditPage } from '@seo/core'\nimport * as z from 'zod/v4'\nimport { resolveJsOption } from '../input-schemas.js'\nimport { toolError, toolSuccess } from '../tool-result.js'\n\nexport function registerAuditPageTool(server: McpServer): void {\n server.registerTool(\n 'seo_audit_page',\n {\n description: 'Run a single-page technical and content audit',\n inputSchema: {\n url: z.string().url(),\n site: z.string().optional(),\n js: z.boolean().optional(),\n refresh: z.boolean().optional(),\n },\n },\n async ({ url, site, js, refresh }) => {\n try {\n const result = await auditPage({\n url,\n site,\n js: resolveJsOption(js, 'auto'),\n refresh,\n })\n return toolSuccess(\n `Audit complete for ${url}. Found ${result.issues.length} issues.`,\n result,\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n}\n","import { fetchRateInput } from '../fetch-rate.js'\nimport { resolveJsOption } from '../input-schemas.js'\nimport { mcpReportInputSchema } from '../report-options.js'\n\nexport const reportFetchInputSchema = mcpReportInputSchema([\n 'verifyContent',\n 'verifyLimit',\n 'js',\n 'fetchConcurrency',\n 'fetchIntervalCap',\n 'fetchIntervalMs',\n 'refresh',\n])\n\nexport type ReportFetchToolInput = {\n verifyContent?: boolean\n verifyLimit?: number\n js?: boolean\n fetchConcurrency?: number\n fetchIntervalCap?: number\n fetchIntervalMs?: number\n refresh?: boolean\n}\n\nexport function reportFetchOptions(input: ReportFetchToolInput) {\n return {\n verifyContent: input.verifyContent,\n verifyLimit: input.verifyLimit,\n js: resolveJsOption(input.js, undefined),\n rate: fetchRateInput({\n fetchConcurrency: input.fetchConcurrency,\n fetchIntervalCap: input.fetchIntervalCap,\n fetchIntervalMs: input.fetchIntervalMs,\n }),\n refresh: input.refresh,\n }\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { monthlyReport, reportPresentation } from '@seo/core'\nimport { calendarMonthSchema } from '../input-schemas.js'\nimport { mcpReportInputSchema } from '../report-options.js'\nimport { toolError, toolSuccess } from '../tool-result.js'\nimport {\n type ReportFetchToolInput,\n reportFetchInputSchema,\n reportFetchOptions,\n} from './input.js'\n\ntype MonthlyReportToolInput = ReportFetchToolInput & {\n site: string\n month?: string\n limit?: number\n includeBrand?: boolean\n}\n\nexport function registerMonthlyReportTool(server: McpServer): void {\n server.registerTool(\n 'seo_monthly_report',\n {\n description: 'Generate a monthly SEO report narrative',\n inputSchema: {\n ...mcpReportInputSchema(['site', 'limit', 'includeBrand']),\n month: calendarMonthSchema.optional(),\n ...reportFetchInputSchema,\n },\n },\n async ({\n site,\n month,\n limit,\n includeBrand,\n ...fetchInput\n }: MonthlyReportToolInput) => {\n try {\n const result = await monthlyReport({\n site,\n month,\n limit,\n includeBrand,\n ...reportFetchOptions(fetchInput),\n })\n return toolSuccess(\n `Monthly report generated for ${result.month}. ${result.headline}`,\n { ...result, presentation: reportPresentation(result) },\n { markdown: result.markdown },\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { reportNarrative, reportPresentation } from '@seo/core'\nimport * as z from 'zod/v4'\nimport { calendarDateSchema } from '../input-schemas.js'\nimport { mcpReportInputSchema } from '../report-options.js'\nimport { toolError, toolSuccess } from '../tool-result.js'\nimport {\n type ReportFetchToolInput,\n reportFetchInputSchema,\n reportFetchOptions,\n} from './input.js'\n\ntype NarrativeReportToolInput = ReportFetchToolInput & {\n site: string\n days?: number\n recentDays?: number\n startDate?: string\n endDate?: string\n limit?: number\n changeLimit?: number\n includeBrand?: boolean\n}\n\nexport function registerNarrativeReportTool(server: McpServer): void {\n server.registerTool(\n 'seo_report_narrative',\n {\n description:\n 'Generate a client-ready SEO narrative across diagnosis, changes, and monitoring',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'recentDays',\n 'limit',\n 'includeBrand',\n ]),\n startDate: calendarDateSchema.optional(),\n endDate: calendarDateSchema.optional(),\n changeLimit: z.number().optional(),\n ...reportFetchInputSchema,\n },\n },\n async ({\n site,\n days,\n recentDays,\n startDate,\n endDate,\n limit,\n changeLimit,\n includeBrand,\n ...fetchInput\n }: NarrativeReportToolInput) => {\n try {\n const result = await reportNarrative({\n site,\n days,\n recentDays,\n startDate,\n endDate,\n limit,\n changeLimit,\n includeBrand,\n ...reportFetchOptions(fetchInput),\n })\n return toolSuccess(\n result.headline,\n { ...result, presentation: reportPresentation(result) },\n { markdown: result.markdown },\n )\n } catch (error) {\n return toolError(error)\n }\n },\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { secondPage } from '@seo/core'\nimport * as z from 'zod/v4'\nimport { mcpReportInputSchema } from '../report-options.js'\nimport { toolError, toolSuccess } from '../tool-result.js'\nimport {\n type ReportFetchToolInput,\n reportFetchInputSchema,\n reportFetchOptions,\n} from './input.js'\n\ntype SecondPageToolInput = ReportFetchToolInput & {\n site: string\n range?: number\n minImpressions?: number\n limit?: number\n includeBrand?: boolean\n brandTerms?: string[]\n}\n\nexport function registerSecondPageTool(server: McpServer): void {\n server.registerTool(\n 'seo_second_page',\n {\n description:\n 'Find URLs with GSC average position above 10 through 20 and return evidence-grounded investigation prompts',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'range',\n 'minImpressions',\n 'limit',\n 'includeBrand',\n ]),\n ...reportFetchInputSchema,\n range: z.number().int().min(1).max(548).optional(),\n minImpressions: z.number().int().min(0).max(1_000_000_000).optional(),\n limit: z.number().int().min(1).max(100).optional(),\n verifyLimit: z.number().int().min(0).max(100).optional(),\n brandTerms: z\n .array(z.string().trim().min(1).max(200))\n .max(20)\n .optional(),\n fetchConcurrency: z.number().int().min(1).max(16).optional(),\n fetchIntervalCap: z.number().int().min(1).max(60).optional(),\n fetchIntervalMs: z.number().int().min(100).max(60_000).optional(),\n },\n },\n async ({\n site,\n range,\n minImpressions,\n limit,\n includeBrand,\n brandTerms,\n ...fetchInput\n }: SecondPageToolInput) => {\n try {\n const result = await secondPage({\n site,\n range,\n minImpressions,\n limit,\n includeBrand,\n brandTerms,\n ...reportFetchOptions(fetchInput),\n })\n return toolSuccess(result.summary.verdict, result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { registerAuditPageTool } from './report-tools/audit-page.js'\nimport { registerMonthlyReportTool } from './report-tools/monthly.js'\nimport { registerNarrativeReportTool } from './report-tools/narrative.js'\nimport { registerSecondPageTool } from './report-tools/second-page.js'\n\nexport function registerReportTools(server: McpServer): void {\n registerNarrativeReportTool(server)\n registerMonthlyReportTool(server)\n registerAuditPageTool(server)\n registerSecondPageTool(server)\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n diagnosePropertyWorkflow,\n monthlyReportWorkflow,\n refreshPrioritiesWorkflow,\n renderWorkflowMarkdown,\n technicalWatchWorkflow,\n updatePostmortemWorkflow,\n type WorkflowReport,\n workflowPresentation,\n} from '@seo/core'\nimport * as z from 'zod/v4'\nimport { calendarMonthSchema, resolveJsOption } from './input-schemas.js'\nimport { mcpReportInputSchema } from './report-options.js'\nimport { toolError, toolSuccess } from './tool-result.js'\n\nconst technicalWatchInputSchema = z\n .strictObject({\n site: z.string().trim().min(1).max(2_048),\n startUrl: z.string().url().optional(),\n urls: z.array(z.string().url()).min(1).max(100).optional(),\n sitemaps: z.array(z.string().url()).min(1).max(20).optional(),\n properties: z\n .array(z.string().trim().min(1).max(2_048))\n .min(1)\n .max(1_000)\n .optional(),\n limit: z.number().int().min(1).max(250_000).optional(),\n refresh: z.boolean().optional(),\n js: z.boolean().optional(),\n languageCode: z.string().trim().min(1).max(35).optional(),\n dailyLimit: z.number().int().min(1).max(2_000).optional(),\n inspectLimit: z.number().int().min(1).max(100).optional(),\n maxUrls: z.number().int().min(1).max(250_000).optional(),\n recoverLinks: z.boolean().optional(),\n recoverDays: z.number().int().min(1).max(548).optional(),\n recoverLimit: z.number().int().min(1).max(100).optional(),\n recoverMinClicks: z.number().int().min(0).max(1_000_000_000).optional(),\n recoverMinImpressions: z\n .number()\n .int()\n .min(0)\n .max(1_000_000_000)\n .optional(),\n })\n .superRefine((input, context) => {\n const hasIndexInput = Boolean(input.urls?.length || input.sitemaps?.length)\n if (!input.startUrl && !hasIndexInput && input.recoverLinks === false) {\n context.addIssue({\n code: 'custom',\n path: ['recoverLinks'],\n message:\n 'Pass startUrl, urls, sitemaps, or enable link recovery for technical-watch.',\n })\n }\n })\n\nfunction workflowSuccess(result: WorkflowReport<unknown>) {\n return toolSuccess(\n result.summary,\n {\n ...result,\n presentation: workflowPresentation(result),\n },\n {\n markdown: renderWorkflowMarkdown(result),\n },\n )\n}\n\nexport function registerWorkflowTools(server: McpServer): void {\n server.registerTool(\n 'seo_workflow_diagnose_property',\n {\n description:\n 'Run the full agent workflow for property diagnosis and next actions',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'recentDays',\n 'limit',\n 'includeBrand',\n 'refresh',\n ]),\n },\n },\n async ({ site, days, recentDays, limit, includeBrand, refresh }) => {\n try {\n const result = await diagnosePropertyWorkflow({\n site,\n days,\n recentDays,\n limit,\n includeBrand,\n refresh,\n })\n return workflowSuccess(result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_workflow_monthly_report',\n {\n description: 'Run the monthly reporting workflow with next actions',\n inputSchema: {\n ...mcpReportInputSchema(['site', 'limit', 'includeBrand', 'refresh']),\n month: calendarMonthSchema.optional(),\n },\n },\n async ({ site, month, limit, includeBrand, refresh }) => {\n try {\n const result = await monthlyReportWorkflow({\n site,\n month,\n limit,\n includeBrand,\n refresh,\n })\n return workflowSuccess(result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_workflow_update_postmortem',\n {\n description:\n 'Run winner/loser postmortem analysis for recent Google update exposure',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'recentDays',\n 'limit',\n 'includeBrand',\n 'refresh',\n ]),\n knownConfounders: z.array(z.string()).optional(),\n includeChangeLog: z.boolean().optional(),\n },\n },\n async ({\n site,\n days,\n recentDays,\n limit,\n includeBrand,\n knownConfounders,\n includeChangeLog,\n refresh,\n }) => {\n try {\n const result = await updatePostmortemWorkflow({\n site,\n days,\n recentDays,\n limit,\n includeBrand,\n knownConfounders,\n includeChangeLog,\n refresh,\n })\n return workflowSuccess(result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_workflow_technical_watch',\n {\n description:\n 'Run scheduled-style crawl-diff and index-watch monitoring in one workflow',\n inputSchema: technicalWatchInputSchema,\n },\n async ({\n site,\n startUrl,\n urls,\n sitemaps,\n properties,\n limit,\n refresh,\n js,\n languageCode,\n dailyLimit,\n inspectLimit,\n maxUrls,\n recoverLinks,\n recoverDays,\n recoverLimit,\n recoverMinClicks,\n recoverMinImpressions,\n }) => {\n try {\n const result = await technicalWatchWorkflow({\n site,\n startUrl,\n urls,\n sitemaps,\n properties,\n limit,\n refresh,\n js: resolveJsOption(js, 'auto'),\n languageCode,\n dailyLimit,\n inspectLimit,\n maxUrls,\n recoverLinks,\n recoverDays,\n recoverLimit,\n recoverMinClicks,\n recoverMinImpressions,\n })\n return workflowSuccess(result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_workflow_refresh_priorities',\n {\n description:\n 'Rank decay, striking-distance, quick-win, cannibalisation, and diagnosis signals into an action queue',\n inputSchema: {\n ...mcpReportInputSchema([\n 'site',\n 'days',\n 'recentDays',\n 'limit',\n 'includeBrand',\n 'verifyContent',\n 'verifyLimit',\n 'refresh',\n ]),\n ga4PropertyId: z.string().optional(),\n },\n },\n async ({\n site,\n days,\n recentDays,\n limit,\n includeBrand,\n ga4PropertyId,\n verifyContent,\n verifyLimit,\n refresh,\n }) => {\n try {\n const result = await refreshPrioritiesWorkflow({\n site,\n days,\n recentDays,\n limit,\n includeBrand,\n ga4PropertyId,\n verifyContent,\n verifyLimit,\n refresh,\n })\n return workflowSuccess(result)\n } catch (error) {\n return toolError(error)\n }\n },\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport * as z from 'zod/v4'\nimport { registerAiOpportunityTools } from './ai-opportunity-tools.js'\nimport { registerCrawlerTools } from './crawler-tools.js'\nimport { registerDiagnosisTools } from './diagnosis-tools.js'\nimport { registerExperimentTools } from './experiment-tools.js'\nimport { registerMonitoringTools } from './monitoring-tools.js'\nimport { registerOpportunityTools } from './opportunity-tools.js'\nimport { registerPseoTools } from './pseo-tools.js'\nimport { getReportGuidance, REPORT_GUIDANCE } from './report-guidance.js'\nimport { registerReportTools } from './report-tools.js'\nimport type { ToolResult } from './tool-result.js'\nimport { registerWorkflowTools } from './workflow-tools.js'\n\nexport const REPORT_CATEGORIES = [\n 'ai-search',\n 'crawl',\n 'diagnosis',\n 'experiments',\n 'monitoring',\n 'opportunities',\n 'reporting',\n 'setup',\n 'workflows',\n] as const\n\nexport type ReportCategory = (typeof REPORT_CATEGORIES)[number]\n\ntype ReportHandler = (\n input: Record<string, unknown>,\n) => ToolResult | Promise<ToolResult>\n\ntype CapturedTool = {\n inputSchema?: z.ZodRawShape | z.ZodObject<z.ZodRawShape>\n handler: ReportHandler\n}\n\ntype ReportGroup = {\n category: ReportCategory\n names: readonly string[]\n register: (server: McpServer) => void\n}\n\nconst reportGroups: readonly ReportGroup[] = [\n {\n category: 'setup',\n register: registerDiagnosisTools,\n names: ['seo_doctor'],\n },\n {\n category: 'diagnosis',\n register: registerDiagnosisTools,\n names: [\n 'seo_segment_impact',\n 'seo_striking_distance',\n 'seo_traffic_anomaly',\n 'seo_update_correlate',\n ],\n },\n {\n category: 'opportunities',\n register: registerOpportunityTools,\n names: [\n 'seo_cannibal',\n 'seo_ctr_underperformers',\n 'seo_decaying',\n 'seo_internal_links',\n 'seo_query_cluster',\n 'seo_quick_wins',\n ],\n },\n {\n category: 'ai-search',\n register: registerAiOpportunityTools,\n names: [\n 'seo_ai_referrals',\n 'seo_community_intent',\n 'seo_content_optimization',\n 'seo_page_opportunities',\n 'seo_performance_audit',\n 'seo_to_ai_query',\n ],\n },\n {\n category: 'crawl',\n register: registerCrawlerTools,\n names: [\n 'seo_affected_urls',\n 'seo_ai_readiness',\n 'seo_audit_urls',\n 'seo_compare_crawl_reports',\n 'seo_crawl_site',\n 'seo_entity_readiness',\n 'seo_explain_issue',\n 'seo_geo_gaps',\n 'seo_get_crawl_report',\n 'seo_list_crawl_reports',\n 'seo_list_rules',\n 'seo_llms_txt_audit',\n 'seo_llms_txt_generate',\n 'seo_okf_build',\n 'seo_okf_validate',\n 'seo_top_fixes',\n ],\n },\n {\n category: 'monitoring',\n register: registerMonitoringTools,\n names: [\n 'seo_crawl_diff',\n 'seo_index_coverage',\n 'seo_index_coverage_plan',\n 'seo_index_monitor',\n 'seo_index_watch',\n 'seo_link_recover',\n 'seo_redirect_trace',\n ],\n },\n {\n category: 'reporting',\n register: registerReportTools,\n names: [\n 'seo_audit_page',\n 'seo_monthly_report',\n 'seo_report_narrative',\n 'seo_second_page',\n ],\n },\n {\n category: 'experiments',\n register: registerExperimentTools,\n names: ['seo_measure_change'],\n },\n {\n category: 'reporting',\n register: registerPseoTools,\n names: ['seo_pseo_audit'],\n },\n {\n category: 'workflows',\n register: registerWorkflowTools,\n names: [\n 'seo_workflow_diagnose_property',\n 'seo_workflow_monthly_report',\n 'seo_workflow_refresh_priorities',\n 'seo_workflow_technical_watch',\n 'seo_workflow_update_postmortem',\n ],\n },\n] as const\n\nexport type ReportSummary = {\n id: string\n category: ReportCategory\n name: string\n description: string\n}\n\nexport type ReportDefinition = ReportSummary & {\n useWhen: readonly string[]\n avoidWhen: readonly string[]\n outcome: string\n inputSchema: z.ZodObject<z.ZodRawShape>\n handler: ReportHandler\n}\n\nconst REPORT_ID_OVERRIDES = {\n cannibal: 'cannibalisation',\n decaying: 'decaying-pages',\n 'crawl-site': 'site-crawl',\n 'link-recover': 'link-recovery',\n 'llms-txt-generate': 'generate-llms-txt',\n 'query-cluster': 'query-clusters',\n 'report-narrative': 'narrative-report',\n 'to-ai-query': 'seo-to-ai-query',\n 'workflow-refresh-priorities': 'refresh-priorities',\n 'workflow-technical-watch': 'technical-watch',\n 'workflow-update-postmortem': 'update-postmortem',\n 'workflow-diagnose-property': 'search-performance-overview',\n 'workflow-monthly-report': 'monthly-action-plan',\n doctor: 'setup-check',\n 'update-correlate': 'update-correlation',\n 'compare-crawl-reports': 'compare-crawls',\n 'list-crawl-reports': 'crawl-history',\n 'list-rules': 'crawler-rules',\n 'get-crawl-report': 'crawl-report',\n 'explain-issue': 'explain-crawl-issue',\n} as const satisfies Record<string, string>\n\nfunction reportId(toolName: string): string {\n const internalId = toolName.replace(/^seo_/, '').replaceAll('_', '-')\n return (\n REPORT_ID_OVERRIDES[internalId as keyof typeof REPORT_ID_OVERRIDES] ??\n internalId\n )\n}\n\nfunction compareIds(a: ReportSummary, b: ReportSummary): number {\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0\n}\n\nfunction captureTools(register: (server: McpServer) => void) {\n const tools = new Map<string, CapturedTool>()\n register({\n registerTool(\n name: string,\n config: {\n description?: string\n inputSchema?: z.ZodRawShape | z.ZodObject<z.ZodRawShape>\n },\n handler: ReportHandler,\n ) {\n tools.set(name, { inputSchema: config.inputSchema, handler })\n },\n } as never)\n return tools\n}\n\nfunction normalizeInputSchema(\n inputSchema?: z.ZodRawShape | z.ZodObject<z.ZodRawShape>,\n): z.ZodObject<z.ZodRawShape> {\n return inputSchema instanceof z.ZodObject\n ? inputSchema\n : z.strictObject(inputSchema ?? {})\n}\n\nfunction createDefinitions(): ReportDefinition[] {\n const capturedByRegister = new Map<\n ReportGroup['register'],\n Map<string, CapturedTool>\n >()\n const definitions: ReportDefinition[] = []\n\n for (const group of reportGroups) {\n let captured = capturedByRegister.get(group.register)\n if (!captured) {\n captured = captureTools(group.register)\n capturedByRegister.set(group.register, captured)\n }\n\n for (const name of group.names) {\n const tool = captured.get(name)\n if (!tool) {\n throw new Error(`MCP report registry references missing tool ${name}.`)\n }\n const id = reportId(name)\n const guidance = getReportGuidance(id)\n if (!guidance) {\n throw new Error(`MCP report registry is missing guidance for ${id}.`)\n }\n definitions.push({\n id,\n category: group.category,\n ...guidance,\n inputSchema: normalizeInputSchema(tool.inputSchema),\n handler: tool.handler,\n })\n }\n }\n\n return definitions.sort(compareIds)\n}\n\nconst definitions = createDefinitions()\nconst definitionIds = new Set(definitions.map((report) => report.id))\nconst extraGuidanceIds = Object.keys(REPORT_GUIDANCE).filter(\n (id) => !definitionIds.has(id),\n)\nif (extraGuidanceIds.length > 0) {\n throw new Error(\n `MCP report guidance references unknown reports: ${extraGuidanceIds.join(', ')}.`,\n )\n}\nconst definitionsById = new Map(\n definitions.map((report) => [report.id, report]),\n)\n\nexport function listReportDefinitions(\n category?: ReportCategory,\n): ReportSummary[] {\n return definitions\n .filter((report) => !category || report.category === category)\n .map(({ id, name, description, category: reportCategory }) => ({\n id,\n category: reportCategory,\n name,\n description,\n }))\n}\n\nexport function getReportDefinition(id: string): ReportDefinition | undefined {\n return definitionsById.get(id)\n}\n","import { SeoError } from '@seo/core'\nimport * as z from 'zod/v4'\nimport {\n getReportDefinition,\n listReportDefinitions,\n type ReportCategory,\n type ReportSummary,\n} from './report-registry.js'\nimport { type ToolResult, toolError } from './tool-result.js'\n\nfunction validationMessage(error: z.ZodError): string {\n return error.issues\n .map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join('.') : 'input'\n return `${path}: ${issue.message}`\n })\n .join('; ')\n}\n\nexport function listReports(category?: ReportCategory): ReportSummary[] {\n return listReportDefinitions(category)\n}\n\nexport function describeReport(id: string) {\n const report = getReportDefinition(id)\n if (!report) throw new SeoError('INVALID_INPUT', `Unknown report: ${id}.`)\n return {\n id: report.id,\n category: report.category,\n name: report.name,\n description: report.description,\n useWhen: report.useWhen,\n avoidWhen: report.avoidWhen,\n outcome: report.outcome,\n inputSchema: z.toJSONSchema(report.inputSchema),\n }\n}\n\nexport async function executeReport(\n id: string,\n params: Record<string, unknown> = {},\n): Promise<ToolResult> {\n const report = getReportDefinition(id)\n if (!report) throw new SeoError('INVALID_INPUT', `Unknown report: ${id}.`)\n\n const parsed = report.inputSchema.safeParse(params)\n if (!parsed.success) {\n throw new SeoError(\n 'INVALID_INPUT',\n `Invalid parameters for ${id}: ${validationMessage(parsed.error)}`,\n )\n }\n\n return report.handler(parsed.data)\n}\n\nexport async function runReport(\n id: string,\n params: Record<string, unknown> = {},\n): Promise<ToolResult> {\n try {\n return await executeReport(id, params)\n } catch (error) {\n return toolError(error)\n }\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport * as z from 'zod/v4'\nimport { REPORT_CATEGORIES } from './report-registry.js'\nimport { describeReport, listReports, runReport } from './reports.js'\nimport { toolError, toolSuccess } from './tool-result.js'\n\nconst openOutputSchema = z.looseObject({})\n\nexport function registerDiscoveryTools(server: McpServer): void {\n server.registerTool(\n 'seo_list_reports',\n {\n description:\n 'List compact SEO report ids, names, and purposes, optionally by category',\n inputSchema: {\n category: z.enum(REPORT_CATEGORIES).optional(),\n },\n outputSchema: openOutputSchema,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n },\n async ({ category }) => {\n const reports = listReports(category)\n const categories = [...new Set(reports.map((report) => report.category))]\n return toolSuccess(\n `${reports.length} SEO reports available across ${categories.length} categories.`,\n { reports, categories },\n )\n },\n )\n\n server.registerTool(\n 'seo_describe_report',\n {\n description:\n 'Explain when to use one SEO report, what it returns, and which parameters it accepts',\n inputSchema: {\n id: z.string().trim().min(1).max(100),\n },\n outputSchema: openOutputSchema,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n },\n async ({ id }) => {\n try {\n const report = describeReport(id)\n return toolSuccess(`${report.id}: ${report.description}`, { report })\n } catch (error) {\n return toolError(error)\n }\n },\n )\n\n server.registerTool(\n 'seo_run_report',\n {\n description:\n 'Run one SEO report by id with parameters from seo_describe_report',\n inputSchema: {\n id: z.string().trim().min(1).max(100),\n params: z.record(z.string(), z.unknown()).optional(),\n },\n outputSchema: openOutputSchema,\n annotations: {\n destructiveHint: false,\n },\n },\n async ({ id, params }) => {\n return runReport(id, params)\n },\n )\n}\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { SEO_VERSION } from '@seo/core'\nimport { registerDiscoveryTools } from './discovery-tools.js'\n\nexport type { ReportGuidance } from './report-guidance.js'\nexport {\n REPORT_CATEGORIES,\n type ReportCategory,\n type ReportSummary,\n} from './report-registry.js'\nexport {\n describeReport,\n executeReport,\n listReports,\n runReport,\n} from './reports.js'\n\nexport function createServer(): McpServer {\n const server = new McpServer(\n {\n name: 'seo',\n version: SEO_VERSION,\n },\n { capabilities: { logging: {} } },\n )\n\n registerDiscoveryTools(server)\n\n return server\n}\n\nexport async function startMcpServer(\n opts: { test?: boolean } = {},\n): Promise<void> {\n const server = createServer()\n if (opts.test) {\n process.stdout.write('seo MCP server constructed successfully.\\n')\n return\n }\n\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAM,gBAAgB;CAClB,eAAe;EAAE,UAAU;EAAG,WAAW;CAAM;CAC/C,sBAAsB;EAAE,UAAU;EAAG,WAAW;CAAM;CACtD,cAAc;EAAE,UAAU;EAAG,WAAW;CAAM;CAC9C,eAAe;EAAE,UAAU;EAAG,WAAW;CAAM;CAC/C,mBAAmB;EAAE,UAAU;EAAG,WAAW;CAAM;CACnD,gBAAgB;EAAE,UAAU;EAAG,WAAW;CAAM;CAChD,eAAe;EAAE,UAAU;EAAG,WAAW;CAAM;CAC/C,+BAA+B;EAAE,UAAU;EAAG,WAAW;CAAK;CAC9D,oBAAoB;EAAE,UAAU;EAAG,WAAW;CAAM;CACpD,sBAAsB;EAAE,UAAU;EAAG,WAAW;CAAK;CACrD,cAAc;EAAE,UAAU;EAAG,WAAW;CAAK;AACjD;AACA,IAAa,WAAb,cAA8B,MAAM;CAChC;CACA;CACA;CACA,YAAY,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ACA;IACA;IACA,IAAI,gBAAgB,IAAI,MAAM;IAC9B,MAAM;KACJ,aAAa;KACb,aAAa;KACb,YAAY;IACd;GACF,CAAC;GACD,MAAM,OAAO,WAAW;GACxB,OAAO,YACL,GAAG,WAAW,OAAO,QAAQ,WAAW,eAAe,EAAE,gBAAgB,WAAW,OAAO,QAAQ,UAAU,UAAU,EAAE,IACzH,OACI;IAAE,QAAQ;IAAQ,cAAc,iBAAiB,MAAM;GAAE,IACzD,EAAE,QAAQ,kBAAkB,MAAM,EAAE,GACxC,OAAO,EAAE,UAAU,mBAAmB,MAAM,EAAE,IAAI,KAAA,CACpD;EACF,SAAS,OAAO;GACd,OAAO,UAAU,KAAK;EACxB;CACF,CACF;AACF;;;AChIA,MAAa,kBAAkB;CAC7B,iBAAiB;EACf,MAAM;EACN,aACE;EACF,SAAS,CACP,4DACA,iEACF;EACA,WAAW,CACT,6CACA,kEACF;EACA,SACE;CACJ;CACA,gBAAgB;EACd,MAAM;EACN,aACE;EACF,SAAS,CACP,iFACA,iFACF;EACA,WAAW,CACT,gEACA,+CACF;EACA,SAAS;CACX;CACA,gBAAgB;EACd,MAAM;EACN,aACE;EACF,SAAS,CACP,mDACA,6DACF;EACA,WAAW,CACT,oDACA,wEACF;EACA,SACE;CACJ;CACA,cAAc;EACZ,MAAM;EACN,aACE;EACF,SAAS,CACP,2DACA,4CACF;EACA,WAAW,CACT,oDACA,gDACF;EACA,SACE;CACJ;CACA,cAAc;EACZ,MAAM;EACN,aACE;EACF,SAAS,CACP,8CACA,wEACF;EACA,WAAW,CACT,mDACA,0CACF;EACA,SAAS;CACX;CACA,iBAAiB;EACf,MAAM;EACN,aACE;EACF,SAAS,CACP,8DACA,oEACF;EACA,WAAW,CACT,yDACA,qEACF;EACA,SACE;CACJ;CACA,oBAAoB;EAClB,MAAM;EACN,aACE;EACF,SAAS,CACP,4EACA,kEACF;EACA,WAAW,CACT,qEACA,2CACF;EACA,SACE;CACJ;CACA,kBAAkB;EAChB,MAAM;EACN,aACE;EACF,SAAS,CACP,gEACA,mEACF;EACA,WAAW,CACT,+DACA,gCACF;EACA,SACE;CACJ;CACA,wBAAwB;EACtB,MAAM;EACN,aACE;EACF,SAAS,CACP,4EACA,sEACF;EACA,WAAW,CACT,iDACA,gDACF;EACA,SACE;CACJ;CACA,cAAc;EACZ,MAAM;EACN,aACE;EACF,SAAS,CACP,4DACA,uDACF;EACA,WAAW,CACT,yCACA,mDACF;EACA,SACE;CACJ;CACA,iBAAiB;EACf,MAAM;EACN,aACE;EACF,SAAS,CACP,yDACA,0DACF;EACA,WAAW,CACT,sEACF;EACA,SACE;CACJ;CACA,gBAAgB;EACd,MAAM;EACN,aACE;EACF,SAAS,CACP,2DACA,sDACF;EACA,WAAW,CACT,mCACA,8CACF;EACA,SAAS;CACX;CACA,iBAAiB;EACf,MAAM;EACN,aACE;EACF,SAAS,CACP,sDACA,mEACF;EACA,WAAW,CAAC,gDAAgD;EAC5D,SAAS;CACX;CACA,uBAAuB;EACrB,MAAM;EACN,aACE;EACF,SAAS,CACP,8EACA,kEACF;EACA,WAAW,CACT,qCACA,6CACF;EACA,SACE;CACJ;CACA,kBAAkB;EAChB,MAAM;EACN,aACE;EACF,SAAS,CACP,+DACA,oDACF;EACA,WAAW,CACT,qDACA,4DACF;EACA,SACE;CACJ;CACA,oBAAoB;EAClB,MAAM;EACN,aACE;EACF,SAAS,CACP,uFACA,+DACF;EACA,WAAW,CACT,oDACA,yCACF;EACA,SACE;CACJ;CACA,uBAAuB;EACrB,MAAM;EACN,aACE;EACF,SAAS,CACP,oDACA,yEACF;EACA,WAAW,CACT,2CACA,gDACF;EACA,SACE;CACJ;CACA,qBAAqB;EACnB,MAAM;EACN,aACE;EACF,SAAS,CACP,sEACA,mEACF;EACA,WAAW,CACT,uEACA,uEACF;EACA,SACE;CACJ;CACA,YAAY;EACV,MAAM;EACN,aACE;EACF,SAAS,CACP,2EACA,iEACF;EACA,WAAW,CACT,2CACA,mDACF;EACA,SACE;CACJ;CACA,uBAAuB;EACrB,MAAM;EACN,aACE;EACF,SAAS,CACP,oEACA,gEACF;EACA,WAAW,CACT,6DACA,wDACF;EACA,SAAS;CACX;CACA,kBAAkB;EAChB,MAAM;EACN,aACE;EACF,SAAS,CACP,wHACA,sEACF;EACA,WAAW,CACT,sFACA,sDACF;EACA,SACE;CACJ;CACA,iBAAiB;EACf,MAAM;EACN,aACE;EACF,SAAS,CACP,oEACA,sDACF;EACA,WAAW,CACT,+DACA,qDACF;EACA,SACE;CACJ;CACA,eAAe;EACb,MAAM;EACN,aACE;EACF,SAAS,CACP,6DACA,mEACF;EACA,WAAW,CACT,qCACA,qDACF;EACA,SACE;CACJ;CACA,kBAAkB;EAChB,MAAM;EACN,aACE;EACF,SAAS,CACP,wEACA,wEACF;EACA,WAAW,CACT,uCACA,yEACF;EACA,SACE;CACJ;CACA,iBAAiB;EACf,MAAM;EACN,aACE;EACF,SAAS,CACP,kEACA,0EACF;EACA,WAAW,CACT,+BACA,uDACF;EACA,SACE;CACJ;CACA,kBAAkB;EAChB,MAAM;EACN,aACE;EACF,SAAS,CACP,0DACA,uEACF;EACA,WAAW,CACT,+DACA,sEACF;EACA,SACE;CACJ;CACA,kBAAkB;EAChB,MAAM;EACN,aACE;EACF,SAAS,CACP,6DACA,4DACF;EACA,WAAW,CACT,mCACA,qDACF;EACA,SACE;CACJ;CACA,uBAAuB;EACrB,MAAM;EACN,aACE;EACF,SAAS,CACP,8DACA,mDACF;EACA,WAAW,CACT,iEACA,gCACF;EACA,SAAS;CACX;CACA,kBAAkB;EAChB,MAAM;EACN,aACE;EACF,SAAS,CACP,sEACA,mDACF;EACA,WAAW,CACT,2DACA,2CACF;EACA,SACE;CACJ;CACA,oBAAoB;EAClB,MAAM;EACN,aACE;EACF,SAAS,CACP,mEACA,uEACF;EACA,WAAW,CACT,2CACA,kDACF;EACA,SACE;CACJ;CACA,aAAa;EACX,MAAM;EACN,aACE;EACF,SAAS,CACP,uEACA,iEACF;EACA,WAAW,CACT,2DACA,4CACF;EACA,SAAS;CACX;CACA,gBAAgB;EACd,MAAM;EACN,aACE;EACF,SAAS,CACP,2DACA,qDACF;EACA,WAAW,CAAC,gDAAgD;EAC5D,SAAS;CACX;CACA,sBAAsB;EACpB,MAAM;EACN,aACE;EACF,SAAS,CACP,qEACA,sDACF;EACA,WAAW,CACT,+CACA,qCACF;EACA,SACE;CACJ;CACA,qBAAqB;EACnB,MAAM;EACN,aACE;EACF,SAAS,CACP,2DACA,gEACF;EACA,WAAW,CACT,kEACA,oDACF;EACA,SACE;CACJ;CACA,cAAc;EACZ,MAAM;EACN,aACE;EACF,SAAS,CACP,0DACA,uEACF;EACA,WAAW,CACT,kEACA,yDACF;EACA,SACE;CACJ;CACA,kBAAkB;EAChB,MAAM;EACN,aACE;EACF,SAAS,CACP,uDACA,0DACF;EACA,WAAW,CACT,yEACA,wDACF;EACA,SAAS;CACX;CACA,cAAc;EACZ,MAAM;EACN,aACE;EACF,SAAS,CACP,iEACA,kEACF;EACA,WAAW,CACT,mCACA,4DACF;EACA,SACE;CACJ;CACA,kBAAkB;EAChB,MAAM;EACN,aACE;EACF,SAAS,CACP,yDACA,6DACF;EACA,WAAW,CACT,6DACA,+CACF;EACA,SAAS;CACX;CACA,sBAAsB;EACpB,MAAM;EACN,aACE;EACF,SAAS,CACP,4DACA,8DACF;EACA,WAAW,CACT,oCACA,qDACF;EACA,SACE;CACJ;CACA,+BAA+B;EAC7B,MAAM;EACN,aACE;EACF,SAAS,CACP,uFACA,6EACF;EACA,WAAW,CACT,qEACA,6DACF;EACA,SACE;CACJ;CACA,eAAe;EACb,MAAM;EACN,aACE;EACF,SAAS,CACP,yEACA,2DACF;EACA,WAAW,CACT,sDACA,8DACF;EACA,SACE;CACJ;CACA,kBAAkB;EAChB,MAAM;EACN,aACE;EACF,SAAS,CACP,qFACA,iEACF;EACA,WAAW,CACT,iDACA,kEACF;EACA,SACE;CACJ;CACA,mBAAmB;EACjB,MAAM;EACN,aACE;EACF,SAAS,CACP,2EACA,oEACF;EACA,WAAW,CACT,gDACA,2DACF;EACA,SACE;CACJ;CACA,eAAe;EACb,MAAM;EACN,aACE;EACF,SAAS,CACP,gDACA,wEACF;EACA,WAAW,CAAC,kDAAkD;EAC9D,SAAS;CACX;CACA,cAAc;EACZ,MAAM;EACN,aACE;EACF,SAAS,CACP,8DACA,8DACF;EACA,WAAW,CACT,wDACA,mEACF;EACA,SACE;CACJ;CACA,qBAAqB;EACnB,MAAM;EACN,aACE;EACF,SAAS,CACP,sDACA,iEACF;EACA,WAAW,CACT,6DACA,4CACF;EACA,SACE;CACJ;CACA,mBAAmB;EACjB,MAAM;EACN,aACE;EACF,SAAS,CACP,6DACA,qEACF;EACA,WAAW,CACT,iEACA,+DACF;EACA,SACE;CACJ;CACA,aAAa;EACX,MAAM;EACN,aACE;EACF,SAAS,CACP,yDACA,sEACF;EACA,WAAW,CACT,6CACA,qDACF;EACA,SACE;CACJ;CACA,mBAAmB;EACjB,MAAM;EACN,aACE;EACF,SAAS,CACP,yDACA,4EACF;EACA,WAAW,CACT,sDACA,0DACF;EACA,SACE;CACJ;CACA,sBAAsB;EACpB,MAAM;EACN,aACE;EACF,SAAS,CACP,gEACA,sEACF;EACA,WAAW,CACT,qDACA,qDACF;EACA,SACE;CACJ;CACA,qBAAqB;EACnB,MAAM;EACN,aACE;EACF,SAAS,CACP,6DACA,+DACF;EACA,WAAW,CACT,gEACA,4EACF;EACA,SACE;CACJ;AACF;AAEA,SAAgB,kBAAkB,IAAwC;CACxE,OAAQ,gBAAmD;AAC7D;;;AClvBA,SAAgB,sBAAsB,QAAyB;CAC7D,OAAO,aACL,kBACA;EACE,aAAa;EACb,aAAa;GACX,KAAKC,IAAE,OAAO,CAAC,CAAC,IAAI;GACpB,MAAMA,IAAE,OAAO,CAAC,CAAC,SAAS;GAC1B,IAAIA,IAAE,QAAQ,CAAC,CAAC,SAAS;GACzB,SAASA,IAAE,QAAQ,CAAC,CAAC,SAAS;EAChC;CACF,GACA,OAAO,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AAC,SAAS;GAC/C,kBAAkBA,IAAE,QAAQ,CAAC,CAAC,SAAS;EACzC;CACF,GACA,OAAO,EACL,MACA,MACA,YACA,OACA,cACA,kBACA,kBACA,cACI;EACJ,IAAI;GAWF,OAAO,gBAAgB,MAVF,yBAAyB;IAC5C;IACA;IACA;IACA;IACA;IACA;IACA;IACA;GACF,CAAC,CAC4B;EAC/B,SAAS,OAAO;GACd,OAAO,UAAU,KAAK;EACxB;CACF,CACF;CAEA,OAAO,aACL,gCACA;EACE,aACE;EACF,aAAa;CACf,GACA,OAAO,EACL,MACA,UACA,MACA,UACA,YACA,OACA,SACA,IACA,cACA,YACA,cACA,SACA,cACA,aACA,cACA,kBACA,4BACI;EACJ,IAAI;GAoBF,OAAO,gBAAgB,MAnBF,uBAAuB;IAC1C;IACA;IACA;IACA;IACA;IACA;IACA;IACA,IAAI,gBAAgB,IAAI,MAAM;IAC9B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;GACF,CAAC,CAC4B;EAC/B,SAAS,OAAO;GACd,OAAO,UAAU,KAAK;EACxB;CACF,CACF;CAEA,OAAO,aACL,mCACA;EACE,aACE;EACF,aAAa;GACX,GAAG,qBAAqB;IACtB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;GACF,CAAC;GACD,eAAeA,IAAE,OAAO,CAAC,CAAC,SAAS;EACrC;CACF,GACA,OAAO,EACL,MACA,MACA,YACA,OACA,cACA,eACA,eACA,aACA,cACI;EACJ,IAAI;GAYF,OAAO,gBAAgB,MAXF,0BAA0B;IAC7C;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;GACF,CAAC,CAC4B;EAC/B,SAAS,OAAO;GACd,OAAO,UAAU,KAAK;EACxB;CACF,CACF;AACF;;;ACtQA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAmBA,MAAM,eAAuC;CAC3C;EACE,UAAU;EACV,UAAU;EACV,OAAO,CAAC,YAAY;CACtB;CACA;EACE,UAAU;EACV,UAAU;EACV,OAAO;GACL;GACA;GACA;GACA;EACF;CACF;CACA;EACE,UAAU;EACV,UAAU;EACV,OAAO;GACL;GACA;GACA;GACA;GACA;GACA;EACF;CACF;CACA;EACE,UAAU;EACV,UAAU;EACV,OAAO;GACL;GACA;GACA;GACA;GACA;GACA;EACF;CACF;CACA;EACE,UAAU;EACV,UAAU;EACV,OAAO;GACL;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF;CACF;CACA;EACE,UAAU;EACV,UAAU;EACV,OAAO;GACL;GACA;GACA;GACA;GACA;GACA;GACA;EACF;CACF;CACA;EACE,UAAU;EACV,UAAU;EACV,OAAO;GACL;GACA;GACA;GACA;EACF;CACF;CACA;EACE,UAAU;EACV,UAAU;EACV,OAAO,CAAC,oBAAoB;CAC9B;CACA;EACE,UAAU;EACV,UAAU;EACV,OAAO,CAAC,gBAAgB;CAC1B;CACA;EACE,UAAU;EACV,UAAU;EACV,OAAO;GACL;GACA;GACA;GACA;GACA;EACF;CACF;AACF;AAiBA,MAAM,sBAAsB;CAC1B,UAAU;CACV,UAAU;CACV,cAAc;CACd,gBAAgB;CAChB,qBAAqB;CACrB,iBAAiB;CACjB,oBAAoB;CACpB,eAAe;CACf,+BAA+B;CAC/B,4BAA4B;CAC5B,8BAA8B;CAC9B,8BAA8B;CAC9B,2BAA2B;CAC3B,QAAQ;CACR,oBAAoB;CACpB,yBAAyB;CACzB,sBAAsB;CACtB,cAAc;CACd,oBAAoB;CACpB,iBAAiB;AACnB;AAEA,SAAS,SAAS,UAA0B;CAC1C,MAAM,aAAa,SAAS,QAAQ,SAAS,EAAE,CAAC,CAAC,WAAW,KAAK,GAAG;CACpE,OACE,oBAAoB,eACpB;AAEJ;AAEA,SAAS,WAAW,GAAkB,GAA0B;CAC9D,OAAO,EAAE,KAAK,EAAE,KAAK,KAAK,EAAE,KAAK,EAAE,KAAK,IAAI;AAC9C;AAEA,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