@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.
Files changed (114) hide show
  1. package/README.md +476 -0
  2. package/dist/cli.cjs +58912 -0
  3. package/dist/constants.js +23 -0
  4. package/dist/declarative-rule/declarative-rule.js +15 -0
  5. package/dist/declarative-rule/header-info.js +12 -0
  6. package/dist/declarative-rule/modify-header-info.js +31 -0
  7. package/dist/declarative-rule/query-key-value.js +12 -0
  8. package/dist/declarative-rule/query-transform.js +12 -0
  9. package/dist/declarative-rule/redirect.js +14 -0
  10. package/dist/declarative-rule/rule-action.js +44 -0
  11. package/dist/declarative-rule/rule-condition.js +77 -0
  12. package/dist/declarative-rule/url-transform.js +30 -0
  13. package/dist/errors/conversion-errors/empty-domains-error.js +24 -0
  14. package/dist/errors/conversion-errors/empty-resources-error.js +24 -0
  15. package/dist/errors/conversion-errors/index.js +17 -0
  16. package/dist/errors/conversion-errors/invalid-declarative-rule-error.js +22 -0
  17. package/dist/errors/conversion-errors/unsupported-modifier-error.js +20 -0
  18. package/dist/errors/conversion-errors/unsupported-regexp-error.js +27 -0
  19. package/dist/errors/converter-options-errors/empty-or-negative-number-of-rules-error.js +18 -0
  20. package/dist/errors/converter-options-errors/index.js +15 -0
  21. package/dist/errors/converter-options-errors/negative-number-of-rules-error.js +18 -0
  22. package/dist/errors/converter-options-errors/resources-path-error.js +18 -0
  23. package/dist/errors/limitation-errors/index.js +17 -0
  24. package/dist/errors/limitation-errors/max-scanned-rules-error.js +20 -0
  25. package/dist/errors/limitation-errors/too-many-error.js +28 -0
  26. package/dist/errors/limitation-errors/too-many-regexp-rules-error.js +25 -0
  27. package/dist/errors/limitation-errors/too-many-rules-error.js +25 -0
  28. package/dist/errors/limitation-errors/too-many-unsafe-rules-error.js +25 -0
  29. package/dist/errors/unavailable-sources-errors/unavailable-filter-source-error.js +21 -0
  30. package/dist/errors/unavailable-sources-errors/unavailable-ruleset-source-error.js +21 -0
  31. package/dist/filter/filter.js +92 -0
  32. package/dist/filter-converter/filter-converter.js +385 -0
  33. package/dist/grouped-rules-converters/url-transform-converter.js +340 -0
  34. package/dist/index.js +30 -0
  35. package/dist/package.json.js +3 -0
  36. package/dist/re2-regexp/re2-validator.js +37 -0
  37. package/dist/re2-regexp/regex-validator-extension.js +30 -0
  38. package/dist/re2.wasm +0 -0
  39. package/dist/rule/option-names.js +65 -0
  40. package/dist/rule/rule-badfilter.js +81 -0
  41. package/dist/rule/rule-priority.js +88 -0
  42. package/dist/rule/rule-validator.js +455 -0
  43. package/dist/rule/rule.js +853 -0
  44. package/dist/rule/string-utils.js +49 -0
  45. package/dist/rule-converters/csp-converter.js +105 -0
  46. package/dist/rule-converters/regular-rule-converter.js +789 -0
  47. package/dist/rule-converters/remove-header-converter.js +97 -0
  48. package/dist/rule-converters/rules-converter.js +365 -0
  49. package/dist/rule-converters/rules-grouper.js +75 -0
  50. package/dist/rules-scanner/rules-scanner.js +136 -0
  51. package/dist/ruleset/metadata-rule.js +35 -0
  52. package/dist/ruleset/metadata-ruleset.js +162 -0
  53. package/dist/ruleset/rules-hash-map.js +71 -0
  54. package/dist/ruleset/ruleset-with-source-map.js +406 -0
  55. package/dist/ruleset/ruleset.js +54 -0
  56. package/dist/ruleset/source-map.js +283 -0
  57. package/dist/types/cli/convert-filters.d.ts +32 -0
  58. package/dist/types/cli/index.d.ts +7 -0
  59. package/dist/types/cli/utils.d.ts +19 -0
  60. package/dist/types/src/declarative-rule/declarative-rule.d.ts +32 -0
  61. package/dist/types/src/declarative-rule/header-info.d.ts +31 -0
  62. package/dist/types/src/declarative-rule/modify-header-info.d.ts +46 -0
  63. package/dist/types/src/declarative-rule/query-key-value.d.ts +24 -0
  64. package/dist/types/src/declarative-rule/query-transform.d.ts +21 -0
  65. package/dist/types/src/declarative-rule/redirect.d.ts +32 -0
  66. package/dist/types/src/declarative-rule/rule-action.d.ts +68 -0
  67. package/dist/types/src/declarative-rule/rule-condition.d.ts +262 -0
  68. package/dist/types/src/declarative-rule/url-transform.d.ts +69 -0
  69. package/dist/types/src/errors/conversion-errors/empty-domains-error.d.ts +21 -0
  70. package/dist/types/src/errors/conversion-errors/empty-resources-error.d.ts +21 -0
  71. package/dist/types/src/errors/conversion-errors/index.d.ts +27 -0
  72. package/dist/types/src/errors/conversion-errors/invalid-declarative-rule-error.d.ts +30 -0
  73. package/dist/types/src/errors/conversion-errors/unsupported-modifier-error.d.ts +20 -0
  74. package/dist/types/src/errors/conversion-errors/unsupported-regexp-error.d.ts +23 -0
  75. package/dist/types/src/errors/converter-options-errors/empty-or-negative-number-of-rules-error.d.ts +13 -0
  76. package/dist/types/src/errors/converter-options-errors/index.d.ts +23 -0
  77. package/dist/types/src/errors/converter-options-errors/negative-number-of-rules-error.d.ts +13 -0
  78. package/dist/types/src/errors/converter-options-errors/resources-path-error.d.ts +13 -0
  79. package/dist/types/src/errors/limitation-errors/index.d.ts +27 -0
  80. package/dist/types/src/errors/limitation-errors/max-scanned-rules-error.d.ts +18 -0
  81. package/dist/types/src/errors/limitation-errors/too-many-error.d.ts +33 -0
  82. package/dist/types/src/errors/limitation-errors/too-many-regexp-rules-error.d.ts +21 -0
  83. package/dist/types/src/errors/limitation-errors/too-many-rules-error.d.ts +21 -0
  84. package/dist/types/src/errors/limitation-errors/too-many-unsafe-rules-error.d.ts +21 -0
  85. package/dist/types/src/errors/unavailable-sources-errors/unavailable-filter-source-error.d.ts +19 -0
  86. package/dist/types/src/errors/unavailable-sources-errors/unavailable-ruleset-source-error.d.ts +19 -0
  87. package/dist/types/src/filter/filter.d.ts +74 -0
  88. package/dist/types/src/filter/types.d.ts +45 -0
  89. package/dist/types/src/filter-converter/conversion-result.d.ts +35 -0
  90. package/dist/types/src/filter-converter/filter-converter-options.d.ts +81 -0
  91. package/dist/types/src/filter-converter/filter-converter.d.ts +197 -0
  92. package/dist/types/src/index.d.ts +37 -0
  93. package/dist/types/src/rule/rule-types.d.ts +33 -0
  94. package/dist/types/src/rule/rule-validator.d.ts +185 -0
  95. package/dist/types/src/rule/rule.d.ts +269 -0
  96. package/dist/types/src/ruleset/metadata-ruleset.d.ts +128 -0
  97. package/dist/types/src/ruleset/rules-hash-map.d.ts +70 -0
  98. package/dist/types/src/ruleset/ruleset-with-source-map.d.ts +318 -0
  99. package/dist/types/src/ruleset/ruleset.d.ts +86 -0
  100. package/dist/types/src/ruleset/source-map.d.ts +45 -0
  101. package/dist/types/src/ruleset/types.d.ts +68 -0
  102. package/dist/types/src/utils/is-safe-rule.d.ts +20 -0
  103. package/dist/types/src/utils/ruleset-utils.d.ts +45 -0
  104. package/dist/types/src/version.d.ts +6 -0
  105. package/dist/url-transform-converter.js +338 -0
  106. package/dist/utils/error.js +22 -0
  107. package/dist/utils/is-safe-rule.js +25 -0
  108. package/dist/utils/lazy-loader.js +116 -0
  109. package/dist/utils/lazy.js +50 -0
  110. package/dist/utils/ruleset-utils.js +76 -0
  111. package/dist/utils/string.js +180 -0
  112. package/dist/utils/valibot.js +74 -0
  113. package/dist/version.js +7 -0
  114. package/package.json +122 -0
