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.
- package/LICENSE +21 -0
- package/README.md +179 -3
- package/data/module-replacements.LICENSE +21 -0
- package/data/module-replacements.json +947 -0
- package/dist/src/anticheat/constants.js +105 -0
- package/dist/src/anticheat/imports.js +419 -0
- package/dist/src/anticheat/tokens.js +177 -0
- package/dist/src/anticheat.js +189 -0
- package/dist/src/card/format.js +113 -0
- package/dist/src/card/svg.js +137 -0
- package/dist/src/card.js +364 -0
- package/dist/src/check.js +139 -0
- package/dist/src/cli.js +333 -0
- package/dist/src/gate/holdout.js +78 -0
- package/dist/src/gate/process.js +78 -0
- package/dist/src/gate.js +532 -0
- package/dist/src/graph.js +148 -0
- package/dist/src/holdout/perturb.js +108 -0
- package/dist/src/holdout/snapshot.js +113 -0
- package/dist/src/init.js +76 -0
- package/dist/src/inputs/generate.js +282 -0
- package/dist/src/inputs.js +273 -0
- package/dist/src/measure.js +149 -0
- package/dist/src/project.js +72 -0
- package/dist/src/record.js +180 -0
- package/dist/src/registry.js +78 -0
- package/dist/src/replacement.js +146 -0
- package/dist/src/runner.js +227 -0
- package/dist/src/runtime/agent-inputs.js +36 -0
- package/dist/src/runtime/child.js +260 -0
- package/dist/src/runtime/esm-hooks.js +44 -0
- package/dist/src/runtime/fsguard.js +264 -0
- package/dist/src/runtime/inspect.js +115 -0
- package/dist/src/runtime/lockdown.js +157 -0
- package/dist/src/runtime/protocol.js +16 -0
- package/dist/src/scan.js +210 -0
- package/dist/src/serialize.js +399 -0
- package/dist/src/tooling.js +88 -0
- package/dist/src/types.js +9 -0
- package/dist/src/usage/common.js +36 -0
- package/dist/src/usage/fallback.js +227 -0
- package/dist/src/usage/ts.js +142 -0
- package/dist/src/usage.js +97 -0
- package/dist/src/util/exports.js +86 -0
- package/dist/src/util/fs.js +64 -0
- package/dist/src/util/term.js +61 -0
- package/package.json +54 -6
- package/skills/AGENTS.section.md +52 -0
- package/skills/depkill/SKILL.md +148 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// Type-driven input generation. `typescript` is a type-only import: the module comes from ProjectInfo.ts.
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { findPackageDir, resolveExports } from '../util/exports.js';
|
|
5
|
+
import { readJson } from '../util/fs.js';
|
|
6
|
+
import { exportName, exportSubpath } from '../runtime/protocol.js';
|
|
7
|
+
export const CORPUS = {
|
|
8
|
+
strings: ['', 'a', 'hello world', ' padded ', 'ÜñíçødÉ', '🙂', '0', '-1', '1e3', 'null'],
|
|
9
|
+
numbers: [0, -0, 1, -1, 1.5, NaN, Infinity, -Infinity, 9007199254740991, -2147483648],
|
|
10
|
+
booleans: [true, false],
|
|
11
|
+
};
|
|
12
|
+
/** 32-bit FNV-1a over the UTF-8 bytes of `text`. */
|
|
13
|
+
export function fnv1a(text) {
|
|
14
|
+
let hash = 0x811c9dc5;
|
|
15
|
+
for (const byte of Buffer.from(text, 'utf8')) {
|
|
16
|
+
hash ^= byte;
|
|
17
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
18
|
+
}
|
|
19
|
+
return hash >>> 0;
|
|
20
|
+
}
|
|
21
|
+
/** mulberry32 PRNG: deterministic floats in [0, 1) for a 32-bit seed. */
|
|
22
|
+
export function mulberry32(seed) {
|
|
23
|
+
let a = seed >>> 0;
|
|
24
|
+
return () => {
|
|
25
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
26
|
+
let t = a;
|
|
27
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
28
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
29
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
// ---------- locating declarations ----------
|
|
33
|
+
const LOOKUP_CONDITIONS = new Set(['types', 'typings', 'node', 'import', 'require', 'default']);
|
|
34
|
+
const DECLARATION = /\.d\.[cm]?ts$/;
|
|
35
|
+
function firstExisting(candidates) {
|
|
36
|
+
return candidates.find((file) => existsSync(file)) ?? null;
|
|
37
|
+
}
|
|
38
|
+
/** `x.js` -> `x.d.ts`, `x.mjs` -> `x.d.mts` (or `.d.ts`), `x.cjs` -> `x.d.cts` (or `.d.ts`). */
|
|
39
|
+
function declarationFor(file) {
|
|
40
|
+
if (DECLARATION.test(file))
|
|
41
|
+
return existsSync(file) ? file : null;
|
|
42
|
+
const base = file.replace(/\.[cm]?[jt]sx?$/, '');
|
|
43
|
+
const ext = /\.mjs$/.test(file) ? ['.d.mts', '.d.ts'] : /\.cjs$/.test(file) ? ['.d.cts', '.d.ts'] : ['.d.ts'];
|
|
44
|
+
return firstExisting([...ext.map((e) => base + e), join(file, 'index.d.ts')]);
|
|
45
|
+
}
|
|
46
|
+
function ownDeclarations(dir, manifest, subpath) {
|
|
47
|
+
if (manifest.exports !== undefined) {
|
|
48
|
+
const target = resolveExports(manifest.exports, `.${subpath}`, LOOKUP_CONDITIONS);
|
|
49
|
+
if (target !== null)
|
|
50
|
+
return declarationFor(resolve(dir, target));
|
|
51
|
+
}
|
|
52
|
+
if (subpath === '') {
|
|
53
|
+
const declared = manifest.types ?? manifest.typings;
|
|
54
|
+
if (declared !== undefined)
|
|
55
|
+
return declarationFor(resolve(dir, declared));
|
|
56
|
+
return firstExisting([manifest.main ? declarationFor(resolve(dir, manifest.main)) : null, join(dir, 'index.d.ts')]
|
|
57
|
+
.filter((f) => f !== null));
|
|
58
|
+
}
|
|
59
|
+
const rel = subpath.slice(1).split('/');
|
|
60
|
+
return firstExisting([`${join(dir, ...rel)}.d.ts`, join(dir, ...rel, 'index.d.ts')]);
|
|
61
|
+
}
|
|
62
|
+
/** Declaration file for `pkg + subpath`: the package's own types, else `@types/<pkg>`. */
|
|
63
|
+
export function findDeclarations(pkgDir, pkg, subpath, root) {
|
|
64
|
+
try {
|
|
65
|
+
const own = ownDeclarations(pkgDir, readJson(join(pkgDir, 'package.json')), subpath);
|
|
66
|
+
if (own !== null)
|
|
67
|
+
return own;
|
|
68
|
+
const typesName = `@types/${pkg.startsWith('@') ? pkg.slice(1).replace('/', '__') : pkg}`;
|
|
69
|
+
const typesDir = findPackageDir(typesName, root);
|
|
70
|
+
return typesDir === null ? null : ownDeclarations(typesDir, readJson(join(typesDir, 'package.json')), subpath);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function resolveAlias(ts, checker, symbol) {
|
|
77
|
+
return symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
|
|
78
|
+
}
|
|
79
|
+
function exportSymbol(ts, checker, sf, name) {
|
|
80
|
+
const moduleSymbol = checker.getSymbolAtLocation(sf);
|
|
81
|
+
if (moduleSymbol === undefined)
|
|
82
|
+
return null;
|
|
83
|
+
const named = checker.getExportsOfModule(moduleSymbol).find((s) => s.escapedName === name);
|
|
84
|
+
if (named !== undefined)
|
|
85
|
+
return resolveAlias(ts, checker, named);
|
|
86
|
+
const exportEquals = moduleSymbol.exports?.get('export=');
|
|
87
|
+
if (exportEquals === undefined)
|
|
88
|
+
return null;
|
|
89
|
+
const target = resolveAlias(ts, checker, exportEquals);
|
|
90
|
+
if (name === 'default')
|
|
91
|
+
return target;
|
|
92
|
+
return checker.getPropertyOfType(checker.getTypeOfSymbolAtLocation(target, sf), name) ?? null;
|
|
93
|
+
}
|
|
94
|
+
function isArrayType(ts, checker, type) {
|
|
95
|
+
const viaChecker = checker.isArrayType;
|
|
96
|
+
if (viaChecker)
|
|
97
|
+
return viaChecker.call(checker, type);
|
|
98
|
+
const name = type.getSymbol()?.getName();
|
|
99
|
+
return (name === 'Array' || name === 'ReadonlyArray') && (type.flags & ts.TypeFlags.Object) !== 0;
|
|
100
|
+
}
|
|
101
|
+
function dedupe(values) {
|
|
102
|
+
const seen = new Set();
|
|
103
|
+
return values.filter((v) => {
|
|
104
|
+
const key = Object.is(v, -0) ? '-0' : typeof v === 'number' ? `n${v}` : `${typeof v}:${JSON.stringify(v)}`;
|
|
105
|
+
if (seen.has(key))
|
|
106
|
+
return false;
|
|
107
|
+
seen.add(key);
|
|
108
|
+
return true;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/** Values to try for a parameter type, or null when the type is outside the generatable set. */
|
|
112
|
+
function valuesOf(ts, checker, type, allowArray) {
|
|
113
|
+
const f = type.flags;
|
|
114
|
+
if (f & ts.TypeFlags.Boolean)
|
|
115
|
+
return [...CORPUS.booleans];
|
|
116
|
+
if (type.isUnion()) {
|
|
117
|
+
const parts = type.types.map((member) => valuesOf(ts, checker, member, allowArray));
|
|
118
|
+
if (parts.some((p) => p === null))
|
|
119
|
+
return null;
|
|
120
|
+
const values = dedupe(parts.flat());
|
|
121
|
+
const t = values.indexOf(true);
|
|
122
|
+
const fl = values.indexOf(false);
|
|
123
|
+
if (t !== -1 && fl !== -1 && fl < t)
|
|
124
|
+
[values[t], values[fl]] = [false, true];
|
|
125
|
+
return values;
|
|
126
|
+
}
|
|
127
|
+
if (f & ts.TypeFlags.String)
|
|
128
|
+
return [...CORPUS.strings];
|
|
129
|
+
if (f & ts.TypeFlags.Number)
|
|
130
|
+
return [...CORPUS.numbers];
|
|
131
|
+
if (type.isStringLiteral() || type.isNumberLiteral())
|
|
132
|
+
return [type.value];
|
|
133
|
+
if (f & ts.TypeFlags.BooleanLiteral)
|
|
134
|
+
return [checker.typeToString(type) === 'true'];
|
|
135
|
+
if (f & ts.TypeFlags.Null)
|
|
136
|
+
return [null];
|
|
137
|
+
if (f & ts.TypeFlags.Undefined)
|
|
138
|
+
return [undefined];
|
|
139
|
+
if (allowArray && isArrayType(ts, checker, type)) {
|
|
140
|
+
const [element] = checker.getTypeArguments(type);
|
|
141
|
+
const items = element === undefined ? null : valuesOf(ts, checker, element, false);
|
|
142
|
+
if (items === null || items.length === 0)
|
|
143
|
+
return null;
|
|
144
|
+
const pick = (i) => items[i % items.length];
|
|
145
|
+
return [[], [pick(1)], [pick(1), pick(2), pick(3)]];
|
|
146
|
+
}
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
function shapeOf(ts, checker, sf, symbol) {
|
|
150
|
+
const signature = checker.getTypeOfSymbolAtLocation(symbol, sf).getCallSignatures()[0];
|
|
151
|
+
if (signature === undefined)
|
|
152
|
+
return { kind: 'value' };
|
|
153
|
+
const params = [];
|
|
154
|
+
for (const param of signature.getParameters()) {
|
|
155
|
+
const decl = param.valueDeclaration;
|
|
156
|
+
if (decl === undefined || !ts.isParameter(decl) || decl.dotDotDotToken)
|
|
157
|
+
return { kind: 'function', params: null };
|
|
158
|
+
const optional = decl.questionToken !== undefined || decl.initializer !== undefined;
|
|
159
|
+
const values = valuesOf(ts, checker, checker.getTypeOfSymbolAtLocation(param, decl), true);
|
|
160
|
+
const usable = optional ? values?.filter((v) => v !== undefined) : values;
|
|
161
|
+
if (!usable || usable.length === 0)
|
|
162
|
+
return { kind: 'function', params: null };
|
|
163
|
+
params.push({ values: usable, optional });
|
|
164
|
+
}
|
|
165
|
+
return { kind: 'function', params };
|
|
166
|
+
}
|
|
167
|
+
/** I4: true when the package's `.d.ts` default export is callable and every call signature returns a function. */
|
|
168
|
+
export function defaultReturnsFunction(ts, pkgDir, pkg, root) {
|
|
169
|
+
try {
|
|
170
|
+
const dts = findDeclarations(pkgDir, pkg, '', root);
|
|
171
|
+
if (dts === null)
|
|
172
|
+
return false;
|
|
173
|
+
const kinds = ts.ModuleResolutionKind;
|
|
174
|
+
const program = ts.createProgram([dts], {
|
|
175
|
+
noEmit: true, allowJs: false, skipLibCheck: true, types: [], lib: ['lib.es2020.d.ts'],
|
|
176
|
+
target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.CommonJS,
|
|
177
|
+
moduleResolution: (kinds.Node10 ?? kinds.NodeJs),
|
|
178
|
+
});
|
|
179
|
+
const sf = program.getSourceFile(dts);
|
|
180
|
+
if (sf === undefined)
|
|
181
|
+
return false;
|
|
182
|
+
const checker = program.getTypeChecker();
|
|
183
|
+
const symbol = exportSymbol(ts, checker, sf, 'default');
|
|
184
|
+
if (symbol === null)
|
|
185
|
+
return false;
|
|
186
|
+
const signatures = checker.getTypeOfSymbolAtLocation(symbol, sf).getCallSignatures();
|
|
187
|
+
if (signatures.length === 0)
|
|
188
|
+
return false;
|
|
189
|
+
const nullable = ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.Void;
|
|
190
|
+
const returnsCallable = (t) => {
|
|
191
|
+
if (t.getCallSignatures().length > 0)
|
|
192
|
+
return true;
|
|
193
|
+
if (!t.isUnion())
|
|
194
|
+
return false;
|
|
195
|
+
const members = t.types.filter((m) => (m.flags & nullable) === 0);
|
|
196
|
+
return members.length > 0 && members.every((m) => m.getCallSignatures().length > 0);
|
|
197
|
+
};
|
|
198
|
+
return signatures.every((sig) => returnsCallable(sig.getReturnType()));
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Shape of each export id per the package's declarations (own `types`/`exports[*].types`/`index.d.ts`, or
|
|
206
|
+
* `@types/*`). Ids without findable declarations are absent from the map. `#*` is never analysed.
|
|
207
|
+
*/
|
|
208
|
+
export function readShapes(ts, pkgDir, pkg, root, exportIds) {
|
|
209
|
+
const files = new Map();
|
|
210
|
+
for (const id of exportIds) {
|
|
211
|
+
const sub = exportSubpath(id);
|
|
212
|
+
if (exportName(id) === '*' || files.has(sub))
|
|
213
|
+
continue;
|
|
214
|
+
const file = findDeclarations(pkgDir, pkg, sub, root);
|
|
215
|
+
if (file !== null)
|
|
216
|
+
files.set(sub, file);
|
|
217
|
+
}
|
|
218
|
+
const shapes = new Map();
|
|
219
|
+
if (files.size === 0)
|
|
220
|
+
return shapes;
|
|
221
|
+
const kinds = ts.ModuleResolutionKind;
|
|
222
|
+
const program = ts.createProgram([...new Set(files.values())], {
|
|
223
|
+
noEmit: true, strict: true, skipLibCheck: true, types: [], lib: ['lib.es2020.d.ts'],
|
|
224
|
+
target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.CommonJS,
|
|
225
|
+
moduleResolution: (kinds.Node10 ?? kinds.NodeJs),
|
|
226
|
+
});
|
|
227
|
+
const checker = program.getTypeChecker();
|
|
228
|
+
for (const id of exportIds) {
|
|
229
|
+
const file = files.get(exportSubpath(id));
|
|
230
|
+
const sf = file === undefined ? undefined : program.getSourceFile(file);
|
|
231
|
+
if (sf === undefined || exportName(id) === '*')
|
|
232
|
+
continue;
|
|
233
|
+
const symbol = exportSymbol(ts, checker, sf, exportName(id));
|
|
234
|
+
if (symbol !== null)
|
|
235
|
+
shapes.set(id, shapeOf(ts, checker, sf, symbol));
|
|
236
|
+
}
|
|
237
|
+
return shapes;
|
|
238
|
+
}
|
|
239
|
+
// ---------- combinations ----------
|
|
240
|
+
/**
|
|
241
|
+
* Argument lists for `params`: every arity from the required count up to all params, Cartesian product of the
|
|
242
|
+
* parameter values. All of them when there are at most `max`; otherwise `max` distinct ones sampled with a
|
|
243
|
+
* mulberry32 PRNG seeded by fnv1a(seedText).
|
|
244
|
+
*/
|
|
245
|
+
export function combinations(params, max, seedText) {
|
|
246
|
+
if (max <= 0)
|
|
247
|
+
return [];
|
|
248
|
+
const required = params.reduce((n, p, i) => (p.optional ? n : i + 1), 0);
|
|
249
|
+
const arities = Array.from({ length: params.length - required + 1 }, (_, i) => required + i);
|
|
250
|
+
const countFor = (arity) => params.slice(0, arity).reduce((n, p) => n * p.values.length, 1);
|
|
251
|
+
const total = arities.reduce((n, arity) => n + countFor(arity), 0);
|
|
252
|
+
const build = (indices) => indices.map((v, i) => params[i].values[v]);
|
|
253
|
+
if (total <= max) {
|
|
254
|
+
const out = [];
|
|
255
|
+
for (const arity of arities) {
|
|
256
|
+
const indices = new Array(arity).fill(0);
|
|
257
|
+
for (let n = 0; n < countFor(arity); n += 1) {
|
|
258
|
+
out.push(build(indices));
|
|
259
|
+
for (let i = arity - 1; i >= 0; i -= 1) {
|
|
260
|
+
indices[i] = (indices[i] + 1) % params[i].values.length;
|
|
261
|
+
if (indices[i] !== 0)
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return out;
|
|
267
|
+
}
|
|
268
|
+
const random = mulberry32(fnv1a(seedText));
|
|
269
|
+
const seen = new Set();
|
|
270
|
+
const out = [];
|
|
271
|
+
for (let attempts = 0; out.length < max && attempts < max * 100; attempts += 1) {
|
|
272
|
+
let pick = random() * total;
|
|
273
|
+
const arity = arities.find((a) => (pick -= countFor(a)) < 0) ?? arities[arities.length - 1];
|
|
274
|
+
const indices = Array.from({ length: arity }, (_, i) => Math.floor(random() * params[i].values.length));
|
|
275
|
+
const key = indices.join(',');
|
|
276
|
+
if (seen.has(key))
|
|
277
|
+
continue;
|
|
278
|
+
seen.add(key);
|
|
279
|
+
out.push(build(indices));
|
|
280
|
+
}
|
|
281
|
+
return out;
|
|
282
|
+
}
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { combinations, readShapes } from './inputs/generate.js';
|
|
7
|
+
import { exportName } from './runtime/protocol.js';
|
|
8
|
+
import { encode } from './serialize.js';
|
|
9
|
+
import { DepkillError } from './types.js';
|
|
10
|
+
import { findPackageDir } from './util/exports.js';
|
|
11
|
+
import { stateDir } from './util/fs.js';
|
|
12
|
+
import { parseSpecifier } from './usage.js';
|
|
13
|
+
import { scriptKind } from './usage/ts.js';
|
|
14
|
+
const AGENT_LOADER = fileURLToPath(new URL('./runtime/agent-inputs.js', import.meta.url));
|
|
15
|
+
const AGENT_TIMEOUT_MS = 30_000;
|
|
16
|
+
const EXPORT_ID = /^(\/[^#]+)?#.+$/;
|
|
17
|
+
// ---------- callsite ----------
|
|
18
|
+
const NOT_LITERAL = Symbol('not literal');
|
|
19
|
+
function unwrap(ts, node) {
|
|
20
|
+
let current = node;
|
|
21
|
+
while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isSatisfiesExpression?.(current)) {
|
|
22
|
+
current = current.expression;
|
|
23
|
+
}
|
|
24
|
+
return current;
|
|
25
|
+
}
|
|
26
|
+
function propertyKey(ts, name) {
|
|
27
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name))
|
|
28
|
+
return name.text;
|
|
29
|
+
if (ts.isNumericLiteral(name))
|
|
30
|
+
return String(Number(name.text));
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
/** Value of a literal expression (strings, numbers incl. negative, booleans, null, undefined, arrays, objects). */
|
|
34
|
+
function literal(ts, node) {
|
|
35
|
+
const e = unwrap(ts, node);
|
|
36
|
+
if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e))
|
|
37
|
+
return e.text;
|
|
38
|
+
if (ts.isNumericLiteral(e))
|
|
39
|
+
return Number.isNaN(Number(e.text)) ? NOT_LITERAL : Number(e.text);
|
|
40
|
+
if (ts.isPrefixUnaryExpression(e) && e.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(e.operand)) {
|
|
41
|
+
return Number.isNaN(Number(e.operand.text)) ? NOT_LITERAL : -Number(e.operand.text);
|
|
42
|
+
}
|
|
43
|
+
if (e.kind === ts.SyntaxKind.TrueKeyword)
|
|
44
|
+
return true;
|
|
45
|
+
if (e.kind === ts.SyntaxKind.FalseKeyword)
|
|
46
|
+
return false;
|
|
47
|
+
if (e.kind === ts.SyntaxKind.NullKeyword)
|
|
48
|
+
return null;
|
|
49
|
+
if (ts.isIdentifier(e) && e.text === 'undefined')
|
|
50
|
+
return undefined;
|
|
51
|
+
if (ts.isArrayLiteralExpression(e)) {
|
|
52
|
+
const items = e.elements.map((el) => (ts.isSpreadElement(el) || ts.isOmittedExpression(el) ? NOT_LITERAL : literal(ts, el)));
|
|
53
|
+
return items.includes(NOT_LITERAL) ? NOT_LITERAL : items;
|
|
54
|
+
}
|
|
55
|
+
if (ts.isObjectLiteralExpression(e)) {
|
|
56
|
+
const out = {};
|
|
57
|
+
for (const prop of e.properties) {
|
|
58
|
+
const key = ts.isPropertyAssignment(prop) ? propertyKey(ts, prop.name) : null;
|
|
59
|
+
if (key === null || key === '__proto__')
|
|
60
|
+
return NOT_LITERAL; // `__proto__:` sets the prototype, not a key
|
|
61
|
+
const value = literal(ts, prop.initializer);
|
|
62
|
+
if (value === NOT_LITERAL)
|
|
63
|
+
return NOT_LITERAL;
|
|
64
|
+
out[key] = value;
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
return NOT_LITERAL;
|
|
69
|
+
}
|
|
70
|
+
/** `require('<spec>')` with a string literal: its specifier, else null. */
|
|
71
|
+
function requiredSpecifier(ts, node) {
|
|
72
|
+
const e = unwrap(ts, node);
|
|
73
|
+
if (!ts.isCallExpression(e) || !ts.isIdentifier(e.expression) || e.expression.text !== 'require')
|
|
74
|
+
return null;
|
|
75
|
+
const [arg] = e.arguments;
|
|
76
|
+
return e.arguments.length === 1 && arg !== undefined && ts.isStringLiteralLike(arg) ? arg.text : null;
|
|
77
|
+
}
|
|
78
|
+
/** Local names bound to the package: callable bindings -> export id, object bindings (namespaces, require results) -> subpath. */
|
|
79
|
+
function packageBindings(ts, sf, subpathOf) {
|
|
80
|
+
const callable = new Map();
|
|
81
|
+
const objects = new Map();
|
|
82
|
+
const bindWhole = (name, sub) => {
|
|
83
|
+
callable.set(name, `${sub}#default`);
|
|
84
|
+
objects.set(name, sub);
|
|
85
|
+
};
|
|
86
|
+
const visit = (node) => {
|
|
87
|
+
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && !node.importClause?.isTypeOnly) {
|
|
88
|
+
const sub = subpathOf(node.moduleSpecifier.text);
|
|
89
|
+
const clause = node.importClause;
|
|
90
|
+
if (sub !== null && clause) {
|
|
91
|
+
// A default import is callable (`_()`) and, for CommonJS / object defaults, a member holder (`_.get()` -> `#get`).
|
|
92
|
+
if (clause.name)
|
|
93
|
+
bindWhole(clause.name.text, sub);
|
|
94
|
+
const bindings = clause.namedBindings;
|
|
95
|
+
if (bindings && ts.isNamespaceImport(bindings))
|
|
96
|
+
objects.set(bindings.name.text, sub);
|
|
97
|
+
else if (bindings) {
|
|
98
|
+
for (const el of bindings.elements)
|
|
99
|
+
if (!el.isTypeOnly)
|
|
100
|
+
callable.set(el.name.text, `${sub}#${(el.propertyName ?? el.name).text}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)
|
|
105
|
+
&& ts.isStringLiteral(node.moduleReference.expression) && !node.isTypeOnly) {
|
|
106
|
+
const sub = subpathOf(node.moduleReference.expression.text);
|
|
107
|
+
if (sub !== null)
|
|
108
|
+
bindWhole(node.name.text, sub);
|
|
109
|
+
}
|
|
110
|
+
else if (ts.isVariableDeclaration(node) && node.initializer) {
|
|
111
|
+
const spec = requiredSpecifier(ts, node.initializer);
|
|
112
|
+
const sub = spec === null ? null : subpathOf(spec);
|
|
113
|
+
if (sub !== null && ts.isIdentifier(node.name))
|
|
114
|
+
bindWhole(node.name.text, sub);
|
|
115
|
+
else if (sub !== null && ts.isObjectBindingPattern(node.name)) {
|
|
116
|
+
for (const el of node.name.elements) {
|
|
117
|
+
const key = el.propertyName ? propertyKey(ts, el.propertyName) : ts.isIdentifier(el.name) ? el.name.text : null;
|
|
118
|
+
if (!el.dotDotDotToken && key !== null && ts.isIdentifier(el.name))
|
|
119
|
+
callable.set(el.name.text, `${sub}#${key}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
ts.forEachChild(node, visit);
|
|
124
|
+
};
|
|
125
|
+
visit(sf);
|
|
126
|
+
return { callable, objects };
|
|
127
|
+
}
|
|
128
|
+
/** Literal-argument calls of package bindings in one source file, in source order. */
|
|
129
|
+
function callsInFile(ts, file, pkg) {
|
|
130
|
+
let text;
|
|
131
|
+
try {
|
|
132
|
+
text = readFileSync(file, 'utf8');
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return [];
|
|
136
|
+
}
|
|
137
|
+
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, scriptKind(ts, file));
|
|
138
|
+
const subpathOf = (spec) => {
|
|
139
|
+
const parsed = parseSpecifier(spec);
|
|
140
|
+
return parsed !== null && parsed.pkg === pkg ? parsed.subpath : null;
|
|
141
|
+
};
|
|
142
|
+
const { callable, objects } = packageBindings(ts, sf, subpathOf);
|
|
143
|
+
const memberOf = (object, member) => {
|
|
144
|
+
const target = unwrap(ts, object);
|
|
145
|
+
if (ts.isIdentifier(target) && objects.has(target.text))
|
|
146
|
+
return `${objects.get(target.text)}#${member}`;
|
|
147
|
+
const spec = requiredSpecifier(ts, target);
|
|
148
|
+
const sub = spec === null ? null : subpathOf(spec);
|
|
149
|
+
return sub === null ? null : `${sub}#${member}`;
|
|
150
|
+
};
|
|
151
|
+
const exportIdOf = (callee) => {
|
|
152
|
+
const e = unwrap(ts, callee);
|
|
153
|
+
if (ts.isIdentifier(e))
|
|
154
|
+
return callable.get(e.text) ?? null;
|
|
155
|
+
if (ts.isPropertyAccessExpression(e))
|
|
156
|
+
return memberOf(e.expression, e.name.text);
|
|
157
|
+
if (ts.isElementAccessExpression(e) && ts.isStringLiteralLike(e.argumentExpression))
|
|
158
|
+
return memberOf(e.expression, e.argumentExpression.text);
|
|
159
|
+
const spec = requiredSpecifier(ts, e);
|
|
160
|
+
const sub = spec === null ? null : subpathOf(spec);
|
|
161
|
+
return sub === null ? null : `${sub}#default`;
|
|
162
|
+
};
|
|
163
|
+
const found = [];
|
|
164
|
+
const visit = (node) => {
|
|
165
|
+
if (ts.isCallExpression(node)) {
|
|
166
|
+
const exportId = exportIdOf(node.expression);
|
|
167
|
+
const args = exportId === null ? [] : node.arguments.map((arg) => (ts.isSpreadElement(arg) ? NOT_LITERAL : literal(ts, arg)));
|
|
168
|
+
if (exportId !== null && !args.includes(NOT_LITERAL))
|
|
169
|
+
found.push({ exportId, args: encode(args) });
|
|
170
|
+
}
|
|
171
|
+
ts.forEachChild(node, visit);
|
|
172
|
+
};
|
|
173
|
+
visit(sf);
|
|
174
|
+
return found;
|
|
175
|
+
}
|
|
176
|
+
function callsiteInputs(ts, root, pkg, sites) {
|
|
177
|
+
const files = [...new Set(sites.filter((s) => s.pkg === pkg).map((s) => s.file))];
|
|
178
|
+
const seen = new Set();
|
|
179
|
+
return files.flatMap((rel) => callsInFile(ts, join(root, ...rel.split('/')), pkg)).filter((input) => {
|
|
180
|
+
const key = `${input.exportId}\u0000${JSON.stringify(input.args)}`;
|
|
181
|
+
if (seen.has(key))
|
|
182
|
+
return false;
|
|
183
|
+
seen.add(key);
|
|
184
|
+
return true;
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
// ---------- agent ----------
|
|
188
|
+
/** Argument lists from `.depkill/<pkg-safe>/inputs.mjs` (default export `{ [exportId]: unknown[][] }`), loaded in a child process. */
|
|
189
|
+
function agentInputs(root, pkg) {
|
|
190
|
+
const file = join(stateDir(root, pkg), 'inputs.mjs');
|
|
191
|
+
if (!existsSync(file))
|
|
192
|
+
return [];
|
|
193
|
+
const dir = mkdtempSync(join(tmpdir(), 'depkill-inputs-'));
|
|
194
|
+
const out = join(dir, 'inputs.json');
|
|
195
|
+
try {
|
|
196
|
+
const env = { ...process.env };
|
|
197
|
+
delete env.NODE_OPTIONS;
|
|
198
|
+
delete env.NODE_TEST_CONTEXT;
|
|
199
|
+
const result = spawnSync(process.execPath, [AGENT_LOADER, file, out], {
|
|
200
|
+
cwd: root, env, timeout: AGENT_TIMEOUT_MS, stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true, encoding: 'utf8',
|
|
201
|
+
});
|
|
202
|
+
if (result.error !== undefined || result.status !== 0 || !existsSync(out)) {
|
|
203
|
+
const why = result.error?.message ?? (result.signal !== null ? `killed (${result.signal}), timeout ${AGENT_TIMEOUT_MS}ms?` : `exit code ${result.status}`);
|
|
204
|
+
throw new DepkillError(`Cannot load ${file}: ${why}`);
|
|
205
|
+
}
|
|
206
|
+
const parsed = JSON.parse(readFileSync(out, 'utf8'));
|
|
207
|
+
if (parsed.error !== undefined || parsed.inputs === undefined)
|
|
208
|
+
throw new DepkillError(`Invalid ${file}: ${parsed.error ?? 'no inputs'}`);
|
|
209
|
+
return Object.entries(parsed.inputs).flatMap(([exportId, lists]) => {
|
|
210
|
+
if (!EXPORT_ID.test(exportId)) {
|
|
211
|
+
throw new DepkillError(`Invalid ${file}: "${exportId}" is not an export id (use "#default", "#name" or "/sub#name").`);
|
|
212
|
+
}
|
|
213
|
+
return lists.map((args) => ({ exportId, args }));
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
finally {
|
|
217
|
+
rmSync(dir, { recursive: true, force: true });
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
// ---------- assembly ----------
|
|
221
|
+
function shapesFor(project, pkg, exportIds) {
|
|
222
|
+
const dir = project.ts === null ? null : findPackageDir(pkg, project.root);
|
|
223
|
+
if (project.ts === null || dir === null)
|
|
224
|
+
return new Map();
|
|
225
|
+
try {
|
|
226
|
+
return readShapes(project.ts, dir, pkg, project.root, exportIds);
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
return new Map(); // unreadable declarations only cost generated evidence
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Inputs to record for `pkg`, ids `"<source>-<exportId>-<n>"`:
|
|
234
|
+
* - `callsite` (needs TS): literal-argument calls of package bindings in the files of `sites`, deduplicated;
|
|
235
|
+
* - `agent`: `.depkill/<pkg-safe>/inputs.mjs`, if present (malformed file: DepkillError, exit 2);
|
|
236
|
+
* - `generated` (needs TS): argument lists from the declared parameter types, at most `maxGenerated` per export;
|
|
237
|
+
* plus one zero-argument constant capture for each used non-function export that got no other input
|
|
238
|
+
* (non-function per `exportKinds`, or per the declarations when no kinds are given; `#*` always is).
|
|
239
|
+
*/
|
|
240
|
+
export function collectInputs(project, pkg, sites, opts) {
|
|
241
|
+
const used = [...new Set(sites.filter((s) => s.pkg === pkg).flatMap((s) => s.exportIds))].sort();
|
|
242
|
+
const cases = [];
|
|
243
|
+
const counters = new Map();
|
|
244
|
+
const add = (source, { exportId, args }) => {
|
|
245
|
+
const key = `${source}-${exportId}`;
|
|
246
|
+
const n = counters.get(key) ?? 0;
|
|
247
|
+
counters.set(key, n + 1);
|
|
248
|
+
cases.push({ id: `${key}-${n}`, exportId, source, args });
|
|
249
|
+
};
|
|
250
|
+
if (project.ts !== null)
|
|
251
|
+
callsiteInputs(project.ts, project.root, pkg, sites).forEach((input) => add('callsite', input));
|
|
252
|
+
agentInputs(project.root, pkg).forEach((input) => add('agent', input));
|
|
253
|
+
const shapes = shapesFor(project, pkg, used);
|
|
254
|
+
const kindOf = (id) => opts.exportKinds?.[id];
|
|
255
|
+
for (const exportId of used) {
|
|
256
|
+
const shape = shapes.get(exportId);
|
|
257
|
+
if (exportName(exportId) === '*' || kindOf(exportId) === 'value' || kindOf(exportId) === 'unloadable')
|
|
258
|
+
continue;
|
|
259
|
+
if (shape?.kind !== 'function' || shape.params === null)
|
|
260
|
+
continue;
|
|
261
|
+
for (const args of combinations(shape.params, opts.maxGenerated, exportId))
|
|
262
|
+
add('generated', { exportId, args: encode(args) });
|
|
263
|
+
}
|
|
264
|
+
for (const exportId of used) {
|
|
265
|
+
if (cases.some((c) => c.exportId === exportId))
|
|
266
|
+
continue;
|
|
267
|
+
const kind = kindOf(exportId);
|
|
268
|
+
const isValue = kind !== undefined ? kind === 'value' : exportName(exportId) === '*' || shapes.get(exportId)?.kind === 'value';
|
|
269
|
+
if (isValue)
|
|
270
|
+
add('generated', { exportId, args: [] });
|
|
271
|
+
}
|
|
272
|
+
return cases;
|
|
273
|
+
}
|