depkill 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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -3
  3. package/data/module-replacements.LICENSE +21 -0
  4. package/data/module-replacements.json +947 -0
  5. package/dist/src/anticheat/constants.js +105 -0
  6. package/dist/src/anticheat/imports.js +419 -0
  7. package/dist/src/anticheat/tokens.js +177 -0
  8. package/dist/src/anticheat.js +189 -0
  9. package/dist/src/card/format.js +113 -0
  10. package/dist/src/card/svg.js +137 -0
  11. package/dist/src/card.js +364 -0
  12. package/dist/src/check.js +139 -0
  13. package/dist/src/cli.js +333 -0
  14. package/dist/src/gate/holdout.js +78 -0
  15. package/dist/src/gate/process.js +78 -0
  16. package/dist/src/gate.js +532 -0
  17. package/dist/src/graph.js +148 -0
  18. package/dist/src/holdout/perturb.js +108 -0
  19. package/dist/src/holdout/snapshot.js +113 -0
  20. package/dist/src/init.js +76 -0
  21. package/dist/src/inputs/generate.js +282 -0
  22. package/dist/src/inputs.js +273 -0
  23. package/dist/src/measure.js +149 -0
  24. package/dist/src/project.js +72 -0
  25. package/dist/src/record.js +180 -0
  26. package/dist/src/registry.js +78 -0
  27. package/dist/src/replacement.js +146 -0
  28. package/dist/src/runner.js +227 -0
  29. package/dist/src/runtime/agent-inputs.js +36 -0
  30. package/dist/src/runtime/child.js +260 -0
  31. package/dist/src/runtime/esm-hooks.js +44 -0
  32. package/dist/src/runtime/fsguard.js +264 -0
  33. package/dist/src/runtime/inspect.js +115 -0
  34. package/dist/src/runtime/lockdown.js +157 -0
  35. package/dist/src/runtime/protocol.js +16 -0
  36. package/dist/src/scan.js +210 -0
  37. package/dist/src/serialize.js +399 -0
  38. package/dist/src/tooling.js +88 -0
  39. package/dist/src/types.js +9 -0
  40. package/dist/src/usage/common.js +36 -0
  41. package/dist/src/usage/fallback.js +227 -0
  42. package/dist/src/usage/ts.js +142 -0
  43. package/dist/src/usage.js +97 -0
  44. package/dist/src/util/exports.js +86 -0
  45. package/dist/src/util/fs.js +64 -0
  46. package/dist/src/util/term.js +61 -0
  47. package/package.json +54 -6
  48. package/skills/AGENTS.section.md +52 -0
  49. package/skills/depkill/SKILL.md +148 -0
