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,177 @@
1
+ /**
2
+ * A small, total JavaScript tokenizer for similarity checks: drops comments and whitespace, keeps identifiers,
3
+ * numbers, punctuators, and string / template-chunk / regex literals as single tokens. It never throws and always
4
+ * advances, so any input (including TypeScript or garbage) yields some token list.
5
+ */
6
+ const SHINGLE_SIZE = 5;
7
+ // Longest first, so `>>>=` wins over `>>`.
8
+ const PUNCTUATORS = [
9
+ '>>>=', '...', '===', '!==', '**=', '<<=', '>>=', '>>>', '&&=', '||=', '??=',
10
+ '=>', '==', '!=', '<=', '>=', '&&', '||', '??', '?.', '++', '--', '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=',
11
+ '<<', '>>', '**',
12
+ ];
13
+ /** Keywords after which `/` starts a regex literal rather than a division. */
14
+ const REGEX_AFTER_WORD = new Set(['return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void', 'throw', 'case', 'do', 'else', 'yield', 'await']);
15
+ const isIdentStart = (ch) => /[A-Za-z_$#\\]/.test(ch) || ch.charCodeAt(0) >= 0x80;
16
+ const isIdentPart = (ch) => /[\w$\\]/.test(ch) || ch.charCodeAt(0) >= 0x80;
17
+ const isDigit = (ch) => ch >= '0' && ch <= '9';
18
+ /** Can a `/` here begin a regex literal, judging by the previous significant token? */
19
+ function regexAllowed(prev) {
20
+ if (prev === undefined)
21
+ return true;
22
+ if (prev.type === 'ident')
23
+ return REGEX_AFTER_WORD.has(prev.value);
24
+ if (prev.type === 'punct')
25
+ return prev.value !== ')' && prev.value !== ']' && prev.value !== '}';
26
+ return prev.type === 'template' && prev.value.endsWith('${');
27
+ }
28
+ export function tokenize(src) {
29
+ const tokens = [];
30
+ /** Brace depth at which each open template substitution resumes its template. */
31
+ const templateDepths = [];
32
+ let depth = 0;
33
+ let line = 1;
34
+ let i = 0;
35
+ const n = src.length;
36
+ const push = (type, start, end) => {
37
+ tokens.push({ type, value: src.slice(start, end), line });
38
+ for (let k = start; k < end; k += 1)
39
+ if (src.charCodeAt(k) === 10)
40
+ line += 1;
41
+ i = end;
42
+ };
43
+ /** Scans template text from `start` (just after "`" or "}") to the closing "`" or the next "${". */
44
+ const templateChunk = (start, from) => {
45
+ let j = from;
46
+ while (j < n) {
47
+ const ch = src[j];
48
+ if (ch === '\\')
49
+ j += 2;
50
+ else if (ch === '`') {
51
+ push('template', start, j + 1);
52
+ return;
53
+ }
54
+ else if (ch === '$' && src[j + 1] === '{') {
55
+ templateDepths.push(depth);
56
+ depth += 1;
57
+ push('template', start, j + 2);
58
+ return;
59
+ }
60
+ else
61
+ j += 1;
62
+ }
63
+ push('template', start, n);
64
+ };
65
+ if (src.startsWith('#!')) {
66
+ while (i < n && src[i] !== '\n')
67
+ i += 1;
68
+ }
69
+ while (i < n) {
70
+ const ch = src[i];
71
+ const next = src[i + 1];
72
+ if (ch === '\n') {
73
+ line += 1;
74
+ i += 1;
75
+ }
76
+ else if (/\s/.test(ch)) {
77
+ i += 1;
78
+ }
79
+ else if (ch === '/' && next === '/') {
80
+ while (i < n && src[i] !== '\n')
81
+ i += 1;
82
+ }
83
+ else if (ch === '/' && next === '*') {
84
+ const end = src.indexOf('*/', i + 2);
85
+ const stop = end === -1 ? n : end + 2;
86
+ for (let k = i; k < stop; k += 1)
87
+ if (src.charCodeAt(k) === 10)
88
+ line += 1;
89
+ i = stop;
90
+ }
91
+ else if (ch === '"' || ch === "'") {
92
+ let j = i + 1;
93
+ while (j < n && src[j] !== ch && src[j] !== '\n')
94
+ j += src[j] === '\\' ? 2 : 1;
95
+ push('string', i, Math.min(j + 1, n));
96
+ }
97
+ else if (ch === '`') {
98
+ templateChunk(i, i + 1);
99
+ }
100
+ else if (ch === '}' && templateDepths.length > 0 && templateDepths[templateDepths.length - 1] === depth - 1) {
101
+ templateDepths.pop();
102
+ depth -= 1;
103
+ templateChunk(i, i + 1);
104
+ }
105
+ else if (isDigit(ch) || (ch === '.' && next !== undefined && isDigit(next))) {
106
+ let j = i + 1;
107
+ while (j < n && (/[\w.]/.test(src[j]) || ((src[j] === '+' || src[j] === '-') && /[eE]/.test(src[j - 1]) && !/^0[xX]/.test(src.slice(i, j)))))
108
+ j += 1;
109
+ push('number', i, j);
110
+ }
111
+ else if (isIdentStart(ch)) {
112
+ let j = i + 1;
113
+ while (j < n && isIdentPart(src[j]))
114
+ j += 1;
115
+ push('ident', i, j);
116
+ }
117
+ else if (ch === '/' && regexAllowed(tokens[tokens.length - 1])) {
118
+ let j = i + 1;
119
+ let inClass = false;
120
+ while (j < n && src[j] !== '\n') {
121
+ const c = src[j];
122
+ if (c === '\\')
123
+ j += 1;
124
+ else if (c === '[')
125
+ inClass = true;
126
+ else if (c === ']')
127
+ inClass = false;
128
+ else if (c === '/' && !inClass)
129
+ break;
130
+ j += 1;
131
+ }
132
+ j += 1;
133
+ while (j < n && isIdentPart(src[j]))
134
+ j += 1;
135
+ push('regex', i, Math.min(j, n));
136
+ }
137
+ else {
138
+ const punct = PUNCTUATORS.find((p) => src.startsWith(p, i)) ?? ch;
139
+ if (punct === '{')
140
+ depth += 1;
141
+ else if (punct === '}')
142
+ depth = Math.max(0, depth - 1);
143
+ push('punct', i, i + punct.length);
144
+ }
145
+ }
146
+ return tokens;
147
+ }
148
+ /** Every run of 5 consecutive tokens, as a string key (type-tagged, so the string "for" is not the keyword). */
149
+ export function shingles(tokens) {
150
+ const keys = tokens.map((t) => `${t.type === 'ident' || t.type === 'punct' ? '' : t.type[0]}${t.value}`);
151
+ const out = new Set();
152
+ for (let k = 0; k + SHINGLE_SIZE <= keys.length; k += 1)
153
+ out.add(keys.slice(k, k + SHINGLE_SIZE).join('\u0001'));
154
+ return out;
155
+ }
156
+ const KEYWORDS = new Set([
157
+ 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum',
158
+ 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'import', 'in', 'instanceof', 'new', 'null', 'return',
159
+ 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield', 'let', 'static',
160
+ 'implements', 'interface', 'package', 'private', 'protected', 'public', 'async', 'of', 'get', 'set', 'undefined',
161
+ 'arguments', 'module', 'exports', 'require',
162
+ ]);
163
+ /**
164
+ * R35: the same tokens with local names erased — every non-keyword identifier not preceded by `.` / `?.`
165
+ * (property names and globals reached through members stay) becomes `$id`, so renaming variables does not hide a
166
+ * copy. String and number literals are kept.
167
+ */
168
+ export function normalizeIdentifiers(tokens) {
169
+ return tokens.map((t, i) => {
170
+ if (t.type !== 'ident' || KEYWORDS.has(t.value))
171
+ return t;
172
+ const prev = tokens[i - 1];
173
+ if (prev !== undefined && prev.type === 'punct' && (prev.value === '.' || prev.value === '?.'))
174
+ return t;
175
+ return { ...t, value: '$id' };
176
+ });
177
+ }
@@ -0,0 +1,189 @@
1
+ // Anti-cheat checks run by `gate` on every replacement file: the replacement must not load the original (or any
2
+ // package), must not be a copy of the original source and must not hardcode the recorded outputs in bulk.
3
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
4
+ import { isBuiltin } from 'node:module';
5
+ import { extname, join, relative, sep } from 'node:path';
6
+ import { scanWithRegex, scanWithTs, stateReferences } from './anticheat/imports.js';
7
+ import { collectConstants } from './anticheat/constants.js';
8
+ import { normalizeIdentifiers, shingles, tokenize } from './anticheat/tokens.js';
9
+ import { isDeniedBuiltin } from './runtime/lockdown.js';
10
+ const ORIGINAL_EXTENSIONS = new Set(['.js', '.cjs', '.mjs']);
11
+ const TS_FILE = /\.[cm]?tsx?$/i;
12
+ const MIN_SHINGLES = 30;
13
+ const COPY_RATIO = 0.6;
14
+ /**
15
+ * R44: only long string outputs are evidence. Short strings and numbers are what data-table packages legitimately
16
+ * contain (ms: `HOUR = 3600000`; statuses: the message table is the package); the dynamic holdout check catches
17
+ * lookup tables of those instead.
18
+ */
19
+ const MIN_OUTPUT_LENGTH = 8;
20
+ const MIN_EMBEDDED = 5;
21
+ const EMBEDDED_RATIO = 0.2;
22
+ const SHOWN_IDS = 5;
23
+ const percent = (ratio) => `${Math.round(ratio * 100)}%`;
24
+ function specifierProblem(spec, pkg, typeOnly) {
25
+ if (spec === pkg || spec.startsWith(`${pkg}/`)) {
26
+ const hint = isBuiltin(spec) && !spec.startsWith('node:') ? ` (for the Node builtin write "node:${spec}")` : '';
27
+ return `imports "${spec}", the package being replaced${hint}`;
28
+ }
29
+ if (typeOnly)
30
+ return null;
31
+ if (!isBuiltin(spec)) {
32
+ return `imports "${spec}": a replacement may import only Node builtins (node:*) and must be one self-contained file`;
33
+ }
34
+ const name = (spec.startsWith('node:') ? spec.slice('node:'.length) : spec).split('/')[0];
35
+ if (name === 'process')
36
+ return `suspicious capability: imports "${spec}" (use the global process through direct member access)`;
37
+ // The same builtins the replay child denies at runtime (R33/R34).
38
+ return isDeniedBuiltin(spec) ? `network or code-loading capability: imports "${spec}" (not on the replacement builtin allowlist)` : null;
39
+ }
40
+ /**
41
+ * `self-contained`: fails when the source loads anything but a Node builtin (`module.isBuiltin`: `fs` and `node:fs`
42
+ * both allowed), loads `pkg` or one of its subpaths, loads a non-literal specifier, mentions `.depkill` or
43
+ * `node_modules`, or uses a capability that runs or loads other code (child_process, vm, eval, process.binding, …).
44
+ * Uses the TypeScript AST when `opts.ts` is given (adding the regex scan when the parse has errors), else a
45
+ * conservative raw-text scan in which comments and strings count.
46
+ */
47
+ export function checkSelfContained(src, pkg, opts = {}) {
48
+ let findings;
49
+ let conservative = true;
50
+ if (opts.ts) {
51
+ const scanned = scanWithTs(opts.ts, src, opts.fileName ?? 'replacement.ts');
52
+ findings = scanned.parseErrors ? [...scanned.findings, ...scanWithRegex(src)] : scanned.findings;
53
+ conservative = scanned.parseErrors;
54
+ }
55
+ else {
56
+ findings = scanWithRegex(src);
57
+ }
58
+ findings = [...findings, ...stateReferences(src)];
59
+ const problems = new Map();
60
+ for (const f of findings) {
61
+ const text = f.problem ?? (f.specifier === undefined ? null : specifierProblem(f.specifier, pkg, f.typeOnly === true));
62
+ if (text !== null)
63
+ problems.set(`${f.line}\0${text}`, { line: f.line, text });
64
+ }
65
+ if (problems.size === 0)
66
+ return { name: 'self-contained', status: 'pass', detail: 'imports only Node builtins' };
67
+ const lines = [...problems.values()].sort((a, b) => a.line - b.line).map((p) => `line ${p.line}: ${p.text}`);
68
+ if (conservative) {
69
+ lines.push(opts.ts ? '(TypeScript could not parse this file, so comments and strings count: fix the syntax or remove the text)'
70
+ : '(typescript is not installed, so comments and strings count: remove the text or install typescript)');
71
+ }
72
+ return { name: 'self-contained', status: 'fail', detail: lines.join('\n') };
73
+ }
74
+ /** `.js/.cjs/.mjs` files under `dir`, recursively (symlinks not followed). */
75
+ function originalFiles(dir) {
76
+ const out = [];
77
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
78
+ const full = join(dir, entry.name);
79
+ if (entry.isDirectory())
80
+ out.push(...originalFiles(full));
81
+ else if (entry.isFile() && ORIGINAL_EXTENSIONS.has(extname(entry.name).toLowerCase()))
82
+ out.push(full);
83
+ }
84
+ return out.sort();
85
+ }
86
+ /** The source as written, plus (for TypeScript files) the same code with types stripped. */
87
+ function comparableSources(src, opts) {
88
+ if (!opts.ts || opts.fileName === undefined || !TS_FILE.test(opts.fileName))
89
+ return [src];
90
+ try {
91
+ const { outputText } = opts.ts.transpileModule(src, {
92
+ fileName: opts.fileName,
93
+ compilerOptions: { module: opts.ts.ModuleKind.ESNext, target: opts.ts.ScriptTarget.ESNext, removeComments: true },
94
+ });
95
+ return [src, outputText];
96
+ }
97
+ catch {
98
+ return [src];
99
+ }
100
+ }
101
+ /**
102
+ * `not-copied`: tokenizes the source and every original file (`originalDir`, recursively; comments and whitespace
103
+ * dropped) into 5-token shingles. Fails when the source has ≥ 30 shingles and ≥ 60% of them occur in the original
104
+ * (union of all files), or when it contains ≥ 60% of the shingles of any single original file with ≥ 30 shingles
105
+ * (a copy padded with unrelated code). Both rules run on raw tokens and on identifier-normalized tokens (R35:
106
+ * renamed locals). TypeScript sources are also compared with their types stripped.
107
+ */
108
+ export function checkNotCopied(src, originalDir, opts = {}) {
109
+ const name = 'not-copied';
110
+ if (!existsSync(originalDir) || !statSync(originalDir).isDirectory()) {
111
+ return { name, status: 'fail', detail: `no snapshot of the original source in ${originalDir}: re-run depkill record` };
112
+ }
113
+ const originals = originalFiles(originalDir).map((file) => ({
114
+ file: relative(originalDir, file).split(sep).join('/'),
115
+ tokens: tokenize(readFileSync(file, 'utf8')),
116
+ }));
117
+ let worst = 0;
118
+ let largest = 0;
119
+ // Raw tokens, then identifier-normalized tokens (R35): the worst of both decides.
120
+ for (const view of [{ label: '', map: (t) => t }, { label: ' (with local names normalized)', map: normalizeIdentifiers }]) {
121
+ const theirs = originals.map((o) => ({ file: o.file, shingles: shingles(view.map(o.tokens)) }));
122
+ const union = new Set(theirs.flatMap((o) => [...o.shingles]));
123
+ for (const source of comparableSources(src, opts)) {
124
+ const own = shingles(view.map(tokenize(source)));
125
+ largest = Math.max(largest, own.size);
126
+ if (own.size < MIN_SHINGLES)
127
+ continue;
128
+ const containment = [...own].filter((s) => union.has(s)).length / own.size;
129
+ worst = Math.max(worst, containment);
130
+ if (containment >= COPY_RATIO) {
131
+ return { name, status: 'fail', detail: `${percent(containment)} of its 5-token sequences appear in the original source${view.label}: write your own implementation instead of copying it` };
132
+ }
133
+ for (const original of theirs) {
134
+ if (original.shingles.size < MIN_SHINGLES)
135
+ continue;
136
+ const coverage = [...original.shingles].filter((s) => own.has(s)).length / original.shingles.size;
137
+ worst = Math.max(worst, coverage);
138
+ if (coverage >= COPY_RATIO) {
139
+ return { name, status: 'fail', detail: `contains ${percent(coverage)} of the original ${original.file}${view.label}: write your own implementation instead of copying it` };
140
+ }
141
+ }
142
+ }
143
+ }
144
+ if (largest < MIN_SHINGLES)
145
+ return { name, status: 'pass', detail: `too small to be a copy (${largest} 5-token sequences)` };
146
+ return { name, status: 'pass', detail: `${percent(worst)} overlap with the original source` };
147
+ }
148
+ /** Forms a recorded string can take inside source code: raw, and escaped as a "…" or '…' literal body. */
149
+ function literalForms(value) {
150
+ const json = JSON.stringify(value).slice(1, -1);
151
+ return [...new Set([value, json, json.replaceAll('\\"', '"').replaceAll("'", "\\'")])];
152
+ }
153
+ /**
154
+ * `no-embedded-outputs` (R42, relaxed by R44): distinct recorded string `return` values of ≥ 8 characters, matched
155
+ * against the source's constants (string literals with adjacent `+` pieces folded, templates), inside longer
156
+ * constants, or in the raw text. Fails when ≥ 5 of them and ≥ 20% appear — judged over all cases and over the
157
+ * real-usage (callsite + agent) cases alone, so a lookup table of the real outputs cannot hide among many generated
158
+ * ones. Numbers are not judged (R44).
159
+ */
160
+ export function checkNoEmbeddedOutputs(src, cases, opts = {}) {
161
+ const name = 'no-embedded-outputs';
162
+ const constants = collectConstants(src, opts);
163
+ const strings = [...constants.strings];
164
+ const stringPresent = (value) => constants.strings.has(value)
165
+ || strings.some((s) => s.includes(value)) || literalForms(value).some((form) => src.includes(form));
166
+ const groups = [
167
+ { label: 'recorded', cases },
168
+ { label: 'real-usage', cases: cases.filter((c) => c.source !== 'generated') },
169
+ ];
170
+ for (const group of groups) {
171
+ const texts = new Map();
172
+ for (const c of group.cases) {
173
+ if (c.outcome.kind !== 'return')
174
+ continue;
175
+ const { value } = c.outcome;
176
+ if (typeof value === 'string' && value.length >= MIN_OUTPUT_LENGTH && !texts.has(value))
177
+ texts.set(value, c.id);
178
+ }
179
+ const present = [...texts].filter(([value]) => stringPresent(value));
180
+ if (present.length >= MIN_EMBEDDED && present.length / texts.size >= EMBEDDED_RATIO) {
181
+ const ids = present.slice(0, SHOWN_IDS).map(([, id]) => id).join(', ');
182
+ return {
183
+ name, status: 'fail',
184
+ detail: `${present.length} of ${texts.size} ${group.label} string return values appear as constants in the source (cases ${ids}${present.length > SHOWN_IDS ? ', …' : ''}): compute results instead of hardcoding recorded outputs`,
185
+ };
186
+ }
187
+ }
188
+ return { name, status: 'pass', detail: 'no recorded outputs embedded' };
189
+ }
@@ -0,0 +1,113 @@
1
+ const MINUS = '−';
2
+ const KB = 1024;
3
+ const MB = 1024 * KB;
4
+ const GB = 1024 * MB;
5
+ /** One decimal below 10, whole numbers from 10 (a value that rounds to 10.0 drops the decimal). */
6
+ function scaled(value, unit) {
7
+ const tenth = Math.round(value * 10) / 10;
8
+ return tenth < 10 ? `${tenth.toFixed(1)} ${unit}` : `${Math.round(value)} ${unit}`;
9
+ }
10
+ /** `500 B`, `1.5 KB`, `500 KB`, `1.5 MB`, `50 MB`, `3.0 GB` (1024-based). */
11
+ export function formatCardBytes(bytes) {
12
+ if (bytes < KB)
13
+ return `${bytes} B`;
14
+ if (bytes < MB)
15
+ return scaled(bytes / KB, 'KB');
16
+ if (bytes < GB)
17
+ return scaled(bytes / MB, 'MB');
18
+ return scaled(bytes / GB, 'GB');
19
+ }
20
+ function delta(before, after, format) {
21
+ const diff = after - before;
22
+ if (diff === 0)
23
+ return '±0';
24
+ return `${diff < 0 ? MINUS : '+'}${format(Math.abs(diff))}`;
25
+ }
26
+ function row(label, before, after, format = String) {
27
+ const [from, to] = [format(before), format(after)];
28
+ return { label, before: from, after: to, value: `${from} → ${to}`, delta: delta(before, after, format) };
29
+ }
30
+ const UNITS = [['GB', GB], ['MB', MB], ['KB', KB]];
31
+ /**
32
+ * A size row. When the change is smaller than the display step but rounding puts the two sizes on different steps
33
+ * (43.51 MB → 43.45 MB as "44 MB → 43 MB"), both get one more decimal in the larger size's unit.
34
+ */
35
+ function bytesRow(label, before, after) {
36
+ const plain = row(label, before, after, formatCardBytes);
37
+ const larger = Math.max(before, after);
38
+ const unit = UNITS.find(([, size]) => larger >= size);
39
+ if (plain.before === plain.after || unit === undefined)
40
+ return plain;
41
+ const [name, size] = unit;
42
+ const decimals = Math.round((larger / size) * 10) / 10 < 10 ? 1 : 0; // as scaled()
43
+ if (Math.abs(after - before) >= size / 10 ** decimals)
44
+ return plain;
45
+ const [from, to] = [before, after].map((n) => `${(n / size).toFixed(decimals + 1)} ${name}`);
46
+ return { ...plain, before: from, after: to, value: `${from} → ${to}` };
47
+ }
48
+ /** True when both maintainer counts were measured (the maintainers block is shown only then). */
49
+ export function maintainersMeasured(input) {
50
+ return input.before.maintainers !== null && input.after.maintainers !== null;
51
+ }
52
+ /** The card's stat blocks: packages, node_modules, install scripts and (when measured) maintainers you trust. */
53
+ export function statRows(input) {
54
+ const { before, after } = input;
55
+ return [
56
+ row('packages', before.packages, after.packages),
57
+ bytesRow('node_modules', before.bytes, after.bytes),
58
+ row('install scripts', before.installScripts, after.installScripts),
59
+ ...(maintainersMeasured(input) ? [row('maintainers you trust', before.maintainers, after.maintainers)] : []),
60
+ ];
61
+ }
62
+ /** The report's extra rows (production-only numbers). */
63
+ export function prodRows(input) {
64
+ const { before, after } = input;
65
+ return [row('production packages', before.prodPackages, after.prodPackages), bytesRow('production node_modules', before.prodBytes, after.prodBytes)];
66
+ }
67
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
68
+ export function headline(input) {
69
+ return `Removed ${plural(input.removed.length, 'dependency', 'dependencies')}`;
70
+ }
71
+ /**
72
+ * R36: `Proven by {real} real-usage cases + {generated} generated + {holdout} fresh holdout cases · gate passed`,
73
+ * then ` · {n} accepted mismatches` when any were accepted, ` · unsandboxed run` when any gate ran unsandboxed, and
74
+ * (R51) ` · tests skipped` / ` · holdout skipped` when any counted gate skipped that check.
75
+ */
76
+ export function evidenceLine(input) {
77
+ const realLabel = input.callsiteCases !== undefined && input.agentCases !== undefined
78
+ ? `${input.realCases} real-usage cases (${input.callsiteCases} call-site, ${input.agentCases} agent-written)`
79
+ : `${input.realCases} real-usage cases`;
80
+ const parts = [`Proven by ${realLabel} + ${input.generatedCases} generated + ${input.holdoutCases} fresh holdout cases`, 'gate passed'];
81
+ if (input.acceptedMismatches > 0)
82
+ parts.push(plural(input.acceptedMismatches, 'accepted mismatch', 'accepted mismatches'));
83
+ if (!input.sandboxed)
84
+ parts.push('unsandboxed run');
85
+ if (input.testsSkipped)
86
+ parts.push('tests skipped');
87
+ if (input.holdoutSkipped)
88
+ parts.push('holdout skipped');
89
+ if (input.typecheckSkipped)
90
+ parts.push('typecheck skipped');
91
+ return parts.join(' · ');
92
+ }
93
+ const SHOWN_UNGATED = 3;
94
+ /** R50: `Totals also include {k} removal(s) without a depkill gate: B, C` (3 names, then "and K more"), or null. */
95
+ export function ungatedCaveat(input) {
96
+ const names = input.ungatedRemovals;
97
+ if (names.length === 0)
98
+ return null;
99
+ const more = names.length - SHOWN_UNGATED;
100
+ const shown = `${names.slice(0, SHOWN_UNGATED).join(', ')}${more > 0 ? ` and ${more} more` : ''}`;
101
+ return `Totals also include ${plural(names.length, 'removal', 'removals')} without a depkill gate: ${shown}`;
102
+ }
103
+ /** I1: `Totals also include {k} dependency change(s) not made by depkill (upgrades/additions)`, or null. */
104
+ export function driftCaveat(input) {
105
+ const drift = input.drift ?? [];
106
+ if (drift.length === 0)
107
+ return null;
108
+ return `Totals also include ${plural(drift.length, 'dependency change', 'dependency changes')} not made by depkill (upgrades/additions)`;
109
+ }
110
+ /** `−23 deps` / `−1 dep`. */
111
+ export function badgeValue(removedCount) {
112
+ return `${MINUS}${removedCount} ${removedCount === 1 ? 'dep' : 'deps'}`;
113
+ }
@@ -0,0 +1,137 @@
1
+ // The shareable card (1200×675) and the README badge: self-contained SVG (no fonts, images, links or scripts),
2
+ // system font stack, every text XML-escaped and cut to fit.
3
+ import { truncate } from '../util/term.js';
4
+ import { badgeValue, driftCaveat, evidenceLine, headline, statRows, ungatedCaveat } from './format.js';
5
+ const WIDTH = 1200;
6
+ const HEIGHT = 675;
7
+ const PAD = 64;
8
+ const CONTENT = WIDTH - 2 * PAD;
9
+ const SANS = "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif";
10
+ const MONO = "ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace";
11
+ const COLORS = { bg: '#0d1117', panel: '#161b22', text: '#e6edf3', muted: '#8b949e', accent: '#ff7b72', good: '#3fb950', bad: '#f85149', warn: '#d29922' };
12
+ /** Average glyph width of the sans stack, in em; used to decide when a line needs squeezing. */
13
+ const EM_WIDTH = 0.52;
14
+ const MAX_PROJECT = 60;
15
+ const MAX_NAME = 26;
16
+ const MAX_VIA = 28;
17
+ const SHOWN_REMOVED = 6;
18
+ const ROWS_PER_COLUMN = 4;
19
+ // XML 1.0 forbids C0 controls other than tab, LF and CR, lone surrogates and U+FFFE/U+FFFF.
20
+ const INVALID_XML = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
21
+ const ENTITIES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' };
22
+ /** Text safe inside an element or a double-quoted attribute. */
23
+ export function escapeXml(text) {
24
+ return text.replace(INVALID_XML, '').replace(/[&<>"']/g, (ch) => ENTITIES[ch]);
25
+ }
26
+ function attrs(values) {
27
+ return Object.entries(values).filter(([, v]) => v !== undefined).map(([k, v]) => ` ${k}="${escapeXml(String(v))}"`).join('');
28
+ }
29
+ /** Squeezes a line that would overflow `maxWidth` (estimated) instead of letting it run off the card. */
30
+ function fit(chars, size, maxWidth) {
31
+ return chars * size * EM_WIDTH > maxWidth ? { textLength: maxWidth, lengthAdjust: 'spacingAndGlyphs' } : {};
32
+ }
33
+ /** `<text>` whose content is already escaped markup (escaped text and tspans). */
34
+ function text(values, content) {
35
+ return `<text${attrs(values)}>${content}</text>`;
36
+ }
37
+ const length = (s) => [...s].length;
38
+ function statBlock(row, x, y) {
39
+ const deltaColor = row.delta.startsWith('+') ? COLORS.bad : row.delta === '±0' ? COLORS.muted : COLORS.good;
40
+ const width = CONTENT / 2 - 24;
41
+ return [
42
+ text({ x, y, 'font-size': 18, fill: COLORS.muted, 'letter-spacing': 1 }, escapeXml(row.label)),
43
+ text({ x, y: y + 48, 'font-size': 40, 'font-weight': 700, fill: COLORS.text, ...fit(length(row.value) + length(row.delta) * 0.7 + 1, 40, width) }, `${escapeXml(row.value)}<tspan${attrs({ fill: deltaColor, 'font-size': 28, 'font-weight': 600 })}> ${escapeXml(row.delta)}</tspan>`),
44
+ ].join('');
45
+ }
46
+ /** Cuts the middle of a long package name (`@scope/lo…ng-name`): scoped names that share a scope stay distinguishable. */
47
+ function middle(name, max) {
48
+ const chars = [...name];
49
+ if (chars.length <= max)
50
+ return name;
51
+ const head = Math.floor((max - 1) * 0.4);
52
+ return `${chars.slice(0, head).join('')}…${chars.slice(chars.length - (max - 1 - head)).join('')}`;
53
+ }
54
+ function removedItem(item) {
55
+ const name = `• ${middle(item.name, MAX_NAME)}`;
56
+ if (item.stillInstalledVia === null)
57
+ return { content: escapeXml(name), chars: length(name) };
58
+ const via = `still via ${middle(item.stillInstalledVia, MAX_VIA)}`;
59
+ return { content: `${escapeXml(name)}<tspan${attrs({ dx: 10, fill: COLORS.muted })}>${escapeXml(via)}</tspan>`, chars: length(name) + 2 + length(via) };
60
+ }
61
+ function removedList(input, top) {
62
+ const shown = input.removed.slice(0, SHOWN_REMOVED).map(removedItem);
63
+ const more = input.removed.length - SHOWN_REMOVED;
64
+ const items = more > 0 ? [...shown, { content: escapeXml(`and ${more} more`), chars: 12 }] : shown;
65
+ const size = 20;
66
+ return items.map(({ content, chars }, i) => text({
67
+ x: PAD + Math.floor(i / ROWS_PER_COLUMN) * (CONTENT / 2), y: top + (i % ROWS_PER_COLUMN) * 26, 'font-size': size,
68
+ fill: i === SHOWN_REMOVED ? COLORS.muted : COLORS.text, ...fit(chars, size, CONTENT / 2 - 16),
69
+ }, content)).join('');
70
+ }
71
+ function combinedCaveat(input) {
72
+ const parts = [ungatedCaveat(input), driftCaveat(input)].filter((c) => c !== null);
73
+ return parts.length > 0 ? parts.join(' · ') : null;
74
+ }
75
+ /** Plain-text summary for screen readers (`<desc>`). */
76
+ function description(input, project) {
77
+ const stats = statRows(input).map((row) => `${row.label} ${row.value} (${row.delta})`).join('; ');
78
+ const shown = input.removed.slice(0, SHOWN_REMOVED).map((r) => (r.stillInstalledVia === null ? truncate(r.name, MAX_PROJECT)
79
+ : `${truncate(r.name, MAX_PROJECT)} (still via ${truncate(r.stillInstalledVia, MAX_PROJECT)})`));
80
+ const more = input.removed.length - SHOWN_REMOVED;
81
+ const removed = [...shown, ...(more > 0 ? [`and ${more} more`] : [])].join(', ');
82
+ const caveat = combinedCaveat(input);
83
+ return `${headline(input)} from ${project}: ${removed}. ${stats}.${caveat === null ? '' : ` ${caveat}.`} ${evidenceLine(input)}.`;
84
+ }
85
+ /**
86
+ * The card: "depkill", the headline, a stat block per measured number (before → after and the change), the removed
87
+ * packages (6 at most, then "and K more"), the un-gated removals / drift caveats (R50/I1), the evidence line (R36) and `npx depkill`. 1200×675, dark background.
88
+ */
89
+ export function renderCard(input) {
90
+ const project = truncate(input.projectName.replace(INVALID_XML, ''), MAX_PROJECT);
91
+ const rows = statRows(input);
92
+ const evidence = evidenceLine(input);
93
+ const statTop = 262;
94
+ const caveat = combinedCaveat(input);
95
+ return [
96
+ `<svg${attrs({ xmlns: 'http://www.w3.org/2000/svg', width: WIDTH, height: HEIGHT, viewBox: `0 0 ${WIDTH} ${HEIGHT}`, role: 'img', 'aria-labelledby': 'depkill-title depkill-desc', 'font-family': SANS })}>`,
97
+ `<title id="depkill-title">${escapeXml(`depkill: ${headline(input)} from ${project}`)}</title>`,
98
+ `<desc id="depkill-desc">${escapeXml(description(input, project))}</desc>`,
99
+ `<rect${attrs({ width: WIDTH, height: HEIGHT, fill: COLORS.bg })}/>`,
100
+ `<rect${attrs({ width: WIDTH, height: 6, fill: COLORS.good })}/>`,
101
+ `<rect${attrs({ x: PAD - 24, y: statTop - 40, width: CONTENT + 48, height: 226, rx: 16, fill: COLORS.panel })}/>`,
102
+ text({ x: PAD, y: 92, 'font-size': 30, 'font-weight': 700, fill: COLORS.accent }, 'depkill'),
103
+ text({ x: WIDTH - PAD, y: 92, 'text-anchor': 'end', 'font-size': 20, fill: COLORS.muted, 'font-family': MONO }, 'npx depkill'),
104
+ text({ x: PAD, y: 166, 'font-size': 56, 'font-weight': 700, fill: COLORS.text }, escapeXml(headline(input))),
105
+ text({ x: PAD, y: 204, 'font-size': 22, fill: COLORS.muted }, escapeXml(project)),
106
+ ...rows.map((row, i) => statBlock(row, PAD + (i % 2) * (CONTENT / 2), statTop + Math.floor(i / 2) * 104)),
107
+ // R50: un-gated removals are in the totals; said right under them.
108
+ ...(caveat === null ? [] : [text({ x: PAD, y: 478, 'font-size': 17, fill: COLORS.warn, ...fit(length(caveat), 17, CONTENT) }, escapeXml(caveat))]),
109
+ text({ x: PAD, y: 506, 'font-size': 16, fill: COLORS.muted, 'letter-spacing': 2 }, 'REMOVED'),
110
+ removedList(input, 532),
111
+ text({ x: PAD, y: 646, 'font-size': 17, fill: COLORS.muted, ...fit(length(evidence), 17, CONTENT) }, escapeXml(evidence)),
112
+ '</svg>',
113
+ '',
114
+ ].join('\n');
115
+ }
116
+ /** Shields-style flat badge: `depkill | −N deps`. */
117
+ export function renderBadge(removedCount) {
118
+ const label = 'depkill';
119
+ const value = badgeValue(removedCount);
120
+ const charWidth = 7;
121
+ const left = label.length * charWidth + 12;
122
+ const right = length(value) * charWidth + 12;
123
+ const total = left + right;
124
+ return [
125
+ `<svg${attrs({ xmlns: 'http://www.w3.org/2000/svg', width: total, height: 20, role: 'img', 'aria-label': `${label}: ${value}` })}>`,
126
+ `<title>${escapeXml(`${label}: ${value}`)}</title>`,
127
+ `<rect${attrs({ width: total, height: 20, rx: 3, fill: '#555' })}/>`,
128
+ `<rect${attrs({ x: left, width: right, height: 20, rx: 3, fill: '#2ea043' })}/>`,
129
+ `<rect${attrs({ x: left, width: 4, height: 20, fill: '#2ea043' })}/>`,
130
+ `<g${attrs({ fill: '#fff', 'text-anchor': 'middle', 'font-family': 'Verdana, Geneva, DejaVu Sans, sans-serif', 'font-size': 11 })}>`,
131
+ text({ x: left / 2, y: 14 }, escapeXml(label)),
132
+ text({ x: left + right / 2, y: 14 }, escapeXml(value)),
133
+ '</g>',
134
+ '</svg>',
135
+ '',
136
+ ].join('\n');
137
+ }