sanity-plugin-seo-copilot 0.2.13 → 0.2.14

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/src/lib/api.ts CHANGED
@@ -103,15 +103,31 @@ export async function fetchQuestions(
103
103
  return response.json();
104
104
  }
105
105
 
106
+ // Telemetry attached to a "Report a problem" submission - which surface/tab the editor
107
+ // was on, etc. Keys must match the backend's strict schema in feedback/route.ts.
108
+ export interface FeedbackContext {
109
+ surface?: string;
110
+ activeTab?: string;
111
+ primaryKeyword?: string;
112
+ documentType?: string;
113
+ url?: string;
114
+ userAgent?: string;
115
+ appVersion?: string;
116
+ timestamp?: string;
117
+ }
118
+
106
119
  export async function submitFeedback(
107
120
  apiUrl: string,
108
- data: { suggestion_type: string; suggestion_text: string; vote: "up" | "down"; document_id?: string; publication?: string; user_id?: string }
121
+ data: { suggestion_type: string; suggestion_text: string; vote: "up" | "down"; document_id?: string; publication?: string; user_id?: string; context?: FeedbackContext }
109
122
  ): Promise<void> {
110
- await fetch(`${apiUrl}/api/seo-copilot/feedback`, {
123
+ const res = await fetch(`${apiUrl}/api/seo-copilot/feedback`, {
111
124
  method: "POST",
112
125
  headers: { "Content-Type": "application/json" },
113
126
  body: JSON.stringify(data),
114
127
  });
128
+ // Surface HTTP failures (500, 429, ...) so the caller can show a real error instead of a
129
+ // false "Thanks" - fetch() only rejects on network errors, not on a bad status.
130
+ if (!res.ok) throw new Error(`Feedback submit failed: HTTP ${res.status}`);
115
131
  }
116
132
 
117
133
  export async function lookupKeywords(
@@ -24,6 +24,7 @@ interface PortableTextBlock {
24
24
  children?: PortableTextSpan[];
25
25
  markDefs?: PortableTextMarkDef[];
26
26
  text?: string;
27
+ listItem?: string;
27
28
  }
28
29
 
29
30
  export function extractText(blocks: unknown): string {
@@ -67,34 +68,116 @@ export function extractHeadingsDetailed(blocks: unknown): HeadingItem[] {
67
68
  return out;
68
69
  }
69
70
 
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>();
71
+ // Normalize a candidate link to an absolute http(s) URL the link-health checker can
72
+ // fetch. Accepts "https://x.com/a" as-is, prepends https:// to scheme-less links like
73
+ // "www.google.com" or "example.com/page", and rejects anything that isn't domain-shaped.
74
+ function normalizeLink(raw: string): string | null {
75
+ const s = raw.trim().replace(/[.,;:!?]+$/, "");
76
+ if (!s) return null;
77
+ if (/^https?:\/\//i.test(s)) return s;
78
+ // www.something OR bare domain like example.com / sub.example.co.uk/path
79
+ if (/^www\.\S+\.\S+/i.test(s) || /^[a-z0-9-]+(\.[a-z0-9-]+)+(\/|$)/i.test(s)) return `https://${s}`;
80
+ return null;
81
+ }
82
+
83
+ // Body paragraphs that LOOK like section headings but are styled as plain text (the editor
84
+ // typed a heading instead of applying the H2 style, so the tool can't count it). Conservative
85
+ // on purpose - we only flag a SHORT, punctuation-free line that is immediately followed by a
86
+ // substantial paragraph (a heading introduces content), and is not a list item / caption /
87
+ // reference. This keeps precision high so the "style this as H2?" nudge is trustworthy.
88
+ // Real articles are well under this many blocks, and section headings that matter live near
89
+ // the top - so cap the scan to bound work on a pathological 10k-block document.
90
+ const UNSTYLED_HEADING_SCAN_CAP = 600;
91
+ export function extractUnstyledHeadings(blocks: unknown): string[] {
92
+ if (!Array.isArray(blocks)) return [];
93
+ const items = (blocks as PortableTextBlock[]).slice(0, UNSTYLED_HEADING_SCAN_CAP).map((b) => {
94
+ if (!b || b._type !== "block") return null;
95
+ const style = b.style || "normal";
96
+ const text = (b.children || []).map((c) => c.text || "").join("").trim();
97
+ return {
98
+ isHeading: /^h[1-6]$/.test(style),
99
+ isPlain: style === "normal",
100
+ isList: typeof b.listItem === "string" && b.listItem.length > 0,
101
+ text,
102
+ words: text ? text.split(/\s+/).filter(Boolean).length : 0,
103
+ };
104
+ });
105
+ const out: string[] = [];
106
+ for (let i = 0; i < items.length; i++) {
107
+ const it = items[i];
108
+ if (!it || it.isHeading || it.isList || !it.isPlain) continue;
109
+ if (it.words < 2 || it.words > 9) continue; // too short to mean anything / too long to be a heading
110
+ if (/[.!?]$/.test(it.text)) continue; // ends like a sentence, not a heading
111
+ if (!/[A-Za-z]/.test(it.text)) continue; // must contain letters
112
+ if (/https?:\/\/|doi:|\baccessed\b|image credit|stock\.adobe|^figure\b|^table\b|^source[:s]?\b|^references?\b/i.test(it.text)) continue; // caption / reference
113
+ // Must be immediately followed by a substantial paragraph - the hallmark of a heading.
114
+ let next: (typeof items)[number] = null;
115
+ for (let j = i + 1; j < items.length; j++) {
116
+ if (items[j] && items[j]!.text) { next = items[j]; break; }
117
+ }
118
+ if (!next || next.isHeading || next.words < 12) continue;
119
+ out.push(it.text);
120
+ if (out.length >= 8) break; // safety cap
121
+ }
122
+ return out;
123
+ }
124
+
125
+ // Every URL in the article body, WITH whether it's an actual hyperlink. Sanity stores
126
+ // real links as Portable Text markDefs (_type "link" + href) - those are clickable
127
+ // (the editor Control-K'd them). A URL that only appears as inline text (typed/pasted,
128
+ // not wrapped in a link annotation) is NOT a hyperlink - readers can't click it and
129
+ // search engines won't follow it. Link Health uses this to tell editors which URLs are
130
+ // real links vs plain text they still need to link.
131
+ export interface BodyLink {
132
+ url: string;
133
+ hyperlinked: boolean;
134
+ // For a real hyperlink, the visible text the editor wrapped in the link (the anchor).
135
+ anchorText?: string;
136
+ }
137
+
138
+ export function extractBodyLinksDetailed(blocks: unknown): BodyLink[] {
139
+ const linked = new Set<string>(); // URLs that appear in a link annotation (a real hyperlink)
140
+ const all = new Set<string>();
141
+ const anchorByUrl = new Map<string, string>(); // url -> the visible anchor text
75
142
  if (Array.isArray(blocks)) {
143
+ // Pass 1: real hyperlinks (Control-K link annotations). Intentional, so a scheme-less
144
+ // href like "www.google.com" is accepted and normalized. Also grab the anchor text -
145
+ // the spans whose marks reference this link's _key.
76
146
  for (const block of blocks as PortableTextBlock[]) {
77
147
  if (block._type === "block" && Array.isArray(block.markDefs)) {
78
148
  for (const md of block.markDefs) {
79
149
  const href = md.href || md.url;
80
- if (typeof href === "string" && /^https?:\/\//i.test(href)) {
81
- urls.add(href.trim());
82
- }
150
+ if (typeof href !== "string") continue;
151
+ const n = normalizeLink(href);
152
+ if (!n) continue;
153
+ linked.add(n);
154
+ all.add(n);
155
+ const anchor = (block.children || [])
156
+ .filter((c) => Array.isArray(c.marks) && md._key && c.marks.includes(md._key))
157
+ .map((c) => c.text || "")
158
+ .join("")
159
+ .trim();
160
+ if (anchor && !anchorByUrl.has(n)) anchorByUrl.set(n, anchor);
83
161
  }
84
162
  }
85
163
  }
86
- }
87
- // Inline URLs that aren't in a link annotation - rare but possible.
88
- if (Array.isArray(blocks)) {
164
+ // Pass 2: inline plain-text URLs - http(s):// OR www.-prefixed. (We don't match bare
165
+ // domains in prose to avoid false positives on things like "e.g." or "vs.".)
89
166
  for (const block of blocks as PortableTextBlock[]) {
90
167
  if (block._type === "block" && Array.isArray(block.children)) {
91
168
  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(/[.,;:!?]+$/, "")));
169
+ const matches = blockText.match(/(?:https?:\/\/|www\.)[^\s"'<>)\]]+/gi);
170
+ if (matches) for (const u of matches) { const n = normalizeLink(u); if (n) all.add(n); }
94
171
  }
95
172
  }
96
173
  }
97
- return Array.from(urls);
174
+ return [...all].map((url) => ({ url, hyperlinked: linked.has(url), anchorText: anchorByUrl.get(url) }));
175
+ }
176
+
177
+ // Flat list of every body URL (both real hyperlinks and plain-text URLs). Used by the
178
+ // broken-link checker, which checks all of them regardless of whether they're linked.
179
+ export function extractBodyLinks(blocks: unknown): string[] {
180
+ return extractBodyLinksDetailed(blocks).map((l) => l.url);
98
181
  }
99
182
 
100
183
  // Slug detection across the common schema shapes. Looks for, in order:
@@ -186,6 +269,72 @@ export function detectAuthor(val: Record<string, unknown> | undefined): {
186
269
  return { authorIsReference: false };
187
270
  }
188
271
 
272
+ // A workflow-status value, not a person's name - so a `reviewer: "pending"` field doesn't
273
+ // read as a fact-checker literally named "pending" (a false "Set" that hides a missing one).
274
+ const FACT_CHECK_STATUS_WORDS = new Set([
275
+ "pending", "approved", "rejected", "done", "complete", "completed", "in review", "in progress",
276
+ "not started", "draft", "review", "reviewed", "unreviewed", "checked", "unchecked", "verified",
277
+ "unverified", "true", "false", "yes", "no", "n/a", "na", "none", "tbd", "todo", "to do",
278
+ ]);
279
+ function isLikelyPersonName(s: string): boolean {
280
+ const t = s.trim().toLowerCase();
281
+ if (!t || FACT_CHECK_STATUS_WORDS.has(t)) return false;
282
+ return /[a-z]/i.test(s);
283
+ }
284
+
285
+ // Fact-checker / reviewer detection. A second named reviewer is a strong E-E-A-T trust
286
+ // signal (MJH renders a "Fact checked by ..." line). Mirrors detectAuthor: handles inline
287
+ // strings, inline objects, arrays of names, and unresolvable Sanity references. Date
288
+ // fields (lastReviewedAt, medicallyReviewedAt, reviewedDate) are explicitly excluded -
289
+ // those are timestamps, not people; status values (pending/approved/...) are excluded too.
290
+ export function detectFactChecker(val: Record<string, unknown> | undefined): {
291
+ factCheckerName?: string;
292
+ factCheckerIsReference: boolean;
293
+ } {
294
+ if (!val) return { factCheckerIsReference: false };
295
+ // Person-denoting field names only. We deliberately do NOT include the bare `factCheck` /
296
+ // `factChecked` flags - those are usually booleans or workflow-status strings ("pending"),
297
+ // not a person's name.
298
+ const candidateFields = [
299
+ "factChecker", "factCheckers", "factCheckedBy",
300
+ "reviewer", "reviewers", "reviewedBy", "medicalReviewer", "medicallyReviewedBy",
301
+ ];
302
+ const dynamic = Object.keys(val).filter(
303
+ (k) =>
304
+ // Require "checker"/"checked by"/"reviewer"/"reviewed by" - NOT a bare "check" flag.
305
+ /factchecker|fact.?checked.?by|reviewer|reviewed.?by/i.test(k) &&
306
+ // never date/timestamp fields (lastReviewedAt, medicallyReviewedAt, reviewedDate),
307
+ // free-text/status/flag sidecars (reviewerNotes, reviewStatus), nor image/url/id fields.
308
+ !/at$|date$|on$|url|link|count|note|comment|status|flag|bool|photo|image|avatar|picture|id$/i.test(k)
309
+ );
310
+ const fields = Array.from(new Set([...candidateFields, ...dynamic]));
311
+ for (const f of fields) {
312
+ const raw = val[f];
313
+ if (!raw) continue;
314
+ // Array of plain-string names ("Fact checked by: A, B") - join the first few.
315
+ if (Array.isArray(raw)) {
316
+ const names = raw.filter((x): x is string => typeof x === "string" && isLikelyPersonName(x)).map((x) => x.trim());
317
+ if (names.length > 0) return { factCheckerName: names.slice(0, 3).join(", "), factCheckerIsReference: false };
318
+ }
319
+ const first = Array.isArray(raw) ? raw[0] : raw;
320
+ if (!first) continue;
321
+ if (typeof first === "string") {
322
+ const trimmed = first.trim();
323
+ if (trimmed && isLikelyPersonName(trimmed)) return { factCheckerName: trimmed, factCheckerIsReference: false };
324
+ continue;
325
+ }
326
+ if (typeof first === "object" && first !== null) {
327
+ const o = first as Record<string, unknown>;
328
+ const name = ([o.name, o.fullName, o.displayName] as unknown[]).find((v): v is string => typeof v === "string" && isLikelyPersonName(v));
329
+ if (name) return { factCheckerName: name, factCheckerIsReference: false };
330
+ if (typeof o._ref === "string" || o._type === "reference") {
331
+ return { factCheckerIsReference: true };
332
+ }
333
+ }
334
+ }
335
+ return { factCheckerIsReference: false };
336
+ }
337
+
189
338
  // Extracts image metadata from top-level image fields AND inline body
190
339
  // figure/image blocks (where MJH stores article images):
191
340
  // - names: alt text + asset filename (for the alt + filename audits)
@@ -240,6 +389,7 @@ export function buildDocumentFields(value: Record<string, unknown> | undefined):
240
389
  const title = typeof val?.title === 'string' ? val.title : undefined;
241
390
  const body = val?.body;
242
391
  const { authorName, authorCredentials, authorBioUrl, authorIsReference } = detectAuthor(val);
392
+ const { factCheckerName, factCheckerIsReference } = detectFactChecker(val);
243
393
  const imageMeta = val ? extractImageMeta(val) : { names: [], titles: [], count: 0 };
244
394
  return {
245
395
  title: title || undefined,
@@ -251,13 +401,17 @@ export function buildDocumentFields(value: Record<string, unknown> | undefined):
251
401
  imageCount: imageMeta.count,
252
402
  headings: extractHeadings(body),
253
403
  headingsDetailed: extractHeadingsDetailed(body),
404
+ unstyledHeadings: extractUnstyledHeadings(body),
254
405
  bodyLinks: extractBodyLinks(body),
406
+ bodyLinksDetailed: extractBodyLinksDetailed(body),
255
407
  contentCategory: typeof val?.contentCategory === 'string' ? val.contentCategory : typeof val?.category === 'string' ? val.category : undefined,
256
408
  contentPlacement: Array.isArray(val?.contentPlacement) ? (val.contentPlacement as string[]) : undefined,
257
409
  authorName,
258
410
  authorCredentials,
259
411
  authorBioUrl,
260
412
  authorIsReference,
413
+ factCheckerName,
414
+ factCheckerIsReference,
261
415
  // `published` is MJH's date field; `publishedAt`/`publishDate` cover other schemas
262
416
  publishedAt: ([val?.publishedAt, val?.publishDate, val?.published, val?._createdAt] as unknown[]).find((v): v is string => typeof v === 'string' && v.trim().length > 0),
263
417
  // `updatedOn` is MJH's "Updated On" field. `updatedAt` is the standard Sanity convention.
@@ -80,9 +80,9 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
80
80
  detail = `Primary keyword over-used at ${density.toFixed(2)}% density - reduce to 0.5-2.5%`;
81
81
  }
82
82
  }
83
- components.push({ label: "Primary keyword", points: pts, max: 25, detail });
83
+ components.push({ label: "Primary keyword usage", points: pts, max: 25, detail });
84
84
  } else {
85
- components.push({ label: "Primary keyword", points: 0, max: 25, detail: "No primary keyword identified yet" });
85
+ components.push({ label: "Primary keyword usage", points: 0, max: 25, detail: "No primary keyword identified yet" });
86
86
  }
87
87
 
88
88
  // 2. Supporting keyword coverage (up to 25)
@@ -92,13 +92,13 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
92
92
  const coverageRatio = inContentCount / supportingKws.length;
93
93
  const pts = Math.round(coverageRatio * 25);
94
94
  components.push({
95
- label: "Supporting keywords",
95
+ label: "Supporting keyword coverage",
96
96
  points: pts,
97
97
  max: 25,
98
98
  detail: `${inContentCount} of ${supportingKws.length} supporting keywords present (${Math.round(coverageRatio * 100)}%)`,
99
99
  });
100
100
  } else {
101
- components.push({ label: "Supporting keywords", points: 0, max: 25, detail: "No supporting keywords yet" });
101
+ components.push({ label: "Supporting keyword coverage", points: 0, max: 25, detail: "No supporting keywords yet" });
102
102
  }
103
103
 
104
104
  // 3. Word count (up to 15)
@@ -290,20 +290,9 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
290
290
  jumpTo: { tab: "technical", anchorId: "anchor-headings-structure" },
291
291
  });
