@whotracksme/reporting 12.0.0 → 12.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,25 @@
1
+ # v12.1.0 (Mon Sep 07 2026)
2
+
3
+ #### 🚀 Enhancement
4
+
5
+ - New builtins [#228](https://github.com/whotracksme/webextension-packages/pull/228) ([@philipp-classen](https://github.com/philipp-classen))
6
+
7
+ #### 🐛 Bug Fix
8
+
9
+ - fixed: processing of transformation steps should stop on null/undefined [#229](https://github.com/whotracksme/webextension-packages/pull/229) ([@philipp-classen](https://github.com/philipp-classen))
10
+
11
+ #### 🏠 Internal
12
+
13
+ - Let e2e runs override the served patterns [#227](https://github.com/whotracksme/webextension-packages/pull/227) ([@chrmod](https://github.com/chrmod))
14
+ - Gate request reporting on documentId support [#203](https://github.com/whotracksme/webextension-packages/pull/203) ([@chrmod](https://github.com/chrmod))
15
+
16
+ #### Authors: 2
17
+
18
+ - Krzysztof Modras ([@chrmod](https://github.com/chrmod))
19
+ - Philipp Claßen ([@philipp-classen](https://github.com/philipp-classen))
20
+
21
+ ---
22
+
1
23
  # v12.0.0 (Wed Aug 19 2026)
2
24
 
3
25
  #### 💥 Breaking Change
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "12.0.0",
3
+ "version": "12.1.0",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -87,6 +87,7 @@ npm --workspace=reporting run e2e -- smoke --json
87
87
  | | `--json` | off | Full capture + step trace instead of the summary |
88
88
  | | `--keep-messages` | off | Do not clear captures first — accumulate across runs |
89
89
  | | `--hub <url>` | `http://127.0.0.1:7878` | Where the hub is |
90
+ | | `--patterns <file>` | off | Replace the served patterns with a local file for this run (re-applied after every `reset`) |
90
91
  | `e2e.hub` | `--port <n>` | `7878` | See the caveat below |
91
92
  | | `--out-dir <path>` | `example/e2e/out` | Where captures are written |
92
93
  | | `--quiet` | off | Suppress per-message logging |
@@ -134,6 +135,7 @@ Everything is appended to `out/messages.jsonl`, `out/events.jsonl` and
134
135
  | `reset` | Clear storage and **restart the worker** — a true fresh install (see note) |
135
136
  | `reload` | Restart the worker without clearing storage; picks up a rebuilt bundle |
136
137
  | `setQuorum {mode}` | `always` or `never` |
138
+ | `setPatterns {rules}` | Replace the served patterns for this session (persisted; the next poll is pushed out by a full interval) |
137
139
  | `closeTabs {urlContains?}` | Tidy between scenarios |
138
140
  | `ping` | Liveness check |
139
141
 
@@ -382,6 +382,32 @@ export function createCommands({
382
382
  return quorumControl.describe();
383
383
  },
384
384
 
385
+ // Replaces the served patterns for this session. They are persisted and
386
+ // the next poll is pushed out by a full interval, so neither a worker
387
+ // restart nor the updater brings the served ones back meanwhile. Applied
388
+ // only once the reporter is active: init() awaits the startup fetch of
389
+ // the served patterns, which would otherwise land on top of these.
390
+ async setPatterns({ rules, timeoutInMs = 30000 }) {
391
+ if (!rules || typeof rules !== 'object') {
392
+ throw new Error('setPatterns requires "rules" (an object)');
393
+ }
394
+ const startedAt = Date.now();
395
+ while (!urlReporter.isActive) {
396
+ if (Date.now() - startedAt > timeoutInMs) {
397
+ throw new Error('reporter did not become active');
398
+ }
399
+ await sleep(100);
400
+ }
401
+ patterns.updatePatterns(rules);
402
+ const { patternsUpdater } = urlReporter;
403
+ patternsUpdater._persistedState.patterns = JSON.stringify(rules);
404
+ patternsUpdater._persistedState.failedAttemptsInARow = 0;
405
+ patternsUpdater._persistedState.skipAttemptsUntil =
406
+ Date.now() + patternsUpdater.defaultUpdateInterval.max;
407
+ await patternsUpdater._savePersistedState();
408
+ return { categories: Object.keys(patterns.getRulesSnapshot() || {}) };
409
+ },
410
+
385
411
  // Restarts rather than unload()+init(): Pages#init is one-shot.
386
412
  async reset() {
387
413
  await chrome.storage.local.clear();
@@ -20,6 +20,7 @@ const { values, positionals } = parseArgs({
20
20
  hub: { type: 'string', default: 'http://127.0.0.1:7878' },
21
21
  json: { type: 'boolean', default: false },
22
22
  'keep-messages': { type: 'boolean', default: false },
23
+ patterns: { type: 'string' },
23
24
  },
24
25
  });
25
26
 
@@ -97,6 +98,40 @@ const startSeq = (await hub('GET', '/health')).body.seq;
97
98
 
98
99
  const STEP_OPTIONS = ['timeout', 'continueOnError'];
99
100
 
101
+ // A local patterns file replaces the served one for the run. A reset restarts
102
+ // the worker with empty storage, so it has to be applied again afterwards.
103
+ const patternsOverride = values.patterns
104
+ ? JSON.parse(fs.readFileSync(values.patterns, 'utf8'))
105
+ : null;
106
+
107
+ async function applyPatternsOverride() {
108
+ if (!patternsOverride) {
109
+ return;
110
+ }
111
+ const { categories } = await command('setPatterns', {
112
+ rules: patternsOverride,
113
+ });
114
+ console.error(` patterns: ${values.patterns} (${categories.join(', ')})`);
115
+ }
116
+
117
+ // The worker reconnects before init() has finished; a navigation that lands
118
+ // in that window is dropped, so a restart is only done once it is active.
119
+ async function waitUntilActive(timeoutInMs = 30000) {
120
+ const startedAt = Date.now();
121
+ for (;;) {
122
+ const state = await command('state');
123
+ if (state.isActive) {
124
+ return;
125
+ }
126
+ if (Date.now() - startedAt > timeoutInMs) {
127
+ throw new Error('reporter did not become active after the restart');
128
+ }
129
+ await new Promise((resolve) => setTimeout(resolve, 250));
130
+ }
131
+ }
132
+
133
+ await applyPatternsOverride();
134
+
100
135
  const trace = [];
101
136
  for (const [index, step] of (scenario.steps || []).entries()) {
102
137
  const entry = Object.entries(step).find(
@@ -116,6 +151,10 @@ for (const [index, step] of (scenario.steps || []).entries()) {
116
151
  const took = Date.now() - startedAt;
117
152
  process.stderr.write(`ok (${took}ms)\n`);
118
153
  trace.push({ step: name, args, result, tookInMs: took });
154
+ if (name === 'reset' || name === 'reload') {
155
+ await waitUntilActive();
156
+ await applyPatternsOverride();
157
+ }
119
158
  } catch (e) {
120
159
  process.stderr.write(`FAILED\n`);
121
160
  console.error(`\n ${e.message}\n`);
@@ -1631,7 +1631,7 @@
1631
1631
  },
1632
1632
  "ts": "",
1633
1633
  "type": "wtm.request",
1634
- "userAgent": ""
1634
+ "userAgent": "chrome"
1635
1635
  },
1636
1636
  {
1637
1637
  "action": "wtm.attrack.tp_events",
@@ -3275,7 +3275,7 @@
3275
3275
  },
3276
3276
  "ts": "",
3277
3277
  "type": "wtm.request",
3278
- "userAgent": ""
3278
+ "userAgent": "chrome"
3279
3279
  },
3280
3280
  {
3281
3281
  "action": "wtm.attrack.tokensv2",
@@ -3296,7 +3296,7 @@
3296
3296
  },
3297
3297
  "ts": "",
3298
3298
  "type": "wtm.request",
3299
- "userAgent": ""
3299
+ "userAgent": "chrome"
3300
3300
  },
3301
3301
  {
3302
3302
  "action": "wtm.attrack.keysv2",
@@ -3486,7 +3486,7 @@
3486
3486
  },
3487
3487
  "ts": "",
3488
3488
  "type": "wtm.request",
3489
- "userAgent": ""
3489
+ "userAgent": "chrome"
3490
3490
  },
3491
3491
  {
3492
3492
  "action": "wtm.attrack.keysv2",
@@ -3676,7 +3676,7 @@
3676
3676
  },
3677
3677
  "ts": "",
3678
3678
  "type": "wtm.request",
3679
- "userAgent": ""
3679
+ "userAgent": "chrome"
3680
3680
  },
3681
3681
  {
3682
3682
  "action": "wtm.attrack.keysv2",
@@ -3702,7 +3702,7 @@
3702
3702
  },
3703
3703
  "ts": "",
3704
3704
  "type": "wtm.request",
3705
- "userAgent": ""
3705
+ "userAgent": "chrome"
3706
3706
  },
3707
3707
  {
3708
3708
  "action": "wtm.attrack.keysv2",
@@ -3728,7 +3728,7 @@
3728
3728
  },
3729
3729
  "ts": "",
3730
3730
  "type": "wtm.request",
3731
- "userAgent": ""
3731
+ "userAgent": "chrome"
3732
3732
  },
3733
3733
  {
3734
3734
  "action": "wtm.attrack.keysv2",
@@ -3754,7 +3754,7 @@
3754
3754
  },
3755
3755
  "ts": "",
3756
3756
  "type": "wtm.request",
3757
- "userAgent": ""
3757
+ "userAgent": "chrome"
3758
3758
  },
3759
3759
  {
3760
3760
  "action": "wtm.attrack.keysv2",
@@ -3780,7 +3780,7 @@
3780
3780
  },
3781
3781
  "ts": "",
3782
3782
  "type": "wtm.request",
3783
- "userAgent": ""
3783
+ "userAgent": "chrome"
3784
3784
  },
3785
3785
  {
3786
3786
  "action": "wtm.attrack.keysv2",
@@ -3806,7 +3806,7 @@
3806
3806
  },
3807
3807
  "ts": "",
3808
3808
  "type": "wtm.request",
3809
- "userAgent": ""
3809
+ "userAgent": "chrome"
3810
3810
  },
3811
3811
  {
3812
3812
  "action": "wtm.attrack.keysv2",
@@ -3832,7 +3832,7 @@
3832
3832
  },
3833
3833
  "ts": "",
3834
3834
  "type": "wtm.request",
3835
- "userAgent": ""
3835
+ "userAgent": "chrome"
3836
3836
  },
