sanity-plugin-seo-copilot 0.2.1 → 0.2.7

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.
@@ -79,6 +79,9 @@ export function useKeywordAnalysis(
79
79
  cacheInitializedRef.current = true;
80
80
  return;
81
81
  }
82
+ docVersionRef.current += 1;
83
+ volumeAbortRef.current?.abort();
84
+ volumeAbortRef.current = null;
82
85
  const fresh = loadCached();
83
86
  cached.current = fresh;
84
87
  setAnalysisRaw(fresh.analysis);
@@ -120,6 +123,14 @@ export function useKeywordAnalysis(
120
123
  }, [text, deepAnalysis, aeoTextSnapshot]);
121
124
 
122
125
  const lastAnalysisRef = useRef<SEOAnalysis | null>(null);
126
+ // Bumped on every document switch; the async resolvers below bail if their
127
+ // captured version is stale, so a slow deep-analysis or volume lookup from a
128
+ // previous document can't write its result onto the document the editor
129
+ // switched to (the regular analysis effect already guards this via `cancelled`).
130
+ const docVersionRef = useRef(0);
131
+ // AbortController for the in-flight volume lookup. Cancelled on doc switch and
132
+ // before each new lookup so only one lookup is ever outstanding at a time.
133
+ const volumeAbortRef = useRef<AbortController | null>(null);
123
134
 
124
135
  useEffect(() => {
125
136
  if ((!text || text.trim().length < 20) && (!effectiveSeeds || effectiveSeeds.length === 0)) {
@@ -128,10 +139,11 @@ export function useKeywordAnalysis(
128
139
  }
129
140
 
130
141
  let cancelled = false;
142
+ const controller = new AbortController();
131
143
  setIsLoading(true);
132
144
  setError(null);
133
145
 
134
- fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary)
146
+ fetchAnalysis(apiUrl, text, "realtime", publication, effectiveSeeds, documentFields, focusPrimary, controller.signal)
135
147
  .then((result) => {
136
148
  if (cancelled) return;
137
149
  const analysisResult = result as SEOAnalysis;
@@ -156,6 +168,7 @@ export function useKeywordAnalysis(
156
168
  }
157
169
  })
158
170
  .catch((err) => {
171
+ if (err instanceof Error && err.name === "AbortError") return;
159
172
  if (!cancelled) {
160
173
  setError(err.message);
161
174
  setIsLoading(false);
@@ -164,11 +177,16 @@ export function useKeywordAnalysis(
164
177
 
165
178
  return () => {
166
179
  cancelled = true;
180
+ controller.abort();
167
181
  };
168
- }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary]);
182
+ // JSON.stringify(documentFields) used instead of documentFields directly to avoid
183
+ // re-running when the caller creates a new object reference with identical contents.
184
+ // eslint-disable-next-line react-hooks/exhaustive-deps
185
+ }, [text, apiUrl, publication, effectiveSeeds?.join(","), focusPrimary, JSON.stringify(documentFields)]);
169
186
 
170
187
  const doVolumeLookup = useCallback((analysisResult: SEOAnalysis, terms?: string[]) => {
171
188
  setIsVolumesLoading(true);
189
+ const myVersion = docVersionRef.current;
172
190
 
173
191
  const lookupTerms = terms || (() => {
174
192
  const candidateTerms = (analysisResult.primaryKeywordCandidates || []).map((c) => c.term);
@@ -187,8 +205,14 @@ export function useKeywordAnalysis(
187
205
  return;
188
206
  }
189
207
 
190
- lookupKeywords(apiUrl, lookupTerms)
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)
191
214
  .then(({ results }) => {
215
+ if (docVersionRef.current !== myVersion) return; // document switched - drop stale volumes
192
216
  // Add new results to persistent cache
193
217
  results.forEach((r) => volumeMapRef.current.set(r.keyword.toLowerCase(), r));
194
218
  // Re-apply all cached volumes to current analysis
@@ -202,7 +226,9 @@ export function useKeywordAnalysis(
202
226
  } catch { /* ignore */ }
203
227
  setIsVolumesLoading(false);
204
228
  })
205
- .catch(() => {
229
+ .catch((err) => {
230
+ if (err instanceof Error && err.name === "AbortError") return;
231
+ if (docVersionRef.current !== myVersion) return;
206
232
  setIsVolumesLoading(false);
207
233
  });
208
234
  }, [apiUrl, cacheKey]);
@@ -221,12 +247,15 @@ export function useKeywordAnalysis(
221
247
  setAeoContentChanged(false);
222
248
  setAeoTextSnapshot(text);
223
249
 
250
+ const myVersion = docVersionRef.current;
224
251
  fetchAnalysis(apiUrl, text, "deep", publication, effectiveSeeds, documentFields, focusPrimary)
225
252
  .then((result) => {
253
+ if (docVersionRef.current !== myVersion) return; // document switched - drop stale result
226
254
  setDeepAnalysis(result as DeepAnalysis);
227
255
  setIsDeepLoading(false);
228
256
  })
229
257
  .catch((err) => {
258
+ if (docVersionRef.current !== myVersion) return;
230
259
  setError(err.message);
231
260
  setIsDeepLoading(false);
232
261
  });
@@ -46,13 +46,15 @@ export function useSEOChat(
46
46
  }, [chatCacheKey]);
47
47
 
48
48
  const [messages, setMessagesRaw] = useState<ChatMessage[]>(loadCachedMessages);
49
+ // Ref always mirrors messages state so sendMessage doesn't need messages in its
50
+ // dependency array (avoiding a re-creation on every streamed token).
51
+ const messagesRef = useRef<ChatMessage[]>([]);
52
+
53
+ // Simplified wrapper - localStorage persistence moved to a debounced useEffect
54
+ // below so it doesn't fire on every individual token during streaming.
49
55
  const setMessages = useCallback((msgs: ChatMessage[] | ((prev: ChatMessage[]) => ChatMessage[])) => {
50
- setMessagesRaw((prev) => {
51
- const next = typeof msgs === "function" ? msgs(prev) : msgs;
52
- try { localStorage.setItem(chatCacheKey, JSON.stringify(next)); } catch {}
53
- return next;
54
- });
55
- }, [chatCacheKey]);
56
+ setMessagesRaw(msgs);
57
+ }, []);
56
58
 
57
59
  const [isStreaming, setIsStreaming] = useState(false);
58
60
  const [historyLoaded, setHistoryLoaded] = useState(false);
@@ -65,6 +67,30 @@ export function useSEOChat(
65
67
  userId.current = sanityUser.id;
66
68
  }
67
69
  }, [sanityUser?.id]);
