@redocly/realm-plugin-asciidoc 0.8.0-next.9 → 0.8.1

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/plugin.ts DELETED
@@ -1,675 +0,0 @@
1
- import path from 'node:path';
2
- import { createHash, randomUUID } from 'node:crypto';
3
- import { existsSync, mkdirSync, copyFileSync, readFileSync } from 'node:fs';
4
- import { fileURLToPath } from 'url';
5
-
6
- import type { ExternalPlugin, GetStaticDataContext } from '@redocly/realm/dist/server/types';
7
- import type { ParsedAsciidoc } from './asciidoc-parser.js';
8
- import type { ContentNode } from './types.js';
9
-
10
- import { getPathPrefix, withPathPrefix } from '@redocly/theme/core/utils';
11
-
12
- import { searchResolver } from './search-resolver.js';
13
- import { getAiDocumentsStore } from './get-ai-search-documents.js';
14
- import { parseAsciidoc } from './asciidoc-parser.js';
15
-
16
- const DIAGRAM_MICROSERVICE_URL =
17
- process.env.REDOCLY_DIAGRAM_MICROSERVICE_URL || 'https://tools.redocly.com/diagram-renders';
18
-
19
- type DiagramType = 'mermaid' | 'excalidraw' | 'plantuml';
20
- type DiagramResultEntry = {
21
- light?: string;
22
- dark?: string;
23
- error?: string;
24
- };
25
- type DiagramHtmlVariants = {
26
- light: string;
27
- dark?: string;
28
- error?: string;
29
- };
30
-
31
- const diagramCache: Record<string, DiagramHtmlVariants> = {};
32
-
33
- function diagramHash(source: string, type: DiagramType): string {
34
- return createHash('sha256').update(`${type}:${source}`).digest('hex');
35
- }
36
-
37
- function normalizeDiagramResult(
38
- entry: string | DiagramResultEntry,
39
- type: string,
40
- ): DiagramHtmlVariants {
41
- if (typeof entry === 'string') {
42
- return { light: entry };
43
- }
44
-
45
- if (entry.error) {
46
- return { light: '', error: `Failed to render ${type} diagram: ${entry.error}` };
47
- }
48
-
49
- return {
50
- light: entry.light ?? entry.dark ?? '',
51
- dark: entry.dark,
52
- };
53
- }
54
-
55
- async function renderDiagramNodes(nodes: ContentNode[]): Promise<ContentNode[]> {
56
- // Collect all diagram nodes
57
- const diagramEntries: { index: number; type: DiagramType; source: string }[] = [];
58
-
59
- function collectDiagrams(nodeList: ContentNode[]) {
60
- for (let i = 0; i < nodeList.length; i++) {
61
- const node = nodeList[i];
62
- if (node.type === 'diagram') {
63
- diagramEntries.push({
64
- index: diagramEntries.length,
65
- type: node.diagramType,
66
- source: node.source,
67
- });
68
- }
69
- // Recurse into children
70
- if ('children' in node && Array.isArray((node as any).children)) {
71
- collectDiagrams((node as any).children);
72
- }
73
- if (node.type === 'list') {
74
- for (const item of node.items) {
75
- collectDiagrams(item.children);
76
- }
77
- }
78
- if (node.type === 'descriptionList') {
79
- for (const item of node.items) {
80
- collectDiagrams(item.children);
81
- }
82
- }
83
- }
84
- }
85
-
86
- collectDiagrams(nodes);
87
-
88
- if (diagramEntries.length === 0) {
89
- return nodes;
90
- }
91
-
92
- const rendered = new Map<number, DiagramHtmlVariants>();
93
-
94
- // Resolve cached diagrams first, collect uncached ones grouped by type
95
- const uncachedByType = new Map<DiagramType, { originalIndex: number; source: string }[]>();
96
- for (const entry of diagramEntries) {
97
- const hash = diagramHash(entry.source, entry.type);
98
- const cached = diagramCache[hash];
99
- if (cached) {
100
- rendered.set(entry.index, cached);
101
- } else {
102
- if (!uncachedByType.has(entry.type)) {
103
- uncachedByType.set(entry.type, []);
104
- }
105
- const items = uncachedByType.get(entry.type);
106
- if (items) {
107
- items.push({ originalIndex: entry.index, source: entry.source });
108
- }
109
- }
110
- }
111
-
112
- const promises = Array.from(uncachedByType.entries()).map(async ([type, items]) => {
113
- const rayId = randomUUID();
114
- const organizationId = process.env.ORGANIZATION_ID;
115
-
116
- try {
117
- const response = await fetch(DIAGRAM_MICROSERVICE_URL, {
118
- method: 'POST',
119
- headers: { 'Content-Type': 'application/json' },
120
- body: JSON.stringify({
121
- type,
122
- definitions: items.map((i) => i.source),
123
- theme: 'both',
124
- rayId,
125
- ...(organizationId ? { organizationId } : {}),
126
- }),
127
- });
128
-
129
- if (response.status !== 200) {
130
- console.error(`Failed to render ${type} diagrams (rayId: ${rayId}): ${response.status}`);
131
- for (const item of items) {
132
- rendered.set(item.originalIndex, {
133
- light: '',
134
- error: `Failed to render ${type} diagram: service returned status ${response.status}`,
135
- });
136
- }
137
- return;
138
- }
139
-
140
- const results = (await response.json()) as (string | DiagramResultEntry)[];
141
- const normalized = results.map((r) => normalizeDiagramResult(r, type));
142
-
143
- for (let i = 0; i < items.length; i++) {
144
- const result = normalized[i];
145
- rendered.set(items[i].originalIndex, result);
146
- if (!result.error) {
147
- diagramCache[diagramHash(items[i].source, type)] = result;
148
- }
149
- }
150
- } catch (err) {
151
- console.error(`Failed to render ${type} diagrams (rayId: ${rayId}):`, err);
152
- const message = err instanceof Error ? err.message : 'Rendering failed';
153
- for (const item of items) {
154
- rendered.set(item.originalIndex, {
155
- light: '',
156
- error: `Failed to render ${type} diagram: ${message}`,
157
- });
158
- }
159
- }
160
- });
161
-
162
- await Promise.all(promises);
163
-
164
- // Apply rendered SVGs to diagram nodes
165
- let diagramIdx = 0;
166
- function applyRendered(nodeList: ContentNode[]): ContentNode[] {
167
- return nodeList.map((node) => {
168
- if (node.type === 'diagram') {
169
- const diagram = rendered.get(diagramIdx++);
170
- if (diagram?.error) {
171
- return { ...node, diagramError: diagram.error };
172
- }
173
- return {
174
- ...node,
175
- diagramHtml: diagram?.light || '',
176
- diagramHtmlDark: diagram?.dark,
177
- };
178
- }
179
- if ('children' in node && Array.isArray((node as any).children)) {
180
- return { ...node, children: applyRendered((node as any).children) };
181
- }
182
- if (node.type === 'list') {
183
- return {
184
- ...node,
185
- items: node.items.map((item) => ({
186
- ...item,
187
- children: applyRendered(item.children),
188
- })),
189
- };
190
- }
191
- if (node.type === 'descriptionList') {
192
- return {
193
- ...node,
194
- items: node.items.map((item) => ({
195
- ...item,
196
- children: applyRendered(item.children),
197
- })),
198
- };
199
- }
200
- return node;
201
- });
202
- }
203
-
204
- return applyRendered(nodes);
205
- }
206
-
207
- const ASCIIDOC_TEMPLATE_ID = 'asciidoc-docs';
208
-
209
- export default function asciidocPlugin(): ExternalPlugin {
210
- return {
211
- id: 'asciidoc',
212
- loaders: {
213
- asciidoc: async (relativePath, context) => {
214
- const content = await context.fs.read(relativePath);
215
- return parseAsciidoc(content, relativePath, context.fs.cwd);
216
- },
217
- },
218
- processContent: async (actions, context) => {
219
- const asciidocTemplateId = actions.createTemplate(
220
- ASCIIDOC_TEMPLATE_ID,
221
- fromCurrentDir(import.meta.url, './template.js'),
222
- );
223
-
224
- for (const record of context.fs.scan(/\.adoc$/)) {
225
- if (await context.isPathIgnored(record.relativePath)) {
226
- continue;
227
- }
228
-
229
- const { relativePath } = record;
230
-
231
- try {
232
- const { data: parsed } = await context.cache.load<ParsedAsciidoc>(
233
- relativePath,
234
- 'asciidoc',
235
- );
236
-
237
- if (!parsed) continue;
238
-
239
- const { title, attributes, sections, contentNodes, links } = parsed;
240
-
241
- // Resolve image src attributes in content nodes to hashed asset URLs
242
- const resolvedContentNodes = resolveContentNodeImages(
243
- contentNodes,
244
- actions.contentDir,
245
- actions.outdir,
246
- );
247
-
248
- const normalizedAttributes = normalizeAsciidocAttributes(attributes);
249
- const fallbackTitle = path.basename(relativePath, '.adoc');
250
- const pageTitle = title || fallbackTitle;
251
- const metadata = {
252
- type: 'asciidoc',
253
- title: pageTitle,
254
- ...normalizedAttributes.metadata,
255
- };
256
-
257
- const frontmatter = {
258
- title: pageTitle,
259
- description: normalizedAttributes.description,
260
- keywords: normalizedAttributes.keywords,
261
- excludeFromSearch: normalizedAttributes.excludeFromSearch,
262
- seo: {
263
- title: normalizedAttributes.doctitle || pageTitle,
264
- description: normalizedAttributes.description || '',
265
- },
266
- };
267
-
268
- actions.addRoute({
269
- excludeFromSearch: normalizedAttributes.excludeFromSearch,
270
- fsPath: relativePath,
271
- templateId: asciidocTemplateId,
272
- metadata,
273
- getNavText: async () => pageTitle,
274
- getStaticData: async (_route, dataContext) => {
275
- // Resolve cross-page links using Realm's route registry
276
- const linkedContentNodes = resolveContentNodeLinks(
277
- resolvedContentNodes,
278
- relativePath,
279
- dataContext,
280
- );
281
-
282
- // Render diagram nodes via the diagram microservice
283
- const renderedContentNodes = await renderDiagramNodes(linkedContentNodes);
284
-
285
- return {
286
- props: {
287
- title: pageTitle,
288
- contentNodes: renderedContentNodes,
289
- sections,
290
- links,
291
- frontmatter,
292
- },
293
- };
294
- },
295
- getSearchDocuments: searchResolver(
296
- frontmatter,
297
- relativePath,
298
- sections,
299
- actions.getSearchFacets,
300
- actions.setSearchFacets,
301
- ),
302
- getAiDocumentsStore: getAiDocumentsStore(
303
- frontmatter,
304
- sections,
305
- actions.getSearchFacets,
306
- ),
307
- });
308
- } catch (e) {
309
- console.error(`Failed to process AsciiDoc file: ${relativePath}`, e);
310
- }
311
- }
312
- },
313
- };
314
- }
315
-
316
- type NormalizedAsciidocAttributes = {
317
- doctitle?: string;
318
- description?: string;
319
- keywords?: string[];
320
- excludeFromSearch: boolean;
321
- metadata: Record<string, string>;
322
- };
323
-
324
- function normalizeAsciidocAttributes(
325
- attributes: ParsedAsciidoc['attributes'],
326
- ): NormalizedAsciidocAttributes {
327
- const doctitle = toStringValue(attributes.doctitle);
328
- const description = toStringValue(attributes.description);
329
- const rawKeywords = toStringValue(attributes.keywords);
330
- const keywords = rawKeywords
331
- ? rawKeywords
332
- .split(',')
333
- .map((keyword) => keyword.trim())
334
- .filter(Boolean)
335
- : undefined;
336
-
337
- const metadata = Object.entries(attributes).reduce<Record<string, string>>(
338
- (acc, [key, value]) => {
339
- if (!key.startsWith('metadata-')) return acc;
340
- const metadataKey = key.slice('metadata-'.length);
341
- if (!metadataKey) return acc;
342
-
343
- acc[metadataKey] = String(value);
344
- return acc;
345
- },
346
- {},
347
- );
348
-
349
- const excludeFromSearch = toBooleanValue(attributes['exclude-from-search'], false);
350
-
351
- return {
352
- doctitle,
353
- description,
354
- keywords,
355
- excludeFromSearch,
356
- metadata,
357
- };
358
- }
359
-
360
- function toStringValue(value: string | number | boolean | undefined): string | undefined {
361
- if (typeof value === 'string') return value;
362
- if (typeof value === 'number' || typeof value === 'boolean') return String(value);
363
- return undefined;
364
- }
365
-
366
- function toBooleanValue(
367
- value: string | number | boolean | undefined,
368
- defaultValue: boolean,
369
- ): boolean {
370
- if (typeof value === 'boolean') return value;
371
- if (typeof value === 'number') return value !== 0;
372
- if (typeof value === 'string') return ['1', 'true', 'yes', 'on'].includes(value.toLowerCase());
373
- return defaultValue;
374
- }
375
-
376
- function __dirname(url: string): string {
377
- const __filename = fileURLToPath(url);
378
- return path.dirname(__filename);
379
- }
380
-
381
- function fromCurrentDir(moduleUrl: string, filePath: string): string {
382
- return path.resolve(__dirname(moduleUrl), filePath);
383
- }
384
-
385
- const ASSETS_URL_PREFIX = '/assets';
386
- const ASSETS_DIRNAME = 'assets';
387
-
388
- /**
389
- * Recursively walks the content node tree and resolves image `src` values
390
- * to hashed asset URLs, copying each file to the output assets directory.
391
- */
392
- function resolveContentNodeImages(
393
- nodes: ContentNode[],
394
- contentDir: string,
395
- outdir: string,
396
- ): ContentNode[] {
397
- return nodes.map((node) => resolveNodeImages(node, contentDir, outdir));
398
- }
399
-
400
- function resolveNodeImages(node: ContentNode, contentDir: string, outdir: string): ContentNode {
401
- switch (node.type) {
402
- case 'image': {
403
- const src = node.src;
404
- if (src.startsWith('/') && !src.startsWith('//') && !src.startsWith('/assets/')) {
405
- try {
406
- const assetUrl = copyImageToAssets(src.slice(1), contentDir, outdir);
407
- return { ...node, src: assetUrl };
408
- } catch {
409
- return node;
410
- }
411
- }
412
- return node;
413
- }
414
- case 'section':
415
- case 'admonition':
416
- case 'quote':
417
- case 'sidebar':
418
- case 'example':
419
- case 'collapsible':
420
- return { ...node, children: resolveContentNodeImages(node.children, contentDir, outdir) };
421
- case 'list':
422
- return {
423
- ...node,
424
- items: node.items.map((item) => ({
425
- ...item,
426
- children: resolveContentNodeImages(item.children, contentDir, outdir),
427
- })),
428
- };
429
- case 'descriptionList':
430
- return {
431
- ...node,
432
- items: node.items.map((item) => ({
433
- ...item,
434
- children: resolveContentNodeImages(item.children, contentDir, outdir),
435
- })),
436
- };
437
- default:
438
- return node;
439
- }
440
- }
441
-
442
- function copyImageToAssets(fileRelativePath: string, contentDir: string, outdir: string): string {
443
- const absolutePath = path.resolve(contentDir, fileRelativePath);
444
- if (!existsSync(absolutePath)) {
445
- throw new Error(`Image not found: ${absolutePath}`);
446
- }
447
-
448
- const assetsDir = path.join(outdir, ASSETS_DIRNAME);
449
- if (!existsSync(assetsDir)) {
450
- mkdirSync(assetsDir, { recursive: true });
451
- }
452
-
453
- const ext = path.extname(absolutePath);
454
- const baseName = path.basename(absolutePath, ext);
455
- const fileContent = readFileSync(absolutePath);
456
- const hash = createHash('sha256').update(fileContent).digest('hex').slice(0, 16);
457
- const hashedName = `${slugifyFileName(baseName)}.${hash}${ext}`;
458
-
459
- const destPath = path.join(assetsDir, hashedName);
460
- copyFileSync(absolutePath, destPath);
461
-
462
- return `${ASSETS_URL_PREFIX}/${hashedName}`;
463
- }
464
-
465
- function slugifyFileName(name: string): string {
466
- return name
467
- .toLowerCase()
468
- .replace(/[^a-z0-9.-]/g, '-')
469
- .replace(/-+/g, '-')
470
- .replace(/^-|-$/g, '');
471
- }
472
-
473
- // Link resolution logic adapted from packages/portal/src/server/plugins/markdown/attribute-resolvers/resolve-link.ts
474
-
475
- const DOC_EXTENSIONS = new Set(['.adoc', '.asciidoc', '.html', '.md']);
476
-
477
- function isLocalLink(href: string): boolean {
478
- return (
479
- href != null &&
480
- !href.match(/^[a-z]+:\/\//) &&
481
- !href.startsWith('//') &&
482
- !href.startsWith('mailto:')
483
- );
484
- }
485
-
486
- function stripKnownExtensions(filePath: string): string {
487
- for (const ext of DOC_EXTENSIONS) {
488
- if (filePath.endsWith(ext)) return filePath.slice(0, -ext.length);
489
- }
490
- return filePath;
491
- }
492
-
493
- function resolveAsciidocLink(
494
- href: string,
495
- fromPage: string,
496
- dataContext: GetStaticDataContext,
497
- ): string {
498
- if (!href || href.startsWith('#') || !isLocalLink(href)) {
499
- return href;
500
- }
501
-
502
- const hashIdx = href.indexOf('#');
503
- const pathAndQuery = hashIdx >= 0 ? href.slice(0, hashIdx) : href;
504
- const hashPart = hashIdx >= 0 ? href.slice(hashIdx) : '';
505
-
506
- const qIdx = pathAndQuery.indexOf('?');
507
- const rawPath = qIdx >= 0 ? pathAndQuery.slice(0, qIdx) : pathAndQuery;
508
- const queryPart = qIdx >= 0 ? pathAndQuery.slice(qIdx) : '';
509
-
510
- if (!rawPath) return href;
511
-
512
- const ext = path.posix.extname(rawPath);
513
-
514
- if (DOC_EXTENSIONS.has(ext)) {
515
- const fsRelativePath = rawPath.startsWith('/')
516
- ? rawPath.slice(1)
517
- : path.posix.normalize(path.posix.join(path.posix.dirname(fromPage), rawPath));
518
-
519
- const route = dataContext.getRouteByFsPath(fsRelativePath);
520
- if (route) {
521
- return maybeAddPathPrefix(route.slug + queryPart + hashPart);
522
- }
523
-
524
- const slug = '/' + stripKnownExtensions(fsRelativePath).replace(/\/index$/, '');
525
- const routeBySlug = dataContext.getRouteBySlug(slug, { followRedirect: true });
526
- if (routeBySlug) {
527
- return maybeAddPathPrefix(routeBySlug.slug + queryPart + hashPart);
528
- }
529
-
530
- return maybeAddPathPrefix(slug + queryPart + hashPart);
531
- }
532
-
533
- if (ext === '') {
534
- if (rawPath.startsWith('/')) {
535
- const route = dataContext.getRouteBySlug(rawPath, { followRedirect: true });
536
- if (route) {
537
- return maybeAddPathPrefix(route.slug + queryPart + hashPart);
538
- }
539
- return maybeAddPathPrefix(rawPath + queryPart + hashPart);
540
- }
541
-
542
- const currentRoute = dataContext.getRouteByFsPath(fromPage);
543
- if (currentRoute) {
544
- const isIndexFile =
545
- fromPage.endsWith('/index.adoc') ||
546
- fromPage.endsWith('/index.md') ||
547
- fromPage.endsWith('/index.html');
548
- const base = isIndexFile ? currentRoute.slug : path.posix.dirname(currentRoute.slug);
549
- const resolved = path.posix.normalize(path.posix.join(base, rawPath));
550
- const normalizedSlug = '/' + resolved.replace(/^\/+/, '');
551
-
552
- const route = dataContext.getRouteBySlug(normalizedSlug, { followRedirect: true });
553
- if (route) {
554
- return maybeAddPathPrefix(route.slug + queryPart + hashPart);
555
- }
556
- return maybeAddPathPrefix(normalizedSlug + queryPart + hashPart);
557
- }
558
-
559
- const baseDir = path.posix.dirname(fromPage);
560
- const joined = path.posix.normalize(path.posix.join(baseDir, rawPath));
561
- const slug = '/' + joined.replace(/^\/+/, '');
562
- return maybeAddPathPrefix(slug + queryPart + hashPart);
563
- }
564
-
565
- return href;
566
- }
567
-
568
- function maybeAddPathPrefix(url: string): string {
569
- const prefix = getPathPrefix();
570
- if (!prefix || url.startsWith(prefix)) return url;
571
- return withPathPrefix(url);
572
- }
573
-
574
- function resolveHtmlLinks(
575
- html: string,
576
- fromPage: string,
577
- dataContext: GetStaticDataContext,
578
- ): string {
579
- return html.replace(
580
- /(<a\s[^>]*?href=")([^"]*?)("[^>]*?>)/gi,
581
- (_match, before: string, href: string, after: string) => {
582
- return before + resolveAsciidocLink(href, fromPage, dataContext) + after;
583
- },
584
- );
585
- }
586
-
587
- function resolveContentNodeLinks(
588
- nodes: ContentNode[],
589
- fromPage: string,
590
- dataContext: GetStaticDataContext,
591
- ): ContentNode[] {
592
- return nodes.map((node) => resolveNodeLinks(node, fromPage, dataContext));
593
- }
594
-
595
- function resolveNodeLinks(
596
- node: ContentNode,
597
- fromPage: string,
598
- ctx: GetStaticDataContext,
599
- ): ContentNode {
600
- switch (node.type) {
601
- case 'paragraph':
602
- return {
603
- ...node,
604
- contentHtml: resolveHtmlLinks(node.contentHtml, fromPage, ctx),
605
- };
606
- case 'heading':
607
- return {
608
- ...node,
609
- contentHtml: resolveHtmlLinks(node.contentHtml, fromPage, ctx),
610
- };
611
- case 'section':
612
- return {
613
- ...node,
614
- titleHtml: resolveHtmlLinks(node.titleHtml, fromPage, ctx),
615
- children: resolveContentNodeLinks(node.children, fromPage, ctx),
616
- };
617
- case 'admonition':
618
- case 'quote':
619
- case 'sidebar':
620
- case 'example':
621
- case 'collapsible':
622
- return {
623
- ...node,
624
- children: resolveContentNodeLinks(node.children, fromPage, ctx),
625
- };
626
- case 'list':
627
- return {
628
- ...node,
629
- items: node.items.map((item) => ({
630
- ...item,
631
- contentHtml: resolveHtmlLinks(item.contentHtml, fromPage, ctx),
632
- children: resolveContentNodeLinks(item.children, fromPage, ctx),
633
- })),
634
- };
635
- case 'descriptionList':
636
- return {
637
- ...node,
638
- items: node.items.map((item) => ({
639
- ...item,
640
- termsHtml: item.termsHtml.map((h) => resolveHtmlLinks(h, fromPage, ctx)),
641
- descriptionHtml: resolveHtmlLinks(item.descriptionHtml, fromPage, ctx),
642
- children: resolveContentNodeLinks(item.children, fromPage, ctx),
643
- })),
644
- };
645
- case 'table':
646
- return {
647
- ...node,
648
- head: node.head.map((row) =>
649
- row.map((cell) => ({
650
- ...cell,
651
- contentHtml: resolveHtmlLinks(cell.contentHtml, fromPage, ctx),
652
- })),
653
- ),
654
- body: node.body.map((row) =>
655
- row.map((cell) => ({
656
- ...cell,
657
- contentHtml: resolveHtmlLinks(cell.contentHtml, fromPage, ctx),
658
- })),
659
- ),
660
- foot: node.foot.map((row) =>
661
- row.map((cell) => ({
662
- ...cell,
663
- contentHtml: resolveHtmlLinks(cell.contentHtml, fromPage, ctx),
664
- })),
665
- ),
666
- };
667
- case 'htmlPassthrough':
668
- return {
669
- ...node,
670
- html: resolveHtmlLinks(node.html, fromPage, ctx),
671
- };
672
- default:
673
- return node;
674
- }
675
- }