prompt-compressor 1.0.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/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # prompt-compressor
2
+
3
+ > Rule-based prompt compression — reduce LLM token usage without a model, without an API, without sending data anywhere.
4
+
5
+ [![npm](https://img.shields.io/npm/v/prompt-compressor)](https://www.npmjs.com/package/prompt-compressor)
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install prompt-compressor
11
+ ```
12
+
13
+ ## Quick start
14
+
15
+ ```js
16
+ import { compress } from 'prompt-compressor';
17
+
18
+ const { output, stats } = compress(systemPrompt, 'low');
19
+
20
+ console.log(stats);
21
+ // { tokensBefore: 1200, tokensAfter: 820, saved: 380, reductionPct: 31 }
22
+ ```
23
+
24
+ ## Risk levels
25
+
26
+ Pick a level — every algorithm at or below that risk runs automatically.
27
+
28
+ | Level | What runs | Typical saving |
29
+ |---|---|---|
30
+ | `'none'` | Whitespace, unicode normalization, indentation | 5–15% |
31
+ | `'very-low'` | + Filler removal, phrase shortening, JSON/SQL minify | 15–30% |
32
+ | `'low'` | + Hedging removal, code comments, deduplication, stack trace truncation | 25–45% |
33
+ | `'medium'` | + Fuzzy dedup, TF-IDF, TextRank (may drop sentences) | 30–70% |
34
+
35
+ ```js
36
+ compress(text, 'none') // safest
37
+ compress(text, 'very-low')
38
+ compress(text, 'low') // recommended default
39
+ compress(text, 'medium') // most aggressive
40
+ ```
41
+
42
+ ## Custom options
43
+
44
+ Override specific algorithms or parameters:
45
+
46
+ ```js
47
+ const { output, stats } = compress(text, {
48
+ level: 'low', // base level
49
+
50
+ // enable something above your level
51
+ tfidf: true,
52
+ tfidfRatio: 0.7, // keep 70% of sentences
53
+
54
+ // disable something in your level
55
+ codeComments: false, // keep code comments intact
56
+ });
57
+ ```
58
+
59
+ ## In a MCP server
60
+
61
+ ```js
62
+ import { compress } from 'prompt-compressor';
63
+
64
+ // Before every Bedrock call:
65
+ const { output } = compress(systemPrompt, 'low');
66
+
67
+ const response = await bedrock.invokeModel({
68
+ body: JSON.stringify({ system: output, messages }),
69
+ ...
70
+ });
71
+ ```
72
+
73
+ ## Individual functions
74
+
75
+ All algorithms are exported individually:
76
+
77
+ ```js
78
+ import {
79
+ removeFiller,
80
+ tfidfCompress,
81
+ deduplicateLines,
82
+ fuzzyDeduplicate,
83
+ estimateTokens,
84
+ } from 'prompt-compressor';
85
+
86
+ const cleaned = removeFiller(text);
87
+ const compressed = tfidfCompress(cleaned, 0.7);
88
+ console.log(estimateTokens(compressed));
89
+ ```
90
+
91
+ ## Variable protection
92
+
93
+ Prompt variables are automatically detected and preserved — compression never breaks your templates.
94
+
95
+ Supported: `{{var}}`, `{var}`, `${var}`, `<tag>`, `[[var]]`, `%VAR%`
96
+
97
+ ```js
98
+ // This is safe:
99
+ compress("Please {{user_name}}, utilize this in order to process {context}", 'low');
100
+ // → "Please {{user_name}}, use this to process {context}"
101
+ // Variables untouched, filler compressed.
102
+ ```
103
+
104
+ ## Result shape
105
+
106
+ ```ts
107
+ {
108
+ output: string,
109
+ stats: {
110
+ tokensBefore: number,
111
+ tokensAfter: number,
112
+ saved: number,
113
+ reductionPct: number, // 0–100
114
+ }
115
+ }
116
+ ```
117
+
118
+ ## Algorithms reference
119
+
120
+ | Algorithm | Risk | What it does |
121
+ |---|---|---|
122
+ | `compressWhitespace` | none | Collapse spaces, tabs, excess blank lines |
123
+ | `normalizeUnicode` | none | Smart quotes, em-dash, zero-width chars |
124
+ | `cleanPunctuation` | none | `!!!` → `!`, `???` → `?` |
125
+ | `stripLicenseHeaders` | none | Remove copyright blocks from code |
126
+ | `normalizeIndentation` | none | 4-space → 2-space in code blocks |
127
+ | `removeFiller` | very-low | Remove "please note that", "e.g.", "i.e." clauses |
128
+ | `shortenPhrases` | very-low | "in order to" → "to", "utilize" → "use" (50+ rules) |
129
+ | `numberWordsToNumerals` | very-low | "twenty" → "20" |
130
+ | `normalizeDates` | very-low | "Monday, Dec 25th 2023" → "2023-12-25" |
131
+ | `minifyJSON` | very-low | Minify JSON code blocks |
132
+ | `minifySQL` | very-low | Remove SQL comments, collapse whitespace |
133
+ | `removeHedging` | low | Remove "perhaps", "it seems", "one might say" |
134
+ | `removeMetaCommentary` | low | Remove "Here is...", "I hope this helps" |
135
+ | `removeParentheticals` | low | Remove "(as mentioned above)", "(see below)" |
136
+ | `stripCodeComments` | low | Remove `//`, `/* */`, `#` comments |
137
+ | `stripDocstrings` | low | Remove Python/JSDoc documentation blocks |
138
+ | `removeNullJsonFields` | low | Strip null/empty fields from JSON |
139
+ | `stripBase64AndHex` | low | Replace long hashes with placeholders |
140
+ | `truncateStackTraces` | low | Keep 4 frames, replace rest with count |
141
+ | `deduplicateLines` | low | Remove duplicate lines |
142
+ | `deduplicateSentences` | low | Remove duplicate sentences |
143
+ | `fuzzyDeduplicate` | medium | Jaccard-based near-duplicate removal |
144
+ | `ngramDeduplicate` | medium | Bigram/trigram near-duplicate removal |
145
+ | `levenshteinDeduplicate` | medium | Edit-distance near-duplicate removal |
146
+ | `tfidfCompress` | medium | Keep top sentences by TF-IDF score |
147
+ | `textRankCompress` | medium | Keep top sentences by PageRank centrality |
148
+ | `extractiveCompress` | medium | Keep top sentences by Term Frequency |
149
+
150
+ ## License
151
+
152
+ MIT
package/index.d.ts ADDED
@@ -0,0 +1,93 @@
1
+ export type RiskLevel = 'none' | 'very-low' | 'low' | 'medium';
2
+
3
+ export interface CompressOptions {
4
+ level?: RiskLevel;
5
+ // structural
6
+ whitespace?: boolean;
7
+ unicode?: boolean;
8
+ punctuation?: boolean;
9
+ ansi?: boolean;
10
+ licenseHeaders?: boolean;
11
+ indentNormalize?: boolean;
12
+ // language
13
+ filler?: boolean;
14
+ phrases?: boolean;
15
+ numberWords?: boolean;
16
+ normalizeDates?: boolean;
17
+ hedging?: boolean;
18
+ meta?: boolean;
19
+ parentheticals?: boolean;
20
+ // code
21
+ codeComments?: boolean;
22
+ docstrings?: boolean;
23
+ jsonMinify?: boolean;
24
+ nullJsonFields?: boolean;
25
+ sqlMinify?: boolean;
26
+ base64Hex?: boolean;
27
+ stackTraces?: boolean;
28
+ // dedup
29
+ lineDedup?: boolean;
30
+ sentenceDedup?: boolean;
31
+ fuzzyDedup?: boolean;
32
+ fuzzyThreshold?: number;
33
+ ngram?: boolean;
34
+ ngramSize?: number;
35
+ ngramThreshold?: number;
36
+ levenshtein?: boolean;
37
+ levenshteinThreshold?: number;
38
+ // extractive
39
+ tfidf?: boolean;
40
+ tfidfRatio?: number;
41
+ textrank?: boolean;
42
+ textrankRatio?: number;
43
+ extractive?: boolean;
44
+ extractiveRatio?: number;
45
+ }
46
+
47
+ export interface CompressStats {
48
+ tokensBefore: number;
49
+ tokensAfter: number;
50
+ saved: number;
51
+ reductionPct: number;
52
+ }
53
+
54
+ export interface CompressResult {
55
+ output: string;
56
+ stats: CompressStats;
57
+ }
58
+
59
+ /** Compress a prompt using rule-based algorithms. No model, no API. */
60
+ export function compress(text: string, options?: RiskLevel | CompressOptions): CompressResult;
61
+
62
+ // Individual algorithm exports
63
+ export function compressWhitespace(text: string): string;
64
+ export function normalizeUnicode(text: string): string;
65
+ export function cleanPunctuation(text: string): string;
66
+ export function stripAnsiCodes(text: string): string;
67
+ export function removeFiller(text: string): string;
68
+ export function shortenPhrases(text: string): string;
69
+ export function numberWordsToNumerals(text: string): string;
70
+ export function normalizeDates(text: string): string;
71
+ export function removeHedging(text: string): string;
72
+ export function removeMetaCommentary(text: string): string;
73
+ export function removeParentheticals(text: string): string;
74
+ export function stripCodeComments(text: string): string;
75
+ export function stripDocstrings(text: string): string;
76
+ export function stripLicenseHeaders(text: string): string;
77
+ export function minifyJSON(text: string): string;
78
+ export function removeNullJsonFields(text: string): string;
79
+ export function minifySQL(text: string): string;
80
+ export function normalizeIndentation(text: string): string;
81
+ export function truncateStackTraces(text: string): string;
82
+ export function stripBase64AndHex(text: string): string;
83
+ export function deduplicateLines(text: string): string;
84
+ export function deduplicateSentences(text: string): string;
85
+ export function fuzzyDeduplicate(text: string, threshold?: number): string;
86
+ export function ngramDeduplicate(text: string, n?: number, threshold?: number): string;
87
+ export function levenshteinDeduplicate(text: string, threshold?: number): string;
88
+ export function extractiveCompress(text: string, ratio?: number): string;
89
+ export function tfidfCompress(text: string, ratio?: number): string;
90
+ export function textRankCompress(text: string, ratio?: number, damping?: number, iterations?: number): string;
91
+ export function estimateTokens(text: string): number;
92
+
93
+ export const LEVELS: Record<RiskLevel, string[]>;
package/index.js ADDED
@@ -0,0 +1,244 @@
1
+ /**
2
+ * prompt-compressor
3
+ *
4
+ * Rule-based prompt compression — no model, no API, nothing leaves your process.
5
+ *
6
+ * @example
7
+ * import { compress } from 'prompt-compressor';
8
+ *
9
+ * // Simple: pick a risk level
10
+ * const result = compress(text, 'low');
11
+ *
12
+ * // Custom: override specific algorithms
13
+ * const result = compress(text, { level: 'low', tfidf: true, tfidfRatio: 0.7 });
14
+ *
15
+ * console.log(result.output); // compressed text
16
+ * console.log(result.stats); // { tokensBefore, tokensAfter, saved, reductionPct }
17
+ */
18
+
19
+ import {
20
+ compressWhitespace, normalizeUnicode, cleanPunctuation, stripAnsiCodes,
21
+ removeFiller, shortenPhrases, numberWordsToNumerals, normalizeDates,
22
+ removeHedging, removeMetaCommentary, removeParentheticals,
23
+ stripCodeComments, stripDocstrings, stripLicenseHeaders,
24
+ minifyJSON, removeNullJsonFields, minifySQL, normalizeIndentation,
25
+ truncateStackTraces, stripBase64AndHex,
26
+ deduplicateLines, deduplicateSentences, fuzzyDeduplicate,
27
+ ngramDeduplicate, levenshteinDeduplicate,
28
+ extractiveCompress, tfidfCompress, textRankCompress,
29
+ } from './src/algorithms.js';
30
+
31
+ import { protectVariables, restoreVariables, estimateTokens } from './src/protect.js';
32
+
33
+ // ─── Risk level definitions ───────────────────────────────────
34
+
35
+ /**
36
+ * Steps grouped by risk level.
37
+ * 'none' → safe, deterministic, no semantic change
38
+ * 'low' → very safe, minimal chance of meaning change
39
+ * 'medium' → may drop content; verify output before using
40
+ */
41
+ export const LEVELS = {
42
+ none: [
43
+ 'whitespace', 'unicode', 'punctuation', 'licenseHeaders', 'indentNormalize',
44
+ ],
45
+ 'very-low': [
46
+ 'filler', 'phrases', 'numberWords', 'normalizeDates',
47
+ 'jsonMinify', 'sqlMinify',
48
+ ],
49
+ low: [
50
+ 'hedging', 'meta', 'parentheticals',
51
+ 'codeComments', 'docstrings', 'nullJsonFields',
52
+ 'base64Hex', 'stackTraces',
53
+ 'lineDedup', 'sentenceDedup',
54
+ ],
55
+ medium: [
56
+ 'fuzzyDedup', 'ngram', 'levenshtein',
57
+ 'tfidf', 'textrank', 'extractive',
58
+ ],
59
+ };
60
+
61
+ // Ordered from safest to riskiest for pipeline execution
62
+ const ALL_STEPS_ORDERED = [
63
+ ...LEVELS.none,
64
+ ...LEVELS['very-low'],
65
+ ...LEVELS.low,
66
+ ...LEVELS.medium,
67
+ ];
68
+
69
+ // Steps eligible for each level (cumulative)
70
+ function stepsForLevel(level) {
71
+ if (level === 'none') return [...LEVELS.none];
72
+ if (level === 'very-low') return [...LEVELS.none, ...LEVELS['very-low']];
73
+ if (level === 'low') return [...LEVELS.none, ...LEVELS['very-low'], ...LEVELS.low];
74
+ if (level === 'medium') return ALL_STEPS_ORDERED;
75
+ throw new Error(`Unknown level: "${level}". Use 'none', 'very-low', 'low', or 'medium'.`);
76
+ }
77
+
78
+ // ─── Default params ───────────────────────────────────────────
79
+ const DEFAULTS = {
80
+ extractiveRatio: 0.65,
81
+ tfidfRatio: 0.65,
82
+ textrankRatio: 0.65,
83
+ fuzzyThreshold: 0.75,
84
+ ngramSize: 2,
85
+ ngramThreshold: 0.6,
86
+ levenshteinThreshold: 0.15,
87
+ };
88
+
89
+ // ─── Algorithm runner ─────────────────────────────────────────
90
+ function runStep(key, text, opts) {
91
+ switch (key) {
92
+ case 'whitespace': return compressWhitespace(text);
93
+ case 'unicode': return normalizeUnicode(text);
94
+ case 'punctuation': return cleanPunctuation(text);
95
+ case 'ansi': return stripAnsiCodes(text);
96
+ case 'licenseHeaders': return stripLicenseHeaders(text);
97
+ case 'indentNormalize': return normalizeIndentation(text);
98
+ case 'filler': return removeFiller(text);
99
+ case 'phrases': return shortenPhrases(text);
100
+ case 'numberWords': return numberWordsToNumerals(text);
101
+ case 'normalizeDates': return normalizeDates(text);
102
+ case 'jsonMinify': return minifyJSON(text);
103
+ case 'sqlMinify': return minifySQL(text);
104
+ case 'hedging': return removeHedging(text);
105
+ case 'meta': return removeMetaCommentary(text);
106
+ case 'parentheticals': return removeParentheticals(text);
107
+ case 'codeComments': return stripCodeComments(text);
108
+ case 'docstrings': return stripDocstrings(text);
109
+ case 'nullJsonFields': return removeNullJsonFields(text);
110
+ case 'base64Hex': return stripBase64AndHex(text);
111
+ case 'stackTraces': return truncateStackTraces(text);
112
+ case 'lineDedup': return deduplicateLines(text);
113
+ case 'sentenceDedup': return deduplicateSentences(text);
114
+ case 'fuzzyDedup': return fuzzyDeduplicate(text, opts.fuzzyThreshold);
115
+ case 'ngram': return ngramDeduplicate(text, opts.ngramSize, opts.ngramThreshold);
116
+ case 'levenshtein': return levenshteinDeduplicate(text, opts.levenshteinThreshold);
117
+ case 'tfidf': return tfidfCompress(text, opts.tfidfRatio);
118
+ case 'textrank': return textRankCompress(text, opts.textrankRatio);
119
+ case 'extractive': return extractiveCompress(text, opts.extractiveRatio);
120
+ default: return text;
121
+ }
122
+ }
123
+
124
+ // ─── Main API ─────────────────────────────────────────────────
125
+
126
+ /**
127
+ * Compress a prompt using rule-based algorithms.
128
+ *
129
+ * @param {string} text - The prompt to compress
130
+ * @param {string | CompressOptions} options - Risk level or options object
131
+ * @returns {CompressResult}
132
+ *
133
+ * @example
134
+ * // Level shorthand
135
+ * compress(text, 'low')
136
+ *
137
+ * // With overrides
138
+ * compress(text, {
139
+ * level: 'low',
140
+ * tfidf: true, // enable a step not in 'low' level
141
+ * tfidfRatio: 0.7,
142
+ * sentenceDedup: false, // disable a step that is in 'low' level
143
+ * })
144
+ */
145
+ export function compress(text, options = 'low') {
146
+ if (!text || typeof text !== 'string') {
147
+ return { output: text ?? '', stats: { tokensBefore: 0, tokensAfter: 0, saved: 0, reductionPct: 0 } };
148
+ }
149
+
150
+ // Normalize options
151
+ const level = typeof options === 'string' ? options : (options.level ?? 'low');
152
+ const overrides = typeof options === 'object' ? options : {};
153
+ const opts = { ...DEFAULTS, ...overrides };
154
+
155
+ // Build active step list
156
+ const levelSteps = new Set(stepsForLevel(level));
157
+
158
+ // Apply per-step overrides: explicit true/false keys in options
159
+ for (const key of ALL_STEPS_ORDERED) {
160
+ if (key in overrides) {
161
+ if (overrides[key] === true) levelSteps.add(key);
162
+ if (overrides[key] === false) levelSteps.delete(key);
163
+ }
164
+ }
165
+
166
+ // Protect variables
167
+ const { protected: safe, map } = protectVariables(text);
168
+
169
+ // Run pipeline in order
170
+ let out = safe;
171
+ for (const step of ALL_STEPS_ORDERED) {
172
+ if (levelSteps.has(step)) {
173
+ out = runStep(step, out, opts);
174
+ }
175
+ }
176
+
177
+ // Final whitespace pass
178
+ out = compressWhitespace(out);
179
+
180
+ // Restore variables
181
+ out = restoreVariables(out, map);
182
+
183
+ // Stats
184
+ const tokensBefore = estimateTokens(text);
185
+ const tokensAfter = estimateTokens(out);
186
+ const saved = tokensBefore - tokensAfter;
187
+ const reductionPct = tokensBefore > 0 ? Math.round((saved / tokensBefore) * 100) : 0;
188
+
189
+ return {
190
+ output: out,
191
+ stats: { tokensBefore, tokensAfter, saved, reductionPct },
192
+ };
193
+ }
194
+
195
+ // ─── Named exports (power users) ─────────────────────────────
196
+ export {
197
+ // Structural
198
+ compressWhitespace, normalizeUnicode, cleanPunctuation, stripAnsiCodes,
199
+ // Language
200
+ removeFiller, shortenPhrases, numberWordsToNumerals, normalizeDates,
201
+ removeHedging, removeMetaCommentary, removeParentheticals,
202
+ // Code
203
+ stripCodeComments, stripDocstrings, stripLicenseHeaders,
204
+ minifyJSON, removeNullJsonFields, minifySQL,
205
+ normalizeIndentation, truncateStackTraces, stripBase64AndHex,
206
+ // Dedup
207
+ deduplicateLines, deduplicateSentences, fuzzyDeduplicate,
208
+ ngramDeduplicate, levenshteinDeduplicate,
209
+ // Extractive
210
+ extractiveCompress, tfidfCompress, textRankCompress,
211
+ // Utils
212
+ estimateTokens, protectVariables, restoreVariables,
213
+ };
214
+
215
+ /**
216
+ * @typedef {Object} CompressOptions
217
+ * @property {'none'|'very-low'|'low'|'medium'} [level='low'] - Base risk level
218
+ * @property {boolean} [whitespace] - Override whitespace cleanup
219
+ * @property {boolean} [filler] - Override filler removal
220
+ * @property {boolean} [phrases] - Override phrase shortening
221
+ * @property {boolean} [tfidf] - Override TF-IDF compression
222
+ * @property {number} [tfidfRatio] - TF-IDF keep ratio (0.3–0.9)
223
+ * @property {boolean} [textrank] - Override TextRank compression
224
+ * @property {number} [textrankRatio] - TextRank keep ratio
225
+ * @property {boolean} [extractive] - Override extractive compression
226
+ * @property {number} [extractiveRatio] - Extractive keep ratio
227
+ * @property {boolean} [fuzzyDedup] - Override fuzzy deduplication
228
+ * @property {number} [fuzzyThreshold] - Jaccard threshold (0–1)
229
+ * @property {boolean} [ngram] - Override n-gram deduplication
230
+ * @property {number} [ngramSize] - N-gram size (default 2)
231
+ * @property {number} [ngramThreshold] - N-gram similarity threshold
232
+ * @property {boolean} [levenshtein] - Override Levenshtein deduplication
233
+ * @property {number} [levenshteinThreshold] - Max edit distance ratio
234
+ */
235
+
236
+ /**
237
+ * @typedef {Object} CompressResult
238
+ * @property {string} output - Compressed text
239
+ * @property {Object} stats
240
+ * @property {number} stats.tokensBefore
241
+ * @property {number} stats.tokensAfter
242
+ * @property {number} stats.saved
243
+ * @property {number} stats.reductionPct
244
+ */
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "prompt-compressor",
3
+ "version": "1.0.0",
4
+ "description": "Rule-based prompt compression — reduce LLM token usage without a model, without an API, without sending data anywhere.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "module": "index.js",
8
+ "types": "index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./index.js",
12
+ "types": "./index.d.ts"
13
+ }
14
+ },
15
+ "files": ["index.js", "index.d.ts", "src/"],
16
+ "keywords": [
17
+ "prompt", "compression", "llm", "tokens", "bedrock", "openai", "anthropic",
18
+ "claude", "gpt", "langchain", "mcp", "rag", "nlp"
19
+ ],
20
+ "author": "Tom Ketter",
21
+ "license": "MIT",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "https://github.com/kettertom/prompt-compressor.git"
25
+ },
26
+ "homepage": "https://prompt-compressor.com",
27
+ "engines": { "node": ">=16" }
28
+ }
@@ -0,0 +1,542 @@
1
+ /**
2
+ * compression.js
3
+ * Pure compression functions — no dependencies, no model, no API.
4
+ * Each function: (string, ...params?) => string
5
+ */
6
+
7
+ // ════════════════════════════════════════════════════════════
8
+ // STRUCTURAL
9
+ // ════════════════════════════════════════════════════════════
10
+
11
+ /**
12
+ * Collapses excess whitespace, normalizes line endings, trims.
13
+ * @risk none | @savings 5–15%
14
+ */
15
+ export function compressWhitespace(text) {
16
+ return text
17
+ .replace(/\r\n/g, "\n").replace(/\r/g, "\n")
18
+ .replace(/\t/g, " ").replace(/[ \t]+/g, " ")
19
+ .replace(/\n{3,}/g, "\n\n")
20
+ .replace(/[ \t]+\n/g, "\n").replace(/\n[ \t]+/g, "\n")
21
+ .trim();
22
+ }
23
+
24
+ /**
25
+ * Normalizes Unicode: smart quotes → straight, em-dash → -, zero-width chars,
26
+ * HTML entities, fullwidth ASCII characters.
27
+ * @risk none | @savings 1–5%
28
+ */
29
+ export function normalizeUnicode(text) {
30
+ return text
31
+ .replace(/[\u2018\u2019]/g, "'").replace(/[\u201C\u201D]/g, '"')
32
+ .replace(/\u2014/g, " - ").replace(/\u2013/g, "-")
33
+ .replace(/\u2026/g, "...")
34
+ .replace(/[\u00A0\u202F\u2009\u200A]/g, " ")
35
+ .replace(/[\u200B\u200C\u200D\uFEFF\u00AD]/g, "")
36
+ .replace(/[\uFF01-\uFF5E]/g, c => String.fromCharCode(c.charCodeAt(0) - 0xFEE0))
37
+ .replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")
38
+ .replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&nbsp;/g, " ");
39
+ }
40
+
41
+ /**
42
+ * Collapses repeated punctuation: !!! → !, ??? → ?, ,, → ,
43
+ * @risk none | @savings 1–3%
44
+ */
45
+ export function cleanPunctuation(text) {
46
+ return text
47
+ .replace(/!{2,}/g, "!").replace(/\?{2,}/g, "?")
48
+ .replace(/\.{4,}/g, "...").replace(/,{2,}/g, ",")
49
+ .replace(/ {2,}/g, " ");
50
+ }
51
+
52
+ /**
53
+ * Removes ANSI terminal escape sequences (colors, styles).
54
+ * @risk none | @savings 1–10%
55
+ */
56
+ export function stripAnsiCodes(text) {
57
+ // eslint-disable-next-line no-control-regex
58
+ return text.replace(/\x1B\[[0-9;]*[mGKHF]/g, "");
59
+ }
60
+
61
+ // ════════════════════════════════════════════════════════════
62
+ // LANGUAGE
63
+ // ════════════════════════════════════════════════════════════
64
+
65
+ /**
66
+ * Removes filler phrases that add no information.
67
+ * Examples: "Please note that", "It is important to note", "e.g.", "i.e."
68
+ * @risk very-low | @savings 10–20%
69
+ */
70
+ export function removeFiller(text) {
71
+ const patterns = [
72
+ [/please note that\s[^.!?\n]+[.!?]/gi, ""],
73
+ [/it is important to note that\s[^.!?\n]+[.!?]/gi, ""],
74
+ [/it's important to note that\s[^.!?\n]+[.!?]/gi, ""],
75
+ [/for example[,:]?\s[^.!?\n]+[.!?]/gi, ""],
76
+ [/e\.g\.[,\s][^.!?\n]+[.!?]/gi, ""],
77
+ [/i\.e\.[,\s][^.!?\n]+[.!?]/gi, ""],
78
+ [/in other words[,:]?\s[^.!?\n]+[.!?]/gi, ""],
79
+ [/as mentioned (above|earlier|before)[,:]?\s[^.!?\n]+[.!?]/gi, ""],
80
+ [/note:\s[^.!?\n]+[.!?]/gi, ""],
81
+ [/\bkindly\b\s/gi, ""],
82
+ [/\bplease\s+be\s+advised\s+that\b/gi, ""],
83
+ [/\bfeel free to\b/gi, ""],
84
+ [/\bit goes without saying\b[^.!?\n]+[.!?]/gi, ""],
85
+ [/\bwhat this means is that\b\s*/gi, ""],
86
+ [/\bit should be noted that\b\s*/gi, ""],
87
+ ];
88
+ let out = text;
89
+ for (const [p, r] of patterns) out = out.replace(p, r);
90
+ return out.replace(/\s{2,}/g, " ").replace(/\n{3,}/g, "\n\n").trim();
91
+ }
92
+
93
+ /**
94
+ * Replaces verbose phrases with concise equivalents. 50+ rules.
95
+ * Examples: "in order to" → "to", "utilize" → "use", "furthermore" → "also"
96
+ * @risk very-low | @savings 5–15%
97
+ */
98
+ export function shortenPhrases(text) {
99
+ const map = [
100
+ [/\bin order to\b/gi, "to"], [/\bdue to the fact that\b/gi, "because"],
101
+ [/\bfor the purpose of\b/gi, "for"], [/\bin the event that\b/gi, "if"],
102
+ [/\bat this point in time\b/gi, "now"], [/\bat the present time\b/gi, "now"],
103
+ [/\bon a regular basis\b/gi, "regularly"], [/\bwith the exception of\b/gi, "except"],
104
+ [/\bwith regard to\b/gi, "regarding"], [/\bwith respect to\b/gi, "regarding"],
105
+ [/\bin spite of the fact that\b/gi, "although"],
106
+ [/\bhas the ability to\b/gi, "can"], [/\bis able to\b/gi, "can"],
107
+ [/\bwill be able to\b/gi, "will"], [/\ba large number of\b/gi, "many"],
108
+ [/\ba majority of\b/gi, "most"], [/\ba sufficient amount of\b/gi, "enough"],
109
+ [/\bat all times\b/gi, "always"], [/\bin close proximity to\b/gi, "near"],
110
+ [/\bprior to\b/gi, "before"], [/\bsubsequent to\b/gi, "after"],
111
+ [/\butilize\b/gi, "use"], [/\bdemonstrate\b/gi, "show"],
112
+ [/\bcommence\b/gi, "start"], [/\bterminate\b/gi, "end"],
113
+ [/\bpurchase\b/gi, "buy"], [/\bassist\b/gi, "help"],
114
+ [/\badditionally\b/gi, "also"], [/\bfurthermore\b/gi, "also"],
115
+ [/\bmoreover\b/gi, "also"], [/\bconsequently\b/gi, "so"],
116
+ [/\btherefore\b/gi, "so"], [/\bthus\b/gi, "so"],
117
+ [/\bin addition to\b/gi, "besides"], [/\bas well as\b/gi, "and"],
118
+ [/\buntil such time as\b/gi, "until"],
119
+ [/\bfor the reason that\b/gi, "because"],
120
+ ];
121
+ let out = text;
122
+ for (const [p, r] of map) out = out.replace(p, r);
123
+ return out;
124
+ }
125
+
126
+ /**
127
+ * Converts number words to digits. "twenty" → "20", "hundred" → "100"
128
+ * @risk very-low | @savings 2–5%
129
+ */
130
+ export function numberWordsToNumerals(text) {
131
+ const map = [
132
+ ["zero",0],["one",1],["two",2],["three",3],["four",4],["five",5],
133
+ ["six",6],["seven",7],["eight",8],["nine",9],["ten",10],["eleven",11],
134
+ ["twelve",12],["thirteen",13],["fourteen",14],["fifteen",15],
135
+ ["sixteen",16],["seventeen",17],["eighteen",18],["nineteen",19],
136
+ ["twenty",20],["thirty",30],["forty",40],["fifty",50],
137
+ ["sixty",60],["seventy",70],["eighty",80],["ninety",90],
138
+ ["hundred",100],["thousand",1000],["million",1000000],
139
+ ];
140
+ let out = text;
141
+ for (const [word, num] of map)
142
+ out = out.replace(new RegExp(`\\b${word}\\b`, "gi"), String(num));
143
+ return out;
144
+ }
145
+
146
+ /**
147
+ * Removes uncertain/hedging language: "perhaps", "it seems", "one might say"
148
+ * @risk low | @savings 3–10%
149
+ */
150
+ export function removeHedging(text) {
151
+ const patterns = [
152
+ [/\b(perhaps|maybe|possibly|arguably|presumably|apparently)\b\s*/gi, ""],
153
+ [/\bit seems (like|that)\b\s*/gi, ""],
154
+ [/\bit appears (that|to be)\b\s*/gi, ""],
155
+ [/\bone might (say|argue|think|suggest)\b[^.!?]*[.!?]/gi, ""],
156
+ [/\bit could be argued that\b\s*/gi, ""],
157
+ [/\bI would (suggest|recommend|advise) (that )?(you )?(consider )?/gi, ""],
158
+ ];
159
+ let out = text;
160
+ for (const [p, r] of patterns) out = out.replace(p, r);
161
+ return out.replace(/\s{2,}/g, " ").trim();
162
+ }
163
+
164
+ /**
165
+ * Removes meta-commentary openers and closers.
166
+ * Examples: "Here is a...", "I hope this helps", "I'd be happy to help"
167
+ * @risk low | @savings 5–15%
168
+ */
169
+ export function removeMetaCommentary(text) {
170
+ const patterns = [
171
+ [/^(sure[,!]?\s*|of course[,!]?\s*|absolutely[,!]?\s*|certainly[,!]?\s*)/gim, ""],
172
+ [/^(i('d| would) be happy to (help|assist)[^.!?\n]*[.!?]\s*)/gim, ""],
173
+ [/^(here('s| is) (a |an |the )?[^.!?\n]*[.!?:]\s*)/gim, ""],
174
+ [/^(the following (is|are|provides)[^.!?\n]*[.!?:]\s*)/gim, ""],
175
+ [/^(below (is|are)[^.!?\n]*[.!?:]\s*)/gim, ""],
176
+ [/(i hope (this|that) (helps?|is helpful)[^.!?\n]*[.!?]\s*)/gi, ""],
177
+ [/(please (let me know|don't hesitate to ask)[^.!?\n]*[.!?]\s*)/gi, ""],
178
+ [/(if you have (any )?(further )?(questions?)[^.!?\n]*[.!?]\s*)/gi, ""],
179
+ ];
180
+ let out = text;
181
+ for (const [p, r] of patterns) out = out.replace(p, r);
182
+ return out.replace(/\n{3,}/g, "\n\n").trim();
183
+ }
184
+
185
+ /**
186
+ * Removes parenthetical asides that add no information.
187
+ * Examples: "(as mentioned above)", "(see below)", "(i.e. X)"
188
+ * @risk low | @savings 2–5%
189
+ */
190
+ export function removeParentheticals(text) {
191
+ const patterns = [
192
+ /\(\s*as (mentioned|noted|described) (above|below|earlier|before)\s*\)/gi,
193
+ /\(\s*see (above|below)\s*\)/gi,
194
+ /\(\s*(emphasis mine|my emphasis)\s*\)/gi,
195
+ /\(\s*(i\.e\.|e\.g\.)[^)]{0,60}\)/gi,
196
+ ];
197
+ let out = text;
198
+ for (const p of patterns) out = out.replace(p, "");
199
+ return out.replace(/\s{2,}/g, " ").trim();
200
+ }
201
+
202
+ /**
203
+ * Normalizes dates to ISO format. "Monday, December 25th, 2023" → "2023-12-25"
204
+ * @risk very-low | @savings 2–6%
205
+ */
206
+ export function normalizeDates(text) {
207
+ const months = {
208
+ january:1,february:2,march:3,april:4,may:5,june:6,
209
+ july:7,august:8,september:9,october:10,november:11,december:12,
210
+ jan:1,feb:2,mar:3,apr:4,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12
211
+ };
212
+ let out = text;
213
+ out = out.replace(
214
+ /\b(january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|jun|jul|aug|sep|oct|nov|dec)\.?\s+(\d{1,2})(?:st|nd|rd|th)?,?\s+(20\d{2})\b/gi,
215
+ (_, m, d, y) => `${y}-${String(months[m.toLowerCase()]).padStart(2,"0")}-${String(d).padStart(2,"0")}`
216
+ );
217
+ out = out.replace(/\b(monday|tuesday|wednesday|thursday|friday|saturday|sunday),?\s+/gi, "");
218
+ return out;
219
+ }
220
+
221
+ // ════════════════════════════════════════════════════════════
222
+ // CODE
223
+ // ════════════════════════════════════════════════════════════
224
+
225
+ /**
226
+ * Removes single-line and block comments from code blocks in the prompt.
227
+ * Handles: // comments, block comments, and # comments
228
+ * @risk low | @savings 5–25%
229
+ */
230
+ export function stripCodeComments(text) {
231
+ let out = text.replace(/(?<!:)\/\/(?!\/)[^\n]*/g, "");
232
+ out = out.replace(/^(\s*)#(?!!)([^\n]*)/gm, "$1");
233
+ out = out.replace(/\/\*[\s\S]*?\*\//g, "");
234
+ return out.replace(/\n{3,}/g, "\n\n").trim();
235
+ }
236
+
237
+ /**
238
+ * Removes Python triple-quote and JSDoc documentation blocks.
239
+ * @risk low | @savings 5–20%
240
+ */
241
+ export function stripDocstrings(text) {
242
+ let out = text.replace(/"""[\s\S]*?"""/g, '""');
243
+ out = out.replace(/'''[\s\S]*?'''/g, "''");
244
+ out = out.replace(/\/\*\*[\s\S]*?\*\//g, "");
245
+ return out.replace(/\n{3,}/g, "\n\n").trim();
246
+ }
247
+
248
+ /**
249
+ * Removes copyright/license comment blocks at the top of code.
250
+ * @risk none | @savings 3–10%
251
+ */
252
+ export function stripLicenseHeaders(text) {
253
+ const patterns = [
254
+ /^\/\*\s*[\s\S]*?(MIT|Apache|GPL|BSD|Copyright|License)[^*]*\*\/\s*/im,
255
+ /^(#[^\n]*\n)*#[^\n]*(Copyright|License|MIT|Apache|GPL|BSD)[^\n]*\n(#[^\n]*\n)*/im,
256
+ /^\/\/[^\n]*(Copyright|©)[^\n]*\n/im,
257
+ ];
258
+ let out = text;
259
+ for (const p of patterns) out = out.replace(p, "");
260
+ return out.trim();
261
+ }
262
+
263
+ /**
264
+ * Minifies JSON code blocks — removes all whitespace inside JSON fences.
265
+ * @risk very-low | @savings 5–30%
266
+ */
267
+ export function minifyJSON(text) {
268
+ return text.replace(/```json\s*([\s\S]*?)```/gi, (_, json) => {
269
+ try { return "```json\n" + JSON.stringify(JSON.parse(json.trim())) + "\n```"; }
270
+ catch { return _; }
271
+ });
272
+ }
273
+
274
+ /**
275
+ * Removes null, empty-string, and empty-array fields from JSON blocks.
276
+ * @risk low | @savings 3–15%
277
+ */
278
+ export function removeNullJsonFields(text) {
279
+ return text.replace(/```json\s*([\s\S]*?)```/gi, (_, json) => {
280
+ try {
281
+ const cleaned = JSON.parse(JSON.stringify(JSON.parse(json.trim()), (k, v) => {
282
+ if (v === null || v === "" || (Array.isArray(v) && v.length === 0)) return undefined;
283
+ return v;
284
+ }));
285
+ return "```json\n" + JSON.stringify(cleaned, null, 2) + "\n```";
286
+ } catch { return _; }
287
+ });
288
+ }
289
+
290
+ /**
291
+ * Minifies SQL code blocks — removes comments, collapses whitespace.
292
+ * @risk very-low | @savings 5–25%
293
+ */
294
+ export function minifySQL(text) {
295
+ return text.replace(/```sql\s*([\s\S]*?)```/gi, (_, sql) => {
296
+ let out = sql.replace(/--[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "").replace(/\s+/g, " ").trim();
297
+ return "```sql\n" + out + "\n```";
298
+ });
299
+ }
300
+
301
+ /**
302
+ * Converts 4-space indentation to 2-space inside code blocks.
303
+ * @risk none | @savings 3–15%
304
+ */
305
+ export function normalizeIndentation(text) {
306
+ return text.replace(/```[\s\S]*?```/g, block =>
307
+ block.replace(/^( )+/gm, m => " ".repeat(m.length / 4))
308
+ );
309
+ }
310
+
311
+ /**
312
+ * Keeps first 4 lines of stack traces, replaces the rest with a count.
313
+ * @risk low | @savings 10–50%
314
+ */
315
+ export function truncateStackTraces(text) {
316
+ return text.replace(
317
+ /((?:Error|Exception|Traceback)[^\n]*\n)((?:\s+at [^\n]+\n|\s+File "[^"]+", line \d+[^\n]*\n|\s+[^\n]+\n){5,})/g,
318
+ (_, header, stack) => {
319
+ const lines = stack.split("\n").filter(Boolean);
320
+ const kept = lines.slice(0, 4).join("\n");
321
+ const remaining = lines.length - 4;
322
+ return header + kept + (remaining > 0 ? `\n ... (${remaining} more frames)\n` : "\n");
323
+ }
324
+ );
325
+ }
326
+
327
+ /**
328
+ * Replaces long base64 strings, hex hashes, and repeated UUIDs with placeholders.
329
+ * @risk low | @savings 5–60%
330
+ */
331
+ export function stripBase64AndHex(text) {
332
+ let out = text.replace(/[A-Za-z0-9+/]{100,}={0,2}/g, "[base64_data]");
333
+ out = out.replace(/\b[0-9a-fA-F]{40,}\b/g, "[hex_data]");
334
+ const uuids = out.match(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi) || [];
335
+ if (uuids.length > 3)
336
+ out = out.replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, "[uuid]");
337
+ return out;
338
+ }
339
+
340
+ // ════════════════════════════════════════════════════════════
341
+ // DEDUPLICATION
342
+ // ════════════════════════════════════════════════════════════
343
+
344
+ /**
345
+ * Removes duplicate lines (case-insensitive).
346
+ * Catches: "Return JSON only\nReturn JSON only\nReturn JSON only" → one line.
347
+ * @risk low | @savings 5–30%
348
+ */
349
+ export function deduplicateLines(text) {
350
+ const seen = new Set();
351
+ return text.split("\n").filter(line => {
352
+ const key = line.trim().toLowerCase();
353
+ if (key === "") return true;
354
+ if (seen.has(key)) return false;
355
+ seen.add(key); return true;
356
+ }).join("\n");
357
+ }
358
+
359
+ /**
360
+ * Removes repeated sentences (exact match, case-insensitive).
361
+ * @risk low | @savings 5–15%
362
+ */
363
+ export function deduplicateSentences(text) {
364
+ const sentences = text.split(/(?<=[.!?])\s+/);
365
+ const seen = new Set();
366
+ return sentences.filter(s => {
367
+ const key = s.toLowerCase().replace(/[^a-z0-9]/g, "");
368
+ if (key.length < 8 || !seen.has(key)) { seen.add(key); return true; }
369
+ return false;
370
+ }).join(" ").trim();
371
+ }
372
+
373
+ /**
374
+ * Removes near-duplicate sentences using Jaccard similarity on word sets.
375
+ * @param threshold - similarity threshold (0–1), default 0.75
376
+ * @risk medium | @savings 5–20%
377
+ */
378
+ export function fuzzyDeduplicate(text, threshold = 0.75) {
379
+ const sentences = text.split(/(?<=[.!?])\s+/).filter(s => s.trim().length > 20);
380
+ if (sentences.length < 4) return text;
381
+ function jaccard(a, b) {
382
+ const sa = new Set(a.toLowerCase().match(/\b\w{3,}\b/g) || []);
383
+ const sb = new Set(b.toLowerCase().match(/\b\w{3,}\b/g) || []);
384
+ const inter = [...sa].filter(w => sb.has(w)).length;
385
+ const union = new Set([...sa, ...sb]).size;
386
+ return union === 0 ? 0 : inter / union;
387
+ }
388
+ const kept = [];
389
+ for (const s of sentences) {
390
+ if (!kept.some(k => jaccard(k, s) >= threshold)) kept.push(s);
391
+ }
392
+ return kept.join(" ").trim();
393
+ }
394
+
395
+ /**
396
+ * Near-duplicate removal using bigram/trigram overlap.
397
+ * Better than Jaccard for paraphrases: "Return only JSON" vs "Only return JSON".
398
+ * @param n - gram size (default 2)
399
+ * @param threshold - similarity threshold (default 0.6)
400
+ * @risk medium | @savings 5–20%
401
+ */
402
+ export function ngramDeduplicate(text, n = 2, threshold = 0.6) {
403
+ const sentences = text.split(/(?<=[.!?])\s+/).filter(s => s.trim().length > 15);
404
+ if (sentences.length <= 2) return text;
405
+ function grams(s) {
406
+ const words = s.toLowerCase().match(/\b\w+\b/g) || [];
407
+ const gs = new Set();
408
+ for (let i = 0; i <= words.length - n; i++) gs.add(words.slice(i, i + n).join(" "));
409
+ return gs;
410
+ }
411
+ const gramSets = sentences.map(grams);
412
+ const kept = [];
413
+ for (let i = 0; i < sentences.length; i++) {
414
+ const isDup = kept.some((_, ki) => {
415
+ const a = gramSets[i], b = gramSets[kept[ki]];
416
+ const inter = [...a].filter(g => b.has(g)).length;
417
+ const union = new Set([...a, ...b]).size;
418
+ return union > 0 && inter / union >= threshold;
419
+ });
420
+ if (!isDup) kept.push(i);
421
+ }
422
+ return kept.map(i => sentences[i]).join(" ").trim();
423
+ }
424
+
425
+ /**
426
+ * Edit-distance deduplication. Catches "Return JSON only." vs "Return JSON only!"
427
+ * @param threshold - max normalized edit distance (default 0.15)
428
+ * @risk medium | @savings 3–15%
429
+ */
430
+ export function levenshteinDeduplicate(text, threshold = 0.15) {
431
+ function lev(a, b) {
432
+ const m = a.length, n = b.length;
433
+ if (Math.abs(m - n) > Math.max(m, n) * 0.4) return Math.max(m, n);
434
+ const dp = Array.from({ length: m + 1 }, (_, i) => [i]);
435
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
436
+ for (let i = 1; i <= m; i++)
437
+ for (let j = 1; j <= n; j++)
438
+ dp[i][j] = a[i-1] === b[j-1] ? dp[i-1][j-1] : 1 + Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]);
439
+ return dp[m][n];
440
+ }
441
+ const sentences = text.split(/(?<=[.!?])\s+/).filter(s => s.trim().length > 10);
442
+ if (sentences.length <= 2) return text;
443
+ const kept = [];
444
+ for (const s of sentences) {
445
+ if (!kept.some(k => lev(s.toLowerCase(), k.toLowerCase()) / Math.max(s.length, k.length) <= threshold))
446
+ kept.push(s);
447
+ }
448
+ return kept.join(" ").trim();
449
+ }
450
+
451
+ // ════════════════════════════════════════════════════════════
452
+ // ADVANCED (EXTRACTIVE)
453
+ // ════════════════════════════════════════════════════════════
454
+
455
+ /**
456
+ * Keeps top N% sentences scored by Term Frequency.
457
+ * @param ratio - fraction of sentences to keep (default 0.65)
458
+ * @risk medium | @savings 20–50%
459
+ */
460
+ export function extractiveCompress(text, ratio = 0.65) {
461
+ const sentences = text.split(/(?<=[.!?\n])\s+/).map(s => s.trim()).filter(s => s.length > 20);
462
+ if (sentences.length <= 3) return text;
463
+ const freq = {};
464
+ const allWords = text.toLowerCase().match(/\b\w{4,}\b/g) || [];
465
+ for (const w of allWords) freq[w] = (freq[w] || 0) + 1;
466
+ const scored = sentences.map((s, i) => {
467
+ const words = s.toLowerCase().match(/\b\w{4,}\b/g) || [];
468
+ const score = words.reduce((acc, w) => acc + (freq[w] || 0), 0) / (words.length || 1);
469
+ return { s, score, i };
470
+ });
471
+ const keepCount = Math.max(2, Math.round(sentences.length * ratio));
472
+ return scored.sort((a, b) => b.score - a.score).slice(0, keepCount)
473
+ .sort((a, b) => a.i - b.i).map(x => x.s).join(" ").trim();
474
+ }
475
+
476
+ /**
477
+ * TF-IDF sentence scoring — penalizes words common across all sentences.
478
+ * Better than pure TF for prompts with boilerplate patterns.
479
+ * @param ratio - fraction of sentences to keep (default 0.65)
480
+ * @risk medium | @savings 20–50%
481
+ */
482
+ export function tfidfCompress(text, ratio = 0.65) {
483
+ const sentences = text.split(/(?<=[.!?\n])\s+/).map(s => s.trim()).filter(s => s.length > 20);
484
+ if (sentences.length <= 3) return text;
485
+ const n = sentences.length;
486
+ const docFreq = {};
487
+ const sentWords = sentences.map(s => {
488
+ const words = s.toLowerCase().match(/\b\w{3,}\b/g) || [];
489
+ [...new Set(words)].forEach(w => { docFreq[w] = (docFreq[w] || 0) + 1; });
490
+ return words;
491
+ });
492
+ const scored = sentences.map((s, i) => {
493
+ const words = sentWords[i];
494
+ if (!words.length) return { s, score: 0, i };
495
+ const freq = {};
496
+ words.forEach(w => { freq[w] = (freq[w] || 0) + 1; });
497
+ const score = words.reduce((acc, w) => {
498
+ const tf = freq[w] / words.length;
499
+ const idf = Math.log((n + 1) / ((docFreq[w] || 0) + 1));
500
+ return acc + tf * idf;
501
+ }, 0) / words.length;
502
+ return { s, score, i };
503
+ });
504
+ const keepCount = Math.max(2, Math.round(n * ratio));
505
+ return scored.sort((a, b) => b.score - a.score).slice(0, keepCount)
506
+ .sort((a, b) => a.i - b.i).map(x => x.s).join(" ").trim();
507
+ }
508
+
509
+ /**
510
+ * TextRank — PageRank-style algorithm on sentence similarity graph.
511
+ * Sentences most "central" to the document survive.
512
+ * @param ratio - fraction of sentences to keep (default 0.65)
513
+ * @risk medium | @savings 20–50%
514
+ */
515
+ export function textRankCompress(text, ratio = 0.65, damping = 0.85, iterations = 20) {
516
+ const sentences = text.split(/(?<=[.!?\n])\s+/).map(s => s.trim()).filter(s => s.length > 15);
517
+ if (sentences.length <= 3) return text;
518
+ const n = sentences.length;
519
+ const sets = sentences.map(s => new Set((s.toLowerCase().match(/\b\w{3,}\b/g) || [])));
520
+ const sim = (i, j) => {
521
+ const a = sets[i], b = sets[j];
522
+ if (!a.size || !b.size) return 0;
523
+ const inter = [...a].filter(w => b.has(w)).length;
524
+ return inter / (Math.log(a.size + 1) + Math.log(b.size + 1));
525
+ };
526
+ const matrix = Array.from({ length: n }, (_, i) =>
527
+ Array.from({ length: n }, (__, j) => i === j ? 0 : sim(i, j))
528
+ );
529
+ const normalized = matrix.map(row => {
530
+ const sum = row.reduce((a, b) => a + b, 0);
531
+ return sum === 0 ? row.map(() => 1 / n) : row.map(v => v / sum);
532
+ });
533
+ let scores = Array(n).fill(1 / n);
534
+ for (let iter = 0; iter < iterations; iter++)
535
+ scores = scores.map((_, i) =>
536
+ (1 - damping) / n + damping * scores.reduce((acc, s, j) => acc + s * normalized[j][i], 0)
537
+ );
538
+ const keepCount = Math.max(2, Math.round(n * ratio));
539
+ return sentences.map((s, i) => ({ s, score: scores[i], i }))
540
+ .sort((a, b) => b.score - a.score).slice(0, keepCount)
541
+ .sort((a, b) => a.i - b.i).map(x => x.s).join(" ").trim();
542
+ }
package/src/protect.js ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * protect.js
3
+ * Detects and shields prompt variables before compression,
4
+ * then restores them exactly after.
5
+ *
6
+ * Supported formats:
7
+ * {{variable}} Handlebars / Jinja / LangChain
8
+ * {variable} Python f-strings / LangChain
9
+ * ${variable} JS template literals
10
+ * <variable> XML-style (protected from HTML stripping)
11
+ * [[variable]] Some frameworks
12
+ * %VARIABLE% Windows-style env vars
13
+ */
14
+
15
+ const VAR_PATTERNS = [
16
+ /\{\{[^{}]+\}\}/g,
17
+ /\$\{[^{}]+\}/g,
18
+ /\[\[[^\[\]]+\]\]/g,
19
+ /%[A-Z_][A-Z0-9_]*%/g,
20
+ /<[a-zA-Z_][a-zA-Z0-9_\-]*>/g,
21
+ /\{[a-zA-Z_][a-zA-Z0-9_\.]*\}/g,
22
+ ];
23
+
24
+ export function protectVariables(text) {
25
+ const map = {};
26
+ let counter = 0;
27
+ let result = text;
28
+ for (const pattern of VAR_PATTERNS) {
29
+ result = result.replace(new RegExp(pattern.source, "g"), match => {
30
+ const key = `\x00VAR${counter++}\x00`;
31
+ map[key] = match;
32
+ return key;
33
+ });
34
+ }
35
+ return { protected: result, map };
36
+ }
37
+
38
+ export function restoreVariables(text, map) {
39
+ let result = text;
40
+ for (const [key, original] of Object.entries(map))
41
+ result = result.split(key).join(original);
42
+ return result;
43
+ }
44
+
45
+ /**
46
+ * Estimates token count without a tokenizer.
47
+ * Approximation based on word length (~4 chars/token for GPT/Claude).
48
+ */
49
+ export function estimateTokens(text) {
50
+ if (!text) return 0;
51
+ const words = text.trim().split(/\s+/).filter(Boolean);
52
+ let tokens = 0;
53
+ for (const word of words) {
54
+ if (word.length <= 4) tokens += 1;
55
+ else if (word.length <= 8) tokens += 1.5;
56
+ else tokens += word.length / 4;
57
+ }
58
+ return Math.round(tokens);
59
+ }