-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
378 lines (339 loc) · 11.6 KB
/
index.js
File metadata and controls
378 lines (339 loc) · 11.6 KB
1
2
3
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import { astToHtmlString } from "@graphcms/rich-text-html-renderer";
/**
* Fetches an article by slug, transforms rich-text content to HTML, and returns
* content metadata for rendering (including jump links).
*
* @param {import('h3').H3Event} event - Incoming Nitro/H3 request event.
* @returns {Promise<object>} Article payload with parsed content.
*/
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig();
const apiUrl = config.graphqlApiUrl;
const query = getQuery(event);
const { urlSlug } = query;
console.log("Fetching article with urlSlug:", urlSlug);
/**
* Queries Hygraph for the primary article and related content, then enriches
* the response with content HTML and heading link metadata.
*
* @returns {Promise<object>} Normalized article response object.
*/
const getSingleArticle = async () => {
const graphqlQuery = `
query GetArticleBySlugAndRelatedArticles($urlSlug: String!) {
article(stage: PUBLISHED, where: { urlSlug: $urlSlug }) {
...ArticleDetailFragment
relatedArticles {
...RelatedArticleFragment
}
}
recentArticles: articles(
where: { urlSlug_not: $urlSlug, domain: protectCom }
stage: PUBLISHED
orderBy: publishedAt_DESC
first: 4
) {
...RelatedArticleFragment
}
}
fragment ArticleDetailFragment on Article {
id
urlSlug
title
secondaryImage {
url
}
readTime
publishedAt
excerpt
date
metaKeywords
vertical
subvertical
coverImage {
url
}
content {
raw
references {
... on AppComponent {
id
componentName
props
}
}
}
contentTag {
tagValue
}
}
fragment RelatedArticleFragment on Article {
id
urlSlug
title
secondaryImage {
url
}
readTime
publishedAt
excerpt
date
coverImage {
url
}
content {
raw
}
}
`;
const variables = {
urlSlug: urlSlug,
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: graphqlQuery,
variables: variables,
}),
};
try {
const { data: article } = await $fetch(apiUrl, options);
const articleContent = article.article;
if (!articleContent || !articleContent.content.raw) {
return article;
}
/**
* Creates a stateful ID generator that slugifies heading text and appends
* numeric suffixes for duplicates.
*
* @returns {(text: string) => string} Unique heading ID generator.
*/
const createUniqueHeadingIdGenerator = () => {
const seenIds = new Map();
/**
* Generates a unique, URL-friendly heading ID.
*
* @param {string} text - Heading text content.
* @returns {string} Stable unique ID for anchor linking.
*/
return (text) => {
const baseId =
String(text || "")
.replace(/[^a-zA-Z0-9]+/g, "-")
.replace(/(^-|-$)/g, "")
.toLowerCase() || "section";
const currentCount = seenIds.get(baseId) || 0;
seenIds.set(baseId, currentCount + 1);
return currentCount === 0 ? baseId : `${baseId}-${currentCount + 1}`;
};
};
const getHeadingIdForToc = createUniqueHeadingIdGenerator();
const getHeadingIdForRender = createUniqueHeadingIdGenerator();
/**
* Recursively extracts plain text from a rich-text AST node.
*
* @param {object|null|undefined} node - Rich-text AST node.
* @returns {string} Concatenated plain-text content.
*/
const extractPlainText = (node) => {
if (!node) return "";
if (typeof node.text === "string") return node.text;
if (Array.isArray(node.children)) {
return node.children.map((child) => extractPlainText(child)).join("");
}
return "";
};
/**
* Removes HTML tags from a string for text-based ID generation.
*
* @param {string} [value=""] - HTML string value.
* @returns {string} Trimmed plain text.
*/
const stripHtmlTags = (value = "") =>
String(value)
.replace(/<[^>]*>/g, "")
.trim();
/**
* Extracts heading metadata from rich-text nodes for jump-link rendering.
* Includes native heading nodes only.
*
* @param {Array<object>} nodes - Root rich-text child nodes.
* @returns {Array<{text: string, id: string, level: number}>} Heading links.
*/
const extractHeadings = (nodes) => {
const headingsList = [];
const levelMap = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6 };
/**
* Converts a heading AST node to a normalized heading metadata object.
*
* @param {object} headingNode - Rich-text heading node.
* @returns {{text: string, id: string, level: number}} Heading metadata.
*/
const generateHeading = (headingNode) => {
const nodeType = headingNode?.type || "heading-two";
const level = nodeType.split("-")[1];
const headingLevel = levelMap[level] || 2;
const text = extractPlainText(headingNode).trim();
if (!text) {
return null;
}
const id = getHeadingIdForToc(text);
return { text, id, level: headingLevel };
};
nodes.forEach((node) => {
if (node?.type?.startsWith("heading-")) {
const heading = generateHeading(node);
if (heading) {
headingsList.push(heading);
}
} else if (node?.children?.length > 0) {
// Recursively check for nested headings within child nodes (e.g., in rich-text)
const childHeadings = extractHeadings(node.children);
headingsList.push(...childHeadings);
}
});
return headingsList;
};
// Always extract headings for table of contents
const contentLinks = extractHeadings(
articleContent.content.raw.children || []
);
articleContent.contentLinks = contentLinks;
/**
* Renders a heading element with an auto-generated anchor ID.
* Utilizes custom renderers to inject `id` attributes for native headings and bold-only paragraphs.
*
* @param {string} tagName - HTML heading tag name (`h1`...`h6`).
* @param {string} children - Inner HTML content.
* @returns {string} Heading HTML string with `id` attribute.
*/
const headingRenderer = (tagName, children) => {
const text = stripHtmlTags(children);
const id = getHeadingIdForRender(text);
return `<${tagName} id="${id}">${children}</${tagName}>`;
};
const embeddedComponents = [];
const embedMarkerPrefix = "__APP_COMPONENT_EMBED__";
articleContent.componentNames = [];
const parsedHtml = astToHtmlString({
content: articleContent.content.raw,
references: articleContent.content.references || [],
renderers: {
h1: ({ children }) => headingRenderer("h1", children),
h2: ({ children }) => headingRenderer("h2", children),
h3: ({ children }) => headingRenderer("h3", children),
h4: ({ children }) => headingRenderer("h4", children),
h5: ({ children }) => headingRenderer("h5", children),
h6: ({ children }) => headingRenderer("h6", children),
p: ({ children }) => {
const boldOnlyMatch = String(children || "").match(
/^\s*<(strong|b)>([\s\S]*?)<\/\1>\s*$/i
);
if (!boldOnlyMatch) {
return `<p>${children}</p>`;
}
const text = stripHtmlTags(boldOnlyMatch[2]);
if (!text) {
return `<p>${children}</p>`;
}
const id = getHeadingIdForRender(text);
return `<p id="${id}">${children}</p>`;
},
img: ({ src, alt }) => {
const altAttribute = alt ? ` alt="${alt}"` : "";
return `<img src="${src}"${altAttribute} />`;
},
embed: {
AppComponent: ({ componentName, nodeId, props }) => {
const componentData = {
type: "component",
name:
String(componentName).slice(0, 1).toUpperCase() +
String(componentName).slice(1), // Ensure component name is capitalized
nodeId,
componentProps: props || {},
};
const componentIndex = embeddedComponents.push(componentData) - 1;
return `<!--${embedMarkerPrefix}:${componentIndex}-->`;
},
},
},
});
const contentParts = [];
const parsedHtmlString = String(parsedHtml || "");
const embedMarkerRegex = new RegExp(
`<!--${embedMarkerPrefix}:(\\d+)-->`,
"g"
);
let previousIndex = 0;
let markerMatch = embedMarkerRegex.exec(parsedHtmlString);
while (markerMatch) {
const markerStartIndex = markerMatch.index;
const markerEndIndex = markerStartIndex + markerMatch[0].length;
if (markerStartIndex > previousIndex) {
const htmlPart = parsedHtmlString.slice(
previousIndex,
markerStartIndex
);
if (htmlPart.trim()) {
contentParts.push({
type: "text",
content: htmlPart,
tag: "rich-text",
});
}
}
const componentIndex = Number(markerMatch[1]);
const embeddedComponent = embeddedComponents[componentIndex];
if (embeddedComponent) {
contentParts.push(embeddedComponent);
if (embeddedComponent.name) {
articleContent.componentNames.push(embeddedComponent.name);
}
}
previousIndex = markerEndIndex;
markerMatch = embedMarkerRegex.exec(parsedHtmlString);
}
if (previousIndex < parsedHtmlString.length) {
const htmlPart = parsedHtmlString.slice(previousIndex);
if (htmlPart.trim()) {
contentParts.push({
type: "text",
content: htmlPart,
tag: "rich-text",
});
}
}
if (!contentParts.length && parsedHtmlString.trim()) {
contentParts.push({
type: "text",
content: parsedHtmlString,
tag: "rich-text",
});
}
articleContent.contentHtml = parsedHtml;
articleContent.contentParts = contentParts;
return {
response: article,
contentParts: articleContent.contentParts,
componentNames: articleContent.componentNames,
contentLinks: articleContent.contentLinks,
recentArticles: article.recentArticles || [],
};
} catch (err) {
// Log server-side for debugging
console.error("Error fetching articles from GraphQL:", err);
// Re-throw a Nuxt-friendly error so the client receives a proper HTTP status
throw createError({
statusCode: err?.statusCode || 502,
statusMessage: "Failed to fetch articles",
data: { original: err?.message || String(err) },
});
}
};
const singleArticleData = await getSingleArticle();
return singleArticleData;
});