-
Notifications
You must be signed in to change notification settings - Fork 306
/
TrustedTypesPlugin.ts
30 lines (29 loc) · 1.21 KB
/
TrustedTypesPlugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import webpack, { type Compiler } from 'webpack'
const { RuntimeModule, Template } = webpack
class TrustedTypesRuntimeModule extends RuntimeModule {
constructor() {
super('trustedTypes', RuntimeModule.STAGE_TRIGGER)
}
override generate(): string {
const { compilation } = this
if (!compilation)
return Template.asString('/* TrustedTypesRuntimeModule skipped because compilation is undefined. */')
return Template.asString([
'if (typeof trustedTypes !== "undefined" && location.protocol.includes("extension") && !trustedTypes.defaultPolicy) {',
Template.indent([`trustedTypes.createPolicy('default', { createScriptURL: (string) => string });`]),
'}',
])
}
}
export class TrustedTypesPlugin {
apply(compiler: Compiler) {
compiler.hooks.compilation.tap('TrustedTypes', (compilation) => {
compilation.hooks.afterChunks.tap('TrustedTypes', (chunks) => {
for (const c of chunks) {
if (!c.hasEntryModule()) continue
compilation.addRuntimeModule(c, new TrustedTypesRuntimeModule(), compilation.chunkGraph)
}
})
})
}
}