sanity-plugin-seo-copilot 0.2.14 → 0.2.16

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 (40) hide show
  1. package/README.md +63 -50
  2. package/dist/index.js +868 -797
  3. package/dist/index.mjs +791 -720
  4. package/package.json +9 -8
  5. package/dist/index.js.map +0 -1
  6. package/dist/index.mjs.map +0 -1
  7. package/sanity.json +0 -3
  8. package/src/components/ChatPanel.tsx +0 -311
  9. package/src/components/ConfigContext.tsx +0 -22
  10. package/src/components/FeedbackButton.tsx +0 -218
  11. package/src/components/KeywordBadge.tsx +0 -50
  12. package/src/components/KeywordPanel.tsx +0 -1233
  13. package/src/components/OnboardingPopup.tsx +0 -108
  14. package/src/components/PlacementIndicators.tsx +0 -80
  15. package/src/components/ReportProblemButton.tsx +0 -212
  16. package/src/components/SEOCopilotPanel.tsx +0 -1287
  17. package/src/components/ScoreDonut.tsx +0 -158
  18. package/src/components/SeedKeywordInput.tsx +0 -128
  19. package/src/components/ShimmerLoader.tsx +0 -123
  20. package/src/components/TabBar.tsx +0 -373
  21. package/src/components/styles.ts +0 -158
  22. package/src/components/tabs/AEOTab.tsx +0 -585
  23. package/src/components/tabs/LinkingTab.tsx +0 -446
  24. package/src/components/tabs/MetaTab.tsx +0 -431
  25. package/src/components/tabs/SummaryTab.tsx +0 -405
  26. package/src/components/tabs/TechnicalTab.tsx +0 -933
  27. package/src/hooks/useDocumentContent.ts +0 -48
  28. package/src/hooks/useKeywordAnalysis.ts +0 -292
  29. package/src/hooks/useSEOChat.ts +0 -254
  30. package/src/index.ts +0 -16
  31. package/src/inspector.ts +0 -58
  32. package/src/lib/api.ts +0 -260
  33. package/src/lib/documentExtract.ts +0 -422
  34. package/src/lib/geoAnalysis.ts +0 -122
  35. package/src/lib/persistence.ts +0 -69
  36. package/src/lib/scoring.ts +0 -197
  37. package/src/lib/summary.ts +0 -645
  38. package/src/lib/types.ts +0 -212
  39. package/src/lib/utils.ts +0 -35
  40. package/v2-incompatible.js +0 -10
@@ -1,122 +0,0 @@
1
- // Client-side Generative Engine Optimization (GEO) analysis.
2
- // 2026 research: AI engines (ChatGPT, Perplexity, Gemini, Google AI Overviews)
3
- // preferentially cite content with high fact-density (verifiable stats every
4
- // 150-200 words) and direct-answer blocks (40-60 word answers right after
5
- // question / topic headings - the RAG extraction pattern).
6
-
7
- const FACT_PATTERN =
8
- /\d+(?:\.\d+)?\s*%|\b\d{1,3}(?:,\d{3})+\b|\bn\s*=\s*\d+\b|\bp\s*[<=]\s*0?\.\d+\b|\b\d+(?:\.\d+)?\s*(?:patients|participants|subjects|cases|deaths|adverse events|mg|mcg|hours|days|weeks|months|years|fold|x)\b|\b(?:NEJM|JAMA|FDA|EMA|CDC|WHO|NIH|ACC|ASCO|ASH|ESMO|AHA|ACS)\b|\bet al\.?\b|\b(?:phase|stage)\s+(?:I{1,3}V?|1|2|3|4)\b/i;
9
-
10
- export interface HeadingAudit {
11
- heading: string;
12
- words: number;
13
- status: "good" | "too-short" | "too-long" | "missing-body";
14
- }
15
-
16
- export interface FactDensityResult {
17
- totalWords: number;
18
- factCount: number;
19
- factsPerThousandWords: number;
20
- driftPassages: number;
21
- status: "strong" | "moderate" | "weak";
22
- }
23
-
24
- export interface GEOAnalysis {
25
- headingAudit: HeadingAudit[];
26
- factDensity: FactDensityResult;
27
- }
28
-
29
- function wordCount(s: string): number {
30
- return s.trim().split(/\s+/).filter(Boolean).length;
31
- }
32
-
33
- export function analyzeHeadings(text: string, headings: string[]): HeadingAudit[] {
34
- if (!text || headings.length === 0) return [];
35
- // Only QUESTION headings (those ending in "?") get a short-answer audit: the
36
- // 40-60 word direct answer after a question is the chunk AI engines extract. A
37
- // section/list heading ("Trials to Watch") - or a declarative one that merely
38
- // starts with "Is"/"Are" ("Is This the Future of Oncology") - is not a question
39
- // and shouldn't be audited. Requiring "?" also matches the AEO score's counter.
40
- const isQuestion = (h: string) => /\?\s*$/.test(h.trim());
41
- const questionHeadings = headings.filter(isQuestion);
42
- if (questionHeadings.length === 0) return [];
43
- const headingSet = new Set(headings.map((h) => h.trim().toLowerCase()));
44
- const lower = text.toLowerCase();
45
- return questionHeadings.map((heading) => {
46
- const needle = heading.trim().toLowerCase();
47
- const idx = lower.indexOf(needle);
48
- if (idx === -1) {
49
- return { heading, words: 0, status: "missing-body" as const };
50
- }
51
- // Walk the lines after the heading: collect non-empty lines that aren't themselves
52
- // another heading. Stop at the next heading (the next section starts).
53
- // Portable Text blocks are joined with single \n by useDocumentContent.extractText,
54
- // so the "answer paragraph" is the next non-empty, non-heading line(s).
55
- const after = text.slice(idx + heading.length);
56
- const lines = after.split(/\n/);
57
- const answerParts: string[] = [];
58
- for (const raw of lines) {
59
- const t = raw.trim();
60
- if (!t) continue;
61
- if (headingSet.has(t.toLowerCase())) break;
62
- answerParts.push(t);
63
- // Cap collection so we don't walk an entire article if no next heading exists
64
- const sofar = answerParts.join(" ");
65
- if (sofar.split(/\s+/).length > 120) break;
66
- }
67
- const words = wordCount(answerParts.join(" "));
68
- if (words === 0) return { heading, words: 0, status: "missing-body" as const };
69
- if (words < 30) return { heading, words, status: "too-short" as const };
70
- if (words > 70) return { heading, words, status: "too-long" as const };
71
- return { heading, words, status: "good" as const };
72
- });
73
- }
74
-
75
- export function analyzeFactDensity(text: string): FactDensityResult {
76
- const total = wordCount(text);
77
- if (total === 0) {
78
- return { totalWords: 0, factCount: 0, factsPerThousandWords: 0, driftPassages: 0, status: "weak" };
79
- }
80
- // Count facts
81
- const matches = text.match(new RegExp(FACT_PATTERN.source, "gi")) || [];
82
- const factCount = matches.length;
83
- const factsPer1000 = Math.round((factCount / total) * 1000);
84
-
85
- // Drift passages: sliding 200-word windows with zero facts
86
- // NB: no lookbehind regex here - `(?<=...)` throws on Safari < 16.4 and would
87
- // crash the whole AEO tab. Split on sentence-ending punctuation + whitespace.
88
- const sentences = text.split(/[.!?]+\s+/).filter((s) => s.trim().length > 0);
89
- let drift = 0;
90
- let runWords = 0;
91
- let runHasFact = false;
92
- for (const s of sentences) {
93
- const w = wordCount(s);
94
- if (new RegExp(FACT_PATTERN.source, "i").test(s)) runHasFact = true;
95
- runWords += w;
96
- if (runWords >= 200) {
97
- if (!runHasFact) drift += 1;
98
- runWords = 0;
99
- runHasFact = false;
100
- }
101
- }
102
-
103
- // 2026 GEO research (Princeton, Averi citation benchmarks): the center of the
104
- // recommended fact-density range is ~8 stats per 1,000 words (1 every ~125
105
- // words). Anything below ~4/1k consistently under-cites in AI Overviews.
106
- // Status is density-only. Drift passages (long stretches with no stat) are a
107
- // SEPARATE signal surfaced on their own - they shouldn't demote an article
108
- // that is otherwise densely-cited just because it has one narrative paragraph.
109
- let status: FactDensityResult["status"];
110
- if (factsPer1000 >= 8) status = "strong";
111
- else if (factsPer1000 >= 4) status = "moderate";
112
- else status = "weak";
113
-
114
- return { totalWords: total, factCount, factsPerThousandWords: factsPer1000, driftPassages: drift, status };
115
- }
116
-
117
- export function analyzeGEO(text: string, headings: string[]): GEOAnalysis {
118
- return {
119
- headingAudit: analyzeHeadings(text, headings),
120
- factDensity: analyzeFactDensity(text),
121
- };
122
- }
@@ -1,69 +0,0 @@
1
- import { useState, useCallback, useEffect, useRef } from "react";
2
-
3
- // localStorage so state survives:
4
- // - dock/undock toggle (PanelContent remount)
5
- // - tab switches (defensive, even though display:none preserves)
6
- // - full page reload / browser close
7
- // - Vite HMR rebuilds during local dev
8
-
9
- const LS: Storage | null = typeof window !== "undefined" ? window.localStorage : null;
10
-
11
- export function loadLocal<T>(key: string, fallback: T): T {
12
- try {
13
- if (!LS) return fallback;
14
- const raw = LS.getItem(key);
15
- if (raw === null) return fallback;
16
- return JSON.parse(raw) as T;
17
- } catch {
18
- return fallback;
19
- }
20
- }
21
-
22
- export function saveLocal(key: string, value: unknown): void {
23
- try {
24
- if (!LS) return;
25
- LS.setItem(key, JSON.stringify(value));
26
- } catch {
27
- // localStorage may throw on quota / private mode - silent fallback to in-memory only
28
- }
29
- }
30
-
31
- export function removeLocal(key: string): void {
32
- try {
33
- if (!LS) return;
34
- LS.removeItem(key);
35
- } catch {
36
- /* silent */
37
- }
38
- }
39
-
40
- /**
41
- * useState that persists to localStorage. Value is reloaded when key changes
42
- * (e.g., when documentId changes for per-doc keys).
43
- */
44
- export function usePersistentState<T>(
45
- key: string,
46
- initial: T
47
- ): [T, (v: T | ((prev: T) => T)) => void] {
48
- const [val, setVal] = useState<T>(() => loadLocal(key, initial));
49
- // Track which key we currently hold so we don't reload on first render.
50
- const heldKey = useRef(key);
51
- useEffect(() => {
52
- if (heldKey.current === key) return;
53
- heldKey.current = key;
54
- setVal(loadLocal(key, initial));
55
- // eslint-disable-next-line react-hooks/exhaustive-deps
56
- }, [key]);
57
-
58
- const set = useCallback(
59
- (v: T | ((prev: T) => T)) => {
60
- setVal((prev) => {
61
- const next = typeof v === "function" ? (v as (p: T) => T)(prev) : v;
62
- saveLocal(key, next);
63
- return next;
64
- });
65
- },
66
- [key]
67
- );
68
- return [val, set];
69
- }
@@ -1,197 +0,0 @@
1
- import type { SEOAnalysis, DocumentFields } from "./types";
2
-
3
- export interface ScoreComponent {
4
- label: string;
5
- points: number;
6
- max: number;
7
- detail: string;
8
- }
9
-
10
- export interface ContentScore {
11
- total: number;
12
- components: ScoreComponent[];
13
- }
14
-
15
- // Count whole-word / whole-phrase occurrences, anchored on word boundaries, so a
16
- // short token like "as" or "cm" can't match inside "phase" or "cmv". Safari-safe:
17
- // uses \b only (no lookbehind). The needle is regex-escaped.
18
- function countWholeMatches(haystack: string, needle: string): number {
19
- if (!needle) return 0;
20
- const esc = needle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
21
- const m = haystack.match(new RegExp(`\\b${esc}\\b`, "g"));
22
- return m ? m.length : 0;
23
- }
24
-
25
- /**
26
- * Client-side content score (0-100) with per-component breakdown.
27
- * Mirrors backend scoring.ts.
28
- */
29
- export function calculateContentScoreDetailed(content: string, analysis: SEOAnalysis, documentFields?: DocumentFields): ContentScore {
30
- if (!content || !analysis) {
31
- return { total: 0, components: [] };
32
- }
33
- const lowerContent = content.toLowerCase();
34
- const words = content.split(/\s+/).filter(Boolean).length;
35
- const components: ScoreComponent[] = [];
36
-
37
- // 1. Primary keyword (up to 25)
38
- const primaryTerm = (analysis.primaryKeyword?.term || "").toLowerCase();
39
- if (primaryTerm) {
40
- // A multi-word primary like "acoramidis ATTR-CM" almost never appears as an
41
- // adjacent phrase, but if every token is in the body the keyword IS present.
42
- // Try the exact phrase first; otherwise fall back to token co-occurrence (all
43
- // tokens present) and use the rarest token as the concept's mention count.
44
- // (This mirrors containsKeywordTokens() used by the Meta + Summary audits.)
45
- const tokens = primaryTerm.split(/\s+/).filter((t) => t.length > 1);
46
- const phraseCount = countWholeMatches(lowerContent, primaryTerm);
47
- let occurrences = phraseCount;
48
- let viaTokens = false;
49
- if (phraseCount === 0 && tokens.length > 0) {
50
- const counts = tokens.map((t) => countWholeMatches(lowerContent, t));
51
- if (counts.every((c) => c > 0)) {
52
- occurrences = Math.min(...counts);
53
- viaTokens = true;
54
- }
55
- }
56
- const primaryWordCount = Math.max(1, primaryTerm.split(/\s+/).filter(Boolean).length);
57
- let pts = 0;
58
- let detail: string;
59
- if (occurrences === 0) {
60
- detail = `Primary keyword "${primaryTerm}" not found in content`;
61
- } else {
62
- pts += 12;
63
- // Exact phrase: an N-word phrase appearing M times occupies M*N keyword-words.
64
- // Token co-occurrence: tokens are spread through the body, so count each once.
65
- const density = words > 0
66
- ? ((viaTokens ? occurrences : occurrences * primaryWordCount) / words) * 100
67
- : 0;
68
- if (density >= 0.5 && density <= 2.5) {
69
- pts += 13;
70
- detail = `Primary keyword present, density ${density.toFixed(2)}% (ideal range)`;
71
- } else if (density < 0.5) {
72
- pts += 7;
73
- detail = `Primary keyword present but density only ${density.toFixed(2)}% - aim for 0.5-2.5%`;
74
- } else if (viaTokens && density <= 6) {
75
- // Tokens spread through the body is topical depth, not keyword stuffing.
76
- pts += 11;
77
- detail = `Primary keyword strongly represented (${density.toFixed(2)}%)`;
78
- } else {
79
- pts += 4;
80
- detail = `Primary keyword over-used at ${density.toFixed(2)}% density - reduce to 0.5-2.5%`;
81
- }
82
- }
83
- components.push({ label: "Primary keyword usage", points: pts, max: 25, detail });
84
- } else {
85
- components.push({ label: "Primary keyword usage", points: 0, max: 25, detail: "No primary keyword identified yet" });
86
- }
87
-
88
- // 2. Supporting keyword coverage (up to 25)
89
- const supportingKws = analysis.supportingKeywords || [];
90
- if (supportingKws.length > 0) {
91
- const inContentCount = supportingKws.filter((kw) => kw != null && typeof kw.term === "string" && lowerContent.includes(kw.term.toLowerCase())).length;
92
- const coverageRatio = inContentCount / supportingKws.length;
93
- const pts = Math.round(coverageRatio * 25);
94
- components.push({
95
- label: "Supporting keyword coverage",
96
- points: pts,
97
- max: 25,
98
- detail: `${inContentCount} of ${supportingKws.length} supporting keywords present (${Math.round(coverageRatio * 100)}%)`,
99
- });
100
- } else {
101
- components.push({ label: "Supporting keyword coverage", points: 0, max: 25, detail: "No supporting keywords yet" });
102
- }
103
-
104
- // 3. Word count (up to 15)
105
- // 450 is the body-text floor. 1,500+ is the competitive target for HCP clinical articles.
106
- let wcPts = 0;
107
- let wcDetail: string;
108
- if (words >= 1500) {
109
- wcPts = 15;
110
- wcDetail = `${words} words - strong length for clinical content`;
111
- } else if (words >= 450) {
112
- wcPts = 11;
113
- wcDetail = `${words} words - above the 450 floor; 1,500+ is the clinical target`;
114
- } else if (words >= 200) {
115
- wcPts = 5;
116
- wcDetail = `${words} words - below the 450-word floor`;
117
- } else {
118
- wcDetail = `${words} words - start writing`;
119
- }
120
- components.push({ label: "Word count", points: wcPts, max: 15, detail: wcDetail });
121
-
122
- // 4. Heading structure (up to 10)
123
- // Prefer the structured heading data the plugin extracts from Portable Text.
124
- // The plain `content` string has no markup, so regexing it for #/<h3> always
125
- // misses real headings - fall back to the regex only for plain-text callers.
126
- let hasH1orTitle: boolean;
127
- let hasSubheadings: boolean;
128
- if (documentFields) {
129
- hasH1orTitle = !!(documentFields.title && documentFields.title.trim());
130
- const det = documentFields.headingsDetailed;
131
- // Any H2+ heading counts as a subheading. Fall back to the flat heading list
132
- // when the detailed list is absent OR empty, so a real outline is never missed.
133
- const detHasSub = Array.isArray(det) && det.some((h) => h.level >= 2);
134
- hasSubheadings = detHasSub || (documentFields.headings?.length || 0) > 0;
135
- } else {
136
- hasH1orTitle = /^#\s|<h1/im.test(content);
137
- hasSubheadings = /^##\s|^###\s|<h2|<h3/im.test(content);
138
- }
139
- const structurePts = (hasH1orTitle ? 5 : 0) + (hasSubheadings ? 5 : 0);
140
- const structureDetail = !hasH1orTitle && !hasSubheadings
141
- ? "No title or subheadings detected"
142
- : !hasSubheadings
143
- ? "Has a title but no H2/H3 subheadings - add section headings"
144
- : !hasH1orTitle
145
- ? "Has subheadings but no title"
146
- : "Title and subheadings present";
147
- components.push({ label: "Heading structure", points: structurePts, max: 10, detail: structureDetail });
148
-
149
- // 5. Missing keyword coverage (up to 15)
150
- const missingCount = (analysis.missingKeywords || []).length;
151
- let mPts = 0;
152
- let mDetail: string;
153
- if (missingCount === 0) {
154
- mPts = 15;
155
- mDetail = "No missing keywords flagged";
156
- } else if (missingCount <= 2) {
157
- mPts = 10;
158
- mDetail = `${missingCount} suggested keywords missing - quick add`;
159
- } else if (missingCount <= 4) {
160
- mPts = 5;
161
- mDetail = `${missingCount} suggested keywords missing`;
162
- } else {
163
- mDetail = `${missingCount} suggested keywords missing - significant gaps`;
164
- }
165
- components.push({ label: "Missing keyword gap", points: mPts, max: 15, detail: mDetail });
166
-
167
- // 6. AEO signals (up to 10) - question-format headings that Google answer
168
- // features and AI engines surface directly. (FAQ scoring removed May 2026 after
169
- // Google sunset FAQ rich results - question headings are the modern equivalent.)
170
- // Detect from the structured heading list (plain `content` has no heading
171
- // markup to regex). Single clean tier: 0 / 4 / 7 / 10 for 0 / 1 / 2 / 3+.
172
- let qCount: number;
173
- if (documentFields) {
174
- qCount = (documentFields.headings || []).filter((h) => h.trim().endsWith("?")).length;
175
- } else {
176
- qCount = (content.match(/^#{1,6}\s+.*\?$/gm) || []).length + (content.match(/<h[1-6][^>]*>.*\?<\/h[1-6]>/gi) || []).length;
177
- }
178
- let aeoPts = 0;
179
- if (qCount >= 3) aeoPts = 10;
180
- else if (qCount === 2) aeoPts = 7;
181
- else if (qCount === 1) aeoPts = 4;
182
- const aeoDetail =
183
- qCount === 0
184
- ? "No question-style headings - AI answer engines favor them"
185
- : `${qCount} question heading${qCount === 1 ? "" : "s"}`;
186
- components.push({ label: "AEO signals", points: aeoPts, max: 10, detail: aeoDetail });
187
-
188
- const total = components.reduce((sum, c) => sum + c.points, 0);
189
- return { total: Math.min(100, Math.max(0, total)), components };
190
- }
191
-
192
- /**
193
- * Backward-compatible: returns just the numeric score.
194
- */
195
- export function calculateContentScore(content: string, analysis: SEOAnalysis): number {
196
- return calculateContentScoreDetailed(content, analysis).total;
197
- }