@johnhenry/sitefile 0.0.2 → 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 +516 -0
- package/README.md +59 -9
- package/lib/src/archive-writers.d.ts +12 -2
- package/lib/src/archive-writers.js +53 -10
- 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 +19 -0
- package/lib/src/canonical.js +60 -0
- package/lib/src/car.d.ts +34 -0
- package/lib/src/car.js +203 -0
- package/lib/src/checklinks.js +8 -2
- package/lib/src/cli/bake.js +4 -3
- package/lib/src/cli/build-image.d.ts +1 -0
- package/lib/src/cli/build-image.js +1 -0
- package/lib/src/cli/common.js +4 -1
- package/lib/src/cli/hosts.d.ts +5 -0
- package/lib/src/cli/hosts.js +78 -0
- package/lib/src/cli/images.js +23 -5
- package/lib/src/cli/import-config.d.ts +2 -0
- package/lib/src/cli/import-config.js +56 -0
- package/lib/src/cli/index.d.ts +6 -1
- package/lib/src/cli/index.js +34 -2
- package/lib/src/cli/integrity.d.ts +2 -0
- package/lib/src/cli/integrity.js +77 -0
- package/lib/src/cli/network.d.ts +7 -0
- package/lib/src/cli/network.js +14 -3
- package/lib/src/cli/serve-keys.d.ts +39 -0
- package/lib/src/cli/serve-keys.js +106 -0
- package/lib/src/cli/serve-worker.js +119 -8
- package/lib/src/cli/servers.d.ts +130 -1
- package/lib/src/cli/servers.js +754 -72
- package/lib/src/cli/up.d.ts +2 -0
- package/lib/src/cli/up.js +193 -0
- package/lib/src/cli/watch.d.ts +14 -1
- package/lib/src/cli/watch.js +20 -3
- package/lib/src/cli.js +138 -18
- package/lib/src/csp.d.ts +17 -0
- package/lib/src/csp.js +52 -0
- package/lib/src/dictionary.d.ts +16 -0
- package/lib/src/dictionary.js +89 -0
- package/lib/src/epub.d.ts +5 -0
- package/lib/src/epub.js +113 -0
- package/lib/src/errors.d.ts +22 -9
- package/lib/src/errors.js +20 -1
- package/lib/src/executor.d.ts +31 -1
- package/lib/src/executor.js +231 -24
- package/lib/src/explain.js +33 -3
- package/lib/src/export-for.d.ts +42 -0
- package/lib/src/export-for.js +466 -0
- package/lib/src/export-formats.d.ts +2 -2
- package/lib/src/export-formats.js +52 -2
- package/lib/src/fingerprint.d.ts +3 -1
- package/lib/src/fingerprint.js +32 -5
- package/lib/src/host-config.d.ts +34 -0
- package/lib/src/host-config.js +645 -0
- package/lib/src/hosts.d.ts +47 -0
- package/lib/src/hosts.js +106 -0
- package/lib/src/hreflang.d.ts +25 -0
- package/lib/src/hreflang.js +72 -0
- package/lib/src/index.d.ts +1 -1
- package/lib/src/index.js +1 -1
- package/lib/src/integrity.d.ts +115 -0
- package/lib/src/integrity.js +273 -0
- package/lib/src/language/ast.d.ts +126 -3
- package/lib/src/language/ast.js +7 -1
- package/lib/src/language/parser.js +189 -7
- package/lib/src/language/validate.js +24 -0
- package/lib/src/links.d.ts +47 -0
- package/lib/src/links.js +289 -3
- package/lib/src/lint.d.ts +1 -1
- package/lib/src/lint.js +26 -1
- package/lib/src/mime-data.d.ts +2 -0
- package/lib/src/mime-data.js +92 -0
- package/lib/src/oci.d.ts +20 -2
- package/lib/src/oci.js +70 -28
- package/lib/src/outdated.d.ts +3 -0
- package/lib/src/outdated.js +4 -4
- package/lib/src/planner.d.ts +87 -2
- package/lib/src/planner.js +189 -8
- package/lib/src/plugins/cache.d.ts +11 -0
- package/lib/src/plugins/cache.js +29 -0
- package/lib/src/plugins/host.d.ts +51 -2
- package/lib/src/plugins/host.js +141 -16
- package/lib/src/plugins/wasm.js +1 -3
- package/lib/src/portable.d.ts +8 -0
- package/lib/src/portable.js +47 -0
- package/lib/src/precache.d.ts +33 -0
- package/lib/src/precache.js +75 -0
- package/lib/src/precompress.d.ts +19 -0
- package/lib/src/precompress.js +35 -0
- package/lib/src/qr.d.ts +18 -0
- package/lib/src/qr.js +372 -0
- package/lib/src/registry-ops.js +4 -2
- package/lib/src/reload-client.d.ts +2 -0
- package/lib/src/reload-client.js +419 -0
- package/lib/src/resources/archive.d.ts +37 -1
- package/lib/src/resources/archive.js +353 -71
- package/lib/src/resources/convert.js +3 -1
- package/lib/src/resources/https.d.ts +9 -1
- package/lib/src/resources/https.js +36 -0
- package/lib/src/resources/network.d.ts +25 -3
- package/lib/src/resources/network.js +77 -6
- package/lib/src/secrets.d.ts +12 -3
- package/lib/src/secrets.js +18 -5
- package/lib/src/serve-auth.d.ts +33 -0
- package/lib/src/serve-auth.js +120 -0
- package/lib/src/serve-rules.d.ts +83 -7
- package/lib/src/serve-rules.js +264 -53
- package/lib/src/server.d.ts +529 -11
- package/lib/src/server.js +1439 -57
- package/lib/src/servers-file.d.ts +36 -0
- package/lib/src/servers-file.js +101 -0
- package/lib/src/servers.d.ts +115 -7
- package/lib/src/servers.js +151 -29
- package/lib/src/single-file.d.ts +12 -0
- package/lib/src/single-file.js +147 -0
- package/lib/src/site.d.ts +58 -0
- package/lib/src/site.js +216 -5
- package/lib/src/store.js +9 -5
- package/lib/src/swbn.d.ts +10 -0
- package/lib/src/swbn.js +86 -0
- package/lib/src/toml.d.ts +17 -0
- package/lib/src/toml.js +323 -0
- package/lib/src/wacz.d.ts +6 -0
- package/lib/src/wacz.js +96 -0
- package/lib/src/warc.d.ts +28 -0
- package/lib/src/warc.js +252 -0
- package/lib/src/watch.d.ts +12 -1
- package/lib/src/watch.js +67 -1
- package/lib/src/wbn.d.ts +9 -1
- package/lib/src/wbn.js +23 -33
- package/lib/src/zstd.d.ts +4 -0
- package/lib/src/zstd.js +328 -0
- package/package.json +1 -1
package/lib/src/cli/servers.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
2
3
|
import { promises as fs } from 'node:fs';
|
|
3
4
|
import net from 'node:net';
|
|
4
5
|
import path from 'node:path';
|
|
@@ -6,14 +7,18 @@ import { fileURLToPath } from 'node:url';
|
|
|
6
7
|
import { SitefileError } from '../errors.js';
|
|
7
8
|
import { collectBuildArgs } from '../build-args.js';
|
|
8
9
|
import { build } from '../executor.js';
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
10
|
+
import { networkOption } from './network.js';
|
|
11
|
+
import { DEFAULT_FETCH_POLICY } from '../resources/types.js';
|
|
12
|
+
import { BUILDING_EVENT, closeServer, createSiteServer, errorEvent, formatUrl, jsonLogLine, listen, logLineAsJson, networkUrls, parseCidr, parseMimeFlag, parseMimeTypes, parseThrottle, startedLogLine, LiveReload, OK_EVENT, parseAllowedHost, reloadEventFor, normalizeBase, safeSegments, normalizeProductionUrl, routingFor, HOST_PROFILES, HTML_HANDLINGS } from '../server.js';
|
|
13
|
+
import { isRunning, loadDirectoryTree, loadServedTree, pidAlive, servedLastModified, ServerRegistry, loadServedSite, checkSiteFiles } from '../servers.js';
|
|
14
|
+
import { BasicAuth, makeVerifier, parseAuthPair, parseHtpasswd } from '../serve-auth.js';
|
|
11
15
|
import { Store } from '../store.js';
|
|
12
16
|
import { Tree } from '../tree.js';
|
|
13
17
|
import { transformCacheDir } from './cache.js';
|
|
14
18
|
import { requireArgs, str, strs, table, usage, usageError } from './common.js';
|
|
15
19
|
import { watchMemo } from '../memo.js';
|
|
16
|
-
import { watchLoop } from './watch.js';
|
|
20
|
+
import { pollOption, watchLoop } from './watch.js';
|
|
21
|
+
import { CLEAR, KEYS_HELP, KEYS_HINT, openBrowser, openUrl, qrText, readKeys, serveUrls, urlsText } from './serve-keys.js';
|
|
17
22
|
const WORKER = fileURLToPath(new URL('./serve-worker.js', import.meta.url));
|
|
18
23
|
/** `-p` value: `port`, `host:port` or `[v6]:port`. Default bind is 127.0.0.1 with a free port. */
|
|
19
24
|
export function parsePublish(spec) {
|
|
@@ -33,11 +38,90 @@ export function parsePublish(spec) {
|
|
|
33
38
|
return { host, port };
|
|
34
39
|
}
|
|
35
40
|
const isWildcard = (h) => h === '0.0.0.0' || h === '::';
|
|
41
|
+
/** `--spa`, `--spa-exclude` and `--spa-fallback` (which implies `--spa`), as server options. */
|
|
42
|
+
export function spaOptions(v) {
|
|
43
|
+
const exclude = strs(v['spa-exclude']);
|
|
44
|
+
for (const g of exclude)
|
|
45
|
+
if (!g.startsWith('/'))
|
|
46
|
+
usage(`--spa-exclude expects a path pattern starting with '/', got '${g}'`);
|
|
47
|
+
const raw = str(v['spa-fallback']);
|
|
48
|
+
let fallback;
|
|
49
|
+
if (raw !== undefined) {
|
|
50
|
+
const segs = safeSegments('/' + raw.replace(/^\/+/, ''));
|
|
51
|
+
if (!segs || segs.length === 0)
|
|
52
|
+
usage(`--spa-fallback expects a file of the site such as /200.html, got '${raw}'`);
|
|
53
|
+
fallback = '/' + segs.join('/');
|
|
54
|
+
}
|
|
55
|
+
const spa = !!v.spa || fallback !== undefined;
|
|
56
|
+
if (!spa && exclude.length > 0)
|
|
57
|
+
usage('--spa-exclude needs --spa');
|
|
58
|
+
return { spa, ...(exclude.length > 0 ? { spaExclude: exclude } : {}), ...(fallback !== undefined ? { spaFallback: fallback } : {}) };
|
|
59
|
+
}
|
|
60
|
+
/** A warning when `--spa-fallback` names a file the site does not have. */
|
|
61
|
+
function warnSpaFallback(tree, fallback, warn) {
|
|
62
|
+
if (fallback !== undefined && !tree.isFile(fallback))
|
|
63
|
+
warn(`--spa-fallback ${fallback} is not a file of the site, so navigations to missing paths get 404`);
|
|
64
|
+
}
|
|
65
|
+
/** `--base`: the path prefix to serve under (`/repo/`), or undefined for `/`. */
|
|
66
|
+
export function parseBase(v) {
|
|
67
|
+
if (v === undefined)
|
|
68
|
+
return undefined;
|
|
69
|
+
const b = normalizeBase(v);
|
|
70
|
+
if (b === undefined)
|
|
71
|
+
usage(`--base expects a path such as /repo/, got '${v}'`);
|
|
72
|
+
return b === '/' ? undefined : b;
|
|
73
|
+
}
|
|
74
|
+
/** The URL a server answers at: its origin and `--base`. */
|
|
75
|
+
const siteUrl = (host, port, base, scheme = 'http') => formatUrl(host, port, scheme) + (base ?? '/').slice(1);
|
|
76
|
+
/** The path of an EXPORT BASE that is an http(s) URL (`https://user.github.io/repo/` → `/repo/`), else undefined. */
|
|
77
|
+
export function exportBasePath(exportBase) {
|
|
78
|
+
if (exportBase === undefined || !/^https?:\/\//i.test(exportBase))
|
|
79
|
+
return undefined;
|
|
80
|
+
const b = normalizeBase(exportBase);
|
|
81
|
+
return b === '/' ? undefined : b;
|
|
82
|
+
}
|
|
83
|
+
/** `--rewrite-base <url>`: the production URL, normalized; usage error when it is not an http(s) URL. */
|
|
84
|
+
export function parseRewriteBase(v) {
|
|
85
|
+
if (v === undefined)
|
|
86
|
+
return undefined;
|
|
87
|
+
const u = normalizeProductionUrl(v);
|
|
88
|
+
if (u === undefined)
|
|
89
|
+
usage(`--rewrite-base expects the production URL such as https://example.com/, got '${v}'`);
|
|
90
|
+
return u;
|
|
91
|
+
}
|
|
92
|
+
/** A build's production URL (`serve --watch`): its EXPORT BASE when that is an http(s) URL, else the first SITEMAP or FEED BASE. */
|
|
93
|
+
export function productionUrl(plan) {
|
|
94
|
+
if (plan.exportBase !== undefined && /^https?:\/\//i.test(plan.exportBase))
|
|
95
|
+
return normalizeProductionUrl(plan.exportBase);
|
|
96
|
+
for (const st of plan.stages)
|
|
97
|
+
for (const op of st.operations)
|
|
98
|
+
if (op.kind === 'SITEMAP' || op.kind === 'FEED')
|
|
99
|
+
return normalizeProductionUrl(op.base);
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
/** `--host-profile` and `--html-handling`, checked: the names, or usage errors. */
|
|
103
|
+
export function profileOptions(v) {
|
|
104
|
+
const p = str(v['host-profile']);
|
|
105
|
+
const h = str(v['html-handling']);
|
|
106
|
+
if (p !== undefined && !HOST_PROFILES.includes(p))
|
|
107
|
+
usage(`--host-profile expects one of ${HOST_PROFILES.join(', ')}, got '${p}'`);
|
|
108
|
+
if (h !== undefined && !HTML_HANDLINGS.includes(h))
|
|
109
|
+
usage(`--html-handling expects one of ${HTML_HANDLINGS.join(', ')}, got '${h}'`);
|
|
110
|
+
return { ...(p !== undefined ? { hostProfile: p } : {}), ...(h !== undefined ? { htmlHandling: h } : {}) };
|
|
111
|
+
}
|
|
112
|
+
/** `--country`: an ISO 3166-1 alpha-2 code (any case). */
|
|
113
|
+
export function parseCountry(v) {
|
|
114
|
+
if (v === undefined)
|
|
115
|
+
return undefined;
|
|
116
|
+
if (!/^[A-Za-z]{2}$/.test(v))
|
|
117
|
+
usage(`--country expects a two-letter country code such as nz, got '${v}'`);
|
|
118
|
+
return v;
|
|
119
|
+
}
|
|
36
120
|
async function isFile(p) {
|
|
37
121
|
return fs.stat(p).then((s) => s.isFile(), () => false);
|
|
38
122
|
}
|
|
39
123
|
/** An archive file source: labelled by its absolute path, stored by its real path. */
|
|
40
|
-
async function archiveSource(arg) {
|
|
124
|
+
export async function archiveSource(arg) {
|
|
41
125
|
const file = path.resolve(arg);
|
|
42
126
|
return { label: file, source: { kind: 'archive', path: await fs.realpath(file).catch(() => file) } };
|
|
43
127
|
}
|
|
@@ -45,7 +129,7 @@ async function archiveSource(arg) {
|
|
|
45
129
|
* A directory or archive file when `arg` looks like a path, else an image reference or ID, else an
|
|
46
130
|
* archive file by that name (`site.zip`). Whether a file is an archive is checked when it is loaded.
|
|
47
131
|
*/
|
|
48
|
-
async function resolveSource(store, arg) {
|
|
132
|
+
export async function resolveSource(store, arg) {
|
|
49
133
|
if (/^(\.\.?|~.*|\.\.?\/.*|\/.*|.*\/)$/.test(arg)) {
|
|
50
134
|
const dir = path.resolve(arg);
|
|
51
135
|
if (await isFile(dir))
|
|
@@ -105,26 +189,120 @@ async function startDetached(reg, state) {
|
|
|
105
189
|
const run = {
|
|
106
190
|
name: 'serve',
|
|
107
191
|
summary: 'serve an image, directory or archive file over HTTP',
|
|
108
|
-
usage: 'serve [--name n] [-p [host:]port] [-d] [--spa] <ref|id|./dir|file> | serve --watch [options] [context]',
|
|
109
|
-
description: 'Serve an image from the local store, a directory (paths starting with ./, ../ or /), or an archive file over HTTP:\nzip, tar, tar.gz, wbn, or an OCI archive as build -o x.oci.tar and save write it (the format is read from the\nbytes). A directory or archive is a snapshot read at start. GET and HEAD only; no directory listings.\nBinds 127.0.0.1 on a free port unless -p is given;\n0.0.0.0 is bound only when you pass it explicitly. Foreground by default (Ctrl-C stops it); -d detaches and\nrecords the server for servers, server stop, rm, logs and restart.\n\nWith --watch the argument is a build context (default .): its Sitefile is built in memory and served, rebuilt\nwhen the context, the Sitefile or a --build-arg-file changes, and open pages reload after each good rebuild\n(
|
|
192
|
+
usage: 'serve [--name n] [-p [host:]port] [-d] [--spa] <ref|id|./dir|file> | serve [-d] --watch [options] [context]',
|
|
193
|
+
description: 'Serve an image from the local store, a directory (paths starting with ./, ../ or /), or an archive file over HTTP:\nzip, tar, tar.gz, wbn, or an OCI archive as build -o x.oci.tar and save write it (the format is read from the\nbytes). A directory or archive is a snapshot read at start. GET and HEAD only; no directory listings.\nBinds 127.0.0.1 on a free port unless -p is given;\n0.0.0.0 is bound only when you pass it explicitly. Foreground by default (Ctrl-C stops it); -d detaches and\nrecords the server for servers, server stop, rm, logs and restart.\n\nWith --watch the argument is a build context (default .): its Sitefile is built in memory and served, rebuilt\nwhen the context, the Sitefile or a --build-arg-file changes, and open pages reload after each good rebuild\n(page loads get a small script, /__sitefile/reload.js). A failed rebuild keeps serving the last\ngood build. Nothing is written to the context except Sitefile.lock. A directory with no Sitefile (and no -f,\n--target or --build-arg*) is served as it is and re-read on change. When only stylesheets changed, pages\nswap them in place. With -d, --watch takes such a directory only: the detached server re-reads it on change,\nopen pages reload, and pages left open across server restart reload once it is back.',
|
|
110
194
|
flags: [
|
|
111
195
|
'--name <n> name for the server (-d only; default site-<6 hex>)',
|
|
112
196
|
'-p, --publish <[host:]port> address to bind (default 127.0.0.1, a free port)',
|
|
113
197
|
'-d, --detach run in the background and print the server ID',
|
|
114
198
|
'--spa serve /index.html for unknown paths without a file extension',
|
|
115
|
-
'--
|
|
199
|
+
'--cors Access-Control-Allow-Origin: * on every response and OPTIONS preflights (204)',
|
|
200
|
+
'--isolate cross-origin isolation headers (COOP same-origin, COEP, CORP same-origin) on every response',
|
|
201
|
+
'--coep <require-corp|credentialless> the Cross-Origin-Embedder-Policy of --isolate (default require-corp)',
|
|
202
|
+
'--max-age <secs> preview production caching: Cache-Control: public, max-age=<secs> on files other than HTML',
|
|
203
|
+
'--immutable add immutable to the --max-age value (fingerprinted assets)',
|
|
204
|
+
'--max-age-html <secs> Cache-Control: public, max-age=<secs> on HTML pages too (default: they keep no-cache)',
|
|
205
|
+
'--log-format <text|json> access-log lines as text (default) or one JSON object per line (a stable format; docs/CLI.md)',
|
|
206
|
+
'--log-ip add the client address to access-log lines',
|
|
207
|
+
'--quiet no access-log lines',
|
|
208
|
+
'--auth <user:password> require HTTP basic authentication (repeatable; or SITEFILE_SERVE_AUTH); only a hash is stored',
|
|
209
|
+
'--auth-file <htpasswd> users from an htpasswd file ({SHA} or bcrypt: htpasswd -s or -B)',
|
|
210
|
+
'--max-connections-per-ip <n> open connections one non-loopback client may hold (default 0: no limit; 503 over it)',
|
|
211
|
+
'--random-route serve the site only under a random secret path (printed in the URL)',
|
|
212
|
+
'--allow-ip <cidr> only answer clients in this block (repeatable; loopback is always allowed)',
|
|
213
|
+
'--deny-ip <cidr> refuse clients in this block (repeatable; checked first)',
|
|
214
|
+
'--stop-after <n>[s|m|h|d] stop the server after this long (not with --watch)',
|
|
215
|
+
'--tls-cert <pem> serve HTTPS with this certificate chain (with --tls-key; or SITEFILE_TLS_CERT)',
|
|
216
|
+
'--tls-key <pem> the private key of --tls-cert (or SITEFILE_TLS_KEY); read at start, never copied',
|
|
217
|
+
'--compress gzip text, JSON, SVG, wasm ... files (1 KiB or more) on the fly (precompressed .br/.gz are always used)',
|
|
218
|
+
'--throttle <3g|slow-3g|kbit[/ms]> limit response bandwidth and add latency (e.g. 400/400)',
|
|
219
|
+
'--mime <ext=type> serve files with this extension as this content type (repeatable; before the built-in table)',
|
|
220
|
+
'--mime-file <mime.types> content types from an nginx or Apache mime.types file (--mime wins)',
|
|
221
|
+
'--allowed-host <name> also answer requests for this Host (repeatable; .example.com: and subdomains; *: any)',
|
|
222
|
+
'--proxy </prefix=url> forward GET/HEAD under /prefix to url + the rest of the path (repeatable; its host is allowed)',
|
|
223
|
+
'--allow-hosts <hosts> hosts _redirects proxy rules (200 to a URL) may reach (repeatable; also $SITEFILE_ALLOW_HOSTS)',
|
|
224
|
+
'--deny-hosts <hosts> hosts never proxied to; beats --allow-hosts and --proxy (also $SITEFILE_DENY_HOSTS)',
|
|
225
|
+
'--allow-http proxy to plain http:// URLs',
|
|
226
|
+
'--allow-private-network proxy to loopback/private addresses (localhost:3000 needs it)',
|
|
227
|
+
'--connect-timeout <ms> proxy connect time limit; --read-timeout <ms>: longest wait for data',
|
|
228
|
+
'--read-timeout <ms> (see --connect-timeout)',
|
|
229
|
+
'--spa answer page navigations to missing paths with the nearest 200.html or index.html',
|
|
230
|
+
'--spa-exclude <glob> paths that never fall back to the app shell (* matches anything; repeatable)',
|
|
231
|
+
'--spa-fallback <path> the file every --spa fallback serves, e.g. /app.html (implies --spa)',
|
|
232
|
+
'--base <path> serve the site under this path, e.g. /repo/ for a GitHub Pages project site (--watch: default the EXPORT BASE URL\'s path)',
|
|
233
|
+
'--rewrite-base <url> replace this production URL with the local one in served HTML, CSS and XML (--watch: on by default, from EXPORT/SITEMAP/FEED BASE)',
|
|
234
|
+
'--no-rewrite-base --watch: leave production URLs as they are',
|
|
235
|
+
'--host-profile <host> route like netlify, cloudflare, vercel, github-pages or firebase (clean URLs, site files, 404s)',
|
|
236
|
+
'--html-handling <mode> auto, force-slash, drop-slash or none: canonical page URLs (Cloudflare\'s modes)',
|
|
237
|
+
'--country <code> the country _redirects Country= conditions match (there is no geolocation locally)',
|
|
238
|
+
'--strict-site-files refuse to serve when a _redirects or _headers line would be ignored',
|
|
239
|
+
'--keep-os-metadata serve __MACOSX, ._*, Thumbs.db and desktop.ini of a directory or archive (default: skipped)',
|
|
240
|
+
'--open[=<path>] open the site (at <path>) in the browser once it is served ($BROWSER, else the system default)',
|
|
241
|
+
'--qr print a QR code of the network URL (with -p 0.0.0.0:...), else of the local URL',
|
|
242
|
+
'--watch build the context, serve it, rebuild on change and live-reload pages (-d: a plain directory only)',
|
|
116
243
|
'-f, --file <path> Sitefile path (--watch; default <context>/Sitefile)',
|
|
117
244
|
'--target <stage> build up to this stage and serve its whole tree (--watch)',
|
|
118
245
|
'--build-arg <NAME=value> set an ARG (--watch; repeatable)',
|
|
119
246
|
'--build-arg-file <path> read ARGs from a .json, .yaml/.yml or .env file (--watch; repeatable)',
|
|
120
247
|
'--no-cache do not use the TRANSFORM result cache (--watch)',
|
|
121
248
|
'--no-lockfile do not read or write Sitefile.lock (--watch)',
|
|
249
|
+
'--keep-service-workers do not unregister service workers and clear caches before a reload (--watch)',
|
|
250
|
+
'--poll poll for changes (every 1000 ms) instead of file system events (--watch, -d --watch)',
|
|
251
|
+
'--poll-interval <ms> poll every <ms> milliseconds (--watch, -d --watch; implies --poll)',
|
|
252
|
+
'--no-css-inject reload the page when only stylesheets changed, instead of swapping them (--watch)',
|
|
253
|
+
'--console also forward console.log/info from pages to the log, not only errors and warnings (--watch)',
|
|
254
|
+
'--no-overlay no Rebuilding badge or build-error overlay in pages (--watch)',
|
|
255
|
+
'--navigate-to-changed after a rebuild that changed one page, open pages go to it (--watch)',
|
|
256
|
+
'--reload <full|morph> morph (default): update a page in place when only HTML changed; full: always reload (--watch)',
|
|
257
|
+
'--sync[=scroll] open pages report where they are and follow each other\'s navigation (=scroll: and scrolling) (--watch, -d --watch)',
|
|
122
258
|
],
|
|
123
259
|
options: {
|
|
124
260
|
name: { type: 'string' },
|
|
125
261
|
publish: { type: 'string', short: 'p' },
|
|
126
262
|
detach: { type: 'boolean', short: 'd' },
|
|
127
263
|
spa: { type: 'boolean' },
|
|
264
|
+
'spa-exclude': { type: 'string', multiple: true },
|
|
265
|
+
'spa-fallback': { type: 'string' },
|
|
266
|
+
base: { type: 'string' },
|
|
267
|
+
'host-profile': { type: 'string' },
|
|
268
|
+
'html-handling': { type: 'string' },
|
|
269
|
+
'rewrite-base': { type: 'string' },
|
|
270
|
+
'no-rewrite-base': { type: 'boolean' },
|
|
271
|
+
country: { type: 'string' },
|
|
272
|
+
'strict-site-files': { type: 'boolean' },
|
|
273
|
+
'keep-os-metadata': { type: 'boolean' },
|
|
274
|
+
'allowed-host': { type: 'string', multiple: true },
|
|
275
|
+
proxy: { type: 'string', multiple: true },
|
|
276
|
+
'allow-hosts': { type: 'string', multiple: true },
|
|
277
|
+
'deny-hosts': { type: 'string', multiple: true },
|
|
278
|
+
'allow-http': { type: 'boolean' },
|
|
279
|
+
'allow-private-network': { type: 'boolean' },
|
|
280
|
+
'connect-timeout': { type: 'string' },
|
|
281
|
+
'read-timeout': { type: 'string' },
|
|
282
|
+
cors: { type: 'boolean' },
|
|
283
|
+
open: { type: 'string' },
|
|
284
|
+
qr: { type: 'boolean' },
|
|
285
|
+
isolate: { type: 'boolean' },
|
|
286
|
+
coep: { type: 'string' },
|
|
287
|
+
'max-age': { type: 'string' },
|
|
288
|
+
immutable: { type: 'boolean' },
|
|
289
|
+
'max-age-html': { type: 'string' },
|
|
290
|
+
'log-format': { type: 'string' },
|
|
291
|
+
'log-ip': { type: 'boolean' },
|
|
292
|
+
quiet: { type: 'boolean' },
|
|
293
|
+
auth: { type: 'string', multiple: true },
|
|
294
|
+
'auth-file': { type: 'string' },
|
|
295
|
+
'max-connections-per-ip': { type: 'string' },
|
|
296
|
+
'random-route': { type: 'boolean' },
|
|
297
|
+
'allow-ip': { type: 'string', multiple: true },
|
|
298
|
+
'deny-ip': { type: 'string', multiple: true },
|
|
299
|
+
'stop-after': { type: 'string' },
|
|
300
|
+
'tls-cert': { type: 'string' },
|
|
301
|
+
compress: { type: 'boolean' },
|
|
302
|
+
throttle: { type: 'string' },
|
|
303
|
+
mime: { type: 'string', multiple: true },
|
|
304
|
+
'mime-file': { type: 'string' },
|
|
305
|
+
'tls-key': { type: 'string' },
|
|
128
306
|
watch: { type: 'boolean' },
|
|
129
307
|
file: { type: 'string', short: 'f' },
|
|
130
308
|
target: { type: 'string' },
|
|
@@ -132,89 +310,571 @@ const run = {
|
|
|
132
310
|
'build-arg-file': { type: 'string', multiple: true },
|
|
133
311
|
'no-cache': { type: 'boolean' },
|
|
134
312
|
'no-lockfile': { type: 'boolean' },
|
|
313
|
+
'keep-service-workers': { type: 'boolean' },
|
|
314
|
+
poll: { type: 'boolean' },
|
|
315
|
+
'poll-interval': { type: 'string' },
|
|
316
|
+
'no-css-inject': { type: 'boolean' },
|
|
317
|
+
console: { type: 'boolean' },
|
|
318
|
+
'no-overlay': { type: 'boolean' },
|
|
319
|
+
'navigate-to-changed': { type: 'boolean' },
|
|
320
|
+
reload: { type: 'string' },
|
|
321
|
+
sync: { type: 'string' },
|
|
135
322
|
},
|
|
136
323
|
async run(v, pos) {
|
|
137
|
-
if (v.watch)
|
|
324
|
+
if (v.watch && !v.detach)
|
|
138
325
|
return serveWatch(v, pos);
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
326
|
+
// `-d --watch`: a plain directory, re-read on change by the detached worker (with live reload).
|
|
327
|
+
const watchDetached = !!v.watch;
|
|
328
|
+
for (const f of WATCH_ONLY) {
|
|
329
|
+
if (v[f] === undefined || (watchDetached && DETACHED_WATCH.includes(f)))
|
|
330
|
+
continue;
|
|
331
|
+
usage(watchDetached ? `--${f} is for serve --watch in the foreground, not -d` : `--${f} needs --watch`);
|
|
332
|
+
}
|
|
333
|
+
if (watchDetached)
|
|
334
|
+
requireArgs(pos, 0, 1, 'a directory');
|
|
335
|
+
else
|
|
336
|
+
requireArgs(pos, 1, 1, 'an image reference, ./directory or archive file');
|
|
337
|
+
const pollMs = watchDetached ? pollOption(!!v.poll, str(v['poll-interval'])) : undefined;
|
|
338
|
+
const sync = watchDetached ? syncOf(v) : undefined;
|
|
143
339
|
const bind = parsePublish(str(v.publish));
|
|
340
|
+
const allowedHosts = allowedHostsOf(v);
|
|
341
|
+
const isolate = isolateOf(v);
|
|
342
|
+
const cache = cacheOf(v);
|
|
343
|
+
const logging = loggingOf(v);
|
|
344
|
+
const auth = await authOf(v, bind.host);
|
|
345
|
+
const perIp = perIpOf(v);
|
|
346
|
+
const sharing = sharingOf(v, bind.host);
|
|
347
|
+
const tls = await tlsOf(v);
|
|
348
|
+
const throttle = throttleOf(v);
|
|
349
|
+
const mime = await mimeOf(v);
|
|
350
|
+
const spa = spaOptions(v);
|
|
351
|
+
const base = sharing.randomBase ?? parseBase(str(v.base));
|
|
352
|
+
const rewriteBase = parseRewriteBase(str(v['rewrite-base']));
|
|
353
|
+
const profiles = profileOptions(v);
|
|
354
|
+
const profile = routingFor(profiles);
|
|
355
|
+
const country = parseCountry(str(v.country));
|
|
356
|
+
const strictSiteFiles = !!v['strict-site-files'];
|
|
144
357
|
const name = str(v.name);
|
|
145
358
|
if (name !== undefined && !v.detach)
|
|
146
359
|
usage('--name needs -d (only detached servers are tracked)');
|
|
147
360
|
const store = await Store.open();
|
|
148
|
-
const { label, source } = await resolveSource(store, pos[0]);
|
|
361
|
+
const { label, source } = watchDetached ? await watchedDirectory(pos[0] ?? '.') : await resolveSource(store, pos[0]);
|
|
149
362
|
if (isWildcard(bind.host))
|
|
150
363
|
process.stderr.write(`warning: binding ${bind.host}: the site will be reachable from other machines\n`);
|
|
364
|
+
const keepOsMetadata = !!v['keep-os-metadata'];
|
|
365
|
+
const warn = (m) => void process.stderr.write(`warning: ${m}\n`);
|
|
151
366
|
if (!v.detach) {
|
|
152
|
-
const tree = await
|
|
153
|
-
|
|
367
|
+
const { tree, content, close } = await loadServedSite(store, source, { keepOsMetadata, warn });
|
|
368
|
+
if (profile?.siteFiles !== false)
|
|
369
|
+
checkSiteFiles(tree, strictSiteFiles, warn, content);
|
|
370
|
+
warnSpaFallback(tree, spa.spaFallback, warn);
|
|
371
|
+
const modified = await servedLastModified(store, source);
|
|
372
|
+
let current = tree;
|
|
373
|
+
const proxy = proxyOption(v);
|
|
374
|
+
const server = createSiteServer(() => current, { allowedHosts, proxy, cors: !!v.cors, ...(isolate ? { isolate } : {}), ...(cache ? { cache } : {}), ...logging, ...(auth.server ? { auth: auth.server } : {}), ...perIp, ...sharing.server, ...(tls.server ? { tls: tls.server } : {}), compress: !!v.compress, ...(throttle ? { throttle: throttle.limits } : {}), ...(mime ? { mime } : {}), lastModified: () => modified, log: logWriter(logging), ...(content ? { content } : {}), ...(country !== undefined ? { country } : {}), ...spa, ...(base !== undefined ? { base } : {}), ...(rewriteBase !== undefined ? { rewriteBase } : {}), ...(profile ? { profile } : {}), devNotFound: !isWildcard(bind.host) });
|
|
154
375
|
const addr = await listen(server, bind.host, bind.port);
|
|
155
|
-
|
|
156
|
-
|
|
376
|
+
if (logging.logFormat === 'json')
|
|
377
|
+
process.stdout.write(`${startedLogLine(new Date().toISOString(), label, tree.size, siteUrl(addr.host, addr.port, base, tls.scheme))}\n`);
|
|
378
|
+
else
|
|
379
|
+
process.stdout.write(`Serving ${label} (${tree.size} files) at ${siteUrl(addr.host, addr.port, base, tls.scheme)} (Ctrl-C to stop)\n${networkLines(addr.host, addr.port, base, tls.scheme)}${throttleLine(throttle?.spec)}`);
|
|
380
|
+
const quit = await terminal(v, addr, base, tls.scheme, warn, async () => {
|
|
381
|
+
if (source.kind !== 'dir') {
|
|
382
|
+
process.stdout.write(`Nothing to re-read: ${label} is ${source.kind === 'image' ? 'an image' : 'an archive file'}; start serve again to read it again\n`);
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
const next = await loadServedSite(store, source, { keepOsMetadata, warn });
|
|
386
|
+
checkSiteFiles(next.tree, false, warn, next.content);
|
|
387
|
+
current = next.tree;
|
|
388
|
+
next.close();
|
|
389
|
+
process.stdout.write(`Re-read ${label} (${current.size} files)\n`);
|
|
390
|
+
});
|
|
391
|
+
const stop = sharing.stopAfter;
|
|
392
|
+
const timer = stop === undefined ? undefined : new Promise((r) => setTimeout(() => r('stop-after'), stop.seconds * 1000).unref());
|
|
393
|
+
const why = await Promise.race([waitForSignal(), quit.promise.then(() => 'quit'), ...(timer ? [timer] : [])]);
|
|
394
|
+
if (why === 'stop-after')
|
|
395
|
+
process.stdout.write(`Stopping: --stop-after ${stop.text} reached\n`);
|
|
396
|
+
quit.stop();
|
|
157
397
|
await closeServer(server);
|
|
398
|
+
close();
|
|
158
399
|
return 0;
|
|
159
400
|
}
|
|
160
|
-
|
|
401
|
+
if (v.open !== undefined || v.qr)
|
|
402
|
+
usage('--open and --qr are for a server in the foreground, not -d');
|
|
161
403
|
const reg = await ServerRegistry.open(store);
|
|
162
|
-
const
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
spa: !!v.spa,
|
|
169
|
-
bind,
|
|
170
|
-
host: bind.host,
|
|
171
|
-
port: bind.port,
|
|
172
|
-
pid: 0,
|
|
173
|
-
started: new Date().toISOString(),
|
|
174
|
-
logFile: reg.logPath(id),
|
|
175
|
-
ready: false,
|
|
176
|
-
};
|
|
177
|
-
await reg.write(state);
|
|
178
|
-
try {
|
|
179
|
-
const up = await startDetached(reg, state);
|
|
180
|
-
process.stdout.write(`Started ${up.name} (${up.id}) serving ${label} at ${formatUrl(up.host, up.port)}\n`);
|
|
181
|
-
return 0;
|
|
182
|
-
}
|
|
183
|
-
catch (e) {
|
|
184
|
-
await reg.remove(id);
|
|
185
|
-
throw e;
|
|
186
|
-
}
|
|
404
|
+
for (const f of PROXY_FLAGS)
|
|
405
|
+
if (v[f] !== undefined)
|
|
406
|
+
usage(`--${f} is for a server in the foreground (or --watch), not -d`);
|
|
407
|
+
const up = await serveDetached(reg, { label, source, name, bind, keepOsMetadata, allowedHosts, cors: !!v.cors, ...(isolate ? { isolate } : {}), ...(cache ? { cache } : {}), ...logging, ...auth.record, ...perIp, ...sharing.record, ...tls.record, ...(v.compress ? { compress: true } : {}), ...(throttle ? { throttle: throttle.spec } : {}), ...(mime ? { mime: Object.fromEntries(mime) } : {}), country, strictSiteFiles, ...spa, base, rewriteBase, ...profiles, ...(watchDetached ? { watch: true, pollMs, sync } : {}) }, warn);
|
|
408
|
+
process.stdout.write(`Started ${up.name} (${up.id}) serving ${label} at ${siteUrl(up.host, up.port, up.base, up.tlsCert ? 'https' : 'http')}\n${networkLines(up.host, up.port, up.base, up.tlsCert ? 'https' : 'http')}${throttleLine(up.throttle)}`);
|
|
409
|
+
return 0;
|
|
187
410
|
},
|
|
188
411
|
};
|
|
412
|
+
/**
|
|
413
|
+
* `serve -d`: check that the source loads, allocate an ID and name, record the server, start its worker and
|
|
414
|
+
* wait until it listens. On failure the record is removed.
|
|
415
|
+
*/
|
|
416
|
+
export async function serveDetached(reg, d, warn) {
|
|
417
|
+
// fail fast on a bad image, directory or archive (or an ignored site-file line with --strict-site-files)
|
|
418
|
+
const site = await loadServedSite(reg.store, d.source, { keepOsMetadata: !!d.keepOsMetadata, ...(warn ? { warn } : {}) });
|
|
419
|
+
try {
|
|
420
|
+
if (routingFor(d)?.siteFiles !== false)
|
|
421
|
+
checkSiteFiles(site.tree, !!d.strictSiteFiles, warn ?? (() => undefined), site.content);
|
|
422
|
+
}
|
|
423
|
+
finally {
|
|
424
|
+
site.close();
|
|
425
|
+
}
|
|
426
|
+
const { id, name: finalName } = await reg.allocate(d.name);
|
|
427
|
+
const state = {
|
|
428
|
+
id,
|
|
429
|
+
name: finalName,
|
|
430
|
+
image: d.label,
|
|
431
|
+
source: d.source,
|
|
432
|
+
spa: d.spa,
|
|
433
|
+
...(d.spaExclude !== undefined && d.spaExclude.length > 0 ? { spaExclude: [...d.spaExclude] } : {}),
|
|
434
|
+
...(d.spaFallback !== undefined ? { spaFallback: d.spaFallback } : {}),
|
|
435
|
+
...(d.base !== undefined ? { base: d.base } : {}),
|
|
436
|
+
...(d.rewriteBase !== undefined ? { rewriteBase: d.rewriteBase } : {}),
|
|
437
|
+
...(d.hostProfile !== undefined ? { hostProfile: d.hostProfile } : {}),
|
|
438
|
+
...(d.htmlHandling !== undefined ? { htmlHandling: d.htmlHandling } : {}),
|
|
439
|
+
...(d.keepOsMetadata ? { keepOsMetadata: true } : {}),
|
|
440
|
+
...(d.allowedHosts !== undefined && d.allowedHosts.length > 0 ? { allowedHosts: d.allowedHosts } : {}),
|
|
441
|
+
...(d.cors ? { cors: true } : {}),
|
|
442
|
+
...(d.isolate ? { isolate: d.isolate } : {}),
|
|
443
|
+
...(d.cache ? { cache: d.cache } : {}),
|
|
444
|
+
...(d.logFormat === 'json' ? { logFormat: 'json' } : {}),
|
|
445
|
+
...(d.logIp ? { logIp: true } : {}),
|
|
446
|
+
...(d.quiet ? { quiet: true } : {}),
|
|
447
|
+
...(d.auth !== undefined ? { auth: d.auth } : {}),
|
|
448
|
+
...(d.authFile !== undefined ? { authFile: d.authFile } : {}),
|
|
449
|
+
...(d.maxConnectionsPerIp ? { maxConnectionsPerIp: d.maxConnectionsPerIp } : {}),
|
|
450
|
+
...(d.hideBase ? { hideBase: true } : {}),
|
|
451
|
+
...(d.allowIp !== undefined ? { allowIp: d.allowIp } : {}),
|
|
452
|
+
...(d.denyIp !== undefined ? { denyIp: d.denyIp } : {}),
|
|
453
|
+
...(d.expires !== undefined ? { expires: d.expires } : {}),
|
|
454
|
+
...(d.tlsCert !== undefined ? { tlsCert: d.tlsCert, tlsKey: d.tlsKey } : {}),
|
|
455
|
+
...(d.compress ? { compress: true } : {}),
|
|
456
|
+
...(d.throttle !== undefined ? { throttle: d.throttle } : {}),
|
|
457
|
+
...(d.mime !== undefined ? { mime: d.mime } : {}),
|
|
458
|
+
...(d.country !== undefined ? { country: d.country } : {}),
|
|
459
|
+
...(d.strictSiteFiles ? { strictSiteFiles: true } : {}),
|
|
460
|
+
...(d.watch ? { watch: true } : {}),
|
|
461
|
+
...(d.watch && d.pollMs !== undefined ? { pollMs: d.pollMs } : {}),
|
|
462
|
+
...(d.watch && d.sync !== undefined ? { sync: d.sync } : {}),
|
|
463
|
+
bind: d.bind,
|
|
464
|
+
host: d.bind.host,
|
|
465
|
+
port: d.bind.port,
|
|
466
|
+
pid: 0,
|
|
467
|
+
started: new Date().toISOString(),
|
|
468
|
+
logFile: reg.logPath(id),
|
|
469
|
+
ready: false,
|
|
470
|
+
...(d.project !== undefined ? { project: d.project } : {}),
|
|
471
|
+
};
|
|
472
|
+
await reg.write(state);
|
|
473
|
+
try {
|
|
474
|
+
return await startDetached(reg, state);
|
|
475
|
+
}
|
|
476
|
+
catch (e) {
|
|
477
|
+
await reg.remove(id);
|
|
478
|
+
throw e;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* `server restart`: stop `s` if it is running, then start it again with the same ID, name, source and
|
|
483
|
+
* requested bind address. On failure the record stays, marked not ready.
|
|
484
|
+
*/
|
|
485
|
+
export async function restartDetached(reg, s, graceMs) {
|
|
486
|
+
await stopServer(reg, s, graceMs);
|
|
487
|
+
(await loadServedSite(reg.store, s.source, { keepOsMetadata: !!s.keepOsMetadata })).close();
|
|
488
|
+
const fresh = { ...s, host: s.bind.host, port: s.bind.port, pid: 0, ready: false, started: new Date().toISOString() };
|
|
489
|
+
delete fresh.error;
|
|
490
|
+
await reg.write(fresh);
|
|
491
|
+
return startDetached(reg, fresh).catch(async (e) => {
|
|
492
|
+
await reg.update(s.id, { ready: false });
|
|
493
|
+
throw e;
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* After the server listens: `--qr`, `--open[=path]`, then single keys (a terminal, see serve-keys.ts).
|
|
498
|
+
* `promise` resolves on `q`; `stop` stops reading keys.
|
|
499
|
+
*/
|
|
500
|
+
async function terminal(v, addr, base, scheme, warn, restart) {
|
|
501
|
+
const urls = serveUrls(addr.host, addr.port, base, scheme);
|
|
502
|
+
if (v.qr)
|
|
503
|
+
process.stdout.write(qrText(urls.network[0] ?? urls.local));
|
|
504
|
+
const open = str(v.open);
|
|
505
|
+
if (open !== undefined)
|
|
506
|
+
openBrowser(openUrl(urls.local, open), warn);
|
|
507
|
+
let resolve;
|
|
508
|
+
const promise = new Promise((r) => (resolve = r));
|
|
509
|
+
let busy = Promise.resolve();
|
|
510
|
+
const stop = readKeys((a) => {
|
|
511
|
+
busy = busy.then(async () => {
|
|
512
|
+
if (a === 'quit')
|
|
513
|
+
resolve();
|
|
514
|
+
else if (a === 'help')
|
|
515
|
+
process.stdout.write(KEYS_HELP);
|
|
516
|
+
else if (a === 'clear')
|
|
517
|
+
process.stdout.write(CLEAR);
|
|
518
|
+
else if (a === 'urls')
|
|
519
|
+
process.stdout.write(urlsText(urls));
|
|
520
|
+
else if (a === 'open')
|
|
521
|
+
openBrowser(openUrl(urls.local, open ?? '/'), warn);
|
|
522
|
+
else
|
|
523
|
+
await restart();
|
|
524
|
+
});
|
|
525
|
+
});
|
|
526
|
+
if (stop)
|
|
527
|
+
process.stdout.write(KEYS_HINT);
|
|
528
|
+
return { promise, stop: stop ?? (() => undefined) };
|
|
529
|
+
}
|
|
530
|
+
/** The --watch flags `serve -d --watch` takes (it watches a plain directory; the rest are for builds or the page script). */
|
|
531
|
+
const DETACHED_WATCH = ['poll', 'poll-interval', 'sync'];
|
|
532
|
+
/**
|
|
533
|
+
* `serve -d --watch [dir]`: the directory (default .) as a source, absolute and real. A Sitefile project
|
|
534
|
+
* is refused: building on change happens in the foreground (`serve --watch`).
|
|
535
|
+
*/
|
|
536
|
+
async function watchedDirectory(arg) {
|
|
537
|
+
const dir = path.resolve(arg);
|
|
538
|
+
const st = await fs.stat(dir).catch(() => undefined);
|
|
539
|
+
if (!st?.isDirectory())
|
|
540
|
+
throw new SitefileError('E_NOT_FOUND', `'${arg}' is not a directory`);
|
|
541
|
+
if (await isFile(path.join(dir, 'Sitefile')))
|
|
542
|
+
usage(`-d --watch serves a plain directory, and ${arg} has a Sitefile: build it with serve --watch in the foreground`);
|
|
543
|
+
return { label: dir, source: { kind: 'dir', path: await fs.realpath(dir) } };
|
|
544
|
+
}
|
|
189
545
|
/** serve flags that only mean something with --watch. */
|
|
190
|
-
const WATCH_ONLY = ['file', 'target', 'build-arg', 'build-arg-file', 'no-cache', 'no-lockfile'];
|
|
191
|
-
/** `
|
|
546
|
+
const WATCH_ONLY = ['file', 'target', 'build-arg', 'build-arg-file', 'no-cache', 'no-lockfile', 'keep-service-workers', 'poll', 'poll-interval', 'no-css-inject', 'console', 'no-overlay', 'navigate-to-changed', 'reload', 'no-rewrite-base', 'sync'];
|
|
547
|
+
/** `--sync` (a bare `--sync` arrives as `--sync=`): `nav`, or `scroll` for `--sync=scroll`; undefined without it. */
|
|
548
|
+
function syncOf(v) {
|
|
549
|
+
const s = str(v.sync);
|
|
550
|
+
if (s === undefined)
|
|
551
|
+
return undefined;
|
|
552
|
+
if (s === '')
|
|
553
|
+
return 'nav';
|
|
554
|
+
if (s === 'scroll')
|
|
555
|
+
return 'scroll';
|
|
556
|
+
return usage(`--sync takes no value or =scroll, got '${s}'`);
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* `serve --watch [context]`: build in memory, serve, rebuild on change, live reload. A directory
|
|
560
|
+
* without a `Sitefile`, given none of -f, --target, --build-arg and --build-arg-file, is served
|
|
561
|
+
* as it is (re-read on change) instead of built.
|
|
562
|
+
*/
|
|
563
|
+
/** serve flags for proxying (#172); a detached server has none, so its proxy rules are all refused. */
|
|
564
|
+
const PROXY_FLAGS = ['proxy', 'allow-hosts', 'deny-hosts', 'allow-http', 'allow-private-network', 'connect-timeout', 'read-timeout'];
|
|
565
|
+
/** `--proxy /prefix=url`: a path prefix (no trailing slash, except `/`) and an http(s) URL. */
|
|
566
|
+
export function parseProxyRoute(raw) {
|
|
567
|
+
const bad = () => usage(`--proxy expects /prefix=http(s)://host[/path], got '${raw}'`);
|
|
568
|
+
const eq = raw.indexOf('=');
|
|
569
|
+
if (eq <= 0)
|
|
570
|
+
bad();
|
|
571
|
+
const prefix = raw.slice(0, eq);
|
|
572
|
+
const target = raw.slice(eq + 1);
|
|
573
|
+
if (!prefix.startsWith('/') || /[\s?#*:]/.test(prefix) || !/^https?:\/\/[^/?#\s]+(\/[^\s#]*)?$/i.test(target))
|
|
574
|
+
bad();
|
|
575
|
+
return { prefix: prefix.length > 1 ? prefix.replace(/\/+$/, '') : prefix, target };
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* The proxy settings of a foreground `serve`: `--proxy` routes, and a strict host list (`--allow-hosts`
|
|
579
|
+
* and `$SITEFILE_ALLOW_HOSTS`, plus each route's host) for `_redirects` proxy rules, under the build fetch
|
|
580
|
+
* policy (https only unless --allow-http, public addresses only unless --allow-private-network).
|
|
581
|
+
*/
|
|
582
|
+
function proxyOption(v) {
|
|
583
|
+
const routes = strs(v.proxy).map(parseProxyRoute);
|
|
584
|
+
const network = networkOption({ 'allow-hosts': v['allow-hosts'], 'deny-hosts': v['deny-hosts'], 'connect-timeout': v['connect-timeout'], 'read-timeout': v['read-timeout'] }) ?? {};
|
|
585
|
+
const routeHosts = routes.map((r) => new URL(r.target).host);
|
|
586
|
+
return {
|
|
587
|
+
routes,
|
|
588
|
+
policy: {
|
|
589
|
+
...DEFAULT_FETCH_POLICY,
|
|
590
|
+
allowHttp: !!v['allow-http'],
|
|
591
|
+
allowPrivateNetwork: !!v['allow-private-network'],
|
|
592
|
+
network: { ...network, strict: true, allowHosts: [...(network.allowHosts ?? []), ...routeHosts] },
|
|
593
|
+
},
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
/** `--allowed-host` values, validated and lowercased (the server always adds localhost names and IP addresses). */
|
|
597
|
+
function allowedHostsOf(v) {
|
|
598
|
+
const out = [];
|
|
599
|
+
for (const raw of strs(v['allowed-host'])) {
|
|
600
|
+
const h = parseAllowedHost(raw);
|
|
601
|
+
if (h === undefined)
|
|
602
|
+
usage(`--allowed-host: invalid host name '${raw}'`);
|
|
603
|
+
if (!out.includes(h))
|
|
604
|
+
out.push(h);
|
|
605
|
+
}
|
|
606
|
+
return out;
|
|
607
|
+
}
|
|
608
|
+
/** `--isolate [--coep require-corp|credentialless]`: the Cross-Origin-Embedder-Policy to send, or undefined. */
|
|
609
|
+
function isolateOf(v) {
|
|
610
|
+
const coep = str(v.coep);
|
|
611
|
+
if (coep !== undefined && !v.isolate)
|
|
612
|
+
usage('--coep needs --isolate');
|
|
613
|
+
if (coep !== undefined && coep !== 'require-corp' && coep !== 'credentialless')
|
|
614
|
+
usage(`--coep must be require-corp or credentialless, not '${coep}'`);
|
|
615
|
+
return v.isolate ? (coep ?? 'require-corp') : undefined;
|
|
616
|
+
}
|
|
617
|
+
/** `--max-age`, `--immutable`, `--max-age-html`, or undefined when none is given. */
|
|
618
|
+
function cacheOf(v) {
|
|
619
|
+
const secs = (flag) => {
|
|
620
|
+
const raw = str(v[flag]);
|
|
621
|
+
if (raw === undefined)
|
|
622
|
+
return undefined;
|
|
623
|
+
if (!/^[0-9]{1,10}$/.test(raw) || Number(raw) > 2147483647)
|
|
624
|
+
usage(`--${flag} must be a number of seconds (0 to 2147483647), not '${raw}'`);
|
|
625
|
+
return Number(raw);
|
|
626
|
+
};
|
|
627
|
+
const maxAge = secs('max-age');
|
|
628
|
+
const maxAgeHtml = secs('max-age-html');
|
|
629
|
+
if (v.immutable && maxAge === undefined)
|
|
630
|
+
usage('--immutable needs --max-age');
|
|
631
|
+
if (maxAge === undefined && maxAgeHtml === undefined)
|
|
632
|
+
return undefined;
|
|
633
|
+
return { ...(maxAge !== undefined ? { maxAge } : {}), ...(v.immutable ? { immutable: true } : {}), ...(maxAgeHtml !== undefined ? { maxAgeHtml } : {}) };
|
|
634
|
+
}
|
|
635
|
+
/** ` Network: <url>` lines for a server bound to all interfaces (none otherwise). */
|
|
636
|
+
function networkLines(host, port, base, scheme = 'http') {
|
|
637
|
+
return networkUrls(host, port, scheme)
|
|
638
|
+
.map((u) => ` Network: ${u}${(base ?? '/').slice(1)}\n`)
|
|
639
|
+
.join('');
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* `--auth`, `--auth-file`, `SITEFILE_SERVE_AUTH`: the server's checker and what the record keeps (verifiers and the
|
|
643
|
+
* file path, never a password). Warns when the bind is not loopback: basic auth over plain HTTP sends the password
|
|
644
|
+
* in the clear.
|
|
645
|
+
*/
|
|
646
|
+
async function authOf(v, bindHost) {
|
|
647
|
+
const pairs = [...strs(v.auth).map((a) => parseAuthPair(a, '--auth'))];
|
|
648
|
+
const env = process.env.SITEFILE_SERVE_AUTH;
|
|
649
|
+
if (env !== undefined && env !== '')
|
|
650
|
+
pairs.push(parseAuthPair(env, 'SITEFILE_SERVE_AUTH'));
|
|
651
|
+
const authFile = str(v['auth-file']);
|
|
652
|
+
const entries = pairs.map((p) => ({ user: p.user, verifier: makeVerifier(p.password) }));
|
|
653
|
+
const fromFile = authFile === undefined ? [] : parseHtpasswd(await fs.readFile(authFile, 'utf8').catch(() => usage(`--auth-file: cannot read ${authFile}`)), authFile);
|
|
654
|
+
if (entries.length === 0 && authFile === undefined)
|
|
655
|
+
return { record: {} };
|
|
656
|
+
if (!isLoopback(bindHost))
|
|
657
|
+
process.stderr.write(`warning: basic authentication over plain HTTP on ${bindHost}: the password crosses the network in the clear\n`);
|
|
658
|
+
return {
|
|
659
|
+
server: new BasicAuth([...entries, ...fromFile]),
|
|
660
|
+
record: { ...(entries.length > 0 ? { auth: entries } : {}), ...(authFile !== undefined ? { authFile: path.resolve(authFile) } : {}) },
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* `--tls-cert`, `--tls-key` (or `SITEFILE_TLS_CERT`, `SITEFILE_TLS_KEY`): the PEM files, read now (the key is never logged
|
|
665
|
+
* or copied; the record keeps both paths, absolute, and a detached server reads them at every start).
|
|
666
|
+
*/
|
|
667
|
+
async function tlsOf(v) {
|
|
668
|
+
const env = (k) => (process.env[k] === '' ? undefined : process.env[k]);
|
|
669
|
+
const cert = str(v['tls-cert']) ?? env('SITEFILE_TLS_CERT');
|
|
670
|
+
const key = str(v['tls-key']) ?? env('SITEFILE_TLS_KEY');
|
|
671
|
+
if (cert === undefined && key === undefined)
|
|
672
|
+
return { record: {}, scheme: 'http' };
|
|
673
|
+
if (cert === undefined || key === undefined)
|
|
674
|
+
usage('--tls-cert and --tls-key go together');
|
|
675
|
+
const read = (f, flag) => fs.readFile(f).catch(() => usage(`--${flag}: cannot read ${f}`));
|
|
676
|
+
return {
|
|
677
|
+
server: { cert: await read(cert, 'tls-cert'), key: await read(key, 'tls-key') },
|
|
678
|
+
record: { tlsCert: path.resolve(cert), tlsKey: path.resolve(key) },
|
|
679
|
+
scheme: 'https',
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
/** `--throttle`: the spec as given and its limits. */
|
|
683
|
+
function throttleOf(v) {
|
|
684
|
+
const spec = str(v.throttle);
|
|
685
|
+
if (spec === undefined)
|
|
686
|
+
return undefined;
|
|
687
|
+
const limits = parseThrottle(spec);
|
|
688
|
+
if (limits === undefined)
|
|
689
|
+
usage(`--throttle expects 3g, slow-3g or <kbit/s>[/<latency ms>], not '${spec}'`);
|
|
690
|
+
return { spec, limits };
|
|
691
|
+
}
|
|
692
|
+
/** `--mime-file` entries, then `--mime` values (a later one replaces an earlier type for the extension), or undefined. */
|
|
693
|
+
async function mimeOf(v) {
|
|
694
|
+
const file = str(v['mime-file']);
|
|
695
|
+
const flags = strs(v.mime);
|
|
696
|
+
if (file === undefined && flags.length === 0)
|
|
697
|
+
return undefined;
|
|
698
|
+
const out = file === undefined ? new Map() : parseMimeTypes(await fs.readFile(file, 'utf8').catch(() => usage(`--mime-file: cannot read ${file}`)), file);
|
|
699
|
+
for (const f of flags) {
|
|
700
|
+
const pair = parseMimeFlag(f);
|
|
701
|
+
if (pair === undefined)
|
|
702
|
+
usage(`--mime expects ext=type/subtype, not '${f}'`);
|
|
703
|
+
out.set(pair[0], pair[1]);
|
|
704
|
+
}
|
|
705
|
+
return out;
|
|
706
|
+
}
|
|
707
|
+
/** The start message's ` Throttle: …` line (none without --throttle). */
|
|
708
|
+
function throttleLine(spec) {
|
|
709
|
+
const t = spec === undefined ? undefined : parseThrottle(spec);
|
|
710
|
+
return t === undefined ? '' : ` Throttle: ${spec} (${t.bytesPerSecond / 125} kbit/s, ${t.latencyMs} ms latency)\n`;
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* `--random-route`, `--allow-ip`, `--deny-ip`, `--stop-after`, and the sharing defaults: `noindex` on a non-loopback bind and
|
|
714
|
+
* client info (address, device) in the access log of non-loopback clients.
|
|
715
|
+
*/
|
|
716
|
+
function sharingOf(v, bindHost) {
|
|
717
|
+
const cidrs = (flag) => {
|
|
718
|
+
const text = strs(v[flag]);
|
|
719
|
+
return {
|
|
720
|
+
text,
|
|
721
|
+
parsed: text.map((t) => {
|
|
722
|
+
const c = parseCidr(t);
|
|
723
|
+
if (c === undefined)
|
|
724
|
+
usage(`--${flag}: invalid address or CIDR block '${t}'`);
|
|
725
|
+
return c;
|
|
726
|
+
}),
|
|
727
|
+
};
|
|
728
|
+
};
|
|
729
|
+
const allow = cidrs('allow-ip');
|
|
730
|
+
const deny = cidrs('deny-ip');
|
|
731
|
+
if (v['random-route'] && v.base !== undefined)
|
|
732
|
+
usage('--random-route and --base both set the path prefix; use one');
|
|
733
|
+
const randomBase = v['random-route'] ? `/${randomBytes(12).toString('hex')}/` : undefined;
|
|
734
|
+
const raw = str(v['stop-after']);
|
|
735
|
+
let stopAfter;
|
|
736
|
+
if (raw !== undefined) {
|
|
737
|
+
const m = /^([0-9]{1,6})(s|m|h|d)$/.exec(raw);
|
|
738
|
+
if (!m || Number(m[1]) === 0)
|
|
739
|
+
usage(`--stop-after expects a duration like 90s, 30m, 2h or 1d, not '${raw}'`);
|
|
740
|
+
stopAfter = { seconds: Number(m[1]) * { s: 1, m: 60, h: 3600, d: 86400 }[m[2]], text: raw };
|
|
741
|
+
}
|
|
742
|
+
const ipRules = allow.parsed.length + deny.parsed.length > 0 ? { allow: allow.parsed, deny: deny.parsed } : undefined;
|
|
743
|
+
return {
|
|
744
|
+
...(randomBase ? { randomBase } : {}),
|
|
745
|
+
server: { ...(randomBase ? { hideBase: true } : {}), ...(ipRules ? { ipRules } : {}), ...(!isLoopback(bindHost) ? { noindex: true } : {}), clientInfo: true },
|
|
746
|
+
record: {
|
|
747
|
+
...(randomBase ? { hideBase: true } : {}),
|
|
748
|
+
...(allow.text.length > 0 ? { allowIp: allow.text } : {}),
|
|
749
|
+
...(deny.text.length > 0 ? { denyIp: deny.text } : {}),
|
|
750
|
+
...(stopAfter ? { expires: new Date(Date.now() + stopAfter.seconds * 1000).toISOString() } : {}),
|
|
751
|
+
},
|
|
752
|
+
...(stopAfter ? { stopAfter } : {}),
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
/** `--max-connections-per-ip <n>`: the option (and record field) when n > 0. */
|
|
756
|
+
function perIpOf(v) {
|
|
757
|
+
const raw = str(v['max-connections-per-ip']);
|
|
758
|
+
if (raw === undefined)
|
|
759
|
+
return {};
|
|
760
|
+
if (!/^[0-9]{1,6}$/.test(raw))
|
|
761
|
+
usage(`--max-connections-per-ip must be a number (0 to 999999), not '${raw}'`);
|
|
762
|
+
const n = Number(raw);
|
|
763
|
+
return n > 0 ? { maxConnectionsPerIp: n } : {};
|
|
764
|
+
}
|
|
765
|
+
function isLoopback(host) {
|
|
766
|
+
return host === 'localhost' || host === '::1' || /^127\./.test(host);
|
|
767
|
+
}
|
|
768
|
+
/** `--log-format`, `--log-ip`, `--quiet`: the server options (and record fields) they set, only those not at their default. */
|
|
769
|
+
function loggingOf(v) {
|
|
770
|
+
const format = str(v['log-format']);
|
|
771
|
+
if (format !== undefined && format !== 'text' && format !== 'json')
|
|
772
|
+
usage(`--log-format must be text or json, not '${format}'`);
|
|
773
|
+
return { ...(format === 'json' ? { logFormat: 'json' } : {}), ...(v['log-ip'] ? { logIp: true } : {}), ...(v.quiet ? { quiet: true } : {}) };
|
|
774
|
+
}
|
|
775
|
+
/** Where a foreground server's log lines go: stdout, other lines wrapped as JSON objects under `--log-format json`. */
|
|
776
|
+
function logWriter(logging) {
|
|
777
|
+
return (l) => void process.stdout.write(`${logging.logFormat === 'json' && !l.startsWith('{') ? jsonLogLine(new Date().toISOString(), l) : l}\n`);
|
|
778
|
+
}
|
|
192
779
|
async function serveWatch(v, pos) {
|
|
193
780
|
requireArgs(pos, 0, 1, 'a build context directory');
|
|
194
|
-
if (v.detach)
|
|
195
|
-
usage('--watch cannot be combined with -d');
|
|
196
781
|
if (v.name !== undefined)
|
|
197
782
|
usage('--name needs -d (only detached servers are tracked)');
|
|
198
783
|
const bind = parsePublish(str(v.publish));
|
|
784
|
+
const allowedHosts = allowedHostsOf(v);
|
|
785
|
+
const isolate = isolateOf(v);
|
|
786
|
+
const cache = cacheOf(v);
|
|
787
|
+
const logging = loggingOf(v);
|
|
788
|
+
const auth = await authOf(v, bind.host);
|
|
789
|
+
const perIp = perIpOf(v);
|
|
790
|
+
if (v['stop-after'] !== undefined)
|
|
791
|
+
usage('--stop-after does not apply to --watch');
|
|
792
|
+
const sharing = sharingOf(v, bind.host);
|
|
793
|
+
const tls = await tlsOf(v);
|
|
794
|
+
const throttle = throttleOf(v);
|
|
795
|
+
const mime = await mimeOf(v);
|
|
199
796
|
const context = pos[0] ?? '.';
|
|
200
797
|
const file = str(v.file);
|
|
201
798
|
const target = str(v.target);
|
|
202
799
|
const argFiles = strs(v['build-arg-file']);
|
|
203
800
|
const argFlags = strs(v['build-arg']);
|
|
801
|
+
const pollMs = pollOption(!!v.poll, str(v['poll-interval']));
|
|
802
|
+
const buildFlags = !!file || target !== undefined || argFiles.length > 0 || argFlags.length > 0;
|
|
803
|
+
const plain = !buildFlags && !(await isFile(path.join(context, 'Sitefile')));
|
|
804
|
+
const cssInject = !v['no-css-inject'];
|
|
805
|
+
const navigate = !!v['navigate-to-changed'];
|
|
806
|
+
const reloadMode = str(v.reload) ?? 'morph';
|
|
807
|
+
const sync = syncOf(v);
|
|
808
|
+
const spa = spaOptions(v);
|
|
809
|
+
const baseFlag = sharing.randomBase ?? parseBase(str(v.base));
|
|
810
|
+
/** `--base`, else the path of the last good build's EXPORT BASE URL. */
|
|
811
|
+
let base = baseFlag;
|
|
812
|
+
const rewriteFlag = parseRewriteBase(str(v['rewrite-base']));
|
|
813
|
+
const noRewrite = !!v['no-rewrite-base'];
|
|
814
|
+
if (noRewrite && rewriteFlag !== undefined)
|
|
815
|
+
usage('--rewrite-base and --no-rewrite-base cannot be combined');
|
|
816
|
+
/** `--rewrite-base`, else (unless --no-rewrite-base) the last good build's production URL. */
|
|
817
|
+
let rewriteBase = noRewrite ? undefined : rewriteFlag;
|
|
818
|
+
const profile = routingFor(profileOptions(v));
|
|
819
|
+
const country = parseCountry(str(v.country));
|
|
820
|
+
const strictSiteFiles = !!v['strict-site-files'];
|
|
821
|
+
/** The site-file warnings last printed: a rebuild repeats them only when they change. */
|
|
822
|
+
let lastSiteWarnings = '';
|
|
823
|
+
const siteFiles = (tree) => {
|
|
824
|
+
if (profile?.siteFiles === false)
|
|
825
|
+
return;
|
|
826
|
+
const shown = [];
|
|
827
|
+
checkSiteFiles(tree, false, (m) => shown.push(m));
|
|
828
|
+
const text = shown.join('\n');
|
|
829
|
+
if (text !== lastSiteWarnings)
|
|
830
|
+
for (const m of shown)
|
|
831
|
+
process.stderr.write(`warning: ${m}\n`);
|
|
832
|
+
lastSiteWarnings = text;
|
|
833
|
+
checkSiteFiles(tree, strictSiteFiles, () => undefined);
|
|
834
|
+
};
|
|
835
|
+
if (reloadMode !== 'full' && reloadMode !== 'morph')
|
|
836
|
+
usage(`--reload expects full or morph, got '${reloadMode}'`);
|
|
204
837
|
if (isWildcard(bind.host))
|
|
205
838
|
process.stderr.write(`warning: binding ${bind.host}: the site will be reachable from other machines\n`);
|
|
206
839
|
let current = Tree.empty;
|
|
840
|
+
let builtAt; // Last-Modified: the time of the build being served
|
|
207
841
|
let started = false;
|
|
208
842
|
const memo = watchMemo();
|
|
209
|
-
const live = new LiveReload();
|
|
210
|
-
|
|
843
|
+
const live = new LiveReload({ resetServiceWorkers: !v['keep-service-workers'], cssInject, console: !!v.console, overlay: !v['no-overlay'], navigateToChanged: navigate, reload: reloadMode, ...(sync ? { sync } : {}) });
|
|
844
|
+
/** Serve `next` and tell open pages what changed. */
|
|
845
|
+
const swap = (next) => {
|
|
846
|
+
const event = started ? (reloadEventFor(current, next, cssInject, navigate) ?? OK_EVENT) : undefined;
|
|
847
|
+
current = next;
|
|
848
|
+
builtAt = Math.floor(Date.now() / 1000);
|
|
849
|
+
if (event !== undefined)
|
|
850
|
+
live.send(event);
|
|
851
|
+
};
|
|
852
|
+
const proxy = proxyOption(v);
|
|
853
|
+
const server = createSiteServer(() => current, { allowedHosts, proxy, cors: !!v.cors, ...(isolate ? { isolate } : {}), ...(cache ? { cache } : {}), ...logging, ...(auth.server ? { auth: auth.server } : {}), ...perIp, ...sharing.server, ...(tls.server ? { tls: tls.server } : {}), compress: !!v.compress, ...(throttle ? { throttle: throttle.limits } : {}), ...(mime ? { mime } : {}), liveReload: live, lastModified: () => builtAt, log: logWriter(logging), warn: (m) => process.stderr.write(`warning: ${m}\n`), ...(country !== undefined ? { country } : {}), ...spa, base: () => base, rewriteBase: () => rewriteBase, ...(profile ? { profile } : {}), devNotFound: !isWildcard(bind.host) });
|
|
854
|
+
const control = {};
|
|
855
|
+
let quit;
|
|
856
|
+
let quitNow;
|
|
857
|
+
const quitting = new Promise((r) => (quitNow = r));
|
|
211
858
|
try {
|
|
212
859
|
return await watchLoop({
|
|
213
860
|
context,
|
|
861
|
+
control,
|
|
862
|
+
stop: Promise.race([waitForSignal().then(() => undefined), quitting]),
|
|
863
|
+
...(pollMs !== undefined ? { pollMs } : {}),
|
|
214
864
|
...(file ? { sitefile: file } : {}),
|
|
865
|
+
...(plain ? { plain } : {}),
|
|
215
866
|
argFiles,
|
|
216
867
|
build: async () => {
|
|
868
|
+
if (started)
|
|
869
|
+
live.send(BUILDING_EVENT);
|
|
217
870
|
try {
|
|
871
|
+
if (plain) {
|
|
872
|
+
const tree = await loadDirectoryTree(context);
|
|
873
|
+
process.stdout.write(`Read ${tree.size} file${tree.size === 1 ? '' : 's'} (${tree.digest()})\n`);
|
|
874
|
+
siteFiles(tree);
|
|
875
|
+
swap(tree);
|
|
876
|
+
return { code: 0 };
|
|
877
|
+
}
|
|
218
878
|
const r = await build({
|
|
219
879
|
contextDir: context,
|
|
220
880
|
...(file ? { sitefile: file } : {}),
|
|
@@ -223,14 +883,18 @@ async function serveWatch(v, pos) {
|
|
|
223
883
|
...(v['no-lockfile'] ? { lockfile: false } : {}),
|
|
224
884
|
...(v['no-cache'] ? {} : { cacheDir: transformCacheDir() }),
|
|
225
885
|
skipBase: true,
|
|
886
|
+
keepOsMetadata: !!v['keep-os-metadata'],
|
|
226
887
|
...(memo ? { memo } : {}),
|
|
227
888
|
onNotice: (m) => process.stderr.write(`${m}\n`),
|
|
228
889
|
onWarning: (m) => process.stderr.write(`warning: ${m}\n`),
|
|
229
890
|
});
|
|
230
|
-
current = r.output;
|
|
231
891
|
process.stdout.write(`Built ${r.output.size} file${r.output.size === 1 ? '' : 's'} (${r.output.digest()})\n`);
|
|
232
|
-
|
|
233
|
-
|
|
892
|
+
siteFiles(r.output);
|
|
893
|
+
if (baseFlag === undefined)
|
|
894
|
+
base = exportBasePath(r.plan.exportBase);
|
|
895
|
+
if (!noRewrite && rewriteFlag === undefined)
|
|
896
|
+
rewriteBase = productionUrl(r.plan);
|
|
897
|
+
swap(r.output);
|
|
234
898
|
return { code: 0 };
|
|
235
899
|
}
|
|
236
900
|
catch (e) {
|
|
@@ -239,17 +903,24 @@ async function serveWatch(v, pos) {
|
|
|
239
903
|
if (e.code === 'E_USAGE')
|
|
240
904
|
return { code: usageError(e.detail) };
|
|
241
905
|
process.stderr.write(`error[${e.code}]: ${e.message}\n`);
|
|
906
|
+
live.send(errorEvent(e)); // pages show it (and pages opened later get it on connect)
|
|
242
907
|
return { code: 1 };
|
|
243
908
|
}
|
|
244
909
|
},
|
|
245
910
|
onStarted: async () => {
|
|
246
911
|
const addr = await listen(server, bind.host, bind.port);
|
|
247
912
|
started = true;
|
|
248
|
-
|
|
913
|
+
if (logging.logFormat === 'json')
|
|
914
|
+
process.stdout.write(`${startedLogLine(new Date().toISOString(), context, current.size, siteUrl(addr.host, addr.port, base, tls.scheme))}\n`);
|
|
915
|
+
else
|
|
916
|
+
process.stdout.write(`Serving ${context} (${current.size} files) at ${siteUrl(addr.host, addr.port, base, tls.scheme)} (Ctrl-C to stop)\n${networkLines(addr.host, addr.port, base, tls.scheme)}${throttleLine(throttle?.spec)}`);
|
|
917
|
+
quit = await terminal(v, addr, base, tls.scheme, (m) => process.stderr.write(`warning: ${m}\n`), async () => control.rebuild?.());
|
|
918
|
+
void quit.promise.then(() => quitNow());
|
|
249
919
|
},
|
|
250
920
|
});
|
|
251
921
|
}
|
|
252
922
|
finally {
|
|
923
|
+
quit?.stop();
|
|
253
924
|
if (started)
|
|
254
925
|
await closeServer(server);
|
|
255
926
|
}
|
|
@@ -268,7 +939,12 @@ const ps = {
|
|
|
268
939
|
const shown = views.filter((s) => v.all || s.status === 'running');
|
|
269
940
|
if (v.json) {
|
|
270
941
|
// 'site' is the image reference or directory being served.
|
|
271
|
-
|
|
942
|
+
// A server bound to all interfaces also lists the URLs other machines use (networkUrls).
|
|
943
|
+
// Credentials never leave the record: a server that needs them shows auth: true.
|
|
944
|
+
const out = shown.map(({ image, auth, ...rest }) => {
|
|
945
|
+
const net = rest.status === 'running' ? networkUrls(rest.host, rest.port, rest.tlsCert !== undefined ? 'https' : 'http') : [];
|
|
946
|
+
return { ...rest, ...(net.length > 0 ? { networkUrls: net } : {}), ...(auth !== undefined || rest.authFile !== undefined ? { auth: true } : {}), site: image };
|
|
947
|
+
});
|
|
272
948
|
process.stdout.write(JSON.stringify(out, null, 2) + '\n');
|
|
273
949
|
return 0;
|
|
274
950
|
}
|
|
@@ -308,7 +984,7 @@ export async function stopServer(reg, s, graceMs) {
|
|
|
308
984
|
await reg.update(s.id, { ready: false }).catch(() => undefined);
|
|
309
985
|
return true;
|
|
310
986
|
}
|
|
311
|
-
function graceOf(v) {
|
|
987
|
+
export function graceOf(v) {
|
|
312
988
|
const t = str(v.time);
|
|
313
989
|
if (t === undefined)
|
|
314
990
|
return 5000;
|
|
@@ -381,10 +1057,10 @@ export function tailLines(text, n) {
|
|
|
381
1057
|
const logs = {
|
|
382
1058
|
name: 'logs',
|
|
383
1059
|
summary: 'show a server\'s access log',
|
|
384
|
-
usage: 'server logs [-f] [-n lines] <name|id>',
|
|
1060
|
+
usage: 'server logs [-f] [-n lines] [--json] <name|id>',
|
|
385
1061
|
description: 'Print the log of a detached server: one line per request ("METHOD /path STATUS BYTES MSms").',
|
|
386
|
-
flags: ['-f, --follow keep printing new lines until Ctrl-C', '-n, --tail <n> only the last n lines'],
|
|
387
|
-
options: { follow: { type: 'boolean', short: 'f' }, tail: { type: 'string', short: 'n' } },
|
|
1062
|
+
flags: ['-f, --follow keep printing new lines until Ctrl-C', '-n, --tail <n> only the last n lines', '--json one JSON object per line (text lines of older servers are converted)'],
|
|
1063
|
+
options: { follow: { type: 'boolean', short: 'f' }, tail: { type: 'string', short: 'n' }, json: { type: 'boolean' } },
|
|
388
1064
|
async run(v, pos) {
|
|
389
1065
|
requireArgs(pos, 1, 1, 'a server id or name');
|
|
390
1066
|
const reg = await ServerRegistry.open();
|
|
@@ -398,9 +1074,22 @@ const logs = {
|
|
|
398
1074
|
usage('--tail expects a non-negative integer');
|
|
399
1075
|
text = tailLines(text, n);
|
|
400
1076
|
}
|
|
401
|
-
|
|
402
|
-
|
|
1077
|
+
let carry = '';
|
|
1078
|
+
/** Write log bytes; with --json, whole lines only, each converted. */
|
|
1079
|
+
const emit = (chunk) => {
|
|
1080
|
+
if (!v.json)
|
|
1081
|
+
return void process.stdout.write(chunk);
|
|
1082
|
+
const lines = (carry + chunk).split('\n');
|
|
1083
|
+
carry = lines.pop() ?? '';
|
|
1084
|
+
if (lines.length > 0)
|
|
1085
|
+
process.stdout.write(lines.map((l) => `${logLineAsJson(l)}\n`).join(''));
|
|
1086
|
+
};
|
|
1087
|
+
emit(text);
|
|
1088
|
+
if (!v.follow) {
|
|
1089
|
+
if (v.json && carry !== '')
|
|
1090
|
+
process.stdout.write(`${logLineAsJson(carry)}\n`);
|
|
403
1091
|
return 0;
|
|
1092
|
+
}
|
|
404
1093
|
let pos2 = offset;
|
|
405
1094
|
let done = false;
|
|
406
1095
|
void waitForSignal().then(() => (done = true));
|
|
@@ -417,7 +1106,7 @@ const logs = {
|
|
|
417
1106
|
const buf = Buffer.alloc(size - pos2);
|
|
418
1107
|
await fh.read(buf, 0, buf.length, pos2);
|
|
419
1108
|
pos2 = size;
|
|
420
|
-
|
|
1109
|
+
emit(buf.toString('utf8'));
|
|
421
1110
|
}
|
|
422
1111
|
}
|
|
423
1112
|
finally {
|
|
@@ -438,19 +1127,12 @@ const restart = {
|
|
|
438
1127
|
requireArgs(pos, 1, 1, 'a server id or name');
|
|
439
1128
|
const reg = await ServerRegistry.open();
|
|
440
1129
|
const s = await reg.find(pos[0]);
|
|
441
|
-
await
|
|
442
|
-
|
|
443
|
-
const fresh = { ...s, host: s.bind.host, port: s.bind.port, pid: 0, ready: false, started: new Date().toISOString() };
|
|
444
|
-
delete fresh.error;
|
|
445
|
-
await reg.write(fresh);
|
|
446
|
-
const up = await startDetached(reg, fresh).catch(async (e) => {
|
|
447
|
-
await reg.update(s.id, { ready: false });
|
|
448
|
-
throw e;
|
|
449
|
-
});
|
|
450
|
-
process.stdout.write(`Restarted ${up.name} (${up.id}) serving ${up.image} at ${formatUrl(up.host, up.port)}\n`);
|
|
1130
|
+
const up = await restartDetached(reg, s, graceOf(v));
|
|
1131
|
+
process.stdout.write(`Restarted ${up.name} (${up.id}) serving ${up.image} at ${siteUrl(up.host, up.port, up.base, up.tlsCert ? 'https' : 'http')}\n${networkLines(up.host, up.port, up.base, up.tlsCert ? 'https' : 'http')}`);
|
|
451
1132
|
return 0;
|
|
452
1133
|
},
|
|
453
1134
|
};
|
|
1135
|
+
export { isFile };
|
|
454
1136
|
/** Top-level: `sitefile serve`, `sitefile servers`. */
|
|
455
1137
|
export const serverCommands = new Map([
|
|
456
1138
|
['serve', run],
|