@johnhenry/sitefile 0.0.7 → 0.0.9

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.
Files changed (68) hide show
  1. package/CHANGELOG.md +104 -1
  2. package/README.md +12 -1
  3. package/lib/src/attest.d.ts +12 -3
  4. package/lib/src/attest.js +15 -10
  5. package/lib/src/bake.js +2 -1
  6. package/lib/src/base-image.d.ts +2 -0
  7. package/lib/src/base-image.js +8 -0
  8. package/lib/src/bucket-follow.d.ts +22 -0
  9. package/lib/src/bucket-follow.js +65 -0
  10. package/lib/src/bucket.d.ts +270 -0
  11. package/lib/src/bucket.js +1130 -0
  12. package/lib/src/cache-limit.d.ts +3 -3
  13. package/lib/src/cache-limit.js +21 -0
  14. package/lib/src/cli/bucket.d.ts +2 -0
  15. package/lib/src/cli/bucket.js +312 -0
  16. package/lib/src/cli/build-image.js +4 -2
  17. package/lib/src/cli/images.js +8 -5
  18. package/lib/src/cli/index.d.ts +1 -1
  19. package/lib/src/cli/index.js +13 -2
  20. package/lib/src/cli/serve-worker.js +63 -11
  21. package/lib/src/cli/servers.js +117 -29
  22. package/lib/src/cli/up.js +2 -0
  23. package/lib/src/cli/watch.d.ts +2 -0
  24. package/lib/src/cli/watch.js +2 -1
  25. package/lib/src/cli.js +6 -3
  26. package/lib/src/dictionary.d.ts +1 -7
  27. package/lib/src/dictionary.js +1 -35
  28. package/lib/src/executor.d.ts +16 -5
  29. package/lib/src/executor.js +127 -58
  30. package/lib/src/index.d.ts +2 -0
  31. package/lib/src/index.js +2 -0
  32. package/lib/src/mime-type.d.ts +6 -0
  33. package/lib/src/mime-type.js +20 -0
  34. package/lib/src/nfc.d.ts +6 -0
  35. package/lib/src/nfc.js +10 -0
  36. package/lib/src/oci.d.ts +65 -1
  37. package/lib/src/oci.js +104 -10
  38. package/lib/src/paths.d.ts +2 -6
  39. package/lib/src/paths.js +2 -8
  40. package/lib/src/plugins/env.d.ts +20 -0
  41. package/lib/src/plugins/env.js +37 -0
  42. package/lib/src/plugins/exec.d.ts +1 -1
  43. package/lib/src/plugins/exec.js +3 -2
  44. package/lib/src/plugins/host.js +3 -2
  45. package/lib/src/precompress.d.ts +6 -0
  46. package/lib/src/precompress.js +6 -0
  47. package/lib/src/recipe.d.ts +37 -0
  48. package/lib/src/recipe.js +96 -0
  49. package/lib/src/registry-ops.d.ts +5 -1
  50. package/lib/src/registry-ops.js +69 -45
  51. package/lib/src/request-path.d.ts +10 -0
  52. package/lib/src/request-path.js +42 -0
  53. package/lib/src/serve-dictionary.d.ts +11 -0
  54. package/lib/src/serve-dictionary.js +45 -0
  55. package/lib/src/serve-rules.js +1 -1
  56. package/lib/src/server.d.ts +16 -229
  57. package/lib/src/server.js +135 -795
  58. package/lib/src/servers.d.ts +25 -0
  59. package/lib/src/servers.js +62 -2
  60. package/lib/src/site-core.d.ts +368 -0
  61. package/lib/src/site-core.js +1065 -0
  62. package/lib/src/site-handler.d.ts +14 -0
  63. package/lib/src/site-handler.js +32 -0
  64. package/lib/src/store.d.ts +31 -2
  65. package/lib/src/store.js +140 -21
  66. package/lib/src/wbn.d.ts +1 -6
  67. package/lib/src/wbn.js +2 -18
  68. package/package.json +5 -1
@@ -13,6 +13,7 @@ import { BasicAuth, parseHtpasswd } from '../serve-auth.js';
13
13
  import { BUILDING_EVENT, closeServer, createSiteServer, errorEvent, formatUrl, jsonLogLine, listen, LiveReload, OK_EVENT, parseCidr, parseThrottle, reloadEventFor, startedLogLine, stoppedLogLine, routingFor } from '../server.js';
14
14
  import { loadServedTree, servedLastModified, ServerRegistry, loadServedSite, checkSiteFiles } from '../servers.js';
15
15
  import { Tree } from '../tree.js';
16
+ import { followBucket } from '../bucket-follow.js';
16
17
  import { isIgnoredChange, RebuildScheduler, resolveReal, watchPaths } from '../watch.js';
17
18
  let json = false; // `--log-format json`: every line is a JSON object
