@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 CHANGED
@@ -1,5 +1,54 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.0.4 (2026-11-09)
4
+
5
+ - **`.tar.zst` / `.tzst` archives** (johnhenry/sitefile#221): `IMPORT … AS tree`, `serve`, `verify` and
6
+ `diff` read Zstandard-compressed tars (detected by magic bytes, like gzip), with the same entry,
7
+ size and ratio limits. TypeScript uses node:zlib's `zstdDecompress`; Rust uses the `ruzstd` crate
8
+ (pure Rust, decode only; new dependency approved by the owner, rationale in rust/Cargo.toml).
9
+ Both read what libzstd reads: several frames, skippable frames, checksums; a window over 128 MiB is
10
+ refused. The E_TYPE message no longer calls zstd unsupported.
11
+ - **hreflang alternates: `LANGUAGES <code>… [DEFAULT <code>]`** (johnhenry/sitefile#303):
12
+ names the site's language folders, so `/en/about.html` and `/fr/about.html` are the same page
13
+ (pages outside the folders are the DEFAULT language's); documents with frontmatter `lang` and
14
+ a shared `translationKey` (rendered by an earlier `RENDER … FOR`) are paired by key instead,
15
+ for different slugs per language. CANONICAL then adds `<link rel="alternate" hreflang="…">`
16
+ for every translation (plus `x-default` for the DEFAULT language's page), and SITEMAP adds
17
+ `xhtml:link` alternates, also in a split sitemap. Unknown language codes and two pages of one
18
+ language in a group are `E_VALIDATION`. Both implementations, with conformance cases, LSP
19
+ hover and completion, grammars; example `examples/hreflang`.
20
+ - **bcrypt entries in `serve --auth-file`** (johnhenry/sitefile#278): `$2y$` (what `htpasswd -B` writes),
21
+ `$2a$` and `$2b$` hashes at cost 4 to 31 are accepted next to `{SHA}`. Keys are the password's UTF-8 bytes
22
+ up to a NUL, at most 72 bytes; digests are compared in constant time. TypeScript has its own
23
+ EksBlowfish (src/bcrypt.ts, no npm dependency); Rust uses the `bcrypt` crate's raw function (new
24
+ dependency approved by the owner, rationale in rust/Cargo.toml). Tested with OpenBSD's and
25
+ htpasswd's vectors in both, and in the `serve-auth` conformance case.
26
+ - **Synced browsing: `serve --watch --sync[=scroll]`** (johnhenry/sitefile#309): opt-in, for
27
+ `serve --watch` and `serve -d --watch` (the record keeps it). Each open page reports its path,
28
+ fragment and title (and with `=scroll` its scroll position) to `POST /__sitefile/client`
29
+ (same origin only, size- and rate-limited, no query strings, form contents, keys or cookies);
30
+ a navigation in one page is sent to the others as `{"type":"navigate"}` (and scrolling as
31
+ `{"type":"scroll"}`), which follow unless a form field has focus. Connected pages are listed
32
+ at `GET /__sitefile/clients` (loopback, non-browser clients only) and logged as `client`
33
+ lines (`{"type":"client",…}` with `--log-format json`), for Sitefile Desktop. Without
34
+ `--sync` nothing changes. Both implementations, with conformance cases.
35
+ - **`serve -d --watch ./dir`, and pages reload after a server restart** (johnhenry/sitefile#304):
36
+ a detached server can watch a plain directory (no Sitefile): it re-reads it on change and
37
+ live-reloads open pages, CSS swaps included; `--poll`/`--poll-interval` apply. The record keeps
38
+ `watch` and `pollMs`, so `server restart` watches again. Every live-reload stream now starts with
39
+ `id: <instance>`, and a page that reconnects with another instance's `Last-Event-ID` (the server
40
+ restarted) is told to reload. Both implementations, with conformance cases.
41
+ - **`IMPORT … AS tree` reads gzip-wrapped Web Bundles** (johnhenry/sitefile#141): after
42
+ gunzip, a Web Bundle is unpacked like a plain `.wbn` instead of failing with `gzip
43
+ content is not a tar archive`, so bundles written by `@johnhenry/fileable`
44
+ (`encode="wbn"`), `@johnhenry/packfile`'s `toArchive()` and `EXPORT … AS wbn COMPRESSION
45
+ gzip` import. Checked-in fixtures from both tools (`test/fixtures/gzip-wbn`) are read
46
+ by both implementations and a conformance case.
47
+ - **`bake` names a gzip Web Bundle target's default output like `build`** (johnhenry/sitefile#151):
48
+ a target with `format: wbn` (or `warc`) and no `output`, whose Sitefile exports in that format
49
+ with `COMPRESSION gzip`, now writes `dist/<target>.wbn.gz` (`.warc.gz`) instead of
50
+ `dist/<target>.wbn`. Both implementations, with a conformance case.
51
+
3
52
  ## 0.0.3 (2026-11-09)
4
53
 
5
54
  - **`serve` keys under `--tls-cert`, and `u`'s network URLs** (johnhenry/sitefile#300): `o` and `u`
package/README.md CHANGED
@@ -76,7 +76,7 @@ no runtime dependencies.
76
76
  | `IMPORT name FROM <dir>\|git+https://…#ref:dir AS sitefile [ARG NAME=value]…` | yes; the stages of another Sitefile, local or from Git, as `name+<stage>` in `FROM` and `--from` (like Earthly targets; `examples/shared-stages`), with its own ARGs and paths, pinned in `Sitefile.lock` |
77
77
  | `ARG NAME[: type] [= value]` | yes, `string`/`number`/`boolean`, `--build-arg` |
78
78
  | `LET NAME[: type] = value` | yes |
79
- | `IMPORT name FROM <path or https URL> [AS file\|text\|json\|yaml\|csv\|markdown\|wbn\|tree] [INTEGRITY sha256:…] [SORT BY key [DESC]] [SCHEMA <file>] [DRAFTS true\|false]` | yes; `AS tree` unpacks tar, tar.gz, zip and Web Bundles; `AS markdown` reads posts with frontmatter (`SCHEMA` checks it against a YAML/JSON schema); `AS yaml`/`csv`/`wbn` give data for templates |
79
+ | `IMPORT name FROM <path or https URL> [AS file\|text\|json\|yaml\|csv\|markdown\|wbn\|tree] [INTEGRITY sha256:…] [SORT BY key [DESC]] [SCHEMA <file>] [DRAFTS true\|false]` | yes; `AS tree` unpacks tar, tar.gz, tar.zst, zip and Web Bundles; `AS markdown` reads posts with frontmatter (`SCHEMA` checks it against a YAML/JSON schema); `AS yaml`/`csv`/`wbn` give data for templates |
80
80
  | `COPY [--overwrite] [--from=<stage>] <source> <dest>` | yes; source is a local path, `name:/path`, `<<EOF` inline content, or with `--from` an absolute path in an earlier stage |
81
81
  | `RENDER [--escape=html] [--overwrite] [--from=<stage>] <template> TO <dest> [FOR item IN list [BY key] [PAGE n [FIRST <dest>]]]` | yes; template is a file or `<<EOF` inline body; `${NAME}`, `${json.path}`, `${#each}`, `${#if}`, `${x\|raw}`; `FOR` renders one page per element, `BY` one per tag, `PAGE` paginates |
82
82
  | `PLUGIN name FROM ./plugins/x.mjs\|x.wasm [INTEGRITY sha256:…]` | yes; a custom renderer: a sandboxed JS module (runs only with `--allow-plugin name`) or an import-free WebAssembly module (no flag needed; see [docs/PLUGINS.md](docs/PLUGINS.md), `examples/wasm/`) |
@@ -84,6 +84,7 @@ no runtime dependencies.
84
84
  | `TOOL name` + `TRANSFORM … WITH name TO <dest> [OPTIONS …] [FOR …] ARGS …` | yes; run an external program (e.g. `ffmpeg`) you allow with `--allow-exec name`: argv only, no shell, temp files, scrubbed environment (see [docs/PLUGINS.md](docs/PLUGINS.md)) |
85
85
  | `SITEMAP BASE <url> [TO <dest>]` | yes; a sitemaps.org `/sitemap.xml` of the `.html` pages so far (a sitemap index and parts above 50,000 URLs or 50 MiB) |
86
86
  | `CANONICAL BASE <url> [PRETTY]` | yes; a `<link rel="canonical">` in every page that has none |
87
+ | `LANGUAGES <code>… [DEFAULT <code>]` | yes; `/en/…`, `/fr/…` folders (or frontmatter `lang` + `translationKey`) are translations: CANONICAL adds `hreflang` alternates, SITEMAP `xhtml:link` alternates (`examples/hreflang/`) |
87
88
  | `FEED <import> BASE <url> LINK <path> [TO <dest>] [TITLE <text>]` | yes; an Atom `/feed.xml` from Markdown posts (`title` and `date` required) |
88
89
  | `ROBOTS [ALLOW\|DISALLOW <path>]… [SITEMAP] [TO <dest>]`, `SECURITY_TXT CONTACT <uri>… EXPIRES <date> [ENCRYPTION <uri>]… [POLICY <uri>]…` | yes; `/robots.txt` (with the SITEMAP URLs) and an RFC 9116 `/.well-known/security.txt` (Expires required; warns when near) |
89
90
  | `REDIRECT <from> <to> [STATUS 301\|302\|303\|307\|308]`, `HEADER <pattern> <Name>: <value>` | yes; `/_redirects` and `/_headers` for Netlify / Cloudflare Pages (and `sitefile serve`); a `wbn` export also bakes HEADER values into each response and exact-path REDIRECTs into 3xx responses (splats stay in `/_redirects`) |
@@ -530,12 +531,12 @@ not published: the npm versions still behave as the rest of that row says.
530
531
  | --- | --- | --- | --- |
531
532
  | fileable, loose output | sitefile | `COPY ./generated/ /` | Works |
532
533
  | fileable, `encode="zip"` | sitefile | `IMPORT gen FROM ./site.zip AS tree`, then `COPY gen:/ /` | Works (same output as loose) |
533
- | fileable, `encode="wbn"` | sitefile | `IMPORT … AS tree` | **Not yet:** it's gzip around a Web Bundle, and `AS tree` reads only plain bundles ([#141](https://github.com/johnhenry/sitefile/issues/141)) |
534
+ | fileable, `encode="wbn"` | sitefile | `IMPORT … AS tree` | **Fixed on main, in the next release:** `AS tree` reads the gzip around the Web Bundle ([#141](https://github.com/johnhenry/sitefile/issues/141)); 0.0.3 and earlier fail with `gzip content is not a tar archive` |
534
535
  | fileable tree, rendered during a build | Sitefile | a JavaScript `TRANSFORM` plugin calling fileable's in-memory `toFiles()` | An example on main, not part of the npm package: [`examples/fileable/`](examples/fileable/) ([#145](https://github.com/johnhenry/sitefile/issues/145)). fileable is vendored into the plugin folder; `cmd`, local `src=` and `env://` fail with `E_PLUGIN` |
535
536
  | sitefile, `EXPORT / AS wbn BASE <url>` | packfile | `fromWebBundle(buffer, { baseURL })` from `@johnhenry/packfile/web-bundle`, then `createRouter(files)` | Works; tested here (`test/packfile-interop.test.ts`), and packfile's own tests read a bundle written by sitefile 0.0.0 |
536
537
  | sitefile `.wbn` | packfile `fromArchive()` | with 0.0.0 / 0.2.0: gzip it, and export with `BASE https://packfile.invalid/` | Works with that workaround. **Fixed on main, in the next release:** `EXPORT … AS wbn COMPRESSION gzip` (or `-o site.wbn.gz`) writes the gzip ([#143](https://github.com/johnhenry/sitefile/issues/143)), and `fromArchive()` takes a `baseURL` or the origin of the bundle's primary URL, so any `BASE` reads back ([packfile#18](https://github.com/johnhenry/packfile/issues/18)) |
537
538
  | sitefile `HEADER` / `REDIRECT` | packfile `createWebBundleRouter()` | -- | **Not applied in 0.0.0:** only the `/_headers` and `/_redirects` files are in the bundle. **Fixed on main, in the next release:** each response carries its HEADER values, and exact-path 301/302/303/307/308 REDIRECTs are 3xx responses with `location` ([#144](https://github.com/johnhenry/sitefile/issues/144)). Splats, `200` rewrites and `404` rules stay in `/_redirects` only |
538
- | packfile `toArchive()` | sitefile | `IMPORT … AS tree` | **Not yet** (same as fileable's `.wbn`, [#141](https://github.com/johnhenry/sitefile/issues/141)) |
539
+ | packfile `toArchive()` | sitefile | `IMPORT … AS tree` | **Fixed on main, in the next release** (same as fileable's `.wbn`, [#141](https://github.com/johnhenry/sitefile/issues/141)); tested here (`test/packfile-interop.test.ts`) |
539
540
 
540
541
  Gotchas when serving a Sitefile bundle with packfile:
541
542
 
package/lib/src/bake.d.ts CHANGED
@@ -21,6 +21,8 @@ export interface BakeTarget {
21
21
  /** `--target <stage>`. */
22
22
  readonly target: string | null;
23
23
  readonly output: string;
24
+ /** No `output` in the bake file: `output` is the default name, `dist/<name>` plus the format's extension. */
25
+ readonly defaultOutput: boolean;
24
26
  readonly format: string | null;
25
27
  readonly tags: readonly string[];
26
28
  /** The matrix values of an expanded target. */
package/lib/src/bake.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { SitefileError } from './errors.js';
4
+ import { collectBuildArgs } from './build-args.js';
5
+ import { planBuild, sitefileCompression } from './executor.js';
4
6
  import { defaultOutName } from './export-formats.js';
5
7
  import { EXPORT_FORMATS, parseExportFormat } from './language/ast.js';
6
8
  import { parseYaml } from './yaml.js';
@@ -231,6 +233,7 @@ function expand(def, bakeDir) {
231
233
  argFiles: (fields['arg-files'] ?? []).map((f) => joinTo(bakeDir, sub('arg-files', f))),
232
234
  target: fields.target !== undefined ? sub('target', fields.target) : null,
233
235
  output: joinTo(bakeDir, fields.output !== undefined ? sub('output', fields.output) : defaultOut),
236
+ defaultOutput: fields.output === undefined,
234
237
  format,
235
238
  tags: (fields.tags ?? []).map((t) => sub('tags', t)),
236
239
  matrix: raw.matrix ? Object.fromEntries(combo) : null,
@@ -309,7 +312,33 @@ function checkConflicts(targets) {
309
312
  }
310
313
  /** Read, check and resolve a bake file. */
311
314
  export async function bakePlan(file, selected) {
312
- return resolveBake(parseBakeDefinition(await loadBakeFile(file), file), file, selected);
315
+ const plan = resolveBake(parseBakeDefinition(await loadBakeFile(file), file), file, selected);
316
+ const targets = await Promise.all(plan.targets.map(compressedDefault));
317
+ if (targets.some((t, i) => t !== plan.targets[i]))
318
+ checkConflicts(targets);
319
+ return { file: plan.file, targets };
320
+ }
321
+ /**
322
+ * A `wbn` or `warc` target with the default output gets the name `build` would give it: `dist/<name>.wbn.gz`
323
+ * (`.warc.gz`) when its Sitefile's EXPORT in that format says `COMPRESSION gzip` (#151). A Sitefile that cannot
324
+ * be planned keeps the plain name; its build reports why.
325
+ */
326
+ async function compressedDefault(t) {
327
+ const format = t.format !== null ? parseExportFormat(t.format) : undefined;
328
+ if (!t.defaultOutput || (format !== 'wbn' && format !== 'warc'))
329
+ return t;
330
+ try {
331
+ const buildArgs = await collectBuildArgs(t.argFiles, Object.entries(t.args).map(([k, v]) => `${k}=${v}`));
332
+ const plan = await planBuild({ contextDir: t.context, sitefile: t.file, buildArgs });
333
+ if (sitefileCompression(plan, format) !== 'gzip')
334
+ return t;
335
+ return { ...t, output: t.output + defaultOutName(format, 'gzip').slice(defaultOutName(format).length) };
336
+ }
337
+ catch (e) {
338
+ if (e instanceof SitefileError)
339
+ return t;
340
+ throw e;
341
+ }
313
342
  }
314
343
  /** `--print --json`. */
315
344
  export function bakePlanJson(plan) {
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Blowfish's initial P-array (18 words) then S-boxes (4 x 256 words): the hexadecimal digits of pi's
3
+ * fractional part, big-endian, base64 (test/bcrypt.test.ts recomputes them from pi).
4
+ */
5
+ export declare const PI_WORDS: string;
6
+ /** Whether `hash` looks like a bcrypt entry at all (`$2a$`, `$2b$`, `$2y$`). */
7
+ export declare const isBcryptPrefix: (hash: string) => boolean;
8
+ /** The parts of a well-formed bcrypt hash (cost 4 to 31, canonical salt and hash encodings), else undefined. */
9
+ export declare function parseBcrypt(hash: string): {
10
+ cost: number;
11
+ salt: Uint8Array;
12
+ digest: Uint8Array;
13
+ } | undefined;
14
+ /**
15
+ * The key bcrypt hashes for `password`: its UTF-8 bytes up to the first NUL (C strings, as htpasswd
16
+ * reads them), then a NUL, at most 72 bytes in all. `$2a$`, `$2b$` and `$2y$` are the same here, as in
17
+ * OpenBSD's and Openwall's current code.
18
+ */
19
+ export declare function bcryptKey(password: string): Uint8Array;
20
+ /** EksBlowfish: the 24 bytes bcrypt computes for `key` (the encoded hash keeps the first 23). */
21
+ export declare function bcryptRaw(cost: number, salt: Uint8Array, key: Uint8Array): Uint8Array;
22
+ /** The bcrypt hash string of `password` with this cost and salt (tests). */
23
+ export declare function bcryptHash(password: string, cost: number, salt: Uint8Array, prefix?: string): string;
24
+ /** Whether `password` matches bcrypt `hash` (false for a malformed one). The digests are compared in constant time. */
25
+ export declare function verifyBcrypt(hash: string, password: string): boolean;
@@ -0,0 +1,201 @@
1
+ // bcrypt (EksBlowfish) password verification for `serve --auth-file` (johnhenry/sitefile#278).
2
+ // rust/src/serve_auth.rs checks the same entries (EksBlowfish from the `bcrypt` crate, parsing and the
3
+ // constant-time comparison as here). Written in-repo rather than as an npm dependency (sitefile has
4
+ // none): node:crypto has no Blowfish with bcrypt's expensive key schedule.
5
+ import { timingSafeEqual } from 'node:crypto';
6
+ /**
7
+ * Blowfish's initial P-array (18 words) then S-boxes (4 x 256 words): the hexadecimal digits of pi's
8
+ * fractional part, big-endian, base64 (test/bcrypt.test.ts recomputes them from pi).
9
+ */
10
+ export const PI_WORDS = 'JD9qiIWjCNMTGYouA3BzRKQJOCIpnzHQCC76mOxObIlFKCHmONATd75UZs806QxswKwpt8l8UN0/hNW1tUcJF5IW1dmJefsb0TEL' +
11
+ 'ppjftawv/XLb0Brft7jhr+1qJn6WunyQRfEsf5kkoZlHs5Fs9wgB8uKFjvwWY2kg2HFXTmmkWP6j9JM9fg2VdI9yjrZYcYvNWIIV' +
12
+ 'Su57VKQdwlpZtZww1Tk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BlywOkQuDsbg4WmNs7TJigvjJ46WSfH5Uy' +
62
+ '4NOS39OgNCuJcfIeGwp0QUujNIzFvnEgw3Yy2N81n42bmS8u5gtvRw/j8R3lTNpUHtrYkc5iec/NPn5vFhixZv0sHQWEj9LF9vsi' +
63
+ 'mfUj81emMnYjk6g1MVbMzQKs8IFiWnXrtW4WNpeI0nPM3pZikoG5SdBMUJAbccZWFObGx70yehQKReHQBsPye5rJqlP9YqgPALsl' +
64
+ 'v+I1vdL2cRJpBbIEAiK2y898zXacK1MRPsAWQOPTOKu9YCVHrfC6OCCc90bOdnevocUgdWBghcv+Torojdh6qvmwTPmqfhlIwlwC' +
65
+ '+4qMAcNq5Nbr4fmQ1PhpplzeoD8JJS3CCOaft05hMs534ltXj9/jOsNy5g==';
66
+ const ALPHABET = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
67
+ /** bcrypt's base64 (its own alphabet, no padding) of `bytes`. */
68
+ function encode(bytes) {
69
+ let out = '';
70
+ for (let i = 0; i < bytes.length; i += 3) {
71
+ const n = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
72
+ const chars = Math.min(4, Math.ceil(((bytes.length - i) * 8) / 6));
73
+ for (let k = 0; k < chars; k++)
74
+ out += ALPHABET[(n >>> (18 - 6 * k)) & 63];
75
+ }
76
+ return out;
77
+ }
78
+ /** `n` bytes from bcrypt base64 `s`, or undefined unless `s` is exactly their canonical encoding. */
79
+ function decode(s, n) {
80
+ const out = new Uint8Array(n);
81
+ let acc = 0;
82
+ let bits = 0;
83
+ let j = 0;
84
+ for (const c of s) {
85
+ const v = ALPHABET.indexOf(c);
86
+ if (v < 0)
87
+ return undefined;
88
+ acc = ((acc << 6) | v) & 0xffffff;
89
+ bits += 6;
90
+ if (bits >= 8) {
91
+ bits -= 8;
92
+ if (j < n)
93
+ out[j++] = (acc >>> bits) & 0xff;
94
+ }
95
+ }
96
+ return j === n && encode(out) === s ? out : undefined;
97
+ }
98
+ /** A bcrypt hash: `$2a$`, `$2b$` or `$2y$`, a cost of 04 to 31, a 22-character salt and a 31-character hash. */
99
+ const BCRYPT_HASH = /^\$2[aby]\$(0[4-9]|[12][0-9]|3[01])\$[./A-Za-z0-9]{53}$/;
100
+ /** Whether `hash` looks like a bcrypt entry at all (`$2a$`, `$2b$`, `$2y$`). */
101
+ export const isBcryptPrefix = (hash) => /^\$2[aby]\$/.test(hash);
102
+ /** The parts of a well-formed bcrypt hash (cost 4 to 31, canonical salt and hash encodings), else undefined. */
103
+ export function parseBcrypt(hash) {
104
+ if (!BCRYPT_HASH.test(hash))
105
+ return undefined;
106
+ const salt = decode(hash.slice(7, 29), 16);
107
+ const digest = decode(hash.slice(29), 23);
108
+ return salt && digest ? { cost: Number(hash.slice(4, 6)), salt, digest } : undefined;
109
+ }
110
+ /**
111
+ * The key bcrypt hashes for `password`: its UTF-8 bytes up to the first NUL (C strings, as htpasswd
112
+ * reads them), then a NUL, at most 72 bytes in all. `$2a$`, `$2b$` and `$2y$` are the same here, as in
113
+ * OpenBSD's and Openwall's current code.
114
+ */
115
+ export function bcryptKey(password) {
116
+ const pw = Buffer.from(password, 'utf8');
117
+ const nul = pw.indexOf(0);
118
+ const bytes = nul < 0 ? pw : pw.subarray(0, nul);
119
+ const key = new Uint8Array(Math.min(bytes.length + 1, 72));
120
+ key.set(bytes.subarray(0, key.length));
121
+ return key;
122
+ }
123
+ /** EksBlowfish: the 24 bytes bcrypt computes for `key` (the encoded hash keeps the first 23). */
124
+ export function bcryptRaw(cost, salt, key) {
125
+ const init = Buffer.from(PI_WORDS, 'base64');
126
+ const P = new Uint32Array(18);
127
+ const S = new Uint32Array(1024);
128
+ for (let i = 0; i < 18; i++)
129
+ P[i] = init.readUInt32BE(4 * i);
130
+ for (let i = 0; i < 1024; i++)
131
+ S[i] = init.readUInt32BE(72 + 4 * i);
132
+ let l = 0;
133
+ let r = 0;
134
+ const f = (x) => (((S[x >>> 24] + S[256 | ((x >>> 16) & 255)]) ^ S[512 | ((x >>> 8) & 255)]) + S[768 | (x & 255)]) | 0;
135
+ const encipher = () => {
136
+ let xl = l ^ P[0];
137
+ let xr = r;
138
+ for (let i = 1; i <= 16; i += 2) {
139
+ xr ^= f(xl) ^ P[i];
140
+ xl ^= f(xr) ^ P[i + 1];
141
+ }
142
+ l = (xr ^ P[17]) >>> 0;
143
+ r = xl >>> 0;
144
+ };
145
+ // The next big-endian word of `data` at `at.i`, cycling through it.
146
+ const word = (data, at) => {
147
+ let w = 0;
148
+ for (let k = 0; k < 4; k++) {
149
+ w = ((w << 8) | data[at.i]) >>> 0;
150
+ at.i = (at.i + 1) % data.length;
151
+ }
152
+ return w;
153
+ };
154
+ const expand = (data, saltStream) => {
155
+ const at = { i: 0 };
156
+ for (let i = 0; i < 18; i++)
157
+ P[i] = P[i] ^ word(data, at);
158
+ const sat = { i: 0 };
159
+ l = 0;
160
+ r = 0;
161
+ for (const t of [P, S]) {
162
+ for (let i = 0; i < t.length; i += 2) {
163
+ if (saltStream) {
164
+ l = (l ^ word(saltStream, sat)) >>> 0;
165
+ r = (r ^ word(saltStream, sat)) >>> 0;
166
+ }
167
+ encipher();
168
+ t[i] = l;
169
+ t[i + 1] = r;
170
+ }
171
+ }
172
+ };
173
+ expand(key, salt);
174
+ for (let n = 2 ** cost; n > 0; n--) {
175
+ expand(key, undefined);
176
+ expand(salt, undefined);
177
+ }
178
+ const out = Buffer.from('OrpheanBeholderScryDoubt', 'latin1');
179
+ for (let b = 0; b < 24; b += 8) {
180
+ l = out.readUInt32BE(b);
181
+ r = out.readUInt32BE(b + 4);
182
+ for (let i = 0; i < 64; i++)
183
+ encipher();
184
+ out.writeUInt32BE(l, b);
185
+ out.writeUInt32BE(r, b + 4);
186
+ }
187
+ return out;
188
+ }
189
+ /** The bcrypt hash string of `password` with this cost and salt (tests). */
190
+ export function bcryptHash(password, cost, salt, prefix = '$2b$') {
191
+ const raw = bcryptRaw(cost, salt, bcryptKey(password));
192
+ return `${prefix}${String(cost).padStart(2, '0')}$${encode(salt)}${encode(raw.subarray(0, 23))}`;
193
+ }
194
+ /** Whether `password` matches bcrypt `hash` (false for a malformed one). The digests are compared in constant time. */
195
+ export function verifyBcrypt(hash, password) {
196
+ const p = parseBcrypt(hash);
197
+ if (!p)
198
+ return false;
199
+ return timingSafeEqual(bcryptRaw(p.cost, p.salt, bcryptKey(password)).subarray(0, 23), p.digest);
200
+ }
201
+ //# sourceMappingURL=bcrypt.js.map
@@ -1,4 +1,5 @@
1
1
  import type { SourceSpan } from './errors.js';
2
+ import { type Languages } from './hreflang.js';
2
3
  import { type Tree } from './tree.js';
3
4
  export interface CanonicalOp {
4
5
  readonly base: string;
@@ -10,7 +11,9 @@ export interface CanonicalOp {
10
11
  export declare function canonicalUrl(base: string, url: string, pretty: boolean): string;
11
12
  /**
12
13
  * The tree with `<link rel="canonical" href="…">` inserted before `</head>` of every `.html`/`.htm` page
13
- * below `root` (except `/404.html` there) that is valid UTF-8 and has no canonical link yet. Pages without
14
- * a `</head>` are left as they are, and named in one warning.
14
+ * below `root` (except `/404.html` there) that is valid UTF-8 and has no canonical link yet. With `langs`
15
+ * (LANGUAGES), a page that has translations also gets a `<link rel="alternate" hreflang="…">` for each
16
+ * (see {@link alternates}), unless it has such links already. Pages without a `</head>` are left as they
17
+ * are, and named in one warning.
15
18
  */
16
- export declare function canonical(tree: Tree, op: CanonicalOp, origin: string, warn: (m: string) => void): Tree;
19
+ export declare function canonical(tree: Tree, op: CanonicalOp, origin: string, warn: (m: string) => void, langs?: Languages): Tree;
@@ -1,4 +1,5 @@
1
- import { canonicalSlot, referenceKind } from './links.js';
1
+ import { alternates } from './hreflang.js';
2
+ import { headLinks, referenceKind } from './links.js';
2
3
  import { pageUrl, xmlEscape } from './site.js';
3
4
  import { makeFile } from './tree.js';
4
5
  const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
@@ -9,18 +10,25 @@ export function canonicalUrl(base, url, pretty) {
9
10
  }
10
11
  /**
11
12
  * The tree with `<link rel="canonical" href="…">` inserted before `</head>` of every `.html`/`.htm` page
12
- * below `root` (except `/404.html` there) that is valid UTF-8 and has no canonical link yet. Pages without
13
- * a `</head>` are left as they are, and named in one warning.
13
+ * below `root` (except `/404.html` there) that is valid UTF-8 and has no canonical link yet. With `langs`
14
+ * (LANGUAGES), a page that has translations also gets a `<link rel="alternate" hreflang="…">` for each
15
+ * (see {@link alternates}), unless it has such links already. Pages without a `</head>` are left as they
16
+ * are, and named in one warning.
14
17
  */
15
- export function canonical(tree, op, origin, warn) {
16
- const files = [];
17
- const headless = [];
18
+ export function canonical(tree, op, origin, warn, langs) {
19
+ const pages = [];
18
20
  for (const [p, node] of tree.entries()) {
19
21
  if (referenceKind(p) !== 'html')
20
22
  continue;
21
23
  const url = op.root === '/' ? p : p.startsWith(op.root + '/') ? p.slice(op.root.length) : undefined;
22
24
  if (url === undefined || url === '/404.html')
23
25
  continue;
26
+ pages.push([p, url, node]);
27
+ }
28
+ const alts = langs ? alternates(pages.map(([p, url]) => [p, url]), langs, 'CANONICAL', op.span) : undefined;
29
+ const files = [];
30
+ const headless = [];
31
+ for (const [p, url, node] of pages) {
24
32
  let text;
25
33
  try {
26
34
  text = UTF8.decode(node.bytes);
@@ -28,15 +36,21 @@ export function canonical(tree, op, origin, warn) {
28
36
  catch {
29
37
  continue;
30
38
  }
31
- const at = canonicalSlot(text);
32
- if (at === 'has')
39
+ const head = headLinks(text);
40
+ const alt = alts?.get(p);
41
+ const addAlternates = alt !== undefined && !head.hreflang;
42
+ if (head.canonical && !addAlternates)
33
43
  continue;
34
- if (at === undefined) {
44
+ if (head.at === undefined) {
35
45
  headless.push(p);
36
46
  continue;
37
47
  }
38
- const link = `<link rel="canonical" href="${xmlEscape(canonicalUrl(op.base, url, op.pretty))}">`;
39
- files.push([p, makeFile(new TextEncoder().encode(text.slice(0, at) + link + text.slice(at)), origin, node.mode)]);
48
+ let links = head.canonical ? '' : `<link rel="canonical" href="${xmlEscape(canonicalUrl(op.base, url, op.pretty))}">`;
49
+ if (addAlternates) {
50
+ for (const [lang, u] of alt)
51
+ links += `<link rel="alternate" hreflang="${xmlEscape(lang)}" href="${xmlEscape(canonicalUrl(op.base, u, op.pretty))}">`;
52
+ }
53
+ files.push([p, makeFile(new TextEncoder().encode(text.slice(0, head.at) + links + text.slice(head.at)), origin, node.mode)]);
40
54
  }
41
55
  if (headless.length > 0) {
42
56
  warn(`${origin}: ${headless.length === 1 ? '1 page has' : `${headless.length} pages have`} no </head>, so no canonical link was added: ${headless.join(', ')}`);
@@ -8,5 +8,8 @@ export declare const LSP_UNAVAILABLE = "'sitefile lsp' (the language server) is
8
8
  export declare const EXTRA_HELP = "\nImages (local store: $SITEFILE_HOME or ~/.sitefile):\n sitefile build [context] -t name[:tag] also store the result as an image (repeatable -t)\n sitefile images [--json] [--digests] [-q] list images (alias: image ls)\n sitefile image inspect <ref> [--json] show an image manifest\n sitefile image prune delete unreferenced manifests and blobs\n sitefile image diff <a> <b> added/removed/changed paths\n sitefile tag <src> <dst> add a name:tag\n sitefile rmi [-f] <ref|id>... remove tags / images\n sitefile save <ref> -o out[.zip|.tar|.tar.gz|.wbn] export an image\n sitefile push <registry/name[:tag]> push a (tagged) image to an OCI registry\n sitefile pull <[registry/]name[:tag][@digest]> pull an image (a bare name means Docker Hub)\n\nIntegrity:\n sitefile build [context] --manifest m.json also write a manifest: every file's size and SHA-256,\n and their Merkle root (save --manifest too)\n sitefile verify <dir|archive|ref> --manifest m.json check a deployed or extracted copy: missing,\n changed and extra files (exit 1 on any)\n sitefile diff <a> <b> [--json] files added, removed and changed between two images,\n directories or archives, and _redirects/_headers rules\n\nVariants:\n sitefile bake [targets...] [-f file] [--print] build several targets (matrix, groups) from\n sitefile.bake.yaml; --print shows the plan\n\nHost config files:\n sitefile import-config <file> [--json] translate netlify.toml, vercel.json, firebase.json,\n staticwebapp.config.json, wrangler.toml or .htaccess\n into _redirects and _headers\n\nOffline builds:\n sitefile vendor [context] [--vendor-dir dir] download remote imports and the BASE image into\n vendor/sitefile; builds then read them from there\n\nPins:\n sitefile outdated [context] [--json] compare remote imports and the BASE image with\n their pins (never changes anything)\n\nNetwork:\n sitefile hosts [context] [--json] list the hosts a build would contact and whether\n --allow-hosts/--network strict allow them (no fetch)\n\nBuild cache (TRANSFORM results: $SITEFILE_HOME/cache/transform):\n sitefile cache info [--json] location, entries, size\n sitefile cache prune [--older-than <days>] delete cached results\n sitefile cache prune --max-size <size> shrink evictable data (LRU) to <size>\n sitefile cache du [--json] size of every cache and the store (alias: cache ls)\n Evictable data over $SITEFILE_CACHE_MAX (default 1GiB, 0 = no limit) is deleted after each build.\n\nServing sites (detached servers are tracked by name):\n sitefile serve [--name n] [-p [host:]port] [-d] [--spa] <ref|./dir|file>\n sitefile serve --watch [-p [host:]port] [ctx] build in memory, serve, rebuild + live reload\n sitefile servers [-a] [--json] list servers (alias: server ls)\n sitefile server stop|rm [-f]|restart|logs [-f] <name|id>\n sitefile up [-f sitefile.servers.yaml] start every server of a servers file (detached, idempotent)\n sitefile down [-f file] stop and remove the servers it started\n sitefile ps [-f file] [--json] list them: running, exited or not created\n\nEditor support:\n sitefile lsp [--stdio] language server over stdio (Rust build only; docs/LSP.md)\n\nRun 'sitefile <command> --help' for the options of a command.\n";
9
9
  export declare function isExtraCommand(name: string | undefined): boolean;
10
10
  export declare function runExtraCommand(argv: readonly string[]): Promise<number>;
11
- /** `serve --open` takes its path only as `--open=<path>`: a bare `--open` (before `--`) is `--open=`. */
11
+ /**
12
+ * `serve --open` and `--sync` take a value only as `--open=<path>`, `--sync=scroll`: a bare `--open`
13
+ * or `--sync` (before `--`) is `--open=`, `--sync=`.
14
+ */
12
15
  export declare function optionalOpen(args: readonly string[]): string[];
@@ -116,9 +116,12 @@ export async function runExtraCommand(argv) {
116
116
  return usageError(`unknown command '${name ?? ''}'`);
117
117
  return runCommand(cmd, name === 'serve' ? optionalOpen(rest) : rest);
118
118
  }
119
- /** `serve --open` takes its path only as `--open=<path>`: a bare `--open` (before `--`) is `--open=`. */
119
+ /**
120
+ * `serve --open` and `--sync` take a value only as `--open=<path>`, `--sync=scroll`: a bare `--open`
121
+ * or `--sync` (before `--`) is `--open=`, `--sync=`.
122
+ */
120
123
  export function optionalOpen(args) {
121
124
  const end = args.indexOf('--');
122
- return args.map((a, i) => (a === '--open' && (end === -1 || i < end) ? '--open=' : a));
125
+ return args.map((a, i) => ((a === '--open' || a === '--sync') && (end === -1 || i < end) ? `${a}=` : a));
123
126
  }
124
127
  //# sourceMappingURL=index.js.map
@@ -4,8 +4,9 @@
4
4
  import { readFile } from 'node:fs/promises';
5
5
  import { SitefileError } from '../errors.js';
6
6
  import { BasicAuth, parseHtpasswd } from '../serve-auth.js';
7
- import { closeServer, createSiteServer, formatUrl, jsonLogLine, listen, parseCidr, parseThrottle, startedLogLine, stoppedLogLine, routingFor } from '../server.js';
7
+ import { BUILDING_EVENT, closeServer, createSiteServer, errorEvent, formatUrl, jsonLogLine, listen, LiveReload, OK_EVENT, parseCidr, parseThrottle, reloadEventFor, startedLogLine, stoppedLogLine, routingFor } from '../server.js';
8
8
  import { loadServedTree, servedLastModified, ServerRegistry, loadServedSite, checkSiteFiles } from '../servers.js';
9
+ import { isIgnoredChange, RebuildScheduler, resolveReal, watchPaths } from '../watch.js';
9
10
  let json = false; // `--log-format json`: every line is a JSON object
10
11
  const stamp = (m) => {
11
12
  const ts = new Date().toISOString();
@@ -27,9 +28,12 @@ async function main() {
27
28
  const { tree, content } = await loadServedSite(reg.store, state.source, { keepOsMetadata: !!state.keepOsMetadata, warn: (m) => stamp(`warning: ${m}`) });
28
29
  if (routingFor(state)?.siteFiles !== false)
29
30
  checkSiteFiles(tree, !!state.strictSiteFiles, (m) => stamp(`warning: ${m}`), content);
30
- const modified = await servedLastModified(reg.store, state.source);
31
+ let modified = await servedLastModified(reg.store, state.source);
32
+ let current = tree;
33
+ // `-d --watch`: the directory is re-read on change and open pages reload (or swap stylesheets).
34
+ const live = state.watch && state.source.kind === 'dir' ? new LiveReload(state.sync === 'nav' || state.sync === 'scroll' ? { sync: state.sync } : {}) : undefined;
31
35
  const authEntries = [...(state.auth ?? []), ...(state.authFile !== undefined ? parseHtpasswd(await readFile(state.authFile, 'utf8'), state.authFile) : [])];
32
- const server = createSiteServer(tree, { spa: state.spa, allowedHosts: state.allowedHosts ?? [], cors: !!state.cors, ...(state.isolate ? { isolate: state.isolate } : {}), ...(state.cache ? { cache: state.cache } : {}), ...(json ? { logFormat: 'json' } : {}), logIp: !!state.logIp, quiet: !!state.quiet, ...(authEntries.length > 0 || state.authFile !== undefined ? { auth: new BasicAuth(authEntries) } : {}), ...(state.maxConnectionsPerIp ? { maxConnectionsPerIp: state.maxConnectionsPerIp } : {}), ...(state.hideBase ? { hideBase: true } : {}), ...(ipRules ? { ipRules } : {}), ...(loopback ? {} : { noindex: true }), clientInfo: true, compress: !!state.compress, ...(state.mime ? { mime: new Map(Object.entries(state.mime)) } : {}), ...(state.throttle !== undefined && parseThrottle(state.throttle) ? { throttle: parseThrottle(state.throttle) } : {}), ...(state.tlsCert !== undefined && state.tlsKey !== undefined ? { tls: { cert: await readFile(state.tlsCert), key: await readFile(state.tlsKey) } } : {}), serverId: id, lastModified: () => modified, log: stamp, ...(content ? { content } : {}), ...(state.country !== undefined ? { country: state.country } : {}), ...(state.spaExclude ? { spaExclude: state.spaExclude } : {}), ...(state.spaFallback !== undefined ? { spaFallback: state.spaFallback } : {}), ...(state.base !== undefined ? { base: state.base } : {}), ...(state.rewriteBase !== undefined ? { rewriteBase: state.rewriteBase } : {}), ...(routingFor(state) ? { profile: routingFor(state) } : {}) });
36
+ const server = createSiteServer(() => current, { ...(live ? { liveReload: live } : {}), spa: state.spa, allowedHosts: state.allowedHosts ?? [], cors: !!state.cors, ...(state.isolate ? { isolate: state.isolate } : {}), ...(state.cache ? { cache: state.cache } : {}), ...(json ? { logFormat: 'json' } : {}), logIp: !!state.logIp, quiet: !!state.quiet, ...(authEntries.length > 0 || state.authFile !== undefined ? { auth: new BasicAuth(authEntries) } : {}), ...(state.maxConnectionsPerIp ? { maxConnectionsPerIp: state.maxConnectionsPerIp } : {}), ...(state.hideBase ? { hideBase: true } : {}), ...(ipRules ? { ipRules } : {}), ...(loopback ? {} : { noindex: true }), clientInfo: true, compress: !!state.compress, ...(state.mime ? { mime: new Map(Object.entries(state.mime)) } : {}), ...(state.throttle !== undefined && parseThrottle(state.throttle) ? { throttle: parseThrottle(state.throttle) } : {}), ...(state.tlsCert !== undefined && state.tlsKey !== undefined ? { tls: { cert: await readFile(state.tlsCert), key: await readFile(state.tlsKey) } } : {}), serverId: id, lastModified: () => modified, log: stamp, ...(content ? { content } : {}), ...(state.country !== undefined ? { country: state.country } : {}), ...(state.spaExclude ? { spaExclude: state.spaExclude } : {}), ...(state.spaFallback !== undefined ? { spaFallback: state.spaFallback } : {}), ...(state.base !== undefined ? { base: state.base } : {}), ...(state.rewriteBase !== undefined ? { rewriteBase: state.rewriteBase } : {}), ...(routingFor(state) ? { profile: routingFor(state) } : {}) });
33
37
  const addr = await listen(server, state.bind.host, state.bind.port);
34
38
  await reg.update(id, { pid: process.pid, host: addr.host, port: addr.port, ready: true, error: undefined });
35
39
  const root = formatUrl(addr.host, addr.port, state.tlsCert !== undefined ? 'https' : 'http');
@@ -38,7 +42,14 @@ async function main() {
38
42
  stamp(startedLogLine(new Date().toISOString(), state.image, tree.size, url));
39
43
  else
40
44
  stamp(`serving ${state.image} (${tree.size} files) at ${url}`);
45
+ const unwatch = live
46
+ ? await watchDirectory(reg, state, live, stamp, (next, lastModified) => {
47
+ current = next;
48
+ modified = lastModified;
49
+ }, () => current)
50
+ : () => undefined;
41
51
  const stop = (signal) => () => {
52
+ unwatch();
42
53
  if (json)
43
54
  stamp(stoppedLogLine(new Date().toISOString(), signal));
44
55
  else
@@ -51,6 +62,7 @@ async function main() {
51
62
  };
52
63
  if (left !== undefined) {
53
64
  setTimeout(() => {
65
+ unwatch();
54
66
  if (json)
55
67
  stamp(stoppedLogLine(new Date().toISOString(), 'expired'));
56
68
  else
@@ -73,6 +85,67 @@ async function main() {
73
85
  process.exit(1);
74
86
  }
75
87
  }
88
+ /**
89
+ * `-d --watch`: watch the served directory (file system events, or polling every `state.pollMs`) and,
90
+ * once changes settle, read it again: a good read is served and open pages are told what changed; a
91
+ * failed one is logged, shown in open pages, and the last good copy stays. Returns a function that stops watching.
92
+ */
93
+ async function watchDirectory(reg, state, live, stamp, swap, current) {
94
+ if (state.source.kind !== 'dir')
95
+ return () => undefined;
96
+ const source = state.source;
97
+ const root = source.path;
98
+ const ignored = [await resolveReal(reg.store.home)];
99
+ const relevant = (p) => !isIgnoredChange(p, [root], ignored);
100
+ const warn = (m) => stamp(`warning: ${m}`);
101
+ const siteFiles = routingFor(state)?.siteFiles !== false;
102
+ /** The site-file warnings last logged: a re-read repeats them only when they change. */
103
+ const warningsOf = (t) => {
104
+ const shown = [];
105
+ if (siteFiles)
106
+ checkSiteFiles(t, false, (m) => shown.push(m));
107
+ return shown.join('\n');
108
+ };
109
+ let lastWarnings = warningsOf(current());
110
+ const scheduler = new RebuildScheduler(async () => {
111
+ stamp('Change detected, re-reading');
112
+ live.send(BUILDING_EVENT);
113
+ try {
114
+ const next = await loadServedTree(reg.store, source, { keepOsMetadata: !!state.keepOsMetadata, warn });
115
+ stamp(`Read ${next.size} file${next.size === 1 ? '' : 's'} (${next.digest()})`);
116
+ const warnings = warningsOf(next);
117
+ if (warnings !== lastWarnings && warnings !== '')
118
+ for (const m of warnings.split('\n'))
119
+ warn(m);
120
+ lastWarnings = warnings;
121
+ if (siteFiles)
122
+ checkSiteFiles(next, !!state.strictSiteFiles, () => undefined);
123
+ const event = reloadEventFor(current(), next, true, false) ?? OK_EVENT;
124
+ swap(next, await servedLastModified(reg.store, source));
125
+ live.send(event);
126
+ }
127
+ catch (e) {
128
+ if (!(e instanceof SitefileError))
129
+ throw e;
130
+ stamp(`error[${e.code}]: ${e.message}`);
131
+ live.send(errorEvent(e));
132
+ stamp('Read failed; serving the last good copy');
133
+ }
134
+ });
135
+ const close = watchPaths({
136
+ dirs: [root],
137
+ files: [],
138
+ onChange: (p) => {
139
+ if (relevant(p))
140
+ scheduler.notify(p);
141
+ },
142
+ ...(state.pollMs !== undefined ? { pollMs: state.pollMs, ignore: (p) => !relevant(p) } : {}),
143
+ });
144
+ return () => {
145
+ close();
146
+ scheduler.close();
147
+ };
148
+ }
76
149
  main().catch((e) => {
77
150
  process.stderr.write(`${e?.stack ?? String(e)}\n`);
78
151
  process.exit(1);