UNPKG

onnxruntime-web

Version:

A Javascript library for running ONNX models on browsers

1 lines 363 kB
{"version":3,"sources":["../../common/lib/backend-impl.ts","../../common/lib/backend.ts","../../common/lib/version.ts","../../common/lib/env-impl.ts","../../common/lib/env.ts","../../common/lib/tensor-conversion-impl.ts","../../common/lib/tensor-factory-impl.ts","../../common/lib/tensor-impl-type-mapping.ts","../../common/lib/tensor-utils-impl.ts","../../common/lib/tensor-impl.ts","../../common/lib/tensor.ts","../../common/lib/trace.ts","../../common/lib/inference-session-impl.ts","../../common/lib/inference-session.ts","../../common/lib/tensor-conversion.ts","../../common/lib/tensor-factory.ts","../../common/lib/onnx-model.ts","../../common/lib/onnx-value.ts","../../common/lib/index.ts","../lib/wasm/wasm-utils-env.ts","../lib/wasm/proxy-worker/main.ts","ort-wasm-simd-threaded.mjs","../lib/wasm/wasm-utils-import.ts","../lib/wasm/wasm-factory.ts","../lib/wasm/wasm-utils.ts","../lib/wasm/run-options.ts","../lib/wasm/session-options.ts","../lib/wasm/wasm-common.ts","../lib/wasm/wasm-utils-load-file.ts","../lib/wasm/wasm-core-impl.ts","../lib/wasm/proxy-wrapper.ts","../lib/wasm/session-handler-inference.ts","../lib/backend-wasm.ts","../lib/index.ts","../lib/version.ts"],"names":["backends","backendsSortedByPriority","registerBackend","tryResolveAndInitializeBackend","resolveBackendAndExecutionProviders","init_backend_impl","__esmMin","name","backend","priority","currentBackend","i","backendName","backendInfo","isInitializing","e","options","eps","backendHints","backendNames","errors","availableBackendNames","resolveResult","err","filteredEps","target","prop","init_backend","version","init_version","logLevelValue","env","init_env_impl","value","init_env","tensorToDataURL","tensorToImageData","init_tensor_conversion_impl","tensor","canvas","pixels2DContext","width","height","inputformat","norm","normMean","normBias","stride","rTensorPointer","gTensorPointer","bTensorPointer","aTensorPointer","j","R","G","B","A","image","channels","step","rImagePointer","gImagePointer","bImagePointer","aImagePointer","bufferToTensor","tensorFromImage","tensorFromTexture","tensorFromGpuBuffer","tensorFromMLTensor","tensorFromPinnedBuffer","init_tensor_factory_impl","init_tensor_impl","buffer","outputformat","float32Data","Tensor","isHTMLImageEle","isImageDataEle","isImageBitmap","isString","data","bufferToTensorOptions","createCanvas","createCanvasContext","tempCanvas","resolve","reject","context","newImage","img","texture","download","dispose","dims","gpuBuffer","dataType","mlTensor","type","NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP","NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP","isTypedArrayChecked","checkTypedArray","init_tensor_impl_type_mapping","isBigInt64ArrayAvailable","isBigUint64ArrayAvailable","Float16Array","isFloat16ArrayAvailable","calculateSize","tensorReshape","init_tensor_utils_impl","size","dim","arg0","arg1","arg2","expectedTypedArrayConstructor","maybeDims","typedArrayConstructor","firstElementType","mappedType","releaseData","init_tensor","TRACE","TRACE_FUNC","TRACE_FUNC_BEGIN","TRACE_FUNC_END","TRACE_EVENT_BEGIN","TRACE_EVENT_END","init_trace","deviceType","label","msg","extraMsg","stack","hasTraceFunc","InferenceSession","init_inference_session_impl","_InferenceSession","handler","feeds","fetches","isFetchesEmpty","isFetches","arg1Keys","v","results","returnValue","key","result","arg3","filePathOrUint8Array","byteOffset","byteLength","optionsWithValidatedEPs","init_inference_session","init_tensor_conversion","init_tensor_factory","init_onnx_model","init_onnx_value","esm_exports","__export","init_esm","init_wasm_utils_env","main_exports","main_default","WORKER_NAME","isProxyWorker","init_main","init_wasm_core_impl","init_wasm_factory","init_wasm_utils_import","ev","message","initializeWebAssembly","initRuntime","epName","initEp","bufferData","copyFromExternalBuffer","model","createSession","sessionMetadata","releaseSession","sessionId","inputIndices","inputs","outputIndices","run","outputs","o","extractTransferableBuffers","endProfiling","urlOverride","scriptSrc","ort_wasm_simd_threaded_exports","ort_wasm_simd_threaded_default","r","init_ort_wasm_simd_threaded","t","n","s","u","f","c","l","d","m","D","g","h","p","b","w","O","_","y","T","C","E","S","M","k","U","F","L","x","W","N","I","P","qr","me","Pr","fe","Pe","$","he","$e","$r","Nr","H","Y","Q","z","V","Wr","pe","we","Te","Ae","Ce","Ee","Re","Se","Me","ke","Ue","De","Fe","Be","xe","We","Ne","Le","He","Ye","Qe","ze","Ve","Ze","Je","Ke","er","nr","ir","ur","cr","lr","or","dr","mr","gr","tr","hr","vr","pr","_r","yr","Er","Sr","ne","Mr","kr","Ur","Fr","re","X","q","Z","J","ae","le","ce","ie","se","K","ee","a","Xr","jr","Lr","Vr","te","oe","ue","Gr","Ir","de","zr","ge","Hr","ve","be","Oe","_e","ye","Ie","Qr","Ge","xr","Br","je","Xe","qe","rr","Yr","ar","sr","fr","br","wr","Or","Tr","Ar","Cr","Rr","Dr","origin","isEsmImportMetaUrlHardcodedAsFileUri","getScriptSrc","inferWasmPathPrefixFromScriptSrc","isSameOrigin","normalizeUrl","fallbackUrl","preload","dynamicImportDefault","createProxyWorker","importProxyWorker","embeddedWasmModule","importWasmModule","URL2","filename","prefixOverride","baseUrl","absoluteUrl","blob","url","isMultiThreaded","isWasmOverridden","useEmbeddedModule","wasmModuleFilename","wasmModuleUrl","needPreload","wasm","initialized","initializing","aborted","isMultiThreadSupported","isSimdSupported","isRelaxedSimdSupported","getInstance","flags","timeout","numThreads","multiThreadSupported","wasmPaths","wasmPrefixOverride","mjsPathOverrideFlag","mjsPathOverride","wasmPathOverrideFlag","wasmPathOverride","wasmBinaryOverride","objectUrl","ortWasmFactory","isTimeout","tasks","config","fileName","inferredWasmPathPrefix","module","what","allocWasmString","iterateExtraOptions","checkLastError","init_wasm_utils","allocs","dataLength","dataOffset","prefix","seen","ptrSize","paramsOffset","errorCode","errorMessagePointer","errorMessage","setRunOptions","init_run_options","runOptionsHandle","runOptions","tagDataOffset","keyDataOffset","valueDataOffset","alloc","getGraphOptimzationLevel","getExecutionMode","appendDefaultOptions","appendSessionConfig","setExecutionProviders","setSessionOptions","init_session_options","graphOptimizationLevel","executionMode","session","ep","sessionOptionsHandle","executionProviders","epOptions","webgpuOptions","epNameDataOffset","epOptionsCount","keysOffset","valuesOffset","sessionOptions","logIdDataOffset","logSeverityLevel","logVerbosityLevel","optimizedModelFilePathOffset","nameOffset","tensorDataTypeStringToEnum","tensorDataTypeEnumToString","calculateTensorSizeInBytes","tensorTypeToTypedArrayConstructor","logLevelStringToEnum","isGpuBufferSupportedType","isMLTensorSupportedType","dataLocationStringToEnum","init_wasm_common","typeProto","dateType","dimsOrSize","elementSize","logLevel","location","loadFile","init_wasm_utils_load_file","file","readFile","createReadStream","stream","chunks","chunk","response","contentLengthHeader","fileSize","reader","pages","offset","done","chunkSize","initOrt","activeSessions","getSessionInputOutputCount","getSessionInputOutputMetadata","prepareInputOutputTensor","loggingLevel","webgpuAdapter","powerPreference","forceFallbackAdapter","sessionHandle","index","metadataOffset","elementType","dimsCount","symbolicDimNameOffset","modelDataOffset","modelData","modelDataLength","ioBindingHandle","inputNamesUTF8Encoded","outputNamesUTF8Encoded","loadingPromises","path","provider","webnnOptions","gpuDevice","inputCount","outputCount","enableGraphCapture","inputNames","outputNames","inputMetadata","outputMetadata","outputPreferredLocations","shape","nameString","buf","ioBindingState","tensorHandles","tensorNameUTF8Encoded","actualLocation","rawData","dataByteLength","registerBuffer","registerMLTensor","isGraphInput","isGraphOutput","tensorName","dataTypeEnum","createTemporaryTensor","uploadTensor","tensorId","dimsOffset","inputTensors","outputTensors","inputOutputBound","runOptionsAllocs","inputTensorHandles","outputTensorHandles","inputOutputAllocs","beforeRunStack","inputValuesOffset","inputNamesOffset","outputValuesOffset","outputNamesOffset","output","outputPromises","beforeGetTensorDataStack","tensorDataOffset","keepOutputTensor","valueType","dimsLength","preferredLocation","stringData","nextOffset","maxBytesToRead","getBuffer","bufferSize","ensureTensor","isGraphInputOutputTypeSupported","profileFileName","tensors","buffers","isProxy","proxyWorker","temporaryObjectUrl","initWasmCallbacks","queuedCallbacks","enqueueCallbacks","ensureWorker","onProxyWorkerMessage","initializeWebAssemblyAndOrtRuntime","initializeOrtEp","init_proxy_wrapper","callbacks","queue","worker","transferable","serializableInputs","encodeTensorMetadata","decodeTensorMetadata","OnnxruntimeWebAssemblySessionHandler","init_session_handler_inference","getName","pathOrBuffer","inputArray","kvp","outputArray","resultMap","backend_wasm_exports","OnnxruntimeWebAssemblyBackend","initializeFlags","wasmBackend","init_backend_wasm","simd","numCpuLogicalCores","index_default"],"mappings":";;;;;usBAAA,IAgBMA,GACAC,GAYOC,GAwCPC,GAwCOC,GA7GbC,GAAAC,EAAA,kBAgBMN,GAAqC,IAAI,IACzCC,GAAqC,CAAA,EAY9BC,GAAkB,CAACK,EAAcC,EAAkBC,IAA0B,CACxF,GAAID,GAAW,OAAOA,EAAQ,MAAS,YAAc,OAAOA,EAAQ,+BAAkC,WAAY,CAChH,IAAME,EAAiBV,GAAS,IAAIO,CAAI,EACxC,GAAIG,IAAmB,OACrBV,GAAS,IAAIO,EAAM,CAAE,QAAAC,EAAS,SAAAC,CAAQ,CAAE,MACnC,IAAIC,EAAe,SAAWD,EAEnC,OACK,GAAIC,EAAe,WAAaD,GACjCC,EAAe,UAAYF,EAC7B,MAAM,IAAI,MAAM,4BAA4BD,CAAI,oBAAoBE,CAAQ,EAAE,EAIlF,GAAIA,GAAY,EAAG,CACjB,IAAME,EAAIV,GAAyB,QAAQM,CAAI,EAC3CI,IAAM,IACRV,GAAyB,OAAOU,EAAG,CAAC,EAGtC,QAASA,EAAI,EAAGA,EAAIV,GAAyB,OAAQU,IACnD,GAAIX,GAAS,IAAIC,GAAyBU,CAAC,CAAC,EAAG,UAAYF,EAAU,CACnER,GAAyB,OAAOU,EAAG,EAAGJ,CAAI,EAC1C,OAGJN,GAAyB,KAAKM,CAAI,EAEpC,OAGF,MAAM,IAAI,UAAU,qBAAqB,CAC3C,EAQMJ,GAAiC,MAAOS,GAAkD,CAC9F,IAAMC,EAAcb,GAAS,IAAIY,CAAW,EAC5C,GAAI,CAACC,EACH,MAAO,qBAGT,GAAIA,EAAY,YACd,OAAOA,EAAY,QACd,GAAIA,EAAY,QACrB,OAAOA,EAAY,MACd,CACL,IAAMC,EAAiB,CA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AAI,KAAK,WAAa,MACjB,CACL,IAAMmjB,EACJ,OAAO,UAAc,IAAc,GAAQ,SAAS,EAAE,KAAK,EAAE,OAAS,UAAU,oBAClFnjB,EAAI,KAAK,WAAa,KAAK,IAAI,EAAG,KAAK,MAAMmjB,GAAsB,GAAK,CAAC,CAAC,CAC5E,CAEJ,EAEaL,GAAN,KAAuD,CAS5D,MAAM,KAAKjkB,EAAoC,CAE7CkkB,GAAgB,EAGhB,MAAMpB,GAAmC,EAGzC,MAAMC,GAAgB/iB,CAAW,CACnC,CASA,MAAM,8BACJ2jB,EACAvjB,EACkC,CAClC,IAAM0H,EAAU,IAAI0b,GACpB,aAAM1b,EAAQ,UAAU6b,EAAcvjB,CAAO,EACtC0H,CACT,CACF,EAEaqc,GAAc,IAAIF,KCtF/B5a,KACAA,KAGAA,KCPO,IAAMrI,GAAU,SDKvB,IAAOujB,GAAQpb,GAwBe,CAC5B,IAAMgb,EAAc,cAA0B,YAO9C7kB,GAAgB,MAAO6kB,EAAa,EAAE,EACtC7kB,GAAgB,OAAQ6kB,EAAa,EAAE,CACzC,CAEA,OAAO,eAAehjB,EAAI,SAAU,MAAO,CAAE,MAAOH,GAAS,WAAY,EAAK,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Backend } from './backend.js';\nimport { InferenceSession } from './inference-session.js';\n\ninterface BackendInfo {\n  backend: Backend;\n  priority: number;\n\n  initPromise?: Promise<void>;\n  initialized?: boolean;\n  aborted?: boolean;\n  error?: string;\n}\n\nconst backends: Map<string, BackendInfo> = new Map();\nconst backendsSortedByPriority: string[] = [];\n\n/**\n * Register a backend.\n *\n * @param name - the name as a key to lookup as an execution provider.\n * @param backend - the backend object.\n * @param priority - an integer indicating the priority of the backend. Higher number means higher priority. if priority\n * < 0, it will be considered as a 'beta' version and will not be used as a fallback backend by default.\n *\n * @ignore\n */\nexport const registerBackend = (name: string, backend: Backend, priority: number): void => {\n  if (backend && typeof backend.init === 'function' && typeof backend.createInferenceSessionHandler === 'function') {\n    const currentBackend = backends.get(name);\n    if (currentBackend === undefined) {\n      backends.set(name, { backend, priority });\n    } else if (currentBackend.priority > priority) {\n      // same name is already registered with a higher priority. skip registeration.\n      return;\n    } else if (currentBackend.priority === priority) {\n      if (currentBackend.backend !== backend) {\n        throw new Error(`cannot register backend \"${name}\" using priority ${priority}`);\n      }\n    }\n\n    if (priority >= 0) {\n      const i = backendsSortedByPriority.indexOf(name);\n      if (i !== -1) {\n        backendsSortedByPriority.splice(i, 1);\n      }\n\n      for (let i = 0; i < backendsSortedByPriority.length; i++) {\n        if (backends.get(backendsSortedByPriority[i])!.priority <= priority) {\n          backendsSortedByPriority.splice(i, 0, name);\n          return;\n        }\n      }\n      backendsSortedByPriority.push(name);\n    }\n    return;\n  }\n\n  throw new TypeError('not a valid backend');\n};\n\n/**\n * Try to resolve and initialize a backend.\n *\n * @param backendName - the name of the backend.\n * @returns the backend instance if resolved and initialized successfully, or an error message if failed.\n */\nconst tryResolveAndInitializeBackend = async (backendName: string): Promise<Backend | string> => {\n  const backendInfo = backends.get(backendName);\n  if (!backendInfo) {\n    return 'backend not found.';\n  }\n\n  if (backendInfo.initialized) {\n    return backendInfo.backend;\n  } else if (backendInfo.aborted) {\n    return backendInfo.error!;\n  } else {\n    const isInitializing = !!backendInfo.initPromise;\n    try {\n      if (!isInitializing) {\n        backendInfo.initPromise = backendInfo.backend.init(backendName);\n      }\n      await backendInfo.initPromise;\n      backendInfo.initialized = true;\n      return backendInfo.backend;\n    } catch (e) {\n      if (!isInitializing) {\n        backendInfo.error = `${e}`;\n        backendInfo.aborted = true;\n      }\n      return backendInfo.error!;\n    } finally {\n      delete backendInfo.initPromise;\n    }\n  }\n};\n\n/**\n * Resolve execution providers from the specific session options.\n *\n * @param options - the session options object.\n * @returns a promise that resolves to a tuple of an initialized backend instance and a session options object with\n * filtered EP list.\n *\n * @ignore\n */\nexport const resolveBackendAndExecutionProviders = async (\n  options: InferenceSession.SessionOptions,\n): Promise<[backend: Backend, options: InferenceSession.SessionOptions]> => {\n  // extract backend hints from session options\n  const eps = options.executionProviders || [];\n  const backendHints = eps.map((i) => (typeof i === 'string' ? i : i.name));\n  const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;\n\n  // try to resolve and initialize all requested backends\n  let backend: Backend | undefined;\n  const errors = [];\n  const availableBackendNames = new Set<string>();\n  for (const backendName of backendNames) {\n    const resolveResult = await tryResolveAndInitializeBackend(backendName);\n    if (typeof resolveResult === 'string') {\n      errors.push({ name: backendName, err: resolveResult });\n    } else {\n      if (!backend) {\n        backend = resolveResult;\n      }\n      if (backend === resolveResult) {\n        availableBackendNames.add(backendName);\n      }\n    }\n  }\n\n  // if no backend is available, throw error.\n  if (!backend) {\n    throw new Error(`no available backend found. ERR: ${errors.map((e) => `[${e.name}] ${e.err}`).join(', ')}`);\n  }\n\n  // for each explicitly requested backend, if it's not available, output warning message.\n  for (const { name, err } of errors) {\n    if (backendHints.includes(name)) {\n      // eslint-disable-next-line no-console\n      console.warn(\n        `removing requested execution provider \"${name}\" from session options because it is not available: ${err}`,\n      );\n    }\n  }\n\n  const filteredEps = eps.filter((i) => availableBackendNames.has(typeof i === 'string' ? i : i.name));\n\n  return [\n    backend,\n    new Proxy(options, {\n      get: (target, prop) => {\n        if (prop === 'executionProviders') {\n          return filteredEps;\n        }\n        return Reflect.get(target, prop);\n      },\n    }),\n  ];\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { InferenceSession } from './inference-session.js';\nimport { OnnxValue } from './onnx-value.js';\n\n/**\n * @ignore\n */\nexport declare namespace SessionHandler {\n  type FeedsType = { [name: string]: OnnxValue };\n  type FetchesType = { [name: string]: OnnxValue | null };\n  type ReturnType = { [name: string]: OnnxValue };\n}\n\n/**\n * Represents shared SessionHandler functionality\n *\n * @ignore\n */\ninterface SessionHandler {\n  dispose(): Promise<void>;\n\n  readonly inputNames: readonly string[];\n  readonly outputNames: readonly string[];\n\n  readonly inputMetadata: readonly InferenceSession.ValueMetadata[];\n  readonly outputMetadata: readonly InferenceSession.ValueMetadata[];\n}\n\n/**\n * Represent a handler instance of an inference session.\n *\n * @ignore\n */\nexport interface InferenceSessionHandler extends SessionHandler {\n  startProfiling(): void;\n  endProfiling(): void;\n\n  run(\n    feeds: SessionHandler.FeedsType,\n    fetches: SessionHandler.FetchesType,\n    options: InferenceSession.RunOptions,\n  ): Promise<SessionHandler.ReturnType>;\n}\n\n/**\n * Represent a backend that provides implementation of model inferencing.\n *\n * @ignore\n */\nexport interface Backend {\n  /**\n   * Initialize the backend asynchronously. Should throw when failed.\n   */\n  init(backendName: string): Promise<void>;\n\n  createInferenceSessionHandler(\n    uriOrBuffer: string | Uint8Array,\n    options?: InferenceSession.SessionOptions,\n  ): Promise<InferenceSessionHandler>;\n}\n\nexport { registerBackend } from './backend-impl.js';\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n// This file is generated by /js/scripts/update-version.ts\n// Do not modify file content manually.\n\nexport const version = '1.23.2';\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Env } from './env.js';\nimport { version } from './version.js';\n\ntype LogLevelType = Env['logLevel'];\n\nlet logLevelValue: Required<LogLevelType> = 'warning';\n\nexport const env: Env = {\n  wasm: {} as Env.WebAssemblyFlags,\n  webgl: {} as Env.WebGLFlags,\n  webgpu: {} as Env.WebGpuFlags,\n  versions: { common: version },\n\n  set logLevel(value: LogLevelType) {\n    if (value === undefined) {\n      return;\n    }\n    if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) {\n      throw new Error(`Unsupported logging level: ${value}`);\n    }\n    logLevelValue = value;\n  },\n  get logLevel(): Required<LogLevelType> {\n    return logLevelValue;\n  },\n};\n\n// set property 'logLevel' so that they can be correctly transferred to worker by `postMessage()`.\nObject.defineProperty(env, 'logLevel', { enumerable: true });\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { env as envImpl } from './env-impl.js';\nimport { TryGetGlobalType } from './type-helper.js';\n\nexport declare namespace Env {\n  export type WasmPathPrefix = string;\n  export interface WasmFilePaths {\n    /**\n     * Specify the override path for the main .wasm file.\n     *\n     * This path should be an absolute path.\n     *\n     * If not modified, the filename of the .wasm file is:\n     * - `ort-wasm-simd-threaded.wasm` for default build\n     * - `ort-wasm-simd-threaded.jsep.wasm` for JSEP build (with WebGPU and WebNN)\n     * - `ort-wasm-simd-threaded.asyncify.wasm` for WebGPU build with Asyncify (with WebNN)\n     */\n    wasm?: URL | string;\n    /**\n     * Specify the override path for the main .mjs file.\n     *\n     * This path should be an absolute path.\n     *\n     * If not modified, the filename of the .mjs file is:\n     * - `ort-wasm-simd-threaded.mjs` for default build\n     * - `ort-wasm-simd-threaded.jsep.mjs` for JSEP build (with WebGPU and WebNN)\n     * - `ort-wasm-simd-threaded.asyncify.mjs` for WebGPU build with Asyncify (with WebNN)\n     */\n    mjs?: URL | string;\n  }\n  export type WasmPrefixOrFilePaths = WasmPathPrefix | WasmFilePaths;\n  export interface WebAssemblyFlags {\n    /**\n     * set or get number of thread(s). If omitted or set to 0, number of thread(s) will be determined by system. If set\n     * to 1, no worker thread will be spawned.\n     *\n     * This setting is available only when WebAssembly multithread feature is available in current context.\n     *\n     * @defaultValue `0`\n     */\n    numThreads?: number;\n\n    /**\n     * set a value indicating whether to enable SIMD.\n     *\n     * ONNX Runtime will perform feature detection based on the value of this property. Specifically, when the value is\n     * set to:\n     * - `undefined`, `true` or `\"fixed\"`: will check availability of Fixed-width SIMD.\n     * - `\"relaxed\"`: will check availability of Relaxed SIMD.\n     * - `false`: will not perform SIMD feature checking.\n     *\n     * Setting this property does not make ONNX Runtime to switch to the corresponding runtime automatically. User need\n     * to set `wasmPaths` or `wasmBinary` property to load the corresponding runtime.\n     *\n     * This setting is available only when WebAssembly SIMD feature is available in current context.\n     *\n     * @defaultValue `true`\n     */\n    simd?: boolean | 'fixed' | 'relaxed';\n\n    /**\n     * set or get a boolean value indicating whether to enable trace.\n     *\n     * @defaultValue `false`\n     *\n     * @deprecated Use `env.trace` instead. If `env.trace` is set, this property will be ignored.\n     */\n    trace?: boolean;\n\n    /**\n     * Set or get a number specifying the timeout for initialization of WebAssembly backend, in milliseconds. A zero\n     * value indicates no timeout is set.\n     *\n     * @defaultValue `0`\n     */\n    initTimeout?: number;\n\n    /**\n     * Set a custom URL prefix to the .wasm/.mjs files, or an object of overrides for both .wasm/.mjs file. The override\n     * path should be an absolute path.\n     */\n    wasmPaths?: WasmPrefixOrFilePaths;\n\n    /**\n     * Set a custom buffer which contains the WebAssembly binary. If this property is set, the `wasmPaths` property will\n     * be ignored.\n     */\n    wasmBinary?: ArrayBufferLike | Uint8Array;\n\n    /**\n     * Set or get a boolean value indicating whether to proxy the execution of main thread to a worker thread.\n     *\n     * @defaultValue `false`\n     */\n    proxy?: boolean;\n  }\n\n  export interface WebGLFlags {\n    /**\n     * Set or get the WebGL Context ID (webgl or webgl2).\n     *\n     * @defaultValue `'webgl2'`\n     */\n    contextId?: 'webgl' | 'webgl2';\n    /**\n     * Get the WebGL rendering context.\n     */\n    readonly context: WebGLRenderingContext;\n    /**\n     * Set or get the maximum batch size for matmul. 0 means to disable batching.\n     *\n     * @deprecated\n     */\n    matmulMaxBatchSize?: number;\n    /**\n     * Set or get the texture cache mode.\n     *\n     * @defaultValue `'full'`\n     */\n    textureCacheMode?: 'initializerOnly' | 'full';\n    /**\n     * Set or get the packed texture mode\n     *\n     * @defaultValue `false`\n     */\n    pack?: boolean;\n    /**\n     * Set or get whether enable async download.\n     *\n     * @defaultValue `false`\n     */\n    async?: boolean;\n  }\n\n  export interface WebGpuProfilingDataV1TensorMetadata {\n    dims: readonly number[];\n    dataType: string;\n  }\n  export interface WebGpuProfilingDataV1 {\n    version: 1;\n    inputsMetadata: readonly WebGpuProfilingDataV1TensorMetadata[];\n    outputsMetadata: readonly WebGpuProfilingDataV1TensorMetadata[];\n    kernelId: number;\n    kernelType: string;\n    kernelName: string;\n    programName: string;\n    startTime: number;\n    endTime: number;\n  }\n\n  export type WebGpuProfilingData = WebGpuProfilingDataV1;\n\n  export interface WebGpuFlags {\n    /**\n     * Set or get the profiling mode.\n     *\n     * @deprecated Use `env.webgpu.profiling.mode` instead. If `env.webgpu.profiling.mode` is set, this property will be\n     * ignored.\n     */\n    profilingMode?: 'off' | 'default';\n    /**\n     * Set or get the profiling configuration.\n     */\n    profiling: {\n      /**\n       * Set or get the profiling mode.\n       *\n       * @defaultValue `'off'`\n       */\n      mode?: 'off' | 'default';\n\n      /**\n       * Set or get a callback function when a profiling data is received. If not set, the profiling data will be\n       * printed to console.\n       */\n      ondata?: (data: WebGpuProfilingData) => void;\n    };\n    /**\n     * Set or get the power preference.\n     *\n     * Setting this property only has effect before the first WebGPU inference session is created. The value will be\n     * used as options for `navigator.gpu.requestAdapter()`.\n     *\n     * See {@link https://gpuweb.github.io/gpuweb/#dictdef-gpurequestadapteroptions} for more details.\n     *\n     * @defaultValue `undefined`\n     *\n     * @deprecated Create your own GPUAdapter, use it to create a GPUDevice instance and set {@link device} property if\n     * you want to use a specific power preference.\n     */\n    powerPreference?: 'low-power' | 'high-performance';\n    /**\n     * Set or get the force fallback adapter flag.\n     *\n     * Setting this property only has effect before the first WebGPU inference session is created. The value will be\n     * used as options for `navigator.gpu.requestAdapter()`.\n     *\n     * See {@link https://gpuweb.github.io/gpuweb/#dictdef-gpurequestadapteroptions} for more details.\n     *\n     * @defaultValue `undefined`\n     *\n     * @deprecated Create your own GPUAdapter, use it to create a GPUDevice instance and set {@link device} property if\n     * you want to use a specific fallback option.\n     */\n    forceFallbackAdapter?: boolean;\n    /**\n     * Set or get the adapter for WebGPU.\n     *\n     * Setting this property only has effect before the first WebGPU inference session is created. The value will be\n     * used as the GPU adapter for the underlying WebGPU backend to create GPU device.\n     *\n     * If this property is not set, it will be available to get after the first WebGPU inference session is created. The\n     * value will be the GPU adapter that created by the underlying WebGPU backend.\n     *\n     * When use with TypeScript, the type of this property is `GPUAdapter` defined in \"@webgpu/types\".\n     *\n     * @deprecated It is no longer recommended to use this property. The latest WebGPU spec adds `GPUDevice.adapterInfo`\n     * (https://www.w3.org/TR/webgpu/#dom-gpudevice-adapterinfo), which allows to get the adapter information from the\n     * device. When it's available, there is no need to set/get the {@link adapter} property.\n     */\n    adapter: TryGetGlobalType<'GPUAdapter'>;\n    /**\n     * Set or get the GPU device for WebGPU.\n     *\n     * There are 3 valid scenarios of accessing this property:\n     * - Set a value before the first WebGPU inference session is created. The value will be used by the WebGPU backend\n     * to perform calculations. If the value is not a `GPUDevice` object, an error will be thrown.\n     * - Get the value before the first WebGPU inference session is created. This will try to create a new GPUDevice\n     * instance. Returns a `Promise` that resolves to a `GPUDevice` object.\n     * - Get the value after the first WebGPU inference session is created. Returns a resolved `Promise` to the\n     * `GPUDevice` object used by the WebGPU backend.\n     */\n    get device(): Promise<TryGetGlobalType<'GPUDevice'>>;\n    set device(value: TryGetGlobalType<'GPUDevice'>);\n    /**\n     * Set or get whether validate input content.\n     *\n     * @defaultValue `false`\n     */\n    validateInputContent?: boolean;\n  }\n}\n\nexport interface Env {\n  /**\n   * set the severity level for logging.\n   *\n   * @defaultValue `'warning'`\n   */\n  logLevel?: 'verbose' | 'info' | 'warning' | 'error' | 'fatal';\n\n  /**\n   * Indicate whether run in debug mode.\n   *\n   * @defaultValue `false`\n   */\n  debug?: boolean;\n\n  /**\n   * set or get a boolean value indicating whether to enable trace.\n   *\n   * @defaultValue `false`\n   */\n  trace?: boolean;\n\n  /**\n   * Get version of the current package.\n   */\n  readonly versions: {\n    readonly common: string;\n    readonly web?: string;\n    readonly node?: string;\n    // eslint-disable-next-line @typescript-eslint/naming-convention\n    readonly 'react-native'?: string;\n  };\n\n  /**\n   * Represent a set of flags for WebAssembly\n   */\n  readonly wasm: Env.WebAssemblyFlags;\n\n  /**\n   * Represent a set of flags for WebGL\n   */\n  readonly webgl: Env.WebGLFlags;\n\n  /**\n   * Represent a set of flags for WebGPU\n   */\n  readonly webgpu: Env.WebGpuFlags;\n\n  [name: string]: unknown;\n}\n\n/**\n * Represent a set of flags as a global singleton.\n */\nexport const env: Env = envImpl;\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { TensorToDataUrlOptions, TensorToImageDataOptions } from './tensor-conversion.js';\nimport { Tensor } from './tensor.js';\n\n/**\n * implementation of Tensor.toDataURL()\n */\nexport const tensorToDataURL = (tensor: Tensor, options?: TensorToDataUrlOptions): string => {\n  const canvas = typeof document !== 'undefined' ? document.createElement('canvas') : new OffscreenCanvas(1, 1);\n  canvas.width = tensor.dims[3];\n  canvas.height = tensor.dims[2];\n  const pixels2DContext = canvas.getContext('2d') as\n    | CanvasRenderingContext2D\n    | OffscreenCanvasRenderingContext2D\n    | null;\n\n  if (pixels2DContext != null) {\n    // Default values for height and width & format\n    let width: number;\n    let height: number;\n    if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n      width = tensor.dims[2];\n      height = tensor.dims[3];\n    } else {\n      // Default layout is NCWH\n      width = tensor.dims[3];\n      height = tensor.dims[2];\n    }\n\n    const inputformat = options?.format !== undefined ? options.format : 'RGB';\n\n    const norm = options?.norm;\n    let normMean: [number, number, number, number];\n    let normBias: [number, number, number, number];\n    if (norm === undefined || norm.mean === undefined) {\n      normMean = [255, 255, 255, 255];\n    } else {\n      if (typeof norm.mean === 'number') {\n        normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n      } else {\n        normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0];\n        if (norm.mean[3] !== undefined) {\n          normMean[3] = norm.mean[3];\n        }\n      }\n    }\n    if (norm === undefined || norm.bias === undefined) {\n      normBias = [0, 0, 0, 0];\n    } else {\n      if (typeof norm.bias === 'number') {\n        normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n      } else {\n        normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n        if (norm.bias[3] !== undefined) {\n          normBias[3] = norm.bias[3];\n        }\n      }\n    }\n\n    const stride = height * width;\n    // Default pointer assignments\n    let rTensorPointer = 0,\n      gTensorPointer = stride,\n      bTensorPointer = stride * 2,\n      aTensorPointer = -1;\n\n    // Updating the pointer assignments based on the input image format\n    if (inputformat === 'RGBA') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n      aTensorPointer = stride * 3;\n    } else if (inputformat === 'RGB') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n    } else if (inputformat === 'RBG') {\n      rTensorPointer = 0;\n      bTensorPointer = stride;\n      gTensorPointer = stride * 2;\n    }\n\n    for (let i = 0; i < height; i++) {\n      for (let j = 0; j < width; j++) {\n        const R = ((tensor.data[rTensorPointer++] as number) - normBias[0]) * normMean[0]; // R value\n        const G = ((tensor.data[gTensorPointer++] as number) - normBias[1]) * normMean[1]; // G value\n        const B = ((tensor.data[bTensorPointer++] as number) - normBias[2]) * normMean[2]; // B value\n        const A = aTensorPointer === -1 ? 255 : ((tensor.data[aTensorPointer++] as number) - normBias[3]) * normMean[3]; // A value\n        // eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n        pixels2DContext.fillStyle = 'rgba(' + R + ',' + G + ',' + B + ',' + A + ')';\n        pixels2DContext.fillRect(j, i, 1, 1);\n      }\n    }\n    if ('toDataURL' in canvas) {\n      return canvas.toDataURL();\n    } else {\n      throw new Error('toDataURL is not supported');\n    }\n  } else {\n    throw new Error('Can not access image data');\n  }\n};\n\n/**\n * implementation of Tensor.toImageData()\n */\nexport const tensorToImageData = (tensor: Tensor, options?: TensorToImageDataOptions): ImageData => {\n  const pixels2DContext =\n    typeof document !== 'undefined'\n      ? document.createElement('canvas').getContext('2d')\n      : (new OffscreenCanvas(1, 1).getContext('2d') as OffscreenCanvasRenderingContext2D);\n  let image: ImageData;\n  if (pixels2DContext != null) {\n    // Default values for height and width & format\n    let width: number;\n    let height: number;\n    let channels: number;\n    if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') {\n      width = tensor.dims[2];\n      height = tensor.dims[1];\n      channels = tensor.dims[3];\n    } else {\n      // Default layout is NCWH\n      width = tensor.dims[3];\n      height = tensor.dims[2];\n      channels = tensor.dims[1];\n    }\n    const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB';\n\n    const norm = options?.norm;\n    let normMean: [number, number, number, number];\n    let normBias: [number, number, number, number];\n    if (norm === undefined || norm.mean === undefined) {\n      normMean = [255, 255, 255, 255];\n    } else {\n      if (typeof norm.mean === 'number') {\n        normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n      } else {\n        normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255];\n        if (norm.mean[3] !== undefined) {\n          normMean[3] = norm.mean[3];\n        }\n      }\n    }\n    if (norm === undefined || norm.bias === undefined) {\n      normBias = [0, 0, 0, 0];\n    } else {\n      if (typeof norm.bias === 'number') {\n        normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n      } else {\n        normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0];\n        if (norm.bias[3] !== undefined) {\n          normBias[3] = norm.bias[3];\n        }\n      }\n    }\n\n    const stride = height * width;\n    if (options !== undefined) {\n      if (\n        (options.format !== undefined && channels === 4 && options.format !== 'RGBA') ||\n        (channels === 3 && options.format !== 'RGB' && options.format !== 'BGR')\n      ) {\n        throw new Error(\"Tensor format doesn't match input tensor dims\");\n      }\n    }\n\n    // Default pointer assignments\n    const step = 4;\n    let rImagePointer = 0,\n      gImagePointer = 1,\n      bImagePointer = 2,\n      aImagePointer = 3;\n    let rTensorPointer = 0,\n      gTensorPointer = stride,\n      bTensorPointer = stride * 2,\n      aTensorPointer = -1;\n\n    // Updating the pointer assignments based on the input image format\n    if (inputformat === 'RGBA') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n      aTensorPointer = stride * 3;\n    } else if (inputformat === 'RGB') {\n      rTensorPointer = 0;\n      gTensorPointer = stride;\n      bTensorPointer = stride * 2;\n    } else if (inputformat === 'RBG') {\n      rTensorPointer = 0;\n      bTensorPointer = stride;\n      gTensorPointer = stride * 2;\n    }\n\n    image = pixels2DContext.createImageData(width, height);\n\n    for (\n      let i = 0;\n      i < height * width;\n      rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++\n    ) {\n      image.data[rImagePointer] = ((tensor.data[rTensorPointer++] as number) - normBias[0]) * normMean[0]; // R value\n      image.data[gImagePointer] = ((tensor.data[gTensorPointer++] as number) - normBias[1]) * normMean[1]; // G value\n      image.data[bImagePointer] = ((tensor.data[bTensorPointer++] as number) - normBias[2]) * normMean[2]; // B value\n      image.data[aImagePointer] =\n        aTensorPointer === -1 ? 255 : ((tensor.data[aTensorPointer++] as number) - normBias[3]) * normMean[3]; // A value\n    }\n  } else {\n    throw new Error('Can not access image data');\n  }\n  return image;\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {\n  OptionsDimensions,\n  OptionsFormat,\n  OptionsNormalizationParameters,\n  OptionsTensorFormat,\n  OptionsTensorLayout,\n  TensorFromGpuBufferOptions,\n  TensorFromImageBitmapOptions,\n  TensorFromImageDataOptions,\n  TensorFromImageElementOptions,\n  TensorFromMLTensorOptions,\n  TensorFromTextureOptions,\n  TensorFromUrlOptions,\n} from './tensor-factory.js';\nimport { Tensor } from './tensor-impl.js';\nimport { Tensor as TensorInterface } from './tensor.js';\n\ninterface BufferToTensorOptions\n  extends OptionsDimensions,\n    OptionsTensorLayout,\n    OptionsNormalizationParameters,\n    OptionsFormat,\n    OptionsTensorFormat {}\n\n/**\n * Create a new tensor object from image object\n *\n * @param buffer - Extracted image buffer data - assuming RGBA format\n * @param imageFormat - input image configuration - required configurations height, width, format\n * @param tensorFormat - output tensor configuration - Default is RGB format\n */\nexport const bufferToTensor = (buffer: Uint8ClampedArray | undefined, options: BufferToTensorOptions): Tensor => {\n  if (buffer === undefined) {\n    throw new Error('Image buffer must be defined');\n  }\n  if (options.height === undefined || options.width === undefined) {\n    throw new Error('Image height and width must be defined');\n  }\n  if (options.tensorLayout === 'NHWC') {\n    throw new Error('NHWC Tensor layout is not supported yet');\n  }\n\n  const { height, width } = options;\n\n  const norm = options.norm ?? { mean: 255, bias: 0 };\n  let normMean: [number, number, number, number];\n  let normBias: [number, number, number, number];\n\n  if (typeof norm.mean === 'number') {\n    normMean = [norm.mean, norm.mean, norm.mean, norm.mean];\n  } else {\n    normMean = [norm.mean![0], norm.mean![1], norm.mean![2], norm.mean![3] ?? 255];\n  }\n\n  if (typeof norm.bias === 'number') {\n    normBias = [norm.bias, norm.bias, norm.bias, norm.bias];\n  } else {\n    normBias = [norm.bias![0], norm.bias![1], norm.bias![2], norm.bias![3] ?? 0];\n  }\n\n  const inputformat = options.format !== undefined ? options.format : 'RGBA';\n  // default value is RGBA since imagedata and HTMLImageElement uses it\n\n  const outputformat =\n    options.tensorFormat !== undefined ? (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') : 'RGB';\n  const stride = height * width;\n  const float32Data = outputformat === 'RGBA' ? new Float32Array(stride * 4) : new Float32Array(stride * 3);\n\n  // Default pointer assignments\n  let step = 4,\n    rImagePointer = 0,\n    gImagePointer = 1,\n    bImagePointer = 2,\n    aImagePointer = 3;\n  let rTensorPointer = 0,\n    gTensorPointer = stride,\n    bTensorPointer = stride * 2,\n    aTensorPointer = -1;\n\n  // Updating the pointer assignments based on the input image format\n  if (inputformat === 'RGB') {\n    step = 3;\n    rImagePointer = 0;\n    gImagePointer = 1;\n    bImagePointer = 2;\n    aImagePointer = -1;\n  }\n\n  // Updating the pointer assignments based on the output tensor format\n  if (outputformat === 'RGBA') {\n    aTensorPointer = stride * 3;\n  } else if (outputformat === 'RBG') {\n    rTensorPointer = 0;\n    bTensorPointer = stride;\n    gTensorPointer = stride * 2;\n  } else if (outputformat === 'BGR') {\n    bTensorPointer = 0;\n    gTensorPointer = stride;\n    rTensorPointer = stride * 2;\n  }\n\n  for (\n    let i = 0;\n    i < stride;\n    i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step\n  ) {\n    float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0];\n    float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1];\n    float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2];\n    if (aTensorPointer !== -1 && aImagePointer !== -1) {\n      float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3];\n    }\n  }\n\n  // Float32Array -> ort.Tensor\n  const outputTensor =\n    outputformat === 'RGBA'\n      ? new Tensor('float32', float32Data, [1, 4, height, width])\n      : new Tensor('float32', float32Data, [1, 3, height, width]);\n  return outputTensor;\n};\n\n/**\n * implementation of Tensor.fromImage().\n */\nexport const tensorFromImage = async (\n  image: ImageData | HTMLImageElement | ImageBitmap | string,\n  options?:\n    | TensorFromImageDataOptions\n    | TensorFromImageElementOptions\n    | TensorFromImageBitmapOptions\n    | TensorFromUrlOptions,\n): Promise<Tensor> => {\n  // checking the type of image object\n  const isHTMLImageEle = typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement;\n  const isImageDataEle = typeof ImageData !== 'undefined' && image instanceof ImageData;\n  const isImageBitmap = typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap;\n  const isString = typeof image === 'string';\n\n  let data: Uint8ClampedArray | undefined;\n  let bufferToTensorOptions: BufferToTensorOptions = options ?? {};\n\n  const createCanvas = () => {\n    if (typeof document !== 'undefined') {\n      return document.createElement('canvas');\n    } else if (typeof OffscreenCanvas !== 'undefined') {\n      return new OffscreenCanvas(1, 1);\n    } else {\n      throw new Error('Canvas is not supported');\n    }\n  };\n  const createCanvasContext = (canvas: HTMLCanvasElement | OffscreenCanvas) => {\n    if (typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement) {\n      return canvas.getContext('2d');\n    } else if (canvas instanceof OffscreenCanvas) {\n      return canvas.getContext('2d') as OffscreenCanvasRenderingContext2D;\n    } else {\n      return null;\n    }\n  };\n  // filling and checking image configuration options\n  if (isHTMLImageEle) {\n    // HTMLImageElement - image object - format is RGBA by default\n    const canvas = createCanvas();\n    canvas.width = image.width;\n    canvas.height = image.height;\n    const pixels2DContext = createCanvasContext(canvas);\n\n    if (pixels2DContext != null) {\n      let height = image.height;\n      let width = image.width;\n      if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) {\n        height = options.resizedHeight;\n        width = options.resizedWidth;\n      }\n\n      if (options !== undefined) {\n        bufferToTensorOptions = options;\n        if (options.tensorFormat !== undefined) {\n          throw new Error('Image input config format must be RGBA for HTMLImageElement');\n        } else {\n          bufferToTensorOptions.tensorFormat = 'RGBA';\n        }\n        bufferToTensorOptions.height = height;\n        bufferToTensorOptions.width = width;\n      } else {\n        bufferToTensorOptions.tensorFormat = 'RGBA';\n        bufferToTensorOptions.height = height;\n        bufferToTensorOptions.width = width;\n      }\n\n      pixels2DContext.drawImage(image, 0, 0);\n      data = pixels2DContext.getImageData(0, 0, width, height).data;\n    } else {\n      throw new Error('Can not access image data');\n    }\n  } else if (isImageDataEle) {\n    let height: number;\n    let width: number;\n\n    if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) {\n      height = options.resizedHeight;\n      width = options.resizedWidth;\n    } else {\n      height = image.height;\n      width = image.width;\n    }\n\n    if (options !== undefined) {\n      bufferToTensorOptions = options;\n    }\n    bufferToTensorOptions.format = 'RGBA';\n    bufferToTensorOptions.height = height;\n    bufferToTensorOptions.width = width;\n\n    if (options !== undefined) {\n      const tempCanvas = createCanvas();\n\n      tempCanvas.width = width;\n      tempCanvas.height = height;\n\n      const pixels2DContext = createCanvasContext(tempCanvas);\n\n      if (pixels2DContext != null) {\n        pixels2DContext.putImageData(image, 0, 0);\n        data = pixels2DContext.getImageData(0, 0, width, height).data;\n      } else {\n        throw new Error('Can not access image data');\n      }\n    } else {\n      data = image.data;\n    }\n  } else if (isImageBitmap) {\n    // ImageBitmap - image object - format must be provided by user\n    if (options === undefined) {\n      throw new Error('Please provide image config with format for Imagebitmap');\n    }\n\n    const canvas = createCanvas();\n    canvas.width = image.width;\n    canvas.height = image.height;\n    const pixels2DContext = createCanvasContext(canvas);\n\n    if (pixels2DContext != null) {\n      const height = image.height;\n      const width = image.width;\n      pixels2DContext.drawImage(image, 0, 0, width, height);\n      data = pixels2DContext.getImageData(0, 0, width, height).data;\n      bufferToTensorOptions.height = height;\n      bufferToTensorOptions.width = width;\n      return bufferToTensor(data, bufferToTensorOptions);\n    } else {\n      throw new Error('Can not access image data');\n    }\n  } else if (isString) {\n    return new Promise((resolve, reject) => {\n      const canvas = createCanvas();\n      const context = createCanvasContext(canvas);\n      if (!image || !context) {\n        return reject();\n      }\n      const newImage = new Image();\n      newImage.crossOrigin = 'Anonymous';\n      newImage.src = image;\n      newImage.onload = () => {\n        canvas.width = newImage.width;\n        canvas.height = newImage.height;\n        context.drawImage(newImage, 0, 0, canvas.width, canvas.height);\n        const img = context.getImageData(0, 0, canvas.width, canvas.height);\n\n        bufferToTensorOptions.height = canvas.height;\n        bufferToTensorOptions.width = canvas.width;\n        resolve(bufferToTensor(img.data, bufferToTensorOptions));\n      };\n    });\n  } else {\n    throw new Error('Input data provided is not supported - aborted tensor creation');\n  }\n\n  if (data !== undefined) {\n    return bufferToTensor(data, bufferToTensorOptions);\n  } else {\n    throw new Error('Input data provided is not supported - aborted tensor creation');\n  }\n};\n\n/**\n * implementation of Tensor.fromTexture().\n */\nexport const tensorFromTexture = <T extends TensorInterface.TextureDataTypes>(\n  texture: TensorInterface.TextureType,\n  options: TensorFromTextureOptions<T>,\n): Tensor => {\n  const { width, height, download, dispose } = options;\n  // Always assume RGBAF32. TODO: support different texture format\n  const dims = [1, height, width, 4];\n  return new Tensor({ location: 'texture', type: 'float32', texture, dims, download, dispose });\n};\n\n/**\n * implementation of Tensor.fromGpuBuffer().\n */\nexport const tensorFromGpuBuffer = <T extends TensorInterface.GpuBufferDataTypes>(\n  gpuBuffer: TensorInterface.GpuBufferType,\n  options: TensorFromGpuBufferOptions<T>,\n): Tensor => {\n  const { dataType, dims, download, dispose } = options;\n  return new Tensor({ location: 'gpu-buffer', type: dataType ?? 'float32', gpuBuffer, dims, download, dispose });\n};\n\n/**\n * implementation of Tensor.fromMLTensor().\n */\nexport const tensorFromMLTensor = <T extends TensorInterface.MLTensorDataTypes>(\n  mlTensor: TensorInterface.MLTensorType,\n  options: TensorFromMLTensorOptions<T>,\n): Tensor => {\n  const { dataType, dims, download, dispose } = options;\n  return new Tensor({ location: 'ml-tensor', type: dataType ?? 'float32', mlTensor, dims, download, dispose });\n};\n\n/**\n * implementation of Tensor.fromPinnedBuffer().\n */\nexport const tensorFromPinnedBuffer = <T extends TensorInterface.CpuPinnedDataTypes>(\n  type: T,\n  buffer: TensorInterface.DataTypeMap[T],\n  dims?: readonly number[],\n): Tensor => new Tensor({ location: 'cpu-pinned', type, data: buffer, dims: dims ?? [buffer.length] });\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Tensor } from './tensor.js';\n\nexport type SupportedTypedArrayConstructors =\n  | Float32ArrayConstructor\n  | Uint8ArrayConstructor\n  | Int8ArrayConstructor\n  | Uint16ArrayConstructor\n  | Int16ArrayConstructor\n  | Int32ArrayConstructor\n  | BigInt64ArrayConstructor\n  | Uint8ArrayConstructor\n  | Float64ArrayConstructor\n  | Uint32ArrayConstructor\n  | BigUint64ArrayConstructor;\nexport type SupportedTypedArray = InstanceType<SupportedTypedArrayConstructors>;\n\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map<string, SupportedTypedArrayConstructors>([\n  ['float32', Float32Array],\n  ['uint8', Uint8Array],\n  ['int8', Int8Array],\n  ['uint16', Uint16Array],\n  ['int16', Int16Array],\n  ['int32', Int32Array],\n  ['bool', Uint8Array],\n  ['float64', Float64Array],\n  ['uint32', Uint32Array],\n  ['int4', Uint8Array],\n  ['uint4', Uint8Array],\n]);\n\n// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap.\nexport const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map<SupportedTypedArrayConstructors, Tensor.Type>([\n  [Float32Array, 'float32'],\n  [Uint8Array, 'uint8'],\n  [Int8Array, 'int8'],\n  [Uint16Array, 'uint16'],\n  [Int16Array, 'int16'],\n  [Int32Array, 'int32'],\n  [Float64Array, 'float64'],\n  [Uint32Array, 'uint32'],\n]);\n\n// the following code allows delaying execution of BigInt/Float16Array checking. This allows lazy initialization for\n// NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP and NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP, which allows BigInt/Float16Array\n// polyfill if available.\nlet isTypedArrayChecked = false;\nexport const checkTypedArray = () => {\n  if (!isTypedArrayChecked) {\n    isTypedArrayChecked = true;\n    const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && BigInt64Array.from;\n    const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && BigUint64Array.from;\n\n    // eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any\n    const Float16Array = (globalThis as any).Float16Array;\n    const isFloat16ArrayAvailable = typeof Float16Array !== 'undefined' && Float16Array.from;\n\n    if (isBigInt64ArrayAvailable) {\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array);\n      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64');\n    }\n    if (isBigUint64ArrayAvailable) {\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array);\n      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64');\n    }\n    if (isFloat16ArrayAvailable) {\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Float16Array);\n      NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array, 'float16');\n    } else {\n      // if Float16Array is not available, use 'Uint16Array' to store the data.\n      NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Uint16Array);\n    }\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {\n  CpuPinnedConstructorParameters,\n  GpuBufferConstructorParameters,\n  MLTensorConstructorParameters,\n  TextureConstructorParameters,\n} from './tensor-factory.js';\nimport { Tensor } from './tensor-impl.js';\n\n/**\n * calculate size from dims.\n *\n * @param dims the dims array. May be an illegal input.\n */\nexport const calculateSize = (dims: readonly unknown[]): number => {\n  let size = 1;\n  for (let i = 0; i < dims.length; i++) {\n    const dim = dims[i];\n    if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) {\n      throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`);\n    }\n    if (dim < 0) {\n      throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`);\n    }\n    size *= dim;\n  }\n  return size;\n};\n\n/**\n * implementation of Tensor.reshape()\n */\nexport const tensorReshape = (tensor: Tensor, dims: readonly number[]): Tensor => {\n  switch (tensor.location) {\n    case 'cpu':\n      return new Tensor(tensor.type, tensor.data, dims);\n    case 'cpu-pinned':\n      return new Tensor({\n        location: 'cpu-pinned',\n        data: tensor.data as CpuPinnedConstructorParameters['data'],\n        type: tensor.type as CpuPinnedConstructorParameters['type'],\n        dims,\n      });\n    case 'texture':\n      return new Tensor({\n        location: 'texture',\n        texture: tensor.texture,\n        type: tensor.type as TextureConstructorParameters['type'],\n        dims,\n      });\n    case 'gpu-buffer':\n      return new Tensor({\n        location: 'gpu-buffer',\n        gpuBuffer: tensor.gpuBuffer,\n        type: tensor.type as GpuBufferConstructorParameters['type'],\n        dims,\n      });\n    case 'ml-tensor':\n      return new Tensor({\n        location: 'ml-tensor',\n        mlTensor: tensor.mlTensor,\n        type: tensor.type as MLTensorConstructorParameters['type'],\n        dims,\n      });\n    default:\n      throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`);\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { tensorToDataURL, tensorToImageData } from './tensor-conversion-impl.js';\nimport { TensorToDataUrlOptions, TensorToImageDataOptions } from './tensor-conversion.js';\nimport {\n  tensorFromGpuBuffer,\n  tensorFromImage,\n  tensorFromMLTensor,\n  tensorFromPinnedBuffer,\n  tensorFromTexture,\n} from './tensor-factory-impl.js';\nimport {\n  CpuPinnedConstructorParameters,\n  GpuBufferConstructorParameters,\n  MLTensorConstructorParameters,\n  TensorFromGpuBufferOptions,\n  TensorFromImageBitmapOptions,\n  TensorFromImageDataOptions,\n  TensorFromImageElementOptions,\n  TensorFromMLTensorOptions,\n  TensorFromTextureOptions,\n  TensorFromUrlOptions,\n  TextureConstructorParameters,\n} from './tensor-factory.js';\nimport {\n  checkTypedArray,\n  NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP,\n  NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP,\n  SupportedTypedArray,\n  SupportedTypedArrayConstructors,\n} from './tensor-impl-type-mapping.js';\nimport { calculateSize, tensorReshape } from './tensor-utils-impl.js';\nimport { Tensor as TensorInterface } from './tensor.js';\n\n// type aliases for those exported from Tensor interface\n\ntype TensorType = TensorInterface.Type;\ntype TensorDataType = TensorInterface.DataType;\ntype TensorDataLocation = TensorInterface.DataLocation;\ntype TensorTextureType = TensorInterface.TextureType;\ntype TensorGpuBufferType = TensorInterface.GpuBufferType;\ntype TensorMLTensorType = TensorInterface.MLTensorType;\n\n/**\n * the implementation of Tensor interface.\n *\n * @ignore\n */\nexport class Tensor implements TensorInterface {\n  // #region constructors\n\n  /**\n   * Construct a new CPU tensor object from the given type, data and dims.\n   */\n  constructor(\n    type: TensorType,\n    data: TensorDataType | Uint8ClampedArray | readonly string[] | readonly number[] | readonly boolean[],\n    dims?: readonly number[],\n  );\n  /**\n   * Construct a new CPU tensor object from the given data and dims. Type is inferred from data.\n   */\n  constructor(\n    data: TensorDataType | Uint8ClampedArray | readonly string[] | readonly boolean[],\n    dims?: readonly number[],\n  );\n  /**\n   * Construct a new tensor object from the pinned CPU data with the given type and dims.\n   *\n   * Tensor's location will be set to 'cpu-pinned'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: CpuPinnedConstructorParameters);\n  /**\n   * Construct a new tensor object from the WebGL texture with the given type and dims.\n   *\n   * Tensor's location will be set to 'texture'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: TextureConstructorParameters);\n  /**\n   * Construct a new tensor object from the WebGPU buffer with the given type and dims.\n   *\n   * Tensor's location will be set to 'gpu-buffer'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: GpuBufferConstructorParameters);\n\n  /**\n   * Construct a new tensor object from the WebNN MLTensor with the given type and dims.\n   *\n   * Tensor's location will be set to 'ml-tensor'.\n   *\n   * @param params - Specify the parameters to construct the tensor.\n   */\n  constructor(params: MLTensorConstructorParameters);\n\n  /**\n   * implementation.\n   */\n  constructor(\n    arg0:\n      | TensorType\n      | TensorDataType\n      | Uint8ClampedArray\n      | readonly string[]\n      | readonly boolean[]\n      | CpuPinnedConstructorParameters\n      | TextureConstructorParameters\n      | GpuBufferConstructorParameters\n      | MLTensorConstructorParameters,\n    arg1?: TensorDataType | Uint8ClampedArray | readonly number[] | readonly string[] | readonly boolean[],\n    arg2?: readonly number[],\n  ) {\n    // perform one-time check for BigInt/Float16Array support\n    checkTypedArray();\n\n    let type: TensorType;\n    let dims: readonly number[];\n\n    if (typeof arg0 === 'object' && 'location' in arg0) {\n      //\n      // constructing tensor from specific location\n      //\n      this.dataLocation = arg0.location;\n      type = arg0.type;\n      dims = arg0.dims;\n      switch (arg0.location) {\n        case 'cpu-pinned': {\n          const expectedTypedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type);\n          if (!expectedTypedArrayConstructor) {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from pinned buffer`);\n          }\n          if (!(arg0.data instanceof expectedTypedArrayConstructor)) {\n            throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`);\n          }\n          this.cpuData = arg0.data;\n          break;\n        }\n        case 'texture': {\n          if (type !== 'float32') {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from texture`);\n          }\n          this.gpuTextureData = arg0.texture;\n          this.downloader = arg0.download;\n          this.disposer = arg0.dispose;\n          break;\n        }\n        case 'gpu-buffer': {\n          if (\n            type !== 'float32' &&\n            type !== 'float16' &&\n            type !== 'int32' &&\n            type !== 'int64' &&\n            type !== 'uint32' &&\n            type !== 'uint8' &&\n            type !== 'bool' &&\n            type !== 'uint4' &&\n            type !== 'int4'\n          ) {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from gpu buffer`);\n          }\n          this.gpuBufferData = arg0.gpuBuffer;\n          this.downloader = arg0.download;\n          this.disposer = arg0.dispose;\n          break;\n        }\n        case 'ml-tensor': {\n          if (\n            type !== 'float32' &&\n            type !== 'float16' &&\n            type !== 'int32' &&\n            type !== 'int64' &&\n            type !== 'uint32' &&\n            type !== 'uint64' &&\n            type !== 'int8' &&\n            type !== 'uint8' &&\n            type !== 'bool' &&\n            type !== 'uint4' &&\n            type !== 'int4'\n          ) {\n            throw new TypeError(`unsupported type \"${type}\" to create tensor from MLTensor`);\n          }\n          this.mlTensorData = arg0.mlTensor;\n          this.downloader = arg0.download;\n          this.disposer = arg0.dispose;\n          break;\n        }\n        default:\n          throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`);\n      }\n    } else {\n      //\n      // constructing tensor of location 'cpu'\n      //\n      let data: TensorDataType;\n      let maybeDims: typeof arg1 | typeof arg2;\n      // check whether arg0 is type or data\n      if (typeof arg0 === 'string') {\n        //\n        // Override: constructor(type, data, ...)\n        //\n        type = arg0;\n        maybeDims = arg2;\n        if (arg0 === 'string') {\n          // string tensor\n          if (!Array.isArray(arg1)) {\n            throw new TypeError(\"A string tensor's data must be a string array.\");\n          }\n          // we don't check whether every element in the array is string; this is too slow. we assume it's correct and\n          // error will be populated at inference\n          data = arg1;\n        } else {\n          // numeric tensor\n          const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0);\n          if (typedArrayConstructor === undefined) {\n            throw new TypeError(`Unsupported tensor type: ${arg0}.`);\n          }\n          if (Array.isArray(arg1)) {\n            if ((arg0 === 'float16' && typedArrayConstructor === Uint16Array) || arg0 === 'uint4' || arg0 === 'int4') {\n              // - 'float16':\n              //   When no Float16Array polyfill is used, we cannot create 'float16' tensor from number array.\n              //\n              //   Throw error here because when user try to use number array as data,\n              //   e.g. new Tensor('float16', [1, 2, 3, 4], dims)), it will actually call\n              //   Uint16Array.from(arg1) which generates wrong data.\n              //\n              // - 'uint4' and 'int4':\n              //   Uint8Array.from(arg1) will generate wrong data for 'uint4' and 'int4' tensor.\n              //\n              throw new TypeError(\n                `Creating a ${arg0} tensor from number array is not supported. Please use ${typedArrayConstructor.name} as data.`,\n              );\n            } else if (arg0 === 'uint64' || arg0 === 'int64') {\n              // use 'as any' here because:\n              // 1. TypeScript's check on type of 'Array.isArray()' does not work with readonly arrays.\n              // see https://github.com/microsoft/TypeScript/issues/17002\n              // 2. TypeScript's check on union type of '(BigInt64ArrayConstructor|BigUint64ArrayConstructor).from()'\n              // does not accept parameter mapFn.\n              // 3. parameters of 'SupportedTypedArrayConstructors.from()' does not match the requirement of the union\n              // type.\n\n              // assume 'arg1' is of type \"readonly number[]|readonly bigint[]\" here.\n\n              // eslint-disable-next-line @typescript-eslint/no-explicit-any\n              data = (typedArrayConstructor as any).from(arg1, BigInt);\n            } else {\n              // assume 'arg1' is of type \"readonly number[]\" here.\n              // eslint-disable-next-line @typescript-eslint/no-explicit-any\n              data = (typedArrayConstructor as any).from(arg1);\n            }\n          } else if (arg1 instanceof typedArrayConstructor) {\n            data = arg1;\n          } else if (arg1 instanceof Uint8ClampedArray) {\n            if (arg0 === 'uint8') {\n              data = Uint8Array.from(arg1);\n            } else {\n              throw new TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);\n            }\n          } else if (arg0 === 'float16' && arg1 instanceof Uint16Array && typedArrayConstructor !== Uint16Array) {\n            // when Float16Array is available and data is of type Uint16Array.\n            // We allow Uint16Array to be passed in as data for 'float16' tensor until Float16Array is generally\n            // supported in JavaScript environment.\n\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            data = new (globalThis as any).Float16Array(arg1.buffer, arg1.byteOffset, arg1.length);\n          } else {\n            throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`);\n          }\n        }\n      } else {\n        //\n        // Override: constructor(data, ...)\n        //\n        maybeDims = arg1;\n        if (Array.isArray(arg0)) {\n          // only boolean[] and string[] is supported\n          if (arg0.length === 0) {\n            throw new TypeError('Tensor type cannot be inferred from an empty array.');\n          }\n          const firstElementType = typeof arg0[0];\n          if (firstElementType === 'string') {\n            type = 'string';\n            data = arg0;\n          } else if (firstElementType === 'boolean') {\n            type = 'bool';\n            // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is\n            // wrong type. We use 'as any' to make it happy.\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            data = Uint8Array.from(arg0 as any[]);\n          } else {\n            throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);\n          }\n        } else if (arg0 instanceof Uint8ClampedArray) {\n          type = 'uint8';\n          data = Uint8Array.from(arg0);\n        } else {\n          // get tensor type from TypedArray\n          const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(\n            arg0.constructor as SupportedTypedArrayConstructors,\n          );\n          if (mappedType === undefined) {\n            throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);\n          }\n          type = mappedType;\n          data = arg0 as SupportedTypedArray;\n        }\n      }\n\n      // type and data is processed, now processing dims\n      if (maybeDims === undefined) {\n        // assume 1-D tensor if dims omitted\n        maybeDims = [data.length];\n      } else if (!Array.isArray(maybeDims)) {\n        throw new TypeError(\"A tensor's dims must be a number array\");\n      }\n      dims = maybeDims as readonly number[];\n\n      this.cpuData = data;\n      this.dataLocation = 'cpu';\n    }\n\n    // perform check on dims\n    const size = calculateSize(dims);\n    // if data is on CPU, check whether data length matches tensor size\n    if (this.cpuData && size !== this.cpuData.length) {\n      if ((type === 'uint4' || type === 'int4') && Math.ceil(size / 2) === this.cpuData.length) {\n        // for (u)int4, the data length is half of the tensor size. So we check this special case when size is odd.\n      } else {\n        throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`);\n      }\n    }\n\n    this.type = type;\n    this.dims = dims;\n    this.size = size;\n  }\n  // #endregion\n\n  // #region factory\n  static async fromImage(\n    image: ImageData | HTMLImageElement | ImageBitmap | string,\n    options?:\n      | TensorFromImageDataOptions\n      | TensorFromImageElementOptions\n      | TensorFromImageBitmapOptions\n      | TensorFromUrlOptions,\n  ): Promise<TensorInterface> {\n    return tensorFromImage(image, options);\n  }\n\n  static fromTexture<T extends TensorInterface.TextureDataTypes>(\n    texture: TensorTextureType,\n    options: TensorFromTextureOptions<T>,\n  ): TensorInterface {\n    return tensorFromTexture(texture, options);\n  }\n\n  static fromGpuBuffer<T extends TensorInterface.GpuBufferDataTypes>(\n    gpuBuffer: TensorGpuBufferType,\n    options: TensorFromGpuBufferOptions<T>,\n  ): TensorInterface {\n    return tensorFromGpuBuffer(gpuBuffer, options);\n  }\n\n  static fromMLTensor<T extends TensorInterface.MLTensorDataTypes>(\n    mlTensor: TensorMLTensorType,\n    options: TensorFromMLTensorOptions<T>,\n  ): TensorInterface {\n    return tensorFromMLTensor(mlTensor, options);\n  }\n\n  static fromPinnedBuffer<T extends TensorInterface.CpuPinnedDataTypes>(\n    type: T,\n    buffer: TensorInterface.DataTypeMap[T],\n    dims?: readonly number[],\n  ): Tensor {\n    return tensorFromPinnedBuffer(type, buffer, dims);\n  }\n\n  // #endregion\n\n  // #region conversions\n  toDataURL(options?: TensorToDataUrlOptions): string {\n    return tensorToDataURL(this, options);\n  }\n\n  toImageData(options?: TensorToImageDataOptions): ImageData {\n    return tensorToImageData(this, options);\n  }\n  // #endregion\n\n  // #region public fields\n  readonly dims: readonly number[];\n  readonly type: TensorType;\n  readonly size: number;\n  // #endregion\n\n  // #region private fields\n\n  /**\n   * stores the location of the data.\n   */\n  private dataLocation: TensorDataLocation;\n\n  /**\n   * stores the data on CPU, if location is 'cpu' or 'cpu-pinned'. otherwise empty.\n   */\n  private cpuData?: TensorDataType;\n\n  /**\n   * stores the underlying texture when location is 'texture'. otherwise empty.\n   */\n  private gpuTextureData?: TensorTextureType;\n\n  /**\n   * stores the underlying GPU buffer when location is 'gpu-buffer'. otherwise empty.\n   */\n  private gpuBufferData?: TensorGpuBufferType;\n\n  /**\n   * stores the underlying WebNN MLTensor when location is 'ml-tensor'. otherwise empty.\n   */\n  private mlTensorData?: TensorMLTensorType;\n\n  /**\n   * stores an optional downloader function to download data from GPU to CPU.\n   */\n  private downloader?(): Promise<TensorDataType>;\n\n  /**\n   * a flag indicating whether the data is being downloaded from GPU to CPU.\n   */\n  private isDownloading?: boolean;\n\n  /**\n   * stores an optional disposer function to dispose the underlying data.\n   */\n  private disposer?(): void;\n  // #endregion\n\n  // #region properties\n  get data(): TensorDataType {\n    this.ensureValid();\n    if (!this.cpuData) {\n      throw new Error(\n        'The data is not on CPU. Use `getData()` to download GPU data to CPU, ' +\n          'or use `texture` or `gpuBuffer` property to access the GPU data directly.',\n      );\n    }\n    return this.cpuData;\n  }\n\n  get location(): TensorDataLocation {\n    return this.dataLocation;\n  }\n\n  get texture(): TensorTextureType {\n    this.ensureValid();\n    if (!this.gpuTextureData) {\n      throw new Error('The data is not stored as a WebGL texture.');\n    }\n    return this.gpuTextureData;\n  }\n\n  get gpuBuffer(): TensorGpuBufferType {\n    this.ensureValid();\n    if (!this.gpuBufferData) {\n      throw new Error('The data is not stored as a WebGPU buffer.');\n    }\n    return this.gpuBufferData;\n  }\n\n  get mlTensor(): TensorMLTensorType {\n    this.ensureValid();\n    if (!this.mlTensorData) {\n      throw new Error('The data is not stored as a WebNN MLTensor.');\n    }\n    return this.mlTensorData;\n  }\n  // #endregion\n\n  // #region methods\n\n  async getData(releaseData?: boolean): Promise<TensorDataType> {\n    this.ensureValid();\n    switch (this.dataLocation) {\n      case 'cpu':\n      case 'cpu-pinned':\n        return this.data;\n      case 'texture':\n      case 'gpu-buffer':\n      case 'ml-tensor': {\n        if (!this.downloader) {\n          throw new Error('The current tensor is not created with a specified data downloader.');\n        }\n        if (this.isDownloading) {\n          throw new Error('The current tensor is being downloaded.');\n        }\n        try {\n          this.isDownloading = true;\n          const data = await this.downloader();\n          this.downloader = undefined;\n          this.dataLocation = 'cpu';\n          this.cpuData = data;\n\n          if (releaseData && this.disposer) {\n            this.disposer();\n            this.disposer = undefined;\n          }\n\n          return data;\n        } finally {\n          this.isDownloading = false;\n        }\n      }\n      default:\n        throw new Error(`cannot get data from location: ${this.dataLocation}`);\n    }\n  }\n\n  dispose(): void {\n    if (this.isDownloading) {\n      throw new Error('The current tensor is being downloaded.');\n    }\n\n    if (this.disposer) {\n      this.disposer();\n      this.disposer = undefined;\n    }\n    this.cpuData = undefined;\n    this.gpuTextureData = undefined;\n    this.gpuBufferData = undefined;\n    this.mlTensorData = undefined;\n    this.downloader = undefined;\n    this.isDownloading = undefined;\n\n    this.dataLocation = 'none';\n  }\n\n  // #endregion\n\n  // #region tensor utilities\n  private ensureValid(): void {\n    if (this.dataLocation === 'none') {\n      throw new Error('The tensor is disposed.');\n    }\n  }\n\n  reshape(dims: readonly number[]): TensorInterface {\n    this.ensureValid();\n    if (this.downloader || this.disposer) {\n      throw new Error('Cannot reshape a tensor that owns GPU resource.');\n    }\n    return tensorReshape(this, dims);\n  }\n  // #endregion\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { TensorFactory } from './tensor-factory.js';\nimport { Tensor as TensorImpl } from './tensor-impl.js';\nimport { TypedTensorUtils } from './tensor-utils.js';\nimport { TryGetGlobalType } from './type-helper.js';\n\n/* eslint-disable @typescript-eslint/no-redeclare */\n\n/**\n * represent a basic tensor with specified dimensions and data type.\n */\ninterface TypedTensorBase<T extends Tensor.Type> {\n  /**\n   * Get the dimensions of the tensor.\n   */\n  readonly dims: readonly number[];\n  /**\n   * Get the data type of the tensor.\n   */\n  readonly type: T;\n  /**\n   * Get the buffer data of the tensor.\n   *\n   * If the data is not on CPU (eg. it's in the form of WebGL texture or WebGPU buffer), throw error.\n   */\n  readonly data: Tensor.DataTypeMap[T];\n  /**\n   * Get the location of the data.\n   */\n  readonly location: Tensor.DataLocation;\n  /**\n   * Get the WebGL texture that holds the tensor data.\n   *\n   * If the data is not on GPU as WebGL texture, throw error.\n   */\n  readonly texture: Tensor.TextureType;\n  /**\n   * Get the WebGPU buffer that holds the tensor data.\n   *\n   * If the data is not on GPU as WebGPU buffer, throw error.\n   */\n  readonly gpuBuffer: Tensor.GpuBufferType;\n\n  /**\n   * Get the WebNN MLTensor that holds the tensor data.\n   *\n   * If the data is not in a WebNN MLTensor, throw error.\n   */\n  readonly mlTensor: Tensor.MLTensorType;\n\n  /**\n   * Get the buffer data of the tensor.\n   *\n   * If the data is on CPU, returns the data immediately.\n   * If the data is on GPU, downloads the data and returns the promise.\n   *\n   * @param releaseData - whether release the data on GPU. Ignore if data is already on CPU.\n   */\n  getData(releaseData?: boolean): Promise<Tensor.DataTypeMap[T]>;\n\n  /**\n   * Dispose the tensor data.\n   *\n   * If the data is on CPU, remove its internal reference to the underlying data.\n   * If the data is on GPU, release the data on GPU.\n   *\n   * After calling this function, the tensor is considered no longer valid. Its location will be set to 'none'.\n   */\n  dispose(): void;\n}\n\nexport declare namespace Tensor {\n  interface DataTypeMap {\n    float32: Float32Array;\n    uint8: Uint8Array;\n    int8: Int8Array;\n    uint16: Uint16Array;\n    int16: Int16Array;\n    int32: Int32Array;\n    int64: BigInt64Array;\n    string: string[];\n    bool: Uint8Array;\n    float16: Uint16Array; // Keep using Uint16Array until we have a concrete solution for float 16.\n    float64: Float64Array;\n    uint32: Uint32Array;\n    uint64: BigUint64Array;\n    // complex64: never;\n    // complex128: never;\n    // bfloat16: never;\n    uint4: Uint8Array;\n    int4: Int8Array;\n  }\n\n  interface ElementTypeMap {\n    float32: number;\n    uint8: number;\n    int8: number;\n    uint16: number;\n    int16: number;\n    int32: number;\n    int64: bigint;\n    string: string;\n    bool: boolean;\n    float16: number; // Keep using Uint16Array until we have a concrete solution for float 16.\n    float64: number;\n    uint32: number;\n    uint64: bigint;\n    // complex64: never;\n    // complex128: never;\n    // bfloat16: never;\n    uint4: number;\n    int4: number;\n  }\n\n  type DataType = DataTypeMap[Type];\n  type ElementType = ElementTypeMap[Type];\n\n  /**\n   * supported data types for constructing a tensor from a pinned CPU buffer\n   */\n  export type CpuPinnedDataTypes = Exclude<Tensor.Type, 'string'>;\n\n  /**\n   * type alias for WebGL texture\n   */\n  export type TextureType = WebGLTexture;\n\n  /**\n   * supported data types for constructing a tensor from a WebGL texture\n   */\n  export type TextureDataTypes = 'float32';\n\n  type GpuBufferTypeFallback = { size: number; mapState: 'unmapped' | 'pending' | 'mapped' };\n  /**\n   * type alias for WebGPU buffer\n   */\n  export type GpuBufferType = TryGetGlobalType<'GPUBuffer', GpuBufferTypeFallback>;\n\n  type MLTensorTypeFallback = { destroy(): void };\n  /**\n   * type alias for WebNN MLTensor\n   *\n   * The specification for WebNN's MLTensor is currently in flux.\n   */\n  export type MLTensorType = TryGetGlobalType<'MLTensor', MLTensorTypeFallback>;\n\n  /**\n   * supported data types for constructing a tensor from a WebGPU buffer\n   */\n  export type GpuBufferDataTypes = 'float32' | 'float16' | 'int32' | 'int64' | 'uint32' | 'uint8' | 'bool';\n\n  /**\n   * supported data types for constructing a tensor from a WebNN MLTensor\n   */\n  export type MLTensorDataTypes =\n    | 'float32'\n    | 'float16'\n    | 'int8'\n    | 'uint8'\n    | 'int32'\n    | 'uint32'\n    | 'int64'\n    | 'uint64'\n    | 'bool'\n    | 'uint4'\n    | 'int4';\n\n  /**\n   * represent where the tensor data is stored\n   */\n  export type DataLocation = 'none' | 'cpu' | 'cpu-pinned' | 'texture' | 'gpu-buffer' | 'ml-tensor';\n\n  /**\n   * represent the data type of a tensor\n   */\n  export type Type = keyof DataTypeMap;\n}\n\n/**\n * Represent multi-dimensional arrays to feed to or fetch from model inferencing.\n */\nexport interface TypedTensor<T extends Tensor.Type> extends TypedTensorBase<T>, TypedTensorUtils<T> {}\n/**\n * Represent multi-dimensional arrays to feed to or fetch from model inferencing.\n */\nexport interface Tensor extends TypedTensorBase<Tensor.Type>, TypedTensorUtils<Tensor.Type> {}\n\n/**\n * type TensorConstructor defines the constructors of 'Tensor' to create CPU tensor instances.\n */\nexport interface TensorConstructor extends TensorFactory {\n  // #region CPU tensor - specify element type\n  /**\n   * Construct a new string tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (\n    type: 'string',\n    data: Tensor.DataTypeMap['string'] | readonly string[],\n    dims?: readonly number[],\n  ): TypedTensor<'string'>;\n\n  /**\n   * Construct a new bool tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (\n    type: 'bool',\n    data: Tensor.DataTypeMap['bool'] | readonly boolean[],\n    dims?: readonly number[],\n  ): TypedTensor<'bool'>;\n\n  /**\n   * Construct a new uint8 tensor object from a Uint8ClampedArray, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (type: 'uint8', data: Uint8ClampedArray, dims?: readonly number[]): TypedTensor<'uint8'>;\n\n  /**\n   * Construct a new 64-bit integer typed tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new <T extends 'uint64' | 'int64'>(\n    type: T,\n    data: Tensor.DataTypeMap[T] | readonly bigint[] | readonly number[],\n    dims?: readonly number[],\n  ): TypedTensor<T>;\n\n  /**\n   * Construct a new numeric tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new <T extends Exclude<Tensor.Type, 'string' | 'bool' | 'uint64' | 'int64'>>(\n    type: T,\n    data: Tensor.DataTypeMap[T] | readonly number[],\n    dims?: readonly number[],\n  ): TypedTensor<T>;\n  // #endregion\n\n  // #region CPU tensor - infer element types\n\n  /**\n   * Construct a new float32 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Float32Array, dims?: readonly number[]): TypedTensor<'float32'>;\n\n  /**\n   * Construct a new int8 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Int8Array, dims?: readonly number[]): TypedTensor<'int8'>;\n\n  /**\n   * Construct a new uint8 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Uint8Array, dims?: readonly number[]): TypedTensor<'uint8'>;\n\n  /**\n   * Construct a new uint8 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Uint8ClampedArray, dims?: readonly number[]): TypedTensor<'uint8'>;\n\n  /**\n   * Construct a new uint16 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Uint16Array, dims?: readonly number[]): TypedTensor<'uint16'>;\n\n  /**\n   * Construct a new int16 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Int16Array, dims?: readonly number[]): TypedTensor<'int16'>;\n\n  /**\n   * Construct a new int32 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Int32Array, dims?: readonly number[]): TypedTensor<'int32'>;\n\n  /**\n   * Construct a new int64 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: BigInt64Array, dims?: readonly number[]): TypedTensor<'int64'>;\n\n  /**\n   * Construct a new string tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: readonly string[], dims?: readonly number[]): TypedTensor<'string'>;\n\n  /**\n   * Construct a new bool tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: readonly boolean[], dims?: readonly number[]): TypedTensor<'bool'>;\n\n  /**\n   * Construct a new float64 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Float64Array, dims?: readonly number[]): TypedTensor<'float64'>;\n\n  /**\n   * Construct a new uint32 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Uint32Array, dims?: readonly number[]): TypedTensor<'uint32'>;\n\n  /**\n   * Construct a new uint64 tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: BigUint64Array, dims?: readonly number[]): TypedTensor<'uint64'>;\n\n  // #endregion\n\n  // #region CPU tensor - fall back to non-generic tensor type declaration\n\n  /**\n   * Construct a new tensor object from the given type, data and dims.\n   *\n   * @param type - Specify the element type.\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (\n    type: Tensor.Type,\n    data: Tensor.DataType | readonly number[] | readonly string[] | readonly bigint[] | readonly boolean[],\n    dims?: readonly number[],\n  ): Tensor;\n\n  /**\n   * Construct a new tensor object from the given data and dims.\n   *\n   * @param data - Specify the CPU tensor data.\n   * @param dims - Specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   */\n  new (data: Tensor.DataType, dims?: readonly number[]): Tensor;\n  // #endregion\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const Tensor = TensorImpl as TensorConstructor;\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { env } from './env-impl.js';\n\n/**\n * @ignore\n */\nexport const TRACE = (deviceType: string, label: string) => {\n  if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n    return;\n  }\n  // eslint-disable-next-line no-console\n  console.timeStamp(`${deviceType}::ORT::${label}`);\n};\n\nconst TRACE_FUNC = (msg: string, extraMsg?: string) => {\n  const stack = new Error().stack?.split(/\\r\\n|\\r|\\n/g) || [];\n  let hasTraceFunc = false;\n  for (let i = 0; i < stack.length; i++) {\n    if (hasTraceFunc && !stack[i].includes('TRACE_FUNC')) {\n      let label = `FUNC_${msg}::${stack[i].trim().split(' ')[1]}`;\n      if (extraMsg) {\n        label += `::${extraMsg}`;\n      }\n      TRACE('CPU', label);\n      return;\n    }\n    if (stack[i].includes('TRACE_FUNC')) {\n      hasTraceFunc = true;\n    }\n  }\n};\n\n/**\n * @ignore\n */\nexport const TRACE_FUNC_BEGIN = (extraMsg?: string) => {\n  if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n    return;\n  }\n  TRACE_FUNC('BEGIN', extraMsg);\n};\n\n/**\n * @ignore\n */\nexport const TRACE_FUNC_END = (extraMsg?: string) => {\n  if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n    return;\n  }\n  TRACE_FUNC('END', extraMsg);\n};\n\n/**\n * @ignore\n */\nexport const TRACE_EVENT_BEGIN = (extraMsg?: string) => {\n  if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n    return;\n  }\n  // eslint-disable-next-line no-console\n  console.time(`ORT::${extraMsg}`);\n};\n\n/**\n * @ignore\n */\nexport const TRACE_EVENT_END = (extraMsg?: string) => {\n  if (typeof env.trace === 'undefined' ? !env.wasm.trace : !env.trace) {\n    return;\n  }\n  // eslint-disable-next-line no-console\n  console.timeEnd(`ORT::${extraMsg}`);\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { resolveBackendAndExecutionProviders } from './backend-impl.js';\nimport { InferenceSessionHandler } from './backend.js';\nimport { InferenceSession as InferenceSessionInterface } from './inference-session.js';\nimport { OnnxValue } from './onnx-value.js';\nimport { Tensor } from './tensor.js';\nimport { TRACE_FUNC_BEGIN, TRACE_FUNC_END, TRACE_EVENT_BEGIN, TRACE_EVENT_END } from './trace.js';\n\ntype SessionOptions = InferenceSessionInterface.SessionOptions;\ntype RunOptions = InferenceSessionInterface.RunOptions;\ntype FeedsType = InferenceSessionInterface.FeedsType;\ntype FetchesType = InferenceSessionInterface.FetchesType;\ntype ReturnType = InferenceSessionInterface.ReturnType;\n\nexport class InferenceSession implements InferenceSessionInterface {\n  private constructor(handler: InferenceSessionHandler) {\n    this.handler = handler;\n  }\n  run(feeds: FeedsType, options?: RunOptions): Promise<ReturnType>;\n  run(feeds: FeedsType, fetches: FetchesType, options?: RunOptions): Promise<ReturnType>;\n  async run(feeds: FeedsType, arg1?: FetchesType | RunOptions, arg2?: RunOptions): Promise<ReturnType> {\n    TRACE_FUNC_BEGIN();\n    TRACE_EVENT_BEGIN('InferenceSession.run');\n    const fetches: { [name: string]: OnnxValue | null } = {};\n    let options: RunOptions = {};\n    // check inputs\n    if (typeof feeds !== 'object' || feeds === null || feeds instanceof Tensor || Array.isArray(feeds)) {\n      throw new TypeError(\n        \"'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.\",\n      );\n    }\n\n    let isFetchesEmpty = true;\n    // determine which override is being used\n    if (typeof arg1 === 'object') {\n      if (arg1 === null) {\n        throw new TypeError('Unexpected argument[1]: cannot be null.');\n      }\n      if (arg1 instanceof Tensor) {\n        throw new TypeError(\"'fetches' cannot be a Tensor\");\n      }\n\n      if (Array.isArray(arg1)) {\n        if (arg1.length === 0) {\n          throw new TypeError(\"'fetches' cannot be an empty array.\");\n        }\n        isFetchesEmpty = false;\n        // output names\n        for (const name of arg1) {\n          if (typeof name !== 'string') {\n            throw new TypeError(\"'fetches' must be a string array or an object.\");\n          }\n          if (this.outputNames.indexOf(name) === -1) {\n            throw new RangeError(`'fetches' contains invalid output name: ${name}.`);\n          }\n          fetches[name] = null;\n        }\n\n        if (typeof arg2 === 'object' && arg2 !== null) {\n          options = arg2;\n        } else if (typeof arg2 !== 'undefined') {\n          throw new TypeError(\"'options' must be an object.\");\n        }\n      } else {\n        // decide whether arg1 is fetches or options\n        // if any output name is present and its value is valid OnnxValue, we consider it fetches\n        let isFetches = false;\n        const arg1Keys = Object.getOwnPropertyNames(arg1);\n        for (const name of this.outputNames) {\n          if (arg1Keys.indexOf(name) !== -1) {\n            const v = (arg1 as InferenceSessionInterface.NullableOnnxValueMapType)[name];\n            if (v === null || v instanceof Tensor) {\n              isFetches = true;\n              isFetchesEmpty = false;\n              fetches[name] = v;\n            }\n          }\n        }\n\n        if (isFetches) {\n          if (typeof arg2 === 'object' && arg2 !== null) {\n            options = arg2;\n          } else if (typeof arg2 !== 'undefined') {\n            throw new TypeError(\"'options' must be an object.\");\n          }\n        } else {\n          options = arg1 as RunOptions;\n        }\n      }\n    } else if (typeof arg1 !== 'undefined') {\n      throw new TypeError(\"Unexpected argument[1]: must be 'fetches' or 'options'.\");\n    }\n\n    // check if all inputs are in feed\n    for (const name of this.inputNames) {\n      if (typeof feeds[name] === 'undefined') {\n        throw new Error(`input '${name}' is missing in 'feeds'.`);\n      }\n    }\n\n    // if no fetches is specified, we use the full output names list\n    if (isFetchesEmpty) {\n      for (const name of this.outputNames) {\n        fetches[name] = null;\n      }\n    }\n\n    // feeds, fetches and options are prepared\n\n    const results = await this.handler.run(feeds, fetches, options);\n    const returnValue: { [name: string]: OnnxValue } = {};\n    for (const key in results) {\n      if (Object.hasOwnProperty.call(results, key)) {\n        const result = results[key];\n        if (result instanceof Tensor) {\n          returnValue[key] = result;\n        } else {\n          returnValue[key] = new Tensor(result.type, result.data, result.dims);\n        }\n      }\n    }\n    TRACE_EVENT_END('InferenceSession.run');\n    TRACE_FUNC_END();\n    return returnValue;\n  }\n\n  async release(): Promise<void> {\n    return this.handler.dispose();\n  }\n\n  static create(path: string, options?: SessionOptions): Promise<InferenceSessionInterface>;\n  static create(buffer: ArrayBufferLike, options?: SessionOptions): Promise<InferenceSessionInterface>;\n  static create(\n    buffer: ArrayBufferLike,\n    byteOffset: number,\n    byteLength?: number,\n    options?: SessionOptions,\n  ): Promise<InferenceSessionInterface>;\n  static create(buffer: Uint8Array, options?: SessionOptions): Promise<InferenceSessionInterface>;\n  static async create(\n    arg0: string | ArrayBufferLike | Uint8Array,\n    arg1?: SessionOptions | number,\n    arg2?: number,\n    arg3?: SessionOptions,\n  ): Promise<InferenceSessionInterface> {\n    TRACE_FUNC_BEGIN();\n    TRACE_EVENT_BEGIN('InferenceSession.create');\n    // either load from a file or buffer\n    let filePathOrUint8Array: string | Uint8Array;\n    let options: SessionOptions = {};\n\n    if (typeof arg0 === 'string') {\n      filePathOrUint8Array = arg0;\n      if (typeof arg1 === 'object' && arg1 !== null) {\n        options = arg1;\n      } else if (typeof arg1 !== 'undefined') {\n        throw new TypeError(\"'options' must be an object.\");\n      }\n    } else if (arg0 instanceof Uint8Array) {\n      filePathOrUint8Array = arg0;\n      if (typeof arg1 === 'object' && arg1 !== null) {\n        options = arg1;\n      } else if (typeof arg1 !== 'undefined') {\n        throw new TypeError(\"'options' must be an object.\");\n      }\n    } else if (\n      arg0 instanceof ArrayBuffer ||\n      (typeof SharedArrayBuffer !== 'undefined' && arg0 instanceof SharedArrayBuffer)\n    ) {\n      const buffer = arg0;\n      let byteOffset = 0;\n      let byteLength = arg0.byteLength;\n      if (typeof arg1 === 'object' && arg1 !== null) {\n        options = arg1;\n      } else if (typeof arg1 === 'number') {\n        byteOffset = arg1;\n        if (!Number.isSafeInteger(byteOffset)) {\n          throw new RangeError(\"'byteOffset' must be an integer.\");\n        }\n        if (byteOffset < 0 || byteOffset >= buffer.byteLength) {\n          throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`);\n        }\n        byteLength = arg0.byteLength - byteOffset;\n        if (typeof arg2 === 'number') {\n          byteLength = arg2;\n          if (!Number.isSafeInteger(byteLength)) {\n            throw new RangeError(\"'byteLength' must be an integer.\");\n          }\n          if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) {\n            throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`);\n          }\n          if (typeof arg3 === 'object' && arg3 !== null) {\n            options = arg3;\n          } else if (typeof arg3 !== 'undefined') {\n            throw new TypeError(\"'options' must be an object.\");\n          }\n        } else if (typeof arg2 !== 'undefined') {\n          throw new TypeError(\"'byteLength' must be a number.\");\n        }\n      } else if (typeof arg1 !== 'undefined') {\n        throw new TypeError(\"'options' must be an object.\");\n      }\n      filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength);\n    } else {\n      throw new TypeError(\"Unexpected argument[0]: must be 'path' or 'buffer'.\");\n    }\n\n    // resolve backend, update session options with validated EPs, and create session handler\n    const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options);\n    const handler = await backend.createInferenceSessionHandler(filePathOrUint8Array, optionsWithValidatedEPs);\n    TRACE_EVENT_END('InferenceSession.create');\n    TRACE_FUNC_END();\n    return new InferenceSession(handler);\n  }\n\n  startProfiling(): void {\n    this.handler.startProfiling();\n  }\n  endProfiling(): void {\n    this.handler.endProfiling();\n  }\n\n  get inputNames(): readonly string[] {\n    return this.handler.inputNames;\n  }\n  get outputNames(): readonly string[] {\n    return this.handler.outputNames;\n  }\n\n  get inputMetadata(): readonly InferenceSessionInterface.ValueMetadata[] {\n    return this.handler.inputMetadata;\n  }\n\n  get outputMetadata(): readonly InferenceSessionInterface.ValueMetadata[] {\n    return this.handler.outputMetadata;\n  }\n\n  private handler: InferenceSessionHandler;\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { InferenceSession as InferenceSessionImpl } from './inference-session-impl.js';\nimport { OnnxModelOptions } from './onnx-model.js';\nimport { OnnxValue, OnnxValueDataLocation } from './onnx-value.js';\nimport type { Tensor } from './tensor.js';\nimport { TryGetGlobalType } from './type-helper.js';\n\n/* eslint-disable @typescript-eslint/no-redeclare */\n\nexport declare namespace InferenceSession {\n  // #region input/output types\n\n  type OnnxValueMapType = { readonly [name: string]: OnnxValue };\n  type NullableOnnxValueMapType = { readonly [name: string]: OnnxValue | null };\n\n  /**\n   * A feeds (model inputs) is an object that uses input names as keys and OnnxValue as corresponding values.\n   */\n  type FeedsType = OnnxValueMapType;\n\n  /**\n   * A fetches (model outputs) could be one of the following:\n   *\n   * - Omitted. Use model's output names definition.\n   * - An array of string indicating the output names.\n   * - An object that use output names as keys and OnnxValue or null as corresponding values.\n   *\n   * @remark\n   * different from input argument, in output, OnnxValue is optional. If an OnnxValue is present it will be\n   * used as a pre-allocated value by the inference engine; if omitted, inference engine will allocate buffer\n   * internally.\n   */\n  type FetchesType = readonly string[] | NullableOnnxValueMapType;\n\n  /**\n   * A inferencing return type is an object that uses output names as keys and OnnxValue as corresponding values.\n   */\n  type ReturnType = OnnxValueMapType;\n\n  // #endregion\n\n  // #region session options\n\n  /**\n   * A set of configurations for session behavior.\n   */\n  export interface SessionOptions extends OnnxModelOptions {\n    /**\n     * An array of execution provider options.\n     *\n     * An execution provider option can be a string indicating the name of the execution provider,\n     * or an object of corresponding type.\n     */\n    executionProviders?: readonly ExecutionProviderConfig[];\n\n    /**\n     * The intra OP threads number.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native).\n     */\n    intraOpNumThreads?: number;\n\n    /**\n     * The inter OP threads number.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native).\n     */\n    interOpNumThreads?: number;\n\n    /**\n     * The free dimension override.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    freeDimensionOverrides?: { readonly [dimensionName: string]: number };\n\n    /**\n     * The optimization level.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    graphOptimizationLevel?: 'disabled' | 'basic' | 'extended' | 'layout' | 'all';\n\n    /**\n     * Whether enable CPU memory arena.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    enableCpuMemArena?: boolean;\n\n    /**\n     * Whether enable memory pattern.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    enableMemPattern?: boolean;\n\n    /**\n     * Execution mode.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    executionMode?: 'sequential' | 'parallel';\n\n    /**\n     * Optimized model file path.\n     *\n     * If this setting is specified, the optimized model will be dumped. In browser, a blob will be created\n     * with a pop-up window.\n     */\n    optimizedModelFilePath?: string;\n\n    /**\n     * Whether enable profiling.\n     *\n     * This setting is a placeholder for a future use.\n     */\n    enableProfiling?: boolean;\n\n    /**\n     * File prefix for profiling.\n     *\n     * This setting is a placeholder for a future use.\n     */\n    profileFilePrefix?: string;\n\n    /**\n     * Log ID.\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    logId?: string;\n\n    /**\n     * Log severity level. See\n     * https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/common/logging/severity.h\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    logSeverityLevel?: 0 | 1 | 2 | 3 | 4;\n\n    /**\n     * Log verbosity level.\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     */\n    logVerbosityLevel?: number;\n\n    /**\n     * Specify string as a preferred data location for all outputs, or an object that use output names as keys and a\n     * preferred data location as corresponding values.\n     *\n     * This setting is available only in ONNXRuntime Web for WebGL and WebGPU EP.\n     */\n    preferredOutputLocation?: OnnxValueDataLocation | { readonly [outputName: string]: OnnxValueDataLocation };\n\n    /**\n     * Whether enable graph capture.\n     * This setting is available only in ONNXRuntime Web for WebGPU EP.\n     */\n    enableGraphCapture?: boolean;\n\n    /**\n     * Store configurations for a session. See\n     * https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/session/\n     * onnxruntime_session_options_config_keys.h\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     *\n     * @example\n     * ```js\n     * extra: {\n     *   session: {\n     *     set_denormal_as_zero: \"1\",\n     *     disable_prepacking: \"1\"\n     *   },\n     *   optimization: {\n     *     enable_gelu_approximation: \"1\"\n     *   }\n     * }\n     * ```\n     */\n    extra?: Record<string, unknown>;\n  }\n\n  // #region execution providers\n\n  // Currently, we have the following backends to support execution providers:\n  // Backend Node.js binding: supports 'cpu', 'dml' (win32), 'coreml' (macOS) and 'cuda' (linux).\n  // Backend WebAssembly: supports 'cpu', 'wasm', 'webgpu' and 'webnn'.\n  // Backend ONNX.js: supports 'webgl'.\n  // Backend React Native: supports 'cpu', 'xnnpack', 'coreml' (iOS), 'nnapi' (Android).\n  interface ExecutionProviderOptionMap {\n    coreml: CoreMLExecutionProviderOption;\n    cpu: CpuExecutionProviderOption;\n    cuda: CudaExecutionProviderOption;\n    dml: DmlExecutionProviderOption;\n    nnapi: NnapiExecutionProviderOption;\n    tensorrt: TensorRtExecutionProviderOption;\n    wasm: WebAssemblyExecutionProviderOption;\n    webgl: WebGLExecutionProviderOption;\n    webgpu: WebGpuExecutionProviderOption;\n    webnn: WebNNExecutionProviderOption;\n    qnn: QnnExecutionProviderOption;\n    xnnpack: XnnpackExecutionProviderOption;\n  }\n\n  type ExecutionProviderName = keyof ExecutionProviderOptionMap;\n  type ExecutionProviderConfig =\n    | ExecutionProviderOptionMap[ExecutionProviderName]\n    | ExecutionProviderOption\n    | ExecutionProviderName\n    | string;\n\n  export interface ExecutionProviderOption {\n    readonly name: string;\n  }\n  export interface CpuExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'cpu';\n    useArena?: boolean;\n  }\n  export interface CudaExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'cuda';\n    deviceId?: number;\n  }\n  export interface DmlExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'dml';\n    deviceId?: number;\n  }\n  export interface TensorRtExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'tensorrt';\n    deviceId?: number;\n  }\n  export interface WebAssemblyExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'wasm';\n  }\n  export interface WebGLExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'webgl';\n    // TODO: add flags\n  }\n  export interface XnnpackExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'xnnpack';\n  }\n  export interface WebGpuExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'webgpu';\n    preferredLayout?: 'NCHW' | 'NHWC';\n  }\n\n  // #region WebNN options\n\n  interface WebNNExecutionProviderName extends ExecutionProviderOption {\n    readonly name: 'webnn';\n  }\n\n  /**\n   * Represents a set of options for creating a WebNN MLContext.\n   *\n   * @see https://www.w3.org/TR/webnn/#dictdef-mlcontextoptions\n   */\n  export interface WebNNContextOptions {\n    deviceType?: 'cpu' | 'gpu' | 'npu';\n    numThreads?: number;\n    powerPreference?: 'default' | 'low-power' | 'high-performance';\n  }\n\n  /**\n   * Represents a set of options for WebNN execution provider without MLContext.\n   */\n  export interface WebNNOptionsWithoutMLContext extends WebNNExecutionProviderName, WebNNContextOptions {\n    context?: never;\n  }\n\n  /**\n   * Represents a set of options for WebNN execution provider with MLContext.\n   *\n   * When MLContext is provided, the deviceType is also required so that the WebNN EP can determine the preferred\n   * channel layout.\n   *\n   * @see https://www.w3.org/TR/webnn/#dom-ml-createcontext\n   */\n  export interface WebNNOptionsWithMLContext\n    extends WebNNExecutionProviderName,\n      Omit<WebNNContextOptions, 'deviceType'>,\n      Required<Pick<WebNNContextOptions, 'deviceType'>> {\n    context: TryGetGlobalType<'MLContext'>;\n  }\n\n  /**\n   * Represents a set of options for WebNN execution provider with MLContext which is created from GPUDevice.\n   *\n   * @see https://www.w3.org/TR/webnn/#dom-ml-createcontext-gpudevice\n   */\n  export interface WebNNOptionsWebGpu extends WebNNExecutionProviderName {\n    context: TryGetGlobalType<'MLContext'>;\n    gpuDevice: TryGetGlobalType<'GPUDevice'>;\n  }\n\n  /**\n   * Options for WebNN execution provider.\n   */\n  export type WebNNExecutionProviderOption =\n    | WebNNOptionsWithoutMLContext\n    | WebNNOptionsWithMLContext\n    | WebNNOptionsWebGpu;\n\n  // #endregion\n\n  export interface QnnExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'qnn';\n    /**\n     * Specify the QNN backend type. E.g., 'cpu' or 'htp'.\n     * Mutually exclusive with `backendPath`.\n     *\n     * @default 'htp'\n     */\n    backendType?: string;\n    /**\n     * Specify a path to the QNN backend library.\n     * Mutually exclusive with `backendType`.\n     */\n    backendPath?: string;\n    /**\n     * Specify whether to enable HTP FP16 precision.\n     *\n     * @default true\n     */\n    enableFp16Precision?: boolean;\n  }\n  export interface CoreMLExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'coreml';\n    /**\n     * The bit flags for CoreML execution provider.\n     *\n     * ```\n     * COREML_FLAG_USE_CPU_ONLY = 0x001\n     * COREML_FLAG_ENABLE_ON_SUBGRAPH = 0x002\n     * COREML_FLAG_ONLY_ENABLE_DEVICE_WITH_ANE = 0x004\n     * COREML_FLAG_ONLY_ALLOW_STATIC_INPUT_SHAPES = 0x008\n     * COREML_FLAG_CREATE_MLPROGRAM = 0x010\n     * COREML_FLAG_USE_CPU_AND_GPU = 0x020\n     * ```\n     *\n     * See include/onnxruntime/core/providers/coreml/coreml_provider_factory.h for more details.\n     *\n     * This flag is available only in ONNXRuntime (Node.js binding).\n     */\n    coreMlFlags?: number;\n    /**\n     * Specify whether to use CPU only in CoreML EP.\n     *\n     * This setting is available only in ONNXRuntime (react-native).\n     */\n    useCPUOnly?: boolean;\n    useCPUAndGPU?: boolean;\n    /**\n     * Specify whether to enable CoreML EP on subgraph.\n     *\n     * This setting is available only in ONNXRuntime (react-native).\n     */\n    enableOnSubgraph?: boolean;\n    /**\n     * Specify whether to only enable CoreML EP for Apple devices with ANE (Apple Neural Engine).\n     *\n     * This setting is available only in ONNXRuntime (react-native).\n     */\n    onlyEnableDeviceWithANE?: boolean;\n  }\n  export interface NnapiExecutionProviderOption extends ExecutionProviderOption {\n    readonly name: 'nnapi';\n    useFP16?: boolean;\n    useNCHW?: boolean;\n    cpuDisabled?: boolean;\n    cpuOnly?: boolean;\n  }\n  // #endregion\n\n  // #endregion\n\n  // #region run options\n\n  /**\n   * A set of configurations for inference run behavior\n   */\n  export interface RunOptions {\n    /**\n     * Log severity level. See\n     * https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/common/logging/severity.h\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    logSeverityLevel?: 0 | 1 | 2 | 3 | 4;\n\n    /**\n     * Log verbosity level.\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     */\n    logVerbosityLevel?: number;\n\n    /**\n     * Terminate all incomplete OrtRun calls as soon as possible if true\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     */\n    terminate?: boolean;\n\n    /**\n     * A tag for the Run() calls using this\n     *\n     * This setting is available only in ONNXRuntime (Node.js binding and react-native) or WebAssembly backend\n     */\n    tag?: string;\n\n    /**\n     * Set a single run configuration entry. See\n     * https://github.com/microsoft/onnxruntime/blob/main/include/onnxruntime/core/session/\n     * onnxruntime_run_options_config_keys.h\n     *\n     * This setting is available only in WebAssembly backend. Will support Node.js binding and react-native later\n     *\n     * @example\n     *\n     * ```js\n     * extra: {\n     *   memory: {\n     *     enable_memory_arena_shrinkage: \"1\",\n     *   }\n     * }\n     * ```\n     */\n    extra?: Record<string, unknown>;\n  }\n\n  // #endregion\n\n  // #region value metadata\n\n  /**\n   * The common part of the value metadata type for both tensor and non-tensor values.\n   */\n  export interface ValueMetadataBase {\n    /**\n     * The name of the specified input or output.\n     */\n    readonly name: string;\n  }\n\n  /**\n   * Represents the metadata of a non-tensor value.\n   */\n  export interface NonTensorValueMetadata extends ValueMetadataBase {\n    /**\n     * Get a value indicating whether the value is a tensor.\n     */\n    readonly isTensor: false;\n  }\n\n  /**\n   * Represents the metadata of a tensor value.\n   */\n  export interface TensorValueMetadata extends ValueMetadataBase {\n    /**\n     * Get a value indicating whether the value is a tensor.\n     */\n    readonly isTensor: true;\n    /**\n     * Get the data type of the tensor.\n     */\n    readonly type: Tensor.Type;\n    /**\n     * Get the shape of the tensor.\n     *\n     * If the shape is not defined, the value will an empty array. Otherwise, it will be an array representing the shape\n     * of the tensor. Each element in the array can be a number or a string. If the element is a number, it represents\n     * the corresponding dimension size. If the element is a string, it represents a symbolic dimension.\n     */\n    readonly shape: ReadonlyArray<number | string>;\n  }\n\n  /**\n   * Represents the metadata of a value.\n   */\n  export type ValueMetadata = NonTensorValueMetadata | TensorValueMetadata;\n\n  // #endregion\n}\n\n/**\n * Represent a runtime instance of an ONNX model.\n */\nexport interface InferenceSession {\n  // #region run()\n\n  /**\n   * Execute the model asynchronously with the given feeds and options.\n   *\n   * @param feeds - Representation of the model input. See type description of `InferenceSession.InputType` for detail.\n   * @param options - Optional. A set of options that controls the behavior of model inference.\n   * @returns A promise that resolves to a map, which uses output names as keys and OnnxValue as corresponding values.\n   */\n  run(feeds: InferenceSession.FeedsType, options?: InferenceSession.RunOptions): Promise<InferenceSession.ReturnType>;\n\n  /**\n   * Execute the model asynchronously with the given feeds, fetches and options.\n   *\n   * @param feeds - Representation of the model input. See type description of `InferenceSession.InputType` for detail.\n   * @param fetches - Representation of the model output. See type description of `InferenceSession.OutputType` for\n   * detail.\n   * @param options - Optional. A set of options that controls the behavior of model inference.\n   * @returns A promise that resolves to a map, which uses output names as keys and OnnxValue as corresponding values.\n   */\n  run(\n    feeds: InferenceSession.FeedsType,\n    fetches: InferenceSession.FetchesType,\n    options?: InferenceSession.RunOptions,\n  ): Promise<InferenceSession.ReturnType>;\n\n  // #endregion\n\n  // #region release()\n\n  /**\n   * Release the inference session and the underlying resources.\n   */\n  release(): Promise<void>;\n\n  // #endregion\n\n  // #region profiling\n\n  /**\n   * Start profiling.\n   */\n  startProfiling(): void;\n\n  /**\n   * End profiling.\n   */\n  endProfiling(): void;\n\n  // #endregion\n\n  // #region metadata\n\n  /**\n   * Get input names of the loaded model.\n   */\n  readonly inputNames: readonly string[];\n\n  /**\n   * Get output names of the loaded model.\n   */\n  readonly outputNames: readonly string[];\n\n  /**\n   * Get input metadata of the loaded model.\n   */\n  readonly inputMetadata: readonly InferenceSession.ValueMetadata[];\n\n  /**\n   * Get output metadata of the loaded model.\n   */\n  readonly outputMetadata: readonly InferenceSession.ValueMetadata[];\n\n  // #endregion\n}\n\nexport interface InferenceSessionFactory {\n  // #region create()\n\n  /**\n   * Create a new inference session and load model asynchronously from an ONNX model file.\n   *\n   * @param uri - The URI or file path of the model to load.\n   * @param options - specify configuration for creating a new inference session.\n   * @returns A promise that resolves to an InferenceSession object.\n   */\n  create(uri: string, options?: InferenceSession.SessionOptions): Promise<InferenceSession>;\n\n  /**\n   * Create a new inference session and load model asynchronously from an array bufer.\n   *\n   * @param buffer - An ArrayBuffer representation of an ONNX model.\n   * @param options - specify configuration for creating a new inference session.\n   * @returns A promise that resolves to an InferenceSession object.\n   */\n  create(buffer: ArrayBufferLike, options?: InferenceSession.SessionOptions): Promise<InferenceSession>;\n\n  /**\n   * Create a new inference session and load model asynchronously from segment of an array bufer.\n   *\n   * @param buffer - An ArrayBuffer representation of an ONNX model.\n   * @param byteOffset - The beginning of the specified portion of the array buffer.\n   * @param byteLength - The length in bytes of the array buffer.\n   * @param options - specify configuration for creating a new inference session.\n   * @returns A promise that resolves to an InferenceSession object.\n   */\n  create(\n    buffer: ArrayBufferLike,\n    byteOffset: number,\n    byteLength?: number,\n    options?: InferenceSession.SessionOptions,\n  ): Promise<InferenceSession>;\n\n  /**\n   * Create a new inference session and load model asynchronously from a Uint8Array.\n   *\n   * @param buffer - A Uint8Array representation of an ONNX model.\n   * @param options - specify configuration for creating a new inference session.\n   * @returns A promise that resolves to an InferenceSession object.\n   */\n  create(buffer: Uint8Array, options?: InferenceSession.SessionOptions): Promise<InferenceSession>;\n\n  // #endregion\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const InferenceSession: InferenceSessionFactory = InferenceSessionImpl;\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { OptionsFormat, OptionsNormalizationParameters, OptionsTensorLayout } from './tensor-factory.js';\n\nexport interface TensorToDataUrlOptions extends OptionsTensorLayout, OptionsFormat, OptionsNormalizationParameters {}\n\nexport interface TensorToImageDataOptions extends OptionsTensorLayout, OptionsFormat, OptionsNormalizationParameters {}\n\nexport interface ConversionUtils {\n  /**\n   * creates a DataURL instance from tensor\n   *\n   * @param options - An optional object representing options for creating a DataURL instance from the tensor.\n   *\n   * The following default settings will be applied:\n   * - `format`: `'RGB'`\n   * - `tensorLayout`: `'NCHW'`\n   * @returns a DataURL string representing the image converted from tensor data\n   */\n  toDataURL(options?: TensorToDataUrlOptions): string;\n\n  /**\n   * creates an ImageData instance from tensor\n   *\n   * @param options - An optional object representing options for creating an ImageData instance from the tensor.\n   *\n   * The following default settings will be applied:\n   * - `format`: `'RGB'`\n   * - `tensorLayout`: `'NCHW'`\n   * @returns an ImageData instance representing the image converted from tensor data\n   */\n  toImageData(options?: TensorToImageDataOptions): ImageData;\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Tensor, TypedTensor } from './tensor.js';\n\nexport type ImageFormat = 'RGB' | 'RGBA' | 'BGR' | 'RBG';\nexport type ImageTensorLayout = 'NHWC' | 'NCHW';\n\n// the following region contains type definitions for constructing tensor from a specific location.\n\n// #region types for constructing a tensor from a specific location\n\n/**\n * represent common properties of the parameter for constructing a tensor from a specific location.\n */\ninterface CommonConstructorParameters<T> extends Pick<Tensor, 'dims'> {\n  /**\n   * Specify the data type of the tensor.\n   */\n  readonly type: T;\n}\n\n/**\n * represent the parameter for constructing a tensor from a GPU resource.\n */\ninterface GpuResourceConstructorParameters<T extends Tensor.Type> {\n  /**\n   * an optional callback function to download data from GPU to CPU.\n   *\n   * If not provided, the tensor treat the GPU data as external resource.\n   */\n  download?(): Promise<Tensor.DataTypeMap[T]>;\n\n  /**\n   * an optional callback function that will be called when the tensor is disposed.\n   *\n   * If not provided, the tensor treat the GPU data as external resource.\n   */\n  dispose?(): void;\n}\n\n/**\n * represent the parameter for constructing a tensor from a pinned CPU buffer\n */\nexport interface CpuPinnedConstructorParameters<T extends Tensor.CpuPinnedDataTypes = Tensor.CpuPinnedDataTypes>\n  extends CommonConstructorParameters<T> {\n  /**\n   * Specify the location of the data to be 'cpu-pinned'.\n   */\n  readonly location: 'cpu-pinned';\n  /**\n   * Specify the CPU pinned buffer that holds the tensor data.\n   */\n  readonly data: Tensor.DataTypeMap[T];\n}\n\n/**\n * represent the parameter for constructing a tensor from a WebGL texture\n */\nexport interface TextureConstructorParameters<T extends Tensor.TextureDataTypes = Tensor.TextureDataTypes>\n  extends CommonConstructorParameters<T>,\n    GpuResourceConstructorParameters<T> {\n  /**\n   * Specify the location of the data to be 'texture'.\n   */\n  readonly location: 'texture';\n  /**\n   * Specify the WebGL texture that holds the tensor data.\n   */\n  readonly texture: Tensor.TextureType;\n}\n\n/**\n * represent the parameter for constructing a tensor from a WebGPU buffer\n */\nexport interface GpuBufferConstructorParameters<T extends Tensor.GpuBufferDataTypes = Tensor.GpuBufferDataTypes>\n  extends CommonConstructorParameters<T>,\n    GpuResourceConstructorParameters<T> {\n  /**\n   * Specify the location of the data to be 'gpu-buffer'.\n   */\n  readonly location: 'gpu-buffer';\n  /**\n   * Specify the WebGPU buffer that holds the tensor data.\n   */\n  readonly gpuBuffer: Tensor.GpuBufferType;\n}\n\nexport interface MLTensorConstructorParameters<T extends Tensor.MLTensorDataTypes = Tensor.MLTensorDataTypes>\n  extends CommonConstructorParameters<T>,\n    GpuResourceConstructorParameters<T> {\n  /**\n   * Specify the location of the data to be 'ml-tensor'.\n   */\n  readonly location: 'ml-tensor';\n\n  /**\n   * Specify the WebNN MLTensor that holds the tensor data.\n   */\n  readonly mlTensor: Tensor.MLTensorType;\n}\n\n// #endregion\n\n// the following region contains type definitions of each individual options.\n// the tensor factory functions use a composition of those options as the parameter type.\n\n// #region Options fields\n\nexport interface OptionsFormat {\n  /**\n   * Describes the image format represented in RGBA color space.\n   */\n  format?: ImageFormat;\n}\n\nexport interface OptionsTensorFormat {\n  /**\n   * Describes the image format of the tensor.\n   *\n   * NOTE: this is different from option 'format'. While option 'format' represents the original image, 'tensorFormat'\n   * represents the target format of the tensor. A transpose will be performed if they are different.\n   */\n  tensorFormat?: ImageFormat;\n}\n\nexport interface OptionsTensorDataType {\n  /**\n   * Describes the data type of the tensor.\n   */\n  dataType?: 'float32' | 'uint8';\n}\n\nexport interface OptionsTensorLayout {\n  /**\n   * Describes the tensor layout when representing data of one or more image(s).\n   */\n  tensorLayout?: ImageTensorLayout;\n}\n\nexport interface OptionsDimensions {\n  /**\n   * Describes the image height in pixel\n   */\n  height?: number;\n  /**\n   * Describes the image width in pixel\n   */\n  width?: number;\n}\n\nexport interface OptionResizedDimensions {\n  /**\n   * Describes the resized height. If omitted, original height will be used.\n   */\n  resizedHeight?: number;\n  /**\n   * Describes resized width - can be accessed via tensor dimensions as well\n   */\n  resizedWidth?: number;\n}\n\nexport interface OptionsNormalizationParameters {\n  /**\n   * Describes normalization parameters when preprocessing the image as model input.\n   *\n   * Data element are ranged from 0 to 255.\n   */\n  norm?: {\n    /**\n     * The 'bias' value for image normalization.\n     * - If omitted, use default value 0.\n     * - If it's a single number, apply to each channel\n     * - If it's an array of 3 or 4 numbers, apply element-wise. Number of elements need to match the number of channels\n     * for the corresponding image format\n     */\n    bias?: number | [number, number, number] | [number, number, number, number];\n    /**\n     * The 'mean' value for image normalization.\n     * - If omitted, use default value 255.\n     * - If it's a single number, apply to each channel\n     * - If it's an array of 3 or 4 numbers, apply element-wise. Number of elements need to match the number of channels\n     * for the corresponding image format\n     */\n    mean?: number | [number, number, number] | [number, number, number, number];\n  };\n}\n\n// #endregion\n\n// #region Options composition\n\nexport interface TensorFromImageDataOptions\n  extends OptionResizedDimensions,\n    OptionsTensorFormat,\n    OptionsTensorLayout,\n    OptionsTensorDataType,\n    OptionsNormalizationParameters {}\n\nexport interface TensorFromImageElementOptions\n  extends OptionResizedDimensions,\n    OptionsTensorFormat,\n    OptionsTensorLayout,\n    OptionsTensorDataType,\n    OptionsNormalizationParameters {}\n\nexport interface TensorFromUrlOptions\n  extends OptionsDimensions,\n    OptionResizedDimensions,\n    OptionsTensorFormat,\n    OptionsTensorLayout,\n    OptionsTensorDataType,\n    OptionsNormalizationParameters {}\n\nexport interface TensorFromImageBitmapOptions\n  extends OptionResizedDimensions,\n    OptionsTensorFormat,\n    OptionsTensorLayout,\n    OptionsTensorDataType,\n    OptionsNormalizationParameters {}\n\nexport interface TensorFromTextureOptions<T extends Tensor.TextureDataTypes>\n  extends Required<OptionsDimensions>,\n    OptionsFormat,\n    GpuResourceConstructorParameters<T> /* TODO: add more */ {}\n\nexport interface TensorFromGpuBufferOptions<T extends Tensor.GpuBufferDataTypes>\n  extends Pick<Tensor, 'dims'>,\n    GpuResourceConstructorParameters<T> {\n  /**\n   * Describes the data type of the tensor.\n   */\n  dataType?: T;\n}\n\nexport interface TensorFromMLTensorOptions<T extends Tensor.MLTensorDataTypes>\n  extends Pick<Tensor, 'dims'>,\n    GpuResourceConstructorParameters<T> {\n  /**\n   * Describes the data type of the tensor.\n   */\n  dataType?: T;\n}\n\n// #endregion\n\n/**\n * type TensorFactory defines the factory functions of 'Tensor' to create tensor instances from existing data or\n * resources.\n */\nexport interface TensorFactory {\n  /**\n   * create a tensor from an ImageData object\n   *\n   * @param imageData - the ImageData object to create tensor from\n   * @param options - An optional object representing options for creating tensor from ImageData.\n   *\n   * The following default settings will be applied:\n   * - `tensorFormat`: `'RGB'`\n   * - `tensorLayout`: `'NCHW'`\n   * - `dataType`: `'float32'`\n   * @returns A promise that resolves to a tensor object\n   */\n  fromImage(\n    imageData: ImageData,\n    options?: TensorFromImageDataOptions,\n  ): Promise<TypedTensor<'float32'> | TypedTensor<'uint8'>>;\n\n  /**\n   * create a tensor from a HTMLImageElement object\n   *\n   * @param imageElement - the HTMLImageElement object to create tensor from\n   * @param options - An optional object representing options for creating tensor from HTMLImageElement.\n   *\n   * The following default settings will be applied:\n   * - `tensorFormat`: `'RGB'`\n   * - `tensorLayout`: `'NCHW'`\n   * - `dataType`: `'float32'`\n   * @returns A promise that resolves to a tensor object\n   */\n  fromImage(\n    imageElement: HTMLImageElement,\n    options?: TensorFromImageElementOptions,\n  ): Promise<TypedTensor<'float32'> | TypedTensor<'uint8'>>;\n\n  /**\n   * create a tensor from URL\n   *\n   * @param urlSource - a string as a URL to the image or a data URL containing the image data.\n   * @param options - An optional object representing options for creating tensor from URL.\n   *\n   * The following default settings will be applied:\n   * - `tensorFormat`: `'RGB'`\n   * - `tensorLayout`: `'NCHW'`\n   * - `dataType`: `'float32'`\n   * @returns A promise that resolves to a tensor object\n   */\n  fromImage(urlSource: string, options?: TensorFromUrlOptions): Promise<TypedTensor<'float32'> | TypedTensor<'uint8'>>;\n\n  /**\n   * create a tensor from an ImageBitmap object\n   *\n   * @param bitmap - the ImageBitmap object to create tensor from\n   * @param options - An optional object representing options for creating tensor from URL.\n   *\n   * The following default settings will be applied:\n   * - `tensorFormat`: `'RGB'`\n   * - `tensorLayout`: `'NCHW'`\n   * - `dataType`: `'float32'`\n   * @returns A promise that resolves to a tensor object\n   */\n  fromImage(\n    bitmap: ImageBitmap,\n    options: TensorFromImageBitmapOptions,\n  ): Promise<TypedTensor<'float32'> | TypedTensor<'uint8'>>;\n\n  /**\n   * create a tensor from a WebGL texture\n   *\n   * @param texture - the WebGLTexture object to create tensor from\n   * @param options - An optional object representing options for creating tensor from WebGL texture.\n   *\n   * The options include following properties:\n   * - `width`: the width of the texture. Required.\n   * - `height`: the height of the texture. Required.\n   * - `format`: the format of the texture. If omitted, assume 'RGBA'.\n   * - `download`: an optional function to download the tensor data from GPU to CPU. If omitted, the GPU data\n   * will not be able to download. Usually, this is provided by a GPU backend for the inference outputs. Users don't\n   * need to provide this function.\n   * - `dispose`: an optional function to dispose the tensor data on GPU. If omitted, the GPU data will not be disposed.\n   * Usually, this is provided by a GPU backend for the inference outputs. Users don't need to provide this function.\n   *\n   * @returns a tensor object\n   */\n  fromTexture<T extends Tensor.TextureDataTypes = 'float32'>(\n    texture: Tensor.TextureType,\n    options: TensorFromTextureOptions<T>,\n  ): TypedTensor<'float32'>;\n\n  /**\n   * create a tensor from a WebGPU buffer\n   *\n   * @param buffer - the GPUBuffer object to create tensor from\n   * @param options - An optional object representing options for creating tensor from WebGPU buffer.\n   *\n   * The options include following properties:\n   * - `dataType`: the data type of the tensor. If omitted, assume 'float32'.\n   * - `dims`: the dimension of the tensor. Required.\n   * - `download`: an optional function to download the tensor data from GPU to CPU. If omitted, the GPU data\n   * will not be able to download. Usually, this is provided by a GPU backend for the inference outputs. Users don't\n   * need to provide this function.\n   * - `dispose`: an optional function to dispose the tensor data on GPU. If omitted, the GPU data will not be disposed.\n   * Usually, this is provided by a GPU backend for the inference outputs. Users don't need to provide this function.\n   *\n   * @returns a tensor object\n   */\n  fromGpuBuffer<T extends Tensor.GpuBufferDataTypes>(\n    buffer: Tensor.GpuBufferType,\n    options: TensorFromGpuBufferOptions<T>,\n  ): TypedTensor<T>;\n\n  /**\n   * create a tensor from a WebNN MLTensor\n   *\n   * @param tensor - the MLTensor object to create tensor from\n   * @param options - An optional object representing options for creating tensor from a WebNN MLTensor.\n   *\n   * The options include following properties:\n   * - `dataType`: the data type of the tensor. If omitted, assume 'float32'.\n   * - `dims`: the dimension of the tensor. Required.\n   * - `download`: an optional function to download the tensor data from the MLTensor to CPU. If omitted, the MLTensor\n   * data will not be able to download. Usually, this is provided by the WebNN backend for the inference outputs.\n   * Users don't need to provide this function.\n   * - `dispose`: an optional function to dispose the tensor data on the WebNN MLTensor. If omitted, the MLTensor will\n   * not be disposed. Usually, this is provided by the WebNN backend for the inference outputs. Users don't need to\n   * provide this function.\n   *\n   * @returns a tensor object\n   */\n  fromMLTensor<T extends Tensor.MLTensorDataTypes>(\n    tensor: Tensor.MLTensorType,\n    options: TensorFromMLTensorOptions<T>,\n  ): TypedTensor<T>;\n\n  /**\n   * create a tensor from a pre-allocated buffer. The buffer will be used as a pinned buffer.\n   *\n   * @param type - the tensor element type.\n   * @param buffer - a TypedArray corresponding to the type.\n   * @param dims - specify the dimension of the tensor. If omitted, a 1-D tensor is assumed.\n   *\n   * @returns a tensor object\n   */\n  fromPinnedBuffer<T extends Exclude<Tensor.Type, 'string'>>(\n    type: T,\n    buffer: Tensor.DataTypeMap[T],\n    dims?: readonly number[],\n  ): TypedTensor<T>;\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n/**\n * A string that represents a file's URL or path.\n *\n * Path is vailable only in onnxruntime-node or onnxruntime-web running in Node.js.\n */\nexport type FileUrlOrPath = string;\n\n/**\n * A Blob object that represents a file.\n */\nexport type FileBlob = Blob;\n\n/**\n * A Uint8Array, ArrayBuffer or SharedArrayBuffer object that represents a file content.\n *\n * When it is an ArrayBuffer or SharedArrayBuffer, the whole buffer is assumed to be the file content.\n */\nexport type FileData = Uint8Array | ArrayBufferLike;\n\n/**\n * Represents a file that can be loaded by the ONNX Runtime JavaScript API.\n */\nexport type FileType = FileUrlOrPath | FileBlob | FileData;\n\n/**\n * Represents an external data file.\n */\nexport interface ExternalDataFileDescription {\n  /**\n   * Specify the external data file.\n   */\n  data: FileType;\n  /**\n   * Specify the file path.\n   */\n  path: string;\n}\n\n/**\n * Represents an external data file.\n *\n * When using a string, it should be a file URL or path that in the same directory as the model file.\n */\nexport type ExternalDataFileType = ExternalDataFileDescription | FileUrlOrPath;\n\n/**\n * Options for model loading.\n */\nexport interface OnnxModelOptions {\n  /**\n   * Specifying a list of files that represents the external data.\n   */\n  externalData?: readonly ExternalDataFileType[];\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Tensor } from './tensor.js';\n\nexport type NonTensorType = never;\n\n/**\n * Type OnnxValue Represents both tensors and non-tensors value for model's inputs/outputs.\n *\n * NOTE: currently not support non-tensor\n */\nexport type OnnxValue = Tensor | NonTensorType;\n\n/**\n * Type OnnxValueDataLocation represents the location of the data of an OnnxValue.\n */\nexport type OnnxValueDataLocation = Tensor.DataLocation;\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n/**\n * # ONNX Runtime JavaScript API\n *\n * ONNX Runtime JavaScript API is a unified API for all JavaScript usages, including the following NPM packages:\n *\n * - [onnxruntime-node](https://www.npmjs.com/package/onnxruntime-node)\n * - [onnxruntime-web](https://www.npmjs.com/package/onnxruntime-web)\n * - [onnxruntime-react-native](https://www.npmjs.com/package/onnxruntime-react-native)\n *\n * See also:\n * - [Get Started](https://onnxruntime.ai/docs/get-started/with-javascript/)\n * - [Inference examples](https://github.com/microsoft/onnxruntime-inference-examples/tree/main/js)\n *\n * @packageDocumentation\n */\n\nexport * from './backend.js';\nexport * from './env.js';\nexport * from './inference-session.js';\nexport * from './tensor.js';\nexport * from './tensor-conversion.js';\nexport * from './tensor-factory.js';\nexport * from './trace.js';\nexport * from './onnx-model.js';\nexport * from './onnx-value.js';\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nexport const isNode = !!(typeof process !== 'undefined' && process.versions && process.versions.node);\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n/// <reference lib=\"webworker\" />\n\n//\n// * type hack for \"HTMLImageElement\"\n//\n// in typescript, the type of \"HTMLImageElement\" is defined in lib.dom.d.ts, which is conflict with lib.webworker.d.ts.\n// when we use webworker, the lib.webworker.d.ts will be used, which does not have HTMLImageElement defined.\n//\n// we will get the following errors complaining that HTMLImageElement is not defined:\n//\n// ====================================================================================================================\n//\n// ../common/dist/cjs/tensor-factory.d.ts:187:29 - error TS2552: Cannot find name 'HTMLImageElement'. Did you mean\n// 'HTMLLIElement'?\n//\n// 187     fromImage(imageElement: HTMLImageElement, options?: TensorFromImageElementOptions):\n// Promise<TypedTensor<'float32'> | TypedTensor<'uint8'>>;\n//                                 ~~~~~~~~~~~~~~~~\n//\n// node_modules/@webgpu/types/dist/index.d.ts:83:7 - error TS2552: Cannot find name 'HTMLImageElement'. Did you mean\n// 'HTMLLIElement'?\n//\n// 83     | HTMLImageElement\n//          ~~~~~~~~~~~~~~~~\n//\n// ====================================================================================================================\n//\n// `HTMLImageElement` is only used in type declaration and not in real code. So we define it as `unknown` here to\n// bypass the type check.\n\n//\n// * type hack for \"document\"\n//\n// in typescript, the type of \"document\" is defined in lib.dom.d.ts, so it's not available in webworker.\n//\n// we will get the following errors complaining that document is not defined:\n//\n// ====================================================================================================================\n//\n// lib/wasm/wasm-utils-import.ts:7:33 - error TS2584: Cannot find name 'document'. Do you need to change your target\n// library? Try changing the 'lib' compiler option to include 'dom'.\n//\n// 7 export const scriptSrc = typeof document !== 'undefined' ? (document?.currentScript as HTMLScriptElement)?.src :\n//                                   ~~~~~~~~\n//\n// lib/wasm/wasm-utils-import.ts:7:61 - error TS2584: Cannot find name 'document'. Do you need to change your target\n// library? Try changing the 'lib' compiler option to include 'dom'.\n//\n// 7 export const scriptSrc = typeof document !== 'undefined' ? (document?.currentScript as HTMLScriptElement)?.src :\n//                                                               ~~~~~~~~\n//\n// lib/wasm/wasm-utils-import.ts:7:88 - error TS2552: Cannot find name 'HTMLScriptElement'. Did you mean\n// 'HTMLLIElement'?\n//\n// 7 export const scriptSrc = typeof document !== 'undefined' ? (document?.currentScript as HTMLScriptElement)?.src :\n//                                                                                          ~~~~~~~~~~~~~~~~~\n// ====================================================================================================================\n//\n// `document` is used to get the current script URL, which is not available in webworker. This file is served as a\n// \"dual\" file for entries of both webworker and the esm module.\n//\ndeclare global {\n  type HTMLImageElement = unknown;\n  type HTMLScriptElement = { src?: string };\n  const document: undefined | { currentScript?: HTMLScriptElement };\n}\n\n/**\n * @summary\n *\n * This file is served as a \"dual\" file for both entries of the following:\n * - The proxy worker itself.\n *   - When used as a worker, it listens to the messages from the main thread and performs the corresponding operations.\n *   - Should be imported directly using `new Worker()` in the main thread.\n *\n * - The ESM module that creates the proxy worker (as a worker launcher).\n *   - When used as a worker launcher, it creates the proxy worker and returns it.\n *   - Should be imported using `import()` in the main thread, with the query parameter `import=1`.\n *\n * This file will be always compiling into ESM format.\n */\n\nimport type { OrtWasmMessage, SerializableTensorMetadata } from '../proxy-messages.js';\nimport {\n  createSession,\n  copyFromExternalBuffer,\n  endProfiling,\n  extractTransferableBuffers,\n  initEp,\n  initRuntime,\n  releaseSession,\n  run,\n} from '../wasm-core-impl.js';\nimport { initializeWebAssembly } from '../wasm-factory.js';\nimport { scriptSrc } from '../wasm-utils-import.js';\n\nconst WORKER_NAME = 'ort-wasm-proxy-worker';\nconst isProxyWorker = globalThis.self?.name === WORKER_NAME;\n\nif (isProxyWorker) {\n  // Worker thread\n  self.onmessage = (ev: MessageEvent<OrtWasmMessage>): void => {\n    const { type, in: message } = ev.data;\n    try {\n      switch (type) {\n        case 'init-wasm':\n          initializeWebAssembly(message!.wasm).then(\n            () => {\n              initRuntime(message!).then(\n                () => {\n                  postMessage({ type });\n                },\n                (err) => {\n                  postMessage({ type, err });\n                },\n              );\n            },\n            (err) => {\n              postMessage({ type, err });\n            },\n          );\n          break;\n        case 'init-ep': {\n          const { epName, env } = message!;\n          initEp(env, epName).then(\n            () => {\n              postMessage({ type });\n            },\n            (err) => {\n              postMessage({ type, err });\n            },\n          );\n          break;\n        }\n        case 'copy-from': {\n          const { buffer } = message!;\n          const bufferData = copyFromExternalBuffer(buffer);\n          postMessage({ type, out: bufferData } as OrtWasmMessage);\n          break;\n        }\n        case 'create': {\n          const { model, options } = message!;\n          createSession(model, options).then(\n            (sessionMetadata) => {\n              postMessage({ type, out: sessionMetadata } as OrtWasmMessage);\n            },\n            (err) => {\n              postMessage({ type, err });\n            },\n          );\n          break;\n        }\n        case 'release':\n          releaseSession(message!);\n          postMessage({ type });\n          break;\n        case 'run': {\n          const { sessionId, inputIndices, inputs, outputIndices, options } = message!;\n          run(sessionId, inputIndices, inputs, outputIndices, new Array(outputIndices.length).fill(null), options).then(\n            (outputs) => {\n              if (outputs.some((o) => o[3] !== 'cpu')) {\n                postMessage({ type, err: 'Proxy does not support non-cpu tensor location.' });\n              } else {\n                postMessage(\n                  { type, out: outputs } as OrtWasmMessage,\n                  extractTransferableBuffers([...inputs, ...outputs] as SerializableTensorMetadata[]),\n                );\n              }\n            },\n            (err) => {\n              postMessage({ type, err });\n            },\n          );\n          break;\n        }\n        case 'end-profiling':\n          endProfiling(message!);\n          postMessage({ type });\n          break;\n        default:\n      }\n    } catch (err) {\n      postMessage({ type, err } as OrtWasmMessage);\n    }\n  };\n}\n\nexport default isProxyWorker\n  ? null\n  : (urlOverride?: string) =>\n      new Worker(urlOverride ?? scriptSrc!, { type: BUILD_DEFS.IS_ESM ? 'module' : 'classic', name: WORKER_NAME });\n","var e=async function(e={}){var r,t,n=e,a=new Promise(((e,n)=>{r=e,t=n})),i=\"object\"==typeof window,o=\"undefined\"!=typeof WorkerGlobalScope,s=o&&self.name?.startsWith(\"em-pthread\");n.mountExternalData=(e,r)=>{e.startsWith(\"./\")&&(e=e.substring(2)),(n.Sa||(n.Sa=new Map)).set(e,r)},n.unmountExternalData=()=>{delete n.Sa};var u,f,c=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,kb:!0}).buffer.constructor,l=(e,r)=>{throw r},d=import.meta.url,m=\"\";if(i||o){try{m=new URL(\".\",d).href}catch{}o&&(f=e=>{var r=new XMLHttpRequest;return r.open(\"GET\",e,!1),r.responseType=\"arraybuffer\",r.send(null),new Uint8Array(r.response)}),u=async e=>{if(D(e))return new Promise(((r,t)=>{var n=new XMLHttpRequest;n.open(\"GET\",e,!0),n.responseType=\"arraybuffer\",n.onload=()=>{200==n.status||0==n.status&&n.response?r(n.response):t(n.status)},n.onerror=t,n.send(null)}));var r=await fetch(e,{credentials:\"same-origin\"});if(r.ok)return r.arrayBuffer();throw Error(r.status+\" : \"+r.url)}}var g,h,v,p,b,w,O,_,y,T,A,C,E,R=console.log.bind(console),S=console.error.bind(console),M=R,k=S,U=!1,D=e=>e.startsWith(\"file://\");function F(){return h.buffer!=b.buffer&&L(),b}function B(){return h.buffer!=b.buffer&&L(),w}function x(){return h.buffer!=b.buffer&&L(),O}function W(){return h.buffer!=b.buffer&&L(),_}function N(){return h.buffer!=b.buffer&&L(),y}function I(){return h.buffer!=b.buffer&&L(),T}function P(){return h.buffer!=b.buffer&&L(),C}if(s){var $=!1;function qr(e){try{var r=e.data,t=r.Ra;if(\"load\"===t){let e=[];self.onmessage=r=>e.push(r),self.startWorker=()=>{postMessage({Ra:\"loaded\"});for(let r of e)qr(r);self.onmessage=qr};for(const e of r.Za)n[e]&&!n[e].proxy||(n[e]=(...r)=>{postMessage({Ra:\"callHandler\",Ya:e,args:r})},\"print\"==e&&(M=n[e]),\"printErr\"==e&&(k=n[e]));h=r.fb,L(),E(r.gb)}else if(\"run\"===t){me(r.Qa),Pr(r.Qa,0,0,1,0,0),fe(),Pe(r.Qa),$||=!0;try{he(r.bb,r.Va)}catch(e){if(\"unwind\"!=e)throw e}}else\"setimmediate\"!==r.target&&(\"checkMailbox\"===t?$&&$e():t&&(k(`worker: received unknown command ${t}`),k(r)))}catch(e){throw $r(),e}}self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=qr}function L(){var e=h.buffer;n.HEAP8=b=new Int8Array(e),O=new Int16Array(e),n.HEAPU8=w=new Uint8Array(e),new Uint16Array(e),n.HEAP32=_=new Int32Array(e),n.HEAPU32=y=new Uint32Array(e),T=new Float32Array(e),C=new Float64Array(e),A=new BigInt64Array(e),new BigUint64Array(e)}function G(){s?startWorker(n):Nr.$()}var H,Y=0,Q=null;function z(){if(0==--Y&&Q){var e=Q;Q=null,e()}}function V(e){throw k(e=\"Aborted(\"+e+\")\"),U=!0,e=new WebAssembly.RuntimeError(e+\". Build with -sASSERTIONS for more info.\"),t(e),e}function j(){return{a:{j:Wr,b:pe,E:we,f:Te,U:Ae,A:Ce,C:Ee,V:Re,S:Se,L:Me,R:ke,n:Ue,B:De,y:Fe,T:Be,z:xe,_:We,O:Ne,w:Le,F:He,t:Ye,i:Qe,N:Pe,X:ze,I:Ve,J:Ze,K:Je,G:Ke,H:er,u:nr,q:ir,Z:ur,o:cr,k:lr,Y:or,d:dr,W:mr,x:gr,c:tr,e:hr,h:vr,v:pr,s:_r,r:yr,P:Er,Q:Sr,D:ne,g:Mr,m:kr,M:Ur,l:Fr,a:h,p:re}}}class X{name=\"ExitStatus\";constructor(e){this.message=`Program terminated with exit(${e})`,this.status=e}}var q=e=>{e.terminate(),e.onmessage=()=>{}},Z=[],J=e=>{0==ae.length&&(le(),ce(ae[0]));var r=ae.pop();if(!r)return 6;ie.push(r),se[e.Qa]=r,r.Qa=e.Qa;var t={Ra:\"run\",bb:e.ab,Va:e.Va,Qa:e.Qa};return r.postMessage(t,e.Xa),0},K=0,ee=(e,r,...t)=>{for(var n=2*t.length,a=Xr(),i=jr(8*n),o=i>>>3,s=0;s<t.length;s++){var u=t[s];\"bigint\"==typeof u?(A[o+2*s]=1n,A[o+2*s+1]=u):(A[o+2*s]=0n,P()[o+2*s+1>>>0]=u)}return e=Lr(e,0,n,i,r),Vr(a),e};function re(e){if(s)return ee(0,1,e);if(p=e,!(0<K)){for(var r of ie)q(r);for(r of ae)q(r);ae=[],ie=[],se={},U=!0}l(0,new X(e))}function te(e){if(s)return ee(1,0,e);ne(e)}var ne=e=>{if(p=e,s)throw te(e),\"unwind\";re(e)},ae=[],ie=[],oe=[],se={},ue=e=>{var r=e.Qa;delete se[r],ae.push(e),ie.splice(ie.indexOf(e),1),e.Qa=0,Gr(r)};function fe(){oe.forEach((e=>e()))}var ce=e=>new Promise((r=>{e.onmessage=t=>{var a=(t=t.data).Ra;if(t.Ta&&t.Ta!=Ir()){var i=se[t.Ta];i?i.postMessage(t,t.Xa):k(`Internal error! Worker sent a message \"${a}\" to target pthread ${t.Ta}, but that thread no longer exists!`)}else\"checkMailbox\"===a?$e():\"spawnThread\"===a?J(t):\"cleanupThread\"===a?ue(se[t.cb]):\"loaded\"===a?(e.loaded=!0,r(e)):\"setimmediate\"===t.target?e.postMessage(t):\"callHandler\"===a?n[t.Ya](...t.args):a&&k(`worker sent an unknown command ${a}`)},e.onerror=e=>{throw k(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e};var t,a=[];for(t of[])n.propertyIsEnumerable(t)&&a.push(t);e.postMessage({Ra:\"load\",Za:a,fb:h,gb:v})}));function le(){var e=new Worker((()=>{const e=URL;return import.meta.url>\"file:\"&&import.meta.url<\"file;\"?new e(BUILD_DEFS.BUNDLE_FILENAME,import.meta.url):new URL(import.meta.url)})(),{type:\"module\",workerData:\"em-pthread\",name:\"em-pthread\"});ae.push(e)}var de,me=e=>{L();var r=N()[e+52>>>2>>>0];e=N()[e+56>>>2>>>0],zr(r,r-e),Vr(r)},ge=[],he=(e,r)=>{K=0;var t=ge[e];t||(ge[e]=t=de.get(e)),e=t(r),0<K?p=e:Hr(e)};class ve{constructor(e){this.Ua=e-24}}function pe(e,r,t){var n=new ve(e>>>=0);throw r>>>=0,t>>>=0,N()[n.Ua+16>>>2>>>0]=0,N()[n.Ua+4>>>2>>>0]=r,N()[n.Ua+8>>>2>>>0]=t,e}function be(e,r,t,n){return s?ee(2,1,e,r,t,n):we(e,r,t,n)}function we(e,r,t,n){if(e>>>=0,t>>>=0,n>>>=0,void 0===c)return 6;var a=[];return s&&0===a.length?be(e,r>>>=0,t,n):(e={ab:t,Qa:e,Va:n,Xa:a},s?(e.Ra=\"spawnThread\",postMessage(e,a),0):J(e))}var Oe=\"undefined\"!=typeof TextDecoder?new TextDecoder:void 0,_e=(e,r=0,t=NaN)=>{var n=(r>>>=0)+t;for(t=r;e[t]&&!(t>=n);)++t;if(16<t-r&&e.buffer&&Oe)return Oe.decode(e.buffer instanceof ArrayBuffer?e.subarray(r,t):e.slice(r,t));for(n=\"\";r<t;){var a=e[r++];if(128&a){var i=63&e[r++];if(192==(224&a))n+=String.fromCharCode((31&a)<<6|i);else{var o=63&e[r++];65536>(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&e[r++])?n+=String.fromCharCode(a):(a-=65536,n+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else n+=String.fromCharCode(a)}return n},ye=(e,r)=>(e>>>=0)?_e(B(),e,r):\"\";function Te(e,r,t){return s?ee(3,1,e,r,t):0}function Ae(e,r){if(s)return ee(4,1,e,r)}function Ce(e,r){if(s)return ee(5,1,e,r)}function Ee(e,r,t){if(s)return ee(6,1,e,r,t)}function Re(e,r,t){return s?ee(7,1,e,r,t):0}function Se(e,r){if(s)return ee(8,1,e,r)}function Me(e,r,t){if(s)return ee(9,1,e,r,t)}function ke(e,r,t,n){if(s)return ee(10,1,e,r,t,n)}function Ue(e,r,t,n){if(s)return ee(11,1,e,r,t,n)}function De(e,r,t,n){if(s)return ee(12,1,e,r,t,n)}function Fe(e){if(s)return ee(13,1,e)}function Be(e,r){if(s)return ee(14,1,e,r)}function xe(e,r,t){if(s)return ee(15,1,e,r,t)}var We=()=>V(\"\");function Ne(e){Pr(e>>>0,!o,1,!i,131072,!1),fe()}var Ie=e=>{if(!U)try{if(e(),!(0<K))try{s?Hr(p):ne(p)}catch(e){e instanceof X||\"unwind\"==e||l(0,e)}}catch(e){e instanceof X||\"unwind\"==e||l(0,e)}};function Pe(e){e>>>=0,\"function\"==typeof Atomics.eb&&(Atomics.eb(W(),e>>>2,e).value.then($e),e+=128,Atomics.store(W(),e>>>2,1))}var $e=()=>{var e=Ir();e&&(Pe(e),Ie(Qr))};function Le(e,r){(e>>>=0)==r>>>0?setTimeout($e):s?postMessage({Ta:e,Ra:\"checkMailbox\"}):(e=se[e])&&e.postMessage({Ra:\"checkMailbox\"})}var Ge=[];function He(e,r,t,n,a){for(r>>>=0,n/=2,Ge.length=n,t=a>>>0>>>3,a=0;a<n;a++)Ge[a]=A[t+2*a]?A[t+2*a+1]:P()[t+2*a+1>>>0];return(r?xr[r]:Br[e])(...Ge)}var Ye=()=>{K=0};function Qe(e){e>>>=0,s?postMessage({Ra:\"cleanupThread\",cb:e}):ue(se[e])}function ze(e){}function Ve(e,r){e=-9007199254740992>e||9007199254740992<e?NaN:Number(e),r>>>=0,e=new Date(1e3*e),W()[r>>>2>>>0]=e.getUTCSeconds(),W()[r+4>>>2>>>0]=e.getUTCMinutes(),W()[r+8>>>2>>>0]=e.getUTCHours(),W()[r+12>>>2>>>0]=e.getUTCDate(),W()[r+16>>>2>>>0]=e.getUTCMonth(),W()[r+20>>>2>>>0]=e.getUTCFullYear()-1900,W()[r+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,W()[r+28>>>2>>>0]=e}var je=e=>0==e%4&&(0!=e%100||0==e%400),Xe=[0,31,60,91,121,152,182,213,244,274,305,335],qe=[0,31,59,90,120,151,181,212,243,273,304,334];function Ze(e,r){e=-9007199254740992>e||9007199254740992<e?NaN:Number(e),r>>>=0,e=new Date(1e3*e),W()[r>>>2>>>0]=e.getSeconds(),W()[r+4>>>2>>>0]=e.getMinutes(),W()[r+8>>>2>>>0]=e.getHours(),W()[r+12>>>2>>>0]=e.getDate(),W()[r+16>>>2>>>0]=e.getMonth(),W()[r+20>>>2>>>0]=e.getFullYear()-1900,W()[r+24>>>2>>>0]=e.getDay();var t=(je(e.getFullYear())?Xe:qe)[e.getMonth()]+e.getDate()-1|0;W()[r+28>>>2>>>0]=t,W()[r+36>>>2>>>0]=-60*e.getTimezoneOffset(),t=new Date(e.getFullYear(),6,1).getTimezoneOffset();var n=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=0|(t!=n&&e.getTimezoneOffset()==Math.min(n,t)),W()[r+32>>>2>>>0]=e}function Je(e){e>>>=0;var r=new Date(W()[e+20>>>2>>>0]+1900,W()[e+16>>>2>>>0],W()[e+12>>>2>>>0],W()[e+8>>>2>>>0],W()[e+4>>>2>>>0],W()[e>>>2>>>0],0),t=W()[e+32>>>2>>>0],n=r.getTimezoneOffset(),a=new Date(r.getFullYear(),6,1).getTimezoneOffset(),i=new Date(r.getFullYear(),0,1).getTimezoneOffset(),o=Math.min(i,a);return 0>t?W()[e+32>>>2>>>0]=Number(a!=i&&o==n):0<t!=(o==n)&&(a=Math.max(i,a),r.setTime(r.getTime()+6e4*((0<t?o:a)-n))),W()[e+24>>>2>>>0]=r.getDay(),t=(je(r.getFullYear())?Xe:qe)[r.getMonth()]+r.getDate()-1|0,W()[e+28>>>2>>>0]=t,W()[e>>>2>>>0]=r.getSeconds(),W()[e+4>>>2>>>0]=r.getMinutes(),W()[e+8>>>2>>>0]=r.getHours(),W()[e+12>>>2>>>0]=r.getDate(),W()[e+16>>>2>>>0]=r.getMonth(),W()[e+20>>>2>>>0]=r.getYear(),e=r.getTime(),BigInt(isNaN(e)?-1:e/1e3)}function Ke(e,r,t,n,a,i,o){return s?ee(16,1,e,r,t,n,a,i,o):-52}function er(e,r,t,n,a,i){if(s)return ee(17,1,e,r,t,n,a,i)}var rr={},tr=()=>performance.timeOrigin+performance.now();function nr(e,r){if(s)return ee(18,1,e,r);if(rr[e]&&(clearTimeout(rr[e].id),delete rr[e]),!r)return 0;var t=setTimeout((()=>{delete rr[e],Ie((()=>Yr(e,performance.timeOrigin+performance.now())))}),r);return rr[e]={id:t,lb:r},0}var ar=(e,r,t)=>{var n=B();if(r>>>=0,0<t){var a=r;t=r+t-1;for(var i=0;i<e.length;++i){var o=e.charCodeAt(i);if(55296<=o&&57343>=o&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++i)),127>=o){if(r>=t)break;n[r++>>>0]=o}else{if(2047>=o){if(r+1>=t)break;n[r++>>>0]=192|o>>6}else{if(65535>=o){if(r+2>=t)break;n[r++>>>0]=224|o>>12}else{if(r+3>=t)break;n[r++>>>0]=240|o>>18,n[r++>>>0]=128|o>>12&63}n[r++>>>0]=128|o>>6&63}n[r++>>>0]=128|63&o}}n[r>>>0]=0,e=r-a}else e=0;return e};function ir(e,r,t,n){e>>>=0,r>>>=0,t>>>=0,n>>>=0;var a=(new Date).getFullYear(),i=new Date(a,0,1).getTimezoneOffset();a=new Date(a,6,1).getTimezoneOffset();var o=Math.max(i,a);N()[e>>>2>>>0]=60*o,W()[r>>>2>>>0]=Number(i!=a),e=(r=e=>{var r=Math.abs(e);return`UTC${0<=e?\"-\":\"+\"}${String(Math.floor(r/60)).padStart(2,\"0\")}${String(r%60).padStart(2,\"0\")}`})(i),r=r(a),a<i?(ar(e,t,17),ar(r,n,17)):(ar(e,n,17),ar(r,t,17))}var or=()=>Date.now(),sr=1;function ur(e,r,t){if(!(0<=e&&3>=e))return 28;if(0===e)e=Date.now();else{if(!sr)return 52;e=performance.timeOrigin+performance.now()}return A[t>>>0>>>3]=BigInt(Math.round(1e6*e)),0}var fr=[];function cr(e,r,t){e>>>=0,r>>>=0,t>>>=0,fr.length=0;for(var n;n=B()[r++>>>0];){var a=105!=n;t+=(a&=112!=n)&&t%8?4:0,fr.push(112==n?N()[t>>>2>>>0]:106==n?A[t>>>3]:105==n?W()[t>>>2>>>0]:P()[t>>>3>>>0]),t+=a?8:4}return xr[e](...fr)}var lr=()=>{};function dr(e,r){return k(ye(e>>>0,r>>>0))}var mr=()=>{throw K+=1,\"unwind\"};function gr(){return 4294901760}var hr=()=>navigator.hardwareConcurrency;function vr(){return V(\"Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER\"),0}function pr(e){e>>>=0;var r=B().length;if(e<=r||4294901760<e)return!1;for(var t=1;4>=t;t*=2){var n=r*(1+.2/t);n=Math.min(n,e+100663296);e:{n=(Math.min(4294901760,65536*Math.ceil(Math.max(e,n)/65536))-h.buffer.byteLength+65535)/65536|0;try{h.grow(n),L();var a=1;break e}catch(e){}a=void 0}if(a)return!0}return!1}var br=()=>(V(\"Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER\"),0),wr={},Or=e=>{e.forEach((e=>{var r=br();r&&(wr[r]=e)}))};function _r(){var e=Error().stack.toString().split(\"\\n\");return\"Error\"==e[0]&&e.shift(),Or(e),wr.Wa=br(),wr.$a=e,wr.Wa}function yr(e,r,t){if(e>>>=0,r>>>=0,wr.Wa==e)var n=wr.$a;else\"Error\"==(n=Error().stack.toString().split(\"\\n\"))[0]&&n.shift(),Or(n);for(var a=3;n[a]&&br()!=e;)++a;for(e=0;e<t&&n[e+a];++e)W()[r+4*e>>>2>>>0]=br();return e}var Tr,Ar={},Cr=()=>{if(!Tr){var e,r={USER:\"web_user\",LOGNAME:\"web_user\",PATH:\"/\",PWD:\"/\",HOME:\"/home/web_user\",LANG:(\"object\"==typeof navigator&&navigator.languages&&navigator.languages[0]||\"C\").replace(\"-\",\"_\")+\".UTF-8\",_:\"./this.program\"};for(e in Ar)void 0===Ar[e]?delete r[e]:r[e]=Ar[e];var t=[];for(e in r)t.push(`${e}=${r[e]}`);Tr=t}return Tr};function Er(e,r){if(s)return ee(19,1,e,r);e>>>=0,r>>>=0;var t,n=0,a=0;for(t of Cr()){var i=r+n;N()[e+a>>>2>>>0]=i,n+=ar(t,i,1/0)+1,a+=4}return 0}var Rr=e=>{for(var r=0,t=0;t<e.length;++t){var n=e.charCodeAt(t);127>=n?r++:2047>=n?r+=2:55296<=n&&57343>=n?(r+=4,++t):r+=3}return r};function Sr(e,r){if(s)return ee(20,1,e,r);e>>>=0,r>>>=0;var t=Cr();for(var n of(N()[e>>>2>>>0]=t.length,e=0,t))e+=Rr(n)+1;return N()[r>>>2>>>0]=e,0}function Mr(e){return s?ee(21,1,e):52}function kr(e,r,t,n){return s?ee(22,1,e,r,t,n):52}function Ur(e,r,t,n){return s?ee(23,1,e,r,t,n):70}var Dr=[null,[],[]];function Fr(e,r,t,n){if(s)return ee(24,1,e,r,t,n);r>>>=0,t>>>=0,n>>>=0;for(var a=0,i=0;i<t;i++){var o=N()[r>>>2>>>0],u=N()[r+4>>>2>>>0];r+=8;for(var f=0;f<u;f++){var c=e,l=B()[o+f>>>0],d=Dr[c];0===l||10===l?((1===c?M:k)(_e(d)),d.length=0):d.push(l)}a+=u}return N()[n>>>2>>>0]=a,0}s||function(){for(var e=n.numThreads-1;e--;)le();Z.push((()=>{Y++,function(e){s?e():Promise.all(ae.map(ce)).then(e)}((()=>z()))}))}(),s||(h=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),L()),n.wasmBinary&&(g=n.wasmBinary),n.stackSave=()=>Xr(),n.stackRestore=e=>Vr(e),n.stackAlloc=e=>jr(e),n.setValue=function(e,r,t=\"i8\"){switch(t.endsWith(\"*\")&&(t=\"*\"),t){case\"i1\":case\"i8\":F()[e>>>0]=r;break;case\"i16\":x()[e>>>1>>>0]=r;break;case\"i32\":W()[e>>>2>>>0]=r;break;case\"i64\":A[e>>>3]=BigInt(r);break;case\"float\":I()[e>>>2>>>0]=r;break;case\"double\":P()[e>>>3>>>0]=r;break;case\"*\":N()[e>>>2>>>0]=r;break;default:V(`invalid type for setValue: ${t}`)}},n.getValue=function(e,r=\"i8\"){switch(r.endsWith(\"*\")&&(r=\"*\"),r){case\"i1\":case\"i8\":return F()[e>>>0];case\"i16\":return x()[e>>>1>>>0];case\"i32\":return W()[e>>>2>>>0];case\"i64\":return A[e>>>3];case\"float\":return I()[e>>>2>>>0];case\"double\":return P()[e>>>3>>>0];case\"*\":return N()[e>>>2>>>0];default:V(`invalid type for getValue: ${r}`)}},n.UTF8ToString=ye,n.stringToUTF8=ar,n.lengthBytesUTF8=Rr;var Br=[re,te,be,Te,Ae,Ce,Ee,Re,Se,Me,ke,Ue,De,Fe,Be,xe,Ke,er,nr,Er,Sr,Mr,kr,Ur,Fr],xr={853836:(e,r,t,a,i)=>{if(void 0===n||!n.Sa)return 1;if((e=ye(Number(e>>>0))).startsWith(\"./\")&&(e=e.substring(2)),!(e=n.Sa.get(e)))return 2;if(r=Number(r>>>0),t=Number(t>>>0),a=Number(a>>>0),r+t>e.byteLength)return 3;try{const o=e.subarray(r,r+t);switch(i){case 0:B().set(o,a>>>0);break;case 1:n.hb?n.hb(a,o):n.jb(a,o);break;default:return 4}return 0}catch{return 4}},854660:()=>\"undefined\"!=typeof wasmOffsetConverter};function Wr(){return\"undefined\"!=typeof wasmOffsetConverter}var Nr=await async function(){function e(e,r){return Nr=e.exports,Nr=function(){var e=Nr,r=e=>()=>e()>>>0,t=e=>r=>e(r)>>>0;return(e=Object.assign({},e)).Aa=r(e.Aa),e.Ca=t(e.Ca),e.Oa=t(e.Oa),e.Pa=r(e.Pa),e.__cxa_get_exception_ptr=t(e.__cxa_get_exception_ptr),e}(),oe.push(Nr.Da),de=Nr.Ea,v=r,z(),Nr}Y++;var r=j();if(n.instantiateWasm)return new Promise((t=>{n.instantiateWasm(r,((r,n)=>{t(e(r,n))}))}));if(s)return new Promise((r=>{E=t=>{var n=new WebAssembly.Instance(t,j());r(e(n,t))}}));H??=n.locateFile?n.locateFile?n.locateFile(\"ort-wasm-simd-threaded.wasm\",m):m+\"ort-wasm-simd-threaded.wasm\":new URL(\"ort-wasm-simd-threaded.wasm\",import.meta.url).href;try{var a=await async function(e){var r=H;if(!g&&\"function\"==typeof WebAssembly.instantiateStreaming&&!D(r))try{var t=fetch(r,{credentials:\"same-origin\"});return await WebAssembly.instantiateStreaming(t,e)}catch(e){k(`wasm streaming compile failed: ${e}`),k(\"falling back to ArrayBuffer instantiation\")}return async function(e,r){try{var t=await async function(e){if(!g)try{var r=await u(e);return new Uint8Array(r)}catch{}if(e==H&&g)e=new Uint8Array(g);else{if(!f)throw\"both async and sync fetching of the wasm failed\";e=f(e)}return e}(e);return await WebAssembly.instantiate(t,r)}catch(e){k(`failed to asynchronously prepare wasm: ${e}`),V(e)}}(r,e)}(r);return e(a.instance,a.module)}catch(e){return t(e),Promise.reject(e)}}();n._OrtInit=(e,r)=>(n._OrtInit=Nr.aa)(e,r),n._OrtGetLastError=(e,r)=>(n._OrtGetLastError=Nr.ba)(e,r),n._OrtCreateSessionOptions=(e,r,t,a,i,o,s,u,f,c)=>(n._OrtCreateSessionOptions=Nr.ca)(e,r,t,a,i,o,s,u,f,c),n._OrtAppendExecutionProvider=(e,r,t,a,i)=>(n._OrtAppendExecutionProvider=Nr.da)(e,r,t,a,i),n._OrtAddFreeDimensionOverride=(e,r,t)=>(n._OrtAddFreeDimensionOverride=Nr.ea)(e,r,t),n._OrtAddSessionConfigEntry=(e,r,t)=>(n._OrtAddSessionConfigEntry=Nr.fa)(e,r,t),n._OrtReleaseSessionOptions=e=>(n._OrtReleaseSessionOptions=Nr.ga)(e),n._OrtCreateSession=(e,r,t)=>(n._OrtCreateSession=Nr.ha)(e,r,t),n._OrtReleaseSession=e=>(n._OrtReleaseSession=Nr.ia)(e),n._OrtGetInputOutputCount=(e,r,t)=>(n._OrtGetInputOutputCount=Nr.ja)(e,r,t),n._OrtGetInputOutputMetadata=(e,r,t,a)=>(n._OrtGetInputOutputMetadata=Nr.ka)(e,r,t,a),n._OrtFree=e=>(n._OrtFree=Nr.la)(e),n._OrtCreateTensor=(e,r,t,a,i,o)=>(n._OrtCreateTensor=Nr.ma)(e,r,t,a,i,o),n._OrtGetTensorData=(e,r,t,a,i)=>(n._OrtGetTensorData=Nr.na)(e,r,t,a,i),n._OrtReleaseTensor=e=>(n._OrtReleaseTensor=Nr.oa)(e),n._OrtCreateRunOptions=(e,r,t,a)=>(n._OrtCreateRunOptions=Nr.pa)(e,r,t,a),n._OrtAddRunConfigEntry=(e,r,t)=>(n._OrtAddRunConfigEntry=Nr.qa)(e,r,t),n._OrtReleaseRunOptions=e=>(n._OrtReleaseRunOptions=Nr.ra)(e),n._OrtCreateBinding=e=>(n._OrtCreateBinding=Nr.sa)(e),n._OrtBindInput=(e,r,t)=>(n._OrtBindInput=Nr.ta)(e,r,t),n._OrtBindOutput=(e,r,t,a)=>(n._OrtBindOutput=Nr.ua)(e,r,t,a),n._OrtClearBoundOutputs=e=>(n._OrtClearBoundOutputs=Nr.va)(e),n._OrtReleaseBinding=e=>(n._OrtReleaseBinding=Nr.wa)(e),n._OrtRunWithBinding=(e,r,t,a,i)=>(n._OrtRunWithBinding=Nr.xa)(e,r,t,a,i),n._OrtRun=(e,r,t,a,i,o,s,u)=>(n._OrtRun=Nr.ya)(e,r,t,a,i,o,s,u),n._OrtEndProfiling=e=>(n._OrtEndProfiling=Nr.za)(e);var Ir=()=>(Ir=Nr.Aa)();n._free=e=>(n._free=Nr.Ba)(e),n._malloc=e=>(n._malloc=Nr.Ca)(e);var Pr=(e,r,t,n,a,i)=>(Pr=Nr.Fa)(e,r,t,n,a,i),$r=()=>($r=Nr.Ga)(),Lr=(e,r,t,n,a)=>(Lr=Nr.Ha)(e,r,t,n,a),Gr=e=>(Gr=Nr.Ia)(e),Hr=e=>(Hr=Nr.Ja)(e),Yr=(e,r)=>(Yr=Nr.Ka)(e,r),Qr=()=>(Qr=Nr.La)(),zr=(e,r)=>(zr=Nr.Ma)(e,r),Vr=e=>(Vr=Nr.Na)(e),jr=e=>(jr=Nr.Oa)(e),Xr=()=>(Xr=Nr.Pa)();return function e(){if(0<Y)Q=e;else if(s)r(n),G();else{for(;0<Z.length;)Z.shift()(n);0<Y?Q=e:(n.calledRun=!0,U||(G(),r(n)))}}(),n.PTR_SIZE=4,a};export default e;var r=globalThis.self?.name?.startsWith(\"em-pthread\");r&&e();","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport type { OrtWasmModule } from './wasm-types';\nimport { isNode } from './wasm-utils-env';\n\n/**\n * The origin of the current location.\n *\n * In Node.js, this is undefined.\n */\nconst origin = isNode || typeof location === 'undefined' ? undefined : location.origin;\n\n/**\n * Some bundlers (eg. Webpack) will rewrite `import.meta.url` to a file URL at compile time.\n *\n * This function checks if `import.meta.url` starts with `file:`, but using the `>` and `<` operators instead of\n * `startsWith` function so that code minimizers can remove the dead code correctly.\n *\n * For example, if we use terser to minify the following code:\n * ```js\n * if (\"file://hard-coded-filename\".startsWith(\"file:\")) {\n *   console.log(1)\n * } else {\n *   console.log(2)\n * }\n *\n * if (\"file://hard-coded-filename\" > \"file:\" && \"file://hard-coded-filename\" < \"file;\") {\n *   console.log(3)\n * } else {\n *   console.log(4)\n * }\n * ```\n *\n * The minified code will be:\n * ```js\n * \"file://hard-coded-filename\".startsWith(\"file:\")?console.log(1):console.log(2),console.log(3);\n * ```\n *\n * (use Terser 5.39.0 with default options, https://try.terser.org/)\n *\n * @returns true if the import.meta.url is hardcoded as a file URI.\n */\nexport const isEsmImportMetaUrlHardcodedAsFileUri =\n  BUILD_DEFS.IS_ESM && BUILD_DEFS.ESM_IMPORT_META_URL! > 'file:' && BUILD_DEFS.ESM_IMPORT_META_URL! < 'file;';\n\nconst getScriptSrc = (): string | undefined => {\n  // if Nodejs, return undefined\n  if (isNode) {\n    return undefined;\n  }\n  // if It's ESM, use import.meta.url\n  if (BUILD_DEFS.IS_ESM) {\n    // For ESM, if the import.meta.url is a file URL, this usually means the bundler rewrites `import.meta.url` to\n    // the file path at compile time. In this case, this file path cannot be used to determine the runtime URL.\n    //\n    // We need to use the URL constructor like this:\n    // ```js\n    // new URL('actual-bundle-name.js', import.meta.url).href\n    // ```\n    // So that bundler can preprocess the URL correctly.\n    if (isEsmImportMetaUrlHardcodedAsFileUri) {\n      // if the rewritten URL is a relative path, we need to use the origin to resolve the URL.\n\n      // The following is a workaround for Vite.\n      //\n      // Vite uses a bundler(rollup/rolldown) that does not rewrite `import.meta.url` to a file URL. So in theory, this\n      // code path should not be executed in Vite. However, the bundler does not know it and it still try to load the\n      // following pattern:\n      // - `return new URL('filename', import.meta.url).href`\n      //\n      // By replacing the pattern above with the following code, we can skip the resource loading behavior:\n      // - `const URL2 = URL; return new URL2('filename', import.meta.url).href;`\n      //\n      // And it still works in Webpack.\n      const URL2 = URL;\n      return new URL(new URL2(BUILD_DEFS.BUNDLE_FILENAME, BUILD_DEFS.ESM_IMPORT_META_URL).href, origin).href;\n    }\n\n    return BUILD_DEFS.ESM_IMPORT_META_URL;\n  }\n\n  return typeof document !== 'undefined'\n    ? (document.currentScript as HTMLScriptElement)?.src\n    : // use `self.location.href` if available\n      typeof self !== 'undefined'\n      ? self.location?.href\n      : undefined;\n};\n\n/**\n * The classic script source URL. This is not always available in non ESModule environments.\n *\n * In Node.js, this is undefined.\n */\nexport const scriptSrc = getScriptSrc();\n\n/**\n * Infer the wasm path prefix from the script source URL.\n *\n * @returns The inferred wasm path prefix, or undefined if the script source URL is not available or is a blob URL.\n */\nexport const inferWasmPathPrefixFromScriptSrc = (): string | undefined => {\n  if (scriptSrc && !scriptSrc.startsWith('blob:')) {\n    return scriptSrc.substring(0, scriptSrc.lastIndexOf('/') + 1);\n  }\n  return undefined;\n};\n\n/**\n * Check if the given filename with prefix is from the same origin.\n */\nconst isSameOrigin = (filename: string, prefixOverride?: string) => {\n  try {\n    const baseUrl = prefixOverride ?? scriptSrc;\n    const url = baseUrl ? new URL(filename, baseUrl) : new URL(filename);\n    return url.origin === origin;\n  } catch {\n    return false;\n  }\n};\n\n/**\n * Normalize the inputs to an absolute URL with the given prefix override. If failed, return undefined.\n */\nconst normalizeUrl = (filename: string, prefixOverride?: string) => {\n  const baseUrl = prefixOverride ?? scriptSrc;\n  try {\n    const url = baseUrl ? new URL(filename, baseUrl) : new URL(filename);\n    return url.href;\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Create a fallback URL if an absolute URL cannot be created by the normalizeUrl function.\n */\nconst fallbackUrl = (filename: string, prefixOverride?: string) => `${prefixOverride ?? './'}${filename}`;\n\n/**\n * This helper function is used to preload a module from a URL.\n *\n * If the origin of the worker URL is different from the current origin, the worker cannot be loaded directly.\n * See discussions in https://github.com/webpack-contrib/worker-loader/issues/154\n *\n * In this case, we will fetch the worker URL and create a new Blob URL with the same origin as a workaround.\n *\n * @param absoluteUrl - The absolute URL to preload.\n *\n * @returns - A promise that resolves to a new Blob URL\n */\nconst preload = async (absoluteUrl: string): Promise<string> => {\n  const response = await fetch(absoluteUrl, { credentials: 'same-origin' });\n  const blob = await response.blob();\n  return URL.createObjectURL(blob);\n};\n\n/**\n * This helper function is used to dynamically import a module from a URL.\n *\n * The build script has special handling for this function to ensure that the URL is not bundled into the final output.\n *\n * @param url - The URL to import.\n *\n * @returns - A promise that resolves to the default export of the module.\n */\nconst dynamicImportDefault = async <T>(url: string): Promise<T> =>\n  (await import(/* webpackIgnore: true */ url)).default;\n\n/**\n * The proxy worker factory imported from the proxy worker module.\n *\n * This is only available when the WebAssembly proxy is not disabled.\n */\nconst createProxyWorker: ((urlOverride?: string) => Worker) | undefined =\n  // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n  BUILD_DEFS.DISABLE_WASM_PROXY ? undefined : require('./proxy-worker/main').default;\n\n/**\n * Import the proxy worker.\n *\n * This function will perform the following steps:\n * 1. If a preload is needed, it will preload the module and return the object URL.\n * 2. Use the proxy worker factory to create the proxy worker.\n *\n * @returns - A promise that resolves to a tuple of 2 elements:\n *            - The object URL of the preloaded module, or undefined if no preload is needed.\n *            - The proxy worker.\n */\nexport const importProxyWorker = async (): Promise<[undefined | string, Worker]> => {\n  if (!scriptSrc) {\n    throw new Error('Failed to load proxy worker: cannot determine the script source URL.');\n  }\n\n  // If the script source is from the same origin, we can use the embedded proxy module directly.\n  if (isSameOrigin(scriptSrc)) {\n    return [undefined, createProxyWorker!()];\n  }\n\n  // Otherwise, need to preload\n  const url = await preload(scriptSrc);\n  return [url, createProxyWorker!(url)];\n};\n\n/**\n * The embedded WebAssembly module.\n *\n * This is only available in ESM and when embedding is not disabled.\n */\nconst embeddedWasmModule: EmscriptenModuleFactory<OrtWasmModule> | undefined =\n  BUILD_DEFS.IS_ESM && BUILD_DEFS.ENABLE_BUNDLE_WASM_JS\n    ? // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n      require(\n        !BUILD_DEFS.DISABLE_JSEP\n          ? '../../dist/ort-wasm-simd-threaded.jsep.mjs'\n          : !BUILD_DEFS.DISABLE_WEBGPU\n            ? '../../dist/ort-wasm-simd-threaded.asyncify.mjs'\n            : '../../dist/ort-wasm-simd-threaded.mjs',\n      ).default\n    : undefined;\n\n/**\n * Import the WebAssembly module.\n *\n * This function will perform the following steps:\n * 1. If the embedded module exists and no custom URL is specified, use the embedded module.\n * 2. If a preload is needed, it will preload the module and return the object URL.\n * 3. Otherwise, it will perform a dynamic import of the module.\n *\n * @returns - A promise that resolves to a tuple of 2 elements:\n *            - The object URL of the preloaded module, or undefined if no preload is needed.\n *            - The default export of the module, which is a factory function to create the WebAssembly module.\n */\nexport const importWasmModule = async (\n  urlOverride: string | undefined,\n  prefixOverride: string | undefined,\n  isMultiThreaded: boolean,\n  isWasmOverridden: boolean,\n): Promise<[undefined | string, EmscriptenModuleFactory<OrtWasmModule>]> => {\n  //\n  // Check if we should use the embedded module.\n  //\n\n  // To use the embedded module, it should be available, and no URL override or prefix override should be specified.\n  let useEmbeddedModule = embeddedWasmModule && !(urlOverride || prefixOverride);\n  if (useEmbeddedModule) {\n    if (!scriptSrc) {\n      // no URL info available.\n      //\n      // Note: when the embedded module is available, it means the current script is ESM. Usually, in ESM, the\n      // `import.meta.url` is available. But in some cases (eg. Cloudflare Workers), the value of `import.meta.url`\n      // can be `null` or `undefined`. In this case, we can only load the embedded module when:\n      //\n      // 1. The WebAssembly module binary is overridden:\n      //    ```js\n      //    env.wasm.wasmPaths = undefined;  // or not specified\n      //    env.wasm.wasmBinary = /* a Uint8Array containing the WebAssembly binary */;\n      //    ```\n      //\n      // 2. The \".wasm\" only is overridden.\n      //    ```js\n      //    env.wasm.wasmPaths = { wasm: /* URL of the .wasm file */ };\n      //    ```\n      //\n      if (isWasmOverridden && !isMultiThreaded) {\n        useEmbeddedModule = true;\n      } else {\n        throw new Error('cannot determine the script source URL.');\n      }\n    } else {\n      // if the script source is available, we can check if it is from the same origin.\n      useEmbeddedModule = isSameOrigin(scriptSrc);\n    }\n  }\n  if (useEmbeddedModule) {\n    return [undefined, embeddedWasmModule!];\n  } else {\n    const wasmModuleFilename = !BUILD_DEFS.DISABLE_JSEP\n      ? 'ort-wasm-simd-threaded.jsep.mjs'\n      : !BUILD_DEFS.DISABLE_WEBGPU\n        ? 'ort-wasm-simd-threaded.asyncify.mjs'\n        : 'ort-wasm-simd-threaded.mjs';\n    const wasmModuleUrl = urlOverride ?? normalizeUrl(wasmModuleFilename, prefixOverride);\n    // need to preload if all of the following conditions are met:\n    // 1. not in Node.js.\n    //    - Node.js does not have the same origin policy for creating workers.\n    // 2. multi-threaded is enabled.\n    //    - If multi-threaded is disabled, no worker will be created. So we don't need to preload the module.\n    // 3. the absolute URL is available.\n    //    - If the absolute URL is failed to be created, the origin cannot be determined. In this case, we will not\n    //    preload the module.\n    // 4. the worker URL is not from the same origin.\n    //    - If the worker URL is from the same origin, we can create the worker directly.\n    const needPreload = !isNode && isMultiThreaded && wasmModuleUrl && !isSameOrigin(wasmModuleUrl, prefixOverride);\n    const url = needPreload\n      ? await preload(wasmModuleUrl)\n      : (wasmModuleUrl ?? fallbackUrl(wasmModuleFilename, prefixOverride));\n    return [needPreload ? url : undefined, await dynamicImportDefault<EmscriptenModuleFactory<OrtWasmModule>>(url)];\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Env } from 'onnxruntime-common';\n\nimport type { OrtWasmModule } from './wasm-types';\nimport { importWasmModule, inferWasmPathPrefixFromScriptSrc } from './wasm-utils-import';\n\nlet wasm: OrtWasmModule | undefined;\nlet initialized = false;\nlet initializing = false;\nlet aborted = false;\n\nconst isMultiThreadSupported = (): boolean => {\n  // If 'SharedArrayBuffer' is not available, WebAssembly threads will not work.\n  if (typeof SharedArrayBuffer === 'undefined') {\n    return false;\n  }\n\n  try {\n    // Test for transferability of SABs (for browsers. needed for Firefox)\n    // https://groups.google.com/forum/#!msg/mozilla.dev.platform/IHkBZlHETpA/dwsMNchWEQAJ\n    if (typeof MessageChannel !== 'undefined') {\n      new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));\n    }\n\n    // Test for WebAssembly threads capability (for both browsers and Node.js)\n    // This typed array is a WebAssembly program containing threaded instructions.\n    return WebAssembly.validate(\n      new Uint8Array([\n        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,\n        2, 0, 26, 11,\n      ]),\n    );\n  } catch (e) {\n    return false;\n  }\n};\n\nconst isSimdSupported = (): boolean => {\n  try {\n    // Test for WebAssembly SIMD capability (for both browsers and Node.js)\n    // This typed array is a WebAssembly program containing SIMD instructions.\n\n    // The binary data is generated from the following code by wat2wasm:\n    //\n    // (module\n    //   (type $t0 (func))\n    //   (func $f0 (type $t0)\n    //     (drop\n    //       (i32x4.dot_i16x8_s\n    //         (i8x16.splat\n    //           (i32.const 0))\n    //         (v128.const i32x4 0x00000000 0x00000000 0x00000000 0x00000000)))))\n\n    return WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0, 253, 15, 253, 12, 0, 0, 0,\n        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11,\n      ]),\n    );\n  } catch (e) {\n    return false;\n  }\n};\n\nconst isRelaxedSimdSupported = (): boolean => {\n  try {\n    // Test for WebAssembly Relaxed SIMD capability (for both browsers and Node.js)\n    // This typed array is a WebAssembly program containing Relaxed SIMD instructions.\n\n    // The binary data is generated from the following code by wat2wasm:\n    // (module\n    //   (func (result v128)\n    //      i32.const 1\n    //      i8x16.splat\n    //      i32.const 2\n    //      i8x16.splat\n    //      i32.const 3\n    //      i8x16.splat\n    //      i32x4.relaxed_dot_i8x16_i7x16_add_s\n    //   )\n    //  )\n    return WebAssembly.validate(\n      new Uint8Array([\n        0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 19, 1, 17, 0, 65, 1, 253, 15, 65, 2, 253,\n        15, 65, 3, 253, 15, 253, 147, 2, 11,\n      ]),\n    );\n  } catch (e) {\n    return false;\n  }\n};\n\nexport const initializeWebAssembly = async (flags: Env.WebAssemblyFlags): Promise<void> => {\n  if (initialized) {\n    return Promise.resolve();\n  }\n  if (initializing) {\n    throw new Error(\"multiple calls to 'initializeWebAssembly()' detected.\");\n  }\n  if (aborted) {\n    throw new Error(\"previous call to 'initializeWebAssembly()' failed.\");\n  }\n\n  initializing = true;\n\n  // wasm flags are already initialized\n  const timeout = flags.initTimeout!;\n  let numThreads = flags.numThreads!;\n\n  // ensure SIMD is supported\n  if (flags.simd === false) {\n    // skip SIMD feature checking as it is disabled explicitly by user\n  } else if (flags.simd === 'relaxed') {\n    // check if relaxed SIMD is supported\n    if (!isRelaxedSimdSupported()) {\n      throw new Error('Relaxed WebAssembly SIMD is not supported in the current environment.');\n    }\n  } else if (!isSimdSupported()) {\n    throw new Error('WebAssembly SIMD is not supported in the current environment.');\n  }\n\n  // check if multi-threading is supported\n  const multiThreadSupported = isMultiThreadSupported();\n  if (numThreads > 1 && !multiThreadSupported) {\n    if (typeof self !== 'undefined' && !self.crossOriginIsolated) {\n      // eslint-disable-next-line no-console\n      console.warn(\n        'env.wasm.numThreads is set to ' +\n          numThreads +\n          ', but this will not work unless you enable crossOriginIsolated mode. ' +\n          'See https://web.dev/cross-origin-isolation-guide/ for more info.',\n      );\n    }\n\n    // eslint-disable-next-line no-console\n    console.warn(\n      'WebAssembly multi-threading is not supported in the current environment. ' + 'Falling back to single-threading.',\n    );\n\n    // set flags.numThreads to 1 so that OrtInit() will not create a global thread pool.\n    flags.numThreads = numThreads = 1;\n  }\n\n  const wasmPaths = flags.wasmPaths;\n  const wasmPrefixOverride = typeof wasmPaths === 'string' ? wasmPaths : undefined;\n  const mjsPathOverrideFlag = (wasmPaths as Env.WasmFilePaths)?.mjs;\n  const mjsPathOverride = (mjsPathOverrideFlag as URL)?.href ?? mjsPathOverrideFlag;\n  const wasmPathOverrideFlag = (wasmPaths as Env.WasmFilePaths)?.wasm;\n  const wasmPathOverride = (wasmPathOverrideFlag as URL)?.href ?? wasmPathOverrideFlag;\n  const wasmBinaryOverride = flags.wasmBinary;\n\n  const [objectUrl, ortWasmFactory] = await importWasmModule(\n    mjsPathOverride,\n    wasmPrefixOverride,\n    numThreads > 1,\n    !!wasmBinaryOverride || !!wasmPathOverride,\n  );\n\n  let isTimeout = false;\n\n  const tasks: Array<Promise<void>> = [];\n\n  // promise for timeout\n  if (timeout > 0) {\n    tasks.push(\n      new Promise((resolve) => {\n        setTimeout(() => {\n          isTimeout = true;\n          resolve();\n        }, timeout);\n      }),\n    );\n  }\n\n  // promise for module initialization\n  tasks.push(\n    new Promise((resolve, reject) => {\n      const config: Partial<OrtWasmModule> = {\n        /**\n         * The number of threads. WebAssembly will create (Module.numThreads - 1) workers. If it is 1, no worker will be\n         * created.\n         */\n        numThreads,\n      };\n\n      if (wasmBinaryOverride) {\n        // Set a custom buffer which contains the WebAssembly binary. This will skip the wasm file fetching.\n        config.wasmBinary = wasmBinaryOverride;\n      } else if (wasmPathOverride || wasmPrefixOverride) {\n        // A callback function to locate the WebAssembly file. The function should return the full path of the file.\n        //\n        // Since Emscripten 3.1.58, this function is only called for the .wasm file.\n        config.locateFile = (fileName) => wasmPathOverride ?? wasmPrefixOverride + fileName;\n      } else if (mjsPathOverride && mjsPathOverride.indexOf('blob:') !== 0) {\n        // if mjs path is specified, use it as the base path for the .wasm file.\n        config.locateFile = (fileName) => new URL(fileName, mjsPathOverride).href;\n      } else if (objectUrl) {\n        const inferredWasmPathPrefix = inferWasmPathPrefixFromScriptSrc();\n        if (inferredWasmPathPrefix) {\n          // if the wasm module is preloaded, use the inferred wasm path as the base path for the .wasm file.\n          config.locateFile = (fileName) => inferredWasmPathPrefix + fileName;\n        }\n      }\n\n      ortWasmFactory(config).then(\n        // wasm module initialized successfully\n        (module) => {\n          initializing = false;\n          initialized = true;\n          wasm = module;\n          resolve();\n          if (objectUrl) {\n            URL.revokeObjectURL(objectUrl);\n          }\n        },\n        // wasm module failed to initialize\n        (what) => {\n          initializing = false;\n          aborted = true;\n          reject(what);\n        },\n      );\n    }),\n  );\n\n  await Promise.race(tasks);\n\n  if (isTimeout) {\n    throw new Error(`WebAssembly backend initializing failed due to timeout: ${timeout}ms`);\n  }\n};\n\nexport const getInstance = (): OrtWasmModule => {\n  if (initialized && wasm) {\n    return wasm;\n  }\n\n  throw new Error('WebAssembly is not initialized yet.');\n};\n\nexport const dispose = (): void => {\n  if (initialized && !initializing && !aborted) {\n    // TODO: currently \"PThread.terminateAllThreads()\" is not exposed in the wasm module.\n    //       And this function is not yet called by any code.\n    //       If it is needed in the future, we should expose it in the wasm module and uncomment the following line.\n\n    // wasm?.PThread?.terminateAllThreads();\n    wasm = undefined;\n\n    initializing = false;\n    initialized = false;\n    aborted = true;\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { getInstance } from './wasm-factory';\n\nexport const allocWasmString = (data: string, allocs: number[]): number => {\n  const wasm = getInstance();\n\n  const dataLength = wasm.lengthBytesUTF8(data) + 1;\n  const dataOffset = wasm._malloc(dataLength);\n  wasm.stringToUTF8(data, dataOffset, dataLength);\n  allocs.push(dataOffset);\n\n  return dataOffset;\n};\n\ninterface ExtraOptionsHandler {\n  (name: string, value: string): void;\n}\n\nexport const iterateExtraOptions = (\n  options: Record<string, unknown>,\n  prefix: string,\n  seen: WeakSet<Record<string, unknown>>,\n  handler: ExtraOptionsHandler,\n): void => {\n  if (typeof options == 'object' && options !== null) {\n    if (seen.has(options)) {\n      throw new Error('Circular reference in options');\n    } else {\n      seen.add(options);\n    }\n  }\n\n  Object.entries(options).forEach(([key, value]) => {\n    const name = prefix ? prefix + key : key;\n    if (typeof value === 'object') {\n      iterateExtraOptions(value as Record<string, unknown>, name + '.', seen, handler);\n    } else if (typeof value === 'string' || typeof value === 'number') {\n      handler(name, value.toString());\n    } else if (typeof value === 'boolean') {\n      handler(name, value ? '1' : '0');\n    } else {\n      throw new Error(`Can't handle extra config type: ${typeof value}`);\n    }\n  });\n};\n\n/**\n * check web assembly API's last error and throw error if any error occurred.\n * @param message a message used when an error occurred.\n */\nexport const checkLastError = (message: string): void => {\n  const wasm = getInstance();\n\n  const stack = wasm.stackSave();\n  try {\n    const ptrSize = wasm.PTR_SIZE;\n    const paramsOffset = wasm.stackAlloc(2 * ptrSize);\n    wasm._OrtGetLastError(paramsOffset, paramsOffset + ptrSize);\n    const errorCode = Number(wasm.getValue(paramsOffset, ptrSize === 4 ? 'i32' : 'i64'));\n    const errorMessagePointer = wasm.getValue(paramsOffset + ptrSize, '*');\n    const errorMessage = errorMessagePointer ? wasm.UTF8ToString(errorMessagePointer) : '';\n    throw new Error(`${message} ERROR_CODE: ${errorCode}, ERROR_MESSAGE: ${errorMessage}`);\n  } finally {\n    wasm.stackRestore(stack);\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { InferenceSession } from 'onnxruntime-common';\n\nimport { getInstance } from './wasm-factory';\nimport { allocWasmString, checkLastError, iterateExtraOptions } from './wasm-utils';\n\nexport const setRunOptions = (options: InferenceSession.RunOptions): [number, number[]] => {\n  const wasm = getInstance();\n  let runOptionsHandle = 0;\n  const allocs: number[] = [];\n\n  const runOptions: InferenceSession.RunOptions = options || {};\n\n  try {\n    if (options?.logSeverityLevel === undefined) {\n      runOptions.logSeverityLevel = 2; // Default to warning\n    } else if (\n      typeof options.logSeverityLevel !== 'number' ||\n      !Number.isInteger(options.logSeverityLevel) ||\n      options.logSeverityLevel < 0 ||\n      options.logSeverityLevel > 4\n    ) {\n      throw new Error(`log severity level is not valid: ${options.logSeverityLevel}`);\n    }\n\n    if (options?.logVerbosityLevel === undefined) {\n      runOptions.logVerbosityLevel = 0; // Default to 0\n    } else if (typeof options.logVerbosityLevel !== 'number' || !Number.isInteger(options.logVerbosityLevel)) {\n      throw new Error(`log verbosity level is not valid: ${options.logVerbosityLevel}`);\n    }\n\n    if (options?.terminate === undefined) {\n      runOptions.terminate = false;\n    }\n\n    let tagDataOffset = 0;\n    if (options?.tag !== undefined) {\n      tagDataOffset = allocWasmString(options.tag, allocs);\n    }\n\n    runOptionsHandle = wasm._OrtCreateRunOptions(\n      runOptions.logSeverityLevel!,\n      runOptions.logVerbosityLevel!,\n      !!runOptions.terminate!,\n      tagDataOffset,\n    );\n    if (runOptionsHandle === 0) {\n      checkLastError(\"Can't create run options.\");\n    }\n\n    if (options?.extra !== undefined) {\n      iterateExtraOptions(options.extra, '', new WeakSet<Record<string, unknown>>(), (key, value) => {\n        const keyDataOffset = allocWasmString(key, allocs);\n        const valueDataOffset = allocWasmString(value, allocs);\n\n        if (wasm._OrtAddRunConfigEntry(runOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n          checkLastError(`Can't set a run config entry: ${key} - ${value}.`);\n        }\n      });\n    }\n\n    return [runOptionsHandle, allocs];\n  } catch (e) {\n    if (runOptionsHandle !== 0) {\n      wasm._OrtReleaseRunOptions(runOptionsHandle);\n    }\n    allocs.forEach((alloc) => wasm._free(alloc));\n    throw e;\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport type { InferenceSession } from 'onnxruntime-common';\n\nimport { getInstance } from './wasm-factory';\nimport { allocWasmString, checkLastError, iterateExtraOptions } from './wasm-utils';\n\nconst getGraphOptimzationLevel = (graphOptimizationLevel: string | unknown): number => {\n  switch (graphOptimizationLevel) {\n    case 'disabled':\n      return 0;\n    case 'basic':\n      return 1;\n    case 'extended':\n      return 2;\n    case 'layout':\n      return 3;\n    case 'all':\n      return 99;\n    default:\n      throw new Error(`unsupported graph optimization level: ${graphOptimizationLevel}`);\n  }\n};\n\nconst getExecutionMode = (executionMode: 'sequential' | 'parallel'): number => {\n  switch (executionMode) {\n    case 'sequential':\n      return 0;\n    case 'parallel':\n      return 1;\n    default:\n      throw new Error(`unsupported execution mode: ${executionMode}`);\n  }\n};\n\nconst appendDefaultOptions = (options: InferenceSession.SessionOptions): void => {\n  if (!options.extra) {\n    options.extra = {};\n  }\n  if (!options.extra.session) {\n    options.extra.session = {};\n  }\n  const session = options.extra.session as Record<string, string>;\n  if (!session.use_ort_model_bytes_directly) {\n    // eslint-disable-next-line camelcase\n    session.use_ort_model_bytes_directly = '1';\n  }\n\n  // if using JSEP with WebGPU, always disable memory pattern\n  if (\n    options.executionProviders &&\n    options.executionProviders.some((ep) => (typeof ep === 'string' ? ep : ep.name) === 'webgpu')\n  ) {\n    options.enableMemPattern = false;\n  }\n};\n\nconst appendSessionConfig = (sessionOptionsHandle: number, key: string, value: string, allocs: number[]): void => {\n  const keyDataOffset = allocWasmString(key, allocs);\n  const valueDataOffset = allocWasmString(value, allocs);\n  if (getInstance()._OrtAddSessionConfigEntry(sessionOptionsHandle, keyDataOffset, valueDataOffset) !== 0) {\n    checkLastError(`Can't set a session config entry: ${key} - ${value}.`);\n  }\n};\n\nconst appendEpOption = (epOptions: Array<[number, number]>, key: string, value: string, allocs: number[]): void => {\n  const keyDataOffset = allocWasmString(key, allocs);\n  const valueDataOffset = allocWasmString(value, allocs);\n  epOptions.push([keyDataOffset, valueDataOffset]);\n};\n\nconst setExecutionProviders = async (\n  sessionOptionsHandle: number,\n  executionProviders: readonly InferenceSession.ExecutionProviderConfig[],\n  allocs: number[],\n): Promise<void> => {\n  for (const ep of executionProviders) {\n    let epName = typeof ep === 'string' ? ep : ep.name;\n    const epOptions: Array<[number, number]> = [];\n\n    // check EP name\n    switch (epName) {\n      case 'webnn':\n        epName = 'WEBNN';\n        if (typeof ep !== 'string') {\n          const webnnOptions = ep as InferenceSession.WebNNExecutionProviderOption;\n          // const context = (webnnOptions as InferenceSession.WebNNOptionsWithMLContext)?.context;\n          const deviceType = (webnnOptions as InferenceSession.WebNNContextOptions)?.deviceType;\n          if (deviceType) {\n            appendSessionConfig(sessionOptionsHandle, 'deviceType', deviceType, allocs);\n          }\n        }\n        break;\n      case 'webgpu':\n        if (!BUILD_DEFS.DISABLE_WEBGPU) {\n          epName = 'WebGPU';\n          let customDevice: GPUDevice | undefined;\n\n          if (typeof ep !== 'string') {\n            const customOptions = ep as unknown as { device: GPUDevice };\n            if (customOptions.device) {\n              if (typeof GPUDevice !== 'undefined' && customOptions.device instanceof GPUDevice) {\n                customDevice = customOptions.device;\n              } else {\n                throw new Error('Invalid GPU device set in WebGPU EP options.');\n              }\n            }\n\n            // TODO: handle more options\n          }\n\n          const info = getInstance().webgpuRegisterDevice!(customDevice);\n          if (info) {\n            const [deviceId, instanceHandle, deviceHandle] = info;\n            appendEpOption(epOptions, 'deviceId', deviceId.toString(), allocs);\n            appendEpOption(epOptions, 'webgpuInstance', instanceHandle.toString(), allocs);\n            appendEpOption(epOptions, 'webgpuDevice', deviceHandle.toString(), allocs);\n          }\n        } else {\n          epName = 'JS';\n          if (typeof ep !== 'string') {\n            const webgpuOptions = ep as InferenceSession.WebGpuExecutionProviderOption;\n            if (webgpuOptions?.preferredLayout) {\n              if (webgpuOptions.preferredLayout !== 'NCHW' && webgpuOptions.preferredLayout !== 'NHWC') {\n                throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${webgpuOptions.preferredLayout}`);\n              }\n              appendSessionConfig(sessionOptionsHandle, 'preferredLayout', webgpuOptions.preferredLayout, allocs);\n            }\n          }\n        }\n        break;\n      case 'wasm':\n      case 'cpu':\n        continue;\n      default:\n        throw new Error(`not supported execution provider: ${epName}`);\n    }\n\n    const epNameDataOffset = allocWasmString(epName, allocs);\n    const epOptionsCount = epOptions.length;\n    let keysOffset = 0;\n    let valuesOffset = 0;\n    if (epOptionsCount > 0) {\n      keysOffset = getInstance()._malloc(epOptionsCount * getInstance().PTR_SIZE);\n      allocs.push(keysOffset);\n      valuesOffset = getInstance()._malloc(epOptionsCount * getInstance().PTR_SIZE);\n      allocs.push(valuesOffset);\n      for (let i = 0; i < epOptionsCount; i++) {\n        getInstance().setValue(keysOffset + i * getInstance().PTR_SIZE, epOptions[i][0], '*');\n        getInstance().setValue(valuesOffset + i * getInstance().PTR_SIZE, epOptions[i][1], '*');\n      }\n    }\n    if (\n      (await getInstance()._OrtAppendExecutionProvider(\n        sessionOptionsHandle,\n        epNameDataOffset,\n        keysOffset,\n        valuesOffset,\n        epOptionsCount,\n      )) !== 0\n    ) {\n      checkLastError(`Can't append execution provider: ${epName}.`);\n    }\n  }\n};\n\nexport const setSessionOptions = async (options?: InferenceSession.SessionOptions): Promise<[number, number[]]> => {\n  const wasm = getInstance();\n  let sessionOptionsHandle = 0;\n  const allocs: number[] = [];\n\n  const sessionOptions: InferenceSession.SessionOptions = options || {};\n  appendDefaultOptions(sessionOptions);\n\n  try {\n    const graphOptimizationLevel = getGraphOptimzationLevel(sessionOptions.graphOptimizationLevel ?? 'all');\n    const executionMode = getExecutionMode(sessionOptions.executionMode ?? 'sequential');\n    const logIdDataOffset =\n      typeof sessionOptions.logId === 'string' ? allocWasmString(sessionOptions.logId, allocs) : 0;\n\n    const logSeverityLevel = sessionOptions.logSeverityLevel ?? 2; // Default to 2 - warning\n    if (!Number.isInteger(logSeverityLevel) || logSeverityLevel < 0 || logSeverityLevel > 4) {\n      throw new Error(`log severity level is not valid: ${logSeverityLevel}`);\n    }\n\n    const logVerbosityLevel = sessionOptions.logVerbosityLevel ?? 0; // Default to 0 - verbose\n    if (!Number.isInteger(logVerbosityLevel) || logVerbosityLevel < 0 || logVerbosityLevel > 4) {\n      throw new Error(`log verbosity level is not valid: ${logVerbosityLevel}`);\n    }\n\n    const optimizedModelFilePathOffset =\n      typeof sessionOptions.optimizedModelFilePath === 'string'\n        ? allocWasmString(sessionOptions.optimizedModelFilePath, allocs)\n        : 0;\n\n    sessionOptionsHandle = wasm._OrtCreateSessionOptions(\n      graphOptimizationLevel,\n      !!sessionOptions.enableCpuMemArena,\n      !!sessionOptions.enableMemPattern,\n      executionMode,\n      !!sessionOptions.enableProfiling,\n      0,\n      logIdDataOffset,\n      logSeverityLevel,\n      logVerbosityLevel,\n      optimizedModelFilePathOffset,\n    );\n    if (sessionOptionsHandle === 0) {\n      checkLastError(\"Can't create session options.\");\n    }\n\n    if (sessionOptions.executionProviders) {\n      await setExecutionProviders(sessionOptionsHandle, sessionOptions.executionProviders, allocs);\n    }\n\n    if (sessionOptions.enableGraphCapture !== undefined) {\n      if (typeof sessionOptions.enableGraphCapture !== 'boolean') {\n        throw new Error(`enableGraphCapture must be a boolean value: ${sessionOptions.enableGraphCapture}`);\n      }\n      appendSessionConfig(\n        sessionOptionsHandle,\n        'enableGraphCapture',\n        sessionOptions.enableGraphCapture.toString(),\n        allocs,\n      );\n    }\n\n    if (sessionOptions.freeDimensionOverrides) {\n      for (const [name, value] of Object.entries(sessionOptions.freeDimensionOverrides)) {\n        if (typeof name !== 'string') {\n          throw new Error(`free dimension override name must be a string: ${name}`);\n        }\n        if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n          throw new Error(`free dimension override value must be a non-negative integer: ${value}`);\n        }\n        const nameOffset = allocWasmString(name, allocs);\n        if (wasm._OrtAddFreeDimensionOverride(sessionOptionsHandle, nameOffset, value) !== 0) {\n          checkLastError(`Can't set a free dimension override: ${name} - ${value}.`);\n        }\n      }\n    }\n\n    if (sessionOptions.extra !== undefined) {\n      iterateExtraOptions(sessionOptions.extra, '', new WeakSet<Record<string, unknown>>(), (key, value) => {\n        appendSessionConfig(sessionOptionsHandle, key, value, allocs);\n      });\n    }\n\n    return [sessionOptionsHandle, allocs];\n  } catch (e) {\n    if (sessionOptionsHandle !== 0) {\n      if (wasm._OrtReleaseSessionOptions(sessionOptionsHandle) !== 0) {\n        checkLastError(\"Can't release session options.\");\n      }\n    }\n    allocs.forEach((alloc) => wasm._free(alloc));\n    throw e;\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Tensor } from 'onnxruntime-common';\n\n// a dummy type declaration for Float16Array in case any polyfill is available.\ndeclare global {\n  // eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any\n  const Float16Array: any;\n}\n\n// This file includes common definitions. They do NOT have dependency on the WebAssembly instance.\n\n/**\n * Copied from ONNX definition. Use this to drop dependency 'onnx_proto' to decrease compiled .js file size.\n */\nexport const enum DataType {\n  undefined = 0,\n  float = 1,\n  uint8 = 2,\n  int8 = 3,\n  uint16 = 4,\n  int16 = 5,\n  int32 = 6,\n  int64 = 7,\n  string = 8,\n  bool = 9,\n  float16 = 10,\n  double = 11,\n  uint32 = 12,\n  uint64 = 13,\n  complex64 = 14,\n  complex128 = 15,\n  bfloat16 = 16,\n\n  // 4-bit data-types\n  uint4 = 21,\n  int4 = 22,\n}\n\n/**\n * Map string tensor data to enum value\n */\nexport const tensorDataTypeStringToEnum = (type: string): DataType => {\n  switch (type) {\n    case 'int8':\n      return DataType.int8;\n    case 'uint8':\n      return DataType.uint8;\n    case 'bool':\n      return DataType.bool;\n    case 'int16':\n      return DataType.int16;\n    case 'uint16':\n      return DataType.uint16;\n    case 'int32':\n      return DataType.int32;\n    case 'uint32':\n      return DataType.uint32;\n    case 'float16':\n      return DataType.float16;\n    case 'float32':\n      return DataType.float;\n    case 'float64':\n      return DataType.double;\n    case 'string':\n      return DataType.string;\n    case 'int64':\n      return DataType.int64;\n    case 'uint64':\n      return DataType.uint64;\n    case 'int4':\n      return DataType.int4;\n    case 'uint4':\n      return DataType.uint4;\n\n    default:\n      throw new Error(`unsupported data type: ${type}`);\n  }\n};\n\n/**\n * Map enum value to string tensor data\n */\nexport const tensorDataTypeEnumToString = (typeProto: DataType): Tensor.Type => {\n  switch (typeProto) {\n    case DataType.int8:\n      return 'int8';\n    case DataType.uint8:\n      return 'uint8';\n    case DataType.bool:\n      return 'bool';\n    case DataType.int16:\n      return 'int16';\n    case DataType.uint16:\n      return 'uint16';\n    case DataType.int32:\n      return 'int32';\n    case DataType.uint32:\n      return 'uint32';\n    case DataType.float16:\n      return 'float16';\n    case DataType.float:\n      return 'float32';\n    case DataType.double:\n      return 'float64';\n    case DataType.string:\n      return 'string';\n    case DataType.int64:\n      return 'int64';\n    case DataType.uint64:\n      return 'uint64';\n    case DataType.int4:\n      return 'int4';\n    case DataType.uint4:\n      return 'uint4';\n\n    default:\n      throw new Error(`unsupported data type: ${typeProto}`);\n  }\n};\n\n/**\n * get tensor size in bytes by the given data type and dimensions\n * @returns size in integer or undefined if the data type is not supported\n */\nexport const calculateTensorSizeInBytes = (\n  dateType: number,\n  dimsOrSize: readonly number[] | number,\n): number | undefined => {\n  const elementSize = [\n    -1, // undefined = 0\n    4, // float = 1\n    1, // uint8 = 2\n    1, // int8 = 3\n    2, // uint16 = 4\n    2, // int16 = 5\n    4, // int32 = 6\n    8, // int64 = 7\n    -1, // string = 8\n    1, // bool = 9\n    2, // float16 = 10\n    8, // double = 11\n    4, // uint32 = 12\n    8, // uint64 = 13\n    -1, // complex64 = 14\n    -1, // complex128 = 15\n    -1, // bfloat16 = 16\n    -1, // FLOAT8E4M3FN = 17\n    -1, // FLOAT8E4M3FNUZ = 18\n    -1, // FLOAT8E5M2 = 19\n    -1, // FLOAT8E5M2FNUZ = 20\n    0.5, // uint4 = 21\n    0.5, // int4 = 22\n  ][dateType];\n\n  const size = typeof dimsOrSize === 'number' ? dimsOrSize : dimsOrSize.reduce((a, b) => a * b, 1);\n  return elementSize > 0 ? Math.ceil(size * elementSize) : undefined;\n};\n\n/**\n * get typed array constructor by the given tensor type\n */\nexport const tensorTypeToTypedArrayConstructor = (\n  type: Tensor.Type,\n):\n  | Float32ArrayConstructor\n  | Uint8ArrayConstructor\n  | Int8ArrayConstructor\n  | Uint16ArrayConstructor\n  | Int16ArrayConstructor\n  | Int32ArrayConstructor\n  | BigInt64ArrayConstructor\n  | Uint8ArrayConstructor\n  | Float64ArrayConstructor\n  | Uint32ArrayConstructor\n  | BigUint64ArrayConstructor => {\n  switch (type) {\n    case 'float16':\n      // allow Float16Array polyfill.\n      return typeof Float16Array !== 'undefined' && Float16Array.from ? Float16Array : Uint16Array;\n    case 'float32':\n      return Float32Array;\n    case 'uint8':\n      return Uint8Array;\n    case 'int8':\n      return Int8Array;\n    case 'uint16':\n      return Uint16Array;\n    case 'int16':\n      return Int16Array;\n    case 'int32':\n      return Int32Array;\n    case 'bool':\n      return Uint8Array;\n    case 'float64':\n      return Float64Array;\n    case 'uint32':\n      return Uint32Array;\n    case 'int64':\n      return BigInt64Array;\n    case 'uint64':\n      return BigUint64Array;\n    default:\n      throw new Error(`unsupported type: ${type}`);\n  }\n};\n\n/**\n * Map string log level to integer value\n */\nexport const logLevelStringToEnum = (logLevel?: 'verbose' | 'info' | 'warning' | 'error' | 'fatal'): number => {\n  switch (logLevel) {\n    case 'verbose':\n      return 0;\n    case 'info':\n      return 1;\n    case 'warning':\n      return 2;\n    case 'error':\n      return 3;\n    case 'fatal':\n      return 4;\n    default:\n      throw new Error(`unsupported logging level: ${logLevel}`);\n  }\n};\n\n/**\n * Check whether the given tensor type is supported by GPU buffer\n */\nexport const isGpuBufferSupportedType = (type: Tensor.Type): type is Tensor.GpuBufferDataTypes =>\n  type === 'float32' ||\n  type === 'float16' ||\n  type === 'int32' ||\n  type === 'int64' ||\n  type === 'uint32' ||\n  type === 'uint8' ||\n  type === 'bool' ||\n  type === 'uint4' ||\n  type === 'int4';\n\n/**\n * Check whether the given tensor type is supported by WebNN MLTensor\n */\nexport const isMLTensorSupportedType = (type: Tensor.Type): type is Tensor.MLTensorDataTypes =>\n  type === 'float32' ||\n  type === 'float16' ||\n  type === 'int32' ||\n  type === 'int64' ||\n  type === 'uint32' ||\n  type === 'uint64' ||\n  type === 'int8' ||\n  type === 'uint8' ||\n  type === 'bool' ||\n  type === 'uint4' ||\n  type === 'int4';\n\n/**\n * Map string data location to integer value\n */\nexport const dataLocationStringToEnum = (location: Tensor.DataLocation): number => {\n  switch (location) {\n    case 'none':\n      return 0;\n    case 'cpu':\n      return 1;\n    case 'cpu-pinned':\n      return 2;\n    case 'texture':\n      return 3;\n    case 'gpu-buffer':\n      return 4;\n    case 'ml-tensor':\n      return 5;\n    default:\n      throw new Error(`unsupported data location: ${location}`);\n  }\n};\n\n/**\n * Map integer data location to string value\n */\nexport const dataLocationEnumToString = (location: number): Tensor.DataLocation | undefined =>\n  (['none', 'cpu', 'cpu-pinned', 'texture', 'gpu-buffer', 'ml-tensor'] as const)[location];\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { isNode } from './wasm-utils-env';\n\n/**\n * Load a file into a Uint8Array.\n *\n * @param file - the file to load. Can be a URL/path, a Blob, an ArrayBuffer, or a Uint8Array.\n * @returns a Uint8Array containing the file data.\n */\nexport const loadFile = async (file: string | Blob | ArrayBufferLike | Uint8Array): Promise<Uint8Array> => {\n  if (typeof file === 'string') {\n    if (isNode) {\n      // load file into ArrayBuffer in Node.js\n      try {\n        const { readFile } = require('node:fs/promises');\n        return new Uint8Array(await readFile(file));\n      } catch (e) {\n        if (e.code === 'ERR_FS_FILE_TOO_LARGE') {\n          // file is too large, use fs.createReadStream instead\n          const { createReadStream } = require('node:fs');\n          const stream = createReadStream(file);\n          const chunks: Uint8Array[] = [];\n          for await (const chunk of stream) {\n            chunks.push(chunk);\n          }\n          return new Uint8Array(Buffer.concat(chunks));\n        }\n        throw e;\n      }\n    } else {\n      // load file into ArrayBuffer in browsers\n      const response = await fetch(file);\n      if (!response.ok) {\n        throw new Error(`failed to load external data file: ${file}`);\n      }\n      const contentLengthHeader = response.headers.get('Content-Length');\n      const fileSize = contentLengthHeader ? parseInt(contentLengthHeader, 10) : 0;\n      if (fileSize < 1073741824 /* 1GB */) {\n        // when Content-Length header is not set, we cannot determine the file size. We assume it is small enough to\n        // load into memory.\n        return new Uint8Array(await response.arrayBuffer());\n      } else {\n        // file is too large, use stream instead\n        if (!response.body) {\n          throw new Error(`failed to load external data file: ${file}, no response body.`);\n        }\n        const reader = response.body.getReader();\n\n        let buffer;\n        try {\n          // try to create ArrayBuffer directly\n          buffer = new ArrayBuffer(fileSize);\n        } catch (e) {\n          if (e instanceof RangeError) {\n            // use WebAssembly Memory to allocate larger ArrayBuffer\n            const pages = Math.ceil(fileSize / 65536);\n            buffer = new WebAssembly.Memory({ initial: pages, maximum: pages }).buffer;\n          } else {\n            throw e;\n          }\n        }\n\n        let offset = 0;\n        // eslint-disable-next-line no-constant-condition\n        while (true) {\n          const { done, value } = await reader.read();\n          if (done) {\n            break;\n          }\n          const chunkSize = value.byteLength;\n          const chunk = new Uint8Array(buffer, offset, chunkSize);\n          chunk.set(value);\n          offset += chunkSize;\n        }\n        return new Uint8Array(buffer, 0, fileSize);\n      }\n    }\n  } else if (file instanceof Blob) {\n    return new Uint8Array(await file.arrayBuffer());\n  } else if (file instanceof Uint8Array) {\n    return file;\n  } else {\n    return new Uint8Array(file);\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n// WebNN API currently does not have a TypeScript definition file. This file is a workaround with types generated from\n// WebNN API specification.\n// https://github.com/webmachinelearning/webnn/issues/677\n/// <reference path=\"jsep/webnn/webnn.d.ts\" />\n\nimport { Env, InferenceSession, Tensor, TRACE_EVENT_BEGIN, TRACE_EVENT_END } from 'onnxruntime-common';\n\nimport {\n  SerializableInternalBuffer,\n  SerializableSessionMetadata,\n  SerializableTensorMetadata,\n  TensorMetadata,\n} from './proxy-messages';\nimport { setRunOptions } from './run-options';\nimport { setSessionOptions } from './session-options';\nimport {\n  calculateTensorSizeInBytes,\n  dataLocationStringToEnum,\n  isGpuBufferSupportedType,\n  isMLTensorSupportedType,\n  logLevelStringToEnum,\n  tensorDataTypeEnumToString,\n  tensorDataTypeStringToEnum,\n  tensorTypeToTypedArrayConstructor,\n} from './wasm-common';\nimport { getInstance } from './wasm-factory';\nimport { allocWasmString, checkLastError } from './wasm-utils';\nimport { loadFile } from './wasm-utils-load-file';\n\n// #region Initializations\n\n/**\n * There are 4 different \"initialization\" steps for ORT. They happen in different places and different time.\n *\n * 1. JavaScript initialization for onnxruntime-common and onnxruntime-web.\n *    This is the first initialization step. In this step, onnxruntime-web calls onnxruntime-common's registerBackend()\n * function multiple times to register all the available backends. The backend registration is very fast. It only\n * registers the backend name with the uninitialized backend object. No heavy initialization is done in this step.\n *    Refer to web/lib/index.ts for the backend registration.\n *\n * 2. WebAssembly artifact initialization.\n *    This happens when any registered wasm backend is used for the first time (ie. `ort.InferenceSession.create()` is\n * called). In this step, onnxruntime-web does the followings:\n *     - create a proxy worker and make sure the proxy worker is ready to receive messages, if proxy is enabled.\n *     - perform feature detection, locate correct WebAssembly artifact path and call the Emscripten generated\n * JavaScript code to initialize the WebAssembly runtime.\n *         - if proxy is enabled, this step happens in the proxy worker using message 'init-wasm'.\n *         - downloading the 'ort-wasm{...}.wasm' file is done in this step.\n *         - if multi-thread is enabled, one or more webworker will be created to initialize the PThread threadpool.\n *\n * 3. ORT environment initialization.\n *    This happens after step 2. In this step, onnxruntime-web performs ONNX Runtime environment initialization.\n * Function `_OrtInit()` is called in this step.\n *     - if proxy is enabled, this step happens in the proxy worker using message 'init-ort'.\n *     - logging level (ort.env.logLevel) and thread number (ort.env.wasm.numThreads) are set in this step.\n *\n * 4. Session initialization.\n *    This happens when `ort.InferenceSession.create()` is called. Unlike the first 3 steps (they only called once),\n * this step will be done for each session. In this step, onnxruntime-web does the followings:\n *    If the parameter is a URL:\n *    - download the model data from the URL.\n *    - copy the model data to the WASM heap. (proxy: 'copy-from')\n *    - dereference the model buffer. This step allows the original ArrayBuffer to be garbage collected.\n *    - call `_OrtCreateSession()` to create the session. (proxy: 'create')\n *\n *    If the parameter is a Uint8Array object:\n *    - copy the model data to the WASM heap. (proxy: 'copy-from')\n *    - call `_OrtCreateSession()` to create the session. (proxy: 'create')\n *\n *\n */\n\n/**\n * initialize ORT environment.\n *\n * @param numThreads SetGlobalIntraOpNumThreads(numThreads)\n * @param loggingLevel CreateEnv(static_cast<OrtLoggingLevel>(logging_level))\n */\nconst initOrt = (numThreads: number, loggingLevel: number): void => {\n  const errorCode = getInstance()._OrtInit(numThreads, loggingLevel);\n  if (errorCode !== 0) {\n    checkLastError(\"Can't initialize onnxruntime.\");\n  }\n};\n\n/**\n * initialize runtime environment.\n * @param env passed in the environment config object.\n */\nexport const initRuntime = async (env: Env): Promise<void> => {\n  // init ORT\n  initOrt(env.wasm.numThreads!, logLevelStringToEnum(env.logLevel));\n};\n\n/**\n * perform EP specific initialization.\n *\n * @param env\n * @param epName\n */\nexport const initEp = async (env: Env, epName: string): Promise<void> => {\n  // initialize ASYNCIFY support\n  getInstance().asyncInit?.();\n\n  // perform WebGPU availability check ( either JSEP or WebGPU EP )\n  let webgpuAdapter = env.webgpu.adapter as GPUAdapter | null;\n  if (epName === 'webgpu') {\n    if (typeof navigator === 'undefined' || !navigator.gpu) {\n      throw new Error('WebGPU is not supported in current environment');\n    }\n    if (!webgpuAdapter) {\n      // if adapter is not set, request a new adapter.\n      const powerPreference = env.webgpu.powerPreference;\n      if (powerPreference !== undefined && powerPreference !== 'low-power' && powerPreference !== 'high-performance') {\n        throw new Error(`Invalid powerPreference setting: \"${powerPreference}\"`);\n      }\n      const forceFallbackAdapter = env.webgpu.forceFallbackAdapter;\n      if (forceFallbackAdapter !== undefined && typeof forceFallbackAdapter !== 'boolean') {\n        throw new Error(`Invalid forceFallbackAdapter setting: \"${forceFallbackAdapter}\"`);\n      }\n      webgpuAdapter = await navigator.gpu.requestAdapter({ powerPreference, forceFallbackAdapter });\n      if (!webgpuAdapter) {\n        throw new Error(\n          'Failed to get GPU adapter. ' +\n            'You may need to enable flag \"--enable-unsafe-webgpu\" if you are using Chrome.',\n        );\n      }\n    } else {\n      // if adapter is set, validate it.\n      if (\n        typeof webgpuAdapter.limits !== 'object' ||\n        typeof webgpuAdapter.features !== 'object' ||\n        typeof webgpuAdapter.requestDevice !== 'function'\n      ) {\n        throw new Error('Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.');\n      }\n    }\n  }\n\n  // perform WebNN availability check ( either JSEP or WebNN EP )\n  if (epName === 'webnn') {\n    if (typeof navigator === 'undefined' || !(navigator as unknown as { ml: unknown }).ml) {\n      throw new Error('WebNN is not supported in current environment');\n    }\n  }\n\n  if (!BUILD_DEFS.DISABLE_JSEP) {\n    // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n    const initJsep = require('./jsep/init').init;\n\n    if (epName === 'webgpu') {\n      await initJsep('webgpu', getInstance(), env, webgpuAdapter);\n    }\n    if (epName === 'webnn') {\n      await initJsep('webnn', getInstance(), env);\n    }\n  } else {\n    if (!BUILD_DEFS.DISABLE_WEBGPU && epName === 'webgpu') {\n      getInstance().webgpuInit!((device) => {\n        env.webgpu.device = device;\n      });\n    }\n    if (!BUILD_DEFS.DISABLE_WEBNN && epName === 'webnn') {\n      // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n      const backend = new (require('./jsep/backend-webnn').WebNNBackend)(env);\n      getInstance().webnnInit!([\n        backend,\n        // webnnReserveTensorId\n        () => backend.reserveTensorId(),\n        // webnnReleaseTensorId,\n        (tensorId: number) => backend.releaseTensorId(tensorId),\n        // webnnEnsureTensor\n        async (sessionId: number | undefined, tensorId: number, onnxDataType: number, shape: number[], copyOld) =>\n          backend.ensureTensor(sessionId, tensorId, onnxDataType, shape, copyOld),\n        // webnnUploadTensor\n        (tensorId: number, data: Uint8Array) => {\n          backend.uploadTensor(tensorId, data);\n        },\n        // webnnDownloadTensor\n        async (tensorId: number, dstBuffer: ArrayBufferView | ArrayBuffer) =>\n          backend.downloadTensor(tensorId, dstBuffer),\n        // webnnRegisterMLContext\n        (sessionId: number, mlContext: MLContext) => backend.registerMLContext(sessionId, mlContext),\n        // webnnEnableTraceEvent\n        !!env.trace,\n      ]);\n    }\n  }\n};\n\n// #endregion Initializations\n\n/**\n * valid data locations for input/output tensors.\n */\ntype SupportedTensorDataLocationForInputOutput =\n  | 'cpu'\n  | 'cpu-pinned'\n  | 'gpu-buffer'\n  | 'ml-tensor'\n  // Use 'ml-tensor' during inference, but output a tensor located on the CPU.\n  | 'ml-tensor-cpu-output';\n\ntype IOBindingState = {\n  /**\n   * the handle of IO binding.\n   */\n  readonly handle: number;\n\n  /**\n   * the preferred location for each output tensor.\n   *\n   * value is one of 'cpu', 'cpu-pinned', 'gpu-buffer', 'ml-tensor'.\n   */\n  readonly outputPreferredLocations: readonly SupportedTensorDataLocationForInputOutput[];\n\n  /**\n   * enum value of the preferred location for each output tensor.\n   */\n  readonly outputPreferredLocationsEncoded: readonly number[];\n};\n\n/**\n *  tuple elements are: InferenceSession ID; inputNamesUTF8Encoded; outputNamesUTF8Encoded; bindingState\n */\ntype SessionMetadata = [\n  inferenceSessionId: number,\n  inputNamesUTF8Encoded: number[],\n  outputNamesUTF8Encoded: number[],\n  bindingState: IOBindingState | null,\n  enableGraphCapture: boolean,\n  inputOutputBound: boolean,\n];\n\nconst activeSessions = new Map<number, SessionMetadata>();\n\n/**\n * get the input/output count of the session.\n * @param sessionHandle the handle representing the session. should be non-zero.\n * @returns a tuple including 2 numbers, representing the input count and output count.\n */\nconst getSessionInputOutputCount = (sessionHandle: number): [number, number] => {\n  const wasm = getInstance();\n  const stack = wasm.stackSave();\n  try {\n    const ptrSize = wasm.PTR_SIZE;\n    const dataOffset = wasm.stackAlloc(2 * ptrSize);\n    const errorCode = wasm._OrtGetInputOutputCount(sessionHandle, dataOffset, dataOffset + ptrSize);\n    if (errorCode !== 0) {\n      checkLastError(\"Can't get session input/output count.\");\n    }\n    const type = ptrSize === 4 ? 'i32' : 'i64';\n    return [Number(wasm.getValue(dataOffset, type)), Number(wasm.getValue(dataOffset + ptrSize, type))];\n  } finally {\n    wasm.stackRestore(stack);\n  }\n};\n\nconst getSessionInputOutputMetadata = (\n  sessionHandle: number,\n  index: number,\n): [nameOffset: number, elementType: number, dims?: Array<number | string>] => {\n  const wasm = getInstance();\n  const stack = wasm.stackSave();\n  let metadataOffset = 0;\n  try {\n    const ptrSize = wasm.PTR_SIZE;\n    const dataOffset = wasm.stackAlloc(2 * ptrSize);\n    const errorCode = wasm._OrtGetInputOutputMetadata(sessionHandle, index, dataOffset, dataOffset + ptrSize);\n    if (errorCode !== 0) {\n      checkLastError(\"Can't get session input/output metadata.\");\n    }\n    const nameOffset = Number(wasm.getValue(dataOffset, '*'));\n    metadataOffset = Number(wasm.getValue(dataOffset + ptrSize, '*'));\n    // get element type\n    const elementType = wasm.HEAP32[metadataOffset / 4];\n    if (elementType === 0) {\n      return [nameOffset, 0]; // non-tensor\n    }\n\n    // get dims count\n    const dimsCount = wasm.HEAPU32[metadataOffset / 4 + 1];\n    // get dims\n    const dims: Array<number | string> = [];\n    for (let i = 0; i < dimsCount; i++) {\n      const symbolicDimNameOffset = Number(wasm.getValue(metadataOffset + 8 + i * ptrSize, '*'));\n      dims.push(\n        symbolicDimNameOffset !== 0\n          ? wasm.UTF8ToString(symbolicDimNameOffset)\n          : Number(wasm.getValue(metadataOffset + 8 + (i + dimsCount) * ptrSize, '*')),\n      );\n    }\n    return [nameOffset, elementType, dims];\n  } finally {\n    wasm.stackRestore(stack);\n    if (metadataOffset !== 0) {\n      wasm._OrtFree(metadataOffset);\n    }\n  }\n};\n\n/**\n * allocate the memory and memcpy the external buffer.\n *\n * @param model - the external buffer containing the model data. Must not be the same buffer as the WASM heap.\n * @returns a 2-elements tuple - the pointer and size of the allocated buffer\n */\nexport const copyFromExternalBuffer = (model: Uint8Array): [number, number] => {\n  const wasm = getInstance();\n  const modelDataOffset = wasm._malloc(model.byteLength);\n  if (modelDataOffset === 0) {\n    throw new Error(`Can't create a session. failed to allocate a buffer of size ${model.byteLength}.`);\n  }\n  wasm.HEAPU8.set(model, modelDataOffset);\n  return [modelDataOffset, model.byteLength];\n};\n\n/**\n * create an inference session from a model data buffer.\n *\n * @param modelData - either a Uint8Array object representing the model data, or a 2-elements tuple containing the\n *     pointer and size of the model data buffer.\n * @param options an optional session options object.\n * @returns a 3-elements tuple containing [session handle, input names, output names]\n */\nexport const createSession = async (\n  modelData: Uint8Array | SerializableInternalBuffer,\n  options?: InferenceSession.SessionOptions,\n): Promise<SerializableSessionMetadata> => {\n  let modelDataOffset: number, modelDataLength: number;\n  const wasm = getInstance();\n\n  if (Array.isArray(modelData)) {\n    // if model data is an array, it must be a 2-elements tuple containing the pointer and size of the model data\n    [modelDataOffset, modelDataLength] = modelData;\n  } else if (modelData.buffer === wasm.HEAPU8.buffer) {\n    // if model data uses the same buffer as the WASM heap, we don't need to copy it.\n    [modelDataOffset, modelDataLength] = [modelData.byteOffset, modelData.byteLength];\n  } else {\n    // otherwise, copy the model data to the WASM heap.\n    [modelDataOffset, modelDataLength] = copyFromExternalBuffer(modelData);\n  }\n\n  let sessionHandle = 0;\n  let sessionOptionsHandle = 0;\n  let ioBindingHandle = 0;\n  let allocs: number[] = [];\n  const inputNamesUTF8Encoded = [];\n  const outputNamesUTF8Encoded = [];\n\n  try {\n    [sessionOptionsHandle, allocs] = await setSessionOptions(options);\n\n    if (options?.externalData && wasm.mountExternalData) {\n      const loadingPromises = [];\n      for (const file of options.externalData) {\n        const path = typeof file === 'string' ? file : file.path;\n        loadingPromises.push(\n          loadFile(typeof file === 'string' ? file : file.data).then((data) => {\n            wasm.mountExternalData(path, data);\n          }),\n        );\n      }\n\n      // wait for all external data files to be loaded\n      await Promise.all(loadingPromises);\n    }\n\n    for (const provider of options?.executionProviders ?? []) {\n      const providerName = typeof provider === 'string' ? provider : provider.name;\n      if (providerName === 'webnn') {\n        wasm.shouldTransferToMLTensor = false;\n        if (typeof provider !== 'string') {\n          const webnnOptions = provider as InferenceSession.WebNNExecutionProviderOption;\n          const context = (webnnOptions as InferenceSession.WebNNOptionsWithMLContext)?.context;\n          const gpuDevice = (webnnOptions as InferenceSession.WebNNOptionsWebGpu)?.gpuDevice;\n          const deviceType = (webnnOptions as InferenceSession.WebNNContextOptions)?.deviceType;\n          const powerPreference = (webnnOptions as InferenceSession.WebNNContextOptions)?.powerPreference;\n          if (context) {\n            wasm.currentContext = context as MLContext;\n          } else if (gpuDevice) {\n            wasm.currentContext = await wasm.webnnCreateMLContext!(gpuDevice);\n          } else {\n            wasm.currentContext = await wasm.webnnCreateMLContext!({ deviceType, powerPreference });\n          }\n        } else {\n          wasm.currentContext = await wasm.webnnCreateMLContext!();\n        }\n        break;\n      }\n    }\n\n    sessionHandle = await wasm._OrtCreateSession(modelDataOffset, modelDataLength, sessionOptionsHandle);\n    wasm.webgpuOnCreateSession?.(sessionHandle);\n    if (sessionHandle === 0) {\n      checkLastError(\"Can't create a session.\");\n    }\n\n    wasm.jsepOnCreateSession?.();\n\n    // clear current MLContext after session creation\n    if (wasm.currentContext) {\n      wasm.webnnRegisterMLContext!(sessionHandle, wasm.currentContext);\n      wasm.currentContext = undefined;\n      wasm.shouldTransferToMLTensor = true;\n    }\n\n    const [inputCount, outputCount] = getSessionInputOutputCount(sessionHandle);\n\n    const enableGraphCapture = !!options?.enableGraphCapture;\n\n    const inputNames = [];\n    const outputNames = [];\n    const inputMetadata: InferenceSession.ValueMetadata[] = [];\n    const outputMetadata: InferenceSession.ValueMetadata[] = [];\n    const outputPreferredLocations: SupportedTensorDataLocationForInputOutput[] = [];\n    for (let i = 0; i < inputCount; i++) {\n      const [nameOffset, elementType, shape] = getSessionInputOutputMetadata(sessionHandle, i);\n      if (nameOffset === 0) {\n        checkLastError(\"Can't get an input name.\");\n      }\n      inputNamesUTF8Encoded.push(nameOffset);\n      const name = wasm.UTF8ToString(nameOffset);\n      inputNames.push(name);\n      inputMetadata.push(\n        elementType === 0\n          ? { name, isTensor: false }\n          : { name, isTensor: true, type: tensorDataTypeEnumToString(elementType), shape: shape! },\n      );\n    }\n    for (let i = 0; i < outputCount; i++) {\n      const [nameOffset, elementType, shape] = getSessionInputOutputMetadata(sessionHandle, i + inputCount);\n      if (nameOffset === 0) {\n        checkLastError(\"Can't get an output name.\");\n      }\n      outputNamesUTF8Encoded.push(nameOffset);\n      const nameString = wasm.UTF8ToString(nameOffset);\n      outputNames.push(nameString);\n      outputMetadata.push(\n        elementType === 0\n          ? { name: nameString, isTensor: false }\n          : { name: nameString, isTensor: true, type: tensorDataTypeEnumToString(elementType), shape: shape! },\n      );\n\n      if (!BUILD_DEFS.DISABLE_JSEP || !BUILD_DEFS.DISABLE_WEBGPU) {\n        if (enableGraphCapture && options?.preferredOutputLocation === undefined) {\n          outputPreferredLocations.push('gpu-buffer');\n          continue;\n        }\n        const location =\n          typeof options?.preferredOutputLocation === 'string'\n            ? options.preferredOutputLocation\n            : (options?.preferredOutputLocation?.[nameString] ?? 'cpu');\n        const isGraphOutput = wasm.webnnIsGraphOutput;\n        if (location === 'cpu' && isGraphOutput && isGraphOutput(sessionHandle, nameString)) {\n          outputPreferredLocations.push('ml-tensor-cpu-output');\n          continue;\n        }\n        if (location !== 'cpu' && location !== 'cpu-pinned' && location !== 'gpu-buffer' && location !== 'ml-tensor') {\n          throw new Error(`Not supported preferred output location: ${location}.`);\n        }\n        if (enableGraphCapture && location !== 'gpu-buffer') {\n          throw new Error(\n            `Not supported preferred output location: ${location}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`,\n          );\n        }\n        outputPreferredLocations.push(location);\n      }\n    }\n\n    // use IO binding only when at least one output is preferred to be on GPU.\n    let bindingState: IOBindingState | null = null;\n    if (\n      (!BUILD_DEFS.DISABLE_JSEP || !BUILD_DEFS.DISABLE_WEBGPU) &&\n      outputPreferredLocations.some((l) => l === 'gpu-buffer' || l === 'ml-tensor' || l === 'ml-tensor-cpu-output')\n    ) {\n      ioBindingHandle = wasm._OrtCreateBinding(sessionHandle);\n      if (ioBindingHandle === 0) {\n        checkLastError(\"Can't create IO binding.\");\n      }\n\n      bindingState = {\n        handle: ioBindingHandle,\n        outputPreferredLocations,\n        outputPreferredLocationsEncoded: outputPreferredLocations\n          // 'ml-tensor-cpu-output' is treated as 'ml-tensor' for the purpose of IO binding.\n          .map((l) => (l === 'ml-tensor-cpu-output' ? 'ml-tensor' : l))\n          .map((l) => dataLocationStringToEnum(l)),\n      };\n    }\n\n    activeSessions.set(sessionHandle, [\n      sessionHandle,\n      inputNamesUTF8Encoded,\n      outputNamesUTF8Encoded,\n      bindingState,\n      enableGraphCapture,\n      false,\n    ]);\n    return [sessionHandle, inputNames, outputNames, inputMetadata, outputMetadata];\n  } catch (e) {\n    inputNamesUTF8Encoded.forEach((buf) => wasm._OrtFree(buf));\n    outputNamesUTF8Encoded.forEach((buf) => wasm._OrtFree(buf));\n\n    if (ioBindingHandle !== 0) {\n      if (wasm._OrtReleaseBinding(ioBindingHandle) !== 0) {\n        checkLastError(\"Can't release IO binding.\");\n      }\n    }\n\n    if (sessionHandle !== 0) {\n      if (wasm._OrtReleaseSession(sessionHandle) !== 0) {\n        checkLastError(\"Can't release session.\");\n      }\n    }\n    throw e;\n  } finally {\n    wasm._free(modelDataOffset);\n    if (sessionOptionsHandle !== 0) {\n      if (wasm._OrtReleaseSessionOptions(sessionOptionsHandle) !== 0) {\n        checkLastError(\"Can't release session options.\");\n      }\n    }\n    allocs.forEach((alloc) => wasm._free(alloc));\n\n    // unmount external data if necessary\n    wasm.unmountExternalData?.();\n  }\n};\n\nexport const releaseSession = (sessionId: number): void => {\n  const wasm = getInstance();\n  const session = activeSessions.get(sessionId);\n  if (!session) {\n    throw new Error(`cannot release session. invalid session id: ${sessionId}`);\n  }\n  const [sessionHandle, inputNamesUTF8Encoded, outputNamesUTF8Encoded, ioBindingState, enableGraphCapture] = session;\n\n  if (ioBindingState) {\n    if (enableGraphCapture) {\n      if (wasm._OrtClearBoundOutputs(ioBindingState.handle) !== 0) {\n        checkLastError(\"Can't clear bound outputs.\");\n      }\n    }\n    if (wasm._OrtReleaseBinding(ioBindingState.handle) !== 0) {\n      checkLastError(\"Can't release IO binding.\");\n    }\n  }\n\n  wasm.jsepOnReleaseSession?.(sessionId);\n  wasm.webnnOnReleaseSession?.(sessionId);\n  wasm.webgpuOnReleaseSession?.(sessionId);\n\n  inputNamesUTF8Encoded.forEach((buf) => wasm._OrtFree(buf));\n  outputNamesUTF8Encoded.forEach((buf) => wasm._OrtFree(buf));\n  if (wasm._OrtReleaseSession(sessionHandle) !== 0) {\n    checkLastError(\"Can't release session.\");\n  }\n  activeSessions.delete(sessionId);\n};\n\nexport const prepareInputOutputTensor = async (\n  tensor: TensorMetadata | null,\n  tensorHandles: number[],\n  allocs: number[],\n  sessionId: number,\n  tensorNameUTF8Encoded: number,\n  index: number,\n  enableGraphCapture = false,\n): Promise<void> => {\n  if (!tensor) {\n    tensorHandles.push(0);\n    return;\n  }\n\n  const wasm = getInstance();\n  const ptrSize = wasm.PTR_SIZE;\n\n  const dataType = tensor[0];\n  const dims = tensor[1];\n  const location = tensor[3];\n  let actualLocation = location;\n\n  let rawData: number;\n  let dataByteLength: number;\n\n  if (dataType === 'string' && (location === 'gpu-buffer' || location === 'ml-tensor')) {\n    throw new Error('String tensor is not supported on GPU.');\n  }\n\n  if (enableGraphCapture && location !== 'gpu-buffer') {\n    throw new Error(\n      `External buffer must be provided for input/output index ${index} when enableGraphCapture is true.`,\n    );\n  }\n\n  if (location === 'gpu-buffer') {\n    const gpuBuffer = tensor[2].gpuBuffer;\n    dataByteLength = calculateTensorSizeInBytes(tensorDataTypeStringToEnum(dataType), dims)!;\n\n    if (!BUILD_DEFS.DISABLE_WEBGPU) {\n      const registerBuffer = wasm.webgpuRegisterBuffer;\n      if (!registerBuffer) {\n        throw new Error('Tensor location \"gpu-buffer\" is not supported without using WebGPU.');\n      }\n\n      rawData = registerBuffer(gpuBuffer, sessionId);\n    } else {\n      const registerBuffer = wasm.jsepRegisterBuffer;\n      if (!registerBuffer) {\n        throw new Error('Tensor location \"gpu-buffer\" is not supported without using WebGPU.');\n      }\n      rawData = registerBuffer(sessionId, index, gpuBuffer, dataByteLength);\n    }\n  } else if (location === 'ml-tensor') {\n    const mlTensor = tensor[2].mlTensor as MLTensor;\n    dataByteLength = calculateTensorSizeInBytes(tensorDataTypeStringToEnum(dataType), dims)!;\n\n    const registerMLTensor = wasm.webnnRegisterMLTensor;\n    if (!registerMLTensor) {\n      throw new Error('Tensor location \"ml-tensor\" is not supported without using WebNN.');\n    }\n    rawData = registerMLTensor(sessionId, mlTensor, tensorDataTypeStringToEnum(dataType), dims);\n  } else {\n    const data = tensor[2];\n\n    if (Array.isArray(data)) {\n      // string tensor\n      dataByteLength = ptrSize * data.length;\n      rawData = wasm._malloc(dataByteLength);\n      allocs.push(rawData);\n      for (let i = 0; i < data.length; i++) {\n        if (typeof data[i] !== 'string') {\n          throw new TypeError(`tensor data at index ${i} is not a string`);\n        }\n        wasm.setValue(rawData + i * ptrSize, allocWasmString(data[i], allocs), '*');\n      }\n    } else {\n      const isGraphInput = wasm.webnnIsGraphInput;\n      const isGraphOutput = wasm.webnnIsGraphOutput;\n      if (dataType !== 'string' && isGraphInput && isGraphOutput) {\n        const tensorName = wasm.UTF8ToString(tensorNameUTF8Encoded);\n        // Promote the tensor to 'ml-tensor' if it is a graph input.\n        if (isGraphInput(sessionId, tensorName) || isGraphOutput(sessionId, tensorName)) {\n          const dataTypeEnum = tensorDataTypeStringToEnum(dataType);\n          dataByteLength = calculateTensorSizeInBytes(dataTypeEnum, dims)!;\n          actualLocation = 'ml-tensor';\n          const createTemporaryTensor = wasm.webnnCreateTemporaryTensor;\n          const uploadTensor = wasm.webnnUploadTensor;\n          if (!createTemporaryTensor || !uploadTensor) {\n            throw new Error('Tensor location \"ml-tensor\" is not supported without using WebNN.');\n          }\n          const tensorId = await createTemporaryTensor(sessionId, dataTypeEnum, dims as number[]);\n          uploadTensor(tensorId, new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n          rawData = tensorId;\n        } else {\n          dataByteLength = data.byteLength;\n          rawData = wasm._malloc(dataByteLength);\n          allocs.push(rawData);\n          wasm.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, dataByteLength), rawData);\n        }\n      } else {\n        dataByteLength = data.byteLength;\n        rawData = wasm._malloc(dataByteLength);\n        allocs.push(rawData);\n        wasm.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, dataByteLength), rawData);\n      }\n    }\n  }\n\n  const stack = wasm.stackSave();\n  const dimsOffset = wasm.stackAlloc(4 * dims.length);\n  try {\n    dims.forEach((d, index) => wasm.setValue(dimsOffset + index * ptrSize, d, ptrSize === 4 ? 'i32' : 'i64'));\n    const tensor = wasm._OrtCreateTensor(\n      tensorDataTypeStringToEnum(dataType),\n      rawData,\n      dataByteLength,\n      dimsOffset,\n      dims.length,\n      dataLocationStringToEnum(actualLocation),\n    );\n    if (tensor === 0) {\n      checkLastError(`Can't create tensor for input/output. session=${sessionId}, index=${index}.`);\n    }\n    tensorHandles.push(tensor);\n  } finally {\n    wasm.stackRestore(stack);\n  }\n};\n\n/**\n * perform inference run\n */\nexport const run = async (\n  sessionId: number,\n  inputIndices: number[],\n  inputTensors: TensorMetadata[],\n  outputIndices: number[],\n  outputTensors: Array<TensorMetadata | null>,\n  options: InferenceSession.RunOptions,\n): Promise<TensorMetadata[]> => {\n  const wasm = getInstance();\n  const ptrSize = wasm.PTR_SIZE;\n  const session = activeSessions.get(sessionId);\n  if (!session) {\n    throw new Error(`cannot run inference. invalid session id: ${sessionId}`);\n  }\n  const sessionHandle = session[0];\n  const inputNamesUTF8Encoded = session[1];\n  const outputNamesUTF8Encoded = session[2];\n  const ioBindingState = session[3];\n  const enableGraphCapture = session[4];\n  const inputOutputBound = session[5];\n\n  const inputCount = inputIndices.length;\n  const outputCount = outputIndices.length;\n\n  let runOptionsHandle = 0;\n  let runOptionsAllocs: number[] = [];\n\n  const inputTensorHandles: number[] = [];\n  const outputTensorHandles: number[] = [];\n  const inputOutputAllocs: number[] = [];\n\n  const beforeRunStack = wasm.stackSave();\n  const inputValuesOffset = wasm.stackAlloc(inputCount * ptrSize);\n  const inputNamesOffset = wasm.stackAlloc(inputCount * ptrSize);\n  const outputValuesOffset = wasm.stackAlloc(outputCount * ptrSize);\n  const outputNamesOffset = wasm.stackAlloc(outputCount * ptrSize);\n\n  try {\n    [runOptionsHandle, runOptionsAllocs] = setRunOptions(options);\n\n    TRACE_EVENT_BEGIN('wasm prepareInputOutputTensor');\n    // create input tensors\n    for (let i = 0; i < inputCount; i++) {\n      await prepareInputOutputTensor(\n        inputTensors[i],\n        inputTensorHandles,\n        inputOutputAllocs,\n        sessionId,\n        inputNamesUTF8Encoded[inputIndices[i]],\n        inputIndices[i],\n        enableGraphCapture,\n      );\n    }\n\n    // create output tensors\n    for (let i = 0; i < outputCount; i++) {\n      await prepareInputOutputTensor(\n        outputTensors[i],\n        outputTensorHandles,\n        inputOutputAllocs,\n        sessionId,\n        outputNamesUTF8Encoded[outputIndices[i]],\n        inputCount + outputIndices[i],\n        enableGraphCapture,\n      );\n    }\n    TRACE_EVENT_END('wasm prepareInputOutputTensor');\n\n    for (let i = 0; i < inputCount; i++) {\n      wasm.setValue(inputValuesOffset + i * ptrSize, inputTensorHandles[i], '*');\n      wasm.setValue(inputNamesOffset + i * ptrSize, inputNamesUTF8Encoded[inputIndices[i]], '*');\n    }\n    for (let i = 0; i < outputCount; i++) {\n      wasm.setValue(outputValuesOffset + i * ptrSize, outputTensorHandles[i], '*');\n      wasm.setValue(outputNamesOffset + i * ptrSize, outputNamesUTF8Encoded[outputIndices[i]], '*');\n    }\n\n    if ((!BUILD_DEFS.DISABLE_JSEP || !BUILD_DEFS.DISABLE_WEBGPU) && ioBindingState && !inputOutputBound) {\n      const { handle, outputPreferredLocations, outputPreferredLocationsEncoded } = ioBindingState;\n\n      if (inputNamesUTF8Encoded.length !== inputCount) {\n        throw new Error(\n          `input count from feeds (${inputCount}) is expected to be always equal to model's input count (${inputNamesUTF8Encoded.length}).`,\n        );\n      }\n\n      TRACE_EVENT_BEGIN('wasm bindInputsOutputs');\n      // process inputs\n      for (let i = 0; i < inputCount; i++) {\n        const index = inputIndices[i];\n        const errorCode = await wasm._OrtBindInput(handle, inputNamesUTF8Encoded[index], inputTensorHandles[i]);\n        if (errorCode !== 0) {\n          checkLastError(`Can't bind input[${i}] for session=${sessionId}.`);\n        }\n      }\n\n      // process pre-allocated outputs\n      for (let i = 0; i < outputCount; i++) {\n        const index = outputIndices[i];\n        const location = outputTensors[i]?.[3]; // undefined means output is not pre-allocated.\n\n        if (location) {\n          // output is pre-allocated. bind the tensor.\n          const errorCode = wasm._OrtBindOutput(handle, outputNamesUTF8Encoded[index], outputTensorHandles[i], 0);\n          if (errorCode !== 0) {\n            checkLastError(`Can't bind pre-allocated output[${i}] for session=${sessionId}.`);\n          }\n        } else {\n          // output is not pre-allocated. reset preferred location.\n          const errorCode = wasm._OrtBindOutput(\n            handle,\n            outputNamesUTF8Encoded[index],\n            0,\n            outputPreferredLocationsEncoded[index],\n          );\n          if (errorCode !== 0) {\n            checkLastError(`Can't bind output[${i}] to ${outputPreferredLocations[i]} for session=${sessionId}.`);\n          }\n        }\n      }\n      TRACE_EVENT_END('wasm bindInputsOutputs');\n      activeSessions.set(sessionId, [\n        sessionHandle,\n        inputNamesUTF8Encoded,\n        outputNamesUTF8Encoded,\n        ioBindingState,\n        enableGraphCapture,\n        true,\n      ]);\n    }\n\n    wasm.jsepOnRunStart?.(sessionHandle);\n    wasm.webnnOnRunStart?.(sessionHandle);\n\n    let errorCode: number;\n    if ((!BUILD_DEFS.DISABLE_JSEP || !BUILD_DEFS.DISABLE_WEBGPU) && ioBindingState) {\n      errorCode = await wasm._OrtRunWithBinding(\n        sessionHandle,\n        ioBindingState.handle,\n        outputCount,\n        outputValuesOffset,\n        runOptionsHandle,\n      );\n    } else {\n      errorCode = await wasm._OrtRun(\n        sessionHandle,\n        inputNamesOffset,\n        inputValuesOffset,\n        inputCount,\n        outputNamesOffset,\n        outputCount,\n        outputValuesOffset,\n        runOptionsHandle,\n      );\n    }\n\n    if (errorCode !== 0) {\n      checkLastError('failed to call OrtRun().');\n    }\n\n    const output: TensorMetadata[] = [];\n    const outputPromises: Array<Promise<[number, Tensor.DataType]>> = [];\n\n    TRACE_EVENT_BEGIN('wasm ProcessOutputTensor');\n    for (let i = 0; i < outputCount; i++) {\n      const tensor = Number(wasm.getValue(outputValuesOffset + i * ptrSize, '*'));\n      if (tensor === outputTensorHandles[i]) {\n        // output tensor is pre-allocated. no need to copy data.\n        output.push(outputTensors[i]!);\n        continue;\n      }\n\n      const beforeGetTensorDataStack = wasm.stackSave();\n      // stack allocate 4 pointer value\n      const tensorDataOffset = wasm.stackAlloc(4 * ptrSize);\n\n      let keepOutputTensor = false;\n      let type: Tensor.Type | undefined,\n        dataOffset = 0;\n      try {\n        const errorCode = wasm._OrtGetTensorData(\n          tensor,\n          tensorDataOffset,\n          tensorDataOffset + ptrSize,\n          tensorDataOffset + 2 * ptrSize,\n\n          tensorDataOffset + 3 * ptrSize,\n        );\n        if (errorCode !== 0) {\n          checkLastError(`Can't access output tensor data on index ${i}.`);\n        }\n        const valueType = ptrSize === 4 ? 'i32' : 'i64';\n        const dataType = Number(wasm.getValue(tensorDataOffset, valueType));\n        dataOffset = wasm.getValue(tensorDataOffset + ptrSize, '*');\n        const dimsOffset = wasm.getValue(tensorDataOffset + ptrSize * 2, '*');\n        const dimsLength = Number(wasm.getValue(tensorDataOffset + ptrSize * 3, valueType));\n        const dims = [];\n        for (let i = 0; i < dimsLength; i++) {\n          dims.push(Number(wasm.getValue(dimsOffset + i * ptrSize, valueType)));\n        }\n        if (wasm._OrtFree(dimsOffset) !== 0) {\n          checkLastError(\"Can't free memory for tensor dims.\");\n        }\n        const size = dims.reduce((a, b) => a * b, 1);\n        type = tensorDataTypeEnumToString(dataType);\n\n        const preferredLocation = ioBindingState?.outputPreferredLocations[outputIndices[i]];\n\n        if (type === 'string') {\n          if (preferredLocation === 'gpu-buffer' || preferredLocation === 'ml-tensor') {\n            throw new Error('String tensor is not supported on GPU.');\n          }\n          const stringData: string[] = [];\n          for (let i = 0; i < size; i++) {\n            const offset = wasm.getValue(dataOffset + i * ptrSize, '*');\n            const nextOffset = wasm.getValue(dataOffset + (i + 1) * ptrSize, '*');\n            const maxBytesToRead = i === size - 1 ? undefined : nextOffset - offset;\n            stringData.push(wasm.UTF8ToString(offset, maxBytesToRead));\n          }\n          output.push([type, dims, stringData, 'cpu']);\n        } else {\n          // If a certain output's preferred location is GPU but the tensor is empty, we still need to create a CPU\n          // tensor for it. There is no mapping GPU buffer for an empty tensor.\n          if (preferredLocation === 'gpu-buffer' && size > 0) {\n            const getBuffer = !BUILD_DEFS.DISABLE_WEBGPU ? wasm.webgpuGetBuffer : wasm.jsepGetBuffer;\n            if (!getBuffer) {\n              throw new Error('preferredLocation \"gpu-buffer\" is not supported without using WebGPU.');\n            }\n            const gpuBuffer = getBuffer(dataOffset);\n            const bufferSize = calculateTensorSizeInBytes(dataType, size);\n            if (bufferSize === undefined || !isGpuBufferSupportedType(type)) {\n              throw new Error(`Unsupported data type: ${type}`);\n            }\n\n            // do not release the tensor right now. it will be released when user calls tensor.dispose().\n            keepOutputTensor = true;\n\n            if (!BUILD_DEFS.DISABLE_WEBGPU) {\n              wasm.webgpuRegisterBuffer!(gpuBuffer, sessionId, dataOffset);\n              const downloadDataFunction = wasm.webgpuCreateDownloader!(gpuBuffer, bufferSize, sessionId);\n              output.push([\n                type,\n                dims,\n                {\n                  gpuBuffer,\n                  download: async () => {\n                    const arrayBuffer = await downloadDataFunction();\n                    const data = new (tensorTypeToTypedArrayConstructor(type!))(arrayBuffer);\n                    return data as Tensor.DataTypeMap[Tensor.GpuBufferDataTypes];\n                  },\n                  dispose: () => {\n                    if (wasm._OrtReleaseTensor(tensor) !== 0) {\n                      checkLastError(\"Can't release tensor.\");\n                    }\n                  },\n                },\n                'gpu-buffer',\n              ]);\n            } else {\n              output.push([\n                type,\n                dims,\n                {\n                  gpuBuffer,\n                  download: wasm.jsepCreateDownloader!(gpuBuffer, bufferSize, type),\n                  dispose: () => {\n                    if (wasm._OrtReleaseTensor(tensor) !== 0) {\n                      checkLastError(\"Can't release tensor.\");\n                    }\n                  },\n                },\n                'gpu-buffer',\n              ]);\n            }\n          } else if (preferredLocation === 'ml-tensor' && size > 0) {\n            const ensureTensor = wasm.webnnEnsureTensor;\n            const isGraphInputOutputTypeSupported = wasm.webnnIsGraphInputOutputTypeSupported;\n            if (!ensureTensor || !isGraphInputOutputTypeSupported) {\n              throw new Error('preferredLocation \"ml-tensor\" is not supported without using WebNN.');\n            }\n            const tensorSize = calculateTensorSizeInBytes(dataType, size);\n            if (tensorSize === undefined || !isMLTensorSupportedType(type)) {\n              throw new Error(`Unsupported data type: ${type}`);\n            }\n            if (!isGraphInputOutputTypeSupported(sessionId, type, false)) {\n              throw new Error(\n                `preferredLocation \"ml-tensor\" for ${type} output is not supported by current WebNN Context.`,\n              );\n            }\n\n            // If the graph has been partitioned, the output tensor may have not been created. For this reason, we use\n            // ensureTensor to get/create the MLTensor. In which case, we don't need to copy the data if a new tensor\n            // has been created.\n            const mlTensor = await ensureTensor(sessionId, dataOffset, dataType, dims, false);\n\n            // do not release the tensor right now. it will be released when user calls tensor.dispose().\n            keepOutputTensor = true;\n\n            output.push([\n              type,\n              dims,\n              {\n                mlTensor,\n                download: wasm.webnnCreateMLTensorDownloader!(dataOffset, type),\n                dispose: () => {\n                  wasm.webnnReleaseTensorId!(dataOffset);\n                  wasm._OrtReleaseTensor(tensor);\n                },\n              },\n              'ml-tensor',\n            ]);\n          } else if (preferredLocation === 'ml-tensor-cpu-output' && size > 0) {\n            const data = wasm.webnnCreateMLTensorDownloader!(dataOffset, type as Tensor.MLTensorDataTypes)();\n            const index = output.length;\n            // Delay the data download and releasing the tensor until we can wait for all output tensors to be downloaded.\n            keepOutputTensor = true;\n            outputPromises.push(\n              (async () => {\n                const result: [number, Tensor.DataType] = [index, await data];\n                wasm.webnnReleaseTensorId!(dataOffset);\n                wasm._OrtReleaseTensor(tensor);\n                return result;\n              })(),\n            );\n            output.push([type, dims, [], 'cpu']);\n          } else {\n            const typedArrayConstructor = tensorTypeToTypedArrayConstructor(type);\n            const data = new typedArrayConstructor(size);\n            new Uint8Array(data.buffer, data.byteOffset, data.byteLength).set(\n              wasm.HEAPU8.subarray(dataOffset, dataOffset + data.byteLength),\n            );\n            output.push([type, dims, data, 'cpu']);\n          }\n        }\n      } finally {\n        wasm.stackRestore(beforeGetTensorDataStack);\n        if (type === 'string' && dataOffset) {\n          wasm._free(dataOffset);\n        }\n        if (!keepOutputTensor) {\n          wasm._OrtReleaseTensor(tensor);\n        }\n      }\n    }\n\n    if (ioBindingState && !enableGraphCapture) {\n      if (wasm._OrtClearBoundOutputs(ioBindingState.handle) !== 0) {\n        checkLastError(\"Can't clear bound outputs.\");\n      }\n      activeSessions.set(sessionId, [\n        sessionHandle,\n        inputNamesUTF8Encoded,\n        outputNamesUTF8Encoded,\n        ioBindingState,\n        enableGraphCapture,\n        false,\n      ]);\n    }\n    // Wait for all output tensor data to be downloaded.\n    for (const [index, data] of await Promise.all(outputPromises)) {\n      output[index][2] = data;\n    }\n    TRACE_EVENT_END('wasm ProcessOutputTensor');\n    return output;\n  } finally {\n    wasm.webnnOnRunEnd?.(sessionHandle);\n\n    wasm.stackRestore(beforeRunStack);\n\n    if (!BUILD_DEFS.DISABLE_WEBGPU) {\n      inputTensors.forEach((t) => {\n        if (t && t[3] === 'gpu-buffer') {\n          wasm.webgpuUnregisterBuffer!(t[2].gpuBuffer);\n        }\n      });\n      outputTensors.forEach((t) => {\n        if (t && t[3] === 'gpu-buffer') {\n          wasm.webgpuUnregisterBuffer!(t[2].gpuBuffer);\n        }\n      });\n    }\n    inputTensorHandles.forEach((v) => wasm._OrtReleaseTensor(v));\n    outputTensorHandles.forEach((v) => wasm._OrtReleaseTensor(v));\n    inputOutputAllocs.forEach((p) => wasm._free(p));\n\n    if (runOptionsHandle !== 0) {\n      wasm._OrtReleaseRunOptions(runOptionsHandle);\n    }\n    runOptionsAllocs.forEach((p) => wasm._free(p));\n  }\n};\n\n/**\n * end profiling\n */\nexport const endProfiling = (sessionId: number): void => {\n  const wasm = getInstance();\n  const session = activeSessions.get(sessionId);\n  if (!session) {\n    throw new Error('invalid session id');\n  }\n  const sessionHandle = session[0];\n\n  // profile file name is not used yet, but it must be freed.\n  const profileFileName = wasm._OrtEndProfiling(sessionHandle);\n  if (profileFileName === 0) {\n    checkLastError(\"Can't get an profile file name.\");\n  }\n  wasm._OrtFree(profileFileName);\n};\n\nexport const extractTransferableBuffers = (tensors: readonly SerializableTensorMetadata[]): ArrayBufferLike[] => {\n  const buffers: ArrayBufferLike[] = [];\n  for (const tensor of tensors) {\n    const data = tensor[2];\n    if (!Array.isArray(data) && 'buffer' in data) {\n      buffers.push(data.buffer);\n    }\n  }\n  return buffers;\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { env, InferenceSession } from 'onnxruntime-common';\n\nimport {\n  OrtWasmMessage,\n  SerializableInternalBuffer,\n  SerializableSessionMetadata,\n  SerializableTensorMetadata,\n  TensorMetadata,\n} from './proxy-messages';\nimport * as core from './wasm-core-impl';\nimport { initializeWebAssembly } from './wasm-factory';\nimport {\n  importProxyWorker,\n  inferWasmPathPrefixFromScriptSrc,\n  isEsmImportMetaUrlHardcodedAsFileUri,\n} from './wasm-utils-import';\n\nconst isProxy = (): boolean => !!env.wasm.proxy && typeof document !== 'undefined';\nlet proxyWorker: Worker | undefined;\nlet initializing = false;\nlet initialized = false;\nlet aborted = false;\nlet temporaryObjectUrl: string | undefined;\n\ntype PromiseCallbacks<T = void> = [resolve: (result: T) => void, reject: (reason: unknown) => void];\nlet initWasmCallbacks: PromiseCallbacks;\nconst queuedCallbacks: Map<OrtWasmMessage['type'], Array<PromiseCallbacks<unknown>>> = new Map();\n\nconst enqueueCallbacks = (type: OrtWasmMessage['type'], callbacks: PromiseCallbacks<unknown>): void => {\n  const queue = queuedCallbacks.get(type);\n  if (queue) {\n    queue.push(callbacks);\n  } else {\n    queuedCallbacks.set(type, [callbacks]);\n  }\n};\n\nconst ensureWorker = (): void => {\n  if (initializing || !initialized || aborted || !proxyWorker) {\n    throw new Error('worker not ready');\n  }\n};\n\nconst onProxyWorkerMessage = (ev: MessageEvent<OrtWasmMessage>): void => {\n  switch (ev.data.type) {\n    case 'init-wasm':\n      initializing = false;\n      if (ev.data.err) {\n        aborted = true;\n        initWasmCallbacks[1](ev.data.err);\n      } else {\n        initialized = true;\n        initWasmCallbacks[0]();\n      }\n      if (temporaryObjectUrl) {\n        URL.revokeObjectURL(temporaryObjectUrl);\n        temporaryObjectUrl = undefined;\n      }\n      break;\n    case 'init-ep':\n    case 'copy-from':\n    case 'create':\n    case 'release':\n    case 'run':\n    case 'end-profiling': {\n      const callbacks = queuedCallbacks.get(ev.data.type)!;\n      if (ev.data.err) {\n        callbacks.shift()![1](ev.data.err);\n      } else {\n        callbacks.shift()![0](ev.data.out!);\n      }\n      break;\n    }\n    default:\n  }\n};\n\nexport const initializeWebAssemblyAndOrtRuntime = async (): Promise<void> => {\n  if (initialized) {\n    return;\n  }\n  if (initializing) {\n    throw new Error(\"multiple calls to 'initWasm()' detected.\");\n  }\n  if (aborted) {\n    throw new Error(\"previous call to 'initWasm()' failed.\");\n  }\n\n  initializing = true;\n\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    return new Promise<void>((resolve, reject) => {\n      proxyWorker?.terminate();\n\n      void importProxyWorker().then(([objectUrl, worker]) => {\n        try {\n          proxyWorker = worker;\n          proxyWorker.onerror = (ev: ErrorEvent) => reject(ev);\n          proxyWorker.onmessage = onProxyWorkerMessage;\n          initWasmCallbacks = [resolve, reject];\n          const message: OrtWasmMessage = { type: 'init-wasm', in: env };\n\n          // if the proxy worker is loaded from a blob URL, we need to make sure the path information is not lost.\n          //\n          // when `env.wasm.wasmPaths` is not set, we need to pass the path information to the worker.\n          //\n          if (!BUILD_DEFS.ENABLE_BUNDLE_WASM_JS && !message.in!.wasm.wasmPaths && objectUrl) {\n            // for a build not bundled the wasm JS, we need to pass the path prefix to the worker.\n            // the path prefix will be used to resolve the path to both the wasm JS and the wasm file.\n            const inferredWasmPathPrefix = inferWasmPathPrefixFromScriptSrc();\n            if (inferredWasmPathPrefix) {\n              message.in!.wasm.wasmPaths = inferredWasmPathPrefix;\n            }\n          }\n\n          if (\n            BUILD_DEFS.IS_ESM &&\n            BUILD_DEFS.ENABLE_BUNDLE_WASM_JS &&\n            !message.in!.wasm.wasmPaths &&\n            (objectUrl || isEsmImportMetaUrlHardcodedAsFileUri)\n          ) {\n            // for a build bundled the wasm JS, if either of the following conditions is met:\n            // - the proxy worker is loaded from a blob URL\n            // - `import.meta.url` is a file URL, it means it is overwritten by the bundler.\n            //\n            // in either case, the path information is lost, we need to pass the path of the .wasm file to the worker.\n            // we need to use the bundler preferred URL format:\n            // new URL('filename', import.meta.url)\n            // so that the bundler can handle the file using corresponding loaders.\n            message.in!.wasm.wasmPaths = {\n              wasm: !BUILD_DEFS.DISABLE_JSEP\n                ? new URL('ort-wasm-simd-threaded.jsep.wasm', BUILD_DEFS.ESM_IMPORT_META_URL).href\n                : !BUILD_DEFS.DISABLE_WEBGPU\n                  ? new URL('ort-wasm-simd-threaded.asyncify.wasm', BUILD_DEFS.ESM_IMPORT_META_URL).href\n                  : new URL('ort-wasm-simd-threaded.wasm', BUILD_DEFS.ESM_IMPORT_META_URL).href,\n            };\n          }\n          proxyWorker.postMessage(message);\n          temporaryObjectUrl = objectUrl;\n        } catch (e) {\n          reject(e);\n        }\n      }, reject);\n    });\n  } else {\n    try {\n      await initializeWebAssembly(env.wasm);\n      await core.initRuntime(env);\n      initialized = true;\n    } catch (e) {\n      aborted = true;\n      throw e;\n    } finally {\n      initializing = false;\n    }\n  }\n};\n\nexport const initializeOrtEp = async (epName: string): Promise<void> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    ensureWorker();\n    return new Promise<void>((resolve, reject) => {\n      enqueueCallbacks('init-ep', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'init-ep', in: { epName, env } };\n      proxyWorker!.postMessage(message);\n    });\n  } else {\n    await core.initEp(env, epName);\n  }\n};\n\nexport const copyFromExternalBuffer = async (buffer: Uint8Array): Promise<SerializableInternalBuffer> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    ensureWorker();\n    return new Promise<SerializableInternalBuffer>((resolve, reject) => {\n      enqueueCallbacks('copy-from', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'copy-from', in: { buffer } };\n      proxyWorker!.postMessage(message, [buffer.buffer]);\n    });\n  } else {\n    return core.copyFromExternalBuffer(buffer);\n  }\n};\n\nexport const createSession = async (\n  model: SerializableInternalBuffer | Uint8Array,\n  options?: InferenceSession.SessionOptions,\n): Promise<SerializableSessionMetadata> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    // check unsupported options\n    if (options?.preferredOutputLocation) {\n      throw new Error('session option \"preferredOutputLocation\" is not supported for proxy.');\n    }\n    ensureWorker();\n    return new Promise<SerializableSessionMetadata>((resolve, reject) => {\n      enqueueCallbacks('create', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'create', in: { model, options: { ...options } } };\n      const transferable: Transferable[] = [];\n      if (model instanceof Uint8Array) {\n        transferable.push(model.buffer);\n      }\n      proxyWorker!.postMessage(message, transferable);\n    });\n  } else {\n    return core.createSession(model, options);\n  }\n};\n\nexport const releaseSession = async (sessionId: number): Promise<void> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    ensureWorker();\n    return new Promise<void>((resolve, reject) => {\n      enqueueCallbacks('release', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'release', in: sessionId };\n      proxyWorker!.postMessage(message);\n    });\n  } else {\n    core.releaseSession(sessionId);\n  }\n};\n\nexport const run = async (\n  sessionId: number,\n  inputIndices: number[],\n  inputs: TensorMetadata[],\n  outputIndices: number[],\n  outputs: Array<TensorMetadata | null>,\n  options: InferenceSession.RunOptions,\n): Promise<TensorMetadata[]> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    // check inputs location\n    if (inputs.some((t) => t[3] !== 'cpu')) {\n      throw new Error('input tensor on GPU is not supported for proxy.');\n    }\n    // check outputs location\n    if (outputs.some((t) => t)) {\n      throw new Error('pre-allocated output tensor is not supported for proxy.');\n    }\n    ensureWorker();\n    return new Promise<SerializableTensorMetadata[]>((resolve, reject) => {\n      enqueueCallbacks('run', [resolve, reject]);\n      const serializableInputs = inputs as SerializableTensorMetadata[]; // every input is on CPU.\n      const message: OrtWasmMessage = {\n        type: 'run',\n        in: { sessionId, inputIndices, inputs: serializableInputs, outputIndices, options },\n      };\n      proxyWorker!.postMessage(message, core.extractTransferableBuffers(serializableInputs));\n    });\n  } else {\n    return core.run(sessionId, inputIndices, inputs, outputIndices, outputs, options);\n  }\n};\n\nexport const endProfiling = async (sessionId: number): Promise<void> => {\n  if (!BUILD_DEFS.DISABLE_WASM_PROXY && isProxy()) {\n    ensureWorker();\n    return new Promise<void>((resolve, reject) => {\n      enqueueCallbacks('end-profiling', [resolve, reject]);\n      const message: OrtWasmMessage = { type: 'end-profiling', in: sessionId };\n      proxyWorker!.postMessage(message);\n    });\n  } else {\n    core.endProfiling(sessionId);\n  }\n};\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport {\n  InferenceSession,\n  InferenceSessionHandler,\n  SessionHandler,\n  Tensor,\n  TRACE_FUNC_BEGIN,\n  TRACE_FUNC_END,\n} from 'onnxruntime-common';\n\nimport { SerializableInternalBuffer, TensorMetadata } from './proxy-messages';\nimport { copyFromExternalBuffer, createSession, endProfiling, releaseSession, run } from './proxy-wrapper';\nimport { isGpuBufferSupportedType, isMLTensorSupportedType } from './wasm-common';\nimport { isNode } from './wasm-utils-env';\nimport { loadFile } from './wasm-utils-load-file';\n\nexport const encodeTensorMetadata = (tensor: Tensor, getName: () => string): TensorMetadata => {\n  switch (tensor.location) {\n    case 'cpu':\n      return [tensor.type, tensor.dims, tensor.data, 'cpu'];\n    case 'gpu-buffer':\n      return [tensor.type, tensor.dims, { gpuBuffer: tensor.gpuBuffer }, 'gpu-buffer'];\n    case 'ml-tensor':\n      return [tensor.type, tensor.dims, { mlTensor: tensor.mlTensor }, 'ml-tensor'];\n    default:\n      throw new Error(`invalid data location: ${tensor.location} for ${getName()}`);\n  }\n};\n\nexport const decodeTensorMetadata = (tensor: TensorMetadata): Tensor => {\n  switch (tensor[3]) {\n    case 'cpu':\n      return new Tensor(tensor[0], tensor[2], tensor[1]);\n    case 'gpu-buffer': {\n      const dataType = tensor[0];\n      if (!isGpuBufferSupportedType(dataType)) {\n        throw new Error(`not supported data type: ${dataType} for deserializing GPU tensor`);\n      }\n      const { gpuBuffer, download, dispose } = tensor[2];\n      return Tensor.fromGpuBuffer(gpuBuffer, { dataType, dims: tensor[1], download, dispose });\n    }\n    case 'ml-tensor': {\n      const dataType = tensor[0];\n      if (!isMLTensorSupportedType(dataType)) {\n        throw new Error(`not supported data type: ${dataType} for deserializing MLTensor tensor`);\n      }\n      const { mlTensor, download, dispose } = tensor[2];\n      return Tensor.fromMLTensor(mlTensor, { dataType, dims: tensor[1], download, dispose });\n    }\n    default:\n      throw new Error(`invalid data location: ${tensor[3]}`);\n  }\n};\n\nexport class OnnxruntimeWebAssemblySessionHandler implements InferenceSessionHandler {\n  private sessionId: number;\n\n  inputNames: readonly string[];\n  outputNames: readonly string[];\n  inputMetadata: readonly InferenceSession.ValueMetadata[];\n  outputMetadata: readonly InferenceSession.ValueMetadata[];\n\n  async fetchModelAndCopyToWasmMemory(path: string): Promise<SerializableInternalBuffer> {\n    // fetch model from url and move to wasm heap.\n    return copyFromExternalBuffer(await loadFile(path));\n  }\n\n  async loadModel(pathOrBuffer: string | Uint8Array, options?: InferenceSession.SessionOptions): Promise<void> {\n    TRACE_FUNC_BEGIN();\n    let model: Parameters<typeof createSession>[0];\n\n    if (typeof pathOrBuffer === 'string') {\n      if (isNode) {\n        // node\n        model = await loadFile(pathOrBuffer);\n      } else {\n        // browser\n        // fetch model and copy to wasm heap.\n        model = await this.fetchModelAndCopyToWasmMemory(pathOrBuffer);\n      }\n    } else {\n      model = pathOrBuffer;\n    }\n\n    [this.sessionId, this.inputNames, this.outputNames, this.inputMetadata, this.outputMetadata] = await createSession(\n      model,\n      options,\n    );\n    TRACE_FUNC_END();\n  }\n\n  async dispose(): Promise<void> {\n    return releaseSession(this.sessionId);\n  }\n\n  async run(\n    feeds: SessionHandler.FeedsType,\n    fetches: SessionHandler.FetchesType,\n    options: InferenceSession.RunOptions,\n  ): Promise<SessionHandler.ReturnType> {\n    TRACE_FUNC_BEGIN();\n    const inputArray: Tensor[] = [];\n    const inputIndices: number[] = [];\n    Object.entries(feeds).forEach((kvp) => {\n      const name = kvp[0];\n      const tensor = kvp[1];\n      const index = this.inputNames.indexOf(name);\n      if (index === -1) {\n        throw new Error(`invalid input '${name}'`);\n      }\n      inputArray.push(tensor);\n      inputIndices.push(index);\n    });\n\n    const outputArray: Array<Tensor | null> = [];\n    const outputIndices: number[] = [];\n    Object.entries(fetches).forEach((kvp) => {\n      const name = kvp[0];\n      const tensor = kvp[1];\n      const index = this.outputNames.indexOf(name);\n      if (index === -1) {\n        throw new Error(`invalid output '${name}'`);\n      }\n      outputArray.push(tensor);\n      outputIndices.push(index);\n    });\n\n    const inputs = inputArray.map((t, i) =>\n      encodeTensorMetadata(t, () => `input \"${this.inputNames[inputIndices[i]]}\"`),\n    );\n    const outputs = outputArray.map((t, i) =>\n      t ? encodeTensorMetadata(t, () => `output \"${this.outputNames[outputIndices[i]]}\"`) : null,\n    );\n\n    const results = await run(this.sessionId, inputIndices, inputs, outputIndices, outputs, options);\n\n    const resultMap: SessionHandler.ReturnType = {};\n    for (let i = 0; i < results.length; i++) {\n      resultMap[this.outputNames[outputIndices[i]]] = outputArray[i] ?? decodeTensorMetadata(results[i]);\n    }\n    TRACE_FUNC_END();\n    return resultMap;\n  }\n\n  startProfiling(): void {\n    // TODO: implement profiling\n  }\n\n  endProfiling(): void {\n    void endProfiling(this.sessionId);\n  }\n}\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\nimport { Backend, env, InferenceSession, InferenceSessionHandler } from 'onnxruntime-common';\n\nimport { initializeOrtEp, initializeWebAssemblyAndOrtRuntime } from './wasm/proxy-wrapper';\nimport { OnnxruntimeWebAssemblySessionHandler } from './wasm/session-handler-inference';\n\n/**\n * This function initializes all flags for WebAssembly.\n *\n * Those flags are accessible from `ort.env.wasm`. Users are allow to set those flags before the first inference session\n * being created, to override default value.\n */\nexport const initializeFlags = (): void => {\n  if (typeof env.wasm.initTimeout !== 'number' || env.wasm.initTimeout < 0) {\n    env.wasm.initTimeout = 0;\n  }\n\n  const simd = env.wasm.simd;\n  if (typeof simd !== 'boolean' && simd !== undefined && simd !== 'fixed' && simd !== 'relaxed') {\n    // eslint-disable-next-line no-console\n    console.warn(\n      `Property \"env.wasm.simd\" is set to unknown value \"${simd}\". Reset it to \\`false\\` and ignore SIMD feature checking.`,\n    );\n    env.wasm.simd = false;\n  }\n\n  if (typeof env.wasm.proxy !== 'boolean') {\n    env.wasm.proxy = false;\n  }\n\n  if (typeof env.wasm.trace !== 'boolean') {\n    env.wasm.trace = false;\n  }\n\n  if (typeof env.wasm.numThreads !== 'number' || !Number.isInteger(env.wasm.numThreads) || env.wasm.numThreads <= 0) {\n    // The following logic only applies when `ort.env.wasm.numThreads` is not set by user. We will always honor user's\n    // setting if it is provided.\n\n    // Browser: when crossOriginIsolated is false, SharedArrayBuffer is not available so WebAssembly threads will not\n    // work. In this case, we will set numThreads to 1.\n    //\n    // There is an exception: when the browser is configured to force-enable SharedArrayBuffer (e.g. Chromuim with\n    // --enable-features=SharedArrayBuffer), it is possible that `self.crossOriginIsolated` is false and\n    // SharedArrayBuffer is available at the same time. This is usually for testing. In this case,  we will still set\n    // numThreads to 1 here. If we want to enable multi-threading in test, we should set `ort.env.wasm.numThreads` to a\n    // value greater than 1.\n    if (typeof self !== 'undefined' && !self.crossOriginIsolated) {\n      env.wasm.numThreads = 1;\n    } else {\n      const numCpuLogicalCores =\n        typeof navigator === 'undefined' ? require('node:os').cpus().length : navigator.hardwareConcurrency;\n      env.wasm.numThreads = Math.min(4, Math.ceil((numCpuLogicalCores || 1) / 2));\n    }\n  }\n};\n\nexport class OnnxruntimeWebAssemblyBackend implements Backend {\n  /**\n   * This function initializes the WebAssembly backend.\n   *\n   * This function will be called only once for each backend name. It will be called the first time when\n   * `ort.InferenceSession.create()` is called with a registered backend name.\n   *\n   * @param backendName - the registered backend name.\n   */\n  async init(backendName: string): Promise<void> {\n    // populate wasm flags\n    initializeFlags();\n\n    // init wasm\n    await initializeWebAssemblyAndOrtRuntime();\n\n    // performe EP specific initialization\n    await initializeOrtEp(backendName);\n  }\n  createInferenceSessionHandler(\n    path: string,\n    options?: InferenceSession.SessionOptions,\n  ): Promise<InferenceSessionHandler>;\n  createInferenceSessionHandler(\n    buffer: Uint8Array,\n    options?: InferenceSession.SessionOptions,\n  ): Promise<InferenceSessionHandler>;\n  async createInferenceSessionHandler(\n    pathOrBuffer: string | Uint8Array,\n    options?: InferenceSession.SessionOptions,\n  ): Promise<InferenceSessionHandler> {\n    const handler = new OnnxruntimeWebAssemblySessionHandler();\n    await handler.loadModel(pathOrBuffer, options);\n    return handler;\n  }\n}\n\nexport const wasmBackend = new OnnxruntimeWebAssemblyBackend();\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n/* eslint-disable @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports */\n\n// We use \"require\" instead of \"import\" here because import statement must be put in top level. Our current code does\n// not allow bundler to tree-shaking code as expected because some codes are treated as having side effects.\n// So we import code inside the if-clause to allow bundler remove the code safely.\n\nexport * from 'onnxruntime-common';\nimport * as ort from 'onnxruntime-common';\nexport default ort;\n\nimport { registerBackend, env } from 'onnxruntime-common';\nimport { version } from './version';\n\nif (!BUILD_DEFS.DISABLE_WEBGL) {\n  const onnxjsBackend = require('./backend-onnxjs').onnxjsBackend;\n  registerBackend('webgl', onnxjsBackend, -10);\n}\n\nif (!BUILD_DEFS.DISABLE_JSEP && !BUILD_DEFS.DISABLE_WEBGPU) {\n  throw new Error(\n    'The current build is specified to enable both JSEP and WebGPU EP. This is not a valid configuration. ' +\n      'JSEP and WebGPU EPs cannot be enabled at the same time.',\n  );\n}\n\nif (!BUILD_DEFS.DISABLE_WEBNN && BUILD_DEFS.DISABLE_JSEP && BUILD_DEFS.DISABLE_WEBGPU) {\n  throw new Error(\n    'The current build is specified to enable WebNN EP without JSEP or WebGPU EP. This is not a valid configuration. ' +\n      'WebNN EP requires either JSEP or WebGPU EP to be enabled.',\n  );\n}\n\nif (!BUILD_DEFS.DISABLE_WASM) {\n  const wasmBackend = require('./backend-wasm').wasmBackend;\n  if (!BUILD_DEFS.DISABLE_JSEP || !BUILD_DEFS.DISABLE_WEBGPU) {\n    registerBackend('webgpu', wasmBackend, 5);\n  }\n  if (!BUILD_DEFS.DISABLE_WEBNN) {\n    registerBackend('webnn', wasmBackend, 5);\n  }\n  registerBackend('cpu', wasmBackend, 10);\n  registerBackend('wasm', wasmBackend, 10);\n}\n\nObject.defineProperty(env.versions, 'web', { value: version, enumerable: true });\n","// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License.\n\n// This file is generated by /js/scripts/update-version.ts\n// Do not modify file content manually.\n\nexport const version = '1.23.2';\n"]}