3837
3837
  {
3838
3838
  "action": "wtm.attrack.keysv2",
@@ -3858,7 +3858,7 @@
3858
3858
  },
3859
3859
  "ts": "",
3860
3860
  "type": "wtm.request",
3861
- "userAgent": ""
3861
+ "userAgent": "chrome"
3862
3862
  },
3863
3863
  {
3864
3864
  "action": "wtm.attrack.keysv2",
@@ -3884,6 +3884,6 @@
3884
3884
  },
3885
3885
  "ts": "",
3886
3886
  "type": "wtm.request",
3887
- "userAgent": ""
3887
+ "userAgent": "chrome"
3888
3888
  }
3889
3889
  ]
@@ -196,7 +196,7 @@
196
196
  },
197
197
  "ts": "",
198
198
  "type": "wtm.request",
199
- "userAgent": ""
199
+ "userAgent": "chrome"
200
200
  },
201
201
  {
202
202
  "action": "wtm.attrack.tp_events",
@@ -398,7 +398,7 @@
398
398
  },
399
399
  "ts": "",
400
400
  "type": "wtm.request",
401
- "userAgent": ""
401
+ "userAgent": "chrome"
402
402
  },
403
403
  {
404
404
  "action": "wtm.attrack.tokensv2",
@@ -419,7 +419,7 @@
419
419
  },
