| 26 | } |
| 27 | |
| 28 | export class BundleBuilder { |
| 29 | private sectionLengths: Array<{ name: string; length: number }> = []; |
| 30 | private sections: CBORValue[] = []; |
| 31 | private responses: Uint8Array[][] = []; |
| 32 | private currentResponsesOffset = 0; |
| 33 | private compatAdapter: CompatAdapter; |
| 34 | |
| 35 | constructor(formatVersion: FormatVersion = DEFAULT_VERSION) { |
| 36 | if (!isApprovedVersion(formatVersion)) { |
| 37 | throw new Error(`Invalid webbundle format version`); |
| 38 | } |
| 39 | this.compatAdapter = this.createCompatAdapter(formatVersion); |
| 40 | } |
| 41 | |
| 42 | createBundle(): Uint8Array { |
| 43 | this.compatAdapter.onCreateBundle(); |
| 44 | |
| 45 | this.addSection('index', this.fixupIndex()); |
| 46 | this.addSection('responses', this.responses); |
| 47 | |
| 48 | const wbn = cborg.encode(this.createTopLevel()); |
| 49 | |
| 50 | // Fill in the length field. |
| 51 | const view = new DataView(wbn.buffer, wbn.byteOffset + wbn.length - 8); |
| 52 | view.setUint32(0, Math.floor(wbn.length / 0x100000000)); |
| 53 | view.setUint32(4, wbn.length & 0xffffffff); |
| 54 | return wbn; |
| 55 | } |
| 56 | |
| 57 | addExchange( |
| 58 | url: string, |
| 59 | status: number, |
| 60 | headers: Headers, |
| 61 | payload: Uint8Array | string |
| 62 | ): BundleBuilder { |
| 63 | validateExchangeURL(url); |
| 64 | if (typeof payload === 'string') { |
| 65 | payload = byteString(payload); |
| 66 | } |
| 67 | this.addIndexEntry( |
| 68 | url, |
| 69 | this.addResponse(new HeaderMap(status, headers), payload) |
| 70 | ); |
| 71 | return this; |
| 72 | } |
| 73 | |
| 74 | setPrimaryURL(url: string): BundleBuilder { |
| 75 | return this.compatAdapter.setPrimaryURL(url); |
| 76 | } |
| 77 | |
| 78 | setManifestURL(url: string): BundleBuilder { |
| 79 | return this.compatAdapter.setManifestURL(url); |
| 80 | } |
| 81 | |
| 82 | private addSection(name: string, content: CBORValue) { |
| 83 | if (this.sectionLengths.some((s) => s.name === name)) { |
| 84 | throw new Error('Duplicated section: ' + name); |
| 85 | } |
nothing calls this directly
no outgoing calls
no test coverage detected