1 // 🐙🕸️ GitWikiWeb ∷ build.js
2 // ====================================================================
4 // Copyright © 2023 Lady [@ Lady’s Computer].
6 // This Source Code Form is subject to the terms of the Mozilla Public
7 // License, v. 2.0. If a copy of the MPL was not distributed with this
8 // file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
10 // --------------------------------------------------------------------
12 // A script for generating static wiki pages from a git repository.
14 // First, clone this repository to your machine in an accessible
15 // location (for example, `/srv/git/GitWikiWeb`). A bare repository is
16 // fine; customize the templates and stylesheets as you like. Then, use
17 // this file as the post‐receive hook for your wiki as follows :—
19 // #!/usr/bin/env -S sh
20 // export GITWIKIWEB=/srv/git/GitWikiWeb
21 // git archive --remote=$GITWIKIWEB HEAD build.js \
23 // | deno run -A - ~/public/wiki $GITWIKIWEB current
25 // The directory `~/public/wiki` (or whatever you specify as the first
26 // argument to `deno run -A -`) **will be deleted** and a new static
27 // wiki will be generated in its place. This script is not very smart
28 // (yet) and cannot selectively determine which pages will need
29 // updating. It just wipes and regenerates the whole thing.
31 // This script will make a number of requests to `$GITWIKIWEB` to
32 // download the latest templates, stylesheets, ⁊·c from this
33 // repository. Consequently, it is best that you set it to a repository
34 // you control and can ensure uptime for—ideally one local to the
35 // computer hosting the wiki.
40 } from "https://deno.land/std@0.196.0/fs/mod.ts";
44 } from "https://deno.land/std@0.196.0/yaml/mod.ts";
45 import djot
from "npm:@djot/djot@0.2.3";
46 import { Parser
} from "npm:htmlparser2@9.0.0";
47 import { DomHandler
, Element
, Text
} from "npm:domhandler@5.0.3";
48 import * as domutils
from "npm:domutils@3.1.0";
49 import domSerializer
from "npm:dom-serializer@2.0.0";
51 const DESTINATION
= Deno
.args
[0] ?? "~/public/wiki";
52 const REMOTE
= Deno
.args
[1] ?? "/srv/git/GitWikiWeb";
53 const REV
= Deno
.args
[2] ?? "HEAD";
61 const NIL
= Object
.preventExtensions(Object
.create(null));
63 const rawBlock
= (strings
, ...substitutions
) => ({
66 text
: String
.raw(strings
, substitutions
),
68 const rawInline
= (strings
, ...substitutions
) => ({
71 text
: String
.raw(strings
, substitutions
),
73 const str
= (strings
, ...substitutions
) => ({
75 text
: String
.raw(strings
, substitutions
),
78 const getDOM
= (source
) => {
80 const handler
= new DomHandler((error
, dom
) => {
82 throw new Error("GitWikiWeb: Failed to process DOM.", {
89 const parser
= new Parser(handler
);
95 const getRemoteContent
= async (pathName
) => {
96 const getArchive
= new Deno
.Command("git", {
97 args
: ["archive", `--remote=${REMOTE}`, REV
, pathName
],
101 const untar
= new Deno
.Command("tar", {
107 getArchive
.stdout
.pipeTo(untar
.stdin
);
114 ] = await Promise
.allSettled([
115 new Response(getArchive
.stderr
).text(),
117 new Response(untar
.stdout
).text(),
118 new Response(untar
.stderr
).text(),
120 ]).then(logErrorsAndCollectResults
);
122 console
.error(err1
+ err2
);
126 if (!getArchiveStatus
.success
) {
128 `GitWikiWeb: git archive returned nonzero exit code: ${getArchiveStatus.code}.`,
130 } else if (!untarStatus
.success
) {
132 `GitWikiWeb: tar returned nonzero exit code: ${untarStatus.code}.`,
139 const logErrorsAndCollectResults
= (results
) =>
140 results
.map(({ value
, reason
}) => {
142 console
.error(reason
);
149 const getReferenceFromPath
= (path
) =>
150 /Sources\/([A-Z][0-9A-Za-z]*\/[A-Z][0-9A-Za-z]*)\.djot$/u.exec(path
)
151 ?.[1]?.replace
?.("/", ":");
153 const listOfInternalLinks
= (references
, wrapper
= ($) => $) => ({
157 children
: Array
.from(
160 const [namespace, pageName
] = splitReference(reference
);
168 "data-realm": "internal",
169 "data-pagename": pageName
,
170 "data-namespace": namespace,
181 const diffReferences
= async (hash
, againstHead
= false) => {
182 const diff
= new Deno
.Command("git", {
190 ...(againstHead
? [hash
, "HEAD"] : [hash
]),
195 const [diffNames
] = await Promise
.allSettled([
196 new Response(diff
.stdout
).text(),
197 new Response(diff
.stderr
).text(),
198 ]).then(logErrorsAndCollectResults
);
199 return references(diffNames
.split("\0")); // returns an iterable
202 function* references(paths
) {
203 for (const path
of paths
) {
204 const reference
= getReferenceFromPath(path
);
213 const splitReference
= (reference
) => {
214 const colonIndex
= reference
.indexOf(":");
216 reference
.substring(0, colonIndex
),
217 reference
.substring(colonIndex
+ 1),
221 class GitWikiWebPage
{
222 #internalLinks
= new Set();
223 #externalLinks
= new Map();
225 constructor(namespace, name
, ast
, source
, config
) {
226 const internalLinks
= this.#internalLinks
;
227 const externalLinks
= this.#externalLinks
;
228 const sections
= Object
.create(null);
229 djot
.applyFilter(ast
, () => {
230 let titleSoFar
= null; // used to collect strs from headings
235 const links_section
= [];
236 if (internalLinks
.size
|| externalLinks
.size
) {
238 rawBlock
`<nav id="links">`,
242 children
: [str
`this page contains links`],
245 if (internalLinks
.size
) {
247 rawBlock
`<details open="">`,
248 rawBlock
`<summary>on this wiki</summary>`,
249 listOfInternalLinks(internalLinks
),
250 rawBlock
`</details>`,
255 if (externalLinks
.size
) {
257 rawBlock
`<details open="">`,
258 rawBlock
`<summary>elsewhere on the Web</summary>`,
263 children
: Array
.from(
265 ([destination
, text
]) => ({
271 attributes
: { "data-realm": "external" },
289 rawBlock
`</details>`,
302 rawBlock
`${"\uFFFF"}`, // footnote placeholder
310 if (titleSoFar
!= null) {
324 const { attributes
} = e
;
325 attributes
.title
??= titleSoFar
;
332 const { attributes
, reference
, destination
} = e
;
334 /^(?:[A-Z][0-9A-Za-z]*|[@#])?:(?:[A-Z][0-9A-Za-z]*)?$/u
335 .test(reference
?? "")
337 const [namespacePrefix
, pageName
] = splitReference(
340 const expandedNamespace
= {
344 }[namespacePrefix
] ?? namespacePrefix
;
345 const resolvedReference
= pageName
== ""
346 ? `Namespace:${expandedNamespace}`
347 : `${expandedNamespace}:${pageName}`;
348 this.#internalLinks
.add(resolvedReference
);
349 e
.reference
= resolvedReference
;
350 attributes
["data-realm"] = "internal";
351 attributes
["data-pagename"] = pageName
;
352 attributes
["data-namespace"] = expandedNamespace
;
354 attributes
["data-realm"] = "external";
355 const remote
= destination
??
356 ast
.references
[reference
]?.destination
;
358 externalLinks
.set(remote
, attributes
?.title
);
365 non_breaking_space
: {
367 if (titleSoFar
!= null) {
368 titleSoFar
+= "\xA0";
379 const { attributes
, children
} = e
;
380 const heading
= children
.find(({ tag
}) =>
383 const title
= (() => {
384 if (heading
?.attributes
?.title
) {
385 const result
= heading
.attributes
.title
;
386 delete heading
.attributes
.title
;
389 return heading
.level
== 1
390 ? `${namespace}:${name}`
391 : "untitled section";
394 const variantTitles
= Object
.create(null);
395 for (const attr
in attributes
) {
396 if (attr
.startsWith("v-")) {
397 Object
.defineProperty(
400 { ...READ_ONLY
, value
: attributes
[attr
] },
402 delete attributes
[attr
];
407 const definition
= Object
.create(null, {
408 title
: { ...READ_ONLY
, value
: title
},
411 value
: Object
.preventExtensions(variantTitles
),
414 if (heading
.level
== 1 && !("main" in sections
)) {
415 attributes
.id
= "main";
416 heading
.attributes
??= {};
417 heading
.attributes
.class = "main";
422 Object
.defineProperty(
428 value
: Object
.preventExtensions(definition
),
433 `GitWikiWeb: A section with the provided @id already exists: ${attributes.id}`,
441 if (titleSoFar
!= null) {
450 enter
: ({ text
}) => {
451 if (titleSoFar
!= null) {
462 const codepoint
= /^U\+([0-9A-Fa-f]+)$/u.exec(alias
)?.[1];
465 String.fromCodePoint(parseInt(codepoint, 16))
468 const resolved
= config
.symbols
?.[alias
];
469 return resolved
!= null ? str
`${resolved}` : e
;
475 Object
.defineProperties(this, {
476 ast
: { ...READ_ONLY
, value
: ast
},
477 namespace: { ...READ_ONLY
, value
: namespace },
478 name
: { ...READ_ONLY
, value
: name
},
481 value
: Object
.preventExtensions(sections
),
483 source
: { ...READ_ONLY
, value
: source
},
488 yield* this.#externalLinks
;
492 yield* this.#internalLinks
;
497 // Patches for Djot HTML renderer.
498 const { HTMLRenderer
: { prototype: htmlRendererPrototype
} } = djot
;
499 const { inTags
: upstreamInTags
} = htmlRendererPrototype
;
500 htmlRendererPrototype
.inTags = function (
504 extraAttrs
= undefined,
506 const attributes
= node
.attributes
?? NIL
;
507 if ("as" in attributes
) {
508 const newTag
= attributes
.as
;
509 delete attributes
.as
;
510 return upstreamInTags
.call(
518 return upstreamInTags
.call(
529 const config
= await
getRemoteContent("config.yaml").then((yaml
) =>
530 parseYaml(yaml
, { schema
: JSON_SCHEMA
})
532 const ls
= new Deno
.Command("git", {
533 args
: ["ls-tree", "-rz", "HEAD"],
541 ] = await Promise
.allSettled([
542 new Response(ls
.stdout
).text().then((lsout
) =>
545 .slice(0, -1) // drop the last entry; it is empty
546 .map(($) => $.split(/\s+/g))
548 new Response(ls
.stderr
).text(),
550 ]).then(logErrorsAndCollectResults
);
552 console
.error(lserr
);
556 if (!lsstatus
.success
) {
558 `GitWikiWeb: git ls-tree returned nonzero exit code: ${lsstatus.code}.`,
561 const requiredButMissingPages
= new Map([
562 ["Special:FrontPage", "front page"],
563 ["Special:NotFound", "not found"],
564 ["Special:RecentlyChanged", "recently changed"],
566 const pages
= new Map();
567 const promises
= [emptyDir(DESTINATION
)];
568 for (const object
of objects
) {
569 const hash
= object
[2];
570 const path
= object
[3];
571 const reference
= getReferenceFromPath(path
);
572 if (reference
== null) {
575 const [namespace, pageName
] = splitReference(reference
);
576 const cat
= new Deno
.Command("git", {
577 args
: ["cat-file", "blob", hash
],
581 const promise
= Promise
.allSettled([
582 new Response(cat
.stdout
).text(),
583 new Response(cat
.stderr
).text(),
585 ]).then(logErrorsAndCollectResults
).then(
586 ([source
, caterr
, catstatus
]) => {
588 console
.error(caterr
);
592 if (!catstatus
.success
) {
594 `GitWikiWeb: git cat-file returned nonzero exit code: ${catstatus.code}.`,
597 const page
= new GitWikiWebPage(
602 console
.warn(`Djot(${reference}): ${$.render()}`),
607 const reference
= `${namespace}:${pageName}`;
608 pages
.set(reference
, page
);
609 requiredButMissingPages
.delete(reference
);
613 promises
.push(promise
);
616 for (const [reference
, defaultTitle
] of requiredButMissingPages
) {
617 const [namespace, pageName
] = splitReference(reference
);
618 const source
= `# ${defaultTitle}\n`;
619 const page
= new GitWikiWebPage(
624 console
.warn(`Djot(${reference}): ${$.render()}`),
629 pages
.set(reference
, page
);
631 await Promise
.allSettled(promises
).then(
632 logErrorsAndCollectResults
,
634 const [template
, recentlyChanged
] = await Promise
.allSettled([
635 getRemoteContent("template.html"),
637 const dateParse
= new Deno
.Command("git", {
638 args
: ["rev-parse", "--after=1 week ago"],
642 const [maxAge
] = await Promise
.allSettled([
643 new Response(dateParse
.stdout
).text(),
644 new Response(dateParse
.stderr
).text(),
645 ]).then(logErrorsAndCollectResults
);
650 const revList
= new Deno
.Command("git", {
651 args
: ["rev-list", maxAge
, "--reverse", "HEAD"],
655 [commit
] = await Promise
.allSettled([
656 new Response(revList
.stdout
).text().then((list
) =>
659 new Response(revList
.stderr
).text(),
660 ]).then(logErrorsAndCollectResults
);
663 const revList2
= new Deno
.Command("git", {
664 args
: ["rev-list", "--max-count=1", "HEAD^"],
668 [commit
] = await Promise
.allSettled([
669 new Response(revList2
.stdout
).text().then((list
) =>
672 new Response(revList2
.stderr
).text(),
673 ]).then(logErrorsAndCollectResults
);
677 const results
= new Array(6);
678 const seen
= new Set();
679 const maxRecency
= Math
.max(config
.max_recency
| 0, 0);
680 let recency
= maxRecency
;
683 const show
= new Deno
.Command("git", {
687 "--format=%H%x00%cI%x00%cD",
688 recency
? `HEAD~${maxRecency - recency}` : commit
,
694 [hash
, dateTime
, humanReadable
],
695 ] = await Promise
.allSettled([
696 new Response(show
.stdout
).text().then((rev
) =>
697 rev
.trim().split("\0")
699 new Response(show
.stderr
).text(),
700 ]).then(logErrorsAndCollectResults
);
704 const ref
of (await
diffReferences(current
, !recency
))
713 results
[recency
] = { dateTime
, hash
, humanReadable
, refs
};
714 } while (recency
-- > 0 && current
&& current
!= commit
);
719 (name
) => ensureDir(`${DESTINATION}/${name}`),
721 ["style.css"].map((dependency
) =>
722 getRemoteContent(dependency
).then((source
) =>
724 `${DESTINATION}/${dependency}`,
730 ]).then(logErrorsAndCollectResults
);
732 const redLinks
= (() => {
733 const result
= new Set();
734 for (const page
of pages
.values()) {
735 for (const link
of page
.internalLinks()) {
736 if (pages
.has(link
)) {
746 const [pageRef
, { ast
, namespace, sections
, source
}] of pages
748 const title
= sections
.main
?.title
?? pageRef
;
749 djot
.applyFilter(ast
, () => {
750 let isNavigationPage
= true;
754 const { content
, navigation
} = (() => {
755 const navigation
= [];
756 if (pageRef
== "Special:RecentlyChanged") {
759 attributes
: { class: "recent-changes" },
762 children
: Array
.from(function* () {
764 const [index
, result
] of recentlyChanged
767 if (result
!= null) {
773 yield* listOfInternalLinks(refs
, (link
) => ({
774 tag
: index
== 0 ? "span" : "strong",
775 attributes
: { "data-recency": `${index}` },
778 ...(index
== 0 ? [] : [
780 rawInline
`<small>(<time dateTime="${dateTime}">`,
781 str
`${humanReadable}`,
782 rawInline
`</time>)</small>`,
793 isNavigationPage
= false;
794 return { content
: e
.children
, navigation
};
802 generated
: "", // will be removed later
805 children
: [str
`${title}`],
807 rawBlock
`<details id="navigation-about" open="">`,
808 rawBlock
`<summary>about this listing</summary>`,
811 rawBlock
`</article>`,
812 rawBlock
`</details>`,
815 rawBlock
`<nav id="navigation">`,
825 rawBlock
`</article>`,
832 const attributes
= e
.attributes
?? NIL
;
834 isNavigationPage
&& e
.level
== 1 &&
835 attributes
?.class == "main"
837 if ("generated" in attributes
) {
838 delete attributes
.generated
;
847 if (e
.level
== 1 && e
.attributes
?.class == "main") {
849 rawBlock
`<header class="main">`,
851 { tag
: "verbatim", text
: pageRef
},
863 const { attributes
, children
, reference
} = e
;
864 if (attributes
["data-realm"] == "internal") {
866 if (redLinks
.has(reference
)) {
868 `/Special:NotFound?path=/${reference}`;
869 attributes
["data-notfound"] = "";
871 e
.destination
= `/${reference}`;
873 if (children
.length
== 0) {
875 pages
.get(reference
)?.sections
?.main
?? NIL
;
876 const { v
} = attributes
;
879 str
`${section.title ?? reference}`,
885 section.variantTitles?.[v] ?? section.title ??
892 if (children
.length
== 0 && "title" in attributes
) {
895 str
`${attributes.title}`,
901 (attributes
.class ?? "").split(/\s/gu).includes("sig")
905 attributes
: { class: "sig" },
906 children
: [str
`—${"\xA0"}`, e
],
916 if (e
.children
.length
< 1) {
917 // The heading for this section was removed and it had
918 // no other children.
927 const renderedAST
= djot
.renderAST(ast
);
928 const doc
= getDOM(template
);
929 const result
= getDOM(djot
.renderHTML(ast
, {
931 raw_block
: (node
, context
) => {
932 if (node
.format
== "html" && node
.text
== "\uFFFF") {
933 if (context
.nextFootnoteIndex
> 1) {
934 const result
= context
.renderNotes(ast
.footnotes
);
935 context
.nextFootnoteIndex
= 1;
941 return context
.renderAstNodeDefault(node
);
946 const headElement
= domutils
.findOne(
947 (node
) => node
.name
== "head",
950 const titleElement
= domutils
.findOne(
951 (node
) => node
.name
== "title",
954 const contentElement
= domutils
.findOne(
955 (node
) => node
.name
== "gitwikiweb-content",
958 if (headElement
== null) {
960 "GitWikiWeb: Template must explicitly include a <head> element.",
963 domutils
.appendChild(
965 new Element("link", {
968 href
: `/${pageRef}/source.djot`,
971 if (titleElement
== null) {
972 domutils
.prependChild(
974 new Element("title", {}, [new Text(title
)]),
977 domutils
.prependChild(titleElement
, new Text(`${title} | `));
980 if (contentElement
== null) {
982 "GitWikiWeb: Template did not include a <gitwikiweb-content> element.",
985 for (const node
of [...result
]) {
986 domutils
.prepend(contentElement
, node
);
988 domutils
.removeElement(contentElement
);
992 `${DESTINATION}/${pageRef}/index.html`,
995 encodeEntities
: "utf8",
996 selfClosingTags
: true,
1004 `${DESTINATION}/${pageRef}/index.ast`,
1006 { createNew
: true },
1011 `${DESTINATION}/${pageRef}/source.djot`,
1013 { createNew
: true },
1017 await Promise
.allSettled(promises
).then(
1018 logErrorsAndCollectResults
,
1020 console
.log(`GitWikiWeb: Wrote ${pages.size} page(s).`);