@muhkoo/cli 0.10.11-alpha.0 → 0.12.0-alpha.0

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.
@@ -0,0 +1,425 @@
1
+ /**
2
+ * `muhkoo vfs` — your Muhkoo filesystem from the terminal.
3
+ *
4
+ * Drives `client.vfs` through the SDK, the same code the IDE runs. The
5
+ * directory records are encrypted with keys chained parent-to-child, so a
6
+ * separate HTTP implementation here would be a second copy of that format to
7
+ * keep byte-exact — and the first one to drift would corrupt real files.
8
+ */
9
+
10
+ import { readFile, writeFile } from "node:fs/promises";
11
+ import { basename, resolve } from "node:path";
12
+ import { openClient, explainWriteFailure } from "../lib/vfs.js";
13
+ import { mount as mountDir, importOnce } from "../lib/mount.js";
14
+ import { draftIgnores } from "../lib/ignore.js";
15
+ import { loadConfig, saveConfig } from "../lib/config.js";
16
+ import { table, json, ok, info, warn, die } from "../lib/ui.js";
17
+
18
+ export const help = `muhkoo vfs — your encrypted filesystem
19
+
20
+ Usage:
21
+ muhkoo vfs cd <path> change directory (remembered)
22
+ muhkoo vfs pwd print the working directory
23
+ muhkoo vfs ls [path] [--json] list a directory
24
+ muhkoo vfs stat <path> size, versions, modified
25
+ muhkoo vfs tree [path] every file beneath a path
26
+ muhkoo vfs cat <path> print a file
27
+ muhkoo vfs put <local> <path> upload a file
28
+ muhkoo vfs get <path> [local] download a file
29
+ muhkoo vfs mkdir <path> create a directory
30
+ muhkoo vfs rm <path> [-r] delete a file or directory
31
+ muhkoo vfs cp <from> <to> copy (a file copy moves no bytes)
32
+ muhkoo vfs mv <from> <to> move or rename
33
+ muhkoo vfs find <glob> e.g. '/apps/**/*.ts'
34
+ muhkoo vfs history <path> prior versions, newest first
35
+ muhkoo vfs restore <path> [index] restore a version (default 0)
36
+ muhkoo vfs ignore [dir] [--write] draft a .vcsignore from the Node
37
+ defaults + the project's .gitignore
38
+ muhkoo vfs import <dir…> [--path <p>] upload whole projects (once, then stop)
39
+ muhkoo vfs mount <dir> [--path <p>] sync a subtree to disk and keep it live
40
+ (dot-files skipped; deletes need --allow-delete)
41
+ muhkoo vfs sweep [--force] reclaim orphaned records
42
+ muhkoo vfs use-app <domain> use an app, by the domain you use it at
43
+ muhkoo vfs app show which app you are writing as
44
+
45
+ What gets synced is decided by .vcsignore, or .gitignore if there is none, or
46
+ built-in Node defaults if there is neither. \`muhkoo vfs ignore\` drafts one.
47
+
48
+ Reading your files is free. WRITING stores bytes, which are metered to an
49
+ app — so put, rm, cp, mv and restore need an app signed in first.
50
+
51
+ Options:
52
+ --app <name> write as this app for one command
53
+ --key <k> supply the app key yourself (apps that publish their public
54
+ config at /.well-known/muhkoo.json need no key)
55
+ --allow-delete propagate local deletions. OFF by default: a delete removes
56
+ the file's history too, so unlike an overwrite it cannot be undone
57
+ --hidden also sync dot-files and dot-directories
58
+ --dry-run (import) list what would be uploaded, and the total size,
59
+ without writing anything
60
+ --no-pair unlock for this command only; pair nothing to this machine`;
61
+
62
+ export default async function vfs(args) {
63
+ const sub = args._[1];
64
+ if (sub === undefined) return die("Missing subcommand. See `muhkoo vfs --help`.");
65
+
66
+ // Purely local subcommands run BEFORE the client exists. Unlocking the vault
67
+ // to write a file on this disk is both pointless and expensive: each unlock
68
+ // is a vault read, and a loop over a dozen projects trips the auth rate
69
+ // limiter long before it finishes.
70
+ if (sub === "ignore") return writeIgnores(args);
71
+
72
+ const client = await openClient(args);
73
+ const fs = client.vfs;
74
+ const a = (n, dflt) => args._[n] ?? dflt;
75
+
76
+ try {
77
+ return await run();
78
+ } catch (err) {
79
+ const cfg = await loadConfig();
80
+ const explained = explainWriteFailure(err, cfg);
81
+ if (explained !== (err?.message ?? String(err))) die(explained);
82
+ throw err;
83
+ }
84
+
85
+ async function run() {
86
+ switch (sub) {
87
+ case "cd": {
88
+ const target = await fs.cd(a(2, "/"));
89
+ const current = await loadConfig();
90
+ await saveConfig({ ...current, vfsCwd: target });
91
+ return ok(target);
92
+ }
93
+
94
+ case "pwd":
95
+ return info(fs.cwd);
96
+
97
+ case "stat": {
98
+ const st = await fs.stat(required(a(2), "stat <path>"));
99
+ if (args.json) return json(st);
100
+ return table(
101
+ ["PATH", "TYPE", "SIZE", "VERSIONS", "MODIFIED"],
102
+ [[st.path, st.kind, st.kind === "dir" ? "-" : humanSize(st.size), String(st.versions), new Date(st.mtime).toISOString().replace("T", " ").slice(0, 19)]],
103
+ );
104
+ }
105
+
106
+ case "ls": {
107
+ const path = a(2, ".");
108
+ const entries = await fs.list(path);
109
+ if (args.json) return json(entries);
110
+ if (!entries.length) return info(`${path} is empty.`);
111
+ return table(
112
+ ["TYPE", "SIZE", "VERSIONS", "MODIFIED", "NAME"],
113
+ entries.map((e) => [
114
+ e.kind === "dir" ? "dir" : "file",
115
+ e.kind === "dir" ? "-" : humanSize(e.size),
116
+ e.versions ? String(e.versions) : "-",
117
+ new Date(e.mtime).toISOString().slice(0, 16).replace("T", " "),
118
+ e.kind === "dir" ? `${e.name}/` : e.name,
119
+ ]),
120
+ );
121
+ }
122
+
123
+ case "tree": {
124
+ const paths = await fs.walk(a(2, "."));
125
+ if (args.json) return json(paths);
126
+ return paths.forEach((p) => info(p));
127
+ }
128
+
129
+ case "cat": {
130
+ const path = required(a(2), "cat <path>");
131
+ process.stdout.write(await fs.readText(path));
132
+ return;
133
+ }
134
+
135
+ case "put": {
136
+ const local = required(a(2), "put <local> <path>");
137
+ const bytes = await readLocal(local);
138
+ // Default the destination to the file's own name, so `put ./a.txt` in a
139
+ // directory does the obvious thing.
140
+ const path = a(3) ?? `/${basename(local)}`;
141
+ const stat = await fs.writeFile(path, bytes);
142
+ return ok(`Wrote ${path} (${humanSize(stat.size)})`);
143
+ }
144
+
145
+ case "get": {
146
+ const path = required(a(2), "get <path> [local]");
147
+ const bytes = await fs.readFile(path);
148
+ const dest = a(3) ?? basename(path);
149
+ await writeFile(dest, bytes).catch((err) =>
150
+ die(`Could not write ${dest}: ${err.code === "EACCES" ? "permission denied" : err.message}`),
151
+ );
152
+ return ok(`Saved ${dest} (${humanSize(bytes.length)})`);
153
+ }
154
+
155
+ case "mkdir":
156
+ await fs.mkdir(required(a(2), "mkdir <path>"), { recursive: true });
157
+ return ok(`Created ${a(2)}`);
158
+
159
+ case "rm": {
160
+ // `-r` arrives as a POSITIONAL: the shared parser only understands
161
+ // `--flags`. Filter it out before reading the path, so `rm -r <path>` and
162
+ // `rm <path> -r` both work and neither tries to delete a file named "-r".
163
+ const recursive = args._.includes("-r") || Boolean(args.r || args.recursive);
164
+ const path = required(args._.filter((t) => t !== "-r")[2], "rm <path> [-r]");
165
+ await fs.delete(path, { recursive });
166
+ return ok(`Deleted ${path}`);
167
+ }
168
+
169
+ case "cp": {
170
+ const [from, to] = pair(args, "cp <from> <to>");
171
+ await fs.copy(from, to);
172
+ return ok(`Copied ${from} → ${to}`);
173
+ }
174
+
175
+ case "mv": {
176
+ const [from, to] = pair(args, "mv <from> <to>");
177
+ await fs.rename(from, to);
178
+ return ok(`Moved ${from} → ${to}`);
179
+ }
180
+
181
+ case "find": {
182
+ const matches = await fs.glob(required(a(2), "find <glob>"));
183
+ if (args.json) return json(matches);
184
+ if (!matches.length) return info("No matches.");
185
+ return matches.forEach((p) => info(p));
186
+ }
187
+
188
+ case "history": {
189
+ const versions = await fs.history(required(a(2), "history <path>"));
190
+ if (args.json) return json(versions);
191
+ if (!versions.length) return info("No prior versions — this file has been written once.");
192
+ return table(
193
+ ["#", "SIZE", "SAVED"],
194
+ versions.map((v, i) => [String(i), humanSize(v.size), new Date(v.mtime).toISOString().replace("T", " ").slice(0, 19)]),
195
+ );
196
+ }
197
+
198
+ case "restore": {
199
+ const path = required(a(2), "restore <path> [index]");
200
+ const index = Number(a(3, "0"));
201
+ const stat = await fs.restore(path, index);
202
+ return ok(`Restored ${path} to version ${index} (${humanSize(stat.size)})`);
203
+ }
204
+
205
+ case "use-app": {
206
+ const slug = args._[2];
207
+ if (!slug) die("Missing app. Usage: muhkoo vfs use-app <slug> [--key <appKey>]");
208
+ const saved = await useApp(slug, args.key);
209
+ return ok(
210
+ `Writing as "${saved.slug}". Reads never needed this; writes are now metered to that app.`,
211
+ );
212
+ }
213
+
214
+ case "app": {
215
+ const current = await loadConfig();
216
+ const slug = current.vfsApp;
217
+ if (args.json) return json({ app: slug ?? null, known: Object.keys(current.vfsApps ?? {}) });
218
+ if (!slug) {
219
+ return info(
220
+ "Not writing as any app — reads work, writes will not.\n" +
221
+ "Sign one in with: muhkoo vfs use-app <slug> --key <appKey>",
222
+ );
223
+ }
224
+ return info(`Writing as "${slug}".`);
225
+ }
226
+
227
+ case "import":
228
+ case "push": {
229
+ const dirs = args._.slice(2);
230
+ if (!dirs.length) return die("Usage: muhkoo vfs import <dir…> [--path /apps/<slug>]");
231
+ // `--path` names ONE destination, so it cannot mean anything sensible for
232
+ // several directories at once.
233
+ if (dirs.length > 1 && args.path) {
234
+ return die("--path takes a single directory. Without it each one goes to /apps/<its name>.");
235
+ }
236
+
237
+ // Several directories in ONE process, on purpose: every invocation of the
238
+ // CLI unlocks the vault, and a shell loop over a dozen projects trips the
239
+ // auth rate limiter before it finishes.
240
+ const opts = {
241
+ hidden: Boolean(args.hidden),
242
+ allowDelete: Boolean(args["allow-delete"]),
243
+ dryRun: Boolean(args["dry-run"]),
244
+ };
245
+ for (const d of dirs) {
246
+ const root = normalizeRoot(args.path ?? `/apps/${await slugFor(resolve(d))}`);
247
+ try {
248
+ await importOnce({ client, dir: resolve(d), root, opts });
249
+ } catch (err) {
250
+ // One unreadable project must not abandon the other twelve.
251
+ warn(`${d}: ${err?.message ?? err}`);
252
+ }
253
+ }
254
+ return;
255
+ }
256
+
257
+ case "mount": {
258
+ const dir = required(a(2), "mount <dir> [--path /apps]");
259
+ const root = normalizeRoot(args.path ?? "/");
260
+ // Ctrl-C is the way out of a foreground watcher, so it has to be a clean
261
+ // stop that flushes state — not a process kill mid-write.
262
+ const controller = new AbortController();
263
+ const stop = () => controller.abort();
264
+ process.on("SIGINT", stop);
265
+ process.on("SIGTERM", stop);
266
+ await mountDir({
267
+ client, dir: resolve(dir), root, signal: controller.signal,
268
+ opts: { allowDelete: Boolean(args["allow-delete"]), hidden: Boolean(args.hidden) },
269
+ });
270
+ return ok("Unmounted.");
271
+ }
272
+
273
+ case "sweep": {
274
+ const { removed } = await fs.sweep({ force: Boolean(args.force) });
275
+ if (args.json) return json(removed);
276
+ return removed.length
277
+ ? ok(`Reclaimed ${removed.length} orphaned record${removed.length === 1 ? "" : "s"}.`)
278
+ : info("Nothing to reclaim — the filesystem is tidy.");
279
+ }
280
+
281
+ default:
282
+ return die(`Unknown subcommand "vfs ${sub}". See \`muhkoo vfs --help\`.`);
283
+ }
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Draft or write a `.vcsignore`. Local only — no session, no network.
289
+ */
290
+ async function writeIgnores(args) {
291
+ const dir = resolve(args._[2] ?? ".");
292
+ const target = `${dir}/.vcsignore`;
293
+ const existing = await readFile(target, "utf8").catch(() => null);
294
+ if (existing && !args.force) {
295
+ return die(`${target} already exists. Pass --force to replace it.`);
296
+ }
297
+ const draft = draftIgnores(await readFile(`${dir}/.gitignore`, "utf8").catch(() => ""));
298
+ if (!args.write) {
299
+ process.stdout.write(draft);
300
+ return info(`\n(nothing written — pass --write to save this to ${target})`);
301
+ }
302
+ await writeFile(target, draft);
303
+ return ok(`Wrote ${target}`);
304
+ }
305
+
306
+ /**
307
+ * Where a project belongs in the filesystem.
308
+ *
309
+ * The app's own slug when the directory declares one, because that is the name
310
+ * everything else addresses it by: the portal opens the IDE at `?app=<slug>`,
311
+ * and the IDE reads `/apps/<slug>`. A project imported under its DIRECTORY name
312
+ * is invisible to both whenever the two differ — which they do for half of these
313
+ * (`portfolio` is `mattgagliardo`, `theater` is `muhkoo-theater`).
314
+ *
315
+ * Falls back to the directory name, which is right for a project that is not
316
+ * deployed anywhere yet.
317
+ */
318
+ async function slugFor(dir) {
319
+ const declared = await readFile(`${dir}/.muhkoo-app.json`, "utf8")
320
+ .then((raw) => JSON.parse(raw).slug)
321
+ .catch(() => null);
322
+ return declared || basename(dir);
323
+ }
324
+
325
+ function required(value, usage) {
326
+ if (!value) die(`Missing argument. Usage: muhkoo vfs ${usage}`);
327
+ return value;
328
+ }
329
+
330
+ function pair(args, usage) {
331
+ const from = args._[2];
332
+ const to = args._[3];
333
+ if (!from || !to) die(`Missing argument. Usage: muhkoo vfs ${usage}`);
334
+ return [from, to];
335
+ }
336
+
337
+ function humanSize(bytes) {
338
+ if (bytes < 1024) return `${bytes} B`;
339
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
340
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
341
+ }
342
+
343
+ /**
344
+ * Point the CLI at an app, by the domain you use it at.
345
+ *
346
+ * A domain is how a USER knows an app — not a slug, and certainly not a key —
347
+ * and this is meant to work for anyone who uses an app, not only whoever built
348
+ * it. So the app publishes its own public config and we read it from there.
349
+ *
350
+ * It has to come from the app rather than the platform: key plaintexts are
351
+ * never stored server-side (only `keyHashPrefix`), so no API can answer "what
352
+ * is the key for this domain". A publishable key is public by design — it ships
353
+ * in the app's own bundle — so the app serving it at a well-known path gives
354
+ * away nothing that loading the app in a browser does not.
355
+ *
356
+ * A bare slug still works for an app you own and have a key for.
357
+ */
358
+ async function useApp(nameOrDomain, key) {
359
+ const cfg = await loadConfig();
360
+ const known = cfg.vfsApps ?? {};
361
+ const looksLikeDomain = nameOrDomain.includes(".");
362
+
363
+ if (!key && !known[nameOrDomain] && looksLikeDomain) {
364
+ key = await fetchPublicKey(nameOrDomain);
365
+ }
366
+
367
+ if (!key && !known[nameOrDomain]) {
368
+ die(
369
+ `Could not work out the app key for "${nameOrDomain}".\n` +
370
+ (looksLikeDomain
371
+ ? `That app does not publish ${WELL_KNOWN} yet. Pass it once with --key <appKey>.`
372
+ : `Pass it once with --key <appKey>, or use the domain you access the app at.\n` +
373
+ `App keys are shown when an app is created (muhkoo apps create).`),
374
+ );
375
+ }
376
+ const next = key ? { ...known, [nameOrDomain]: key } : known;
377
+ await saveConfig({ ...cfg, vfsApps: next, vfsApp: nameOrDomain });
378
+ return { slug: nameOrDomain, key: next[nameOrDomain] };
379
+ }
380
+
381
+ const WELL_KNOWN = "/.well-known/muhkoo.json";
382
+
383
+ /** Read an app's published public config. Returns the key, or null. */
384
+ async function fetchPublicKey(domain) {
385
+ const host = domain.replace(/^https?:\/\//, "").replace(/\/.*$/, "");
386
+ const url = `https://${host}${WELL_KNOWN}`;
387
+ try {
388
+ const res = await fetch(url);
389
+ if (!res.ok) return null;
390
+ const body = await res.json();
391
+ const key = body?.publishableKey ?? body?.key;
392
+ // Only ever accept a PUBLISHABLE key from a public document. A site that
393
+ // served a secret key here would be leaking it, and storing it because it
394
+ // was offered would make us complicit in that.
395
+ if (typeof key !== "string" || !/_pk_/.test(key)) return null;
396
+ info(`Read ${host}'s public config (app ${body?.slug ?? body?.appId ?? "?"}).`);
397
+ return key;
398
+ } catch {
399
+ return null;
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Read a local file for upload.
405
+ *
406
+ * A missing file is the most likely thing to go wrong here and it is entirely
407
+ * mundane — a typo, or the wrong directory. A Node stack trace for that is
408
+ * noise that buries the one fact that matters: which path was not found.
409
+ */
410
+ async function readLocal(path) {
411
+ try {
412
+ return new Uint8Array(await readFile(path));
413
+ } catch (err) {
414
+ if (err.code === "ENOENT") die(`No such file: ${resolve(path)}`);
415
+ if (err.code === "EISDIR") die(`${path} is a directory — put takes a single file.`);
416
+ if (err.code === "EACCES") die(`Cannot read ${path}: permission denied.`);
417
+ throw err;
418
+ }
419
+ }
420
+
421
+ /** A mount root is always an absolute directory path, with no trailing slash. */
422
+ function normalizeRoot(path) {
423
+ const p = ("/" + path).replace(/\/+/g, "/").replace(/\/$/, "");
424
+ return p === "" ? "/" : p;
425
+ }
package/src/index.js CHANGED
@@ -20,6 +20,9 @@ const COMMANDS = {
20
20
  provision: () => import("./commands/provision.js"),
21
21
  deploy: () => import("./commands/deploy.js"),
22
22
  promote: () => import("./commands/promote.js"),
23
+ vfs: () => import("./commands/vfs.js"),
24
+ vcs: () => import("./commands/vcs.js"),
25
+ devices: () => import("./commands/devices.js"),
23
26
  hosting: () => import("./commands/hosting.js"),
24
27
  domains: () => import("./commands/domains.js"),
25
28
  tables: () => import("./commands/tables.js"),
@@ -37,6 +40,7 @@ Usage:
37
40
  Account
38
41
  login sign in as a developer (stores a session token)
39
42
  logout clear the stored session
43
+ devices ls|rm machines paired to your account
40
44
  whoami show the signed-in developer
41
45
 
42
46
  Apps
@@ -50,6 +54,11 @@ Backend
50
54
  agents ls|get|rm|enable|disable|models
51
55
  functions ls|get|code|deploy|rm|enable|disable
52
56
 
57
+ Files
58
+ vfs ls|cat|put|get|rm|cp|mv|find|history|restore
59
+ vcs status|commit|log|diff|branch|switch|merge
60
+ your encrypted filesystem
61
+
53
62
  Hosting
54
63
  deploy deploy a built client to Muhkoo hosting (test env)
55
64
  promote promote an app's test hosting → production
package/src/lib/auth.js CHANGED
@@ -14,7 +14,7 @@ import { die, step } from "./ui.js";
14
14
  * Download the ZK login circuit assets (wasm + zkey) to a temp dir and return
15
15
  * local file paths — in Node the prover reads them off disk, not over HTTP.
16
16
  */
17
- async function downloadCircuits(baseUrl) {
17
+ export async function downloadCircuits(baseUrl) {
18
18
  const dir = await mkdtemp(join(tmpdir(), "muhkoo-circuits-"));
19
19
  const fetchTo = async (path, file) => {
20
20
  const res = await fetch(baseUrl + path);
@@ -31,7 +31,7 @@ async function downloadCircuits(baseUrl) {
31
31
  }
32
32
 
33
33
  /** Resolve `@muhkoo/connect`'s `Client` from the CLI's own dependencies. */
34
- async function loadClient() {
34
+ export async function loadClient() {
35
35
  try {
36
36
  const mod = await import("@muhkoo/connect");
37
37
  if (!mod.Client) throw new Error("Client export missing");
@@ -0,0 +1,174 @@
1
+ /**
2
+ * `.vcsignore` — what not to sync.
3
+ *
4
+ * Same syntax as `.gitignore`, because that is the file everyone already knows
5
+ * how to write and every project already has one to crib from. A separate file
6
+ * rather than reading `.gitignore` directly: the two answer different questions.
7
+ * Git ignores build output because it is derivable; the filesystem also wants to
8
+ * skip things that ARE committed but are pointless to sync — lockfiles you never
9
+ * open, fixtures measured in megabytes.
10
+ *
11
+ * `.gitignore` is still used as a fallback when no `.vcsignore` exists, so a
12
+ * project that has not opted in gets sensible behaviour on day one.
13
+ */
14
+
15
+ /** What a Node project almost always wants ignored. */
16
+ export const NODE_DEFAULTS = `# Dependencies and build output — reinstallable, and large.
17
+ node_modules/
18
+ dist/
19
+ build/
20
+ out/
21
+ coverage/
22
+ .next/
23
+ .nuxt/
24
+ .svelte-kit/
25
+ .turbo/
26
+ .parcel-cache/
27
+ .vite/
28
+ *.tsbuildinfo
29
+
30
+ # Logs and local state
31
+ *.log
32
+ npm-debug.log*
33
+ yarn-debug.log*
34
+ yarn-error.log*
35
+ .DS_Store
36
+ .muhkoo/
37
+
38
+ # Secrets. These should never leave the machine by accident.
39
+ .env
40
+ .env.*
41
+ !.env.example
42
+ `;
43
+
44
+ /**
45
+ * Compile ignore rules into a matcher.
46
+ *
47
+ * Returns `(path, isDir) => boolean`, where `path` is slash-separated and
48
+ * relative to the directory the ignore file sits in, with no leading slash.
49
+ *
50
+ * Last match wins, which is what makes `!` negation work: `*.log` followed by
51
+ * `!keep.log` keeps that one file.
52
+ */
53
+ export function compileIgnores(text) {
54
+ const rules = [];
55
+ for (const raw of String(text ?? "").split(/\r?\n/)) {
56
+ const line = raw.trim();
57
+ if (!line || line.startsWith("#")) continue;
58
+
59
+ let pattern = line;
60
+ let negated = false;
61
+ if (pattern.startsWith("!")) {
62
+ negated = true;
63
+ pattern = pattern.slice(1);
64
+ }
65
+ // An escaped leading '#' or '!' is a literal.
66
+ if (pattern.startsWith("\\")) pattern = pattern.slice(1);
67
+
68
+ let dirOnly = false;
69
+ if (pattern.endsWith("/")) {
70
+ dirOnly = true;
71
+ pattern = pattern.slice(0, -1);
72
+ }
73
+ if (!pattern) continue;
74
+
75
+ // A pattern with a slash anywhere but the end is anchored to the root;
76
+ // a bare name matches at any depth. This is the rule that makes
77
+ // `node_modules/` catch nested copies while `/dist` catches only the
78
+ // top-level one.
79
+ const anchored = pattern.includes("/");
80
+ if (anchored && pattern.startsWith("/")) pattern = pattern.slice(1);
81
+
82
+ rules.push({ ...toRegExp(pattern, anchored), negated, dirOnly });
83
+ }
84
+
85
+ return (path, isDir = false) => {
86
+ let ignored = false;
87
+ for (const rule of rules) {
88
+ // A directory rule matches the directory itself only when the thing
89
+ // being tested IS one — but it always matches what lives beneath it.
90
+ // `node_modules/` has to catch `node_modules/react/index.js`, which
91
+ // is a file, or pruning would ignore the directory and sync its
92
+ // entire contents anyway.
93
+ const hit = rule.under.test(path) || ((isDir || !rule.dirOnly) && rule.self.test(path));
94
+ if (hit) ignored = !rule.negated;
95
+ }
96
+ return ignored;
97
+ };
98
+ }
99
+
100
+ /**
101
+ * Glob → RegExp, with gitignore's wildcard rules.
102
+ *
103
+ * `*` stops at a path separator, `**` crosses them, `?` is a single character
104
+ * that is not a separator. An unanchored pattern may start at any segment
105
+ * boundary, which is how `*.log` matches `src/deep/thing.log`.
106
+ */
107
+ function toRegExp(pattern, anchored) {
108
+ let out = "";
109
+ for (let i = 0; i < pattern.length; i++) {
110
+ const ch = pattern[i];
111
+ if (ch === "*") {
112
+ if (pattern[i + 1] === "*") {
113
+ // `**/` may match nothing at all, so `**/foo` also matches `foo`.
114
+ if (pattern[i + 2] === "/") { out += "(?:.*/)?"; i += 2; }
115
+ else { out += ".*"; i += 1; }
116
+ } else out += "[^/]*";
117
+ } else if (ch === "?") out += "[^/]";
118
+ else if (ch === "[") {
119
+ const close = pattern.indexOf("]", i + 1);
120
+ if (close === -1) out += "\\[";
121
+ else { out += pattern.slice(i, close + 1); i = close; }
122
+ } else out += ch.replace(/[.+^${}()|\\]/g, "\\$&");
123
+ }
124
+ // Two regexes, because "is this the thing" and "is this inside the thing"
125
+ // are answered differently for a directory-only rule.
126
+ const head = anchored ? "^" : "^(?:.*/)?";
127
+ return {
128
+ self: new RegExp(`${head}${out}$`),
129
+ under: new RegExp(`${head}${out}/.*$`),
130
+ };
131
+ }
132
+
133
+ /**
134
+ * The ignore matcher for a directory.
135
+ *
136
+ * `.vcsignore` wins outright when present — a project that wrote one meant it.
137
+ * Otherwise `.gitignore` stands in, and the Node defaults apply when there is
138
+ * neither.
139
+ */
140
+ export async function loadIgnores(dir, readFile) {
141
+ for (const name of [".vcsignore", ".gitignore"]) {
142
+ try {
143
+ const text = await readFile(`${dir}/${name}`, "utf8");
144
+ // Defaults come first so a project file can negate them with `!`.
145
+ return { match: compileIgnores(NODE_DEFAULTS + "\n" + text), source: name };
146
+ } catch {
147
+ // not there; try the next
148
+ }
149
+ }
150
+ return { match: compileIgnores(NODE_DEFAULTS), source: "defaults" };
151
+ }
152
+
153
+ /**
154
+ * Starter `.vcsignore` for a project.
155
+ *
156
+ * Seeded from the Node defaults, then from the project's own `.gitignore` when
157
+ * it has one — the patterns a project already maintains are the best statement
158
+ * of what is derivable in it, and re-typing them is how the two files drift.
159
+ */
160
+ export function draftIgnores(gitignore) {
161
+ const theirs = String(gitignore ?? "")
162
+ .split(/\r?\n/)
163
+ .map((line) => line.trim())
164
+ // Drop what the defaults already cover, so the file reads as "and also
165
+ // these" rather than a wall of duplicates.
166
+ .filter((line) => line && !line.startsWith("#") && !DEFAULT_LINES.has(line));
167
+
168
+ if (!theirs.length) return NODE_DEFAULTS;
169
+ return `${NODE_DEFAULTS}\n# Carried over from .gitignore.\n${[...new Set(theirs)].join("\n")}\n`;
170
+ }
171
+
172
+ const DEFAULT_LINES = new Set(
173
+ NODE_DEFAULTS.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith("#")),
174
+ );