Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: modifier replacer for NetworkFilter.toString #3699

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 6 additions & 2 deletions packages/adblocker/src/filters/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1087,7 +1087,7 @@ export default class NetworkFilter implements IFilter {
* there are things which cannot be recovered though, like domains options
* of which only hashes are stored.
*/
public toString() {
public toString(modifierReplacer?: (modifier: string) => string) {
if (this.rawLine !== undefined) {
return this.rawLine;
}
Expand Down Expand Up @@ -1201,7 +1201,11 @@ export default class NetworkFilter implements IFilter {
}

if (options.length > 0) {
filter += `$${options.join(',')}`;
if (typeof modifierReplacer === 'function') {
filter += `$${options.map(modifierReplacer).join(',')}`;
} else {
filter += `$${options.join(',')}`;
}
}

return filter;
Expand Down
23 changes: 19 additions & 4 deletions packages/adblocker/test/parsing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,16 @@ const DEFAULT_NETWORK_FILTER = {

describe('Network filters', () => {
describe('toString', () => {
const checkToString = (line: string, expected: string, debug: boolean = false) => {
const checkToString = (
line: string,
expected: string,
debug: boolean = false,
modifierReplacer = (modifier: string) => modifier,
) => {
const parsed = NetworkFilter.parse(line, debug);
expect(parsed).not.to.be.null;
if (parsed !== null) {
expect(parsed.toString()).to.equal(expected);
expect(parsed.toString(modifierReplacer)).to.equal(expected);
}
};

Expand Down Expand Up @@ -178,6 +183,16 @@ describe('Network filters', () => {
true,
);
});

it('pprint longer form of modifiers', () => {
checkToString('||foo.com^$3p', '||foo.com^$third-party', false, (modifier) => {
if (modifier === '3p') {
return 'third-party';
}

return modifier;
});
});
});

it('parses pattern', () => {
Expand Down Expand Up @@ -1365,9 +1380,9 @@ describe('Network filters', () => {
[new Uint32Array([NORMALIZED_TYPE_TOKEN.document])],
],
['@@/wp-content/themes/$script', [hashStrings(['content'])]],
]) {
] as const) {
it(`get tokens for ${filter}`, () => {
const parsed = NetworkFilter.parse(filter as string, true);
const parsed = NetworkFilter.parse(filter, true);
expect(parsed).not.to.be.null;
if (parsed !== null) {
expect(parsed.getTokens()).to.eql(regexTokens);
Expand Down