@johnhenry/sitefile 0.0.8 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28,12 +28,12 @@ export declare function formatLimit(bytes: number): string;
28
28
  /** The limit from $SITEFILE_CACHE_MAX (unset or empty: the default). A bad value warns and uses the default. */
29
29
  export declare function cacheLimitFromEnv(env?: NodeJS.ProcessEnv, warn?: (m: string) => void): number;
30
30
  export interface CacheUsage {
31
- readonly name: 'transform' | 'wasm' | 'store' | 'servers';
31
+ readonly name: 'transform' | 'wasm' | 'store' | 'servers' | 'buckets';
32
32
  readonly path: string;
33
- /** TRANSFORM entries, .cwasm modules, store blobs, server files. */
33
+ /** TRANSFORM entries, .cwasm modules, store blobs, server files, bucket files. */
34
34
  readonly items: number;
35
35
  readonly bytes: number;
36
- /** Bytes the size limit may delete (everything but tagged images' blobs and server state). */
36
+ /** Bytes the size limit may delete (everything but tagged images' blobs, server state and buckets). */
37
37
  readonly evictable: number;
38
38
  }
39
39
  export declare function cachePaths(home: string): Record<CacheUsage['name'], string>;
@@ -72,6 +72,7 @@ export function cachePaths(home) {
72
72
  wasm: path.join(home, 'cache', 'wasm'),
73
73
  store: path.join(home, 'blobs', 'sha256'),
74
74
  servers: path.join(home, 'servers'),
75
+ buckets: path.join(home, 'buckets'),
75
76
  };
76
77
  }