420
420
  "ts": "",
421
421
  "type": "wtm.request",
422
- "userAgent": ""
422
+ "userAgent": "chrome"
423
423
  },
424
424
  {
425
425
  "action": "wtm.attrack.keysv2",
@@ -609,7 +609,7 @@
609
609
  },
610
610
  "ts": "",
611
611
  "type": "wtm.request",
612
- "userAgent": ""
612
+ "userAgent": "chrome"
613
613
  },
614
614
  {
615
615
  "action": "wtm.attrack.keysv2",
@@ -799,6 +799,6 @@
799
799
  },
800
800
  "ts": "",
801
801
  "type": "wtm.request",
802
- "userAgent": ""
802
+ "userAgent": "chrome"
803
803
  }
804
804
  ]
@@ -130,7 +130,7 @@
130
130
  },
131
131
  "ts": "",
132
132
  "type": "wtm.request",
133
- "userAgent": ""
133
+ "userAgent": "chrome"
134
134
  },
135
135
  {
136
136
  "action": "wtm.attrack.tp_events",
@@ -243,7 +243,7 @@
243
243
  },
244
244
  "ts": "",
245
245
  "type": "wtm.request",
246
- "userAgent": ""
246
+ "userAgent": "chrome"
247
247
  },
248
248
  {
249
249
  "action": "wtm.attrack.tp_events",
@@ -684,7 +684,7 @@
684
684
  },
685
685
  "ts": "",
686
686
  "type": "wtm.request",
687
- "userAgent": ""
687
+ "userAgent": "chrome"
688
688
  },
689
689
  {
690
690
  "action": "wtm.attrack.tp_events",
@@ -1146,7 +1146,7 @@
1146
1146
  },
1147
1147
  "ts": "",
1148
1148
  "type": "wtm.request",
1149
- "userAgent": ""
1149
+ "userAgent": "chrome"
1150
1150
  },
1151
1151
  {
1152
1152
  "action": "wtm.attrack.tp_events",
@@ -1279,7 +1279,7 @@
1279
1279
  },
1280
1280
  "ts": "",
1281
1281
  "type": "wtm.request",
1282
- "userAgent": ""
1282
+ "userAgent": "chrome"
1283
1283
  },
1284
1284
  {
1285
1285
  "action": "wtm.attrack.tp_events",
@@ -1392,7 +1392,7 @@
1392
1392
  },
1393
1393
  "ts": "",
1394
1394
  "type": "wtm.request",
1395
- "userAgent": ""
1395
+ "userAgent": "chrome"
1396
1396
  },
1397
1397
  {
1398
1398
  "action": "wtm.attrack.tp_events",
@@ -1833,7 +1833,7 @@
1833
1833
  },
1834
1834
  "ts": "",
1835
1835
  "type": "wtm.request",
1836
- "userAgent": ""
1836
+ "userAgent": "chrome"
1837
1837
  },
1838
1838
  {
1839
1839
  "action": "wtm.attrack.tp_events",
@@ -2295,7 +2295,7 @@
2295
2295
  },
2296
2296
  "ts": "",
