@@ -6,27 +6,38 @@ const staticAssets = new Map();
66/**
77 * Converts a data URL (base64 or plain) into a Fetch API Response object.
88 *
9- * @param {string } dataUrl - The data URL to convert. Example: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
9+ * @param {string } dataUrl - The data URL to convert. Example: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." or "data:text/plain,Hello%20World"
1010 * @returns {Response } A Response object representing the decoded data URL content.
1111 */
1212function dataUrlToResponse ( dataUrl ) {
13- const match = / ^ d a t a : ( i m a g e \/ [ a - z A - Z + ] + ) ; b a s e 6 4 , ( [ A - Z a - z 0 - 9 + / = ] + ) $ / . exec ( dataUrl ) ;
14- if ( ! match ) {
15- throw new Error ( 'Invalid or unsupported data URL: must be a base64-encoded image' ) ;
16- }
13+ // Try base64 image format first
14+ const base64Match = / ^ d a t a : ( i m a g e \/ [ a - z A - Z + ] + ) ; b a s e 6 4 , ( [ A - Z a - z 0 - 9 + / = ] + ) $ / . exec ( dataUrl ) ;
15+ if ( base64Match ) {
16+ const [ , mimeType , base64Data ] = /** @type { any[] } */ ( base64Match ) ;
1717
18- const [ , mimeType , base64Data ] = /** @type {any[] } */ ( match ) ;
18+ // Decode base64 to Uint8Array
19+ const binaryString = atob ( base64Data ) ;
20+ const bytes = new Uint8Array ( binaryString . length ) ;
21+ for ( let i = 0 ; i < binaryString . length ; i ++ ) {
22+ bytes [ i ] = binaryString . charCodeAt ( i ) ;
23+ }
1924
20- // Decode base64 to Uint8Array
21- const binaryString = atob ( base64Data ) ;
22- const bytes = new Uint8Array ( binaryString . length ) ;
23- for ( let i = 0 ; i < binaryString . length ; i ++ ) {
24- bytes [ i ] = binaryString . charCodeAt ( i ) ;
25+ return new Response ( bytes , {
26+ headers : { 'Content-Type' : mimeType }
27+ } ) ;
2528 }
2629
27- return new Response ( bytes , {
28- headers : { 'Content-Type' : mimeType }
29- } ) ;
30+ // Try plain text format
31+ const textMatch = / ^ d a t a : ( t e x t \/ [ a - z A - Z + ] + ) , ( .* ) $ / . exec ( dataUrl ) ;
32+ if ( textMatch ) {
33+ const [ , mimeType , textData ] = /** @type {any[] } */ ( textMatch ) ;
34+ const decodedText = decodeURIComponent ( textData ) ;
35+ return new Response ( decodedText , {
36+ headers : { 'Content-Type' : mimeType }
37+ } ) ;
38+ }
39+
40+ throw new Error ( 'Invalid or unsupported data URL: must be a base64-encoded image or plain text' ) ;
3041}
3142
3243addEventListener ( 'message' , ( event ) => {
0 commit comments