(key: string, config: Config)
| 28 | } |
| 29 | |
| 30 | async function loadAsBlob(key: string, config: Config) { |
| 31 | // load resource metadata |
| 32 | |
| 33 | const resourceUri = ensureAbsoluteURI('./resources.json', config.publicPath); |
| 34 | |
| 35 | const resourceResponse = await loadFromURI(resourceUri); |
| 36 | |
| 37 | if (!resourceResponse.ok) { |
| 38 | throw new Error( |
| 39 | `Resource metadata not found. Ensure that the config.publicPath is configured correctly.` |
| 40 | ); |
| 41 | } |
| 42 | const resourceMap = await resourceResponse.json(); |
| 43 | const entry = resourceMap[key]; |
| 44 | |
| 45 | if (!entry) { |
| 46 | throw new Error( |
| 47 | `Resource ${key} not found. Ensure that the config.publicPath is configured correctly.` |
| 48 | ); |
| 49 | } |
| 50 | |
| 51 | const chunks = entry.chunks; // list of entries |
| 52 | |
| 53 | let downloadedSize = 0; |
| 54 | const responses = chunks.map(async (chunk) => { |
| 55 | const url = ensureAbsoluteURI(chunk.hash, config.publicPath); |
| 56 | const chunkSize = chunk.offsets[1] - chunk.offsets[0]; |
| 57 | const response = await loadFromURI(url, { |
| 58 | headers: { 'Content-Type': entry.mime } |
| 59 | }); |
| 60 | const blob = await response.blob(); |
| 61 | |
| 62 | if (chunkSize !== blob.size) { |
| 63 | throw new Error( |
| 64 | `Failed to fetch ${key} with size ${chunkSize} but got ${blob.size}` |
| 65 | ); |
| 66 | } |
| 67 | |
| 68 | if (config.progress) { |
| 69 | downloadedSize += chunkSize; |
| 70 | config.progress(`fetch:${key}`, downloadedSize, entry.size); |
| 71 | } |
| 72 | return blob; |
| 73 | }); |
| 74 | |
| 75 | // we could create a new buffer here and use the chunk entries and combine the file instead |
| 76 | |
| 77 | const allChunkData = await Promise.all(responses); |
| 78 | |
| 79 | const data = new Blob(allChunkData, { type: entry.mime }); |
| 80 | if (data.size !== entry.size) { |
| 81 | throw new Error( |
| 82 | `Failed to fetch ${key} with size ${entry.size} but got ${data.size}` |
| 83 | ); |
| 84 | } |
| 85 | return data; |
| 86 | } |
no test coverage detected