2297
2297
  "type": "wtm.request",
2298
- "userAgent": ""
2298
+ "userAgent": "chrome"
2299
2299
  },
2300
2300
  {
2301
2301
  "action": "wtm.attrack.tokensv2",
@@ -2316,7 +2316,7 @@
2316
2316
  },
2317
2317
  "ts": "",
2318
2318
  "type": "wtm.request",
2319
- "userAgent": ""
2319
+ "userAgent": "chrome"
2320
2320
  },
2321
2321
  {
2322
2322
  "action": "wtm.attrack.keysv2",
@@ -4602,7 +4602,7 @@
4602
4602
  },
4603
4603
  "ts": "",
4604
4604
  "type": "wtm.request",
4605
- "userAgent": ""
4605
+ "userAgent": "chrome"
4606
4606
  },
4607
4607
  {
4608
4608
  "action": "wtm.attrack.keysv2",
@@ -6892,7 +6892,7 @@
6892
6892
  },
6893
6893
  "ts": "",
6894
6894
  "type": "wtm.request",
6895
- "userAgent": ""
6895
+ "userAgent": "chrome"
6896
6896
  },
6897
6897
  {
6898
6898
  "action": "wtm.attrack.keysv2",
@@ -6918,7 +6918,7 @@
6918
6918
  },
6919
6919
  "ts": "",
6920
6920
  "type": "wtm.request",
6921
- "userAgent": ""
6921
+ "userAgent": "chrome"
6922
6922
  },
6923
6923
  {
6924
6924
  "action": "wtm.attrack.keysv2",
@@ -6944,6 +6944,6 @@
6944
6944
  },
6945
6945
  "ts": "",
6946
6946
  "type": "wtm.request",
6947
- "userAgent": ""
6947
+ "userAgent": "chrome"
6948
6948
  }
6949
6949
  ]
@@ -10,7 +10,12 @@
10
10
  */
11
11
 
12
12
  import logger from './logger';
13
- import { requireParam, requireInt, lazyInitAsync } from './utils';
13
+ import {
14
+ requireParam,
15
+ requireInt,
16
+ lazyInitAsync,
17
+ isSubSequence,
18
+ } from './utils';
14
19
  import { randomBetween } from './random';
15
20
  import { BadJobError } from './errors';
16
21
  import { anonymousHttpGet } from './http';
@@ -28,25 +33,6 @@ const ALLOW_HTML_AND_TEXT = [
28
33
  'application/xhtml+xml', // legacy format
29
34
  ];
30
35
 