18
19
  const stamp = (m) => {
@@ -34,8 +35,9 @@ async function main() {
34
35
  const loopback = state.bind.host === 'localhost' || state.bind.host === '::1' || /^127\./.test(state.bind.host);
35
36
  // `-d --watch` on a build context (#306): built in memory by watchLoop below, served from an empty
36
37
  // tree until the first build finishes.
38
+ const bucketCache = new Map(); // a bucket server's files read so far (reloads read only what changed)
37
39
  const building = !!state.watch && state.source.kind === 'dir' && state.build !== undefined;
38
- const { tree, content } = building ? { tree: Tree.empty, content: undefined } : await loadServedSite(reg.store, state.source, { keepOsMetadata: !!state.keepOsMetadata, warn: (m) => stamp(`warning: ${m}`) });
40
+ const { tree, content } = building ? { tree: Tree.empty, content: undefined } : await loadServedSite(reg.store, state.source, { keepOsMetadata: !!state.keepOsMetadata, warn: (m) => stamp(`warning: ${m}`), bucketCache });
39
41
  if (!building && routingFor(state)?.siteFiles !== false)
40
42
  checkSiteFiles(tree, !!state.strictSiteFiles, (m) => stamp(`warning: ${m}`), content);
41
43
  let modified = building ? undefined : await servedLastModified(reg.store, state.source);
@@ -49,10 +51,14 @@ async function main() {
49
51
  const live = watching || state.reload !== undefined ? new LiveReload(liveOptionsOf(state)) : undefined;
50
52
  const authEntries = [...(state.auth ?? []), ...(state.authFile !== undefined ? parseHtpasswd(await readFile(state.authFile, 'utf8'), state.authFile) : [])];
51
53
  const server = createSiteServer(() => current, { ...(live ? { liveReload: live, warn: (m) => stamp(`warning: ${m}`) } : {}), spa: state.spa, allowedHosts: state.allowedHosts ?? [], cors: !!state.cors, ...(state.isolate ? { isolate: state.isolate } : {}), ...(state.cache ? { cache: state.cache } : {}), ...(json ? { logFormat: 'json' } : {}), logIp: !!state.logIp, quiet: !!state.quiet, ...(authEntries.length > 0 || state.authFile !== undefined ? { auth: new BasicAuth(authEntries) } : {}), ...(state.maxConnectionsPerIp ? { maxConnectionsPerIp: state.maxConnectionsPerIp } : {}), ...(state.hideBase ? { hideBase: true } : {}), ...(ipRules ? { ipRules } : {}), ...(loopback ? {} : { noindex: true }), clientInfo: true, compress: !!state.compress, ...(state.mime ? { mime: new Map(Object.entries(state.mime)) } : {}), ...(state.throttle !== undefined && parseThrottle(state.throttle) ? { throttle: parseThrottle(state.throttle) } : {}), ...(state.tlsCert !== undefined && state.tlsKey !== undefined ? { tls: { cert: await readFile(state.tlsCert), key: await readFile(state.tlsKey) } } : {}), serverId: id, lastModified: () => modified, log: stamp, ...(content ? { content } : {}), ...(state.country !== undefined ? { country: state.country } : {}), ...(state.spaExclude ? { spaExclude: state.spaExclude } : {}), ...(state.spaFallback !== undefined ? { spaFallback: state.spaFallback } : {}), ...(building ? { base: () => base, rewriteBase: () => rewriteBase } : { ...(state.base !== undefined ? { base: state.base } : {}), ...(state.rewriteBase !== undefined ? { rewriteBase: state.rewriteBase } : {}) }), ...(routingFor(state) ? { profile: routingFor(state) } : {}) });
52
- const addr = await listen(server, state.bind.host, state.bind.port);
53
- await reg.update(id, { pid: process.pid, host: addr.host, port: addr.port, ready: true, error: undefined });
54
- const root = formatUrl(addr.host, addr.port, state.tlsCert !== undefined ? 'https' : 'http');
55
- const served = () => {
54
+ /**
55
+ * Bind, record the address and report ready. A build context (#354) does this only after its first build
56
+ * has finished, so no request is answered from the empty tree and `serve -d` returns when the site is there.
57
+ */
58
+ const up = async () => {
59
+ const addr = await listen(server, state.bind.host, state.bind.port);
60
+ await reg.update(id, { pid: process.pid, host: addr.host, port: addr.port, ready: true, error: undefined });
61
+ const root = formatUrl(addr.host, addr.port, state.tlsCert !== undefined ? 'https' : 'http');
56
62
  const url = `${root}${(base ?? '/').slice(1)}`;
57
63
  if (json)
58
64
  stamp(startedLogLine(new Date().toISOString(), state.image, current.size, url));
@@ -60,8 +66,8 @@ async function main() {
60
66
  stamp(`serving ${state.image} (${current.size} files) at ${url}`);
61
67
  };
62
68
  if (!building)
63
- served();
64
- const unwatch = live && building
69
+ await up();
70
+ const unwatchSource = live && building
65
71
  ? watchBuild(state, live, stamp, {
66
72
  current: () => current,
67
73
  swap: (next) => {
@@ -74,7 +80,10 @@ async function main() {
74
80
  if (state.rewriteBase === undefined && !state.build?.noRewriteBase)
75
81
  rewriteBase = rb;
76
82
  },
77
- started: served,
83
+ started: up,
84
+ failed: (message) => {
85
+ void reg.update(id, { pid: 0, ready: false, error: message }).catch(() => undefined).then(() => process.exit(1));
86
+ },
78
87
  })
79
88
  : live && watching
80
89
  ? await watchDirectory(reg, state, live, stamp, (next, lastModified) => {
@@ -82,6 +91,31 @@ async function main() {
82
91
  modified = lastModified;
83
92
  }, () => current)
84
93
  : () => undefined;
94
+ // A bucket is followed on its own (a request after a change sees the new files within a second); with
95
+ // `--reload` the open pages reload as well.
96
+ const source = state.source;
97
+ const unfollow = source.kind === 'bucket'
98
+ ? followBucket(reg.store, source, {
99
+ reload: async () => {
100
+ const next = await loadServedTree(reg.store, source, { keepOsMetadata: !!state.keepOsMetadata, warn: (m) => stamp(`warning: ${m}`), bucketCache });
101
+ if (next.digest() === current.digest())
102
+ return;
103
+ if (routingFor(state)?.siteFiles !== false)
104
+ checkSiteFiles(next, !!state.strictSiteFiles, (m) => stamp(`warning: ${m}`));
105
+ const event = live ? (reloadEventFor(current, next, !state.noCssInject, !!state.navigateToChanged) ?? OK_EVENT) : undefined;
106
+ current = next;
107
+ modified = await servedLastModified(reg.store, source);
108
+ if (event !== undefined)
109
+ live?.send(event);
110
+ stamp(`Re-read ${state.image} (${next.size} files)`);
111
+ },
112
+ onError: (e) => stamp(`warning: ${e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : e.message}; serving the last good copy`),
113
+ })
114
+ : undefined;
115
+ const unwatch = () => {
116
+ unwatchSource();
117
+ unfollow?.();
118
+ };
85
119
  const stop = (signal) => () => {
86
120
  unwatch();
87
121
  if (json)
@@ -189,17 +223,35 @@ function watchBuild(state, live, stamp, site) {
189
223
  return { code: 1 };
190
224
  }
191
225
  };
226
+ let listening = false;
192
227
  void watchLoop({
193
228
  context,
194
229
  ...(b.sitefile !== undefined ? { sitefile: b.sitefile } : {}),
195
230
  argFiles: b.buildArgFiles ?? [],
196
231
  ...(state.pollMs !== undefined ? { pollMs: state.pollMs } : {}),
197
232
  build: run,
198
- onStarted: async () => site.started(),
233
+ onStarted: async () => {
234
+ try {
235
+ await site.started();
236
+ }
237
+ catch (e) {
238
+ site.failed(e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : `error: ${e.message}`);
239
+ throw e;
240
+ }
241
+ listening = true;
242
+ },
199
243
  stop: stopped,
200
244
  say: (line) => stamp(line.replace(/\n$/, '')),
201
- }).catch((e) => {
202
- stamp(e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : `error: ${e.message}`);
245
+ })
246
+ .then(() => {
247
+ if (!listening)
248
+ site.failed('the first build did not finish');
249
+ })
250
+ .catch((e) => {
251
+ const message = e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : `error: ${e.message}`;
252
+ stamp(message);
253
+ if (!listening)
254
+ site.failed(message);
203
255
  });
204
256
  return stop;
205
257
  }
@@ -5,15 +5,18 @@ import net from 'node:net';
5
5
  import path from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { SitefileError } from '../errors.js';
8
+ import { findRecipeName, isDefaultRecipeNames, recipeNames, RECIPE_NAMES_ENV } from '../recipe.js';
8
9
  import { collectBuildArgs } from '../build-args.js';
9
10
  import { build } from '../executor.js';
10
11
  import { networkOption } from './network.js';
11
12
  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';
13
+ import { BUILDING_EVENT, closeServer, createSiteResponder, createSiteServer, handlerOptionsOf, 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';
14
+ import { isRunning, loadDirectoryTree, loadServedTree, pidAlive, servedLastModified, ServerRegistry, loadServedSite, checkSiteFiles, awaitReady } from '../servers.js';
14
15
  import { BasicAuth, makeVerifier, parseAuthPair, parseHtpasswd } from '../serve-auth.js';
15
16
  import { Store } from '../store.js';
16
17
  import { Tree } from '../tree.js';
18
+ import { bucketLabel, Buckets, parseBucketSource } from '../bucket.js';
19
+ import { followBucket } from '../bucket-follow.js';
17
20
  import { transformCacheDir } from './cache.js';
18
21
  import { requireArgs, str, strs, table, usage, usageError } from './common.js';
19
22
  import { watchMemo } from '../memo.js';
@@ -130,6 +133,12 @@ export async function archiveSource(arg) {
130
133
  * archive file by that name (`site.zip`). Whether a file is an archive is checked when it is loaded.
131
134
  */
132
135
  export async function resolveSource(store, arg) {
136
+ const bucket = parseBucketSource(arg);
137
+ if (bucket) {
138
+ const buckets = Buckets.open(store);
139
+ await buckets.resolveDirectory(bucket.name, bucket.prefix === undefined ? [] : bucket.prefix.split('/'));
140
+ return { label: bucketLabel(bucket.name, bucket.prefix), source: { kind: 'bucket', name: bucket.name, ...(bucket.prefix !== undefined ? { prefix: bucket.prefix } : {}) } };
141
+ }
133
142
  if (/^(\.\.?|~.*|\.\.?\/.*|\/.*|.*\/)$/.test(arg)) {
134
143
  const dir = path.resolve(arg);
135
144
  if (await isFile(dir))
@@ -164,33 +173,24 @@ async function startDetached(reg, state) {
164
173
  const child = spawn(process.execPath, [WORKER, state.id], {
165
174
  detached: true,
166
175
  stdio: ['ignore', log.fd, log.fd],
167
- env: { ...process.env, SITEFILE_HOME: reg.store.home },
176
+ // The recipe names of this process reach the worker, which is another process.
177
+ env: { ...process.env, SITEFILE_HOME: reg.store.home, ...(isDefaultRecipeNames(recipeNames()) ? {} : { [RECIPE_NAMES_ENV]: recipeNames().join(',') }) },
168
178
  });
169
179
  await log.close();
170
180
  let exited = false;
171
181
  child.once('exit', () => (exited = true));
172
182
  child.once('error', () => (exited = true));
173
- const deadline = Date.now() + 15_000;
174
- for (;;) {
175
- const cur = await reg.read(state.id);
176
- if (cur?.ready) {
177
- child.unref();
178
- return cur;
179
- }
180
- if (exited || cur?.error || Date.now() > deadline) {
181
- if (!exited)
182
- child.kill('SIGKILL');
183
- const why = cur?.error ?? (exited ? 'the server process exited before it was ready' : 'timed out waiting for the server to start');
184
- throw new SitefileError('E_SERVER', why.replace(/^error\[E_SERVER\]: /, ''));
185
- }
186
- await sleep(40);
187
- }
183
+ const up = await awaitReady(() => reg.read(state.id), () => exited, () => child.kill('SIGKILL'),
184
+ // A build context is ready after its first build (#354), which may take a while.
185
+ state.watch && state.build !== undefined ? { timeoutMs: 120_000 } : {});
186
+ child.unref();
187
+ return up;
188
188
  }
189
189
  const run = {
190
190
  name: 'serve',
191
- summary: 'serve an image, directory or archive file over HTTP',
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 the detached server does the same (a build context or a plain directory) and keeps\nthe build and page options in its record; pages left open across server restart reload once it is back.',
191
+ summary: 'serve an image, directory, archive file or bucket over HTTP',
192
+ usage: 'serve [--name n] [-p [host:]port] [-d] [--spa] <ref|id|./dir|file|bucket:name[/prefix]> | 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. A bucket (bucket:<name>[/prefix], see "sitefile bucket --help") is followed: a request made after its files change sees the new ones. 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 the detached server does the same (a build context or a plain directory) and keeps\nthe build and page options in its record; pages left open across server restart reload once it is back.',
194
194
  flags: [
195
195
  '--name <n> name for the server (-d only; default site-<6 hex>)',
196
196
  '-p, --publish <[host:]port> address to bind (default 127.0.0.1, a free port)',
@@ -236,6 +236,7 @@ const run = {
236
236
  '--html-handling <mode> auto, force-slash, drop-slash or none: canonical page URLs (Cloudflare\'s modes)',
237
237
  '--country <code> the country _redirects Country= conditions match (there is no geolocation locally)',
238
238
  '--strict-site-files refuse to serve when a _redirects or _headers line would be ignored',
239
+ '--max-bytes <n> a bucket: most bytes it may hold in memory (default 2147483648; a larger bucket is an error)',
239
240
  '--keep-os-metadata serve __MACOSX, ._*, Thumbs.db and desktop.ini of a directory or archive (default: skipped)',
240
241
  '--open[=<path>] open the site (at <path>) in the browser once it is served ($BROWSER, else the system default)',
241
242
  '--qr print a QR code of the network URL (with -p 0.0.0.0:...), else of the local URL',
@@ -271,6 +272,7 @@ const run = {
271
272
  country: { type: 'string' },
272
273
  'strict-site-files': { type: 'boolean' },
273
274
  'keep-os-metadata': { type: 'boolean' },
275
+ 'max-bytes': { type: 'string' },
274
276
  'allowed-host': { type: 'string', multiple: true },
275
277
  proxy: { type: 'string', multiple: true },
276
278
  'allow-hosts': { type: 'string', multiple: true },
@@ -297,6 +299,8 @@ const run = {
297
299
  'allow-ip': { type: 'string', multiple: true },
298
300
  'deny-ip': { type: 'string', multiple: true },
299
301
  'stop-after': { type: 'string' },
302
+ // Hidden (conformance): answer the requests on stdin with the site handler and exit.
303
+ 'respond-stdin': { type: 'boolean' },
300
304
  'tls-cert': { type: 'string' },
301
305
  compress: { type: 'boolean' },
302
306
  throttle: { type: 'string' },
@@ -321,6 +325,16 @@ const run = {
321
325
  sync: { type: 'string' },
322
326
  },
323
327
  async run(v, pos) {
328
+ if (v['respond-stdin'])
329
+ refuseWithRespondStdin(v);
330
+ // A bucket is followed on its own; `--watch` on one only adds live reload, as `--reload` does.
331
+ if (v.watch && pos[0]?.startsWith('bucket:')) {
332
+ for (const f of WATCH_ONLY)
333
+ if (v[f] !== undefined && v[f] !== false)
334
+ usage(`--${f} does not apply to a bucket: the server follows it on its own (--watch only turns on live reload, like --reload)`);
335
+ v.watch = false;
336
+ v.reload ??= '';
337
+ }
324
338
  if (v.watch && !v.detach)
325
339
  return serveWatch(v, pos);
326
340
  // `-d --watch`: a plain directory re-read on change, or a build context built and rebuilt on change,
@@ -333,7 +347,7 @@ const run = {
333
347
  if (watchDetached)
334
348
  requireArgs(pos, 0, 1, 'a directory');
335
349
  else
336
- requireArgs(pos, 1, 1, 'an image reference, ./directory or archive file');
350
+ requireArgs(pos, 1, 1, 'an image reference, ./directory, archive file or bucket:name');
337
351
  const pollMs = watchDetached ? pollOption(!!v.poll, str(v['poll-interval'])) : undefined;
338
352
  const sync = watchDetached ? syncOf(v) : undefined;
339
353
  // `--reload` without --watch: the live-reload script and stream, so pages reload after a restart.
@@ -360,30 +374,65 @@ const run = {
360
374
  if (name !== undefined && !v.detach)
361
375
  usage('--name needs -d (only detached servers are tracked)');
362
376
  const store = await Store.open();
363
- const { label, source } = watchDetached ? await watchedDirectory(pos[0] ?? '.') : await resolveSource(store, pos[0]);
377
+ const resolved = watchDetached ? await watchedDirectory(pos[0] ?? '.') : await resolveSource(store, pos[0]);
378
+ const label = resolved.label;
379
+ let source = resolved.source;
380
+ const maxBytes = str(v['max-bytes']);
381
+ if (maxBytes !== undefined) {
382
+ if (source.kind !== 'bucket')
383
+ usage('--max-bytes is for a bucket (bucket:<name>)');
384
+ if (!/^[0-9]{1,15}$/.test(maxBytes) || Number(maxBytes) < 1)
385
+ usage(`--max-bytes expects a number of bytes (at least 1), got '${maxBytes}'`);
386
+ source = { ...source, maxBytes: Number(maxBytes) };
387
+ }
364
388
  const watchRecord = watchDetached ? await detachedWatchOf(v, source) : {};
365
389
  if (isWildcard(bind.host))
366
390
  process.stderr.write(`warning: binding ${bind.host}: the site will be reachable from other machines\n`);
367
391
  const keepOsMetadata = !!v['keep-os-metadata'];
368
392
  const warn = (m) => void process.stderr.write(`warning: ${m}\n`);
369
393
  if (!v.detach) {
370
- const { tree, content, close } = await loadServedSite(store, source, { keepOsMetadata, warn });
394
+ const bucketCache = new Map(); // a bucket server's files read so far (reloads read only what changed)
395
+ const { tree, content, close } = await loadServedSite(store, source, { keepOsMetadata, warn, bucketCache });
371
396
  if (profile?.siteFiles !== false)
372
397
  checkSiteFiles(tree, strictSiteFiles, warn, content);
373
398
  warnSpaFallback(tree, spa.spaFallback, warn);
374
- const modified = await servedLastModified(store, source);
399
+ let modified = await servedLastModified(store, source);
375
400
  let current = tree;
376
401
  const proxy = proxyOption(v);
377
402
  const live = reload !== undefined ? new LiveReload({ reload }) : undefined;
378
- const server = createSiteServer(() => current, { ...(live ? { liveReload: live, warn } : {}), 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) });
403
+ const siteOptions = { ...(live ? { liveReload: live, warn } : {}), 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) };
404
+ if (v['respond-stdin']) {
405
+ await respondStdin(() => current, siteOptions);
406
+ close();
407
+ return 0;
408
+ }
409
+ const server = createSiteServer(() => current, siteOptions);
379
410
  const addr = await listen(server, bind.host, bind.port);
380
411
  if (logging.logFormat === 'json')
381
412
  process.stdout.write(`${startedLogLine(new Date().toISOString(), label, tree.size, siteUrl(addr.host, addr.port, base, tls.scheme))}\n`);
382
413
  else
383
414
  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)}`);
415
+ const unfollow = source.kind === 'bucket'
416
+ ? followBucket(store, source, {
417
+ reload: async () => {
418
+ const next = await loadServedSite(store, source, { keepOsMetadata, warn, bucketCache });
419
+ if (next.tree.digest() === current.digest())
420
+ return;
421
+ if (profile?.siteFiles !== false)
422
+ checkSiteFiles(next.tree, strictSiteFiles, warn, next.content);
423
+ const event = live ? (reloadEventFor(current, next.tree, true, false) ?? OK_EVENT) : undefined;
424
+ current = next.tree;
425
+ modified = await servedLastModified(store, source);
426
+ if (event !== undefined)
427
+ live?.send(event);
428
+ process.stdout.write(`Re-read ${label} (${current.size} files)\n`);
429
+ },
430
+ onError: (e) => warn(`${label}: ${e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : e.message}; serving the last good copy`),
431
+ })
432
+ : undefined;
384
433
  const quit = await terminal(v, addr, base, tls.scheme, warn, async () => {
385
434
  if (source.kind !== 'dir') {
386
- 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`);
435
+ process.stdout.write(`Nothing to re-read: ${label} is ${source.kind === 'image' ? 'an image' : source.kind === 'bucket' ? 'a bucket, followed on its own' : 'an archive file'}; ${source.kind === 'bucket' ? 'changes are picked up within a second' : 'start serve again to read it again'}\n`);
387
436
  return;
388
437
  }
389
438
  const next = await loadServedSite(store, source, { keepOsMetadata, warn });
@@ -398,6 +447,7 @@ const run = {
398
447
  if (why === 'stop-after')
399
448
  process.stdout.write(`Stopping: --stop-after ${stop.text} reached\n`);
400
449
  quit.stop();
450
+ unfollow?.();
401
451
  await closeServer(server);
402
452
  close();
403
453
  return 0;
@@ -413,6 +463,44 @@ const run = {
413
463
  return 0;
414
464
  },
415
465
  };
466
+ /**
467
+ * `--respond-stdin` has no listener, so what belongs to one is a usage error, not something silently ignored (or, for `-d`,
468
+ * a real server): detaching, watching, a bind address, TLS and authentication. The same refusal as the Rust CLI's.
469
+ */
470
+ function refuseWithRespondStdin(v) {
471
+ for (const [flag, shown] of [['detach', '-d'], ['watch', '--watch'], ['publish', '-p'], ['tls-cert', '--tls-cert'], ['tls-key', '--tls-key'], ['auth', '--auth'], ['auth-file', '--auth-file']]) {
472
+ if (v[flag] !== undefined && v[flag] !== false)
473
+ usage(`--respond-stdin answers without a listener: it takes no ${shown}`);
474
+ }
475
+ }
476
+ /**
477
+ * The hidden `serve --respond-stdin` (conformance, see conformance/servers.mjs): read a JSON array of requests
478
+ * (`{ method, target, headers }`) from stdin, answer each with the site handler alone (no listener, no `Host`
479
+ * check, no authentication) and print a JSON array of `{ status, headers: [[name, value]...], body: <base64> }`.
480
+ * The Rust twin is `respond_stdin` in rust/src/cli/servers.rs.
481
+ */
482
+ async function respondStdin(site, options) {
483
+ let text = '';
484
+ for await (const chunk of process.stdin)
485
+ text += chunk;
486
+ const bad = () => usage('--respond-stdin expects a JSON array of requests ({ method, target, headers }) on stdin');
487
+ let requests;
488
+ try {
489
+ requests = JSON.parse(text);
490
+ }
491
+ catch {
492
+ bad();
493
+ }
494
+ if (!Array.isArray(requests) || requests.some((r) => typeof r !== 'object' || r === null || Array.isArray(r)))
495
+ bad();
496
+ const respond = createSiteResponder(site, handlerOptionsOf(options));
497
+ const answers = [];
498
+ for (const r of requests) {
499
+ const { response } = await respond({ method: r.method ?? 'GET', target: r.target ?? '/', headers: new Headers(r.headers ?? {}) });
500
+ answers.push({ status: response.status, headers: [...response.headers], body: Buffer.from(await response.arrayBuffer()).toString('base64') });
501
+ }
502
+ process.stdout.write(`${JSON.stringify(answers)}\n`);
503
+ }
416
504
  /**
417
505
  * `serve -d`: check that the source loads, allocate an ID and name, record the server, start its worker and
418
506
  * wait until it listens. On failure the record is removed.
@@ -571,7 +659,7 @@ async function detachedWatchOf(v, source) {
571
659
  ...(v['navigate-to-changed'] ? { navigateToChanged: true } : {}),
572
660
  ...(v['keep-service-workers'] ? { keepServiceWorkers: true } : {}),
573
661
  };
574
- if (!buildFlags && !(await isFile(path.join(dir, 'Sitefile'))))
662
+ if (!buildFlags && findRecipeName(dir) === undefined)
575
663
  return page;
576
664
  if (v['no-rewrite-base'] && v['rewrite-base'] !== undefined)
577
665
  usage('--rewrite-base and --no-rewrite-base cannot be combined');
@@ -859,7 +947,7 @@ async function serveWatch(v, pos) {
859
947
  const argFlags = strs(v['build-arg']);
860
948
  const pollMs = pollOption(!!v.poll, str(v['poll-interval']));
861
949
  const buildFlags = !!file || target !== undefined || argFiles.length > 0 || argFlags.length > 0;
862
- const plain = !buildFlags && !(await isFile(path.join(context, 'Sitefile')));
950
+ const plain = !buildFlags && findRecipeName(context) === undefined;
863
951
  const cssInject = !v['no-css-inject'];
864
952
  const navigate = !!v['navigate-to-changed'];
865
953
  const reloadMode = reloadOf(v) ?? 'morph';
package/lib/src/cli/up.js CHANGED
@@ -14,6 +14,8 @@ const PATH_LIKE = /^(\.\.?|~.*|\.\.?\/.*|\/.*|.*\/)$/;
14
14
  * an image reference or ID, else an archive file by that name next to the file.
15
15
  */
16
16
  async function fileSource(store, dir, src) {
17
+ if (src.startsWith('bucket:'))
18
+ return resolveSource(store, src);
17
19
  if (PATH_LIKE.test(src))
18
20
  return resolveSource(store, path.resolve(dir, src));
19
21
  try {
@@ -9,6 +9,8 @@ export interface WatchLoopOptions {
9
9
  readonly context: string;
10
10
  /** `-f`: the Sitefile path (default `<context>/Sitefile`). */
11
11
  readonly sitefile?: string;
12
+ /** The recipe names searched when `sitefile` is not given (default: the process-wide list). */
13
+ readonly recipeNames?: readonly string[];
12
14
  /** `--build-arg-file` files; they are re-read on every build. */
13
15
  readonly argFiles: readonly string[];
14
16
  readonly build: () => Promise<BuildOutcome>;
@@ -1,6 +1,7 @@
1
1
  import { promises as fs } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { SitefileError } from '../errors.js';
4
+ import { recipePath } from '../recipe.js';
4
5
  import { resolveStoreHome } from '../store.js';
5
6
  import { DEFAULT_POLL_MS, isIgnoredChange, RebuildScheduler, resolveReal, watchPaths } from '../watch.js';
6
7
  /**
@@ -36,7 +37,7 @@ export async function watchLoop(o) {
36
37
  if (!st?.isDirectory())
37
38
  throw new SitefileError('E_NOT_FOUND', `'${o.context}' is not a directory`);
38
39
  const root = await fs.realpath(o.context);
39
- const sitefile = await resolveReal(o.sitefile ?? path.join(o.context, 'Sitefile'));
40
+ const sitefile = await resolveReal(o.sitefile ?? recipePath(o.context, o.recipeNames));
40
41
  const argFiles = await Promise.all(o.argFiles.map(resolveReal));
41
42
  // The build itself writes the export, Sitefile.lock and (maybe) the store; none of that is input.
42
43
  const ignored = new Set([await resolveReal(resolveStoreHome()), path.join(path.dirname(sitefile), 'Sitefile.lock')]);
package/lib/src/cli.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { parseArgs } from 'node:util';
3
3
  import path from 'node:path';
4
4
  import { errorJson, SitefileError, isSitefileError } from './errors.js';
5
+ import { findRecipeName, recipeNames } from './recipe.js';
5
6
  import { build, buildToDirectory, checkPlanPins, lintBuild, planBuild, sitefileCompression } from './executor.js';
6
7
  import { LINT_RULES } from './lint.js';
7
8
  import { compressionFromExtension, defaultOutName, formatFromExtension } from './export-formats.js';
@@ -73,7 +74,9 @@ Options:
73
74
  --sbom attach an SBOM attestation (CycloneDX: every file with its SHA-256);
74
75
  both are OCI 1.1 referrers of the image (its ID does not change),
75
76
  written into the oci export and kept with -t images for push
76
- --platform <os/arch> oci image platform (default linux/amd64); with a BASE, the platform pulled
77
+ --platform <os/arch> oci image platform (default linux/amd64); with a BASE, the platform pulled.
78
+ A list (linux/amd64,linux/arm64) writes one image index over a manifest per
79
+ platform, the site layer shared; its digest is the image ID
77
80
  --base <image> build the oci image on <image> (runnable; overrides EXPORT ... AS oci BASE);
78
81
  a bare name means Docker Hub. Pin it: nginx:alpine@sha256:...
79
82
  --insecure-registry <h> allow plain http to registry host[:port] (repeatable; localhost always may)
@@ -392,7 +395,7 @@ export async function main(argv, run = {}) {
392
395
  const options = {
393
396
  contextDir: context,
394
397
  ...(file ? { sitefile: file } : {}),
395
- ...(fetched ? { label: o.file ?? 'Sitefile' } : {}),
398
+ ...(fetched ? { label: o.file ?? findRecipeName(context) ?? recipeNames()[0] } : {}),
396
399
  ...(o.target !== undefined ? { target: o.target } : {}),
397
400
  buildArgs,
398
401
  ...(secrets.size ? { secrets } : {}),
@@ -464,7 +467,7 @@ export async function main(argv, run = {}) {
464
467
  labels,
465
468
  gitLabels: !!o['git-labels'],
466
469
  attest,
467
- build: { contextDir: context, ...(file ? { sitefile: file } : {}), ...(fetched ? { label: o.file ?? 'Sitefile' } : {}), buildArgs },
470
+ build: { contextDir: context, ...(file ? { sitefile: file } : {}), ...(fetched ? { label: o.file ?? findRecipeName(context) ?? recipeNames()[0] } : {}), buildArgs },
468
471
  };
469
472
  await remoteCache?.load();
470
473
  const dictionaryFrom = await previousBuild(o['experimental-dictionary']);
@@ -7,10 +7,4 @@ export interface DictionaryResult {
7
7
  }
8
8
  /** The exported tree with `.dcz` deltas against `previous` and the `Use-As-Dictionary` headers. */
9
9
  export declare function addDictionaryDeltas(tree: Tree, previous: Tree): DictionaryResult;
10
- /** True when `Accept-Encoding` lists `dcz` with a non-zero quality. */
11
- export declare function acceptsDcz(acceptEncoding: string | undefined): boolean;
12
- /**
13
- * The `dcz` response for `path`: the bytes of `<path>.dcz` when the request accepts `dcz` and its
14
- * `Available-Dictionary` is the hash the delta was made against; otherwise undefined.
15
- */
16
- export declare function deltaFor(tree: Tree, path: string, availableDictionary: string | undefined, acceptEncoding: string | undefined): Uint8Array | undefined;
10
+ export { acceptsDcz, deltaFor } from './serve-dictionary.js';
@@ -51,39 +51,5 @@ export function addDictionaryDeltas(tree, previous) {
51
51
  }
52
52
  return { tree: tree.withFiles(added, 'overwrite'), deltas };
53
53
  }
54
- /** The bytes of an RFC 8941 byte sequence (`:base64:`), or undefined. */
55
- function sfBinary(v) {
56
- const m = v === undefined ? null : /^\s*:([A-Za-z0-9+/]*={0,2}):\s*$/.exec(v);
57
- return m ? new Uint8Array(Buffer.from(m[1], 'base64')) : undefined;
58
- }
59
- /** True when `Accept-Encoding` lists `dcz` with a non-zero quality. */
60
- export function acceptsDcz(acceptEncoding) {
61
- if (acceptEncoding === undefined)
62
- return false;
63
- return acceptEncoding.split(',').some((part) => {
64
- const [token, ...params] = part.split(';').map((s) => s.trim());
65
- if (token?.toLowerCase() !== 'dcz')
66
- return false;
67
- const q = params.find((p) => /^q=/i.test(p));
68
- return q === undefined || Number(q.slice(2)) > 0;
69
- });
70
- }
71
- /**
72
- * The `dcz` response for `path`: the bytes of `<path>.dcz` when the request accepts `dcz` and its
73
- * `Available-Dictionary` is the hash the delta was made against; otherwise undefined.
74
- */
75
- export function deltaFor(tree, path, availableDictionary, acceptEncoding) {
76
- if (!acceptsDcz(acceptEncoding))
77
- return undefined;
78
- const hash = sfBinary(availableDictionary);
79
- if (!hash || hash.byteLength !== 32)
80
- return undefined;
81
- const sidecar = tree.get(`${path}.dcz`);
82
- if (!sidecar || sidecar.bytes.byteLength < 40)
83
- return undefined;
84
- for (let i = 0; i < 32; i++)
85
- if (sidecar.bytes[8 + i] !== hash[i])
86
- return undefined;
87
- return sidecar.bytes;
88
- }
54
+ export { acceptsDcz, deltaFor } from './serve-dictionary.js';
89
55
  //# sourceMappingURL=dictionary.js.map
@@ -21,8 +21,13 @@ import type { TemplateNode } from './render.js';
21
21
  export interface BuildOptions {
22
22
  /** Build context directory; local paths resolve from here. */
23
23
  readonly contextDir: string;
24
- /** Sitefile path. Default: `<contextDir>/Sitefile`. */
24
+ /** Sitefile path. Default: the first of `recipeNames` that exists in `contextDir`. */
25
25
  readonly sitefile?: string;
26
+ /**
27
+ * The file names searched, in order, in `contextDir` when `sitefile` is not given (default: the
28
+ * process-wide list, `recipeNames()`, `["Sitefile"]` unless changed). An empty list is the same as none.
29
+ */
30
+ readonly recipeNames?: readonly string[];
26
31
  /** How messages name the Sitefile (default: its path relative to the working directory). */
27
32
  readonly label?: string;
28
33
  /**
@@ -135,6 +140,8 @@ export interface BuildResult {
135
140
  readonly lockfileWritten: boolean;
136
141
  /** The resolved BASE image (EXPORT ... AS oci BASE <image> or --base), whose blobs are in the store. */
137
142
  readonly base?: BaseImage;
143
+ /** With two or more `--platform`s: each platform's resolved BASE (`base` is the first platform's). */
144
+ readonly bases?: ReadonlyMap<string, BaseImage>;
138
145
  /** The `FROM image` stage bases this build read, in stage order (name and image digest). */
139
146
  readonly images?: readonly FromImageUse[];
140
147
  /** Allow-listed tools this build resolved. */
@@ -181,7 +188,7 @@ interface Loaded {
181
188
  readonly source: string;
182
189
  }
183
190
  /** Read, parse and validate a Sitefile. */
184
- export declare function loadProgram(options: Pick<BuildOptions, 'contextDir' | 'sitefile' | 'label'>): Promise<Loaded>;
191
+ export declare function loadProgram(options: Pick<BuildOptions, 'contextDir' | 'sitefile' | 'label' | 'recipeNames'>): Promise<Loaded>;
185
192
  /** Parse, validate and evaluate variables, without reading any sources. */
186
193
  export declare function planBuild(options: BuildOptions): Promise<Plan>;
187
194
  /** `validate`'s lint warnings (src/lint.ts) for the whole Sitefile (a `--target` does not narrow them). */
@@ -272,7 +279,9 @@ export declare function sitefileCompression(plan: Pick<Plan, 'exportFormat' | 'e
272
279
  * The attestations (`--provenance`, `--sbom`) of an image built from `result`: in-toto statements
273
280
  * whose subject is the image manifest. They never change the image itself.
274
281
  */
275
- export declare function imageAttestations(result: BuildResult, img: Pick<OciImage, 'manifestDigest' | 'manifestBytes' | 'configBytes' | 'root'>, options: Pick<BuildOptions, 'contextDir' | 'sitefile' | 'label' | 'buildArgs' | 'platform'>, request: AttestRequest): Promise<Referrer[]>;
282
+ export declare function imageAttestations(result: BuildResult, img: Pick<OciImage, 'manifestDigest' | 'manifestBytes' | 'configBytes' | 'root'> & {
283
+ readonly mediaType?: string;
284
+ }, options: Pick<BuildOptions, 'contextDir' | 'sitefile' | 'label' | 'buildArgs' | 'platform'>, request: AttestRequest): Promise<Referrer[]>;
276
285
  /** What fetching a remote IMPORT needs: the network policy and the lockfile rules (and, for builds, the vendor directory). */
277
286
  export interface RemoteEnv {
278
287
  readonly policy: FetchPolicy;
@@ -322,7 +331,7 @@ export interface LabelScope {
322
331
  readonly dir: string;
323
332
  }
324
333
  /** The label an imported Sitefile's messages and file origins use. */
325
- export declare function sitefileLabel(scope: LabelScope): string;
334
+ export declare function sitefileLabel(scope: LabelScope, name?: string): string;
326
335
  /** The ARG values an `IMPORT … AS sitefile` passes, checked against the imported Sitefile's ARGs. */
327
336
  export declare function importedArgs(spec: ImportSpec, program: Program): Record<string, string>;
328
337
  /**
@@ -361,6 +370,8 @@ export interface ImportedSitefile {
361
370
  * a local context, or a directory of a Git tree held in memory.
362
371
  */
363
372
  export type SitefileSource = {
373
+ readonly names: readonly string[];
374
+ } & ({
364
375
  readonly kind: 'local';
365
376
  readonly local: LocalContext;
366
377
  readonly scope: LabelScope;
@@ -379,7 +390,7 @@ export type SitefileSource = {
379
390
  readonly id: string;
380
391
  readonly label: string;
381
392
  }>;
382
- };
393
+ });
383
394
  /** The source of the build's own Sitefile, for {@link readImportedSitefile}. */
384
395
  export declare function rootSitefileSource(options: BuildOptions, label: string, sitefilePath: string): Promise<SitefileSource>;
385
396
  /**