@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.
Files changed (130) hide show
  1. package/CHANGELOG.md +467 -0
  2. package/README.md +55 -6
  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 +141 -16
  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
@@ -34,21 +34,63 @@ function dosDateTime(epoch) {
34
34
  date: ((year - 1980) << 9) | ((d.getUTCMonth() + 1) << 5) | d.getUTCDate(),
35
35
  };
36
36
  }
37
- /** Zip (no zip64). Deflate when it shrinks the data, otherwise stored. */
38
- export function writeZip(tree, options = {}) {
39
- const entries = entriesOf(tree);
37
+ /** File extensions (ASCII, lowercase) whose content is already compressed; zip stores them without deflating. */
38
+ export const COMPRESSED_MEDIA = [
39
+ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'heic', 'jxl',
40
+ 'woff', 'woff2',
41
+ 'mp3', 'm4a', 'aac', 'ogg', 'oga', 'opus', 'flac',
42
+ 'mp4', 'm4v', 'webm', 'mov', 'mkv',
43
+ 'zip', 'gz', 'tgz', 'br', 'zst', 'xz', 'bz2', '7z', 'rar', 'wbn',
44
+ ];
45
+ const COMPRESSED = new Set(COMPRESSED_MEDIA);
46
+ /** Whether a zip entry name ends in an already-compressed media extension ({@link COMPRESSED_MEDIA}), ASCII case-insensitively. */
47
+ export function isCompressedMedia(name) {
48
+ const base = name.slice(name.lastIndexOf('/') + 1);
49
+ const dot = base.lastIndexOf('.');
50
+ return dot > 0 && COMPRESSED.has(base.slice(dot + 1).replace(/[A-Z]/g, (c) => c.toLowerCase()));
51
+ }
52
+ /**
53
+ * The extended-timestamp extra field (0x5455 "UT", APPNOTE 4.4.6, Info-ZIP extrafld.txt) with the
54
+ * modification time only: unlike the DOS time, which unzippers read as local time, it is UTC
55
+ * seconds, so SOURCE_DATE_EPOCH survives extraction in any time zone. The same 9 bytes go in the
56
+ * local and the central header. Without an epoch it says 1980-01-01, as the DOS time does.
57
+ */
58
+ function extendedTimestamp(epoch) {
59
+ const ut = Buffer.alloc(9);
60
+ ut.writeUInt16LE(0x5455, 0);
61
+ ut.writeUInt16LE(5, 2);
62
+ ut[4] = 1; // mtime present
63
+ ut.writeUInt32LE(Math.min(Math.max(epoch ?? 315532800, 0), 0xffffffff), 5);
64
+ return ut;
65
+ }
66
+ /**
67
+ * Zip (no zip64). Deflate when it shrinks the data, otherwise stored.
68
+ *
69
+ * `first` (tree paths, e.g. `['/mimetype']` for EPUB): these entries come first, in that order, stored
70
+ * and without an extra field (the EPUB container requires its `mimetype` entry that way); the rest
71
+ * follow in path order as usual.
72
+ */
73
+ export function writeZip(tree, options = {}, first = []) {
74
+ const all = entriesOf(tree);
75
+ const firstNames = first.map((p) => p.slice(1));
76
+ const plain = new Set(firstNames);
77
+ const entries = [...firstNames.flatMap((n) => all.filter((e) => e.name === n)), ...all.filter((e) => !plain.has(e.name))];
40
78
  if (entries.length > ZIP_MAX_ENTRIES) {
41
79
  throw new SitefileError('E_EXPORT', `zip export supports at most ${ZIP_MAX_ENTRIES} entries (zip64 is not implemented); got ${entries.length}`);
42
80
  }
43
81
  const { time, date } = dosDateTime(options.epoch);
82
+ const ut = extendedTimestamp(options.epoch);
44
83
  const chunks = [];
45
84
  const central = [];
46
85
  let offset = 0;
47
86
  for (const e of entries) {
48
87
  if (e.nameBytes.length > 0xffff)
49
88
  throw new SitefileError('E_EXPORT', `zip entry name is too long (${e.nameBytes.length} bytes): '${e.name.slice(0, 60)}…'`);
50
- const deflated = deflateRaw(e.bytes);
51
- const stored = deflated.length >= e.bytes.length;
89
+ const isPlain = plain.has(e.name);
90
+ // Already-compressed media is stored as is: deflate would only spend time to gain nothing (#203).
91
+ const deflated = isPlain || isCompressedMedia(e.name) ? undefined : deflateRaw(e.bytes);
92
+ const stored = deflated === undefined || deflated.length >= e.bytes.length;
93
+ const extra = isPlain ? Buffer.alloc(0) : ut;
52
94
  const data = stored ? e.bytes : deflated;
53
95
  if (e.bytes.length > ZIP_MAX || data.length > ZIP_MAX) {
54
96
  throw new SitefileError('E_EXPORT', `zip export does not support files of 4 GiB or more (zip64 is not implemented): '/${e.name}'`);
@@ -68,7 +110,7 @@ export function writeZip(tree, options = {}) {
68
110
  lh.writeUInt32LE(data.length, 18);
69
111
  lh.writeUInt32LE(e.bytes.length, 22);
70
112
  lh.writeUInt16LE(e.nameBytes.length, 26);
71
- lh.writeUInt16LE(0, 28);
113
+ lh.writeUInt16LE(extra.length, 28);
72
114
  const ch = Buffer.alloc(46);
73
115
  ch.writeUInt32LE(0x02014b50, 0);
74
116
  ch.writeUInt16LE((3 << 8) | 20, 4); // made by: Unix, spec 2.0
@@ -81,12 +123,13 @@ export function writeZip(tree, options = {}) {
81
123
  ch.writeUInt32LE(data.length, 20);
82
124
  ch.writeUInt32LE(e.bytes.length, 24);
83
125
  ch.writeUInt16LE(e.nameBytes.length, 28);
84
- // extra, comment, disk number, internal attrs = 0
126
+ ch.writeUInt16LE(extra.length, 30);
127
+ // comment, disk number, internal attrs = 0
85
128
  ch.writeUInt32LE(((0o100000 | e.mode) << 16) >>> 0, 38);
86
129
  ch.writeUInt32LE(offset, 42);
87
- chunks.push(lh, e.nameBytes, data);
88
- central.push(ch, e.nameBytes);
89
- offset += 30 + e.nameBytes.length + data.length;
130
+ chunks.push(lh, e.nameBytes, extra, data);
131
+ central.push(ch, e.nameBytes, extra);
132
+ offset += 30 + e.nameBytes.length + extra.length + data.length;
90
133
  }
91
134
  const cdSize = central.reduce((n, c) => n + c.length, 0);
92
135
  if (offset + cdSize > ZIP_MAX)
@@ -0,0 +1,16 @@
1
+ import type { SourceSpan } from './errors.js';
2
+ import { type Tree } from './tree.js';
3
+ export interface CanonicalOp {
4
+ readonly base: string;
5
+ readonly pretty: boolean;
6
+ readonly root: string;
7
+ readonly span: SourceSpan;
8
+ }
9
+ /** A page's canonical URL: `<base><url path>`, `…/index.html` as its directory, and with `pretty` no `.html`. */
10
+ export declare function canonicalUrl(base: string, url: string, pretty: boolean): string;
11
+ /**
12
+ * The tree with `<link rel="canonical" href="…">` inserted before `</head>` of every `.html`/`.htm` page
13
+ * below `root` (except `/404.html` there) that is valid UTF-8 and has no canonical link yet. Pages without
14
+ * a `</head>` are left as they are, and named in one warning.
15
+ */
16
+ export declare function canonical(tree: Tree, op: CanonicalOp, origin: string, warn: (m: string) => void): Tree;
@@ -0,0 +1,46 @@
1
+ import { canonicalSlot, referenceKind } from './links.js';
2
+ import { pageUrl, xmlEscape } from './site.js';
3
+ import { makeFile } from './tree.js';
4
+ const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
5
+ /** A page's canonical URL: `<base><url path>`, `…/index.html` as its directory, and with `pretty` no `.html`. */
6
+ export function canonicalUrl(base, url, pretty) {
7
+ const u = pretty && url.endsWith('.html') && !url.endsWith('/index.html') ? url.slice(0, -'.html'.length) : url;
8
+ return pageUrl(base, u);
9
+ }
10
+ /**
11
+ * The tree with `<link rel="canonical" href="…">` inserted before `</head>` of every `.html`/`.htm` page
12
+ * below `root` (except `/404.html` there) that is valid UTF-8 and has no canonical link yet. Pages without
13
+ * a `</head>` are left as they are, and named in one warning.
14
+ */
15
+ export function canonical(tree, op, origin, warn) {
16
+ const files = [];
17
+ const headless = [];
18
+ for (const [p, node] of tree.entries()) {
19
+ if (referenceKind(p) !== 'html')
20
+ continue;
21
+ const url = op.root === '/' ? p : p.startsWith(op.root + '/') ? p.slice(op.root.length) : undefined;
22
+ if (url === undefined || url === '/404.html')
23
+ continue;
24
+ let text;
25
+ try {
26
+ text = UTF8.decode(node.bytes);
27
+ }
28
+ catch {
29
+ continue;
30
+ }
31
+ const at = canonicalSlot(text);
32
+ if (at === 'has')
33
+ continue;
34
+ if (at === undefined) {
35
+ headless.push(p);
36
+ continue;
37
+ }
38
+ const link = `<link rel="canonical" href="${xmlEscape(canonicalUrl(op.base, url, op.pretty))}">`;
39
+ files.push([p, makeFile(new TextEncoder().encode(text.slice(0, at) + link + text.slice(at)), origin, node.mode)]);
40
+ }
41
+ if (headless.length > 0) {
42
+ warn(`${origin}: ${headless.length === 1 ? '1 page has' : `${headless.length} pages have`} no </head>, so no canonical link was added: ${headless.join(', ')}`);
43
+ }
44
+ return files.length ? tree.withFiles(files, 'overwrite', op.span) : tree;
45
+ }
46
+ //# sourceMappingURL=canonical.js.map
@@ -0,0 +1,34 @@
1
+ import type { Tree } from './tree.js';
2
+ /**
3
+ * `EXPORT … AS car` (issue #208): the tree as a UnixFS DAG in a CARv1 file, the way
4
+ * `ipfs add -r --hidden --cid-version=1` (kubo) builds it, so the root CID is the one kubo
5
+ * prints for the same directory:
6
+ *
7
+ * - files are cut into 262144-byte chunks (kubo's default `size-262144` chunker); each chunk
8
+ * is a raw block (CIDv1, codec raw 0x55); a one-chunk file is that block;
9
+ * - longer files are a balanced tree of dag-pb UnixFS File nodes of at most 174 links;
10
+ * - directories are dag-pb UnixFS Directory nodes, links sorted by name (no HAMT sharding:
11
+ * a directory large enough for kubo to shard is refused);
12
+ * - every CID is v1 with a SHA-256 multihash; the root is the tree's `/` directory.
13
+ *
14
+ * The CAR holds every block once, root first, then depth first in link order. No
15
+ * timestamps or modes are recorded (kubo stores neither by default), so the output
16
+ * depends only on paths and contents.
17
+ */
18
+ export declare const CHUNK_SIZE = 262144;
19
+ export declare const MAX_LINKS = 174;
20
+ /** kubo shards a directory (HAMT) when the names and CIDs of its links exceed this many bytes. */
21
+ export declare const HAMT_THRESHOLD = 262144;
22
+ /** A CID as text: multibase base32 (lower case, no padding) with the `b` prefix. */
23
+ export declare function cidString(cid: Uint8Array): string;
24
+ /** The root CID of `tree` as `EXPORT … AS car` writes it. */
25
+ export declare function carRoot(tree: Tree): string;
26
+ /** CARv1: a dag-cbor header `{roots: [root], version: 1}`, then each block as varint(len) CID data. */
27
+ export declare function writeCar(tree: Tree): Uint8Array;
28
+ /** {@link writeCar} and the root CID. */
29
+ export declare function encodeCar(tree: Tree): {
30
+ bytes: Uint8Array;
31
+ root: string;
32
+ };
33
+ /** The CID of one file's UnixFS DAG (a raw block for a file of one chunk). */
34
+ export declare function fileCid(bytes: Uint8Array): string;
package/lib/src/car.js ADDED
@@ -0,0 +1,203 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { SitefileError } from './errors.js';
3
+ /**
4
+ * `EXPORT … AS car` (issue #208): the tree as a UnixFS DAG in a CARv1 file, the way
5
+ * `ipfs add -r --hidden --cid-version=1` (kubo) builds it, so the root CID is the one kubo
6
+ * prints for the same directory:
7
+ *
8
+ * - files are cut into 262144-byte chunks (kubo's default `size-262144` chunker); each chunk
9
+ * is a raw block (CIDv1, codec raw 0x55); a one-chunk file is that block;
10
+ * - longer files are a balanced tree of dag-pb UnixFS File nodes of at most 174 links;
11
+ * - directories are dag-pb UnixFS Directory nodes, links sorted by name (no HAMT sharding:
12
+ * a directory large enough for kubo to shard is refused);
13
+ * - every CID is v1 with a SHA-256 multihash; the root is the tree's `/` directory.
14
+ *
15
+ * The CAR holds every block once, root first, then depth first in link order. No
16
+ * timestamps or modes are recorded (kubo stores neither by default), so the output
17
+ * depends only on paths and contents.
18
+ */
19
+ export const CHUNK_SIZE = 262144;
20
+ export const MAX_LINKS = 174;
21
+ /** kubo shards a directory (HAMT) when the names and CIDs of its links exceed this many bytes. */
22
+ export const HAMT_THRESHOLD = 262144;
23
+ const RAW = 0x55;
24
+ const DAG_PB = 0x70;
25
+ function varint(n) {
26
+ const out = [];
27
+ let v = n;
28
+ while (v >= 0x80) {
29
+ out.push((v % 0x80) | 0x80);
30
+ v = Math.floor(v / 0x80);
31
+ }
32
+ out.push(v);
33
+ return out;
34
+ }
35
+ function concat(parts) {
36
+ let n = 0;
37
+ for (const p of parts)
38
+ n += p.byteLength;
39
+ const out = new Uint8Array(n);
40
+ let o = 0;
41
+ for (const p of parts) {
42
+ out.set(p, o);
43
+ o += p.byteLength;
44
+ }
45
+ return out;
46
+ }
47
+ /** CIDv1 bytes: version, codec, sha2-256 multihash. */
48
+ function cidOf(codec, block) {
49
+ const digest = createHash('sha256').update(block).digest();
50
+ return new Uint8Array([1, codec, 0x12, 0x20, ...digest]);
51
+ }
52
+ const B32 = 'abcdefghijklmnopqrstuvwxyz234567';
53
+ /** A CID as text: multibase base32 (lower case, no padding) with the `b` prefix. */
54
+ export function cidString(cid) {
55
+ let out = 'b';
56
+ let bits = 0;
57
+ let value = 0;
58
+ for (const byte of cid) {
59
+ value = (value << 8) | byte;
60
+ bits += 8;
61
+ while (bits >= 5) {
62
+ out += B32[(value >>> (bits - 5)) & 31];
63
+ bits -= 5;
64
+ }
65
+ value &= (1 << bits) - 1;
66
+ }
67
+ if (bits > 0)
68
+ out += B32[(value << (5 - bits)) & 31];
69
+ return out;
70
+ }
71
+ // --- protobuf (only what dag-pb and UnixFS need) ------------------------------
72
+ const field = (num, wire) => varint(num * 8 + wire);
73
+ const pbVarint = (num, v) => [...field(num, 0), ...varint(v)];
74
+ const pbBytes = (num, b) => concat([new Uint8Array([...field(num, 2), ...varint(b.byteLength)]), b]);
75
+ /** UnixFS `Data` message: Type, filesize, blocksizes (Data and the rest omitted). */
76
+ function unixfs(type, filesize, blocksizes = []) {
77
+ return new Uint8Array([...pbVarint(1, type), ...(filesize !== undefined ? pbVarint(3, filesize) : []), ...blocksizes.flatMap((s) => pbVarint(4, s))]);
78
+ }
79
+ /** A dag-pb node: links first (field 2), then data (field 1), as the dag-pb spec's canonical form has it. */
80
+ function dagPb(links, data) {
81
+ const enc = new TextEncoder();
82
+ const parts = links.map((l) => pbBytes(2, concat([pbBytes(1, l.cid), pbBytes(2, enc.encode(l.name)), new Uint8Array(pbVarint(3, l.tsize))])));
83
+ return concat([...parts, pbBytes(1, data)]);
84
+ }
85
+ class Dag {
86
+ /** Blocks by CID (hex), in creation order, and their children for the CAR walk. */
87
+ blocks = new Map();
88
+ put(codec, data, children) {
89
+ const cid = cidOf(codec, data);
90
+ const key = Buffer.from(cid).toString('hex');
91
+ if (!this.blocks.has(key))
92
+ this.blocks.set(key, { cid, data, children });
93
+ return cid;
94
+ }
95
+ file(bytes) {
96
+ const leaves = [];
97
+ for (let o = 0; o < bytes.byteLength || (o === 0 && leaves.length === 0); o += CHUNK_SIZE) {
98
+ const chunk = bytes.subarray(o, Math.min(o + CHUNK_SIZE, bytes.byteLength));
99
+ leaves.push({ cid: this.put(RAW, chunk, []), tsize: chunk.byteLength, fileSize: chunk.byteLength });
100
+ if (bytes.byteLength === 0)
101
+ break;
102
+ }
103
+ if (leaves.length === 1)
104
+ return leaves[0];
105
+ let depth = 1;
106
+ let span = MAX_LINKS;
107
+ while (span < leaves.length) {
108
+ depth++;
109
+ span *= MAX_LINKS;
110
+ }
111
+ return this.fileNode(leaves, depth);
112
+ }
113
+ /** kubo's balanced layout: every subtree but the last is full. */
114
+ fileNode(leaves, depth) {
115
+ let children;
116
+ if (depth === 1)
117
+ children = [...leaves];
118
+ else {
119
+ const per = MAX_LINKS ** (depth - 1);
120
+ children = [];
121
+ for (let i = 0; i < leaves.length; i += per)
122
+ children.push(this.fileNode(leaves.slice(i, i + per), depth - 1));
123
+ }
124
+ const fileSize = children.reduce((n, c) => n + c.fileSize, 0);
125
+ const block = dagPb(children.map((c) => ({ cid: c.cid, name: '', tsize: c.tsize })), unixfs(2, fileSize, children.map((c) => c.fileSize)));
126
+ const cid = this.put(DAG_PB, block, children.map((c) => c.cid));
127
+ return { cid, tsize: block.byteLength + children.reduce((n, c) => n + c.tsize, 0), fileSize };
128
+ }
129
+ dir(path, entries) {
130
+ const enc = new TextEncoder();
131
+ // dag-pb sorts links by name bytes.
132
+ const sorted = [...entries].sort(([a], [b]) => Buffer.compare(enc.encode(a), enc.encode(b)));
133
+ const estimate = sorted.reduce((n, [name, c]) => n + enc.encode(name).byteLength + c.cid.byteLength, 0);
134
+ if (estimate > HAMT_THRESHOLD) {
135
+ throw new SitefileError('E_EXPORT', `car export: directory '${path}' has too many entries for a plain UnixFS directory (IPFS would shard it; HAMT directories are not supported)`);
136
+ }
137
+ const block = dagPb(sorted.map(([name, c]) => ({ cid: c.cid, name, tsize: c.tsize })), unixfs(1));
138
+ const cid = this.put(DAG_PB, block, sorted.map(([, c]) => c.cid));
139
+ return { cid, tsize: block.byteLength + sorted.reduce((n, [, c]) => n + c.tsize, 0), fileSize: 0 };
140
+ }
141
+ }
142
+ function buildDag(tree) {
143
+ const top = { files: new Map(), dirs: new Map() };
144
+ for (const [p, n] of tree.entries()) {
145
+ const segs = p.slice(1).split('/');
146
+ let d = top;
147
+ for (const s of segs.slice(0, -1)) {
148
+ let next = d.dirs.get(s);
149
+ if (!next)
150
+ d.dirs.set(s, (next = { files: new Map(), dirs: new Map() }));
151
+ d = next;
152
+ }
153
+ d.files.set(segs[segs.length - 1], n.bytes);
154
+ }
155
+ const dag = new Dag();
156
+ const walk = (d, path) => {
157
+ const entries = [];
158
+ for (const [name, sub] of d.dirs)
159
+ entries.push([name, walk(sub, path === '/' ? `/${name}` : `${path}/${name}`)]);
160
+ for (const [name, bytes] of d.files)
161
+ entries.push([name, dag.file(bytes)]);
162
+ return dag.dir(path, entries);
163
+ };
164
+ return { dag, root: walk(top, '/').cid };
165
+ }
166
+ /** The root CID of `tree` as `EXPORT … AS car` writes it. */
167
+ export function carRoot(tree) {
168
+ return cidString(buildDag(tree).root);
169
+ }
170
+ /** CARv1: a dag-cbor header `{roots: [root], version: 1}`, then each block as varint(len) CID data. */
171
+ export function writeCar(tree) {
172
+ return encodeCar(tree).bytes;
173
+ }
174
+ /** {@link writeCar} and the root CID. */
175
+ export function encodeCar(tree) {
176
+ const { dag, root } = buildDag(tree);
177
+ const enc = new TextEncoder();
178
+ // dag-cbor: map(2) "roots" -> [tag 42 bytes(0x00 ‖ cid)], "version" -> 1 (keys by length, then bytes).
179
+ const cidBytes = [0x00, ...root];
180
+ const header = new Uint8Array([0xa2, 0x65, ...enc.encode('roots'), 0x81, 0xd8, 0x2a, 0x58, cidBytes.length, ...cidBytes, 0x67, ...enc.encode('version'), 0x01]);
181
+ const parts = [new Uint8Array(varint(header.byteLength)), header];
182
+ const seen = new Set();
183
+ const stack = [root];
184
+ while (stack.length) {
185
+ const cid = stack.pop();
186
+ const key = Buffer.from(cid).toString('hex');
187
+ if (seen.has(key))
188
+ continue;
189
+ seen.add(key);
190
+ const b = dag.blocks.get(key);
191
+ if (!b)
192
+ throw new Error('car: missing block');
193
+ parts.push(new Uint8Array(varint(cid.byteLength + b.data.byteLength)), cid, b.data);
194
+ for (let i = b.children.length - 1; i >= 0; i--)
195
+ stack.push(b.children[i]);
196
+ }
197
+ return { bytes: concat(parts), root: cidString(root) };
198
+ }
199
+ /** The CID of one file's UnixFS DAG (a raw block for a file of one chunk). */
200
+ export function fileCid(bytes) {
201
+ return cidString(new Dag().file(bytes).cid);
202
+ }
203
+ //# sourceMappingURL=car.js.map
@@ -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 });