-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path_config.ts
More file actions
1038 lines (901 loc) · 31.6 KB
/
_config.ts
File metadata and controls
1038 lines (901 loc) · 31.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import lume from "lume/mod.ts";
import icons from "lume/plugins/icons.ts";
import pagefind from "./_plugins/pagefind.ts";
import date from "lume/plugins/date.ts";
import sass from "lume/plugins/sass.ts";
import inline from "lume/plugins/inline.ts";
import esbuild from "lume/plugins/esbuild.ts";
import prism from "lume/plugins/prism.ts";
import sitemap from "lume/plugins/sitemap.ts";
import feed from "lume/plugins/feed.ts";
import jsx from "lume/plugins/jsx.ts";
import mdx from "lume/plugins/mdx.ts";
import { slugify } from "./_components/utils/stringHelpers.ts";
import { parse as yamlParse } from "@std/yaml";
// Data highlights
import "prismjs/components/prism-yaml.js";
import "prismjs/components/prism-json.js";
import "prismjs/components/prism-toml.js";
// Lang highlights
import "prismjs/components/prism-bash.js";
import "prismjs/components/prism-ruby.js";
import "prismjs/components/prism-scss.js";
import "prismjs/components/prism-typescript.js";
import "prismjs/components/prism-python.js";
import "prismjs/components/prism-go.js";
// Required language dependencies for languages like liquid
import "prismjs/components/prism-markup-templating.js";
// Template highlights
import "prismjs/components/prism-markdown.js";
import "prismjs/components/prism-liquid.js";
import "prismjs/components/prism-jsx.js";
// Custom highlights
import "./_config/prism-tree.ts";
import "./_config/prism-annotated.ts";
import { DOMParser } from "@b-fuze/deno-dom";
//import { Page } from "lume/core.ts";
import { Element } from "lume/deps/dom.ts";
import { extract } from "lume/deps/front_matter.ts";
import { remark } from "remark";
import remarkParse from "remark-parse";
import strip from "strip-markdown";
import { parseChangelogFilename } from "./parseChangelogFilename.ts";
import type { ContentNavItem, DocEntry } from "./_types.d.ts";
import { buildRefNav } from "./developer/reference/_shared/buildRefNav.ts";
import documentation from "@cloudcannon/configuration-types/dist/documentation.json" with {
type: "json",
};
import llmsTxt from "./_config/llms-text.ts";
import markdownPages from "./_config/markdown-pages.ts";
// Type the documentation as nested sections (section -> gid -> entry)
const typedDocs = documentation as unknown as Record<
string,
Record<string, DocEntry>
>;
// Store nested documentation structure for section-aware lookups
globalThis.DOCS = typedDocs;
// Partition documentation entries by section for layouts
const routingDocs: DocEntry[] = Object.values(
typedDocs["type.Routing"] ?? {},
);
const initialSiteSettingsDocs: DocEntry[] = Object.values(
typedDocs["type.InitialSiteSettings"] ?? {},
);
const configDocs: DocEntry[] = Object.values(
typedDocs["type.Configuration"] ?? {},
);
// Build timing instrumentation
const buildTimings: Record<string, number> = {};
const phaseStarts: Record<string, number> = {};
// Caches for expensive operations (persist across incremental builds)
const renderTextOnlyCache = new Map<string, string>();
const glossaryTermCache = new Map<string, string>();
const glossaryTermNameCache = new Map<string, string>();
const changelogDescriptionCache = new Map<string, string>();
// Reusable remark processor (avoid recreating on each call)
// deno-lint-ignore no-explicit-any
let remarkProcessor: any = null;
function getRemarkProcessor() {
if (!remarkProcessor) {
remarkProcessor = remark().use(remarkParse).use(strip);
}
return remarkProcessor;
}
function startPhase(name: string) {
phaseStarts[name] = performance.now();
}
function endPhase(name: string) {
buildTimings[name] = performance.now() - phaseStarts[name];
}
function stripHTML(html: string): string {
const doc = new DOMParser().parseFromString(html, "text/html");
return doc?.body?.textContent || "";
}
const domainsRegExp = new RegExp("cloudcannon.com|^\/|^\#");
const site = lume({
location: new URL("https://cloudcannon.com/documentation/"),
server: {
port: 9010,
},
});
// Build precompiled reference navigation
const refNavSections = buildRefNav(
configDocs,
routingDocs,
initialSiteSettingsDocs,
);
site.data("ref_nav", refNavSections);
// Track whether we're in an update cycle (vs initial build)
let isUpdating = false;
let updatePageCount = 0;
// Build timing event listeners
site.addEventListener("afterLoad", () => {
endPhase("load");
startPhase("render");
if (!isUpdating) {
console.log(` Load files: ${buildTimings.load.toFixed(0)}ms`);
}
});
site.addEventListener("afterRender", (event) => {
endPhase("render");
startPhase("process");
updatePageCount = event.pages.length;
if (!isUpdating) {
console.log(
` Render pages: ${
buildTimings.render.toFixed(0)
}ms (${event.pages.length} pages)`,
);
}
});
site.addEventListener("beforeSave", () => {
endPhase("process");
startPhase("save");
if (!isUpdating) {
console.log(` Process HTML: ${buildTimings.process.toFixed(0)}ms`);
}
});
site.addEventListener("afterBuild", (event) => {
endPhase("save");
endPhase("total");
console.log(` Save files: ${buildTimings.save.toFixed(0)}ms`);
console.log(` ─────────────────────────`);
console.log(` TOTAL: ${buildTimings.total.toFixed(0)}ms`);
console.log(` Pages built: ${event.pages.length}`);
console.log(` Static files: ${event.staticFiles.length}`);
console.log("=== BUILD TIMING END ===\n");
});
// Incremental update timing (for watch mode)
site.addEventListener("beforeUpdate", (event) => {
isUpdating = true;
startPhase("update");
startPhase("load");
console.log(`\n=== UPDATE START (${event.files.size} files changed) ===`);
for (const file of event.files) {
console.log(` Changed: ${file}`);
}
});
site.addEventListener("afterUpdate", (event) => {
endPhase("save");
endPhase("update");
console.log(` ─────────────────────────`);
console.log(` Load files: ${buildTimings.load.toFixed(0)}ms`);
console.log(
` Render pages: ${
buildTimings.render.toFixed(0)
}ms (${updatePageCount} pages)`,
);
console.log(` Process HTML: ${buildTimings.process.toFixed(0)}ms`);
console.log(` Save files: ${buildTimings.save.toFixed(0)}ms`);
console.log(` ─────────────────────────`);
console.log(` TOTAL: ${buildTimings.update.toFixed(0)}ms`);
console.log(` Pages rebuilt: ${event.pages.length}`);
console.log("=== UPDATE END ===\n");
isUpdating = false;
});
// Log the server URL when it starts (currently suppressed by LUME_LOGS=critical)
site.addEventListener("afterStartServer", () => {
const port = site.options.server.port;
console.log(
`\n Server running at: http://localhost:${port}/documentation/\n`,
);
});
// Configure scoped updates for faster incremental rebuilds
// Files in each scope only rebuild when files in that scope change
site.scopedUpdates(
// CSS/SCSS files are independent
(path) => /\.(css|scss)$/.test(path),
);
site.use(icons());
const injectedSections: Promise<string>[] = [];
const mdFilter = site.renderer.helpers.get("md")?.[0];
site.ignore("README.md", "AGENTS.md", "unused", "STYLE_GUIDE.mdx", "scripts");
// Detect dev mode (serve command uses -s flag)
const isDevMode = Deno.args.includes("-s") || Deno.args.includes("--serve");
// In dev mode, only load recent changelogs for faster builds
if (isDevMode) {
site.ignore(
"changelogs/2015",
"changelogs/2016",
"changelogs/2017",
"changelogs/2018",
"changelogs/2019",
"changelogs/2020",
"changelogs/2021",
"changelogs/2022",
"changelogs/2023",
);
console.log(" Dev mode: Loading only recent changelogs (2024-2025)");
}
// Sets `/documentation/` through the url filter when running locally
if (isDevMode) {
site.options.location = new URL("http://localhost:9010/documentation/");
}
// Output all files to `/documentation/*` to match the location
// (by default `_site/index.html` would represent `https://cloudcannon.com/documentation/`,
// but to subpath it on CloudCannon we want this at `_site/documentation/index.html`)
site.preprocess("*", (pages) =>
pages.forEach((page) => {
page.data.url = `/documentation${page.data.url}`;
}));
// Creates an excerpt for all changelogs saved in description.
site.preprocess([".md", ".mdx"], (pages) =>
pages.forEach((page) => {
if (
!page.data.description && page.src.path.startsWith("/changelogs/")
) {
const parsedDate = parseChangelogFilename(page.src.path);
if (parsedDate) {
page.data.date = parsedDate;
}
const firstLine = String(page.data.content).trim().split("\n")[0];
if (!firstLine) {
return;
}
// Cache key based on path + first line (description only depends on these)
const cacheKey = `${page.src.path}:${firstLine}`;
const cached = changelogDescriptionCache.get(cacheKey);
if (cached) {
page.data.description = cached;
return;
}
const markdownInline = mdFilter?.(firstLine, true) || "";
const description = stripHTML(markdownInline);
changelogDescriptionCache.set(cacheKey, description);
page.data.description = description;
}
}));
site.copy("ye_olde_images", "documentation/ye_olde_images");
site.copy("assets/external_screenshots", "documentation/assets/external_screenshots");
site.copy("assets/onboarding_screenshots", "documentation/assets/onboarding_screenshots");
site.copy("assets/diagrams", "documentation/assets/diagrams");
site.copy("assets/deprecated", "documentation/assets/deprecated");
site.copy("uploads", "documentation/static");
site.copy("robots.txt", "documentation/robots.txt");
if (Deno.env.get("DOCSHOTS_LOCAL")) {
site.copy("local-docshots", "documentation/local-docshots");
}
// Temporary trick to disable indented code blocks if we happen to use markdown-it
// deno-lint-ignore no-explicit-any
(site.formats.get(".md")?.engines?.[0] as any)?.engine?.disable?.("code");
// Pagefind search indexing - runs automatically after each build
// Uses local plugin (_plugins/pagefind.ts) with pagefind v1.5.0-beta.1
site.use(pagefind({
outputPath: "/documentation/_pagefind",
ui: false, // Disable old PagefindUI
componentUI: true, // Enable new Component UI (v1.5+)
}));
site.use(jsx());
site.use(mdx());
site.use(esbuild());
site.add("/assets/js/site.js", "/documentation/assets/js/site.js");
site.use(sass());
site.add("/assets/css/site.scss", "/documentation/assets/css/site.css");
site.add("/assets/img", "/documentation/assets/img");
// Uploads are copied via site.copy() above - don't also add them here
// site.add("/uploads");
site.use(date());
site.use(sitemap({
filename: "/documentation/sitemap.xml",
query: "!url^=/documentation/404/",
}));
site.use(markdownPages());
site.use(llmsTxt());
// Changelog RSS feed - uses changelogs tag (year pages use changelog-year tag instead)
site.use(feed({
output: ["/documentation/changelog/feed.xml"],
query: "changelogs",
sort: "date=desc",
limit: 20,
info: {
title: "CloudCannon Documentation Changelog",
description: "Latest updates and changes to CloudCannon",
},
items: {
title: "=title",
description: "=description",
published: "=date",
content: "=children",
},
}));
site.loadPages(
[".md"],
((page: Lume.Page) => {
if (page.src.path.startsWith("user/glossary/")) {
page.data.collection = "glossary";
}
}) as unknown as undefined,
);
// JSX doesn't like to output some alpine attributes,
// so we write them with an `alpine` prefix and re-map them here.
const alpineRemaps = {
"alpine:class": ":class",
"alpine:click": "@click",
"alpine:href": ":href",
"alpine:src": ":src",
"alpine:style": ":style",
"alpine:key": ":key",
"alpine-click-stop": "@click.stop",
"alpine-click-away": "@click.away",
"alpine-click-outside": "@click.outside",
"alpine:checked": ":checked",
"alpine:scroll": "x-on:scroll.window.throttle.50ms",
"alpine-scroll-window": "@scroll.window",
"alpine-resize-window": "@resize.window",
"alpine-keydown-down": "@keydown.down",
"alpine-keydown-up": "@keydown.up",
"alpine-keydown-down-prevent": "@keydown.down.prevent",
"alpine-keydown-up-prevent": "@keydown.up.prevent",
"alpine-keydown-escape": "@keydown.escape",
"alpine-keydown-window-prevent-ctrl-k": "@keydown.window.prevent.ctrl.k",
"alpine-keydown-window-prevent-cmd-k": "@keydown.window.prevent.cmd.k",
"x-trap-inert": "x-trap.inert",
"x-trap-noscroll": "x-trap.noscroll",
"x-on-toggle": "x-on:toggle",
"x-on-click": "x-on:click",
"x-on-keydown": "x-on:keydown",
"x-on-mouseenter": "x-on:mouseenter",
"x-on-mouseleave": "x-on:mouseleave",
};
function createLink(page: Lume.Page, text: string, href: string) {
const a = page.document!.createElement("a");
const linkText = page.document!.createTextNode(text);
a.appendChild(linkText);
a.setAttribute("href", href);
return a;
}
function appendTargetBlank(_page: Lume.Page, el: Element): void {
if (el.hasAttribute("href")) {
const href = el.getAttribute("href");
if (href && !domainsRegExp.test(href)) {
el.setAttribute("target", "_blank");
el.setAttribute("rel", "noopener");
}
}
}
const commentAnnotationRegex =
/^\/\*\s*(\d+|\*)\s*\*\/$|^(?:\/\/|#)\s*(\d+|\*)\s*|^<!--\s*(\d+|\*)\s*-->$/;
const tokenAnnotationRegex = /___(\d+|\*)___/g;
const annotateCodeBlocks = (page: Lume.Page): void => {
// Comment tokens for standard code blocks, annotations
// are inserted for syntax comments containing only digits
page.document?.querySelectorAll(".token.comment").forEach((commentEl) => {
const el = commentEl as HTMLElement;
if (!commentAnnotationRegex.test(el.innerText)) return;
const matches = el.innerText.match(commentAnnotationRegex);
const annotationId = matches?.[1] ?? matches?.[2] ?? matches?.[3];
if (!annotationId) return;
// Empty the comment token and replace it with a clickable annotation box
el.innerText = "";
el.classList.add("annotation", "code-annotation");
if (annotationId === "*" || annotationId === "0") {
el.setAttribute("data-annotation-number", "★");
} else {
el.setAttribute("data-annotation-number", annotationId);
el.setAttribute("@click", `highlighedAnnotation = ${annotationId}`);
}
});
// Any text for MultiCodeBlocks, annotations are inserted any time
// a digit surrounded by three underscores on either side is encountered
page.document?.querySelectorAll(".highlight > pre > code").forEach(
(codeEl) => {
[...codeEl.childNodes].reverse().forEach((tokenEl) => {
const token = tokenEl as HTMLElement & { nodeValue?: string };
const is_text = token.nodeName === "#text";
if (
!tokenAnnotationRegex.test(
is_text ? (token.nodeValue || "") : (token.innerText || ""),
)
) return;
const matches = (is_text ? token.nodeValue : token.innerText)?.match(
tokenAnnotationRegex,
);
for (const match of matches || []) {
const annotationId = match.replace(/___/g, "");
if (!annotationId) continue;
// Create a new empty comment token as a clickable annotation box
const commentEl = page.document?.createElement("span");
commentEl.classList.add(
"token",
"comment",
"annotation",
"code-annotation",
);
if (annotationId === "*" || annotationId === "0") {
commentEl.setAttribute("data-annotation-number", "★");
} else {
commentEl.setAttribute("data-annotation-number", annotationId);
commentEl.setAttribute(
"@click",
`highlighedAnnotation = ${annotationId}`,
);
}
// To insert after the token containing the annotation
// const insert_before_el = token.nextSibling || token;
// To insert at the end of the line containing the annotation
let next_newline: ChildNode | null = null;
let next_el: ChildNode | null = token;
while (next_el && !next_newline) {
const nodeEl = next_el as HTMLElement & { nodeValue?: string };
if (
/\n/.test(nodeEl?.nodeValue ?? "") ||
/\n/.test(nodeEl?.innerText ?? "")
) {
next_newline = next_el;
break;
}
next_el = next_el.nextSibling;
}
let insert_before_el: ChildNode | null = next_newline || token;
// Text nodes might span multiple lines, so we split it on newlines
// and re-add each as independent text nodes, so that we can add an element before
// the newline.
const insertNodeValue = (insert_before_el as Text)?.nodeValue;
if (insertNodeValue && /\n/.test(insertNodeValue)) {
const chunks = insertNodeValue
.split("\n")
.map((chunk: string) => page.document!.createTextNode(chunk));
for (let i = 0; i < chunks.length; i += 1) {
insert_before_el?.parentNode?.insertBefore(
chunks[i],
insert_before_el,
);
if (i !== chunks.length - 1) {
insert_before_el?.parentNode?.insertBefore(
page.document!.createTextNode("\n"),
insert_before_el,
);
}
}
insert_before_el?.remove();
insert_before_el = chunks[0].nextSibling;
}
insert_before_el?.parentNode?.insertBefore(
commentEl,
insert_before_el,
);
}
if (is_text) {
token.nodeValue = (token.nodeValue || "").replace(
tokenAnnotationRegex,
"",
);
} else {
token.innerText = (token.innerText || "").replace(
tokenAnnotationRegex,
"",
);
}
});
},
);
};
const injectReusableContent = async (el: Element) => {
const reusableContent = el.querySelectorAll(
`:scope [data-common-content-id]`,
);
for (const node of reusableContent) {
const injectionEl = node as Element;
const injectionSlots: Record<string, string> = {};
for (
const slotContentEl of injectionEl.querySelectorAll(
`:scope [data-common-content-slot-content]`,
)
) {
const slotName = (slotContentEl as Element).getAttribute(
"data-common-content-slot-content",
);
if (!slotName) continue;
injectionSlots[slotName] = (slotContentEl as Element).innerHTML;
}
const content_id = parseInt(
injectionEl.getAttribute("data-common-content-id")!,
);
const content = await injectedSections[content_id];
injectionEl.innerHTML = content?.toString() || content;
for (
const slotEl of injectionEl.querySelectorAll(
`:scope [data-common-content-slot]`,
)
) {
const slotName = (slotEl as Element).getAttribute(
"data-common-content-slot",
);
if (!slotName) continue;
if (injectionSlots[slotName]) {
(slotEl as Element).innerHTML = injectionSlots[slotName];
}
}
injectReusableContent(injectionEl);
}
};
site.process([".html"], async (pages) => {
await Promise.all(pages.map(async (page) => {
if (page.document) {
await injectReusableContent(page.document.body as unknown as Element);
}
// Helper function to remap Alpine attributes
// deno-lint-ignore no-explicit-any
function remapAlpineAttrs(root: any): void {
for (const [attr, newattr] of Object.entries(alpineRemaps)) {
root?.querySelectorAll(`[${attr}]`).forEach(
(
el: {
setAttribute: (a: string, b: string) => void;
getAttribute: (a: string) => string | null;
removeAttribute: (a: string) => void;
},
) => {
el.setAttribute(newattr, el.getAttribute(attr) || "");
el.removeAttribute(attr);
},
);
}
// Also process elements inside <template> tags
// deno-lint-ignore no-explicit-any
root?.querySelectorAll("template").forEach((template: any) => {
if (template.content) {
remapAlpineAttrs(template.content);
}
});
}
remapAlpineAttrs(page.document);
const collisions: Record<string, boolean> = {};
function fixIdCollisions(slugPrefix: string): string {
let slug = slugPrefix;
let count = 0;
while (collisions[slug]) {
count += 1;
slug = `${slugPrefix}-${count}`;
}
collisions[slug] = true;
return slug;
}
let tocContainer = page.document?.querySelectorAll(`.l-toc`)?.[0];
const toc = page.document.createElement("ol");
toc.classList.add("l-toc__list");
// deno-lint-ignore no-explicit-any
function appendAnchorHeader(el: any, slug: string): void {
el.setAttribute("id", slug);
el.classList.add("c-anchor-header");
const link = createLink(page, "#", `#${slug}`);
link.classList.add("c-anchor-header__link");
link.setAttribute("data-pagefind-ignore", "true");
el.appendChild(link);
}
let hasItems = false;
let selector =
`main h1:not(.exclude-from-toc), main h2:not(.exclude-from-toc)`;
if (!tocContainer) {
tocContainer = page.document?.querySelectorAll(`.l-toc-changelog-list`)
?.[0];
if (tocContainer) {
selector = `main .changelog-entry > h2`;
}
}
if (!tocContainer) {
tocContainer = page.document?.querySelectorAll(`.l-toc-glossary`)?.[0];
if (tocContainer) {
selector = `main .c-card--glossary .c-card__title`;
}
}
if (!tocContainer) {
return;
}
page.document?.querySelectorAll(selector).forEach((el) => {
if (el.hasAttribute("data-skip-anchor")) return;
const text = (el as HTMLElement).innerText || el.textContent || "";
const slugPrefix = el.getAttribute("id") || slugify(text);
if (!slugPrefix) {
return;
}
const slug = fixIdCollisions(slugPrefix);
appendAnchorHeader(el, slug);
if (tocContainer) {
hasItems = true;
const li = page.document!.createElement("li");
li.setAttribute(
"x-bind:class",
`visibleHeadingId === '${slug}' ? 'active' : ''`,
);
li.appendChild(createLink(page, text, `#${slug}`));
toc.appendChild(li);
}
});
page.document?.querySelectorAll(`.c-data-reference__header`).forEach(
(el) => {
const keyEl = el.querySelector(".c-data-reference__key") as
| HTMLElement
| null;
const text = keyEl?.innerText || keyEl?.textContent || "";
const slug = fixIdCollisions(text);
appendAnchorHeader(el, slug);
},
);
if (hasItems) {
const h3 = page.document.createElement("h3");
h3.classList.add("l-toc__heading");
const headingText = page.document.createTextNode("On this page");
h3.appendChild(headingText);
tocContainer?.appendChild(h3);
tocContainer?.appendChild(toc);
}
page.document?.querySelectorAll("a").forEach((el) => {
appendTargetBlank(page, el as unknown as Element);
});
const mobile_toc = page.document?.querySelector(
".l-toc-mobile > .l-toc__list",
);
if (mobile_toc) {
mobile_toc.innerHTML = toc?.innerHTML || "";
if (!toc || toc.childNodes.length == 0) {
mobile_toc.closest(".l-toc-mobile")?.remove();
}
}
}));
});
// These MUST appear after our custom site.process([".html"] handling,
// as in that function we inject content that should then be processed by the inline plugin,
// and processing runs in the order it was instantiated.
// Note: inline should be used before feed per lume best practices, but we need it after our custom HTML processing
// deno-lint-ignore lume/plugin-order
site.use(inline());
site.use(prism());
// This annotation process relies on the syntax highlighting,
// so needs to run after prism
site.process([".html"], async (pages) => {
await Promise.all(pages.map((page) => {
annotateCodeBlocks(page);
}));
});
site.filter(
"get_by_uuid",
(resources: Array<{ _uuid?: string }>, uuid: string) => {
const found = resources.filter((x: { _uuid?: string }) => x._uuid === uuid);
if (found && found.length > 0) {
return found[0];
}
return null;
},
);
site.filter("is_gid_inside", (gid: string | undefined, parentGid: string) => {
if (gid) {
return parentGid === "type.Configuration"
? !gid.startsWith("type.")
: gid.startsWith(`${parentGid}.`);
} else return false;
});
// Helper to find a doc by gid across all sections
function findDocByGid(gid: string): DocEntry | null {
for (const section of Object.values(typedDocs)) {
if (section && section[gid]) {
return section[gid];
}
}
return null;
}
// Helper to find a doc by gid within a specific section (derived from parent chain)
function findDocInSection(
gid: string,
sectionDocs: Record<string, DocEntry>,
): DocEntry | null {
return sectionDocs[gid] || null;
}
// Derive the section from a doc entry by walking up the parent chain
function getSectionFromDoc(doc: DocEntry): Record<string, DocEntry> | null {
// Check each section for this doc's gid
for (const [_sectionKey, sectionDocs] of Object.entries(typedDocs)) {
if (sectionDocs && doc.gid && sectionDocs[doc.gid]) {
return sectionDocs;
}
}
return null;
}
site.filter("get_docs_by_gid", (gid: string) => {
return findDocByGid(gid);
});
site.filter("get_docs_by_ref", (docRef: DocEntry) => {
const doc = findDocByGid(docRef.gid || "") || docRef;
if (docRef.documentation) {
// Use more specific documentation entry
return {
...doc,
title: docRef.documentation.title || doc.title,
description: docRef.documentation.description || doc.description,
examples: docRef.documentation.examples?.length
? docRef.documentation.examples
: doc.documentation?.examples,
documentation: docRef.documentation,
};
}
return doc;
});
site.filter("parent_gids_from_doc", (doc: DocEntry) => {
// Get the section this doc belongs to
const sectionDocs = getSectionFromDoc(doc);
const parentGids: string[] = [];
let parentGid = doc.parent;
while (parentGid) {
parentGids.unshift(parentGid);
const parentDoc = sectionDocs
? findDocInSection(parentGid, sectionDocs)
: findDocByGid(parentGid);
parentGid = parentDoc?.parent;
}
return parentGids;
});
// TODO: Redo docnav as JSX and move this logic into the component
const bubble_up_nav = (obj: ContentNavItem): string[] | undefined => {
if (obj._bubbled) return;
if (obj._type === "heading" || obj._type === "group") {
const articles = obj.items
? obj.items.flatMap((o: ContentNavItem) => bubble_up_nav(o) || [])
: [];
obj._bubbled = articles;
return articles;
} else {
// TODO: Temporary URL map, until a UUID refactor.
return obj.articles;
}
};
site.filter("render_page_content", async (page: Lume.Page) => {
return await site.renderer.render(
page.data.content,
page.data,
`${page.src.path}.${page.src.ext || "mdx"}`,
);
}, true);
site.filter("render_text_only", async (markdown: string) => {
// Check cache first
const cached = renderTextOnlyCache.get(markdown);
if (cached !== undefined) {
return cached;
}
const result = await getRemarkProcessor().process(markdown);
const text = String(result).trim();
renderTextOnlyCache.set(markdown, text);
return text;
}, true);
site.filter("bubble_up_nav", (blocks: ContentNavItem[]) => {
blocks.forEach(bubble_up_nav);
return blocks;
});
site.filter(
"nav_contains",
(nav: { headings: ContentNavItem[] }, url: string) => {
nav.headings.forEach(bubble_up_nav);
for (const block of nav.headings) {
if (block._bubbled?.includes(url)) {
return true;
}
}
return false;
},
);
site.filter("index_of", (block: unknown[], item: unknown) => {
return block.indexOf(item);
});
site.filter("unslug", (str: string) => {
return str.replace(
/(^|_)(\w)/g,
(_: string, u: string, c: string) =>
`${u.replace("_", " ")}${c.toUpperCase()}`,
);
});
const summaryMarker = "</p>";
site.filter("changelog_summary", (block: string, _item: unknown) => {
return block.substring(
0,
block.indexOf(summaryMarker) + summaryMarker.length,
);
});
site.filter(
"render_common",
(file: string, data: Record<string, unknown> = {}) => {
// TODO: Remove the `/usr/local/__site/src/` replacement after fixing path selection
const file_content = Deno.readTextFileSync(
file.replace("/usr/local/__site/src/", ""),
);
const { body } = extract(file_content);
const content_id = injectedSections.push(
site.renderer.render(body, data, file),
);
return content_id - 1;
},
);
site.filter("get_glossary_term", (file: string) => {
// Check cache first
const cached = glossaryTermCache.get(file);
if (cached !== undefined) {
return cached;
}
const mdFilterFn = site.renderer.helpers.get("md")?.[0];
const file_content = Deno.readTextFileSync(`${file.slice(1)}`);
// deno-lint-ignore no-explicit-any
const yml = yamlParse(file_content) as any;
const description = mdFilterFn?.(yml?.term_description) || "";
glossaryTermCache.set(file, description);
return description;
});
site.filter("get_glossary_term_name", (file: string) => {
const cached = glossaryTermNameCache.get(file);
if (cached !== undefined) {
return cached;
}
const file_content = Deno.readTextFileSync(`${file.slice(1)}`);
// deno-lint-ignore no-explicit-any
const yml = yamlParse(file_content) as any;
const name = yml?.glossary_term_name || "";
glossaryTermNameCache.set(file, name);
return name;
});
site.filter("get_index_page", (page: string) => {
page = page.replace("/documentation", "").split("/")[1];
if (page.indexOf("-") != -1) {
try {
const page_parts = page.split("-");
const file_content = Deno.readTextFileSync(
`${page_parts[0]}/${page_parts[1]}/index.mdx`,
);
const { attrs } = extract(file_content);
return {
attrs: attrs as Record<string, unknown>,
url: `/documentation/${page_parts[0]}-${page_parts[1]}/`,
};
} catch (_e) {
//console.log(e);
}
}
//else
//console.log("no")
return null;
});
let changelogsData: { keys: string[]; [year: string]: number | string[] } = {
keys: [],
};
site.addEventListener("beforeBuild", async () => {
startPhase("total");
startPhase("load");
console.log("\n=== BUILD TIMING START ===");
const dir = "changelogs";
const years: { keys: string[]; [year: string]: number | string[] } = {
keys: [],
};
for await (const entry of Deno.readDir(dir)) {
if (entry.isDirectory) {
const dirname = entry.name;
years.keys.push(dirname);
years[dirname] = 0;
const subdir = `${dir}/${dirname}`;
for await (const entry of Deno.readDir(subdir)) {
if (entry.isFile) {