]> Lady’s Gitweb - Beorn/blob - build.js
785b86f94b9db7e39c28ffd0f381725e15ae1d81
[Beorn] / build.js
1 #!/usr/bin/env -S deno run --allow-read --allow-write
2 // 🧸📔 Bjørn ∷ build.js
3 // ====================================================================
4 //
5 // Copyright © 2022 Lady [@ Lady’s Computer].
6 //
7 // This Source Code Form is subject to the terms of the Mozilla Public
8 // License, v. 2.0. If a copy of the MPL was not distributed with this
9 // file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
10
11 // As the shebang at the top of this file indicates, it must be run via
12 // Deno with read and write permissions. You can get Deno from
13 // <https://deno.land/>.
14 //
15 // This file generates a minimal, Atom‐supporting blog from a handful
16 // of R·D·F∕X·M·L files and a couple of templates. It will silently
17 // overwrite the files it generates. This is usually what you want.
18 //
19 // ※ The actual run script is at the very end of this file. It is
20 // preceded by a number of helper function definitions, of which the
21 // most important is `applyMetadata` (which is used to generate the
22 // HTML and Atom elements from the processed metadata).
23 //
24 // ※ The list of supported metadata properties and their R·D·F
25 // representations is provided by `context`. You can add support for
26 // new metadata fields simply by adding them to the `context` and then
27 // handling them appropriately in `applyMetadata`.
28 //
29 // This script is a bit of a mess and you shouldn’t bother trying to
30 // understand the whole thing before you start hacking on it. Just find
31 // the parts relevant to whatever you want to change, and assume that
32 // things will work in sensible (if cumbersome) browser‐like ways.
33
34 // This import polyfills a (mediocre but sufficient) D·O·M environment
35 // onto the global object.
36 import "https://git.ladys.computer/Lemon/blob_plain/0.2.2:/window/mod.js";
37
38 // Much of the H·T·M·L generation in this script uses the 🍋🏷 Lemon
39 // library for convenience (<https://git.ladys.computer/Lemon>).
40 //
41 // Frequently this will be bound to a different document than the
42 // global one and called as `LMN`.
43 import Lemon from "https://git.ladys.computer/Lemon/blob_plain/0.2.2:/mod.js";
44
45 // Markdown processing uses rusty_markdown, which uses Rust’s
46 // pulldown-cmark behind the scenes via WebAssembly.
47 import {
48 html as markdownTokensToHTML,
49 tokens as markdownTokens,
50 } from "https://deno.land/x/rusty_markdown@v0.4.1/mod.ts";
51
52 // Various namespaces.
53 const AWOL = "http://bblfish.net/work/atom-owl/2006-06-06/";
54 const DC11 = "http://purl.org/dc/elements/1.1/";
55 const FOAF = "http://xmlns.com/foaf/0.1/";
56 const RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
57 const RDFS = "http://www.w3.org/2000/01/rdf-schema#";
58 const SIOC = "http://rdfs.org/sioc/ns#";
59 const XML = "http://www.w3.org/XML/1998/namespace";
60 const XHTML = "http://www.w3.org/1999/xhtml";
61
62 /**
63 * Adds the provided content to the provided element.
64 *
65 * Content may be either nullish (in which case nothing is added), a
66 * string (object or literal), a NodeList, or an array of zero or more
67 * of these values. Nodes need not belong to the same document as the
68 * provided element; they will be imported. During this process,
69 * special care is taken to ensure that the resulting content is
70 * correctly language‐tagged for its new context.
71 *
72 * ☡ If the provided element is not attached to anything, then it won’t
73 * be possible to walk its parent nodes in search of language
74 * information. Generally, it is best to attach elements to a document
75 * BEFORE calling this function.
76 */
77 const addContent = (element, content) => {
78 const { ownerDocument: document } = element;
79 const LMN = Lemon.bind({ document });
80 if (content == null) {
81 // The provided content is nullish.
82 /* do nothing */
83 } else if (Array.isArray(content)) {
84 // The provided content is an array.
85 content.forEach(addContent.bind(null, element));
86 } else if (Object(content) instanceof String) {
87 // The provided content is a string (object or literal).
88 const { lang } = content;
89 if (lang && lang != getLanguage(element)) {
90 const newChild = element.appendChild(LMN.span`${content}`);
91 setLanguage(newChild, lang);
92 } else {
93 element.appendChild(document.createTextNode(`${content}`));
94 }
95 } else {
96 // Assume the provided content is a NodeList.
97 if (element.hasAttribute("property")) {
98 // The provided element has an R·D·F∕A property; note that its
99 // datatype is `XMLLiteral`.
100 element.setAttribute("datatype", "XMLLiteral");
101 } else {
102 // The provided element does not have an R·D·F∕A property.
103 /* do nothing */
104 }
105 for (const child of Array.from(content)) {
106 // Iterate over the nodes in the provided NodeList and handle
107 // them appropriately.
108 const lang = getLanguage(child);
109 const newChild = (() => {
110 const imported = document.importNode(child, true);
111 if (lang && lang != getLanguage(element)) {
112 // The imported node’s language would change if it were just
113 // imported directly into the provided element.
114 if (imported.nodeType == 1) {
115 // The imported node is an element node.
116 setLanguage(imported, lang);
117 return imported;
118 } else if (imported.nodeType <= 4) {
119 // The imported node is a text node.
120 const result = LMN.span`${imported}`;
121 setLanguage(result, lang);
122 return result;
123 } else {
124 // The imported node is not an element or text.
125 return imported;
126 }
127 } else {
128 // The imported node’s language will not change if imported
129 // directly into the provided element.
130 return imported;
131 }
132 })();
133 element.appendChild(newChild);
134 }
135 }
136 return element;
137 };
138
139 /**
140 * Adds HTML for the provided people to the provided element, tagging
141 * them with the provided property.
142 *
143 * ☡ As with `addContent`, it is best to attach elements to a document
144 * PRIOR to providing them to this function, for language‐detection
145 * reasons.
146 */
147 const addPeople = (element, people, property) => {
148 const { ownerDocument: document } = element;
149 const LMN = Lemon.bind({ document });
150 const { length } = people;
151 for (const [index, { uri, name }] of people.entries()) {
152 const personElement = element.appendChild(
153 uri
154 ? LMN.a.rel(`${property}`).href(`${uri}`)``
155 : LMN.span.rel(`${property}`)``,
156 );
157 if (name == null) {
158 // The current person has no name; provide its `uri`.
159 personElement.appendChild(LMN.code`${uri}`);
160 } else {
161 // The current person has a name.
162 addContent(
163 personElement.appendChild(
164 LMN.span.property(`${FOAF}name`)``,
165 ),
166 name,
167 );
168 }
169 if (index < length - 2) {
170 // The current person is two or greater from the end.
171 addContent(element, ", ");
172 } else if (index < length - 1) {
173 // The current person is one from the end.
174 addContent(element, " & ");
175 } else {
176 // The current person is the last.
177 /* do nothing */
178 }
179 }
180 return element;
181 };
182
183 /**
184 * Applies the provided metadata to the provided node by creating and
185 * inserting the appropriate elements, then returns the provided node.
186 *
187 * If the provided node is a document, it is assumed to be an entry
188 * template, and full entry H·T·M·L is generated. If it is a document
189 * fragment, it is assumed to be a document fragment collecting entries
190 * for the H·T·M·L feed index page, and entry H·T·M·L links are
191 * generated. Otherwise, the provided node is assumed to be an Atom
192 * element, and Atom metadata elements are generated.
193 */
194 const applyMetadata = (node, metadata) => {
195 if (node.nodeType == 9) {
196 // The provided node is a document.
197 //
198 // Assume it is an entry template document and insert the full
199 // entry H·T·M·L accordingly.
200 const document = node;
201 const { documentElement } = document;
202 if (hasExpandedName(documentElement, XHTML, "html")) {
203 // This is an XHTML template.
204 const LMN = Lemon.bind({ document });
205 const {
206 id,
207 title,
208 author,
209 contributor,
210 published,
211 content,
212 rights,
213 updated,
214 } = metadata;
215 fillOutHead(document, metadata, "entry");
216 const contentPlaceholder = document.getElementsByTagNameNS(
217 XHTML,
218 "bjørn-content",
219 ).item(0);
220 if (contentPlaceholder != null) {
221 // The content placeholder exists; replace it with the content
222 // nodes.
223 const { parentNode: contentParent } = contentPlaceholder;
224 const contentElement = contentParent.insertBefore(
225 LMN.article.about(`${id}`)`${"\n"}`,
226 contentPlaceholder,
227 );
228
229 // Handle the entry content header.
230 contentElement.appendChild(
231 document.createComment(" BEGIN ENTRY HEADER "),
232 );
233 addContent(contentElement, "\n");
234 const contentHeader = contentElement.appendChild(
235 LMN.header.id("entry.header")`${"\n\t"}`,
236 );
237 addContent(
238 contentHeader.appendChild(
239 LMN.h1.id("entry.title").property(`${DC11}title`)``,
240 ),
241 title,
242 );
243 if (author.length > 0) {
244 // This entry has authors.
245 addContent(contentHeader, "\n\t");
246 addPeople(
247 contentHeader.appendChild(
248 LMN.p.id("entry.author")``,
249 ),
250 author,
251 `${DC11}creator`,
252 );
253 } else {
254 // This entry does not have authors.
255 /* do nothing */
256 }
257 if (contributor.length > 0) {
258 // This entry has contributors.
259 addContent(contentHeader, "\n\t");
260 addContent(
261 addPeople(
262 contentHeader.appendChild(
263 LMN.p.id(
264 "entry.contributor",
265 )`With contributions from `,
266 ),
267 contributor,
268 `${DC11}contributor`,
269 ),
270 ".",
271 );
272 } else {
273 // This entry does not have contributors.
274 /* do nothing */
275 }
276 if (published) {
277 // This entry has a publication date.
278 addContent(contentHeader, "\n\t");
279 contentHeader.appendChild(
280 LMN.p.id("entry.published")`Published: ${LMN.time.property(
281 `${DC11}date`,
282 )`${published}`}.`,
283 );
284 } else {
285 // This entry does not have a publication date.
286 /* do nothing */
287 }
288 addContent(contentHeader, "\n");
289 addContent(contentElement, "\n");
290 contentElement.appendChild(
291 document.createComment(" END ENTRY HEADER "),
292 );
293 addContent(contentElement, "\n");
294
295 // Handle the entry content.
296 contentElement.appendChild(
297 document.createComment(" BEGIN ENTRY CONTENT "),
298 );
299 addContent(contentElement, "\n");
300 addContent(
301 contentElement.appendChild(
302 LMN.div.id("entry.content").property(`${SIOC}content`)``,
303 ),
304 content,
305 );
306 addContent(contentElement, "\n");
307 contentElement.appendChild(
308 document.createComment(" END ENTRY CONTENT "),
309 );
310 addContent(contentElement, "\n");
311
312 // Handle the entry content footer.
313 contentElement.appendChild(
314 document.createComment(" BEGIN ENTRY FOOTER "),
315 );
316 addContent(contentElement, "\n");
317 const contentFooter = contentElement.appendChild(
318 LMN.footer.id("entry.footer")`${"\n\t"}`,
319 );
320 if (rights) {
321 addContent(
322 contentFooter.appendChild(
323 LMN.div.id("entry.rights").property(`${DC11}rights`)``,
324 ),
325 rights,
326 );
327 addContent(contentFooter, "\n\t");
328 }
329 contentFooter.appendChild(
330 LMN.p.id("entry.updated")`Last updated: ${LMN.time.property(
331 `${AWOL}updated`,
332 )`${updated}`}.`,
333 );
334 addContent(contentFooter, "\n");
335 addContent(contentElement, "\n");
336 contentElement.appendChild(
337 document.createComment(" END ENTRY FOOTER "),
338 );
339 addContent(contentElement, "\n");
340
341 // Remove the placeholder.
342 contentParent.removeChild(contentPlaceholder);
343 } else {
344 // There is no content placeholder.
345 /* do nothing */
346 }
347 } else {
348 // This is not an XHTML template.
349 /* do nothing */
350 }
351 } else if (node.nodeType == 11) {
352 // The provided node is a document fragment.
353 //
354 // Assume it is collecting H·T·M·L feed entry links and insert a
355 // new one for the provided metadata.
356 const { ownerDocument: document } = node;
357 const LMN = Lemon.bind({ document });
358 const {
359 id,
360 title,
361 author,
362 published,
363 summary,
364 } = metadata;
365 // The content placeholder exists; replace it with the content
366 // nodes.
367 node.appendChild(
368 document.createComment(` <${id}> `),
369 );
370 addContent(node, "\n");
371 const contentElement = node.appendChild(
372 LMN.li.resource(`${id}`)`${"\n"}`,
373 );
374 addContent(
375 contentElement.appendChild(
376 LMN.a.href(`${id}`)``,
377 ).appendChild(
378 LMN.h3.property(`${DC11}title`)``,
379 ),
380 title,
381 );
382 if (author.length > 0) {
383 // This entry has authors.
384 addContent(contentElement, "\n");
385 addPeople(
386 contentElement.appendChild(
387 LMN.p``,
388 ),
389 author,
390 `${DC11}creator`,
391 );
392 } else {
393 // This entry does not have authors.
394 /* do nothing */
395 }
396 if (published) {
397 // This entry has a publication date.
398 addContent(contentElement, "\n");
399 contentElement.appendChild(
400 LMN.time.property(`${DC11}date`)`${published}`,
401 );
402 } else {
403 // This entry does not have a publication date.
404 /* do nothing */
405 }
406 addContent(contentElement, "\n");
407 addContent(
408 contentElement.appendChild(
409 LMN.div.property(`${DC11}abstract`)``,
410 ),
411 summary,
412 );
413 addContent(contentElement, "\n");
414 addContent(node, "\n");
415 } else {
416 // The provided node is not a document or document fragment.
417 //
418 // Assume it is an Atom element of some sort and add the
419 // the appropriate metadata as child elements.
420 const { ownerDocument: document } = node;
421 const alternateLink = node.appendChild(
422 document.createElement("link"),
423 );
424 alternateLink.setAttribute("rel", "alternate");
425 alternateLink.setAttribute("type", "application/xhtml+xml");
426 alternateLink.setAttribute("href", metadata.id);
427 for (const [property, values] of Object.entries(metadata)) {
428 for (const value of Array.isArray(values) ? values : [values]) {
429 const propertyNode = document.createElement(property);
430 switch (context[property]?.type) {
431 case "person": {
432 // The property describes a person.
433 const { name, uri } = value;
434 if (uri) {
435 // The person has a U·R·I.
436 const subnode = document.createElement("uri");
437 subnode.textContent = uri;
438 propertyNode.appendChild(subnode);
439 } else {
440 // The person does not have a U·R·I.
441 /* do nothing */
442 }
443 if (name != null) {
444 // The person has a name.
445 const subnode = document.createElement("name");
446 subnode.textContent = name;
447 propertyNode.appendChild(subnode);
448 } else {
449 // The person does not have a name.
450 /* do nothing */
451 }
452 if (propertyNode.childNodes.length == 0) {
453 // Neither a U·R·I nor a name was added; skip adding this
454 // property.
455 continue;
456 } else {
457 break;
458 }
459 }
460 default: {
461 // The property describes (potentially rich) text.
462 if (value == null) {
463 // The property has no value; skip appending it to the node.
464 continue;
465 } else if (Object(value) instanceof String) {
466 // The property has a string value.
467 propertyNode.textContent = value;
468 break;
469 } else {
470 // The property value is a list of nodes.
471 propertyNode.setAttribute("type", "xhtml");
472 const div = document.createElementNS(XHTML, "div");
473 for (const child of Array.from(value)) {
474 div.appendChild(document.importNode(child, true));
475 }
476 propertyNode.appendChild(div);
477 break;
478 }
479 }
480 }
481 node.appendChild(propertyNode);
482 }
483 }
484 }
485 return node;
486 };
487
488 /**
489 * The base path from which to pull files and generate resulting
490 * documents.
491 */
492 const basePath = `./${Deno.args[0] ?? ""}`;
493
494 /**
495 * Mappings from Atom concepts to R·D·F∕X·M·L ones.
496 *
497 * `namespace` and `localName` give the R·D·F representation for the
498 * concept. Three `type`s are supported :—
499 *
500 * - "person": Has a `name` (`foaf:name`) and an `iri` (`rdf:about`).
501 * Emails are NOT supported.
502 *
503 * - "text": Can be string, markdown, or X·M·L content.
504 *
505 * - "literal": This is a plaintext field.
506 */
507 const context = {
508 author: { namespace: DC11, localName: "creator", type: "person" },
509 // category is not supported at this time
510 content: { namespace: SIOC, localName: "content", type: "text" },
511 contributor: {
512 namespace: DC11,
513 localName: "contributor",
514 type: "person",
515 },
516 // generator is provided by the build script
517 icon: { namespace: AWOL, localName: "icon", type: "literal" },
518 // link is provided by the build script
519 logo: { namespace: AWOL, localName: "logo", type: "literal" },
520 published: {
521 namespace: DC11,
522 localName: "date",
523 type: "literal",
524 },
525 rights: { namespace: DC11, localName: "rights", type: "text" },
526 // source is not supported at this time
527 subtitle: { namespace: RDFS, localName: "label", type: "text" },
528 summary: { namespace: DC11, localName: "abstract", type: "text" },
529 title: { namespace: DC11, localName: "title", type: "text" },
530 // updated is provided by the build script
531 };
532
533 const {
534 /**
535 * Returns a new document created from the source code of the named
536 * template.
537 */
538 documentFromTemplate,
539 } = (() => {
540 const cache = Object.create(null);
541 return {
542 documentFromTemplate: async (name) =>
543 parser.parseFromString(
544 name in cache ? cache[name] : (
545 cache[name] = await Deno.readTextFile(
546 `${basePath}/index#${name}.xhtml`,
547 )
548 ),
549 "application/xml",
550 ),
551 };
552 })();
553
554 /**
555 * Fills out the `head` of the provided H·T·M·L document with the
556 * appropriate metadata.
557 */
558 const fillOutHead = (document, metadata, type) => {
559 const { documentElement } = document;
560 const LMN = Lemon.bind({ document });
561 const head =
562 Array.from(documentElement.childNodes).find(($) =>
563 hasExpandedName($, XHTML, "head")
564 ) ?? documentElement.insertBefore(
565 LMN.head``,
566 documentElement.childNodes.item(0),
567 );
568 const titleElement =
569 Array.from(head.childNodes).find(($) =>
570 hasExpandedName($, XHTML, "title")
571 ) ?? head.appendChild(LMN.title``);
572 const {
573 title,
574 author,
575 subtitle,
576 summary,
577 } = metadata;
578 titleElement.textContent = Object(title) instanceof String
579 ? title
580 : Array.from(title ?? []).map(($) => $.textContent).join("");
581 for (const person of author) {
582 // Iterate over authors and add appropriate meta tags.
583 head.appendChild(
584 LMN.meta({
585 name: "author",
586 content: person.name ?? person.uri,
587 })``,
588 );
589 }
590 head.appendChild(
591 LMN.meta({ name: "generator", content: "🧸📔 Bjørn" })``,
592 );
593 if (type == "entry") {
594 // The provided document is an entry document.
595 if (summary) {
596 // The entry has a summary.
597 head.appendChild(
598 LMN.meta({
599 name: "description",
600 content: Object(summary) instanceof String
601 ? summary
602 : Array.from(summary).map(($) => $.textContent).join(""),
603 })``,
604 );
605 } else {
606 /* do nothing */
607 }
608 head.appendChild(
609 LMN.link
610 .rel("alternate")
611 .type("application/atom+xml")
612 .href("../../feed.atom")``,
613 );
614 } else {
615 // The provided document is not an entry document.
616 if (subtitle) {
617 // The entry has a subtitle.
618 head.appendChild(
619 LMN.meta({
620 name: "description",
621 content: Object(subtitle) instanceof String
622 ? summary
623 : Array.from(subtitle).map(($) => $.textContent).join(""),
624 })``,
625 );
626 } else {
627 /* do nothing */
628 }
629 head.appendChild(
630 LMN.link
631 .rel("alternate")
632 .type("application/atom+xml")
633 .href("./feed.atom")``,
634 );
635 }
636 };
637
638 /**
639 * Returns the language of the provided node, or null if it has no
640 * language.
641 *
642 * ※ This function returns null regardless of whether a node has no
643 * language implicitly (because no parent element had a language set)
644 * or explicitly (because the value of the @xml:lang attribute was "").
645 *
646 * ※ If no language is set, the language of the node is ambiguous.
647 * Because this typically occurs when a node is expected to inherit its
648 * language from some parent context, this lack of language information
649 * SHOULD NOT be preserved when inserting the node into a document
650 * where language information is present (instead allowing the node to
651 * inherit language information from the node it is being inserted
652 * into). There are explicit language codes which may be used if this
653 * behaviour is undesirable: If you want to signal that a node does not
654 * contain linguistic content, use the language code `zxx`. If you want
655 * to signal that a node’s language is undetermined in a way which will
656 * never inherit from a parent node, use the language code `und`.
657 */
658 const getLanguage = (node) => {
659 const { nodeType } = node;
660 if (nodeType == 1) {
661 // The provided node is an element.
662 const ownLanguage =
663 node.namespaceURI == XHTML && node.hasAttribute("lang") &&
664 node.getAttribute("lang") ||
665 node.hasAttributeNS(XML, "lang") &&
666 node.getAttributeNS(XML, "lang");
667 if (ownLanguage) {
668 // The element has a recognized language attribute set to a
669 // nonempty value.
670 return ownLanguage;
671 } else if (ownLanguage === "") {
672 // The element explicitly has no language.
673 return null;
674 } else {
675 // The element has no language attribute, but may inherit a
676 // language from its parent.
677 const { parentNode } = node;
678 if (parentNode != null && parentNode.nodeType != 9) {
679 // The provided node has a nondocument parent; get the language
680 // from there.
681 return getLanguage(parentNode);
682 } else {
683 // The provided node has no parent and consequently no language.
684 return null;
685 }
686 }
687 } else if (nodeType == 9) {
688 // The provided node is a document.
689 return getLanguage(node.documentElement);
690 } else if (nodeType == 11) {
691 // The provided node is a document fragment.
692 return getLanguage(node.ownerDocument.documentElement);
693 } else {
694 // The provided node may inherit a language from a parent node.
695 const { parentNode } = node;
696 if (parentNode != null) {
697 // The provided node has a parent; get the language from there.
698 return getLanguage(parentNode);
699 } else {
700 // The provided node has no parent and consequently no language.
701 return null;
702 }
703 }
704 };
705
706 /**
707 * Returns whether the provided node has the provided namespace and
708 * local name.
709 */
710 const hasExpandedName = (node, namespace, localName) =>
711 node.namespaceURI == namespace && node.localName == localName;
712
713 /**
714 * Processes an RDF document and returns an object of Atom metadata.
715 *
716 * See `context` for the metadata properties supported.
717 */
718 const metadataFromDocument = (
719 { documentElement: root, lastModified },
720 ) => {
721 const contextEntries = [...Object.entries(context)];
722 const documentType = hasExpandedName(root, AWOL, "Feed")
723 ? "feed"
724 : "entry";
725 const result = Object.assign(Object.create(null), {
726 id: root.getAttributeNS(RDF, "about"),
727 updated: documentType == "feed" || lastModified == null
728 ? new Date().toISOString()
729 : lastModified.toISOString(),
730 title: null,
731 author: [],
732 contributor: [],
733 rights: null,
734 ...(documentType == "feed"
735 ? { // additional feed properties
736 subtitle: null,
737 logo: null,
738 icon: null,
739 }
740 : { // additional entry properties
741 published: null,
742 summary: null,
743 content: null,
744 }),
745 });
746 for (
747 const node of [
748 ...Array.from(root.attributes),
749 ...Array.from(root.childNodes),
750 ]
751 ) {
752 // Iterate over all child nodes and attributes, finding ones which
753 // correspond to Atom properties and assigning the appropriate
754 // metadata.
755 const [name, { type }] = contextEntries.find(
756 ([_, value]) =>
757 hasExpandedName(node, value.namespace, value.localName),
758 ) ?? [, {}];
759 if (name != null && name in result) {
760 // The current node corresponds with an Atom property.
761 const { [name]: existing } = result;
762 const content = (() => {
763 switch (type) {
764 case "person": {
765 // The node describes a person.
766 const base =
767 node.getAttributeNS?.(RDF, "parseType") == "Resource"
768 ? node
769 : Array.from(node.childNodes).find(($) =>
770 $.nodeType == 1
771 );
772 const person = {
773 name: null,
774 uri: base.getAttributeNS?.(RDF, "about") || null,
775 };
776 for (
777 const subnode of [
778 ...Array.from(base.attributes),
779 ...Array.from(base.childNodes),
780 ]
781 ) {
782 // Process child nodes and attributes for the current
783 // person, looking for name metadata.
784 if (hasExpandedName(subnode, FOAF, "name")) {
785 // This is a name node.
786 if (person.name == null) {
787 // No name has been set yet.
788 person.name = subnode.textContent;
789 } else {
790 // A name has already been set.
791 throw new TypeError(
792 `Duplicate name found for person${
793 person.id != null ? ` <${person.id}>` : ""
794 } while processing <${result.id}>.`,
795 );
796 }
797 } else {
798 // This is not a name node
799 /* do nothing */
800 }
801 }
802 return person;
803 }
804 case "text": {
805 // The node describes (potentially rich) textual content.
806 //
807 // ☡ Don’t return an Array here or it will look like a list
808 // of multiple values. Return the NodeList of child nodes
809 // directly.
810 const parseType = node.getAttributeNS?.(RDF, "parseType");
811 if (parseType == "Markdown") {
812 // This is an element with Markdown content (which
813 // hopefully can be converted into X·M·L).
814 return parser.parseFromString(
815 `<福 xmlns="${XHTML}" lang="${
816 getLanguage(node) ?? ""
817 }">${
818 markdownTokensToHTML(
819 markdownTokens(node.textContent),
820 )
821 }</福>`,
822 "application/xml",
823 ).documentElement.childNodes;
824 } else if (parseType == "Literal") {
825 // This is an element with literal X·M·L contents.
826 return node.childNodes;
827 } else {
828 // This is an element without literal X·M·L contents.
829 /* do nothing */
830 }
831 } // falls through
832 default: {
833 // The node describes something in plaintext.
834 const text = new String(node.textContent);
835 const lang = getLanguage(node);
836 if (lang) {
837 text.lang = lang;
838 } else {
839 /* do nothing */
840 }
841 return text;
842 }
843 }
844 })();
845 if (existing == null) {
846 // The property takes at most one value, but none has been set.
847 result[name] = content;
848 } else if (Array.isArray(existing)) {
849 // The property takes multiple values.
850 existing.push(content);
851 } else {
852 // The property takes at most one value, and one has already
853 // been set.
854 throw new TypeError(
855 `Duplicate content found for ${name} while processing <${result.id}>.`,
856 );
857 }
858 } else {
859 // The current node does not correspond with an Atom property.
860 /* do nothing */
861 }
862 }
863 return validateMetadata(result, documentType);
864 };
865
866 /** The DOMParser used by this script. */
867 const parser = new DOMParser();
868
869 /** The XMLSerializer used by this script. */
870 const serializer = new XMLSerializer();
871
872 /**
873 * Sets the @xml:lang attribute of the provided element, and if it is
874 * an H·T·M·L element also sets the @lang.
875 */
876 const setLanguage = (element, lang) => {
877 element.setAttributeNS(XML, "xml:lang", lang ?? "");
878 if (element.namespaceURI == XHTML) {
879 element.setAttribute("lang", lang ?? "");
880 } else {
881 /* do nothing */
882 }
883 };
884
885 /**
886 * Throws if the provided metadata does not conform to expectations for
887 * the provided type, and otherwise returns it.
888 */
889 const validateMetadata = (metadata, type) => {
890 if (metadata.id == null) {
891 throw new TypeError("Missing id.");
892 } else if (metadata.title == null) {
893 throw new TypeError(`Missing title for item <${metadata.id}>.`);
894 } else if (type == "feed" && metadata.author == null) {
895 throw new TypeError(`Missing author for feed <${metadata.id}>.`);
896 } else if (type == "entry" && metadata.content == null) {
897 throw new TypeError(`Missing content for entry <${metadata.id}>.`);
898 } else {
899 return metadata;
900 }
901 };
902
903 await (async () => { // this is the run script
904 const writes = [];
905
906 // Set up the feed metadata and Atom feed document.
907 const feedMetadata = metadataFromDocument(
908 parser.parseFromString(
909 await Deno.readTextFile(`${basePath}/#feed.rdf`),
910 "application/xml",
911 ),
912 );
913 const feedURI = new URL(feedMetadata.id);
914 const document = parser.parseFromString(
915 `<?xml version="1.0" encoding="utf-8"?>
916 <feed xmlns="http://www.w3.org/2005/Atom"><generator>🧸📔 Bjørn</generator><link rel="self" type="application/atom+xml" href="${new URL(
917 "./feed.atom",
918 feedURI,
919 )}"/></feed>`,
920 "application/xml",
921 );
922 const { documentElement: feed } = document;
923 applyMetadata(feed, feedMetadata);
924
925 // Set up the index page.
926 const feedTemplate = await documentFromTemplate("feed");
927 const feedEntries = feedTemplate.createDocumentFragment();
928
929 // Process entries and save the resulting index files.
930 for await (
931 const { name: date, isDirectory } of Deno.readDir(
932 `${basePath}/`,
933 )
934 ) {
935 // Iterate over each directory and process the ones which are
936 // dates.
937 if (!isDirectory || !/[0-9]{4}-[0-9]{2}-[0-9]{2}/u.test(date)) {
938 // This isn’t a dated directory.
939 continue;
940 } else {
941 // This is a dated directory.
942 for (
943 const { name: entryName, isDirectory } of Array.from(
944 Deno.readDirSync(`${basePath}/${date}/`),
945 ).sort(({ name: a }, { name: b }) =>
946 a < b ? -1 : a > b ? 1 : 0
947 )
948 ) {
949 // Iterate over each directory and process the ones which look
950 // like entries.
951 if (
952 !isDirectory ||
953 //deno-lint-ignore no-control-regex
954 /[\x00-\x20\x22#%/<>?\\^\x60{|}\x7F]/u.test(entryName)
955 ) {
956 // This isn’t an entry directory.
957 continue;
958 } else {
959 // Process the entry.
960 const entry = document.createElement("entry");
961 const entryPath =
962 `${basePath}/${date}/${entryName}/#entry.rdf`;
963 const entryDocument = parser.parseFromString(
964 await Deno.readTextFile(entryPath),
965 "application/xml",
966 );
967 const { documentElement: entryRoot } = entryDocument;
968 entryDocument.lastModified =
969 (await Deno.lstat(entryPath)).mtime;
970 if (!entryRoot.hasAttributeNS(RDF, "about")) {
971 // The entry doesn’t have an identifier; let’s give it one.
972 entryRoot.setAttributeNS(
973 RDF,
974 "about",
975 new URL(`./${date}/${entryName}/`, feedURI),
976 );
977 } else {
978 // The entry already has an identifier.
979 /* do nothing */
980 }
981 const entryMetadata = metadataFromDocument(entryDocument);
982 if (entryMetadata.author.length == 0) {
983 // The entry metadata did not supply an author.
984 entryMetadata.author = feedMetadata.author;
985 } else {
986 // The entry metadata supplied its own author.
987 /* do nothing */
988 }
989 const entryTemplate = await documentFromTemplate("entry");
990 const { documentElement: templateRoot } = entryTemplate;
991 const lang = getLanguage(entryRoot);
992 if (lang && !getLanguage(templateRoot)) {
993 // The root element of the template does not have an
994 // assigned language, but the entry does.
995 setLanguage(templateRoot, lang);
996 } else {
997 // Either the template root already has a language, or the
998 // entry doesn’t either.
999 /* do nothing */
1000 }
1001 writes.push(
1002 Deno.writeTextFile(
1003 `${basePath}/${date}/${entryName}/index.xhtml`,
1004 serializer.serializeToString(
1005 applyMetadata(entryTemplate, entryMetadata),
1006 ) + "\n",
1007 ),
1008 );
1009 applyMetadata(entry, entryMetadata);
1010 applyMetadata(feedEntries, entryMetadata);
1011 feed.appendChild(entry);
1012 }
1013 }
1014 }
1015 }
1016
1017 // Apply the feed metadata to the feed template and save the
1018 // resulting index file.
1019 const { documentElement: feedRoot } = feedTemplate;
1020 if (hasExpandedName(feedRoot, XHTML, "html")) {
1021 // This is an XHTML template.
1022 const LMN = Lemon.bind({ document: feedTemplate });
1023 const {
1024 id,
1025 title,
1026 subtitle,
1027 rights,
1028 updated,
1029 } = feedMetadata;
1030 fillOutHead(feedTemplate, feedMetadata, "feed");
1031 const contentPlaceholder = feedTemplate.getElementsByTagNameNS(
1032 XHTML,
1033 "bjørn-content",
1034 ).item(0);
1035 if (contentPlaceholder != null) {
1036 // There is a content placeholder.
1037 const { parentNode: contentParent } = contentPlaceholder;
1038 const contentElement = contentParent.insertBefore(
1039 LMN.nav.about(`${id}`)`${"\n"}`,
1040 contentPlaceholder,
1041 );
1042 const contentHeader = contentElement.appendChild(
1043 LMN.header`${"\n\t"}`,
1044 );
1045 addContent(
1046 contentHeader.appendChild(LMN.h1.property(`${DC11}title`)``),
1047 title,
1048 );
1049 addContent(contentHeader, "\n");
1050 if (subtitle) {
1051 // The feed has a subtitle.
1052 addContent(
1053 contentHeader.appendChild(LMN.p.property(`${RDFS}label`)``),
1054 subtitle,
1055 );
1056 addContent(contentHeader, "\n");
1057 } else {
1058 // The feed has no subtitle.
1059 /* do nothing */
1060 }
1061 addContent(contentElement, "\n");
1062 const entriesElement = contentElement.appendChild(
1063 LMN.ul.rel(`${AWOL}entry`)`${"\n"}`,
1064 );
1065 entriesElement.appendChild(feedEntries);
1066 addContent(contentElement, "\n");
1067 const contentFooter = contentElement.appendChild(
1068 LMN.footer`${"\n\t"}`,
1069 );
1070 if (rights) {
1071 // The feed has a rights statement.
1072 addContent(
1073 contentFooter.appendChild(
1074 LMN.div.property(`${DC11}rights`)``,
1075 ),
1076 rights,
1077 );
1078 addContent(contentFooter, "\n\t");
1079 } else {
1080 // The feed has no rights statement.
1081 /* do nothing */
1082 }
1083 contentFooter.appendChild(
1084 LMN.p.id("entry.updated")`Last updated: ${LMN.time.property(
1085 `${AWOL}updated`,
1086 )`${updated}`}.`,
1087 );
1088 addContent(contentFooter, "\n");
1089 addContent(contentElement, "\n");
1090 contentParent.removeChild(contentPlaceholder);
1091 } else {
1092 /* do nothing */
1093 }
1094 }
1095 writes.push(
1096 Deno.writeTextFile(
1097 "index.xhtml",
1098 serializer.serializeToString(feedTemplate) + "\n",
1099 ),
1100 );
1101
1102 // Save the feed Atom file.
1103 writes.push(
1104 Deno.writeTextFile(
1105 "feed.atom",
1106 serializer.serializeToString(document) + "\n",
1107 ),
1108 );
1109
1110 // Await all writes.
1111 await Promise.all(writes);
1112 })();
This page took 0.177276 seconds and 3 git commands to generate.