@adguard/dnr-converter 1.0.0-alpha.2
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 +476 -0
- package/dist/cli.cjs +58912 -0
- package/dist/constants.js +23 -0
- package/dist/declarative-rule/declarative-rule.js +15 -0
- package/dist/declarative-rule/header-info.js +12 -0
- package/dist/declarative-rule/modify-header-info.js +31 -0
- package/dist/declarative-rule/query-key-value.js +12 -0
- package/dist/declarative-rule/query-transform.js +12 -0
- package/dist/declarative-rule/redirect.js +14 -0
- package/dist/declarative-rule/rule-action.js +44 -0
- package/dist/declarative-rule/rule-condition.js +77 -0
- package/dist/declarative-rule/url-transform.js +30 -0
- package/dist/errors/conversion-errors/empty-domains-error.js +24 -0
- package/dist/errors/conversion-errors/empty-resources-error.js +24 -0
- package/dist/errors/conversion-errors/index.js +17 -0
- package/dist/errors/conversion-errors/invalid-declarative-rule-error.js +22 -0
- package/dist/errors/conversion-errors/unsupported-modifier-error.js +20 -0
- package/dist/errors/conversion-errors/unsupported-regexp-error.js +27 -0
- package/dist/errors/converter-options-errors/empty-or-negative-number-of-rules-error.js +18 -0
- package/dist/errors/converter-options-errors/index.js +15 -0
- package/dist/errors/converter-options-errors/negative-number-of-rules-error.js +18 -0
- package/dist/errors/converter-options-errors/resources-path-error.js +18 -0
- package/dist/errors/limitation-errors/index.js +17 -0
- package/dist/errors/limitation-errors/max-scanned-rules-error.js +20 -0
- package/dist/errors/limitation-errors/too-many-error.js +28 -0
- package/dist/errors/limitation-errors/too-many-regexp-rules-error.js +25 -0
- package/dist/errors/limitation-errors/too-many-rules-error.js +25 -0
- package/dist/errors/limitation-errors/too-many-unsafe-rules-error.js +25 -0
- package/dist/errors/unavailable-sources-errors/unavailable-filter-source-error.js +21 -0
- package/dist/errors/unavailable-sources-errors/unavailable-ruleset-source-error.js +21 -0
- package/dist/filter/filter.js +92 -0
- package/dist/filter-converter/filter-converter.js +385 -0
- package/dist/grouped-rules-converters/url-transform-converter.js +340 -0
- package/dist/index.js +30 -0
- package/dist/package.json.js +3 -0
- package/dist/re2-regexp/re2-validator.js +37 -0
- package/dist/re2-regexp/regex-validator-extension.js +30 -0
- package/dist/re2.wasm +0 -0
- package/dist/rule/option-names.js +65 -0
- package/dist/rule/rule-badfilter.js +81 -0
- package/dist/rule/rule-priority.js +88 -0
- package/dist/rule/rule-validator.js +455 -0
- package/dist/rule/rule.js +853 -0
- package/dist/rule/string-utils.js +49 -0
- package/dist/rule-converters/csp-converter.js +105 -0
- package/dist/rule-converters/regular-rule-converter.js +789 -0
- package/dist/rule-converters/remove-header-converter.js +97 -0
- package/dist/rule-converters/rules-converter.js +365 -0
- package/dist/rule-converters/rules-grouper.js +75 -0
- package/dist/rules-scanner/rules-scanner.js +136 -0
- package/dist/ruleset/metadata-rule.js +35 -0
- package/dist/ruleset/metadata-ruleset.js +162 -0
- package/dist/ruleset/rules-hash-map.js +71 -0
- package/dist/ruleset/ruleset-with-source-map.js +406 -0
- package/dist/ruleset/ruleset.js +54 -0
- package/dist/ruleset/source-map.js +283 -0
- package/dist/types/cli/convert-filters.d.ts +32 -0
- package/dist/types/cli/index.d.ts +7 -0
- package/dist/types/cli/utils.d.ts +19 -0
- package/dist/types/src/declarative-rule/declarative-rule.d.ts +32 -0
- package/dist/types/src/declarative-rule/header-info.d.ts +31 -0
- package/dist/types/src/declarative-rule/modify-header-info.d.ts +46 -0
- package/dist/types/src/declarative-rule/query-key-value.d.ts +24 -0
- package/dist/types/src/declarative-rule/query-transform.d.ts +21 -0
- package/dist/types/src/declarative-rule/redirect.d.ts +32 -0
- package/dist/types/src/declarative-rule/rule-action.d.ts +68 -0
- package/dist/types/src/declarative-rule/rule-condition.d.ts +262 -0
- package/dist/types/src/declarative-rule/url-transform.d.ts +69 -0
- package/dist/types/src/errors/conversion-errors/empty-domains-error.d.ts +21 -0
- package/dist/types/src/errors/conversion-errors/empty-resources-error.d.ts +21 -0
- package/dist/types/src/errors/conversion-errors/index.d.ts +27 -0
- package/dist/types/src/errors/conversion-errors/invalid-declarative-rule-error.d.ts +30 -0
- package/dist/types/src/errors/conversion-errors/unsupported-modifier-error.d.ts +20 -0
- package/dist/types/src/errors/conversion-errors/unsupported-regexp-error.d.ts +23 -0
- package/dist/types/src/errors/converter-options-errors/empty-or-negative-number-of-rules-error.d.ts +13 -0
- package/dist/types/src/errors/converter-options-errors/index.d.ts +23 -0
- package/dist/types/src/errors/converter-options-errors/negative-number-of-rules-error.d.ts +13 -0
- package/dist/types/src/errors/converter-options-errors/resources-path-error.d.ts +13 -0
- package/dist/types/src/errors/limitation-errors/index.d.ts +27 -0
- package/dist/types/src/errors/limitation-errors/max-scanned-rules-error.d.ts +18 -0
- package/dist/types/src/errors/limitation-errors/too-many-error.d.ts +33 -0
- package/dist/types/src/errors/limitation-errors/too-many-regexp-rules-error.d.ts +21 -0
- package/dist/types/src/errors/limitation-errors/too-many-rules-error.d.ts +21 -0
- package/dist/types/src/errors/limitation-errors/too-many-unsafe-rules-error.d.ts +21 -0
- package/dist/types/src/errors/unavailable-sources-errors/unavailable-filter-source-error.d.ts +19 -0
- package/dist/types/src/errors/unavailable-sources-errors/unavailable-ruleset-source-error.d.ts +19 -0
- package/dist/types/src/filter/filter.d.ts +74 -0
- package/dist/types/src/filter/types.d.ts +45 -0
- package/dist/types/src/filter-converter/conversion-result.d.ts +35 -0
- package/dist/types/src/filter-converter/filter-converter-options.d.ts +81 -0
- package/dist/types/src/filter-converter/filter-converter.d.ts +197 -0
- package/dist/types/src/index.d.ts +37 -0
- package/dist/types/src/rule/rule-types.d.ts +33 -0
- package/dist/types/src/rule/rule-validator.d.ts +185 -0
- package/dist/types/src/rule/rule.d.ts +269 -0
- package/dist/types/src/ruleset/metadata-ruleset.d.ts +128 -0
- package/dist/types/src/ruleset/rules-hash-map.d.ts +70 -0
- package/dist/types/src/ruleset/ruleset-with-source-map.d.ts +318 -0
- package/dist/types/src/ruleset/ruleset.d.ts +86 -0
- package/dist/types/src/ruleset/source-map.d.ts +45 -0
- package/dist/types/src/ruleset/types.d.ts +68 -0
- package/dist/types/src/utils/is-safe-rule.d.ts +20 -0
- package/dist/types/src/utils/ruleset-utils.d.ts +45 -0
- package/dist/types/src/version.d.ts +6 -0
- package/dist/url-transform-converter.js +338 -0
- package/dist/utils/error.js +22 -0
- package/dist/utils/is-safe-rule.js +25 -0
- package/dist/utils/lazy-loader.js +116 -0
- package/dist/utils/lazy.js +50 -0
- package/dist/utils/ruleset-utils.js +76 -0
- package/dist/utils/string.js +180 -0
- package/dist/utils/valibot.js +74 -0
- package/dist/version.js +7 -0
- package/package.json +122 -0
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import { splitByDelimiterWithEscapeCharacter } from './utils/string.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Keyword for Base64 decode transform.
|
|
5
|
+
*/ const B64_KEYWORD = 'b64';
|
|
6
|
+
/**
|
|
7
|
+
* Keyword for percent-decode transform.
|
|
8
|
+
*/ const PCT_KEYWORD = 'pct';
|
|
9
|
+
/**
|
|
10
|
+
* Parses a `/pattern/replacement/flags` string into its raw components.
|
|
11
|
+
* Uses the same delimiter-splitting logic as parseRegexSubstitution
|
|
12
|
+
* but returns raw strings rather than a compiled RegExp.
|
|
13
|
+
*
|
|
14
|
+
* @param value The raw substitution value (e.g. `/regex/repl/flags`).
|
|
15
|
+
*
|
|
16
|
+
* @returns Parsed parts.
|
|
17
|
+
*/ function parseUrlTransformParts(value) {
|
|
18
|
+
const parts = splitByDelimiterWithEscapeCharacter(value, '/', '\\', true, false);
|
|
19
|
+
return {
|
|
20
|
+
pattern: parts[0] || '',
|
|
21
|
+
replacement: parts[1] || '',
|
|
22
|
+
flags: parts[2] || ''
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Converts an AdGuard replacement string to DNR regexSubstitution format.
|
|
27
|
+
*
|
|
28
|
+
* - `$N` → `\\N` (shifted by offset).
|
|
29
|
+
* - `\$` → literal `$`.
|
|
30
|
+
*
|
|
31
|
+
* @param replacement The AdGuard replacement string.
|
|
32
|
+
* @param offset Number to add to each group reference (for path-only wrapping).
|
|
33
|
+
*
|
|
34
|
+
* @returns DNR-compatible regexSubstitution string.
|
|
35
|
+
*/ function convertReplacementToDnr(replacement, offset) {
|
|
36
|
+
let result = '';
|
|
37
|
+
let i = 0;
|
|
38
|
+
while(i < replacement.length){
|
|
39
|
+
const ch = replacement[i];
|
|
40
|
+
// Handle escaped dollar: \$N is a backreference (escaped for filter modifier syntax)
|
|
41
|
+
if (ch === '\\' && i + 1 < replacement.length && replacement[i + 1] === '$') {
|
|
42
|
+
if (i + 2 < replacement.length && replacement[i + 2] >= '0' && replacement[i + 2] <= '9') {
|
|
43
|
+
// \$N → \\N (backreference)
|
|
44
|
+
const groupNum = parseInt(replacement[i + 2], 10) + offset;
|
|
45
|
+
result += `\\${groupNum}`;
|
|
46
|
+
i += 3;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
// \$ not followed by digit → literal $
|
|
50
|
+
result += '$';
|
|
51
|
+
i += 2;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
// Handle unescaped $N group references.
|
|
55
|
+
// Only single-digit refs ($0–$9) are handled because DNR
|
|
56
|
+
// regexSubstitution only supports \\0–\\9.
|
|
57
|
+
if (ch === '$' && i + 1 < replacement.length) {
|
|
58
|
+
const nextCh = replacement[i + 1];
|
|
59
|
+
if (nextCh >= '0' && nextCh <= '9') {
|
|
60
|
+
const groupNum = parseInt(nextCh, 10) + offset;
|
|
61
|
+
result += `\\${groupNum}`;
|
|
62
|
+
i += 2;
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
result += ch;
|
|
67
|
+
i += 1;
|
|
68
|
+
}
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Prefix that identifies full-URL mode patterns.
|
|
73
|
+
*/ const FULL_URL_PATTERN_PREFIX = '^http';
|
|
74
|
+
/**
|
|
75
|
+
* Origin-capturing prefix for path-only transforms.
|
|
76
|
+
*/ const ORIGIN_PREFIX = '^(https?://[^/]+)';
|
|
77
|
+
/**
|
|
78
|
+
* Prefix for patterns that can match anywhere in the path.
|
|
79
|
+
* Uses a non-greedy match to capture everything before the pattern.
|
|
80
|
+
*/ const FLOATING_PREFIX = '^(https?://[^?#]*?)';
|
|
81
|
+
/**
|
|
82
|
+
* Origin-capturing prefix for query-targeting transforms.
|
|
83
|
+
*/ const ORIGIN_PREFIX_QUERY = '^(https?://[^?]+)';
|
|
84
|
+
/**
|
|
85
|
+
* Checks if a pattern is a full-URL mode pattern.
|
|
86
|
+
*
|
|
87
|
+
* @param pattern The regex pattern.
|
|
88
|
+
*
|
|
89
|
+
* @returns True if the pattern starts with `^http`.
|
|
90
|
+
*/ function isFullUrlPattern(pattern) {
|
|
91
|
+
return pattern.startsWith(FULL_URL_PATTERN_PREFIX);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Converts a full-URL $urltransform to DNR regexFilter + regexSubstitution.
|
|
95
|
+
*
|
|
96
|
+
* @param pattern The regex pattern (already unescaped from the rule).
|
|
97
|
+
* @param replacement The replacement template (AdGuard format).
|
|
98
|
+
* @param flags The flags string.
|
|
99
|
+
*
|
|
100
|
+
* @returns DNR conversion result.
|
|
101
|
+
*/ function convertFullUrlTransform(pattern, replacement, flags) {
|
|
102
|
+
// Unescape filter-syntax escapes in the pattern:
|
|
103
|
+
// - \/ → / (slash escaped to avoid conflicting with the
|
|
104
|
+
// /pattern/replacement/flags delimiter)
|
|
105
|
+
// - \$ → $ (dollar escaped because $ is the modifier separator
|
|
106
|
+
// in AdGuard syntax; in the regex it must act as the
|
|
107
|
+
// end-of-string anchor)
|
|
108
|
+
const unescapedPattern = pattern.replace(/\\\//g, '/').replace(/\\\$/g, '$');
|
|
109
|
+
let dnrReplacement = convertReplacementToDnr(replacement, 0);
|
|
110
|
+
dnrReplacement = dnrReplacement.replace(/\\\//g, '/');
|
|
111
|
+
return {
|
|
112
|
+
regexFilter: unescapedPattern,
|
|
113
|
+
regexSubstitution: dnrReplacement,
|
|
114
|
+
isUrlFilterCaseSensitive: flags.includes('i') ? false : undefined
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Counts the number of unescaped capturing groups in a regex pattern.
|
|
119
|
+
* Non-capturing groups (?:...) are excluded.
|
|
120
|
+
*
|
|
121
|
+
* @param pattern Regex pattern string.
|
|
122
|
+
*
|
|
123
|
+
* @returns Number of capturing groups.
|
|
124
|
+
*/ function countCaptureGroups(pattern) {
|
|
125
|
+
let count = 0;
|
|
126
|
+
let escaped = false;
|
|
127
|
+
let inCharClass = false;
|
|
128
|
+
for(let i = 0; i < pattern.length; i += 1){
|
|
129
|
+
const ch = pattern[i];
|
|
130
|
+
if (escaped) {
|
|
131
|
+
escaped = false;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (ch === '\\') {
|
|
135
|
+
escaped = true;
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (ch === '[') {
|
|
139
|
+
inCharClass = true;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (ch === ']') {
|
|
143
|
+
inCharClass = false;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (inCharClass) {
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (ch === '(' && i + 1 < pattern.length && pattern[i + 1] !== '?') {
|
|
150
|
+
count += 1;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return count;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Converts a path-only $urltransform to DNR format by wrapping the pattern
|
|
157
|
+
* with an origin-capturing prefix and shifting capture group references.
|
|
158
|
+
*
|
|
159
|
+
* @param pattern The regex pattern (path-only, not starting with `^http`).
|
|
160
|
+
* @param replacement The replacement template (AdGuard format).
|
|
161
|
+
* @param flags The flags string.
|
|
162
|
+
*
|
|
163
|
+
* @returns DNR conversion result.
|
|
164
|
+
*/ function convertPathOnlyTransform(pattern, replacement, flags) {
|
|
165
|
+
let workPattern = pattern;
|
|
166
|
+
// Strip leading ^ — the origin-capturing prefix already anchors
|
|
167
|
+
// the regex at the start of the URL.
|
|
168
|
+
if (workPattern.startsWith('^')) {
|
|
169
|
+
workPattern = workPattern.substring(1);
|
|
170
|
+
}
|
|
171
|
+
// Check for end-of-string anchor (\$ in filter syntax, which
|
|
172
|
+
// becomes $ in regex). When present, we must NOT append the
|
|
173
|
+
// remainder-capturing group (.*) after the pattern.
|
|
174
|
+
let hasEndAnchor = false;
|
|
175
|
+
if (workPattern.endsWith('\\$')) {
|
|
176
|
+
hasEndAnchor = true;
|
|
177
|
+
workPattern = workPattern.substring(0, workPattern.length - 2);
|
|
178
|
+
}
|
|
179
|
+
const userGroupCount = countCaptureGroups(workPattern);
|
|
180
|
+
// Determine if this is a query-targeting pattern
|
|
181
|
+
const isQueryPattern = workPattern.startsWith('\\?') || workPattern.startsWith('?');
|
|
182
|
+
// Determine if pattern is anchored to path start (starts with \/)
|
|
183
|
+
const isPathAnchored = !isQueryPattern && workPattern.startsWith('\\/');
|
|
184
|
+
// Choose prefix based on pattern type
|
|
185
|
+
let prefix;
|
|
186
|
+
if (isQueryPattern) {
|
|
187
|
+
prefix = ORIGIN_PREFIX_QUERY;
|
|
188
|
+
} else if (isPathAnchored) {
|
|
189
|
+
prefix = ORIGIN_PREFIX;
|
|
190
|
+
} else {
|
|
191
|
+
// Pattern can match anywhere in the path (floating match)
|
|
192
|
+
prefix = FLOATING_PREFIX;
|
|
193
|
+
}
|
|
194
|
+
// Remove leading escaped slash from path pattern for joining
|
|
195
|
+
let innerPattern = workPattern;
|
|
196
|
+
if (isPathAnchored) {
|
|
197
|
+
innerPattern = innerPattern.substring(2);
|
|
198
|
+
}
|
|
199
|
+
// Remove trailing escaped slash for clean joining
|
|
200
|
+
let trailingSlash = '/';
|
|
201
|
+
if (!isQueryPattern && innerPattern.endsWith('\\/')) {
|
|
202
|
+
innerPattern = innerPattern.substring(0, innerPattern.length - 2);
|
|
203
|
+
trailingSlash = '/';
|
|
204
|
+
} else if (!isQueryPattern) {
|
|
205
|
+
trailingSlash = '';
|
|
206
|
+
}
|
|
207
|
+
// Build wrapped regexFilter
|
|
208
|
+
const remainderGroup = hasEndAnchor ? '' : '(.*)';
|
|
209
|
+
const endAnchor = hasEndAnchor ? '$' : '';
|
|
210
|
+
let regexFilter;
|
|
211
|
+
if (isQueryPattern) {
|
|
212
|
+
regexFilter = `${prefix}${innerPattern}${remainderGroup}${endAnchor}`;
|
|
213
|
+
} else if (isPathAnchored) {
|
|
214
|
+
regexFilter = `${prefix}/${innerPattern}${trailingSlash}${remainderGroup}${endAnchor}`;
|
|
215
|
+
} else {
|
|
216
|
+
// Floating pattern: no extra slash between prefix and pattern
|
|
217
|
+
regexFilter = `${prefix}${innerPattern}${trailingSlash}${remainderGroup}${endAnchor}`;
|
|
218
|
+
}
|
|
219
|
+
// Unescape filter-syntax escapes in the assembled regex:
|
|
220
|
+
// - \/ → / (slash escaped for /pattern/replacement/flags delimiter)
|
|
221
|
+
// - \$ → $ (dollar escaped because $ is the modifier separator)
|
|
222
|
+
regexFilter = regexFilter.replace(/\\\//g, '/');
|
|
223
|
+
regexFilter = regexFilter.replace(/\\\$/g, '$');
|
|
224
|
+
// Build regexSubstitution: \\1 (origin) + converted replacement
|
|
225
|
+
// + optional \\(last) (remainder, only when no end anchor)
|
|
226
|
+
// Convert $N refs, shifting by 1 for the origin wrapper group
|
|
227
|
+
let dnrReplacement = convertReplacementToDnr(replacement, 1);
|
|
228
|
+
// Unescape \\/ in replacement to /
|
|
229
|
+
dnrReplacement = dnrReplacement.replace(/\\\//g, '/');
|
|
230
|
+
let regexSubstitution;
|
|
231
|
+
if (hasEndAnchor) {
|
|
232
|
+
// No remainder group — substitution is just origin + replacement
|
|
233
|
+
regexSubstitution = `\\1${dnrReplacement}`;
|
|
234
|
+
} else {
|
|
235
|
+
const remainderRef = `\\${userGroupCount + 2}`;
|
|
236
|
+
regexSubstitution = `\\1${dnrReplacement}${remainderRef}`;
|
|
237
|
+
}
|
|
238
|
+
return {
|
|
239
|
+
regexFilter,
|
|
240
|
+
regexSubstitution,
|
|
241
|
+
isUrlFilterCaseSensitive: flags.includes('i') ? false : undefined
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Splits a $urltransform value into pipeline segments by `|`.
|
|
246
|
+
*
|
|
247
|
+
* Handles `|` inside `/…/…/…/` substitution blocks correctly — those are
|
|
248
|
+
* regex alternation operators, not pipeline separators.
|
|
249
|
+
*
|
|
250
|
+
* NOTE: This is a self-contained copy of the logic from
|
|
251
|
+
* `src/modifiers/url-transform-modifier.ts`. Duplicated intentionally so
|
|
252
|
+
* the declarative converter stays independent for future package extraction.
|
|
253
|
+
*
|
|
254
|
+
* @param value The raw $urltransform modifier value.
|
|
255
|
+
*
|
|
256
|
+
* @returns Array of pipeline segment strings.
|
|
257
|
+
*/ function splitPipeline(value) {
|
|
258
|
+
const segments = [];
|
|
259
|
+
let current = '';
|
|
260
|
+
let slashCount = 0;
|
|
261
|
+
let inSubstitute = false;
|
|
262
|
+
let escaped = false;
|
|
263
|
+
for(let i = 0; i < value.length; i += 1){
|
|
264
|
+
const ch = value[i];
|
|
265
|
+
if (escaped) {
|
|
266
|
+
current += ch;
|
|
267
|
+
escaped = false;
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
if (ch === '\\') {
|
|
271
|
+
current += ch;
|
|
272
|
+
escaped = true;
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
if (ch === '|' && !inSubstitute) {
|
|
276
|
+
segments.push(current);
|
|
277
|
+
current = '';
|
|
278
|
+
slashCount = 0;
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
if (ch === '/') {
|
|
282
|
+
if (!inSubstitute && current.length === 0) {
|
|
283
|
+
inSubstitute = true;
|
|
284
|
+
slashCount = 0;
|
|
285
|
+
}
|
|
286
|
+
if (inSubstitute) {
|
|
287
|
+
slashCount += 1;
|
|
288
|
+
if (slashCount >= 3) {
|
|
289
|
+
inSubstitute = false;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
current += ch;
|
|
294
|
+
}
|
|
295
|
+
segments.push(current);
|
|
296
|
+
return segments;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Decode keywords that cannot be converted to DNR.
|
|
300
|
+
*/ const DECODE_KEYWORDS = new Set([
|
|
301
|
+
B64_KEYWORD,
|
|
302
|
+
PCT_KEYWORD
|
|
303
|
+
]);
|
|
304
|
+
/**
|
|
305
|
+
* Converts a complete $urltransform modifier value (possibly with pipeline)
|
|
306
|
+
* into one or more DNR conversion results.
|
|
307
|
+
*
|
|
308
|
+
* @param value The raw modifier value (e.g. `/pattern/repl/flags` or pipeline).
|
|
309
|
+
*
|
|
310
|
+
* @returns Array of DNR conversion results, one per pipeline stage.
|
|
311
|
+
*
|
|
312
|
+
* @throws Error if the value contains unsupported decode stages.
|
|
313
|
+
*/ function convertUrlTransformToDnr(value) {
|
|
314
|
+
const stages = splitPipeline(value);
|
|
315
|
+
// Check for decode keywords
|
|
316
|
+
for (const stage of stages){
|
|
317
|
+
const trimmed = stage.trim();
|
|
318
|
+
if (DECODE_KEYWORDS.has(trimmed)) {
|
|
319
|
+
throw new Error(`Decode stages (b64/pct) are not supported in DNR conversion: "${trimmed}"`);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
const results = [];
|
|
323
|
+
for (const stage of stages){
|
|
324
|
+
const trimmed = stage.trim();
|
|
325
|
+
if (trimmed.length === 0) {
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
const parts = parseUrlTransformParts(trimmed);
|
|
329
|
+
if (isFullUrlPattern(parts.pattern)) {
|
|
330
|
+
results.push(convertFullUrlTransform(parts.pattern, parts.replacement, parts.flags));
|
|
331
|
+
} else {
|
|
332
|
+
results.push(convertPathOnlyTransform(parts.pattern, parts.replacement, parts.flags));
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
return results;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export { convertFullUrlTransform, convertPathOnlyTransform, convertReplacementToDnr, convertUrlTransformToDnr, countCaptureGroups, isFullUrlPattern, parseUrlTransformParts };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { ValiError } from 'valibot';
|
|
2
|
+
import { getErrorMessage as getErrorMessage$1 } from '@adguard/logger';
|
|
3
|
+
import { extractMessageFromValiError } from './valibot.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Converts error object to error with message.
|
|
7
|
+
* This method might be helpful to handle thrown errors.
|
|
8
|
+
* If error is instance of {@link ValiError},
|
|
9
|
+
* it will prettify the error messages via {@link extractMessageFromValiError}.
|
|
10
|
+
*
|
|
11
|
+
* @param error Error object.
|
|
12
|
+
*
|
|
13
|
+
* @returns Message of the error.
|
|
14
|
+
*/ function getErrorMessage(error) {
|
|
15
|
+
// Special case: pretty print Valibot errors
|
|
16
|
+
if (error instanceof ValiError) {
|
|
17
|
+
return extractMessageFromValiError(error);
|
|
18
|
+
}
|
|
19
|
+
return getErrorMessage$1(error);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export { getErrorMessage };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { RuleActionType } from '../declarative-rule/rule-action.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* List of declarative rule actions which are considered safe.
|
|
5
|
+
*
|
|
6
|
+
* @see {@link https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest#safe_rules}
|
|
7
|
+
*/ const SAFE_RULE_ACTIONS = new Set([
|
|
8
|
+
RuleActionType.Block,
|
|
9
|
+
RuleActionType.Allow,
|
|
10
|
+
RuleActionType.AllowAllRequests,
|
|
11
|
+
RuleActionType.UpgradeScheme
|
|
12
|
+
]);
|
|
13
|
+
/**
|
|
14
|
+
* Checks whether the declarative rule is safe.
|
|
15
|
+
*
|
|
16
|
+
* @see {@link https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest#safe_rules}
|
|
17
|
+
*
|
|
18
|
+
* @param rule Declarative rule to check.
|
|
19
|
+
*
|
|
20
|
+
* @returns True if the rule is safe, otherwise false.
|
|
21
|
+
*/ function isSafeRule(rule) {
|
|
22
|
+
return SAFE_RULE_ACTIONS.has(rule.action.type);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export { isSafeRule };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Generic lazy-loader utility that wraps an async producer with result
|
|
3
|
+
* caching, in-flight-call coalescing, and safe unload-during-load handling.
|
|
4
|
+
*/ /**
|
|
5
|
+
* Wraps an async producer function and caches its result after the first
|
|
6
|
+
* successful call.
|
|
7
|
+
*
|
|
8
|
+
* Responsibilities:
|
|
9
|
+
* - **Caching** — after the producer resolves, subsequent {@link get} calls
|
|
10
|
+
* return the cached value synchronously (as a resolved promise) without
|
|
11
|
+
* invoking the producer again.
|
|
12
|
+
* - **Coalescing** — concurrent {@link get} calls made while a load is in
|
|
13
|
+
* flight share the same promise; the producer is invoked at most once per
|
|
14
|
+
* load cycle.
|
|
15
|
+
* - **Retry on failure** — if the producer rejects, the in-flight promise is
|
|
16
|
+
* cleared so the next {@link get} call re-invokes it.
|
|
17
|
+
* - **Safe reset during load** — {@link reset} called while a load is in
|
|
18
|
+
* flight defers clearing the cached value until the load settles, preventing
|
|
19
|
+
* a load from being silently overwritten or an infinite reset loop.
|
|
20
|
+
*
|
|
21
|
+
* @template T Type of the produced value. Use `void` for side-effect-only
|
|
22
|
+
* producers that populate external state.
|
|
23
|
+
*/ class LazyLoader {
|
|
24
|
+
/**
|
|
25
|
+
* Returns the cached value, awaiting the in-flight load or starting a new
|
|
26
|
+
* one as needed.
|
|
27
|
+
*
|
|
28
|
+
* @returns Promise resolving to the produced value.
|
|
29
|
+
*
|
|
30
|
+
* @throws Whatever the producer throws (not wrapped).
|
|
31
|
+
*/ async get() {
|
|
32
|
+
if (this.loaded) {
|
|
33
|
+
return this.value;
|
|
34
|
+
}
|
|
35
|
+
if (this.loadingPromise !== null) {
|
|
36
|
+
return this.loadingPromise;
|
|
37
|
+
}
|
|
38
|
+
// Assign the promise synchronously so concurrent callers coalesce onto it.
|
|
39
|
+
this.loadingPromise = (async ()=>{
|
|
40
|
+
try {
|
|
41
|
+
const v = await this.producer();
|
|
42
|
+
this.value = v;
|
|
43
|
+
this.loaded = true;
|
|
44
|
+
return v;
|
|
45
|
+
} finally{
|
|
46
|
+
// Must be cleared here (not only on error) — `reset()` checks
|
|
47
|
+
// `loadingPromise !== null` to detect an in-flight load and
|
|
48
|
+
// would enter an infinite .finally() scheduling loop if this
|
|
49
|
+
// field still held a resolved promise after the load completed.
|
|
50
|
+
this.loadingPromise = null;
|
|
51
|
+
}
|
|
52
|
+
})();
|
|
53
|
+
return this.loadingPromise;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Returns `true` if the value has been successfully loaded and not reset.
|
|
57
|
+
*
|
|
58
|
+
* @returns Whether the cached value is available.
|
|
59
|
+
*/ isLoaded() {
|
|
60
|
+
return this.loaded;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Returns `true` if a load is currently in flight.
|
|
64
|
+
*
|
|
65
|
+
* @returns Whether a producer call is pending.
|
|
66
|
+
*/ isLoading() {
|
|
67
|
+
return this.loadingPromise !== null;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Clears the cached value so the next {@link get} call re-invokes the
|
|
71
|
+
* producer. If a load is currently in flight, the reset is deferred until
|
|
72
|
+
* it settles to avoid overwriting fresh state with `null` or racing with
|
|
73
|
+
* callers waiting on the promise.
|
|
74
|
+
*
|
|
75
|
+
* Fire-and-forget is intentional here: the deferred reset runs as a
|
|
76
|
+
* microtask after the in-flight load settles and has no observable
|
|
77
|
+
* consumers beyond the cache state. Producer errors are silently
|
|
78
|
+
* swallowed because they are already surfaced to the caller of
|
|
79
|
+
* {@link get}.
|
|
80
|
+
*/ reset() {
|
|
81
|
+
if (this.loadingPromise !== null) {
|
|
82
|
+
// Defer reset until the in-flight load settles. The recursive
|
|
83
|
+
// `reset()` call then runs the clear branch below (or defers again
|
|
84
|
+
// if a new load has started in the meantime, which is also fine).
|
|
85
|
+
this.loadingPromise.finally(()=>{
|
|
86
|
+
this.reset();
|
|
87
|
+
}).catch(()=>{
|
|
88
|
+
// Empty on purpose. `.finally()` does not swallow rejections —
|
|
89
|
+
// it re-throws the producer error into this chain. Without
|
|
90
|
+
// `.catch()` that duplicate rejection would bubble up as an
|
|
91
|
+
// unhandled rejection, because nothing awaits this chain.
|
|
92
|
+
// The original error is still delivered to whoever awaited
|
|
93
|
+
// `get()`.
|
|
94
|
+
});
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
this.value = undefined;
|
|
98
|
+
this.loaded = false;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Constructs a new lazy loader.
|
|
102
|
+
*
|
|
103
|
+
* @param producer Async function that produces the value to cache.
|
|
104
|
+
*/ constructor(producer){
|
|
105
|
+
/**
|
|
106
|
+
* `true` once the producer has resolved at least once and the value has
|
|
107
|
+
* not been reset since.
|
|
108
|
+
*/ this.loaded = false;
|
|
109
|
+
/**
|
|
110
|
+
* In-flight producer promise; `null` when no load is in progress.
|
|
111
|
+
*/ this.loadingPromise = null;
|
|
112
|
+
this.producer = producer;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export { LazyLoader };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Generic synchronous lazy-initialisation utility that wraps a producer
|
|
3
|
+
* function and caches its result after the first call to {@link Lazy.get}.
|
|
4
|
+
*/ /**
|
|
5
|
+
* Wraps a synchronous producer function and caches its result after the first
|
|
6
|
+
* successful {@link get} call.
|
|
7
|
+
*
|
|
8
|
+
* Responsibilities:
|
|
9
|
+
* - **Caching** — after the producer runs, subsequent {@link get} calls return
|
|
10
|
+
* the cached value without invoking the producer again.
|
|
11
|
+
* - **Falsy-safe** — caching is tracked by a separate `loaded` flag so that
|
|
12
|
+
* falsy produced values (`0`, `null`, `undefined`) are still cached.
|
|
13
|
+
*
|
|
14
|
+
* This is the synchronous counterpart of {@link LazyLoader}, intended for
|
|
15
|
+
* cheap synchronous producers where introducing promise machinery would be
|
|
16
|
+
* counterproductive.
|
|
17
|
+
*
|
|
18
|
+
* @template T Type of the produced value.
|
|
19
|
+
*/ class Lazy {
|
|
20
|
+
/**
|
|
21
|
+
* Returns the cached value, invoking the producer on the first call.
|
|
22
|
+
*
|
|
23
|
+
* @returns The produced (and cached) value.
|
|
24
|
+
*/ get() {
|
|
25
|
+
if (!this.loaded) {
|
|
26
|
+
this.value = this.producer();
|
|
27
|
+
this.loaded = true;
|
|
28
|
+
}
|
|
29
|
+
return this.value;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Returns `true` if the producer has run and the value is cached.
|
|
33
|
+
*
|
|
34
|
+
* @returns Whether the cached value is available.
|
|
35
|
+
*/ isLoaded() {
|
|
36
|
+
return this.loaded;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Constructs a new lazy wrapper.
|
|
40
|
+
*
|
|
41
|
+
* @param producer Function that produces the value to cache.
|
|
42
|
+
*/ constructor(producer){
|
|
43
|
+
/**
|
|
44
|
+
* `true` once the producer has run and the value has not been reset.
|
|
45
|
+
*/ this.loaded = false;
|
|
46
|
+
this.producer = producer;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export { Lazy };
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Utility functions for constructing and parsing rule set IDs and paths.
|
|
3
|
+
*/ /**
|
|
4
|
+
* Prefix used for ruleset names and IDs.
|
|
5
|
+
*/ const RULESET_NAME_PREFIX = 'ruleset_';
|
|
6
|
+
/**
|
|
7
|
+
* Extension for ruleset files.
|
|
8
|
+
*/ const RULESET_FILE_EXT = '.json';
|
|
9
|
+
/**
|
|
10
|
+
* Path separator (forward slash, browser-safe).
|
|
11
|
+
*/ const PATH_SEPARATOR = '/';
|
|
12
|
+
/**
|
|
13
|
+
* Regex that matches only numeric strings.
|
|
14
|
+
*/ const RE_NUMBER = /^\d+$/;
|
|
15
|
+
/**
|
|
16
|
+
* Ensures a rule set ID has the `ruleset_` prefix.
|
|
17
|
+
*
|
|
18
|
+
* @param rulesetId Rule set ID (number or string).
|
|
19
|
+
*
|
|
20
|
+
* @returns Rule set ID with the prefix.
|
|
21
|
+
*/ function getRulesetId(rulesetId) {
|
|
22
|
+
let id = String(rulesetId);
|
|
23
|
+
if (!id.startsWith(RULESET_NAME_PREFIX)) {
|
|
24
|
+
id = `${RULESET_NAME_PREFIX}${id}`;
|
|
25
|
+
}
|
|
26
|
+
return id;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Returns the file path for a rule set.
|
|
30
|
+
*
|
|
31
|
+
* Uses forward slashes as path separator (browser-safe).
|
|
32
|
+
*
|
|
33
|
+
* @param rulesetId Rule set ID (number or string).
|
|
34
|
+
* @param baseDir Optional base directory.
|
|
35
|
+
*
|
|
36
|
+
* @returns Path to the rule set JSON file.
|
|
37
|
+
*/ function getRulesetPath(rulesetId, baseDir) {
|
|
38
|
+
const idWithPrefix = getRulesetId(rulesetId);
|
|
39
|
+
const base = baseDir ? `${baseDir}${PATH_SEPARATOR}` : '';
|
|
40
|
+
return `${base}${idWithPrefix}${PATH_SEPARATOR}${idWithPrefix}${RULESET_FILE_EXT}`;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Extracts the numeric filter ID from a rule set ID or path.
|
|
44
|
+
*
|
|
45
|
+
* Accepted formats:
|
|
46
|
+
* - `ruleset_<id>`
|
|
47
|
+
* - `ruleset_<id>.json`
|
|
48
|
+
* - `<path>/ruleset_<id>.json`.
|
|
49
|
+
*
|
|
50
|
+
* @param rulesetId The rule set ID or path to parse.
|
|
51
|
+
*
|
|
52
|
+
* @returns The numeric filter ID, or `null` if it cannot be extracted.
|
|
53
|
+
*/ function extractRulesetId(rulesetId) {
|
|
54
|
+
let id = rulesetId;
|
|
55
|
+
// Extract the last path segment if the string contains '/'
|
|
56
|
+
const lastSlashIndex = id.lastIndexOf(PATH_SEPARATOR);
|
|
57
|
+
if (lastSlashIndex !== -1) {
|
|
58
|
+
id = id.slice(lastSlashIndex + PATH_SEPARATOR.length);
|
|
59
|
+
}
|
|
60
|
+
// Must start with the ruleset prefix
|
|
61
|
+
if (!id.startsWith(RULESET_NAME_PREFIX)) {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
id = id.slice(RULESET_NAME_PREFIX.length);
|
|
65
|
+
// Strip the .json extension if present
|
|
66
|
+
if (id.endsWith(RULESET_FILE_EXT)) {
|
|
67
|
+
id = id.slice(0, -RULESET_FILE_EXT.length);
|
|
68
|
+
}
|
|
69
|
+
// The remaining part must be a numeric string
|
|
70
|
+
if (!RE_NUMBER.test(id)) {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
return parseInt(id, 10);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export { RULESET_FILE_EXT, RULESET_NAME_PREFIX, extractRulesetId, getRulesetId, getRulesetPath };
|