70
+
71
+ // Keep messagesRef in sync with state so sendMessage can read current messages
72
+ // without capturing a stale closure value.
73
+ useEffect(() => {
74
+ messagesRef.current = messages;
75
+ }, [messages]);
76
+
77
+ // Persist chat history to localStorage, debounced so we don't write on every
78
+ // individual token during streaming (only once the stream settles).
79
+ useEffect(() => {
80
+ const timer = setTimeout(() => {
81
+ try { localStorage.setItem(chatCacheKey, JSON.stringify(messages)); } catch {}
82
+ }, 500);
83
+ return () => clearTimeout(timer);
84
+ }, [messages, chatCacheKey]);
85
+
86
+ // AbortController for the in-flight chat stream. Aborted on doc switch and unmount.
87
+ const streamAbortRef = useRef<AbortController | null>(null);
88
+
89
+ // Abort any in-flight stream on unmount to prevent state updates on a dead component.
90
+ useEffect(() => {
91
+ return () => { streamAbortRef.current?.abort(); };
92
+ }, []);
93
+
68
94
  const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
69
95
 
70
96
  // Per-document operation version to invalidate stale in-flight loads
@@ -79,6 +105,8 @@ export function useSEOChat(
79
105
  return;
80
106
  }
81
107
  opVersionRef.current += 1;
108
+ streamAbortRef.current?.abort();
109
+ streamAbortRef.current = null;
82
110
  setMessagesRaw(loadCachedMessages());
83
111
  setIsStreaming(false);
84
112
  setHistoryLoaded(false);
