@adguard/agtree
Version:
Tool set for working with adblock filter lists
90 lines (87 loc) • 3.08 kB
JavaScript
/*
* AGTree v4.1.1 (build date: Thu, 23 Apr 2026 09:15:37 GMT)
* (c) 2026 Adguard Software Ltd.
* Released under the MIT license
* https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme
*/
import { EMPTY } from '../utils/constants.js';
import { QuoteUtils } from '../utils/quotes.js';
import { isUndefined, isNull } from '../utils/type-guards.js';
/**
* @file Utility functions for working with scriptlet nodes.
*/
/**
* Get name of the scriptlet from the scriptlet node.
*
* @param scriptletNode Scriptlet node to get name of.
*
* @returns Name of the scriptlet.
*
* @throws If the scriptlet is empty.
*/
function getScriptletName(scriptletNode) {
if (scriptletNode.children.length === 0) {
throw new Error('Empty scriptlet');
}
return scriptletNode.children[0]?.value ?? EMPTY;
}
/**
* Transform the nth argument of the scriptlet node.
*
* @param scriptletNode Scriptlet node to transform argument of.
* @param index Index of the argument to transform (index 0 is the scriptlet name).
* @param transform Function to transform the argument.
*/
function transformNthScriptletArgument(scriptletNode, index, transform) {
const child = scriptletNode.children[index];
if (!isUndefined(child)) {
const transformed = transform(child?.value ?? null);
if (isNull(transformed)) {
// eslint-disable-next-line no-param-reassign
scriptletNode.children[index] = null;
return;
}
if (isNull(child)) {
// eslint-disable-next-line no-param-reassign
scriptletNode.children[index] = {
type: 'Value',
value: transformed,
};
return;
}
child.value = transformed;
}
}
/**
* Transform all arguments of the scriptlet node.
*
* @param scriptletNode Scriptlet node to transform arguments of.
* @param transform Function to transform the arguments.
*/
function transformAllScriptletArguments(scriptletNode, transform) {
for (let i = 0; i < scriptletNode.children.length; i += 1) {
transformNthScriptletArgument(scriptletNode, i, transform);
}
}
/**
* Set name of the scriptlet.
* Modifies input `scriptletNode` if needed.
*
* @param scriptletNode Scriptlet node to set name of.
* @param name Name to set.
*/
function setScriptletName(scriptletNode, name) {
transformNthScriptletArgument(scriptletNode, 0, () => name);
}
/**
* Set quote type of the scriptlet parameters.
*
* @param scriptletNode Scriptlet node to set quote type of.
* @param quoteType Preferred quote type.
*/
function setScriptletQuoteType(scriptletNode, quoteType) {
// null is a special value that means "no value", but we can't change its quote type,
// so we need to convert it to empty string
transformAllScriptletArguments(scriptletNode, (value) => QuoteUtils.setStringQuoteType(value ?? EMPTY, quoteType));
}
export { getScriptletName, setScriptletName, setScriptletQuoteType, transformAllScriptletArguments, transformNthScriptletArgument };