@johnhenry/sitefile 0.0.1 → 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.
Files changed (130) hide show
  1. package/CHANGELOG.md +480 -3
  2. package/README.md +70 -21
  3. package/lib/src/archive-writers.d.ts +12 -2
  4. package/lib/src/archive-writers.js +53 -10
  5. package/lib/src/canonical.d.ts +16 -0
  6. package/lib/src/canonical.js +46 -0
  7. package/lib/src/car.d.ts +34 -0
  8. package/lib/src/car.js +203 -0
  9. package/lib/src/checklinks.js +8 -2
  10. package/lib/src/cli/bake.js +4 -3
  11. package/lib/src/cli/build-image.d.ts +1 -0
  12. package/lib/src/cli/build-image.js +1 -0
  13. package/lib/src/cli/common.js +4 -1
  14. package/lib/src/cli/hosts.d.ts +5 -0
  15. package/lib/src/cli/hosts.js +78 -0
  16. package/lib/src/cli/images.js +23 -5
  17. package/lib/src/cli/import-config.d.ts +2 -0
  18. package/lib/src/cli/import-config.js +56 -0
  19. package/lib/src/cli/index.d.ts +3 -1
  20. package/lib/src/cli/index.js +31 -2
  21. package/lib/src/cli/integrity.d.ts +2 -0
  22. package/lib/src/cli/integrity.js +77 -0
  23. package/lib/src/cli/network.d.ts +7 -0
  24. package/lib/src/cli/network.js +14 -3
  25. package/lib/src/cli/serve-keys.d.ts +39 -0
  26. package/lib/src/cli/serve-keys.js +106 -0
  27. package/lib/src/cli/serve-worker.js +46 -8
  28. package/lib/src/cli/servers.d.ts +124 -1
  29. package/lib/src/cli/servers.js +705 -62
  30. package/lib/src/cli/up.d.ts +2 -0
  31. package/lib/src/cli/up.js +193 -0
  32. package/lib/src/cli/watch.d.ts +14 -1
  33. package/lib/src/cli/watch.js +20 -3
  34. package/lib/src/cli.js +138 -18
  35. package/lib/src/csp.d.ts +17 -0
  36. package/lib/src/csp.js +52 -0
  37. package/lib/src/dictionary.d.ts +16 -0
  38. package/lib/src/dictionary.js +89 -0
  39. package/lib/src/epub.d.ts +5 -0
  40. package/lib/src/epub.js +113 -0
  41. package/lib/src/errors.d.ts +22 -9
  42. package/lib/src/errors.js +20 -1
  43. package/lib/src/executor.d.ts +31 -1
  44. package/lib/src/executor.js +192 -22
  45. package/lib/src/explain.js +33 -3
  46. package/lib/src/export-for.d.ts +42 -0
  47. package/lib/src/export-for.js +466 -0
  48. package/lib/src/export-formats.d.ts +2 -2
  49. package/lib/src/export-formats.js +52 -2
  50. package/lib/src/fingerprint.d.ts +3 -1
  51. package/lib/src/fingerprint.js +32 -5
  52. package/lib/src/host-config.d.ts +34 -0
  53. package/lib/src/host-config.js +645 -0
  54. package/lib/src/hosts.d.ts +47 -0
  55. package/lib/src/hosts.js +106 -0
  56. package/lib/src/index.d.ts +1 -1
  57. package/lib/src/index.js +1 -1
  58. package/lib/src/integrity.d.ts +115 -0
  59. package/lib/src/integrity.js +273 -0
  60. package/lib/src/language/ast.d.ts +116 -3
  61. package/lib/src/language/ast.js +7 -1
  62. package/lib/src/language/parser.js +176 -7
  63. package/lib/src/language/validate.js +21 -0
  64. package/lib/src/links.d.ts +33 -0
  65. package/lib/src/links.js +271 -3
  66. package/lib/src/lint.d.ts +1 -1
  67. package/lib/src/lint.js +26 -1
  68. package/lib/src/mime-data.d.ts +2 -0
  69. package/lib/src/mime-data.js +92 -0
  70. package/lib/src/oci.d.ts +20 -2
  71. package/lib/src/oci.js +70 -28
  72. package/lib/src/outdated.d.ts +3 -0
  73. package/lib/src/outdated.js +4 -4
  74. package/lib/src/planner.d.ts +69 -2
  75. package/lib/src/planner.js +150 -8
  76. package/lib/src/plugins/cache.d.ts +11 -0
  77. package/lib/src/plugins/cache.js +29 -0
  78. package/lib/src/plugins/host.d.ts +51 -2
  79. package/lib/src/plugins/host.js +144 -18
  80. package/lib/src/plugins/wasm.js +1 -3
  81. package/lib/src/portable.d.ts +8 -0
  82. package/lib/src/portable.js +47 -0
  83. package/lib/src/precache.d.ts +33 -0
  84. package/lib/src/precache.js +75 -0
  85. package/lib/src/precompress.d.ts +19 -0
  86. package/lib/src/precompress.js +35 -0
  87. package/lib/src/qr.d.ts +18 -0
  88. package/lib/src/qr.js +372 -0
  89. package/lib/src/registry-ops.js +4 -2
  90. package/lib/src/reload-client.d.ts +2 -0
  91. package/lib/src/reload-client.js +304 -0
  92. package/lib/src/resources/archive.d.ts +36 -0
  93. package/lib/src/resources/archive.js +338 -67
  94. package/lib/src/resources/convert.js +3 -1
  95. package/lib/src/resources/https.d.ts +9 -1
  96. package/lib/src/resources/https.js +36 -0
  97. package/lib/src/resources/network.d.ts +25 -3
  98. package/lib/src/resources/network.js +77 -6
  99. package/lib/src/secrets.d.ts +12 -3
  100. package/lib/src/secrets.js +18 -5
  101. package/lib/src/serve-auth.d.ts +32 -0
  102. package/lib/src/serve-auth.js +112 -0
  103. package/lib/src/serve-rules.d.ts +83 -7
  104. package/lib/src/serve-rules.js +264 -53
  105. package/lib/src/server.d.ts +437 -10
  106. package/lib/src/server.js +1236 -52
  107. package/lib/src/servers-file.d.ts +36 -0
  108. package/lib/src/servers-file.js +101 -0
  109. package/lib/src/servers.d.ts +109 -7
  110. package/lib/src/servers.js +151 -29
  111. package/lib/src/single-file.d.ts +12 -0
  112. package/lib/src/single-file.js +147 -0
  113. package/lib/src/site.d.ts +54 -0
  114. package/lib/src/site.js +204 -6
  115. package/lib/src/store.js +9 -5
  116. package/lib/src/swbn.d.ts +10 -0
  117. package/lib/src/swbn.js +86 -0
  118. package/lib/src/toml.d.ts +17 -0
  119. package/lib/src/toml.js +323 -0
  120. package/lib/src/wacz.d.ts +6 -0
  121. package/lib/src/wacz.js +96 -0
  122. package/lib/src/warc.d.ts +28 -0
  123. package/lib/src/warc.js +252 -0
  124. package/lib/src/watch.d.ts +12 -1
  125. package/lib/src/watch.js +67 -1
  126. package/lib/src/wbn.d.ts +9 -1
  127. package/lib/src/wbn.js +23 -33
  128. package/lib/src/zstd.d.ts +4 -0
  129. package/lib/src/zstd.js +328 -0
  130. package/package.json +1 -1
