{"version":3,"sources":["utils.ts"],"sourcesContent":["\n\n//import { Storage } from \"../storage/storage.ts\"; TODO Storage cannot be importet here, handle file caching somehow (somewhere else)\nimport { ValueError } from \"../types/errors.ts\";\nimport { baseURL, Deno } from \"./global_values.ts\";\nimport { client_type } from \"./constants.ts\";\n\nexport function getRandomString(template: string = \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\", charset: string = \"abcdefghijklmnopqrstuvwxyz0123456789\") {\n    return template.replace(/x/g, (_: string, ...args: any[]) => {\n        return charset[getRandomInt(0, charset.length-1)]\n    });\n}\n\nexport function getRandomInt(min = 0, max: number = Number.MAX_SAFE_INTEGER): number {\n    const byte: number = globalThis.crypto.getRandomValues(new Uint8Array(1))[0];\n    const range = max - min + 1;\n    if (byte >= Math.floor(256 / range) * range)\n        return getRandomInt(min, max);\n    return min + (byte % range);\n}\n\n// get local file content (node) or url content (browser)\nexport async function getFileContent<E extends boolean = true>(url:string|URL, error_on_fail?:E, binary = false):  Promise<E extends false ? Uint8Array|string|null : Uint8Array|string> {\n    const path = url.toString();\n    error_on_fail ??= <any>true;\n\n    // get local file\n    if (client_type == \"deno\" && (path.startsWith(\"/\") || path.startsWith(\"file://\"))) {\n        return getLocalFileContent(path, error_on_fail, binary);\n    }\n\n    // get from url\n    try {\n        const res = await fetch(path, {credentials: 'include', mode:'cors'});\n        if (binary) return new Uint8Array(await res.arrayBuffer());\n        else return (await res.text()).replaceAll(\"\\r\\n\", \"\\n\");\n    } \n    catch(e) {\n        if (error_on_fail) {\n            // logger.error(\"Could not read file \" + path);\n            throw (e)\n        }\n    }\n    return <any>null\n}\n\n// get local file content (node only)\nexport async function getLocalFileContent<E extends boolean = true>(file_path:string|URL, error_on_fail?:E, binary = false): Promise<E extends false ? Uint8Array|string|null : Uint8Array|string> {\n    error_on_fail ??= <any>true;\n    \n    try {\n        const read = binary ? Deno.readFile : Deno.readTextFile;\n        const res = await read(file_path instanceof URL ? file_path : (file_path.startsWith('/') ? new URL('file://'+file_path) : new URL(file_path, baseURL)));\n        return res;\n    }\n    catch (e) {\n        if (error_on_fail) {\n            // logger.error(\"Could not read file \" + file_path);\n            throw (e)\n        }\n    }\n    return <any>null;\n}\n\n// // get local file content as string (node only)\n// export async function getLocalFileTextContent<E extends boolean = true>(file_path:string|URL, error_on_fail?: E): Promise<E extends false ? string|null : string> {\n//     if (error_on_fail == undefined) error_on_fail = <any>true;\n//     const content = await getLocalFileContent(file_path, error_on_fail);\n//     if (content) return new TextDecoder().decode(content).replaceAll(\"\\r\\n\", \"\\n\");\n//     else return <any>null;\n// }\n\n\nexport function urlToPath(url:URL) {\n    return url.toString().replace(/^(file|https?)\\:\\/\\//,'');\n}\n\n// binary - base64 conversion\nexport const btoa = globalThis.btoa;\nexport const atob = globalThis.atob;\n\n/** ArrayBuffer <-> Base64 String */\nexport function arrayBufferToBase64(buffer:ArrayBuffer):string {\n\tlet binary = '';\n\tconst bytes = new Uint8Array( buffer );\n\tconst len = bytes.byteLength;\n\tfor (let i = 0; i < len; i++) {\n\t\tbinary += globalThis.String.fromCharCode( bytes[ i ] );\n\t}\n\treturn btoa( binary );\n}\n\nexport function base64ToArrayBuffer(base64:string):ArrayBuffer {\n    const binary_string = atob(base64);\n    const len = binary_string.length;\n    const bytes = new Uint8Array( len );\n    for (let i = 0; i < len; i++)        {\n        bytes[i] = binary_string.charCodeAt(i);\n    }\n    return bytes.buffer;\n}\n\n\n\n// get hex string id from buffer\nexport function buffer2hex(buffer:Uint8Array|ArrayBuffer, seperator?:string, pad_size_bytes?:number, x_shorthand = false):string {\n    if (buffer instanceof ArrayBuffer) buffer = new Uint8Array(buffer);\n\n    // first pad buffer\n    if (pad_size_bytes) buffer = buffer.slice(0, pad_size_bytes);\n\n    let array:string[] = <string[]> Array.prototype.map.call(buffer, x => ('00' + x.toString(16).toUpperCase()).slice(-2))\n    let skipped_bytes = 0;\n\n    // collapse multiple 0s to x...\n    if (x_shorthand) {\n        array = array.slice(0,pad_size_bytes).reduce((previous, current) => {\n            if (current == '00') {\n                if (previous.endsWith('00')) {\n                    skipped_bytes++;\n                    return previous.slice(0, -2) + \"x2\"; // add to existing 00\n                }\n                else if (previous[previous.length-2] == 'x') {\n                    const count = (parseInt(previous[previous.length-1],16)+1);\n                    if (count <= 0xf) {\n                        skipped_bytes++;\n                        return previous.slice(0, -1) + count.toString(16).toUpperCase()  // add to existing x... max 15\n                    }\n                }\n            }\n            return previous + current;\n        }).split(/(..)/g).filter(s=>!!s);\n    }\n\n    if (pad_size_bytes != undefined) array = Array.from({...array, length: pad_size_bytes-skipped_bytes}, x=>x==undefined?'00':x); // pad\n\n    return array.join(seperator??'');\n}\n\n// get buffer from hex string id, x_shorthand: replace [x2] with [00 00], [xa] with [00] * 10\nexport function hex2buffer(hex:string, pad_size_bytes?:number, x_shorthand = false):Uint8Array { \n    if (!hex) return new Uint8Array(0); // empty buffer\n\n    hex = hex.replace(/[_\\- ]/g, \"\");\n    if (hex.length%2 != 0) throw new ValueError('Invalid hexadecimal buffer: ' + hex);    \n    if ((x_shorthand && hex.match(/[G-WYZ\\s]/i)) || (!x_shorthand && hex.match(/[G-Z\\s]/i))) throw new ValueError('Invalid hexadecimal buffer: ' + hex);       \n\n    let array:number[];\n\n    if (!x_shorthand) array = hex.match(/[\\dA-Fa-fxX]{2}/gi)?.map( s => parseInt(s, 16)) ?? [];\n    else array = hex.match(/[\\dA-Fa-fxX]{2}/gi)?.map((s, i, a) => {\n        s = s.toLowerCase();\n        if (s.startsWith(\"x\") && s[1]!=\"x\") return Array(parseInt(s[1],16)).fill(0); // expand x...\n        else if (s.includes(\"x\")) throw new ValueError('Invalid buffer \"x\" shorthand: ' + hex.slice(0, 30)); \n        return parseInt(s, 16)\n    }).flat(1) ?? []\n\n    if (pad_size_bytes != undefined) return new Uint8Array({...array, length: pad_size_bytes});\n    else return new Uint8Array(array);\n}"],"names":["ValueError","baseURL","Deno","client_type","getRandomString","template","charset","replace","_","args","getRandomInt","length","min","max","Number","MAX_SAFE_INTEGER","byte","globalThis","crypto","getRandomValues","Uint8Array","range","Math","floor","getFileContent","url","error_on_fail","binary","path","toString","startsWith","getLocalFileContent","res","fetch","credentials","mode","arrayBuffer","text","replaceAll","e","file_path","read","readFile","readTextFile","URL","urlToPath","btoa","atob","arrayBufferToBase64","buffer","bytes","len","byteLength","i","String","fromCharCode","base64ToArrayBuffer","base64","binary_string","charCodeAt","buffer2hex","seperator","pad_size_bytes","x_shorthand","ArrayBuffer","slice","array","Array","prototype","map","call","x","toUpperCase","skipped_bytes","reduce","previous","current","endsWith","count","parseInt","split","filter","s","undefined","from","join","hex2buffer","hex","match","a","toLowerCase","fill","includes","flat"],"mappings":"AAGA,SAASA,UAAU,QAAQ,qBAAqB;AAChD,SAASC,OAAO,EAAEC,IAAI,QAAQ,qBAAqB;AACnD,SAASC,WAAW,QAAQ,iBAAiB;AAE7C,OAAO,SAASC,gBAAgBC,WAAmB,sCAAsC,EAAEC,UAAkB,sCAAsC;IAC/I,OAAOD,SAASE,OAAO,CAAC,MAAM,CAACC,GAAW,GAAGC,OAClCH,OAAO,CAACI,aAAa,GAAGJ,QAAQK,MAAM,GAAC,GAAG;AAEzD;AAEA,OAAO,SAASD,aAAaE,MAAM,CAAC,EAAEC,MAAcC,OAAOC,gBAAgB;IACvE,IAAMC,OAAeC,WAAWC,MAAM,CAACC,eAAe,CAAC,IAAIC,WAAW,GAAG,CAAC,EAAE,EACtEC,QAAQR,MAAMD,MAAM;WAC1B,AAAII,QAAQM,KAAKC,KAAK,CAAC,MAAMF,SAASA,QAC3BX,aAAaE,KAAKC,OACtBD,MAAOI,OAAOK;AACzB;AAGA,OAAO,eAAeG,eAAyCC,GAAc,EAAEC,aAAgB,EAAEC,SAAS,CAAA,CAAK;IAC3G,IAAMC,OAAOH,IAAII,QAAQ;IAIzB,IAHAH,kBAAuB,CAAA,GAGnBvB,AAAe,UAAfA,eAA0ByB,CAAAA,KAAKE,UAAU,CAAC,QAAQF,KAAKE,UAAU,CAAC,UAAS,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