31
- /**
32
- * Checks if one string (subsequence) can be derived from another string (sequence)
33
- * by only removing characters. This means that the subsequence appears in the
34
- * sequence in the same relative order but not necessarily consecutively.
35
- *
36
- * Example: "anana" is a subsequence of "banana", but "ab" is not.
37
- */
38
- function isSubSequence({ sequence, subsequence }) {
39
- let i = 0;
40
- let j = 0;
41
- while (i < subsequence.length && j < sequence.length) {
42
- if (subsequence[i] === sequence[j]) {
43
- i++;
44
- }
45
- j++;
46
- }
47
- return i === subsequence.length;
48
- }
49
-
50
36
  export function toTrustedUrl(url, { baseUrl, log, logWarn }) {
51
37
  if (!url) {
52
38
  return null;
@@ -10,4 +10,5 @@
10
10
  */
11
11
  export { default as UrlReporter } from './reporting';
12
12
  export { default as RequestReporter } from './request/index';
13
+ export { isRequestReportingSupported } from './request/support';
13
14
  export { setLogLevel, describeLoggers } from './logger';
@@ -320,6 +320,143 @@ const TRANSFORMS = new Map(
320
320
  requireString(text);
321
321
  return text.trim();
322
322
  },
323
+
324
+ /**
325
+ * Removes the first match of a regular expression. The length cannot
326
+ * increase, because characters can only be removed, never added.
327
+ *
328
+ * Example ["removeFirstMatch", "AB+"]:
329
+ * - "xABBBy ABz" -> "xy ABz"
330
+ *
331
+ * @since: 9
332
+ */
333
+ removeFirstMatch: (text, pattern) => {
334
+ requireString(text);
335
+ requireString(pattern);
336
+ if (text.length === 0) {
337
+ return '';
338
+ }
339
+ try {
340
+ return text.replace(new RegExp(pattern), '');
341
+ } catch (e) {
342
+ return '';
343
+ }
344
+ },
345
+
346
+ /**
347
+ * Removes every match of a regular expression. The length cannot
348
+ * increase, because characters can only be removed, never added.
349
+ *
350
+ * Example ["removeAllMatches", "AB+"]:
351
+ * - "xABBBy ABz" -> "xy z"
352
+ *
353
+ * @since: 9
354
+ */
355
+ removeAllMatches: (text, pattern) => {
356
+ requireString(text);
357
+ requireString(pattern);
358
+ if (text.length === 0) {
359
+ return '';
360
+ }
361
+ try {
362
+ return text.replaceAll(new RegExp(pattern, 'g'), '');
363
+ } catch (e) {
364
+ return '';
365
+ }
366
+ },
367
+
368
+ /**
369
+ * Keeps only the first match of a regular expression (or an empty
370
+ * string if there is no match). The length cannot increase, because
371
+ * characters can only be removed, never added.
372
+ *
373
+ * Example ["selectFirstMatch", "AB+"]:
374
+ * - "xABBBy ABz" -> "ABBB"
375
+ *
376
+ * @since: 9
377
+ */
378
+ selectFirstMatch: (text, pattern) => {
379
+ requireString(text);
380
+ requireString(pattern);
381
+ if (text.length === 0) {
382
+ return '';
383
+ }
384
+ try {
385
+ const m = new RegExp(pattern).exec(text);
386
+ return m ? m[0] : '';
387
+ } catch (e) {
388
+ return '';
389
+ }
390
+ },
391
+
392
+ /**
393
+ * Keeps only the matches of a regular expression, concatenated in
394
+ * order (everything else is removed). The length cannot increase,
395
+ * because characters can only be removed, never added.
396
+ *
397
+ * Example ["selectAllMatches", "AB+"]:
398
+ * - "xABBBy ABz" -> "ABBBAB"
399
+ *
400
+ * @since: 9
401
+ */
402
+ selectAllMatches: (text, pattern) => {
403
+ requireString(text);
404
+ requireString(pattern);
405
+ if (text.length === 0) {
406
+ return '';
407
+ }
408
+ try {
409
+ const regexp = new RegExp(pattern, 'g');
410
+
411
+ // Pathological patterns will always be slow, but we can defend against
412
+ // one class: if the pattern can match empty and we can prove it,
413
+ // we can switch to a more memory-efficient implementation, avoiding
414
+ // massive arrays of empty strings.
415
+ //
416
+ // The test('') heuristic is incomplete, but it catches common cases
417
+ // that could be introduced by accident (e.g. "[^a-zA-Z0-9]*").
418
+ const canMatchEmpty = regexp.test('');
419
+ if (canMatchEmpty) {
420
+ // "exec" is safer for empty-matching patterns. It avoids the worst case
421
+ // of creating massive arrays of empty strings.
422
+ let matches = [];
423
+ let m;
424
+ regexp.lastIndex = 0;
425
+ while ((m = regexp.exec(text)) !== null) {
426
+ if (m[0]) {
427
+ matches.push(m[0]);
428
+ } else {
429
+ regexp.lastIndex += 1;
430
+ }
431
+ }
432
+ return matches.join('');
433
+ }
434
+
435
+ // "match" is slightly faster for non-empty-matching patterns
436
+ const matches = text.match(regexp);
437
+ return matches ? matches.join('') : '';
438
+ } catch (e) {
439
+ return '';
440
+ }
441
+ },
442
+
443
+ /**
444
+ * @since: 9
445
+ */
446
+ maxLength: (text, size) => {
447
+ requireString(text);
448
+ requireInt(size);
449
+ return text.length <= size ? text : null;
450
+ },
451
+
452
+ /**
453
+ * @since: 9
454
+ */
455
+ minLength: (text, size) => {
456
+ requireString(text);
457
+ requireInt(size);
458
+ return text.length >= size ? text : null;
459
+ },
323
460
  }),
324
461
  );
325
462
 
