@dryfit/cli 0.0.0-stage → 0.1.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,4160 @@
1
+ #!/usr/bin/env node
2
+ import { homedir, userInfo } from "node:os";
3
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
4
+ import { access, chmod, cp, link, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
+ import { spawn } from "node:child_process";
7
+ import { closeSync, existsSync, openSync, realpathSync, watch } from "node:fs";
8
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
9
+ import { runServer } from "verdaccio";
10
+ import { createServer } from "node:http";
11
+ import semver from "semver";
12
+ import { parseArgs } from "node:util";
13
+ // src/core/errors.ts
14
+ /**
15
+ * An expected failure the user can act on. Clients map `code` to their own wording; `message` is a
16
+ * plain-English fallback and `details` carries the data (paths, command output) behind it.
17
+ */
18
+ var DryfitError = class extends Error {
19
+ name = "DryfitError";
20
+ code;
21
+ details;
22
+ constructor(code, message, details = {}) {
23
+ super(message);
24
+ this.code = code;
25
+ this.details = details;
26
+ }
27
+ };
28
+ // src/core/util/json.ts
29
+ function isRecord(value) {
30
+ return typeof value === "object" && value !== null && !Array.isArray(value);
31
+ }
32
+ /** Parses JSON, returning undefined instead of throwing on invalid input. */
33
+ function tryParseJson(text) {
34
+ try {
35
+ return JSON.parse(text);
36
+ } catch {
37
+ return;
38
+ }
39
+ }
40
+ /** JSON with object keys sorted at every level, for order-insensitive comparison. */
41
+ function stableStringify(value) {
42
+ return JSON.stringify(value, (_key, nested) => isRecord(nested) ? Object.fromEntries(Object.entries(nested).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : nested);
43
+ }
44
+ /** The indentation a JSON document uses, so rewrites keep the author's formatting. */
45
+ function detectIndent(text) {
46
+ return /^[{[]\r?\n([ \t]+)/.exec(text)?.[1] ?? " ";
47
+ }
48
+ // src/adapters/node/dryfit-home.ts
49
+ /** Fixed ports keep lockfile URLs and the launchd agent stable; 4873 is Verdaccio's own default. */
50
+ const DEFAULT_CONFIG = {
51
+ roots: [],
52
+ ports: {
53
+ api: 4875,
54
+ registry: 4874
55
+ }
56
+ };
57
+ /**
58
+ * dryfit's folder (`~/.dryfit`, or `$DRYFIT_HOME`), shared by the daemon and the CLI (ADR 0012).
59
+ * The folder is private to the user: it holds the API token and copies of consumers' manifests.
60
+ */
61
+ var DryfitHome = class DryfitHome {
62
+ root;
63
+ paths;
64
+ constructor(root) {
65
+ this.root = root;
66
+ this.paths = {
67
+ config: join(root, "config.json"),
68
+ state: join(root, "state.json"),
69
+ token: join(root, "token"),
70
+ daemon: join(root, "daemon.json"),
71
+ registry: join(root, "registry"),
72
+ logs: join(root, "logs"),
73
+ log: join(root, "logs", "daemon.log")
74
+ };
75
+ }
76
+ static locate(env = process.env, home = homedir()) {
77
+ return new DryfitHome(env.DRYFIT_HOME || join(home, ".dryfit"));
78
+ }
79
+ async ensure() {
80
+ await mkdir(this.root, {
81
+ recursive: true,
82
+ mode: 448
83
+ });
84
+ await chmod(this.root, 448);
85
+ }
86
+ async readConfig() {
87
+ const text = await readOptional$1(this.paths.config);
88
+ if (text === void 0) return DEFAULT_CONFIG;
89
+ let parsed;
90
+ try {
91
+ parsed = JSON.parse(text);
92
+ } catch {
93
+ throw this.#invalidConfig("is not valid JSON");
94
+ }
95
+ if (!isRecord(parsed)) throw this.#invalidConfig("must hold a JSON object");
96
+ const roots = parsed.roots ?? DEFAULT_CONFIG.roots;
97
+ if (!Array.isArray(roots) || !roots.every((root) => typeof root === "string" && root.startsWith("/"))) throw this.#invalidConfig("needs \"roots\" to be a list of absolute paths");
98
+ const ports = {
99
+ ...DEFAULT_CONFIG.ports,
100
+ ...isRecord(parsed.ports) ? parsed.ports : {}
101
+ };
102
+ for (const [name, port] of Object.entries(ports)) if (!Number.isInteger(port) || port < 0 || port > 65535) throw this.#invalidConfig(`has an invalid "ports.${name}"`);
103
+ return {
104
+ roots,
105
+ ports
106
+ };
107
+ }
108
+ async writeConfig(config) {
109
+ await this.ensure();
110
+ await writeAtomically(this.paths.config, `${JSON.stringify(config, null, 2)}\n`);
111
+ }
112
+ /**
113
+ * The API token, created on first use. Every client must present it (ADR 0003). The file is written
114
+ * in full under a temporary name and then linked into place, so no reader ever sees a half-written
115
+ * token; a damaged one is replaced.
116
+ */
117
+ async ensureToken() {
118
+ await this.ensure();
119
+ const existing = await this.readToken();
120
+ if (existing) return existing;
121
+ const token = randomBytes(32).toString("hex");
122
+ const temporary = `${this.paths.token}.${randomUUID()}`;
123
+ await writeFile(temporary, `${token}\n`, { mode: 384 });
124
+ try {
125
+ await link(temporary, this.paths.token);
126
+ return token;
127
+ } catch (error) {
128
+ if (!(error instanceof Error && "code" in error && error.code === "EEXIST")) throw error;
129
+ const theirs = await this.readToken();
130
+ if (theirs) return theirs;
131
+ await rename(temporary, this.paths.token);
132
+ return token;
133
+ } finally {
134
+ await rm(temporary, { force: true });
135
+ }
136
+ }
137
+ async readToken() {
138
+ const token = (await readOptional$1(this.paths.token))?.trim();
139
+ return token && /^[0-9a-f]{64}$/.test(token) ? token : void 0;
140
+ }
141
+ async writeDaemonInfo(info) {
142
+ await this.ensure();
143
+ await writeAtomically(this.paths.daemon, `${JSON.stringify(info, null, 2)}\n`);
144
+ }
145
+ async readDaemonInfo() {
146
+ const text = await readOptional$1(this.paths.daemon);
147
+ try {
148
+ const info = text === void 0 ? void 0 : JSON.parse(text);
149
+ return isRecord(info) && typeof info.pid === "number" && typeof info.port === "number" ? info : void 0;
150
+ } catch {
151
+ return;
152
+ }
153
+ }
154
+ /** Removes the record, but only if it still describes `pid`: a newer daemon may have replaced it. */
155
+ async removeDaemonInfo(pid) {
156
+ if ((await this.readDaemonInfo())?.pid === pid) await rm(this.paths.daemon, { force: true });
157
+ }
158
+ #invalidConfig(problem) {
159
+ return new DryfitError("invalid-config", `${this.paths.config} ${problem}`, { path: this.paths.config });
160
+ }
161
+ };
162
+ async function readOptional$1(path) {
163
+ try {
164
+ return await readFile(path, "utf8");
165
+ } catch (error) {
166
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
167
+ throw error;
168
+ }
169
+ }
170
+ async function writeAtomically(path, content) {
171
+ const temporary = `${path}.${randomUUID()}.tmp`;
172
+ try {
173
+ await writeFile(temporary, content, { mode: 384 });
174
+ await rename(temporary, path);
175
+ } catch (error) {
176
+ await rm(temporary, { force: true });
177
+ throw error;
178
+ }
179
+ }
180
+ // src/version.ts
181
+ /** This dryfit's version. The CLI restarts a daemon whose version differs (ADR 0012). */
182
+ const VERSION = "0.1.0";
183
+ // src/adapters/node/node-process-runner.ts
184
+ /** Output beyond this is dropped from the front: the end of a failed npm run holds the error. */
185
+ const MAX_OUTPUT = 1e6;
186
+ /** A hung install should not block every later job forever, but a cold Angular build can be slow. */
187
+ const DEFAULT_TIMEOUT_MS = 9e5;
188
+ /** How long a stopped process tree gets to exit after SIGTERM before it is killed outright. */
189
+ const KILL_GRACE_MS = 3e3;
190
+ /**
191
+ * How long output may keep arriving after the command itself exits. Past this, whatever still holds
192
+ * the pipes is a background process the command left behind, and waiting for it would hang the job.
193
+ */
194
+ const OUTPUT_GRACE_MS = 1e3;
195
+ /**
196
+ * Runs commands as child processes without a shell, so arguments can never be interpreted.
197
+ *
198
+ * `npm_*` variables are removed from the child's environment. When dryfit itself is started by npm
199
+ * (`npx @dryfit/cli`, an npm script), npm exports its whole config as `npm_config_*`, which the npm that
200
+ * dryfit runs would obey: a stray `npm_config_global` or `npm_config_registry` would install into the
201
+ * wrong place or from the wrong registry.
202
+ *
203
+ * Each command leads its own process group, so a timeout or cancellation kills the whole tree: npm
204
+ * runs lifecycle scripts and builders as grandchildren that would otherwise keep running. A command
205
+ * is finished when it exits; background processes it leaves in its group are ended shortly after.
206
+ */
207
+ var NodeProcessRunner = class {
208
+ #env;
209
+ #timeoutMs;
210
+ #signal;
211
+ constructor(options = {}) {
212
+ const baseEnv = options.baseEnv ?? process.env;
213
+ this.#env = {
214
+ ...Object.fromEntries(Object.entries(baseEnv).filter(([key]) => !/^npm_/i.test(key))),
215
+ ...options.env
216
+ };
217
+ this.#timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
218
+ this.#signal = options.signal;
219
+ }
220
+ run(spec) {
221
+ if (this.#signal?.aborted) return Promise.resolve({
222
+ exitCode: 130,
223
+ stdout: "",
224
+ stderr: "dryfit: cancelled before it started\n"
225
+ });
226
+ return new Promise((resolve, reject) => {
227
+ const child = spawn(spec.command, [...spec.args], {
228
+ cwd: spec.cwd,
229
+ env: spec.env === void 0 ? this.#env : {
230
+ ...this.#env,
231
+ ...spec.env
232
+ },
233
+ shell: false,
234
+ detached: true,
235
+ stdio: [
236
+ "ignore",
237
+ "pipe",
238
+ "pipe"
239
+ ]
240
+ });
241
+ const stdout = new TailBuffer(MAX_OUTPUT);
242
+ const stderr = new TailBuffer(MAX_OUTPUT);
243
+ let stopped;
244
+ let killTimer;
245
+ const stop = (exitCode, reason) => {
246
+ if (stopped || child.pid === void 0) return;
247
+ stopped = {
248
+ exitCode,
249
+ reason
250
+ };
251
+ killGroup(child.pid, "SIGTERM");
252
+ killTimer = setTimeout(() => killGroup(child.pid, "SIGKILL"), KILL_GRACE_MS);
253
+ };
254
+ const seconds = this.#timeoutMs / 1e3;
255
+ const timeout = setTimeout(() => stop(124, `timed out after ${seconds} s`), this.#timeoutMs);
256
+ const onAbort = () => stop(130, "cancelled");
257
+ this.#signal?.addEventListener("abort", onAbort, { once: true });
258
+ const cleanUp = () => {
259
+ clearTimeout(timeout);
260
+ this.#signal?.removeEventListener("abort", onAbort);
261
+ };
262
+ child.stdout.setEncoding("utf8").on("data", (chunk) => stdout.append(chunk));
263
+ child.stderr.setEncoding("utf8").on("data", (chunk) => stderr.append(chunk));
264
+ child.once("error", (error) => {
265
+ cleanUp();
266
+ reject(error);
267
+ });
268
+ let settled = false;
269
+ let outputTimer;
270
+ const settle = (code, signal) => {
271
+ if (settled) return;
272
+ settled = true;
273
+ cleanUp();
274
+ clearTimeout(outputTimer);
275
+ if (stopped) {
276
+ if (child.pid !== void 0) killGroup(child.pid, "SIGKILL");
277
+ clearTimeout(killTimer);
278
+ stderr.append(`\ndryfit: ${spec.command} ${stopped.reason}\n`);
279
+ }
280
+ resolve({
281
+ exitCode: stopped?.exitCode ?? code ?? (signal === null ? 1 : 128),
282
+ stdout: stdout.toString(),
283
+ stderr: stderr.toString()
284
+ });
285
+ };
286
+ child.once("close", settle);
287
+ child.once("exit", (code, signal) => {
288
+ outputTimer = setTimeout(() => {
289
+ if (child.pid !== void 0) killGroup(child.pid, "SIGTERM");
290
+ child.stdout.destroy();
291
+ child.stderr.destroy();
292
+ settle(code, signal);
293
+ }, OUTPUT_GRACE_MS);
294
+ });
295
+ });
296
+ }
297
+ };
298
+ function killGroup(pid, signal) {
299
+ try {
300
+ process.kill(-pid, signal);
301
+ } catch {}
302
+ }
303
+ /** Keeps the last `limit` characters of a stream without re-copying on every chunk. */
304
+ var TailBuffer = class {
305
+ #limit;
306
+ #text = "";
307
+ constructor(limit) {
308
+ this.#limit = limit;
309
+ }
310
+ append(chunk) {
311
+ this.#text += chunk;
312
+ if (this.#text.length > this.#limit * 2) this.#text = this.#text.slice(-this.#limit);
313
+ }
314
+ toString() {
315
+ return this.#text.length > this.#limit ? this.#text.slice(-this.#limit) : this.#text;
316
+ }
317
+ };
318
+ // src/adapters/registry/npm-uplinks.ts
319
+ /**
320
+ * Reads the effective registries with `npm config list --json`, then the user and global npmrc files
321
+ * for credentials, which npm redacts from that listing. Credentials stay in memory.
322
+ */
323
+ async function readNpmRegistries(runner, options) {
324
+ const result = await runner.run({
325
+ command: "npm",
326
+ args: [
327
+ "config",
328
+ "list",
329
+ "--json"
330
+ ],
331
+ cwd: options.cwd
332
+ });
333
+ const config = result.exitCode === 0 ? tryParseJson(result.stdout) : void 0;
334
+ const listed = isRecord(config) ? config : {};
335
+ const settings = /* @__PURE__ */ new Map();
336
+ for (const key of ["globalconfig", "userconfig"]) {
337
+ const path = listed[key];
338
+ if (typeof path !== "string") continue;
339
+ const text = await readFile(path, "utf8").catch(() => "");
340
+ for (const [name, value] of parseNpmrc(text, options.env ?? process.env)) settings.set(name, value);
341
+ }
342
+ const scoped = {};
343
+ for (const [key, value] of Object.entries(listed)) {
344
+ const scope = /^(@[^:]+):registry$/.exec(key)?.[1];
345
+ if (scope !== void 0 && typeof value === "string") scoped[scope] = value;
346
+ }
347
+ return {
348
+ registry: typeof listed.registry === "string" ? listed.registry : "https://registry.npmjs.org/",
349
+ scoped,
350
+ settings
351
+ };
352
+ }
353
+ /** Parses npmrc text: `key=value` lines, `;` and `#` comments, `${VAR}` expanded from `env`. */
354
+ function parseNpmrc(text, env) {
355
+ const settings = /* @__PURE__ */ new Map();
356
+ for (const raw of text.split(/\r?\n/)) {
357
+ const line = raw.trim();
358
+ if (line === "" || line.startsWith(";") || line.startsWith("#")) continue;
359
+ const equals = line.indexOf("=");
360
+ if (equals === -1) continue;
361
+ const key = line.slice(0, equals).trim();
362
+ const value = line.slice(equals + 1).trim().replace(/\$\{([^}?]+)\??\}/g, (_, name) => env[name] ?? "");
363
+ settings.set(key, value);
364
+ }
365
+ return settings;
366
+ }
367
+ /**
368
+ * Turns npm's registries into Verdaccio uplinks: the default registry serves everything, each other
369
+ * registry serves the scopes configured for it. dryfit's own registry is never proxied.
370
+ */
371
+ function uplinksFrom(input) {
372
+ const own = withSlash(input.ownRegistry);
373
+ const byUrl = /* @__PURE__ */ new Map();
374
+ const defaultUrl = withSlash(input.registry);
375
+ if (defaultUrl !== own) byUrl.set(defaultUrl, { scopes: [] });
376
+ for (const [scope, url] of Object.entries(input.scoped)) {
377
+ const normalized = withSlash(url);
378
+ if (normalized === own || normalized === defaultUrl) continue;
379
+ const entry = byUrl.get(normalized) ?? { scopes: [] };
380
+ entry.scopes.push(scope);
381
+ byUrl.set(normalized, entry);
382
+ }
383
+ const uplinks = {};
384
+ for (const [url, { scopes }] of byUrl) {
385
+ const auth = credentialsFor(url, input.settings);
386
+ uplinks[uniqueName(url, uplinks)] = {
387
+ url,
388
+ ...auth && { auth },
389
+ ...scopes.length > 0 && { scopes }
390
+ };
391
+ }
392
+ return uplinks;
393
+ }
394
+ /** npm keys credentials by the registry URL without its protocol, falling back to parent paths. */
395
+ function credentialsFor(url, settings) {
396
+ const { host, pathname } = new URL(url);
397
+ const segments = pathname.split("/").filter(Boolean);
398
+ for (let depth = segments.length; depth >= 0; depth -= 1) {
399
+ const key = `//${host}/${segments.slice(0, depth).map((segment) => `${segment}/`).join("")}`;
400
+ const token = settings.get(`${key}:_authToken`);
401
+ if (token) return {
402
+ type: "bearer",
403
+ token
404
+ };
405
+ const basic = settings.get(`${key}:_auth`);
406
+ if (basic) return {
407
+ type: "basic",
408
+ token: basic
409
+ };
410
+ const username = settings.get(`${key}:username`);
411
+ const password = settings.get(`${key}:_password`);
412
+ const pair = username && password ? basicPair(username, password) : void 0;
413
+ if (pair) return {
414
+ type: "basic",
415
+ token: pair
416
+ };
417
+ }
418
+ }
419
+ /** npm stores `_password` base64-encoded. A malformed one is skipped; `doctor` shows the uplink as unauthenticated. */
420
+ function basicPair(username, password) {
421
+ try {
422
+ return btoa(`${username}:${atob(password)}`);
423
+ } catch {
424
+ return;
425
+ }
426
+ }
427
+ function uniqueName(url, taken) {
428
+ const { hostname, port } = new URL(url);
429
+ const base = `${hostname}${port ? `-${port}` : ""}`.replace(/[^a-z0-9.-]/gi, "-");
430
+ let name = base;
431
+ for (let n = 2; Object.hasOwn(taken, name); n += 1) name = `${base}-${n}`;
432
+ return name;
433
+ }
434
+ function withSlash(url) {
435
+ return url.endsWith("/") ? url : `${url}/`;
436
+ }
437
+ // src/core/guard/commit-guard.ts
438
+ /**
439
+ * The commit guard (ADR 0005, ADR 0012): a block of POSIX sh placed at the top of a consumer's
440
+ * pre-commit hook. It refuses a commit when a staged manifest or lockfile mentions a dryfit dev
441
+ * version, which is exactly what a linked consumer's files contain until they are restored.
442
+ *
443
+ * It needs neither Node nor dryfit at commit time, so it works from GUI git clients with a minimal
444
+ * PATH and cannot break when dryfit is moved or uninstalled.
445
+ */
446
+ const START = "# >>> dryfit commit guard >>>";
447
+ const END = "# <<< dryfit commit guard <<<";
448
+ const NEW_HOOK = "#!/bin/sh\n";
449
+ /** Matches a dev version as `nextDevVersion` writes it: `-dev.` or `.dev.` plus a 14-digit stamp. */
450
+ const DEV_VERSION_PATTERN = "[-.]dev\\.[0-9]{14}";
451
+ const STAGED_FILES = [
452
+ "package.json",
453
+ "package-lock.json",
454
+ "npm-shrinkwrap.json",
455
+ "pnpm-lock.yaml",
456
+ "yarn.lock",
457
+ "bun.lock"
458
+ ].map((name) => `':(glob)**/${name}'`).join(" ");
459
+ /** Marks a hook file dryfit created itself, so restoring deletes it rather than leaving a stub. */
460
+ const CREATED = "# dryfit created this hook file; restoring deletes it.";
461
+ const BODY = [
462
+ "# Added by `dryfit link`, removed by `dryfit restore`. Refuses commits that would ship a dev build.",
463
+ `dryfit_leaks=$(git -c core.quotePath=false diff --cached --name-only --diff-filter=ACMR -- ${STAGED_FILES} | while IFS= read -r dryfit_file; do`,
464
+ ` if git show ":$dryfit_file" 2>/dev/null | grep -Eq -- '${DEV_VERSION_PATTERN}'; then printf ' %s\\n' "$dryfit_file"; fi`,
465
+ "done)",
466
+ "if [ -n \"$dryfit_leaks\" ]; then",
467
+ ` printf 'dryfit: these staged files point at a local dev build:\\n%s\\n' "$dryfit_leaks" >&2`,
468
+ " printf 'Run `dryfit restore` in this project first, or commit with --no-verify if you are sure.\\n' >&2",
469
+ " exit 1",
470
+ "fi"
471
+ ];
472
+ const block = (created) => [
473
+ START,
474
+ ...created ? [CREATED] : [],
475
+ ...BODY,
476
+ END
477
+ ].join("\n");
478
+ /** Lines that are verbatim dryfit's, for taking out a block whose end marker was edited away. */
479
+ const OWN_LINES = /* @__PURE__ */ new Set([
480
+ START,
481
+ CREATED,
482
+ ...BODY,
483
+ END
484
+ ]);
485
+ function hasGuard(hook) {
486
+ return hook?.includes(START) ?? false;
487
+ }
488
+ /** The hook with the guard as its first step. Applying it again replaces the old block. */
489
+ function withGuard(hook) {
490
+ const base = hook === void 0 ? void 0 : withoutGuard(hook);
491
+ if (base === void 0) return `${NEW_HOOK}${block(true)}\n`;
492
+ if (!base.startsWith("#!")) return `${block(false)}\n${base}`;
493
+ const newline = base.indexOf("\n");
494
+ const shebang = newline === -1 ? `${base}\n` : base.slice(0, newline + 1);
495
+ const rest = newline === -1 ? "" : base.slice(newline + 1);
496
+ return `${shebang}${block(false)}\n${rest}`;
497
+ }
498
+ /**
499
+ * The hook without the guard, exactly as it was before; undefined when dryfit created the file and
500
+ * nothing but a shebang would remain. If the end marker is gone, only lines that are verbatim
501
+ * dryfit's are taken out, so the user's own hook lines are never removed.
502
+ */
503
+ function withoutGuard(hook) {
504
+ const start = hook.indexOf(START);
505
+ if (start === -1) return hook;
506
+ const endMarker = hook.indexOf(END, start);
507
+ let end = endMarker + 29;
508
+ if (endMarker === -1) {
509
+ const lines = hook.slice(start).split("\n");
510
+ const own = lines.findIndex((line) => !OWN_LINES.has(line));
511
+ end = start + lines.slice(0, own === -1 ? lines.length : own).join("\n").length;
512
+ }
513
+ if (hook[end] === "\n") end += 1;
514
+ const created = hook.slice(start, end).includes(CREATED);
515
+ const rest = hook.slice(0, start) + hook.slice(end);
516
+ return created && /^(#![^\n]*\n?)?\s*$/.test(rest) ? void 0 : rest;
517
+ }
518
+ // src/core/package-manager/detect.ts
519
+ const PACKAGE_MANAGERS = [
520
+ "npm",
521
+ "pnpm",
522
+ "yarn",
523
+ "bun"
524
+ ];
525
+ /** Lockfiles that identify a package manager when found at the project root. */
526
+ const LOCKFILES = {
527
+ "package-lock.json": "npm",
528
+ "npm-shrinkwrap.json": "npm",
529
+ "pnpm-lock.yaml": "pnpm",
530
+ "yarn.lock": "yarn",
531
+ "bun.lock": "bun",
532
+ "bun.lockb": "bun"
533
+ };
534
+ /** Lockfiles dryfit cannot snapshot and restore, because they are not text. */
535
+ const BINARY_LOCKFILES = ["bun.lockb"];
536
+ /**
537
+ * Decides which package manager owns a project (ADR 0006): the `packageManager` field wins, then a
538
+ * single lockfile, then npm. Lockfiles from different managers are ambiguous, so detection refuses to
539
+ * guess rather than risk rewriting the wrong lockfile.
540
+ */
541
+ function detectPackageManager({ files, manifest }) {
542
+ const field = manifest.packageManager;
543
+ if (field !== void 0) {
544
+ const [name, version = ""] = field.split("@");
545
+ const yarnClassic = name === "yarn" && /^1\./.test(version);
546
+ return isPackageManagerName(name) && !yarnClassic ? {
547
+ ok: true,
548
+ name,
549
+ source: "packageManager-field"
550
+ } : {
551
+ ok: false,
552
+ reason: "unsupported-package-manager",
553
+ value: field
554
+ };
555
+ }
556
+ const lockfiles = files.filter((file) => file in LOCKFILES).sort();
557
+ const [only, ...others] = new Set(lockfiles.map((file) => LOCKFILES[file]));
558
+ if (only === void 0) return {
559
+ ok: true,
560
+ name: "npm",
561
+ source: "default"
562
+ };
563
+ if (others.length > 0) return {
564
+ ok: false,
565
+ reason: "multiple-lockfiles",
566
+ lockfiles
567
+ };
568
+ if (lockfiles.filter((file) => !BINARY_LOCKFILES.includes(file)).length === 0) return {
569
+ ok: false,
570
+ reason: "binary-lockfile",
571
+ lockfile: lockfiles[0] ?? ""
572
+ };
573
+ return {
574
+ ok: true,
575
+ name: only,
576
+ source: "lockfile"
577
+ };
578
+ }
579
+ function isPackageManagerName(value) {
580
+ return PACKAGE_MANAGERS.some((name) => name === value);
581
+ }
582
+ // src/core/util/path.ts
583
+ /**
584
+ * Minimal POSIX path helpers so core/ stays free of `node:path` (ADR 0008). Every segment after the
585
+ * first is treated as relative; `..` cannot climb above the root.
586
+ */
587
+ function joinPath(first, ...rest) {
588
+ const absolute = first.startsWith("/");
589
+ const segments = [];
590
+ for (const part of [first, ...rest]) for (const segment of part.split("/")) {
591
+ if (segment === "" || segment === ".") continue;
592
+ if (segment === "..") {
593
+ if (segments.length > 0 && segments.at(-1) !== "..") segments.pop();
594
+ else if (!absolute) segments.push("..");
595
+ continue;
596
+ }
597
+ segments.push(segment);
598
+ }
599
+ const joined = segments.join("/");
600
+ return absolute ? `/${joined}` : joined;
601
+ }
602
+ /** `path` itself when absolute, otherwise `path` resolved against `base`. */
603
+ function resolvePath(base, path) {
604
+ return path.startsWith("/") ? joinPath(path) : joinPath(base, path);
605
+ }
606
+ /** `path` relative to `base` when it is inside it (`''` for `base` itself), otherwise undefined. */
607
+ function relativeInside(base, path) {
608
+ const from = joinPath(base);
609
+ const to = joinPath(path);
610
+ if (to === from) return "";
611
+ const prefix = from === "/" ? "/" : `${from}/`;
612
+ return to.startsWith(prefix) ? to.slice(prefix.length) : void 0;
613
+ }
614
+ /**
615
+ * A single folder name for per-item storage (snapshots, staging). The readable part helps when
616
+ * browsing `~/.dryfit`; the hash keeps two inputs from sharing a folder when their readable parts
617
+ * collide (`/a/b_c` and `/a/b/c`).
618
+ */
619
+ function pathSlug(value) {
620
+ return `${value.replace(/^[/@]+/, "").replace(/[^A-Za-z0-9.-]+/g, "_").slice(0, 80)}-${fnv1a(value)}`;
621
+ }
622
+ /** 32-bit FNV-1a, hex. Not cryptographic; only needs to separate local paths. */
623
+ function fnv1a(value) {
624
+ let hash = 0x811c9dc5;
625
+ for (let index = 0; index < value.length; index++) {
626
+ hash ^= value.charCodeAt(index);
627
+ hash = Math.imul(hash, 16777619);
628
+ }
629
+ return (hash >>> 0).toString(16).padStart(8, "0");
630
+ }
631
+ // src/core/use-cases/shared.ts
632
+ /** The dist-tag every dev version is published under, so `latest` is never touched (ADR 0004). */
633
+ const DEV_TAG = "dryfit";
634
+ function requireLibrary(state, name) {
635
+ const library = state.libraries.find((candidate) => candidate.name === name);
636
+ if (!library) throw new DryfitError("library-not-found", `No library named ${name} is registered`, { library: name });
637
+ return library;
638
+ }
639
+ function withLibrary(state, library) {
640
+ const others = state.libraries.filter((candidate) => candidate.name !== library.name);
641
+ return {
642
+ ...state,
643
+ libraries: [...others, library]
644
+ };
645
+ }
646
+ /** Inserts or replaces a link, keeping the existing order so status lists stay stable. */
647
+ function withLink(state, link) {
648
+ const index = state.links.findIndex((candidate) => sameLink(candidate, link));
649
+ const links = index === -1 ? [...state.links, link] : state.links.with(index, link);
650
+ return {
651
+ ...state,
652
+ links
653
+ };
654
+ }
655
+ function sameLink(a, b) {
656
+ return a.library === b.library && a.consumer === b.consumer;
657
+ }
658
+ function snapshotDir(deps, consumer) {
659
+ return joinPath(deps.home, "snapshots", pathSlug(consumer));
660
+ }
661
+ function stagingDir(deps, library) {
662
+ return joinPath(deps.home, "staging", pathSlug(library));
663
+ }
664
+ /** The adapter for a project's package manager, or a DryfitError explaining why there is none. */
665
+ function adapterFor(deps, project) {
666
+ const detection = detectPackageManager({
667
+ files: project.rootFiles,
668
+ manifest: project.manifest
669
+ });
670
+ if (!detection.ok) {
671
+ if (detection.reason === "multiple-lockfiles") throw new DryfitError("package-manager-undetected", `${project.root} has lockfiles from more than one package manager (${detection.lockfiles.join(", ")}). Delete the ones you don't use.`, {
672
+ project: project.root,
673
+ lockfiles: detection.lockfiles
674
+ });
675
+ if (detection.reason === "binary-lockfile") throw new DryfitError("unsupported-package-manager", `${project.root} has a binary ${detection.lockfile}, which dryfit cannot restore. Switch to the text lockfile with \`bun install --save-text-lockfile\`.`, {
676
+ project: project.root,
677
+ packageManager: "bun"
678
+ });
679
+ throw new DryfitError("unsupported-package-manager", `${project.root} uses ${detection.value}, which dryfit does not support`, {
680
+ project: project.root,
681
+ packageManager: detection.value
682
+ });
683
+ }
684
+ const adapter = deps.packageManagers[detection.name];
685
+ if (!adapter) throw new DryfitError("unsupported-package-manager", `${project.root} uses ${detection.name}, which dryfit does not support yet`, {
686
+ project: project.root,
687
+ packageManager: detection.name
688
+ });
689
+ return adapter;
690
+ }
691
+ /**
692
+ * Runs a command, turning a failure to start it (npm not on PATH, a missing cwd) into a failed result
693
+ * so callers handle every failure the same way instead of skipping their cleanup.
694
+ */
695
+ async function runSafely(deps, spec) {
696
+ try {
697
+ return await deps.process.run(spec);
698
+ } catch (error) {
699
+ return {
700
+ exitCode: -1,
701
+ stdout: "",
702
+ stderr: error instanceof Error ? error.message : String(error)
703
+ };
704
+ }
705
+ }
706
+ /** The most useful text from a failed command: stderr when there is any, else stdout. */
707
+ function commandOutput(result) {
708
+ return result.stderr.trim() || result.stdout.trim();
709
+ }
710
+ // src/adapters/git/git-commit-guard.ts
711
+ /**
712
+ * Installs the commit guard into the hook git will actually run: `git rev-parse --git-path hooks`
713
+ * follows `core.hooksPath` (Husky, lefthook) and worktrees, so the guard lands where it takes effect.
714
+ */
715
+ var GitCommitGuard = class {
716
+ #runner;
717
+ constructor(runner) {
718
+ this.#runner = runner;
719
+ }
720
+ async install(consumer) {
721
+ const hook = await this.#hookPath(consumer);
722
+ if (hook === void 0) return "not-a-repo";
723
+ await mkdir(join(hook, ".."), { recursive: true });
724
+ await writeFile(hook, withGuard(await readOptional(hook)));
725
+ await chmod(hook, 493);
726
+ return "installed";
727
+ }
728
+ async remove(consumer) {
729
+ const hook = await this.#hookPath(consumer);
730
+ const current = hook === void 0 ? void 0 : await readOptional(hook);
731
+ if (hook === void 0 || current === void 0) return;
732
+ const remaining = withoutGuard(current);
733
+ if (remaining === void 0) await rm(hook, { force: true });
734
+ else if (remaining !== current) await writeFile(hook, remaining);
735
+ }
736
+ async #hookPath(consumer) {
737
+ const result = await this.#runner.run({
738
+ command: "git",
739
+ args: [
740
+ "rev-parse",
741
+ "--git-path",
742
+ "hooks"
743
+ ],
744
+ cwd: consumer
745
+ }).catch(() => void 0);
746
+ if (result?.exitCode !== 0) return void 0;
747
+ return join(resolve(consumer, result.stdout.trim()), "pre-commit");
748
+ }
749
+ };
750
+ async function readOptional(path) {
751
+ try {
752
+ return await readFile(path, "utf8");
753
+ } catch (error) {
754
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return void 0;
755
+ throw error;
756
+ }
757
+ }
758
+ // src/core/project/cache-paths.ts
759
+ /**
760
+ * Cache folders to clear for a project: every detected integration's paths plus the user's extras.
761
+ *
762
+ * Every path is deleted recursively, so anything that is not strictly inside the project is dropped:
763
+ * `.`, `..`, absolute paths, or a config value such as `"../.."` would otherwise delete the project or
764
+ * its parent folders.
765
+ */
766
+ function cachePathsFor(project, integrations, extraPaths = []) {
767
+ const candidates = [...integrations.filter((integration) => integration.detect(project)).flatMap((integration) => integration.cachePaths(project)), ...extraPaths];
768
+ return [...new Set(candidates.filter((path) => isStrictlyInside(project.root, path)))];
769
+ }
770
+ /** True when the manifest declares any of `names` in any dependency field. */
771
+ function dependsOnAny(project, names) {
772
+ const { dependencies, devDependencies, optionalDependencies, peerDependencies } = project.manifest;
773
+ return names.some((name) => [
774
+ dependencies,
775
+ devDependencies,
776
+ optionalDependencies,
777
+ peerDependencies
778
+ ].some((field) => field?.[name]));
779
+ }
780
+ function isStrictlyInside(root, relativePath) {
781
+ if (relativePath.startsWith("/")) return false;
782
+ const base = joinPath(root);
783
+ return joinPath(base, relativePath).startsWith(`${base}/`);
784
+ }
785
+ // src/adapters/integrations/angular.ts
786
+ const DEFAULT_CACHE = ".angular/cache";
787
+ // src/adapters/integrations/index.ts
788
+ const builtInIntegrations = [
789
+ {
790
+ id: "angular",
791
+ configFiles: ["angular.json"],
792
+ detect: (project) => project.rootFiles.includes("angular.json") || dependsOnAny(project, ["@angular/core"]),
793
+ cachePaths(project) {
794
+ const config = project.configs.get("angular.json");
795
+ const cli = isRecord(config) ? config.cli : void 0;
796
+ const cache = isRecord(cli) ? cli.cache : void 0;
797
+ const path = isRecord(cache) ? cache.path : void 0;
798
+ return [typeof path === "string" && path.length > 0 ? path : DEFAULT_CACHE];
799
+ }
800
+ },
801
+ {
802
+ id: "native-federation",
803
+ detect: (project) => dependsOnAny(project, ["@angular-architects/native-federation", "@softarc/native-federation"]),
804
+ cachePaths: () => ["node_modules/.cache/native-federation"]
805
+ },
806
+ {
807
+ id: "vite",
808
+ detect: (project) => dependsOnAny(project, ["vite"]),
809
+ cachePaths: () => ["node_modules/.vite"]
810
+ }
811
+ ];
812
+ // src/adapters/package-managers/tarball-url.ts
813
+ /**
814
+ * Where an npm-compatible registry serves one version's tarball: `<registry>/<name>/-/<base>-<version>.tgz`,
815
+ * where `<base>` is the name without its scope. Installing from this URL needs no registry config at all,
816
+ * which is what Yarn and Bun need, since neither lets a command override a scope's registry.
817
+ */
818
+ function tarballUrl(registryUrl, packageName, version) {
819
+ return `${registryUrl.replace(/\/*$/, "/")}${packageName}/-/${packageName.split("/").at(-1) ?? packageName}-${version}.tgz`;
820
+ }
821
+ // src/adapters/package-managers/bun.ts
822
+ const SAVE_FLAG$3 = {
823
+ dependencies: void 0,
824
+ devDependencies: "--dev",
825
+ optionalDependencies: "--optional",
826
+ peerDependencies: "--peer"
827
+ };
828
+ /**
829
+ * Bun with its text lockfile (a binary bun.lockb is refused at detection). `--registry` does not
830
+ * override a scope mapped in .npmrc or bunfig.toml, so the dev build is installed from its tarball
831
+ * URL, as with Yarn. The manifest holds the URL until restore puts it back.
832
+ */
833
+ const bun = {
834
+ name: "bun",
835
+ lockfiles: ["bun.lock"],
836
+ install({ cwd, packageName, version, dependencyField, registryUrl }) {
837
+ const saveFlag = SAVE_FLAG$3[dependencyField];
838
+ return {
839
+ command: "bun",
840
+ args: [
841
+ "add",
842
+ `${packageName}@${tarballUrl(registryUrl, packageName, version)}`,
843
+ ...saveFlag === void 0 ? [] : [saveFlag]
844
+ ],
845
+ cwd
846
+ };
847
+ },
848
+ cleanInstall({ cwd, hasLockfile }) {
849
+ return {
850
+ command: "bun",
851
+ args: hasLockfile ? ["install", "--frozen-lockfile"] : ["install", "--no-save"],
852
+ cwd
853
+ };
854
+ }
855
+ };
856
+ // src/adapters/package-managers/npm.ts
857
+ const QUIET = ["--no-audit", "--no-fund"];
858
+ const SAVE_FLAG$2 = {
859
+ dependencies: void 0,
860
+ devDependencies: "--save-dev",
861
+ optionalDependencies: "--save-optional",
862
+ peerDependencies: "--save-peer"
863
+ };
864
+ const npm = {
865
+ name: "npm",
866
+ lockfiles: ["package-lock.json", "npm-shrinkwrap.json"],
867
+ install({ cwd, packageName, version, dependencyField, registryUrl }) {
868
+ const saveFlag = SAVE_FLAG$2[dependencyField];
869
+ return {
870
+ command: "npm",
871
+ args: [
872
+ "install",
873
+ `${packageName}@${version}`,
874
+ "--save-exact",
875
+ ...saveFlag === void 0 ? [] : [saveFlag],
876
+ registryFlag(packageName, registryUrl),
877
+ ...QUIET
878
+ ],
879
+ cwd
880
+ };
881
+ },
882
+ cleanInstall({ cwd, hasLockfile }) {
883
+ return {
884
+ command: "npm",
885
+ args: hasLockfile ? ["ci", ...QUIET] : [
886
+ "install",
887
+ "--no-package-lock",
888
+ ...QUIET
889
+ ],
890
+ cwd
891
+ };
892
+ }
893
+ };
894
+ /** Publishes every library, whichever package manager it uses: the staged folder is a plain package. */
895
+ const npmPublisher = {
896
+ publish({ cwd, registryUrl, tag }) {
897
+ return {
898
+ command: "npm",
899
+ args: [
900
+ "publish",
901
+ `--registry=${registryUrl}`,
902
+ `--tag=${tag}`,
903
+ "--provenance=false"
904
+ ],
905
+ cwd
906
+ };
907
+ },
908
+ publishAuthFiles({ registryUrl, credentials }) {
909
+ return { ".npmrc": `${registryUrl.replace(/^https?:/, "").replace(/\/*$/, "/")}:_auth=${btoa(`${credentials.username}:${credentials.password}`)}\n` };
910
+ }
911
+ };
912
+ /**
913
+ * A scoped package can be pointed at the local registry on its own, leaving every other dependency
914
+ * on the user's normal registry. An unscoped one cannot, so the whole install goes through the local
915
+ * registry, which proxies everything it does not hold (ADR 0002).
916
+ */
917
+ function registryFlag(packageName, registryUrl) {
918
+ const scope = /^(@[^/]+)\//.exec(packageName)?.[1];
919
+ return scope === void 0 ? `--registry=${registryUrl}` : `--${scope}:registry=${registryUrl}`;
920
+ }
921
+ // src/adapters/package-managers/pnpm.ts
922
+ const SAVE_FLAG$1 = {
923
+ dependencies: void 0,
924
+ devDependencies: "--save-dev",
925
+ optionalDependencies: "--save-optional",
926
+ peerDependencies: "--save-peer"
927
+ };
928
+ /**
929
+ * pnpm takes registries as `--config.<key>` for one command, so, like npm, only the library's scope
930
+ * is pointed at the local registry. `minimumReleaseAge` is lifted for that one install: a dev build
931
+ * is always seconds old, and pnpm would otherwise refuse it or record an exception in the project's
932
+ * pnpm-workspace.yaml.
933
+ */
934
+ const pnpm = {
935
+ name: "pnpm",
936
+ lockfiles: ["pnpm-lock.yaml"],
937
+ install({ cwd, packageName, version, dependencyField, registryUrl }) {
938
+ const saveFlag = SAVE_FLAG$1[dependencyField];
939
+ const scope = /^(@[^/]+)\//.exec(packageName)?.[1];
940
+ return {
941
+ command: "pnpm",
942
+ args: [
943
+ "add",
944
+ `${packageName}@${version}`,
945
+ "--save-exact",
946
+ ...saveFlag === void 0 ? [] : [saveFlag],
947
+ scope === void 0 ? `--config.registry=${registryUrl}` : `--config.${scope}:registry=${registryUrl}`,
948
+ "--config.minimumReleaseAge=0"
949
+ ],
950
+ cwd
951
+ };
952
+ },
953
+ cleanInstall({ cwd, hasLockfile }) {
954
+ return {
955
+ command: "pnpm",
956
+ args: hasLockfile ? ["install", "--frozen-lockfile"] : ["install", "--config.lockfile=false"],
957
+ cwd
958
+ };
959
+ }
960
+ };
961
+ // src/adapters/package-managers/yarn.ts
962
+ const SAVE_FLAG = {
963
+ dependencies: void 0,
964
+ devDependencies: "--dev",
965
+ optionalDependencies: "--optional",
966
+ peerDependencies: "--peer"
967
+ };
968
+ /** CI sets immutable installs by default, which would refuse the manifest change `add` makes. */
969
+ const MUTABLE = { YARN_ENABLE_IMMUTABLE_INSTALLS: "false" };
970
+ /**
971
+ * Yarn 2 and later (Yarn 1 is refused at detection). Yarn reads per-scope registries only from
972
+ * .yarnrc.yml, which dryfit never edits, so the dev build is installed from its tarball URL: that
973
+ * works whatever registry the project maps the scope to, and skips Yarn's release-age gate, which
974
+ * applies to registry versions only. The manifest holds the URL until restore puts it back.
975
+ */
976
+ const yarn = {
977
+ name: "yarn",
978
+ lockfiles: ["yarn.lock"],
979
+ install({ cwd, packageName, version, dependencyField, registryUrl }) {
980
+ const saveFlag = SAVE_FLAG[dependencyField];
981
+ const url = new URL(registryUrl);
982
+ return {
983
+ command: "yarn",
984
+ args: [
985
+ "add",
986
+ `${packageName}@${tarballUrl(registryUrl, packageName, version)}`,
987
+ ...saveFlag === void 0 ? [] : [saveFlag]
988
+ ],
989
+ cwd,
990
+ env: url.protocol === "http:" ? {
991
+ ...MUTABLE,
992
+ YARN_UNSAFE_HTTP_WHITELIST: url.hostname
993
+ } : MUTABLE
994
+ };
995
+ },
996
+ cleanInstall({ cwd, hasLockfile }) {
997
+ return hasLockfile ? {
998
+ command: "yarn",
999
+ args: ["install", "--immutable"],
1000
+ cwd
1001
+ } : {
1002
+ command: "yarn",
1003
+ args: ["install"],
1004
+ cwd,
1005
+ env: MUTABLE
1006
+ };
1007
+ }
1008
+ };
1009
+ // src/core/model.ts
1010
+ const DEPENDENCY_FIELDS = [
1011
+ "dependencies",
1012
+ "devDependencies",
1013
+ "optionalDependencies",
1014
+ "peerDependencies"
1015
+ ];
1016
+ const EMPTY_STATE = {
1017
+ libraries: [],
1018
+ links: [],
1019
+ groups: []
1020
+ };
1021
+ // src/adapters/node/json-state-store.ts
1022
+ const STATE_VERSION = 2;
1023
+ /** Versions this dryfit can read; older ones are upgraded on load. */
1024
+ const READABLE_VERSIONS = [1, 2];
1025
+ /**
1026
+ * dryfit's state as one JSON file (`~/.dryfit/state.json`). Writes go to a temporary file that is
1027
+ * renamed over the old one, so a crash mid-write never leaves a half-written state behind.
1028
+ */
1029
+ var JsonStateStore = class {
1030
+ #path;
1031
+ constructor(path) {
1032
+ this.#path = path;
1033
+ }
1034
+ async load() {
1035
+ let text;
1036
+ try {
1037
+ text = await readFile(this.#path, "utf8");
1038
+ } catch (error) {
1039
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return EMPTY_STATE;
1040
+ throw error;
1041
+ }
1042
+ let parsed;
1043
+ try {
1044
+ parsed = JSON.parse(text);
1045
+ } catch {
1046
+ throw this.#corrupt("is not valid JSON");
1047
+ }
1048
+ if (!isRecord(parsed) || !READABLE_VERSIONS.includes(parsed.version)) throw this.#corrupt(`has an unknown format version (this dryfit reads version ${STATE_VERSION})`);
1049
+ const { libraries, links, groups = parsed.version === 1 ? [] : void 0 } = parsed;
1050
+ if (!Array.isArray(libraries) || !Array.isArray(links) || !Array.isArray(groups)) throw this.#corrupt("is missing its libraries, links or groups");
1051
+ if (!libraries.every(isLibraryRecord)) throw this.#corrupt("has a malformed library entry");
1052
+ if (!links.every(isLinkRecord)) throw this.#corrupt("has a malformed link entry");
1053
+ if (!groups.every(isGroupRecord)) throw this.#corrupt("has a malformed group entry");
1054
+ return {
1055
+ libraries,
1056
+ links,
1057
+ groups
1058
+ };
1059
+ }
1060
+ async save(state) {
1061
+ await mkdir(dirname(this.#path), { recursive: true });
1062
+ const temporary = `${this.#path}.${randomUUID()}.tmp`;
1063
+ const content = `${JSON.stringify({
1064
+ version: STATE_VERSION,
1065
+ ...state
1066
+ }, null, 2)}\n`;
1067
+ try {
1068
+ const file = await open(temporary, "w", 384);
1069
+ try {
1070
+ await file.writeFile(content, "utf8");
1071
+ await file.sync();
1072
+ } finally {
1073
+ await file.close();
1074
+ }
1075
+ await rename(temporary, this.#path);
1076
+ } catch (error) {
1077
+ await rm(temporary, { force: true });
1078
+ throw error;
1079
+ }
1080
+ }
1081
+ #corrupt(problem) {
1082
+ return new DryfitError("state-corrupt", `${this.#path} ${problem}. Move it aside to start fresh; your consumers' snapshots are kept separately.`, { path: this.#path });
1083
+ }
1084
+ };
1085
+ const LINK_STATUSES = [
1086
+ "pending",
1087
+ "installed",
1088
+ "failed"
1089
+ ];
1090
+ function isLibraryRecord(value) {
1091
+ return isRecord(value) && typeof value.name === "string" && typeof value.root === "string" && typeof value.publishDir === "string";
1092
+ }
1093
+ function isLinkRecord(value) {
1094
+ return isRecord(value) && typeof value.library === "string" && typeof value.consumer === "string" && LINK_STATUSES.includes(value.status);
1095
+ }
1096
+ function isGroupRecord(value) {
1097
+ return isRecord(value) && typeof value.name === "string" && Array.isArray(value.consumers) && value.consumers.every((consumer) => typeof consumer === "string");
1098
+ }
1099
+ // src/adapters/node/node-file-system.ts
1100
+ /** The real file system. Must pass the same contract suite as the in-memory fake (ADR 0009). */
1101
+ var NodeFileSystem = class {
1102
+ async readText(path) {
1103
+ try {
1104
+ return await readFile(path, "utf8");
1105
+ } catch (error) {
1106
+ if (hasCode(error, "ENOENT")) return void 0;
1107
+ throw error;
1108
+ }
1109
+ }
1110
+ async writeText(path, content, options) {
1111
+ await mkdir(dirname(path), { recursive: true });
1112
+ if (!options?.private) return writeFile(path, content, "utf8");
1113
+ await chmod(path, 384).catch((error) => {
1114
+ if (!hasCode(error, "ENOENT")) throw error;
1115
+ });
1116
+ await writeFile(path, content, {
1117
+ encoding: "utf8",
1118
+ mode: 384
1119
+ });
1120
+ }
1121
+ async exists(path) {
1122
+ try {
1123
+ await access(path);
1124
+ return true;
1125
+ } catch {
1126
+ return false;
1127
+ }
1128
+ }
1129
+ async readDir(path) {
1130
+ try {
1131
+ return (await readdir(path, { withFileTypes: true })).map((entry) => ({
1132
+ name: entry.name,
1133
+ isDirectory: entry.isDirectory()
1134
+ })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1135
+ } catch (error) {
1136
+ if (hasCode(error, "ENOENT") || hasCode(error, "ENOTDIR")) return [];
1137
+ throw error;
1138
+ }
1139
+ }
1140
+ async remove(path) {
1141
+ await rm(path, {
1142
+ recursive: true,
1143
+ force: true
1144
+ });
1145
+ }
1146
+ async copyDir(from, to, options) {
1147
+ await cp(from, to, {
1148
+ recursive: true,
1149
+ verbatimSymlinks: true,
1150
+ filter: (source) => source === from || !options.exclude.includes(basename(source))
1151
+ });
1152
+ }
1153
+ };
1154
+ function hasCode(error, code) {
1155
+ return error instanceof Error && "code" in error && error.code === code;
1156
+ }
1157
+ // src/adapters/node/node-deps.ts
1158
+ /** Wires the core to the real machine: Node file system, child processes, a JSON state file. */
1159
+ function createNodeDeps(options) {
1160
+ return {
1161
+ fs: new NodeFileSystem(),
1162
+ process: options.process ?? new NodeProcessRunner(),
1163
+ clock: { now: () => /* @__PURE__ */ new Date() },
1164
+ state: new JsonStateStore(join(options.home, "state.json")),
1165
+ events: options.events ?? { emit: () => {} },
1166
+ packageManagers: {
1167
+ npm,
1168
+ pnpm,
1169
+ yarn,
1170
+ bun
1171
+ },
1172
+ publisher: npmPublisher,
1173
+ integrations: builtInIntegrations,
1174
+ registryUrl: options.registry.url,
1175
+ registryCredentials: options.registry.credentials,
1176
+ home: options.home
1177
+ };
1178
+ }
1179
+ // src/adapters/node/node-library-watcher.ts
1180
+ /** Folders whose changes never mean the library's sources changed. */
1181
+ const IGNORED_FOLDERS = /* @__PURE__ */ new Set([
1182
+ "node_modules",
1183
+ ".git",
1184
+ ".angular",
1185
+ ".nx",
1186
+ ".cache",
1187
+ ".turbo",
1188
+ "coverage",
1189
+ "dist",
1190
+ "out-tsc",
1191
+ "tmp"
1192
+ ]);
1193
+ /** Editor droppings and build bookkeeping. */
1194
+ const IGNORED_FILE = /(^\.DS_Store$|\.swp$|\.swx$|~$|^4913$|\.tsbuildinfo$)/;
1195
+ /**
1196
+ * Watches a library's folder and reports a burst of changes as one, after a quiet period (ADR 0012).
1197
+ * Changes inside the publish folder are ignored even when it sits inside the library, or every build
1198
+ * would trigger the next one.
1199
+ */
1200
+ var NodeLibraryWatcher = class {
1201
+ #debounceMs;
1202
+ #strategy;
1203
+ #fsWatch;
1204
+ constructor(options = {}) {
1205
+ this.#debounceMs = options.debounceMs ?? 400;
1206
+ this.#strategy = options.strategy ?? (process.platform === "linux" ? "walk" : "recursive");
1207
+ this.#fsWatch = options.fsWatch ?? watch;
1208
+ }
1209
+ watch(library, onChange, onError) {
1210
+ const publishDir = relative(library.root, library.publishDir);
1211
+ const ignorePublishDir = publishDir !== "" && !publishDir.startsWith("..");
1212
+ let timer;
1213
+ let close = () => {};
1214
+ /** Whether a path relative to the root can hold the library's sources. */
1215
+ const relevant = (filename) => {
1216
+ if (filename === null || filename === "") return true;
1217
+ if (ignorePublishDir && (filename === publishDir || filename.startsWith(publishDir + sep))) return false;
1218
+ const segments = filename.split(sep);
1219
+ return !segments.some((segment) => IGNORED_FOLDERS.has(segment)) && !IGNORED_FILE.test(segments.at(-1) ?? "");
1220
+ };
1221
+ const changed = () => {
1222
+ clearTimeout(timer);
1223
+ timer = setTimeout(onChange, this.#debounceMs);
1224
+ };
1225
+ let ended = false;
1226
+ const fail = (error) => {
1227
+ if (ended) return;
1228
+ ended = true;
1229
+ clearTimeout(timer);
1230
+ close();
1231
+ onError(error);
1232
+ };
1233
+ try {
1234
+ close = this.#strategy === "walk" ? this.#walk(library.root, relevant, changed, fail) : this.#recursive(library.root, relevant, changed, fail);
1235
+ } catch (error) {
1236
+ setImmediate(() => fail(error instanceof Error ? error : new Error(String(error))));
1237
+ }
1238
+ return () => {
1239
+ ended = true;
1240
+ clearTimeout(timer);
1241
+ close();
1242
+ };
1243
+ }
1244
+ #recursive(root, relevant, changed, fail) {
1245
+ const watcher = this.#fsWatch(root, { recursive: true }, (_event, filename) => {
1246
+ if (relevant(filename)) changed();
1247
+ });
1248
+ watcher.on("error", fail);
1249
+ return () => watcher.close();
1250
+ }
1251
+ #walk(root, relevant, changed, fail) {
1252
+ /** Keyed by folder relative to the root, '' being the root itself. */
1253
+ const watchers = /* @__PURE__ */ new Map();
1254
+ let closed = false;
1255
+ const forget = (folder) => {
1256
+ for (const [key, watcher] of watchers) if (key === folder || key.startsWith(folder + sep)) {
1257
+ watcher.close();
1258
+ watchers.delete(key);
1259
+ }
1260
+ };
1261
+ /** Starts watching one folder. Throws when it cannot be watched, e.g. because it is gone. */
1262
+ const watchFolder = (folder) => {
1263
+ const watcher = this.#fsWatch(join(root, folder), (_event, filename) => {
1264
+ const entry = filename === null ? folder : join(folder, filename);
1265
+ if (!relevant(entry)) return;
1266
+ changed();
1267
+ if (filename !== null) add(entry);
1268
+ });
1269
+ watcher.on("error", (error) => {
1270
+ if (folder === "") fail(error);
1271
+ else forget(folder);
1272
+ });
1273
+ watchers.set(folder, watcher);
1274
+ };
1275
+ /** Watches the folders below one already watched, listing it after its watch starts so nothing is missed. */
1276
+ const addChildren = async (folder) => {
1277
+ let entries;
1278
+ try {
1279
+ entries = await readdir(join(root, folder), { withFileTypes: true });
1280
+ } catch (error) {
1281
+ if (folder === "") fail(error instanceof Error ? error : new Error(String(error)));
1282
+ else forget(folder);
1283
+ return;
1284
+ }
1285
+ for (const entry of entries) {
1286
+ const child = join(folder, entry.name);
1287
+ if (entry.isDirectory() && relevant(child)) await add(child);
1288
+ }
1289
+ };
1290
+ /** Watches a folder and the relevant folders below it; a name that is a file or gone is ignored. */
1291
+ const add = async (folder) => {
1292
+ if (closed || watchers.has(folder)) return;
1293
+ try {
1294
+ watchFolder(folder);
1295
+ } catch {
1296
+ return;
1297
+ }
1298
+ await addChildren(folder);
1299
+ };
1300
+ watchFolder("");
1301
+ addChildren("");
1302
+ return () => {
1303
+ closed = true;
1304
+ for (const watcher of watchers.values()) watcher.close();
1305
+ watchers.clear();
1306
+ };
1307
+ }
1308
+ };
1309
+ // src/adapters/registry/verdaccio-registry.ts
1310
+ const HOST$1 = "127.0.0.1";
1311
+ const USER = "dryfit";
1312
+ /**
1313
+ * The local registry (ADR 0002): Verdaccio, started in-process.
1314
+ *
1315
+ * Hardening beyond Verdaccio's defaults, because it serves unreleased and often private code:
1316
+ * - it listens on 127.0.0.1 only;
1317
+ * - its storage folder is private to the current user: it holds Verdaccio's token-signing secret;
1318
+ * - publishing needs HTTP Basic auth as the single `dryfit` user, whose random password is created on
1319
+ * every start and only ever held in memory (htpasswd keeps a hash). Registration is disabled and the
1320
+ * user exists before the port opens, so no other process can claim publish rights, and credentials
1321
+ * from an earlier start stop working;
1322
+ * - any request carrying an `Origin` header, or a `Host` other than the loopback address, is refused.
1323
+ * The npm CLI sends neither, while a web page always sends `Origin` cross-site and a DNS-rebinding
1324
+ * page sends a foreign `Host`; without this, any site you visit could read your dev builds through
1325
+ * Verdaccio's permissive CORS.
1326
+ */
1327
+ var VerdaccioRegistry = class VerdaccioRegistry {
1328
+ url;
1329
+ credentials;
1330
+ #server;
1331
+ constructor(server, url, credentials) {
1332
+ this.#server = server;
1333
+ this.url = url;
1334
+ this.credentials = credentials;
1335
+ }
1336
+ static async start(options) {
1337
+ await mkdir(options.storage, {
1338
+ recursive: true,
1339
+ mode: 448
1340
+ });
1341
+ await chmod(options.storage, 448);
1342
+ const credentials = {
1343
+ username: USER,
1344
+ password: randomBytes(32).toString("base64url")
1345
+ };
1346
+ const htpasswd = join(options.storage, "htpasswd");
1347
+ const entries = Object.entries(options.uplinks ?? {});
1348
+ const uplinks = Object.fromEntries(entries.map(([name, { url, auth }]) => [name, {
1349
+ url,
1350
+ timeout: "30s",
1351
+ max_fails: 2,
1352
+ ...auth && { auth }
1353
+ }]));
1354
+ const rule = (proxy) => ({
1355
+ access: options.requireAuthToRead ? "$authenticated" : "$all",
1356
+ publish: "$authenticated",
1357
+ unpublish: "$authenticated",
1358
+ ...proxy.length > 0 && { proxy: [...proxy] }
1359
+ });
1360
+ const scoped = entries.flatMap(([name, uplink]) => (uplink.scopes ?? []).map((scope) => [`${scope}/*`, rule([name])]));
1361
+ const general = entries.filter(([, uplink]) => !uplink.scopes?.length).map(([name]) => name);
1362
+ const server = await runServer({
1363
+ self_path: join(options.storage, "config.yaml"),
1364
+ storage: options.storage,
1365
+ auth: { htpasswd: {
1366
+ file: htpasswd,
1367
+ max_users: -1
1368
+ } },
1369
+ uplinks,
1370
+ packages: {
1371
+ ...Object.fromEntries(scoped),
1372
+ "**": rule(general)
1373
+ },
1374
+ web: { enable: false },
1375
+ log: {
1376
+ type: "stdout",
1377
+ format: "json",
1378
+ level: options.logLevel ?? "warn"
1379
+ }
1380
+ });
1381
+ try {
1382
+ guardAgainstBrowsers(server);
1383
+ const port = await listen$1(server, options.port);
1384
+ const hash = createHash("sha1").update(credentials.password).digest("base64");
1385
+ await writeFile(htpasswd, `${USER}:{SHA}${hash}\n`, { mode: 384 });
1386
+ await chmod(htpasswd, 384);
1387
+ return new VerdaccioRegistry(server, `http://${HOST$1}:${port}/`, credentials);
1388
+ } catch (error) {
1389
+ await close(server);
1390
+ throw error;
1391
+ }
1392
+ }
1393
+ async stop() {
1394
+ await close(this.#server);
1395
+ }
1396
+ };
1397
+ function guardAgainstBrowsers(server) {
1398
+ const handlers = server.listeners("request");
1399
+ server.removeAllListeners("request");
1400
+ server.on("request", (req, res) => {
1401
+ if (req.headers.origin !== void 0 || !isLoopbackHost$1(req.headers.host, server)) {
1402
+ res.writeHead(403, { "content-type": "text/plain" }).end("dryfit registry: browser requests are refused\n");
1403
+ return;
1404
+ }
1405
+ for (const handler of handlers) handler(req, res);
1406
+ });
1407
+ }
1408
+ function isLoopbackHost$1(host, server) {
1409
+ const { port } = server.address();
1410
+ return host === `${HOST$1}:${port}` || host === `localhost:${port}`;
1411
+ }
1412
+ function listen$1(server, port) {
1413
+ return new Promise((resolve, reject) => {
1414
+ const onError = (error) => {
1415
+ reject(new DryfitError("registry-failed", `The local registry could not start: ${error.code === "EADDRINUSE" ? `port ${port} is already in use` : error.message}`, { port }));
1416
+ };
1417
+ server.once("error", onError);
1418
+ server.listen(port, HOST$1, () => {
1419
+ server.off("error", onError);
1420
+ resolve(server.address().port);
1421
+ });
1422
+ });
1423
+ }
1424
+ function close(server) {
1425
+ return new Promise((resolve) => {
1426
+ if (!server.listening) return resolve();
1427
+ server.close(() => resolve());
1428
+ server.closeAllConnections();
1429
+ });
1430
+ }
1431
+ // src/daemon/schema.ts
1432
+ var ValidationError = class extends Error {
1433
+ name = "ValidationError";
1434
+ };
1435
+ const fail = (path, problem) => {
1436
+ throw new ValidationError(`${path || "(input)"}: ${problem}`);
1437
+ };
1438
+ const string$1 = () => ({
1439
+ json: {
1440
+ type: "string",
1441
+ minLength: 1
1442
+ },
1443
+ parse(value, path = "") {
1444
+ if (typeof value !== "string") return fail(path, "expected a string");
1445
+ if (value.length === 0) return fail(path, "must not be empty");
1446
+ return value;
1447
+ }
1448
+ });
1449
+ const path = () => ({
1450
+ json: {
1451
+ type: "string",
1452
+ pattern: "^/"
1453
+ },
1454
+ parse(value, at = "") {
1455
+ if (typeof value !== "string") return fail(at, "expected a string");
1456
+ if (!value.startsWith("/")) return fail(at, "expected an absolute path");
1457
+ return value;
1458
+ }
1459
+ });
1460
+ const boolean = () => ({
1461
+ json: { type: "boolean" },
1462
+ parse(value, path = "") {
1463
+ return typeof value === "boolean" ? value : fail(path, "expected true or false");
1464
+ }
1465
+ });
1466
+ const array = (item) => ({
1467
+ json: {
1468
+ type: "array",
1469
+ items: item.json
1470
+ },
1471
+ parse(value, path = "") {
1472
+ if (!Array.isArray(value)) return fail(path, "expected a list");
1473
+ return value.map((entry, index) => item.parse(entry, `${path}[${index}]`));
1474
+ }
1475
+ });
1476
+ const optional = (schema) => ({
1477
+ optional: true,
1478
+ json: schema.json,
1479
+ parse: (value, path) => value === void 0 ? void 0 : schema.parse(value, path)
1480
+ });
1481
+ const object = (shape) => {
1482
+ const required = Object.entries(shape).filter(([, schema]) => !("optional" in schema)).map(([key]) => key);
1483
+ return {
1484
+ json: {
1485
+ type: "object",
1486
+ additionalProperties: false,
1487
+ required,
1488
+ properties: Object.fromEntries(Object.entries(shape).map(([key, schema]) => [key, schema.json]))
1489
+ },
1490
+ parse(value, path = "") {
1491
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return fail(path, "expected an object");
1492
+ const at = (key) => path ? `${path}.${key}` : key;
1493
+ const record = value;
1494
+ for (const key of Object.keys(record)) if (!Object.hasOwn(shape, key)) fail(at(key), "unknown field");
1495
+ const result = {};
1496
+ for (const [key, schema] of Object.entries(shape)) {
1497
+ if (record[key] === void 0 && required.includes(key)) fail(at(key), "required");
1498
+ const parsed = schema.parse(record[key], at(key));
1499
+ if (parsed !== void 0) result[key] = parsed;
1500
+ }
1501
+ return result;
1502
+ }
1503
+ };
1504
+ };
1505
+ const s = {
1506
+ string: string$1,
1507
+ path,
1508
+ boolean,
1509
+ array,
1510
+ optional,
1511
+ object
1512
+ };
1513
+ // src/daemon/api.ts
1514
+ const operations = {
1515
+ status: s.object({}),
1516
+ register: s.object({
1517
+ root: s.path(),
1518
+ publishDir: s.optional(s.path()),
1519
+ build: s.optional(s.object({
1520
+ command: s.string(),
1521
+ args: s.array(s.string())
1522
+ }))
1523
+ }),
1524
+ unregister: s.object({ library: s.string() }),
1525
+ inspect: s.object({ root: s.path() }),
1526
+ sync: s.object({ library: s.string() }),
1527
+ watch: s.object({
1528
+ library: s.string(),
1529
+ enabled: s.boolean()
1530
+ }),
1531
+ discover: s.object({ library: s.optional(s.string()) }),
1532
+ link: s.object({
1533
+ library: s.string(),
1534
+ consumer: s.path(),
1535
+ guard: s.optional(s.boolean())
1536
+ }),
1537
+ restore: s.object({
1538
+ consumer: s.path(),
1539
+ library: s.optional(s.string()),
1540
+ force: s.optional(s.boolean())
1541
+ }),
1542
+ saveGroup: s.object({
1543
+ name: s.string(),
1544
+ consumers: s.array(s.path())
1545
+ }),
1546
+ deleteGroup: s.object({ name: s.string() }),
1547
+ linkGroup: s.object({
1548
+ group: s.string(),
1549
+ library: s.string()
1550
+ }),
1551
+ restoreGroup: s.object({
1552
+ group: s.string(),
1553
+ force: s.optional(s.boolean())
1554
+ }),
1555
+ roots: s.object({}),
1556
+ setRoots: s.object({ roots: s.array(s.path()) }),
1557
+ shutdown: s.object({})
1558
+ };
1559
+ function isOperationName(name) {
1560
+ return Object.hasOwn(operations, name);
1561
+ }
1562
+ // src/daemon/event-hub.ts
1563
+ /**
1564
+ * Fans events out to every connected client and keeps a bounded history, so a client that reconnects
1565
+ * with `Last-Event-ID` catches up on what it missed instead of showing stale status.
1566
+ */
1567
+ var EventHub = class {
1568
+ #now;
1569
+ #capacity;
1570
+ #history = [];
1571
+ #listeners = /* @__PURE__ */ new Set();
1572
+ #nextId = 1;
1573
+ constructor(options = {}) {
1574
+ this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
1575
+ this.#capacity = options.capacity ?? 500;
1576
+ }
1577
+ emit(event) {
1578
+ const stamped = {
1579
+ id: this.#nextId++,
1580
+ at: this.#now().toISOString(),
1581
+ ...event
1582
+ };
1583
+ this.#history.push(stamped);
1584
+ if (this.#history.length > this.#capacity) this.#history.shift();
1585
+ for (const listener of this.#listeners) deliver(listener, stamped);
1586
+ }
1587
+ /**
1588
+ * Listens for new events; with `after`, first replays the kept history newer than that id. An id
1589
+ * this hub never issued comes from a daemon that has since restarted, so all history is replayed.
1590
+ */
1591
+ subscribe(listener, options = {}) {
1592
+ if (options.after !== void 0) {
1593
+ const after = options.after < this.#nextId ? options.after : 0;
1594
+ for (const event of this.#history) if (event.id > after) deliver(listener, event);
1595
+ }
1596
+ this.#listeners.add(listener);
1597
+ return () => this.#listeners.delete(listener);
1598
+ }
1599
+ };
1600
+ function deliver(listener, event) {
1601
+ try {
1602
+ listener(event);
1603
+ } catch {}
1604
+ }
1605
+ // src/daemon/http-server.ts
1606
+ const MAX_BODY_BYTES = 1e6;
1607
+ /** Unsent event output a slow client may hold before its stream is dropped. */
1608
+ const MAX_UNSENT_EVENT_BYTES = 4e6;
1609
+ /**
1610
+ * The daemon's HTTP API (ADR 0003, ADR 0012). Before anything else it refuses requests a browser could
1611
+ * make (an `Origin` header or a foreign `Host`), then everything but `/v1/health` without the bearer
1612
+ * token: an API that can publish and install runs arbitrary code, so no web page may reach it.
1613
+ */
1614
+ function createApiServer(options) {
1615
+ const expected = Buffer.from(`Bearer ${options.token}`);
1616
+ const { onError } = options;
1617
+ const server = createServer((req, res) => {
1618
+ if (req.headers.origin !== void 0 || !isLoopbackHost(req.headers.host, server)) return sendError(res, 403, "forbidden", "dryfit refuses requests made by browsers");
1619
+ const path = (req.url ?? "").split("?")[0] ?? "";
1620
+ if (req.method === "GET" && path === "/v1/health") return sendJson(res, 200, options.health());
1621
+ const auth = Buffer.from(req.headers.authorization ?? "");
1622
+ if (auth.length !== expected.length || !timingSafeEqual(auth, expected)) return sendError(res, 401, "unauthorized", "Missing or wrong dryfit token");
1623
+ if (req.method === "GET" && path === "/v1/events") return streamEvents(req, res, options);
1624
+ const operation = req.method === "POST" ? /^\/v1\/([A-Za-z]+)$/.exec(path)?.[1] : void 0;
1625
+ if (operation === void 0 || !isOperationName(operation)) return sendError(res, 404, "not-found", `No route for ${req.method} ${path}`);
1626
+ handleOperation(req, res, operation, options, onError);
1627
+ });
1628
+ return server;
1629
+ }
1630
+ function handleOperation(req, res, operation, options, onError) {
1631
+ const chunks = [];
1632
+ let size = 0;
1633
+ req.on("data", (chunk) => {
1634
+ size += chunk.length;
1635
+ if (size <= MAX_BODY_BYTES) chunks.push(chunk);
1636
+ });
1637
+ req.on("end", async () => {
1638
+ if (size > MAX_BODY_BYTES) return sendError(res, 413, "payload-too-large", "The request body is too large");
1639
+ try {
1640
+ const text = Buffer.concat(chunks).toString("utf8");
1641
+ let body;
1642
+ try {
1643
+ body = text.length === 0 ? {} : JSON.parse(text);
1644
+ } catch {
1645
+ return sendError(res, 400, "invalid-request", "The request body is not valid JSON");
1646
+ }
1647
+ const input = operations[operation].parse(body);
1648
+ sendJson(res, 200, await options.service.call(operation, input));
1649
+ } catch (error) {
1650
+ if (error instanceof ValidationError) return sendError(res, 400, "invalid-request", error.message);
1651
+ if (error instanceof DryfitError) return sendError(res, error.code === "daemon-stopping" ? 503 : 422, error.code, error.message, error.details);
1652
+ onError(error);
1653
+ sendError(res, 500, "internal", "dryfit hit an unexpected error; see the daemon log");
1654
+ }
1655
+ });
1656
+ }
1657
+ function streamEvents(req, res, options) {
1658
+ res.writeHead(200, {
1659
+ "content-type": "text/event-stream",
1660
+ "cache-control": "no-cache",
1661
+ connection: "keep-alive"
1662
+ });
1663
+ res.write(": dryfit events\n\n");
1664
+ const send = (text) => {
1665
+ if (res.writableLength > MAX_UNSENT_EVENT_BYTES) res.destroy();
1666
+ else res.write(text);
1667
+ };
1668
+ const lastId = Number(req.headers["last-event-id"]);
1669
+ const unsubscribe = options.hub.subscribe((event) => send(`id: ${event.id}\ndata: ${JSON.stringify(event)}\n\n`), Number.isInteger(lastId) && lastId >= 0 ? { after: lastId } : {});
1670
+ const heartbeat = setInterval(() => send(": ping\n\n"), options.heartbeatMs ?? 15e3);
1671
+ heartbeat.unref();
1672
+ res.on("close", () => {
1673
+ clearInterval(heartbeat);
1674
+ unsubscribe();
1675
+ });
1676
+ }
1677
+ function isLoopbackHost(host, server) {
1678
+ const { port } = server.address();
1679
+ return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
1680
+ }
1681
+ function sendJson(res, status, body) {
1682
+ res.writeHead(status, { "content-type": "application/json" }).end(JSON.stringify(body));
1683
+ }
1684
+ function sendError(res, status, code, message, details = {}) {
1685
+ sendJson(res, status, { error: {
1686
+ code,
1687
+ message,
1688
+ details
1689
+ } });
1690
+ }
1691
+ // src/core/project/manifest.ts
1692
+ /** Reads `<dir>/package.json`. Throws `invalid-manifest` when it is missing or not a JSON object. */
1693
+ async function readManifest(fs, dir) {
1694
+ const path = joinPath(dir, "package.json");
1695
+ const text = await fs.readText(path);
1696
+ if (text === void 0) throw new DryfitError("invalid-manifest", `No package.json found in ${dir}`, { path });
1697
+ const parsed = tryParseJson(text);
1698
+ if (!isRecord(parsed)) throw new DryfitError("invalid-manifest", `${path} is not a valid JSON object`, { path });
1699
+ return {
1700
+ path,
1701
+ manifest: parsed,
1702
+ text
1703
+ };
1704
+ }
1705
+ /** Serialises a manifest the way npm does, keeping the original file's indentation. */
1706
+ function formatManifest(manifest, original) {
1707
+ return `${JSON.stringify(manifest, null, original === void 0 ? 2 : detectIndent(original))}\n`;
1708
+ }
1709
+ /**
1710
+ * Where a manifest declares a package. Installable fields win over `peerDependencies`, because a
1711
+ * library that peers on a package usually also lists it in devDependencies to develop against it.
1712
+ */
1713
+ function findDependency(manifest, packageName) {
1714
+ const order = [...DEPENDENCY_FIELDS.filter((field) => field !== "peerDependencies"), "peerDependencies"];
1715
+ for (const field of order) {
1716
+ const range = manifest[field]?.[packageName];
1717
+ if (typeof range === "string") return {
1718
+ field,
1719
+ range
1720
+ };
1721
+ }
1722
+ }
1723
+ // src/core/project/detect-library-build.ts
1724
+ /** How far up from a library to look for an Nx or Angular workspace. */
1725
+ const MAX_WORKSPACE_DEPTH = 6;
1726
+ /**
1727
+ * Works out how a library is built and what gets published, so `dryfit add` needs no flags for the
1728
+ * common cases: an Nx library, an Angular CLI library (both usually ng-packagr), or a package with a
1729
+ * `build` script. Flags passed by the user always win over this.
1730
+ */
1731
+ async function detectLibraryBuild(fs, root) {
1732
+ const libraryRoot = joinPath(root);
1733
+ const { manifest } = await readManifest(fs, libraryRoot);
1734
+ const ngPackage = await readJson(fs, joinPath(libraryRoot, "ng-package.json"));
1735
+ const ngDest = ngPackage === void 0 ? void 0 : resolvePath(libraryRoot, typeof ngPackage.dest === "string" ? ngPackage.dest : "dist");
1736
+ const project = await readJson(fs, joinPath(libraryRoot, "project.json"));
1737
+ const nxRoot = project && await findUp(fs, libraryRoot, "nx.json");
1738
+ if (project && nxRoot !== void 0) {
1739
+ const name = typeof project.name === "string" ? project.name : String(manifest.name);
1740
+ const projectRoot = relativeInside(nxRoot, libraryRoot) ?? "";
1741
+ return {
1742
+ kind: "nx",
1743
+ build: {
1744
+ command: joinPath(nxRoot, "node_modules/.bin/nx"),
1745
+ args: ["build", name]
1746
+ },
1747
+ publishDir: ngDest ?? nxOutputPath(project, nxRoot, projectRoot) ?? libraryRoot
1748
+ };
1749
+ }
1750
+ const angularRoot = await findUp(fs, libraryRoot, "angular.json");
1751
+ if (angularRoot !== void 0) {
1752
+ const workspace = await readJson(fs, joinPath(angularRoot, "angular.json"));
1753
+ const relative = relativeInside(angularRoot, libraryRoot);
1754
+ const projects = isRecord(workspace?.projects) ? workspace.projects : {};
1755
+ const match = Object.entries(projects).find(([, config]) => isRecord(config) && typeof config.root === "string" && joinPath("/", config.root) === joinPath("/", relative ?? "-"));
1756
+ if (match) return {
1757
+ kind: "angular",
1758
+ build: {
1759
+ command: joinPath(angularRoot, "node_modules/.bin/ng"),
1760
+ args: ["build", match[0]]
1761
+ },
1762
+ publishDir: ngDest ?? libraryRoot
1763
+ };
1764
+ }
1765
+ if (typeof (isRecord(manifest.scripts) ? manifest.scripts : {}).build === "string") return {
1766
+ kind: "npm-script",
1767
+ build: {
1768
+ command: "npm",
1769
+ args: ["run", "build"]
1770
+ },
1771
+ publishDir: libraryRoot
1772
+ };
1773
+ return {
1774
+ kind: "none",
1775
+ publishDir: libraryRoot
1776
+ };
1777
+ }
1778
+ function nxOutputPath(project, workspace, projectRoot) {
1779
+ const targets = isRecord(project.targets) ? project.targets : {};
1780
+ const build = isRecord(targets.build) ? targets.build : {};
1781
+ const options = isRecord(build.options) ? build.options : {};
1782
+ if (typeof options.outputPath !== "string") return void 0;
1783
+ return resolvePath(workspace, options.outputPath.replaceAll("{workspaceRoot}", workspace).replaceAll("{projectRoot}", projectRoot));
1784
+ }
1785
+ async function findUp(fs, from, file) {
1786
+ let dir = from;
1787
+ for (let depth = 0; depth <= MAX_WORKSPACE_DEPTH; depth += 1) {
1788
+ if (await fs.exists(joinPath(dir, file))) return dir;
1789
+ if (dir === "/") return void 0;
1790
+ dir = joinPath(dir, "..");
1791
+ }
1792
+ }
1793
+ async function readJson(fs, path) {
1794
+ const text = await fs.readText(path);
1795
+ const parsed = text === void 0 ? void 0 : tryParseJson(text);
1796
+ return isRecord(parsed) ? parsed : void 0;
1797
+ }
1798
+ // src/core/status/coherence.ts
1799
+ /**
1800
+ * Consumers saved in one group run together, such as a federation host and its remotes. If they run
1801
+ * different dev versions of one library, what you see in the browser is a mix of both (ADR 0005).
1802
+ * Only installed links count: a pending or failed one has no version to compare yet.
1803
+ */
1804
+ function coherenceWarnings(state) {
1805
+ const warnings = [];
1806
+ for (const group of state.groups) {
1807
+ const members = new Set(group.consumers);
1808
+ const byLibrary = /* @__PURE__ */ new Map();
1809
+ for (const link of state.links) {
1810
+ if (!members.has(link.consumer) || link.status !== "installed" || !link.installedVersion) continue;
1811
+ const versions = byLibrary.get(link.library) ?? [];
1812
+ versions.push({
1813
+ consumer: link.consumer,
1814
+ version: link.installedVersion
1815
+ });
1816
+ byLibrary.set(link.library, versions);
1817
+ }
1818
+ for (const [library, versions] of byLibrary) if (new Set(versions.map((entry) => entry.version)).size > 1) warnings.push({
1819
+ group: group.name,
1820
+ library,
1821
+ versions
1822
+ });
1823
+ }
1824
+ return warnings;
1825
+ }
1826
+ // src/core/project/load-project.ts
1827
+ /**
1828
+ * Gathers what integrations and use cases need to know about a project folder in one pass: its
1829
+ * manifest, root entries, and any root config files the given integrations asked for.
1830
+ */
1831
+ async function loadProject(fs, root, integrations = []) {
1832
+ const [{ manifest }, entries] = await Promise.all([readManifest(fs, root), fs.readDir(root)]);
1833
+ const rootFiles = entries.map((entry) => entry.name);
1834
+ const wanted = new Set(integrations.flatMap((integration) => integration.configFiles ?? []));
1835
+ const configs = /* @__PURE__ */ new Map();
1836
+ for (const file of wanted) {
1837
+ if (!rootFiles.includes(file)) continue;
1838
+ const text = await fs.readText(joinPath(root, file));
1839
+ const parsed = text === void 0 ? void 0 : tryParseJson(text);
1840
+ if (parsed !== void 0) configs.set(file, parsed);
1841
+ }
1842
+ return {
1843
+ root,
1844
+ manifest,
1845
+ rootFiles,
1846
+ configs
1847
+ };
1848
+ }
1849
+ // src/core/use-cases/discover-consumers.ts
1850
+ const SKIPPED_FOLDERS = /* @__PURE__ */ new Set([
1851
+ "node_modules",
1852
+ "dist",
1853
+ "build",
1854
+ "coverage"
1855
+ ]);
1856
+ /**
1857
+ * Lists projects that depend on a registered library (ADR 0005). Read-only: it never changes a
1858
+ * project. The search stops at the first package.json in a branch, because that folder owns the
1859
+ * lockfile and is where an install has to run.
1860
+ */
1861
+ async function discoverConsumers(deps, { roots, maxDepth = 3 }) {
1862
+ const { libraries } = await deps.state.load();
1863
+ if (libraries.length === 0) return [];
1864
+ const libraryRoots = new Set(libraries.map((library) => library.root));
1865
+ const found = [];
1866
+ const visit = async (dir, depth) => {
1867
+ const entries = await deps.fs.readDir(dir);
1868
+ if (entries.some((entry) => entry.name === "package.json" && !entry.isDirectory)) {
1869
+ if (libraryRoots.has(dir)) return;
1870
+ const project = await tryLoadProject(deps, dir);
1871
+ const consumer = project && asConsumer(project, libraries);
1872
+ if (consumer) found.push(consumer);
1873
+ return;
1874
+ }
1875
+ if (depth >= maxDepth) return;
1876
+ for (const entry of entries) if (entry.isDirectory && !entry.name.startsWith(".") && !SKIPPED_FOLDERS.has(entry.name)) await visit(joinPath(dir, entry.name), depth + 1);
1877
+ };
1878
+ for (const root of roots) await visit(joinPath(root), 0);
1879
+ return found.sort((a, b) => a.root < b.root ? -1 : a.root > b.root ? 1 : 0);
1880
+ }
1881
+ async function tryLoadProject(deps, dir) {
1882
+ try {
1883
+ return await loadProject(deps.fs, dir);
1884
+ } catch (error) {
1885
+ if (error instanceof DryfitError && error.code === "invalid-manifest") return void 0;
1886
+ throw error;
1887
+ }
1888
+ }
1889
+ function asConsumer(project, libraries) {
1890
+ const used = libraries.flatMap(({ name }) => {
1891
+ const declaration = findDependency(project.manifest, name);
1892
+ return declaration ? [{
1893
+ name,
1894
+ ...declaration
1895
+ }] : [];
1896
+ });
1897
+ if (used.length === 0) return void 0;
1898
+ return {
1899
+ root: project.root,
1900
+ name: project.manifest.name,
1901
+ packageManager: detectPackageManager({
1902
+ files: project.rootFiles,
1903
+ manifest: project.manifest
1904
+ }),
1905
+ libraries: used
1906
+ };
1907
+ }
1908
+ // src/core/use-cases/install-link.ts
1909
+ /**
1910
+ * Installs one dev version into one linked consumer, then clears the caches that would hide it
1911
+ * (ADR 0007). Every expected failure is an outcome, not an exception: a consumer that no longer
1912
+ * depends on the library, has an unsupported package manager, or whose install fails is marked
1913
+ * `failed`, and the others still get installed. The snapshot still allows a restore.
1914
+ */
1915
+ async function installLink(deps, { library, consumer, version }) {
1916
+ const fail = async (output) => {
1917
+ deps.events.emit({
1918
+ type: "install:failed",
1919
+ library: library.name,
1920
+ consumer,
1921
+ version,
1922
+ output
1923
+ });
1924
+ const link = await saveLink(deps, {
1925
+ library: library.name,
1926
+ consumer,
1927
+ status: "failed"
1928
+ });
1929
+ return {
1930
+ outcome: {
1931
+ consumer,
1932
+ ok: false,
1933
+ version,
1934
+ output
1935
+ },
1936
+ link
1937
+ };
1938
+ };
1939
+ let target;
1940
+ try {
1941
+ target = await resolveTarget(deps, library, consumer);
1942
+ } catch (error) {
1943
+ if (error instanceof DryfitError) return fail(error.message);
1944
+ throw error;
1945
+ }
1946
+ const { project, declaration, adapter } = target;
1947
+ deps.events.emit({
1948
+ type: "install:started",
1949
+ library: library.name,
1950
+ consumer,
1951
+ version
1952
+ });
1953
+ const result = await runSafely(deps, adapter.install({
1954
+ cwd: consumer,
1955
+ packageName: library.name,
1956
+ version,
1957
+ dependencyField: declaration.field,
1958
+ registryUrl: deps.registryUrl
1959
+ }));
1960
+ if (result.exitCode !== 0) return fail(commandOutput(result));
1961
+ const clearedCaches = cachePathsFor(project, deps.integrations);
1962
+ for (const path of clearedCaches) await deps.fs.remove(joinPath(consumer, path));
1963
+ deps.events.emit({
1964
+ type: "install:succeeded",
1965
+ library: library.name,
1966
+ consumer,
1967
+ version
1968
+ });
1969
+ if (clearedCaches.length > 0) deps.events.emit({
1970
+ type: "caches:cleared",
1971
+ consumer,
1972
+ paths: clearedCaches
1973
+ });
1974
+ const link = await saveLink(deps, {
1975
+ library: library.name,
1976
+ consumer,
1977
+ status: "installed",
1978
+ installedVersion: version
1979
+ });
1980
+ return {
1981
+ outcome: {
1982
+ consumer,
1983
+ ok: true,
1984
+ version,
1985
+ clearedCaches
1986
+ },
1987
+ link
1988
+ };
1989
+ }
1990
+ async function resolveTarget(deps, library, consumer) {
1991
+ const project = await loadProject(deps.fs, consumer, deps.integrations);
1992
+ const declaration = findDependency(project.manifest, library.name);
1993
+ if (!declaration) throw new DryfitError("not-a-consumer", `${consumer} no longer depends on ${library.name}`, {
1994
+ consumer,
1995
+ library: library.name
1996
+ });
1997
+ return {
1998
+ project,
1999
+ declaration,
2000
+ adapter: adapterFor(deps, project)
2001
+ };
2002
+ }
2003
+ /** Writes a link against freshly loaded state, so concurrent edits to other records survive. */
2004
+ async function saveLink(deps, link) {
2005
+ const state = await deps.state.load();
2006
+ const previous = state.links.find((candidate) => sameLink(candidate, link));
2007
+ const merged = {
2008
+ ...previous,
2009
+ ...link,
2010
+ ...link.status === "failed" && { installedVersion: previous?.installedVersion }
2011
+ };
2012
+ await deps.state.save(withLink(state, merged));
2013
+ return merged;
2014
+ }
2015
+ // src/core/use-cases/link-consumer.ts
2016
+ /**
2017
+ * Opts a consumer in to receiving dev versions of a library (ADR 0005). The consumer's manifest and
2018
+ * lockfiles are snapshotted before anything changes; if the library has been published before, its
2019
+ * latest dev version is installed straight away.
2020
+ */
2021
+ async function linkConsumer(deps, input) {
2022
+ const consumer = joinPath(input.consumer);
2023
+ const state = await deps.state.load();
2024
+ const library = requireLibrary(state, input.library);
2025
+ const project = await loadProject(deps.fs, consumer);
2026
+ if (!findDependency(project.manifest, library.name)) throw new DryfitError("not-a-consumer", `${consumer} does not depend on ${library.name}`, {
2027
+ consumer,
2028
+ library: library.name
2029
+ });
2030
+ const adapter = adapterFor(deps, project);
2031
+ const existing = state.links.find((link) => sameLink(link, {
2032
+ library: library.name,
2033
+ consumer
2034
+ }));
2035
+ if (existing) return existing;
2036
+ if (!state.links.some((link) => link.consumer === consumer)) await takeSnapshot(deps, project, adapter);
2037
+ const link = {
2038
+ library: library.name,
2039
+ consumer,
2040
+ status: "pending"
2041
+ };
2042
+ await deps.state.save(withLink(await deps.state.load(), link));
2043
+ if (library.lastPublishedVersion === void 0) return link;
2044
+ return (await installLink(deps, {
2045
+ library,
2046
+ consumer,
2047
+ version: library.lastPublishedVersion
2048
+ })).link;
2049
+ }
2050
+ /**
2051
+ * Taken when a consumer's first library is linked, replacing any leftover snapshot (from a restore
2052
+ * that was interrupted) because only the current files reflect what the user has committed since.
2053
+ * Later links into the same consumer must not take one: by then the files contain dryfit's edits.
2054
+ */
2055
+ async function takeSnapshot(deps, project, adapter) {
2056
+ const dir = snapshotDir(deps, project.root);
2057
+ const lockfiles = adapter.lockfiles.filter((file) => project.rootFiles.includes(file));
2058
+ await deps.fs.remove(dir);
2059
+ for (const file of ["package.json", ...lockfiles]) {
2060
+ const text = await deps.fs.readText(joinPath(project.root, file));
2061
+ if (text !== void 0) await deps.fs.writeText(joinPath(dir, file), text);
2062
+ }
2063
+ const meta = {
2064
+ consumer: project.root,
2065
+ packageManager: adapter.name,
2066
+ lockfiles,
2067
+ createdAt: deps.clock.now().toISOString()
2068
+ };
2069
+ await deps.fs.writeText(joinPath(dir, "meta.json"), `${JSON.stringify(meta, null, 2)}\n`);
2070
+ }
2071
+ // src/core/use-cases/restore-consumer.ts
2072
+ /**
2073
+ * Returns a consumer to exactly the state it was in before its first link (ADR 0005): manifest and
2074
+ * lockfiles are written back from the snapshot, then a clean install makes node_modules match them.
2075
+ *
2076
+ * Files are restored first and unconditionally, so even if the clean install fails the repository is
2077
+ * already correct and the user only has to rerun the install. Only package.json is checked for user
2078
+ * changes; lockfile changes made while linked are reverted by design (see ADR 0005).
2079
+ *
2080
+ * With `library`, only that library goes back to its release. The consumer is restored as above,
2081
+ * then the dev builds of its other linked libraries are installed again at the versions they had, and
2082
+ * the snapshot is kept for them. One snapshot per consumer keeps the lockfile exact for the library
2083
+ * restored, at the cost of a second install.
2084
+ */
2085
+ async function restoreConsumer(deps, input) {
2086
+ const consumer = joinPath(input.consumer);
2087
+ const dir = snapshotDir(deps, consumer);
2088
+ const metaText = await deps.fs.readText(joinPath(dir, "meta.json"));
2089
+ const snapshotManifest = await deps.fs.readText(joinPath(dir, "package.json"));
2090
+ if (metaText === void 0 || snapshotManifest === void 0) throw new DryfitError("snapshot-missing", `${consumer} has no dryfit snapshot to restore`, { consumer });
2091
+ const meta = JSON.parse(metaText);
2092
+ const adapter = deps.packageManagers[meta.packageManager];
2093
+ if (!adapter) throw new DryfitError("unsupported-package-manager", `No adapter for ${meta.packageManager}`, { consumer });
2094
+ const links = (await deps.state.load()).links.filter((link) => link.consumer === consumer);
2095
+ const linkedLibraries = links.map((link) => link.library);
2096
+ if (input.library !== void 0 && !linkedLibraries.includes(input.library)) throw new DryfitError("invalid-request", `${input.library} is not linked into ${consumer}`, {
2097
+ consumer,
2098
+ library: input.library
2099
+ });
2100
+ const kept = input.library === void 0 ? [] : links.filter((link) => link.library !== input.library);
2101
+ if (!input.force) {
2102
+ if (userControlled(await deps.fs.readText(joinPath(consumer, "package.json")) ?? "", linkedLibraries) !== userControlled(snapshotManifest, linkedLibraries)) throw new DryfitError("manifest-drifted", `${consumer}/package.json has changes dryfit did not make. Commit or move them, or restore with force.`, { consumer });
2103
+ }
2104
+ await deps.fs.writeText(joinPath(consumer, "package.json"), snapshotManifest);
2105
+ for (const lockfile of adapter.lockfiles) {
2106
+ const saved = meta.lockfiles.includes(lockfile) ? await deps.fs.readText(joinPath(dir, lockfile)) : void 0;
2107
+ if (saved === void 0) await deps.fs.remove(joinPath(consumer, lockfile));
2108
+ else await deps.fs.writeText(joinPath(consumer, lockfile), saved);
2109
+ }
2110
+ const result = await runSafely(deps, adapter.cleanInstall({
2111
+ cwd: consumer,
2112
+ hasLockfile: meta.lockfiles.length > 0
2113
+ }));
2114
+ for (const lockfile of adapter.lockfiles) if (!meta.lockfiles.includes(lockfile)) await deps.fs.remove(joinPath(consumer, lockfile));
2115
+ const caches = cachePathsFor(await loadProject(deps.fs, consumer, deps.integrations), deps.integrations);
2116
+ for (const path of caches) await deps.fs.remove(joinPath(consumer, path));
2117
+ if (caches.length > 0) deps.events.emit({
2118
+ type: "caches:cleared",
2119
+ consumer,
2120
+ paths: caches
2121
+ });
2122
+ const ok = result.exitCode === 0;
2123
+ if (input.library !== void 0 && kept.length > 0) {
2124
+ await relinkOthers(deps, consumer, input.library, ok);
2125
+ deps.events.emit({
2126
+ type: "consumer:restored",
2127
+ consumer,
2128
+ library: input.library,
2129
+ ok
2130
+ });
2131
+ return ok ? { ok } : {
2132
+ ok,
2133
+ output: commandOutput(result)
2134
+ };
2135
+ }
2136
+ const latest = await deps.state.load();
2137
+ await deps.state.save({
2138
+ ...latest,
2139
+ links: latest.links.filter((link) => link.consumer !== consumer)
2140
+ });
2141
+ await deps.fs.remove(dir);
2142
+ deps.events.emit({
2143
+ type: "consumer:restored",
2144
+ consumer,
2145
+ ok
2146
+ });
2147
+ return ok ? { ok } : {
2148
+ ok,
2149
+ output: commandOutput(result)
2150
+ };
2151
+ }
2152
+ /**
2153
+ * After a whole-consumer restore made for one library: drops that library's link and puts the other
2154
+ * libraries' dev builds back. Their links are pending until reinstalled, since the files now hold the
2155
+ * releases; when the clean install failed they stay pending, for the next sync.
2156
+ */
2157
+ async function relinkOthers(deps, consumer, restored, installed) {
2158
+ const state = await deps.state.load();
2159
+ const others = state.links.filter((link) => link.consumer === consumer && link.library !== restored);
2160
+ await deps.state.save({
2161
+ ...state,
2162
+ links: [...state.links.filter((link) => link.consumer !== consumer), ...others.map(({ installedVersion: _, ...link }) => ({
2163
+ ...link,
2164
+ status: "pending"
2165
+ }))]
2166
+ });
2167
+ if (!installed) return;
2168
+ for (const link of others) {
2169
+ if (link.installedVersion === void 0) continue;
2170
+ await installLink(deps, {
2171
+ library: requireLibrary(state, link.library),
2172
+ consumer,
2173
+ version: link.installedVersion
2174
+ });
2175
+ }
2176
+ }
2177
+ /**
2178
+ * A manifest reduced to what the user controls, for drift detection: entries for linked libraries are
2179
+ * removed (dryfit rewrote those), dependency fields left empty by that are dropped (a package manager
2180
+ * may have created them), and keys are sorted (package managers reorder them). Unparseable text is
2181
+ * compared as-is.
2182
+ */
2183
+ function userControlled(text, libraries) {
2184
+ const manifest = tryParseJson(text);
2185
+ if (!isRecord(manifest)) return text;
2186
+ const reduced = { ...manifest };
2187
+ for (const field of DEPENDENCY_FIELDS) {
2188
+ const entries = manifest[field];
2189
+ if (!isRecord(entries)) continue;
2190
+ const kept = Object.entries(entries).filter(([name]) => !libraries.includes(name));
2191
+ if (kept.length === 0) delete reduced[field];
2192
+ else reduced[field] = Object.fromEntries(kept);
2193
+ }
2194
+ return stableStringify(reduced);
2195
+ }
2196
+ // src/core/use-cases/groups.ts
2197
+ /** Saves consumers that run together under a name, replacing any group of that name (ADR 0005). */
2198
+ async function saveGroup(deps, input) {
2199
+ const name = input.name.trim();
2200
+ const consumers = [...new Set(input.consumers.map((consumer) => joinPath(consumer)))];
2201
+ if (name.length === 0) throw new DryfitError("invalid-group", "A group needs a name", {});
2202
+ if (consumers.length === 0) throw new DryfitError("invalid-group", `Group ${name} needs at least one consumer`, { group: name });
2203
+ const group = {
2204
+ name,
2205
+ consumers
2206
+ };
2207
+ const state = await deps.state.load();
2208
+ const others = state.groups.filter((candidate) => candidate.name !== name);
2209
+ await deps.state.save({
2210
+ ...state,
2211
+ groups: [...others, group]
2212
+ });
2213
+ return group;
2214
+ }
2215
+ async function deleteGroup(deps, { name }) {
2216
+ const state = await deps.state.load();
2217
+ requireGroup(state, name);
2218
+ await deps.state.save({
2219
+ ...state,
2220
+ groups: state.groups.filter((group) => group.name !== name)
2221
+ });
2222
+ }
2223
+ function requireGroup(state, name) {
2224
+ const group = state.groups.find((candidate) => candidate.name === name);
2225
+ if (!group) throw new DryfitError("group-not-found", `No group named ${name} is saved`, { group: name });
2226
+ return group;
2227
+ }
2228
+ /**
2229
+ * Links a library into every member of a group, one at a time. A member that cannot be linked (it does
2230
+ * not use the library, or is not a project) is skipped with the reason, so one odd member does not
2231
+ * block the rest.
2232
+ */
2233
+ async function linkGroup(deps, input) {
2234
+ const state = await deps.state.load();
2235
+ const group = requireGroup(state, input.group);
2236
+ requireLibrary(state, input.library);
2237
+ const outcomes = [];
2238
+ for (const consumer of group.consumers) try {
2239
+ await linkConsumer(deps, {
2240
+ library: input.library,
2241
+ consumer
2242
+ });
2243
+ outcomes.push({
2244
+ consumer,
2245
+ status: "done"
2246
+ });
2247
+ } catch (error) {
2248
+ if (!(error instanceof DryfitError)) throw error;
2249
+ const status = error.code === "not-a-consumer" ? "skipped" : "failed";
2250
+ outcomes.push({
2251
+ consumer,
2252
+ status,
2253
+ message: error.message
2254
+ });
2255
+ }
2256
+ return outcomes;
2257
+ }
2258
+ /** Restores every linked member of a group; members that are not linked are skipped. */
2259
+ async function restoreGroup(deps, input) {
2260
+ const state = await deps.state.load();
2261
+ const group = requireGroup(state, input.group);
2262
+ const linked = new Set(state.links.map((link) => link.consumer));
2263
+ const outcomes = [];
2264
+ for (const consumer of group.consumers) {
2265
+ if (!linked.has(consumer)) {
2266
+ outcomes.push({
2267
+ consumer,
2268
+ status: "skipped",
2269
+ message: `${consumer} is not linked`
2270
+ });
2271
+ continue;
2272
+ }
2273
+ try {
2274
+ const result = await restoreConsumer(deps, {
2275
+ consumer,
2276
+ force: input.force
2277
+ });
2278
+ outcomes.push(result.ok ? {
2279
+ consumer,
2280
+ status: "done"
2281
+ } : {
2282
+ consumer,
2283
+ status: "failed",
2284
+ message: result.output
2285
+ });
2286
+ } catch (error) {
2287
+ if (!(error instanceof DryfitError)) throw error;
2288
+ outcomes.push({
2289
+ consumer,
2290
+ status: "failed",
2291
+ message: error.message
2292
+ });
2293
+ }
2294
+ }
2295
+ return outcomes;
2296
+ }
2297
+ // src/core/use-cases/register-library.ts
2298
+ /** Adds a library, or updates its paths while keeping its publish history. */
2299
+ async function registerLibrary(deps, input) {
2300
+ const root = joinPath(input.root);
2301
+ const { manifest, path } = await readManifest(deps.fs, root);
2302
+ if (typeof manifest.name !== "string" || manifest.name.length === 0) throw new DryfitError("invalid-manifest", `${path} has no "name", so it cannot be published`, { path });
2303
+ const state = await deps.state.load();
2304
+ const existing = state.libraries.find((library) => library.name === manifest.name);
2305
+ const library = {
2306
+ name: manifest.name,
2307
+ root,
2308
+ publishDir: resolvePublishDir(root, input.publishDir),
2309
+ build: input.build && {
2310
+ ...input.build,
2311
+ cwd: root
2312
+ },
2313
+ lastPublishedVersion: existing?.lastPublishedVersion,
2314
+ watch: existing?.watch
2315
+ };
2316
+ await deps.state.save(withLibrary(state, library));
2317
+ return library;
2318
+ }
2319
+ function resolvePublishDir(root, publishDir) {
2320
+ if (publishDir === void 0) return root;
2321
+ return publishDir.startsWith("/") ? joinPath(publishDir) : joinPath(root, publishDir);
2322
+ }
2323
+ // src/core/version/dev-version.ts
2324
+ /** Prerelease identifier that marks a version as published by dryfit (ADR 0004). */
2325
+ const DEV_IDENTIFIER = "dev";
2326
+ /** `YYYYMMDDHHmmss`: 14 digits, a safe integer that sorts chronologically. */
2327
+ const STAMP_PATTERN = /^\d{14}$/;
2328
+ /**
2329
+ * Derives a unique, strictly increasing dev version for one publish.
2330
+ *
2331
+ * `1.4.0` becomes `1.4.1-dev.<stamp>`, so the dev build sorts above the release it came from;
2332
+ * `2.0.0-rc.1` becomes `2.0.0-rc.1.dev.<stamp>`. When the clock would produce a stamp that is not
2333
+ * newer than `previous`, the stamp continues from `previous + 1` instead. The stamp is then an
2334
+ * ordering key rather than a valid time, which is fine: it only has to sort.
2335
+ */
2336
+ function nextDevVersion({ base, now, previous }) {
2337
+ const parsed = semver.parse(base);
2338
+ if (!parsed) throw new Error(`Library version is not a valid semver version: "${base}"`);
2339
+ if (isDevVersion(parsed.version)) throw new Error(`"${base}" is already a dev version. Dev versions are derived from the library's own version.`);
2340
+ const prefix = devPrefix(parsed);
2341
+ const clockStamp = utcStamp(now);
2342
+ const previousStamp = previous === void 0 ? void 0 : stampAfterPrefix(previous, prefix);
2343
+ return `${prefix}${previousStamp !== void 0 && clockStamp <= previousStamp ? previousStamp + 1 : clockStamp}`;
2344
+ }
2345
+ /** True only for versions in dryfit's own scheme, i.e. ending in `dev.<14-digit stamp>`. */
2346
+ function isDevVersion(version) {
2347
+ const prerelease = semver.parse(version)?.prerelease ?? [];
2348
+ const identifier = prerelease.at(-2);
2349
+ const stamp = prerelease.at(-1);
2350
+ return identifier === DEV_IDENTIFIER && STAMP_PATTERN.test(String(stamp));
2351
+ }
2352
+ function devPrefix({ major, minor, patch, prerelease }) {
2353
+ if (prerelease.length === 0) return `${major}.${minor}.${patch + 1}-${DEV_IDENTIFIER}.`;
2354
+ return `${major}.${minor}.${patch}-${prerelease.join(".")}.${DEV_IDENTIFIER}.`;
2355
+ }
2356
+ function stampAfterPrefix(version, prefix) {
2357
+ if (!version.startsWith(prefix)) return void 0;
2358
+ const rest = version.slice(prefix.length);
2359
+ return STAMP_PATTERN.test(rest) ? Number(rest) : void 0;
2360
+ }
2361
+ function utcStamp(date) {
2362
+ const pad = (value) => String(value).padStart(2, "0");
2363
+ const stamp = String(date.getUTCFullYear()) + pad(date.getUTCMonth() + 1) + pad(date.getUTCDate()) + pad(date.getUTCHours()) + pad(date.getUTCMinutes()) + pad(date.getUTCSeconds());
2364
+ return Number(stamp);
2365
+ }
2366
+ // src/core/use-cases/publish-library.ts
2367
+ /** Folders never copied into the staging area. */
2368
+ const NOT_PUBLISHED = ["node_modules", ".git"];
2369
+ /**
2370
+ * Builds a library and publishes it to the local registry under a fresh dev version (ADR 0004).
2371
+ *
2372
+ * The version is written into a staged copy of the publish folder, never into the library's own
2373
+ * files, so the working tree and the build output stay exactly as the developer left them.
2374
+ */
2375
+ async function publishLibrary(deps, { library: name }) {
2376
+ const library = requireLibrary(await deps.state.load(), name);
2377
+ await build(deps, library);
2378
+ const { manifest, text, path } = await readManifest(deps.fs, library.publishDir);
2379
+ if (typeof manifest.version !== "string") throw new DryfitError("invalid-manifest", `${path} has no "version"`, { path });
2380
+ const version = nextDevVersion({
2381
+ base: manifest.version,
2382
+ now: deps.clock.now(),
2383
+ previous: library.lastPublishedVersion
2384
+ });
2385
+ refuseWorkspaceRanges(manifest, path);
2386
+ const staging = stagingDir(deps, library.name);
2387
+ try {
2388
+ await deps.fs.remove(staging);
2389
+ await deps.fs.copyDir(library.publishDir, staging, { exclude: NOT_PUBLISHED });
2390
+ await deps.fs.writeText(joinPath(staging, "package.json"), formatManifest({
2391
+ ...manifest,
2392
+ version
2393
+ }, text));
2394
+ const authFiles = deps.publisher.publishAuthFiles({
2395
+ registryUrl: deps.registryUrl,
2396
+ credentials: deps.registryCredentials
2397
+ });
2398
+ for (const [file, content] of Object.entries(authFiles)) await deps.fs.writeText(joinPath(staging, file), content, { private: true });
2399
+ const result = await runSafely(deps, deps.publisher.publish({
2400
+ cwd: staging,
2401
+ registryUrl: deps.registryUrl,
2402
+ tag: DEV_TAG
2403
+ }));
2404
+ if (result.exitCode !== 0) {
2405
+ const output = commandOutput(result);
2406
+ throw new DryfitError("publish-failed", `Publishing ${library.name}@${version} failed`, {
2407
+ library: library.name,
2408
+ version,
2409
+ output
2410
+ });
2411
+ }
2412
+ } finally {
2413
+ await deps.fs.remove(staging);
2414
+ }
2415
+ const state = await deps.state.load();
2416
+ await deps.state.save(withLibrary(state, {
2417
+ ...requireLibrary(state, name),
2418
+ lastPublishedVersion: version
2419
+ }));
2420
+ deps.events.emit({
2421
+ type: "publish:succeeded",
2422
+ library: library.name,
2423
+ version
2424
+ });
2425
+ return { version };
2426
+ }
2427
+ /**
2428
+ * `workspace:` and `catalog:` ranges mean something only inside the library's own pnpm, Yarn or Bun
2429
+ * workspace, which rewrites them when it publishes. A staged copy has no workspace around it, so
2430
+ * they would reach consumers as-is and fail their installs.
2431
+ */
2432
+ function refuseWorkspaceRanges(manifest, path) {
2433
+ const unresolved = DEPENDENCY_FIELDS.flatMap((field) => {
2434
+ const entries = manifest[field];
2435
+ return isRecord(entries) ? Object.entries(entries).filter(([, range]) => typeof range === "string" && /^(workspace|catalog):/.test(range)) : [];
2436
+ });
2437
+ if (unresolved.length === 0) return;
2438
+ throw new DryfitError("invalid-manifest", `${path} depends on ${unresolved.map(([name, range]) => `${name} (${String(range)})`).join(", ")}, which only the library's workspace can resolve. Publish a build output whose package.json has real versions, and point dryfit at it with \`dryfit add --publish-dir\`.`, { path });
2439
+ }
2440
+ async function build(deps, library) {
2441
+ if (!library.build) return;
2442
+ deps.events.emit({
2443
+ type: "build:started",
2444
+ library: library.name
2445
+ });
2446
+ const result = await runSafely(deps, library.build);
2447
+ if (result.exitCode !== 0) {
2448
+ const output = commandOutput(result);
2449
+ deps.events.emit({
2450
+ type: "build:failed",
2451
+ library: library.name,
2452
+ output
2453
+ });
2454
+ throw new DryfitError("build-failed", `Building ${library.name} failed`, {
2455
+ library: library.name,
2456
+ output
2457
+ });
2458
+ }
2459
+ deps.events.emit({
2460
+ type: "build:succeeded",
2461
+ library: library.name
2462
+ });
2463
+ }
2464
+ // src/core/use-cases/sync-library.ts
2465
+ /**
2466
+ * One full cycle: build and publish the library once, then install that version into every linked
2467
+ * consumer in turn. Consumers are installed one at a time because package managers share a global
2468
+ * cache that does not tolerate concurrent writers well.
2469
+ */
2470
+ async function syncLibrary(deps, { library: name }) {
2471
+ const { version } = await publishLibrary(deps, { library: name });
2472
+ const state = await deps.state.load();
2473
+ const library = requireLibrary(state, name);
2474
+ const consumers = state.links.filter((link) => link.library === name).map((link) => link.consumer);
2475
+ const installs = [];
2476
+ for (const consumer of consumers) installs.push((await installLink(deps, {
2477
+ library,
2478
+ consumer,
2479
+ version
2480
+ })).outcome);
2481
+ return {
2482
+ version,
2483
+ installs
2484
+ };
2485
+ }
2486
+ // src/core/use-cases/unregister-library.ts
2487
+ /**
2488
+ * Forgets a library. Refused while consumers are linked to it: their only way back to the release is
2489
+ * a restore, and restoring is easier to reason about while the library is still known.
2490
+ */
2491
+ async function unregisterLibrary(deps, { library: name }) {
2492
+ const state = await deps.state.load();
2493
+ requireLibrary(state, name);
2494
+ const consumers = state.links.filter((link) => link.library === name).map((link) => link.consumer);
2495
+ if (consumers.length > 0) throw new DryfitError("library-linked", `${name} is still linked into ${consumers.length === 1 ? consumers[0] : `${consumers.length} consumers`}; restore ${consumers.length === 1 ? "it" : "them"} first`, {
2496
+ library: name,
2497
+ consumers
2498
+ });
2499
+ await deps.state.save({
2500
+ ...state,
2501
+ libraries: state.libraries.filter((library) => library.name !== name)
2502
+ });
2503
+ await deps.fs.remove(stagingDir(deps, name));
2504
+ }
2505
+ // src/daemon/job-queue.ts
2506
+ /**
2507
+ * Runs the daemon's work one job at a time (ADR 0012), so two operations never write the same
2508
+ * lockfile or the state file at once. A request whose key matches a job that is still waiting joins
2509
+ * it; one that matches the running job queues a single follow-up. A burst of file saves therefore
2510
+ * costs at most two syncs.
2511
+ */
2512
+ var JobQueue = class {
2513
+ #now;
2514
+ #listener;
2515
+ #waiting = [];
2516
+ #idleWaiters = [];
2517
+ #running;
2518
+ #nextId = 1;
2519
+ #closed = false;
2520
+ constructor(options = {}) {
2521
+ this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
2522
+ this.#listener = options.listener ?? {};
2523
+ }
2524
+ run(label, task, options = {}) {
2525
+ if (this.#closed) return Promise.reject(stopping());
2526
+ if (options.key !== void 0) {
2527
+ const waiting = this.#waiting.find((entry) => entry.info.key === options.key);
2528
+ if (waiting) return waiting.promise;
2529
+ }
2530
+ let resolve;
2531
+ let reject;
2532
+ const promise = new Promise((res, rej) => {
2533
+ resolve = res;
2534
+ reject = rej;
2535
+ });
2536
+ const info = {
2537
+ id: this.#nextId++,
2538
+ label,
2539
+ ...options.key !== void 0 && { key: options.key },
2540
+ queuedAt: this.#now().toISOString()
2541
+ };
2542
+ this.#waiting.push({
2543
+ info,
2544
+ task,
2545
+ promise,
2546
+ resolve,
2547
+ reject
2548
+ });
2549
+ this.#listener.queued?.(info);
2550
+ this.#pump();
2551
+ return promise;
2552
+ }
2553
+ snapshot() {
2554
+ return {
2555
+ ...this.#running && { running: this.#running.info },
2556
+ queued: this.#waiting.map((entry) => entry.info)
2557
+ };
2558
+ }
2559
+ /** Resolves once nothing is running or waiting. */
2560
+ idle() {
2561
+ if (!this.#running && this.#waiting.length === 0) return Promise.resolve();
2562
+ return new Promise((resolve) => this.#idleWaiters.push(resolve));
2563
+ }
2564
+ /** Refuses new jobs and drops waiting ones; resolves when the running job has finished. */
2565
+ close() {
2566
+ this.#closed = true;
2567
+ for (const entry of this.#waiting.splice(0)) entry.reject(stopping());
2568
+ return this.idle();
2569
+ }
2570
+ #pump() {
2571
+ if (this.#running) return;
2572
+ const entry = this.#waiting.shift();
2573
+ if (!entry) {
2574
+ for (const resolve of this.#idleWaiters.splice(0)) resolve();
2575
+ return;
2576
+ }
2577
+ entry.info = {
2578
+ ...entry.info,
2579
+ startedAt: this.#now().toISOString()
2580
+ };
2581
+ this.#running = entry;
2582
+ this.#listener.started?.(entry.info);
2583
+ const finish = (error) => {
2584
+ this.#running = void 0;
2585
+ this.#listener.finished?.(entry.info, error);
2586
+ this.#pump();
2587
+ };
2588
+ let task;
2589
+ try {
2590
+ task = entry.task();
2591
+ } catch (error) {
2592
+ task = Promise.reject(error);
2593
+ }
2594
+ task.then((value) => {
2595
+ entry.resolve(value);
2596
+ finish();
2597
+ }, (error) => {
2598
+ entry.reject(error);
2599
+ finish(error);
2600
+ });
2601
+ }
2602
+ };
2603
+ function stopping() {
2604
+ return new DryfitError("daemon-stopping", "dryfit is shutting down", {});
2605
+ }
2606
+ // src/daemon/service.ts
2607
+ /**
2608
+ * Everything the API can ask for, behind one `call`. Work that changes state or touches a repository
2609
+ * goes through the job queue; reads answer immediately. This is where the daemon adds what the pure
2610
+ * core does not know about: job and state events, file watching and the commit guard.
2611
+ */
2612
+ var DaemonService = class {
2613
+ #deps;
2614
+ #options;
2615
+ #queue;
2616
+ #watching = /* @__PURE__ */ new Map();
2617
+ /** Set by `stop`; a job still finishing must not start watchers nothing would close. */
2618
+ #stopped = false;
2619
+ #handlers;
2620
+ constructor(options) {
2621
+ this.#options = options;
2622
+ this.#deps = options.deps;
2623
+ const { hub } = options;
2624
+ this.#queue = new JobQueue({
2625
+ now: () => this.#deps.clock.now(),
2626
+ listener: {
2627
+ queued: (job) => hub.emit({
2628
+ type: "job:queued",
2629
+ job
2630
+ }),
2631
+ started: (job) => hub.emit({
2632
+ type: "job:started",
2633
+ job
2634
+ }),
2635
+ finished: (job, error) => {
2636
+ hub.emit({
2637
+ type: "job:finished",
2638
+ job,
2639
+ ...error !== void 0 && { error: describe(error) }
2640
+ });
2641
+ hub.emit({ type: "state:changed" });
2642
+ }
2643
+ }
2644
+ });
2645
+ this.#handlers = this.#createHandlers();
2646
+ }
2647
+ call(name, input) {
2648
+ return this.#handlers[name](input);
2649
+ }
2650
+ /** Resumes watching the libraries that were being watched when the daemon last stopped. */
2651
+ async start() {
2652
+ const { libraries } = await this.#deps.state.load();
2653
+ for (const library of libraries) if (library.watch) this.#startWatching(library);
2654
+ }
2655
+ /** Resolves once no job is running or waiting. */
2656
+ idle() {
2657
+ return this.#queue.idle();
2658
+ }
2659
+ /** Stops watching, drops waiting jobs and waits for the running one. */
2660
+ async stop() {
2661
+ this.#stopped = true;
2662
+ for (const stopWatching of this.#watching.values()) stopWatching();
2663
+ this.#watching.clear();
2664
+ await this.#queue.close();
2665
+ }
2666
+ #createHandlers() {
2667
+ const deps = this.#deps;
2668
+ const job = (label, task, key) => this.#queue.run(label, task, key === void 0 ? {} : { key });
2669
+ return {
2670
+ status: async () => {
2671
+ const state = await deps.state.load();
2672
+ return {
2673
+ daemon: this.#options.health(),
2674
+ libraries: state.libraries,
2675
+ links: state.links,
2676
+ groups: state.groups,
2677
+ warnings: coherenceWarnings(state),
2678
+ jobs: this.#queue.snapshot()
2679
+ };
2680
+ },
2681
+ register: (input) => job(`register ${input.root}`, async () => {
2682
+ const given = input.publishDir !== void 0 || input.build !== void 0;
2683
+ const known = given ? void 0 : (await deps.state.load()).libraries.find((entry) => entry.root === joinPath(input.root));
2684
+ const detected = given || known ? void 0 : await detectLibraryBuild(deps.fs, input.root);
2685
+ const library = await registerLibrary(deps, {
2686
+ root: input.root,
2687
+ publishDir: detected?.publishDir ?? input.publishDir ?? known?.publishDir,
2688
+ build: detected?.build ?? input.build ?? (known?.build && {
2689
+ command: known.build.command,
2690
+ args: known.build.args
2691
+ })
2692
+ });
2693
+ if (library.watch) this.#startWatching(library);
2694
+ return {
2695
+ library,
2696
+ detected: detected?.kind ?? "given"
2697
+ };
2698
+ }),
2699
+ unregister: ({ library }) => job(`unregister ${library}`, async () => {
2700
+ await unregisterLibrary(deps, { library });
2701
+ this.#stopWatching(library);
2702
+ return { ok: true };
2703
+ }),
2704
+ inspect: async ({ root }) => {
2705
+ const libraryRoot = joinPath(root);
2706
+ const { manifest } = await readManifest(deps.fs, libraryRoot);
2707
+ const detected = await detectLibraryBuild(deps.fs, libraryRoot);
2708
+ const known = (await deps.state.load()).libraries.find((entry) => entry.root === libraryRoot);
2709
+ const build = known ? known.build : detected.build;
2710
+ return {
2711
+ name: String(manifest.name ?? ""),
2712
+ version: String(manifest.version ?? ""),
2713
+ root: libraryRoot,
2714
+ detected: detected.kind,
2715
+ publishDir: known?.publishDir ?? detected.publishDir,
2716
+ ...build && { build: {
2717
+ command: build.command,
2718
+ args: build.args
2719
+ } },
2720
+ registered: known !== void 0
2721
+ };
2722
+ },
2723
+ sync: ({ library }) => job(`sync ${library}`, async () => {
2724
+ const result = await syncLibrary(deps, { library });
2725
+ await this.#reapplyGuards(library);
2726
+ return result;
2727
+ }, `sync:${library}`),
2728
+ watch: ({ library: name, enabled }) => job(`${enabled ? "watch" : "unwatch"} ${name}`, async () => {
2729
+ const state = await deps.state.load();
2730
+ const library = {
2731
+ ...requireLibrary(state, name),
2732
+ watch: enabled
2733
+ };
2734
+ await deps.state.save(withLibrary(state, library));
2735
+ if (enabled) this.#startWatching(library);
2736
+ else this.#stopWatching(name);
2737
+ return library;
2738
+ }),
2739
+ discover: async ({ library }) => {
2740
+ const consumers = await discoverConsumers(deps, { roots: await this.#options.roots() });
2741
+ return library === void 0 ? consumers : consumers.filter((consumer) => consumer.libraries.some((entry) => entry.name === library));
2742
+ },
2743
+ link: ({ library, consumer, guard = true }) => job(`link ${library} into ${consumer}`, async () => {
2744
+ const link = await linkConsumer(deps, {
2745
+ library,
2746
+ consumer
2747
+ });
2748
+ if (!guard) return {
2749
+ link,
2750
+ guard: "declined"
2751
+ };
2752
+ const installed = await this.#options.guard.install(link.consumer);
2753
+ return {
2754
+ link: installed === "installed" ? await this.#markGuarded(link) : link,
2755
+ guard: installed
2756
+ };
2757
+ }),
2758
+ restore: ({ consumer, library, force }) => job(library ? `restore ${library} in ${consumer}` : `restore ${consumer}`, async () => {
2759
+ return this.#restoring(() => restoreConsumer(deps, {
2760
+ consumer,
2761
+ library,
2762
+ force
2763
+ }));
2764
+ }),
2765
+ saveGroup: (input) => job(`save group ${input.name}`, () => saveGroup(deps, input)),
2766
+ deleteGroup: ({ name }) => job(`delete group ${name}`, async () => {
2767
+ await deleteGroup(deps, { name });
2768
+ return { ok: true };
2769
+ }),
2770
+ linkGroup: (input) => job(`link ${input.library} into group ${input.group}`, async () => {
2771
+ const outcomes = await linkGroup(deps, input);
2772
+ const state = await deps.state.load();
2773
+ const reported = [];
2774
+ for (const outcome of outcomes) {
2775
+ const link = state.links.find((candidate) => sameLink(candidate, {
2776
+ library: input.library,
2777
+ consumer: outcome.consumer
2778
+ }));
2779
+ if (outcome.status !== "done" || !link) {
2780
+ reported.push(outcome);
2781
+ continue;
2782
+ }
2783
+ try {
2784
+ if (await this.#options.guard.install(link.consumer) === "installed") await this.#markGuarded(link);
2785
+ reported.push(outcome);
2786
+ } catch (error) {
2787
+ const reason = error instanceof Error ? error.message : String(error);
2788
+ reported.push({
2789
+ ...outcome,
2790
+ message: `linked, but the commit guard could not be installed: ${reason}`
2791
+ });
2792
+ }
2793
+ }
2794
+ return reported;
2795
+ }),
2796
+ restoreGroup: (input) => job(`restore group ${input.group}`, async () => {
2797
+ return this.#restoring(() => restoreGroup(deps, input));
2798
+ }),
2799
+ roots: async () => ({ roots: await this.#options.roots() }),
2800
+ setRoots: async (input) => {
2801
+ const roots = [...new Set(input.roots.map((root) => joinPath(root)))];
2802
+ await this.#options.saveRoots(roots);
2803
+ return { roots };
2804
+ },
2805
+ shutdown: async () => {
2806
+ setTimeout(() => this.#options.onShutdown(), 0);
2807
+ return { ok: true };
2808
+ }
2809
+ };
2810
+ }
2811
+ #startWatching(library) {
2812
+ this.#stopWatching(library.name);
2813
+ if (this.#stopped) return;
2814
+ const { name } = library;
2815
+ const stop = this.#options.watcher.watch(library, () => {
2816
+ this.#options.hub.emit({
2817
+ type: "library:changed",
2818
+ library: name
2819
+ });
2820
+ this.call("sync", { library: name }).catch(() => {});
2821
+ }, (error) => {
2822
+ this.#stopWatching(name);
2823
+ this.#options.hub.emit({
2824
+ type: "watch:failed",
2825
+ library: name,
2826
+ message: error.message
2827
+ });
2828
+ this.call("watch", {
2829
+ library: name,
2830
+ enabled: false
2831
+ }).catch(() => {});
2832
+ });
2833
+ this.#watching.set(name, stop);
2834
+ }
2835
+ #stopWatching(name) {
2836
+ this.#watching.get(name)?.();
2837
+ this.#watching.delete(name);
2838
+ }
2839
+ async #markGuarded(link) {
2840
+ const state = await this.#deps.state.load();
2841
+ const guarded = {
2842
+ ...link,
2843
+ guard: true
2844
+ };
2845
+ await this.#deps.state.save(withLink(state, guarded));
2846
+ return guarded;
2847
+ }
2848
+ /** Husky and friends regenerate hook files on install, so a sync may have wiped the guard. */
2849
+ async #reapplyGuards(library) {
2850
+ const { links } = await this.#deps.state.load();
2851
+ for (const link of links) {
2852
+ if (link.library !== library || !link.guard) continue;
2853
+ await this.#options.guard.install(link.consumer).catch(() => void 0);
2854
+ }
2855
+ }
2856
+ /**
2857
+ * Runs a restore, then takes the guard out of every guarded consumer that no longer has a link. A
2858
+ * restore drops a consumer's links once its files are back, even if the clean install then fails.
2859
+ */
2860
+ async #restoring(restore) {
2861
+ const before = await this.#deps.state.load();
2862
+ const guarded = new Set(before.links.filter((link) => link.guard).map((link) => link.consumer));
2863
+ try {
2864
+ return await restore();
2865
+ } finally {
2866
+ const { links } = await this.#deps.state.load();
2867
+ const linked = new Set(links.map((link) => link.consumer));
2868
+ for (const consumer of guarded) if (!linked.has(consumer)) await this.#options.guard.remove(consumer).catch(() => void 0);
2869
+ }
2870
+ }
2871
+ };
2872
+ function describe(error) {
2873
+ if (error instanceof DryfitError) return {
2874
+ code: error.code,
2875
+ message: error.message
2876
+ };
2877
+ return {
2878
+ code: "internal",
2879
+ message: error instanceof Error ? error.message : String(error)
2880
+ };
2881
+ }
2882
+ // src/daemon/daemon.ts
2883
+ const HOST = "127.0.0.1";
2884
+ /**
2885
+ * Starts dryfitd (ADR 0003, ADR 0012): the registry, the job queue and the HTTP API. It stops on a
2886
+ * `shutdown` request or `stop()`: the API closes, running commands are cancelled, the registry stops,
2887
+ * and `daemon.json` is removed so clients no longer find it.
2888
+ */
2889
+ async function startDaemon(options) {
2890
+ const { home, version } = options;
2891
+ const env = options.env ?? process.env;
2892
+ const { log } = options;
2893
+ await home.ensure();
2894
+ const config = await home.readConfig();
2895
+ const token = await home.ensureToken();
2896
+ const abort = new AbortController();
2897
+ const runner = new NodeProcessRunner({
2898
+ baseEnv: env,
2899
+ signal: abort.signal
2900
+ });
2901
+ const ownRegistry = `http://${HOST}:${config.ports.registry}/`;
2902
+ const npmRegistries = await readNpmRegistries(runner, {
2903
+ cwd: env.HOME ?? homedir(),
2904
+ env
2905
+ });
2906
+ const registry = await VerdaccioRegistry.start({
2907
+ storage: home.paths.registry,
2908
+ port: config.ports.registry,
2909
+ uplinks: uplinksFrom({
2910
+ ...npmRegistries,
2911
+ ownRegistry
2912
+ }),
2913
+ logLevel: "warn"
2914
+ });
2915
+ const hub = new EventHub();
2916
+ let deps;
2917
+ try {
2918
+ deps = createNodeDeps({
2919
+ home: home.root,
2920
+ registry,
2921
+ events: hub,
2922
+ process: runner
2923
+ });
2924
+ } catch (error) {
2925
+ await registry.stop();
2926
+ throw error;
2927
+ }
2928
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2929
+ const health = () => ({
2930
+ name: "dryfit",
2931
+ version,
2932
+ apiVersion: 1,
2933
+ pid: process.pid,
2934
+ registryUrl: registry.url,
2935
+ startedAt
2936
+ });
2937
+ let resolveStopped;
2938
+ const stopped = new Promise((resolve) => resolveStopped = resolve);
2939
+ let stopping;
2940
+ const stop = () => {
2941
+ stopping ??= (async () => {
2942
+ try {
2943
+ server.closeAllConnections();
2944
+ await new Promise((resolve) => server.close(resolve));
2945
+ abort.abort();
2946
+ await service.stop();
2947
+ await registry.stop();
2948
+ await home.removeDaemonInfo(process.pid);
2949
+ } catch (error) {
2950
+ log(`stopping: ${String(error)}`);
2951
+ } finally {
2952
+ resolveStopped();
2953
+ }
2954
+ })();
2955
+ return stopping;
2956
+ };
2957
+ const service = new DaemonService({
2958
+ deps,
2959
+ hub,
2960
+ health,
2961
+ roots: async () => (await home.readConfig()).roots,
2962
+ saveRoots: async (roots) => home.writeConfig({
2963
+ ...await home.readConfig(),
2964
+ roots
2965
+ }),
2966
+ watcher: new NodeLibraryWatcher(),
2967
+ guard: new GitCommitGuard(new NodeProcessRunner({
2968
+ baseEnv: env,
2969
+ signal: abort.signal,
2970
+ timeoutMs: 3e4
2971
+ })),
2972
+ onShutdown: () => void stop()
2973
+ });
2974
+ const server = createApiServer({
2975
+ token,
2976
+ hub,
2977
+ health,
2978
+ service,
2979
+ onError: (error) => log(String(error))
2980
+ });
2981
+ let port;
2982
+ try {
2983
+ port = await listen(server, config.ports.api);
2984
+ } catch (error) {
2985
+ await registry.stop();
2986
+ throw error;
2987
+ }
2988
+ try {
2989
+ await home.writeDaemonInfo({
2990
+ pid: process.pid,
2991
+ port,
2992
+ version,
2993
+ registryUrl: registry.url,
2994
+ startedAt
2995
+ });
2996
+ await service.start();
2997
+ } catch (error) {
2998
+ await stop();
2999
+ throw error;
3000
+ }
3001
+ log(`dryfit ${version} listening on http://${HOST}:${port}/, registry ${registry.url}`);
3002
+ return {
3003
+ url: `http://${HOST}:${port}/`,
3004
+ registryUrl: registry.url,
3005
+ stopped,
3006
+ stop
3007
+ };
3008
+ }
3009
+ function listen(server, port) {
3010
+ return new Promise((resolve, reject) => {
3011
+ const onError = (error) => {
3012
+ reject(new DryfitError("daemon-failed", `The dryfit daemon could not start: ${error.code === "EADDRINUSE" ? `port ${port} is already in use (change "ports.api" in config.json, or stop what uses it)` : error.message}`, { port }));
3013
+ };
3014
+ server.once("error", onError);
3015
+ server.listen(port, HOST, () => {
3016
+ server.off("error", onError);
3017
+ resolve(server.address().port);
3018
+ });
3019
+ });
3020
+ }
3021
+ // src/cli/client.ts
3022
+ /** A failure the daemon reported, or `daemon-unavailable` when it could not be reached. */
3023
+ var ApiError = class extends Error {
3024
+ name = "ApiError";
3025
+ code;
3026
+ details;
3027
+ constructor(code, message, details = {}) {
3028
+ super(message);
3029
+ this.code = code;
3030
+ this.details = details;
3031
+ }
3032
+ };
3033
+ /** Talks to dryfitd over its HTTP API (ADR 0012). */
3034
+ var DaemonClient = class {
3035
+ baseUrl;
3036
+ #token;
3037
+ constructor(baseUrl, token) {
3038
+ this.baseUrl = baseUrl;
3039
+ this.#token = token;
3040
+ }
3041
+ /**
3042
+ * Who is listening. Sent without the token, so a client can check it is talking to dryfit before
3043
+ * trusting the port; a daemon that does not answer within `timeoutMs` counts as unavailable.
3044
+ */
3045
+ health(options = {}) {
3046
+ return this.#request("GET", "v1/health", void 0, {
3047
+ token: false,
3048
+ signal: AbortSignal.timeout(options.timeoutMs ?? 2e3)
3049
+ });
3050
+ }
3051
+ call(name, input) {
3052
+ return this.#request("POST", `v1/${name}`, input);
3053
+ }
3054
+ /** Delivers events as they happen until `signal` aborts or the daemon goes away. */
3055
+ async events(onEvent, options) {
3056
+ let response;
3057
+ try {
3058
+ response = await fetch(`${this.baseUrl}v1/events`, {
3059
+ headers: this.#headers(),
3060
+ signal: options.signal
3061
+ });
3062
+ } catch (error) {
3063
+ if (options.signal.aborted) return;
3064
+ throw unavailable(error);
3065
+ }
3066
+ if (!response.ok || !response.body) throw await toError(response);
3067
+ options.onOpen?.();
3068
+ const decoder = new TextDecoder();
3069
+ let buffer = "";
3070
+ try {
3071
+ for await (const chunk of response.body) {
3072
+ buffer += decoder.decode(chunk, { stream: true });
3073
+ let boundary = buffer.indexOf("\n\n");
3074
+ while (boundary !== -1) {
3075
+ const block = buffer.slice(0, boundary);
3076
+ buffer = buffer.slice(boundary + 2);
3077
+ const data = block.split("\n").filter((line) => line.startsWith("data: ")).map((line) => line.slice(6)).join("\n");
3078
+ if (data) onEvent(JSON.parse(data));
3079
+ if (options.signal.aborted) return;
3080
+ boundary = buffer.indexOf("\n\n");
3081
+ }
3082
+ }
3083
+ } catch (error) {
3084
+ if (!options.signal.aborted) throw unavailable(error);
3085
+ }
3086
+ }
3087
+ async #request(method, path, body, options = {}) {
3088
+ try {
3089
+ const response = await fetch(`${this.baseUrl}${path}`, {
3090
+ method,
3091
+ headers: {
3092
+ ...options.token !== false && this.#headers(),
3093
+ ...body !== void 0 && { "content-type": "application/json" }
3094
+ },
3095
+ ...body !== void 0 && { body: JSON.stringify(body) },
3096
+ ...options.signal && { signal: options.signal }
3097
+ });
3098
+ if (!response.ok) throw await toError(response);
3099
+ return await response.json();
3100
+ } catch (error) {
3101
+ throw error instanceof ApiError ? error : unavailable(error);
3102
+ }
3103
+ }
3104
+ #headers() {
3105
+ return { authorization: `Bearer ${this.#token}` };
3106
+ }
3107
+ };
3108
+ async function toError(response) {
3109
+ const error = (await response.json().catch(() => void 0))?.error;
3110
+ return error ? new ApiError(error.code, error.message, error.details) : new ApiError("internal", `The daemon answered HTTP ${response.status}`);
3111
+ }
3112
+ function unavailable(error) {
3113
+ return new ApiError("daemon-unavailable", `Could not reach the dryfit daemon (${error instanceof Error ? error.message : String(error)})`);
3114
+ }
3115
+ // src/cli/launchd.ts
3116
+ /** The launchd agent that starts dryfitd at login (ADR 0012). */
3117
+ const LAUNCH_AGENT_LABEL = "dev.dryfit.daemon";
3118
+ function launchAgentPlist(input) {
3119
+ const env = {
3120
+ PATH: input.path,
3121
+ ...input.env
3122
+ };
3123
+ return `<?xml version="1.0" encoding="UTF-8"?>
3124
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3125
+ <plist version="1.0">
3126
+ <dict>
3127
+ <key>Label</key>
3128
+ <string>${LAUNCH_AGENT_LABEL}</string>
3129
+ <key>ProgramArguments</key>
3130
+ <array>
3131
+ ${[
3132
+ input.node,
3133
+ input.entry,
3134
+ "daemon",
3135
+ "run"
3136
+ ].map((arg) => ` <string>${xml(arg)}</string>`).join("\n")}
3137
+ </array>
3138
+ <key>EnvironmentVariables</key>
3139
+ <dict>
3140
+ ${Object.entries(env).map(([key, value]) => ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`).join("\n")}
3141
+ </dict>
3142
+ <key>RunAtLoad</key>
3143
+ <true/>
3144
+ <key>KeepAlive</key>
3145
+ <dict>
3146
+ <key>SuccessfulExit</key>
3147
+ <false/>
3148
+ </dict>
3149
+ <key>ProcessType</key>
3150
+ <string>Background</string>
3151
+ <key>StandardOutPath</key>
3152
+ <string>${xml(input.log)}</string>
3153
+ <key>StandardErrorPath</key>
3154
+ <string>${xml(input.log)}</string>
3155
+ </dict>
3156
+ </plist>
3157
+ `;
3158
+ }
3159
+ function xml(value) {
3160
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
3161
+ }
3162
+ // src/cli/local.ts
3163
+ const START_TIMEOUT_MS = 2e4;
3164
+ const STOP_TIMEOUT_MS = 1e4;
3165
+ /** Starts, finds and stops the daemon, and checks the machine (ADR 0012). */
3166
+ var LocalMachine = class {
3167
+ #options;
3168
+ #home;
3169
+ constructor(options) {
3170
+ this.#options = options;
3171
+ this.#home = options.home;
3172
+ }
3173
+ async init(roots) {
3174
+ await this.#home.ensure();
3175
+ const config = await this.#home.readConfig();
3176
+ await this.#home.writeConfig({
3177
+ ...config,
3178
+ roots
3179
+ });
3180
+ await this.#home.ensureToken();
3181
+ return {
3182
+ home: this.#home.root,
3183
+ roots
3184
+ };
3185
+ }
3186
+ /** A client for a daemon of this version, starting or restarting one as needed. */
3187
+ async connect() {
3188
+ const running = await this.#find();
3189
+ if (running && running.health.version === this.#options.version) return running.client;
3190
+ if (running) await this.#stop(running);
3191
+ return this.#start();
3192
+ }
3193
+ async daemon(action) {
3194
+ const { out } = this.#options;
3195
+ switch (action) {
3196
+ case "run": return this.#runInForeground();
3197
+ case "start": {
3198
+ const client = await this.connect();
3199
+ const health = await client.health();
3200
+ out.ok(`dryfit ${health.version} is running (pid ${health.pid}) at ${client.baseUrl}`);
3201
+ return 0;
3202
+ }
3203
+ case "stop": {
3204
+ const running = await this.#find();
3205
+ if (running) {
3206
+ await this.#stop(running);
3207
+ out.ok("Stopped dryfit");
3208
+ return 0;
3209
+ }
3210
+ return this.#reportUnresponsive();
3211
+ }
3212
+ case "restart": {
3213
+ const running = await this.#find();
3214
+ if (running) await this.#stop(running);
3215
+ else if (await this.#reportUnresponsive() !== 0) return 1;
3216
+ return this.daemon("start");
3217
+ }
3218
+ case "status": {
3219
+ const running = await this.#find();
3220
+ if (!running) {
3221
+ out.line("dryfit is not running. Any command starts it.");
3222
+ return 1;
3223
+ }
3224
+ const { health, client } = running;
3225
+ out.ok(`dryfit ${health.version} running since ${health.startedAt} (pid ${health.pid})`);
3226
+ out.line(` api ${client.baseUrl}`);
3227
+ out.line(` registry ${health.registryUrl}`);
3228
+ out.line(` at login ${existsSync(agentPath()) ? "yes (launchd)" : "no"}`);
3229
+ return 0;
3230
+ }
3231
+ case "install": return this.#installAgent();
3232
+ case "uninstall": return this.#uninstallAgent();
3233
+ }
3234
+ }
3235
+ async doctor(out, json) {
3236
+ const checks = [];
3237
+ const add = (status, check, detail = "") => checks.push({
3238
+ status,
3239
+ check,
3240
+ detail
3241
+ });
3242
+ const runner = new NodeProcessRunner({
3243
+ baseEnv: this.#options.env,
3244
+ timeoutMs: 3e4
3245
+ });
3246
+ const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
3247
+ const nodeOk = major > 22 || major === 22 && minor >= 12;
3248
+ add(nodeOk ? "ok" : "fail", `Node ${process.versions.node}`, nodeOk ? "" : "dryfit needs 22.12 or newer");
3249
+ const npm = await runner.run({
3250
+ command: "npm",
3251
+ args: ["--version"],
3252
+ cwd: homedir()
3253
+ }).catch(() => void 0);
3254
+ if (npm?.exitCode === 0) add("ok", `npm ${npm.stdout.trim()}`);
3255
+ else add("fail", "npm", "not found on PATH");
3256
+ let roots = [];
3257
+ try {
3258
+ roots = (await this.#home.readConfig()).roots;
3259
+ if (roots.length === 0) add("warn", "Project roots", "none set, so `dryfit consumers` finds nothing; run `dryfit init`");
3260
+ for (const root of roots) add(existsSync(root) ? "ok" : "warn", `Root ${out.path(root)}`, existsSync(root) ? "" : "does not exist");
3261
+ } catch (error) {
3262
+ add("fail", "Config", error instanceof Error ? error.message : String(error));
3263
+ }
3264
+ const running = await this.#find().catch(() => void 0);
3265
+ let status;
3266
+ if (!running) add("warn", "Daemon", "not running; any command starts it");
3267
+ else {
3268
+ const same = running.health.version === this.#options.version;
3269
+ add(same ? "ok" : "warn", `Daemon ${running.health.version} (pid ${running.health.pid})`, same ? "" : `this CLI is ${this.#options.version}; the next command restarts it`);
3270
+ const ping = await fetch(`${running.health.registryUrl}-/ping`, { signal: AbortSignal.timeout(5e3) }).catch(() => void 0);
3271
+ add(ping?.ok ? "ok" : "fail", `Registry ${running.health.registryUrl}`, ping?.ok ? "" : "not answering");
3272
+ status = await running.client.call("status", {}).catch(() => void 0);
3273
+ }
3274
+ try {
3275
+ const registries = await readNpmRegistries(runner, {
3276
+ cwd: this.#options.env.HOME ?? homedir(),
3277
+ env: this.#options.env
3278
+ });
3279
+ const own = running?.health.registryUrl ?? "http://127.0.0.1:0/";
3280
+ for (const [name, uplink] of Object.entries(uplinksFrom({
3281
+ ...registries,
3282
+ ownRegistry: own
3283
+ }))) add("ok", `Proxies ${name}${uplink.scopes ? ` for ${uplink.scopes.join(", ")}` : ""}`, uplink.auth ? "with your npm credentials" : "without credentials");
3284
+ } catch {
3285
+ add("warn", "npm registries", "could not read your npm config");
3286
+ }
3287
+ for (const link of status?.links ?? []) {
3288
+ const where = out.path(link.consumer);
3289
+ const snapshot = join(snapshotDir({ home: this.#home.root }, link.consumer), "meta.json");
3290
+ if (!existsSync(snapshot)) add("fail", `Snapshot for ${where}`, "missing, so restore cannot work; reinstall from git");
3291
+ if (link.guard && !await guardPresent(runner, link.consumer)) add("warn", `Commit guard in ${where}`, "missing (Husky may have regenerated hooks); the next sync adds it back");
3292
+ if (link.status === "failed") add("warn", `${link.library} in ${where}`, "last install failed; run `dryfit sync`");
3293
+ }
3294
+ for (const warning of status?.warnings ?? []) add("warn", `Group ${warning.group}`, `runs different versions of ${warning.library}`);
3295
+ if (process.platform === "darwin") {
3296
+ if (!existsSync(agentPath())) add("ok", "Start at login", "off (`dryfit daemon install`)");
3297
+ else if (await this.#launchctl(["print", `gui/${userInfo().uid}/dev.dryfit.daemon`]) === 0) add("ok", "Start at login", "launchd agent loaded");
3298
+ else add("warn", "Start at login", "agent installed but not loaded; run `dryfit daemon install` again");
3299
+ }
3300
+ if (json) out.line(JSON.stringify(checks, null, 2));
3301
+ else for (const { status: state, check, detail } of checks) {
3302
+ const text = detail ? `${check} ${out.dim(`— ${detail}`)}` : check;
3303
+ if (state === "ok") out.ok(text);
3304
+ else if (state === "warn") out.warn(text);
3305
+ else out.fail(text);
3306
+ }
3307
+ return checks.some((check) => check.status === "fail") ? 1 : 0;
3308
+ }
3309
+ /**
3310
+ * The daemon `daemon.json` describes, if it answers as that daemon. A pid can be reused after a crash
3311
+ * or reboot and a port taken by something else, so nothing is trusted (or sent the token, or
3312
+ * signalled) until health confirms both.
3313
+ */
3314
+ async #find() {
3315
+ const info = await this.#home.readDaemonInfo();
3316
+ if (!info || !isAlive(info.pid)) return void 0;
3317
+ const client = new DaemonClient(`http://127.0.0.1:${info.port}/`, await this.#home.ensureToken());
3318
+ const health = await client.health().catch(() => void 0);
3319
+ if (health?.name !== "dryfit" || health.pid !== info.pid) return void 0;
3320
+ return {
3321
+ info,
3322
+ client,
3323
+ health
3324
+ };
3325
+ }
3326
+ /** Explains a `daemon.json` whose process is alive but does not answer as dryfit; signals nothing. */
3327
+ async #reportUnresponsive() {
3328
+ const { out } = this.#options;
3329
+ const info = await this.#home.readDaemonInfo();
3330
+ if (!info || !isAlive(info.pid)) {
3331
+ out.line("dryfit is not running.");
3332
+ return 0;
3333
+ }
3334
+ out.fail(`${out.path(this.#home.paths.daemon)} names pid ${info.pid}, which does not answer as dryfit.`);
3335
+ out.line(out.dim(`If that is a stuck dryfit daemon, end it with \`kill ${info.pid}\`; otherwise delete the file.`));
3336
+ return 1;
3337
+ }
3338
+ async #start() {
3339
+ const { env, entry } = this.#options;
3340
+ await mkdir(this.#home.paths.logs, { recursive: true });
3341
+ let exited;
3342
+ if (!(existsSync(agentPath()) && await this.#launchctl(["kickstart", `gui/${userInfo().uid}/dev.dryfit.daemon`]) === 0)) {
3343
+ const log = openSync(this.#home.paths.log, "a");
3344
+ try {
3345
+ const child = spawn(process.execPath, [
3346
+ ...process.execArgv,
3347
+ entry,
3348
+ "daemon",
3349
+ "run"
3350
+ ], {
3351
+ detached: true,
3352
+ stdio: [
3353
+ "ignore",
3354
+ log,
3355
+ log
3356
+ ],
3357
+ env
3358
+ });
3359
+ child.once("exit", (code) => exited = code);
3360
+ child.once("error", () => exited = null);
3361
+ child.unref();
3362
+ } finally {
3363
+ closeSync(log);
3364
+ }
3365
+ }
3366
+ const deadline = Date.now() + START_TIMEOUT_MS;
3367
+ while (Date.now() < deadline) {
3368
+ const running = await this.#find();
3369
+ if (running?.health.version === this.#options.version) return running.client;
3370
+ if (exited !== void 0) break;
3371
+ await setTimeout$1(100);
3372
+ }
3373
+ const tail = (await readFile(this.#home.paths.log, "utf8").catch(() => "")).trimEnd().split("\n").slice(-15).join("\n");
3374
+ throw new DryfitError("daemon-failed", exited !== void 0 ? "The dryfit daemon stopped right after starting" : "The dryfit daemon did not come up in time", { output: tail });
3375
+ }
3376
+ /** Stops a daemon `#find` has confirmed, so the pid it signals is known to be dryfit's. */
3377
+ async #stop({ info, client }) {
3378
+ await client.call("shutdown", {}).catch(() => signal(info.pid, "SIGTERM"));
3379
+ const deadline = Date.now() + STOP_TIMEOUT_MS;
3380
+ while (isAlive(info.pid) && Date.now() < deadline) await setTimeout$1(100);
3381
+ if (isAlive(info.pid)) signal(info.pid, "SIGKILL");
3382
+ await this.#home.removeDaemonInfo(info.pid);
3383
+ }
3384
+ async #runInForeground() {
3385
+ const { home, version, env, err, signal: stop } = this.#options;
3386
+ const log = (message) => err.line(`${(/* @__PURE__ */ new Date()).toISOString()} ${message}`);
3387
+ let daemon;
3388
+ try {
3389
+ daemon = await startDaemon({
3390
+ home,
3391
+ version,
3392
+ env,
3393
+ log
3394
+ });
3395
+ } catch (error) {
3396
+ log(error instanceof Error ? error.message : String(error));
3397
+ return 1;
3398
+ }
3399
+ stop.addEventListener("abort", () => void daemon.stop(), { once: true });
3400
+ await daemon.stopped;
3401
+ log("stopped");
3402
+ return 0;
3403
+ }
3404
+ async #installAgent() {
3405
+ const { out, env } = this.#options;
3406
+ if (process.platform !== "darwin") {
3407
+ out.line("Starting at login uses launchd, which is macOS only.");
3408
+ return 1;
3409
+ }
3410
+ await mkdir(join(homedir(), "Library", "LaunchAgents"), { recursive: true });
3411
+ await mkdir(this.#home.paths.logs, { recursive: true });
3412
+ const plist = launchAgentPlist({
3413
+ node: process.execPath,
3414
+ entry: realpathSync(this.#options.entry),
3415
+ path: env.PATH ?? "/usr/bin:/bin",
3416
+ log: this.#home.paths.log,
3417
+ ...env.DRYFIT_HOME && { env: { DRYFIT_HOME: env.DRYFIT_HOME } }
3418
+ });
3419
+ const running = await this.#find();
3420
+ if (running) await this.#stop(running);
3421
+ await this.#launchctl(["bootout", `gui/${userInfo().uid}/${LAUNCH_AGENT_LABEL}`]);
3422
+ await writeFile(agentPath(), plist);
3423
+ if (await this.#launchctl([
3424
+ "bootstrap",
3425
+ `gui/${userInfo().uid}`,
3426
+ agentPath()
3427
+ ]) !== 0) {
3428
+ out.fail(`launchctl could not load ${agentPath()}`);
3429
+ return 1;
3430
+ }
3431
+ out.ok(`dryfit now starts at login (${out.path(agentPath())})`);
3432
+ return 0;
3433
+ }
3434
+ async #uninstallAgent() {
3435
+ const { out } = this.#options;
3436
+ if (!existsSync(agentPath())) {
3437
+ out.line("dryfit is not set to start at login.");
3438
+ return 0;
3439
+ }
3440
+ await this.#launchctl(["bootout", `gui/${userInfo().uid}/${LAUNCH_AGENT_LABEL}`]);
3441
+ await rm(agentPath(), { force: true });
3442
+ out.ok("dryfit no longer starts at login");
3443
+ return 0;
3444
+ }
3445
+ async #launchctl(args) {
3446
+ return (await new NodeProcessRunner({ baseEnv: this.#options.env }).run({
3447
+ command: "launchctl",
3448
+ args,
3449
+ cwd: homedir()
3450
+ }).catch(() => void 0))?.exitCode ?? 1;
3451
+ }
3452
+ };
3453
+ function agentPath() {
3454
+ return join(homedir(), "Library", "LaunchAgents", `${LAUNCH_AGENT_LABEL}.plist`);
3455
+ }
3456
+ function isAlive(pid) {
3457
+ try {
3458
+ process.kill(pid, 0);
3459
+ return true;
3460
+ } catch (error) {
3461
+ return error instanceof Error && "code" in error && error.code === "EPERM";
3462
+ }
3463
+ }
3464
+ function signal(pid, name) {
3465
+ try {
3466
+ process.kill(pid, name);
3467
+ } catch {}
3468
+ }
3469
+ async function guardPresent(runner, consumer) {
3470
+ const result = await runner.run({
3471
+ command: "git",
3472
+ args: [
3473
+ "rev-parse",
3474
+ "--git-path",
3475
+ "hooks"
3476
+ ],
3477
+ cwd: consumer
3478
+ }).catch(() => void 0);
3479
+ if (result?.exitCode !== 0) return true;
3480
+ const hook = resolve(consumer, result.stdout.trim(), "pre-commit");
3481
+ if (!await stat(hook).catch(() => void 0)) return false;
3482
+ return hasGuard(await readFile(hook, "utf8"));
3483
+ }
3484
+ // src/cli/output.ts
3485
+ /** Terminal output with optional color. Color is off when NO_COLOR is set or output is not a TTY. */
3486
+ var Output = class {
3487
+ #write;
3488
+ #color;
3489
+ #home;
3490
+ constructor(write, options) {
3491
+ this.#write = write;
3492
+ this.#color = options.color;
3493
+ this.#home = options.home;
3494
+ }
3495
+ line(text = "") {
3496
+ this.#write(`${text}\n`);
3497
+ }
3498
+ bold = (text) => this.#paint(1, 22, text);
3499
+ dim = (text) => this.#paint(2, 22, text);
3500
+ green = (text) => this.#paint(32, 39, text);
3501
+ red = (text) => this.#paint(31, 39, text);
3502
+ yellow = (text) => this.#paint(33, 39, text);
3503
+ cyan = (text) => this.#paint(36, 39, text);
3504
+ ok = (text) => this.line(`${this.green("✓")} ${text}`);
3505
+ fail = (text) => this.line(`${this.red("✗")} ${text}`);
3506
+ step = (text) => this.line(`${this.dim("•")} ${text}`);
3507
+ warn = (text) => this.line(`${this.yellow("!")} ${text}`);
3508
+ /** A path with the home folder shown as `~`. */
3509
+ path = (path) => path === this.#home ? "~" : path.startsWith(`${this.#home}/`) ? `~${path.slice(this.#home.length)}` : path;
3510
+ /** The end of a command's output, indented, which is where npm and builders put the error. */
3511
+ output(text, lines = 15) {
3512
+ const tail = text.trimEnd().split("\n").slice(-lines);
3513
+ for (const entry of tail) this.line(this.dim(` ${entry}`));
3514
+ }
3515
+ #paint(open, close, text) {
3516
+ return this.#color ? `\u001b[${open}m${text}\u001b[${close}m` : text;
3517
+ }
3518
+ };
3519
+ /** Prints one pipeline or daemon event as a line of progress. Job bookkeeping only when `jobs`. */
3520
+ function renderEvent(out, event, options) {
3521
+ switch (event.type) {
3522
+ case "build:started":
3523
+ out.step(`Building ${event.library}…`);
3524
+ return;
3525
+ case "build:succeeded":
3526
+ out.ok(`Built ${event.library}`);
3527
+ return;
3528
+ case "build:failed":
3529
+ out.fail(`Build of ${event.library} failed`);
3530
+ out.output(event.output);
3531
+ return;
3532
+ case "publish:succeeded":
3533
+ out.ok(`Published ${event.library}@${out.cyan(event.version)}`);
3534
+ return;
3535
+ case "install:started":
3536
+ out.step(`Installing into ${out.path(event.consumer)}…`);
3537
+ return;
3538
+ case "install:succeeded":
3539
+ out.ok(`Installed into ${out.path(event.consumer)}`);
3540
+ return;
3541
+ case "install:failed":
3542
+ out.fail(`Install into ${out.path(event.consumer)} failed`);
3543
+ out.output(event.output);
3544
+ return;
3545
+ case "caches:cleared":
3546
+ out.line(out.dim(` cleared ${event.paths.join(", ")}`));
3547
+ return;
3548
+ case "consumer:restored":
3549
+ if (event.library !== void 0) {
3550
+ if (event.ok) out.ok(`Restored ${event.library} in ${out.path(event.consumer)}`);
3551
+ else out.fail(`Restored ${event.library} in ${out.path(event.consumer)}, but the clean install failed`);
3552
+ } else if (event.ok) out.ok(`Restored ${out.path(event.consumer)}`);
3553
+ else out.fail(`Restored the files of ${out.path(event.consumer)}, but the clean install failed`);
3554
+ return;
3555
+ case "library:changed":
3556
+ out.step(`${event.library} changed`);
3557
+ return;
3558
+ case "watch:failed":
3559
+ out.fail(`Stopped watching ${event.library}: ${event.message}. Run \`dryfit watch\` to start again.`);
3560
+ return;
3561
+ case "job:started":
3562
+ if (options.jobs) out.line(out.bold(event.job.label));
3563
+ return;
3564
+ case "job:finished":
3565
+ if (options.jobs && event.error) out.fail(`${event.job.label}: ${event.error.message}`);
3566
+ return;
3567
+ case "job:queued":
3568
+ case "state:changed": return;
3569
+ }
3570
+ }
3571
+ // src/cli/main.ts
3572
+ /** dryfit's name on npm, for the commands it suggests. The command itself is `dryfit`. */
3573
+ const PACKAGE_NAME = "@dryfit/cli";
3574
+ /** An expected problem with how the CLI was used, reported without a stack trace. */
3575
+ var CliError = class extends Error {
3576
+ exitCode;
3577
+ constructor(message, exitCode = 1) {
3578
+ super(message);
3579
+ this.exitCode = exitCode;
3580
+ }
3581
+ };
3582
+ /** The help text, which the website also turns into its CLI reference. */
3583
+ const USAGE = `Usage: dryfit <command> [options]
3584
+
3585
+ Set up
3586
+ init [--root <dir>]... Choose where your projects live and start dryfit
3587
+ add [dir] Register the library in dir (default: here)
3588
+ --publish-dir <dir> Folder to publish, when it cannot be detected
3589
+ --build "<command>" Build command, when it cannot be detected
3590
+ remove <library> Forget a library
3591
+
3592
+ Linking
3593
+ consumers [library] List the projects that use your libraries
3594
+ link <consumer>... Install dev builds of a library into consumers
3595
+ --library <name> Which library (default: the one here, or the only one)
3596
+ --group <name> Link every consumer in a saved group
3597
+ --no-guard Do not add the pre-commit guard
3598
+ restore [consumer]... Put consumers back exactly as they were (alias: unlink)
3599
+ --library <name> Restore only this library and keep the others linked
3600
+ --group <name> --all --force
3601
+
3602
+ Working
3603
+ sync [library] Build, publish and install into linked consumers now
3604
+ watch [library] Sync on every change; Ctrl-C stops following, not watching
3605
+ --detach Turn watching on and return
3606
+ unwatch [library] Stop syncing on change
3607
+ status Libraries, links, groups and warnings
3608
+ events Follow what the daemon is doing
3609
+
3610
+ Groups
3611
+ group save <name> <consumer>... Save consumers that run together
3612
+ group delete <name>
3613
+ group list
3614
+
3615
+ Daemon
3616
+ daemon start|stop|restart|status
3617
+ daemon install|uninstall Start dryfit at login (launchd)
3618
+ doctor Check that everything is in order
3619
+
3620
+ Every command accepts --json.
3621
+ `;
3622
+ /** Runs one CLI invocation and returns its exit code. */
3623
+ async function run(argv, ctx) {
3624
+ const out = new Output(ctx.stdout, {
3625
+ color: ctx.color,
3626
+ home: ctx.home
3627
+ });
3628
+ const err = new Output(ctx.stderr, {
3629
+ color: ctx.color,
3630
+ home: ctx.home
3631
+ });
3632
+ const [name, ...rest] = argv;
3633
+ if (name === void 0 || name === "help" || name === "--help" || name === "-h") {
3634
+ out.line(USAGE.trimEnd());
3635
+ return 0;
3636
+ }
3637
+ if (name === "--version" || name === "-v") {
3638
+ out.line(VERSION);
3639
+ return 0;
3640
+ }
3641
+ const command = COMMANDS[name];
3642
+ if (!command) {
3643
+ err.line(`Unknown command: ${name}\n`);
3644
+ err.line(USAGE.trimEnd());
3645
+ return 2;
3646
+ }
3647
+ let parsed;
3648
+ try {
3649
+ parsed = parseArgs({
3650
+ args: [...rest],
3651
+ allowPositionals: true,
3652
+ strict: true,
3653
+ options: {
3654
+ json: { type: "boolean" },
3655
+ ...command.options
3656
+ }
3657
+ });
3658
+ } catch (error) {
3659
+ err.line(`dryfit ${name}: ${error instanceof Error ? error.message : String(error)}`);
3660
+ return 2;
3661
+ }
3662
+ const json = parsed.values.json === true;
3663
+ try {
3664
+ return await command.run({
3665
+ positionals: parsed.positionals,
3666
+ values: parsed.values,
3667
+ ctx,
3668
+ out,
3669
+ err,
3670
+ json
3671
+ });
3672
+ } catch (error) {
3673
+ return reportError(err, error);
3674
+ }
3675
+ }
3676
+ function reportError(err, error) {
3677
+ if (error instanceof CliError) {
3678
+ err.line(`dryfit: ${error.message}`);
3679
+ return error.exitCode;
3680
+ }
3681
+ if (explain(err, error)) return 1;
3682
+ err.line(`dryfit: unexpected error: ${error instanceof Error ? error.message : String(error)}`);
3683
+ err.line(err.dim("This is a bug in dryfit. The daemon log may say more: ~/.dryfit/logs/daemon.log"));
3684
+ return 1;
3685
+ }
3686
+ /** Prints an error dryfit knows about (message, captured output, hint); false for anything else. */
3687
+ function explain(err, error) {
3688
+ if (!(error instanceof ApiError || error instanceof DryfitError)) return false;
3689
+ err.line(`dryfit: ${error.message}`);
3690
+ const output = error.details.output;
3691
+ if (typeof output === "string" && output.length > 0) err.output(output);
3692
+ const hint = HINTS[error.code];
3693
+ if (hint) err.line(err.dim(hint));
3694
+ return true;
3695
+ }
3696
+ const HINTS = {
3697
+ "manifest-drifted": "Commit or stash those changes first, or run `dryfit restore --force` to overwrite them.",
3698
+ "library-not-found": "Run `dryfit status` to see registered libraries, or `dryfit add` in the library.",
3699
+ "not-a-consumer": "Check the path, or run `dryfit consumers` to see which projects use the library.",
3700
+ "library-linked": "Run `dryfit restore` for those consumers first.",
3701
+ "snapshot-missing": "dryfit has nothing to restore there: it was never linked, or was already restored.",
3702
+ "daemon-unavailable": "Start it with `dryfit daemon start`, or run `dryfit doctor`.",
3703
+ "daemon-failed": "See `dryfit doctor` and the log in ~/.dryfit/logs/daemon.log.",
3704
+ unauthorized: "The token changed since the daemon started. Run `dryfit daemon restart`.",
3705
+ "invalid-config": "Fix the file, or delete it and run `dryfit init` again.",
3706
+ "group-not-found": "Run `dryfit group list` to see saved groups."
3707
+ };
3708
+ const absolute = (ctx, path) => isAbsolute(path) ? resolve(path) : resolve(ctx.cwd, path);
3709
+ const strings = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
3710
+ const string = (value) => typeof value === "string" ? value : void 0;
3711
+ /**
3712
+ * The library a command is about: the one named, else the registered library whose folder contains
3713
+ * the current one, else the only registered library.
3714
+ */
3715
+ function resolveLibrary(status, named, cwd) {
3716
+ if (named) return named;
3717
+ const containing = status.libraries.filter((library) => cwd === library.root || cwd.startsWith(`${library.root}/`)).sort((a, b) => b.root.length - a.root.length)[0];
3718
+ if (containing) return containing.name;
3719
+ const [only, ...others] = status.libraries;
3720
+ if (only && others.length === 0) return only.name;
3721
+ if (!only) throw new CliError("No library is registered yet. Run `dryfit add` in your library first.");
3722
+ throw new CliError(`Which library? Pass --library: ${status.libraries.map((library) => library.name).join(", ")}`);
3723
+ }
3724
+ /** Prints a result for scripts; the exit code still says whether everything succeeded. */
3725
+ /** The linked project `cwd` is in (the nearest, for nested projects), or `cwd` itself. */
3726
+ function linkedProjectAround(status, cwd) {
3727
+ return status.links.map((link) => link.consumer).filter((consumer) => cwd === consumer || cwd.startsWith(`${consumer}/`)).sort((a, b) => b.length - a.length)[0] ?? cwd;
3728
+ }
3729
+ function printJson(out, value, exitCode = 0) {
3730
+ out.line(JSON.stringify(value, null, 2));
3731
+ return exitCode;
3732
+ }
3733
+ const anyFailed = (outcomes) => outcomes.some((outcome) => outcome.status === "failed") ? 1 : 0;
3734
+ /**
3735
+ * Runs `task` while printing the daemon's events, subscribing first so that none are missed.
3736
+ * `relevant` filters what is shown.
3737
+ */
3738
+ async function withProgress(input, client, relevant, task) {
3739
+ if (input.json) return task();
3740
+ const controller = new AbortController();
3741
+ await new Promise((resolveOpen) => {
3742
+ client.events((event) => relevant(event) && renderEvent(input.out, event, { jobs: false }), {
3743
+ signal: controller.signal,
3744
+ onOpen: resolveOpen
3745
+ }).catch(() => resolveOpen());
3746
+ });
3747
+ try {
3748
+ return await task();
3749
+ } finally {
3750
+ controller.abort();
3751
+ }
3752
+ }
3753
+ const aboutLibrary = (library) => (event) => "library" in event ? event.library === library : event.type === "consumer:restored";
3754
+ /** Follows events until Ctrl-C. */
3755
+ async function follow(input, client, relevant) {
3756
+ const signal = input.ctx.signal ?? new AbortController().signal;
3757
+ await client.events((event) => {
3758
+ if (!relevant(event)) return;
3759
+ if (input.json) input.out.line(JSON.stringify(event));
3760
+ else renderEvent(input.out, event, { jobs: true });
3761
+ }, { signal });
3762
+ }
3763
+ function describeLibrary(out, library) {
3764
+ return `${library.build ? `${[library.build.command.split("/").at(-1), ...library.build.args].join(" ")} → ` : ""}${out.path(library.publishDir)}`;
3765
+ }
3766
+ const COMMANDS = {
3767
+ init: {
3768
+ options: { root: {
3769
+ type: "string",
3770
+ multiple: true
3771
+ } },
3772
+ async run({ values, ctx, out, json }) {
3773
+ const local = requireLocal(ctx);
3774
+ const roots = strings(values.root).map((root) => absolute(ctx, root));
3775
+ const result = await local.init(roots.length > 0 ? roots : [resolve(ctx.cwd, "..")]);
3776
+ const status = await (await ctx.connect()).call("status", {});
3777
+ if (json) return printJson(out, {
3778
+ ...result,
3779
+ registryUrl: status.daemon.registryUrl
3780
+ });
3781
+ out.ok("dryfit is ready");
3782
+ out.line(` home ${out.path(result.home)}`);
3783
+ out.line(` roots ${result.roots.map(out.path).join(", ")}`);
3784
+ out.line(` registry ${status.daemon.registryUrl}`);
3785
+ const npx = /[\\/]_npx[\\/]/.test(ctx.entry ?? "");
3786
+ const dryfit = npx ? `npx ${PACKAGE_NAME}` : "dryfit";
3787
+ out.line();
3788
+ out.line(`Next: run ${out.bold(`${dryfit} add`)} in a library, then ${out.bold(`${dryfit} link <consumer>`)}.`);
3789
+ if (npx) out.line(`To type ${out.bold("dryfit")} directly, install it: npm install --global ${PACKAGE_NAME}`);
3790
+ return 0;
3791
+ }
3792
+ },
3793
+ add: {
3794
+ options: {
3795
+ "publish-dir": { type: "string" },
3796
+ build: { type: "string" }
3797
+ },
3798
+ async run({ positionals, values, ctx, out, json }) {
3799
+ const root = absolute(ctx, positionals[0] ?? ".");
3800
+ const publishDir = string(values["publish-dir"]);
3801
+ const build = string(values.build)?.trim().split(/\s+/);
3802
+ if (build?.[0] === "") throw new CliError("--build needs a command, such as --build \"npm run build\"", 2);
3803
+ const result = await (await ctx.connect()).call("register", {
3804
+ root,
3805
+ ...publishDir !== void 0 && { publishDir: absolute({
3806
+ ...ctx,
3807
+ cwd: root
3808
+ }, publishDir) },
3809
+ ...build?.[0] !== void 0 && { build: {
3810
+ command: build[0],
3811
+ args: build.slice(1)
3812
+ } }
3813
+ });
3814
+ if (json) return printJson(out, result);
3815
+ const how = result.detected === "given" ? "" : out.dim(` (detected: ${result.detected})`);
3816
+ out.ok(`Registered ${out.bold(result.library.name)}: ${describeLibrary(out, result.library)}${how}`);
3817
+ out.line(`Next: ${out.bold("dryfit consumers")} to see who uses it, then ${out.bold("dryfit link <consumer>")}.`);
3818
+ return 0;
3819
+ }
3820
+ },
3821
+ remove: { async run({ positionals, ctx, out, json }) {
3822
+ const library = positionals[0];
3823
+ if (!library) throw new CliError("Which library? Usage: dryfit remove <library>", 2);
3824
+ const result = await (await ctx.connect()).call("unregister", { library });
3825
+ if (json) return printJson(out, result);
3826
+ out.ok(`Removed ${library}`);
3827
+ return 0;
3828
+ } },
3829
+ consumers: { async run({ positionals, ctx, out, json }) {
3830
+ const client = await ctx.connect();
3831
+ const [found, status] = await Promise.all([client.call("discover", positionals[0] ? { library: positionals[0] } : {}), client.call("status", {})]);
3832
+ if (json) return printJson(out, found);
3833
+ if (found.length === 0) {
3834
+ out.line("No consumers found. Add the folders your projects live in with `dryfit init --root <dir>`.");
3835
+ return 0;
3836
+ }
3837
+ const linked = new Set(status.links.map((link) => `${link.library}\u0000${link.consumer}`));
3838
+ for (const consumer of found) {
3839
+ out.line(`${out.bold(consumer.name ?? "(unnamed)")} ${out.dim(out.path(consumer.root))}`);
3840
+ for (const library of consumer.libraries) {
3841
+ const state = linked.has(`${library.name}\u0000${consumer.root}`) ? out.green("linked") : "";
3842
+ out.line(` ${library.name} ${out.dim(library.range)} ${state}`.trimEnd());
3843
+ }
3844
+ }
3845
+ return 0;
3846
+ } },
3847
+ link: {
3848
+ options: {
3849
+ library: { type: "string" },
3850
+ group: { type: "string" },
3851
+ "no-guard": { type: "boolean" }
3852
+ },
3853
+ async run(input) {
3854
+ const { positionals, values, ctx, out, json } = input;
3855
+ const client = await ctx.connect();
3856
+ const library = resolveLibrary(await client.call("status", {}), string(values.library), ctx.cwd);
3857
+ const group = string(values.group);
3858
+ if (group) {
3859
+ const outcomes = await client.call("linkGroup", {
3860
+ group,
3861
+ library
3862
+ });
3863
+ if (json) return printJson(out, outcomes, anyFailed(outcomes));
3864
+ for (const outcome of outcomes) if (outcome.status === "done") out.ok(`Linked ${library} into ${out.path(outcome.consumer)}`);
3865
+ else if (outcome.status === "skipped") out.step(`Skipped ${out.path(outcome.consumer)}: ${outcome.message}`);
3866
+ else out.fail(`${out.path(outcome.consumer)}: ${outcome.message}`);
3867
+ return anyFailed(outcomes);
3868
+ }
3869
+ if (positionals.length === 0) throw new CliError("Which consumers? Usage: dryfit link <consumer>...", 2);
3870
+ const results = [];
3871
+ let failed = 0;
3872
+ for (const consumer of positionals.map((path) => absolute(ctx, path))) {
3873
+ let result;
3874
+ try {
3875
+ result = await client.call("link", {
3876
+ library,
3877
+ consumer,
3878
+ ...values["no-guard"] === true && { guard: false }
3879
+ });
3880
+ } catch (error) {
3881
+ if (!(error instanceof ApiError || error instanceof DryfitError)) throw error;
3882
+ failed = 1;
3883
+ results.push({
3884
+ consumer,
3885
+ error: {
3886
+ code: error.code,
3887
+ message: error.message
3888
+ }
3889
+ });
3890
+ if (!json) explain(input.err, error);
3891
+ continue;
3892
+ }
3893
+ results.push(result);
3894
+ if (json) continue;
3895
+ const notes = ["snapshot taken"];
3896
+ if (result.guard === "installed") notes.push("commit guard installed");
3897
+ if (result.guard === "not-a-repo") notes.push("not a git repository, so no commit guard");
3898
+ out.ok(`Linked ${library} into ${out.path(consumer)} ${out.dim(`(${notes.join(", ")})`)}`);
3899
+ if (result.link.installedVersion) out.line(out.dim(` running ${result.link.installedVersion}`));
3900
+ }
3901
+ if (json) return printJson(out, results, failed);
3902
+ if (failed === 0) out.line(`Next: ${out.bold("dryfit sync")} to build and install, or ${out.bold("dryfit watch")} to do it on every change.`);
3903
+ return failed;
3904
+ }
3905
+ },
3906
+ restore: restoreCommand(),
3907
+ unlink: restoreCommand(),
3908
+ sync: { async run(input) {
3909
+ const { positionals, ctx, out, json } = input;
3910
+ const client = await ctx.connect();
3911
+ const library = resolveLibrary(await client.call("status", {}), positionals[0], ctx.cwd);
3912
+ let result;
3913
+ try {
3914
+ result = await withProgress(input, client, aboutLibrary(library), () => client.call("sync", { library }));
3915
+ } catch (error) {
3916
+ if (!json && error instanceof ApiError && (error.code === "build-failed" || error.code === "publish-failed")) throw new CliError(error.message);
3917
+ throw error;
3918
+ }
3919
+ const failed = result.installs.filter((install) => !install.ok).length;
3920
+ if (json) return printJson(out, result, failed > 0 ? 1 : 0);
3921
+ if (result.installs.length === 0) out.line(out.dim("Nothing is linked yet, so nothing was installed."));
3922
+ else if (failed > 0) out.line(out.red(`${failed} of ${result.installs.length} consumers did not take ${result.version}.`));
3923
+ return failed > 0 ? 1 : 0;
3924
+ } },
3925
+ watch: {
3926
+ options: { detach: { type: "boolean" } },
3927
+ async run(input) {
3928
+ const { positionals, values, ctx, out, json } = input;
3929
+ const client = await ctx.connect();
3930
+ const library = resolveLibrary(await client.call("status", {}), positionals[0], ctx.cwd);
3931
+ const record = await client.call("watch", {
3932
+ library,
3933
+ enabled: true
3934
+ });
3935
+ if (json && values.detach === true) return printJson(out, record);
3936
+ if (!json) out.ok(`Watching ${library}: every change builds, publishes and installs`);
3937
+ if (values.detach === true) return 0;
3938
+ if (!json) out.line(out.dim("Following its activity. Ctrl-C stops following; watching continues until `dryfit unwatch`."));
3939
+ await follow(input, client, aboutLibrary(library));
3940
+ return 0;
3941
+ }
3942
+ },
3943
+ unwatch: { async run({ positionals, ctx, out, json }) {
3944
+ const client = await ctx.connect();
3945
+ const library = resolveLibrary(await client.call("status", {}), positionals[0], ctx.cwd);
3946
+ const record = await client.call("watch", {
3947
+ library,
3948
+ enabled: false
3949
+ });
3950
+ if (json) return printJson(out, record);
3951
+ out.ok(`Stopped watching ${library}`);
3952
+ return 0;
3953
+ } },
3954
+ status: { async run({ ctx, out, json }) {
3955
+ const status = await (await ctx.connect()).call("status", {});
3956
+ if (json) return printJson(out, status);
3957
+ printStatus(out, status);
3958
+ return 0;
3959
+ } },
3960
+ events: { async run(input) {
3961
+ const client = await input.ctx.connect();
3962
+ if (!input.json) input.out.line(input.out.dim("Following dryfit. Ctrl-C to stop."));
3963
+ await follow(input, client, () => true);
3964
+ return 0;
3965
+ } },
3966
+ group: { async run({ positionals, ctx, out, json }) {
3967
+ const [action, name, ...consumers] = positionals;
3968
+ const client = await ctx.connect();
3969
+ if (action === "list" || action === void 0) {
3970
+ const { groups } = await client.call("status", {});
3971
+ if (json) return printJson(out, groups);
3972
+ if (groups.length === 0) out.line("No groups yet. Save one with `dryfit group save <name> <consumer>...`.");
3973
+ for (const group of groups) out.line(`${out.bold(group.name)} ${group.consumers.map(out.path).join(", ")}`);
3974
+ return 0;
3975
+ }
3976
+ if (!name) throw new CliError(`Usage: dryfit group ${action} <name>`, 2);
3977
+ if (action === "save") {
3978
+ if (consumers.length === 0) throw new CliError("Usage: dryfit group save <name> <consumer>...", 2);
3979
+ const group = await client.call("saveGroup", {
3980
+ name,
3981
+ consumers: consumers.map((path) => absolute(ctx, path))
3982
+ });
3983
+ if (json) return printJson(out, group);
3984
+ out.ok(`Saved group ${group.name}: ${group.consumers.map(out.path).join(", ")}`);
3985
+ return 0;
3986
+ }
3987
+ if (action === "delete") {
3988
+ const result = await client.call("deleteGroup", { name });
3989
+ if (json) return printJson(out, result);
3990
+ out.ok(`Deleted group ${name}`);
3991
+ return 0;
3992
+ }
3993
+ throw new CliError(`Unknown group action: ${action}. Use save, delete or list.`, 2);
3994
+ } },
3995
+ daemon: { async run({ positionals, ctx }) {
3996
+ const action = positionals[0] ?? "status";
3997
+ const actions = [
3998
+ "start",
3999
+ "stop",
4000
+ "restart",
4001
+ "status",
4002
+ "run",
4003
+ "install",
4004
+ "uninstall"
4005
+ ];
4006
+ const known = actions.find((candidate) => candidate === action);
4007
+ if (!known) throw new CliError(`Unknown daemon action: ${action}. Use ${actions.join(", ")}.`, 2);
4008
+ return requireLocal(ctx).daemon(known);
4009
+ } },
4010
+ doctor: { async run({ ctx, out, json }) {
4011
+ return requireLocal(ctx).doctor(out, json);
4012
+ } }
4013
+ };
4014
+ function restoreCommand() {
4015
+ return {
4016
+ options: {
4017
+ group: { type: "string" },
4018
+ all: { type: "boolean" },
4019
+ force: { type: "boolean" },
4020
+ library: { type: "string" }
4021
+ },
4022
+ async run(input) {
4023
+ const { positionals, values, ctx, out, json } = input;
4024
+ const client = await ctx.connect();
4025
+ const force = values.force === true ? { force: true } : {};
4026
+ const library = string(values.library);
4027
+ const group = string(values.group);
4028
+ if (group) {
4029
+ const outcomes = await client.call("restoreGroup", {
4030
+ group,
4031
+ ...force
4032
+ });
4033
+ if (json) return printJson(out, outcomes, anyFailed(outcomes));
4034
+ for (const outcome of outcomes) if (outcome.status === "done") out.ok(`Restored ${out.path(outcome.consumer)}`);
4035
+ else if (outcome.status === "skipped") out.step(`Skipped ${out.path(outcome.consumer)}: not linked`);
4036
+ else out.fail(`${out.path(outcome.consumer)}: ${outcome.message}`);
4037
+ return anyFailed(outcomes);
4038
+ }
4039
+ let consumers = positionals.map((path) => absolute(ctx, path));
4040
+ if (values.all === true) {
4041
+ consumers = [...new Set((await client.call("status", {})).links.map((link) => link.consumer))];
4042
+ if (consumers.length === 0) out.line("Nothing is linked.");
4043
+ } else if (consumers.length === 0) consumers = [linkedProjectAround(await client.call("status", {}), ctx.cwd)];
4044
+ const results = [];
4045
+ let failed = false;
4046
+ for (const consumer of consumers) {
4047
+ let result;
4048
+ try {
4049
+ result = await client.call("restore", {
4050
+ consumer,
4051
+ ...library && { library },
4052
+ ...force
4053
+ });
4054
+ } catch (error) {
4055
+ if (!(error instanceof ApiError || error instanceof DryfitError)) throw error;
4056
+ failed = true;
4057
+ results.push({
4058
+ consumer,
4059
+ ok: false,
4060
+ error: {
4061
+ code: error.code,
4062
+ message: error.message
4063
+ }
4064
+ });
4065
+ if (!json) explain(input.err, error);
4066
+ continue;
4067
+ }
4068
+ results.push({
4069
+ consumer,
4070
+ ...result
4071
+ });
4072
+ if (!result.ok) failed = true;
4073
+ if (json) continue;
4074
+ const what = library ? `${library} in ${out.path(consumer)}` : out.path(consumer);
4075
+ if (result.ok) out.ok(`Restored ${what}`);
4076
+ else {
4077
+ out.fail(`Restored the files of ${what}, but the clean install failed:`);
4078
+ out.output(result.output);
4079
+ }
4080
+ }
4081
+ return json ? printJson(out, results, failed ? 1 : 0) : failed ? 1 : 0;
4082
+ }
4083
+ };
4084
+ }
4085
+ function printStatus(out, status) {
4086
+ const { daemon, jobs } = status;
4087
+ const activity = jobs.running ? `running ${jobs.running.label}${jobs.queued.length > 0 ? ` (+${jobs.queued.length} queued)` : ""}` : "idle";
4088
+ out.line(out.dim(`dryfit ${daemon.version} · registry ${daemon.registryUrl} · ${activity}`));
4089
+ out.line();
4090
+ out.line(out.bold("Libraries"));
4091
+ if (status.libraries.length === 0) out.line(out.dim(" None yet. Run `dryfit add` in a library folder."));
4092
+ for (const library of status.libraries) {
4093
+ const notes = [library.lastPublishedVersion ? `last ${library.lastPublishedVersion}` : "not published yet", ...library.watch ? [out.cyan("watching")] : []];
4094
+ out.line(` ${out.bold(library.name)} ${out.dim(out.path(library.root))} ${notes.join(" ")}`);
4095
+ }
4096
+ out.line();
4097
+ out.line(out.bold("Links"));
4098
+ if (status.links.length === 0) out.line(out.dim(" None. Link a consumer with `dryfit link <consumer>`."));
4099
+ for (const link of status.links) {
4100
+ const state = link.status === "installed" ? out.green(`installed ${link.installedVersion ?? ""}`.trimEnd()) : link.status === "failed" ? out.red("last install failed") : out.yellow("waiting for the first sync");
4101
+ out.line(` ${link.library} → ${out.path(link.consumer)} ${state}${link.guard ? out.dim(" guarded") : ""}`);
4102
+ }
4103
+ if (status.groups.length > 0) {
4104
+ out.line();
4105
+ out.line(out.bold("Groups"));
4106
+ for (const group of status.groups) out.line(` ${group.name} ${out.dim(group.consumers.map(out.path).join(", "))}`);
4107
+ }
4108
+ if (status.warnings.length > 0) {
4109
+ out.line();
4110
+ for (const warning of status.warnings) {
4111
+ const versions = warning.versions.map((entry) => `${out.path(entry.consumer)} ${entry.version}`).join(", ");
4112
+ out.warn(`${warning.group} runs different versions of ${warning.library}: ${versions}. Run \`dryfit sync\`.`);
4113
+ }
4114
+ }
4115
+ }
4116
+ function requireLocal(ctx) {
4117
+ if (!ctx.local) throw new CliError("This command needs local access to the machine.");
4118
+ return ctx.local;
4119
+ }
4120
+ // src/cli/bin.ts
4121
+ const color = process.stdout.isTTY === true && !process.env.NO_COLOR;
4122
+ const stdout = (text) => void process.stdout.write(text);
4123
+ const stderr = (text) => void process.stderr.write(text);
4124
+ const home = homedir();
4125
+ const interrupt = new AbortController();
4126
+ for (const name of ["SIGINT", "SIGTERM"]) process.on(name, () => {
4127
+ if (interrupt.signal.aborted) process.exit(130);
4128
+ interrupt.abort();
4129
+ });
4130
+ const local = new LocalMachine({
4131
+ home: DryfitHome.locate(process.env, home),
4132
+ version: VERSION,
4133
+ env: process.env,
4134
+ entry: process.argv[1] ?? "",
4135
+ out: new Output(stdout, {
4136
+ color,
4137
+ home
4138
+ }),
4139
+ err: new Output(stderr, {
4140
+ color: process.stderr.isTTY === true && !process.env.NO_COLOR,
4141
+ home
4142
+ }),
4143
+ signal: interrupt.signal
4144
+ });
4145
+ const argv = process.argv.slice(2);
4146
+ const code = await run(argv, {
4147
+ cwd: process.cwd(),
4148
+ env: process.env,
4149
+ home,
4150
+ stdout,
4151
+ stderr,
4152
+ connect: () => local.connect(),
4153
+ local,
4154
+ color,
4155
+ signal: interrupt.signal,
4156
+ entry: process.argv[1] ?? ""
4157
+ });
4158
+ if (argv[0] === "daemon" && argv[1] === "run") process.exit(code);
4159
+ process.exitCode = code;
4160
+ export {};