@@ -0,0 +1,340 @@
1
+ import { isConversionError } from '../errors/conversion-errors/index.js';
2
+ import { OPTION_NAMES } from '../rule/option-names.js';
3
+ import { RuleDeclarativeValidator } from '../rule/rule-validator.js';
4
+ import { RegularRuleConverter } from '../rule-converters/regular-rule-converter.js';
5
+ import { convertUrlTransformToDnr, parseUrlTransformParts, isFullUrlPattern } from '../url-transform-converter.js';
6
+ import { RuleActionType } from '../declarative-rule/rule-action.js';
7
+
8
+ /**
9
+ * Describes how to convert $urltransform rules.
10
+ *
11
+ * Overrides {@link RegularRuleConverter.convertRule} to apply
12
+ * urltransform-specific post-processing:
13
+ * - Replaces the urlFilter-based condition with a regexFilter from the
14
+ * DNR conversion result.
15
+ * - Preserves domain scope by extracting the domain from the original
16
+ * pattern and adding it to requestDomains.
17
+ * - Defaults full-URL (origin-changing) rules to GET-only when no
18
+ * explicit $method modifier is set.
19
+ * - Generates additional declarative rules for multi-stage pipelines.
20
+ */ class UrlTransformRulesConverter extends RegularRuleConverter {
21
+ /**
22
+ * Generates a unique ID for a rule using its text hash.
23
+ *
24
+ * @param rule The rule to generate an ID for.
25
+ * @param usedIds Set of already-used IDs to avoid collisions.
26
+ *
27
+ * @returns A unique ID.
28
+ */ static getUniqueId(rule, usedIds) {
29
+ let id = rule.getTextHash();
30
+ let salt = 0;
31
+ while(usedIds.has(id)){
32
+ salt += 1;
33
+ id = rule.getTextHash(salt);
34
+ }
35
+ usedIds.add(id);
36
+ return id;
37
+ }
38
+ /**
39
+ * Wraps an error into a {@link ConversionError} if needed.
40
+ *
41
+ * @param index The rule index.
42
+ * @param id The rule ID.
43
+ * @param error The caught error.
44
+ *
45
+ * @returns The wrapped error.
46
+ */ static wrapError(index, id, error) {
47
+ if (isConversionError(error)) {
48
+ return error;
49
+ }
50
+ if (error instanceof Error) {
51
+ return error;
52
+ }
53
+ return new Error(`Error converting rule at index ${index}`);
54
+ }
55
+ /**
56
+ * Converts rules grouped by $urltransform into declarative rules.
57
+ *
58
+ * Overrides the parent to handle multi-stage pipelines:
59
+ * for each $urltransform rule, the base conversion produces one
60
+ * declarative rule, and additional pipeline stages generate
61
+ * extra rules with sequential IDs and their own source map entries.
62
+ *
63
+ * @param filterId Filter id.
64
+ * @param rules List of rules.
65
+ * @param usedIds Set with already used IDs to exclude duplications in IDs.
66
+ *
67
+ * @returns Converted rules.
68
+ */ async convert(filterId, rules, usedIds) {
69
+ const res = {
70
+ declarativeRules: [],
71
+ errors: [],
72
+ sourceMapValues: []
73
+ };
74
+ for (const rule of rules){
75
+ const { index } = rule;
76
+ const baseId = UrlTransformRulesConverter.getUniqueId(rule, usedIds);
77
+ try {
78
+ // Validate rule can be converted to DNR format
79
+ if (!RuleDeclarativeValidator.shouldConvertRule(rule)) {
80
+ continue;
81
+ }
82
+ const urlTransformValue = rule.advancedModifierValue;
83
+ const isUrlTransform = !rule.allowlist && !!urlTransformValue && rule.isModifierEnabled(OPTION_NAMES.URLTRANSFORM);
84
+ let dnrResults = null;
85
+ if (isUrlTransform) {
86
+ dnrResults = convertUrlTransformToDnr(urlTransformValue);
87
+ }
88
+ // Perform generic conversion (action, condition, priority, validation).
89
+ // eslint-disable-next-line no-await-in-loop
90
+ const baseRule = await super.convertRule(baseId, rule);
91
+ // Skip urltransform post-processing for allowlist rules or when no DNR results
92
+ if (!isUrlTransform || !dnrResults || dnrResults.length === 0) {
93
+ res.sourceMapValues.push({
94
+ declarativeRuleId: baseRule.id,
95
+ sourceRuleIndex: index,
96
+ filterId
97
+ });
98
+ res.declarativeRules.push(baseRule);
99
+ continue;
100
+ }
101
+ // Fix the action: set redirect with regexSubstitution from DNR conversion
102
+ baseRule.action = {
103
+ type: RuleActionType.Redirect,
104
+ redirect: {
105
+ regexSubstitution: dnrResults[0].regexSubstitution
106
+ }
107
+ };
108
+ // Apply urltransform-specific post-processing
109
+ UrlTransformRulesConverter.applyDomainScope(baseRule, rule);
110
+ UrlTransformRulesConverter.applyMethodDefault(baseRule, rule, urlTransformValue, dnrResults);
111
+ UrlTransformRulesConverter.applyRegexFilter(baseRule, dnrResults);
112
+ // Build all pipeline stages
113
+ const allRules = UrlTransformRulesConverter.buildPipelineStages(baseId, baseRule, dnrResults);
114
+ // Reserve all pipeline-stage IDs to prevent collisions with
115
+ // subsequent rules (baseId + stageIdx).
116
+ allRules.forEach((r)=>usedIds.add(r.id));
117
+ // Validate all stages against DNR constraints
118
+ // eslint-disable-next-line no-await-in-loop
119
+ await UrlTransformRulesConverter.validateAllStages(allRules, rule);
120
+ // Add source map entries for all pipeline stages
121
+ for(let stageIdx = 0; stageIdx < allRules.length; stageIdx += 1){
122
+ const stageRule = allRules[stageIdx];
123
+ res.sourceMapValues.push({
124
+ declarativeRuleId: stageRule.id,
125
+ sourceRuleIndex: index,
126
+ filterId
127
+ });
128
+ res.declarativeRules.push(stageRule);
129
+ }
130
+ } catch (e) {
131
+ const err = UrlTransformRulesConverter.wrapError(index, baseId, e);
132
+ res.errors.push(err);
133
+ }
134
+ }
135
+ return res;
136
+ }
137
+ /**
138
+ * Converts a single $urltransform network rule into one or more
139
+ * declarative rules.
140
+ *
141
+ * First performs the generic conversion via
142
+ * {@link RegularRuleConverter.convertRule}, then applies
143
+ * urltransform-specific post-processing:
144
+ * - Replaces urlFilter with regexFilter from the DNR transform result.
145
+ * - Preserves domain scope from the original pattern.
146
+ * - Defaults full-URL mode rules to GET-only when no $method is set.
147
+ * - Generates additional declarative rules for multi-stage pipelines.
148
+ * - Re-validates all produced rules against DNR constraints.
149
+ *
150
+ * @param id Rule identifier.
151
+ * @param rule Network rule.
152
+ *
153
+ * @returns A list of declarative rules.
154
+ */ async convertRule(id, rule) {
155
+ // Perform generic conversion (action, condition, priority, validation).
156
+ const baseRule = await super.convertRule(id, rule);
157
+ // Skip post-processing for allowlist rules
158
+ if (rule.allowlist) {
159
+ return baseRule;
160
+ }
161
+ const urlTransformValue = rule.advancedModifierValue;
162
+ if (!urlTransformValue) {
163
+ return baseRule;
164
+ }
165
+ const dnrResults = convertUrlTransformToDnr(urlTransformValue);
166
+ if (dnrResults.length === 0) {
167
+ return baseRule;
168
+ }
169
+ // Fix the action: set redirect with regexSubstitution from DNR conversion
170
+ baseRule.action = {
171
+ type: RuleActionType.Redirect,
172
+ redirect: {
173
+ regexSubstitution: dnrResults[0].regexSubstitution
174
+ }
175
+ };
176
+ // Post-process the base declarative rule.
177
+ UrlTransformRulesConverter.applyDomainScope(baseRule, rule);
178
+ UrlTransformRulesConverter.applyMethodDefault(baseRule, rule, urlTransformValue, dnrResults);
179
+ UrlTransformRulesConverter.applyRegexFilter(baseRule, dnrResults);
180
+ await UrlTransformRulesConverter.validateAllStages([
181
+ baseRule
182
+ ], rule);
183
+ return baseRule;
184
+ }
185
+ /**
186
+ * Preserves domain scope from the original pattern by extracting the
187
+ * domain and adding it to requestDomains so the rule doesn't apply
188
+ * to all sites after urlFilter is replaced by regexFilter.
189
+ *
190
+ * @param declarativeRule The declarative rule to modify.
191
+ * @param rule The original network rule.
192
+ */ static applyDomainScope(declarativeRule, rule) {
193
+ if (declarativeRule.condition.requestDomains) {
194
+ return;
195
+ }
196
+ const domain = UrlTransformRulesConverter.extractDomainFromPattern(rule.pattern);
197
+ if (domain) {
198
+ // eslint-disable-next-line no-param-reassign
199
+ declarativeRule.condition.requestDomains = [
200
+ domain
201
+ ];
202
+ }
203
+ }
204
+ /**
205
+ * Defaults full-URL (origin-changing) rules to GET-only when no
206
+ * explicit $method modifier is set, preventing unintended redirects
207
+ * that would discard POST/PUT request bodies.
208
+ *
209
+ * @param declarativeRule The declarative rule to modify.
210
+ * @param rule The original network rule.
211
+ * @param urlTransformValue The $urltransform modifier value.
212
+ * @param dnrResults The DNR conversion results for all pipeline stages.
213
+ */ static applyMethodDefault(declarativeRule, rule, urlTransformValue, dnrResults) {
214
+ if (!rule.isModifierEnabled(OPTION_NAMES.METHOD) && !declarativeRule.condition.requestMethods) {
215
+ const parts = parseUrlTransformParts(urlTransformValue);
216
+ // Check the first stage (via pattern) and all subsequent stages
217
+ // (via their DNR regexFilter) so that multi-stage pipelines where
218
+ // only a later stage changes the URL origin also get the GET-only
219
+ // default.
220
+ const isAnyStageFullUrl = isFullUrlPattern(parts.pattern) || dnrResults.some((r)=>/^\^https?/.test(r.regexFilter));
221
+ if (isAnyStageFullUrl) {
222
+ // eslint-disable-next-line no-param-reassign
223
+ declarativeRule.condition.requestMethods = [
224
+ 'get'
225
+ ];
226
+ }
227
+ }
228
+ }
229
+ /**
230
+ * Replaces the urlFilter-based condition with regexFilter from the
231
+ * DNR conversion result.
232
+ *
233
+ * @param declarativeRule The declarative rule to modify.
234
+ * @param dnrResults The DNR conversion results.
235
+ */ static applyRegexFilter(declarativeRule, dnrResults) {
236
+ // eslint-disable-next-line no-param-reassign
237
+ delete declarativeRule.condition.urlFilter;
238
+ // eslint-disable-next-line no-param-reassign
239
+ declarativeRule.condition.regexFilter = dnrResults[0].regexFilter;
240
+ if (dnrResults[0].isUrlFilterCaseSensitive !== undefined) {
241
+ // eslint-disable-next-line no-param-reassign
242
+ declarativeRule.condition.isUrlFilterCaseSensitive = dnrResults[0].isUrlFilterCaseSensitive;
243
+ }
244
+ }
245
+ /**
246
+ * Builds the full list of declarative rules for multi-stage pipelines.
247
+ * Single-stage rules return an array with just the base rule.
248
+ * Multi-stage pipelines generate additional rules for stages 2+.
249
+ *
250
+ * @param id Base rule identifier.
251
+ * @param baseRule The base declarative rule.
252
+ * @param dnrResults The DNR conversion results.
253
+ *
254
+ * @returns Array of all declarative rules (single or multi-stage).
255
+ */ static buildPipelineStages(id, baseRule, dnrResults) {
256
+ const allRules = [
257
+ baseRule
258
+ ];
259
+ // Multi-stage pipeline: generate additional rules for stages 2+.
260
+ for(let stageIdx = 1; stageIdx < dnrResults.length; stageIdx += 1){
261
+ const stageResult = dnrResults[stageIdx];
262
+ const stageRule = {
263
+ id: id + stageIdx,
264
+ action: {
265
+ type: RuleActionType.Redirect,
266
+ redirect: {
267
+ regexSubstitution: stageResult.regexSubstitution
268
+ }
269
+ },
270
+ condition: {
271
+ ...baseRule.condition
272
+ }
273
+ };
274
+ stageRule.condition.regexFilter = stageResult.regexFilter;
275
+ if (stageResult.isUrlFilterCaseSensitive !== undefined) {
276
+ stageRule.condition.isUrlFilterCaseSensitive = stageResult.isUrlFilterCaseSensitive;
277
+ }
278
+ if (baseRule.priority) {
279
+ stageRule.priority = baseRule.priority;
280
+ }
281
+ allRules.push(stageRule);
282
+ }
283
+ return allRules;
284
+ }
285
+ /**
286
+ * Validates all rules (including pipeline stages) against DNR
287
+ * constraints (RE2 compatibility, empty resources, etc.).
288
+ *
289
+ * @param allRules All declarative rules to validate.
290
+ * @param rule The original network rule.
291
+ *
292
+ * @throws Error if any rule fails validation.
293
+ */ static async validateAllStages(allRules, rule) {
294
+ for (const stageRule of allRules){
295
+ // eslint-disable-next-line no-await-in-loop
296
+ const stageErr = await RegularRuleConverter.checkRuleApplication(rule, stageRule);
297
+ if (stageErr) {
298
+ throw stageErr;
299
+ }
300
+ }
301
+ }
302
+ /**
303
+ * Extracts the domain from a URL pattern string.
304
+ *
305
+ * Handles common adblock pattern formats:
306
+ * - `||example.com^` → `example.com`.
307
+ * - `example.com/path` → `example.com`.
308
+ * - `https://example.com` → `example.com`.
309
+ * - `/path` → null (no domain).
310
+ *
311
+ * @param pattern The URL pattern string.
312
+ *
313
+ * @returns The extracted domain, or null if no domain could be extracted.
314
+ */ static extractDomainFromPattern(pattern) {
315
+ if (!pattern) {
316
+ return null;
317
+ }
318
+ let workStr = pattern;
319
+ // Remove leading || (domain name anchor)
320
+ if (workStr.startsWith('||')) {
321
+ workStr = workStr.slice(2);
322
+ }
323
+ // Extract domain part (up to first /, ^, or end)
324
+ const domainEnd = workStr.search(/[/^]/);
325
+ const domain = domainEnd === -1 ? workStr : workStr.slice(0, domainEnd);
326
+ // Remove leading protocol if present (e.g., https:// or http://)
327
+ const protocolMatch = domain.match(/^(?:https?:)?\/\/(.+)/);
328
+ if (protocolMatch) {
329
+ return protocolMatch[1] || null;
330
+ }
331
+ // Remove port number if present
332
+ const portIdx = domain.indexOf(':');
333
+ if (portIdx !== -1) {
334
+ return domain.slice(0, portIdx) || null;
335
+ }
336
+ return domain || null;
337
+ }
338
+ }
339
+
340
+ export { UrlTransformRulesConverter };
package/dist/index.js ADDED
@@ -0,0 +1,30 @@
1
+ export { DNR_CONVERTER_VERSION } from './version.js';
2
+ export { isSafeRule } from './utils/is-safe-rule.js';
3
+ export { Ruleset } from './ruleset/ruleset.js';
4
+ export { RulesetWithSourceMap } from './ruleset/ruleset-with-source-map.js';
5
+ export { Filter } from './filter/filter.js';
6
+ export { RulesHashMap } from './ruleset/rules-hash-map.js';
7
+ export { METADATA_RULESET_ID, MetadataRuleset } from './ruleset/metadata-ruleset.js';
8
+ export { Rule } from './rule/rule.js';
9
+ export { RuleDeclarativeValidator } from './rule/rule-validator.js';
10
+ export { isConversionError } from './errors/conversion-errors/index.js';
11
+ export { isConverterOptionsError } from './errors/converter-options-errors/index.js';
12
+ export { isLimitationError } from './errors/limitation-errors/index.js';
13
+ export { RULESET_NAME_PREFIX, extractRulesetId, getRulesetId, getRulesetPath } from './utils/ruleset-utils.js';
14
+ export { FilterConverter } from './filter-converter/filter-converter.js';
15
+ export { UnavailableFilterSourceError } from './errors/unavailable-sources-errors/unavailable-filter-source-error.js';
16
+ export { UnavailableRulesetSourceError } from './errors/unavailable-sources-errors/unavailable-ruleset-source-error.js';
17
+ export { ResourceType } from './declarative-rule/rule-condition.js';
18
+ export { RuleActionType } from './declarative-rule/rule-action.js';
19
+ export { EmptyDomainsError } from './errors/conversion-errors/empty-domains-error.js';
20
+ export { EmptyResourcesError } from './errors/conversion-errors/empty-resources-error.js';
21
+ export { UnsupportedModifierError } from './errors/conversion-errors/unsupported-modifier-error.js';
22
+ export { UnsupportedRegexpError } from './errors/conversion-errors/unsupported-regexp-error.js';
23
+ export { InvalidDeclarativeRuleError } from './errors/conversion-errors/invalid-declarative-rule-error.js';
24
+ export { EmptyOrNegativeNumberOfRulesError } from './errors/converter-options-errors/empty-or-negative-number-of-rules-error.js';
25
+ export { NegativeNumberOfRulesError } from './errors/converter-options-errors/negative-number-of-rules-error.js';
26
+ export { ResourcesPathError } from './errors/converter-options-errors/resources-path-error.js';
27
+ export { MaxScannedRulesError } from './errors/limitation-errors/max-scanned-rules-error.js';
28
+ export { TooManyRegexpRulesError } from './errors/limitation-errors/too-many-regexp-rules-error.js';
29
+ export { TooManyUnsafeRulesError } from './errors/limitation-errors/too-many-unsafe-rules-error.js';
30
+ export { TooManyRulesError } from './errors/limitation-errors/too-many-rules-error.js';
@@ -0,0 +1,3 @@
1
+ var version = "1.0.0-alpha.2";
2
+
3
+ export { version };
@@ -0,0 +1,37 @@
1
+ import { regexValidatorExtension } from './regex-validator-extension.js';
2
+
3
+ /**
4
+ * Class to manage regex validation using a customizable validator function.
5
+ * By default, it uses the Chrome validator, but a custom validator can be set.
6
+ */ class Re2Validator {
7
+ /**
8
+ * Set a custom validator function.
9
+ *
10
+ * @param validator The custom validator function to use.
11
+ */ setValidator(validator) {
12
+ this.validator = validator;
13
+ }
14
+ /**
15
+ * Check if the regex is supported using the current validator function.
16
+ *
17
+ * @param regexFilter The regex pattern to validate.
18
+ *
19
+ * @returns A promise that resolves to true if the regex is supported.
20
+ *
21
+ * @throws Error if the regex is unsupported.
22
+ */ async isRegexSupported(regexFilter) {
23
+ return this.validator(regexFilter);
24
+ }
25
+ constructor(){
26
+ /**
27
+ * The default validator function.
28
+ * By default, it uses the builtin browser validator.
29
+ */ this.validator = regexValidatorExtension;
30
+ }
31
+ }
32
+ /**
33
+ * Singleton instance of the {@link Re2Validator} class.
34
+ * Provides a single point of access to manage regex validation.
35
+ */ const re2Validator = new Re2Validator();
36
+
37
+ export { re2Validator };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Options for {@link chrome.declarativeNetRequest.isRegexSupported}.
3
+ */ /**
4
+ * Check if the regex is supported in a browser extension using the built-in chrome.declarativeNetRequest API.
5
+ *
6
+ * @param regexFilter Regex to check.
7
+ *
8
+ * @returns Promise that resolves to true if the regex is supported, and rejects with an error otherwise.
9
+ */ async function regexValidatorExtension(regexFilter) {
10
+ return new Promise((resolve, reject)=>{
11
+ if (typeof chrome !== 'undefined' && chrome.declarativeNetRequest) {
12
+ const regexOptions = {
13
+ regex: regexFilter
14
+ };
15
+ chrome.declarativeNetRequest.isRegexSupported(regexOptions, (result)=>{
16
+ if (chrome.runtime.lastError) {
17
+ reject(chrome.runtime.lastError);
18
+ } else if (result.isSupported) {
19
+ resolve(true);
20
+ } else {
21
+ reject(new Error(result.reason));
22
+ }
23
+ });
24
+ } else {
25
+ reject(new Error('chrome.declarativeNetRequest is not available'));
26
+ }
27
+ });
28
+ }
29
+
30
+ export { regexValidatorExtension };
package/dist/re2.wasm ADDED
Binary file
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @file Canonical modifier name constants for network filtering rules.
3
+ */ /**
4
+ * Canonical modifier names for network filtering rules.
5
+ *
6
+ * @see {@link https://adguard.com/kb/general/ad-filtering/create-own-filters/#basic-rule-modifiers}
7
+ */ const OPTION_NAMES = Object.freeze({
8
+ THIRD_PARTY: 'third-party',
9
+ FIRST_PARTY: 'first-party',
10
+ MATCH_CASE: 'match-case',
11
+ IMPORTANT: 'important',
12
+ DOMAIN: 'domain',
13
+ DENYALLOW: 'denyallow',
14
+ ELEMHIDE: 'elemhide',
15
+ GENERICHIDE: 'generichide',
16
+ SPECIFICHIDE: 'specifichide',
17
+ GENERICBLOCK: 'genericblock',
18
+ JSINJECT: 'jsinject',
19
+ URLBLOCK: 'urlblock',
20
+ CONTENT: 'content',
21
+ DOCUMENT: 'document',
22
+ DOC: 'doc',
23
+ STEALTH: 'stealth',
24
+ POPUP: 'popup',
25
+ EMPTY: 'empty',
26
+ MP4: 'mp4',
27
+ SCRIPT: 'script',
28
+ STYLESHEET: 'stylesheet',
29
+ SUBDOCUMENT: 'subdocument',
30
+ OBJECT: 'object',
31
+ IMAGE: 'image',
32
+ XMLHTTPREQUEST: 'xmlhttprequest',
33
+ MEDIA: 'media',
34
+ FONT: 'font',
35
+ WEBSOCKET: 'websocket',
36
+ OTHER: 'other',
37
+ PING: 'ping',
38
+ BADFILTER: 'badfilter',
39
+ CSP: 'csp',
40
+ REPLACE: 'replace',
41
+ COOKIE: 'cookie',
42
+ REDIRECT: 'redirect',
43
+ REDIRECTRULE: 'redirect-rule',
44
+ REMOVEPARAM: 'removeparam',
45
+ REMOVEHEADER: 'removeheader',
46
+ JSONPRUNE: 'jsonprune',
47
+ HLS: 'hls',
48
+ REFERRERPOLICY: 'referrerpolicy',
49
+ APP: 'app',
50
+ NETWORK: 'network',
51
+ EXTENSION: 'extension',
52
+ NOOP: '_',
53
+ CLIENT: 'client',
54
+ DNSREWRITE: 'dnsrewrite',
55
+ DNSTYPE: 'dnstype',
56
+ CTAG: 'ctag',
57
+ HEADER: 'header',
58
+ METHOD: 'method',
59
+ URLTRANSFORM: 'urltransform',
60
+ TO: 'to',
61
+ PERMISSIONS: 'permissions',
62
+ ALL: 'all'
63
+ });
64
+
65
+ export { OPTION_NAMES };
@@ -0,0 +1,81 @@
1
+ import { OPTION_NAMES } from './option-names.js';
2
+ import { stringArraysEqual, stringArraysHaveIntersection } from './string-utils.js';
3
+
4
+ /**
5
+ * Joins sorted elements of an array into a comma-separated string.
6
+ *
7
+ * @param arr Input array.
8
+ *
9
+ * @returns Sorted, comma-joined string.
10
+ */ function sortedJoin(arr) {
11
+ return [
12
+ ...arr
13
+ ].sort().join(',');
14
+ }
15
+ /**
16
+ * Helper class for checking whether a `$badfilter` rule negates another rule.
17
+ */ class RuleBadfilter {
18
+ /**
19
+ * Checks whether `badfilterRule` negates `targetRule`.
20
+ *
21
+ * A `$badfilter` rule negates another rule when both rules have:
22
+ * - the same allowlist flag,
23
+ * - the same pattern,
24
+ * - the same enabled modifiers (excluding `$badfilter` itself),
25
+ * - the same disabled modifiers,
26
+ * - the same permitted/restricted resource types,
27
+ * - the same restricted domains,
28
+ * - overlapping permitted domains, and
29
+ * - the same denyallow domains.
30
+ *
31
+ * @param badfilterRule The rule that carries the `$badfilter` modifier.
32
+ * @param targetRule The rule to test for negation.
33
+ *
34
+ * @returns `true` if `badfilterRule` negates `targetRule`.
35
+ */ static negates(badfilterRule, targetRule) {
36
+ if (!badfilterRule.enabledModifiers.has(OPTION_NAMES.BADFILTER)) {
37
+ return false;
38
+ }
39
+ if (badfilterRule.allowlist !== targetRule.allowlist) {
40
+ return false;
41
+ }
42
+ if (badfilterRule.pattern !== targetRule.pattern) {
43
+ return false;
44
+ }
45
+ // Compare resource type arrays (order-independent).
46
+ if (sortedJoin(badfilterRule.permittedResourceTypes) !== sortedJoin(targetRule.permittedResourceTypes)) {
47
+ return false;
48
+ }
49
+ if (sortedJoin(badfilterRule.restrictedResourceTypes) !== sortedJoin(targetRule.restrictedResourceTypes)) {
50
+ return false;
51
+ }
52
+ // Compare enabled modifiers excluding $badfilter itself.
53
+ const badfilterEnabled = new Set(badfilterRule.enabledModifiers);
54
+ badfilterEnabled.delete(OPTION_NAMES.BADFILTER);
55
+ const sameSize = badfilterEnabled.size === targetRule.enabledModifiers.size;
56
+ const sameModifiers = [
57
+ ...badfilterEnabled
58
+ ].every((m)=>targetRule.enabledModifiers.has(m));
59
+ if (!sameSize || !sameModifiers) {
60
+ return false;
61
+ }
62
+ // Compare disabled modifiers.
63
+ if (badfilterRule.disabledModifiers.size !== targetRule.disabledModifiers.size || ![
64
+ ...badfilterRule.disabledModifiers
65
+ ].every((m)=>targetRule.disabledModifiers.has(m))) {
66
+ return false;
67
+ }
68
+ if (!stringArraysEqual(badfilterRule.restrictedDomains, targetRule.restrictedDomains)) {
69
+ return false;
70
+ }
71
+ if (!stringArraysHaveIntersection(badfilterRule.permittedDomains, targetRule.permittedDomains)) {
72
+ return false;
73
+ }
74
+ if (!stringArraysEqual(badfilterRule.denyAllowDomains, targetRule.denyAllowDomains)) {
75
+ return false;
76
+ }
77
+ return true;
78
+ }
79
+ }
80
+
81
+ export { RuleBadfilter };
@@ -0,0 +1,88 @@
1
+ /**
2
+ * @file Priority calculation for {@link ParsedNetworkRule} instances.
3
+ *
4
+ * Extracted from the main rule module so that the priority logic can be
5
+ * reasoned about and tested in isolation.
6
+ */ /**
7
+ * Calculates DNR rule priority from intermediate {@link ConversionMeta}.
8
+ *
9
+ * Priority mirrors the calculation performed by tsurlfilter's
10
+ * `calculateRulePriority()`:
11
+ *
12
+ * - Category 1 (+1 each): `$third-party`, `$match-case`, `$dnsrewrite`,
13
+ * restricted domains, restricted methods, denyallow domains, `$to`.
14
+ * - Category 2 (+50 / count): permitted content types.
15
+ * - Category 3 (+100 / count): permitted domains.
16
+ * - Category 4 (+1 000): redirect modifiers.
17
+ * - Category 5 (*10 000): specific exclusion modifiers.
18
+ * - Category 6 (+100 000): allowlist rules.
19
+ * - Category 7 (+1 000 000): `$important`.
20
+ *
21
+ * The final value is rounded up to the nearest integer (≥ 1).
22
+ */ class RulePriority {
23
+ /**
24
+ * Calculates rule priority from intermediate {@link ConversionMeta}.
25
+ *
26
+ * @param meta Intermediate conversion metadata produced during modifier
27
+ * processing.
28
+ * @param isAllowlist Whether the rule is an allowlist (exception) rule.
29
+ *
30
+ * @returns Rule priority (positive integer ≥ 1).
31
+ */ static calculate(meta, isAllowlist) {
32
+ // Base weight (1) + category-1 modifier contributions (+1 each).
33
+ let weight = 1 + meta.baseModifierCount;
34
+ // Category 2 — permitted content types
35
+ if (meta.permittedContentTypeCount > 0) {
36
+ weight += RulePriority.CATEGORY_TWO_WEIGHT + RulePriority.CATEGORY_TWO_WEIGHT / meta.permittedContentTypeCount;
37
+ }
38
+ // Category 2 — permitted HTTP methods (same formula as content types)
39
+ if (meta.permittedMethodCount > 0) {
40
+ weight += RulePriority.CATEGORY_TWO_WEIGHT + RulePriority.CATEGORY_TWO_WEIGHT / meta.permittedMethodCount;
41
+ }
42
+ // Category 2 — $header modifier (flat weight, no /count division)
43
+ if (meta.hasHeader) {
44
+ weight += RulePriority.CATEGORY_TWO_WEIGHT;
45
+ }
46
+ // Category 3 — permitted domains
47
+ if (meta.permittedDomainCount > 0) {
48
+ weight += RulePriority.CATEGORY_THREE_WEIGHT + RulePriority.CATEGORY_THREE_WEIGHT / meta.permittedDomainCount;
49
+ }
50
+ // Category 4 — redirect
51
+ if (meta.hasRedirect) {
52
+ weight += RulePriority.CATEGORY_FOUR_WEIGHT;
53
+ }
54
+ // Category 5 — specific exclusions (additive: +10_000 per modifier)
55
+ if (meta.specificExclusionCount > 0) {
56
+ weight += meta.specificExclusionCount * RulePriority.CATEGORY_FIVE_WEIGHT;
57
+ }
58
+ // Category 6 — allowlist
59
+ if (isAllowlist) {
60
+ weight += RulePriority.CATEGORY_SIX_WEIGHT;
61
+ }
62
+ // Category 7 — important
63
+ if (meta.hasImportant) {
64
+ weight += RulePriority.CATEGORY_SEVEN_WEIGHT;
65
+ }
66
+ return Math.max(1, Math.ceil(weight));
67
+ }
68
+ }
69
+ /**
70
+ * Weight for a single permitted content-type when only one type is set.
71
+ */ RulePriority.CATEGORY_TWO_WEIGHT = 50;
72
+ /**
73
+ * Weight for a single permitted domain.
74
+ */ RulePriority.CATEGORY_THREE_WEIGHT = 100;
75
+ /**
76
+ * Base weight for redirect rules (Category 4).
77
+ */ RulePriority.CATEGORY_FOUR_WEIGHT = 1000;
78
+ /**
79
+ * Weight per specific-exclusion modifier (Category 5).
80
+ */ RulePriority.CATEGORY_FIVE_WEIGHT = 10000;
81
+ /**
82
+ * Weight for allowlist rules (Category 6).
83
+ */ RulePriority.CATEGORY_SIX_WEIGHT = 100000;
84
+ /**
85
+ * Weight for `$important` modifier (Category 7).
86
+ */ RulePriority.CATEGORY_SEVEN_WEIGHT = 1000000;
87
+
88
+ export { RulePriority };