@@ -0,0 +1,149 @@
1
+ // `card` measurements: a clean install of a manifest + lockfile in a fresh temp directory (never the project's own
2
+ // node_modules, which may be stale or hand-edited), measured with the same graph code as `scan`.
3
+ import { cpSync, existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { runProcess } from './gate/process.js';
7
+ import { buildGraph, dependencyClosure } from './graph.js';
8
+ import { fetchMaintainers } from './registry.js';
9
+ import { DepkillError } from './types.js';
10
+ import { readJson } from './util/fs.js';
11
+ const INSTALL_TIMEOUT_MS = 10 * 60 * 1000;
12
+ const ERROR_LINES = 20;
13
+ /** Lockfile names per package manager, preferred first; every one present is copied. */
14
+ const LOCKFILES = {
15
+ npm: ['package-lock.json', 'npm-shrinkwrap.json'],
16
+ pnpm: ['pnpm-lock.yaml'],
17
+ yarn: ['yarn.lock'],
18
+ 'yarn-berry': ['yarn.lock'],
19
+ };
20
+ /**
21
+ * Package-manager configuration an install depends on (registry and auth, yarn's pinned release and plugins,
22
+ * pnpm settings and patches): copied when present, so the temp install resolves like the project's. No sources.
23
+ */
24
+ const CONFIG_PATHS = ['.npmrc', '.yarnrc', '.yarnrc.yml', '.yarn/releases', '.yarn/plugins', '.yarn/patches', '.pnpmfile.cjs', 'pnpm-workspace.yaml', 'patches'];
25
+ /**
26
+ * Clean, script-free install command. With a lockfile (default) the install is frozen: npm `ci`, pnpm
27
+ * `--frozen-lockfile`, yarn `--frozen-lockfile`, yarn berry `--immutable`. `offline` adds the offline flag
28
+ * (yarn berry: `YARN_ENABLE_NETWORK=0`). Yarn berry always gets `YARN_NODE_LINKER=node-modules`.
29
+ */
30
+ export function installCommand(pm, opts = {}) {
31
+ const frozen = opts.lockfile !== false;
32
+ const offline = opts.offline === true ? ['--offline'] : [];
33
+ switch (pm) {
34
+ case 'npm':
35
+ return { cmd: 'npm', args: [frozen ? 'ci' : 'install', '--ignore-scripts', '--no-audit', '--no-fund', ...(frozen ? [] : ['--package-lock=false']), ...offline] };
36
+ case 'pnpm':
37
+ return { cmd: 'pnpm', args: ['install', frozen ? '--frozen-lockfile' : '--no-frozen-lockfile', '--ignore-scripts', ...offline] };
38
+ case 'yarn':
39
+ return { cmd: 'yarn', args: ['install', ...(frozen ? ['--frozen-lockfile'] : []), '--ignore-scripts', ...(frozen ? [] : ['--no-lockfile']), ...offline] };
40
+ case 'yarn-berry': {
41
+ // node_modules even when the project uses Plug'n'Play: the measurement reads node_modules.
42
+ const env = { YARN_NODE_LINKER: 'node-modules', ...(opts.offline === true ? { YARN_ENABLE_NETWORK: '0' } : {}) };
43
+ return { cmd: 'yarn', args: ['install', frozen ? '--immutable' : '--no-immutable', '--mode=skip-build'], env };
44
+ }
45
+ }
46
+ }
47
+ /** The lockfile `pm` would use in `dir`, or null. */
48
+ export function findLockfile(dir, pm) {
49
+ const name = LOCKFILES[pm].find((candidate) => existsSync(join(dir, candidate)));
50
+ return name === undefined ? null : join(dir, name);
51
+ }
52
+ function commandText(command) {
53
+ const env = Object.entries(command.env ?? {}).map(([key, value]) => `${key}=${value} `).join('');
54
+ return `${env}${[command.cmd, ...command.args].join(' ')}`;
55
+ }
56
+ /** npm, pnpm and yarn are `.cmd` shims on Windows: run them through the shell there (every token is a fixed flag). */
57
+ const defaultInstall = (cwd, command, timeoutMs) => (process.platform === 'win32'
58
+ ? runProcess([command.cmd, ...command.args].join(' '), [], { cwd, timeoutMs, shell: true, env: command.env })
59
+ : runProcess(command.cmd, command.args, { cwd, timeoutMs, env: command.env }));
60
+ function installError(command, result, offline) {
61
+ const why = result.timedOut ? 'timed out after 10 minutes' : `failed (exit code ${result.code ?? 'none'})`;
62
+ const hint = offline ? '\nThe offline install needs every package in the package manager cache; run depkill card without --offline.' : '';
63
+ const tail = result.output.replace(/\r\n/g, '\n').trimEnd().split('\n').slice(-ERROR_LINES).join('\n');
64
+ return new DepkillError(`Clean install for measuring: ${commandText(command)} ${why}.${hint}${tail === '' ? '' : `\n${tail}`}`);
65
+ }
66
+ /** Best effort: Windows may hold files briefly (antivirus, indexer), so rmSync retries on EBUSY/EPERM. */
67
+ function removeTemp(dir) {
68
+ try {
69
+ rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
70
+ }
71
+ catch (error) {
72
+ process.stderr.write(`depkill: could not remove the temp install ${dir}: ${error instanceof Error ? error.message : String(error)}\n`);
73
+ }
74
+ }
75
+ /** Packages, sizes and install scripts of `graph`; prod = everything reachable from a prod dependency. */
76
+ export function measurementOf(graph, maintainers) {
77
+ const all = [...graph.nodes.values()];
78
+ const prodIds = new Set([...graph.direct.prod.keys()].flatMap((name) => dependencyClosure(graph, name).map((node) => node.id)));
79
+ const prod = all.filter((node) => prodIds.has(node.id));
80
+ const bytes = (nodes) => nodes.reduce((total, node) => total + node.sizeBytes, 0);
81
+ return {
82
+ packages: all.length,
83
+ prodPackages: prod.length,
84
+ bytes: bytes(all),
85
+ prodBytes: bytes(prod),
86
+ installScripts: all.filter((node) => node.hasInstallScript).length,
87
+ maintainers,
88
+ };
89
+ }
90
+ /** buildGraph over a finished temp install; any failure names the temporary install (not the user's project). */
91
+ function readInstall(temp, pm) {
92
+ try {
93
+ return buildGraph(temp, readJson(join(temp, 'package.json')));
94
+ }
95
+ catch (error) {
96
+ throw new DepkillError(`could not read the temporary install (${pm}): ${error instanceof Error ? error.message : String(error)}`);
97
+ }
98
+ }
99
+ function readManifest(dir) {
100
+ const file = join(dir, 'package.json');
101
+ if (!existsSync(file))
102
+ throw new DepkillError(`No package.json in ${dir} to measure.`);
103
+ try {
104
+ readJson(file);
105
+ }
106
+ catch (error) {
107
+ throw new DepkillError(error instanceof Error ? error.message : String(error));
108
+ }
109
+ }
110
+ /**
111
+ * Installs `manifestDir/package.json` + its lockfile (+ package-manager config from `configDir`) into a fresh
112
+ * `realpath(os.tmpdir()/depkill-*)` with `pm`'s clean install (installCommand; 10-minute timeout) and measures it:
113
+ * every installed package (buildGraph), prod = reachable from `dependencies`, maintainers over all packages from the
114
+ * registry (null when offline or unreachable). The temp directory is always removed. DepkillError (exit 2) on a
115
+ * missing manifest or a failed install, with the last 20 lines of its output.
116
+ */
117
+ export async function measureProject(manifestDir, pm, opts) {
118
+ readManifest(manifestDir);
119
+ const lockfiles = LOCKFILES[pm].filter((name) => existsSync(join(manifestDir, name)));
120
+ const command = installCommand(pm, { offline: opts.offline, lockfile: lockfiles.length > 0 });
121
+ const configDir = opts.configDir ?? manifestDir;
122
+ let created = null;
123
+ try {
124
+ created = mkdtempSync(join(tmpdir(), 'depkill-'));
125
+ const temp = realpathSync(created);
126
+ for (const name of ['package.json', ...lockfiles])
127
+ cpSync(join(manifestDir, name), join(temp, name));
128
+ for (const rel of CONFIG_PATHS) {
129
+ const from = join(configDir, ...rel.split('/'));
130
+ if (existsSync(from))
131
+ cpSync(from, join(temp, ...rel.split('/')), { recursive: true });
132
+ }
133
+ const result = await (opts.install ?? defaultInstall)(temp, command, INSTALL_TIMEOUT_MS);
134
+ if (result.timedOut || result.code !== 0)
135
+ throw installError(command, result, opts.offline);
136
+ const graph = readInstall(temp, pm);
137
+ // fetchMaintainers would return null offline too; it is not even called then.
138
+ const maintainers = opts.offline ? null : await fetchMaintainers([...graph.nodes.values()], { offline: false });
139
+ return { measurement: measurementOf(graph, maintainers), graph, withoutLockfile: lockfiles.length === 0 };
140
+ }
141
+ finally {
142
+ if (created !== null)
143
+ removeTemp(created);
144
+ }
145
+ }
146
+ /** measureProject, numbers only. */
147
+ export async function measureInstall(manifestDir, pm, opts) {
148
+ return (await measureProject(manifestDir, pm, opts)).measurement;
149
+ }
@@ -0,0 +1,72 @@
1
+ import { existsSync, realpathSync, statSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { DepkillError } from './types.js';
5
+ import { readJson } from './util/fs.js';
6
+ function isDirectory(p) {
7
+ try {
8
+ return statSync(p).isDirectory();
9
+ }
10
+ catch {
11
+ return false;
12
+ }
13
+ }
14
+ /** Nearest directory at or above `start` that contains a package.json, or null. */
15
+ function findRoot(start) {
16
+ for (let dir = resolve(start);; dir = dirname(dir)) {
17
+ if (existsSync(join(dir, 'package.json')))
18
+ return dir;
19
+ if (dirname(dir) === dir)
20
+ return null;
21
+ }
22
+ }
23
+ function detectPm(root) {
24
+ const at = (name) => (existsSync(join(root, name)) ? join(root, name) : null);
25
+ const pnpm = at('pnpm-lock.yaml');
26
+ if (pnpm)
27
+ return { pm: 'pnpm', lockfile: pnpm };
28
+ const yarn = at('yarn.lock');
29
+ if (yarn)
30
+ return { pm: at('.yarnrc.yml') ? 'yarn-berry' : 'yarn', lockfile: yarn };
31
+ return { pm: 'npm', lockfile: at('package-lock.json') ?? at('npm-shrinkwrap.json') };
32
+ }
33
+ /** The project's own TypeScript (resolved like the project would), or null when unavailable. */
34
+ function loadTypescript(root) {
35
+ try {
36
+ return createRequire(join(root, 'package.json'))('typescript');
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ /**
43
+ * Finds the project that contains `cwd` (nearest package.json walking up) and describes it.
44
+ * `root` is a real path (fs.realpathSync).
45
+ * Throws DepkillError (exit 2) when there is no package.json, the package uses workspaces,
46
+ * or dependencies are not installed.
47
+ */
48
+ export function detectProject(cwd) {
49
+ const found = findRoot(cwd);
50
+ if (found === null)
51
+ throw new DepkillError(`No package.json found in ${resolve(cwd)} or any parent directory.`);
52
+ // Real path, so root and every GraphNode.dir agree (e.g. macOS /var -> /private/var, symlinked checkouts).
53
+ const root = realpathSync(found);
54
+ let pkg;
55
+ try {
56
+ pkg = readJson(join(root, 'package.json'));
57
+ }
58
+ catch (error) {
59
+ throw new DepkillError(error instanceof Error ? error.message : String(error));
60
+ }
61
+ if (pkg.workspaces !== undefined) {
62
+ throw new DepkillError(`${join(root, 'package.json')} declares "workspaces"; depkill supports single-package projects only.`);
63
+ }
64
+ if (existsSync(join(root, 'pnpm-workspace.yaml'))) {
65
+ throw new DepkillError(`${join(root, 'pnpm-workspace.yaml')} declares pnpm workspaces; depkill supports single-package projects only.`);
66
+ }
67
+ if (!isDirectory(join(root, 'node_modules'))) {
68
+ throw new DepkillError(`No node_modules in ${root}; install dependencies first (e.g. npm install).`);
69
+ }
70
+ const { pm, lockfile } = detectPm(root);
71
+ return { root, pm, lockfile, pkg, hasTsconfig: existsSync(join(root, 'tsconfig.json')), ts: loadTypescript(root) };
72
+ }
@@ -0,0 +1,180 @@
1
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
2
+ import { basename, dirname, extname, join } from 'node:path';
3
+ import { collectInputs } from './inputs.js';
4
+ import { exportName } from './runtime/protocol.js';
5
+ import { snapshotRuntime } from './holdout/snapshot.js';
6
+ import { probeExports, runCases } from './runner.js';
7
+ import { DepkillError } from './types.js';
8
+ import { findPackageDir } from './util/exports.js';
9
+ import { pkgSafe, readJson, stateDir, writeJson } from './util/fs.js';
10
+ import { scanUsage } from './usage.js';
11
+ const ORIGINAL_LIMIT_BYTES = 2 * 1024 * 1024;
12
+ const SNAPSHOT_EXTENSIONS = new Set(['.js', '.cjs', '.mjs']);
13
+ /**
14
+ * Copies `.js/.cjs/.mjs` files and `package.json` files of `src` into `dest` (breadth-first, sorted, each
15
+ * directory's package.json first), skipping `node_modules` and symlinks. Stops before the total would exceed
16
+ * `limitBytes` and then reports `truncated`.
17
+ */
18
+ export function snapshotOriginal(src, dest, limitBytes) {
19
+ let used = 0;
20
+ const queue = [[]];
21
+ while (queue.length > 0) {
22
+ const rel = queue.shift();
23
+ const entries = readdirSync(join(src, ...rel), { withFileTypes: true }).sort((a, b) => {
24
+ const rank = (name) => (name === 'package.json' ? 0 : 1);
25
+ return rank(a.name) - rank(b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
26
+ });
27
+ for (const entry of entries) {
28
+ if (entry.isDirectory()) {
29
+ if (entry.name !== 'node_modules')
30
+ queue.push([...rel, entry.name]);
31
+ continue;
32
+ }
33
+ if (!entry.isFile() || !(entry.name === 'package.json' || SNAPSHOT_EXTENSIONS.has(extname(entry.name).toLowerCase())))
34
+ continue;
35
+ const from = join(src, ...rel, entry.name);
36
+ const size = statSync(from).size;
37
+ if (used + size > limitBytes)
38
+ return { truncated: true };
39
+ used += size;
40
+ mkdirSync(join(dest, ...rel), { recursive: true });
41
+ copyFileSync(from, join(dest, ...rel, entry.name));
42
+ }
43
+ }
44
+ return { truncated: false };
45
+ }
46
+ /** I6: keeps generated snapshots, build files and check diffs out of git when `.depkill/.gitignore` is missing. */
47
+ function ensureStateGitignore(root) {
48
+ const file = join(stateDir(root), '.gitignore');
49
+ if (existsSync(file))
50
+ return;
51
+ mkdirSync(dirname(file), { recursive: true });
52
+ writeFileSync(file, '*/original/\n*/runtime/\n.build/\n*/check.json\n');
53
+ }
54
+ /** On the first record in a project, keeps package.json and the lockfile as they were before any removal. */
55
+ function snapshotBaseline(project) {
56
+ const dir = join(stateDir(project.root), 'baseline');
57
+ if (existsSync(join(dir, 'package.json')))
58
+ return;
59
+ mkdirSync(dir, { recursive: true });
60
+ if (project.lockfile !== null)
61
+ copyFileSync(project.lockfile, join(dir, basename(project.lockfile)));
62
+ copyFileSync(join(project.root, 'package.json'), join(dir, 'package.json'));
63
+ }
64
+ function assertDirectDependency(project, pkg) {
65
+ const { dependencies = {}, devDependencies = {}, optionalDependencies = {} } = project.pkg;
66
+ if (![dependencies, devDependencies, optionalDependencies].some((deps) => Object.hasOwn(deps, pkg))) {
67
+ throw new DepkillError(`"${pkg}" is not a direct dependency of this project (not in package.json dependencies or devDependencies).`);
68
+ }
69
+ const dir = findPackageDir(pkg, project.root);
70
+ if (dir === null)
71
+ throw new DepkillError(`"${pkg}" is not installed; run your package manager's install first.`);
72
+ return dir;
73
+ }
74
+ function inputsPath(pkg) {
75
+ return `.depkill/${pkgSafe(pkg)}/inputs.mjs`;
76
+ }
77
+ function noInputsError(project, pkg, used) {
78
+ const why = used.length === 0 ? 'it is not imported by any project source file' : 'no call sites with literal arguments or typed parameters were found';
79
+ const ts = project.ts === null ? ', or install typescript for call-site and generated inputs' : '';
80
+ // Name the export ids the project actually uses, so the example is not misleading for named imports.
81
+ const ids = used.filter((id) => exportName(id) !== '*');
82
+ const example = (ids.length > 0 ? ids : ['#default']).map((id) => `"${id}": [["arg", 1]]`).join(', ');
83
+ const forIds = ids.length > 0 ? ` for the used export ids (${ids.join(', ')})` : '';
84
+ return new DepkillError(`Nothing to record for "${pkg}": ${why}. Add argument lists to ${inputsPath(pkg)}${forIds} `
85
+ + `(export default { ${example} })${ts}.`);
86
+ }
87
+ function countBy(items, key) {
88
+ const counts = new Map();
89
+ for (const item of items)
90
+ counts.set(key(item), (counts.get(key(item)) ?? 0) + 1);
91
+ return counts;
92
+ }
93
+ function report(pkg, version, result, missing, project) {
94
+ const { cases, summary } = result;
95
+ const lines = [`Recorded ${cases.length} cases for ${pkg}@${version}`];
96
+ for (const source of ['callsite', 'agent', 'generated'])
97
+ lines.push(` ${source.padEnd(17)}${summary[source]}`);
98
+ const unsupported = cases.filter((c) => c.outcome.kind === 'unsupported');
99
+ if (unsupported.length > 0) {
100
+ lines.push(` ${'unsupported'.padEnd(17)}${unsupported.length}`);
101
+ const reasons = countBy(unsupported, (c) => (c.outcome.kind === 'unsupported' ? `${c.exportId}: ${c.outcome.reason}` : ''));
102
+ for (const [reason, n] of reasons)
103
+ lines.push(` ${reason} (x${n})`);
104
+ }
105
+ const nondeterministic = cases.filter((c) => c.outcome.kind === 'nondeterministic');
106
+ if (nondeterministic.length > 0) {
107
+ const ids = [...new Set(nondeterministic.map((c) => c.exportId))].join(', ');
108
+ lines.push(` ${'nondeterministic'.padEnd(17)}${nondeterministic.length} (${ids})`);
109
+ }
110
+ for (const id of missing)
111
+ lines.push(` no inputs for ${id}: add argument lists to ${inputsPath(pkg)}`);
112
+ // An export whose cases are mostly unsupported (e.g. a middleware factory returning a function) cannot be proven.
113
+ for (const [id, total] of countBy(cases, (c) => c.exportId)) {
114
+ const uncomparable = cases.filter((c) => c.exportId === id && c.outcome.kind !== 'return' && c.outcome.kind !== 'throw').length;
115
+ if (uncomparable * 2 > total) {
116
+ lines.push(`Warning: ${uncomparable} of ${total} ${id} cases cannot be compared, so a replacement for ${id} `
117
+ + 'cannot be proven; prefer a package whose cases return comparable values.');
118
+ }
119
+ }
120
+ if (project.ts === null) {
121
+ lines.push('Note: typescript is not installed in this project, so only agent inputs were used; '
122
+ + 'install it (e.g. npm i -D typescript) for call-site and type-generated inputs.');
123
+ }
124
+ lines.push(`Next: write your replacement, then depkill check ${pkg}`);
125
+ return `${lines.join('\n')}\n`;
126
+ }
127
+ /**
128
+ * Records how `pkg` (a direct dependency) behaves: collects inputs (call sites, agent inputs, generated),
129
+ * runs them against the installed package in a child process and writes `.depkill/<pkg-safe>/cases.jsonl`
130
+ * and `meta.json`, the original package code under `original/`, and — on the first record in the project —
131
+ * `.depkill/baseline/` (package.json + lockfile), plus `runtime/` (R43: the original and its dependency closure,
132
+ * runnable after removal; meta.json `holdoutAvailable`/`holdoutReason` say whether it could be written).
133
+ * DepkillError (exit 2) when `pkg` is not a direct dependency or there is nothing to record.
134
+ */
135
+ export async function runRecord(project, pkg, opts) {
136
+ const log = opts.log ?? ((text) => { process.stdout.write(text); });
137
+ const dir = stateDir(project.root, pkg);
138
+ const pkgDir = assertDirectDependency(project, pkg);
139
+ let version = '0.0.0';
140
+ try {
141
+ version = readJson(join(pkgDir, 'package.json')).version ?? '0.0.0';
142
+ }
143
+ catch (error) {
144
+ throw new DepkillError(`Cannot read ${pkg} manifest: ${error instanceof Error ? error.message : String(error)}`);
145
+ }
146
+ const sites = scanUsage(project, new Set([pkg]));
147
+ const used = [...new Set(sites.flatMap((s) => s.exportIds))].sort();
148
+ const target = { kind: 'package', name: pkg, resolveFrom: project.root };
149
+ const runOptions = { caseTimeoutMs: opts.caseTimeoutMs, cwd: project.root };
150
+ const exportKinds = await probeExports(target, used, runOptions);
151
+ const inputs = collectInputs(project, pkg, sites, { maxGenerated: opts.maxGenerated, exportKinds });
152
+ if (inputs.length === 0)
153
+ throw noInputsError(project, pkg, used);
154
+ const cases = await runCases(target, inputs, runOptions);
155
+ const summary = { callsite: 0, agent: 0, generated: 0 };
156
+ for (const c of cases)
157
+ summary[c.source] += 1;
158
+ const result = {
159
+ cases, summary, unsupported: cases.filter((c) => c.outcome.kind === 'unsupported' || c.outcome.kind === 'nondeterministic').length,
160
+ };
161
+ mkdirSync(dir, { recursive: true });
162
+ ensureStateGitignore(project.root);
163
+ writeFileSync(join(dir, 'cases.jsonl'), cases.map((c) => `${JSON.stringify(c)}\n`).join(''));
164
+ const original = join(dir, 'original');
165
+ rmSync(original, { recursive: true, force: true });
166
+ const { truncated } = snapshotOriginal(pkgDir, original, ORIGINAL_LIMIT_BYTES);
167
+ snapshotBaseline(project);
168
+ // R43: a runnable copy of the original and its closure, for the gate's holdout after the package is removed.
169
+ const runtime = snapshotRuntime(project, pkg, join(dir, 'runtime'));
170
+ writeJson(join(dir, 'meta.json'), {
171
+ pkg, version, exportIds: [...new Set([...used, ...cases.map((c) => c.exportId)])].sort(),
172
+ // C1: the gate accepts any compared case as evidence for a plain-value export, only real cases for functions.
173
+ exportKinds,
174
+ recordedAt: new Date().toISOString(), originalTruncated: truncated, sources: summary,
175
+ holdoutAvailable: runtime.available, ...(runtime.available ? {} : { holdoutReason: runtime.reason }),
176
+ });
177
+ const missing = used.filter((id) => exportName(id) !== '*' && exportKinds[id] === 'function' && !cases.some((c) => c.exportId === id));
178
+ log(report(pkg, version, result, missing, project));
179
+ return result;
180
+ }
@@ -0,0 +1,78 @@
1
+ const REGISTRY = 'https://registry.npmjs.org';
2
+ const DEFAULT_TIMEOUT_MS = 5000;
3
+ const DEFAULT_CONCURRENCY = 8;
4
+ /**
5
+ * Runs `fn` over `items` with at most `limit` calls in flight; results keep input order.
6
+ * Rejects on the first failure and starts no further calls after it.
7
+ */
8
+ export async function mapPool(items, limit, fn) {
9
+ const results = new Array(items.length);
10
+ let next = 0;
11
+ let failed = false;
12
+ const worker = async () => {
13
+ while (!failed && next < items.length) {
14
+ const index = next;
15
+ next += 1;
16
+ try {
17
+ results[index] = await fn(items[index]);
18
+ }
19
+ catch (error) {
20
+ failed = true;
21
+ throw error;
22
+ }
23
+ }
24
+ };
25
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, worker));
26
+ return results;
27
+ }
28
+ function namesOf(maintainers) {
29
+ return maintainers.flatMap((m) => {
30
+ const name = typeof m === 'object' && m !== null ? m.name : undefined;
31
+ return typeof name === 'string' ? [name] : [];
32
+ });
33
+ }
34
+ /**
35
+ * Maintainer names of one published version (its publisher when the version has no maintainers list); throws on
36
+ * any HTTP, network, timeout or shape problem.
37
+ * The timeout covers the whole request including the body, and its timer keeps the event loop alive meanwhile.
38
+ */
39
+ async function versionMaintainers(node, timeoutMs) {
40
+ const url = `${REGISTRY}/${encodeURIComponent(node.name)}/${encodeURIComponent(node.version)}`;
41
+ const controller = new AbortController();
42
+ const timer = setTimeout(() => controller.abort(new Error(`${url}: timed out after ${timeoutMs} ms`)), timeoutMs);
43
+ try {
44
+ const response = await fetch(url, { signal: controller.signal, headers: { accept: 'application/json' } });
45
+ if (!response.ok)
46
+ throw new Error(`${url}: HTTP ${response.status}`);
47
+ const doc = (await response.json());
48
+ if (Array.isArray(doc?.maintainers))
49
+ return namesOf(doc.maintainers);
50
+ // Some versions are published without a maintainers list; the publishing account is then the one we know of.
51
+ const publisher = namesOf(doc?.maintainers === undefined && doc?._npmUser !== undefined ? [doc._npmUser] : []);
52
+ if (publisher.length === 0)
53
+ throw new Error(`${url}: no maintainers list`);
54
+ return publisher;
55
+ }
56
+ finally {
57
+ clearTimeout(timer);
58
+ controller.abort(); // releases an unread body (e.g. on HTTP errors); no-op once the body was consumed
59
+ }
60
+ }
61
+ /**
62
+ * Number of unique maintainer names across `nodes`, read from `GET registry.npmjs.org/<name>/<version>`.
63
+ * Returns null when offline (fetch is never called) or when any request fails, times out or is malformed.
64
+ */
65
+ export async function fetchMaintainers(nodes, opts) {
66
+ if (opts.offline)
67
+ return null;
68
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
69
+ // m8: identical name@version nodes share the same registry document.
70
+ const unique = [...new Map(nodes.map((node) => [`${node.name}@${node.version}`, node])).values()];
71
+ try {
72
+ const lists = await mapPool(unique, opts.concurrency ?? DEFAULT_CONCURRENCY, (node) => versionMaintainers(node, timeoutMs));
73
+ return new Set(lists.flat()).size;
74
+ }
75
+ catch {
76
+ return null;
77
+ }
78
+ }
@@ -0,0 +1,146 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
3
+ import { extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { DepkillError } from './types.js';
5
+ import { pkgSafe, readJson, stateDir } from './util/fs.js';
6
+ const JS_EXTENSIONS = new Set(['.js', '.mjs', '.cjs']);
7
+ const TS_EXTENSIONS = new Set(['.ts', '.mts', '.cts']);
8
+ function configPath(project, pkg) {
9
+ return join(stateDir(project.root, pkg), 'config.json');
10
+ }
11
+ function howToSet(project, pkg) {
12
+ const where = relative(project.root, configPath(project, pkg)).split('\\').join('/');
13
+ return `Pass --replacement <path>, or create ${where} with { "replacement": "src/vendor/${pkgSafe(pkg)}.ts" } `
14
+ + '(paths relative to the project root; add "subpaths": { "/sub": "<path>" } for subpath imports).';
15
+ }
16
+ function readConfig(project, pkg) {
17
+ const file = configPath(project, pkg);
18
+ if (!existsSync(file))
19
+ return null;
20
+ let config;
21
+ try {
22
+ config = readJson(file);
23
+ }
24
+ catch (error) {
25
+ throw new DepkillError(`${error instanceof Error ? error.message : String(error)}. ${howToSet(project, pkg)}`);
26
+ }
27
+ if (config === null || typeof config !== 'object' || Array.isArray(config)) {
28
+ throw new DepkillError(`${file} must be a JSON object. ${howToSet(project, pkg)}`);
29
+ }
30
+ return config;
31
+ }
32
+ /** Case-insensitive file systems (Windows, default macOS) compare paths without case. */
33
+ function foldCase(path) {
34
+ return process.platform === 'win32' || process.platform === 'darwin' ? path.toLowerCase() : path;
35
+ }
36
+ /**
37
+ * R29: a replacement must be the project's own code. Its real path (symlinks resolved) must lie inside the
38
+ * project root, not under any `node_modules` segment (the package itself, or any other dependency) and not
39
+ * under `<root>/.depkill/` (the recorded original, build output).
40
+ */
41
+ function assertProjectFile(project, file, what) {
42
+ const real = realpathSync.native(file);
43
+ const rel = relative(foldCase(realpathSync.native(project.root)), foldCase(real));
44
+ if (rel === '' || isAbsolute(rel) || rel.split(sep)[0] === '..') {
45
+ throw new DepkillError(`${what} ${real} is outside the project (${project.root}); the replacement must be project code.`);
46
+ }
47
+ const segments = rel.split(sep).map((segment) => segment.toLowerCase());
48
+ if (segments.includes('node_modules')) {
49
+ throw new DepkillError(`${what} ${real} is inside node_modules; the replacement must be your own project code, not a dependency.`);
50
+ }
51
+ if (segments[0] === '.depkill') {
52
+ throw new DepkillError(`${what} ${real} is inside .depkill/ (recorded original or build output); write the replacement in your sources.`);
53
+ }
54
+ }
55
+ /** Absolute path of an existing replacement file inside the project; relative paths are taken from the project root. */
56
+ function existingFile(project, path, what) {
57
+ const file = resolve(project.root, path);
58
+ let isFile = false;
59
+ try {
60
+ isFile = statSync(file).isFile();
61
+ }
62
+ catch {
63
+ isFile = false;
64
+ }
65
+ if (!isFile)
66
+ throw new DepkillError(`${what} ${file} does not exist.`);
67
+ assertProjectFile(project, file, what);
68
+ return file;
69
+ }
70
+ function readSubpaths(project, pkg, value) {
71
+ if (value === undefined)
72
+ return {};
73
+ const bad = () => new DepkillError(`"subpaths" in ${configPath(project, pkg)} must map subpaths starting with "/" to file paths, e.g. { "/sub": "src/vendor/sub.ts" }.`);
74
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
75
+ throw bad();
76
+ const subpaths = {};
77
+ for (const [subpath, path] of Object.entries(value)) {
78
+ if (!subpath.startsWith('/') || subpath.includes('#') || typeof path !== 'string' || path === '')
79
+ throw bad();
80
+ subpaths[subpath] = existingFile(project, path, `Replacement for ${pkg}${subpath}:`);
81
+ }
82
+ return subpaths;
83
+ }
84
+ /**
85
+ * Replacement files of `pkg`: the root file from `override` (`--replacement`) or `.depkill/<pkg-safe>/config.json`
86
+ * `{ "replacement": "<path>" }`, plus the config's `"subpaths"` files. Relative paths resolve from the project
87
+ * root. DepkillError (exit 2) when nothing is configured, the config is malformed or a file does not exist.
88
+ */
89
+ export function resolveReplacementFiles(project, pkg, override) {
90
+ const config = readConfig(project, pkg);
91
+ const subpaths = readSubpaths(project, pkg, config?.subpaths);
92
+ if (override !== undefined)
93
+ return { root: existingFile(project, override, 'Replacement file'), subpaths };
94
+ if (config === null)
95
+ throw new DepkillError(`No replacement configured for ${pkg}. ${howToSet(project, pkg)}`);
96
+ if (typeof config.replacement !== 'string' || config.replacement === '') {
97
+ throw new DepkillError(`"replacement" in ${configPath(project, pkg)} must be a file path. ${howToSet(project, pkg)}`);
98
+ }
99
+ return { root: existingFile(project, config.replacement, 'Replacement file'), subpaths };
100
+ }
101
+ /** Absolute path of the root replacement file (see resolveReplacementFiles). */
102
+ export function resolveReplacement(project, pkg, override) {
103
+ return resolveReplacementFiles(project, pkg, override).root;
104
+ }
105
+ function transpile(project, file, commonJs) {
106
+ const ts = project.ts;
107
+ if (ts === null)
108
+ throw new DepkillError(`Cannot load ${file}: install typescript or write the replacement in JS.`);
109
+ const source = readFileSync(file, 'utf8');
110
+ const output = ts.transpileModule(source, {
111
+ fileName: file,
112
+ reportDiagnostics: true,
113
+ compilerOptions: {
114
+ module: commonJs ? ts.ModuleKind.CommonJS : ts.ModuleKind.ESNext,
115
+ target: ts.ScriptTarget.ES2022,
116
+ esModuleInterop: true,
117
+ },
118
+ });
119
+ const errors = (output.diagnostics ?? []).filter((d) => d.category === ts.DiagnosticCategory.Error);
120
+ if (errors.length > 0) {
121
+ const first = errors[0];
122
+ const line = first.file !== undefined && first.start !== undefined ? first.file.getLineAndCharacterOfPosition(first.start).line + 1 : 1;
123
+ throw new DepkillError(`Cannot transpile ${file}:${line}: ${ts.flattenDiagnosticMessageText(first.messageText, ' ')}`);
124
+ }
125
+ // Content-addressed (path + source), yet the file is rewritten on every call: see below.
126
+ const hash = createHash('sha256').update(file).update('\0').update(source).digest('hex').slice(0, 16);
127
+ const dir = join(stateDir(project.root), '.build');
128
+ const out = join(dir, `${hash}${commonJs ? '.cjs' : '.mjs'}`);
129
+ // Always (re)written: cheap, and a file left half-written by an interrupted run can never be reused.
130
+ mkdirSync(dir, { recursive: true });
131
+ writeFileSync(out, output.outputText);
132
+ return out;
133
+ }
134
+ /**
135
+ * A path the child runtime can import for replacement `file`: `.js/.mjs/.cjs` as is; `.ts/.mts` transpiled to ESM
136
+ * `.depkill/.build/<hash>.mjs`, `.cts` to CommonJS `<hash>.cjs` (hash: sha256 of path + source, 16 hex chars).
137
+ * DepkillError when TypeScript is unavailable, the file has syntax errors or the extension is not supported.
138
+ */
139
+ export function loadableReplacement(project, file) {
140
+ const ext = extname(file).toLowerCase();
141
+ if (JS_EXTENSIONS.has(ext))
142
+ return file;
143
+ if (TS_EXTENSIONS.has(ext))
144
+ return transpile(project, file, ext === '.cts');
145
+ throw new DepkillError(`Unsupported replacement file type ${file}: use .js, .mjs, .cjs, .ts, .mts or .cts.`);
146
+ }