-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathhtml-rewriting-stream.ts
53 lines (50 loc) · 1.46 KB
/
html-rewriting-stream.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Readable, Writable } from 'stream';
export async function htmlRewritingStream(content: string): Promise<{
rewriter: import('parse5-html-rewriting-stream');
transformedContent: () => Promise<string>;
}> {
const chunks: Buffer[] = [];
const rewriter = new (await import('parse5-html-rewriting-stream')).default();
return {
rewriter,
transformedContent: () => {
return new Promise((resolve) => {
new Readable({
encoding: 'utf8',
read(): void {
this.push(Buffer.from(content));
this.push(null);
},
})
.pipe(rewriter)
.pipe(
new Writable({
write(
chunk: string | Buffer,
encoding: string | undefined,
callback: Function,
): void {
chunks.push(
typeof chunk === 'string'
? Buffer.from(chunk, encoding as BufferEncoding)
: chunk,
);
callback();
},
final(callback: (error?: Error) => void): void {
callback();
resolve(Buffer.concat(chunks).toString());
},
}),
);
});
},
};
}