-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
html.ts
32 lines (24 loc) · 946 Bytes
/
html.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
31
32
import RewritingStream from 'parse5-html-rewriting-stream'
import * as htmlRules from './html-rules'
import type stream from 'stream'
import type { DeferSourceMapRewriteFn } from './js'
// the HTML rewriter passes inline JS to the JS rewriter, hence
// the lack of basic `rewriteHtml` or `HtmlRewriter` exports here
export function HtmlJsRewriter (url: string, deferSourceMapRewrite?: DeferSourceMapRewriteFn): stream.Transform {
const rewriter = new RewritingStream()
htmlRules.install(url, rewriter, deferSourceMapRewrite)
return rewriter
}
export function rewriteHtmlJs (url: string, html: string, deferSourceMapRewrite?: DeferSourceMapRewriteFn): Promise<string> {
let out = ''
const rewriter = HtmlJsRewriter(url, deferSourceMapRewrite)
rewriter.on('data', (chunk) => {
out += chunk
})
rewriter.end(html)
return new Promise<string>((resolve) => {
rewriter.on('end', () => {
resolve(out)
})
})
}