@@ -3,6 +3,7 @@
3
3
  // same messages.
4
4
  import { isSitefileError, SitefileError } from './errors.js';
5
5
  import { resolveReference, scanFile } from './links.js';
6
+ import { foldCase } from './paths.js';
6
7
  import { fetchRemote } from './resources/https.js';
7
8
  /** The most broken links an error lists (CHECKLINKS --warn prints every one). */
8
9
  export const MAX_LISTED = 20;
@@ -61,6 +62,7 @@ function externalReason(e, url, policy) {
61
62
  export async function brokenLinks(tree, op, policy) {
62
63
  const out = [];
63
64
  const external = new Map();
65
+ let folded;
64
66
  const entries = tree.entries().sort(([a], [b]) => Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8')));
65
67
  for (const [file, node] of entries) {
66
68
  const scan = scanFile(file, node.bytes);
@@ -91,8 +93,12 @@ export async function brokenLinks(tree, op, policy) {
91
93
  else if (!isServed(tree, t.path, t.dir)) {
92
94
  const url = urlPath(op.root, t.path);
93
95
  const display = t.dir && t.path !== '/' ? t.path + '/' : t.path;
94
- if (url === undefined || !redirected(op.redirects, t.dir && url !== '/' ? url + '/' : url))
95
- reason = `not found: ${display}`;
96
+ if (url === undefined || !redirected(op.redirects, t.dir && url !== '/' ? url + '/' : url)) {
97
+ // A case-insensitive file system (macOS, Windows) finds a file whose name differs only in case.
98
+ folded ??= new Map(entries.map(([f]) => [foldCase(f), f]));
99
+ const near = t.dir ? undefined : folded.get(foldCase(t.path));
100
+ reason = near === undefined ? `not found: ${display}` : `not found: ${display}; '${near}' differs only in case, which works on macOS and Windows but not on Linux hosts`;
101
+ }
96
102
  }
97
103
  if (reason !== undefined)
98
104
  out.push({ file, line: r.line, url: r.url, reason });
@@ -10,8 +10,8 @@ import { str, strs, usage } from './common.js';
10
10
  const CLI = fileURLToPath(new URL('../cli.js', import.meta.url));
11
11
  const DEFAULT_JOBS = 4;
12
12
  /** Flags passed unchanged to every target's build. */
13
- const PASS_BOOLEANS = ['allow-plugins', 'no-cache', 'strict-pins', 'frozen-lockfile', 'update-lock', 'no-lockfile', 'allow-http', 'allow-private-network', 'allow-hardlinks', 'force'];
14
- const PASS_STRINGS = ['vendor-dir', 'max-download-bytes', 'timeout', 'plugin-timeout'];
13
+ const PASS_BOOLEANS = ['allow-plugins', 'no-cache', 'strict-pins', 'frozen-lockfile', 'update-lock', 'no-lockfile', 'allow-http', 'allow-private-network', 'allow-hardlinks', 'keep-os-metadata', 'force'];
14
+ const PASS_STRINGS = ['vendor-dir', 'max-download-bytes', 'timeout', 'plugin-timeout', 'plugin-memory', 'node'];
15
15
  const PASS_LISTS = ['allow-exec', 'allow-plugin', 'cache-from', 'insecure-registry', 'build-arg-file', 'build-arg'];
16
16
  function positive(raw, flag) {
17
17
  if (raw === undefined)
@@ -79,7 +79,8 @@ const bakeCommand = {
79
79
  '--build-arg-file <path> read ARGs for every target from a file (after the targets\' own; repeatable)',
80
80
  'Passed to every build: --allow-exec, --allow-plugin, --allow-plugins, --no-cache, --cache-from, --strict-pins,',
81
81
  ' --frozen-lockfile, --update-lock, --no-lockfile, --vendor-dir, --allow-http, --allow-private-network,',
82
- ' --allow-hardlinks, --max-download-bytes, --timeout, --plugin-timeout, --insecure-registry, --force',
82
+ ' --allow-hardlinks, --keep-os-metadata, --max-download-bytes, --timeout, --plugin-timeout, --plugin-memory, --node,',
83
+ ' --insecure-registry, --force',
83
84
  ],
84
85
  options: {
85
86
  file: { type: 'string', short: 'f' },
@@ -11,6 +11,7 @@ export declare function storeBuildAsImage(result: BuildResult, tags: readonly st
11
11
  readonly contextDir: string;
12
12
  readonly ociRoot?: string | undefined;
13
13
  readonly ociCompression?: OciCompression | undefined;
14
+ readonly ociLayers?: number | undefined;
14
15
  readonly platform?: string | undefined;
15
16
  readonly labels?: Readonly<Record<string, string>> | undefined;
16
17
  readonly gitLabels?: boolean | undefined;
@@ -21,6 +21,7 @@ export async function storeBuildAsImage(result, tags, info) {
21
21
  const { id } = await store.addImage(result.output, {
22
22
  root: info.ociRoot ?? result.plan.exportRoot,
23
23
  compression: info.ociCompression ?? sitefileCompression(result.plan, 'oci'),
24
+ ...(info.ociLayers !== undefined ? { layers: info.ociLayers } : {}),
24
25
  platform: info.platform,
25
26
  epoch: sourceDateEpoch(),
26
27
  base: result.base,
@@ -1,5 +1,5 @@
1
1
  import { parseArgs } from 'node:util';
2
- import { SitefileError } from '../errors.js';
2
+ import { errorJson, SitefileError } from '../errors.js';
3
3
  export function commandHelp(c) {
4
4
  return `Usage: sitefile ${c.usage}\n\n${c.description}\n${c.flags.length ? `\nOptions:\n${c.flags.map((f) => ` ${f}`).join('\n')}\n` : ''}`;
5
5
  }
@@ -27,6 +27,9 @@ export async function runCommand(command, args) {
27
27
  if (e instanceof SitefileError) {
28
28
  if (e.code === 'E_USAGE')
29
29
  return usageError(e.detail);
30
+ // With --json, the failure is also machine-readable on stdout (code, span, needs).
31
+ if (parsed.values.json === true)
32
+ process.stdout.write(errorJson(e));
30
33
  process.stderr.write(`error[${e.code}]: ${e.message}\n`);
31
34
  return 1;
32
35
  }
@@ -0,0 +1,5 @@
1
+ import { type HostsReport } from '../hosts.js';
2
+ import { type Command } from './common.js';
3
+ /** The text report: one row per use, then what each refused host or secret needs, and a summary line. */
4
+ export declare function formatHosts(r: HostsReport): string;
5
+ export declare const hostsCommands: ReadonlyMap<string, Command>;
@@ -0,0 +1,78 @@
1
+ import { NETWORK_OPTIONS, networkHelp, networkOption } from './network.js';
2
+ import { collectBuildArgs } from '../build-args.js';
3
+ import { hosts, hostsJson } from '../hosts.js';
4
+ import { requireArgs, str, strs, table } from './common.js';
5
+ function usedBy(u) {
6
+ const what = u.kind === 'import' ? `IMPORT ${u.name}` : u.kind === 'image' ? `FROM image ${u.name}` : 'BASE';
7
+ return u.span ? `${what} (${u.span.file}:${u.span.line})` : what;
8
+ }
9
+ /** The text report: one row per use, then what each refused host or secret needs, and a summary line. */
10
+ export function formatHosts(r) {
11
+ let out = '';
12
+ if (r.hosts.length === 0)
13
+ out = 'No remote inputs: the Sitefile names no host to contact\n';
14
+ else {
15
+ const rows = [['HOST', 'PORT', 'STATUS', 'USED BY']];
16
+ for (const h of r.hosts)
17
+ for (const u of h.uses)
18
+ rows.push([h.host, String(h.port), h.status, usedBy(u)]);
19
+ out = table(rows);
20
+ for (const h of r.hosts)
21
+ if (h.needs)
22
+ out += `${h.host}: needs ${h.needs.flag} ${h.needs.name}\n`;
23
+ for (const h of r.hosts)
24
+ for (const u of h.uses)
25
+ if (u.needs)
26
+ out += `${usedBy(u)}: secret needs ${u.needs.flag} ${u.needs.name}\n`;
27
+ for (const h of r.hosts)
28
+ for (const u of h.uses)
29
+ if (u.nested)
30
+ out += `${usedBy(u)}: an imported Sitefile; the hosts it needs are known once it is fetched\n`;
31
+ const n = r.hosts.length;
32
+ const counts = ['allowed', 'blocked', 'denied'].map((s) => [s, r.hosts.filter((h) => h.status === s).length]).filter(([, k]) => k > 0);
33
+ out += `${n} host${n === 1 ? '' : 's'}${r.strict ? ' (strict network mode)' : ''}: ${counts.map(([s, k]) => `${k} ${s}`).join(', ')}\n`;
34
+ }
35
+ for (const line of r.checklinksExternal)
36
+ out += `CHECKLINKS --external (line ${line}) also contacts the hosts of external links\n`;
37
+ return out;
38
+ }
39
+ const hostsCommand = {
40
+ name: 'hosts',
41
+ summary: 'list the hosts a build would contact, before contacting any',
42
+ usage: 'hosts [context] [options]',
43
+ description: "List the hosts a build of the Sitefile would contact (remote IMPORTs, FROM image registries, the BASE\nimage's registry), what needs each, and whether the network rules (--allow-hosts, --deny-hosts,\n--network strict, --allow-secret-host) allow it. Nothing is fetched. Redirects, registry token and blob\nhosts and the inputs of an imported Sitefile are only known while building.",
44
+ flags: [
45
+ '-f, --file <path> Sitefile path (default: <context>/Sitefile)',
46
+ '--json machine-readable output',
47
+ '--build-arg <NAME=value> set an ARG (repeatable); --build-arg NAME reads $NAME',
48
+ '--build-arg-file <path> read ARGs from a .json, .yaml/.yml or .env file (repeatable)',
49
+ '--base <image> include this BASE image (overrides EXPORT ... AS oci BASE)',
50
+ ...networkHelp(30),
51
+ ],
52
+ options: {
53
+ ...NETWORK_OPTIONS,
54
+ file: { type: 'string', short: 'f' },
55
+ json: { type: 'boolean' },
56
+ 'build-arg': { type: 'string', multiple: true },
57
+ 'build-arg-file': { type: 'string', multiple: true },
58
+ base: { type: 'string' },
59
+ },
60
+ async run(v, pos) {
61
+ requireArgs(pos, 0, 1, 'a context directory');
62
+ const network = networkOption(v);
63
+ const file = str(v.file);
64
+ const base = str(v.base);
65
+ const r = await hosts({
66
+ contextDir: pos[0] ?? '.',
67
+ ...(file ? { sitefile: file } : {}),
68
+ buildArgs: await collectBuildArgs(strs(v['build-arg-file']), strs(v['build-arg'])),
69
+ fetchPolicy: network ? { network } : {},
70
+ ...(base !== undefined ? { baseImage: base } : {}),
71
+ onWarning: (m) => process.stderr.write(`warning: ${m}\n`),
72
+ });
73
+ process.stdout.write(v.json ? hostsJson(r) : formatHosts(r));
74
+ return 0;
75
+ },
76
+ };
77
+ export const hostsCommands = new Map([['hosts', hostsCommand]]);
78
+ //# sourceMappingURL=hosts.js.map
@@ -9,6 +9,8 @@ import { EXPORT_FORMATS, parseExportFormat } from '../language/ast.js';
9
9
  import { MEDIA, siteLayerIndex } from '../oci.js';
10
10
  import { looksLikeImageId, parseLocalRef, refKey } from '../ref.js';
11
11
  import { shortId, Store } from '../store.js';
12
+ import { encodeCar } from '../car.js';
13
+ import { encodeManifest, manifestOf } from '../integrity.js';
12
14
  import { humanSize, relativeTime, requireArgs, str, table, usage } from './common.js';
13
15
  function split(key) {
14
16
  const i = key.lastIndexOf(':');
@@ -174,15 +176,16 @@ const prune = {
174
176
  const save = {
175
177
  name: 'save',
176
178
  summary: 'export an image to a directory or archive',
177
- usage: 'save <ref|id> -o <out> [--format fmt] [--base-url url] [--force]',
178
- description: 'Write an image\'s files to a directory, or to a zip, tar, tar.gz (tgz) or wbn archive, or the image itself as\nan OCI archive (-o x.oci.tar) or OCI layout directory (--format oci). The format is chosen like "build -o":\nfrom --format, else the extension (.zip .tar .tar.gz .tgz .wbn .wbn.gz .oci.tar), else a directory; a wbn\nwritten to *.wbn.gz is gzipped.\nArchives are deterministic (set SOURCE_DATE_EPOCH to stamp them). A non-empty destination needs --force.',
179
+ usage: 'save <ref|id> -o <out> [--format fmt] [--base-url url] [--manifest file] [--force]',
180
+ description: 'Write an image\'s files to a directory, or to a zip, tar, tar.gz (tgz) or wbn archive, an IPFS CAR, a single-file\npage (html, mhtml), a WARC or WACZ, an EPUB, or the image itself as\nan OCI archive (-o x.oci.tar) or OCI layout directory (--format oci). The format is chosen like "build -o":\nfrom --format, else the extension (.zip .tar .tar.gz .tgz .wbn .wbn.gz .oci.tar .car .mhtml .warc .warc.gz .swbn .wacz .epub), else a directory; a wbn\nwritten to *.wbn.gz is gzipped.\nArchives are deterministic (set SOURCE_DATE_EPOCH to stamp them). A non-empty destination needs --force.',
179
181
  flags: [
180
182
  '-o, --out <path> destination (required)',
181
183
  ` --format <fmt> ${EXPORT_FORMATS.join(' | ')} (alias tar.gz)`,
182
184
  ' --base-url <url> https URL ending in "/" (wbn only; required for wbn)',
185
+ ' --manifest <file> also write a manifest of the files (see sitefile verify)',
183
186
  ' --force replace a non-empty destination or an existing file',
184
187
  ],
185
- options: { out: { type: 'string', short: 'o' }, format: { type: 'string' }, 'base-url': { type: 'string' }, force: { type: 'boolean' } },
188
+ options: { out: { type: 'string', short: 'o' }, format: { type: 'string' }, 'base-url': { type: 'string' }, manifest: { type: 'string' }, force: { type: 'boolean' } },
186
189
  async run(v, pos) {
187
190
  requireArgs(pos, 1, 1, 'an image reference');
188
191
  const out = str(v.out);
@@ -195,6 +198,14 @@ const save = {
195
198
  usage(`--format expects one of ${EXPORT_FORMATS.join(', ')} (or tar.gz)`);
196
199
  }
197
200
  format ??= formatFromExtension(out) ?? 'directory';
201
+ const manifest = str(v.manifest);
202
+ if (manifest === '')
203
+ usage('--manifest expects a file path');
204
+ if (manifest !== undefined && format === 'directory') {
205
+ const rel = path.relative(path.resolve(out), path.resolve(manifest));
206
+ if (rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel))
207
+ usage(`--manifest '${manifest}' is inside the exported directory '${out}': write it elsewhere`);
208
+ }
198
209
  const store = await Store.open();
199
210
  const id = await store.resolve(pos[0]);
200
211
  // An empty scratch directory as the "context": the destination is then always
@@ -202,6 +213,10 @@ const save = {
202
213
  const scratch = await fs.mkdtemp(path.join(os.tmpdir(), 'sitefile-save-'));
203
214
  try {
204
215
  const opts = { contextDir: scratch, ...(v.force ? { force: true } : {}) };
216
+ const writeManifest = async () => {
217
+ if (manifest !== undefined)
218
+ await exportFile(encodeManifest(manifestOf(await store.loadTree(id))), manifest, opts);
219
+ };
205
220
  if (format === 'oci') {
206
221
  // The stored image as-is (same digests): an OCI archive for *.tar, else a layout directory.
207
222
  const input = pos[0];
@@ -215,6 +230,7 @@ const save = {
215
230
  const w = await exportDirectory(layout, out, opts);
216
231
  process.stdout.write(`Saved ${shortId(id)} to ${shown(w.outDir)} (oci layout)\n`);
217
232
  }
233
+ await writeManifest();
218
234
  return 0;
219
235
  }
220
236
  const tree = await store.loadTree(id);
@@ -223,10 +239,12 @@ const save = {
223
239
  process.stdout.write(`Saved ${shortId(id)} (${tree.size} files) to ${shown(w.outDir)}\n`);
224
240
  }
225
241
  else {
226
- const data = encodeTree(tree, format, { epoch: sourceDateEpoch(), baseUrl: str(v['base-url']), compression: compressionFromExtension(out, format) });
242
+ const car = format === 'car' ? encodeCar(tree) : undefined;
243
+ const data = car?.bytes ?? encodeTree(tree, format, { epoch: sourceDateEpoch(), baseUrl: str(v['base-url']), compression: compressionFromExtension(out, format) });
227
244
  const w = await exportFile(data, out, opts);
228
- process.stdout.write(`Saved ${shortId(id)} (${tree.size} files) to ${shown(w.outFile)} (${format === 'tgz' ? 'tar.gz' : format}, ${w.bytes} bytes)\n`);
245
+ process.stdout.write(`Saved ${shortId(id)} (${tree.size} files) to ${shown(w.outFile)} (${format === 'tgz' ? 'tar.gz' : format}, ${w.bytes} bytes${car ? `, root ${car.root}` : ''})\n`);
229
246
  }
247
+ await writeManifest();
230
248
  }
231
249
  finally {
232
250
  await fs.rm(scratch, { recursive: true, force: true });
@@ -0,0 +1,2 @@
1
+ import { type Command } from './common.js';
2
+ export declare const importConfigCommands: ReadonlyMap<string, Command>;
@@ -0,0 +1,56 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { SitefileError } from '../errors.js';
3
+ import { formatOf, headersText, HOST_FORMATS, importHostConfig, redirectsText } from '../host-config.js';
4
+ import { requireArgs, str, usage } from './common.js';
5
+ const importConfig = {
6
+ name: 'import-config',
7
+ summary: "translate a host's config file into _redirects and _headers",
8
+ usage: 'import-config <file> [--format f] [--redirects | --headers] [--json]',
9
+ description: "Read netlify.toml, vercel.json, firebase.json, staticwebapp.config.json, wrangler.toml / wrangler.json\n([assets]) or .htaccess, and print the _redirects and _headers that sitefile serve understands today.\nEvery rule printed is one serve applies as written; anything else (placeholders, conditions, proxying,\nregular expressions, settings with no _redirects form) is listed on stderr as a warning, never half\ntranslated. The format comes from the file name unless --format is given.",
10
+ flags: [
11
+ `--format <f> ${HOST_FORMATS.join(', ')}`,
12
+ '--redirects print only the _redirects text',
13
+ '--headers print only the _headers text',
14
+ '--json machine-readable output (rules and unsupported entries)',
15
+ ],
16
+ options: { format: { type: 'string' }, redirects: { type: 'boolean' }, headers: { type: 'boolean' }, json: { type: 'boolean' } },
17
+ async run(v, pos) {
18
+ requireArgs(pos, 1, 1, 'a host config file');
19
+ const file = pos[0];
20
+ const given = str(v.format);
21
+ if (given !== undefined && !HOST_FORMATS.includes(given))
22
+ usage(`--format expects one of ${HOST_FORMATS.join(', ')}, got '${given}'`);
23
+ const format = given ?? formatOf(file);
24
+ if (format === undefined)
25
+ usage(`cannot tell the format of '${file}' from its name; pass --format (${HOST_FORMATS.join(', ')})`);
26
+ if (v.redirects && v.headers)
27
+ usage('--redirects and --headers conflict');
28
+ if (v.json && (v.redirects || v.headers))
29
+ usage('--json prints both; drop --redirects/--headers');
30
+ let text;
31
+ try {
32
+ text = await readFile(file, 'utf8');
33
+ }
34
+ catch (e) {
35
+ throw new SitefileError('E_NOT_FOUND', `cannot read '${file}'`, undefined, { cause: e });
36
+ }
37
+ const c = importHostConfig(text, file, format);
38
+ if (v.json) {
39
+ process.stdout.write(JSON.stringify({ format: c.format, redirects: c.redirects, headers: c.headers.map((b) => ({ pattern: b.pattern, headers: b.headers })), unsupported: c.unsupported }, null, 2) + '\n');
40
+ return 0;
41
+ }
42
+ for (const u of c.unsupported)
43
+ process.stderr.write(`warning: ${file}: ${u.entry}: ${u.reason}\n`);
44
+ const r = redirectsText(c);
45
+ const h = headersText(c);
46
+ if (v.redirects)
47
+ process.stdout.write(r);
48
+ else if (v.headers)
49
+ process.stdout.write(h);
50
+ else
51
+ process.stdout.write(`${r ? `# _redirects\n${r}` : ''}${r && h ? '\n' : ''}${h ? `# _headers\n${h}` : ''}`);
52
+ return 0;
53
+ },
54
+ };
55
+ export const importConfigCommands = new Map([['import-config', importConfig]]);
56
+ //# sourceMappingURL=import-config.js.map
@@ -5,6 +5,8 @@ export declare const EXTRA_COMMANDS: readonly string[];
5
5
  * an editor tool. Here `sitefile lsp` is a usage error that points there.
6
6
  */
7
7
  export declare const LSP_UNAVAILABLE = "'sitefile lsp' (the language server) is provided by the Rust implementation: build it with 'cd rust && cargo build --release' and run 'rust/target/release/sitefile lsp' (see docs/LSP.md)";
8
- export declare const EXTRA_HELP = "\nImages (local store: $SITEFILE_HOME or ~/.sitefile):\n sitefile build [context] -t name[:tag] also store the result as an image (repeatable -t)\n sitefile images [--json] [--digests] [-q] list images (alias: image ls)\n sitefile image inspect <ref> [--json] show an image manifest\n sitefile image prune delete unreferenced manifests and blobs\n sitefile image diff <a> <b> added/removed/changed paths\n sitefile tag <src> <dst> add a name:tag\n sitefile rmi [-f] <ref|id>... remove tags / images\n sitefile save <ref> -o out[.zip|.tar|.tar.gz|.wbn] export an image\n sitefile push <registry/name[:tag]> push a (tagged) image to an OCI registry\n sitefile pull <[registry/]name[:tag][@digest]> pull an image (a bare name means Docker Hub)\n\nVariants:\n sitefile bake [targets...] [-f file] [--print] build several targets (matrix, groups) from\n sitefile.bake.yaml; --print shows the plan\n\nOffline builds:\n sitefile vendor [context] [--vendor-dir dir] download remote imports and the BASE image into\n vendor/sitefile; builds then read them from there\n\nPins:\n sitefile outdated [context] [--json] compare remote imports and the BASE image with\n their pins (never changes anything)\n\nBuild cache (TRANSFORM results: $SITEFILE_HOME/cache/transform):\n sitefile cache info [--json] location, entries, size\n sitefile cache prune [--older-than <days>] delete cached results\n sitefile cache prune --max-size <size> shrink evictable data (LRU) to <size>\n sitefile cache du [--json] size of every cache and the store (alias: cache ls)\n Evictable data over $SITEFILE_CACHE_MAX (default 1GiB, 0 = no limit) is deleted after each build.\n\nServing sites (detached servers are tracked by name):\n sitefile serve [--name n] [-p [host:]port] [-d] [--spa] <ref|./dir|file>\n sitefile serve --watch [-p [host:]port] [ctx] build in memory, serve, rebuild + live reload\n sitefile servers [-a] [--json] list servers (alias: server ls)\n sitefile server stop|rm [-f]|restart|logs [-f] <name|id>\n\nEditor support:\n sitefile lsp [--stdio] language server over stdio (Rust build only; docs/LSP.md)\n\nRun 'sitefile <command> --help' for the options of a command.\n";
8
+ export declare const EXTRA_HELP = "\nImages (local store: $SITEFILE_HOME or ~/.sitefile):\n sitefile build [context] -t name[:tag] also store the result as an image (repeatable -t)\n sitefile images [--json] [--digests] [-q] list images (alias: image ls)\n sitefile image inspect <ref> [--json] show an image manifest\n sitefile image prune delete unreferenced manifests and blobs\n sitefile image diff <a> <b> added/removed/changed paths\n sitefile tag <src> <dst> add a name:tag\n sitefile rmi [-f] <ref|id>... remove tags / images\n sitefile save <ref> -o out[.zip|.tar|.tar.gz|.wbn] export an image\n sitefile push <registry/name[:tag]> push a (tagged) image to an OCI registry\n sitefile pull <[registry/]name[:tag][@digest]> pull an image (a bare name means Docker Hub)\n\nIntegrity:\n sitefile build [context] --manifest m.json also write a manifest: every file's size and SHA-256,\n and their Merkle root (save --manifest too)\n sitefile verify <dir|archive|ref> --manifest m.json check a deployed or extracted copy: missing,\n changed and extra files (exit 1 on any)\n sitefile diff <a> <b> [--json] files added, removed and changed between two images,\n directories or archives, and _redirects/_headers rules\n\nVariants:\n sitefile bake [targets...] [-f file] [--print] build several targets (matrix, groups) from\n sitefile.bake.yaml; --print shows the plan\n\nHost config files:\n sitefile import-config <file> [--json] translate netlify.toml, vercel.json, firebase.json,\n staticwebapp.config.json, wrangler.toml or .htaccess\n into _redirects and _headers\n\nOffline builds:\n sitefile vendor [context] [--vendor-dir dir] download remote imports and the BASE image into\n vendor/sitefile; builds then read them from there\n\nPins:\n sitefile outdated [context] [--json] compare remote imports and the BASE image with\n their pins (never changes anything)\n\nNetwork:\n sitefile hosts [context] [--json] list the hosts a build would contact and whether\n --allow-hosts/--network strict allow them (no fetch)\n\nBuild cache (TRANSFORM results: $SITEFILE_HOME/cache/transform):\n sitefile cache info [--json] location, entries, size\n sitefile cache prune [--older-than <days>] delete cached results\n sitefile cache prune --max-size <size> shrink evictable data (LRU) to <size>\n sitefile cache du [--json] size of every cache and the store (alias: cache ls)\n Evictable data over $SITEFILE_CACHE_MAX (default 1GiB, 0 = no limit) is deleted after each build.\n\nServing sites (detached servers are tracked by name):\n sitefile serve [--name n] [-p [host:]port] [-d] [--spa] <ref|./dir|file>\n sitefile serve --watch [-p [host:]port] [ctx] build in memory, serve, rebuild + live reload\n sitefile servers [-a] [--json] list servers (alias: server ls)\n sitefile server stop|rm [-f]|restart|logs [-f] <name|id>\n sitefile up [-f sitefile.servers.yaml] start every server of a servers file (detached, idempotent)\n sitefile down [-f file] stop and remove the servers it started\n sitefile ps [-f file] [--json] list them: running, exited or not created\n\nEditor support:\n sitefile lsp [--stdio] language server over stdio (Rust build only; docs/LSP.md)\n\nRun 'sitefile <command> --help' for the options of a command.\n";
9
9
  export declare function isExtraCommand(name: string | undefined): boolean;
10
10
  export declare function runExtraCommand(argv: readonly string[]): Promise<number>;
11
+ /** `serve --open` takes its path only as `--open=<path>`: a bare `--open` (before `--`) is `--open=`. */
12
+ export declare function optionalOpen(args: readonly string[]): string[];
@@ -5,12 +5,16 @@ import { serverCommands, serverSubcommands } from './servers.js';
5
5
  import { cacheSubcommands } from './cache.js';
6
6
  import { vendorCommands } from './vendor.js';
7
7
  import { outdatedCommands } from './outdated.js';
8
+ import { hostsCommands } from './hosts.js';
8
9
  import { bakeCommands } from './bake.js';
10
+ import { upCommands } from './up.js';
11
+ import { importConfigCommands } from './import-config.js';
12
+ import { integrityCommands } from './integrity.js';
9
13
  /**
10
14
  * Image-store and site-server commands. They live outside cli.ts' build/validate/inspect
11
15
  * parser: each has its own options and `--help`.
12
16
  */
13
- const TOP = new Map([...imageCommands, ...serverCommands, ...registryCommands, ...vendorCommands, ...outdatedCommands, ...bakeCommands].filter(([k]) => !k.includes(' ')));
17
+ const TOP = new Map([...imageCommands, ...serverCommands, ...registryCommands, ...vendorCommands, ...outdatedCommands, ...hostsCommands, ...bakeCommands, ...integrityCommands, ...upCommands, ...importConfigCommands].filter(([k]) => !k.includes(' ')));
14
18
  export const EXTRA_COMMANDS = [...TOP.keys(), 'image', 'server', 'cache', 'lsp'];
15
19
  /**
16
20
  * The language server exists only in the Rust implementation (a tooling
@@ -31,10 +35,23 @@ Images (local store: $SITEFILE_HOME or ~/.sitefile):
31
35
  sitefile push <registry/name[:tag]> push a (tagged) image to an OCI registry
32
36
  sitefile pull <[registry/]name[:tag][@digest]> pull an image (a bare name means Docker Hub)
33
37
 
38
+ Integrity:
39
+ sitefile build [context] --manifest m.json also write a manifest: every file's size and SHA-256,
40
+ and their Merkle root (save --manifest too)
41
+ sitefile verify <dir|archive|ref> --manifest m.json check a deployed or extracted copy: missing,
42
+ changed and extra files (exit 1 on any)
43
+ sitefile diff <a> <b> [--json] files added, removed and changed between two images,
44
+ directories or archives, and _redirects/_headers rules
45
+
34
46
  Variants:
35
47
  sitefile bake [targets...] [-f file] [--print] build several targets (matrix, groups) from
36
48
  sitefile.bake.yaml; --print shows the plan
37
49
 
50
+ Host config files:
51
+ sitefile import-config <file> [--json] translate netlify.toml, vercel.json, firebase.json,
52
+ staticwebapp.config.json, wrangler.toml or .htaccess
53
+ into _redirects and _headers
54
+
38
55
  Offline builds:
39
56
  sitefile vendor [context] [--vendor-dir dir] download remote imports and the BASE image into
40
57
  vendor/sitefile; builds then read them from there
@@ -43,6 +60,10 @@ Pins:
43
60
  sitefile outdated [context] [--json] compare remote imports and the BASE image with
44
61
  their pins (never changes anything)
45
62
 
63
+ Network:
64
+ sitefile hosts [context] [--json] list the hosts a build would contact and whether
65
+ --allow-hosts/--network strict allow them (no fetch)
66
+
46
67
  Build cache (TRANSFORM results: $SITEFILE_HOME/cache/transform):
47
68
  sitefile cache info [--json] location, entries, size
48
69
  sitefile cache prune [--older-than <days>] delete cached results
@@ -55,6 +76,9 @@ Serving sites (detached servers are tracked by name):
55
76
  sitefile serve --watch [-p [host:]port] [ctx] build in memory, serve, rebuild + live reload
56
77
  sitefile servers [-a] [--json] list servers (alias: server ls)
57
78
  sitefile server stop|rm [-f]|restart|logs [-f] <name|id>
79
+ sitefile up [-f sitefile.servers.yaml] start every server of a servers file (detached, idempotent)
80
+ sitefile down [-f file] stop and remove the servers it started
81
+ sitefile ps [-f file] [--json] list them: running, exited or not created
58
82
 
59
83
  Editor support:
60
84
  sitefile lsp [--stdio] language server over stdio (Rust build only; docs/LSP.md)
@@ -90,6 +114,11 @@ export async function runExtraCommand(argv) {
90
114
  const cmd = name === undefined ? undefined : TOP.get(name);
91
115
  if (!cmd)
92
116
  return usageError(`unknown command '${name ?? ''}'`);
93
- return runCommand(cmd, rest);
117
+ return runCommand(cmd, name === 'serve' ? optionalOpen(rest) : rest);
118
+ }
119
+ /** `serve --open` takes its path only as `--open=<path>`: a bare `--open` (before `--`) is `--open=`. */
120
+ export function optionalOpen(args) {
121
+ const end = args.indexOf('--');
122
+ return args.map((a, i) => (a === '--open' && (end === -1 || i < end) ? '--open=' : a));
94
123
  }
95
124
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ import { type Command } from './common.js';
2
+ export declare const integrityCommands: ReadonlyMap<string, Command>;
@@ -0,0 +1,77 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { SitefileError } from '../errors.js';
3
+ import { diffText, diffTrees, loadTarget, manifestOf, parseManifest, pathInside, resolveTarget, verifyText, verifyTree } from '../integrity.js';
4
+ import { Store } from '../store.js';
5
+ import { requireArgs, str, usage } from './common.js';
6
+ const openStore = () => {
7
+ let s;
8
+ return () => (s ??= Store.open());
9
+ };
10
+ const verify = {
11
+ name: 'verify',
12
+ summary: 'check a directory, archive or image against a file manifest',
13
+ usage: 'verify <dir|archive|ref|id> [--manifest <file>] [--json]',
14
+ description: 'Compare a deployed or extracted copy with the manifest written by "build --manifest" or "save --manifest":\nevery file the manifest lists must be there with the same size and SHA-256, and no other file may be.\nPrints one line per difference (missing, changed, extra) and fails with E_INTEGRITY when there is any.\nA directory is read like a build context (hidden files count; .git is skipped); an archive is read from\nits bytes (zip, tar, tar.gz, wbn, OCI archive). A manifest file inside the verified directory is not\ncounted as extra. Without --manifest the target must be an image: its stored blobs are checked.',
15
+ flags: ['--manifest <file> the manifest to check against (JSON, see docs/CLI.md)', '--json machine-readable report'],
16
+ options: { manifest: { type: 'string' }, json: { type: 'boolean' } },
17
+ async run(v, pos) {
18
+ requireArgs(pos, 1, 1, 'a directory, archive file or image reference');
19
+ const arg = pos[0];
20
+ const store = openStore();
21
+ const target = await resolveTarget(arg, store);
22
+ const manifestFile = str(v.manifest);
23
+ if (manifestFile === '')
24
+ usage('--manifest expects a file path');
25
+ if (manifestFile === undefined && target.kind !== 'image')
26
+ usage('verify needs --manifest <file> for a directory or an archive');
27
+ const tree = await loadTarget(target, store);
28
+ let manifest;
29
+ let ignore;
30
+ if (manifestFile !== undefined) {
31
+ const bytes = await fs.readFile(manifestFile).catch((e) => {
32
+ throw new SitefileError(e.code === 'ENOENT' ? 'E_NOT_FOUND' : 'E_INTEGRITY', `cannot read the manifest '${manifestFile}'`);
33
+ });
34
+ manifest = parseManifest(new Uint8Array(bytes), manifestFile);
35
+ if (target.kind === 'dir')
36
+ ignore = await pathInside(target.path, manifestFile);
37
+ }
38
+ else {
39
+ manifest = manifestOf(tree); // loadTree checked every blob against its digest
40
+ }
41
+ const r = verifyTree(tree, manifest, ignore);
42
+ process.stdout.write(v.json ? JSON.stringify(r, null, 2) + '\n' : r.ok ? `OK: ${r.files} file${r.files === 1 ? '' : 's'} match ${r.root}\n` : verifyText(r));
43
+ if (!r.ok) {
44
+ const message = `'${arg}' does not match the manifest: ${r.missing.length} missing, ${r.changed.length} changed, ${r.extra.length} extra`;
45
+ // With --json the report above is the one document on stdout (it already says ok: false),
46
+ // so the error goes to stderr only instead of through the generic --json error output.
47
+ if (v.json) {
48
+ process.stderr.write(`error[E_INTEGRITY]: ${message}\n`);
49
+ return 1;
50
+ }
51
+ throw new SitefileError('E_INTEGRITY', message);
52
+ }
53
+ return 0;
54
+ },
55
+ };
56
+ const diff = {
57
+ name: 'diff',
58
+ summary: 'files changed between two images, directories or archives',
59
+ usage: 'diff <a> <b> [--json] [--exit-code]',
60
+ description: 'List the files added (A), removed (D) and changed (C: content or mode) going from <a> to <b>, with their\nsizes, then the rules added (+) and removed (-) in _redirects and _headers. Each side is a directory, an\narchive file (zip, tar, tar.gz, wbn, OCI archive) or an image reference or ID, read as "sitefile verify"\nreads it (hidden files count). Digests, not timestamps, decide what changed.',
61
+ flags: ['--json machine-readable report (sizes in bytes, digests, modes)', '--exit-code exit 1 when the two differ (default 0 either way)'],
62
+ options: { json: { type: 'boolean' }, 'exit-code': { type: 'boolean' } },
63
+ async run(v, pos) {
64
+ requireArgs(pos, 2, 2, 'two images, directories or archive files');
65
+ const store = openStore();
66
+ const [a, b] = [await resolveTarget(pos[0], store), await resolveTarget(pos[1], store)];
67
+ const r = diffTrees(await loadTarget(a, store), await loadTarget(b, store));
68
+ process.stdout.write(v.json ? JSON.stringify(r, null, 2) + '\n' : diffText(r));
69
+ const same = !r.added.length && !r.removed.length && !r.changed.length && !Object.keys(r.rules).length;
70
+ return v['exit-code'] && !same ? 1 : 0;
71
+ },
72
+ };
73
+ export const integrityCommands = new Map([
74
+ ['verify', verify],
75
+ ['diff', diff],
76
+ ]);
77
+ //# sourceMappingURL=integrity.js.map
@@ -16,6 +16,13 @@ export declare const NETWORK_OPTIONS: {
16
16
  readonly type: 'string';
17
17
  readonly multiple: true;
18
18
  };
19
+ readonly network: {
20
+ readonly type: 'string';
21
+ };
22
+ readonly 'allow-secret-host': {
23
+ readonly type: 'string';
24
+ readonly multiple: true;
25
+ };
19
26
  readonly 'connect-timeout': {
20
27
  readonly type: 'string';
21
28
  };
@@ -1,11 +1,13 @@
1
1
  import { SitefileError } from '../errors.js';
2
- import { mergeNetwork, networkFromEnv, networkProblem, splitList } from '../resources/network.js';
2
+ import { mergeNetwork, networkFromEnv, networkProblem, parseNetworkMode, splitList } from '../resources/network.js';
3
3
  /** parseArgs options for the network flags (build, validate, inspect, graph, why, pull, push, vendor, outdated). */
4
4
  export const NETWORK_OPTIONS = {
5
5
  proxy: { type: 'string' },
6
6
  'no-proxy': { type: 'string', multiple: true },
7
7
  'allow-hosts': { type: 'string', multiple: true },
8
8
  'deny-hosts': { type: 'string', multiple: true },
9
+ network: { type: 'string' },
10
+ 'allow-secret-host': { type: 'string', multiple: true },
9
11
  'connect-timeout': { type: 'string' },
10
12
  'read-timeout': { type: 'string' },
11
13
  };
@@ -16,12 +18,17 @@ export function networkHelp(width) {
16
18
  ['--no-proxy <hosts>', ['hosts reached directly, not through the proxy (NO_PROXY syntax; repeatable,', 'comma-separated; also $SITEFILE_NO_PROXY)']],
17
19
  ['--allow-hosts <hosts>', ['contact only hosts matching these patterns (repeatable, comma-separated;', 'also $SITEFILE_ALLOW_HOSTS)']],
18
20
  ['--deny-hosts <hosts>', ['never contact hosts matching these patterns; beats --allow-hosts', '(repeatable, comma-separated; also $SITEFILE_DENY_HOSTS)']],
21
+ ['--network <mode>', ['open (default) or strict: every host must match --allow-hosts, even with none', 'given (also $SITEFILE_NETWORK)']],
22
+ ['--allow-secret-host <id=host>', ['in strict mode, let IMPORT ... SECRET <id> send its secret to this host', '(a host pattern; repeatable)']],
19
23
  ['--connect-timeout <ms>', ['time limit for opening each connection (also $SITEFILE_FETCH_TIMEOUT)']],
20
24
  ['--read-timeout <ms>', ['longest wait for data on a connection (also $SITEFILE_FETCH_TIMEOUT)']],
21
25
  ];
22
26
  const out = [];
23
27
  for (const [flag, lines] of rows) {
24
- lines.forEach((l, i) => out.push(`${(i === 0 ? flag : '').padEnd(width)}${l}`));
28
+ // A flag wider than the column gets a line of its own.
29
+ if (flag.length >= width)
30
+ out.push(flag);
31
+ lines.forEach((l, i) => out.push(`${(i === 0 && flag.length < width ? flag : '').padEnd(width)}${l}`));
25
32
  }
26
33
  return out;
27
34
  }
@@ -44,10 +51,14 @@ export function networkOption(v, env = process.env) {
44
51
  noProxy: strings(v['no-proxy']).flatMap(splitList),
45
52
  allowHosts: strings(v['allow-hosts']).flatMap(splitList),
46
53
  denyHosts: strings(v['deny-hosts']).flatMap(splitList),
54
+ secretHosts: strings(v['allow-secret-host']).flatMap(splitList),
47
55
  connectTimeoutMs: ms(typeof v['connect-timeout'] === 'string' ? v['connect-timeout'] : undefined, '--connect-timeout'),
48
56
  readTimeoutMs: ms(typeof v['read-timeout'] === 'string' ? v['read-timeout'] : undefined, '--read-timeout'),
49
57
  };
50
- const merged = mergeNetwork(networkFromEnv(env), flags);
58
+ const fromEnv = networkFromEnv(env);
59
+ // --network replaces SITEFILE_NETWORK (--network open turns an inherited strict mode off).
60
+ const mode = typeof v.network === 'string' ? (parseNetworkMode(v.network === '' ? '?' : v.network, '--network') ?? false) : undefined;
61
+ const merged = mergeNetwork(mode === undefined ? fromEnv : { ...fromEnv, strict: undefined }, mode ? { ...flags, strict: true } : flags);
51
62
  const problem = networkProblem(merged);
52
63
  if (problem)
53
64
  throw new SitefileError('E_USAGE', problem);
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `serve` in a terminal (issue #224): single keys while serving in the foreground, `--open[=path]` and
3
+ * `--qr`. Ported as rust/src/cli/serve_keys.rs (the same keys, messages and QR codes).
4
+ */
5
+ export type KeyAction = 'open' | 'urls' | 'restart' | 'clear' | 'quit' | 'help';
6
+ /** What a key does (letters in either case; Ctrl-C and Ctrl-D quit), or undefined. */
7
+ export declare function keyAction(byte: number): KeyAction | undefined;
8
+ export declare const KEYS_HINT = "Press h for keys\n";
9
+ export declare const KEYS_HELP = "Keys: o open in the browser, u show the URLs, r rebuild (--watch) or re-read the directory, c clear the screen, q quit, h this help\n";
10
+ export declare const CLEAR = "\u001B[2J\u001B[3J\u001B[H";
11
+ /**
12
+ * The URLs to show (below `serve --base`, `https://` for a TLS server): the local one, and when bound to every
13
+ * interface the same network URLs as the start line (one per interface address, IPv4 first).
14
+ */
15
+ export declare function serveUrls(host: string, port: number, base?: string, scheme?: 'http' | 'https'): {
16
+ local: string;
17
+ network: string[];
18
+ };
19
+ /** `u`: the URLs, and a QR code of the first network URL when there is one. */
20
+ export declare function urlsText(urls: {
21
+ local: string;
22
+ network: readonly string[];
23
+ }): string;
24
+ /** `--qr`: the URL and its QR code. */
25
+ export declare function qrText(url: string): string;
26
+ /** `--open=<path>` (or `--open`, `/`) joined to the server's URL. */
27
+ export declare function openUrl(base: string, path: string): string;
28
+ /**
29
+ * Open `url` in the browser: `$BROWSER` when set (a program, run with the URL as its only argument, no
30
+ * shell), else `open` (macOS), `rundll32 url.dll,FileProtocolHandler` (Windows) or `xdg-open`. A failure is
31
+ * a warning: the server keeps running.
32
+ */
33
+ export declare function openBrowser(url: string, warn: (m: string) => void): void;
34
+ /**
35
+ * Read single keys from stdin while serving: when stdin is a terminal (raw mode), or when
36
+ * `SITEFILE_SERVE_KEYS=1` (tests drive it through a pipe). Returns a function that stops reading and
37
+ * restores the terminal, or undefined when keys are off.
38
+ */
39
+ export declare function readKeys(onAction: (a: KeyAction) => void): (() => void) | undefined;