|
1 | 1 | /** |
2 | 2 | * Creates a blob URL from the given text. |
3 | 3 | * @param text The text to create a blob URL from. |
4 | | - * @returns An object containing the blob URL, the size of the text in bytes, and a function to revoke the URL. |
| 4 | + * @param options Options. |
| 5 | + * @param options.withNodeWorkaround Whether to add an extra space at the end of the text |
| 6 | + * to work around the Node.js bug (https://github.com/nodejs/node/issues/60382). Defaults to false. |
| 7 | + * @returns An object containing the blob URL, the size of the file in bytes (without the extra space, |
| 8 | + * if `withNodeWorkaround` is true), and a function to revoke the URL. |
5 | 9 | */ |
6 | | -export function toURL(text: string): { |
| 10 | +export function toURL(text: string, { withNodeWorkaround }: { withNodeWorkaround?: boolean } = {}): { |
7 | 11 | url: string |
8 | 12 | fileSize: number |
9 | 13 | revoke: () => void |
10 | 14 | } { |
| 15 | + withNodeWorkaround = withNodeWorkaround ?? false |
11 | 16 | // add an extra space to fix https://github.com/nodejs/node/issues/60382 |
12 | | - const blob = new Blob([text + ' ']) |
| 17 | + const blob = new Blob([withNodeWorkaround ? text + ' ' : text]) |
13 | 18 | const url = URL.createObjectURL(blob) |
14 | 19 | return { |
15 | 20 | url, |
16 | | - fileSize: blob.size - 1, // subtract the extra space |
| 21 | + // remove the extra space from the file size |
| 22 | + fileSize: withNodeWorkaround ? blob.size - 1 : blob.size, |
17 | 23 | revoke: () => { |
18 | 24 | URL.revokeObjectURL(url) |
19 | 25 | }, |
20 | 26 | } |
21 | 27 | } |
22 | 28 |
|
| 29 | +/** |
| 30 | + * Checks if the given URL is an empty Blob URL. |
| 31 | + * @param url The URL to check. |
| 32 | + * @returns Whether the URL is an empty Blob URL. |
| 33 | + */ |
| 34 | +export async function isEmptyBlobURL(url: string): Promise<boolean> { |
| 35 | + if (!url.startsWith('blob:')) { |
| 36 | + return false |
| 37 | + } |
| 38 | + try { |
| 39 | + const response = await fetch(url) |
| 40 | + const blob = await response.blob() |
| 41 | + return blob.size === 0 |
| 42 | + } |
| 43 | + catch { |
| 44 | + return false |
| 45 | + } |
| 46 | +} |
| 47 | + |
23 | 48 | /** |
24 | 49 | * Decodes the given bytes using the provided decoder. |
25 | 50 | * @param bytes The bytes to decode. |
|
0 commit comments