@@ -340,7 +477,7 @@ export function lookupBuiltinTransform(name) {
340
477
  * to disable clients that do not meet the minimum requirements of the
341
478
  * current patterns.
342
479
  */
343
- const PATTERN_DSL_VERSION = 8;
480
+ const PATTERN_DSL_VERSION = 9;
344
481
 
345
482
  /**
346
483
  * "Magic" empty rule set, which exists only if patterns were loaded, but
@@ -40,6 +40,7 @@ import {
40
40
  } from './steps/check-context.js';
41
41
  import PageStore from './page-store.js';
42
42
  import ChromeStorageMap from './utils/chrome-storage-map.js';
43
+ import { isRequestReportingSupported } from './support.js';
43
44
 
44
45
  const DAY_CHANGE_INTERVAL = 20 * 1000;
45
46
  const RECENTLY_MODIFIED_TTL = 30 * 1000;
@@ -68,6 +69,11 @@ export default class RequestReporter {
68
69
  pauseState, // see Reporting#constructor (../reporting.js)
69
70
  },
70
71
  ) {
72
+ if (!isRequestReportingSupported()) {
73
+ throw new Error(
74
+ 'RequestReporter requires documentId support in webRequest and webNavigation (Chromium >= 106, Safari >= 18.4, or Firefox >= 153)',
75
+ );
76
+ }
71
77
  this.settings = settings;
72
78
  this.onMessageReady = onMessageReady;
73
79
  this.trustedClock = trustedClock;
@@ -284,6 +284,7 @@ export default class PageStore {
284
284
  parentDocumentId,
285
285
  url,
286
286
  }) => {
287
+ if (!documentId) return;
287
288
  if (frameId !== 0) {
288
289
  if (this.#documentIndex.has(documentId)) return;
289
290
  const owner =
@@ -0,0 +1,29 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://whotracks.me/
4
+ *
5
+ * Copyright 2017-present Ghostery GmbH. All rights reserved.
6
+ *
7
+ * This Source Code Form is subject to the terms of the Mozilla Public
8
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
9
+ * file, You can obtain one at http://mozilla.org/MPL/2.0
10
+ */
11
+
12
+ // Chromium forks (Edge, Opera, Yandex) keep the Chrome/<major> token.
13
+ const DOCUMENT_ID_MIN_VERSIONS = [
14
+ [/Chrom(?:e|ium)\/(\d+)/, 106],
15
+ [/Firefox\/(\d+)/, 153],
16
+ [/Version\/(\d+(?:\.\d+)?).*Safari/, 18.4],
17
+ ];
18
+
19
+ export function isRequestReportingSupported(
20
+ userAgent = globalThis.navigator?.userAgent,
21
+ ) {
22
+ for (const [pattern, minVersion] of DOCUMENT_ID_MIN_VERSIONS) {
23
+ const match = userAgent?.match(pattern);
24
+ if (match) {
25
+ return parseFloat(match[1]) >= minVersion;
26
+ }
27
+ }
28
+ return false;
29
+ }
@@ -54,7 +54,8 @@ function runSelector(item, selector, attr, baseURI) {
54
54
  return null;
55
55
  }
56
56
 
57
- function runTransforms(value, transformSteps = []) {
57
+ // Note: exported for tests only
58
+ export function runTransforms(value, transformSteps = []) {
58
59
  if (!Array.isArray(transformSteps)) {
59
60
  throw new BadPatternError(
60
61
  'Transform definitions must be an array (of arrays).',
@@ -73,8 +74,11 @@ function runTransforms(value, transformSteps = []) {
73
74
  const [name, ...args] = step;
74
75
  const transform = lookupBuiltinTransform(name);
75
76
  tmpValue = transform(tmpValue, ...args);
77
+ if (tmpValue === undefined || tmpValue === null) {
78
+ return null;
79
+ }
76
80
  }
77
- return tmpValue ?? null;
81
+ return tmpValue;
78
82
  }
79
83
 
80
84
  function findFirstMatch(rootItem, selectorDef, baseURI) {
@@ -345,6 +345,25 @@ export function includesMiddleChar(str, char) {
345
345
  return false;
346
346
  }
347
347
 
348
+ /**
349
+ * Checks if one string (subsequence) can be derived from another string (sequence)
350
+ * by only removing characters. This means that the subsequence appears in the
351
+ * sequence in the same relative order but not necessarily consecutively.
352
+ *
353
+ * Example: "anana" is a subsequence of "banana", but "ab" is not.
354
+ */
355
+ export function isSubSequence({ sequence, subsequence }) {
356
+ let i = 0;
357
+ let j = 0;
358
+ while (i < subsequence.length && j < sequence.length) {
359
+ if (subsequence[i] === sequence[j]) {
360
+ i++;
361
+ }
362
+ j++;
363
+ }
364
+ return i === subsequence.length;
365
+ }
366
+
348
367
  /**
349
368
  * Drop-in replacement for JSON.parse if you need to handle untrusted data.
350
369
  *
@@ -13,6 +13,7 @@ import { expect } from 'chai';
13
13
  import fc from 'fast-check';
14
14
 
15
15
  import Patterns, { lookupBuiltinTransform } from '../src/patterns.js';
16
+ import { isSubSequence } from '../src/utils.js';
16
17
 
17
18
  describe('Test builtin primitives', function () {
18
19
  describe('#queryParam', function () {
@@ -915,6 +916,234 @@ describe('Test builtin primitives', function () {
915
916
  });
916
917
  });
917
918
  });
919
+
920
+ describe('#removeFirstMatch', function () {
921
+ let uut;
922
+
923
+ beforeEach(function () {
924
+ uut = lookupBuiltinTransform('removeFirstMatch');
925
+ });
926
+
927
+ describe('core functionality', function () {
928
+ it('["xABBBy ABz", "AB+"] -> "xy ABz"', function () {
929
+ expect(uut('xABBBy ABz', 'AB+')).to.eql('xy ABz');
930
+ });
931
+
932
+ it('should return the text unchanged if there is no match', function () {
933
+ expect(uut('some text', 'XYZ')).to.eql('some text');
934
+ });
935
+ });
936
+
937
+ describe('robustness on untrusted data', function () {
938
+ it('should fail if input is not [string, string] (more parameters are ignored)', function () {
939
+ expect(() => uut()).to.throw();
940
+ expect(() => uut('too few args')).to.throw();
941
+ expect(() => uut({ wrong: 'types' }, 42)).to.throw();
942
+ });
943
+
944
+ it('should not fail on arbitrary text and patterns', function () {
945
+ fc.assert(
946
+ fc.property(fc.fullUnicodeString(), fc.string(), (text, pattern) => {
947
+ expect(uut(text, pattern)).to.be.a('string');
948
+ }),
949
+ );
950
+ });
951
+
952
+ it('should only remove characters from the text (the result never grows)', function () {
953
+ fc.assert(
954
+ fc.property(fc.fullUnicodeString(), fc.string(), (text, pattern) => {
955
+ const subsequence = uut(text, pattern);
956
+ expect(isSubSequence({ sequence: text, subsequence })).to.be.true;
957
+ }),
958
+ );
959
+ });
960
+ });
961
+ });
962
+
963
+ describe('#removeAllMatches', function () {
964
+ let uut;
965
+
966
+ beforeEach(function () {
967
+ uut = lookupBuiltinTransform('removeAllMatches');
968
+ });
969
+
970
+ describe('core functionality', function () {
971
+ it('["xABBBy ABz", "AB+"] -> "xy z"', function () {
972
+ expect(uut('xABBBy ABz', 'AB+')).to.eql('xy z');
973
+ });
974
+
975
+ it('should return the text unchanged if there is no match', function () {
976
+ expect(uut('some text', 'XYZ')).to.eql('some text');
977
+ });
978
+ });
979
+
980
+ describe('robustness on untrusted data', function () {
981
+ it('should fail if input is not [string, string] (more parameters are ignored)', function () {
982
+ expect(() => uut()).to.throw();
983
+ expect(() => uut('too few args')).to.throw();
984
+ expect(() => uut({ wrong: 'types' }, 42)).to.throw();
985
+ });
986
+
987
+ it('should not fail on arbitrary text and patterns', function () {
988
+ fc.assert(
989
+ fc.property(fc.fullUnicodeString(), fc.string(), (text, pattern) => {
990
+ expect(uut(text, pattern)).to.be.a('string');
991
+ }),
992
+ );
993
+ });
994
+
995
+ it('should only remove characters from the text (the result never grows)', function () {
996
+ fc.assert(
997
+ fc.property(fc.fullUnicodeString(), fc.string(), (text, pattern) => {
998
+ const subsequence = uut(text, pattern);
999
+ expect(isSubSequence({ sequence: text, subsequence })).to.be.true;
1000
+ }),
1001
+ );
1002
+ });
1003
+ });
1004
+ });
1005
+
1006
+ describe('#selectFirstMatch', function () {
1007
+ let uut;
1008
+
1009
+ beforeEach(function () {
1010
+ uut = lookupBuiltinTransform('selectFirstMatch');
1011
+ });
1012
+
1013
+ describe('core functionality', function () {
1014
+ it('["xABBBy ABz", "AB+"] -> "ABBB"', function () {
1015
+ expect(uut('xABBBy ABz', 'AB+')).to.eql('ABBB');
1016
+ });
1017
+
1018
+ it('should return an empty string if there is no match', function () {
1019
+ expect(uut('some text', 'XYZ')).to.eql('');
1020
+ });
1021
+ });
1022
+
1023
+ describe('robustness on untrusted data', function () {
1024
+ it('should fail if input is not [string, string] (more parameters are ignored)', function () {
1025
+ expect(() => uut()).to.throw();
1026
+ expect(() => uut('too few args')).to.throw();
1027
+ expect(() => uut({ wrong: 'types' }, 42)).to.throw();
1028
+ });
1029
+
1030
+ it('should not fail on arbitrary text and patterns', function () {
1031
+ fc.assert(
1032
+ fc.property(fc.fullUnicodeString(), fc.string(), (text, pattern) => {
1033
+ expect(uut(text, pattern)).to.be.a('string');
1034
+ }),
1035
+ );
1036
+ });
1037
+
1038
+ it('should only remove characters from the text (the result never grows)', function () {
1039
+ fc.assert(
1040
+ fc.property(fc.fullUnicodeString(), fc.string(), (text, pattern) => {
1041
+ const subsequence = uut(text, pattern);
1042
+ expect(isSubSequence({ sequence: text, subsequence })).to.be.true;
1043
+ }),
1044
+ );
1045
+ });
1046
+ });
1047
+ });
1048
+
1049
+ describe('#selectAllMatches', function () {
1050
+ let uut;
1051
+
1052
+ beforeEach(function () {
1053
+ uut = lookupBuiltinTransform('selectAllMatches');
1054
+ });
1055
+
1056
+ describe('core functionality', function () {
1057
+ it('["xABBBy ABz", "AB+"] -> "ABBBAB"', function () {
1058
+ expect(uut('xABBBy ABz', 'AB+')).to.eql('ABBBAB');
1059
+ });
1060
+
1061
+ it('should return an empty string if there is no match', function () {
1062
+ expect(uut('some text', 'XYZ')).to.eql('');
1063
+ });
1064
+
1065
+ it('should support patterns that can match the empty string', function () {
1066
+ expect(uut('baaacaa', 'a*')).to.eql('aaaaa');
1067
+ });
1068
+
1069
+ it('should behave like a naive match(...).join("") implementation', function () {
1070
+ fc.assert(
1071
+ fc.property(fc.fullUnicodeString(), fc.string(), (text, pattern) => {
1072
+ let expected = '';
1073
+ try {
1074
+ expected = (text.match(new RegExp(pattern, 'g')) || []).join('');
1075
+ } catch (e) {
1076
+ // invalid regular expression: expect the value to be cleared
1077
+ }
1078
+ expect(uut(text, pattern)).to.eql(expected);
1079
+ }),
1080
+ );
1081
+ });
1082
+ });
1083
+
1084
+ describe('robustness on untrusted data', function () {
1085
+ it('should fail if input is not [string, string] (more parameters are ignored)', function () {
1086
+ expect(() => uut()).to.throw();
1087
+ expect(() => uut('too few args')).to.throw();
1088
+ expect(() => uut({ wrong: 'types' }, 42)).to.throw();
1089
+ });
1090
+
1091
+ it('should not fail on arbitrary text and patterns', function () {
1092
+ fc.assert(
1093
+ fc.property(fc.fullUnicodeString(), fc.string(), (text, pattern) => {
1094
+ expect(uut(text, pattern)).to.be.a('string');
1095
+ }),
1096
+ );
1097
+ });
1098
+
1099
+ it('should only remove characters from the text (the result never grows)', function () {
1100
+ fc.assert(
1101
+ fc.property(fc.fullUnicodeString(), fc.string(), (text, pattern) => {
1102
+ const subsequence = uut(text, pattern);
1103
+ expect(isSubSequence({ sequence: text, subsequence })).to.be.true;
1104
+ }),
1105
+ );
1106
+ });
1107
+ });
1108
+ });
1109
+
1110
+ describe('#maxLength', function () {
1111
+ let uut;
1112
+
1113
+ beforeEach(function () {
1114
+ uut = lookupBuiltinTransform('maxLength');
1115
+ });
1116
+
1117
+ it('should keep text up to the given size, but null out longer text', function () {
1118
+ expect(uut('foo', 3)).to.eql('foo');
1119
+ expect(uut('foo!', 3)).to.be.null;
1120
+ expect(uut('', 0)).to.eql('');
1121
+ });
1122
+
1123
+ it('should fail if input is not [string, integer]', function () {
1124
+ expect(() => uut()).to.throw();
1125
+ expect(() => uut('foo', 'not an int')).to.throw();
1126
+ });
1127
+ });
1128
+
1129
+ describe('#minLength', function () {
1130
+ let uut;
1131
+
1132
+ beforeEach(function () {
1133
+ uut = lookupBuiltinTransform('minLength');
1134
+ });
1135
+
1136
+ it('should keep text of at least the given size, but null out shorter text', function () {
1137
+ expect(uut('foo', 3)).to.eql('foo');
1138
+ expect(uut('fo', 3)).to.be.null;
1139
+ expect(uut('', 0)).to.eql('');
1140
+ });
1141
+
1142
+ it('should fail if input is not [string, integer]', function () {
1143
+ expect(() => uut()).to.throw();
1144
+ expect(() => uut('foo', 'not an int')).to.throw();
1145
+ });
1146
+ });
918
1147
  });
919
1148
 
920
1149
  describe('Patterns', function () {
@@ -10,7 +10,7 @@
10
10
  */
11
11
 
12
12
  import { expect } from 'chai';
13
- import SearchExtractor from '../src/search-extractor.js';
13
+ import SearchExtractor, { runTransforms } from '../src/search-extractor.js';
14
14
  import {
15
15
  allSupportedParsers,
16
16
  mockDocumentWith,
@@ -666,3 +666,21 @@ ${total} tests run: ${passed} passed, ${failed} failed (${ratio}% passed)
666
666
  });
667
667
  });
668
668
  });
