@johnhenry/sitefile 0.0.2 → 0.0.3
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 +467 -0
- package/README.md +55 -6
- package/lib/src/archive-writers.d.ts +12 -2
- package/lib/src/archive-writers.js +53 -10
- package/lib/src/canonical.d.ts +16 -0
- package/lib/src/canonical.js +46 -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 +3 -1
- package/lib/src/cli/index.js +31 -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 +46 -8
- package/lib/src/cli/servers.d.ts +124 -1
- package/lib/src/cli/servers.js +705 -62
- 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 +192 -22
- 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/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 +116 -3
- package/lib/src/language/ast.js +7 -1
- package/lib/src/language/parser.js +176 -7
- package/lib/src/language/validate.js +21 -0
- package/lib/src/links.d.ts +33 -0
- package/lib/src/links.js +271 -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 +69 -2
- package/lib/src/planner.js +150 -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 +304 -0
- package/lib/src/resources/archive.d.ts +36 -0
- package/lib/src/resources/archive.js +338 -67
- 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 +32 -0
- package/lib/src/serve-auth.js +112 -0
- package/lib/src/serve-rules.d.ts +83 -7
- package/lib/src/serve-rules.js +264 -53
- package/lib/src/server.d.ts +437 -10
- package/lib/src/server.js +1236 -52
- package/lib/src/servers-file.d.ts +36 -0
- package/lib/src/servers-file.js +101 -0
- package/lib/src/servers.d.ts +109 -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 +54 -0
- package/lib/src/site.js +204 -6
- 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))
|
|
@@ -106,12 +190,55 @@ const run = {
|
|
|
106
190
|
name: 'serve',
|
|
107
191
|
summary: 'serve an image, directory or archive file over HTTP',
|
|
108
192
|
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(
|
|
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.',
|
|
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',
|
|
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} entries, htpasswd -s)',
|
|
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',
|
|
115
242
|
'--watch build the context, serve it, rebuild on change and live-reload pages (foreground 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)',
|
|
@@ -119,12 +246,62 @@ const run = {
|
|
|
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)',
|
|
251
|
+
'--poll-interval <ms> poll every <ms> milliseconds (--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)',
|
|
122
257
|
],
|
|
123
258
|
options: {
|
|
124
259
|
name: { type: 'string' },
|
|
125
260
|
publish: { type: 'string', short: 'p' },
|
|
126
261
|
detach: { type: 'boolean', short: 'd' },
|
|
127
262
|
spa: { type: 'boolean' },
|
|
263
|
+
'spa-exclude': { type: 'string', multiple: true },
|
|
264
|
+
'spa-fallback': { type: 'string' },
|
|
265
|
+
base: { type: 'string' },
|
|
266
|
+
'host-profile': { type: 'string' },
|
|
267
|
+
'html-handling': { type: 'string' },
|
|
268
|
+
'rewrite-base': { type: 'string' },
|
|
269
|
+
'no-rewrite-base': { type: 'boolean' },
|
|
270
|
+
country: { type: 'string' },
|
|
271
|
+
'strict-site-files': { type: 'boolean' },
|
|
272
|
+
'keep-os-metadata': { type: 'boolean' },
|
|
273
|
+
'allowed-host': { type: 'string', multiple: true },
|
|
274
|
+
proxy: { type: 'string', multiple: true },
|
|
275
|
+
'allow-hosts': { type: 'string', multiple: true },
|
|
276
|
+
'deny-hosts': { type: 'string', multiple: true },
|
|
277
|
+
'allow-http': { type: 'boolean' },
|
|
278
|
+
'allow-private-network': { type: 'boolean' },
|
|
279
|
+
'connect-timeout': { type: 'string' },
|
|
280
|
+
'read-timeout': { type: 'string' },
|
|
281
|
+
cors: { type: 'boolean' },
|
|
282
|
+
open: { type: 'string' },
|
|
283
|
+
qr: { type: 'boolean' },
|
|
284
|
+
isolate: { type: 'boolean' },
|
|
285
|
+
coep: { type: 'string' },
|
|
286
|
+
'max-age': { type: 'string' },
|
|
287
|
+
immutable: { type: 'boolean' },
|
|
288
|
+
'max-age-html': { type: 'string' },
|
|
289
|
+
'log-format': { type: 'string' },
|
|
290
|
+
'log-ip': { type: 'boolean' },
|
|
291
|
+
quiet: { type: 'boolean' },
|
|
292
|
+
auth: { type: 'string', multiple: true },
|
|
293
|
+
'auth-file': { type: 'string' },
|
|
294
|
+
'max-connections-per-ip': { type: 'string' },
|
|
295
|
+
'random-route': { type: 'boolean' },
|
|
296
|
+
'allow-ip': { type: 'string', multiple: true },
|
|
297
|
+
'deny-ip': { type: 'string', multiple: true },
|
|
298
|
+
'stop-after': { type: 'string' },
|
|
299
|
+
'tls-cert': { type: 'string' },
|
|
300
|
+
compress: { type: 'boolean' },
|
|
301
|
+
throttle: { type: 'string' },
|
|
302
|
+
mime: { type: 'string', multiple: true },
|
|
303
|
+
'mime-file': { type: 'string' },
|
|
304
|
+
'tls-key': { type: 'string' },
|
|
128
305
|
watch: { type: 'boolean' },
|
|
129
306
|
file: { type: 'string', short: 'f' },
|
|
130
307
|
target: { type: 'string' },
|
|
@@ -132,6 +309,14 @@ const run = {
|
|
|
132
309
|
'build-arg-file': { type: 'string', multiple: true },
|
|
133
310
|
'no-cache': { type: 'boolean' },
|
|
134
311
|
'no-lockfile': { type: 'boolean' },
|
|
312
|
+
'keep-service-workers': { type: 'boolean' },
|
|
313
|
+
poll: { type: 'boolean' },
|
|
314
|
+
'poll-interval': { type: 'string' },
|
|
315
|
+
'no-css-inject': { type: 'boolean' },
|
|
316
|
+
console: { type: 'boolean' },
|
|
317
|
+
'no-overlay': { type: 'boolean' },
|
|
318
|
+
'navigate-to-changed': { type: 'boolean' },
|
|
319
|
+
reload: { type: 'string' },
|
|
135
320
|
},
|
|
136
321
|
async run(v, pos) {
|
|
137
322
|
if (v.watch)
|
|
@@ -141,6 +326,23 @@ const run = {
|
|
|
141
326
|
usage(`--${f} needs --watch`);
|
|
142
327
|
requireArgs(pos, 1, 1, 'an image reference, ./directory or archive file');
|
|
143
328
|
const bind = parsePublish(str(v.publish));
|
|
329
|
+
const allowedHosts = allowedHostsOf(v);
|
|
330
|
+
const isolate = isolateOf(v);
|
|
331
|
+
const cache = cacheOf(v);
|
|
332
|
+
const logging = loggingOf(v);
|
|
333
|
+
const auth = await authOf(v, bind.host);
|
|
334
|
+
const perIp = perIpOf(v);
|
|
335
|
+
const sharing = sharingOf(v, bind.host);
|
|
336
|
+
const tls = await tlsOf(v);
|
|
337
|
+
const throttle = throttleOf(v);
|
|
338
|
+
const mime = await mimeOf(v);
|
|
339
|
+
const spa = spaOptions(v);
|
|
340
|
+
const base = sharing.randomBase ?? parseBase(str(v.base));
|
|
341
|
+
const rewriteBase = parseRewriteBase(str(v['rewrite-base']));
|
|
342
|
+
const profiles = profileOptions(v);
|
|
343
|
+
const profile = routingFor(profiles);
|
|
344
|
+
const country = parseCountry(str(v.country));
|
|
345
|
+
const strictSiteFiles = !!v['strict-site-files'];
|
|
144
346
|
const name = str(v.name);
|
|
145
347
|
if (name !== undefined && !v.detach)
|
|
146
348
|
usage('--name needs -d (only detached servers are tracked)');
|
|
@@ -148,47 +350,392 @@ const run = {
|
|
|
148
350
|
const { label, source } = await resolveSource(store, pos[0]);
|
|
149
351
|
if (isWildcard(bind.host))
|
|
150
352
|
process.stderr.write(`warning: binding ${bind.host}: the site will be reachable from other machines\n`);
|
|
353
|
+
const keepOsMetadata = !!v['keep-os-metadata'];
|
|
354
|
+
const warn = (m) => void process.stderr.write(`warning: ${m}\n`);
|
|
151
355
|
if (!v.detach) {
|
|
152
|
-
const tree = await
|
|
153
|
-
|
|
356
|
+
const { tree, content, close } = await loadServedSite(store, source, { keepOsMetadata, warn });
|
|
357
|
+
if (profile?.siteFiles !== false)
|
|
358
|
+
checkSiteFiles(tree, strictSiteFiles, warn, content);
|
|
359
|
+
warnSpaFallback(tree, spa.spaFallback, warn);
|
|
360
|
+
const modified = await servedLastModified(store, source);
|
|
361
|
+
let current = tree;
|
|
362
|
+
const proxy = proxyOption(v);
|
|
363
|
+
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
364
|
const addr = await listen(server, bind.host, bind.port);
|
|
155
|
-
|
|
156
|
-
|
|
365
|
+
if (logging.logFormat === 'json')
|
|
366
|
+
process.stdout.write(`${startedLogLine(new Date().toISOString(), label, tree.size, siteUrl(addr.host, addr.port, base, tls.scheme))}\n`);
|
|
367
|
+
else
|
|
368
|
+
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)}`);
|
|
369
|
+
const quit = await terminal(v, addr, base, tls.scheme, warn, async () => {
|
|
370
|
+
if (source.kind !== 'dir') {
|
|
371
|
+
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`);
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const next = await loadServedSite(store, source, { keepOsMetadata, warn });
|
|
375
|
+
checkSiteFiles(next.tree, false, warn, next.content);
|
|
376
|
+
current = next.tree;
|
|
377
|
+
next.close();
|
|
378
|
+
process.stdout.write(`Re-read ${label} (${current.size} files)\n`);
|
|
379
|
+
});
|
|
380
|
+
const stop = sharing.stopAfter;
|
|
381
|
+
const timer = stop === undefined ? undefined : new Promise((r) => setTimeout(() => r('stop-after'), stop.seconds * 1000).unref());
|
|
382
|
+
const why = await Promise.race([waitForSignal(), quit.promise.then(() => 'quit'), ...(timer ? [timer] : [])]);
|
|
383
|
+
if (why === 'stop-after')
|
|
384
|
+
process.stdout.write(`Stopping: --stop-after ${stop.text} reached\n`);
|
|
385
|
+
quit.stop();
|
|
157
386
|
await closeServer(server);
|
|
387
|
+
close();
|
|
158
388
|
return 0;
|
|
159
389
|
}
|
|
160
|
-
|
|
390
|
+
if (v.open !== undefined || v.qr)
|
|
391
|
+
usage('--open and --qr are for a server in the foreground, not -d');
|
|
161
392
|
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
|
-
}
|
|
393
|
+
for (const f of PROXY_FLAGS)
|
|
394
|
+
if (v[f] !== undefined)
|
|
395
|
+
usage(`--${f} is for a server in the foreground (or --watch), not -d`);
|
|
396
|
+
const up = await serveDetached(reg, { label, source, name, bind, keepOsMetadata, allowedHosts, cors: !!v.cors, ...(isolate ? { isolate } : {}), ...(cache ? { cache } : {}), ...logging, ...auth.record, ...perIp, ...sharing.record, ...tls.record, ...(v.compress ? { compress: true } : {}), ...(throttle ? { throttle: throttle.spec } : {}), ...(mime ? { mime: Object.fromEntries(mime) } : {}), country, strictSiteFiles, ...spa, base, rewriteBase, ...profiles }, warn);
|
|
397
|
+
process.stdout.write(`Started ${up.name} (${up.id}) serving ${label} at ${siteUrl(up.host, up.port, up.base, up.tlsCert ? 'https' : 'http')}\n${networkLines(up.host, up.port, up.base, up.tlsCert ? 'https' : 'http')}${throttleLine(up.throttle)}`);
|
|
398
|
+
return 0;
|
|
187
399
|
},
|
|
188
400
|
};
|
|
401
|
+
/**
|
|
402
|
+
* `serve -d`: check that the source loads, allocate an ID and name, record the server, start its worker and
|
|
403
|
+
* wait until it listens. On failure the record is removed.
|
|
404
|
+
*/
|
|
405
|
+
export async function serveDetached(reg, d, warn) {
|
|
406
|
+
// fail fast on a bad image, directory or archive (or an ignored site-file line with --strict-site-files)
|
|
407
|
+
const site = await loadServedSite(reg.store, d.source, { keepOsMetadata: !!d.keepOsMetadata, ...(warn ? { warn } : {}) });
|
|
408
|
+
try {
|
|
409
|
+
if (routingFor(d)?.siteFiles !== false)
|
|
410
|
+
checkSiteFiles(site.tree, !!d.strictSiteFiles, warn ?? (() => undefined), site.content);
|
|
411
|
+
}
|
|
412
|
+
finally {
|
|
413
|
+
site.close();
|
|
414
|
+
}
|
|
415
|
+
const { id, name: finalName } = await reg.allocate(d.name);
|
|
416
|
+
const state = {
|
|
417
|
+
id,
|
|
418
|
+
name: finalName,
|
|
419
|
+
image: d.label,
|
|
420
|
+
source: d.source,
|
|
421
|
+
spa: d.spa,
|
|
422
|
+
...(d.spaExclude !== undefined && d.spaExclude.length > 0 ? { spaExclude: [...d.spaExclude] } : {}),
|
|
423
|
+
...(d.spaFallback !== undefined ? { spaFallback: d.spaFallback } : {}),
|
|
424
|
+
...(d.base !== undefined ? { base: d.base } : {}),
|
|
425
|
+
...(d.rewriteBase !== undefined ? { rewriteBase: d.rewriteBase } : {}),
|
|
426
|
+
...(d.hostProfile !== undefined ? { hostProfile: d.hostProfile } : {}),
|
|
427
|
+
...(d.htmlHandling !== undefined ? { htmlHandling: d.htmlHandling } : {}),
|
|
428
|
+
...(d.keepOsMetadata ? { keepOsMetadata: true } : {}),
|
|
429
|
+
...(d.allowedHosts !== undefined && d.allowedHosts.length > 0 ? { allowedHosts: d.allowedHosts } : {}),
|
|
430
|
+
...(d.cors ? { cors: true } : {}),
|
|
431
|
+
...(d.isolate ? { isolate: d.isolate } : {}),
|
|
432
|
+
...(d.cache ? { cache: d.cache } : {}),
|
|
433
|
+
...(d.logFormat === 'json' ? { logFormat: 'json' } : {}),
|
|
434
|
+
...(d.logIp ? { logIp: true } : {}),
|
|
435
|
+
...(d.quiet ? { quiet: true } : {}),
|
|
436
|
+
...(d.auth !== undefined ? { auth: d.auth } : {}),
|
|
437
|
+
...(d.authFile !== undefined ? { authFile: d.authFile } : {}),
|
|
438
|
+
...(d.maxConnectionsPerIp ? { maxConnectionsPerIp: d.maxConnectionsPerIp } : {}),
|
|
439
|
+
...(d.hideBase ? { hideBase: true } : {}),
|
|
440
|
+
...(d.allowIp !== undefined ? { allowIp: d.allowIp } : {}),
|
|
441
|
+
...(d.denyIp !== undefined ? { denyIp: d.denyIp } : {}),
|
|
442
|
+
...(d.expires !== undefined ? { expires: d.expires } : {}),
|
|
443
|
+
...(d.tlsCert !== undefined ? { tlsCert: d.tlsCert, tlsKey: d.tlsKey } : {}),
|
|
444
|
+
...(d.compress ? { compress: true } : {}),
|
|
445
|
+
...(d.throttle !== undefined ? { throttle: d.throttle } : {}),
|
|
446
|
+
...(d.mime !== undefined ? { mime: d.mime } : {}),
|
|
447
|
+
...(d.country !== undefined ? { country: d.country } : {}),
|
|
448
|
+
...(d.strictSiteFiles ? { strictSiteFiles: true } : {}),
|
|
449
|
+
bind: d.bind,
|
|
450
|
+
host: d.bind.host,
|
|
451
|
+
port: d.bind.port,
|
|
452
|
+
pid: 0,
|
|
453
|
+
started: new Date().toISOString(),
|
|
454
|
+
logFile: reg.logPath(id),
|
|
455
|
+
ready: false,
|
|
456
|
+
...(d.project !== undefined ? { project: d.project } : {}),
|
|
457
|
+
};
|
|
458
|
+
await reg.write(state);
|
|
459
|
+
try {
|
|
460
|
+
return await startDetached(reg, state);
|
|
461
|
+
}
|
|
462
|
+
catch (e) {
|
|
463
|
+
await reg.remove(id);
|
|
464
|
+
throw e;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* `server restart`: stop `s` if it is running, then start it again with the same ID, name, source and
|
|
469
|
+
* requested bind address. On failure the record stays, marked not ready.
|
|
470
|
+
*/
|
|
471
|
+
export async function restartDetached(reg, s, graceMs) {
|
|
472
|
+
await stopServer(reg, s, graceMs);
|
|
473
|
+
(await loadServedSite(reg.store, s.source, { keepOsMetadata: !!s.keepOsMetadata })).close();
|
|
474
|
+
const fresh = { ...s, host: s.bind.host, port: s.bind.port, pid: 0, ready: false, started: new Date().toISOString() };
|
|
475
|
+
delete fresh.error;
|
|
476
|
+
await reg.write(fresh);
|
|
477
|
+
return startDetached(reg, fresh).catch(async (e) => {
|
|
478
|
+
await reg.update(s.id, { ready: false });
|
|
479
|
+
throw e;
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
/**
|
|
483
|
+
* After the server listens: `--qr`, `--open[=path]`, then single keys (a terminal, see serve-keys.ts).
|
|
484
|
+
* `promise` resolves on `q`; `stop` stops reading keys.
|
|
485
|
+
*/
|
|
486
|
+
async function terminal(v, addr, base, scheme, warn, restart) {
|
|
487
|
+
const urls = serveUrls(addr.host, addr.port, base, scheme);
|
|
488
|
+
if (v.qr)
|
|
489
|
+
process.stdout.write(qrText(urls.network[0] ?? urls.local));
|
|
490
|
+
const open = str(v.open);
|
|
491
|
+
if (open !== undefined)
|
|
492
|
+
openBrowser(openUrl(urls.local, open), warn);
|
|
493
|
+
let resolve;
|
|
494
|
+
const promise = new Promise((r) => (resolve = r));
|
|
495
|
+
let busy = Promise.resolve();
|
|
496
|
+
const stop = readKeys((a) => {
|
|
497
|
+
busy = busy.then(async () => {
|
|
498
|
+
if (a === 'quit')
|
|
499
|
+
resolve();
|
|
500
|
+
else if (a === 'help')
|
|
501
|
+
process.stdout.write(KEYS_HELP);
|
|
502
|
+
else if (a === 'clear')
|
|
503
|
+
process.stdout.write(CLEAR);
|
|
504
|
+
else if (a === 'urls')
|
|
505
|
+
process.stdout.write(urlsText(urls));
|
|
506
|
+
else if (a === 'open')
|
|
507
|
+
openBrowser(openUrl(urls.local, open ?? '/'), warn);
|
|
508
|
+
else
|
|
509
|
+
await restart();
|
|
510
|
+
});
|
|
511
|
+
});
|
|
512
|
+
if (stop)
|
|
513
|
+
process.stdout.write(KEYS_HINT);
|
|
514
|
+
return { promise, stop: stop ?? (() => undefined) };
|
|
515
|
+
}
|
|
189
516
|
/** serve flags that only mean something with --watch. */
|
|
190
|
-
const WATCH_ONLY = ['file', 'target', 'build-arg', 'build-arg-file', 'no-cache', 'no-lockfile'];
|
|
191
|
-
/**
|
|
517
|
+
const WATCH_ONLY = ['file', 'target', 'build-arg', 'build-arg-file', 'no-cache', 'no-lockfile', 'keep-service-workers', 'poll', 'poll-interval', 'no-css-inject', 'console', 'no-overlay', 'navigate-to-changed', 'reload', 'no-rewrite-base'];
|
|
518
|
+
/**
|
|
519
|
+
* `serve --watch [context]`: build in memory, serve, rebuild on change, live reload. A directory
|
|
520
|
+
* without a `Sitefile`, given none of -f, --target, --build-arg and --build-arg-file, is served
|
|
521
|
+
* as it is (re-read on change) instead of built.
|
|
522
|
+
*/
|
|
523
|
+
/** serve flags for proxying (#172); a detached server has none, so its proxy rules are all refused. */
|
|
524
|
+
const PROXY_FLAGS = ['proxy', 'allow-hosts', 'deny-hosts', 'allow-http', 'allow-private-network', 'connect-timeout', 'read-timeout'];
|
|
525
|
+
/** `--proxy /prefix=url`: a path prefix (no trailing slash, except `/`) and an http(s) URL. */
|
|
526
|
+
export function parseProxyRoute(raw) {
|
|
527
|
+
const bad = () => usage(`--proxy expects /prefix=http(s)://host[/path], got '${raw}'`);
|
|
528
|
+
const eq = raw.indexOf('=');
|
|
529
|
+
if (eq <= 0)
|
|
530
|
+
bad();
|
|
531
|
+
const prefix = raw.slice(0, eq);
|
|
532
|
+
const target = raw.slice(eq + 1);
|
|
533
|
+
if (!prefix.startsWith('/') || /[\s?#*:]/.test(prefix) || !/^https?:\/\/[^/?#\s]+(\/[^\s#]*)?$/i.test(target))
|
|
534
|
+
bad();
|
|
535
|
+
return { prefix: prefix.length > 1 ? prefix.replace(/\/+$/, '') : prefix, target };
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* The proxy settings of a foreground `serve`: `--proxy` routes, and a strict host list (`--allow-hosts`
|
|
539
|
+
* and `$SITEFILE_ALLOW_HOSTS`, plus each route's host) for `_redirects` proxy rules, under the build fetch
|
|
540
|
+
* policy (https only unless --allow-http, public addresses only unless --allow-private-network).
|
|
541
|
+
*/
|
|
542
|
+
function proxyOption(v) {
|
|
543
|
+
const routes = strs(v.proxy).map(parseProxyRoute);
|
|
544
|
+
const network = networkOption({ 'allow-hosts': v['allow-hosts'], 'deny-hosts': v['deny-hosts'], 'connect-timeout': v['connect-timeout'], 'read-timeout': v['read-timeout'] }) ?? {};
|
|
545
|
+
const routeHosts = routes.map((r) => new URL(r.target).host);
|
|
546
|
+
return {
|
|
547
|
+
routes,
|
|
548
|
+
policy: {
|
|
549
|
+
...DEFAULT_FETCH_POLICY,
|
|
550
|
+
allowHttp: !!v['allow-http'],
|
|
551
|
+
allowPrivateNetwork: !!v['allow-private-network'],
|
|
552
|
+
network: { ...network, strict: true, allowHosts: [...(network.allowHosts ?? []), ...routeHosts] },
|
|
553
|
+
},
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
/** `--allowed-host` values, validated and lowercased (the server always adds localhost names and IP addresses). */
|
|
557
|
+
function allowedHostsOf(v) {
|
|
558
|
+
const out = [];
|
|
559
|
+
for (const raw of strs(v['allowed-host'])) {
|
|
560
|
+
const h = parseAllowedHost(raw);
|
|
561
|
+
if (h === undefined)
|
|
562
|
+
usage(`--allowed-host: invalid host name '${raw}'`);
|
|
563
|
+
if (!out.includes(h))
|
|
564
|
+
out.push(h);
|
|
565
|
+
}
|
|
566
|
+
return out;
|
|
567
|
+
}
|
|
568
|
+
/** `--isolate [--coep require-corp|credentialless]`: the Cross-Origin-Embedder-Policy to send, or undefined. */
|
|
569
|
+
function isolateOf(v) {
|
|
570
|
+
const coep = str(v.coep);
|
|
571
|
+
if (coep !== undefined && !v.isolate)
|
|
572
|
+
usage('--coep needs --isolate');
|
|
573
|
+
if (coep !== undefined && coep !== 'require-corp' && coep !== 'credentialless')
|
|
574
|
+
usage(`--coep must be require-corp or credentialless, not '${coep}'`);
|
|
575
|
+
return v.isolate ? (coep ?? 'require-corp') : undefined;
|
|
576
|
+
}
|
|
577
|
+
/** `--max-age`, `--immutable`, `--max-age-html`, or undefined when none is given. */
|
|
578
|
+
function cacheOf(v) {
|
|
579
|
+
const secs = (flag) => {
|
|
580
|
+
const raw = str(v[flag]);
|
|
581
|
+
if (raw === undefined)
|
|
582
|
+
return undefined;
|
|
583
|
+
if (!/^[0-9]{1,10}$/.test(raw) || Number(raw) > 2147483647)
|
|
584
|
+
usage(`--${flag} must be a number of seconds (0 to 2147483647), not '${raw}'`);
|
|
585
|
+
return Number(raw);
|
|
586
|
+
};
|
|
587
|
+
const maxAge = secs('max-age');
|
|
588
|
+
const maxAgeHtml = secs('max-age-html');
|
|
589
|
+
if (v.immutable && maxAge === undefined)
|
|
590
|
+
usage('--immutable needs --max-age');
|
|
591
|
+
if (maxAge === undefined && maxAgeHtml === undefined)
|
|
592
|
+
return undefined;
|
|
593
|
+
return { ...(maxAge !== undefined ? { maxAge } : {}), ...(v.immutable ? { immutable: true } : {}), ...(maxAgeHtml !== undefined ? { maxAgeHtml } : {}) };
|
|
594
|
+
}
|
|
595
|
+
/** ` Network: <url>` lines for a server bound to all interfaces (none otherwise). */
|
|
596
|
+
function networkLines(host, port, base, scheme = 'http') {
|
|
597
|
+
return networkUrls(host, port, scheme)
|
|
598
|
+
.map((u) => ` Network: ${u}${(base ?? '/').slice(1)}\n`)
|
|
599
|
+
.join('');
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* `--auth`, `--auth-file`, `SITEFILE_SERVE_AUTH`: the server's checker and what the record keeps (verifiers and the
|
|
603
|
+
* file path, never a password). Warns when the bind is not loopback: basic auth over plain HTTP sends the password
|
|
604
|
+
* in the clear.
|
|
605
|
+
*/
|
|
606
|
+
async function authOf(v, bindHost) {
|
|
607
|
+
const pairs = [...strs(v.auth).map((a) => parseAuthPair(a, '--auth'))];
|
|
608
|
+
const env = process.env.SITEFILE_SERVE_AUTH;
|
|
609
|
+
if (env !== undefined && env !== '')
|
|
610
|
+
pairs.push(parseAuthPair(env, 'SITEFILE_SERVE_AUTH'));
|
|
611
|
+
const authFile = str(v['auth-file']);
|
|
612
|
+
const entries = pairs.map((p) => ({ user: p.user, verifier: makeVerifier(p.password) }));
|
|
613
|
+
const fromFile = authFile === undefined ? [] : parseHtpasswd(await fs.readFile(authFile, 'utf8').catch(() => usage(`--auth-file: cannot read ${authFile}`)), authFile);
|
|
614
|
+
if (entries.length === 0 && authFile === undefined)
|
|
615
|
+
return { record: {} };
|
|
616
|
+
if (!isLoopback(bindHost))
|
|
617
|
+
process.stderr.write(`warning: basic authentication over plain HTTP on ${bindHost}: the password crosses the network in the clear\n`);
|
|
618
|
+
return {
|
|
619
|
+
server: new BasicAuth([...entries, ...fromFile]),
|
|
620
|
+
record: { ...(entries.length > 0 ? { auth: entries } : {}), ...(authFile !== undefined ? { authFile: path.resolve(authFile) } : {}) },
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* `--tls-cert`, `--tls-key` (or `SITEFILE_TLS_CERT`, `SITEFILE_TLS_KEY`): the PEM files, read now (the key is never logged
|
|
625
|
+
* or copied; the record keeps both paths, absolute, and a detached server reads them at every start).
|
|
626
|
+
*/
|
|
627
|
+
async function tlsOf(v) {
|
|
628
|
+
const env = (k) => (process.env[k] === '' ? undefined : process.env[k]);
|
|
629
|
+
const cert = str(v['tls-cert']) ?? env('SITEFILE_TLS_CERT');
|
|
630
|
+
const key = str(v['tls-key']) ?? env('SITEFILE_TLS_KEY');
|
|
631
|
+
if (cert === undefined && key === undefined)
|
|
632
|
+
return { record: {}, scheme: 'http' };
|
|
633
|
+
if (cert === undefined || key === undefined)
|
|
634
|
+
usage('--tls-cert and --tls-key go together');
|
|
635
|
+
const read = (f, flag) => fs.readFile(f).catch(() => usage(`--${flag}: cannot read ${f}`));
|
|
636
|
+
return {
|
|
637
|
+
server: { cert: await read(cert, 'tls-cert'), key: await read(key, 'tls-key') },
|
|
638
|
+
record: { tlsCert: path.resolve(cert), tlsKey: path.resolve(key) },
|
|
639
|
+
scheme: 'https',
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
/** `--throttle`: the spec as given and its limits. */
|
|
643
|
+
function throttleOf(v) {
|
|
644
|
+
const spec = str(v.throttle);
|
|
645
|
+
if (spec === undefined)
|
|
646
|
+
return undefined;
|
|
647
|
+
const limits = parseThrottle(spec);
|
|
648
|
+
if (limits === undefined)
|
|
649
|
+
usage(`--throttle expects 3g, slow-3g or <kbit/s>[/<latency ms>], not '${spec}'`);
|
|
650
|
+
return { spec, limits };
|
|
651
|
+
}
|
|
652
|
+
/** `--mime-file` entries, then `--mime` values (a later one replaces an earlier type for the extension), or undefined. */
|
|
653
|
+
async function mimeOf(v) {
|
|
654
|
+
const file = str(v['mime-file']);
|
|
655
|
+
const flags = strs(v.mime);
|
|
656
|
+
if (file === undefined && flags.length === 0)
|
|
657
|
+
return undefined;
|
|
658
|
+
const out = file === undefined ? new Map() : parseMimeTypes(await fs.readFile(file, 'utf8').catch(() => usage(`--mime-file: cannot read ${file}`)), file);
|
|
659
|
+
for (const f of flags) {
|
|
660
|
+
const pair = parseMimeFlag(f);
|
|
661
|
+
if (pair === undefined)
|
|
662
|
+
usage(`--mime expects ext=type/subtype, not '${f}'`);
|
|
663
|
+
out.set(pair[0], pair[1]);
|
|
664
|
+
}
|
|
665
|
+
return out;
|
|
666
|
+
}
|
|
667
|
+
/** The start message's ` Throttle: …` line (none without --throttle). */
|
|
668
|
+
function throttleLine(spec) {
|
|
669
|
+
const t = spec === undefined ? undefined : parseThrottle(spec);
|
|
670
|
+
return t === undefined ? '' : ` Throttle: ${spec} (${t.bytesPerSecond / 125} kbit/s, ${t.latencyMs} ms latency)\n`;
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* `--random-route`, `--allow-ip`, `--deny-ip`, `--stop-after`, and the sharing defaults: `noindex` on a non-loopback bind and
|
|
674
|
+
* client info (address, device) in the access log of non-loopback clients.
|
|
675
|
+
*/
|
|
676
|
+
function sharingOf(v, bindHost) {
|
|
677
|
+
const cidrs = (flag) => {
|
|
678
|
+
const text = strs(v[flag]);
|
|
679
|
+
return {
|
|
680
|
+
text,
|
|
681
|
+
parsed: text.map((t) => {
|
|
682
|
+
const c = parseCidr(t);
|
|
683
|
+
if (c === undefined)
|
|
684
|
+
usage(`--${flag}: invalid address or CIDR block '${t}'`);
|
|
685
|
+
return c;
|
|
686
|
+
}),
|
|
687
|
+
};
|
|
688
|
+
};
|
|
689
|
+
const allow = cidrs('allow-ip');
|
|
690
|
+
const deny = cidrs('deny-ip');
|
|
691
|
+
if (v['random-route'] && v.base !== undefined)
|
|
692
|
+
usage('--random-route and --base both set the path prefix; use one');
|
|
693
|
+
const randomBase = v['random-route'] ? `/${randomBytes(12).toString('hex')}/` : undefined;
|
|
694
|
+
const raw = str(v['stop-after']);
|
|
695
|
+
let stopAfter;
|
|
696
|
+
if (raw !== undefined) {
|
|
697
|
+
const m = /^([0-9]{1,6})(s|m|h|d)$/.exec(raw);
|
|
698
|
+
if (!m || Number(m[1]) === 0)
|
|
699
|
+
usage(`--stop-after expects a duration like 90s, 30m, 2h or 1d, not '${raw}'`);
|
|
700
|
+
stopAfter = { seconds: Number(m[1]) * { s: 1, m: 60, h: 3600, d: 86400 }[m[2]], text: raw };
|
|
701
|
+
}
|
|
702
|
+
const ipRules = allow.parsed.length + deny.parsed.length > 0 ? { allow: allow.parsed, deny: deny.parsed } : undefined;
|
|
703
|
+
return {
|
|
704
|
+
...(randomBase ? { randomBase } : {}),
|
|
705
|
+
server: { ...(randomBase ? { hideBase: true } : {}), ...(ipRules ? { ipRules } : {}), ...(!isLoopback(bindHost) ? { noindex: true } : {}), clientInfo: true },
|
|
706
|
+
record: {
|
|
707
|
+
...(randomBase ? { hideBase: true } : {}),
|
|
708
|
+
...(allow.text.length > 0 ? { allowIp: allow.text } : {}),
|
|
709
|
+
...(deny.text.length > 0 ? { denyIp: deny.text } : {}),
|
|
710
|
+
...(stopAfter ? { expires: new Date(Date.now() + stopAfter.seconds * 1000).toISOString() } : {}),
|
|
711
|
+
},
|
|
712
|
+
...(stopAfter ? { stopAfter } : {}),
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
/** `--max-connections-per-ip <n>`: the option (and record field) when n > 0. */
|
|
716
|
+
function perIpOf(v) {
|
|
717
|
+
const raw = str(v['max-connections-per-ip']);
|
|
718
|
+
if (raw === undefined)
|
|
719
|
+
return {};
|
|
720
|
+
if (!/^[0-9]{1,6}$/.test(raw))
|
|
721
|
+
usage(`--max-connections-per-ip must be a number (0 to 999999), not '${raw}'`);
|
|
722
|
+
const n = Number(raw);
|
|
723
|
+
return n > 0 ? { maxConnectionsPerIp: n } : {};
|
|
724
|
+
}
|
|
725
|
+
function isLoopback(host) {
|
|
726
|
+
return host === 'localhost' || host === '::1' || /^127\./.test(host);
|
|
727
|
+
}
|
|
728
|
+
/** `--log-format`, `--log-ip`, `--quiet`: the server options (and record fields) they set, only those not at their default. */
|
|
729
|
+
function loggingOf(v) {
|
|
730
|
+
const format = str(v['log-format']);
|
|
731
|
+
if (format !== undefined && format !== 'text' && format !== 'json')
|
|
732
|
+
usage(`--log-format must be text or json, not '${format}'`);
|
|
733
|
+
return { ...(format === 'json' ? { logFormat: 'json' } : {}), ...(v['log-ip'] ? { logIp: true } : {}), ...(v.quiet ? { quiet: true } : {}) };
|
|
734
|
+
}
|
|
735
|
+
/** Where a foreground server's log lines go: stdout, other lines wrapped as JSON objects under `--log-format json`. */
|
|
736
|
+
function logWriter(logging) {
|
|
737
|
+
return (l) => void process.stdout.write(`${logging.logFormat === 'json' && !l.startsWith('{') ? jsonLogLine(new Date().toISOString(), l) : l}\n`);
|
|
738
|
+
}
|
|
192
739
|
async function serveWatch(v, pos) {
|
|
193
740
|
requireArgs(pos, 0, 1, 'a build context directory');
|
|
194
741
|
if (v.detach)
|
|
@@ -196,25 +743,99 @@ async function serveWatch(v, pos) {
|
|
|
196
743
|
if (v.name !== undefined)
|
|
197
744
|
usage('--name needs -d (only detached servers are tracked)');
|
|
198
745
|
const bind = parsePublish(str(v.publish));
|
|
746
|
+
const allowedHosts = allowedHostsOf(v);
|
|
747
|
+
const isolate = isolateOf(v);
|
|
748
|
+
const cache = cacheOf(v);
|
|
749
|
+
const logging = loggingOf(v);
|
|
750
|
+
const auth = await authOf(v, bind.host);
|
|
751
|
+
const perIp = perIpOf(v);
|
|
752
|
+
if (v['stop-after'] !== undefined)
|
|
753
|
+
usage('--stop-after does not apply to --watch');
|
|
754
|
+
const sharing = sharingOf(v, bind.host);
|
|
755
|
+
const tls = await tlsOf(v);
|
|
756
|
+
const throttle = throttleOf(v);
|
|
757
|
+
const mime = await mimeOf(v);
|
|
199
758
|
const context = pos[0] ?? '.';
|
|
200
759
|
const file = str(v.file);
|
|
201
760
|
const target = str(v.target);
|
|
202
761
|
const argFiles = strs(v['build-arg-file']);
|
|
203
762
|
const argFlags = strs(v['build-arg']);
|
|
763
|
+
const pollMs = pollOption(!!v.poll, str(v['poll-interval']));
|
|
764
|
+
const buildFlags = !!file || target !== undefined || argFiles.length > 0 || argFlags.length > 0;
|
|
765
|
+
const plain = !buildFlags && !(await isFile(path.join(context, 'Sitefile')));
|
|
766
|
+
const cssInject = !v['no-css-inject'];
|
|
767
|
+
const navigate = !!v['navigate-to-changed'];
|
|
768
|
+
const reloadMode = str(v.reload) ?? 'morph';
|
|
769
|
+
const spa = spaOptions(v);
|
|
770
|
+
const baseFlag = sharing.randomBase ?? parseBase(str(v.base));
|
|
771
|
+
/** `--base`, else the path of the last good build's EXPORT BASE URL. */
|
|
772
|
+
let base = baseFlag;
|
|
773
|
+
const rewriteFlag = parseRewriteBase(str(v['rewrite-base']));
|
|
774
|
+
const noRewrite = !!v['no-rewrite-base'];
|
|
775
|
+
if (noRewrite && rewriteFlag !== undefined)
|
|
776
|
+
usage('--rewrite-base and --no-rewrite-base cannot be combined');
|
|
777
|
+
/** `--rewrite-base`, else (unless --no-rewrite-base) the last good build's production URL. */
|
|
778
|
+
let rewriteBase = noRewrite ? undefined : rewriteFlag;
|
|
779
|
+
const profile = routingFor(profileOptions(v));
|
|
780
|
+
const country = parseCountry(str(v.country));
|
|
781
|
+
const strictSiteFiles = !!v['strict-site-files'];
|
|
782
|
+
/** The site-file warnings last printed: a rebuild repeats them only when they change. */
|
|
783
|
+
let lastSiteWarnings = '';
|
|
784
|
+
const siteFiles = (tree) => {
|
|
785
|
+
if (profile?.siteFiles === false)
|
|
786
|
+
return;
|
|
787
|
+
const shown = [];
|
|
788
|
+
checkSiteFiles(tree, false, (m) => shown.push(m));
|
|
789
|
+
const text = shown.join('\n');
|
|
790
|
+
if (text !== lastSiteWarnings)
|
|
791
|
+
for (const m of shown)
|
|
792
|
+
process.stderr.write(`warning: ${m}\n`);
|
|
793
|
+
lastSiteWarnings = text;
|
|
794
|
+
checkSiteFiles(tree, strictSiteFiles, () => undefined);
|
|
795
|
+
};
|
|
796
|
+
if (reloadMode !== 'full' && reloadMode !== 'morph')
|
|
797
|
+
usage(`--reload expects full or morph, got '${reloadMode}'`);
|
|
204
798
|
if (isWildcard(bind.host))
|
|
205
799
|
process.stderr.write(`warning: binding ${bind.host}: the site will be reachable from other machines\n`);
|
|
206
800
|
let current = Tree.empty;
|
|
801
|
+
let builtAt; // Last-Modified: the time of the build being served
|
|
207
802
|
let started = false;
|
|
208
803
|
const memo = watchMemo();
|
|
209
|
-
const live = new LiveReload();
|
|
210
|
-
|
|
804
|
+
const live = new LiveReload({ resetServiceWorkers: !v['keep-service-workers'], cssInject, console: !!v.console, overlay: !v['no-overlay'], navigateToChanged: navigate, reload: reloadMode });
|
|
805
|
+
/** Serve `next` and tell open pages what changed. */
|
|
806
|
+
const swap = (next) => {
|
|
807
|
+
const event = started ? (reloadEventFor(current, next, cssInject, navigate) ?? OK_EVENT) : undefined;
|
|
808
|
+
current = next;
|
|
809
|
+
builtAt = Math.floor(Date.now() / 1000);
|
|
810
|
+
if (event !== undefined)
|
|
811
|
+
live.send(event);
|
|
812
|
+
};
|
|
813
|
+
const proxy = proxyOption(v);
|
|
814
|
+
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) });
|
|
815
|
+
const control = {};
|
|
816
|
+
let quit;
|
|
817
|
+
let quitNow;
|
|
818
|
+
const quitting = new Promise((r) => (quitNow = r));
|
|
211
819
|
try {
|
|
212
820
|
return await watchLoop({
|
|
213
821
|
context,
|
|
822
|
+
control,
|
|
823
|
+
stop: Promise.race([waitForSignal().then(() => undefined), quitting]),
|
|
824
|
+
...(pollMs !== undefined ? { pollMs } : {}),
|
|
214
825
|
...(file ? { sitefile: file } : {}),
|
|
826
|
+
...(plain ? { plain } : {}),
|
|
215
827
|
argFiles,
|
|
216
828
|
build: async () => {
|
|
829
|
+
if (started)
|
|
830
|
+
live.send(BUILDING_EVENT);
|
|
217
831
|
try {
|
|
832
|
+
if (plain) {
|
|
833
|
+
const tree = await loadDirectoryTree(context);
|
|
834
|
+
process.stdout.write(`Read ${tree.size} file${tree.size === 1 ? '' : 's'} (${tree.digest()})\n`);
|
|
835
|
+
siteFiles(tree);
|
|
836
|
+
swap(tree);
|
|
837
|
+
return { code: 0 };
|
|
838
|
+
}
|
|
218
839
|
const r = await build({
|
|
219
840
|
contextDir: context,
|
|
220
841
|
...(file ? { sitefile: file } : {}),
|
|
@@ -223,14 +844,18 @@ async function serveWatch(v, pos) {
|
|
|
223
844
|
...(v['no-lockfile'] ? { lockfile: false } : {}),
|
|
224
845
|
...(v['no-cache'] ? {} : { cacheDir: transformCacheDir() }),
|
|
225
846
|
skipBase: true,
|
|
847
|
+
keepOsMetadata: !!v['keep-os-metadata'],
|
|
226
848
|
...(memo ? { memo } : {}),
|
|
227
849
|
onNotice: (m) => process.stderr.write(`${m}\n`),
|
|
228
850
|
onWarning: (m) => process.stderr.write(`warning: ${m}\n`),
|
|
229
851
|
});
|
|
230
|
-
current = r.output;
|
|
231
852
|
process.stdout.write(`Built ${r.output.size} file${r.output.size === 1 ? '' : 's'} (${r.output.digest()})\n`);
|
|
232
|
-
|
|
233
|
-
|
|
853
|
+
siteFiles(r.output);
|
|
854
|
+
if (baseFlag === undefined)
|
|
855
|
+
base = exportBasePath(r.plan.exportBase);
|
|
856
|
+
if (!noRewrite && rewriteFlag === undefined)
|
|
857
|
+
rewriteBase = productionUrl(r.plan);
|
|
858
|
+
swap(r.output);
|
|
234
859
|
return { code: 0 };
|
|
235
860
|
}
|
|
236
861
|
catch (e) {
|
|
@@ -239,17 +864,24 @@ async function serveWatch(v, pos) {
|
|
|
239
864
|
if (e.code === 'E_USAGE')
|
|
240
865
|
return { code: usageError(e.detail) };
|
|
241
866
|
process.stderr.write(`error[${e.code}]: ${e.message}\n`);
|
|
867
|
+
live.send(errorEvent(e)); // pages show it (and pages opened later get it on connect)
|
|
242
868
|
return { code: 1 };
|
|
243
869
|
}
|
|
244
870
|
},
|
|
245
871
|
onStarted: async () => {
|
|
246
872
|
const addr = await listen(server, bind.host, bind.port);
|
|
247
873
|
started = true;
|
|
248
|
-
|
|
874
|
+
if (logging.logFormat === 'json')
|
|
875
|
+
process.stdout.write(`${startedLogLine(new Date().toISOString(), context, current.size, siteUrl(addr.host, addr.port, base, tls.scheme))}\n`);
|
|
876
|
+
else
|
|
877
|
+
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)}`);
|
|
878
|
+
quit = await terminal(v, addr, base, tls.scheme, (m) => process.stderr.write(`warning: ${m}\n`), async () => control.rebuild?.());
|
|
879
|
+
void quit.promise.then(() => quitNow());
|
|
249
880
|
},
|
|
250
881
|
});
|
|
251
882
|
}
|
|
252
883
|
finally {
|
|
884
|
+
quit?.stop();
|
|
253
885
|
if (started)
|
|
254
886
|
await closeServer(server);
|
|
255
887
|
}
|
|
@@ -268,7 +900,12 @@ const ps = {
|
|
|
268
900
|
const shown = views.filter((s) => v.all || s.status === 'running');
|
|
269
901
|
if (v.json) {
|
|
270
902
|
// 'site' is the image reference or directory being served.
|
|
271
|
-
|
|
903
|
+
// A server bound to all interfaces also lists the URLs other machines use (networkUrls).
|
|
904
|
+
// Credentials never leave the record: a server that needs them shows auth: true.
|
|
905
|
+
const out = shown.map(({ image, auth, ...rest }) => {
|
|
906
|
+
const net = rest.status === 'running' ? networkUrls(rest.host, rest.port, rest.tlsCert !== undefined ? 'https' : 'http') : [];
|
|
907
|
+
return { ...rest, ...(net.length > 0 ? { networkUrls: net } : {}), ...(auth !== undefined || rest.authFile !== undefined ? { auth: true } : {}), site: image };
|
|
908
|
+
});
|
|
272
909
|
process.stdout.write(JSON.stringify(out, null, 2) + '\n');
|
|
273
910
|
return 0;
|
|
274
911
|
}
|
|
@@ -308,7 +945,7 @@ export async function stopServer(reg, s, graceMs) {
|
|
|
308
945
|
await reg.update(s.id, { ready: false }).catch(() => undefined);
|
|
309
946
|
return true;
|
|
310
947
|
}
|
|
311
|
-
function graceOf(v) {
|
|
948
|
+
export function graceOf(v) {
|
|
312
949
|
const t = str(v.time);
|
|
313
950
|
if (t === undefined)
|
|
314
951
|
return 5000;
|
|
@@ -381,10 +1018,10 @@ export function tailLines(text, n) {
|
|
|
381
1018
|
const logs = {
|
|
382
1019
|
name: 'logs',
|
|
383
1020
|
summary: 'show a server\'s access log',
|
|
384
|
-
usage: 'server logs [-f] [-n lines] <name|id>',
|
|
1021
|
+
usage: 'server logs [-f] [-n lines] [--json] <name|id>',
|
|
385
1022
|
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' } },
|
|
1023
|
+
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)'],
|
|
1024
|
+
options: { follow: { type: 'boolean', short: 'f' }, tail: { type: 'string', short: 'n' }, json: { type: 'boolean' } },
|
|
388
1025
|
async run(v, pos) {
|
|
389
1026
|
requireArgs(pos, 1, 1, 'a server id or name');
|
|
390
1027
|
const reg = await ServerRegistry.open();
|
|
@@ -398,9 +1035,22 @@ const logs = {
|
|
|
398
1035
|
usage('--tail expects a non-negative integer');
|
|
399
1036
|
text = tailLines(text, n);
|
|
400
1037
|
}
|
|
401
|
-
|
|
402
|
-
|
|
1038
|
+
let carry = '';
|
|
1039
|
+
/** Write log bytes; with --json, whole lines only, each converted. */
|
|
1040
|
+
const emit = (chunk) => {
|
|
1041
|
+
if (!v.json)
|
|
1042
|
+
return void process.stdout.write(chunk);
|
|
1043
|
+
const lines = (carry + chunk).split('\n');
|
|
1044
|
+
carry = lines.pop() ?? '';
|
|
1045
|
+
if (lines.length > 0)
|
|
1046
|
+
process.stdout.write(lines.map((l) => `${logLineAsJson(l)}\n`).join(''));
|
|
1047
|
+
};
|
|
1048
|
+
emit(text);
|
|
1049
|
+
if (!v.follow) {
|
|
1050
|
+
if (v.json && carry !== '')
|
|
1051
|
+
process.stdout.write(`${logLineAsJson(carry)}\n`);
|
|
403
1052
|
return 0;
|
|
1053
|
+
}
|
|
404
1054
|
let pos2 = offset;
|
|
405
1055
|
let done = false;
|
|
406
1056
|
void waitForSignal().then(() => (done = true));
|
|
@@ -417,7 +1067,7 @@ const logs = {
|
|
|
417
1067
|
const buf = Buffer.alloc(size - pos2);
|
|
418
1068
|
await fh.read(buf, 0, buf.length, pos2);
|
|
419
1069
|
pos2 = size;
|
|
420
|
-
|
|
1070
|
+
emit(buf.toString('utf8'));
|
|
421
1071
|
}
|
|
422
1072
|
}
|
|
423
1073
|
finally {
|
|
@@ -438,19 +1088,12 @@ const restart = {
|
|
|
438
1088
|
requireArgs(pos, 1, 1, 'a server id or name');
|
|
439
1089
|
const reg = await ServerRegistry.open();
|
|
440
1090
|
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`);
|
|
1091
|
+
const up = await restartDetached(reg, s, graceOf(v));
|
|
1092
|
+
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
1093
|
return 0;
|
|
452
1094
|
},
|
|
453
1095
|
};
|
|
1096
|
+
export { isFile };
|
|
454
1097
|
/** Top-level: `sitefile serve`, `sitefile servers`. */
|
|
455
1098
|
export const serverCommands = new Map([
|
|
456
1099
|
['serve', run],
|