@johnhenry/sitefile 0.0.5 → 0.0.6

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,66 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ## 0.0.6 (2026-11-09)
6
+
7
+ - **`pattern` in schemas** (johnhenry/sitefile#135): a property rule can say
8
+ `pattern: '^[a-z0-9-]+$'`; string values (and each element of a list) must match it, like JSON
9
+ Schema's `pattern`. Patterns are a subset of JavaScript regular expressions (`u` flag: literals,
10
+ classes, `.`, `\d \w \s`, `* + ? {n,m}`, groups, `|`, `^ $`) run by a small engine written for
11
+ both implementations (`src/pattern.ts`, `rust/src/pattern.rs`; no new dependency), linear-time
12
+ (a Pike VM). Invalid patterns are `E_SCHEMA` with the position and reason. Shared test vectors
13
+ (`rust/tests/fixtures/pattern/vectors.json`), a seeded differential fixture (`fuzz.json`) and a
14
+ check that every accepted pattern means what JavaScript's `RegExp` means. `examples/blog`'s schema
15
+ checks tag names with one.
16
+ - **Schema checks in the language server** (johnhenry/sitefile#135): when a Sitefile is opened or
17
+ saved, `sitefile lsp` reads every local `IMPORT … SCHEMA` (documents and schema file, as a build
18
+ reads them, DRAFTS applied) and reports `E_SCHEMA` and friends at the IMPORT line or SCHEMA clause,
19
+ without a build. Remote and Git imports are skipped (the server never fetches); an edit clears
20
+ these diagnostics until the next save. docs/LSP.md describes it.
21
+
22
+ - **The version comes from `package.json`** (johnhenry/sitefile#146): `sitefile --version`, the help
23
+ text and the builder version in build attestations said `0.1.0` in both implementations. TypeScript
24
+ now reads `package.json`; Rust reports `rust/Cargo.toml`'s version (now `0.0.5`), and tests on both
25
+ sides (`test/version.test.ts`, `rust/tests/version.rs`) fail when it differs from `package.json`.
26
+ New conformance case `version`. **Attestation bytes change**: `--provenance` statements record the
27
+ real version (`runDetails.builder.version.sitefile`, as does the SBOM's tool component), so their
28
+ digests and OCI referrer digests differ from earlier builds, and will change with every release.
29
+ Image IDs are unchanged.
30
+ - **Release binaries** (johnhenry/sitefile#69): a new workflow,
31
+ `.github/workflows/release-binaries.yml`, attaches `sitefile-<version>-<target>.tar.gz` for
32
+ macOS (arm64, x86_64) and Linux (x86_64, arm64; glibc), the VS Code extension
33
+ `sitefile-vscode-<version>.vsix` and `SHA256SUMS` to each GitHub Release. It runs after a
34
+ successful npm publish (or on a hand-made release, or by dispatch with a `dry_run` input) and
35
+ publishes nothing itself; publish.yml is unchanged. No Windows build yet (the Rust port uses Unix
36
+ file APIs). README "Install" covers npm, the prebuilt binaries with checksum verification, and
37
+ `cargo install`; docs/RUST.md and the editor READMEs point at the binaries. The MIT `LICENSE`
38
+ was already present and in the npm package.
39
+ - **`serve -d --watch <context>`** (johnhenry/sitefile#306): a detached server can build a Sitefile project. The
40
+ worker runs the in-memory build loop of `serve --watch` (rebuild on change, live reload, error overlay on a
41
+ failed build, the last good build served; a failed first build serves an empty site with the error). It listens
42
+ before the first build, so `serve -d` returns at once. The record keeps the build inputs in a `build` object
43
+ (`sitefile`, `target`, `buildArgs`, `buildArgFiles`, `noCache`, `noLockfile`, `noRewriteBase`) and the page-script
44
+ flags (`noCssInject`, `console`, `noOverlay`, `navigateToChanged`, `keepServiceWorkers`; now also for plain
45
+ directories), so `server restart` keeps them. The `-d --watch` refusals (`… has a Sitefile` and `--<flag> is for
46
+ serve --watch in the foreground, not -d`) are gone; build args are checked when the server is created. Both
47
+ implementations; conformance case `watch/detached-build`; the two `err-serve-detach-watch-*` step cases now cover
48
+ the up-front build-arg and `--rewrite-base` checks.
49
+ - **`serve --reload` without `--watch`** (johnhenry/sitefile#317): servers of images, archive files and
50
+ directory snapshots (foreground or `-d`) inject the live-reload script and serve `/__sitefile/reload`, so pages
51
+ left open reload after a restart (`server restart`, a restart on a new image), using the per-process instance ID
52
+ from #305. With `-d` it is kept in the server record as `"reload": "morph"|"full"` (`servers --json`), and
53
+ `-d --watch` now accepts `--reload` too. `--reload` takes its mode only when the next argument is `full` or
54
+ `morph`, so a bare `--reload` works before the operand; `--reload <other>` is now a bare `--reload` followed by
55
+ an operand (write `--reload=<mode>`). Detached live-reload servers now log the CSP warning. Both
56
+ implementations, conformance cases `reload/detached-image` and `reload/foreground`.
57
+ - **Tag index pages and per-tag feeds** (johnhenry/sitefile#135): templates can group a list with
58
+ `${#each posts by tags as tag}…${/each}` (`tag` is `{ key, count, items }`, grouped exactly like
59
+ `RENDER … FOR … BY`), so one page (`/tags/index.html`) lists every tag with its count; and
60
+ `FEED tag … TO /tags/${tag.key}/feed.xml [TITLE …] FOR tag IN posts BY tags` writes one Atom feed
61
+ per tag. Both implementations, the tree-sitter and VS Code grammars and the language server
62
+ (hover, definitions) know both forms; `examples/blog` uses them.
63
+
3
64
  ## 0.0.5 (2026-11-09)
4
65
 
5
66
  - **`PRECOMPRESS br`** (johnhenry/sitefile#203): Brotli sidecars `<file>.br`, alone or with gzip
package/README.md CHANGED
@@ -53,9 +53,42 @@ npx @johnhenry/sitefile build . # or without installing
53
53
  ```
54
54
 
55
55
  Requires Node.js 26 or later; the npm package has no runtime dependencies.
56
- The Rust binary (faster, and the one that provides `sitefile lsp` for editors)
57
- builds from this repository: `cargo install --path rust`. Prebuilt binaries are
58
- not published yet (johnhenry/sitefile#69).
56
+
57
+ ### Prebuilt binaries
58
+
59
+ The Rust binary is faster and is the one that provides `sitefile lsp` for
60
+ editors. Each [GitHub Release](https://github.com/johnhenry/sitefile/releases)
61
+ after v0.0.5 carries `sitefile-<version>-<target>.tar.gz` for
62
+ `aarch64-apple-darwin`, `x86_64-apple-darwin`, `x86_64-unknown-linux-gnu`
63
+ and `aarch64-unknown-linux-gnu` (each holds `sitefile`, `LICENSE` and
64
+ `README.md`), the VS Code extension `sitefile-vscode-<version>.vsix`, and
65
+ `SHA256SUMS`. Download, verify, and put the binary on `PATH`:
66
+
67
+ ```bash
68
+ v=0.0.6 t=aarch64-apple-darwin # the release you want; a target from the list above
69
+ base=https://github.com/johnhenry/sitefile/releases/download/v$v
70
+ curl -fsSLO "$base/sitefile-$v-$t.tar.gz" -O "$base/SHA256SUMS"
71
+ shasum -a 256 -c --ignore-missing SHA256SUMS # Linux: sha256sum -c --ignore-missing SHA256SUMS
72
+ tar -xzf "sitefile-$v-$t.tar.gz"
73
+ install -m 755 "sitefile-$v-$t/sitefile" ~/.local/bin/ # any directory on PATH
74
+ ```
75
+
76
+ Or with the GitHub CLI: `gh release download v$v -R johnhenry/sitefile -p
77
+ '*aarch64-apple-darwin*' -p SHA256SUMS`. The macOS binaries are not signed or
78
+ notarized: if Gatekeeper blocks a downloaded one, run
79
+ `xattr -d com.apple.quarantine sitefile`. The Linux binaries link glibc
80
+ (built on Ubuntu 22.04, glibc 2.35). There is no Windows build yet: the Rust
81
+ port uses Unix file APIs.
82
+
83
+ ### From source
84
+
85
+ ```bash
86
+ git clone https://github.com/johnhenry/sitefile && cd sitefile
87
+ cargo install --locked --path rust # installs ~/.cargo/bin/sitefile
88
+ ```
89
+
90
+ Needs a stable Rust toolchain (1.85 or later) and a C compiler (`ring` and
91
+ the vendored Brotli encoder are C).
59
92
 
60
93
  `@johnhenry/sitefile` is a new package: it was never published to npm under any
61
94
  name, and `0.0.0` is its first version.
@@ -85,7 +118,7 @@ no runtime dependencies.
85
118
  | `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
119
  | `CANONICAL BASE <url> [PRETTY]` | yes; a `<link rel="canonical">` in every page that has none |
87
120
  | `LANGUAGES <code>… [DEFAULT <code>]` | yes; `/en/…`, `/fr/…` folders (or frontmatter `lang` + `translationKey`) are translations: CANONICAL adds `hreflang` alternates, SITEMAP `xhtml:link` alternates (`examples/hreflang/`) |
88
- | `FEED <import> BASE <url> LINK <path> [TO <dest>] [TITLE <text>]` | yes; an Atom `/feed.xml` from Markdown posts (`title` and `date` required) |
121
+ | `FEED <import> BASE <url> LINK <path> [TO <dest>] [TITLE <text>] [FOR <var> IN <import> BY <key>]` | yes; an Atom `/feed.xml` from Markdown posts (`title` and `date` required), or one feed per tag with `FOR … BY` |
89
122
  | `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) |
90
123
  | `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`) |
91
124
  | `CSP [POLICY <policy>] [META]` | yes; a strict Content-Security-Policy per page in `/_headers` (or a `<meta>`), with the SHA-256 of each inline script and style instead of `'unsafe-inline'` |
@@ -238,7 +271,8 @@ sitefile serve --watch examples/hello # build in memory, serve on 127.0.0.1,
238
271
  Rebuilds are debounced (100 ms) and changes made during a build become one follow-up build. The output
239
272
  directory, `.git`, `Sitefile.lock` and the store are not watched. A failed rebuild prints the error and keeps the
240
273
  last good output (exports are swapped in atomically; `serve --watch` keeps serving the last good build). Live
241
- reload is a small script added to HTML responses only under `serve --watch`, listening on the reserved
274
+ reload is a small script added to HTML responses only under `serve --watch` (or `serve --reload`, which
275
+ reloads pages left open after a server restart), listening on the reserved
242
276
  `/__sitefile/reload` event stream; it is never written to exports. Rebuilds are incremental: steps whose inputs
243
277
  are unchanged (by content digest) are reused from the previous build, in memory, and the result is identical to a
244
278
  clean build (`SITEFILE_NO_INCREMENTAL=1` turns it off). See [docs/CLI.md](docs/CLI.md#watch-mode).
@@ -308,13 +342,16 @@ sites, with a fraction of the memory; see [docs/RUST.md](docs/RUST.md) and
308
342
  Highlighting works on its own; the language features (diagnostics,
309
343
  completion, hover, go to definition, references, rename, outline) come from
310
344
  the Rust binary's language server, `sitefile lsp`
311
- ([docs/LSP.md](docs/LSP.md)), so put it on `PATH` with
312
- `cargo install --path rust` or point the editor at it.
345
+ ([docs/LSP.md](docs/LSP.md)), so put it on `PATH` (a
346
+ [prebuilt binary](#prebuilt-binaries) or `cargo install --path rust`) or
347
+ point the editor at it.
313
348
 
314
349
  - **VS Code**: [editors/vscode/](editors/vscode/), a TextMate grammar plus a
315
350
  language client that starts `sitefile lsp` (`sitefile.server.path`). Not
316
- published; `(cd editors/vscode && npm install && npm run package)`, then
317
- `code --install-extension editors/vscode/sitefile-0.2.0.vsix`.
351
+ on the Marketplace; download `sitefile-vscode-<version>.vsix` from a
352
+ [release](https://github.com/johnhenry/sitefile/releases) and
353
+ `code --install-extension sitefile-vscode-<version>.vsix`, or build it
354
+ (`cd editors/vscode && npm install && npm run package`).
318
355
  - **Zed**: [editors/zed/](editors/zed/), tree-sitter highlighting and the
319
356
  `sitefile-lsp` language server; **zed: install dev extension** on
320
357
  `editors/zed`.
@@ -1,5 +1,6 @@
1
1
  import type { BuildResult, Pins } from './executor.js';
2
2
  import type { Tree } from './tree.js';
3
+ import { SITEFILE_VERSION } from './version.js';
3
4
  /**
4
5
  * Build attestations for OCI site images (`build --provenance` / `--sbom`).
5
6
  *
@@ -19,8 +20,8 @@ import type { Tree } from './tree.js';
19
20
  * or without attestations. Everything is canonical JSON with no timestamps unless SOURCE_DATE_EPOCH
20
21
  * is set, so the same build gives byte-identical attestations (in both implementations).
21
22
  */
22
- /** Sitefile version recorded as the builder version (also `sitefile --version`). */
23
- export declare const SITEFILE_VERSION = "0.1.0";
23
+ /** Sitefile version recorded as the builder version (also `sitefile --version`); from package.json. */
24
+ export { SITEFILE_VERSION };
24
25
  export declare const ATTEST: {
25
26
  /** artifactType of the attestation manifest and media type of its layer. */
26
27
  readonly inToto: 'application/vnd.in-toto+json';
package/lib/src/attest.js CHANGED
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { sha256 } from './digest.js';
4
4
  import { SitefileError } from './errors.js';
5
5
  import { canonicalJson, MEDIA } from './oci.js';
6
+ import { SITEFILE_VERSION } from './version.js';
6
7
  /**
7
8
  * Build attestations for OCI site images (`build --provenance` / `--sbom`).
8
9
  *
@@ -22,8 +23,8 @@ import { canonicalJson, MEDIA } from './oci.js';
22
23
  * or without attestations. Everything is canonical JSON with no timestamps unless SOURCE_DATE_EPOCH
23
24
  * is set, so the same build gives byte-identical attestations (in both implementations).
24
25
  */
25
- /** Sitefile version recorded as the builder version (also `sitefile --version`). */
26
- export const SITEFILE_VERSION = '0.1.0';
26
+ /** Sitefile version recorded as the builder version (also `sitefile --version`); from package.json. */
27
+ export { SITEFILE_VERSION };
27
28
  export const ATTEST = {
28
29
  /** artifactType of the attestation manifest and media type of its layer. */
29
30
  inToto: 'application/vnd.in-toto+json',
@@ -10,6 +10,7 @@ export declare function isExtraCommand(name: string | undefined): boolean;
10
10
  export declare function runExtraCommand(argv: readonly string[]): Promise<number>;
11
11
  /**
12
12
  * `serve --open` and `--sync` take a value only as `--open=<path>`, `--sync=scroll`: a bare `--open`
13
- * or `--sync` (before `--`) is `--open=`, `--sync=`.
13
+ * or `--sync` (before `--`) is `--open=`, `--sync=`. `--reload` takes `full` or `morph` as the next
14
+ * argument too (`--reload full`); followed by anything else (or nothing) it is `--reload=`.
14
15
  */
15
16
  export declare function optionalOpen(args: readonly string[]): string[];
@@ -118,10 +118,19 @@ export async function runExtraCommand(argv) {
118
118
  }
119
119
  /**
120
120
  * `serve --open` and `--sync` take a value only as `--open=<path>`, `--sync=scroll`: a bare `--open`
121
- * or `--sync` (before `--`) is `--open=`, `--sync=`.
121
+ * or `--sync` (before `--`) is `--open=`, `--sync=`. `--reload` takes `full` or `morph` as the next
122
+ * argument too (`--reload full`); followed by anything else (or nothing) it is `--reload=`.
122
123
  */
123
124
  export function optionalOpen(args) {
124
125
  const end = args.indexOf('--');
125
- return args.map((a, i) => ((a === '--open' || a === '--sync') && (end === -1 || i < end) ? `${a}=` : a));
126
+ return args.map((a, i) => {
127
+ if (end !== -1 && i >= end)
128
+ return a;
129
+ if (a === '--open' || a === '--sync')
130
+ return `${a}=`;
131
+ if (a === '--reload' && !(i + 1 < (end === -1 ? args.length : end) && (args[i + 1] === 'full' || args[i + 1] === 'morph')))
132
+ return '--reload=';
133
+ return a;
134
+ });
126
135
  }
127
136
  //# sourceMappingURL=index.js.map
@@ -2,10 +2,17 @@
2
2
  // Detached server process spawned by `sitefile serve -d` / `restart`.
3
3
  // Usage: node serve-worker.js <server id>. State and logs live in $SITEFILE_HOME/servers.
4
4
  import { readFile } from 'node:fs/promises';
5
+ import { collectBuildArgs } from '../build-args.js';
5
6
  import { SitefileError } from '../errors.js';
7
+ import { build } from '../executor.js';
8
+ import { watchMemo } from '../memo.js';
9
+ import { transformCacheDir } from './cache.js';
10
+ import { exportBasePath, productionUrl } from './servers.js';
11
+ import { watchLoop } from './watch.js';
6
12
  import { BasicAuth, parseHtpasswd } from '../serve-auth.js';
7
13
  import { BUILDING_EVENT, closeServer, createSiteServer, errorEvent, formatUrl, jsonLogLine, listen, LiveReload, OK_EVENT, parseCidr, parseThrottle, reloadEventFor, startedLogLine, stoppedLogLine, routingFor } from '../server.js';
8
14
  import { loadServedTree, servedLastModified, ServerRegistry, loadServedSite, checkSiteFiles } from '../servers.js';
15
+ import { Tree } from '../tree.js';
9
16
  import { isIgnoredChange, RebuildScheduler, resolveReal, watchPaths } from '../watch.js';
10
17
  let json = false; // `--log-format json`: every line is a JSON object
11
18
  const stamp = (m) => {
@@ -25,29 +32,56 @@ async function main() {
25
32
  throw new SitefileError('E_SERVER', `server expired at ${state.expires} (--stop-after)`);
26
33
  const ipRules = state.allowIp !== undefined || state.denyIp !== undefined ? { allow: (state.allowIp ?? []).flatMap((t) => parseCidr(t) ?? []), deny: (state.denyIp ?? []).flatMap((t) => parseCidr(t) ?? []) } : undefined;
27
34
  const loopback = state.bind.host === 'localhost' || state.bind.host === '::1' || /^127\./.test(state.bind.host);
28
- const { tree, content } = await loadServedSite(reg.store, state.source, { keepOsMetadata: !!state.keepOsMetadata, warn: (m) => stamp(`warning: ${m}`) });
29
- if (routingFor(state)?.siteFiles !== false)
35
+ // `-d --watch` on a build context (#306): built in memory by watchLoop below, served from an empty
36
+ // tree until the first build finishes.
37
+ const building = !!state.watch && state.source.kind === 'dir' && state.build !== undefined;
38
+ const { tree, content } = building ? { tree: Tree.empty, content: undefined } : await loadServedSite(reg.store, state.source, { keepOsMetadata: !!state.keepOsMetadata, warn: (m) => stamp(`warning: ${m}`) });
39
+ if (!building && routingFor(state)?.siteFiles !== false)
30
40
  checkSiteFiles(tree, !!state.strictSiteFiles, (m) => stamp(`warning: ${m}`), content);
31
- let modified = await servedLastModified(reg.store, state.source);
41
+ let modified = building ? undefined : await servedLastModified(reg.store, state.source);
32
42
  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;
43
+ /** A build context's `--base` / `--rewrite-base`, else what the last good build's EXPORT BASE (or SITEMAP/FEED BASE) gives. */
44
+ let base = state.base;
45
+ let rewriteBase = state.rewriteBase;
46
+ // `-d --watch`: the directory is re-read (or the context rebuilt) on change and open pages reload (or swap stylesheets).
47
+ const watching = !!state.watch && state.source.kind === 'dir';
48
+ // `-d --reload` (without --watch too): the script and stream, so open pages reload after a restart.
49
+ const live = watching || state.reload !== undefined ? new LiveReload(liveOptionsOf(state)) : undefined;
35
50
  const authEntries = [...(state.auth ?? []), ...(state.authFile !== undefined ? parseHtpasswd(await readFile(state.authFile, 'utf8'), state.authFile) : [])];
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) } : {}) });
51
+ const server = createSiteServer(() => current, { ...(live ? { liveReload: live, warn: (m) => stamp(`warning: ${m}`) } : {}), 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 } : {}), ...(building ? { base: () => base, rewriteBase: () => rewriteBase } : { ...(state.base !== undefined ? { base: state.base } : {}), ...(state.rewriteBase !== undefined ? { rewriteBase: state.rewriteBase } : {}) }), ...(routingFor(state) ? { profile: routingFor(state) } : {}) });
37
52
  const addr = await listen(server, state.bind.host, state.bind.port);
38
53
  await reg.update(id, { pid: process.pid, host: addr.host, port: addr.port, ready: true, error: undefined });
39
54
  const root = formatUrl(addr.host, addr.port, state.tlsCert !== undefined ? 'https' : 'http');
40
- const url = `${root}${(state.base ?? '/').slice(1)}`;
41
- if (json)
42
- stamp(startedLogLine(new Date().toISOString(), state.image, tree.size, url));
43
- else
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;
55
+ const served = () => {
56
+ const url = `${root}${(base ?? '/').slice(1)}`;
57
+ if (json)
58
+ stamp(startedLogLine(new Date().toISOString(), state.image, current.size, url));
59
+ else
60
+ stamp(`serving ${state.image} (${current.size} files) at ${url}`);
61
+ };
62
+ if (!building)
63
+ served();
64
+ const unwatch = live && building
65
+ ? watchBuild(state, live, stamp, {
66
+ current: () => current,
67
+ swap: (next) => {
68
+ current = next;
69
+ modified = Math.floor(Date.now() / 1000);
70
+ },
71
+ bases: (b, rb) => {
72
+ if (state.base === undefined)
73
+ base = b;
74
+ if (state.rewriteBase === undefined && !state.build?.noRewriteBase)
75
+ rewriteBase = rb;
76
+ },
77
+ started: served,
78
+ })
79
+ : live && watching
80
+ ? await watchDirectory(reg, state, live, stamp, (next, lastModified) => {
81
+ current = next;
82
+ modified = lastModified;
83
+ }, () => current)
84
+ : () => undefined;
51
85
  const stop = (signal) => () => {
52
86
  unwatch();
53
87
  if (json)
@@ -85,6 +119,90 @@ async function main() {
85
119
  process.exit(1);
86
120
  }
87
121
  }
122
+ /** The live-reload options a detached server's record asks for (`--reload`, `--sync` and the `-d --watch` page-script flags). */
123
+ function liveOptionsOf(state) {
124
+ return {
125
+ resetServiceWorkers: !state.keepServiceWorkers,
126
+ cssInject: !state.noCssInject,
127
+ console: !!state.console,
128
+ overlay: !state.noOverlay,
129
+ navigateToChanged: !!state.navigateToChanged,
130
+ reload: state.reload ?? 'morph',
131
+ ...(state.sync === 'nav' || state.sync === 'scroll' ? { sync: state.sync } : {}),
132
+ };
133
+ }
134
+ /**
135
+ * `-d --watch` on a build context (johnhenry/sitefile#306): build it in memory (like `serve --watch`), then
136
+ * rebuild whenever the context, the Sitefile or a `--build-arg-file` changes. A good build is served and open
137
+ * pages are told what changed; a failed one is logged and shown in open pages, and the last good build stays.
138
+ * The first build runs while the server already listens (on an empty tree). Returns a function that stops it.
139
+ */
140
+ function watchBuild(state, live, stamp, site) {
141
+ const b = state.build ?? {};
142
+ const context = state.source.kind === 'dir' ? state.source.path : '.';
143
+ const cssInject = !state.noCssInject;
144
+ const navigate = !!state.navigateToChanged;
145
+ const siteFilesOn = routingFor(state)?.siteFiles !== false;
146
+ const warn = (m) => stamp(`warning: ${m}`);
147
+ const memo = watchMemo();
148
+ let lastWarnings = '';
149
+ let stop;
150
+ const stopped = new Promise((r) => (stop = r));
151
+ const run = async () => {
152
+ live.send(BUILDING_EVENT);
153
+ try {
154
+ const r = await build({
155
+ contextDir: context,
156
+ ...(b.sitefile !== undefined ? { sitefile: b.sitefile } : {}),
157
+ ...(b.target !== undefined ? { target: b.target } : {}),
158
+ buildArgs: await collectBuildArgs(b.buildArgFiles ?? [], b.buildArgs ?? []),
159
+ ...(b.noLockfile ? { lockfile: false } : {}),
160
+ ...(b.noCache ? {} : { cacheDir: transformCacheDir() }),
161
+ skipBase: true,
162
+ keepOsMetadata: !!state.keepOsMetadata,
163
+ ...(memo ? { memo } : {}),
164
+ onNotice: (m) => stamp(m),
165
+ onWarning: warn,
166
+ });
167
+ stamp(`Built ${r.output.size} file${r.output.size === 1 ? '' : 's'} (${r.output.digest()})`);
168
+ if (siteFilesOn) {
169
+ const shown = [];
170
+ checkSiteFiles(r.output, false, (m) => shown.push(m));
171
+ const text = shown.join('\n');
172
+ if (text !== lastWarnings)
173
+ for (const m of shown)
174
+ warn(m);
175
+ lastWarnings = text;
176
+ checkSiteFiles(r.output, !!state.strictSiteFiles, () => undefined);
177
+ }
178
+ site.bases(exportBasePath(r.plan.exportBase), productionUrl(r.plan));
179
+ const event = reloadEventFor(site.current(), r.output, cssInject, navigate) ?? OK_EVENT;
180
+ site.swap(r.output);
181
+ live.send(event);
182
+ return { code: 0 };
183
+ }
184
+ catch (e) {
185
+ if (!(e instanceof SitefileError))
186
+ throw e;
187
+ stamp(e.code === 'E_USAGE' ? `error: ${e.detail}` : `error[${e.code}]: ${e.message}`);
188
+ live.send(errorEvent(e)); // pages show it (and pages opened later get it on connect)
189
+ return { code: 1 };
190
+ }
191
+ };
192
+ void watchLoop({
193
+ context,
194
+ ...(b.sitefile !== undefined ? { sitefile: b.sitefile } : {}),
195
+ argFiles: b.buildArgFiles ?? [],
196
+ ...(state.pollMs !== undefined ? { pollMs: state.pollMs } : {}),
197
+ build: run,
198
+ onStarted: async () => site.started(),
199
+ stop: stopped,
200
+ say: (line) => stamp(line.replace(/\n$/, '')),
201
+ }).catch((e) => {
202
+ stamp(e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : `error: ${e.message}`);
203
+ });
204
+ return stop;
205
+ }
88
206
  /**
89
207
  * `-d --watch`: watch the served directory (file system events, or polling every `state.pollMs`) and,
90
208
  * once changes settle, read it again: a good read is served and open pages are told what changed; a
@@ -120,7 +238,7 @@ async function watchDirectory(reg, state, live, stamp, swap, current) {
120
238
  lastWarnings = warnings;
121
239
  if (siteFiles)
122
240
  checkSiteFiles(next, !!state.strictSiteFiles, () => undefined);
123
- const event = reloadEventFor(current(), next, true, false) ?? OK_EVENT;
241
+ const event = reloadEventFor(current(), next, !state.noCssInject, !!state.navigateToChanged) ?? OK_EVENT;
124
242
  swap(next, await servedLastModified(reg.store, source));
125
243
  live.send(event);
126
244
  }
@@ -1,5 +1,5 @@
1
1
  import { type CachePreview, type HostProfileName, type HtmlHandling, type SyncMode } from '../server.js';
2
- import { ServerRegistry, type ServerState } from '../servers.js';
2
+ import { ServerRegistry, type ServerState, type WatchBuild } from '../servers.js';
3
3
  import { type AuthEntry } from '../serve-auth.js';
4
4
  import type { Plan } from '../planner.js';
5
5
  import { Store } from '../store.js';
@@ -114,6 +114,16 @@ export interface DetachedServe {
114
114
  readonly pollMs?: number | undefined;
115
115
  /** `--sync` with `-d --watch`. */
116
116
  readonly sync?: SyncMode | undefined;
117
+ /** `--reload`: inject the live-reload script (with or without --watch) in this mode. */
118
+ readonly reload?: 'full' | 'morph' | undefined;
119
+ /** `-d --watch` on a build context: the build inputs. */
120
+ readonly build?: WatchBuild | undefined;
121
+ /** `-d --watch` page-script flags. */
122
+ readonly noCssInject?: boolean | undefined;
123
+ readonly console?: boolean | undefined;
124
+ readonly noOverlay?: boolean | undefined;
125
+ readonly navigateToChanged?: boolean | undefined;
126
+ readonly keepServiceWorkers?: boolean | undefined;
117
127
  /** The servers file it belongs to (`sitefile up`). */
118
128
  readonly project?: string | undefined;
119
129
  }