669
+
670
+ describe('#runTransforms', function () {
671
+ it('should apply all steps if none of them returns null', function () {
672
+ expect(runTransforms(' foo•bar ', [['split', '•', 0], ['trim']])).to.eql(
673
+ 'foo',
674
+ );
675
+ });
676
+
677
+ it('should stop the chain without an error when a step returns null', function () {
678
+ expect(runTransforms('no separator here', [['split', '•', 0], ['trim']])).to
679
+ .be.null;
680
+ });
681
+
682
+ it('should return null for missing values', function () {
683
+ expect(runTransforms(null, [['trim']])).to.be.null;
684
+ expect(runTransforms(undefined, [['trim']])).to.be.null;
685
+ });
686
+ });
@@ -18,6 +18,15 @@ import chrome from 'sinon-chrome';
18
18
  chai.use(chaiAsPromised);
19
19
  chai.use(sinonChai);
20
20
 
21
+ // Node's own navigator.userAgent would fail the documentId support check.
22
+ Object.defineProperty(globalThis, 'navigator', {
23
+ value: {
24
+ userAgent:
25
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
26
+ },
27
+ configurable: true,
28
+ });
29
+
21
30
  // Fill in missing APIs if sinon-chrome did not provide them
22
31
  chrome.webRequest.OnBeforeRequestOptions ||= {
23
32
  blocking: 'blocking',