Improve `trusted-replace-outbound-text` scriptlet

Add vararg `condition, [pattern]`.
This commit is contained in:
Raymond Hill 2024-04-02 11:04:27 -04:00
parent f9408415a5
commit c6e99f8490
No known key found for this signature in database
GPG Key ID: 25E1490B761470C2
1 changed files with 15 additions and 9 deletions

View File

@ -4717,22 +4717,28 @@ builtinScriptlets.push({
function trustedReplaceOutboundText( function trustedReplaceOutboundText(
propChain = '', propChain = '',
pattern = '', pattern = '',
replacement = '' replacement = '',
...args
) { ) {
if ( propChain === '' ) { return; } if ( propChain === '' ) { return; }
const safe = safeSelf(); const safe = safeSelf();
const logPrefix = safe.makeLogPrefix('trusted-replace-outbound-text', propChain, pattern, replacement); const logPrefix = safe.makeLogPrefix('trusted-replace-outbound-text', propChain, pattern, replacement, ...args);
const rePattern = safe.patternToRegex(pattern); const rePattern = safe.patternToRegex(pattern);
const extraArgs = safe.getExtraArgs(args);
const reCondition = safe.patternToRegex(extraArgs.condition || '');
const reflector = proxyApplyFn(propChain, function(...args) { const reflector = proxyApplyFn(propChain, function(...args) {
const textBefore = reflector(...args); const textBefore = reflector(...args);
const textAfter = pattern !== '' if ( pattern === '' ) {
? textBefore.replace(rePattern, replacement) safe.uboLog(logPrefix, 'Outbound text:\n', textBefore);
: textBefore; return textBefore;
if ( textAfter !== textBefore ) {
safe.uboLog(logPrefix, 'Matched and replaced');
} }
if ( safe.logLevel > 1 || pattern === '' ) { reCondition.lastIndex = 0;
safe.uboLog(logPrefix, 'Outbound text:\n', textAfter); if ( reCondition.test(textBefore) === false ) { return textBefore; }
const textAfter = textBefore.replace(rePattern, replacement);
if ( textAfter === textBefore ) { return textBefore; }
safe.uboLog(logPrefix, 'Matched and replaced');
if ( safe.logLevel > 1 ) {
safe.uboLog(logPrefix, 'Modified outbound text:\n', textAfter);
} }
return textAfter; return textAfter;
}); });