sanity-plugin-seo-copilot 0.2.1 → 0.2.5
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 +300 -117
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +298 -115
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/components/KeywordPanel.tsx +6 -4
- package/src/components/SEOCopilotPanel.tsx +18 -7
- package/src/components/tabs/AEOTab.tsx +9 -3
- package/src/components/tabs/MetaTab.tsx +9 -6
- package/src/components/tabs/SummaryTab.tsx +2 -2
- package/src/components/tabs/TechnicalTab.tsx +70 -30
- package/src/hooks/useDocumentContent.ts +47 -216
- package/src/hooks/useKeywordAnalysis.ts +12 -0
- package/src/hooks/useSEOChat.ts +16 -7
- package/src/lib/documentExtract.ts +257 -0
- package/src/lib/geoAnalysis.ts +16 -3
- package/src/lib/scoring.ts +37 -14
- package/src/lib/summary.ts +59 -7
- package/src/lib/types.ts +4 -1
|
@@ -1,216 +1,47 @@
|
|
|
1
|
-
import { useState, useEffect, useRef } from "react";
|
|
2
|
-
import { useDocumentPane } from "sanity/structure";
|
|
3
|
-
import type { DocumentFields
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
return headings;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// Headings with their numeric level (1-6), so the Technical tab can audit hierarchy.
|
|
54
|
-
function extractHeadingsDetailed(blocks: unknown): HeadingItem[] {
|
|
55
|
-
if (!blocks || !Array.isArray(blocks)) return [];
|
|
56
|
-
const out: HeadingItem[] = [];
|
|
57
|
-
for (const block of blocks as PortableTextBlock[]) {
|
|
58
|
-
if (block._type === "block" && block.style && /^h[1-6]$/.test(block.style) && block.children) {
|
|
59
|
-
const text = block.children.map((child) => child.text || "").join("").trim();
|
|
60
|
-
const level = Number(block.style.slice(1));
|
|
61
|
-
// Include empty headings too - the Technical tab flags them.
|
|
62
|
-
out.push({ text, level });
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
return out;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// Every URL the editor has linked from this article body. Sanity stores them
|
|
69
|
-
// in Portable Text markDefs (with _type: "link" and href/url). We also catch
|
|
70
|
-
// inline plain-text URLs as a fallback.
|
|
71
|
-
function extractBodyLinks(blocks: unknown): string[] {
|
|
72
|
-
const urls = new Set<string>();
|
|
73
|
-
if (Array.isArray(blocks)) {
|
|
74
|
-
for (const block of blocks as PortableTextBlock[]) {
|
|
75
|
-
if (block._type === "block" && Array.isArray(block.markDefs)) {
|
|
76
|
-
for (const md of block.markDefs) {
|
|
77
|
-
const href = md.href || md.url;
|
|
78
|
-
if (typeof href === "string" && /^https?:\/\//i.test(href)) {
|
|
79
|
-
urls.add(href.trim());
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
// Inline URLs that aren't in a link annotation - rare but possible.
|
|
86
|
-
if (Array.isArray(blocks)) {
|
|
87
|
-
for (const block of blocks as PortableTextBlock[]) {
|
|
88
|
-
if (block._type === "block" && Array.isArray(block.children)) {
|
|
89
|
-
const blockText = block.children.map((c) => c.text || "").join(" ");
|
|
90
|
-
const matches = blockText.match(/https?:\/\/[^\s"'<>)\]]+/g);
|
|
91
|
-
if (matches) matches.forEach((u) => urls.add(u.replace(/[.,;:!?]+$/, "")));
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
return Array.from(urls);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// Extracts image metadata from the known top-level image fields:
|
|
99
|
-
// - names: alt text + asset filename (for the alt + filename audits)
|
|
100
|
-
// - titles: the `title` field on the image object or asset (the hover tooltip)
|
|
101
|
-
// - count: number of real images found (so the title audit can say "X of N")
|
|
102
|
-
function extractImageMeta(value: Record<string, unknown>): { names: string[]; titles: string[]; count: number } {
|
|
103
|
-
const names: string[] = [];
|
|
104
|
-
const titles: string[] = [];
|
|
105
|
-
let count = 0;
|
|
106
|
-
const imageFields = ["mainImage", "image", "heroImage", "thumbnail", "featuredImage"];
|
|
107
|
-
for (const field of imageFields) {
|
|
108
|
-
const img = value[field] as Record<string, unknown> | undefined;
|
|
109
|
-
if (!img || typeof img !== "object") continue;
|
|
110
|
-
const asset = img.asset && typeof img.asset === "object" ? (img.asset as Record<string, unknown>) : undefined;
|
|
111
|
-
// Only count entries that are actually images (have an asset or an image _type).
|
|
112
|
-
if (!asset && img._type !== "image") continue;
|
|
113
|
-
count++;
|
|
114
|
-
if (typeof img.alt === "string" && img.alt) names.push(img.alt);
|
|
115
|
-
if (asset && typeof asset.originalFilename === "string" && asset.originalFilename) names.push(asset.originalFilename);
|
|
116
|
-
// The hover-tooltip title can live on the image object or on the asset.
|
|
117
|
-
if (typeof img.title === "string" && img.title) titles.push(img.title);
|
|
118
|
-
else if (asset && typeof asset.title === "string" && asset.title) titles.push(asset.title);
|
|
119
|
-
}
|
|
120
|
-
return { names, titles, count };
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
export function useDocumentContent(): { text: string; isLoading: boolean; documentFields: DocumentFields; documentId: string | undefined } {
|
|
124
|
-
const { value, ready } = useDocumentPane();
|
|
125
|
-
const documentId = (value?._id as string | undefined) || undefined;
|
|
126
|
-
const title = value?.title as string | undefined;
|
|
127
|
-
const body = value?.body;
|
|
128
|
-
const [debouncedText, setDebouncedText] = useState("");
|
|
129
|
-
const [isLoading, setIsLoading] = useState(!ready);
|
|
130
|
-
const [documentFields, setDocumentFields] = useState<DocumentFields>({});
|
|
131
|
-
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
132
|
-
const prevDocIdRef = useRef<string | undefined>(documentId);
|
|
133
|
-
|
|
134
|
-
// Reset loading state on doc switch so downstream tabs can show their own loading UI
|
|
135
|
-
// instead of flashing "Missing" cards based on the previous doc's data.
|
|
136
|
-
useEffect(() => {
|
|
137
|
-
if (prevDocIdRef.current !== documentId) {
|
|
138
|
-
prevDocIdRef.current = documentId;
|
|
139
|
-
setIsLoading(true);
|
|
140
|
-
}
|
|
141
|
-
}, [documentId]);
|
|
142
|
-
|
|
143
|
-
useEffect(() => {
|
|
144
|
-
const bodyText = extractText(body);
|
|
145
|
-
const fullText = [title, bodyText].filter(Boolean).join("\n\n");
|
|
146
|
-
|
|
147
|
-
const val = value as Record<string, unknown> | undefined;
|
|
148
|
-
|
|
149
|
-
// Author extraction - covers several common Sanity schemas.
|
|
150
|
-
// Note: Sanity references aren't auto-resolved by useDocumentPane; we detect them
|
|
151
|
-
// separately so the audit doesn't flag ref-based authors as "Missing".
|
|
152
|
-
let authorName: string | undefined;
|
|
153
|
-
let authorCredentials: string | undefined;
|
|
154
|
-
let authorBioUrl: string | undefined;
|
|
155
|
-
let authorIsReference = false;
|
|
156
|
-
const author = (val?.author || (Array.isArray(val?.authors) && (val.authors as unknown[])[0]) || val?.byline) as
|
|
157
|
-
| Record<string, unknown>
|
|
158
|
-
| string
|
|
159
|
-
| undefined;
|
|
160
|
-
if (typeof author === "string") {
|
|
161
|
-
authorName = author;
|
|
162
|
-
} else if (author && typeof author === "object") {
|
|
163
|
-
authorName =
|
|
164
|
-
(author.name as string | undefined) ||
|
|
165
|
-
(author.fullName as string | undefined) ||
|
|
166
|
-
(author.displayName as string | undefined);
|
|
167
|
-
authorCredentials =
|
|
168
|
-
(author.credentials as string | undefined) ||
|
|
169
|
-
(author.title as string | undefined) ||
|
|
170
|
-
(author.suffix as string | undefined);
|
|
171
|
-
authorBioUrl = (author.bioUrl as string | undefined) || ((author.slug as { current?: string })?.current ? `/author/${(author.slug as { current?: string }).current}` : undefined);
|
|
172
|
-
// Sanity reference: { _type: 'reference', _ref: '...' } with no inline name
|
|
173
|
-
if (!authorName && typeof author._ref === "string") {
|
|
174
|
-
authorIsReference = true;
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
|
|
179
|
-
const fields: DocumentFields = {
|
|
180
|
-
title: title || undefined,
|
|
181
|
-
metaDescription: (val?.metaDescription || val?.summary || val?.description || val?.seoDescription) as string | undefined,
|
|
182
|
-
slug: (val?.slug as { current?: string })?.current || undefined,
|
|
183
|
-
imageNames: imageMeta.names,
|
|
184
|
-
imageTitles: imageMeta.titles,
|
|
185
|
-
imageCount: imageMeta.count,
|
|
186
|
-
headings: extractHeadings(body),
|
|
187
|
-
headingsDetailed: extractHeadingsDetailed(body),
|
|
188
|
-
bodyLinks: extractBodyLinks(body),
|
|
189
|
-
contentCategory: (val?.contentCategory || val?.category) as string | undefined,
|
|
190
|
-
contentPlacement: Array.isArray(val?.contentPlacement) ? (val.contentPlacement as string[]) : undefined,
|
|
191
|
-
authorName,
|
|
192
|
-
authorCredentials,
|
|
193
|
-
authorBioUrl,
|
|
194
|
-
authorIsReference,
|
|
195
|
-
publishedAt: (val?.publishedAt || val?.publishDate || val?._createdAt) as string | undefined,
|
|
196
|
-
updatedAt: (val?.updatedAt || val?._updatedAt) as string | undefined,
|
|
197
|
-
lastReviewedAt: (val?.lastReviewedAt || val?.lastReviewed || val?.medicallyReviewedAt) as string | undefined,
|
|
198
|
-
};
|
|
199
|
-
|
|
200
|
-
// documentFields are cheap and shown immediately so the Technical tab doesn't flash
|
|
201
|
-
// "Missing" cards while the text debounce is pending. Only debounce text since that
|
|
202
|
-
// drives the expensive AI analysis calls.
|
|
203
|
-
setDocumentFields(fields);
|
|
204
|
-
|
|
205
|
-
if (timerRef.current) clearTimeout(timerRef.current);
|
|
206
|
-
|
|
207
|
-
timerRef.current = setTimeout(() => {
|
|
208
|
-
setDebouncedText(fullText);
|
|
209
|
-
setIsLoading(false);
|
|
210
|
-
}, 2000);
|
|
211
|
-
|
|
212
|
-
return () => { if (timerRef.current) clearTimeout(timerRef.current); };
|
|
213
|
-
}, [title, body, value]);
|
|
214
|
-
|
|
215
|
-
return { text: debouncedText, isLoading, documentFields, documentId };
|
|
216
|
-
}
|
|
1
|
+
import { useState, useEffect, useRef } from "react";
|
|
2
|
+
import { useDocumentPane } from "sanity/structure";
|
|
3
|
+
import type { DocumentFields } from "../lib/types";
|
|
4
|
+
import { extractText, buildDocumentFields } from "../lib/documentExtract";
|
|
5
|
+
|
|
6
|
+
export function useDocumentContent(): { text: string; isLoading: boolean; documentFields: DocumentFields; documentId: string | undefined } {
|
|
7
|
+
const { value, ready } = useDocumentPane();
|
|
8
|
+
const documentId = (value?._id as string | undefined) || undefined;
|
|
9
|
+
const title = value?.title as string | undefined;
|
|
10
|
+
const body = value?.body;
|
|
11
|
+
const [debouncedText, setDebouncedText] = useState("");
|
|
12
|
+
const [isLoading, setIsLoading] = useState(!ready);
|
|
13
|
+
const [documentFields, setDocumentFields] = useState<DocumentFields>({});
|
|
14
|
+
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
15
|
+
const prevDocIdRef = useRef<string | undefined>(documentId);
|
|
16
|
+
|
|
17
|
+
// Reset loading state on doc switch so downstream tabs can show their own loading UI
|
|
18
|
+
// instead of flashing "Missing" cards based on the previous doc's data.
|
|
19
|
+
useEffect(() => {
|
|
20
|
+
if (prevDocIdRef.current !== documentId) {
|
|
21
|
+
prevDocIdRef.current = documentId;
|
|
22
|
+
setIsLoading(true);
|
|
23
|
+
}
|
|
24
|
+
}, [documentId]);
|
|
25
|
+
|
|
26
|
+
useEffect(() => {
|
|
27
|
+
const bodyText = extractText(body);
|
|
28
|
+
const fullText = [title, bodyText].filter(Boolean).join("\n\n");
|
|
29
|
+
const fields = buildDocumentFields(value as Record<string, unknown> | undefined);
|
|
30
|
+
|
|
31
|
+
// documentFields are cheap and shown immediately so the Technical tab doesn't flash
|
|
32
|
+
// "Missing" cards while the text debounce is pending. Only debounce text since that
|
|
33
|
+
// drives the expensive AI analysis calls.
|
|
34
|
+
setDocumentFields(fields);
|
|
35
|
+
|
|
36
|
+
if (timerRef.current) clearTimeout(timerRef.current);
|
|
37
|
+
|
|
38
|
+
timerRef.current = setTimeout(() => {
|
|
39
|
+
setDebouncedText(fullText);
|
|
40
|
+
setIsLoading(false);
|
|
41
|
+
}, 2000);
|
|
42
|
+
|
|
43
|
+
return () => { if (timerRef.current) clearTimeout(timerRef.current); };
|
|
44
|
+
}, [title, body, value]);
|
|
45
|
+
|
|
46
|
+
return { text: debouncedText, isLoading, documentFields, documentId };
|
|
47
|
+
}
|
|
@@ -79,6 +79,7 @@ export function useKeywordAnalysis(
|
|
|
79
79
|
cacheInitializedRef.current = true;
|
|
80
80
|
return;
|
|
81
81
|
}
|
|
82
|
+
docVersionRef.current += 1;
|
|
82
83
|
const fresh = loadCached();
|
|
83
84
|
cached.current = fresh;
|
|
84
85
|
setAnalysisRaw(fresh.analysis);
|
|
@@ -120,6 +121,11 @@ export function useKeywordAnalysis(
|
|
|
120
121
|
}, [text, deepAnalysis, aeoTextSnapshot]);
|
|
121
122
|
|
|
122
123
|
const lastAnalysisRef = useRef<SEOAnalysis | null>(null);
|
|
124
|
+
// Bumped on every document switch; the async resolvers below bail if their
|
|
125
|
+
// captured version is stale, so a slow deep-analysis or volume lookup from a
|
|
126
|
+
// previous document can't write its result onto the document the editor
|
|
127
|
+
// switched to (the regular analysis effect already guards this via `cancelled`).
|
|
128
|
+
const docVersionRef = useRef(0);
|
|
123
129
|
|
|
124
130
|
useEffect(() => {
|
|
125
131
|
if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
|
|
@@ -169,6 +175,7 @@ export function useKeywordAnalysis(
|
|
|
169
175
|
|
|
170
176
|
const doVolumeLookup = useCallback((analysisResult: SEOAnalysis, terms?: string[]) => {
|
|
171
177
|
setIsVolumesLoading(true);
|
|
178
|
+
const myVersion = docVersionRef.current;
|
|
172
179
|
|
|
173
180
|
const lookupTerms = terms || (() => {
|
|
174
181
|
const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
|
|
@@ -189,6 +196,7 @@ export function useKeywordAnalysis(
|
|
|
189
196
|
|
|
190
197
|
lookupKeywords(apiUrl, lookupTerms)
|
|
191
198
|
.then(({ results }) => {
|
|
199
|
+
if (docVersionRef.current !== myVersion) return; // document switched - drop stale volumes
|
|
192
200
|
// Add new results to persistent cache
|
|
193
201
|
results.forEach((r) => volumeMapRef.current.set(r.keyword.toLowerCase(), r));
|
|
194
202
|
// Re-apply all cached volumes to current analysis
|
|
@@ -203,6 +211,7 @@ export function useKeywordAnalysis(
|
|
|
203
211
|
setIsVolumesLoading(false);
|
|
204
212
|
})
|
|
205
213
|
.catch(() => {
|
|
214
|
+
if (docVersionRef.current !== myVersion) return;
|
|
206
215
|
setIsVolumesLoading(false);
|
|
207
216
|
});
|
|
208
217
|
}, [apiUrl, cacheKey]);
|
|
@@ -221,12 +230,15 @@ export function useKeywordAnalysis(
|
|
|
221
230
|
setAeoContentChanged(false);
|
|
222
231
|
setAeoTextSnapshot(text);
|
|
223
232
|
|
|
233
|
+
const myVersion = docVersionRef.current;
|
|
224
234
|
fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary)
|
|
225
235
|
.then((result) => {
|
|
236
|
+
if (docVersionRef.current !== myVersion) return; // document switched - drop stale result
|
|
226
237
|
setDeepAnalysis(result as DeepAnalysis);
|
|
227
238
|
setIsDeepLoading(false);
|
|
228
239
|
})
|
|
229
240
|
.catch((err) => {
|
|
241
|
+
if (docVersionRef.current !== myVersion) return;
|
|
230
242
|
setError(err.message);
|
|
231
243
|
setIsDeepLoading(false);
|
|
232
244
|
});
|
package/src/hooks/useSEOChat.ts
CHANGED
|
@@ -116,6 +116,7 @@ export function useSEOChat(
|
|
|
116
116
|
|
|
117
117
|
const sendMessage = useCallback(
|
|
118
118
|
async (text: string) => {
|
|
119
|
+
const myVersion = opVersionRef.current;
|
|
119
120
|
const userMessage: ChatMessage = { role: "user", content: text };
|
|
120
121
|
const updatedMessages = [...messages, userMessage];
|
|
121
122
|
setMessages(updatedMessages);
|
|
@@ -139,12 +140,17 @@ export function useSEOChat(
|
|
|
139
140
|
const decoder = new TextDecoder();
|
|
140
141
|
let assistantContent = "";
|
|
141
142
|
|
|
143
|
+
// If the editor switched documents while the request was in flight, stop -
|
|
144
|
+
// don't inject this stream into the new document's chat.
|
|
145
|
+
if (opVersionRef.current !== myVersion) { try { await reader.cancel(); } catch {} setIsStreaming(false); return; }
|
|
146
|
+
|
|
142
147
|
// Add empty assistant message that we'll update
|
|
143
148
|
setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
|
|
144
149
|
|
|
145
150
|
while (true) {
|
|
146
151
|
const { done, value } = await reader.read();
|
|
147
152
|
if (done) break;
|
|
153
|
+
if (opVersionRef.current !== myVersion) { try { await reader.cancel(); } catch {} break; } // doc switched mid-stream
|
|
148
154
|
|
|
149
155
|
const chunk = decoder.decode(value, { stream: true });
|
|
150
156
|
const lines = chunk.split("\n");
|
|
@@ -174,13 +180,16 @@ export function useSEOChat(
|
|
|
174
180
|
}
|
|
175
181
|
}
|
|
176
182
|
|
|
177
|
-
// Save history after stream completes
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
+
// Save history after stream completes (skip if the doc was switched away).
|
|
184
|
+
if (opVersionRef.current === myVersion) {
|
|
185
|
+
const finalMessages: ChatMessage[] = [
|
|
186
|
+
...updatedMessages,
|
|
187
|
+
{ role: "assistant", content: assistantContent },
|
|
188
|
+
];
|
|
189
|
+
scheduleSave(finalMessages);
|
|
190
|
+
}
|
|
183
191
|
} catch (err) {
|
|
192
|
+
if (opVersionRef.current !== myVersion) { setIsStreaming(false); return; }
|
|
184
193
|
const errorMsg = err instanceof Error ? err.message : "Chat failed";
|
|
185
194
|
setMessages((prev) => [
|
|
186
195
|
...prev,
|
|
@@ -188,7 +197,7 @@ export function useSEOChat(
|
|
|
188
197
|
]);
|
|
189
198
|
}
|
|
190
199
|
|
|
191
|
-
setIsStreaming(false);
|
|
200
|
+
if (opVersionRef.current === myVersion) setIsStreaming(false);
|
|
192
201
|
},
|
|
193
202
|
[messages, apiUrl, documentText, publication, keywordPanelData, scheduleSave]
|
|
194
203
|
);
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// Pure document-parsing helpers, split out of useDocumentContent so they can be
|
|
2
|
+
// unit-tested without a React / Sanity Studio runtime. No imports from "react"
|
|
3
|
+
// or "sanity" here - everything operates on plain Sanity document values.
|
|
4
|
+
|
|
5
|
+
import type { DocumentFields, HeadingItem } from "./types";
|
|
6
|
+
|
|
7
|
+
interface PortableTextSpan {
|
|
8
|
+
_type: string;
|
|
9
|
+
text?: string;
|
|
10
|
+
marks?: string[];
|
|
11
|
+
children?: PortableTextSpan[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface PortableTextMarkDef {
|
|
15
|
+
_key: string;
|
|
16
|
+
_type: string;
|
|
17
|
+
href?: string;
|
|
18
|
+
url?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface PortableTextBlock {
|
|
22
|
+
_type: string;
|
|
23
|
+
style?: string;
|
|
24
|
+
children?: PortableTextSpan[];
|
|
25
|
+
markDefs?: PortableTextMarkDef[];
|
|
26
|
+
text?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function extractText(blocks: unknown): string {
|
|
30
|
+
if (!blocks || !Array.isArray(blocks)) return "";
|
|
31
|
+
const parts: string[] = [];
|
|
32
|
+
for (const block of blocks as PortableTextBlock[]) {
|
|
33
|
+
if (block._type === "block" && block.children) {
|
|
34
|
+
const blockText = block.children.map((child) => child.text || "").join("");
|
|
35
|
+
if (blockText) parts.push(blockText);
|
|
36
|
+
} else if (typeof block === "string") {
|
|
37
|
+
parts.push(block);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return parts.join("\n");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function extractHeadings(blocks: unknown): string[] {
|
|
44
|
+
if (!blocks || !Array.isArray(blocks)) return [];
|
|
45
|
+
const headings: string[] = [];
|
|
46
|
+
for (const block of blocks as PortableTextBlock[]) {
|
|
47
|
+
if (block._type === "block" && block.style && /^h[1-6]$/.test(block.style) && block.children) {
|
|
48
|
+
const text = block.children.map((child) => child.text || "").join("");
|
|
49
|
+
if (text) headings.push(text);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return headings;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Headings with their numeric level (1-6), so the Technical tab can audit hierarchy.
|
|
56
|
+
export function extractHeadingsDetailed(blocks: unknown): HeadingItem[] {
|
|
57
|
+
if (!blocks || !Array.isArray(blocks)) return [];
|
|
58
|
+
const out: HeadingItem[] = [];
|
|
59
|
+
for (const block of blocks as PortableTextBlock[]) {
|
|
60
|
+
if (block._type === "block" && block.style && /^h[1-6]$/.test(block.style) && block.children) {
|
|
61
|
+
const text = block.children.map((child) => child.text || "").join("").trim();
|
|
62
|
+
const level = Number(block.style.slice(1));
|
|
63
|
+
// Include empty headings too - the Technical tab flags them.
|
|
64
|
+
out.push({ text, level });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Every URL the editor has linked from this article body. Sanity stores them
|
|
71
|
+
// in Portable Text markDefs (with _type: "link" and href/url). We also catch
|
|
72
|
+
// inline plain-text URLs as a fallback.
|
|
73
|
+
export function extractBodyLinks(blocks: unknown): string[] {
|
|
74
|
+
const urls = new Set<string>();
|
|
75
|
+
if (Array.isArray(blocks)) {
|
|
76
|
+
for (const block of blocks as PortableTextBlock[]) {
|
|
77
|
+
if (block._type === "block" && Array.isArray(block.markDefs)) {
|
|
78
|
+
for (const md of block.markDefs) {
|
|
79
|
+
const href = md.href || md.url;
|
|
80
|
+
if (typeof href === "string" && /^https?:\/\//i.test(href)) {
|
|
81
|
+
urls.add(href.trim());
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// Inline URLs that aren't in a link annotation - rare but possible.
|
|
88
|
+
if (Array.isArray(blocks)) {
|
|
89
|
+
for (const block of blocks as PortableTextBlock[]) {
|
|
90
|
+
if (block._type === "block" && Array.isArray(block.children)) {
|
|
91
|
+
const blockText = block.children.map((c) => c.text || "").join(" ");
|
|
92
|
+
const matches = blockText.match(/https?:\/\/[^\s"'<>)\]]+/g);
|
|
93
|
+
if (matches) matches.forEach((u) => urls.add(u.replace(/[.,;:!?]+$/, "")));
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return Array.from(urls);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Slug detection across the common schema shapes. Looks for, in order:
|
|
101
|
+
// 1) A Sanity `slug` type object on any of several field names. MJH stores the
|
|
102
|
+
// slug at `url.current` (a Sanity slug type named "url"); the standard
|
|
103
|
+
// convention is `slug.current`. Check both, plus a few common variants.
|
|
104
|
+
// 2) Plain-string fields under common slug field names (fallback for schemas
|
|
105
|
+
// that store the slug as a flat string).
|
|
106
|
+
// We only accept a string if it looks slug-shaped (lowercase/hyphens, no spaces,
|
|
107
|
+
// no protocol) so we don't mistake a fully-qualified URL for a slug.
|
|
108
|
+
export function detectSlug(val: Record<string, unknown> | undefined): string | undefined {
|
|
109
|
+
if (!val) return undefined;
|
|
110
|
+
// Sanity slug-type objects: { _type: "slug", current: "..." }
|
|
111
|
+
const slugTypeFields = ["slug", "url", "urlSlug", "permalink", "pathname"];
|
|
112
|
+
for (const f of slugTypeFields) {
|
|
113
|
+
const obj = val[f] as { current?: unknown } | undefined;
|
|
114
|
+
if (obj && typeof obj === "object" && typeof obj.current === "string" && obj.current.trim()) {
|
|
115
|
+
return obj.current.trim();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// Plain-string fallbacks
|
|
119
|
+
const stringFields = ["urlSlug", "url", "URL", "path", "permalink", "pathname"];
|
|
120
|
+
const slugShape = /^[a-z0-9._~-]+(?:\/[a-z0-9._~-]+)*\/?$/i;
|
|
121
|
+
for (const f of stringFields) {
|
|
122
|
+
const v = val[f];
|
|
123
|
+
if (typeof v === "string") {
|
|
124
|
+
const trimmed = v.trim();
|
|
125
|
+
if (trimmed && !/^https?:\/\//i.test(trimmed) && slugShape.test(trimmed)) {
|
|
126
|
+
return trimmed;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return undefined;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Author detection across a broad set of schema shapes. Tries every reasonable
|
|
134
|
+
// field name, handles inline strings, inline objects, and Sanity references
|
|
135
|
+
// (which we can't resolve here, so we mark them so the audit doesn't shout
|
|
136
|
+
// "Missing").
|
|
137
|
+
export function detectAuthor(val: Record<string, unknown> | undefined): {
|
|
138
|
+
authorName?: string;
|
|
139
|
+
authorCredentials?: string;
|
|
140
|
+
authorBioUrl?: string;
|
|
141
|
+
authorIsReference: boolean;
|
|
142
|
+
} {
|
|
143
|
+
if (!val) return { authorIsReference: false };
|
|
144
|
+
const candidateFields = [
|
|
145
|
+
"author", "authors", "byline", "articleAuthor", "primaryAuthor",
|
|
146
|
+
"writer", "writers", "contributor", "contributors",
|
|
147
|
+
"authorMapping", // MJH schema - array of author references
|
|
148
|
+
"Author", "Authors", // PascalCase variants
|
|
149
|
+
];
|
|
150
|
+
for (const f of candidateFields) {
|
|
151
|
+
const raw = val[f];
|
|
152
|
+
if (!raw) continue;
|
|
153
|
+
const first = Array.isArray(raw) ? raw[0] : raw;
|
|
154
|
+
if (!first) continue;
|
|
155
|
+
if (typeof first === "string") {
|
|
156
|
+
const trimmed = first.trim();
|
|
157
|
+
if (trimmed) return { authorName: trimmed, authorIsReference: false };
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (typeof first === "object" && first !== null) {
|
|
161
|
+
const o = first as Record<string, unknown>;
|
|
162
|
+
const name = (o.name || o.fullName || o.displayName) as string | undefined;
|
|
163
|
+
const creds = (o.credentials || o.title || o.suffix) as string | undefined;
|
|
164
|
+
const slug = (o.slug as { current?: string } | undefined)?.current;
|
|
165
|
+
const bio = (o.bioUrl as string | undefined) || (slug ? `/author/${slug}` : undefined);
|
|
166
|
+
if (name) {
|
|
167
|
+
return { authorName: name, authorCredentials: creds, authorBioUrl: bio, authorIsReference: false };
|
|
168
|
+
}
|
|
169
|
+
// Reference shape - has _ref, or is typed as a reference.
|
|
170
|
+
if (typeof o._ref === "string" || o._type === "reference") {
|
|
171
|
+
return { authorIsReference: true };
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return { authorIsReference: false };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Extracts image metadata from top-level image fields AND inline body
|
|
179
|
+
// figure/image blocks (where MJH stores article images):
|
|
180
|
+
// - names: alt text + asset filename (for the alt + filename audits)
|
|
181
|
+
// - titles: the `title` field on the image object or asset (the hover tooltip)
|
|
182
|
+
// - count: number of real images found (so the title audit can say "X of N")
|
|
183
|
+
export function extractImageMeta(value: Record<string, unknown>): { names: string[]; titles: string[]; count: number } {
|
|
184
|
+
const names: string[] = [];
|
|
185
|
+
const titles: string[] = [];
|
|
186
|
+
let count = 0;
|
|
187
|
+
const imageFields = ["mainImage", "image", "heroImage", "thumbnail", "featuredImage"];
|
|
188
|
+
for (const field of imageFields) {
|
|
189
|
+
const img = value[field] as Record<string, unknown> | undefined;
|
|
190
|
+
if (!img || typeof img !== "object") continue;
|
|
191
|
+
const asset = img.asset && typeof img.asset === "object" ? (img.asset as Record<string, unknown>) : undefined;
|
|
192
|
+
// Only count entries that are actually images (have an asset or an image _type).
|
|
193
|
+
if (!asset && img._type !== "image") continue;
|
|
194
|
+
count++;
|
|
195
|
+
if (typeof img.alt === "string" && img.alt) names.push(img.alt);
|
|
196
|
+
if (asset && typeof asset.originalFilename === "string" && asset.originalFilename) names.push(asset.originalFilename);
|
|
197
|
+
// The hover-tooltip title can live on the image object or on the asset.
|
|
198
|
+
if (typeof img.title === "string" && img.title) titles.push(img.title);
|
|
199
|
+
else if (asset && typeof asset.title === "string" && asset.title) titles.push(asset.title);
|
|
200
|
+
}
|
|
201
|
+
// Inline body images: MJH (and most editorial schemas) embed article images as
|
|
202
|
+
// `figure`/`image` blocks INSIDE the Portable Text body, not as a top-level
|
|
203
|
+
// field. Without this walk the entire image audit (count, alt, title) is blind
|
|
204
|
+
// to the images that are actually in the article.
|
|
205
|
+
const body = value.body;
|
|
206
|
+
if (Array.isArray(body)) {
|
|
207
|
+
for (const blk of body) {
|
|
208
|
+
if (!blk || typeof blk !== "object") continue;
|
|
209
|
+
const b = blk as Record<string, unknown>;
|
|
210
|
+
if (b._type !== "figure" && b._type !== "image") continue;
|
|
211
|
+
const asset = b.asset && typeof b.asset === "object" ? (b.asset as Record<string, unknown>) : undefined;
|
|
212
|
+
if (!asset && b._type !== "image") continue;
|
|
213
|
+
count++;
|
|
214
|
+
if (typeof b.alt === "string" && b.alt) names.push(b.alt);
|
|
215
|
+
// Asset is usually an unresolved reference here, so originalFilename is
|
|
216
|
+
// rarely present - push it only when the studio expanded the asset.
|
|
217
|
+
if (asset && typeof asset.originalFilename === "string" && asset.originalFilename) names.push(asset.originalFilename);
|
|
218
|
+
if (typeof b.title === "string" && b.title) titles.push(b.title);
|
|
219
|
+
else if (asset && typeof asset.title === "string" && asset.title) titles.push(asset.title);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return { names, titles, count };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Assembles the full DocumentFields object from a raw Sanity document value.
|
|
226
|
+
// Pure + side-effect-free so it can be exercised against real fetched documents.
|
|
227
|
+
export function buildDocumentFields(value: Record<string, unknown> | undefined): DocumentFields {
|
|
228
|
+
const val = value;
|
|
229
|
+
const title = val?.title as string | undefined;
|
|
230
|
+
const body = val?.body;
|
|
231
|
+
const { authorName, authorCredentials, authorBioUrl, authorIsReference } = detectAuthor(val);
|
|
232
|
+
const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
|
|
233
|
+
return {
|
|
234
|
+
title: title || undefined,
|
|
235
|
+
// MJH uses `summary`; standard Sanity SEO plugins use `metaDescription`
|
|
236
|
+
metaDescription: (val?.metaDescription || val?.summary || val?.description || val?.seoDescription) as string | undefined,
|
|
237
|
+
slug: detectSlug(val),
|
|
238
|
+
imageNames: imageMeta.names,
|
|
239
|
+
imageTitles: imageMeta.titles,
|
|
240
|
+
imageCount: imageMeta.count,
|
|
241
|
+
headings: extractHeadings(body),
|
|
242
|
+
headingsDetailed: extractHeadingsDetailed(body),
|
|
243
|
+
bodyLinks: extractBodyLinks(body),
|
|
244
|
+
contentCategory: (val?.contentCategory || val?.category) as string | undefined,
|
|
245
|
+
contentPlacement: Array.isArray(val?.contentPlacement) ? (val.contentPlacement as string[]) : undefined,
|
|
246
|
+
authorName,
|
|
247
|
+
authorCredentials,
|
|
248
|
+
authorBioUrl,
|
|
249
|
+
authorIsReference,
|
|
250
|
+
// `published` is MJH's date field; `publishedAt`/`publishDate` cover other schemas
|
|
251
|
+
publishedAt: (val?.published || val?.publishedAt || val?.publishDate || val?._createdAt) as string | undefined,
|
|
252
|
+
// `updatedOn` is MJH's "Updated On" field. `updatedAt` is the standard Sanity convention.
|
|
253
|
+
// `_updatedAt` is the Sanity-managed timestamp as a final fallback.
|
|
254
|
+
updatedAt: (val?.updatedOn || val?.updatedAt || val?._updatedAt) as string | undefined,
|
|
255
|
+
lastReviewedAt: (val?.lastReviewedAt || val?.lastReviewed || val?.medicallyReviewedAt) as string | undefined,
|
|
256
|
+
};
|
|
257
|
+
}
|