Skip to content

Commit 578594b

Browse files
committed
Improve logging capabilities of json-prune scriptlet
Specifically: - Log entries as received by client code - Prettier and more readable console output - Ability to only log entries matching a specific needle As per internal discussion at <https://github.com/uBlockOrigin/uAssets>; limited logging capabilities of json-prune originally raised by <https://github.com/gwarser>.
1 parent 96343ec commit 578594b

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

assets/resources/scriptlets.js

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -249,16 +249,35 @@
249249

250250

251251
/// json-prune.js
252+
//
253+
// When no "prune paths" argument is provided, the scriptlet is
254+
// used for logging purpose and the "needle paths" argument is
255+
// used to filter logging output.
252256
(function() {
253-
const log = console.log.bind(console);
254257
const rawPrunePaths = '{{1}}';
255258
const rawNeedlePaths = '{{2}}';
256259
const prunePaths = rawPrunePaths !== '{{1}}' && rawPrunePaths !== ''
257260
? rawPrunePaths.split(/ +/)
258261
: [];
259-
const needlePaths = rawNeedlePaths !== '{{2}}' && rawNeedlePaths !== ''
260-
? rawNeedlePaths.split(/ +/)
261-
: [];
262+
let needlePaths;
263+
let log, reLogNeedle;
264+
if ( prunePaths.length !== 0 ) {
265+
needlePaths = prunePaths.length !== 0 &&
266+
rawNeedlePaths !== '{{2}}' && rawNeedlePaths !== ''
267+
? rawNeedlePaths.split(/ +/)
268+
: [];
269+
} else {
270+
log = console.log.bind(console);
271+
let needle;
272+
if ( rawNeedlePaths === '' || rawNeedlePaths === '{{2}}' ) {
273+
needle = '.?';
274+
} else if ( rawNeedlePaths.charAt(0) === '/' && rawNeedlePaths.slice(-1) === '/' ) {
275+
needle = rawNeedlePaths.slice(1, -1);
276+
} else {
277+
needle = rawNeedlePaths.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
278+
}
279+
reLogNeedle = new RegExp(needle);
280+
}
262281
const findOwner = function(root, path) {
263282
let owner = root;
264283
let chain = path;
@@ -286,8 +305,11 @@
286305
JSON.parse = new Proxy(JSON.parse, {
287306
apply: function() {
288307
const r = Reflect.apply(...arguments);
289-
if ( prunePaths.length === 0 ) {
290-
log(location.hostname, r);
308+
if ( log !== undefined ) {
309+
const json = JSON.stringify(r, null, 2);
310+
if ( reLogNeedle.test(json) ) {
311+
log(location.hostname, json);
312+
}
291313
return r;
292314
}
293315
if ( mustProcess(r) === false ) { return r; }

0 commit comments

Comments
 (0)