From 5f3b0d4a1043f5fd4158bc4201bdc4f02eaa7e30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Molakvo=C3=A6?= Date: Tue, 23 Jan 2024 18:12:47 +0100 Subject: [PATCH] fix: do not try to slice in chunk larger than the File itself MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: John Molakvoæ --- __tests__/utils/upload.spec.ts | 14 ++++++++++++-- lib/utils/upload.ts | 4 ++++ package.json | 2 +- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/__tests__/utils/upload.spec.ts b/__tests__/utils/upload.spec.ts index 5ec362b1..e9758fef 100644 --- a/__tests__/utils/upload.spec.ts +++ b/__tests__/utils/upload.spec.ts @@ -35,9 +35,19 @@ describe('Get chunk from file', () => { expect(chunk.size).toBe(10 * 1024 * 1024) }) - test('Chunking an invalid file', async () => { + test('Requesting a chunk bigger than the file', async () => { const blob = new Blob([new ArrayBuffer(5 * 1024 * 1024)]) - const file = new File([blob as BlobPart], 'image.jpg') + const file = new File([blob as BlobPart], 'image.jpg', { type: 'image/jpeg' }) + + const chunk = await getChunk(file, 0, 10 * 1024 * 1024) + expect(chunk.size).toBe(5 * 1024 * 1024) + expect(chunk.type).toBe('image/jpeg') + + }) + + test('Chunking an unknown file', async () => { + const blob = new Blob([new ArrayBuffer(5 * 1024 * 1024)]) + const file = new File([blob as BlobPart], 'image.jpg', { }) const chunk = await getChunk(file, 0, 10 * 1024 * 1024) expect(chunk.size).toBe(5 * 1024 * 1024) diff --git a/lib/utils/upload.ts b/lib/utils/upload.ts index 259f111f..85527ce3 100644 --- a/lib/utils/upload.ts +++ b/lib/utils/upload.ts @@ -62,6 +62,10 @@ export const uploadData = async function( * garbage collection */ export const getChunk = function(file: File, start: number, length: number): Promise { + if (start === 0 && file.size <= length) { + return Promise.resolve(new Blob([file], { type: file.type || 'application/octet-stream' })) + } + // Since we use a global FileReader, we need to only read one chunk at a time return readerLimit(() => new Promise((resolve, reject) => { reader.onload = () => { diff --git a/package.json b/package.json index 7e9643dc..36399b08 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ "cypress": "cypress run --component", "cypress:gui": "cypress open --component", "test": "vitest run", - "test:watch": "vitest run --watch", + "test:watch": "vitest watch", "test:coverage": "vitest run --coverage", "l10n:extract": "node build/extract-l10n.js" },