Skip to content

Commit

Permalink
Merge pull request #599 from brave/new-ubo-scriptlets-format
Browse files Browse the repository at this point in the history
Update code to support new uBlock Origin scriptlets format
  • Loading branch information
antonok-edm authored Jul 3, 2023
2 parents 2e49d11 + 19ec61b commit fc3f094
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
55 changes: 53 additions & 2 deletions lib/adBlockRustUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,65 @@ const lazyInit = (fn) => {
}
}

// Wraps new template scriptlets with the older "numbered template arg" format and any required dependency code
const wrapScriptletArgFormat = (fnString, dependencyPrelude) => `{
const args = ['{{1}}', '{{2}}', '{{3}}', '{{4}}', '{{5}}', '{{6}}', '{{7}}', '{{8}}', '{{9}}'];
let last_arg_index = 0;
for (const arg_index in args) {
if (args[arg_index] === '{{' + (Number(arg_index) + 1) + '}}') {
break;
}
last_arg_index += 1;
}
${dependencyPrelude}
(${fnString})(...args.slice(0, last_arg_index))
}`

const generateResources = lazyInit(async () => {
const { builtinScriptlets } = await import(path.join('..', uBlockScriptlets).toString())

const dependencyFns = builtinScriptlets.filter(s => s.name.endsWith('.fn'))
const dependencyMap = dependencyFns.reduce((map, entry) => {
map[entry.name] = entry
return map
}, {})

// ignore "trusted" scriptlets for now
const transformedUboBuiltins = builtinScriptlets.filter(s => !s.name.endsWith('.fn') && !s.requiresTrust).map(s => {
// Bundle dependencies wherever needed. This causes some small duplication but makes each scriptlet fully self-contained.
let dependencyPrelude = ''
const requiredDependencies = s.dependencies ?? []
for (const dep of requiredDependencies) {
for (const recursiveDep of dependencyMap[dep].dependencies ?? []) {
if (!requiredDependencies.includes(recursiveDep)) {
requiredDependencies.push(recursiveDep)
}
}
}
for (const dep of requiredDependencies.reverse()) {
const thisDepCode = dependencyMap[dep].fn.toString()
if (thisDepCode === undefined) {
throw new Error(`Couldn't find dependency ${dep}`)
}
dependencyPrelude += thisDepCode + '\n'
}
const content = Buffer.from(wrapScriptletArgFormat(s.fn.toString(), dependencyPrelude)).toString('base64')
return {
name: s.name,
aliases: s.aliases ?? [],
kind: { mime: 'application/javascript' },
content
}
})

const resourceData = uBlockResources(
uBlockWebAccessibleResources,
uBlockRedirectEngine,
uBlockScriptlets
uBlockRedirectEngine
)

const braveResources = await requestJSON(braveResourcesUrl)
resourceData.push(...braveResources)
resourceData.push(...transformedUboBuiltins)
return JSON.stringify(resourceData)
})

Expand Down
2 changes: 1 addition & 1 deletion submodules/uBlock
Submodule uBlock updated 635 files

0 comments on commit fc3f094

Please sign in to comment.