diff --git a/src/file-selector.spec.ts b/src/file-selector.spec.ts index edd1a40..e137ff9 100644 --- a/src/file-selector.spec.ts +++ b/src/file-selector.spec.ts @@ -333,6 +333,13 @@ it('should not use getAsFileSystemHandle when not in a secure context', async () window.isSecureContext = true; }); +it('should reject when getAsFileSystemHandle resolves to null', async () => { + const evt = dragEvtFromItems([ + dataTransferItemWithFsHandle(null, null) + ]); + expect(fromEvent(evt)).rejects.toMatch('is not a File'); +}); + function dragEvtFromItems(items: DataTransferItem | DataTransferItem[], type: string = 'drop'): DragEvent { return { type, @@ -403,7 +410,7 @@ function dataTransferItemFromEntry(entry: FileEntry | DirEntry, file?: File): Da } as any; } -function dataTransferItemWithFsHandle(file?: File, h?: FileSystemFileHandle): DataTransferItem { +function dataTransferItemWithFsHandle(file?: File | null, h?: FileSystemFileHandle | null): DataTransferItem { return { kind: 'file', getAsFile() { @@ -510,7 +517,7 @@ function sortFiles(files: T[]) { interface FileSystemFileHandle { - getFile(): Promise; + getFile(): Promise; } type FileOrDirEntry = FileEntry | DirEntry diff --git a/src/file-selector.ts b/src/file-selector.ts index d5d4dfa..619bcc0 100644 --- a/src/file-selector.ts +++ b/src/file-selector.ts @@ -130,6 +130,9 @@ function fromDataTransferItem(item: DataTransferItem, entry?: FileSystemEntry | if (globalThis.isSecureContext && typeof (item as any).getAsFileSystemHandle === 'function') { return (item as any).getAsFileSystemHandle() .then(async (h: any) => { + if (!h) { + return notAFile(item); + } const file = await h.getFile(); file.handle = h; return toFileWithPath(file); @@ -137,12 +140,16 @@ function fromDataTransferItem(item: DataTransferItem, entry?: FileSystemEntry | } const file = item.getAsFile(); if (!file) { - return Promise.reject(`${item} is not a File`); + return notAFile(item); } const fwp = toFileWithPath(file, entry?.fullPath ?? undefined); return Promise.resolve(fwp); } +function notAFile(item: DataTransferItem) { + return Promise.reject(`${item} is not a File`); +} + // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemEntry async function fromEntry(entry: any) { return entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry);