sanity-plugin-seo-copilot 0.2.7 → 0.2.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +244 -137
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +266 -159
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -2
- package/src/components/ChatPanel.tsx +5 -3
- package/src/components/FeedbackButton.tsx +6 -1
- package/src/components/KeywordPanel.tsx +20 -10
- package/src/components/OnboardingPopup.tsx +108 -108
- package/src/components/SEOCopilotPanel.tsx +60 -7
- package/src/components/ShimmerLoader.tsx +4 -0
- package/src/components/TabBar.tsx +3 -0
- package/src/components/tabs/AEOTab.tsx +4 -2
- package/src/components/tabs/LinkingTab.tsx +15 -11
- package/src/components/tabs/MetaTab.tsx +2 -11
- package/src/components/tabs/SummaryTab.tsx +1 -1
- package/src/components/tabs/TechnicalTab.tsx +12 -33
- package/src/hooks/useKeywordAnalysis.ts +68 -52
- package/src/hooks/useSEOChat.ts +5 -1
- package/src/inspector.ts +58 -51
- package/src/lib/api.ts +9 -7
- package/src/lib/documentExtract.ts +8 -8
- package/src/lib/scoring.ts +2 -2
- package/src/lib/summary.ts +24 -33
- package/src/lib/utils.ts +35 -0
|
@@ -3,6 +3,7 @@ import { FeedbackButton } from "../FeedbackButton";
|
|
|
3
3
|
import { ScoreDonut, ScoreDonutLegend } from "../ScoreDonut";
|
|
4
4
|
import { MJH_BLUE } from "../styles";
|
|
5
5
|
import type { SEOAnalysis, LinkingSuggestion } from "../../lib/types";
|
|
6
|
+
import { KNOWN_MJH_PUBLICATIONS } from "../../lib/utils";
|
|
6
7
|
|
|
7
8
|
interface LinkingTabProps {
|
|
8
9
|
analysis: SEOAnalysis | null;
|
|
@@ -22,15 +23,14 @@ interface LinkingTabProps {
|
|
|
22
23
|
documentType?: string;
|
|
23
24
|
}
|
|
24
25
|
|
|
25
|
-
// Build the public, reader-facing URL for a suggested article.
|
|
26
|
-
//
|
|
27
|
-
//
|
|
28
|
-
// exists - otherwise we render no live link rather than a broken one.
|
|
26
|
+
// Build the public, reader-facing URL for a suggested article. Only constructed for
|
|
27
|
+
// known MJH publications (verified via CDN probe to use www.{pub}.com/view/{slug}).
|
|
28
|
+
// Returns null for unknown publications rather than risking a broken link.
|
|
29
29
|
function buildLiveUrl(publication?: string, slug?: string): string | null {
|
|
30
30
|
if (!slug) return null;
|
|
31
31
|
const pub = (publication || "").trim().toLowerCase();
|
|
32
|
-
if (
|
|
33
|
-
const cleanSlug = slug.replace(/^\/+/, "");
|
|
32
|
+
if (!KNOWN_MJH_PUBLICATIONS.has(pub)) return null;
|
|
33
|
+
const cleanSlug = slug.replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/");
|
|
34
34
|
return `https://www.${pub}.com/view/${cleanSlug}`;
|
|
35
35
|
}
|
|
36
36
|
|
|
@@ -147,6 +147,7 @@ function freshnessChip(label: LinkingSuggestion["freshnessLabel"], score: number
|
|
|
147
147
|
"very-old": { bg: "rgba(220,38,38,0.1)", color: "#dc2626", text: "Very old" },
|
|
148
148
|
} as const;
|
|
149
149
|
const c = map[label];
|
|
150
|
+
if (!c) return null;
|
|
150
151
|
return (
|
|
151
152
|
<span
|
|
152
153
|
style={{
|
|
@@ -247,7 +248,10 @@ export function LinkingTab({
|
|
|
247
248
|
{/* Stale banner - article changed since these were generated */}
|
|
248
249
|
{isStale && suggestions.length > 0 && !isLoading && (
|
|
249
250
|
<div
|
|
251
|
+
role="button"
|
|
252
|
+
tabIndex={0}
|
|
250
253
|
onClick={onRefresh}
|
|
254
|
+
onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onRefresh(); } }}
|
|
251
255
|
style={{
|
|
252
256
|
display: "flex",
|
|
253
257
|
alignItems: "center",
|
|
@@ -338,10 +342,10 @@ export function LinkingTab({
|
|
|
338
342
|
>
|
|
339
343
|
<ScoreDonut
|
|
340
344
|
size={64}
|
|
341
|
-
topic={s.topicScore}
|
|
342
|
-
freshness={s.freshnessScore}
|
|
343
|
-
sectionFit={s.sectionFitScore}
|
|
344
|
-
composite={s.compositeScore}
|
|
345
|
+
topic={Math.max(0, Math.min(100, s.topicScore))}
|
|
346
|
+
freshness={Math.max(0, Math.min(100, s.freshnessScore))}
|
|
347
|
+
sectionFit={Math.max(0, Math.min(100, s.sectionFitScore))}
|
|
348
|
+
composite={Math.max(0, Math.min(100, s.compositeScore))}
|
|
345
349
|
/>
|
|
346
350
|
<div style={{ flex: 1, minWidth: 0 }}>
|
|
347
351
|
<div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 3, flexWrap: "wrap" }}>
|
|
@@ -358,7 +362,7 @@ export function LinkingTab({
|
|
|
358
362
|
</div>
|
|
359
363
|
{(() => {
|
|
360
364
|
const liveUrl = buildLiveUrl(publication, s.slug);
|
|
361
|
-
const sanityUrl = buildSanityUrl(sanityBaseUrl, s._id,
|
|
365
|
+
const sanityUrl = buildSanityUrl(sanityBaseUrl, s._id); // omit type - resolves by ID, suggested doc type differs from current
|
|
362
366
|
if (!liveUrl && !sanityUrl) return null;
|
|
363
367
|
return (
|
|
364
368
|
<div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 6 }}>
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { useMemo } from "react";
|
|
2
2
|
import type { DocumentFields, TechnicalAuditItem } from "../../lib/types";
|
|
3
|
+
import { containsKeywordTokens } from "../../lib/utils";
|
|
3
4
|
|
|
4
5
|
interface MetaTabProps {
|
|
5
6
|
documentFields?: DocumentFields;
|
|
@@ -8,16 +9,6 @@ interface MetaTabProps {
|
|
|
8
9
|
isLoading?: boolean;
|
|
9
10
|
}
|
|
10
11
|
|
|
11
|
-
// Token-based keyword match so "selinexor in myelofibrosis" still counts as containing
|
|
12
|
-
// the primary keyword "selinexor myelofibrosis" (word order / connecting words don't matter).
|
|
13
|
-
function containsKeywordTokens(haystack: string, needle?: string): boolean {
|
|
14
|
-
if (!needle) return true;
|
|
15
|
-
const tokens = needle.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
|
|
16
|
-
if (tokens.length === 0) return true;
|
|
17
|
-
const lower = haystack.toLowerCase();
|
|
18
|
-
return tokens.every((t) => lower.includes(t));
|
|
19
|
-
}
|
|
20
|
-
|
|
21
12
|
const cardStyle: React.CSSProperties = {
|
|
22
13
|
borderRadius: 14,
|
|
23
14
|
background: "rgba(255,255,255,0.55)",
|
|
@@ -108,7 +99,7 @@ function keywordCoverageNote(haystack: string, primaryKeyword?: string, secondar
|
|
|
108
99
|
return `Your primary keyword "${primaryKeyword}" isn't included${secondaryKeyword ? ` (secondary keyword "${secondaryKeyword}" ${hasSecondary ? "is" : "isn't"}).` : "."}`;
|
|
109
100
|
}
|
|
110
101
|
if (secondaryKeyword && !hasSecondary) {
|
|
111
|
-
return `Your
|
|
102
|
+
return `Your secondary keyword "${secondaryKeyword}" isn't included${primaryKeyword && hasPrimary ? ` (primary keyword "${primaryKeyword}" is present)` : ""}. Work it in if it reads naturally.`;
|
|
112
103
|
}
|
|
113
104
|
return "";
|
|
114
105
|
}
|
|
@@ -251,7 +251,7 @@ export function SummaryTab({
|
|
|
251
251
|
// Score against the editor's SELECTED primary so the score updates the instant
|
|
252
252
|
// they pick a different candidate (no wait for the focus re-analysis round-trip).
|
|
253
253
|
const scored =
|
|
254
|
-
primaryKeyword && primaryKeyword !== analysis.primaryKeyword
|
|
254
|
+
primaryKeyword && analysis.primaryKeyword && primaryKeyword !== analysis.primaryKeyword.term
|
|
255
255
|
? { ...analysis, primaryKeyword: { ...analysis.primaryKeyword, term: primaryKeyword } }
|
|
256
256
|
: analysis;
|
|
257
257
|
return calculateContentScoreDetailed(text, scored, documentFields);
|
|
@@ -3,6 +3,7 @@ import { LoadingBars } from "../SEOCopilotPanel";
|
|
|
3
3
|
import { MJH_BLUE, MJH_GOLD } from "../styles";
|
|
4
4
|
import type { DocumentFields, HeadingItem, LinkCheckResult, TechnicalAuditItem } from "../../lib/types";
|
|
5
5
|
import { isShortFormContent } from "../../lib/summary";
|
|
6
|
+
import { containsKeywordTokens, keywordLeadsSlug } from "../../lib/utils";
|
|
6
7
|
|
|
7
8
|
interface TechnicalTabProps {
|
|
8
9
|
text: string;
|
|
@@ -18,31 +19,6 @@ interface TechnicalTabProps {
|
|
|
18
19
|
onCheckLinks: () => void;
|
|
19
20
|
}
|
|
20
21
|
|
|
21
|
-
// Token-based keyword match so "selinexor in myelofibrosis" still counts as containing
|
|
22
|
-
// "selinexor myelofibrosis" (word order / connecting words don't matter).
|
|
23
|
-
function containsKeywordTokens(haystack: string, needle?: string): boolean {
|
|
24
|
-
if (!needle) return true;
|
|
25
|
-
const tokens = needle.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
|
|
26
|
-
if (tokens.length === 0) return true;
|
|
27
|
-
const lower = haystack.toLowerCase();
|
|
28
|
-
return tokens.every((t) => lower.includes(t));
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
// True when the primary keyword sits near the START of the slug. Editors get the
|
|
32
|
-
// most SEO/CTR value when the keyword leads the URL (and it survives truncation).
|
|
33
|
-
function keywordLeadsUrl(slug: string, primaryKeyword?: string): boolean {
|
|
34
|
-
if (!primaryKeyword) return true;
|
|
35
|
-
const slugWords = slug.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean);
|
|
36
|
-
const tokens = primaryKeyword.toLowerCase().split(/\s+/).filter((t) => t.length > 1);
|
|
37
|
-
if (tokens.length === 0 || slugWords.length === 0) return true;
|
|
38
|
-
let earliest = Infinity;
|
|
39
|
-
for (const t of tokens) {
|
|
40
|
-
const idx = slugWords.findIndex((w) => w.includes(t));
|
|
41
|
-
if (idx >= 0) earliest = Math.min(earliest, idx);
|
|
42
|
-
}
|
|
43
|
-
return earliest <= 2; // within the first three slug words
|
|
44
|
-
}
|
|
45
|
-
|
|
46
22
|
// URL Slug audit (moved here from Meta per the 6/10 director notes). Deliberately
|
|
47
23
|
// vague and non-numeric: we never cite a character count or say "too long" - just
|
|
48
24
|
// scan for the primary keyword (ideally leading the URL) and nudge toward short,
|
|
@@ -59,7 +35,7 @@ function urlAudit(slug?: string, primaryKeyword?: string, secondaryKeyword?: str
|
|
|
59
35
|
}
|
|
60
36
|
const slugAsWords = slug.replace(/-/g, " ");
|
|
61
37
|
const hasPrimary = primaryKeyword ? containsKeywordTokens(slugAsWords, primaryKeyword) : true;
|
|
62
|
-
const leads = primaryKeyword ?
|
|
38
|
+
const leads = primaryKeyword ? keywordLeadsSlug(slug, primaryKeyword) : true;
|
|
63
39
|
const hasSecondary = secondaryKeyword ? containsKeywordTokens(slugAsWords, secondaryKeyword) : true;
|
|
64
40
|
|
|
65
41
|
if (primaryKeyword && !hasPrimary) {
|
|
@@ -252,7 +228,7 @@ function imageFilenameAudit(filenames: string[]): TechnicalAuditItem | null {
|
|
|
252
228
|
const words = base.split("-").filter(Boolean);
|
|
253
229
|
if (words.length < 2) {
|
|
254
230
|
issues.push({ filename: f, reason: "single word - use 2-3 descriptive hyphenated words" });
|
|
255
|
-
} else if (words.length >
|
|
231
|
+
} else if (words.length > 5) {
|
|
256
232
|
issues.push({ filename: f, reason: "too many words - keep to 3-5" });
|
|
257
233
|
}
|
|
258
234
|
}
|
|
@@ -287,7 +263,7 @@ function imageAltTextAudit(altTexts: string[]): TechnicalAuditItem | null {
|
|
|
287
263
|
audited++;
|
|
288
264
|
const len = trimmed.length;
|
|
289
265
|
const wc = trimmed.split(/\s+/).filter(Boolean).length;
|
|
290
|
-
if (len
|
|
266
|
+
if (len >= 125) {
|
|
291
267
|
issues.push({ alt: trimmed, reason: `${len} chars - shorten to under 125` });
|
|
292
268
|
} else if (wc < 2) {
|
|
293
269
|
issues.push({ alt: trimmed, reason: "just one word - use 2-5 descriptive keywords" });
|
|
@@ -742,9 +718,12 @@ export function TechnicalTab({
|
|
|
742
718
|
const headingsDetailed = documentFields?.headingsDetailed;
|
|
743
719
|
// Fall back gracefully if a host (e.g. older Notebook builds) doesn't supply heading
|
|
744
720
|
// levels - we still get the count audit from the flat string list.
|
|
745
|
-
const headingsForStructure: HeadingItem[] =
|
|
746
|
-
|
|
747
|
-
|
|
721
|
+
const headingsForStructure: HeadingItem[] = useMemo(
|
|
722
|
+
() => headingsDetailed
|
|
723
|
+
? headingsDetailed
|
|
724
|
+
: headings.map((text) => ({ text, level: 2 })),
|
|
725
|
+
[headingsDetailed, headings]
|
|
726
|
+
);
|
|
748
727
|
|
|
749
728
|
// Word count drives both the dedicated Word Count audit and the heading-density check.
|
|
750
729
|
const wordCount = text ? text.split(/\s+/).filter(Boolean).length : 0;
|
|
@@ -890,8 +869,8 @@ export function TechnicalTab({
|
|
|
890
869
|
{h.text || "(empty)"}
|
|
891
870
|
</div>
|
|
892
871
|
))}
|
|
893
|
-
{headings.length > 12 && (
|
|
894
|
-
<div style={{ fontSize: 10, color: "#4b5563" }}>+ {headings.length - 12} more</div>
|
|
872
|
+
{(headingsDetailed ?? headings).length > 12 && (
|
|
873
|
+
<div style={{ fontSize: 10, color: "#4b5563" }}>+ {(headingsDetailed ?? headings).length - 12} more</div>
|
|
895
874
|
)}
|
|
896
875
|
</div>
|
|
897
876
|
</div>
|
|
@@ -82,6 +82,8 @@ export function useKeywordAnalysis(
|
|
|
82
82
|
docVersionRef.current += 1;
|
|
83
83
|
volumeAbortRef.current?.abort();
|
|
84
84
|
volumeAbortRef.current = null;
|
|
85
|
+
deepAbortRef.current?.abort();
|
|
86
|
+
deepAbortRef.current = null;
|
|
85
87
|
const fresh = loadCached();
|
|
86
88
|
cached.current = fresh;
|
|
87
89
|
setAnalysisRaw(fresh.analysis);
|
|
@@ -131,6 +133,66 @@ export function useKeywordAnalysis(
|
|
|
131
133
|
// AbortController for the in-flight volume lookup. Cancelled on doc switch and
|
|
132
134
|
// before each new lookup so only one lookup is ever outstanding at a time.
|
|
133
135
|
const volumeAbortRef = useRef<AbortController | null>(null);
|
|
136
|
+
const deepAbortRef = useRef<AbortController | null>(null);
|
|
137
|
+
|
|
138
|
+
// Abort any in-flight volume lookup or deep analysis when the hook unmounts so a late
|
|
139
|
+
// resolver can't run after teardown and we don't waste backend (Claude/SEMrush) spend.
|
|
140
|
+
useEffect(() => () => {
|
|
141
|
+
volumeAbortRef.current?.abort();
|
|
142
|
+
deepAbortRef.current?.abort();
|
|
143
|
+
}, []);
|
|
144
|
+
|
|
145
|
+
const doVolumeLookup = useCallback((analysisResult: SEOAnalysis, terms?: string[]) => {
|
|
146
|
+
setIsVolumesLoading(true);
|
|
147
|
+
const myVersion = docVersionRef.current;
|
|
148
|
+
|
|
149
|
+
const lookupTerms = terms || (() => {
|
|
150
|
+
const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
|
|
151
|
+
return [
|
|
152
|
+
...new Set([
|
|
153
|
+
...candidateTerms,
|
|
154
|
+
analysisResult.primaryKeyword.term,
|
|
155
|
+
...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
|
|
156
|
+
...analysisResult.missingKeywords.map((kw) => kw.term),
|
|
157
|
+
]),
|
|
158
|
+
];
|
|
159
|
+
})();
|
|
160
|
+
|
|
161
|
+
if (lookupTerms.length === 0) {
|
|
162
|
+
setIsVolumesLoading(false);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Cancel any previous in-flight lookup before starting a new one
|
|
167
|
+
volumeAbortRef.current?.abort();
|
|
168
|
+
const controller = new AbortController();
|
|
169
|
+
volumeAbortRef.current = controller;
|
|
170
|
+
|
|
171
|
+
lookupKeywords(apiUrl, lookupTerms, controller.signal)
|
|
172
|
+
.then(({ results }) => {
|
|
173
|
+
if (docVersionRef.current !== myVersion) return; // document switched - drop stale volumes
|
|
174
|
+
// Add new results to persistent cache
|
|
175
|
+
results.forEach((r) => volumeMapRef.current.set(r.keyword.toLowerCase(), r));
|
|
176
|
+
// Re-apply all cached volumes to current analysis
|
|
177
|
+
const current = lastAnalysisRef.current || analysisResult;
|
|
178
|
+
const merged = mergeVolumes(current, volumeMapRef.current);
|
|
179
|
+
lastAnalysisRef.current = merged;
|
|
180
|
+
setAnalysisRaw(merged);
|
|
181
|
+
try {
|
|
182
|
+
const prev = loadCached();
|
|
183
|
+
localStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: merged }));
|
|
184
|
+
} catch { /* ignore */ }
|
|
185
|
+
setIsVolumesLoading(false);
|
|
186
|
+
})
|
|
187
|
+
.catch((err) => {
|
|
188
|
+
if (err instanceof Error && err.name === "AbortError") return;
|
|
189
|
+
if (docVersionRef.current !== myVersion) return;
|
|
190
|
+
setIsVolumesLoading(false);
|
|
191
|
+
});
|
|
192
|
+
}, [apiUrl, cacheKey]);
|
|
193
|
+
|
|
194
|
+
const doVolumeLookupRef = useRef(doVolumeLookup);
|
|
195
|
+
useEffect(() => { doVolumeLookupRef.current = doVolumeLookup; }, [doVolumeLookup]);
|
|
134
196
|
|
|
135
197
|
useEffect(() => {
|
|
136
198
|
if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
|
|
@@ -164,7 +226,7 @@ export function useKeywordAnalysis(
|
|
|
164
226
|
const uncachedTerms = allTerms.filter((t) => !volumeMapRef.current.has(t.toLowerCase()));
|
|
165
227
|
|
|
166
228
|
if (uncachedTerms.length > 0) {
|
|
167
|
-
|
|
229
|
+
doVolumeLookupRef.current(analysisResult, uncachedTerms);
|
|
168
230
|
}
|
|
169
231
|
})
|
|
170
232
|
.catch((err) => {
|
|
@@ -184,55 +246,6 @@ export function useKeywordAnalysis(
|
|
|
184
246
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
185
247
|
}, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary, JSON.stringify(documentFields)]);
|
|
186
248
|
|
|
187
|
-
const doVolumeLookup = useCallback((analysisResult: SEOAnalysis, terms?: string[]) => {
|
|
188
|
-
setIsVolumesLoading(true);
|
|
189
|
-
const myVersion = docVersionRef.current;
|
|
190
|
-
|
|
191
|
-
const lookupTerms = terms || (() => {
|
|
192
|
-
const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
|
|
193
|
-
return [
|
|
194
|
-
...new Set([
|
|
195
|
-
...candidateTerms,
|
|
196
|
-
analysisResult.primaryKeyword.term,
|
|
197
|
-
...(analysisResult.supportingKeywords || []).map((kw) => kw.term),
|
|
198
|
-
...analysisResult.missingKeywords.map((kw) => kw.term),
|
|
199
|
-
]),
|
|
200
|
-
];
|
|
201
|
-
})();
|
|
202
|
-
|
|
203
|
-
if (lookupTerms.length === 0) {
|
|
204
|
-
setIsVolumesLoading(false);
|
|
205
|
-
return;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
// Cancel any previous in-flight lookup before starting a new one
|
|
209
|
-
volumeAbortRef.current?.abort();
|
|
210
|
-
const controller = new AbortController();
|
|
211
|
-
volumeAbortRef.current = controller;
|
|
212
|
-
|
|
213
|
-
lookupKeywords(apiUrl, lookupTerms, controller.signal)
|
|
214
|
-
.then(({ results }) => {
|
|
215
|
-
if (docVersionRef.current !== myVersion) return; // document switched - drop stale volumes
|
|
216
|
-
// Add new results to persistent cache
|
|
217
|
-
results.forEach((r) => volumeMapRef.current.set(r.keyword.toLowerCase(), r));
|
|
218
|
-
// Re-apply all cached volumes to current analysis
|
|
219
|
-
const current = lastAnalysisRef.current || analysisResult;
|
|
220
|
-
const merged = mergeVolumes(current, volumeMapRef.current);
|
|
221
|
-
lastAnalysisRef.current = merged;
|
|
222
|
-
setAnalysisRaw(merged);
|
|
223
|
-
try {
|
|
224
|
-
const prev = loadCached();
|
|
225
|
-
localStorage.setItem(cacheKey, JSON.stringify({ ...prev, analysis: merged }));
|
|
226
|
-
} catch { /* ignore */ }
|
|
227
|
-
setIsVolumesLoading(false);
|
|
228
|
-
})
|
|
229
|
-
.catch((err) => {
|
|
230
|
-
if (err instanceof Error && err.name === "AbortError") return;
|
|
231
|
-
if (docVersionRef.current !== myVersion) return;
|
|
232
|
-
setIsVolumesLoading(false);
|
|
233
|
-
});
|
|
234
|
-
}, [apiUrl, cacheKey]);
|
|
235
|
-
|
|
236
249
|
const refreshVolumes = useCallback(() => {
|
|
237
250
|
const current = lastAnalysisRef.current || analysis;
|
|
238
251
|
if (!current) return;
|
|
@@ -248,18 +261,21 @@ export function useKeywordAnalysis(
|
|
|
248
261
|
setAeoTextSnapshot(text);
|
|
249
262
|
|
|
250
263
|
const myVersion = docVersionRef.current;
|
|
251
|
-
|
|
264
|
+
deepAbortRef.current?.abort(); const deepController = new AbortController(); deepAbortRef.current = deepController;
|
|
265
|
+
fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary, deepController.signal)
|
|
252
266
|
.then((result) => {
|
|
253
267
|
if (docVersionRef.current !== myVersion) return; // document switched - drop stale result
|
|
254
268
|
setDeepAnalysis(result as DeepAnalysis);
|
|
255
269
|
setIsDeepLoading(false);
|
|
256
270
|
})
|
|
257
271
|
.catch((err) => {
|
|
272
|
+
// Aborted (doc switch or unmount) is normal teardown, not an error to surface.
|
|
273
|
+
if (deepController.signal.aborted || err?.name === "AbortError") return;
|
|
258
274
|
if (docVersionRef.current !== myVersion) return;
|
|
259
275
|
setError(err.message);
|
|
260
276
|
setIsDeepLoading(false);
|
|
261
277
|
});
|
|
262
|
-
}, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields]);
|
|
278
|
+
}, [text, apiUrl, publication, effectiveSeeds?.join(","), documentFields, focusPrimary]);
|
|
263
279
|
|
|
264
280
|
return {
|
|
265
281
|
analysis,
|
package/src/hooks/useSEOChat.ts
CHANGED
|
@@ -15,6 +15,7 @@ interface KeywordPanelData {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
function getLocalUserId(): string {
|
|
18
|
+
if (typeof window === 'undefined') return 'anonymous';
|
|
18
19
|
const key = "seo-copilot-user-id";
|
|
19
20
|
try {
|
|
20
21
|
let id = localStorage.getItem(key);
|
|
@@ -88,7 +89,10 @@ export function useSEOChat(
|
|
|
88
89
|
|
|
89
90
|
// Abort any in-flight stream on unmount to prevent state updates on a dead component.
|
|
90
91
|
useEffect(() => {
|
|
91
|
-
return () => {
|
|
92
|
+
return () => {
|
|
93
|
+
streamAbortRef.current?.abort();
|
|
94
|
+
if (saveTimerRef.current) clearTimeout(saveTimerRef.current);
|
|
95
|
+
};
|
|
92
96
|
}, []);
|
|
93
97
|
|
|
94
98
|
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
package/src/inspector.ts
CHANGED
|
@@ -1,51 +1,58 @@
|
|
|
1
|
-
import { type DocumentInspector, type DocumentInspectorProps } from "sanity";
|
|
2
|
-
import { createElement } from "react";
|
|
3
|
-
import type { SEOCopilotConfig } from "./index";
|
|
4
|
-
import SEOCopilotPanel from "./components/SEOCopilotPanel";
|
|
5
|
-
|
|
6
|
-
function SEOIcon() {
|
|
7
|
-
return createElement("svg", { viewBox: "0 0 25 25", width: "1em", height: "1em", fill: "none" },
|
|
8
|
-
createElement("circle", { cx: "12.5", cy: "12.5", r: "11.5", fill: "#E6C01B" }),
|
|
9
|
-
createElement("text", {
|
|
10
|
-
x: "12.5", y: "7.5",
|
|
11
|
-
textAnchor: "middle",
|
|
12
|
-
dominantBaseline: "central",
|
|
13
|
-
fill: "white",
|
|
14
|
-
fontSize: "7",
|
|
15
|
-
fontWeight: "900",
|
|
16
|
-
fontFamily: "Arial Black, Impact, sans-serif",
|
|
17
|
-
}, "S"),
|
|
18
|
-
createElement("text", {
|
|
19
|
-
x: "12.5", y: "12.8",
|
|
20
|
-
textAnchor: "middle",
|
|
21
|
-
dominantBaseline: "central",
|
|
22
|
-
fill: "white",
|
|
23
|
-
fontSize: "7",
|
|
24
|
-
fontWeight: "900",
|
|
25
|
-
fontFamily: "Arial Black, Impact, sans-serif",
|
|
26
|
-
}, "E"),
|
|
27
|
-
createElement("text", {
|
|
28
|
-
x: "12.5", y: "18",
|
|
29
|
-
textAnchor: "middle",
|
|
30
|
-
dominantBaseline: "central",
|
|
31
|
-
fill: "white",
|
|
32
|
-
fontSize: "7",
|
|
33
|
-
fontWeight: "900",
|
|
34
|
-
fontFamily: "Arial Black, Impact, sans-serif",
|
|
35
|
-
}, "O")
|
|
36
|
-
);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export function seoCopilotInspector(config: SEOCopilotConfig): DocumentInspector {
|
|
40
|
-
return {
|
|
41
|
-
name: "seo-copilot",
|
|
42
|
-
useMenuItem: () => ({
|
|
43
|
-
title: "SEO Copilot",
|
|
44
|
-
icon: SEOIcon,
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
1
|
+
import { type DocumentInspector, type DocumentInspectorProps } from "sanity";
|
|
2
|
+
import { createElement } from "react";
|
|
3
|
+
import type { SEOCopilotConfig } from "./index";
|
|
4
|
+
import SEOCopilotPanel from "./components/SEOCopilotPanel";
|
|
5
|
+
|
|
6
|
+
function SEOIcon() {
|
|
7
|
+
return createElement("svg", { viewBox: "0 0 25 25", width: "1em", height: "1em", fill: "none" },
|
|
8
|
+
createElement("circle", { cx: "12.5", cy: "12.5", r: "11.5", fill: "#E6C01B" }),
|
|
9
|
+
createElement("text", {
|
|
10
|
+
x: "12.5", y: "7.5",
|
|
11
|
+
textAnchor: "middle",
|
|
12
|
+
dominantBaseline: "central",
|
|
13
|
+
fill: "white",
|
|
14
|
+
fontSize: "7",
|
|
15
|
+
fontWeight: "900",
|
|
16
|
+
fontFamily: "Arial Black, Impact, sans-serif",
|
|
17
|
+
}, "S"),
|
|
18
|
+
createElement("text", {
|
|
19
|
+
x: "12.5", y: "12.8",
|
|
20
|
+
textAnchor: "middle",
|
|
21
|
+
dominantBaseline: "central",
|
|
22
|
+
fill: "white",
|
|
23
|
+
fontSize: "7",
|
|
24
|
+
fontWeight: "900",
|
|
25
|
+
fontFamily: "Arial Black, Impact, sans-serif",
|
|
26
|
+
}, "E"),
|
|
27
|
+
createElement("text", {
|
|
28
|
+
x: "12.5", y: "18",
|
|
29
|
+
textAnchor: "middle",
|
|
30
|
+
dominantBaseline: "central",
|
|
31
|
+
fill: "white",
|
|
32
|
+
fontSize: "7",
|
|
33
|
+
fontWeight: "900",
|
|
34
|
+
fontFamily: "Arial Black, Impact, sans-serif",
|
|
35
|
+
}, "O")
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function seoCopilotInspector(config: SEOCopilotConfig): DocumentInspector {
|
|
40
|
+
return {
|
|
41
|
+
name: "seo-copilot",
|
|
42
|
+
useMenuItem: () => ({
|
|
43
|
+
title: "SEO Copilot",
|
|
44
|
+
icon: SEOIcon,
|
|
45
|
+
// Toolbar placement test: showAsAction renders this as a button in the document
|
|
46
|
+
// toolbar (where editors expect it). The original crash came from passing
|
|
47
|
+
// showAsAction WITHOUT a tone; pairing it with a valid string tone is how Sanity's
|
|
48
|
+
// own built-in inspectors (Validation, etc.) keep their toolbar button safely.
|
|
49
|
+
// If this still crashes in Nick's studio, remove these two lines to fall back to
|
|
50
|
+
// the "..." overflow menu (the known-safe placement).
|
|
51
|
+
showAsAction: true,
|
|
52
|
+
tone: "default",
|
|
53
|
+
}),
|
|
54
|
+
component: function SEOCopilotInspector(props: DocumentInspectorProps) {
|
|
55
|
+
return createElement(SEOCopilotPanel, { ...props, config });
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
package/src/lib/api.ts
CHANGED
|
@@ -43,7 +43,6 @@ export async function fetchAnalysis(
|
|
|
43
43
|
|
|
44
44
|
if (!response.ok) {
|
|
45
45
|
const err = safeParseJson<{ error?: string }>(text);
|
|
46
|
-
console.error("[seo-copilot] analyze error", response.status, err.error);
|
|
47
46
|
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
48
47
|
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
49
48
|
throw new Error("Something went wrong analyzing this document.");
|
|
@@ -76,7 +75,6 @@ export async function fetchChatStream(
|
|
|
76
75
|
|
|
77
76
|
if (!response.ok) {
|
|
78
77
|
const err = await response.json().catch(() => ({ error: "Request failed" }));
|
|
79
|
-
console.error("[seo-copilot] chat error", response.status, err.error);
|
|
80
78
|
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
81
79
|
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
82
80
|
throw new Error("Something went wrong. Please try again.");
|
|
@@ -87,17 +85,18 @@ export async function fetchChatStream(
|
|
|
87
85
|
|
|
88
86
|
export async function fetchQuestions(
|
|
89
87
|
apiUrl: string,
|
|
90
|
-
keyword: string
|
|
88
|
+
keyword: string,
|
|
89
|
+
signal?: AbortSignal
|
|
91
90
|
): Promise<{ questions: { question: string; volume: number; cpc: number; competition: number }[]; apiUnitsUsed: number }> {
|
|
92
91
|
const response = await fetch(`${apiUrl}/api/seo-copilot/questions`, {
|
|
93
92
|
method: "POST",
|
|
94
93
|
headers: { "Content-Type": "application/json" },
|
|
95
94
|
body: JSON.stringify({ keyword }),
|
|
95
|
+
signal,
|
|
96
96
|
});
|
|
97
97
|
|
|
98
98
|
if (!response.ok) {
|
|
99
99
|
const err = await response.json().catch(() => ({ error: "Request failed" }));
|
|
100
|
-
console.error("[seo-copilot] questions error", response.status, err.error);
|
|
101
100
|
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
102
101
|
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
103
102
|
throw new Error("Something went wrong. Please try again.");
|
|
@@ -131,7 +130,6 @@ export async function lookupKeywords(
|
|
|
131
130
|
|
|
132
131
|
if (!response.ok) {
|
|
133
132
|
const err = await response.json().catch(() => ({ error: "Request failed" }));
|
|
134
|
-
console.error("[seo-copilot] keywords error", response.status, err.error);
|
|
135
133
|
if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
|
|
136
134
|
if (response.status >= 500) throw new Error("Could not reach the SEO service.");
|
|
137
135
|
throw new Error("Something went wrong. Please try again.");
|
|
@@ -161,7 +159,8 @@ export async function fetchContentSuggestions(
|
|
|
161
159
|
apiUrl: string,
|
|
162
160
|
content: string,
|
|
163
161
|
primaryKeyword: string,
|
|
164
|
-
publication?: string
|
|
162
|
+
publication?: string,
|
|
163
|
+
signal?: AbortSignal
|
|
165
164
|
): Promise<ContentSuggestions> {
|
|
166
165
|
const empty: ContentSuggestions = { keyTakeaways: [], infographicOpportunities: [], bulletListItems: [] };
|
|
167
166
|
try {
|
|
@@ -169,6 +168,7 @@ export async function fetchContentSuggestions(
|
|
|
169
168
|
method: "POST",
|
|
170
169
|
headers: { "Content-Type": "application/json" },
|
|
171
170
|
body: JSON.stringify({ content, primaryKeyword, publication }),
|
|
171
|
+
signal,
|
|
172
172
|
});
|
|
173
173
|
if (!res.ok) return empty;
|
|
174
174
|
const data = await res.json().catch(() => null);
|
|
@@ -233,7 +233,8 @@ export async function fetchLinkingSuggestions(
|
|
|
233
233
|
primaryKeyword: string,
|
|
234
234
|
supportingKeywords: string[],
|
|
235
235
|
currentDocumentId?: string,
|
|
236
|
-
publication?: string
|
|
236
|
+
publication?: string,
|
|
237
|
+
signal?: AbortSignal
|
|
237
238
|
): Promise<LinkingSuggestion[]> {
|
|
238
239
|
if (!content || content.trim().length < 50) return [];
|
|
239
240
|
try {
|
|
@@ -241,6 +242,7 @@ export async function fetchLinkingSuggestions(
|
|
|
241
242
|
method: "POST",
|
|
242
243
|
headers: { "Content-Type": "application/json" },
|
|
243
244
|
body: JSON.stringify({ content, primaryKeyword, supportingKeywords, currentDocumentId, publication }),
|
|
245
|
+
signal,
|
|
244
246
|
});
|
|
245
247
|
if (!res.ok) return [];
|
|
246
248
|
const data = await res.json().catch(() => null);
|
|
@@ -170,8 +170,8 @@ export function detectAuthor(val: Record<string, unknown> | undefined): {
|
|
|
170
170
|
}
|
|
171
171
|
if (typeof first === "object" && first !== null) {
|
|
172
172
|
const o = first as Record<string, unknown>;
|
|
173
|
-
const name = (o.name
|
|
174
|
-
const creds = (o.credentials
|
|
173
|
+
const name = ([o.name, o.fullName, o.displayName] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0);
|
|
174
|
+
const creds = ([o.credentials, o.title, o.suffix] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0);
|
|
175
175
|
const slug = (o.slug as { current?: string } | undefined)?.current;
|
|
176
176
|
const bio = (o.bioUrl as string | undefined) || (slug ? `/author/${slug}` : undefined);
|
|
177
177
|
if (name) {
|
|
@@ -237,14 +237,14 @@ export function extractImageMeta(value: Record<string, unknown>): { names: strin
|
|
|
237
237
|
// Pure + side-effect-free so it can be exercised against real fetched documents.
|
|
238
238
|
export function buildDocumentFields(value: Record<string, unknown> | undefined): DocumentFields {
|
|
239
239
|
const val = value;
|
|
240
|
-
const title = val?.title
|
|
240
|
+
const title = typeof val?.title === 'string' ? val.title : undefined;
|
|
241
241
|
const body = val?.body;
|
|
242
242
|
const { authorName, authorCredentials, authorBioUrl, authorIsReference } = detectAuthor(val);
|
|
243
243
|
const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
|
|
244
244
|
return {
|
|
245
245
|
title: title || undefined,
|
|
246
246
|
// MJH uses `summary`; standard Sanity SEO plugins use `metaDescription`
|
|
247
|
-
metaDescription: (val?.metaDescription
|
|
247
|
+
metaDescription: ([val?.metaDescription, val?.summary, val?.description, val?.seoDescription] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
|
|
248
248
|
slug: detectSlug(val),
|
|
249
249
|
imageNames: imageMeta.names,
|
|
250
250
|
imageTitles: imageMeta.titles,
|
|
@@ -252,17 +252,17 @@ export function buildDocumentFields(value: Record<string, unknown> | undefined):
|
|
|
252
252
|
headings: extractHeadings(body),
|
|
253
253
|
headingsDetailed: extractHeadingsDetailed(body),
|
|
254
254
|
bodyLinks: extractBodyLinks(body),
|
|
255
|
-
contentCategory:
|
|
255
|
+
contentCategory: typeof val?.contentCategory === 'string' ? val.contentCategory : typeof val?.category === 'string' ? val.category : undefined,
|
|
256
256
|
contentPlacement: Array.isArray(val?.contentPlacement) ? (val.contentPlacement as string[]) : undefined,
|
|
257
257
|
authorName,
|
|
258
258
|
authorCredentials,
|
|
259
259
|
authorBioUrl,
|
|
260
260
|
authorIsReference,
|
|
261
261
|
// `published` is MJH's date field; `publishedAt`/`publishDate` cover other schemas
|
|
262
|
-
publishedAt: (val?.
|
|
262
|
+
publishedAt: ([val?.publishedAt, val?.publishDate, val?.published, val?._createdAt] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
|
|
263
263
|
// `updatedOn` is MJH's "Updated On" field. `updatedAt` is the standard Sanity convention.
|
|
264
264
|
// `_updatedAt` is the Sanity-managed timestamp as a final fallback.
|
|
265
|
-
updatedAt: (val?.updatedOn
|
|
266
|
-
lastReviewedAt: (val?.lastReviewedAt
|
|
265
|
+
updatedAt: ([val?.updatedOn, val?.updatedAt, val?._updatedAt] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
|
|
266
|
+
lastReviewedAt: ([val?.lastReviewedAt, val?.lastReviewed, val?.medicallyReviewedAt] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
|
|
267
267
|
};
|
|
268
268
|
}
|
package/src/lib/scoring.ts
CHANGED
|
@@ -41,7 +41,7 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
|
|
|
41
41
|
// adjacent phrase, but if every token is in the body the keyword IS present.
|
|
42
42
|
// Try the exact phrase first; otherwise fall back to token co-occurrence (all
|
|
43
43
|
// tokens present) and use the rarest token as the concept's mention count.
|
|
44
|
-
// (This mirrors
|
|
44
|
+
// (This mirrors containsKeywordTokens() used by the Meta + Summary audits.)
|
|
45
45
|
const tokens = primaryTerm.split(/\s+/).filter((t) => t.length > 1);
|
|
46
46
|
const phraseCount = countWholeMatches(lowerContent, primaryTerm);
|
|
47
47
|
let occurrences = phraseCount;
|
|
@@ -88,7 +88,7 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
|
|
|
88
88
|
// 2. Supporting keyword coverage (up to 25)
|
|
89
89
|
const supportingKws = analysis.supportingKeywords || [];
|
|
90
90
|
if (supportingKws.length > 0) {
|
|
91
|
-
const inContentCount = supportingKws.filter((kw) => lowerContent.includes(kw.term.toLowerCase())).length;
|
|
91
|
+
const inContentCount = supportingKws.filter((kw) => kw != null && typeof kw.term === "string" && lowerContent.includes(kw.term.toLowerCase())).length;
|
|
92
92
|
const coverageRatio = inContentCount / supportingKws.length;
|
|
93
93
|
const pts = Math.round(coverageRatio * 25);
|
|
94
94
|
components.push({
|