sanity-plugin-seo-copilot 0.2.5 → 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.
@@ -1,257 +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
- 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
- }
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
+ }
@@ -12,6 +12,16 @@ export interface ContentScore {
12
12
  components: ScoreComponent[];
13
13
  }
14
14
 
15
+ // Count whole-word / whole-phrase occurrences, anchored on word boundaries, so a
16
+ // short token like "as" or "cm" can't match inside "phase" or "cmv". Safari-safe:
17
+ // uses \b only (no lookbehind). The needle is regex-escaped.
18
+ function countWholeMatches(haystack: string, needle: string): number {
19
+ if (!needle) return 0;
20
+ const esc = needle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
21
+ const m = haystack.match(new RegExp(`\\b${esc}\\b`, "g"));
22
+ return m ? m.length : 0;
23
+ }
24
+
15
25
  /**
16
26
  * Client-side content score (0-100) with per-component breakdown.
17
27
  * Mirrors backend scoring.ts.
@@ -27,27 +37,44 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
27
37
  // 1. Primary keyword (up to 25)
28
38
  const primaryTerm = (analysis.primaryKeyword?.term || "").toLowerCase();
29
39
  if (primaryTerm) {
30
- const escaped = primaryTerm.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
31
- const primaryRegex = new RegExp(escaped, "gi");
32
- const primaryMatches = content.match(primaryRegex);
33
- const primaryCount = primaryMatches?.length || 0;
34
- // Density counts keyword WORDS, not phrase occurrences, so a multi-word
35
- // primary isn't unfairly scored "too thin": one mention of a 4-word phrase
36
- // in 760 words reads as ~0.5% (the healthy floor), not 0.13%.
40
+ // A multi-word primary like "acoramidis ATTR-CM" almost never appears as an
41
+ // adjacent phrase, but if every token is in the body the keyword IS present.
42
+ // Try the exact phrase first; otherwise fall back to token co-occurrence (all
43
+ // tokens present) and use the rarest token as the concept's mention count.
44
+ // (This mirrors tokensContain() used by the Meta + Summary audits.)
45
+ const tokens = primaryTerm.split(/\s+/).filter((t) => t.length > 1);
46
+ const phraseCount = countWholeMatches(lowerContent, primaryTerm);
47
+ let occurrences = phraseCount;
48
+ let viaTokens = false;
49
+ if (phraseCount === 0 && tokens.length > 0) {
50
+ const counts = tokens.map((t) => countWholeMatches(lowerContent, t));
51
+ if (counts.every((c) => c > 0)) {
52
+ occurrences = Math.min(...counts);
53
+ viaTokens = true;
54
+ }
55
+ }
37
56
  const primaryWordCount = Math.max(1, primaryTerm.split(/\s+/).filter(Boolean).length);
38
57
  let pts = 0;
39
58
  let detail: string;
40
- if (primaryCount === 0) {
59
+ if (occurrences === 0) {
41
60
  detail = `Primary keyword "${primaryTerm}" not found in content`;
42
61
  } else {
43
62
  pts += 12;
44
- const density = words > 0 ? ((primaryCount * primaryWordCount) / words) * 100 : 0;
63
+ // Exact phrase: an N-word phrase appearing M times occupies M*N keyword-words.
64
+ // Token co-occurrence: tokens are spread through the body, so count each once.
65
+ const density = words > 0
66
+ ? ((viaTokens ? occurrences : occurrences * primaryWordCount) / words) * 100
67
+ : 0;
45
68
  if (density >= 0.5 && density <= 2.5) {
46
69
  pts += 13;
47
70
  detail = `Primary keyword present, density ${density.toFixed(2)}% (ideal range)`;
48
71
  } else if (density < 0.5) {
49
72
  pts += 7;
50
73
  detail = `Primary keyword present but density only ${density.toFixed(2)}% - aim for 0.5-2.5%`;
74
+ } else if (viaTokens && density <= 6) {
75
+ // Tokens spread through the body is topical depth, not keyword stuffing.
76
+ pts += 11;
77
+ detail = `Primary keyword strongly represented (${density.toFixed(2)}%)`;
51
78
  } else {
52
79
  pts += 4;
53
80
  detail = `Primary keyword over-used at ${density.toFixed(2)}% density - reduce to 0.5-2.5%`;
@@ -101,9 +128,10 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
101
128
  if (documentFields) {
102
129
  hasH1orTitle = !!(documentFields.title && documentFields.title.trim());
103
130
  const det = documentFields.headingsDetailed;
104
- hasSubheadings = det
105
- ? det.some((h) => h.level >= 2 && h.level <= 4)
106
- : (documentFields.headings?.length || 0) > 0;
131
+ // Any H2+ heading counts as a subheading. Fall back to the flat heading list
132
+ // when the detailed list is absent OR empty, so a real outline is never missed.
133
+ const detHasSub = Array.isArray(det) && det.some((h) => h.level >= 2);
134
+ hasSubheadings = detHasSub || (documentFields.headings?.length || 0) > 0;
107
135
  } else {
108
136
  hasH1orTitle = /^#\s|<h1/im.test(content);
109
137
  hasSubheadings = /^##\s|^###\s|<h2|<h3/im.test(content);
@@ -145,8 +173,7 @@ export function calculateContentScoreDetailed(content: string, analysis: SEOAnal
145
173
  if (documentFields) {
146
174
  qCount = (documentFields.headings || []).filter((h) => h.trim().endsWith("?")).length;
147
175
  } else {
148
- const questionHeadings = content.match(/^#{1,6}\s+.*\?$/gm) || content.match(/<h[1-6][^>]*>.*\?<\/h[1-6]>/gi);
149
- qCount = questionHeadings?.length || 0;
176
+ qCount = (content.match(/^#{1,6}\s+.*\?$/gm) || []).length + (content.match(/<h[1-6][^>]*>.*\?<\/h[1-6]>/gi) || []).length;
150
177
  }
151
178
  let aeoPts = 0;
152
179
  if (qCount >= 3) aeoPts = 10;