-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathmake-rulesets.js
1444 lines (1289 loc) · 47.8 KB
/
make-rulesets.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
uBlock Origin - a comprehensive, efficient content blocker
Copyright (C) 2022-present Raymond Hill
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
Home: https://github.com/gorhill/uBlock
*/
import * as makeScriptlet from './make-scriptlets.js';
import * as sfp from './js/static-filtering-parser.js';
import { createHash, randomBytes } from 'crypto';
import { dnrRulesetFromRawLists } from './js/static-dnr-filtering.js';
import fs from 'fs/promises';
import https from 'https';
import path from 'path';
import process from 'process';
import redirectResourcesMap from './js/redirect-resources.js';
import { safeReplace } from './safe-replace.js';
/******************************************************************************/
const commandLineArgs = (( ) => {
const args = new Map();
let name, value;
for ( const arg of process.argv.slice(2) ) {
const pos = arg.indexOf('=');
if ( pos === -1 ) {
name = arg;
value = '';
} else {
name = arg.slice(0, pos);
value = arg.slice(pos+1);
}
args.set(name, value);
}
return args;
})();
const platform = commandLineArgs.get('platform') || 'chromium';
const outputDir = commandLineArgs.get('output') || '.';
const cacheDir = `${outputDir}/../mv3-data`;
const rulesetDir = `${outputDir}/rulesets`;
const scriptletDir = `${rulesetDir}/scripting`;
const env = [
platform,
'mv3',
'ublock',
'ubol',
'user_stylesheet',
];
if ( platform !== 'firefox' ) {
env.push('native_css_has');
}
/******************************************************************************/
const jsonSetMapReplacer = (k, v) => {
if ( v instanceof Set || v instanceof Map ) {
if ( v.size === 0 ) { return; }
return Array.from(v);
}
return v;
};
const uidint32 = (s) => {
const h = createHash('sha256').update(s).digest('hex').slice(0,8);
return parseInt(h,16) & 0x7FFFFFFF;
};
/******************************************************************************/
const stdOutput = [];
const log = (text, silent = false) => {
stdOutput.push(text);
if ( silent === false ) {
console.log(text);
}
};
/******************************************************************************/
const urlToFileName = url => {
return url
.replace(/^https?:\/\//, '')
.replace(/\//g, '_');
};
const fetchText = (url, cacheDir) => {
return new Promise((resolve, reject) => {
const fname = urlToFileName(url);
fs.readFile(`${cacheDir}/${fname}`, { encoding: 'utf8' }).then(content => {
log(`\tFetched local ${url}`);
resolve({ url, content });
}).catch(( ) => {
log(`\tFetching remote ${url}`);
https.get(url, response => {
const data = [];
response.on('data', chunk => {
data.push(chunk.toString());
});
response.on('end', ( ) => {
const content = data.join('');
try {
writeFile(`${cacheDir}/${fname}`, content);
} catch (ex) {
}
resolve({ url, content });
});
}).on('error', error => {
reject(error);
});
});
});
};
/******************************************************************************/
const writeFile = async (fname, data) => {
const dir = path.dirname(fname);
await fs.mkdir(dir, { recursive: true });
const promise = fs.writeFile(fname, data);
writeOps.push(promise);
return promise;
};
const copyFile = async (from, to) => {
const dir = path.dirname(to);
await fs.mkdir(dir, { recursive: true });
const promise = fs.copyFile(from, to);
writeOps.push(promise);
return promise;
};
const writeOps = [];
/******************************************************************************/
const ruleResources = [];
const rulesetDetails = [];
const scriptletStats = new Map();
const genericDetails = new Map();
const requiredRedirectResources = new Set();
/******************************************************************************/
async function fetchList(assetDetails) {
// Remember fetched URLs
const fetchedURLs = new Set();
// Fetch list and expand `!#include` directives
let parts = assetDetails.urls.map(url => ({ url }));
while ( parts.every(v => typeof v === 'string') === false ) {
const newParts = [];
for ( const part of parts ) {
if ( typeof part === 'string' ) {
newParts.push(part);
continue;
}
if ( fetchedURLs.has(part.url) ) {
newParts.push('');
continue;
}
fetchedURLs.add(part.url);
if ( part.url.startsWith('https://ublockorigin.github.io/uAssets/filters/') ) {
newParts.push(`!#trusted on ${assetDetails.secret}`);
}
newParts.push(
fetchText(part.url, cacheDir).then(details => {
const { url } = details;
const content = details.content.trim();
if ( typeof content === 'string' && content !== '' ) {
if (
content.startsWith('<') === false ||
content.endsWith('>') === false
) {
return { url, content };
}
}
log(`No valid content for ${details.name}`);
return { url, content: '' };
})
);
newParts.push(`!#trusted off ${assetDetails.secret}`);
}
parts = await Promise.all(newParts);
parts = sfp.utils.preparser.expandIncludes(parts, env);
}
const text = parts.join('\n');
if ( text === '' ) {
log('No filterset found');
}
return text;
}
/******************************************************************************/
const isUnsupported = rule =>
rule._error !== undefined;
const isRegex = rule =>
rule.condition !== undefined &&
rule.condition.regexFilter !== undefined;
const isRedirect = rule => {
if ( isUnsupported(rule) ) { return false; }
if ( rule.action.type !== 'redirect' ) { return false; }
if ( rule.action.redirect?.extensionPath !== undefined ) { return true; }
if ( rule.action.redirect?.transform?.path !== undefined ) { return true; }
return false;
};
const isModifyHeaders = rule =>
isUnsupported(rule) === false &&
rule.action.type === 'modifyHeaders';
const isRemoveparam = rule =>
isUnsupported(rule) === false &&
rule.action.type === 'redirect' &&
rule.action.redirect.transform !== undefined;
const isSafe = rule =>
isUnsupported(rule) === false &&
rule.action !== undefined && (
rule.action.type === 'block' ||
rule.action.type === 'allow' ||
rule.action.type === 'allowAllRequests'
);
const isURLSkip = rule =>
isUnsupported(rule) === false &&
rule.action !== undefined &&
rule.action.type === 'urlskip';
/******************************************************************************/
// Two distinct hostnames:
// www.example.com
// example.com
// Can be reduced to a single one:
// example.com
// Since if example.com matches, then www.example.com (or any other subdomain
// of example.com) will always match.
function pruneHostnameArray(hostnames) {
const rootMap = new Map();
for ( const hostname of hostnames ) {
const labels = hostname.split('.');
let currentMap = rootMap;
let i = labels.length;
while ( i-- ) {
const label = labels[i];
let nextMap = currentMap.get(label);
if ( nextMap === null ) { break; }
if ( nextMap === undefined ) {
if ( i === 0 ) {
currentMap.set(label, (nextMap = null));
} else {
currentMap.set(label, (nextMap = new Map()));
}
} else if ( i === 0 ) {
currentMap.set(label, null);
}
currentMap = nextMap;
}
}
const assemble = (currentMap, currentHostname, out) => {
for ( const [ label, nextMap ] of currentMap ) {
const nextHostname = currentHostname === ''
? label
: `${label}.${currentHostname}`;
if ( nextMap === null ) {
out.push(nextHostname);
} else {
assemble(nextMap, nextHostname, out);
}
}
return out;
};
return assemble(rootMap, '', []);
}
/*******************************************************************************
*
* For large rulesets, one rule per line for compromise between size and
* readability. This also means that the number of lines in resulting file
* representative of the number of rules in the ruleset.
*
* */
function toJSONRuleset(ruleset) {
const replacer = (k, v) => {
if ( k.startsWith('_') ) { return; }
if ( Array.isArray(v) ) {
return v.sort();
}
if ( v instanceof Object ) {
const sorted = {};
for ( const kk of Object.keys(v).sort() ) {
sorted[kk] = v[kk];
}
return sorted;
}
return v;
};
const indent = ruleset.length > 10 ? undefined : 1;
const out = [];
for ( const rule of ruleset ) {
out.push(JSON.stringify(rule, replacer, indent));
}
return `[\n${out.join(',\n')}\n]\n`;
}
/******************************************************************************/
async function processNetworkFilters(assetDetails, network) {
const { ruleset: rules } = network;
log(`Input filter count: ${network.filterCount}`);
log(`\tAccepted filter count: ${network.acceptedFilterCount}`);
log(`\tRejected filter count: ${network.rejectedFilterCount}`);
log(`Output rule count: ${rules.length}`);
// Minimize requestDomains arrays
for ( const rule of rules ) {
const condition = rule.condition;
if ( condition === undefined ) { continue; }
const requestDomains = condition.requestDomains;
if ( requestDomains === undefined ) { continue; }
const beforeCount = requestDomains.length;
condition.requestDomains = pruneHostnameArray(requestDomains);
const afterCount = condition.requestDomains.length;
if ( afterCount !== beforeCount ) {
log(`\tPruning requestDomains: from ${beforeCount} to ${afterCount}`);
}
}
// Add native DNR ruleset if present
if ( assetDetails.dnrURL ) {
const result = await fetchText(assetDetails.dnrURL, cacheDir);
for ( const rule of JSON.parse(result.content) ) {
rules.push(rule);
}
}
const plainGood = rules.filter(rule => isSafe(rule) && isRegex(rule) === false);
log(`\tPlain good: ${plainGood.length}`);
log(plainGood
.filter(rule => Array.isArray(rule._warning))
.map(rule => rule._warning.map(v => `\t\t${v}`))
.join('\n'), true
);
const regexes = rules.filter(rule => isSafe(rule) && isRegex(rule));
log(`\tMaybe good (regexes): ${regexes.length}`);
const redirects = rules.filter(rule =>
isUnsupported(rule) === false &&
isRedirect(rule)
);
redirects.forEach(rule => {
if ( rule.action.redirect.extensionPath === undefined ) { return; }
requiredRedirectResources.add(
rule.action.redirect.extensionPath.replace(/^\/+/, '')
);
});
log(`\tredirect=: ${redirects.length}`);
const removeparamsGood = rules.filter(rule =>
isUnsupported(rule) === false && isRemoveparam(rule)
);
const removeparamsBad = rules.filter(rule =>
isUnsupported(rule) && isRemoveparam(rule)
);
log(`\tremoveparams= (accepted/discarded): ${removeparamsGood.length}/${removeparamsBad.length}`);
const modifyHeaders = rules.filter(rule =>
isUnsupported(rule) === false &&
isModifyHeaders(rule)
);
log(`\tmodifyHeaders=: ${modifyHeaders.length}`);
const urlskips = rules.filter(rule => isURLSkip(rule)).filter(rule =>
rule.__modifierAction === 0 &&
rule.condition &&
rule.condition.regexFilter &&
rule.condition.resourceTypes &&
rule.condition.resourceTypes.includes('main_frame')
).map(rule => {
const steps = rule.__modifierValue;
return {
re: rule.condition.regexFilter,
c: rule.condition.isUrlFilterCaseSensitive,
steps: steps.includes(' ') && steps.split(/ +/) || [ steps ],
};
});
log(`\turlskip=: ${urlskips.length}`);
const bad = rules.filter(rule =>
isUnsupported(rule)
);
log(`\tUnsupported: ${bad.length}`);
log(bad.map(rule => rule._error.map(v => `\t\t${v}`)).join('\n'), true);
writeFile(
`${rulesetDir}/main/${assetDetails.id}.json`,
toJSONRuleset(plainGood)
);
if ( regexes.length !== 0 ) {
writeFile(
`${rulesetDir}/regex/${assetDetails.id}.json`,
toJSONRuleset(regexes)
);
}
if ( removeparamsGood.length !== 0 ) {
writeFile(
`${rulesetDir}/removeparam/${assetDetails.id}.json`,
toJSONRuleset(removeparamsGood)
);
}
if ( redirects.length !== 0 ) {
writeFile(
`${rulesetDir}/redirect/${assetDetails.id}.json`,
toJSONRuleset(redirects)
);
}
if ( modifyHeaders.length !== 0 ) {
writeFile(
`${rulesetDir}/modify-headers/${assetDetails.id}.json`,
toJSONRuleset(modifyHeaders)
);
}
const strictBlocked = new Set();
for ( const rule of plainGood ) {
if ( rule.action.type !== 'block' ) { continue; }
if ( rule.condition.domainType ) { continue; }
if ( rule.condition.regexFilter ) { continue; }
if ( rule.condition.urlFilter ) { continue; }
if ( rule.condition.requestMethods ) { continue; }
if ( rule.condition.excludedRequestMethods ) { continue; }
if ( rule.condition.resourceTypes ) { continue; }
if ( rule.condition.excludedResourceTypes ) { continue; }
if ( rule.condition.responseHeaders ) { continue; }
if ( rule.condition.excludedResponseHeaders ) { continue; }
if ( rule.condition.initiatorDomains ) { continue; }
if ( rule.condition.excludedInitiatorDomains ) { continue; }
if ( rule.condition.requestDomains === undefined ) { continue; }
if ( rule.condition.excludedRequestDomains ) { continue; }
for ( const hn of rule.condition.requestDomains ) {
strictBlocked.add(hn);
}
}
if ( strictBlocked.size !== 0 ) {
writeFile(
`${rulesetDir}/strictblock/${assetDetails.id}.json`,
toJSONRuleset(Array.from(strictBlocked))
);
}
if ( urlskips.length !== 0 ) {
writeFile(
`${rulesetDir}/urlskip/${assetDetails.id}.json`,
JSON.stringify(urlskips, null, 1)
);
}
return {
total: rules.length,
plain: plainGood.length,
discarded: removeparamsBad.length,
rejected: bad.length,
regex: regexes.length,
removeparam: removeparamsGood.length,
redirect: redirects.length,
modifyHeaders: modifyHeaders.length,
strictblock: strictBlocked.size,
urlskip: urlskips.length,
};
}
/******************************************************************************/
// TODO: unify css/scriptlet processing code since now css styles are
// injected using scriptlet injection.
// Load all available scriptlets into a key-val map, where the key is the
// scriptlet token, and val is the whole content of the file.
let scriptletsMapPromise;
function loadAllSourceScriptlets() {
if ( scriptletsMapPromise !== undefined ) {
return scriptletsMapPromise;
}
scriptletsMapPromise = fs.readdir('./scriptlets').then(files => {
const readTemplateFile = file =>
fs.readFile(`./scriptlets/${file}`, { encoding: 'utf8' })
.then(text => ({ file, text }));
const readPromises = [];
for ( const file of files ) {
readPromises.push(readTemplateFile(file));
}
return Promise.all(readPromises).then(results => {
const originalScriptletMap = new Map();
for ( const details of results ) {
originalScriptletMap.set(
details.file.replace('.template.js', '')
.replace('.template.css', ''),
details.text
);
}
return originalScriptletMap;
});
});
return scriptletsMapPromise;
}
/******************************************************************************/
async function processGenericCosmeticFilters(assetDetails, bucketsMap, exceptionSet) {
if ( bucketsMap === undefined ) { return 0; }
if ( exceptionSet ) {
for ( const [ hash, selectors ] of bucketsMap ) {
let i = selectors.length;
while ( i-- ) {
const selector = selectors[i];
if ( exceptionSet.has(selector) === false ) { continue; }
selectors.splice(i, 1);
//log(`\tRemoving excepted generic filter ##${selector}`);
}
if ( selectors.length === 0 ) {
bucketsMap.delete(hash);
}
}
}
if ( bucketsMap.size === 0 ) { return 0; }
const bucketsList = Array.from(bucketsMap);
const count = bucketsList.reduce((a, v) => a += v[1].length, 0);
if ( count === 0 ) { return 0; }
const selectorLists = bucketsList.map(v => [ v[0], v[1].join(',') ]);
const originalScriptletMap = await loadAllSourceScriptlets();
let patchedScriptlet = originalScriptletMap.get('css-generic').replace(
'$rulesetId$',
assetDetails.id
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$genericSelectorMap\$/,
`${JSON.stringify(selectorLists, scriptletJsonReplacer)}`
);
writeFile(
`${scriptletDir}/generic/${assetDetails.id}.js`,
patchedScriptlet
);
log(`CSS-generic: ${count} plain CSS selectors`);
return count;
}
/******************************************************************************/
async function processGenericHighCosmeticFilters(assetDetails, selectorSet, exceptionSet) {
if ( selectorSet === undefined ) { return 0; }
if ( exceptionSet ) {
for ( const selector of selectorSet ) {
if ( exceptionSet.has(selector) === false ) { continue; }
selectorSet.delete(selector);
//log(`\tRemoving excepted generic filter ##${selector}`);
}
}
if ( selectorSet.size === 0 ) { return 0; }
const selectorLists = Array.from(selectorSet).sort().join(',\n');
const originalScriptletMap = await loadAllSourceScriptlets();
let patchedScriptlet = originalScriptletMap.get('css-generichigh').replace(
'$rulesetId$',
assetDetails.id
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\$selectorList\$/,
selectorLists
);
writeFile(
`${scriptletDir}/generichigh/${assetDetails.id}.css`,
patchedScriptlet
);
log(`CSS-generic-high: ${selectorSet.size} plain CSS selectors`);
return selectorSet.size;
}
/******************************************************************************/
// This merges selectors which are used by the same hostnames
function groupSelectorsByHostnames(mapin) {
if ( mapin === undefined ) { return []; }
const merged = new Map();
for ( const [ selector, details ] of mapin ) {
if ( details.rejected ) { continue; }
const json = JSON.stringify(details);
let entries = merged.get(json);
if ( entries === undefined ) {
entries = new Set();
merged.set(json, entries);
}
entries.add(selector);
}
const out = [];
for ( const [ json, entries ] of merged ) {
const details = JSON.parse(json);
details.selectors = Array.from(entries).sort();
out.push(details);
}
return out;
}
// This merges hostnames which have the same set of selectors.
//
// Also, we sort the hostnames to increase likelihood that selector with
// same hostnames will end up in same generated scriptlet.
function groupHostnamesBySelectors(arrayin) {
const contentMap = new Map();
for ( const entry of arrayin ) {
const id = uidint32(JSON.stringify(entry.selectors));
let details = contentMap.get(id);
if ( details === undefined ) {
details = { a: entry.selectors };
contentMap.set(id, details);
}
if ( entry.matches !== undefined ) {
if ( details.y === undefined ) {
details.y = new Set();
}
for ( const hn of entry.matches ) {
details.y.add(hn);
}
}
if ( entry.excludeMatches !== undefined ) {
if ( details.n === undefined ) {
details.n = new Set();
}
for ( const hn of entry.excludeMatches ) {
details.n.add(hn);
}
}
}
const out = Array.from(contentMap).map(a => [
a[0], {
a: a[1].a,
y: a[1].y ? Array.from(a[1].y) : undefined,
n: a[1].n ? Array.from(a[1].n) : undefined,
}
]);
return out;
}
const scriptletHostnameToIdMap = (hostnames, id, map) => {
for ( const hn of hostnames ) {
const existing = map.get(hn);
if ( existing === undefined ) {
map.set(hn, id);
} else if ( Array.isArray(existing) ) {
existing.push(id);
} else {
map.set(hn, [ existing, id ]);
}
}
};
const scriptletJsonReplacer = (k, v) => {
if ( k === 'n' ) {
if ( v === undefined || v.size === 0 ) { return; }
return Array.from(v);
}
if ( v instanceof Set || v instanceof Map ) {
if ( v.size === 0 ) { return; }
return Array.from(v);
}
return v;
};
/******************************************************************************/
function argsMap2List(argsMap, hostnamesMap) {
const argsList = [];
const indexMap = new Map();
for ( const [ id, details ] of argsMap ) {
indexMap.set(id, argsList.length);
argsList.push(details);
}
for ( const [ hn, ids ] of hostnamesMap ) {
if ( typeof ids === 'number' ) {
hostnamesMap.set(hn, indexMap.get(ids));
continue;
}
for ( let i = 0; i < ids.length; i++ ) {
ids[i] = indexMap.get(ids[i]);
}
}
return argsList;
}
/******************************************************************************/
async function processCosmeticFilters(assetDetails, mapin) {
if ( mapin === undefined ) { return 0; }
if ( mapin.size === 0 ) { return 0; }
const domainBasedEntries = groupHostnamesBySelectors(
groupSelectorsByHostnames(mapin)
);
// We do not want more than n CSS files per subscription, so we will
// group multiple unrelated selectors in the same file, and distinct
// css declarations will be injected programmatically according to the
// hostname of the current document.
//
// The cosmetic filters will be injected programmatically as content
// script and the decisions to activate the cosmetic filters will be
// done at injection time according to the document's hostname.
const generatedFiles = [];
const argsMap = domainBasedEntries.map(entry => [
entry[0],
{
a: entry[1].a ? entry[1].a.join(',\n') : undefined,
n: entry[1].n
}
]);
const hostnamesMap = new Map();
for ( const [ id, details ] of domainBasedEntries ) {
if ( details.y === undefined ) { continue; }
scriptletHostnameToIdMap(details.y, id, hostnamesMap);
}
const argsList = argsMap2List(argsMap, hostnamesMap);
const entitiesMap = new Map();
for ( const [ hn, details ] of hostnamesMap ) {
if ( hn.endsWith('.*') === false ) { continue; }
hostnamesMap.delete(hn);
entitiesMap.set(hn.slice(0, -2), details);
}
// Extract exceptions from argsList, simplify argsList entries
const exceptionsMap = new Map();
for ( let i = 0; i < argsList.length; i++ ) {
const details = argsList[i];
if ( details.n ) {
for ( const hn of details.n ) {
if ( exceptionsMap.has(hn) === false ) {
exceptionsMap.set(hn, []);
}
exceptionsMap.get(hn).push(i);
}
}
argsList[i] = details.a;
}
const originalScriptletMap = await loadAllSourceScriptlets();
let patchedScriptlet = originalScriptletMap.get('css-specific').replace(
'$rulesetId$',
assetDetails.id
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$argsList\$/,
`${JSON.stringify(argsList, scriptletJsonReplacer)}`
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$hostnamesMap\$/,
`${JSON.stringify(hostnamesMap, scriptletJsonReplacer)}`
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$entitiesMap\$/,
`${JSON.stringify(entitiesMap, scriptletJsonReplacer)}`
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$exceptionsMap\$/,
`${JSON.stringify(exceptionsMap, scriptletJsonReplacer)}`
);
writeFile(`${scriptletDir}/specific/${assetDetails.id}.js`, patchedScriptlet);
generatedFiles.push(`${assetDetails.id}`);
if ( generatedFiles.length !== 0 ) {
log(`CSS-specific: ${mapin.size} distinct filters`);
log(`\tCombined into ${hostnamesMap.size} distinct hostnames`);
log(`\tCombined into ${entitiesMap.size} distinct entities`);
}
return hostnamesMap.size + entitiesMap.size;
}
/******************************************************************************/
async function processDeclarativeCosmeticFilters(assetDetails, mapin) {
if ( mapin === undefined ) { return 0; }
if ( mapin.size === 0 ) { return 0; }
// Distinguish declarative-compiled-as-procedural from actual procedural.
const declaratives = new Map();
mapin.forEach((details, jsonSelector) => {
const selector = JSON.parse(jsonSelector);
if ( selector.cssable !== true ) { return; }
selector.cssable = undefined;
declaratives.set(JSON.stringify(selector), details);
});
if ( declaratives.size === 0 ) { return 0; }
const contentArray = groupHostnamesBySelectors(
groupSelectorsByHostnames(declaratives)
);
const argsMap = contentArray.map(entry => [
entry[0],
{
a: entry[1].a,
n: entry[1].n,
}
]);
const hostnamesMap = new Map();
for ( const [ id, details ] of contentArray ) {
if ( details.y === undefined ) { continue; }
scriptletHostnameToIdMap(details.y, id, hostnamesMap);
}
const argsList = argsMap2List(argsMap, hostnamesMap);
const entitiesMap = new Map();
for ( const [ hn, details ] of hostnamesMap ) {
if ( hn.endsWith('.*') === false ) { continue; }
hostnamesMap.delete(hn);
entitiesMap.set(hn.slice(0, -2), details);
}
// Extract exceptions from argsList, simplify argsList entries
const exceptionsMap = new Map();
for ( let i = 0; i < argsList.length; i++ ) {
const details = argsList[i];
if ( details.n ) {
for ( const hn of details.n ) {
if ( exceptionsMap.has(hn) === false ) {
exceptionsMap.set(hn, []);
}
exceptionsMap.get(hn).push(i);
}
}
argsList[i] = details.a;
}
const originalScriptletMap = await loadAllSourceScriptlets();
let patchedScriptlet = originalScriptletMap.get('css-declarative').replace(
'$rulesetId$',
assetDetails.id
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$argsList\$/,
`${JSON.stringify(argsList, scriptletJsonReplacer)}`
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$hostnamesMap\$/,
`${JSON.stringify(hostnamesMap, scriptletJsonReplacer)}`
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$entitiesMap\$/,
`${JSON.stringify(entitiesMap, scriptletJsonReplacer)}`
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$exceptionsMap\$/,
`${JSON.stringify(exceptionsMap, scriptletJsonReplacer)}`
);
writeFile(`${scriptletDir}/declarative/${assetDetails.id}.js`, patchedScriptlet);
if ( contentArray.length !== 0 ) {
log(`CSS-declarative: ${declaratives.size} distinct filters`);
log(`\tCombined into ${hostnamesMap.size} distinct hostnames`);
log(`\tCombined into ${entitiesMap.size} distinct entities`);
}
return hostnamesMap.size + entitiesMap.size;
}
/******************************************************************************/
async function processProceduralCosmeticFilters(assetDetails, mapin) {
if ( mapin === undefined ) { return 0; }
if ( mapin.size === 0 ) { return 0; }
// Distinguish declarative-compiled-as-procedural from actual procedural.
const procedurals = new Map();
mapin.forEach((details, jsonSelector) => {
const selector = JSON.parse(jsonSelector);
if ( selector.cssable ) { return; }
procedurals.set(jsonSelector, details);
});
if ( procedurals.size === 0 ) { return 0; }
const contentArray = groupHostnamesBySelectors(
groupSelectorsByHostnames(procedurals)
);
const argsMap = contentArray.map(entry => [
entry[0],
{
a: entry[1].a,
n: entry[1].n,
}
]);
const hostnamesMap = new Map();
for ( const [ id, details ] of contentArray ) {
if ( details.y === undefined ) { continue; }
scriptletHostnameToIdMap(details.y, id, hostnamesMap);
}
const argsList = argsMap2List(argsMap, hostnamesMap);
const entitiesMap = new Map();
for ( const [ hn, details ] of hostnamesMap ) {
if ( hn.endsWith('.*') === false ) { continue; }
hostnamesMap.delete(hn);
entitiesMap.set(hn.slice(0, -2), details);
}
// Extract exceptions from argsList, simplify argsList entries
const exceptionsMap = new Map();
for ( let i = 0; i < argsList.length; i++ ) {
const details = argsList[i];
if ( details.n ) {
for ( const hn of details.n ) {
if ( exceptionsMap.has(hn) === false ) {
exceptionsMap.set(hn, []);
}
exceptionsMap.get(hn).push(i);
}
}
argsList[i] = details.a;
}
const originalScriptletMap = await loadAllSourceScriptlets();
let patchedScriptlet = originalScriptletMap.get('css-procedural').replace(
'$rulesetId$',
assetDetails.id
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$argsList\$/,
`${JSON.stringify(argsList, scriptletJsonReplacer)}`
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$hostnamesMap\$/,
`${JSON.stringify(hostnamesMap, scriptletJsonReplacer)}`
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$entitiesMap\$/,
`${JSON.stringify(entitiesMap, scriptletJsonReplacer)}`
);
patchedScriptlet = safeReplace(patchedScriptlet,
/\bself\.\$exceptionsMap\$/,
`${JSON.stringify(exceptionsMap, scriptletJsonReplacer)}`
);
writeFile(`${scriptletDir}/procedural/${assetDetails.id}.js`, patchedScriptlet);
if ( contentArray.length !== 0 ) {
log(`Procedural-related distinct filters: ${procedurals.size} distinct combined selectors`);
log(`\tCombined into ${hostnamesMap.size} distinct hostnames`);
log(`\tCombined into ${entitiesMap.size} distinct entities`);
}
return hostnamesMap.size + entitiesMap.size;
}
/******************************************************************************/
async function processScriptletFilters(assetDetails, mapin) {
if ( mapin === undefined ) { return 0; }
if ( mapin.size === 0 ) { return 0; }
makeScriptlet.init();
for ( const details of mapin.values() ) {