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,88 @@
|
|
|
1
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { readJson } from './util/fs.js';
|
|
4
|
+
/**
|
|
5
|
+
* Conservative "is this un-imported dependency still used?" checks (ruling R21): a package nobody imports may
|
|
6
|
+
* still be type definitions, a CLI run from package.json scripts, or a plugin named in tooling config.
|
|
7
|
+
*/
|
|
8
|
+
const ROOT_CONFIG_FILES = [
|
|
9
|
+
/\.config\.(?:js|cjs|mjs|ts|cts|mts|json)$/i,
|
|
10
|
+
/^\..+rc$/i,
|
|
11
|
+
/^\..+rc\.(?:js|cjs|mjs|json|yaml|yml)$/i,
|
|
12
|
+
/^tsconfig.*\.json$/i,
|
|
13
|
+
];
|
|
14
|
+
const DEPENDENCY_KEYS = new Set(['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies', 'scripts']);
|
|
15
|
+
const WORD_CHAR = '[A-Za-z0-9_@~$-]';
|
|
16
|
+
function isConfigName(fileName) {
|
|
17
|
+
return ROOT_CONFIG_FILES.some((pattern) => pattern.test(fileName));
|
|
18
|
+
}
|
|
19
|
+
/** True for a root-level tooling config file, given a project-relative `/`-separated path (UsageSite.file). */
|
|
20
|
+
export function isRootConfigFile(relPath) {
|
|
21
|
+
return !relPath.includes('/') && isConfigName(relPath);
|
|
22
|
+
}
|
|
23
|
+
function readText(file) {
|
|
24
|
+
try {
|
|
25
|
+
return readFileSync(file, 'utf8');
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** Scripts and tooling config of the project root, read once per scan. Unreadable files are ignored. */
|
|
32
|
+
export function loadToolingContext(project) {
|
|
33
|
+
let names = [];
|
|
34
|
+
try {
|
|
35
|
+
names = readdirSync(project.root, { withFileTypes: true })
|
|
36
|
+
.filter((entry) => entry.isFile() && isConfigName(entry.name))
|
|
37
|
+
.map((entry) => entry.name)
|
|
38
|
+
.sort();
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// no readable root listing: no config files
|
|
42
|
+
}
|
|
43
|
+
const pkg = project.pkg;
|
|
44
|
+
const pkgValues = Object.entries(pkg)
|
|
45
|
+
.filter(([key]) => !DEPENDENCY_KEYS.has(key))
|
|
46
|
+
.map(([, value]) => JSON.stringify(value) ?? '');
|
|
47
|
+
return {
|
|
48
|
+
scripts: Object.values(pkg.scripts ?? {}).filter((value) => typeof value === 'string'),
|
|
49
|
+
configTexts: [...names.map((name) => readText(join(project.root, name))).filter((t) => t !== null), ...pkgValues],
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function escapeRegExp(text) {
|
|
53
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
54
|
+
}
|
|
55
|
+
/** `word` delimited by non-name characters (so `clt` matches `clt .` and `npx clt`, not `cltx` or `clt-extra`). */
|
|
56
|
+
function containsWord(text, word) {
|
|
57
|
+
return new RegExp(`(?<!${WORD_CHAR})${escapeRegExp(word)}(?!${WORD_CHAR})`).test(text);
|
|
58
|
+
}
|
|
59
|
+
/** Bin names a package installs: a string bin is named after the package (without scope), an object bin by its keys. */
|
|
60
|
+
function binNames(name, dir) {
|
|
61
|
+
let manifest;
|
|
62
|
+
try {
|
|
63
|
+
manifest = readJson(join(dir, 'package.json'));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return [];
|
|
67
|
+
}
|
|
68
|
+
if (typeof manifest.bin === 'string')
|
|
69
|
+
return [name.split('/').pop()];
|
|
70
|
+
if (typeof manifest.bin === 'object' && manifest.bin !== null)
|
|
71
|
+
return Object.keys(manifest.bin);
|
|
72
|
+
return [];
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Why a dependency with no import sites must not be called unused, or null when it really looks unused.
|
|
76
|
+
* `dir` is the installed package directory.
|
|
77
|
+
*/
|
|
78
|
+
export function toolingReason(context, name, dir) {
|
|
79
|
+
if (name.startsWith('@types/'))
|
|
80
|
+
return 'type definitions, not runtime code';
|
|
81
|
+
const words = [name, ...binNames(name, dir)];
|
|
82
|
+
if (context.scripts.some((script) => words.some((word) => containsWord(script, word)))) {
|
|
83
|
+
return 'used as a CLI in package.json scripts';
|
|
84
|
+
}
|
|
85
|
+
if (context.configTexts.some((text) => text.includes(name)))
|
|
86
|
+
return 'referenced from tooling config';
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export function emptyUse() {
|
|
2
|
+
return { props: new Set(), called: false, bare: false };
|
|
3
|
+
}
|
|
4
|
+
/** `const x = require('m')`: accessed properties, plus `default` when x is called, used whole, or never dereferenced. */
|
|
5
|
+
export function requireBindingNames(use) {
|
|
6
|
+
const names = [...use.props];
|
|
7
|
+
if (names.length === 0 || use.called || use.bare)
|
|
8
|
+
names.push('default');
|
|
9
|
+
return names;
|
|
10
|
+
}
|
|
11
|
+
/** `import * as ns from 'm'`: accessed properties, plus `*` when ns is used whole or never dereferenced. */
|
|
12
|
+
export function namespaceBindingNames(use) {
|
|
13
|
+
const names = [...use.props];
|
|
14
|
+
if (names.length === 0 || use.called || use.bare)
|
|
15
|
+
names.push('*');
|
|
16
|
+
return names;
|
|
17
|
+
}
|
|
18
|
+
/** 1-based line lookup for character offsets. */
|
|
19
|
+
export function lineIndex(text) {
|
|
20
|
+
const starts = [0];
|
|
21
|
+
for (let i = 0; i < text.length; i++)
|
|
22
|
+
if (text.charCodeAt(i) === 10)
|
|
23
|
+
starts.push(i + 1);
|
|
24
|
+
return (offset) => {
|
|
25
|
+
let lo = 0;
|
|
26
|
+
let hi = starts.length - 1;
|
|
27
|
+
while (lo < hi) {
|
|
28
|
+
const mid = (lo + hi + 1) >> 1;
|
|
29
|
+
if (starts[mid] <= offset)
|
|
30
|
+
lo = mid;
|
|
31
|
+
else
|
|
32
|
+
hi = mid - 1;
|
|
33
|
+
}
|
|
34
|
+
return lo + 1;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// Regex import collector, used when the project has no TypeScript. Best effort: comments are blanked,
|
|
2
|
+
// keyword matches inside strings are rejected, and anything it cannot bind precisely becomes `*`.
|
|
3
|
+
import { emptyUse, lineIndex, namespaceBindingNames, requireBindingNames } from './common.js';
|
|
4
|
+
/** Tokens after which a `/` starts a regex literal rather than a division. */
|
|
5
|
+
const REGEX_PRECEDERS = new Set([
|
|
6
|
+
...'(,=:[!&|?{};+-*%<>~^',
|
|
7
|
+
'return', 'typeof', 'case', 'do', 'else', 'in', 'of', 'new', 'delete', 'void', 'throw', 'yield', 'await',
|
|
8
|
+
]);
|
|
9
|
+
/** Index just past the literal opened by `quote` at `start`, and whether it was closed. */
|
|
10
|
+
function literalEnd(text, start, quote) {
|
|
11
|
+
let inClass = false;
|
|
12
|
+
let end = start + 1;
|
|
13
|
+
while (end < text.length) {
|
|
14
|
+
const ch = text[end];
|
|
15
|
+
if (ch === '\\')
|
|
16
|
+
end += 2;
|
|
17
|
+
else if (quote !== '`' && ch === '\n')
|
|
18
|
+
return { end, closed: false }; // recover at end of line
|
|
19
|
+
else if (quote === '/' && ch === '[') {
|
|
20
|
+
inClass = true;
|
|
21
|
+
end++;
|
|
22
|
+
}
|
|
23
|
+
else if (quote === '/' && ch === ']') {
|
|
24
|
+
inClass = false;
|
|
25
|
+
end++;
|
|
26
|
+
}
|
|
27
|
+
else if (ch === quote && !inClass)
|
|
28
|
+
return { end: end + 1, closed: true };
|
|
29
|
+
else
|
|
30
|
+
end++;
|
|
31
|
+
}
|
|
32
|
+
return { end: text.length, closed: false };
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Tokenizes just enough JS to tell code from comments and literals. Fails safe: a template literal still
|
|
36
|
+
* open at end of file (a stray backtick, e.g. in JSX text) is treated as plain text so it cannot hide imports.
|
|
37
|
+
*/
|
|
38
|
+
function mask(text) {
|
|
39
|
+
const stripped = text.split(''); // UTF-16 units, so indices match text[i]
|
|
40
|
+
const code = text.split('');
|
|
41
|
+
const blank = (from, to, both) => {
|
|
42
|
+
for (let k = from; k < to; k++) {
|
|
43
|
+
if (text[k] === '\n' || text[k] === '\r')
|
|
44
|
+
continue;
|
|
45
|
+
code[k] = ' ';
|
|
46
|
+
if (both)
|
|
47
|
+
stripped[k] = ' ';
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
let prev = ''; // last significant code token: a punctuation character or a whole word
|
|
51
|
+
let i = 0;
|
|
52
|
+
while (i < text.length) {
|
|
53
|
+
const c = text[i];
|
|
54
|
+
const next = text[i + 1];
|
|
55
|
+
let end = i + 1;
|
|
56
|
+
if (c === '/' && next === '/') {
|
|
57
|
+
while (end < text.length && text[end] !== '\n')
|
|
58
|
+
end++;
|
|
59
|
+
blank(i, end, true);
|
|
60
|
+
}
|
|
61
|
+
else if (c === '/' && next === '*') {
|
|
62
|
+
const close = text.indexOf('*/', i + 2);
|
|
63
|
+
end = close === -1 ? text.length : close + 2;
|
|
64
|
+
blank(i, end, true);
|
|
65
|
+
}
|
|
66
|
+
else if (c === '"' || c === "'" || c === '`' || (c === '/' && (prev === '' || REGEX_PRECEDERS.has(prev)))) {
|
|
67
|
+
const literal = literalEnd(text, i, c);
|
|
68
|
+
if (c === '`' && !literal.closed) {
|
|
69
|
+
prev = c; // stray backtick: plain text, keep scanning right after it
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
end = Math.min(literal.end, text.length);
|
|
73
|
+
blank(i + 1, literal.closed ? end - 1 : end, false);
|
|
74
|
+
prev = c;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
else if (/[\w$]/.test(c)) {
|
|
78
|
+
while (end < text.length && /[\w$]/.test(text[end]))
|
|
79
|
+
end++;
|
|
80
|
+
// A member name (`obj.in`, `x?.of`) is not a keyword: `/` after it is a division.
|
|
81
|
+
prev = prev === '.' ? `.${text.slice(i, end)}` : text.slice(i, end);
|
|
82
|
+
}
|
|
83
|
+
else if (!/\s/.test(c)) {
|
|
84
|
+
prev = c;
|
|
85
|
+
}
|
|
86
|
+
i = end;
|
|
87
|
+
}
|
|
88
|
+
return { stripped: stripped.join(''), code: code.join('') };
|
|
89
|
+
}
|
|
90
|
+
const ID = '[\\w$]+';
|
|
91
|
+
/** Not preceded by an identifier char or a member dot (`a.x`, `a?.x`); a spread `...x` still counts. */
|
|
92
|
+
const NOT_MEMBER = '(?<![\\w$])(?<!(?<!\\.\\.)\\.)';
|
|
93
|
+
const STATIC_IMPORT = /(?<![\w$.])import(?=[\s{*])([\w$*{}\s,]*?)\bfrom\s*(['"])([^'"\r\n]+)\2/g;
|
|
94
|
+
const SIDE_EFFECT_IMPORT = /(?<![\w$.])import\s*(['"])([^'"\r\n]+)\1/g;
|
|
95
|
+
const EXPORT_FROM = /(?<![\w$.])export\s*(type\s+)?(\*(?:\s*as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\r\n]+)\3/g;
|
|
96
|
+
// `typeof import('m')` is a type query (erased), not a dynamic import.
|
|
97
|
+
// A `,` may follow the specifier: import attributes (`import('m', { with })`) or a trailing comma.
|
|
98
|
+
const DYNAMIC_IMPORT = /(?<![\w$.])(?<!\btypeof\s*)import\s*\(\s*(['"`])([^'"`\r\n]+)\1\s*[,)]/g;
|
|
99
|
+
// The optional trailing comma is consumed so that what follows the call (`.foo`, `(...)`) is still seen.
|
|
100
|
+
const REQUIRE = /(?<![\w$.])require\s*\(\s*(['"`])([^'"`\r\n]+)\1\s*(?:,\s*)?\)/g;
|
|
101
|
+
/** `require.resolve('m'[, options])` / `import.meta.resolve('m')`: no export used, but still need the package. */
|
|
102
|
+
const REQUIRE_RESOLVE = /(?<![\w$.])require\s*\.\s*resolve\s*\(\s*(['"`])([^'"`\r\n]+)\1/g;
|
|
103
|
+
const IMPORT_META_RESOLVE = /(?<![\w$.])import\s*\.\s*meta\s*\.\s*resolve\s*\(\s*(['"`])([^'"`\r\n]+)\1/g;
|
|
104
|
+
/**
|
|
105
|
+
* Fail-safe pass over the RAW text (no comment stripping, no literal mask, so lexer mistakes cannot hide anything):
|
|
106
|
+
* an import keyword directly followed by a quoted specifier is reported even inside comments or literals.
|
|
107
|
+
* Over-reporting beats missing an import.
|
|
108
|
+
* A specifier in an ordinary string (`const s = 'pkg'`) never matches: the keyword must precede the quote.
|
|
109
|
+
*/
|
|
110
|
+
const SAFE_SPEC = String.raw `(['"\x60])([^'"\x60\r\n]+)\1`;
|
|
111
|
+
/**
|
|
112
|
+
* Gap between keyword, `(`, `.`, `from` and the quote: whitespace, block comments, line comments.
|
|
113
|
+
* A block comment body cannot contain `*\/`, so every gap has exactly one parse and matching stays linear.
|
|
114
|
+
*/
|
|
115
|
+
const GAP = String.raw `(?:\s|/\*(?:[^*]|\*(?!/))*\*/|//[^\n]*\n)*`;
|
|
116
|
+
const safe = (source) => new RegExp(String.raw `(?<![\w$.])${source}${SAFE_SPEC}`, 'g');
|
|
117
|
+
const SAFETY_PATTERNS = [
|
|
118
|
+
[safe(String.raw `require${GAP}\(${GAP}`), ['*']],
|
|
119
|
+
[safe(String.raw `(?<!\btypeof\s*)import${GAP}\(${GAP}`), ['*']],
|
|
120
|
+
[safe(String.raw `import${GAP}`), ['*']],
|
|
121
|
+
[safe(String.raw `from${GAP}`), ['*']],
|
|
122
|
+
[safe(String.raw `require${GAP}\.${GAP}resolve${GAP}\(${GAP}`), []],
|
|
123
|
+
[safe(String.raw `import${GAP}\.${GAP}meta${GAP}\.${GAP}resolve${GAP}\(${GAP}`), []],
|
|
124
|
+
];
|
|
125
|
+
const escapeRe = (s) => s.replace(/[$]/g, '\\$');
|
|
126
|
+
/** Collects every import of a wanted specifier in one file, in source order. */
|
|
127
|
+
export function collectWithFallback(text, wanted) {
|
|
128
|
+
const { stripped, code } = mask(text);
|
|
129
|
+
const lineOf = lineIndex(text);
|
|
130
|
+
const out = [];
|
|
131
|
+
const consumed = new Set(); // start offsets of specifiers already reported
|
|
132
|
+
const window = (from, to) => stripped.slice(Math.max(0, from), to);
|
|
133
|
+
/** Name-based use of a binding across the file (strings blanked, so literals do not count). */
|
|
134
|
+
const useOf = (name) => {
|
|
135
|
+
const use = emptyUse();
|
|
136
|
+
for (const m of code.matchAll(new RegExp(`${NOT_MEMBER}${escapeRe(name)}(?![\\w$])`, 'g'))) {
|
|
137
|
+
const at = m.index;
|
|
138
|
+
const after = window(at + name.length, at + name.length + 200);
|
|
139
|
+
if (/\bas\s+$/.test(window(at - 8, at)))
|
|
140
|
+
continue; // `* as name` / `{ x as name }` declarations
|
|
141
|
+
if (/^\s*=(?![=>])/.test(after))
|
|
142
|
+
continue; // declaration or reassignment, not a use
|
|
143
|
+
const prop = /^\s*\??\.\s*([\w$]+)/.exec(after) ?? /^\s*\[\s*(['"])([^'"\r\n]+)\1\s*\]/.exec(after);
|
|
144
|
+
if (prop)
|
|
145
|
+
use.props.add(prop[2] ?? prop[1]);
|
|
146
|
+
else if (/^\s*\(/.test(after))
|
|
147
|
+
use.called = true;
|
|
148
|
+
else
|
|
149
|
+
use.bare = true;
|
|
150
|
+
}
|
|
151
|
+
return use;
|
|
152
|
+
};
|
|
153
|
+
const clauseNames = (clause) => {
|
|
154
|
+
const c = clause.trim();
|
|
155
|
+
if (/^type\s+[\w${*]/.test(c))
|
|
156
|
+
return [];
|
|
157
|
+
const names = [];
|
|
158
|
+
const braces = /\{([^}]*)\}/.exec(c);
|
|
159
|
+
for (const el of braces ? braces[1].split(',') : []) {
|
|
160
|
+
const item = el.trim();
|
|
161
|
+
if (item !== '' && !/^type\s/.test(item))
|
|
162
|
+
names.push(item.split(/\s+as\s+/)[0].trim());
|
|
163
|
+
}
|
|
164
|
+
for (const part of c.replace(/\{[^}]*\}/, '').split(',').map((p) => p.trim()).filter(Boolean)) {
|
|
165
|
+
const ns = new RegExp(`^\\*\\s*as\\s+(${ID})$`).exec(part);
|
|
166
|
+
names.push(...(ns ? namespaceBindingNames(useOf(ns[1])) : part.startsWith('*') ? ['*'] : ['default']));
|
|
167
|
+
}
|
|
168
|
+
return names;
|
|
169
|
+
};
|
|
170
|
+
const exportClauseNames = (clause) => {
|
|
171
|
+
if (clause.startsWith('*'))
|
|
172
|
+
return ['*'];
|
|
173
|
+
return clause.slice(1, -1).split(',').map((el) => el.trim())
|
|
174
|
+
.filter((el) => el !== '' && !/^type\s/.test(el)).map((el) => el.split(/\s+as\s+/)[0].trim());
|
|
175
|
+
};
|
|
176
|
+
const requireNames = (start, end) => {
|
|
177
|
+
const before = window(start - 300, start);
|
|
178
|
+
const after = window(end, end + 200);
|
|
179
|
+
// What directly follows the call wins: `require('m').foo`, `require('m')['foo']`, `require('m')(...)`.
|
|
180
|
+
const prop = /^\s*\??\.\s*([\w$]+)/.exec(after) ?? /^\s*\[\s*(['"])([^'"\r\n]+)\1\s*\]/.exec(after);
|
|
181
|
+
if (prop)
|
|
182
|
+
return [prop[2] ?? prop[1]];
|
|
183
|
+
if (/^\s*\[/.test(after))
|
|
184
|
+
return ['*'];
|
|
185
|
+
if (/^\s*\(/.test(after))
|
|
186
|
+
return ['default'];
|
|
187
|
+
const id = new RegExp(`(?:const|let|var)\\s+(${ID})\\s*=\\s*$`).exec(before);
|
|
188
|
+
if (id)
|
|
189
|
+
return requireBindingNames(useOf(id[1]));
|
|
190
|
+
const destructured = /(?:const|let|var)\s*\{([^{}]*)\}\s*=\s*$/.exec(before);
|
|
191
|
+
if (destructured) {
|
|
192
|
+
return destructured[1].split(',').map((el) => el.split('=')[0].trim()).filter(Boolean)
|
|
193
|
+
.map((el) => (el.startsWith('...') ? '*' : el.split(':')[0].trim().replace(/^(['"])(.*)\1$/, '$2')));
|
|
194
|
+
}
|
|
195
|
+
const statementStart = /[;{})]\s*$/.test(before) || (start <= 300 && before.trim() === '');
|
|
196
|
+
if (statementStart && /^[ \t]*(;|\r?\n|$)/.test(after))
|
|
197
|
+
return [];
|
|
198
|
+
return ['default'];
|
|
199
|
+
};
|
|
200
|
+
/**
|
|
201
|
+
* With a `keyword`: matches `re` on comment-stripped text, only where the mask says that keyword is real code.
|
|
202
|
+
* Without one (fail-safe pass): matches `re` on the raw text. All views share offsets, so de-duplication holds.
|
|
203
|
+
*/
|
|
204
|
+
const scan = (re, keyword, specGroup, names) => {
|
|
205
|
+
for (const m of (keyword === null ? text : stripped).matchAll(re)) {
|
|
206
|
+
const spec = m[specGroup];
|
|
207
|
+
const specStart = m.index + m[0].lastIndexOf(spec);
|
|
208
|
+
if (consumed.has(specStart) || (keyword !== null && !code.startsWith(keyword, m.index)))
|
|
209
|
+
continue;
|
|
210
|
+
if (spec.includes('${') || !wanted(spec))
|
|
211
|
+
continue;
|
|
212
|
+
consumed.add(specStart);
|
|
213
|
+
out.push({ offset: m.index, line: lineOf(m.index), specifier: spec, names: names(m) });
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
scan(STATIC_IMPORT, 'import', 3, (m) => clauseNames(m[1]));
|
|
217
|
+
scan(SIDE_EFFECT_IMPORT, 'import', 2, () => []);
|
|
218
|
+
scan(EXPORT_FROM, 'export', 4, (m) => (m[1] ? [] : exportClauseNames(m[2])));
|
|
219
|
+
scan(DYNAMIC_IMPORT, 'import', 2, () => ['*']);
|
|
220
|
+
scan(REQUIRE, 'require', 2, (m) => requireNames(m.index, m.index + m[0].length));
|
|
221
|
+
scan(REQUIRE_RESOLVE, 'require', 2, () => []);
|
|
222
|
+
scan(IMPORT_META_RESOLVE, 'import', 2, () => []);
|
|
223
|
+
// Fail-safe: whatever the precise pass skipped (possibly a mis-lexed literal) is still reported.
|
|
224
|
+
for (const [re, names] of SAFETY_PATTERNS)
|
|
225
|
+
scan(re, null, 2, () => names);
|
|
226
|
+
return out.sort((a, b) => a.offset - b.offset);
|
|
227
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { emptyUse, namespaceBindingNames, requireBindingNames } from './common.js';
|
|
2
|
+
export function scriptKind(ts, file) {
|
|
3
|
+
const lower = file.toLowerCase();
|
|
4
|
+
if (lower.endsWith('.tsx'))
|
|
5
|
+
return ts.ScriptKind.TSX;
|
|
6
|
+
if (lower.endsWith('.jsx'))
|
|
7
|
+
return ts.ScriptKind.JSX;
|
|
8
|
+
if (/\.[cm]?ts$/.test(lower))
|
|
9
|
+
return ts.ScriptKind.TS;
|
|
10
|
+
return ts.ScriptKind.JS;
|
|
11
|
+
}
|
|
12
|
+
/** Collects every import of a wanted specifier in one file, in source order. */
|
|
13
|
+
export function collectWithTs(ts, file, text, wanted) {
|
|
14
|
+
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, scriptKind(ts, file));
|
|
15
|
+
const out = [];
|
|
16
|
+
/** Is this identifier occurrence a value reference (not a declaration name, property key or type)? */
|
|
17
|
+
const isReference = (id) => {
|
|
18
|
+
const p = id.parent;
|
|
19
|
+
if (ts.isShorthandPropertyAssignment(p))
|
|
20
|
+
return true;
|
|
21
|
+
if (ts.isExportSpecifier(p))
|
|
22
|
+
return (p.propertyName ?? p.name) === id;
|
|
23
|
+
if (ts.isQualifiedName(p) || ts.isTypeQueryNode(p) || ts.isTypeReferenceNode(p))
|
|
24
|
+
return false;
|
|
25
|
+
const named = p;
|
|
26
|
+
return named.name !== id && named.propertyName !== id;
|
|
27
|
+
};
|
|
28
|
+
/** How `binding` is used in this file. Same-file and name-based only (shadowing is not tracked). */
|
|
29
|
+
const useOf = (binding) => {
|
|
30
|
+
const use = emptyUse();
|
|
31
|
+
const visit = (node) => {
|
|
32
|
+
if (ts.isIdentifier(node) && node !== binding && node.text === binding.text && isReference(node)) {
|
|
33
|
+
const p = node.parent;
|
|
34
|
+
if (ts.isPropertyAccessExpression(p) && p.expression === node)
|
|
35
|
+
use.props.add(p.name.text);
|
|
36
|
+
else if (ts.isElementAccessExpression(p) && p.expression === node && ts.isStringLiteralLike(p.argumentExpression)) {
|
|
37
|
+
use.props.add(p.argumentExpression.text);
|
|
38
|
+
}
|
|
39
|
+
else if (ts.isCallExpression(p) && p.expression === node)
|
|
40
|
+
use.called = true;
|
|
41
|
+
else
|
|
42
|
+
use.bare = true;
|
|
43
|
+
}
|
|
44
|
+
ts.forEachChild(node, visit);
|
|
45
|
+
};
|
|
46
|
+
visit(sf);
|
|
47
|
+
return use;
|
|
48
|
+
};
|
|
49
|
+
/** Names bound by `<pattern> = require('m')`. */
|
|
50
|
+
const bindingNames = (name) => {
|
|
51
|
+
if (ts.isIdentifier(name))
|
|
52
|
+
return requireBindingNames(useOf(name));
|
|
53
|
+
if (ts.isArrayBindingPattern(name))
|
|
54
|
+
return ['default'];
|
|
55
|
+
return name.elements.map((el) => {
|
|
56
|
+
const key = el.propertyName ?? el.name;
|
|
57
|
+
if (el.dotDotDotToken || !(ts.isIdentifier(key) || ts.isStringLiteralLike(key) || ts.isNumericLiteral(key)))
|
|
58
|
+
return '*';
|
|
59
|
+
return key.text;
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
/** Names a bare `require('m')` call is used for, judged by its syntactic parent. */
|
|
63
|
+
const requireNames = (call) => {
|
|
64
|
+
let expr = call;
|
|
65
|
+
while (ts.isParenthesizedExpression(expr.parent))
|
|
66
|
+
expr = expr.parent;
|
|
67
|
+
const p = expr.parent;
|
|
68
|
+
if (ts.isVariableDeclaration(p) && p.initializer === expr)
|
|
69
|
+
return bindingNames(p.name);
|
|
70
|
+
if (ts.isPropertyAccessExpression(p) && p.expression === expr)
|
|
71
|
+
return [p.name.text];
|
|
72
|
+
if (ts.isElementAccessExpression(p) && p.expression === expr) {
|
|
73
|
+
return ts.isStringLiteralLike(p.argumentExpression) ? [p.argumentExpression.text] : ['*'];
|
|
74
|
+
}
|
|
75
|
+
if (ts.isExpressionStatement(p))
|
|
76
|
+
return [];
|
|
77
|
+
return ['default'];
|
|
78
|
+
};
|
|
79
|
+
// `isTypeOnly` (deprecated in TS 5.9 in favour of phaseModifier) is kept for older project TypeScript versions.
|
|
80
|
+
const importNames = (clause) => {
|
|
81
|
+
if (!clause || clause.isTypeOnly)
|
|
82
|
+
return [];
|
|
83
|
+
const names = clause.name ? ['default'] : [];
|
|
84
|
+
const bindings = clause.namedBindings;
|
|
85
|
+
if (bindings && ts.isNamespaceImport(bindings))
|
|
86
|
+
names.push(...namespaceBindingNames(useOf(bindings.name)));
|
|
87
|
+
else if (bindings)
|
|
88
|
+
for (const el of bindings.elements)
|
|
89
|
+
if (!el.isTypeOnly)
|
|
90
|
+
names.push((el.propertyName ?? el.name).text);
|
|
91
|
+
return names;
|
|
92
|
+
};
|
|
93
|
+
const exportNames = (decl) => {
|
|
94
|
+
if (decl.isTypeOnly)
|
|
95
|
+
return [];
|
|
96
|
+
if (!decl.exportClause || ts.isNamespaceExport(decl.exportClause))
|
|
97
|
+
return ['*'];
|
|
98
|
+
return decl.exportClause.elements.filter((el) => !el.isTypeOnly).map((el) => (el.propertyName ?? el.name).text);
|
|
99
|
+
};
|
|
100
|
+
/** [specifier, names] when `node` imports a wanted specifier. */
|
|
101
|
+
const inspect = (node) => {
|
|
102
|
+
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
|
|
103
|
+
return [node.moduleSpecifier.text, () => importNames(node.importClause)];
|
|
104
|
+
}
|
|
105
|
+
if (ts.isExportDeclaration(node) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
|
|
106
|
+
return [node.moduleSpecifier.text, () => exportNames(node)];
|
|
107
|
+
}
|
|
108
|
+
if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)
|
|
109
|
+
&& ts.isStringLiteral(node.moduleReference.expression)) {
|
|
110
|
+
return [node.moduleReference.expression.text, () => (node.isTypeOnly ? [] : requireBindingNames(useOf(node.name)))];
|
|
111
|
+
}
|
|
112
|
+
if (ts.isCallExpression(node) && node.arguments.length >= 1 && ts.isStringLiteralLike(node.arguments[0])) {
|
|
113
|
+
const spec = node.arguments[0].text;
|
|
114
|
+
if (node.expression.kind === ts.SyntaxKind.ImportKeyword)
|
|
115
|
+
return [spec, () => ['*']];
|
|
116
|
+
if (ts.isIdentifier(node.expression) && node.expression.text === 'require' && node.arguments.length === 1) {
|
|
117
|
+
return [spec, () => requireNames(node)];
|
|
118
|
+
}
|
|
119
|
+
// `require.resolve('m')` / `import.meta.resolve('m')` use no export, but still need the package installed.
|
|
120
|
+
const callee = node.expression;
|
|
121
|
+
if (ts.isPropertyAccessExpression(callee) && callee.name.text === 'resolve') {
|
|
122
|
+
const target = callee.expression;
|
|
123
|
+
const isRequire = ts.isIdentifier(target) && target.text === 'require';
|
|
124
|
+
const isImportMeta = ts.isMetaProperty(target) && target.keywordToken === ts.SyntaxKind.ImportKeyword
|
|
125
|
+
&& target.name.text === 'meta';
|
|
126
|
+
if (isRequire || isImportMeta)
|
|
127
|
+
return [spec, () => []];
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return null;
|
|
131
|
+
};
|
|
132
|
+
const visit = (node) => {
|
|
133
|
+
const found = inspect(node);
|
|
134
|
+
if (found && wanted(found[0])) {
|
|
135
|
+
const offset = node.getStart(sf);
|
|
136
|
+
out.push({ offset, line: sf.getLineAndCharacterOfPosition(offset).line + 1, specifier: found[0], names: found[1]() });
|
|
137
|
+
}
|
|
138
|
+
ts.forEachChild(node, visit);
|
|
139
|
+
};
|
|
140
|
+
visit(sf);
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { extname, join, relative, sep } from 'node:path';
|
|
3
|
+
import { DepkillError } from './types.js';
|
|
4
|
+
import { collectWithFallback } from './usage/fallback.js';
|
|
5
|
+
import { collectWithTs } from './usage/ts.js';
|
|
6
|
+
const SOURCE_EXTENSIONS = new Set(['.js', '.cjs', '.mjs', '.jsx', '.ts', '.cts', '.mts', '.tsx']);
|
|
7
|
+
const SFC_EXTENSIONS = new Set(['.vue', '.svelte', '.astro']);
|
|
8
|
+
const SKIPPED_DIRS = new Set(['node_modules', 'dist', 'build', '.depkill', 'coverage']);
|
|
9
|
+
const DECLARATION_FILE = /\.d\.[cm]?ts$/i;
|
|
10
|
+
/** Absolute paths of the project's own source files, sorted. Skips build output, deps and dot-folders. */
|
|
11
|
+
export function listSourceFiles(root) {
|
|
12
|
+
const files = [];
|
|
13
|
+
const walk = (dir) => {
|
|
14
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
15
|
+
const full = join(dir, entry.name);
|
|
16
|
+
if (entry.isDirectory()) {
|
|
17
|
+
if (!SKIPPED_DIRS.has(entry.name) && !entry.name.startsWith('.'))
|
|
18
|
+
walk(full);
|
|
19
|
+
}
|
|
20
|
+
else if (entry.isFile()) {
|
|
21
|
+
const ext = extname(entry.name).toLowerCase();
|
|
22
|
+
if ((SOURCE_EXTENSIONS.has(ext) || SFC_EXTENSIONS.has(ext)) && !DECLARATION_FILE.test(entry.name))
|
|
23
|
+
files.push(full);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
walk(root);
|
|
28
|
+
return files.sort();
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Package and subpath a bare specifier refers to: `@scope/name/rest` -> `@scope/name` + `/rest`,
|
|
32
|
+
* `name/rest` -> `name` + `/rest`. Null for relative/absolute paths, `#imports` and scheme specifiers
|
|
33
|
+
* (`node:fs`, `file:`, `C:\`). Bare builtin names (`events`, `util`) are NOT excluded: npm packages share
|
|
34
|
+
* them, and scanUsage only reports packages it was asked for.
|
|
35
|
+
*/
|
|
36
|
+
export function parseSpecifier(specifier) {
|
|
37
|
+
if (specifier === '' || /^[./\\#]/.test(specifier) || /^[a-z][a-z\d+.-]*:/i.test(specifier))
|
|
38
|
+
return null;
|
|
39
|
+
const parts = specifier.split('/');
|
|
40
|
+
const nameParts = specifier.startsWith('@') ? 2 : 1;
|
|
41
|
+
if (parts.length < nameParts || parts.slice(0, nameParts).includes(''))
|
|
42
|
+
return null;
|
|
43
|
+
const rest = parts.slice(nameParts).join('/');
|
|
44
|
+
return { pkg: parts.slice(0, nameParts).join('/'), subpath: rest === '' ? '' : `/${rest}` };
|
|
45
|
+
}
|
|
46
|
+
function readSource(file) {
|
|
47
|
+
try {
|
|
48
|
+
return readFileSync(file, 'utf8');
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
52
|
+
throw new DepkillError(`Cannot read source file ${file}: ${reason}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** TS AST when available (except SFCs); the regex scanner otherwise, or when TS fails on this file. */
|
|
56
|
+
function collectImports(project, file, text, wanted) {
|
|
57
|
+
if (project.ts && !SFC_EXTENSIONS.has(extname(file).toLowerCase())) {
|
|
58
|
+
try {
|
|
59
|
+
return collectWithTs(project.ts, file, text, wanted);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// fall through to the regex scanner
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return collectWithFallback(text, wanted);
|
|
66
|
+
}
|
|
67
|
+
/** Relative import/require specifiers (`./…`, `../…`) in `file`. Used by `gate` for `wired` and `ships`. */
|
|
68
|
+
export function collectRelativeImports(project, file, text) {
|
|
69
|
+
return collectImports(project, file, text, (s) => s.startsWith('./') || s.startsWith('../')).map((imp) => imp.specifier);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Every place the project imports one of `pkgNames` (import, require, dynamic import, re-export),
|
|
73
|
+
* with the export ids used there (`<subpath>#<name>`). Uses the project's TypeScript when available,
|
|
74
|
+
* a regex fallback otherwise. Sorted by file (relative, `/`-separated) then line.
|
|
75
|
+
*/
|
|
76
|
+
export function scanUsage(project, pkgNames) {
|
|
77
|
+
if (pkgNames.size === 0)
|
|
78
|
+
return [];
|
|
79
|
+
const wanted = (specifier) => {
|
|
80
|
+
const parsed = parseSpecifier(specifier);
|
|
81
|
+
return parsed !== null && pkgNames.has(parsed.pkg);
|
|
82
|
+
};
|
|
83
|
+
const sites = [];
|
|
84
|
+
for (const file of listSourceFiles(project.root)) {
|
|
85
|
+
const text = readSource(file);
|
|
86
|
+
if (![...pkgNames].some((name) => text.includes(name)))
|
|
87
|
+
continue; // cheap pre-filter
|
|
88
|
+
const imports = collectImports(project, file, text, wanted);
|
|
89
|
+
const rel = relative(project.root, file).split(sep).join('/');
|
|
90
|
+
for (const { line, specifier, names } of imports) {
|
|
91
|
+
const { pkg, subpath } = parseSpecifier(specifier);
|
|
92
|
+
const exportIds = [...new Set(names.map((name) => `${subpath}#${name}`))].sort();
|
|
93
|
+
sites.push({ file: rel, line, specifier, pkg, exportIds });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return sites.sort((a, b) => (a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1));
|
|
97
|
+
}
|