292
292
  }
293
- // H1 inside body (the title is already the H1)
293
+ // (H1-in-body is intentionally no longer flagged: the article title IS the H1, and the
294
+ // Heading Outline on the Other Recs tab now shows it explicitly instead of warning.)
294
295
  if (headingsDetailed) {
295
- const bodyH1 = headingsDetailed.filter((h) => h.level === 1).length;
296
- if (bodyH1 > 0) {
297
- items.push({
298
- id: "headings-h1-in-body",
299
- category: "headings",
300
- severity: "warning",
301
- label: "H1 inside the body",
302
- description: `${bodyH1} H1 heading${bodyH1 === 1 ? "" : "s"} in the body of the article.`,
303
- howToFix: "The article title is your H1. Body headings should start at H2 so the outline isn't ambiguous.",
304
- jumpTo: { tab: "technical", anchorId: "anchor-headings-structure" },
305
- });
306
- }
307
296
  // Skipped-level check
308
297
  let prevLevel = 0;
309
298
  let skips = 0;
@@ -335,6 +324,26 @@ export function buildSummaryItems(input: BuildSummaryInput): SummaryItem[] {
335
324
  jumpTo: { tab: "technical", anchorId: "anchor-headings-structure" },
336
325
  });
337
326
  }
327
+ // Keyword-in-headings opportunity - mirrors the "Keywords in Headings" audit on the
328
+ // Other Recs tab so the nudge also surfaces in the Summary hub. Only when subheadings
329
+ // exist and neither target keyword appears in any of them.
330
+ const subheads = headingsDetailed.filter((h) => h.level >= 2);
331
+ if (subheads.length > 0 && (primaryKeyword || secondaryKeyword)) {
332
+ const subText = subheads.map((h) => h.text).join(" ");
333
+ const hasP = primaryKeyword ? containsKeywordTokens(subText, primaryKeyword) : false;
334
+ const hasS = secondaryKeyword ? containsKeywordTokens(subText, secondaryKeyword) : false;
335
+ if (!hasP && !hasS) {
336
+ items.push({
337
+ id: "headings-keyword-missing",
338
+ category: "headings",
339
+ severity: "opportunity",
340
+ label: "Keyword missing from subheadings",
341
+ description: "No H2/H3 subheading uses your primary or secondary keyword.",
342
+ howToFix: "Work your primary or secondary keyword into at least one subheading - keywords in headers reinforce relevance for readers and search.",
343
+ jumpTo: { tab: "technical", anchorId: "anchor-headings-keyword" },
344
+ });
345
+ }
346
+ }
338
347
  }
