Skip to content

Commit 2fd86a6

Browse files
committed
Add json-prune.js scriptlet
The scriptlet will trap calls to JSON.parse, and if the result of the parsing is an Object, it will remove specified properties from the result before returning to the caller. Usage: ##+js(json-prune, arg1, [arg2]) Where: - arg1: a list of space-separated properties to remove - arg2: optional, a list of space-separated properties which must be all present for the pruning to occur Example: ##+js(json-prune, enabled, adpath config) A property in a list of properties can be a chain of properties, example: adpath.url.first
1 parent 4792e0e commit 2fd86a6

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

assets/resources/scriptlets.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,61 @@
236236
})();
237237

238238

239+
/// json-prune.js
240+
(function() {
241+
const log = console.log.bind(console);
242+
const rawPrunePaths = '{{1}}';
243+
const rawNeedlePaths = '{{2}}';
244+
const prunePaths = rawPrunePaths !== '{{1}}' && rawPrunePaths !== ''
245+
? rawPrunePaths.split(/ +/)
246+
: [];
247+
const needlePaths = rawNeedlePaths !== '{{2}}' && rawNeedlePaths !== ''
248+
? rawNeedlePaths.split(/ +/)
249+
: [];
250+
const findOwner = function(root, path) {
251+
let owner = root;
252+
let chain = path;
253+
for (;;) {
254+
if ( owner instanceof Object === false ) { return; }
255+
const pos = chain.indexOf('.');
256+
if ( pos === -1 ) {
257+
return owner.hasOwnProperty(chain)
258+
? [ owner, chain ]
259+
: undefined;
260+
}
261+
const prop = chain.slice(0, pos);
262+
if ( owner.hasOwnProperty(prop) === false ) { return; }
263+
owner = owner[prop];
264+
chain = chain.slice(pos + 1);
265+
}
266+
};
267+
const mustProcess = function(root) {
268+
for ( const needlePath of needlePaths ) {
269+
const details = findOwner(root, needlePath);
270+
if ( details === undefined ) { return false; }
271+
}
272+
return true;
273+
};
274+
JSON.parse = new Proxy(JSON.parse, {
275+
apply: function() {
276+
const r = Reflect.apply(...arguments);
277+
if ( prunePaths.length === 0 ) {
278+
log(location.hostname, r);
279+
return r;
280+
}
281+
if ( mustProcess(r) === false ) { return r; }
282+
for ( const path of prunePaths ) {
283+
const details = findOwner(r, path);
284+
if ( details !== undefined ) {
285+
delete details[0][details[1]];
286+
}
287+
}
288+
return r;
289+
},
290+
});
291+
})();
292+
293+
239294
// Imported from:
240295
// https://github.com/NanoAdblocker/NanoFilters/blob/1f3be7211bb0809c5106996f52564bf10c4525f7/NanoFiltersSource/NanoResources.txt#L126
241296
//

0 commit comments

Comments
 (0)