@johnhenry/sitefile 0.0.2 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +516 -0
- package/README.md +59 -9
- package/lib/src/archive-writers.d.ts +12 -2
- package/lib/src/archive-writers.js +53 -10
- package/lib/src/bake.d.ts +2 -0
- package/lib/src/bake.js +30 -1
- package/lib/src/bcrypt.d.ts +25 -0
- package/lib/src/bcrypt.js +201 -0
- package/lib/src/canonical.d.ts +19 -0
- package/lib/src/canonical.js +60 -0
- package/lib/src/car.d.ts +34 -0
- package/lib/src/car.js +203 -0
- package/lib/src/checklinks.js +8 -2
- package/lib/src/cli/bake.js +4 -3
- package/lib/src/cli/build-image.d.ts +1 -0
- package/lib/src/cli/build-image.js +1 -0
- package/lib/src/cli/common.js +4 -1
- package/lib/src/cli/hosts.d.ts +5 -0
- package/lib/src/cli/hosts.js +78 -0
- package/lib/src/cli/images.js +23 -5
- package/lib/src/cli/import-config.d.ts +2 -0
- package/lib/src/cli/import-config.js +56 -0
- package/lib/src/cli/index.d.ts +6 -1
- package/lib/src/cli/index.js +34 -2
- package/lib/src/cli/integrity.d.ts +2 -0
- package/lib/src/cli/integrity.js +77 -0
- package/lib/src/cli/network.d.ts +7 -0
- package/lib/src/cli/network.js +14 -3
- package/lib/src/cli/serve-keys.d.ts +39 -0
- package/lib/src/cli/serve-keys.js +106 -0
- package/lib/src/cli/serve-worker.js +119 -8
- package/lib/src/cli/servers.d.ts +130 -1
- package/lib/src/cli/servers.js +754 -72
- package/lib/src/cli/up.d.ts +2 -0
- package/lib/src/cli/up.js +193 -0
- package/lib/src/cli/watch.d.ts +14 -1
- package/lib/src/cli/watch.js +20 -3
- package/lib/src/cli.js +138 -18
- package/lib/src/csp.d.ts +17 -0
- package/lib/src/csp.js +52 -0
- package/lib/src/dictionary.d.ts +16 -0
- package/lib/src/dictionary.js +89 -0
- package/lib/src/epub.d.ts +5 -0
- package/lib/src/epub.js +113 -0
- package/lib/src/errors.d.ts +22 -9
- package/lib/src/errors.js +20 -1
- package/lib/src/executor.d.ts +31 -1
- package/lib/src/executor.js +231 -24
- package/lib/src/explain.js +33 -3
- package/lib/src/export-for.d.ts +42 -0
- package/lib/src/export-for.js +466 -0
- package/lib/src/export-formats.d.ts +2 -2
- package/lib/src/export-formats.js +52 -2
- package/lib/src/fingerprint.d.ts +3 -1
- package/lib/src/fingerprint.js +32 -5
- package/lib/src/host-config.d.ts +34 -0
- package/lib/src/host-config.js +645 -0
- package/lib/src/hosts.d.ts +47 -0
- package/lib/src/hosts.js +106 -0
- package/lib/src/hreflang.d.ts +25 -0
- package/lib/src/hreflang.js +72 -0
- package/lib/src/index.d.ts +1 -1
- package/lib/src/index.js +1 -1
- package/lib/src/integrity.d.ts +115 -0
- package/lib/src/integrity.js +273 -0
- package/lib/src/language/ast.d.ts +126 -3
- package/lib/src/language/ast.js +7 -1
- package/lib/src/language/parser.js +189 -7
- package/lib/src/language/validate.js +24 -0
- package/lib/src/links.d.ts +47 -0
- package/lib/src/links.js +289 -3
- package/lib/src/lint.d.ts +1 -1
- package/lib/src/lint.js +26 -1
- package/lib/src/mime-data.d.ts +2 -0
- package/lib/src/mime-data.js +92 -0
- package/lib/src/oci.d.ts +20 -2
- package/lib/src/oci.js +70 -28
- package/lib/src/outdated.d.ts +3 -0
- package/lib/src/outdated.js +4 -4
- package/lib/src/planner.d.ts +87 -2
- package/lib/src/planner.js +189 -8
- package/lib/src/plugins/cache.d.ts +11 -0
- package/lib/src/plugins/cache.js +29 -0
- package/lib/src/plugins/host.d.ts +51 -2
- package/lib/src/plugins/host.js +141 -16
- package/lib/src/plugins/wasm.js +1 -3
- package/lib/src/portable.d.ts +8 -0
- package/lib/src/portable.js +47 -0
- package/lib/src/precache.d.ts +33 -0
- package/lib/src/precache.js +75 -0
- package/lib/src/precompress.d.ts +19 -0
- package/lib/src/precompress.js +35 -0
- package/lib/src/qr.d.ts +18 -0
- package/lib/src/qr.js +372 -0
- package/lib/src/registry-ops.js +4 -2
- package/lib/src/reload-client.d.ts +2 -0
- package/lib/src/reload-client.js +419 -0
- package/lib/src/resources/archive.d.ts +37 -1
- package/lib/src/resources/archive.js +353 -71
- package/lib/src/resources/convert.js +3 -1
- package/lib/src/resources/https.d.ts +9 -1
- package/lib/src/resources/https.js +36 -0
- package/lib/src/resources/network.d.ts +25 -3
- package/lib/src/resources/network.js +77 -6
- package/lib/src/secrets.d.ts +12 -3
- package/lib/src/secrets.js +18 -5
- package/lib/src/serve-auth.d.ts +33 -0
- package/lib/src/serve-auth.js +120 -0
- package/lib/src/serve-rules.d.ts +83 -7
- package/lib/src/serve-rules.js +264 -53
- package/lib/src/server.d.ts +529 -11
- package/lib/src/server.js +1439 -57
- package/lib/src/servers-file.d.ts +36 -0
- package/lib/src/servers-file.js +101 -0
- package/lib/src/servers.d.ts +115 -7
- package/lib/src/servers.js +151 -29
- package/lib/src/single-file.d.ts +12 -0
- package/lib/src/single-file.js +147 -0
- package/lib/src/site.d.ts +58 -0
- package/lib/src/site.js +216 -5
- package/lib/src/store.js +9 -5
- package/lib/src/swbn.d.ts +10 -0
- package/lib/src/swbn.js +86 -0
- package/lib/src/toml.d.ts +17 -0
- package/lib/src/toml.js +323 -0
- package/lib/src/wacz.d.ts +6 -0
- package/lib/src/wacz.js +96 -0
- package/lib/src/warc.d.ts +28 -0
- package/lib/src/warc.js +252 -0
- package/lib/src/watch.d.ts +12 -1
- package/lib/src/watch.js +67 -1
- package/lib/src/wbn.d.ts +9 -1
- package/lib/src/wbn.js +23 -33
- package/lib/src/zstd.d.ts +4 -0
- package/lib/src/zstd.js +328 -0
- package/package.json +1 -1
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { alternates } from './hreflang.js';
|
|
2
|
+
import { headLinks, referenceKind } from './links.js';
|
|
3
|
+
import { pageUrl, xmlEscape } from './site.js';
|
|
4
|
+
import { makeFile } from './tree.js';
|
|
5
|
+
const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
6
|
+
/** A page's canonical URL: `<base><url path>`, `…/index.html` as its directory, and with `pretty` no `.html`. */
|
|
7
|
+
export function canonicalUrl(base, url, pretty) {
|
|
8
|
+
const u = pretty && url.endsWith('.html') && !url.endsWith('/index.html') ? url.slice(0, -'.html'.length) : url;
|
|
9
|
+
return pageUrl(base, u);
|
|
10
|
+
}
|
|
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. With `langs`
|
|
14
|
+
* (LANGUAGES), a page that has translations also gets a `<link rel="alternate" hreflang="…">` for each
|
|
15
|
+
* (see {@link alternates}), unless it has such links already. Pages without a `</head>` are left as they
|
|
16
|
+
* are, and named in one warning.
|
|
17
|
+
*/
|
|
18
|
+
export function canonical(tree, op, origin, warn, langs) {
|
|
19
|
+
const pages = [];
|
|
20
|
+
for (const [p, node] of tree.entries()) {
|
|
21
|
+
if (referenceKind(p) !== 'html')
|
|
22
|
+
continue;
|
|
23
|
+
const url = op.root === '/' ? p : p.startsWith(op.root + '/') ? p.slice(op.root.length) : undefined;
|
|
24
|
+
if (url === undefined || url === '/404.html')
|
|
25
|
+
continue;
|
|
26
|
+
pages.push([p, url, node]);
|
|
27
|
+
}
|
|
28
|
+
const alts = langs ? alternates(pages.map(([p, url]) => [p, url]), langs, 'CANONICAL', op.span) : undefined;
|
|
29
|
+
const files = [];
|
|
30
|
+
const headless = [];
|
|
31
|
+
for (const [p, url, node] of pages) {
|
|
32
|
+
let text;
|
|
33
|
+
try {
|
|
34
|
+
text = UTF8.decode(node.bytes);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
const head = headLinks(text);
|
|
40
|
+
const alt = alts?.get(p);
|
|
41
|
+
const addAlternates = alt !== undefined && !head.hreflang;
|
|
42
|
+
if (head.canonical && !addAlternates)
|
|
43
|
+
continue;
|
|
44
|
+
if (head.at === undefined) {
|
|
45
|
+
headless.push(p);
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
let links = head.canonical ? '' : `<link rel="canonical" href="${xmlEscape(canonicalUrl(op.base, url, op.pretty))}">`;
|
|
49
|
+
if (addAlternates) {
|
|
50
|
+
for (const [lang, u] of alt)
|
|
51
|
+
links += `<link rel="alternate" hreflang="${xmlEscape(lang)}" href="${xmlEscape(canonicalUrl(op.base, u, op.pretty))}">`;
|
|
52
|
+
}
|
|
53
|
+
files.push([p, makeFile(new TextEncoder().encode(text.slice(0, head.at) + links + text.slice(head.at)), origin, node.mode)]);
|
|
54
|
+
}
|
|
55
|
+
if (headless.length > 0) {
|
|
56
|
+
warn(`${origin}: ${headless.length === 1 ? '1 page has' : `${headless.length} pages have`} no </head>, so no canonical link was added: ${headless.join(', ')}`);
|
|
57
|
+
}
|
|
58
|
+
return files.length ? tree.withFiles(files, 'overwrite', op.span) : tree;
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=canonical.js.map
|
package/lib/src/car.d.ts
ADDED
|
@@ -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
|
package/lib/src/checklinks.js
CHANGED
|
@@ -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
|
-
|
|
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 });
|
package/lib/src/cli/bake.js
CHANGED
|
@@ -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, --
|
|
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,
|
package/lib/src/cli/common.js
CHANGED
|
@@ -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
|
package/lib/src/cli/images.js
CHANGED
|
@@ -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
|
|
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,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
|
package/lib/src/cli/index.d.ts
CHANGED
|
@@ -5,6 +5,11 @@ 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
|
+
/**
|
|
12
|
+
* `serve --open` and `--sync` take a value only as `--open=<path>`, `--sync=scroll`: a bare `--open`
|
|
13
|
+
* or `--sync` (before `--`) is `--open=`, `--sync=`.
|
|
14
|
+
*/
|
|
15
|
+
export declare function optionalOpen(args: readonly string[]): string[];
|