@@ -116,18 +144,25 @@ export function useSEOChat(
116
144
 
117
145
  const sendMessage = useCallback(
118
146
  async (text: string) => {
147
+ const myVersion = opVersionRef.current;
119
148
  const userMessage: ChatMessage = { role: "user", content: text };
120
- const updatedMessages = [...messages, userMessage];
149
+ // Read from ref so messages is not needed in the dep array - prevents
150
+ // sendMessage from being recreated on every streamed token.
151
+ const updatedMessages = [...messagesRef.current, userMessage];
121
152
  setMessages(updatedMessages);
122
153
  setIsStreaming(true);
123
154
 
155
+ const controller = new AbortController();
156
+ streamAbortRef.current = controller;
157
+
124
158
  try {
125
159
  const stream = await fetchChatStream(
126
160
  apiUrl,
127
161
  updatedMessages,
128
162
  documentText,
129
163
  publication,
130
- keywordPanelData
164
+ keywordPanelData,
165
+ controller.signal
131
166
  );
132
167
 
133
168
  if (!stream) {
@@ -139,12 +174,17 @@ export function useSEOChat(
139
174
  const decoder = new TextDecoder();
140
175
  let assistantContent = "";
141
176
 
177
+ // If the editor switched documents while the request was in flight, stop -
178
+ // don't inject this stream into the new document's chat.
179
+ if (opVersionRef.current !== myVersion) { try { await reader.cancel(); } catch {} setIsStreaming(false); return; }
180
+
142
181
  // Add empty assistant message that we'll update
143
182
  setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
144
183
 
145
184
  while (true) {
146
185
  const { done, value } = await reader.read();
147
186
  if (done) break;
187
+ if (opVersionRef.current !== myVersion) { try { await reader.cancel(); } catch {} break; } // doc switched mid-stream
148
188
 
149
189
  const chunk = decoder.decode(value, { stream: true });
150
190
  const lines = chunk.split("\n");
@@ -174,13 +214,18 @@ export function useSEOChat(
174
214
  }
175
215
  }
176
216
 
177
- // Save history after stream completes
178
- const finalMessages: ChatMessage[] = [
179
- ...updatedMessages,
180
- { role: "assistant", content: assistantContent },
181
- ];
182
- scheduleSave(finalMessages);
217
+ // Save history after stream completes (skip if the doc was switched away).
218
+ if (opVersionRef.current === myVersion) {
219
+ const finalMessages: ChatMessage[] = [
220
+ ...updatedMessages,
221
+ { role: "assistant", content: assistantContent },
222
+ ];
223
+ scheduleSave(finalMessages);
224
+ }
183
225
  } catch (err) {
226
+ // Abort is silent - happens on doc switch or unmount, not an error for the editor.
227
+ if (err instanceof Error && err.name === "AbortError") { setIsStreaming(false); return; }
228
+ if (opVersionRef.current !== myVersion) { setIsStreaming(false); return; }
184
229
  const errorMsg = err instanceof Error ? err.message : "Chat failed";
185
230
  setMessages((prev) => [
186
231
  ...prev,
@@ -188,9 +233,9 @@ export function useSEOChat(
188
233
  ]);
189
234
  }
190
235
 
191
- setIsStreaming(false);
236
+ if (opVersionRef.current === myVersion) setIsStreaming(false);
192
237
  },
193
- [messages, apiUrl, documentText, publication, keywordPanelData, scheduleSave]
238
+ [apiUrl, documentText, publication, keywordPanelData, scheduleSave]
194
239
  );
195
240
 
196
241
  const clearChat = useCallback(() => {
package/src/lib/api.ts CHANGED
@@ -29,19 +29,24 @@ export async function fetchAnalysis(
29
29
  publication?: string,
30
30
  seedKeywords?: string[],
31
31
  documentFields?: DocumentFields,
32
- focusKeyword?: string
32
+ focusKeyword?: string,
33
+ signal?: AbortSignal
33
34
  ): Promise<SEOAnalysis | DeepAnalysis> {
34
35
  const response = await fetch(`${apiUrl}/api/seo-copilot/analyze`, {
35
36
  method: "POST",
36
37
  headers: { "Content-Type": "application/json" },
37
38
  body: JSON.stringify({ content, mode, publication, seedKeywords, documentFields, focusKeyword }),
39
+ signal,
38
40
  });
39
41
 
40
42
  const text = await response.text();
41
43
 
42
44
  if (!response.ok) {
43
45
  const err = safeParseJson<{ error?: string }>(text);
44
- throw new Error(err.error || `HTTP ${response.status}`);
46
+ console.error("[seo-copilot] analyze error", response.status, err.error);
47
+ if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
48
+ if (response.status >= 500) throw new Error("Could not reach the SEO service.");
49
+ throw new Error("Something went wrong analyzing this document.");
45
50
  }
46
51
 
47
52
  return safeParseJson<SEOAnalysis | DeepAnalysis>(text);
@@ -59,17 +64,22 @@ export async function fetchChatStream(
59
64
  aeoData?: {
60
65
  questionHeadings: { suggestedHeading: string; rationale: string }[];
61
66
  };
62
- }
67
+ },
68
+ signal?: AbortSignal
63
69
  ): Promise<ReadableStream<Uint8Array> | null> {
64
70
  const response = await fetch(`${apiUrl}/api/seo-copilot/chat`, {
65
71
  method: "POST",
66
72
  headers: { "Content-Type": "application/json" },
67
73
  body: JSON.stringify({ messages, documentContext, publication, keywordPanelData }),
74
+ signal,
68
75
  });
69
76
 
70
77
  if (!response.ok) {
71
78
  const err = await response.json().catch(() => ({ error: "Request failed" }));
72
- throw new Error(err.error || `HTTP ${response.status}`);
79
+ console.error("[seo-copilot] chat error", response.status, err.error);
80
+ if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
81
+ if (response.status >= 500) throw new Error("Could not reach the SEO service.");
82
+ throw new Error("Something went wrong. Please try again.");
73
83
  }
74
84
 
75
85
  return response.body;
@@ -87,7 +97,10 @@ export async function fetchQuestions(
87
97
 
88
98
  if (!response.ok) {
89
99
  const err = await response.json().catch(() => ({ error: "Request failed" }));
90
- throw new Error(err.error || `HTTP ${response.status}`);
100
+ console.error("[seo-copilot] questions error", response.status, err.error);
101
+ if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
102
+ if (response.status >= 500) throw new Error("Could not reach the SEO service.");
103
+ throw new Error("Something went wrong. Please try again.");
91
104
  }
92
105
 
93
106
  return response.json();
@@ -106,17 +119,22 @@ export async function submitFeedback(
106
119
 
107
120
  export async function lookupKeywords(
108
121
  apiUrl: string,
109
- keywords: string[]
122
+ keywords: string[],
123
+ signal?: AbortSignal
110
124
  ): Promise<{ results: { keyword: string; volume: number; cpc: number; competition: number }[]; apiUnitsUsed: number }> {
111
125
  const response = await fetch(`${apiUrl}/api/seo-copilot/keywords`, {
112
126
  method: "POST",
113
127
  headers: { "Content-Type": "application/json" },
114
128
  body: JSON.stringify({ keywords }),
129
+ signal,
115
130
  });
116
131
 
117
132
  if (!response.ok) {
118
133
  const err = await response.json().catch(() => ({ error: "Request failed" }));
119
- throw new Error(err.error || `HTTP ${response.status}`);
134
+ console.error("[seo-copilot] keywords error", response.status, err.error);
135
+ if (response.status === 429) throw new Error("Analysis service is busy. Please try again.");
136
+ if (response.status >= 500) throw new Error("Could not reach the SEO service.");
137
+ throw new Error("Something went wrong. Please try again.");
120
138
  }
121
139
 
122
140
  return response.json();
@@ -0,0 +1,268 @@
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
+ // Also scan any field whose NAME mentions author/byline (covers MJH's exact
151
+ // field name whatever it turns out to be), but never the fact-check / reviewer
152
+ // fields - those aren't the visible byline. This is why a referenced author was
153
+ // showing as "Missing": the real field name wasn't in the fixed list above.
154
+ const dynamic = Object.keys(val).filter(
155
+ // Author/byline-ish names, but never fact-check/reviewer fields, nor image/url/
156
+ // id sidecars (e.g. authorPhoto, authorImageUrl, authorId) that could otherwise
157
+ // be mistaken for a reference-typed author.
158
+ (k) => /author|byline/i.test(k) && !/fact|check|review|photo|image|avatar|picture|url|link|count|id$/i.test(k)
159
+ );
160
+ const fields = Array.from(new Set([...candidateFields, ...dynamic]));
161
+ for (const f of fields) {
162
+ const raw = val[f];
163
+ if (!raw) continue;
164
+ const first = Array.isArray(raw) ? raw[0] : raw;
165
+ if (!first) continue;
166
+ if (typeof first === "string") {
167
+ const trimmed = first.trim();
168
+ if (trimmed) return { authorName: trimmed, authorIsReference: false };
169
+ continue;
170
+ }
171
+ if (typeof first === "object" && first !== null) {
172
+ const o = first as Record<string, unknown>;
173
+ const name = (o.name || o.fullName || o.displayName) as string | undefined;
174
+ const creds = (o.credentials || o.title || o.suffix) as string | undefined;
175
+ const slug = (o.slug as { current?: string } | undefined)?.current;
176
+ const bio = (o.bioUrl as string | undefined) || (slug ? `/author/${slug}` : undefined);
177
+ if (name) {
178
+ return { authorName: name, authorCredentials: creds, authorBioUrl: bio, authorIsReference: false };
179
+ }
180
+ // Reference shape - has _ref, or is typed as a reference.
181
+ if (typeof o._ref === "string" || o._type === "reference") {
182
+ return { authorIsReference: true };
183
+ }
184
+ }
185
+ }
186
+ return { authorIsReference: false };
187
+ }
188
+
189
+ // Extracts image metadata from top-level image fields AND inline body
190
+ // figure/image blocks (where MJH stores article images):
191
+ // - names: alt text + asset filename (for the alt + filename audits)
192
+ // - titles: the `title` field on the image object or asset (the hover tooltip)
193
+ // - count: number of real images found (so the title audit can say "X of N")
194
+ export function extractImageMeta(value: Record<string, unknown>): { names: string[]; titles: string[]; count: number } {
195
+ const names: string[] = [];
196
+ const titles: string[] = [];
197
+ let count = 0;
198
+ const imageFields = ["mainImage", "image", "heroImage", "thumbnail", "featuredImage"];
199
+ for (const field of imageFields) {
200
+ const img = value[field] as Record<string, unknown> | undefined;
201
+ if (!img || typeof img !== "object") continue;
202
+ const asset = img.asset && typeof img.asset === "object" ? (img.asset as Record<string, unknown>) : undefined;
203
+ // Only count entries that are actually images (have an asset or an image _type).
204
+ if (!asset && img._type !== "image") continue;
205
+ count++;
206
+ if (typeof img.alt === "string" && img.alt) names.push(img.alt);
207
+ if (asset && typeof asset.originalFilename === "string" && asset.originalFilename) names.push(asset.originalFilename);
208
+ // The hover-tooltip title can live on the image object or on the asset.
209
+ if (typeof img.title === "string" && img.title) titles.push(img.title);
210
+ else if (asset && typeof asset.title === "string" && asset.title) titles.push(asset.title);
211
+ }
212
+ // Inline body images: MJH (and most editorial schemas) embed article images as
213
+ // `figure`/`image` blocks INSIDE the Portable Text body, not as a top-level
214
+ // field. Without this walk the entire image audit (count, alt, title) is blind
215
+ // to the images that are actually in the article.
216
+ const body = value.body;
217
+ if (Array.isArray(body)) {
218
+ for (const blk of body) {
219
+ if (!blk || typeof blk !== "object") continue;
220
+ const b = blk as Record<string, unknown>;
221
+ if (b._type !== "figure" && b._type !== "image") continue;
222
+ const asset = b.asset && typeof b.asset === "object" ? (b.asset as Record<string, unknown>) : undefined;
223
+ if (!asset && b._type !== "image") continue;
224
+ count++;
225
+ if (typeof b.alt === "string" && b.alt) names.push(b.alt);
226
+ // Asset is usually an unresolved reference here, so originalFilename is
227
+ // rarely present - push it only when the studio expanded the asset.
228
+ if (asset && typeof asset.originalFilename === "string" && asset.originalFilename) names.push(asset.originalFilename);
229
+ if (typeof b.title === "string" && b.title) titles.push(b.title);
230
+ else if (asset && typeof asset.title === "string" && asset.title) titles.push(asset.title);
231
+ }
232
+ }
233
+ return { names, titles, count };
234
+ }
235
+
236
+ // Assembles the full DocumentFields object from a raw Sanity document value.
237
+ // Pure + side-effect-free so it can be exercised against real fetched documents.
238
+ export function buildDocumentFields(value: Record<string, unknown> | undefined): DocumentFields {
239
+ const val = value;
240
+ const title = val?.title as string | undefined;
241
+ const body = val?.body;
242
+ const { authorName, authorCredentials, authorBioUrl, authorIsReference } = detectAuthor(val);
243
+ const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
244
+ return {
245
+ title: title || undefined,
246
+ // MJH uses `summary`; standard Sanity SEO plugins use `metaDescription`
247
+ metaDescription: (val?.metaDescription || val?.summary || val?.description || val?.seoDescription) as string | undefined,
248
+ slug: detectSlug(val),
249
+ imageNames: imageMeta.names,
250
+ imageTitles: imageMeta.titles,
251
+ imageCount: imageMeta.count,
252
+ headings: extractHeadings(body),
253
+ headingsDetailed: extractHeadingsDetailed(body),
254
+ bodyLinks: extractBodyLinks(body),
255
+ contentCategory: (val?.contentCategory || val?.category) as string | undefined,
256
+ contentPlacement: Array.isArray(val?.contentPlacement) ? (val.contentPlacement as string[]) : undefined,
257
+ authorName,
258
+ authorCredentials,
259
+ authorBioUrl,
260
+ authorIsReference,
261
+ // `published` is MJH's date field; `publishedAt`/`publishDate` cover other schemas
262
+ publishedAt: (val?.published || val?.publishedAt || val?.publishDate || val?._createdAt) as string | undefined,
263
+ // `updatedOn` is MJH's "Updated On" field. `updatedAt` is the standard Sanity convention.
264
+ // `_updatedAt` is the Sanity-managed timestamp as a final fallback.
265
+ updatedAt: (val?.updatedOn || val?.updatedAt || val?._updatedAt) as string | undefined,
266
+ lastReviewedAt: (val?.lastReviewedAt || val?.lastReviewed || val?.medicallyReviewedAt) as string | undefined,
267
+ };
268
+ }
@@ -32,9 +32,17 @@ function wordCount(s: string): number {
32
32
 
33
33
  export function analyzeHeadings(text: string, headings: string[]): HeadingAudit[] {
34
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 [];
35
43
  const headingSet = new Set(headings.map((h) => h.trim().toLowerCase()));
36
44
  const lower = text.toLowerCase();
37
- return headings.map((heading) => {
45
+ return questionHeadings.map((heading) => {
38
46
  const needle = heading.trim().toLowerCase();
39
47
  const idx = lower.indexOf(needle);
40
48
  if (idx === -1) {
@@ -75,7 +83,9 @@ export function analyzeFactDensity(text: string): FactDensityResult {
75
83
  const factsPer1000 = Math.round((factCount / total) * 1000);
76
84
 
77
85
  // Drift passages: sliding 200-word windows with zero facts
78
- const sentences = text.split(/(?<=[.!?])\s+/).filter((s) => s.trim().length > 0);
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);
79
89
  let drift = 0;
80
90
  let runWords = 0;
81
91
  let runHasFact = false;
@@ -93,8 +103,11 @@ export function analyzeFactDensity(text: string): FactDensityResult {
93
103
  // 2026 GEO research (Princeton, Averi citation benchmarks): the center of the
94
104
  // recommended fact-density range is ~8 stats per 1,000 words (1 every ~125
95
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.
96
109
  let status: FactDensityResult["status"];
97
- if (factsPer1000 >= 8 && drift === 0) status = "strong";
110
+ if (factsPer1000 >= 8) status = "strong";
98
111
  else if (factsPer1000 >= 4) status = "moderate";
99
112
  else status = "weak";
100
113