]> Lady’s Gitweb - Beorn/blob - build.js
af75d5b06308e62687cf8d8f6631150eaf7f0766
[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 if (summary) {
407 // This entry has a summary.
408 addContent(contentElement, "\n");
409 addContent(
410 contentElement.appendChild(
411 LMN.div.property(`${DC11}abstract`)``,
412 ),
413 summary,
414 );
415 } else {
416 // This entry does not have a summary.
417 /* do nothing */
418 }
419 addContent(contentElement, "\n");
420 addContent(node, "\n");
421 } else {
422 // The provided node is not a document or document fragment.
423 //
424 // Assume it is an Atom element of some sort and add the
425 // the appropriate metadata as child elements.
426 const { ownerDocument: document } = node;
427 const alternateLink = node.appendChild(
428 document.createElement("link"),
429 );
430 alternateLink.setAttribute("rel", "alternate");
431 alternateLink.setAttribute("type", "application/xhtml+xml");
432 alternateLink.setAttribute("href", metadata.id);
433 for (const [property, values] of Object.entries(metadata)) {
434 for (const value of Array.isArray(values) ? values : [values]) {
435 const propertyNode = document.createElement(property);
436 switch (context[property]?.type) {
437 case "person": {
438 // The property describes a person.
439 const { name, uri } = value;
440 if (uri) {
441 // The person has a U·R·I.
442 const subnode = document.createElement("uri");
443 subnode.textContent = uri;
444 propertyNode.appendChild(subnode);
445 } else {
446 // The person does not have a U·R·I.
447 /* do nothing */
448 }
449 if (name != null) {
450 // The person has a name.
451 const subnode = document.createElement("name");
452 subnode.textContent = name;
453 propertyNode.appendChild(subnode);
454 } else {
455 // The person does not have a name.
456 /* do nothing */
457 }
458 if (propertyNode.childNodes.length == 0) {
459 // Neither a U·R·I nor a name was added; skip adding this
460 // property.
461 continue;
462 } else {
463 break;
464 }
465 }
466 default: {
467 // The property describes (potentially rich) text.
468 if (value == null) {
469 // The property has no value; skip appending it to the node.
470 continue;
471 } else if (Object(value) instanceof String) {
472 // The property has a string value.
473 propertyNode.textContent = value;
474 break;
475 } else {
476 // The property value is a list of nodes.
477 propertyNode.setAttribute("type", "xhtml");
478 const div = document.createElementNS(XHTML, "div");
479 for (const child of Array.from(value)) {
480 div.appendChild(document.importNode(child, true));
481 }
482 propertyNode.appendChild(div);
483 break;
484 }
485 }
486 }
487 node.appendChild(propertyNode);
488 }
489 }
490 }
491 return node;
492 };
493
494 /**
495 * The base path from which to pull files and generate resulting
496 * documents.
497 */
498 const basePath = `./${Deno.args[0] ?? ""}`;
499
500 /**
501 * Mappings from Atom concepts to R·D·F∕X·M·L ones.
502 *
503 * `namespace` and `localName` give the R·D·F representation for the
504 * concept. Three `type`s are supported :—
505 *
506 * - "person": Has a `name` (`foaf:name`) and an `iri` (`rdf:about`).
507 * Emails are NOT supported.
508 *
509 * - "text": Can be string, markdown, or X·M·L content.
510 *
511 * - "literal": This is a plaintext field.
512 */
513 const context = {
514 author: { namespace: DC11, localName: "creator", type: "person" },
515 // category is not supported at this time
516 content: { namespace: SIOC, localName: "content", type: "text" },
517 contributor: {
518 namespace: DC11,
519 localName: "contributor",
520 type: "person",
521 },
522 // generator is provided by the build script
523 icon: { namespace: AWOL, localName: "icon", type: "literal" },
524 // link is provided by the build script
525 logo: { namespace: AWOL, localName: "logo", type: "literal" },
526 published: {
527 namespace: DC11,
528 localName: "date",
529 type: "literal",
530 },
531 rights: { namespace: DC11, localName: "rights", type: "text" },
532 // source is not supported at this time
533 subtitle: { namespace: RDFS, localName: "label", type: "text" },
534 summary: { namespace: DC11, localName: "abstract", type: "text" },
535 title: { namespace: DC11, localName: "title", type: "text" },
536 // updated is provided by the build script
537 };
538
539 const {
540 /**
541 * Returns a new document created from the source code of the named
542 * template.
543 */
544 documentFromTemplate,
545 } = (() => {
546 const cache = Object.create(null);
547 return {
548 documentFromTemplate: async (name) =>
549 parser.parseFromString(
550 name in cache ? cache[name] : (
551 cache[name] = await Deno.readTextFile(
552 `${basePath}/index#${name}.xhtml`,
553 )
554 ),
555 "application/xml",
556 ),
557 };
558 })();
559
560 /**
561 * Fills out the `head` of the provided H·T·M·L document with the
562 * appropriate metadata.
563 */
564 const fillOutHead = (document, metadata, type) => {
565 const { documentElement } = document;
566 const LMN = Lemon.bind({ document });
567 const head =
568 Array.from(documentElement.childNodes).find(($) =>
569 hasExpandedName($, XHTML, "head")
570 ) ?? documentElement.insertBefore(
571 LMN.head``,
572 documentElement.childNodes.item(0),
573 );
574 const titleElement =
575 Array.from(head.childNodes).find(($) =>
576 hasExpandedName($, XHTML, "title")
577 ) ?? head.appendChild(LMN.title``);
578 const {
579 title,
580 author,
581 subtitle,
582 summary,
583 } = metadata;
584 titleElement.textContent = Object(title) instanceof String
585 ? title
586 : Array.from(title ?? []).map(($) => $.textContent).join("");
587 for (const person of author) {
588 // Iterate over authors and add appropriate meta tags.
589 head.appendChild(
590 LMN.meta({
591 name: "author",
592 content: person.name ?? person.uri,
593 })``,
594 );
595 }
596 head.appendChild(
597 LMN.meta({ name: "generator", content: "🧸📔 Bjørn" })``,
598 );
599 if (type == "entry") {
600 // The provided document is an entry document.
601 if (summary) {
602 // The entry has a summary.
603 head.appendChild(
604 LMN.meta({
605 name: "description",
606 content: Object(summary) instanceof String
607 ? summary
608 : Array.from(summary).map(($) => $.textContent).join(""),
609 })``,
610 );
611 } else {
612 /* do nothing */
613 }
614 head.appendChild(
615 LMN.link
616 .rel("alternate")
617 .type("application/atom+xml")
618 .href("../../feed.atom")``,
619 );
620 } else {
621 // The provided document is not an entry document.
622 if (subtitle) {
623 // The entry has a subtitle.
624 head.appendChild(
625 LMN.meta({
626 name: "description",
627 content: Object(subtitle) instanceof String
628 ? summary
629 : Array.from(subtitle).map(($) => $.textContent).join(""),
630 })``,
631 );
632 } else {
633 /* do nothing */
634 }
635 head.appendChild(
636 LMN.link
637 .rel("alternate")
638 .type("application/atom+xml")
639 .href("./feed.atom")``,
640 );
641 }
642 };
643
644 /**
645 * Returns the language of the provided node, or null if it has no
646 * language.
647 *
648 * ※ This function returns null regardless of whether a node has no
649 * language implicitly (because no parent element had a language set)
650 * or explicitly (because the value of the @xml:lang attribute was "").
651 *
652 * ※ If no language is set, the language of the node is ambiguous.
653 * Because this typically occurs when a node is expected to inherit its
654 * language from some parent context, this lack of language information
655 * SHOULD NOT be preserved when inserting the node into a document
656 * where language information is present (instead allowing the node to
657 * inherit language information from the node it is being inserted
658 * into). There are explicit language codes which may be used if this
659 * behaviour is undesirable: If you want to signal that a node does not
660 * contain linguistic content, use the language code `zxx`. If you want
661 * to signal that a node’s language is undetermined in a way which will
662 * never inherit from a parent node, use the language code `und`.
663 */
664 const getLanguage = (node) => {
665 const { nodeType } = node;
666 if (nodeType == 1) {
667 // The provided node is an element.
668 const ownLanguage =
669 node.namespaceURI == XHTML && node.hasAttribute("lang") &&
670 node.getAttribute("lang") ||
671 node.hasAttributeNS(XML, "lang") &&
672 node.getAttributeNS(XML, "lang");
673 if (ownLanguage) {
674 // The element has a recognized language attribute set to a
675 // nonempty value.
676 return ownLanguage;
677 } else if (ownLanguage === "") {
678 // The element explicitly has no language.
679 return null;
680 } else {
681 // The element has no language attribute, but may inherit a
682 // language from its parent.
683 const { parentNode } = node;
684 if (parentNode != null && parentNode.nodeType != 9) {
685 // The provided node has a nondocument parent; get the language
686 // from there.
687 return getLanguage(parentNode);
688 } else {
689 // The provided node has no parent and consequently no language.
690 return null;
691 }
692 }
693 } else if (nodeType == 9) {
694 // The provided node is a document.
695 return getLanguage(node.documentElement);
696 } else if (nodeType == 11) {
697 // The provided node is a document fragment.
698 return getLanguage(node.ownerDocument.documentElement);
699 } else {
700 // The provided node may inherit a language from a parent node.
701 const { parentNode } = node;
702 if (parentNode != null) {
703 // The provided node has a parent; get the language from there.
704 return getLanguage(parentNode);
705 } else {
706 // The provided node has no parent and consequently no language.
707 return null;
708 }
709 }
710 };
711
712 /**
713 * Returns whether the provided node has the provided namespace and
714 * local name.
715 */
716 const hasExpandedName = (node, namespace, localName) =>
717 node.namespaceURI == namespace && node.localName == localName;
718
719 /**
720 * Processes an RDF document and returns an object of Atom metadata.
721 *
722 * See `context` for the metadata properties supported.
723 */
724 const metadataFromDocument = (
725 { documentElement: root, lastModified },
726 ) => {
727 const contextEntries = [...Object.entries(context)];
728 const documentType = hasExpandedName(root, AWOL, "Feed")
729 ? "feed"
730 : "entry";
731 const result = Object.assign(Object.create(null), {
732 id: root.getAttributeNS(RDF, "about"),
733 updated: documentType == "feed" || lastModified == null
734 ? new Date().toISOString()
735 : lastModified.toISOString(),
736 title: null,
737 author: [],
738 contributor: [],
739 rights: null,
740 ...(documentType == "feed"
741 ? { // additional feed properties
742 subtitle: null,
743 logo: null,
744 icon: null,
745 }
746 : { // additional entry properties
747 published: null,
748 summary: null,
749 content: null,
750 }),
751 });
752 for (
753 const node of [
754 ...Array.from(root.attributes),
755 ...Array.from(root.childNodes),
756 ]
757 ) {
758 // Iterate over all child nodes and attributes, finding ones which
759 // correspond to Atom properties and assigning the appropriate
760 // metadata.
761 const [name, { type }] = contextEntries.find(
762 ([_, value]) =>
763 hasExpandedName(node, value.namespace, value.localName),
764 ) ?? [, {}];
765 if (name != null && name in result) {
766 // The current node corresponds with an Atom property.
767 const { [name]: existing } = result;
768 const content = (() => {
769 switch (type) {
770 case "person": {
771 // The node describes a person.
772 const base =
773 node.getAttributeNS?.(RDF, "parseType") == "Resource"
774 ? node
775 : Array.from(node.childNodes).find(($) =>
776 $.nodeType == 1
777 );
778 const person = {
779 name: null,
780 uri: base.getAttributeNS?.(RDF, "about") || null,
781 };
782 for (
783 const subnode of [
784 ...Array.from(base.attributes),
785 ...Array.from(base.childNodes),
786 ]
787 ) {
788 // Process child nodes and attributes for the current
789 // person, looking for name metadata.
790 if (hasExpandedName(subnode, FOAF, "name")) {
791 // This is a name node.
792 if (person.name == null) {
793 // No name has been set yet.
794 person.name = subnode.textContent;
795 } else {
796 // A name has already been set.
797 throw new TypeError(
798 `Duplicate name found for person${
799 person.id != null ? ` <${person.id}>` : ""
800 } while processing <${result.id}>.`,
801 );
802 }
803 } else {
804 // This is not a name node
805 /* do nothing */
806 }
807 }
808 return person;
809 }
810 case "text": {
811 // The node describes (potentially rich) textual content.
812 //
813 // ☡ Don’t return an Array here or it will look like a list
814 // of multiple values. Return the NodeList of child nodes
815 // directly.
816 const parseType = node.getAttributeNS?.(RDF, "parseType");
817 if (parseType == "Markdown") {
818 // This is an element with Markdown content (which
819 // hopefully can be converted into X·M·L).
820 return parser.parseFromString(
821 `<福 xmlns="${XHTML}" lang="${
822 getLanguage(node) ?? ""
823 }">${
824 markdownTokensToHTML(
825 markdownTokens(node.textContent),
826 )
827 }</福>`,
828 "application/xml",
829 ).documentElement.childNodes;
830 } else if (parseType == "Literal") {
831 // This is an element with literal X·M·L contents.
832 return node.childNodes;
833 } else {
834 // This is an element without literal X·M·L contents.
835 /* do nothing */
836 }
837 } // falls through
838 default: {
839 // The node describes something in plaintext.
840 const text = new String(node.textContent);
841 const lang = getLanguage(node);
842 if (lang) {
843 text.lang = lang;
844 } else {
845 /* do nothing */
846 }
847 return text;
848 }
849 }
850 })();
851 if (existing == null) {
852 // The property takes at most one value, but none has been set.
853 result[name] = content;
854 } else if (Array.isArray(existing)) {
855 // The property takes multiple values.
856 existing.push(content);
857 } else {
858 // The property takes at most one value, and one has already
859 // been set.
860 throw new TypeError(
861 `Duplicate content found for ${name} while processing <${result.id}>.`,
862 );
863 }
864 } else {
865 // The current node does not correspond with an Atom property.
866 /* do nothing */
867 }
868 }
869 return validateMetadata(result, documentType);
870 };
871
872 /** The DOMParser used by this script. */
873 const parser = new DOMParser();
874
875 /** The XMLSerializer used by this script. */
876 const serializer = new XMLSerializer();
877
878 /**
879 * Sets the @xml:lang attribute of the provided element, and if it is
880 * an H·T·M·L element also sets the @lang.
881 */
882 const setLanguage = (element, lang) => {
883 element.setAttributeNS(XML, "xml:lang", lang ?? "");
884 if (element.namespaceURI == XHTML) {
885 element.setAttribute("lang", lang ?? "");
886 } else {
887 /* do nothing */
888 }
889 };
890
891 /**
892 * Throws if the provided metadata does not conform to expectations for
893 * the provided type, and otherwise returns it.
894 */
895 const validateMetadata = (metadata, type) => {
896 if (metadata.id == null) {
897 throw new TypeError("Missing id.");
898 } else if (metadata.title == null) {
899 throw new TypeError(`Missing title for item <${metadata.id}>.`);
900 } else if (type == "feed" && metadata.author == null) {
901 throw new TypeError(`Missing author for feed <${metadata.id}>.`);
902 } else if (type == "entry" && metadata.content == null) {
903 throw new TypeError(`Missing content for entry <${metadata.id}>.`);
904 } else {
905 return metadata;
906 }
907 };
908
909 await (async () => { // this is the run script
910 const writes = [];
911
912 // Set up the feed metadata and Atom feed document.
913 const feedMetadata = metadataFromDocument(
914 parser.parseFromString(
915 await Deno.readTextFile(`${basePath}/#feed.rdf`),
916 "application/xml",
917 ),
918 );
919 const feedURI = new URL(feedMetadata.id);
920 const document = parser.parseFromString(
921 `<?xml version="1.0" encoding="utf-8"?>
922 <feed xmlns="http://www.w3.org/2005/Atom"><generator>🧸📔 Bjørn</generator><link rel="self" type="application/atom+xml" href="${new URL(
923 "./feed.atom",
924 feedURI,
925 )}"/></feed>`,
926 "application/xml",
927 );
928 const { documentElement: feed } = document;
929 applyMetadata(feed, feedMetadata);
930
931 // Set up the index page.
932 const feedTemplate = await documentFromTemplate("feed");
933 const feedEntries = feedTemplate.createDocumentFragment();
934
935 // Process entries and save the resulting index files.
936 for await (
937 const { name: date, isDirectory } of Deno.readDir(
938 `${basePath}/`,
939 )
940 ) {
941 // Iterate over each directory and process the ones which are
942 // dates.
943 if (!isDirectory || !/[0-9]{4}-[0-9]{2}-[0-9]{2}/u.test(date)) {
944 // This isn’t a dated directory.
945 continue;
946 } else {
947 // This is a dated directory.
948 for (
949 const { name: entryName, isDirectory } of Array.from(
950 Deno.readDirSync(`${basePath}/${date}/`),
951 ).sort(({ name: a }, { name: b }) =>
952 a < b ? -1 : a > b ? 1 : 0
953 )
954 ) {
955 // Iterate over each directory and process the ones which look
956 // like entries.
957 if (
958 !isDirectory ||
959 //deno-lint-ignore no-control-regex
960 /[\x00-\x20\x22#%/<>?\\^\x60{|}\x7F]/u.test(entryName)
961 ) {
962 // This isn’t an entry directory.
963 continue;
964 } else {
965 // Process the entry.
966 const entry = document.createElement("entry");
967 const entryPath =
968 `${basePath}/${date}/${entryName}/#entry.rdf`;
969 const entryDocument = parser.parseFromString(
970 await Deno.readTextFile(entryPath),
971 "application/xml",
972 );
973 const { documentElement: entryRoot } = entryDocument;
974 entryDocument.lastModified =
975 (await Deno.lstat(entryPath)).mtime;
976 if (!entryRoot.hasAttributeNS(RDF, "about")) {
977 // The entry doesn’t have an identifier; let’s give it one.
978 entryRoot.setAttributeNS(
979 RDF,
980 "about",
981 new URL(`./${date}/${entryName}/`, feedURI),
982 );
983 } else {
984 // The entry already has an identifier.
985 /* do nothing */
986 }
987 const entryMetadata = metadataFromDocument(entryDocument);
988 if (entryMetadata.author.length == 0) {
989 // The entry metadata did not supply an author.
990 entryMetadata.author = feedMetadata.author;
991 } else {
992 // The entry metadata supplied its own author.
993 /* do nothing */
994 }
995 const entryTemplate = await documentFromTemplate("entry");
996 const { documentElement: templateRoot } = entryTemplate;
997 const lang = getLanguage(entryRoot);
998 if (lang && !getLanguage(templateRoot)) {
999 // The root element of the template does not have an
1000 // assigned language, but the entry does.
1001 setLanguage(templateRoot, lang);
1002 } else {
1003 // Either the template root already has a language, or the
1004 // entry doesn’t either.
1005 /* do nothing */
1006 }
1007 writes.push(
1008 Deno.writeTextFile(
1009 `${basePath}/${date}/${entryName}/index.xhtml`,
1010 serializer.serializeToString(
1011 applyMetadata(entryTemplate, entryMetadata),
1012 ) + "\n",
1013 ),
1014 );
1015 applyMetadata(entry, entryMetadata);
1016 applyMetadata(feedEntries, entryMetadata);
1017 feed.appendChild(entry);
1018 }
1019 }
1020 }
1021 }
1022
1023 // Apply the feed metadata to the feed template and save the
1024 // resulting index file.
1025 const { documentElement: feedRoot } = feedTemplate;
1026 if (hasExpandedName(feedRoot, XHTML, "html")) {
1027 // This is an XHTML template.
1028 const LMN = Lemon.bind({ document: feedTemplate });
1029 const {
1030 id,
1031 title,
1032 subtitle,
1033 rights,
1034 updated,
1035 } = feedMetadata;
1036 fillOutHead(feedTemplate, feedMetadata, "feed");
1037 const contentPlaceholder = feedTemplate.getElementsByTagNameNS(
1038 XHTML,
1039 "bjørn-content",
1040 ).item(0);
1041 if (contentPlaceholder != null) {
1042 // There is a content placeholder.
1043 const { parentNode: contentParent } = contentPlaceholder;
1044 const contentElement = contentParent.insertBefore(
1045 LMN.nav.about(`${id}`)`${"\n"}`,
1046 contentPlaceholder,
1047 );
1048 const contentHeader = contentElement.appendChild(
1049 LMN.header`${"\n\t"}`,
1050 );
1051 addContent(
1052 contentHeader.appendChild(LMN.h1.property(`${DC11}title`)``),
1053 title,
1054 );
1055 addContent(contentHeader, "\n");
1056 if (subtitle) {
1057 // The feed has a subtitle.
1058 addContent(
1059 contentHeader.appendChild(LMN.p.property(`${RDFS}label`)``),
1060 subtitle,
1061 );
1062 addContent(contentHeader, "\n");
1063 } else {
1064 // The feed has no subtitle.
1065 /* do nothing */
1066 }
1067 addContent(contentElement, "\n");
1068 const entriesElement = contentElement.appendChild(
1069 LMN.ul.rel(`${AWOL}entry`)`${"\n"}`,
1070 );
1071 entriesElement.appendChild(feedEntries);
1072 addContent(contentElement, "\n");
1073 const contentFooter = contentElement.appendChild(
1074 LMN.footer`${"\n\t"}`,
1075 );
1076 if (rights) {
1077 // The feed has a rights statement.
1078 addContent(
1079 contentFooter.appendChild(
1080 LMN.div.property(`${DC11}rights`)``,
1081 ),
1082 rights,
1083 );
1084 addContent(contentFooter, "\n\t");
1085 } else {
1086 // The feed has no rights statement.
1087 /* do nothing */
1088 }
1089 contentFooter.appendChild(
1090 LMN.p.id("entry.updated")`Last updated: ${LMN.time.property(
1091 `${AWOL}updated`,
1092 )`${updated}`}.`,
1093 );
1094 addContent(contentFooter, "\n");
1095 addContent(contentElement, "\n");
1096 contentParent.removeChild(contentPlaceholder);
1097 } else {
1098 /* do nothing */
1099 }
1100 }
1101 writes.push(
1102 Deno.writeTextFile(
1103 "index.xhtml",
1104 serializer.serializeToString(feedTemplate) + "\n",
1105 ),
1106 );
1107
1108 // Save the feed Atom file.
1109 writes.push(
1110 Deno.writeTextFile(
1111 "feed.atom",
1112 serializer.serializeToString(document) + "\n",
1113 ),
1114 );
1115
1116 // Await all writes.
1117 await Promise.all(writes);
1118 })();
This page took 0.16493 seconds and 3 git commands to generate.