diff options
Diffstat (limited to 'src/write/build-modes')
-rw-r--r-- | src/write/build-modes/index.js | 4 | ||||
-rw-r--r-- | src/write/build-modes/live-dev-server.js | 576 | ||||
-rw-r--r-- | src/write/build-modes/repl.js | 165 | ||||
-rw-r--r-- | src/write/build-modes/sort.js | 76 | ||||
-rw-r--r-- | src/write/build-modes/static-build.js | 632 |
5 files changed, 1453 insertions, 0 deletions
diff --git a/src/write/build-modes/index.js b/src/write/build-modes/index.js new file mode 100644 index 00000000..4b61619d --- /dev/null +++ b/src/write/build-modes/index.js @@ -0,0 +1,4 @@ +export * as 'live-dev-server' from './live-dev-server.js'; +export * as 'repl' from './repl.js'; +export * as 'sort' from './sort.js'; +export * as 'static-build' from './static-build.js'; diff --git a/src/write/build-modes/live-dev-server.js b/src/write/build-modes/live-dev-server.js new file mode 100644 index 00000000..ecb9df21 --- /dev/null +++ b/src/write/build-modes/live-dev-server.js @@ -0,0 +1,576 @@ +import {spawn} from 'node:child_process'; +import * as http from 'node:http'; +import {open, stat} from 'node:fs/promises'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import {pipeline} from 'node:stream/promises'; +import {inspect as nodeInspect} from 'node:util'; + +import {openAggregate} from '#aggregate'; +import {ENABLE_COLOR, colors, fileIssue, logInfo, logWarn, progressCallAll} + from '#cli'; +import {watchContentDependencies} from '#content-dependencies'; +import {quickEvaluate} from '#content-function'; +import * as html from '#html'; +import * as pageSpecs from '#page-specs'; +import {serializeThings} from '#serialize'; + +import { + getPagePathname, + getURLsFrom, + getURLsFromRoot, +} from '#urls'; + +import {bindUtilities} from '../bind-utilities.js'; +import {generateRandomLinkDataJSON, generateRedirectHTML} from '../common-templates.js'; + +const defaultHost = '0.0.0.0'; +const defaultPort = 8002; + +export const description = `Hosts a local HTTP server which generates page content as it is requested, instead of all at once\n\nIntended for local development ONLY; this custom HTTP server is NOT rigorously tested and almost certainly has security flaws`; + +export const config = { + fileSizes: { + default: 'perform', + }, + + languageReloading: { + default: 'perform', + }, + + mediaValidation: { + default: 'perform', + }, + + thumbs: { + default: 'perform', + }, + + webRoutes: { + required: true, + }, +}; + +function inspect(value, opts = {}) { + return nodeInspect(value, {colors: ENABLE_COLOR, ...opts}); +} + +export function getCLIOptions() { + return { + host: { + help: `Hostname to which HTTP server is bound\nDefaults to ${defaultHost}`, + type: 'value', + }, + + port: { + help: `Port to which HTTP server is bound\nDefaults to ${defaultPort}`, + type: 'value', + validate(size) { + if (parseInt(size) !== parseFloat(size)) return 'an integer'; + if (parseInt(size) < 1024 || parseInt(size) > 49151) return 'a user/registered port (1024-49151)'; + return true; + }, + }, + + 'loud-responses': { + help: `Enables outputting [200] and [404] responses in the server log, which are suppressed by default`, + type: 'flag', + }, + + 'show-timings': { + help: `Enables outputting timings in the server log for how long pages to take to generate`, + type: 'flag', + }, + + 'serve-sfx': { + help: `Plays the specified sound file once the HTTP server is ready (this requires mpv)`, + type: 'value', + }, + + 'skip-serving': { + help: `Causes the build to exit when it would start serving over HTTP instead\n\nMainly useful for testing performance`, + type: 'flag', + }, + }; +} + +const getContentType = extname => ({ + // BRB covering all my bases + 'aac': 'audio/aac', + 'bmp': 'image/bmp', + 'css': 'text/css', + 'csv': 'text/csv', + 'gif': 'image/gif', + 'ico': 'image/vnd.microsoft.icon', + 'jpg': 'image/jpeg', + 'jpeg': 'image/jpeg', + 'js': 'text/javascript', + 'mjs': 'text/javascript', + 'mp3': 'audio/mpeg', + 'mp4': 'video/mp4', + 'oga': 'audio/ogg', + 'ogg': 'audio/ogg', + 'ogv': 'video/ogg', + 'opus': 'audio/opus', + 'png': 'image/png', + 'pdf': 'application/pdf', + 'svg': 'image/svg+xml', + 'ttf': 'font/ttf', + 'txt': 'text/plain', + 'wav': 'audio/wav', + 'weba': 'audio/webm', + 'webm': 'video/webm', + 'woff': 'font/woff', + 'woff2': 'font/woff2', + 'xml': 'application/xml', + 'zip': 'application/zip', +})[extname]; + +export async function go({ + cliOptions, + + universalUtilities, + + defaultLanguage, + languages, + urls, + webRoutes, + wikiData, + + niceShowAggregate, +}) { + const showError = (error) => { + if (niceShowAggregate) { + if (error.errors || error.cause) { + niceShowAggregate(error); + return; + } + } + + console.error(inspect(error, {depth: Infinity})); + }; + + const host = cliOptions['host'] ?? defaultHost; + const port = parseInt(cliOptions['port'] ?? defaultPort); + const loudResponses = cliOptions['loud-responses'] ?? false; + const showTimings = cliOptions['show-timings'] ?? false; + const skipServing = cliOptions['skip-serving'] ?? false; + const serveSFX = cliOptions['serve-sfx'] ?? null; + + const contentDependenciesWatcher = await watchContentDependencies({ + showAggregate: niceShowAggregate, + }); + + const {contentDependencies} = contentDependenciesWatcher; + + contentDependenciesWatcher.on('error', () => {}); + await new Promise(resolve => contentDependenciesWatcher.once('ready', resolve)); + + const commonUtilities = {...universalUtilities}; + + const pathAggregate = openAggregate({message: `Errors computing page paths`}); + + let targetSpecPairs = getPageSpecsWithTargets({wikiData}); + const pages = progressCallAll(`Computing page paths for ${targetSpecPairs.length} targets.`, + targetSpecPairs.flatMap(({ + pageSpec, + target, + targetless, + }) => () => { + try { + if (targetless) { + const result = pageSpec.pathsTargetless({wikiData}); + return Array.isArray(result) ? result : [result]; + } else { + return pageSpec.pathsForTarget(target); + } + } catch (caughtError) { + if (targetless) { + pathAggregate.push(new Error( + `Failed to compute targetless paths for ` + + inspect(pageSpec, {compact: true}), + {cause: caughtError})); + } else { + pathAggregate.push(new Error( + `Failed to compute paths for ` + + inspect(target), + {cause: caughtError})); + } + return []; + } + })).flat(); + + try { + pathAggregate.close(); + } catch (error) { + niceShowAggregate(error); + logWarn`Failed to compute page paths for some targets.`; + logWarn`This means some pages that normally exist will be 404s.`; + fileIssue(); + } + + logInfo`Will be serving a total of ${pages.length} pages.`; + + const urlToPageMap = Object.fromEntries(pages + .filter(page => page.type === 'page' || page.type === 'redirect') + .flatMap(page => { + let servePath; + if (page.type === 'page') + servePath = page.path; + else if (page.type === 'redirect') + servePath = page.fromPath; + + return Object.values(languages).map(language => { + const baseDirectory = + language === defaultLanguage ? '' : language.code; + + const pathname = getPagePathname({ + baseDirectory, + pagePath: servePath, + urls, + }); + + return [pathname, { + baseDirectory, + language, + page, + servePath, + }]; + }); + })); + + const server = http.createServer(async (request, response) => { + const contentTypeHTML = {'Content-Type': 'text/html; charset=utf-8'}; + const contentTypeJSON = {'Content-Type': 'application/json; charset=utf-8'}; + const contentTypePlain = {'Content-Type': 'text/plain; charset=utf-8'}; + + const requestTime = new Date().toLocaleDateString('en-US', {hour: '2-digit', minute: '2-digit', second: '2-digit'}); + const requestHead = + (loudResponses + ? `${requestTime} - ${request.socket.remoteAddress}` + : `${requestTime}`); + + let url; + try { + url = new URL(request.url, `http://${request.headers.host}`); + } catch (error) { + response.writeHead(500, contentTypePlain); + response.end('Failed to parse request URL\n'); + return; + } + + const {pathname} = url; + + // Specialized routes + + if (pathname === '/random-link-data.json') { + try { + const json = generateRandomLinkDataJSON({ + serializeThings, + wikiData, + }); + + response.writeHead(200, contentTypeJSON); + response.end(json); + if (loudResponses) console.log(`${requestHead} [200] ${pathname} (${colors.yellow(`special`)})`); + } catch (error) { + response.writeHead(500, contentTypeJSON); + response.end(`Internal error serializing wiki JSON`); + console.error(`${requestHead} [500] ${pathname}`); + showError(error); + } + return; + } + + const matchedWebRoute = + webRoutes + .find(({to}) => pathname.startsWith('/' + to)); + + if (matchedWebRoute) { + const localFilePath = pathname.slice(1 + matchedWebRoute.to.length); + + // Not security tested, man, this is a dev server!! + const safePath = + path.posix + .resolve('/', localFilePath) + .replace(/^\//, ''); + + const localDirectory = matchedWebRoute.from; + + let filePath; + try { + filePath = path.resolve(localDirectory, decodeURI(safePath.split('/').join(path.sep))); + } catch (error) { + response.writeHead(404, contentTypePlain); + response.end(`File not found for: ${safePath}`); + console.log(`${requestHead} [404] ${pathname}`); + console.log(`Failed to decode request pathname`); + } + + try { + await stat(filePath); + } catch (error) { + if (error.code === 'ENOENT') { + response.writeHead(404, contentTypePlain); + response.end(`File not found for: ${safePath}`); + console.log(`${requestHead} [404] ${pathname}`); + console.log(`ENOENT for stat: ${filePath}`); + } else { + response.writeHead(500, contentTypePlain); + response.end(`Internal error accessing file for: ${safePath}`); + console.error(`${requestHead} [500] ${pathname}`); + showError(error); + } + return; + } + + const extname = path.extname(safePath).slice(1).toLowerCase(); + const contentType = getContentType(extname); + + let fd, size; + try { + ({size} = await stat(filePath)); + fd = await open(filePath); + } catch (error) { + if (error.code === 'EISDIR') { + response.writeHead(404, contentTypePlain); + response.end(`File not found for: ${safePath}`); + console.error(`${requestHead} [404] ${pathname} (is directory)`); + } else { + response.writeHead(500, contentTypePlain); + response.end(`Failed during file-to-response pipeline`); + console.error(`${requestHead} [500] ${pathname}`); + showError(error); + } + return; + } + + response.writeHead(200, { + ...contentType ? {'Content-Type': contentType} : {}, + 'Content-Length': size, + }); + + try { + await pipeline(fd.createReadStream(), response); + } catch (error) { + if (error.code === 'ERR_STREAM_PREMATURE_CLOSE') { + // Connection was dropped, this is OK. + return; + } else { + throw error; + } + } + + if (loudResponses) console.log(`${requestHead} [200] ${pathname} (${colors.magenta(`web route`)})`); + + return; + } + + // Other routes determined by page and URL specs + + const startTiming = () => { + if (!showTimings) { + return () => ''; + } + + const timeStart = Date.now(); + + return () => { + const timeEnd = Date.now(); + const timeDelta = timeEnd - timeStart; + + if (timeDelta > 100) { + return `${(timeDelta / 1000).toFixed(2)}s`; + } else { + return `${timeDelta}ms`; + } + }; + }; + + // URL to page map expects trailing slash but no leading slash. + const pathnameKey = pathname.replace(/^\//, '') + (pathname.endsWith('/') ? '' : '/'); + + const is404 = + !Object.hasOwn(urlToPageMap, pathnameKey) || + !(urlToPageMap[pathnameKey].page.condition?.() ?? true); + + if (is404) { + response.writeHead(404, contentTypePlain); + response.end(`No page found for: ${pathnameKey}\n`); + if (loudResponses) console.log(`${requestHead} [404] ${pathname} (no page)`); + return; + } + + // All pages expect to be served at a URL with a trailing slash, which must + // be fulfilled for relative URLs (ex. href="../lofam5/") to work. Redirect + // if there is no trailing slash in the request URL. + if (!pathname.endsWith('/')) { + const target = pathname + '/'; + response.writeHead(301, { + ...contentTypePlain, + 'Location': target, + }); + response.end(`Redirecting to: ${target}\n`); + console.log(`${requestHead} [301] (trl. slash) ${pathname}`); + return; + } + + const { + baseDirectory, + language, + page, + servePath, + } = urlToPageMap[pathnameKey]; + + const to = getURLsFrom({ + baseDirectory, + pagePath: servePath, + urls, + }); + + const absoluteTo = getURLsFromRoot({ + baseDirectory, + urls, + }); + + try { + if (page.type === 'redirect') { + const title = + page.title ?? + page.getTitle?.({language}); + + const target = to('localized.' + page.toPath[0], ...page.toPath.slice(1)); + + response.writeHead(301, { + ...contentTypeHTML, + 'Location': target, + }); + + const redirectHTML = generateRedirectHTML(title, target, {language}); + + response.end(redirectHTML); + + console.log(`${requestHead} [301] (redirect) ${pathname}`); + return; + } + + const timing = startTiming(); + + const bound = bindUtilities({ + ...commonUtilities, + + absoluteTo, + language, + pagePath: servePath, + pagePathStringFromRoot: pathname.replace(/^\//, ''), + to: page.absoluteLinks ? absoluteTo : to, + }); + + const topLevelResult = + quickEvaluate({ + contentDependencies, + extraDependencies: {...bound, appendIndexHTML: false}, + + name: page.contentFunction.name, + args: page.contentFunction.args ?? [], + }); + + const {pageHTML} = html.resolve(topLevelResult); + + const timeString = timing(); + const status = (timeString ? `200 ${timeString}` : `200`); + if (showTimings || loudResponses) { + console.log(`${requestHead} [${status}] ${pathname} (${colors.blue(`page`)})`); + } + + response.writeHead(200, contentTypeHTML); + response.end(pageHTML); + } catch (error) { + console.error(`${requestHead} [500] ${pathname}`); + showError(error); + response.writeHead(500, contentTypePlain); + response.end(`Error generating page, view server log for details\n`); + } + }); + + const addresses = + (host === '0.0.0.0' + ? [`http://localhost:${port}/`, + `http://${os.hostname()}:${port}/`] + : host === '127.0.0.1' + ? [`http://localhost:${port}/`] + : [`http://${host}:${port}/`]); + + server.on('error', error => { + if (error.code === 'EADDRINUSE') { + logWarn`Port ${port} is already in use - will (continually) retry after 10 seconds.`; + logWarn`Press ^C here (control+C) to exit and change ${'--port'} number, or stop the server currently running on port ${port}.`; + setTimeout(() => { + server.close(); + server.listen(port, host); + }, 10_000); + } else { + console.error(`Server error detected (code: ${error.code})`); + showError(error); + } + }); + + server.on('listening', () => { + if (addresses.length === 1) { + logInfo`${'All done!'} Listening at: ${addresses[0]}`; + } else { + logInfo`${`All done!`} Listening at:`; + for (const address of addresses) { + logInfo`- ${address}`; + } + } + + logInfo`Press ^C here (control+C) to stop the server and exit.`; + if (showTimings && loudResponses) { + logInfo`Printing all HTTP responses, plus page generation timings.`; + } else if (showTimings) { + logInfo`Printing page generation timings.`; + } else if (loudResponses) { + logInfo`Printing all HTTP responses.` + } else { + logInfo`Suppressing [200] and [404] response logging.` + logInfo`(Pass --loud-responses to show these.)`; + } + + if (serveSFX) { + spawn('mpv', [serveSFX, '--volume=75']); + } + }); + + if (skipServing) { + logInfo`Ready to serve! But --skip-serving was passed, so all done.`; + } else { + process.on('SIGINT', () => { + process.stdout.write('\n'); + server.close(); + }); + + await new Promise(resolve => { + server.listen(port, host); + server.on('close', () => resolve()); + }); + } + + return true; +} + +function getPageSpecsWithTargets({ + wikiData, +}) { + return Object.values(pageSpecs) + .filter(pageSpec => pageSpec.condition?.({wikiData}) ?? true) + .flatMap(pageSpec => [ + ...pageSpec.targets + ? pageSpec.targets({wikiData}) + .map(target => ({pageSpec, target})) + : [], + Object.hasOwn(pageSpec, 'pathsTargetless') && + {pageSpec, targetless: true}, + ]) + .filter(Boolean); +} diff --git a/src/write/build-modes/repl.js b/src/write/build-modes/repl.js new file mode 100644 index 00000000..920ad9f7 --- /dev/null +++ b/src/write/build-modes/repl.js @@ -0,0 +1,165 @@ +export const description = `Provide command-line interactive access to wiki data objects`; + +export const config = { + fileSizes: { + default: 'skip', + }, + + languageReloading: { + default: 'perform', + }, + + mediaValidation: { + default: 'skip', + }, + + search: { + default: 'skip', + }, + + thumbs: { + applicable: false, + }, +}; + +export function getCLIOptions() { + return { + 'no-repl-history': { + help: `Disable locally logging commands entered into the REPL in your home directory`, + type: 'flag', + }, + }; +} + +import * as os from 'node:os'; +import * as path from 'node:path'; +import * as repl from 'node:repl'; + +import _find, {bindFind} from '#find'; +import _reverse, {bindReverse} from '#reverse'; +import CacheableObject from '#cacheable-object'; +import {logWarn} from '#cli'; +import {debugComposite} from '#composite'; +import * as serialize from '#serialize'; +import * as sort from '#sort'; +import * as sugar from '#sugar'; +import thingConstructors from '#things'; +import * as wikiDataUtils from '#wiki-data'; + +export async function getContextAssignments({ + dataPath, + mediaPath, + mediaCachePath, + + universalUtilities, + + defaultLanguage, + wikiData, + + niceShowAggregate: showAggregate, +}) { + let find; + try { + find = bindFind(wikiData); + } catch (error) { + console.error(error); + logWarn`Failed to prepare wikiData-bound find() functions`; + logWarn`\`find\` variable will be missing`; + } + + let reverse; + try { + reverse = bindReverse(wikiData); + } catch (error) { + console.error(error); + logWarn`Failed to prepare wikiData-bound reverse() functions`; + logWarn`\`reverse\` variable will be missing`; + } + + const replContext = { + universalUtilities, + ...universalUtilities, + + dataPath, + mediaPath, + mediaCachePath, + + language: defaultLanguage, + + wikiData, + ...wikiData, + WD: wikiData, + + ...thingConstructors, + CacheableObject, + debugComposite, + + ...sort, + ...sugar, + ...wikiDataUtils, + + serialize, + S: serialize, + + _find, + find, + bindFind, + + _reverse, + reverse, + bindReverse, + + showAggregate, + }; + + replContext.replContext = replContext; + + return replContext; +} + +export async function go(buildOptions) { + const { + cliOptions, + closeLanguageWatchers, + } = buildOptions; + + const disableHistory = cliOptions['no-repl-history'] ?? false; + + console.log('HSMusic data REPL'); + + const replServer = repl.start(); + + Object.assign(replServer.context, + await getContextAssignments(buildOptions)); + + if (disableHistory) { + console.log(`\rInput history disabled (--no-repl-history provided)`); + } else { + const historyFile = path.join(os.homedir(), '.hsmusic_repl_history'); + await new Promise(resolve => { + replServer.setupHistory(historyFile, (err) => { + if (err) { + console.error(`\rFailed to begin locally logging input history to ${historyFile} (provide --no-repl-history to disable)`); + } else { + console.log(`\rLogging input history to ${historyFile} (provide --no-repl-history to disable)`); + } + resolve(); + }); + }); + } + + replServer.displayPrompt(true); + + let resolveDone; + + replServer.on('exit', () => { + closeLanguageWatchers(); + resolveDone(); + }); + + await new Promise(resolve => { + resolveDone = resolve; + }); + + return true; +} diff --git a/src/write/build-modes/sort.js b/src/write/build-modes/sort.js new file mode 100644 index 00000000..1a738ac8 --- /dev/null +++ b/src/write/build-modes/sort.js @@ -0,0 +1,76 @@ +export const description = `Update data files in-place to satisfy custom sorting rules`; + +import {logInfo} from '#cli'; +import {empty} from '#sugar'; +import thingConstructors from '#things'; + +export const config = { + fileSizes: { + applicable: false, + }, + + languageReloading: { + applicable: false, + }, + + mediaValidation: { + applicable: false, + }, + + search: { + applicable: false, + }, + + thumbs: { + applicable: false, + }, + + webRoutes: { + applicable: false, + }, + + sort: { + applicable: false, + }, +}; + +export function getCLIOptions() { + return {}; +} + +export async function go({wikiData, dataPath}) { + if (empty(wikiData.sortingRules)) { + logInfo`There aren't any sorting rules in for this wiki.`; + return true; + } + + const {SortingRule} = thingConstructors; + + let numUpdated = 0; + let numActive = 0; + + for await (const result of SortingRule.go({wikiData, dataPath})) { + numActive++; + + const niceMessage = `"${result.rule.message}"`; + + if (result.changed) { + numUpdated++; + logInfo`Updating to satisfy ${niceMessage}.`; + } else { + logInfo`Already good: ${niceMessage}`; + } + } + + if (numUpdated > 1) { + logInfo`Updated data files to satisfy ${numUpdated} sorting rules.`; + } else if (numUpdated === 1) { + logInfo`Updated data files to satisfy ${1} sorting rule.` + } else if (numActive >= 1) { + logInfo`All sorting rules were already satisfied. Good to go!`; + } else { + logInfo`No sorting rules are currently active.`; + } + + return true; +} diff --git a/src/write/build-modes/static-build.js b/src/write/build-modes/static-build.js new file mode 100644 index 00000000..2baed816 --- /dev/null +++ b/src/write/build-modes/static-build.js @@ -0,0 +1,632 @@ +import * as path from 'node:path'; + +import { + copyFile, + cp, + mkdir, + stat, + symlink, + writeFile, + unlink, +} from 'node:fs/promises'; + +import {rimraf} from 'rimraf'; + +import {quickLoadContentDependencies} from '#content-dependencies'; +import {quickEvaluate} from '#content-function'; +import * as html from '#html'; +import * as pageSpecs from '#page-specs'; +import {empty, queue, withEntries} from '#sugar'; + +import { + fileIssue, + logError, + logInfo, + logWarn, + progressPromiseAll, +} from '#cli'; + +import { + getOrigin, + getPagePathname, + getURLsFrom, + getURLsFromRoot, +} from '#urls'; + +import {bindUtilities} from '../bind-utilities.js'; +import {generateRedirectHTML, generateRandomLinkDataJSON} from '../common-templates.js'; + +const pageFlags = Object.keys(pageSpecs); + +export const description = `Generates all page content in one build (according to the contents of data files at build time) and writes them to disk, preparing the output folder for upload and serving by any static web host\n\nIntended for any production or public-facing release of a wiki; serviceable for local development, but can be a bit unwieldy and time/CPU-expensive`; + +export const config = { + fileSizes: { + default: 'perform', + }, + + languageReloading: { + applicable: false, + }, + + mediaValidation: { + default: 'perform', + }, + + search: { + default: 'perform', + }, + + thumbs: { + default: 'perform', + }, + + webRoutes: { + required: true, + }, +}; + +export function getCLIOptions() { + return { + // This is the output directory. It's the one you'll upload online with + // rsync or whatever when you're pushing an upd8, and also the one + // you'd archive if you wanted to make a 8ackup of the whole dang + // site. Just keep in mind that the gener8ted result will contain a + // couple symlinked directories, so if you're uploading, you're pro8a8ly + // gonna want to resolve those yourself. + 'out-path': { + help: `Specify path to output directory, into which HTML page files and other output are written and other directories are linked\n\nAlways required alongside --static-build mode, but may be provided via the HSMUSIC_OUT environment variable instead`, + type: 'value', + }, + + // Working without a dev server and just using file:// URLs in your we8 + // 8rowser? This will automatically append index.html to links across + // the site. Not recommended for production, since it isn't guaranteed + // 100% error-free (and index.html-style links are less pretty anyway). + 'append-index-html': { + help: `Apply "index.html" to the end of page links, instead of just linking to the directory (ex. "/track/ng2yu/"); useful when no local server hosting option is available and browsing build output directly off the disk drive\n\nDefinitely not intended for production: this option isn't extensively tested and may include conspicuous oddities`, + type: 'flag', + }, + + // Only want to 8uild one language during testing? This can chop down + // 8uild times a pretty 8ig chunk! Just pass a single language code. + 'lang': { + help: `Skip rest and build only pages for this locale language (specify a language code)`, + type: 'value', + }, + + // NOT for neatly ena8ling or disa8ling specific features of the site! + // This is only in charge of what general groups of files to write. + // They're here to make development quicker when you're only working + // on some particular area(s) of the site rather than making changes + // across all of them. + ...withEntries(pageSpecs, entries => entries.map( + ([key, spec]) => [key, { + help: spec.description && + `Skip rest and build only:\n${spec.description}`, + type: 'flag', + }])), + }; +} + +export async function go({ + cliOptions, + queueSize, + + universalUtilities, + + mediaPath, + + defaultLanguage, + languages, + urls, + webRoutes, + wikiData, + + niceShowAggregate, +}) { + const outputPath = cliOptions['out-path'] || process.env.HSMUSIC_OUT; + const appendIndexHTML = cliOptions['append-index-html'] ?? false; + const writeOneLanguage = cliOptions['lang'] ?? null; + + if (!outputPath) { + logError`Expected ${'--out-path'} option or ${'HSMUSIC_OUT'} to be set`; + return false; + } + + if (appendIndexHTML) { + logWarn`Appending index.html to link hrefs. (Note: not recommended for production release!)`; + } + + if (writeOneLanguage && !(writeOneLanguage in languages)) { + logError`Specified to write only ${writeOneLanguage}, but there is no strings file with this language code!`; + return false; + } else if (writeOneLanguage) { + logInfo`Writing only language ${writeOneLanguage} this run.`; + } else { + logInfo`Writing all languages.`; + } + + const selectedPageFlags = Object.keys(cliOptions) + .filter(key => pageFlags.includes(key)); + + const writeAll = empty(selectedPageFlags) || selectedPageFlags.includes('all'); + logInfo`Writing site pages: ${writeAll ? 'all' : selectedPageFlags.join(', ')}`; + + await mkdir(outputPath, {recursive: true}); + + await writeWebRouteSymlinks({ + outputPath, + webRoutes, + }); + + await writeWebRouteCopies({ + outputPath, + webRoutes, + }); + + if (writeAll) { + await writeFavicon({ + mediaPath, + outputPath, + }); + + await writeSharedFilesAndPages({ + outputPath, + randomLinkDataJSON: generateRandomLinkDataJSON({wikiData}), + }); + } else { + logInfo`Skipping favicon and shared files (not writing all site pages).` + } + + const buildSteps = writeAll + ? Object.entries(pageSpecs) + : Object.entries(pageSpecs) + .filter(([flag]) => selectedPageFlags.includes(flag)); + + let writes; + { + let error = false; + + // TODO: Port this to aggregate error + writes = buildSteps + .map(([flag, pageSpec]) => { + if (pageSpec.condition && !pageSpec.condition({wikiData})) { + return null; + } + + let paths = []; + + if (pageSpec.pathsTargetless) { + const result = pageSpec.pathsTargetless({wikiData}); + if (Array.isArray(result)) { + paths.push(...result); + } else { + paths.push(result); + } + } + + if (pageSpec.targets) { + if (!pageSpec.pathsForTarget) { + logError`${flag + '.targets'} is specified, but ${flag + '.pathsForTarget'} is missing!`; + error = true; + return null; + } + + const targets = pageSpec.targets({wikiData}); + + if (!Array.isArray(targets)) { + logError`${flag + '.targets'} was called, but it didn't return an array! (${targets})`; + error = true; + return null; + } + + paths.push(...targets.flatMap(target => pageSpec.pathsForTarget(target))); + // TODO: Validate each pathsForTargets entry + } + + paths = + paths.filter(path => path.condition?.() ?? true); + + return paths; + }) + .filter(Boolean) + .flat(); + + if (error) { + return false; + } + } + + const pageWrites = writes.filter(({type}) => type === 'page'); + const dataWrites = writes.filter(({type}) => type === 'data'); + const redirectWrites = writes.filter(({type}) => type === 'redirect'); + + if (writes.length) { + logInfo`Total of ${writes.length} writes returned. (${pageWrites.length} page, ${dataWrites.length} data [currently skipped], ${redirectWrites.length} redirect)`; + } else { + logWarn`No writes returned at all, so exiting early. This is probably a bug!`; + return false; + } + + /* + await progressPromiseAll(`Writing data files shared across languages.`, queue( + dataWrites.map(({path, data}) => () => { + const bound = {}; + + bound.serializeLink = bindOpts(serializeLink, {}); + + bound.serializeContribs = bindOpts(serializeContribs, {}); + + bound.serializeImagePaths = bindOpts(serializeImagePaths, { + thumb + }); + + bound.serializeCover = bindOpts(serializeCover, { + [bindOpts.bindIndex]: 2, + serializeImagePaths: bound.serializeImagePaths, + urls + }); + + bound.serializeGroupsForAlbum = bindOpts(serializeGroupsForAlbum, { + serializeLink + }); + + bound.serializeGroupsForTrack = bindOpts(serializeGroupsForTrack, { + serializeLink + }); + + // TODO: This only supports one <>-style argument. + return writeData(path[0], path[1], data({...bound})); + }), + queueSize + )); + */ + + let errored = false; + + const contentDependencies = await quickLoadContentDependencies({ + showAggregate: niceShowAggregate, + }); + + const commonUtilities = {...universalUtilities}; + + const perLanguageFn = async (language, i, entries) => { + const baseDirectory = + language === defaultLanguage ? '' : language.code; + + console.log(`\x1b[34;1m${`[${i + 1}/${entries.length}] ${language.code} (-> /${baseDirectory}) `.padEnd(60, '-')}\x1b[0m`); + + await progressPromiseAll(`Writing ${language.code}`, queue([ + ...pageWrites.map(page => () => { + const pagePath = page.path; + + const pathname = getPagePathname({ + baseDirectory, + pagePath, + urls, + }); + + const to = getURLsFrom({ + baseDirectory, + pagePath, + urls, + }); + + const absoluteTo = getURLsFromRoot({ + baseDirectory, + urls, + }); + + const bound = bindUtilities({ + ...commonUtilities, + + absoluteTo, + language, + pagePath, + pagePathStringFromRoot: pathname, + to: page.absoluteLinks ? absoluteTo : to, + }); + + let pageHTML, oEmbedJSON; + try { + const topLevelResult = + quickEvaluate({ + contentDependencies, + extraDependencies: {...bound, appendIndexHTML}, + + name: page.contentFunction.name, + args: page.contentFunction.args ?? [], + }); + + ({pageHTML, oEmbedJSON} = html.resolve(topLevelResult)); + } catch (error) { + logError`\rError generating page: ${pathname}`; + niceShowAggregate(error); + errored = true; + return; + } + + return writePage({ + pageHTML, + oEmbedJSON, + outputDirectory: path.join(outputPath, getPagePathname({ + baseDirectory, + device: true, + pagePath, + urls, + })), + }); + }), + + ...redirectWrites.map(({fromPath, toPath, title, getTitle}) => () => { + title ??= getTitle?.({language}); + + const to = getURLsFrom({ + baseDirectory, + pagePath: fromPath, + urls, + }); + + const target = to('localized.' + toPath[0], ...toPath.slice(1)); + const pageHTML = generateRedirectHTML(title, target, {language}); + + return writePage({ + pageHTML, + outputDirectory: path.join(outputPath, getPagePathname({ + baseDirectory, + device: true, + pagePath: fromPath, + urls, + })), + }); + }), + ], queueSize)); + }; + + await wrapLanguages(perLanguageFn, { + languages, + writeOneLanguage, + }); + + // The single most important step. + logInfo`Written!`; + + if (errored) { + logWarn`The code generating content for some pages ended up erroring.`; + logWarn`These pages were skipped, so if you ran a build previously and`; + logWarn`they didn't error that time, then the old version is still`; + logWarn`available - albeit possibly outdated! Please scroll up and send`; + logWarn`the HSMusic developers a copy of the errors:`; + fileIssue({topMessage: null}); + + return false; + } + + return true; +} + +// Wrapper function for running a function once for all languages. +async function wrapLanguages(fn, { + languages, + writeOneLanguage = null, +}) { + const k = writeOneLanguage; + const languagesToRun = k ? {[k]: languages[k]} : languages; + + const entries = Object.entries(languagesToRun).filter( + ([key]) => key !== 'default' + ); + + for (let i = 0; i < entries.length; i++) { + const [_key, language] = entries[i]; + + await fn(language, i, entries); + } +} + +async function writePage({ + pageHTML, + oEmbedJSON = '', + outputDirectory, +}) { + await mkdir(outputDirectory, {recursive: true}); + + await Promise.all([ + writeFile(path.join(outputDirectory, 'index.html'), pageHTML), + + oEmbedJSON && + writeFile(path.join(outputDirectory, 'oembed.json'), oEmbedJSON), + ].filter(Boolean)); +} + +function filterNoOrigin(route) { + return !getOrigin(route.to); +} + +function writeWebRouteSymlinks({ + outputPath, + webRoutes, +}) { + const symlinkRoutes = + webRoutes + .filter(route => route.statically === 'symlink') + .filter(filterNoOrigin); + + const promises = + symlinkRoutes.map(async route => { + const parts = route.to.split('/'); + const parentDirectoryParts = parts.slice(0, -1); + const symlinkNamePart = parts.at(-1); + + const parentDirectory = path.join(outputPath, ...parentDirectoryParts); + const symlinkPath = path.join(parentDirectory, symlinkNamePart); + + try { + await unlink(symlinkPath); + } catch (error) { + if (error.code !== 'ENOENT') { + throw error; + } + } + + await mkdir(parentDirectory, {recursive: true}); + + try { + await symlink(route.from, symlinkPath); + } catch (error) { + if (error.code === 'EPERM') { + await symlink(route.from, symlinkPath, 'junction'); + } else { + throw error; + } + } + }); + + return progressPromiseAll(`Writing web route symlinks.`, promises); +} + +async function writeWebRouteCopies({ + outputPath, + webRoutes, +}) { + const copyRoutes = + webRoutes + .filter(route => route.statically === 'copy') + .filter(filterNoOrigin); + + const promises = + copyRoutes.map(async route => { + const permissionName = '__hsmusic-ok-for-deletion.txt'; + + const parts = route.to.split('/'); + const parentDirectoryParts = parts.slice(0, -1); + const copyNamePart = parts.at(-1); + + const parentDirectory = path.join(outputPath, ...parentDirectoryParts); + const copyPath = path.join(parentDirectory, copyNamePart); + + // We're going to do a rimraf call! This is freaking terrifying, + // so nope out on a couple important conditions. + + let needsDelete; + try { + await stat(copyPath); + needsDelete = true; + } catch (error) { + if (error.code === 'ENOENT') { + needsDelete = false; + } else { + throw error; + } + } + + if (needsDelete) { + // First remove it directly, in case it's a symlink. + try { + await unlink(copyPath); + needsDelete = false; + } catch (error) { + // EPERM is POSIX, but libuv may or may not flat-out just raise + // the system error (which is ostensibly EISDIR on Linux). + // https://github.com/nodejs/node-v0.x-archive/issues/5791 + // https://man7.org/linux/man-pages/man2/unlink.2.html + // + // Both of these indidcate "a directory, probably" and we'll + // still check for the deletion permission file where we expect + // it before actually touching anything. + if (error.code !== 'EPERM' && error.code !== 'EISDIR') { + throw error; + } + } + } + + if (needsDelete) { + // Then check that the deletion permission file exists + // where we expect it. + try { + await stat(path.join(copyPath, permissionName)); + } catch (error) { + if (error.code === 'ENOENT') { + throw new Error(`Couldn't find ${permissionName} in ${copyPath} - please delete or move away this folder manually`); + } else { + throw error; + } + } + + // And *then* actually delete that directory. + await rimraf(copyPath); + } + + // Actually copy the source path where it's wanted. + await cp(route.from, copyPath, {recursive: true}); + + // And certify that it's OK to delete this path, next time around. + await writeFile(path.join(copyPath, permissionName), + `The presence of this file (by its name, not its contents)\n` + + `indicates hsmusic may delete everything contained in this\n` + + `directory (the one which directly contains this file, *not*\n` + + `any further-up parent directories).\n` + + `\n` + + `If you make edits, or add any files, they will be deleted or\n` + + `overwritten the next time you run the build.\n` + + `\n` + + `If you delete *this* file, hsmusic will error during the next\n` + + `build, and will ask that you delete the containing directory\n` + + `yourself.\n`); + }); + + const results = + await Promise.allSettled(promises); + + const errors = + results + .filter(({status}) => status === 'rejected') + .map(({reason}) => reason) + .map(err => + (err.message.startsWith(`Couldn't find`) + ? err.message + : err)); + + if (empty(errors)) { + logInfo`Wrote web route copies.`; + } else { + throw new AggregateError(errors, `Errors copying internal files ("web routes")`); + } +} + +async function writeFavicon({ + mediaPath, + outputPath, +}) { + const faviconFile = 'favicon.ico'; + + try { + await stat(path.join(mediaPath, faviconFile)); + } catch (error) { + return; + } + + try { + await copyFile( + path.join(mediaPath, faviconFile), + path.join(outputPath, faviconFile)); + } catch (error) { + logWarn`Failed to copy favicon! ${error.message}`; + return; + } + + logInfo`Copied favicon to site root.`; +} + +async function writeSharedFilesAndPages({ + outputPath, + randomLinkDataJSON, +}) { + return progressPromiseAll(`Writing files & pages shared across languages.`, [ + randomLinkDataJSON && + writeFile( + path.join(outputPath, 'random-link-data.json'), + randomLinkDataJSON), + ].filter(Boolean)); +} |