77
78
  class Model {
@@ -151,6 +152,24 @@ async function sizeOf(dir) {
151
152
  const f = await files(dir);
152
153
  return [f.length, f.reduce((a, x) => a + x.size, 0)];
153
154
  }
155
+ /** Files and bytes under `dir`, below its subdirectories too (links are not followed, never counted). */
156
+ async function deepSizeOf(dir) {
157
+ let items = 0;
158
+ let bytes = 0;
159
+ for (const name of await readdir(dir).catch(() => [])) {
160
+ const st = await lstat(path.join(dir, name)).catch(() => undefined);
161
+ if (st?.isDirectory()) {
162
+ const [i, b] = await deepSizeOf(path.join(dir, name));
163
+ items += i;
164
+ bytes += b;
165
+ }
166
+ else if (st?.isFile()) {
167
+ items++;
168
+ bytes += st.size;
169
+ }
170
+ }
171
+ return [items, bytes];
172
+ }
154
173
  /** Sizes per cache under `home` (for `cache du`). */
155
174
  export async function cacheUsage(home) {
156
175
  const p = cachePaths(home);
@@ -165,11 +184,13 @@ export async function cacheUsage(home) {
165
184
  if (store)
166
185
  [storeItems, storeBytes] = await addStore(s, store, p.store);
167
186
  const [serverItems, serverBytes] = await sizeOf(p.servers);
187
+ const [bucketItems, bucketBytes] = await deepSizeOf(p.buckets);
168
188
  return [
169
189
  { name: 'transform', path: p.transform, items: entries, bytes: t.total, evictable: t.total },
170
190
  { name: 'wasm', path: p.wasm, items: modules, bytes: w.total, evictable: w.total },
171
191
  { name: 'store', path: p.store, items: storeItems, bytes: storeBytes, evictable: s.total },
172
192
  { name: 'servers', path: p.servers, items: serverItems, bytes: serverBytes, evictable: 0 },
193
+ { name: 'buckets', path: p.buckets, items: bucketItems, bytes: bucketBytes, evictable: 0 },
173
194
  ];
174
195
  }
175
196
  /**
@@ -0,0 +1,2 @@
1
+ import { type Command } from './common.js';
2
+ export declare const bucketSubcommands: ReadonlyMap<string, Command>;
@@ -0,0 +1,312 @@
1
+ import { createReadStream, promises as fs } from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { sourceDateEpoch } from '../archive-writers.js';
5
+ import { BUCKET_NAME_MAX, Buckets, checkBucketName, checkBucketPath, DEFAULT_LOAD_MAX_BYTES, DEFAULT_PUT_MAX_BYTES, splitBucketRef } from '../bucket.js';
6
+ import { SitefileError } from '../errors.js';
7
+ import { exportFile } from '../exporter.js';
8
+ import { parseLabels } from '../oci.js';
9
+ import { parseLocalRef } from '../ref.js';
10
+ import { LocalContext } from '../resources/local.js';
11
+ import { isRunning, ServerRegistry } from '../servers.js';
12
+ import { shortId, Store } from '../store.js';
13
+ import { Tree } from '../tree.js';
14
+ import { validateImageTags } from './build-image.js';
15
+ import { humanSize, relativeTime, requireArgs, str, strs, table, usage } from './common.js';
16
+ const octal = (mode) => mode.toString(8);
17
+ async function open() {
18
+ const store = await Store.open();
19
+ return { store, buckets: Buckets.open(store) };
20
+ }
21
+ /** `--max-bytes`: a whole number of bytes, at least 1. */
22
+ function maxBytesOf(v) {
23
+ const raw = str(v['max-bytes']);
24
+ if (raw === undefined)
25
+ return DEFAULT_PUT_MAX_BYTES;
26
+ if (!/^[0-9]{1,15}$/.test(raw) || Number(raw) < 1)
27
+ usage(`--max-bytes expects a number of bytes (at least 1), got '${raw}'`);
28
+ return Number(raw);
29
+ }
30
+ /** `--max-bytes` for a bucket read into memory (`snapshot`, `restore`): a whole number of bytes, at least 1. */
31
+ function loadLimitOf(v) {
32
+ const raw = str(v['max-bytes']);
33
+ if (raw === undefined)
34
+ return DEFAULT_LOAD_MAX_BYTES;
35
+ if (!/^[0-9]{1,15}$/.test(raw) || Number(raw) < 1)
36
+ usage(`--max-bytes expects a number of bytes (at least 1), got '${raw}'`);
37
+ return Number(raw);
38
+ }
39
+ /** A path with a hidden segment: a name starting with a dot, but `.well-known` (what `serve` hides from a folder or a bucket). */
40
+ const isHiddenPath = (p) => p.split('/').some((s) => s.startsWith('.') && s !== '.well-known' && s !== '');
41
+ const create = {
42
+ name: 'bucket create',
43
+ summary: 'create an empty bucket',
44
+ usage: 'bucket create <name>',
45
+ description: `Create an empty bucket: a named, mutable tree of files in the store ($SITEFILE_HOME/buckets/<name>/, plain files).\nA name is lowercase letters, digits, '.', '_' and '-' between them, at most ${BUCKET_NAME_MAX} characters.`,
46
+ flags: [],
47
+ options: {},
48
+ async run(_v, pos) {
49
+ requireArgs(pos, 1, 1, 'a bucket name');
50
+ const { buckets } = await open();
51
+ const name = checkBucketName(pos[0]);
52
+ await buckets.create(name);
53
+ process.stdout.write(`Created bucket ${name}\n`);
54
+ return 0;
55
+ },
56
+ };
57
+ const ls = {
58
+ name: 'bucket ls',
59
+ summary: 'list buckets, or the files of one',
60
+ usage: 'bucket ls [<name>[/prefix]] [--json] [-q]',
61
+ description: 'Without an argument, list the buckets (NAME FILES SIZE CREATED). With <name>[/prefix], list the files under that\ndirectory (or the one file), as MODE SIZE PATH, paths relative to the bucket. A prefix is a path of whole names.',
62
+ flags: ['--json machine-readable output', '-q, --quiet only the names (buckets) or paths (files)'],
63
+ options: { json: { type: 'boolean' }, quiet: { type: 'boolean', short: 'q' } },
64
+ async run(v, pos) {
65
+ requireArgs(pos, 0, 1, 'a bucket name, or name/prefix');
66
+ const { buckets } = await open();
67
+ if (pos.length === 0) {
68
+ const list = await buckets.list();
69
+ if (v.json)
70
+ process.stdout.write(JSON.stringify(list, null, 2) + '\n');
71
+ else if (v.quiet)
72
+ for (const b of list)
73
+ process.stdout.write(`${b.name}\n`);
74
+ else
75
+ process.stdout.write(table([['NAME', 'FILES', 'SIZE', 'CREATED'], ...list.map((b) => [b.name, b.problem === undefined ? String(b.files) : '-', b.problem === undefined ? humanSize(b.size) : '-', relativeTime(b.created)])]));
76
+ // A bucket that cannot be read says why and what to do; the others are listed all the same.
77
+ if (!v.json)
78
+ for (const b of list)
79
+ if (b.problem !== undefined)
80
+ process.stderr.write(`warning: ${b.problem}\n`);
81
+ return 0;
82
+ }
83
+ const { name, segs } = splitBucketRef(pos[0]);
84
+ const files = await buckets.listFiles(name, segs);
85
+ if (v.json)
86
+ process.stdout.write(JSON.stringify(files.map((f) => ({ path: f.path, mode: octal(f.mode), size: f.size })), null, 2) + '\n');
87
+ else if (v.quiet)
88
+ for (const f of files)
89
+ process.stdout.write(`${f.path}\n`);
90
+ else
91
+ for (const f of files)
92
+ process.stdout.write(`${octal(f.mode)} ${String(f.size).padStart(8)} ${f.path}\n`);
93
+ return 0;
94
+ },
95
+ };
96
+ const rm = {
97
+ name: 'bucket rm',
98
+ summary: 'remove a bucket, a file or a directory of one',
99
+ usage: 'bucket rm [-f] [-r] <name>[/path]',
100
+ description: 'With a bare <name>, remove the bucket: it must be empty and not served by a running server, or pass -f (the files are\ngone for good; a server keeps serving its last copy until it is restarted, and then cannot start). With <name>/<path>,\nremove that file, or with -r that directory and everything in it. Links inside a bucket are removed, never followed.',
101
+ flags: ['-f, --force remove a bucket that has files or is served', '-r, --recursive remove a directory and everything in it'],
102
+ options: { force: { type: 'boolean', short: 'f' }, recursive: { type: 'boolean', short: 'r' } },
103
+ async run(v, pos) {
104
+ requireArgs(pos, 1, 1, 'a bucket name, or name/path');
105
+ const { store, buckets } = await open();
106
+ const ref = pos[0];
107
+ const { name, segs, slash } = splitBucketRef(ref);
108
+ if (slash) {
109
+ if (segs.length === 0)
110
+ usage("expected name/path; to remove the bucket itself, write its name without a '/'");
111
+ await buckets.removePath(name, segs, !!v.recursive);
112
+ process.stdout.write(`Removed ${name}/${segs.join('/')}\n`);
113
+ return 0;
114
+ }
115
+ if (v.recursive)
116
+ usage('-r is for a directory inside a bucket (name/path); a bucket with files needs -f');
117
+ const isLink = (await buckets.kindOf(name)) === 'link'; // a link planted where the bucket should be: rm removes the link only
118
+ if (!isLink)
119
+ await buckets.realDir(name);
120
+ const reg = await ServerRegistry.open(store);
121
+ const serving = [];
122
+ for (const s of await reg.all()) {
123
+ if (s.source.kind === 'bucket' && s.source.name === name && (await isRunning(s)))
124
+ serving.push({ name: s.name, id: s.id });
125
+ }
126
+ if (serving.length > 0 && !v.force) {
127
+ throw new SitefileError('E_SERVER', `bucket '${name}' is served by ${serving.map((s) => `${s.name} (${s.id})`).join(', ')}; stop ${serving.length === 1 ? 'it' : 'them'} first ("sitefile server rm ${serving[0].name}"), or use -f to remove the bucket anyway`);
128
+ }
129
+ const files = isLink ? 0 : v.force ? await buckets.stats(name).then((s) => s.files, () => 0) : (await buckets.stats(name)).files;
130
+ if (files > 0 && !v.force)
131
+ throw new SitefileError('E_CONFLICT', `bucket '${name}' holds ${files} file${files === 1 ? '' : 's'}; use -f to remove it and them`);
132
+ // Said before the removal: if a late step fails after the bucket is gone, the person has been told what happens to the servers.
133
+ for (const s of serving)
134
+ process.stderr.write(`warning: ${s.name} (${s.id}) serves bucket '${name}': it keeps its last copy, and cannot be restarted until the bucket exists again\n`);
135
+ await buckets.remove(name);
136
+ process.stdout.write(isLink ? `Removed bucket ${name} (a link; what it pointed at was not touched)\n` : `Removed bucket ${name} (${files} file${files === 1 ? '' : 's'})\n`);
137
+ return 0;
138
+ },
139
+ };
140
+ const put = {
141
+ name: 'bucket put',
142
+ summary: 'put a file, or a directory of files, into a bucket',
143
+ usage: 'bucket put [--max-bytes n] <name>/<path> [<file|->] | bucket put [--overwrite] [--batch] <name>[/prefix] <dir>',
144
+ description: 'Write <file> (or stdin, also written "-") to <path> in the bucket. The file is written to a temporary name and\nrenamed into place, so a reader sees the old file or the new one, never half of it; an existing file is replaced.\nWith a directory, every file in it is put under <prefix> (default: the root of the bucket); a file that would\nreplace different content needs --overwrite. By default each file is written on its own; with --batch the\nresulting tree is built beside the bucket and swapped in with one rename, so a reader sees all of the change or\nnone of it. Paths: no "..", no absolute or backslash paths, no names Windows cannot hold, and no two names that\ndiffer only in case.',
145
+ flags: [
146
+ `--max-bytes <n> most bytes a file or a directory may hold (default ${DEFAULT_PUT_MAX_BYTES}); stdin is cut off there`,
147
+ '--overwrite a directory put may replace files that hold different content',
148
+ '--batch a directory put becomes visible all at once (see above)',
149
+ ],
150
+ options: { 'max-bytes': { type: 'string' }, overwrite: { type: 'boolean' }, batch: { type: 'boolean' } },
151
+ async run(v, pos) {
152
+ requireArgs(pos, 1, 2, '<name>/<path> and a file (or - for stdin)');
153
+ const { buckets } = await open();
154
+ const ref = pos[0];
155
+ const { name, segs } = splitBucketRef(ref);
156
+ const src = pos[1] ?? '-';
157
+ const maxBytes = maxBytesOf(v);
158
+ const st = src === '-' ? undefined : await fs.stat(src).catch(() => undefined);
159
+ if (src !== '-' && st === undefined)
160
+ throw new SitefileError('E_NOT_FOUND', `'${src}' does not exist`);
161
+ if (st?.isDirectory()) {
162
+ const ctx = await LocalContext.open(src, { sitefileignore: false });
163
+ const { tree } = await ctx.readTree('', 'bucket put');
164
+ let total = 0;
165
+ const writes = [];
166
+ for (const [p, node] of tree.entries()) {
167
+ total += node.bytes.byteLength;
168
+ if (total > maxBytes)
169
+ throw new SitefileError('E_TOO_LARGE', `'${src}' holds more than the limit of ${maxBytes} bytes (--max-bytes raises it)`);
170
+ const full = '/' + checkBucketPath([...segs, ...p.slice(1).split('/')].join('/')).join('/');
171
+ writes.push([full, node]);
172
+ }
173
+ await buckets.recover(name);
174
+ await buckets.realDir(name);
175
+ const r = await buckets.apply(name, { writes, deleteOthers: false }, { overwrite: !!v.overwrite, batch: !!v.batch });
176
+ process.stdout.write(`Put ${r.written} file${r.written === 1 ? '' : 's'} into ${ref.replace(/\/+$/, '')} (${r.unchanged} unchanged)\n`);
177
+ return 0;
178
+ }
179
+ if (v.overwrite || v.batch)
180
+ usage('--overwrite and --batch are for putting a directory');
181
+ if (segs.length === 0 || ref.endsWith('/'))
182
+ usage(`expected <name>/<path> of a file, got '${ref}'`);
183
+ if (st !== undefined && !st.isFile())
184
+ throw new SitefileError('E_UNSUPPORTED_FILE', `'${src}' is not a regular file or directory`);
185
+ if (st !== undefined && st.size > maxBytes)
186
+ throw new SitefileError('E_TOO_LARGE', `'${src}' is larger than the limit of ${maxBytes} bytes (--max-bytes raises it)`);
187
+ const source = st === undefined ? process.stdin : createReadStream(src);
188
+ const { result, size } = await buckets.putFile(name, segs, source, st?.mode ?? 0o644, maxBytes);
189
+ const verb = result === 'created' ? 'Put' : result === 'replaced' ? 'Replaced' : 'Unchanged';
190
+ process.stdout.write(`${verb} ${name}/${segs.join('/')} (${size} byte${size === 1 ? '' : 's'})\n`);
191
+ return 0;
192
+ },
193
+ };
194
+ const get = {
195
+ name: 'bucket get',
196
+ summary: 'write a file of a bucket to stdout or a file',
197
+ usage: 'bucket get <name>/<path> [-o <file>] [--force]',
198
+ description: 'Write the file to stdout, or with -o to <file> (an existing file needs --force). A symbolic link, or a file with more\nthan one hard link, is refused: a bucket never reads through them.',
199
+ flags: ['-o, --out <file> write here instead of stdout', '--force replace an existing -o file'],
200
+ options: { out: { type: 'string', short: 'o' }, force: { type: 'boolean' } },
201
+ async run(v, pos) {
202
+ requireArgs(pos, 1, 1, '<name>/<path>');
203
+ const { buckets } = await open();
204
+ const ref = pos[0];
205
+ const { name, segs } = splitBucketRef(ref);
206
+ if (segs.length === 0 || ref.endsWith('/'))
207
+ usage(`expected <name>/<path> of a file, got '${ref}'`);
208
+ const f = await buckets.get(name, segs);
209
+ const out = str(v.out);
210
+ if (out === undefined) {
211
+ process.stdout.write(f.bytes);
212
+ return 0;
213
+ }
214
+ const scratch = await fs.mkdtemp(path.join(os.tmpdir(), 'sitefile-bucket-'));
215
+ try {
216
+ await exportFile(f.bytes, out, { contextDir: scratch, ...(v.force ? { force: true } : {}) });
217
+ }
218
+ finally {
219
+ await fs.rm(scratch, { recursive: true, force: true });
220
+ }
221
+ return 0;
222
+ },
223
+ };
224
+ const snapshot = {
225
+ name: 'bucket snapshot',
226
+ summary: 'write an image from a bucket\'s current files',
227
+ usage: 'bucket snapshot <name> -t <name[:tag]>... [--include-hidden] [--max-bytes n] [--label key=value] [--oci-root path] [--platform os/arch]',
228
+ description: 'Store an image of the files the bucket holds now and tag it: the same image `build -t` makes from a Sitefile that\ncopies those files (same files, same root, platform and labels, so the same image ID). This is how a version of a\nbucket is made; the bucket itself keeps no history. Hidden files (a name starting with a dot, but .well-known) are\nleft out, and the command says how many: an image serves every file it holds and a bucket does not serve those, so a\n.env or .git put in a bucket by mistake does not become public. --include-hidden puts them in, with a warning.',
229
+ flags: ['-t, --tag <name[:tag]> tag the image (repeatable; at least one)', '--include-hidden also put hidden files in the image (default: left out)', '--max-bytes <n> most bytes the bucket may hold (default 2147483648)', '--label <key=value> add an OCI image config label (repeatable)', '--oci-root <path> directory inside the image layer (default /srv/www)', '--platform <os/arch> image platform (default linux/amd64)'],
230
+ options: { tag: { type: 'string', short: 't', multiple: true }, label: { type: 'string', multiple: true }, 'oci-root': { type: 'string' }, platform: { type: 'string' }, 'include-hidden': { type: 'boolean' }, 'max-bytes': { type: 'string' } },
231
+ async run(v, pos) {
232
+ requireArgs(pos, 1, 1, 'a bucket name');
233
+ const name = checkBucketName(pos[0]);
234
+ const tags = strs(v.tag);
235
+ if (tags.length === 0)
236
+ usage('snapshot requires -t <name[:tag]>');
237
+ validateImageTags(tags);
238
+ const labels = parseLabels(strs(v.label));
239
+ const { store, buckets } = await open();
240
+ const maxBytes = loadLimitOf(v);
241
+ await buckets.recover(name);
242
+ let tree = await store.withLock(() => buckets.loadTree(name, [], { maxBytes, locked: true })); // one consistent view: writers hold the lock
243
+ const hidden = tree.entries().map(([p]) => p).filter(isHiddenPath);
244
+ const list = () => hidden.slice(0, 3).join(', ') + (hidden.length > 3 ? `, … (${hidden.length} in all)` : '');
245
+ if (hidden.length > 0 && v['include-hidden']) {
246
+ process.stderr.write(`warning: the snapshot holds ${hidden.length === 1 ? 'a hidden file' : 'hidden files'} (${list()}); a bucket does not serve hidden files, but an image does\n`);
247
+ }
248
+ else if (hidden.length > 0) {
249
+ process.stderr.write(`warning: left out ${hidden.length} hidden ${hidden.length === 1 ? 'file' : 'files'} (${list()}); --include-hidden puts ${hidden.length === 1 ? 'it' : 'them'} in the image, which serves every file it holds\n`);
250
+ const drop = new Set(hidden);
251
+ tree = Tree.fromFiles(tree.entries().filter(([p]) => !drop.has(p)));
252
+ }
253
+ const { id } = await store.addImage(tree, {
254
+ root: str(v['oci-root']),
255
+ platform: str(v.platform),
256
+ epoch: sourceDateEpoch(),
257
+ title: name,
258
+ ...(strs(v.label).length > 0 ? { labels } : {}),
259
+ });
260
+ for (const t of tags) {
261
+ const key = await store.tag(id, parseLocalRef(t));
262
+ process.stdout.write(`Tagged ${key} ${shortId(id)} (${tree.size} file${tree.size === 1 ? '' : 's'})\n`);
263
+ }
264
+ return 0;
265
+ },
266
+ };
267
+ const restore = {
268
+ name: 'bucket restore',
269
+ summary: 'write an image\'s files into a bucket',
270
+ usage: 'bucket restore <ref|id> <name> [--overwrite] [--delete] [--batch] [--max-bytes n]',
271
+ description: 'Write the files of an image of the store into the bucket (created when it does not exist). A file that would\nreplace different content stops the restore before anything is written, unless --overwrite. With --delete the files\nthe image does not have are removed too, so the bucket then holds exactly the image. With --batch the change is\nbuilt beside the bucket and swapped in with one rename, so a reader sees all of it or none.',
272
+ flags: ['--overwrite replace files that hold different content', '--delete remove files the image does not have', '--batch make the change visible all at once', '--max-bytes <n> most bytes the image may hold (default 2147483648)'],
273
+ options: { overwrite: { type: 'boolean' }, delete: { type: 'boolean' }, batch: { type: 'boolean' }, 'max-bytes': { type: 'string' } },
274
+ async run(v, pos) {
275
+ requireArgs(pos, 2, 2, 'an image reference and a bucket name');
276
+ const name = checkBucketName(pos[1]);
277
+ const { store, buckets } = await open();
278
+ const id = await store.resolve(pos[0]);
279
+ const tree = await store.loadTree(id);
280
+ const limit = loadLimitOf(v);
281
+ const total = tree.entries().reduce((n, [, f]) => n + f.bytes.byteLength, 0);
282
+ if (total > limit)
283
+ throw new SitefileError('E_TOO_LARGE', `the image holds ${total} bytes, more than the limit of ${limit} (--max-bytes raises it)`);
284
+ const writes = [];
285
+ for (const [p, node] of tree.entries())
286
+ writes.push(['/' + checkBucketPath(p.slice(1)).join('/'), node]);
287
+ await buckets.recover(name);
288
+ try {
289
+ await buckets.realDir(name);
290
+ }
291
+ catch (e) {
292
+ if (!(e instanceof SitefileError) || e.code !== 'E_NOT_FOUND')
293
+ throw e;
294
+ await buckets.create(name);
295
+ process.stdout.write(`Created bucket ${name}\n`);
296
+ }
297
+ const r = await buckets.apply(name, { writes, deleteOthers: !!v.delete }, { overwrite: !!v.overwrite, batch: !!v.batch });
298
+ process.stdout.write(`Restored ${shortId(id)} into ${name}: ${r.written} written, ${r.unchanged} unchanged, ${r.removed} removed\n`);
299
+ return 0;
300
+ },
301
+ };
302
+ export const bucketSubcommands = new Map([
303
+ ['create', create],
304
+ ['ls', ls],
305
+ ['list', ls],
306
+ ['rm', rm],
307
+ ['put', put],
308
+ ['get', get],
309
+ ['snapshot', snapshot],
310
+ ['restore', restore],
311
+ ]);
312
+ //# sourceMappingURL=bucket.js.map
@@ -5,7 +5,7 @@ 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\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";
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\nBuckets (named, mutable file trees in the store; serve one with 'sitefile serve bucket:<name>'):\n sitefile bucket create|ls|rm <name> create, list or remove buckets\n sitefile bucket put <name>/<path> [file|dir|-] put a file (stdin by default) or a directory\n sitefile bucket get <name>/<path> [-o file] write a file to stdout or a file\n sitefile bucket ls <name>[/prefix] list the files under a prefix\n sitefile bucket rm <name>/<path> [-r] remove a file or directory\n sitefile bucket snapshot <name> -t <name:tag> write an image from the bucket's files\n sitefile bucket restore <ref> <name> write an image's files into a bucket\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|bucket:name>\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
11
  /**
@@ -1,5 +1,6 @@
1
1
  import { runCommand, usageError } from './common.js';
2
2
  import { imageCommands, imageSubcommands } from './images.js';
3
+ import { bucketSubcommands } from './bucket.js';
3
4
  import { registryCommands } from './registry.js';
4
5
  import { serverCommands, serverSubcommands } from './servers.js';
5
6
  import { cacheSubcommands } from './cache.js';
@@ -15,7 +16,7 @@ import { integrityCommands } from './integrity.js';
15
16
  * parser: each has its own options and `--help`.
16
17
  */
17
18
  const TOP = new Map([...imageCommands, ...serverCommands, ...registryCommands, ...vendorCommands, ...outdatedCommands, ...hostsCommands, ...bakeCommands, ...integrityCommands, ...upCommands, ...importConfigCommands].filter(([k]) => !k.includes(' ')));
18
- export const EXTRA_COMMANDS = [...TOP.keys(), 'image', 'server', 'cache', 'lsp'];
19
+ export const EXTRA_COMMANDS = [...TOP.keys(), 'image', 'server', 'cache', 'bucket', 'lsp'];
19
20
  /**
20
21
  * The language server exists only in the Rust implementation (a tooling
21
22
  * exception, docs/RUST.md): the language is the same in both, the server is
@@ -35,6 +36,15 @@ Images (local store: $SITEFILE_HOME or ~/.sitefile):
35
36
  sitefile push <registry/name[:tag]> push a (tagged) image to an OCI registry
36
37
  sitefile pull <[registry/]name[:tag][@digest]> pull an image (a bare name means Docker Hub)
37
38
 
39
+ Buckets (named, mutable file trees in the store; serve one with 'sitefile serve bucket:<name>'):
40
+ sitefile bucket create|ls|rm <name> create, list or remove buckets
41
+ sitefile bucket put <name>/<path> [file|dir|-] put a file (stdin by default) or a directory
42
+ sitefile bucket get <name>/<path> [-o file] write a file to stdout or a file
43
+ sitefile bucket ls <name>[/prefix] list the files under a prefix
44
+ sitefile bucket rm <name>/<path> [-r] remove a file or directory
45
+ sitefile bucket snapshot <name> -t <name:tag> write an image from the bucket's files
46
+ sitefile bucket restore <ref> <name> write an image's files into a bucket
47
+
38
48
  Integrity:
39
49
  sitefile build [context] --manifest m.json also write a manifest: every file's size and SHA-256,
40
50
  and their Merkle root (save --manifest too)
@@ -72,7 +82,7 @@ Build cache (TRANSFORM results: $SITEFILE_HOME/cache/transform):
72
82
  Evictable data over $SITEFILE_CACHE_MAX (default 1GiB, 0 = no limit) is deleted after each build.
73
83
 
74
84
  Serving sites (detached servers are tracked by name):
75
- sitefile serve [--name n] [-p [host:]port] [-d] [--spa] <ref|./dir|file>
85
+ sitefile serve [--name n] [-p [host:]port] [-d] [--spa] <ref|./dir|file|bucket:name>
76
86
  sitefile serve --watch [-p [host:]port] [ctx] build in memory, serve, rebuild + live reload
77
87
  sitefile servers [-a] [--json] list servers (alias: server ls)
78
88
  sitefile server stop|rm [-f]|restart|logs [-f] <name|id>
@@ -90,6 +100,7 @@ export function isExtraCommand(name) {
90
100
  }
91
101
  const GROUPS = new Map([
92
102
  ['image', { subs: imageSubcommands, usage: 'image <ls|inspect|tag|rm|save|prune|diff>' }],
103
+ ['bucket', { subs: bucketSubcommands, usage: 'bucket <create|ls|rm|put|get|snapshot|restore>' }],
93
104
  ['server', { subs: serverSubcommands, usage: 'server <ls|stop|rm|logs|restart>' }],
94
105
  ['cache', { subs: cacheSubcommands, usage: 'cache <info|prune|du>' }],
95
106
  ]);
@@ -13,6 +13,7 @@ import { BasicAuth, parseHtpasswd } from '../serve-auth.js';
13
13
  import { BUILDING_EVENT, closeServer, createSiteServer, errorEvent, formatUrl, jsonLogLine, listen, LiveReload, OK_EVENT, parseCidr, parseThrottle, reloadEventFor, startedLogLine, stoppedLogLine, routingFor } from '../server.js';
14
14
  import { loadServedTree, servedLastModified, ServerRegistry, loadServedSite, checkSiteFiles } from '../servers.js';
15
15
  import { Tree } from '../tree.js';
16
+ import { followBucket } from '../bucket-follow.js';
16
17
  import { isIgnoredChange, RebuildScheduler, resolveReal, watchPaths } from '../watch.js';
17
18
  let json = false; // `--log-format json`: every line is a JSON object
18
19
  const stamp = (m) => {
@@ -34,8 +35,9 @@ async function main() {
34
35
  const loopback = state.bind.host === 'localhost' || state.bind.host === '::1' || /^127\./.test(state.bind.host);
35
36
  // `-d --watch` on a build context (#306): built in memory by watchLoop below, served from an empty
36
37
  // tree until the first build finishes.
38
+ const bucketCache = new Map(); // a bucket server's files read so far (reloads read only what changed)
37
39
  const building = !!state.watch && state.source.kind === 'dir' && state.build !== undefined;
38
- const { tree, content } = building ? { tree: Tree.empty, content: undefined } : await loadServedSite(reg.store, state.source, { keepOsMetadata: !!state.keepOsMetadata, warn: (m) => stamp(`warning: ${m}`) });
40
+ const { tree, content } = building ? { tree: Tree.empty, content: undefined } : await loadServedSite(reg.store, state.source, { keepOsMetadata: !!state.keepOsMetadata, warn: (m) => stamp(`warning: ${m}`), bucketCache });
39
41
  if (!building && routingFor(state)?.siteFiles !== false)
40
42
  checkSiteFiles(tree, !!state.strictSiteFiles, (m) => stamp(`warning: ${m}`), content);
41
43
  let modified = building ? undefined : await servedLastModified(reg.store, state.source);
@@ -49,10 +51,14 @@ async function main() {
49
51
  const live = watching || state.reload !== undefined ? new LiveReload(liveOptionsOf(state)) : undefined;
50
52
  const authEntries = [...(state.auth ?? []), ...(state.authFile !== undefined ? parseHtpasswd(await readFile(state.authFile, 'utf8'), state.authFile) : [])];
51
53
  const server = createSiteServer(() => current, { ...(live ? { liveReload: live, warn: (m) => stamp(`warning: ${m}`) } : {}), spa: state.spa, allowedHosts: state.allowedHosts ?? [], cors: !!state.cors, ...(state.isolate ? { isolate: state.isolate } : {}), ...(state.cache ? { cache: state.cache } : {}), ...(json ? { logFormat: 'json' } : {}), logIp: !!state.logIp, quiet: !!state.quiet, ...(authEntries.length > 0 || state.authFile !== undefined ? { auth: new BasicAuth(authEntries) } : {}), ...(state.maxConnectionsPerIp ? { maxConnectionsPerIp: state.maxConnectionsPerIp } : {}), ...(state.hideBase ? { hideBase: true } : {}), ...(ipRules ? { ipRules } : {}), ...(loopback ? {} : { noindex: true }), clientInfo: true, compress: !!state.compress, ...(state.mime ? { mime: new Map(Object.entries(state.mime)) } : {}), ...(state.throttle !== undefined && parseThrottle(state.throttle) ? { throttle: parseThrottle(state.throttle) } : {}), ...(state.tlsCert !== undefined && state.tlsKey !== undefined ? { tls: { cert: await readFile(state.tlsCert), key: await readFile(state.tlsKey) } } : {}), serverId: id, lastModified: () => modified, log: stamp, ...(content ? { content } : {}), ...(state.country !== undefined ? { country: state.country } : {}), ...(state.spaExclude ? { spaExclude: state.spaExclude } : {}), ...(state.spaFallback !== undefined ? { spaFallback: state.spaFallback } : {}), ...(building ? { base: () => base, rewriteBase: () => rewriteBase } : { ...(state.base !== undefined ? { base: state.base } : {}), ...(state.rewriteBase !== undefined ? { rewriteBase: state.rewriteBase } : {}) }), ...(routingFor(state) ? { profile: routingFor(state) } : {}) });
52
- const addr = await listen(server, state.bind.host, state.bind.port);
53
- await reg.update(id, { pid: process.pid, host: addr.host, port: addr.port, ready: true, error: undefined });
54
- const root = formatUrl(addr.host, addr.port, state.tlsCert !== undefined ? 'https' : 'http');
55
- const served = () => {
54
+ /**
55
+ * Bind, record the address and report ready. A build context (#354) does this only after its first build
56
+ * has finished, so no request is answered from the empty tree and `serve -d` returns when the site is there.
57
+ */
58
+ const up = async () => {
59
+ const addr = await listen(server, state.bind.host, state.bind.port);
60
+ await reg.update(id, { pid: process.pid, host: addr.host, port: addr.port, ready: true, error: undefined });
61
+ const root = formatUrl(addr.host, addr.port, state.tlsCert !== undefined ? 'https' : 'http');
56
62
  const url = `${root}${(base ?? '/').slice(1)}`;
57
63
  if (json)
58
64
  stamp(startedLogLine(new Date().toISOString(), state.image, current.size, url));
@@ -60,8 +66,8 @@ async function main() {
60
66
  stamp(`serving ${state.image} (${current.size} files) at ${url}`);
61
67
  };
62
68
  if (!building)
63
- served();
64
- const unwatch = live && building
69
+ await up();
70
+ const unwatchSource = live && building
65
71
  ? watchBuild(state, live, stamp, {
66
72
  current: () => current,
67
73
  swap: (next) => {
@@ -74,7 +80,10 @@ async function main() {
74
80
  if (state.rewriteBase === undefined && !state.build?.noRewriteBase)
75
81
  rewriteBase = rb;
76
82
  },
77
- started: served,
83
+ started: up,
84
+ failed: (message) => {
85
+ void reg.update(id, { pid: 0, ready: false, error: message }).catch(() => undefined).then(() => process.exit(1));
86
+ },
78
87
  })
79
88
  : live && watching
80
89
  ? await watchDirectory(reg, state, live, stamp, (next, lastModified) => {
@@ -82,6 +91,31 @@ async function main() {
82
91
  modified = lastModified;
83
92
  }, () => current)
84
93
  : () => undefined;
94
+ // A bucket is followed on its own (a request after a change sees the new files within a second); with
95
+ // `--reload` the open pages reload as well.
96
+ const source = state.source;
97
+ const unfollow = source.kind === 'bucket'
98
+ ? followBucket(reg.store, source, {
99
+ reload: async () => {
100
+ const next = await loadServedTree(reg.store, source, { keepOsMetadata: !!state.keepOsMetadata, warn: (m) => stamp(`warning: ${m}`), bucketCache });
101
+ if (next.digest() === current.digest())
102
+ return;
103
+ if (routingFor(state)?.siteFiles !== false)
104
+ checkSiteFiles(next, !!state.strictSiteFiles, (m) => stamp(`warning: ${m}`));
105
+ const event = live ? (reloadEventFor(current, next, !state.noCssInject, !!state.navigateToChanged) ?? OK_EVENT) : undefined;
106
+ current = next;
107
+ modified = await servedLastModified(reg.store, source);
108
+ if (event !== undefined)
109
+ live?.send(event);
110
+ stamp(`Re-read ${state.image} (${next.size} files)`);
111
+ },
112
+ onError: (e) => stamp(`warning: ${e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : e.message}; serving the last good copy`),
113
+ })
114
+ : undefined;
115
+ const unwatch = () => {
116
+ unwatchSource();
117
+ unfollow?.();
118
+ };
85
119
  const stop = (signal) => () => {
86
120
  unwatch();
87
121
  if (json)
@@ -189,17 +223,35 @@ function watchBuild(state, live, stamp, site) {
189
223
  return { code: 1 };
190
224
  }
191
225
  };
226
+ let listening = false;
192
227
  void watchLoop({
193
228
  context,
194
229
  ...(b.sitefile !== undefined ? { sitefile: b.sitefile } : {}),
195
230
  argFiles: b.buildArgFiles ?? [],
196
231
  ...(state.pollMs !== undefined ? { pollMs: state.pollMs } : {}),
197
232
  build: run,
198
- onStarted: async () => site.started(),
233
+ onStarted: async () => {
234
+ try {
235
+ await site.started();
236
+ }
237
+ catch (e) {
238
+ site.failed(e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : `error: ${e.message}`);
239
+ throw e;
240
+ }
241
+ listening = true;
242
+ },
199
243
  stop: stopped,
200
244
  say: (line) => stamp(line.replace(/\n$/, '')),
201
- }).catch((e) => {
202
- stamp(e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : `error: ${e.message}`);
245
+ })
246
+ .then(() => {
247
+ if (!listening)
248
+ site.failed('the first build did not finish');
249
+ })
250
+ .catch((e) => {
251
+ const message = e instanceof SitefileError ? `error[${e.code}]: ${e.message}` : `error: ${e.message}`;
252
+ stamp(message);
253
+ if (!listening)
254
+ site.failed(message);
203
255
  });
204
256
  return stop;
205
257
  }