@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/server.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
1
2
|
import http from 'node:http';
|
|
2
3
|
import https from 'node:https';
|
|
3
4
|
import os from 'node:os';
|
|
@@ -94,7 +95,7 @@ export const STREAM_HEADERS = {
|
|
|
94
95
|
};
|
|
95
96
|
/** The script served at {@link RELOAD_SCRIPT_PATH}: {@link RELOAD_CLIENT} called with `options` (keys in a fixed order). */
|
|
96
97
|
export function clientScript(options = {}) {
|
|
97
|
-
return `${RELOAD_CLIENT}({"resetServiceWorkers":${options.resetServiceWorkers !== false},"cssInject":${options.cssInject !== false},"console":${options.console === true},"overlay":${options.overlay !== false},"navigateToChanged":${options.navigateToChanged === true},"reload":"${options.reload ?? 'morph'}"});\n`;
|
|
98
|
+
return `${RELOAD_CLIENT}({"resetServiceWorkers":${options.resetServiceWorkers !== false},"cssInject":${options.cssInject !== false},"console":${options.console === true},"overlay":${options.overlay !== false},"navigateToChanged":${options.navigateToChanged === true},"reload":"${options.reload ?? 'morph'}"${options.sync !== undefined ? `,"sync":"${options.sync}"` : ''}});\n`;
|
|
98
99
|
}
|
|
99
100
|
/** Reserved for browser console messages (POST) while `serve --watch` runs. */
|
|
100
101
|
export const CONSOLE_PATH = '/__sitefile/console';
|
|
@@ -162,6 +163,78 @@ export function isSameOriginPost(headers) {
|
|
|
162
163
|
return false;
|
|
163
164
|
return origin === `http://${host}` || origin === `https://${host}`;
|
|
164
165
|
}
|
|
166
|
+
/** Reserved for location reports (POST) from pages while `serve --watch --sync` runs. */
|
|
167
|
+
export const CLIENT_PATH = '/__sitefile/client';
|
|
168
|
+
/** Reserved for the list of connected pages (GET, loopback only, not from a browser) while `serve --watch --sync` runs. */
|
|
169
|
+
export const CLIENTS_PATH = '/__sitefile/clients';
|
|
170
|
+
/** Largest location report accepted (bytes). */
|
|
171
|
+
export const MAX_CLIENT_BODY = 4096;
|
|
172
|
+
/** At most this many reports are accepted from one page per {@link CLIENT_WINDOW_MS} (more get `429`). */
|
|
173
|
+
export const CLIENT_REPORT_LIMIT = 60;
|
|
174
|
+
export const CLIENT_WINDOW_MS = 10_000;
|
|
175
|
+
/** At most this many pages are tracked (one that left is forgotten first to make room). */
|
|
176
|
+
export const MAX_CLIENTS = 64;
|
|
177
|
+
const CLIENT_ID = /^[0-9a-f]{16}$/;
|
|
178
|
+
/** A location report body (JSON `{id, url, title?, nav?, scroll?}`), or undefined when it is not one. */
|
|
179
|
+
export function parseClientReport(body) {
|
|
180
|
+
let v;
|
|
181
|
+
try {
|
|
182
|
+
v = JSON.parse(body);
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
|
187
|
+
if (typeof v !== 'object' || v === null || Array.isArray(v))
|
|
188
|
+
return undefined;
|
|
189
|
+
const o = v;
|
|
190
|
+
if (typeof o.id !== 'string' || !CLIENT_ID.test(o.id))
|
|
191
|
+
return undefined;
|
|
192
|
+
if (typeof o.url !== 'string' || o.url.length > 2048 || !/^\/(?!\/)[\x21-\x7e]*$/.test(o.url))
|
|
193
|
+
return undefined;
|
|
194
|
+
if (o.title !== undefined && typeof o.title !== 'string')
|
|
195
|
+
return undefined;
|
|
196
|
+
if (o.nav !== undefined && typeof o.nav !== 'boolean')
|
|
197
|
+
return undefined;
|
|
198
|
+
let scroll;
|
|
199
|
+
if (o.scroll !== undefined) {
|
|
200
|
+
const sc = o.scroll;
|
|
201
|
+
const part = (x) => typeof x === 'number' && Number.isInteger(x) && x >= 0 && x <= 10000;
|
|
202
|
+
if (!Array.isArray(sc) || sc.length !== 2 || !part(sc[0]) || !part(sc[1]))
|
|
203
|
+
return undefined;
|
|
204
|
+
scroll = [sc[0], sc[1]];
|
|
205
|
+
}
|
|
206
|
+
return { id: o.id, url: o.url, title: cleanText(typeof o.title === 'string' ? o.title : '', 200), nav: o.nav === true, ...(scroll ? { scroll } : {}) };
|
|
207
|
+
}
|
|
208
|
+
/** The tab ID a page's event stream names (`/__sitefile/reload?client=<id>`, the first `client`), else undefined. */
|
|
209
|
+
export function streamClientId(search) {
|
|
210
|
+
for (const pair of search.replace(/^\?/, '').split('&')) {
|
|
211
|
+
const eq = pair.indexOf('=');
|
|
212
|
+
if (eq === -1 || pair.slice(0, eq) !== 'client')
|
|
213
|
+
continue;
|
|
214
|
+
const id = pair.slice(eq + 1);
|
|
215
|
+
return CLIENT_ID.test(id) ? id : undefined;
|
|
216
|
+
}
|
|
217
|
+
return undefined;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Whether a request for {@link CLIENTS_PATH} comes from the operator (Sitefile Desktop, curl), not a
|
|
221
|
+
* page: a loopback client that sends no `Origin` and no `Sec-Fetch-*` header.
|
|
222
|
+
*/
|
|
223
|
+
export function isOperatorRequest(remote, headers) {
|
|
224
|
+
if (!isLoopbackAddress(remote))
|
|
225
|
+
return false;
|
|
226
|
+
return headers.origin === undefined && headers['sec-fetch-site'] === undefined && headers['sec-fetch-mode'] === undefined;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* A `--sync` log line. Text: `client <event> <id> <url> <remote> <device>`. JSON (a stable contract,
|
|
230
|
+
* docs/CLI.md): `{"type":"client","ts","event","id","url","title","remote","device"}`, `title` only
|
|
231
|
+
* when not empty.
|
|
232
|
+
*/
|
|
233
|
+
export function clientLogLine(format, e) {
|
|
234
|
+
if (format === 'text')
|
|
235
|
+
return `client ${e.event} ${e.id} ${e.url} ${e.remote} ${e.device}`;
|
|
236
|
+
return `{"type":"client","ts":${JSON.stringify(e.ts)},"event":${JSON.stringify(e.event)},"id":${JSON.stringify(e.id)},"url":${JSON.stringify(e.url)}${e.title !== '' ? `,"title":${JSON.stringify(e.title)}` : ''},"remote":${JSON.stringify(e.remote)},"device":${JSON.stringify(e.device)}}`;
|
|
237
|
+
}
|
|
165
238
|
/** The event that tells every page to reload. */
|
|
166
239
|
export const RELOAD_EVENT = '{"type":"reload"}';
|
|
167
240
|
/** Sent when a rebuild starts (pages show a Rebuilding badge). */
|
|
@@ -232,35 +305,120 @@ export function reloadEventFor(prev, next, cssInject, navigate = false) {
|
|
|
232
305
|
}
|
|
233
306
|
/** Open live-reload streams; {@link LiveReload.send} gives every page an event ({@link LiveReload.reload}: reload). */
|
|
234
307
|
export class LiveReload {
|
|
235
|
-
|
|
308
|
+
/** Open streams, with the tab ID each names (`--sync`). */
|
|
309
|
+
clients = new Map();
|
|
310
|
+
/** `--sync`: the pages that reported, in the order they first connected. */
|
|
311
|
+
known = new Map();
|
|
312
|
+
/** `--sync`, else undefined. */
|
|
313
|
+
sync;
|
|
236
314
|
/** The client script for this session ({@link clientScript}). */
|
|
237
315
|
script;
|
|
238
316
|
/** Time between heartbeat comments on an open stream (15 s; tests pass less). */
|
|
239
317
|
heartbeatMs;
|
|
318
|
+
/**
|
|
319
|
+
* This server process's instance ID (16 hex digits, random). Every stream starts with it as the
|
|
320
|
+
* event ID, so a page that reconnects after a restart (`server restart`, a new `serve --watch`)
|
|
321
|
+
* sends the old one in `Last-Event-ID` and is told to reload.
|
|
322
|
+
*/
|
|
323
|
+
instance = randomBytes(8).toString('hex');
|
|
240
324
|
constructor(options = {}, heartbeatMs = HEARTBEAT_MS) {
|
|
241
325
|
this.script = clientScript(options);
|
|
242
326
|
this.heartbeatMs = heartbeatMs;
|
|
243
327
|
this.console = options.console === true;
|
|
328
|
+
this.sync = options.sync;
|
|
244
329
|
}
|
|
245
330
|
/**
|
|
246
331
|
* Hold `res` open as a text/event-stream until the client goes away. The headers keep proxies
|
|
247
332
|
* and tunnels from buffering or compressing it, and a comment every 15 s keeps idle
|
|
248
333
|
* connections from being cut (and finds clients that went away).
|
|
249
334
|
*/
|
|
250
|
-
attach(res, headers) {
|
|
335
|
+
attach(res, headers, lastEventId, client) {
|
|
251
336
|
res.writeHead(200, { ...headers, ...STREAM_HEADERS });
|
|
252
|
-
res.write(
|
|
337
|
+
res.write(`retry: 1000\n\nid: ${this.instance}\n\n`);
|
|
338
|
+
// A page that was connected to an earlier instance of this server (it restarted) reloads.
|
|
339
|
+
if (lastEventId !== undefined && lastEventId !== '' && lastEventId !== this.instance)
|
|
340
|
+
res.write(`data: ${RELOAD_EVENT}\n\n`);
|
|
253
341
|
// A page opened while the last build is broken shows the error at once.
|
|
254
342
|
if (this.failure !== undefined)
|
|
255
343
|
res.write(`data: ${this.failure}\n\n`);
|
|
256
|
-
this.
|
|
344
|
+
const entry = client !== undefined && this.sync !== undefined ? this.track(client) : undefined;
|
|
345
|
+
this.clients.set(res, entry?.id);
|
|
257
346
|
const beat = setInterval(() => res.write(': ping\n\n'), this.heartbeatMs);
|
|
258
347
|
beat.unref();
|
|
259
348
|
res.on('close', () => {
|
|
260
349
|
clearInterval(beat);
|
|
261
350
|
this.clients.delete(res);
|
|
351
|
+
if (entry !== undefined) {
|
|
352
|
+
entry.streams--;
|
|
353
|
+
entry.lastSeen = new Date().toISOString();
|
|
354
|
+
}
|
|
262
355
|
});
|
|
263
356
|
}
|
|
357
|
+
/** `--sync`: the entry for a page whose stream opened (undefined when {@link MAX_CLIENTS} are connected). */
|
|
358
|
+
track(client) {
|
|
359
|
+
const now = new Date().toISOString();
|
|
360
|
+
let entry = this.known.get(client.id);
|
|
361
|
+
if (entry === undefined) {
|
|
362
|
+
if (this.known.size >= MAX_CLIENTS) {
|
|
363
|
+
const gone = [...this.known.values()].find((e) => e.streams === 0);
|
|
364
|
+
if (gone === undefined)
|
|
365
|
+
return undefined;
|
|
366
|
+
this.known.delete(gone.id);
|
|
367
|
+
}
|
|
368
|
+
entry = { id: client.id, remote: client.remote, device: client.device, url: '', title: '', since: now, lastSeen: now, streams: 0, window: 0, count: 0 };
|
|
369
|
+
this.known.set(client.id, entry);
|
|
370
|
+
}
|
|
371
|
+
entry.remote = client.remote;
|
|
372
|
+
entry.device = client.device;
|
|
373
|
+
entry.lastSeen = now;
|
|
374
|
+
entry.streams++;
|
|
375
|
+
return entry;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* `--sync`: take a page's location report. The status to answer: `404` when its stream is not
|
|
379
|
+
* open, `429` over {@link CLIENT_REPORT_LIMIT}, else `204`; then the log line it gives (its first
|
|
380
|
+
* report, or a new URL) and the events sent to the other pages (`navigate`, and `scroll` with
|
|
381
|
+
* `--sync=scroll`).
|
|
382
|
+
*/
|
|
383
|
+
report(r, now, format) {
|
|
384
|
+
const entry = this.known.get(r.id);
|
|
385
|
+
if (entry === undefined || entry.streams === 0 || this.sync === undefined)
|
|
386
|
+
return { status: 404 };
|
|
387
|
+
if (now - entry.window >= CLIENT_WINDOW_MS) {
|
|
388
|
+
entry.window = now;
|
|
389
|
+
entry.count = 0;
|
|
390
|
+
}
|
|
391
|
+
if (++entry.count > CLIENT_REPORT_LIMIT)
|
|
392
|
+
return { status: 429 };
|
|
393
|
+
const ts = new Date(now).toISOString();
|
|
394
|
+
const event = entry.url === '' ? 'connect' : entry.url !== r.url ? 'navigate' : undefined;
|
|
395
|
+
entry.url = r.url;
|
|
396
|
+
entry.title = r.title;
|
|
397
|
+
entry.lastSeen = ts;
|
|
398
|
+
if (r.nav)
|
|
399
|
+
this.sendExcept(JSON.stringify({ type: 'navigate', url: r.url }), r.id);
|
|
400
|
+
if (r.scroll !== undefined && this.sync === 'scroll')
|
|
401
|
+
this.sendExcept(JSON.stringify({ type: 'scroll', url: r.url, x: r.scroll[0], y: r.scroll[1] }), r.id);
|
|
402
|
+
if (event === undefined)
|
|
403
|
+
return { status: 204 };
|
|
404
|
+
return { status: 204, log: clientLogLine(format, { ts, event, id: r.id, url: r.url, title: r.title, remote: entry.remote, device: entry.device }) };
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* `--sync`: the connected pages as {@link CLIENTS_PATH} answers them:
|
|
408
|
+
* `{"clients":[{"id","url","title","remote","device","since","lastSeen"}]}` (one line), by
|
|
409
|
+
* `since`, then `id`. A page that has not reported yet has an empty `url`.
|
|
410
|
+
*/
|
|
411
|
+
clientsJson() {
|
|
412
|
+
const list = [...this.known.values()].filter((e) => e.streams > 0).sort((a, b) => (a.since < b.since ? -1 : a.since > b.since ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
413
|
+
const items = list.map((e) => `{"id":${JSON.stringify(e.id)},"url":${JSON.stringify(e.url)},"title":${JSON.stringify(e.title)},"remote":${JSON.stringify(e.remote)},"device":${JSON.stringify(e.device)},"since":${JSON.stringify(e.since)},"lastSeen":${JSON.stringify(e.lastSeen)}}`);
|
|
414
|
+
return `{"clients":[${items.join(',')}]}\n`;
|
|
415
|
+
}
|
|
416
|
+
/** Send `event` to every open page except those of tab `id`. */
|
|
417
|
+
sendExcept(event, id) {
|
|
418
|
+
for (const [c, cid] of this.clients)
|
|
419
|
+
if (cid !== id)
|
|
420
|
+
c.write(`data: ${event}\n\n`);
|
|
421
|
+
}
|
|
264
422
|
console;
|
|
265
423
|
consoleWindow = 0;
|
|
266
424
|
consoleCount = 0;
|
|
@@ -286,7 +444,7 @@ export class LiveReload {
|
|
|
286
444
|
this.failure = event;
|
|
287
445
|
else if (event !== BUILDING_EVENT)
|
|
288
446
|
this.failure = undefined;
|
|
289
|
-
for (const c of this.clients)
|
|
447
|
+
for (const c of this.clients.keys())
|
|
290
448
|
c.write(`data: ${event}\n\n`);
|
|
291
449
|
}
|
|
292
450
|
reload() {
|
|
@@ -1036,6 +1194,44 @@ export function createSiteServer(site, options = {}) {
|
|
|
1036
1194
|
});
|
|
1037
1195
|
return;
|
|
1038
1196
|
}
|
|
1197
|
+
if (live?.sync !== undefined && url.split(/[?#]/, 1)[0] === CLIENT_PATH) {
|
|
1198
|
+
// --sync: a page's location report (the client script sends it; not access-logged).
|
|
1199
|
+
if (method !== 'POST')
|
|
1200
|
+
return finish(405, { allow: 'POST', 'content-length': 0 }, undefined, true);
|
|
1201
|
+
if (!isSameOriginPost(req.headers))
|
|
1202
|
+
return finish(403, { 'content-length': 0 }, undefined, true);
|
|
1203
|
+
const chunks = [];
|
|
1204
|
+
let size = 0;
|
|
1205
|
+
let tooBig = false;
|
|
1206
|
+
req.on('data', (c) => {
|
|
1207
|
+
size += c.byteLength;
|
|
1208
|
+
if (size > MAX_CLIENT_BODY)
|
|
1209
|
+
tooBig = true;
|
|
1210
|
+
else
|
|
1211
|
+
chunks.push(c);
|
|
1212
|
+
});
|
|
1213
|
+
req.on('end', () => {
|
|
1214
|
+
if (tooBig)
|
|
1215
|
+
return finish(413, { 'content-length': 0, connection: 'close' }, undefined, true);
|
|
1216
|
+
const r = parseClientReport(Buffer.concat(chunks).toString('utf8'));
|
|
1217
|
+
if (r === undefined)
|
|
1218
|
+
return finish(400, { 'content-length': 0 }, undefined, true);
|
|
1219
|
+
const done = live.report(r, Date.now(), options.logFormat ?? 'text');
|
|
1220
|
+
if (done.log !== undefined)
|
|
1221
|
+
options.log?.(done.log);
|
|
1222
|
+
finish(done.status, done.status === 204 ? {} : { 'content-length': 0 }, undefined, true);
|
|
1223
|
+
});
|
|
1224
|
+
return;
|
|
1225
|
+
}
|
|
1226
|
+
if (live?.sync !== undefined && url.split(/[?#]/, 1)[0] === CLIENTS_PATH) {
|
|
1227
|
+
// --sync: the connected pages, for Sitefile Desktop and other local tools (not access-logged).
|
|
1228
|
+
if (method !== 'GET' && method !== 'HEAD')
|
|
1229
|
+
return finish(405, { allow: 'GET, HEAD', 'content-length': 0 }, undefined, true);
|
|
1230
|
+
if (!isOperatorRequest(req.socket.remoteAddress ?? '', req.headers))
|
|
1231
|
+
return finish(403, { 'content-length': 0 }, undefined, true);
|
|
1232
|
+
const json = live.clientsJson();
|
|
1233
|
+
return finish(200, { 'content-type': 'application/json', 'cache-control': 'no-store', 'content-length': Buffer.byteLength(json) }, json, true);
|
|
1234
|
+
}
|
|
1039
1235
|
if (options.cors && method === 'OPTIONS') {
|
|
1040
1236
|
// A CORS preflight: any path, nothing is looked up.
|
|
1041
1237
|
const allowHeaders = preflightHeaders(req.headers['access-control-request-headers']);
|
|
@@ -1055,7 +1251,9 @@ export function createSiteServer(site, options = {}) {
|
|
|
1055
1251
|
if (options.liveReload && rawPath === RELOAD_PATH) {
|
|
1056
1252
|
if (method === 'HEAD')
|
|
1057
1253
|
return finish(200, { ...STREAM_HEADERS }, undefined);
|
|
1058
|
-
|
|
1254
|
+
const id = options.liveReload.sync !== undefined ? streamClientId(url.slice(rawPath.length).split('#', 1)[0]) : undefined;
|
|
1255
|
+
const client = id !== undefined ? { id, remote: req.socket.remoteAddress ?? '', device: deviceOf(req.headers['user-agent']) } : undefined;
|
|
1256
|
+
return options.liveReload.attach(res, base, header(req.headers['last-event-id']), client); // not access-logged: one long request per open page
|
|
1059
1257
|
}
|
|
1060
1258
|
if (options.liveReload && rawPath === RELOAD_SCRIPT_PATH) {
|
|
1061
1259
|
// not access-logged either: every page load fetches it
|
package/lib/src/servers.d.ts
CHANGED
|
@@ -87,6 +87,12 @@ export interface ServerState {
|
|
|
87
87
|
readonly country?: string;
|
|
88
88
|
/** `--strict-site-files`: an ignored `_redirects`/`_headers` line stops the server from starting (absent: false). */
|
|
89
89
|
readonly strictSiteFiles?: boolean;
|
|
90
|
+
/** `-d --watch` (a directory only): re-read the directory on change and live-reload open pages (absent: false). */
|
|
91
|
+
readonly watch?: boolean;
|
|
92
|
+
/** `--poll`, `--poll-interval` with `-d --watch`: poll every this many milliseconds instead of file system events (absent: events). */
|
|
93
|
+
readonly pollMs?: number;
|
|
94
|
+
/** `--sync` with `-d --watch`: pages report where they are and follow each other (`scroll`: their scrolling too) (absent: off). */
|
|
95
|
+
readonly sync?: 'nav' | 'scroll';
|
|
90
96
|
/** The requested bind address (port 0 = pick a free port). */
|
|
91
97
|
readonly bind: {
|
|
92
98
|
readonly host: string;
|
package/lib/src/site.d.ts
CHANGED
|
@@ -17,17 +17,21 @@ export declare const SITEMAP_LIMITS: {
|
|
|
17
17
|
};
|
|
18
18
|
/** sitemaps.org XML for every `.html` file in the tree except `/404.html`, sorted by path. */
|
|
19
19
|
export declare function sitemapXml(tree: Tree, base: string): string;
|
|
20
|
+
/** The pages a sitemap lists: every `.html` file except `/404.html`, sorted by path (UTF-8 bytes). */
|
|
21
|
+
export declare function sitemapPages(tree: Tree): string[];
|
|
20
22
|
/** `/sitemap.xml` -> `/sitemap-2.xml`: the n-th part of a split sitemap (before the extension, or at the end). */
|
|
21
23
|
export declare function sitemapPart(dest: string, n: number): string;
|
|
22
24
|
/**
|
|
23
25
|
* The sitemap files for the tree: one at `dest` when it is within `limits`, or else a sitemap index at
|
|
24
26
|
* `dest` and the parts (`sitemapPart`) it lists, each with at most `limits.urls` URLs and `limits.bytes`
|
|
25
|
-
* bytes (a part is closed when the next URL would pass either limit).
|
|
27
|
+
* bytes (a part is closed when the next URL would pass either limit). `alternates` (LANGUAGES: tree path ->
|
|
28
|
+
* [hreflang, URL path] pairs) adds `<xhtml:link rel="alternate">` elements to those pages' entries, and the
|
|
29
|
+
* `xhtml` namespace to every urlset when there is any.
|
|
26
30
|
*/
|
|
27
31
|
export declare function sitemapFiles(tree: Tree, base: string, dest: string, limits?: {
|
|
28
32
|
urls: number;
|
|
29
33
|
bytes: number;
|
|
30
|
-
}): Array<[string, string]>;
|
|
34
|
+
}, alternates?: ReadonlyMap<string, ReadonlyArray<readonly [string, string]>>): Array<[string, string]>;
|
|
31
35
|
export interface FeedDate {
|
|
32
36
|
/** RFC 3339 form written to the feed. */
|
|
33
37
|
readonly text: string;
|
package/lib/src/site.js
CHANGED
|
@@ -31,21 +31,31 @@ export function xmlEscape(s) {
|
|
|
31
31
|
function utf8Compare(a, b) {
|
|
32
32
|
return Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'));
|
|
33
33
|
}
|
|
34
|
-
const
|
|
34
|
+
const SITEMAP_HEAD_PLAIN = '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n';
|
|
35
35
|
const SITEMAP_TAIL = '</urlset>\n';
|
|
36
|
+
/** The urlset head when entries have `xhtml:link` alternates (LANGUAGES). */
|
|
37
|
+
const SITEMAP_HEAD_XHTML = '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">\n';
|
|
36
38
|
/** The sitemaps.org limits of one sitemap file: 50,000 URLs and 50 MiB (52,428,800 bytes) uncompressed. */
|
|
37
39
|
export const SITEMAP_LIMITS = { urls: 50_000, bytes: 52_428_800 };
|
|
38
40
|
/** sitemaps.org XML for every `.html` file in the tree except `/404.html`, sorted by path. */
|
|
39
41
|
export function sitemapXml(tree, base) {
|
|
40
|
-
return
|
|
42
|
+
return SITEMAP_HEAD_PLAIN + sitemapEntries(tree, base).join('') + SITEMAP_TAIL;
|
|
41
43
|
}
|
|
42
|
-
|
|
44
|
+
/** The pages a sitemap lists: every `.html` file except `/404.html`, sorted by path (UTF-8 bytes). */
|
|
45
|
+
export function sitemapPages(tree) {
|
|
43
46
|
return tree
|
|
44
47
|
.entries()
|
|
45
48
|
.map(([p]) => p)
|
|
46
49
|
.filter((p) => p.endsWith('.html') && p !== '/404.html')
|
|
47
|
-
.sort(utf8Compare)
|
|
48
|
-
|
|
50
|
+
.sort(utf8Compare);
|
|
51
|
+
}
|
|
52
|
+
function sitemapEntries(tree, base, alternates) {
|
|
53
|
+
return sitemapPages(tree).map((p) => {
|
|
54
|
+
let links = '';
|
|
55
|
+
for (const [lang, u] of alternates?.get(p) ?? [])
|
|
56
|
+
links += `<xhtml:link rel="alternate" hreflang="${xmlEscape(lang)}" href="${xmlEscape(pageUrl(base, u))}"/>`;
|
|
57
|
+
return ` <url><loc>${xmlEscape(pageUrl(base, p))}</loc>${links}</url>\n`;
|
|
58
|
+
});
|
|
49
59
|
}
|
|
50
60
|
/** `/sitemap.xml` -> `/sitemap-2.xml`: the n-th part of a split sitemap (before the extension, or at the end). */
|
|
51
61
|
export function sitemapPart(dest, n) {
|
|
@@ -56,10 +66,13 @@ export function sitemapPart(dest, n) {
|
|
|
56
66
|
/**
|
|
57
67
|
* The sitemap files for the tree: one at `dest` when it is within `limits`, or else a sitemap index at
|
|
58
68
|
* `dest` and the parts (`sitemapPart`) it lists, each with at most `limits.urls` URLs and `limits.bytes`
|
|
59
|
-
* bytes (a part is closed when the next URL would pass either limit).
|
|
69
|
+
* bytes (a part is closed when the next URL would pass either limit). `alternates` (LANGUAGES: tree path ->
|
|
70
|
+
* [hreflang, URL path] pairs) adds `<xhtml:link rel="alternate">` elements to those pages' entries, and the
|
|
71
|
+
* `xhtml` namespace to every urlset when there is any.
|
|
60
72
|
*/
|
|
61
|
-
export function sitemapFiles(tree, base, dest, limits = SITEMAP_LIMITS) {
|
|
62
|
-
const entries = sitemapEntries(tree, base);
|
|
73
|
+
export function sitemapFiles(tree, base, dest, limits = SITEMAP_LIMITS, alternates) {
|
|
74
|
+
const entries = sitemapEntries(tree, base, alternates);
|
|
75
|
+
const SITEMAP_HEAD = alternates && alternates.size > 0 ? SITEMAP_HEAD_XHTML : SITEMAP_HEAD_PLAIN;
|
|
63
76
|
const frame = utf8Length(SITEMAP_HEAD) + utf8Length(SITEMAP_TAIL);
|
|
64
77
|
const sizes = entries.map(utf8Length);
|
|
65
78
|
const total = frame + sizes.reduce((a, b) => a + b, 0);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/sitefile",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.4",
|
|
4
4
|
"description": "Docker-inspired static artifact builder: compose immutable file trees from local and remote sources, render templates, and export a deployable site. No container runtime, no shell, no runtime dependencies.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"static-site",
|