339
348
 
340
349
  // ---------- IMAGES ----------
package/src/lib/types.ts CHANGED
@@ -99,9 +99,16 @@ export interface DocumentFields {
99
99
  headings?: string[];
100
100
  // Headings with their H-level, used by the Technical tab for hierarchy checks.
101
101
  headingsDetailed?: HeadingItem[];
102
+ // Body paragraphs that look like section headings but were typed as plain text (not styled
103
+ // as H2). Drives the "this looks like a heading - style it as H2?" nudge.
104
+ unstyledHeadings?: string[];
102
105
  // All URL links found in the body (from Portable Text markDefs + inline URL regex).
103
106
  // Used by the Technical tab's broken-link checker.
104
107
  bodyLinks?: string[];
108
+ // Same URLs, but flagged with whether each is an actual hyperlink (a Control-K link
109
+ // annotation) vs plain text the editor still needs to link, plus the visible anchor
110
+ // text for real links. Drives the Link Health "hyperlinked vs plain text" breakdown.
111
+ bodyLinksDetailed?: { url: string; hyperlinked: boolean; anchorText?: string }[];
105
112
  contentCategory?: string;
106
113
  contentPlacement?: string[];
107
114
  // E-E-A-T fields - 2026 healthcare content scrutiny
@@ -111,6 +118,11 @@ export interface DocumentFields {
111
118
  // True when the author field is set as a Sanity reference we can't resolve client-side
112
119
  // (vs. truly missing). Lets the audit distinguish "schema uses refs, looks fine" from "no author".
113
120
  authorIsReference?: boolean;
121
+ // Fact-checker / reviewer - a second named person who reviewed the article (MJH shows a
122
+ // "Fact checked by ..." line). Strong E-E-A-T trust signal for healthcare content.
123
+ // factCheckerIsReference mirrors the author's reference case.
124
+ factCheckerName?: string;
125
+ factCheckerIsReference?: boolean;
114
126
  publishedAt?: string;
115
127
  updatedAt?: string;
116
128
  lastReviewedAt?: string;