|
1 | 1 | // The structure is from the MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/TransformStream
|
2 | 2 |
|
3 |
| -import type { CompressStream, BrotliWasmType } from 'brotli-wasm' |
| 3 | +import type { CompressStream, BrotliWasmType, DecompressStream } from 'brotli-wasm' |
4 | 4 |
|
5 | 5 | interface BrotliCompressTransformer extends Transformer<Uint8Array, Uint8Array> {
|
6 | 6 | brotliWasm: BrotliWasmType
|
@@ -49,3 +49,41 @@ export class BrotliCompressTransformStream extends TransformStream<Uint8Array, U
|
49 | 49 | super(brotliCompressTransformerBuilder(brotliWasm, outputSize, quality))
|
50 | 50 | }
|
51 | 51 | }
|
| 52 | + |
| 53 | +interface BrotliDecompressTransformer extends Transformer<Uint8Array, Uint8Array> { |
| 54 | + brotliWasm: BrotliWasmType |
| 55 | + outputSize: number |
| 56 | + stream: DecompressStream |
| 57 | +} |
| 58 | + |
| 59 | +const brotliDecompressTransformerBuilder: ( |
| 60 | + brotliWasm: BrotliWasmType, |
| 61 | + outputSize: number |
| 62 | +) => BrotliDecompressTransformer = (brotliWasm, outputSize) => ({ |
| 63 | + brotliWasm, |
| 64 | + outputSize, |
| 65 | + stream: new brotliWasm.DecompressStream(), |
| 66 | + start() {}, |
| 67 | + transform(chunk, controller) { |
| 68 | + do { |
| 69 | + const inputOffset = this.stream.last_input_offset() |
| 70 | + const input = chunk.slice(inputOffset) |
| 71 | + const output = this.stream.decompress(input, this.outputSize) |
| 72 | + controller.enqueue(output) |
| 73 | + } while (this.stream.result() === brotliWasm.BrotliStreamResult.NeedsMoreOutput) |
| 74 | + if ( |
| 75 | + this.stream.result() !== brotliWasm.BrotliStreamResult.NeedsMoreInput && |
| 76 | + this.stream.result() !== brotliWasm.BrotliStreamResult.ResultSuccess |
| 77 | + ) { |
| 78 | + controller.error(`Brotli decompression failed when transforming with error code ${this.stream.result()}`) |
| 79 | + } |
| 80 | + }, |
| 81 | + // Brotli decompression does not need flushing |
| 82 | + flush() {}, |
| 83 | +}) |
| 84 | + |
| 85 | +export class BrotliDecompressTransformStream extends TransformStream<Uint8Array, Uint8Array> { |
| 86 | + constructor(brotliWasm: BrotliWasmType, outputSize: number) { |
| 87 | + super(brotliDecompressTransformerBuilder(brotliWasm, outputSize)) |
| 88 | + } |
| 89 | +} |
0 commit comments