/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@litertjs/core@2.4.0/dist/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
var ElementType={NONE:0,FLOAT32:1,INT32:2,UINT8:3,INT64:4,STRING:5,BOOL:6,INT16:7,COMPLEX64:8,INT8:9,FLOAT16:10,FLOAT64:11,COMPLEX128:12,UINT64:13,RESOURCE:14,VARIANT:15,UINT32:16,UINT16:17,INT4:18,BFLOAT16:19},ElementTypeName={[ElementType.NONE]:"NONE",[ElementType.FLOAT32]:"FLOAT32",[ElementType.INT32]:"INT32",[ElementType.UINT8]:"UINT8",[ElementType.INT64]:"INT64",[ElementType.STRING]:"STRING",[ElementType.BOOL]:"BOOL",[ElementType.INT16]:"INT16",[ElementType.COMPLEX64]:"COMPLEX64",[ElementType.INT8]:"INT8",[ElementType.FLOAT16]:"FLOAT16",[ElementType.FLOAT64]:"FLOAT64",[ElementType.COMPLEX128]:"COMPLEX128",[ElementType.UINT64]:"UINT64",[ElementType.RESOURCE]:"RESOURCE",[ElementType.VARIANT]:"VARIANT",[ElementType.UINT32]:"UINT32",[ElementType.UINT16]:"UINT16",[ElementType.INT4]:"INT4",[ElementType.BFLOAT16]:"BFLOAT16"},TensorBufferType={HOST_MEMORY:1,WEB_GPU_BUFFER:20,WEB_GPU_BUFFER_FP16:21,WEB_GPU_BUFFER_PACKED:26},TensorBufferTypeName={[TensorBufferType.HOST_MEMORY]:"HOST_MEMORY",[TensorBufferType.WEB_GPU_BUFFER]:"WEB_GPU_BUFFER",[TensorBufferType.WEB_GPU_BUFFER_FP16]:"WEB_GPU_BUFFER_FP16",[TensorBufferType.WEB_GPU_BUFFER_PACKED]:"WEB_GPU_BUFFER_PACKED"},DATATYPES=Object.freeze([{dtype:"float32",typedArrayConstructor:Float32Array,elementType:ElementType.FLOAT32},{dtype:"int32",typedArrayConstructor:Int32Array,elementType:ElementType.INT32},{dtype:"uint8",typedArrayConstructor:Uint8Array,elementType:ElementType.UINT8}]);function getDataType(e){for(const t of DATATYPES)if(t.dtype===e||t.typedArrayConstructor===e||e instanceof t.typedArrayConstructor||t.elementType===e)return t;throw"string"==typeof e?new Error(`DType ${e} is not supported.`):e instanceof Object?new Error(`Typed array ${"name"in e?e.name:e.constructor.name} is not supported.`):new Error(`Element type ${ElementTypeName[e]??e} is not supported.`)}var LiteRtNotLoadedError=class extends Error{constructor(){super("LiteRT is not initialized yet. Please call loadLiteRt() and wait for its promise to resolve to load the LiteRT WASM module.")}},globalLiteRt=void 0,globalLiteRtPromise=void 0;function getGlobalLiteRt(){if(!globalLiteRt)throw new LiteRtNotLoadedError;return globalLiteRt}function hasGlobalLiteRt(){return Boolean(globalLiteRt)}function setGlobalLiteRt(e){globalLiteRt=e}function getGlobalLiteRtPromise(){return globalLiteRtPromise}function hasGlobalLiteRtPromise(){return Boolean(globalLiteRtPromise)}function setGlobalLiteRtPromise(e){globalLiteRtPromise=e}var AcceleratorDefaultTensorBufferType={webgpu:TensorBufferType.WEB_GPU_BUFFER_PACKED,wasm:TensorBufferType.HOST_MEMORY},TensorBufferTypeToAccelerator={[TensorBufferType.HOST_MEMORY]:"wasm",[TensorBufferType.WEB_GPU_BUFFER]:"webgpu",[TensorBufferType.WEB_GPU_BUFFER_FP16]:"webgpu",[TensorBufferType.WEB_GPU_BUFFER_PACKED]:"webgpu"},DESIRED_WEBGPU_FEATURES=["shader-f16","subgroups"],Environment=class e{constructor(e){this.options=e,this.liteRtEnvironment=getGlobalLiteRt().liteRtWasm.LiteRtEnvironment.create(e.webGpuDevice)}liteRtEnvironment;static async create(t={}){let r=null;if("webGpuDevice"in t)t.webGpuDevice&&(r=t.webGpuDevice);else try{r=await createDefaultWebGpuDevice()}catch(e){console.warn("Failed to create default WebGPU device:",e)}return new e({...t,webGpuDevice:r})}get webGpuDevice(){return this.options.webGpuDevice}delete(){this.liteRtEnvironment.delete()}};async function createDefaultWebGpuDevice(){const e=await navigator.gpu.requestAdapter({powerPreference:"high-performance"});if(!e)throw new Error("No GPU adapter found.");const t={maxBufferSize:e.limits.maxBufferSize,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxStorageBuffersPerShaderStage:e.limits.maxStorageBuffersPerShaderStage,maxTextureDimension2D:e.limits.maxTextureDimension2D},r=[];for(const t of DESIRED_WEBGPU_FEATURES)e.features.has(t)&&r.push(t);return await e.requestDevice({requiredFeatures:r,requiredLimits:t})}function emscriptenVectorToArray(e){const t=new Array(e.size());for(let r=0;r<e.size();++r)t[r]=e.get(r);return e.delete(),t}function fillEmscriptenVector(e,t){for(const r of e)t.push_back(r)}function parseData(e){const t=e.shift();if(t instanceof getGlobalLiteRt().liteRtWasm.LiteRtTensorBuffer)return{liteRtTensorBuffer:t};if(ArrayBuffer.isView(t))return{typedArray:t};if(t instanceof GPUBuffer)return{gpuBuffer:t};throw new Error(`Unknown type (${t?.constructor.name??t}) provided to create a Tensor`)}function parseShape(e){return Array.isArray(e[0])||e[0]instanceof Int32Array?{shape:e.shift()}:{}}function shiftUntilDefined(e){for(;e.length>0&&void 0===e[0];)e.shift()}function parseDataType(e){if(shiftUntilDefined(e),"string"==typeof e[0]){return{dataType:getDataType(e.shift()).dtype}}return{}}function parseEnvironment(e){return shiftUntilDefined(e),e[0]instanceof Environment?{environment:e.shift()}:{}}function parseOnDelete(e){return shiftUntilDefined(e),e[0]instanceof Function?{onDelete:e.shift()}:{}}function parseArgs(e){return{...parseData(e),...parseShape(e),...parseDataType(e),...parseEnvironment(e),...parseOnDelete(e)}}var Tensor=class e{liteRtTensorBuffer;type;environment;deletedInternal=!1;onDelete;static copyFunctions=new Map;constructor(e,t,r,n,o){const{typedArray:i,gpuBuffer:s,liteRtTensorBuffer:a,shape:l,dataType:u,environment:f,onDelete:p}=parseArgs([e,t,r,n,o]);if(this.onDelete=p,this.environment=f??getGlobalLiteRt().getDefaultEnvironment(),a){if(l)throw new Error("A LiteRtTensorBuffer cannot be provided with a shape.");if(u)throw new Error("A LiteRtTensorBuffer cannot be provided with a data type.");this.liteRtTensorBuffer=a}else if(s){if(!l)throw new Error("A GPUBuffer must be provided with a shape.");if(!u)throw new Error("A GPUBuffer must be provided with a data type.");const[e,t]=webGpuBufferToLiteRtTensorBuffer(s,l,u,this.environment);this.liteRtTensorBuffer=e;const r=this.onDelete;this.onDelete=()=>{getGlobalLiteRt().liteRtWasm.wgpuBufferRelease(t),r?.()}}else{if(!i)throw new Error("No data provided to create a Tensor.");this.liteRtTensorBuffer=typedArrayToLiteRtTensorBuffer(i,l,f)}this.type=liteRtTensorBufferToTensorType(this.liteRtTensorBuffer)}static fromTypedArray(t,r,n){return new e(t,r,n)}ensureNotDeleted(){if(this.deleted)throw new Error("Tensor is deleted and cannot be used.")}async data(){if(this.ensureNotDeleted(),this.liteRtTensorBuffer.bufferType().value===TensorBufferType.HOST_MEMORY)return this.toTypedArray();const e=await this.copyTo("wasm"),t=await e.data();return e.delete(),t}toTypedArray(){this.ensureNotDeleted();const e=getGlobalLiteRt().liteRtWasm;if(this.liteRtTensorBuffer.isWebGpuMemory())throw new Error("Cannot convert a Tensor with WebGPU memory to a TypedArray.");if(this.liteRtTensorBuffer.bufferType().value!==e.LiteRtTensorBufferType.HOST_MEMORY.value)throw new Error("Cannot convert a Tensor with non-host memory to a TypedArray.");if(this.liteRtTensorBuffer.size()!==this.liteRtTensorBuffer.packedSize()||0!==this.liteRtTensorBuffer.offset())throw new Error("Tensors with strides or padding are not yet supported.");const t=this.liteRtTensorBuffer.tensorType(),r=t.elementType(),n=e.liteRtGetByteWidth(r);t.delete();const o=getDataType(r.value).typedArrayConstructor;if(o.BYTES_PER_ELEMENT!==n)throw new Error(`Byte width ${n} of the tensor's element type ${ElementTypeName[r.value]} does not match the expected byte width ${o.BYTES_PER_ELEMENT} of the ${o.name}.`);const i=this.liteRtTensorBuffer.lock(getGlobalLiteRt().liteRtWasm.LiteRtTensorBufferLockMode.READ);try{const t=e.HEAPU8.slice(i,i+this.liteRtTensorBuffer.packedSize());return new o(t.buffer,t.byteOffset,t.byteLength/n)}finally{this.liteRtTensorBuffer.unlock()}}getBufferType(){return this.ensureNotDeleted(),this.liteRtTensorBuffer.bufferType().value}toGpuBuffer(){this.ensureNotDeleted();const e=getGlobalLiteRt().liteRtWasm;if(!this.liteRtTensorBuffer.isWebGpuMemory())throw new Error("Cannot convert a Tensor with non-WebGPU memory to a GPUBuffer.");const t=this.liteRtTensorBuffer.bufferType().value;if(t!==e.LiteRtTensorBufferType.WEB_GPU_BUFFER.value&&t!==e.LiteRtTensorBufferType.WEB_GPU_BUFFER_FP16.value&&t!==e.LiteRtTensorBufferType.WEB_GPU_BUFFER_PACKED.value)throw new Error("Cannot convert a Tensor with host memory to a GPUBuffer.");if(this.liteRtTensorBuffer.size()!==this.liteRtTensorBuffer.packedSize()||0!==this.liteRtTensorBuffer.offset())throw new Error("Tensors with strides or padding are not yet supported.");const r=this.liteRtTensorBuffer.getWebGpuBuffer();return e.WebGPU.getJsObject(r)}getCopyFunctionSet(t){this.ensureNotDeleted();const r=this.getBufferType(),n=e.copyFunctions.get(r);if(!n)throw new Error(`TensorBufferType ${TensorBufferTypeName[r]??r} does not support copying or moving`);const o="string"==typeof t?AcceleratorDefaultTensorBufferType[t]:t;if(null==o)throw new Error(`Unknown destination '${t}' for copying or moving.`);const i=n.get(o);if(!i){const e=[...n].map((([e])=>TensorBufferTypeName[e]??e));throw new Error(`TensorBufferType ${TensorBufferTypeName[r]} does not support copying or moving to ${TensorBufferTypeName[o]}. It supports the following TensorBufferTypes: [${e.join(", ")}].`)}return[i,o]}async copyTo(e,t){const[r,n]=this.getCopyFunctionSet(e);if(!r.copyTo)throw new Error(`Copying to ${TensorBufferTypeName[n]} is not supported by this tensor.`);return r.copyTo(this,t)}async moveTo(e,t){const[r,n]=this.getCopyFunctionSet(e);if(!r.moveTo)throw new Error(`Moving to ${TensorBufferTypeName[n]} is not supported by this tensor.`);return r.moveTo(this,t)}get bufferType(){return this.liteRtTensorBuffer.bufferType().value}get accelerator(){const e=TensorBufferTypeToAccelerator[this.bufferType];if(void 0===e)throw new Error(`TensorBufferType ${TensorBufferTypeName[this.bufferType]} has an unknown accelerator type.`);return e}get deleted(){return this.deletedInternal}delete(){this.deletedInternal||(this.deletedInternal=!0,this.liteRtTensorBuffer.delete(),this.onDelete?.())}};function liteRtTensorBufferToTensorType(e){const t=e.tensorType(),r=t.elementType(),n=t.layout(),o=n.dimensions();return n.delete(),t.delete(),{dtype:getDataType(r.value).dtype,layout:{dimensions:emscriptenVectorToArray(o)}}}function webGpuBufferToLiteRtTensorBuffer(e,t,r,n){const o=getGlobalLiteRt().liteRtWasm,i=new o.VectorInt32;fillEmscriptenVector(t,i);const s=o.LiteRtLayout.create(i);i.delete();const a=o.LiteRtRankedTensorType.create({value:getDataType(r).elementType},s);s.delete();const l=o.WebGPU.importJsBuffer(e),u=o.LiteRtTensorBuffer.createFromWebGpuBuffer(n.liteRtEnvironment,a,o.LiteRtTensorBufferType.WEB_GPU_BUFFER_PACKED,l,e.size);return a.delete(),[u,l]}function typedArrayToLiteRtTensorBuffer(e,t,r){const n=getGlobalLiteRt(),o=n.liteRtWasm;r=r??n.getDefaultEnvironment();const i=getDataType(e).elementType,s=new o.VectorInt32;fillEmscriptenVector(t??[e.length],s);const a=o.LiteRtLayout.create(s);s.delete();const l=a.numElements();if(e.length!==l)throw a.delete(),new Error(`Number of elements ${e.length} of the provided TypedArray does not match the expected number of elements ${l}.`);const u=o.LiteRtRankedTensorType.create({value:i},a);a.delete();const f=e.constructor.BYTES_PER_ELEMENT*e.length,p=u.bytes();if(f!==p)throw u.delete(),new Error(`Byte length ${f} of the provided TypedArray does not match the expected buffer size ${p}.`);const d=o.LiteRtTensorBuffer.createManaged(r.liteRtEnvironment,o.LiteRtTensorBufferType.HOST_MEMORY,u,f);u.delete();const c=d.lock(o.LiteRtTensorBufferLockMode.WRITE);try{const t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);o.HEAPU8.set(t,c)}finally{d.unlock()}return d}var CompiledModelSignatureRunner=class{constructor(e,t,r,n){this.signatureIndex=e,this.liteRtModel=t,this.liteRtCompiledModel=r,this.options=n,this.liteRtSimpleSignature=t.getSignature(e);const o=emscriptenVectorToArray(this.liteRtSimpleSignature.inputNames()),i=[];for(let n=0;n<o.length;n++){const s=o[n],a=t.getInputTensorType(e,n),l=r.getInputBufferRequirements(e,n);i.push(makeTensorDetails(s,n,a,l))}this.inputDetails=Object.freeze(i);const s=emscriptenVectorToArray(this.liteRtSimpleSignature.outputNames()),a=[];for(let n=0;n<s.length;n++){const o=s[n],i=t.getOutputTensorType(e,n),l=r.getOutputBufferRequirements(e,n);a.push(makeTensorDetails(o,n,i,l))}this.outputDetails=Object.freeze(a)}inputDetails;outputDetails;liteRtSimpleSignature;deletedInternal=!1;get key(){return this.ensureNotDeleted(),this.liteRtSimpleSignature.key()}getInputDetails(){return this.ensureNotDeleted(),this.inputDetails}getOutputDetails(){return this.ensureNotDeleted(),this.outputDetails}async run(e){this.ensureNotDeleted();const t=this.inputsToArray(e),{inputsOnAccelerator:r,cleanup:n}=await this.ensureInputsOnAccelerator(t);let o;try{o=await this.runWithArray(r)}finally{n()}return Array.isArray(e)||e instanceof Tensor?o:this.outputsToRecord(o)}inputsToArray(e){if(Array.isArray(e)){if(e.length!==this.inputDetails.length)throw new Error(`run() called with ${e.length} inputs, but signature expects ${this.inputDetails.length} inputs`);return e}if(e instanceof Tensor){if(1!==this.inputDetails.length)throw new Error(`run() called with a single tensor, but signature expects ${this.inputDetails.length} inputs`);return[e]}const t=[];for(const r of this.inputDetails){if(!(r.name in e))throw new Error(`run() called with input record that is missing input ${r.name} with index ${r.index}`);t.push(e[r.name])}return t}outputsToRecord(e){const t={};for(let r=0;r<this.outputDetails.length;r++)t[this.outputDetails[r].name]=e[r];return t}async ensureInputsOnAccelerator(e){const t=[],r=[],n=this.getInputDetails();if(e.length!==n.length)throw new Error(`ensureInputsOnAccelerator() called with ${e.length} inputs, but signature expects ${n.length} inputs`);for(let o=0;o<e.length;o++){const i=e[o],s=i.getBufferType(),a=n[o].supportedBufferTypes;if(0===a.size)throw new Error(`Tensor ${n[o].name} with index ${n[o].index} has no supported buffer types.`);if(a.has(s))r.push(i);else{const e=a.values().next().value,n=await i.copyTo(e);t.push(n),r.push(n)}}return{inputsOnAccelerator:r,cleanup:()=>{for(const e of t)e.delete()}}}async runWithArray(e){for(let t=0;t<e.length;t++){const r=e[t],n=this.liteRtModel.getInputTensorType(this.signatureIndex,t),o=this.liteRtCompiledModel.getInputBufferRequirements(this.signatureIndex,t);getGlobalLiteRt().liteRtWasm.checkTensorBufferCompatible(r.liteRtTensorBuffer,n,o),n.delete(),o.delete()}return(await this.liteRtCompiledModel.run(this.signatureIndex,e.map((e=>e.liteRtTensorBuffer)))).map((e=>new Tensor(e,this.options.environment)))}get deleted(){return this.deletedInternal}ensureNotDeleted(){if(this.deleted)throw new Error("CompiledModelSignatureRunner is deleted and cannot be used.")}delete(){this.deletedInternal||(this.deletedInternal=!0,this.liteRtSimpleSignature.delete())}};function makeTensorDetails(e,t,r,n){const o=r.layout(),i=emscriptenVectorToArray(o.dimensions());o.delete();const s=new Set(emscriptenVectorToArray(n.supportedTypes()).map((({value:e})=>e))),a={name:e,index:t,dtype:getDataType(r.elementType().value).dtype,shape:new Int32Array(i),supportedBufferTypes:s};return r.delete(),n.delete(),a}var CompiledModel=class{constructor(e,t,r,n){this.model=e,this.liteRtCompiledModel=t,this.options=r,this.onDelete=n;const o=e.liteRtModel.getNumSignatures(),i={};for(let n=0;n<o;n++){const o=new CompiledModelSignatureRunner(n,e.liteRtModel,t,r);i[o.key]=o}this.compiledModelSignatureRunners=Object.freeze(i),this.defaultSignature=Object.values(this.signatures)[0],this.key=this.defaultSignature.key}defaultSignature;compiledModelSignatureRunners;key;deletedInternal=!1;get signatures(){return this.ensureNotDeleted(),this.compiledModelSignatureRunners}getInputDetails(){return this.ensureNotDeleted(),this.defaultSignature.getInputDetails()}getOutputDetails(){return this.ensureNotDeleted(),this.defaultSignature.getOutputDetails()}async run(e,t){this.ensureNotDeleted();const[r,n]=this.parseRunInputs(e,t);return await r.run(n)}parseRunInputs(e,t){let r,n;if("string"==typeof e){if(r=this.signatures[e],!r)throw new Error(`No signature named ${e} found in model.`);if(!t)throw new Error(`No input provided for signature ${e}`);n=t}else r=this.defaultSignature,n=e;return[r,n]}get deleted(){return this.deletedInternal}ensureNotDeleted(){if(this.deleted)throw new Error("CompiledModel is deleted and cannot be used.")}get isFullyAccelerated(){return this.ensureNotDeleted(),this.liteRtCompiledModel.isFullyAccelerated()}delete(){if(!this.deletedInternal){this.deletedInternal=!0,this.liteRtCompiledModel.delete(),this.model.delete();for(const e of Object.values(this.compiledModelSignatureRunners))e.delete();this.onDelete()}}};async function urlToUint8Array(e){const t=await fetch(e);return new Uint8Array(await t.arrayBuffer())}async function readableStreamDefaultReaderToUint8Array(e){let t=0,r=new Uint8Array(1024);const n=2e9;for(;;){const{done:o,value:i}=await e.read();if(i){if(r.byteLength<t+i.byteLength){if(t+i.byteLength>n)throw new Error("Model is too large (> 2000000000 bytes).");const e=new Uint8Array(Math.min(n,2*Math.max(r.byteLength,i.byteLength)));e.set(r),r=e}r.set(i,t),t+=i.byteLength}if(o)break}return r.slice(0,t)}var Model=class{constructor(e,t){this.liteRtModel=e,this.onDelete=t}delete(){this.liteRtModel.delete(),this.onDelete()}};function isWebGPUSupported(){return!("undefined"==typeof globalThis||!globalThis.navigator||!globalThis.navigator.gpu)}function getDefaultEnvironment(){return getGlobalLiteRt().getDefaultEnvironment()}function loadAndCompile(e,t){return getGlobalLiteRt().loadAndCompile(e,t)}function getWebGpuDevice(){return getGlobalLiteRt().getWebGpuDevice()}function setWebGpuDevice(e){getGlobalLiteRt().setWebGpuDevice(e)}var LiteRt=class{liteRtWasm;defaultEnvironment;objectsToDelete=new Set;constructor(e){this.liteRtWasm=e,this.liteRtWasm.setupLogging()}setDefaultEnvironment(e){this.defaultEnvironment=e}getDefaultEnvironment(){if(!this.defaultEnvironment)throw new Error("Default environment is not set.");return this.defaultEnvironment}setWebGpuDevice(e){const t=this.getDefaultEnvironment();this.setDefaultEnvironment(new Environment({...t.options,webGpuDevice:e}))}getWebGpuDevice(){return this.getDefaultEnvironment().webGpuDevice}async loadAndCompile(e,t={}){let r;if("string"==typeof e||e instanceof URL)r=await urlToUint8Array(e);else if(e instanceof Uint8Array)r=e;else{if(!(e instanceof ReadableStreamDefaultReader))throw new Error("Unsupported model type.");r=await readableStreamDefaultReaderToUint8Array(e)}const n=t.environment??this.getDefaultEnvironment(),o=t.accelerator??(n.webGpuDevice?"webgpu":"wasm");if((Array.isArray(o)?o.includes("webgpu"):"webgpu"===o)&&!n.webGpuDevice)throw new Error("WebGPU was requested but no WebGPU device is set in the environment.");const i={environment:n,accelerator:o,cpuOptions:t.cpuOptions??{numThreads:this.liteRtWasm.getThreadCount()},gpuOptions:t.gpuOptions??{},webNNOptions:t.webNNOptions??{}},s=this.liteRtWasm._malloc(r.byteLength);this.liteRtWasm.HEAPU8.set(r,s);const a=this.liteRtWasm.loadModel(i.environment.liteRtEnvironment,s,r.byteLength),l=await this.liteRtWasm.compileModel(i.environment.liteRtEnvironment,a,i),u=new Model(a,(()=>{this.liteRtWasm._free(s)})),f=new CompiledModel(u,l,i,(()=>{this.objectsToDelete.delete(f)}));return this.objectsToDelete.add(f),f}delete(){for(const e of this.objectsToDelete)e.delete()}};import{createWasmLib}from"@litertjs/wasm-utils";function pathToString(e){return e}function appendPathSegment(e,t){if(!e)return t;if(!t)return e;return(e.endsWith("/")?e:e+"/")+(t.startsWith("/")?t.substring(1):t)}var WASM_RELAXED_SIMD_CHECK=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,15,1,13,0,65,1,253,15,65,2,253,15,253,128,2,11]),WASM_THREADS_CHECK=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]),WASM_FEATURE_VALUES={relaxedSimd:void 0,threads:void 0,jspi:void 0,webnn:void 0};function isJspiSupported(){return"Suspending"in WebAssembly}function isWebNnSupported(){return"undefined"!=typeof navigator&&!!navigator.ml}async function tryWasm(e){try{return await WebAssembly.instantiate(e),{supported:!0}}catch(e){return{supported:!1,error:e}}}var WASM_FEATURE_CHECKS={relaxedSimd:()=>(void 0===WASM_FEATURE_VALUES.relaxedSimd&&(WASM_FEATURE_VALUES.relaxedSimd=tryWasm(WASM_RELAXED_SIMD_CHECK)),WASM_FEATURE_VALUES.relaxedSimd),threads:()=>{if(void 0===WASM_FEATURE_VALUES.threads)try{"undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WASM_FEATURE_VALUES.threads=tryWasm(WASM_THREADS_CHECK)}catch(e){WASM_FEATURE_VALUES.threads=Promise.resolve({supported:!1,error:e})}return WASM_FEATURE_VALUES.threads},jspi:()=>{if(void 0===WASM_FEATURE_VALUES.jspi){const e=isJspiSupported();WASM_FEATURE_VALUES.jspi=Promise.resolve({supported:e,error:e?void 0:new Error("JSPI is not supported")})}return WASM_FEATURE_VALUES.jspi},webnn:()=>{if(void 0===WASM_FEATURE_VALUES.webnn){const e=isWebNnSupported();WASM_FEATURE_VALUES.webnn=Promise.resolve({supported:e,error:e?void 0:new Error("WebNN is not supported")})}return WASM_FEATURE_VALUES.webnn}};async function supportsFeature(e){const t=WASM_FEATURE_CHECKS[e]?.();if(!t)throw new Error(`Unknown feature: ${e}`);return(await t).supported}async function throwIfFeatureNotSupported(e){const t=WASM_FEATURE_CHECKS[e]?.();if(!t)throw new Error(`Unknown feature: ${e}`);const r=await t;if(!r.supported)throw r.error}var WASM_JS_FILE_NAME="litert_wasm_internal.js",WASM_JS_COMPAT_FILE_NAME="litert_wasm_compat_internal.js",WASM_JS_THREADED_FILE_NAME="litert_wasm_threaded_internal.js",WASM_JS_JSPI_FILE_NAME="litert_wasm_jspi_internal.js";async function load(e,t){const r=pathToString(e),n=r.endsWith(".wasm")||r.endsWith(".js"),o=await supportsFeature("relaxedSimd");if(t?.threads){if(t?.jspi)throw new Error("The `threads` and `jspi` options are mutually exclusive.");if(n&&console.warn(`The \`threads\` option was specified, but the wasm path ${r} is a full file path. Whether threads are available or not will depend on the loaded file. To allow LiteRT.js to load the threaded wasm file, use a directory path instead of a full file path.`),!o)throw new Error("Threads are only supported with relaxed SIMD, and the current browser does not support relaxed SIMD.");await throwIfFeatureNotSupported("threads")}t?.jspi&&(n&&console.warn(`The \`jspi\` option was specified, but the wasm path ${r} is a full file path. Whether JSPI is available or not will depend on the loaded file. To allow LiteRT.js to load the JSPI wasm file, use a directory path instead of a full file path.`),await throwIfFeatureNotSupported("jspi"));let i=WASM_JS_COMPAT_FILE_NAME;o&&(i=t?.threads?WASM_JS_THREADED_FILE_NAME:t?.jspi?WASM_JS_JSPI_FILE_NAME:WASM_JS_FILE_NAME);let s=e;if(r.endsWith(".wasm"))throw new Error("Please load the `.js` file corresponding to the `.wasm` file, or load the directory containing it.");return r.endsWith(".js")||(s=appendPathSegment(e,i)),createWasmLib(LiteRt,s)}function loadLiteRt(e,t){if(hasGlobalLiteRtPromise())throw new Error("LiteRT is already loading / loaded.");return setGlobalLiteRtPromise(load(e,t).then((async e=>(setGlobalLiteRt(e),e.setDefaultEnvironment(await Environment.create()),e))).catch((e=>{throw setGlobalLiteRtPromise(void 0),e}))),getGlobalLiteRtPromise()}function unloadLiteRt(){if(hasGlobalLiteRtPromise()&&!hasGlobalLiteRt())throw new Error("LiteRT is loading and can not be unloaded or canceled until it is finished loading.");hasGlobalLiteRt()&&(getGlobalLiteRt().delete(),setGlobalLiteRt(void 0)),setGlobalLiteRtPromise(void 0)}async function copyHostMemoryToHostMemory(e,t={}){const r=t.environment??e.environment,n=getGlobalLiteRt().liteRtWasm,o=e.liteRtTensorBuffer;if(o.bufferType().value!==TensorBufferType.HOST_MEMORY)throw new Error("Source tensor is not in host memory. Cannot copy to host memory.");const i=o.lock(n.LiteRtTensorBufferLockMode.READ);let s;try{s=n.LiteRtTensorBuffer.createManaged(r.liteRtEnvironment,n.LiteRtTensorBufferType.HOST_MEMORY,o.tensorType(),o.size());const e=s.lock(n.LiteRtTensorBufferLockMode.WRITE);try{const t=new Uint8Array(n.HEAPU8.buffer,i,o.size());n.HEAPU8.set(t,e)}finally{s.unlock()}}finally{o.unlock()}if(!s)throw new Error("Failed to create destination tensor buffer.");return new Tensor(s,r)}async function cpuTensorToGpuTensor(e,t={}){const r=t.environment??e.environment,n=r.webGpuDevice;if(!n)throw new Error("No WebGPU device is available. Did you forget to pass a destination environment that has a WebGPU device?");const o=getGlobalLiteRt().liteRtWasm,i=e.liteRtTensorBuffer.size()+3&-4,s=n.createBuffer({size:i,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,mappedAtCreation:!0}),a=await s.getMappedRange(),l=new Uint8Array(a),u=e.liteRtTensorBuffer.lock(o.LiteRtTensorBufferLockMode.READ);try{const t=new Uint8Array(o.HEAPU8.buffer,u,e.liteRtTensorBuffer.size());l.set(t)}finally{e.liteRtTensorBuffer.unlock()}s.unmap();const f=n.createBuffer({size:i,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE}),p=n.createCommandEncoder();return p.copyBufferToBuffer(s,0,f,0,i),n.queue.submit([p.finish()]),s.destroy(),new Tensor(f,e.type.layout.dimensions,e.type.dtype,r,(()=>{f.destroy()}))}async function gpuTensorToCpuTensor(e,t={}){const r=t.environment??e.environment,n=e.environment.webGpuDevice;if(!n)throw new Error("No WebGPU device is available. Does the source tensor have a WebGPU device?");const o=getGlobalLiteRt().liteRtWasm,i=e.liteRtTensorBuffer,s=i.bufferType();if(s!==o.LiteRtTensorBufferType.WEB_GPU_BUFFER_PACKED)throw new Error(`Cannot convert a tensor with a non-WebGPU buffer type ${s} to a CPU tensor.`);const a=o.WebGPU.getJsObject(i.getWebGpuBuffer()),l=i.offset(),u=i.tensorType(),f=u.layout(),p=f.numElements(),d=getDataType(u.elementType().value).typedArrayConstructor;f.delete(),u.delete();let c=a,T=()=>{};if(!(a.usage&GPUBufferUsage.MAP_READ)){c=n.createBuffer({size:a.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),T=()=>{c.destroy()};const e=n.createCommandEncoder();e.copyBufferToBuffer(a,0,c,0,a.size),n.queue.submit([e.finish()])}await c.mapAsync(GPUMapMode.READ);const h=new d(c.getMappedRange(),l,p),y=new Tensor(h,e.type.layout.dimensions,r);return c.unmap(),T(),y}function makeMoveTo(e){return async(t,r)=>{const n=await e(t,r);return t.delete(),n}}function registerCopyFunctions(){Tensor.copyFunctions.set(TensorBufferType.HOST_MEMORY,new Map([[TensorBufferType.HOST_MEMORY,{copyTo:copyHostMemoryToHostMemory,moveTo:makeMoveTo(copyHostMemoryToHostMemory)}],[TensorBufferType.WEB_GPU_BUFFER_PACKED,{copyTo:cpuTensorToGpuTensor,moveTo:makeMoveTo(cpuTensorToGpuTensor)}]])),Tensor.copyFunctions.set(TensorBufferType.WEB_GPU_BUFFER_PACKED,new Map([[TensorBufferType.HOST_MEMORY,{copyTo:gpuTensorToCpuTensor,moveTo:makeMoveTo(gpuTensorToCpuTensor)}]]))}registerCopyFunctions();export{CompiledModel,Environment,LiteRt,LiteRtNotLoadedError,Tensor,TensorBufferType,getDefaultEnvironment,getGlobalLiteRt,getGlobalLiteRtPromise,getWebGpuDevice,isWebGPUSupported,loadAndCompile,loadLiteRt,setWebGpuDevice,supportsFeature,unloadLiteRt};
//# sourceMappingURL=/sm/dd6102b61661c5f1cf112556245ae8aa11f9d9eeda74772ad1616ea8e128e056.map