@johnhenry/sitefile 0.0.3 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -0
- package/README.md +4 -3
- package/lib/src/bake.d.ts +2 -0
- package/lib/src/bake.js +30 -1
- package/lib/src/bcrypt.d.ts +25 -0
- package/lib/src/bcrypt.js +201 -0
- package/lib/src/canonical.d.ts +6 -3
- package/lib/src/canonical.js +25 -11
- package/lib/src/cli/index.d.ts +4 -1
- package/lib/src/cli/index.js +5 -2
- package/lib/src/cli/serve-worker.js +76 -3
- package/lib/src/cli/servers.d.ts +7 -1
- package/lib/src/cli/servers.js +56 -17
- package/lib/src/executor.js +42 -5
- package/lib/src/hreflang.d.ts +25 -0
- package/lib/src/hreflang.js +72 -0
- package/lib/src/language/ast.d.ts +11 -1
- package/lib/src/language/parser.js +13 -0
- package/lib/src/language/validate.js +3 -0
- package/lib/src/links.d.ts +14 -0
- package/lib/src/links.js +22 -4
- package/lib/src/planner.d.ts +18 -0
- package/lib/src/planner.js +39 -0
- package/lib/src/reload-client.js +116 -1
- package/lib/src/resources/archive.d.ts +1 -1
- package/lib/src/resources/archive.js +24 -13
- package/lib/src/serve-auth.d.ts +3 -2
- package/lib/src/serve-auth.js +14 -6
- package/lib/src/server.d.ts +92 -1
- package/lib/src/server.js +205 -7
- package/lib/src/servers.d.ts +6 -0
- package/lib/src/site.d.ts +6 -2
- package/lib/src/site.js +21 -8
- package/package.json +1 -1
package/lib/src/cli/servers.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type CachePreview, type HostProfileName, type HtmlHandling } from '../server.js';
|
|
1
|
+
import { type CachePreview, type HostProfileName, type HtmlHandling, type SyncMode } from '../server.js';
|
|
2
2
|
import { ServerRegistry, type ServerState } from '../servers.js';
|
|
3
3
|
import { type AuthEntry } from '../serve-auth.js';
|
|
4
4
|
import type { Plan } from '../planner.js';
|
|
@@ -108,6 +108,12 @@ export interface DetachedServe {
|
|
|
108
108
|
readonly country?: string | undefined;
|
|
109
109
|
/** `--strict-site-files`. */
|
|
110
110
|
readonly strictSiteFiles?: boolean | undefined;
|
|
111
|
+
/** `-d --watch`: a directory source re-read on change, with live reload. */
|
|
112
|
+
readonly watch?: boolean | undefined;
|
|
113
|
+
/** `--poll`, `--poll-interval` with `-d --watch`. */
|
|
114
|
+
readonly pollMs?: number | undefined;
|
|
115
|
+
/** `--sync` with `-d --watch`. */
|
|
116
|
+
readonly sync?: SyncMode | undefined;
|
|
111
117
|
/** The servers file it belongs to (`sitefile up`). */
|
|
112
118
|
readonly project?: string | undefined;
|
|
113
119
|
}
|
package/lib/src/cli/servers.js
CHANGED
|
@@ -189,8 +189,8 @@ async function startDetached(reg, state) {
|
|
|
189
189
|
const run = {
|
|
190
190
|
name: 'serve',
|
|
191
191
|
summary: 'serve an image, directory or archive file over HTTP',
|
|
192
|
-
usage: 'serve [--name n] [-p [host:]port] [-d] [--spa] <ref|id|./dir|file> | serve --watch [options] [context]',
|
|
193
|
-
description: 'Serve an image from the local store, a directory (paths starting with ./, ../ or /), or an archive file over HTTP:\nzip, tar, tar.gz, wbn, or an OCI archive as build -o x.oci.tar and save write it (the format is read from the\nbytes). A directory or archive is a snapshot read at start. GET and HEAD only; no directory listings.\nBinds 127.0.0.1 on a free port unless -p is given;\n0.0.0.0 is bound only when you pass it explicitly. Foreground by default (Ctrl-C stops it); -d detaches and\nrecords the server for servers, server stop, rm, logs and restart.\n\nWith --watch the argument is a build context (default .): its Sitefile is built in memory and served, rebuilt\nwhen the context, the Sitefile or a --build-arg-file changes, and open pages reload after each good rebuild\n(page loads get a small script, /__sitefile/reload.js). A failed rebuild keeps serving the last\ngood build. Nothing is written to the context except Sitefile.lock. A directory with no Sitefile (and no -f,\n--target or --build-arg*) is served as it is and re-read on change. When only stylesheets changed, pages\nswap them in place.',
|
|
192
|
+
usage: 'serve [--name n] [-p [host:]port] [-d] [--spa] <ref|id|./dir|file> | serve [-d] --watch [options] [context]',
|
|
193
|
+
description: 'Serve an image from the local store, a directory (paths starting with ./, ../ or /), or an archive file over HTTP:\nzip, tar, tar.gz, wbn, or an OCI archive as build -o x.oci.tar and save write it (the format is read from the\nbytes). A directory or archive is a snapshot read at start. GET and HEAD only; no directory listings.\nBinds 127.0.0.1 on a free port unless -p is given;\n0.0.0.0 is bound only when you pass it explicitly. Foreground by default (Ctrl-C stops it); -d detaches and\nrecords the server for servers, server stop, rm, logs and restart.\n\nWith --watch the argument is a build context (default .): its Sitefile is built in memory and served, rebuilt\nwhen the context, the Sitefile or a --build-arg-file changes, and open pages reload after each good rebuild\n(page loads get a small script, /__sitefile/reload.js). A failed rebuild keeps serving the last\ngood build. Nothing is written to the context except Sitefile.lock. A directory with no Sitefile (and no -f,\n--target or --build-arg*) is served as it is and re-read on change. When only stylesheets changed, pages\nswap them in place. With -d, --watch takes such a directory only: the detached server re-reads it on change,\nopen pages reload, and pages left open across server restart reload once it is back.',
|
|
194
194
|
flags: [
|
|
195
195
|
'--name <n> name for the server (-d only; default site-<6 hex>)',
|
|
196
196
|
'-p, --publish <[host:]port> address to bind (default 127.0.0.1, a free port)',
|
|
@@ -206,7 +206,7 @@ const run = {
|
|
|
206
206
|
'--log-ip add the client address to access-log lines',
|
|
207
207
|
'--quiet no access-log lines',
|
|
208
208
|
'--auth <user:password> require HTTP basic authentication (repeatable; or SITEFILE_SERVE_AUTH); only a hash is stored',
|
|
209
|
-
'--auth-file <htpasswd> users from an htpasswd file ({SHA}
|
|
209
|
+
'--auth-file <htpasswd> users from an htpasswd file ({SHA} or bcrypt: htpasswd -s or -B)',
|
|
210
210
|
'--max-connections-per-ip <n> open connections one non-loopback client may hold (default 0: no limit; 503 over it)',
|
|
211
211
|
'--random-route serve the site only under a random secret path (printed in the URL)',
|
|
212
212
|
'--allow-ip <cidr> only answer clients in this block (repeatable; loopback is always allowed)',
|
|
@@ -239,7 +239,7 @@ const run = {
|
|
|
239
239
|
'--keep-os-metadata serve __MACOSX, ._*, Thumbs.db and desktop.ini of a directory or archive (default: skipped)',
|
|
240
240
|
'--open[=<path>] open the site (at <path>) in the browser once it is served ($BROWSER, else the system default)',
|
|
241
241
|
'--qr print a QR code of the network URL (with -p 0.0.0.0:...), else of the local URL',
|
|
242
|
-
'--watch build the context, serve it, rebuild on change and live-reload pages (
|
|
242
|
+
'--watch build the context, serve it, rebuild on change and live-reload pages (-d: a plain directory only)',
|
|
243
243
|
'-f, --file <path> Sitefile path (--watch; default <context>/Sitefile)',
|
|
244
244
|
'--target <stage> build up to this stage and serve its whole tree (--watch)',
|
|
245
245
|
'--build-arg <NAME=value> set an ARG (--watch; repeatable)',
|
|
@@ -247,13 +247,14 @@ const run = {
|
|
|
247
247
|
'--no-cache do not use the TRANSFORM result cache (--watch)',
|
|
248
248
|
'--no-lockfile do not read or write Sitefile.lock (--watch)',
|
|
249
249
|
'--keep-service-workers do not unregister service workers and clear caches before a reload (--watch)',
|
|
250
|
-
'--poll poll for changes (every 1000 ms) instead of file system events (--watch)',
|
|
251
|
-
'--poll-interval <ms> poll every <ms> milliseconds (--watch; implies --poll)',
|
|
250
|
+
'--poll poll for changes (every 1000 ms) instead of file system events (--watch, -d --watch)',
|
|
251
|
+
'--poll-interval <ms> poll every <ms> milliseconds (--watch, -d --watch; implies --poll)',
|
|
252
252
|
'--no-css-inject reload the page when only stylesheets changed, instead of swapping them (--watch)',
|
|
253
253
|
'--console also forward console.log/info from pages to the log, not only errors and warnings (--watch)',
|
|
254
254
|
'--no-overlay no Rebuilding badge or build-error overlay in pages (--watch)',
|
|
255
255
|
'--navigate-to-changed after a rebuild that changed one page, open pages go to it (--watch)',
|
|
256
256
|
'--reload <full|morph> morph (default): update a page in place when only HTML changed; full: always reload (--watch)',
|
|
257
|
+
'--sync[=scroll] open pages report where they are and follow each other\'s navigation (=scroll: and scrolling) (--watch, -d --watch)',
|
|
257
258
|
],
|
|
258
259
|
options: {
|
|
259
260
|
name: { type: 'string' },
|
|
@@ -317,14 +318,24 @@ const run = {
|
|
|
317
318
|
'no-overlay': { type: 'boolean' },
|
|
318
319
|
'navigate-to-changed': { type: 'boolean' },
|
|
319
320
|
reload: { type: 'string' },
|
|
321
|
+
sync: { type: 'string' },
|
|
320
322
|
},
|
|
321
323
|
async run(v, pos) {
|
|
322
|
-
if (v.watch)
|
|
324
|
+
if (v.watch && !v.detach)
|
|
323
325
|
return serveWatch(v, pos);
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
326
|
+
// `-d --watch`: a plain directory, re-read on change by the detached worker (with live reload).
|
|
327
|
+
const watchDetached = !!v.watch;
|
|
328
|
+
for (const f of WATCH_ONLY) {
|
|
329
|
+
if (v[f] === undefined || (watchDetached && DETACHED_WATCH.includes(f)))
|
|
330
|
+
continue;
|
|
331
|
+
usage(watchDetached ? `--${f} is for serve --watch in the foreground, not -d` : `--${f} needs --watch`);
|
|
332
|
+
}
|
|
333
|
+
if (watchDetached)
|
|
334
|
+
requireArgs(pos, 0, 1, 'a directory');
|
|
335
|
+
else
|
|
336
|
+
requireArgs(pos, 1, 1, 'an image reference, ./directory or archive file');
|
|
337
|
+
const pollMs = watchDetached ? pollOption(!!v.poll, str(v['poll-interval'])) : undefined;
|
|
338
|
+
const sync = watchDetached ? syncOf(v) : undefined;
|
|
328
339
|
const bind = parsePublish(str(v.publish));
|
|
329
340
|
const allowedHosts = allowedHostsOf(v);
|
|
330
341
|
const isolate = isolateOf(v);
|
|
@@ -347,7 +358,7 @@ const run = {
|
|
|
347
358
|
if (name !== undefined && !v.detach)
|
|
348
359
|
usage('--name needs -d (only detached servers are tracked)');
|
|
349
360
|
const store = await Store.open();
|
|
350
|
-
const { label, source } = await resolveSource(store, pos[0]);
|
|
361
|
+
const { label, source } = watchDetached ? await watchedDirectory(pos[0] ?? '.') : await resolveSource(store, pos[0]);
|
|
351
362
|
if (isWildcard(bind.host))
|
|
352
363
|
process.stderr.write(`warning: binding ${bind.host}: the site will be reachable from other machines\n`);
|
|
353
364
|
const keepOsMetadata = !!v['keep-os-metadata'];
|
|
@@ -393,7 +404,7 @@ const run = {
|
|
|
393
404
|
for (const f of PROXY_FLAGS)
|
|
394
405
|
if (v[f] !== undefined)
|
|
395
406
|
usage(`--${f} is for a server in the foreground (or --watch), not -d`);
|
|
396
|
-
const up = await serveDetached(reg, { label, source, name, bind, keepOsMetadata, allowedHosts, cors: !!v.cors, ...(isolate ? { isolate } : {}), ...(cache ? { cache } : {}), ...logging, ...auth.record, ...perIp, ...sharing.record, ...tls.record, ...(v.compress ? { compress: true } : {}), ...(throttle ? { throttle: throttle.spec } : {}), ...(mime ? { mime: Object.fromEntries(mime) } : {}), country, strictSiteFiles, ...spa, base, rewriteBase, ...profiles }, warn);
|
|
407
|
+
const up = await serveDetached(reg, { label, source, name, bind, keepOsMetadata, allowedHosts, cors: !!v.cors, ...(isolate ? { isolate } : {}), ...(cache ? { cache } : {}), ...logging, ...auth.record, ...perIp, ...sharing.record, ...tls.record, ...(v.compress ? { compress: true } : {}), ...(throttle ? { throttle: throttle.spec } : {}), ...(mime ? { mime: Object.fromEntries(mime) } : {}), country, strictSiteFiles, ...spa, base, rewriteBase, ...profiles, ...(watchDetached ? { watch: true, pollMs, sync } : {}) }, warn);
|
|
397
408
|
process.stdout.write(`Started ${up.name} (${up.id}) serving ${label} at ${siteUrl(up.host, up.port, up.base, up.tlsCert ? 'https' : 'http')}\n${networkLines(up.host, up.port, up.base, up.tlsCert ? 'https' : 'http')}${throttleLine(up.throttle)}`);
|
|
398
409
|
return 0;
|
|
399
410
|
},
|
|
@@ -446,6 +457,9 @@ export async function serveDetached(reg, d, warn) {
|
|
|
446
457
|
...(d.mime !== undefined ? { mime: d.mime } : {}),
|
|
447
458
|
...(d.country !== undefined ? { country: d.country } : {}),
|
|
448
459
|
...(d.strictSiteFiles ? { strictSiteFiles: true } : {}),
|
|
460
|
+
...(d.watch ? { watch: true } : {}),
|
|
461
|
+
...(d.watch && d.pollMs !== undefined ? { pollMs: d.pollMs } : {}),
|
|
462
|
+
...(d.watch && d.sync !== undefined ? { sync: d.sync } : {}),
|
|
449
463
|
bind: d.bind,
|
|
450
464
|
host: d.bind.host,
|
|
451
465
|
port: d.bind.port,
|
|
@@ -513,8 +527,34 @@ async function terminal(v, addr, base, scheme, warn, restart) {
|
|
|
513
527
|
process.stdout.write(KEYS_HINT);
|
|
514
528
|
return { promise, stop: stop ?? (() => undefined) };
|
|
515
529
|
}
|
|
530
|
+
/** The --watch flags `serve -d --watch` takes (it watches a plain directory; the rest are for builds or the page script). */
|
|
531
|
+
const DETACHED_WATCH = ['poll', 'poll-interval', 'sync'];
|
|
532
|
+
/**
|
|
533
|
+
* `serve -d --watch [dir]`: the directory (default .) as a source, absolute and real. A Sitefile project
|
|
534
|
+
* is refused: building on change happens in the foreground (`serve --watch`).
|
|
535
|
+
*/
|
|
536
|
+
async function watchedDirectory(arg) {
|
|
537
|
+
const dir = path.resolve(arg);
|
|
538
|
+
const st = await fs.stat(dir).catch(() => undefined);
|
|
539
|
+
if (!st?.isDirectory())
|
|
540
|
+
throw new SitefileError('E_NOT_FOUND', `'${arg}' is not a directory`);
|
|
541
|
+
if (await isFile(path.join(dir, 'Sitefile')))
|
|
542
|
+
usage(`-d --watch serves a plain directory, and ${arg} has a Sitefile: build it with serve --watch in the foreground`);
|
|
543
|
+
return { label: dir, source: { kind: 'dir', path: await fs.realpath(dir) } };
|
|
544
|
+
}
|
|
516
545
|
/** serve flags that only mean something with --watch. */
|
|
517
|
-
const WATCH_ONLY = ['file', 'target', 'build-arg', 'build-arg-file', 'no-cache', 'no-lockfile', 'keep-service-workers', 'poll', 'poll-interval', 'no-css-inject', 'console', 'no-overlay', 'navigate-to-changed', 'reload', 'no-rewrite-base'];
|
|
546
|
+
const WATCH_ONLY = ['file', 'target', 'build-arg', 'build-arg-file', 'no-cache', 'no-lockfile', 'keep-service-workers', 'poll', 'poll-interval', 'no-css-inject', 'console', 'no-overlay', 'navigate-to-changed', 'reload', 'no-rewrite-base', 'sync'];
|
|
547
|
+
/** `--sync` (a bare `--sync` arrives as `--sync=`): `nav`, or `scroll` for `--sync=scroll`; undefined without it. */
|
|
548
|
+
function syncOf(v) {
|
|
549
|
+
const s = str(v.sync);
|
|
550
|
+
if (s === undefined)
|
|
551
|
+
return undefined;
|
|
552
|
+
if (s === '')
|
|
553
|
+
return 'nav';
|
|
554
|
+
if (s === 'scroll')
|
|
555
|
+
return 'scroll';
|
|
556
|
+
return usage(`--sync takes no value or =scroll, got '${s}'`);
|
|
557
|
+
}
|
|
518
558
|
/**
|
|
519
559
|
* `serve --watch [context]`: build in memory, serve, rebuild on change, live reload. A directory
|
|
520
560
|
* without a `Sitefile`, given none of -f, --target, --build-arg and --build-arg-file, is served
|
|
@@ -738,8 +778,6 @@ function logWriter(logging) {
|
|
|
738
778
|
}
|
|
739
779
|
async function serveWatch(v, pos) {
|
|
740
780
|
requireArgs(pos, 0, 1, 'a build context directory');
|
|
741
|
-
if (v.detach)
|
|
742
|
-
usage('--watch cannot be combined with -d');
|
|
743
781
|
if (v.name !== undefined)
|
|
744
782
|
usage('--name needs -d (only detached servers are tracked)');
|
|
745
783
|
const bind = parsePublish(str(v.publish));
|
|
@@ -766,6 +804,7 @@ async function serveWatch(v, pos) {
|
|
|
766
804
|
const cssInject = !v['no-css-inject'];
|
|
767
805
|
const navigate = !!v['navigate-to-changed'];
|
|
768
806
|
const reloadMode = str(v.reload) ?? 'morph';
|
|
807
|
+
const sync = syncOf(v);
|
|
769
808
|
const spa = spaOptions(v);
|
|
770
809
|
const baseFlag = sharing.randomBase ?? parseBase(str(v.base));
|
|
771
810
|
/** `--base`, else the path of the last good build's EXPORT BASE URL. */
|
|
@@ -801,7 +840,7 @@ async function serveWatch(v, pos) {
|
|
|
801
840
|
let builtAt; // Last-Modified: the time of the build being served
|
|
802
841
|
let started = false;
|
|
803
842
|
const memo = watchMemo();
|
|
804
|
-
const live = new LiveReload({ resetServiceWorkers: !v['keep-service-workers'], cssInject, console: !!v.console, overlay: !v['no-overlay'], navigateToChanged: navigate, reload: reloadMode });
|
|
843
|
+
const live = new LiveReload({ resetServiceWorkers: !v['keep-service-workers'], cssInject, console: !!v.console, overlay: !v['no-overlay'], navigateToChanged: navigate, reload: reloadMode, ...(sync ? { sync } : {}) });
|
|
805
844
|
/** Serve `next` and tell open pages what changed. */
|
|
806
845
|
const swap = (next) => {
|
|
807
846
|
const event = started ? (reloadEventFor(current, next, cssInject, navigate) ?? OK_EVENT) : undefined;
|
package/lib/src/executor.js
CHANGED
|
@@ -44,12 +44,13 @@ import { groupBy, paginate } from './pages.js';
|
|
|
44
44
|
import { parseYaml } from './yaml.js';
|
|
45
45
|
import { brokenLinks, reportBrokenLinks } from './checklinks.js';
|
|
46
46
|
import { canonical } from './canonical.js';
|
|
47
|
+
import { alternates, isLanguageTag } from './hreflang.js';
|
|
47
48
|
import { composeRenames, fingerprint } from './fingerprint.js';
|
|
48
49
|
import { exportForHost } from './export-for.js';
|
|
49
50
|
import { portabilityProblems } from './portable.js';
|
|
50
51
|
import { precache } from './precache.js';
|
|
51
52
|
import { precompress } from './precompress.js';
|
|
52
|
-
import { atomXml, cacheHeaderRules, headersFile, pageUrl, parseFeedDate, redirectsFile, sitemapFiles } from './site.js';
|
|
53
|
+
import { atomXml, cacheHeaderRules, headersFile, pageUrl, parseFeedDate, redirectsFile, sitemapFiles, sitemapPages, SITEMAP_LIMITS } from './site.js';
|
|
53
54
|
import { cspPages } from './csp.js';
|
|
54
55
|
/** Read, parse and validate a Sitefile. */
|
|
55
56
|
export async function loadProgram(options) {
|
|
@@ -1352,8 +1353,11 @@ async function executeOp(op, tree, prevKey, env) {
|
|
|
1352
1353
|
}
|
|
1353
1354
|
const opId = memoKey('op', env.envKey, valueKey(op));
|
|
1354
1355
|
if (op.kind === 'SITEMAP' || op.kind === 'FINGERPRINT' || op.kind === 'CANONICAL' || op.kind === 'PRECOMPRESS' || op.kind === 'PRECACHE' || op.kind === 'CHECKLINKS') {
|
|
1355
|
-
// Reads the whole tree: only the chain key can say it is unchanged.
|
|
1356
|
-
const
|
|
1356
|
+
// Reads the whole tree: only the chain key can say it is unchanged. With LANGUAGES, also the documents' lists.
|
|
1357
|
+
const langs = (op.kind === 'CANONICAL' || op.kind === 'SITEMAP') && op.languages ? op.languages : undefined;
|
|
1358
|
+
const key = langs
|
|
1359
|
+
? memoKey('chain', prevKey, opId, namesKey(env, operandNames(langs.sources.map((src) => src.dest), new Set(langs.sources.map((src) => src.list)))))
|
|
1360
|
+
: memoKey('chain', prevKey, opId);
|
|
1357
1361
|
if (op.kind === 'CHECKLINKS') {
|
|
1358
1362
|
// The tree is unchanged; a hit skips the check (and its requests) and prints its warnings again.
|
|
1359
1363
|
const hit = memo.get(key);
|
|
@@ -1437,7 +1441,37 @@ function fingerprintOp(op, tree, env) {
|
|
|
1437
1441
|
return fingerprint(tree, op, `${env.label}:${op.span.line} FINGERPRINT`, env.warn);
|
|
1438
1442
|
}
|
|
1439
1443
|
function canonicalOp(op, tree, env) {
|
|
1440
|
-
return canonical(tree, op, `${env.label}:${op.span.line} CANONICAL`, env.warn);
|
|
1444
|
+
return canonical(tree, op, `${env.label}:${op.span.line} CANONICAL`, env.warn, op.languages ? languagesOf(op.languages, 'CANONICAL', op.span, env) : undefined);
|
|
1445
|
+
}
|
|
1446
|
+
/**
|
|
1447
|
+
* LANGUAGES with the translations of the documents of the stage's earlier `RENDER … FOR` lines: an element with
|
|
1448
|
+
* a `translationKey` (text or a number) and a `lang` (text) gives the page its destination names. A `lang` that is
|
|
1449
|
+
* not a language code is `E_VALIDATION`.
|
|
1450
|
+
*/
|
|
1451
|
+
function languagesOf(spec, what, span, env) {
|
|
1452
|
+
const docs = new Map();
|
|
1453
|
+
for (const src of spec.sources) {
|
|
1454
|
+
const items = valueOf(src.list, [], span, false, env);
|
|
1455
|
+
if (!Array.isArray(items))
|
|
1456
|
+
continue;
|
|
1457
|
+
items.forEach((item, i) => {
|
|
1458
|
+
if (item === null || typeof item !== 'object' || Array.isArray(item))
|
|
1459
|
+
return;
|
|
1460
|
+
const doc = item;
|
|
1461
|
+
const key = doc['translationKey'];
|
|
1462
|
+
const lang = doc['lang'];
|
|
1463
|
+
if ((typeof key !== 'string' && typeof key !== 'number') || typeof lang !== 'string')
|
|
1464
|
+
return;
|
|
1465
|
+
if (!isLanguageTag(lang)) {
|
|
1466
|
+
const name = typeof doc['path'] === 'string' ? doc['path'] : `#${i + 1}`;
|
|
1467
|
+
throw new SitefileError('E_VALIDATION', `${what}: document '${name}' of '${src.list}' has lang '${lang}', which is not a language code (a BCP 47 tag such as en, fr or pt-BR)`, span);
|
|
1468
|
+
}
|
|
1469
|
+
const target = normalizeVirtual(interpolate(src.dest, { ...env, loop: { name: src.as, value: item } }), src.dest.span, `RENDER destination for ${src.as}`);
|
|
1470
|
+
if (!target.trailingSlash)
|
|
1471
|
+
docs.set(target.path, { lang, key: String(key) });
|
|
1472
|
+
});
|
|
1473
|
+
}
|
|
1474
|
+
return { codes: spec.codes, ...(spec.default !== undefined ? { default: spec.default } : {}), docs };
|
|
1441
1475
|
}
|
|
1442
1476
|
function precompressOp(op, tree, env) {
|
|
1443
1477
|
return precompress(tree, op, `${env.label}:${op.span.line} PRECOMPRESS`, env.warn);
|
|
@@ -1447,7 +1481,10 @@ function precacheOp(op, tree, env) {
|
|
|
1447
1481
|
}
|
|
1448
1482
|
function sitemap(op, tree, env) {
|
|
1449
1483
|
const origin = `${env.label}:${op.span.line} SITEMAP`;
|
|
1450
|
-
const
|
|
1484
|
+
const alts = op.languages
|
|
1485
|
+
? alternates(sitemapPages(tree).map((p) => [p, p]), languagesOf(op.languages, 'SITEMAP', op.span, env), 'SITEMAP', op.span)
|
|
1486
|
+
: undefined;
|
|
1487
|
+
const files = sitemapFiles(tree, op.base, op.dest, SITEMAP_LIMITS, alts).map(([p, xml]) => [p, makeFile(new TextEncoder().encode(xml), origin)]);
|
|
1451
1488
|
return tree.withFiles(files, op.overwrite ? 'overwrite' : 'error', op.span);
|
|
1452
1489
|
}
|
|
1453
1490
|
/** Check a plugin file (sandbox, own folder, integrity) and start its process. */
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type SourceSpan } from './errors.js';
|
|
2
|
+
/** A basic BCP 47 check: a 2-3 letter language, then `-` subtags of 1-8 letters or digits (`en`, `pt-BR`, `zh-Hant-TW`). */
|
|
3
|
+
export declare function isLanguageTag(s: string): boolean;
|
|
4
|
+
/** What a document's frontmatter says about the page it renders: `lang` and `translationKey`. */
|
|
5
|
+
export interface Translation {
|
|
6
|
+
readonly lang: string;
|
|
7
|
+
readonly key: string;
|
|
8
|
+
}
|
|
9
|
+
/** One alternate of a page: its `hreflang` value and the URL path of the translation (the caller makes it absolute). */
|
|
10
|
+
export type Alternate = readonly [hreflang: string, url: string];
|
|
11
|
+
/** LANGUAGES, evaluated, with the translations documents give (tree path -> translation). */
|
|
12
|
+
export interface Languages {
|
|
13
|
+
readonly codes: readonly string[];
|
|
14
|
+
readonly default?: string;
|
|
15
|
+
readonly docs: ReadonlyMap<string, Translation>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The alternates of every page that has a translation. `pages` are [tree path, URL path] pairs (the URL path
|
|
19
|
+
* is what the language folder is read from). A page a document renders is grouped by its `translationKey`
|
|
20
|
+
* in its `lang`; any other page by its URL path without the language folder (`/fr/about.html` is the `fr`
|
|
21
|
+
* page of `/about.html`), and one in no language folder is the DEFAULT language's (without DEFAULT, it has
|
|
22
|
+
* none). A group of two or more pages gives each of them every page of the group, ordered by language, then
|
|
23
|
+
* `x-default` for the DEFAULT language's page. Two pages of one language in a group are `E_VALIDATION`.
|
|
24
|
+
*/
|
|
25
|
+
export declare function alternates(pages: ReadonlyArray<readonly [string, string]>, langs: Languages, what: string, span: SourceSpan): Map<string, Alternate[]>;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// LANGUAGES (docs/LANGUAGE.md, "Site files"): which pages translate each other, for the hreflang alternates
|
|
2
|
+
// CANONICAL and SITEMAP write. Ported as rust/src/hreflang.rs: both must find the same groups and messages.
|
|
3
|
+
import { SitefileError } from './errors.js';
|
|
4
|
+
const TAG_RE = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{1,8})*$/;
|
|
5
|
+
/** A basic BCP 47 check: a 2-3 letter language, then `-` subtags of 1-8 letters or digits (`en`, `pt-BR`, `zh-Hant-TW`). */
|
|
6
|
+
export function isLanguageTag(s) {
|
|
7
|
+
return TAG_RE.test(s);
|
|
8
|
+
}
|
|
9
|
+
function utf8Compare(a, b) {
|
|
10
|
+
return Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'));
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* The alternates of every page that has a translation. `pages` are [tree path, URL path] pairs (the URL path
|
|
14
|
+
* is what the language folder is read from). A page a document renders is grouped by its `translationKey`
|
|
15
|
+
* in its `lang`; any other page by its URL path without the language folder (`/fr/about.html` is the `fr`
|
|
16
|
+
* page of `/about.html`), and one in no language folder is the DEFAULT language's (without DEFAULT, it has
|
|
17
|
+
* none). A group of two or more pages gives each of them every page of the group, ordered by language, then
|
|
18
|
+
* `x-default` for the DEFAULT language's page. Two pages of one language in a group are `E_VALIDATION`.
|
|
19
|
+
*/
|
|
20
|
+
export function alternates(pages, langs, what, span) {
|
|
21
|
+
const groups = new Map();
|
|
22
|
+
for (const [path, url] of [...pages].sort((a, b) => utf8Compare(a[0], b[0]))) {
|
|
23
|
+
const doc = langs.docs.get(path);
|
|
24
|
+
let group;
|
|
25
|
+
let lang;
|
|
26
|
+
let label;
|
|
27
|
+
if (doc) {
|
|
28
|
+
group = `k\0${doc.key}`;
|
|
29
|
+
lang = doc.lang;
|
|
30
|
+
label = `translationKey '${doc.key}'`;
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
const slash = url.indexOf('/', 1);
|
|
34
|
+
const folder = slash > 0 ? url.slice(1, slash) : undefined;
|
|
35
|
+
if (folder !== undefined && langs.codes.includes(folder)) {
|
|
36
|
+
lang = folder;
|
|
37
|
+
group = `f\0${url.slice(slash)}`;
|
|
38
|
+
label = `'${url.slice(slash)}'`;
|
|
39
|
+
}
|
|
40
|
+
else if (langs.default !== undefined) {
|
|
41
|
+
lang = langs.default;
|
|
42
|
+
group = `f\0${url}`;
|
|
43
|
+
label = `'${url}'`;
|
|
44
|
+
}
|
|
45
|
+
else
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
let members = groups.get(group);
|
|
49
|
+
if (!members)
|
|
50
|
+
groups.set(group, (members = []));
|
|
51
|
+
const same = members.find((m) => m.lang.toLowerCase() === lang.toLowerCase());
|
|
52
|
+
if (same) {
|
|
53
|
+
throw new SitefileError('E_VALIDATION', `${what}: ${same.path} and ${path} are both the '${lang}' page of ${label}; a translation group has one page per language`, span);
|
|
54
|
+
}
|
|
55
|
+
members.push({ path, url, lang });
|
|
56
|
+
}
|
|
57
|
+
const out = new Map();
|
|
58
|
+
const dflt = langs.default?.toLowerCase();
|
|
59
|
+
for (const members of groups.values()) {
|
|
60
|
+
if (members.length < 2)
|
|
61
|
+
continue;
|
|
62
|
+
const sorted = [...members].sort((a, b) => (a.lang.toLowerCase() < b.lang.toLowerCase() ? -1 : a.lang.toLowerCase() > b.lang.toLowerCase() ? 1 : 0));
|
|
63
|
+
const alts = sorted.map((m) => [m.lang, m.url]);
|
|
64
|
+
const d = sorted.find((m) => m.lang.toLowerCase() === dflt);
|
|
65
|
+
if (d)
|
|
66
|
+
alts.push(['x-default', d.url]);
|
|
67
|
+
for (const m of members)
|
|
68
|
+
out.set(m.path, alts);
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=hreflang.js.map
|
|
@@ -370,6 +370,16 @@ export interface CanonicalInstruction {
|
|
|
370
370
|
readonly base: Operand;
|
|
371
371
|
readonly pretty: boolean;
|
|
372
372
|
}
|
|
373
|
+
/**
|
|
374
|
+
* `LANGUAGES <code>… [DEFAULT <code>]`: the site's language folders (`/en/…`, `/fr/…`, pages at the root in the
|
|
375
|
+
* DEFAULT language). CANONICAL and SITEMAP write hreflang alternates for the pages that translate each other.
|
|
376
|
+
*/
|
|
377
|
+
export interface LanguagesInstruction {
|
|
378
|
+
readonly kind: 'LANGUAGES';
|
|
379
|
+
readonly span: SourceSpan;
|
|
380
|
+
readonly codes: readonly Operand[];
|
|
381
|
+
readonly default?: Operand;
|
|
382
|
+
}
|
|
373
383
|
/** A PRECOMPRESS sidecar format: `gzip` writes `<file>.gz` (`br` and `zstd` are reserved: no encoder yet). */
|
|
374
384
|
export type PrecompressFormat = 'gzip';
|
|
375
385
|
/**
|
|
@@ -453,7 +463,7 @@ export interface CheckLinksInstruction {
|
|
|
453
463
|
/** `--external`: also request http(s) links (under the network policy). */
|
|
454
464
|
readonly external: boolean;
|
|
455
465
|
}
|
|
456
|
-
export type Instruction = FromInstruction | ArgInstruction | LetInstruction | FragmentInstruction | ImportInstruction | CopyInstruction | RenderInstruction | PluginInstruction | ToolInstruction | TransformInstruction | SitemapInstruction | FeedInstruction | RedirectInstruction | HeaderInstruction | MimeInstruction | FingerprintInstruction | CanonicalInstruction | PrecompressInstruction | RobotsInstruction | SecurityTxtInstruction | PrecacheInstruction | CspInstruction | CheckLinksInstruction | ExportInstruction;
|
|
466
|
+
export type Instruction = FromInstruction | ArgInstruction | LetInstruction | FragmentInstruction | ImportInstruction | CopyInstruction | RenderInstruction | PluginInstruction | ToolInstruction | TransformInstruction | SitemapInstruction | FeedInstruction | RedirectInstruction | HeaderInstruction | MimeInstruction | FingerprintInstruction | CanonicalInstruction | LanguagesInstruction | PrecompressInstruction | RobotsInstruction | SecurityTxtInstruction | PrecacheInstruction | CspInstruction | CheckLinksInstruction | ExportInstruction;
|
|
457
467
|
/** A parsed and semantically validated Sitefile. */
|
|
458
468
|
export interface Program {
|
|
459
469
|
readonly file: string;
|
|
@@ -49,6 +49,8 @@ function parseInstruction(c) {
|
|
|
49
49
|
return parseFingerprint(c, span);
|
|
50
50
|
case 'CANONICAL':
|
|
51
51
|
return parseCanonical(c, span);
|
|
52
|
+
case 'LANGUAGES':
|
|
53
|
+
return parseLanguages(c, span);
|
|
52
54
|
case 'PRECOMPRESS':
|
|
53
55
|
return parsePrecompress(c, span);
|
|
54
56
|
case 'ROBOTS':
|
|
@@ -606,6 +608,17 @@ function parseCanonical(c, span) {
|
|
|
606
608
|
c.expectEnd();
|
|
607
609
|
return { kind: 'CANONICAL', span, base, pretty };
|
|
608
610
|
}
|
|
611
|
+
/** `LANGUAGES <code>… [DEFAULT <code>]` */
|
|
612
|
+
function parseLanguages(c, span) {
|
|
613
|
+
const codes = [];
|
|
614
|
+
while (!c.atEnd() && !c.peekKeyword('DEFAULT'))
|
|
615
|
+
codes.push(c.operand('language code'));
|
|
616
|
+
if (codes.length === 0)
|
|
617
|
+
throw c.error('E_SYNTAX', 'expected a language code (LANGUAGES en fr de DEFAULT en)');
|
|
618
|
+
const dflt = c.keyword('DEFAULT') ? c.operand('default language code') : undefined;
|
|
619
|
+
c.expectEnd();
|
|
620
|
+
return { kind: 'LANGUAGES', span, codes, ...(dflt ? { default: dflt } : {}) };
|
|
621
|
+
}
|
|
609
622
|
/** Sidecar formats PRECOMPRESS knows; only gzip has an encoder (src/deflate.ts, shared with the Rust port). */
|
|
610
623
|
const PRECOMPRESS_FORMATS = ['gzip', 'br', 'zstd'];
|
|
611
624
|
/** `PRECOMPRESS [--overwrite] [gzip]… <pattern>… [MIN <bytes>]` */
|
|
@@ -52,6 +52,8 @@ export function operandsOf(ins) {
|
|
|
52
52
|
return [...ins.patterns, ...(ins.manifest ? [ins.manifest] : [])];
|
|
53
53
|
case 'CANONICAL':
|
|
54
54
|
return [ins.base];
|
|
55
|
+
case 'LANGUAGES':
|
|
56
|
+
return [...ins.codes, ...(ins.default ? [ins.default] : [])];
|
|
55
57
|
case 'PRECOMPRESS':
|
|
56
58
|
return [...ins.patterns, ...(ins.min ? [ins.min] : [])];
|
|
57
59
|
case 'ROBOTS':
|
|
@@ -292,6 +294,7 @@ export function validate(instructions, file) {
|
|
|
292
294
|
case 'MIME':
|
|
293
295
|
case 'FINGERPRINT':
|
|
294
296
|
case 'CANONICAL':
|
|
297
|
+
case 'LANGUAGES':
|
|
295
298
|
case 'PRECOMPRESS':
|
|
296
299
|
case 'ROBOTS':
|
|
297
300
|
case 'SECURITY_TXT':
|
package/lib/src/links.d.ts
CHANGED
|
@@ -49,6 +49,20 @@ export declare function integrityTags(text: string): IntegrityTag[];
|
|
|
49
49
|
* there is no `</head>`. Comments, declarations and raw text are skipped as in {@link scanHtml}.
|
|
50
50
|
*/
|
|
51
51
|
export declare function canonicalSlot(text: string): number | 'has' | undefined;
|
|
52
|
+
/** What CANONICAL needs from a page's head: see {@link headLinks}. */
|
|
53
|
+
export interface HeadLinks {
|
|
54
|
+
/** The offset of the first `</head` end tag; undefined when there is none. */
|
|
55
|
+
readonly at: number | undefined;
|
|
56
|
+
/** A `<link>` whose `rel` has the token `canonical` comes before it (or anywhere, without `</head>`). */
|
|
57
|
+
readonly canonical: boolean;
|
|
58
|
+
/** So does a `<link>` whose `rel` has the token `alternate` and that has an `hreflang` attribute. */
|
|
59
|
+
readonly hreflang: boolean;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Where links go in a page's head and which it already has (ASCII case-insensitive `rel` tokens). Comments,
|
|
63
|
+
* declarations and raw text are skipped as in {@link scanHtml}.
|
|
64
|
+
*/
|
|
65
|
+
export declare function headLinks(text: string): HeadLinks;
|
|
52
66
|
/** What CSP needs from a page: its inline script and style texts, in order, and where its `<head>` start tag ends. */
|
|
53
67
|
export interface InlineBlocks {
|
|
54
68
|
/** The contents of each `<script>` without a `src` attribute (also empty ones). */
|
package/lib/src/links.js
CHANGED
|
@@ -505,6 +505,16 @@ export function integrityTags(text) {
|
|
|
505
505
|
* there is no `</head>`. Comments, declarations and raw text are skipped as in {@link scanHtml}.
|
|
506
506
|
*/
|
|
507
507
|
export function canonicalSlot(text) {
|
|
508
|
+
const h = headLinks(text);
|
|
509
|
+
return h.canonical ? 'has' : h.at;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* Where links go in a page's head and which it already has (ASCII case-insensitive `rel` tokens). Comments,
|
|
513
|
+
* declarations and raw text are skipped as in {@link scanHtml}.
|
|
514
|
+
*/
|
|
515
|
+
export function headLinks(text) {
|
|
516
|
+
let canonical = false;
|
|
517
|
+
let hreflang = false;
|
|
508
518
|
const n = text.length;
|
|
509
519
|
let i = 0;
|
|
510
520
|
while (i < n) {
|
|
@@ -521,7 +531,7 @@ export function canonicalSlot(text) {
|
|
|
521
531
|
if (next === '/') {
|
|
522
532
|
const end = i + 6;
|
|
523
533
|
if (lowerAscii(text.slice(i + 2, end)) === 'head' && (end >= n || isWs(text[end]) || text[end] === '/' || text[end] === '>'))
|
|
524
|
-
return i;
|
|
534
|
+
return { at: i, canonical, hreflang };
|
|
525
535
|
}
|
|
526
536
|
if (next === '!' || next === '?' || next === '/') {
|
|
527
537
|
const j = text.indexOf('>', i + 2);
|
|
@@ -538,6 +548,7 @@ export function canonicalSlot(text) {
|
|
|
538
548
|
const tag = lowerAscii(text.slice(i + 1, j));
|
|
539
549
|
i = j;
|
|
540
550
|
let rel;
|
|
551
|
+
let lang = false;
|
|
541
552
|
for (;;) {
|
|
542
553
|
while (i < n && (isWs(text[i]) || text[i] === '/'))
|
|
543
554
|
i++;
|
|
@@ -552,6 +563,8 @@ export function canonicalSlot(text) {
|
|
|
552
563
|
while (i < n && !isWs(text[i]) && text[i] !== '/' && text[i] !== '>' && text[i] !== '=')
|
|
553
564
|
i++;
|
|
554
565
|
const name = lowerAscii(text.slice(nameStart, i));
|
|
566
|
+
if (name === 'hreflang')
|
|
567
|
+
lang = true;
|
|
555
568
|
let k = i;
|
|
556
569
|
while (k < n && isWs(text[k]))
|
|
557
570
|
k++;
|
|
@@ -578,12 +591,17 @@ export function canonicalSlot(text) {
|
|
|
578
591
|
if (name === 'rel' && rel === undefined)
|
|
579
592
|
rel = text.slice(start, end);
|
|
580
593
|
}
|
|
581
|
-
if (tag === 'link' && rel !== undefined
|
|
582
|
-
|
|
594
|
+
if (tag === 'link' && rel !== undefined) {
|
|
595
|
+
const tokens = lowerAscii(decodeHtmlText(rel)).split(/[ \t\n\r\f]+/);
|
|
596
|
+
if (tokens.includes('canonical'))
|
|
597
|
+
canonical = true;
|
|
598
|
+
if (lang && tokens.includes('alternate'))
|
|
599
|
+
hreflang = true;
|
|
600
|
+
}
|
|
583
601
|
if (RAW_TEXT.has(tag))
|
|
584
602
|
i = indexOfCloseTag(text, tag, i);
|
|
585
603
|
}
|
|
586
|
-
return undefined;
|
|
604
|
+
return { at: undefined, canonical, hreflang };
|
|
587
605
|
}
|
|
588
606
|
/** The inline scripts and styles of an HTML text (comments and other raw text skipped as in {@link scanHtml}). */
|
|
589
607
|
export function inlineBlocks(text) {
|
package/lib/src/planner.d.ts
CHANGED
|
@@ -127,6 +127,20 @@ export interface CspSpec {
|
|
|
127
127
|
}
|
|
128
128
|
/** CSP's base policy when POLICY is not given: same-origin resources only, no plugins, no `<base>` hijacking. */
|
|
129
129
|
export declare const DEFAULT_CSP = "default-src 'self'; base-uri 'self'; object-src 'none'";
|
|
130
|
+
/**
|
|
131
|
+
* LANGUAGES, evaluated, as CANONICAL and SITEMAP see it: the language folders, the DEFAULT language, and the
|
|
132
|
+
* stage's `RENDER … FOR` lines before them (without BY or PAGE), whose documents may set `lang` and
|
|
133
|
+
* `translationKey`.
|
|
134
|
+
*/
|
|
135
|
+
export interface LanguagesSpec {
|
|
136
|
+
readonly codes: readonly string[];
|
|
137
|
+
readonly default?: string;
|
|
138
|
+
readonly sources: ReadonlyArray<{
|
|
139
|
+
readonly as: string;
|
|
140
|
+
readonly list: string;
|
|
141
|
+
readonly dest: Operand;
|
|
142
|
+
}>;
|
|
143
|
+
}
|
|
130
144
|
export type Operation = {
|
|
131
145
|
/** Report the references in the tree's HTML and CSS files that point at nothing. */
|
|
132
146
|
readonly kind: 'CHECKLINKS';
|
|
@@ -159,6 +173,8 @@ export type Operation = {
|
|
|
159
173
|
/** The EXPORT path: a page's URL is its path below it. */
|
|
160
174
|
readonly root: string;
|
|
161
175
|
readonly span: SourceSpan;
|
|
176
|
+
/** With LANGUAGES: hreflang alternates too. */
|
|
177
|
+
readonly languages?: LanguagesSpec;
|
|
162
178
|
} | {
|
|
163
179
|
/** Write a `.gz` sidecar for each matching compressible file of at least `min` bytes, when smaller. */
|
|
164
180
|
readonly kind: 'PRECOMPRESS';
|
|
@@ -186,6 +202,8 @@ export type Operation = {
|
|
|
186
202
|
readonly dest: string;
|
|
187
203
|
readonly overwrite: boolean;
|
|
188
204
|
readonly span: SourceSpan;
|
|
205
|
+
/** With LANGUAGES: `xhtml:link` alternates too. */
|
|
206
|
+
readonly languages?: LanguagesSpec;
|
|
189
207
|
} | {
|
|
190
208
|
/** An Atom feed of a list import; `link` is interpolated per element (`${item…}`). */
|
|
191
209
|
readonly kind: 'FEED';
|
package/lib/src/planner.js
CHANGED
|
@@ -3,6 +3,7 @@ import { importedStage, isFragment, isImageBase, isInline, stageNames } from './
|
|
|
3
3
|
import { normalizeLocal, normalizeVirtual } from './paths.js';
|
|
4
4
|
import { parseRef } from './ref.js';
|
|
5
5
|
import { checkPattern } from './fingerprint.js';
|
|
6
|
+
import { isLanguageTag } from './hreflang.js';
|
|
6
7
|
import { checkBaseUrl, checkFieldUri, checkCspPolicy, checkHeaderName, checkHeaderValue, checkMimeExtension, checkMimeType, checkRedirectTarget, checkSitePath, pageUrl, parseFeedDate, robotsTxt, securityTxt } from './site.js';
|
|
7
8
|
import { coerce, evaluateOperand } from './values.js';
|
|
8
9
|
import { isGitUri, parseGitUri } from './resources/git.js';
|
|
@@ -28,6 +29,7 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
|
|
|
28
29
|
const sitemapUrls = [];
|
|
29
30
|
const robots = [];
|
|
30
31
|
let csp;
|
|
32
|
+
let languages;
|
|
31
33
|
const mimes = new Map();
|
|
32
34
|
const warnings = [];
|
|
33
35
|
const declaredArgs = new Set();
|
|
@@ -304,6 +306,26 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
|
|
|
304
306
|
});
|
|
305
307
|
break;
|
|
306
308
|
}
|
|
309
|
+
case 'LANGUAGES': {
|
|
310
|
+
if (languages)
|
|
311
|
+
throw new SitefileError('E_VALIDATION', `LANGUAGES given twice (line ${languages.span.line} already lists the languages)`, ins.span);
|
|
312
|
+
const codes = [];
|
|
313
|
+
for (const o of ins.codes) {
|
|
314
|
+
const code = languageTag(evaluateOperand(o, vars), o.span);
|
|
315
|
+
if (codes.some((c) => c.toLowerCase() === code.toLowerCase()))
|
|
316
|
+
throw new SitefileError('E_VALIDATION', `LANGUAGES: '${code}' is listed twice`, o.span);
|
|
317
|
+
codes.push(code);
|
|
318
|
+
}
|
|
319
|
+
let dflt;
|
|
320
|
+
if (ins.default) {
|
|
321
|
+
dflt = languageTag(evaluateOperand(ins.default, vars), ins.default.span);
|
|
322
|
+
const d = dflt;
|
|
323
|
+
if (!codes.some((c) => c === d))
|
|
324
|
+
throw new SitefileError('E_VALIDATION', `LANGUAGES … DEFAULT ${d}: '${d}' is not one of the languages listed (${codes.join(' ')})`, ins.default.span);
|
|
325
|
+
}
|
|
326
|
+
languages = { codes, ...(dflt !== undefined ? { default: dflt } : {}), span: ins.span };
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
307
329
|
case 'CSP': {
|
|
308
330
|
if (csp)
|
|
309
331
|
throw new SitefileError('E_VALIDATION', `CSP given twice (line ${csp.span.line} already sets the policy)`, ins.span);
|
|
@@ -359,6 +381,17 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
|
|
|
359
381
|
if (op.kind === 'CHECKLINKS')
|
|
360
382
|
st.operations[i] = { ...op, root: exportPath ?? '/', redirects: redirects.map((r) => r.from) };
|
|
361
383
|
});
|
|
384
|
+
if (languages) {
|
|
385
|
+
// Each CANONICAL and SITEMAP sees the stage's RENDER … FOR lines before it.
|
|
386
|
+
const sources = [];
|
|
387
|
+
st.operations.forEach((op, i) => {
|
|
388
|
+
if (op.kind === 'RENDER' && op.each && op.each.by === undefined && op.each.page === undefined)
|
|
389
|
+
sources.push({ as: op.each.as, list: op.each.list, dest: op.each.dest });
|
|
390
|
+
if (op.kind === 'CANONICAL' || op.kind === 'SITEMAP') {
|
|
391
|
+
st.operations[i] = { ...op, languages: { codes: languages.codes, ...(languages.default !== undefined ? { default: languages.default } : {}), sources: [...sources] } };
|
|
392
|
+
}
|
|
393
|
+
});
|
|
394
|
+
}
|
|
362
395
|
}
|
|
363
396
|
// An unnamed stage can be neither a FROM base nor a COPY --from source; only the last one is useful (EXPORT reads it).
|
|
364
397
|
for (const st of stages.slice(0, -1)) {
|
|
@@ -455,6 +488,12 @@ function minSize(op, vars) {
|
|
|
455
488
|
}
|
|
456
489
|
return Number(raw);
|
|
457
490
|
}
|
|
491
|
+
/** A LANGUAGES code: a basic BCP 47 tag (`E_VALIDATION` otherwise). */
|
|
492
|
+
function languageTag(raw, span) {
|
|
493
|
+
if (!isLanguageTag(raw))
|
|
494
|
+
throw new SitefileError('E_VALIDATION', `LANGUAGES: '${raw}' is not a language code (a BCP 47 tag such as en, fr or pt-BR)`, span);
|
|
495
|
+
return raw;
|
|
496
|
+
}
|
|
458
497
|
/** `TO <dest>` of SITEMAP/FEED or `MANIFEST <dest>` of FINGERPRINT (a file path), or the default. */
|
|
459
498
|
function fileDest(op, vars, fallback, what) {
|
|
460
499
|
if (!op)
|