@p2arthur/webinference-sdk 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -32,6 +32,16 @@ export interface ModelDescriptor<T extends ModelTask = ModelTask> extends ModelR
32
32
  readonly requiresFp16: boolean
33
33
  }
34
34
 
35
+ export interface LocalModelDescriptor<T extends ModelTask = ModelTask> extends Omit<ModelDescriptor<T>, 'repo' | 'revision'> {
36
+ readonly source: 'local'
37
+ readonly folder: string
38
+ }
39
+
40
+ export interface LocalModelReport<T extends ModelTask = ModelTask> {
41
+ models: LocalModelDescriptor<T>[]
42
+ issues: string[]
43
+ }
44
+
35
45
  export interface InspectOptions {
36
46
  signal?: AbortSignal
37
47
  findRelated?: boolean
@@ -56,7 +66,7 @@ export interface DeviceInfo {
56
66
  }
57
67
 
58
68
  export interface LoadProgress {
59
- stage: 'download' | 'initialize' | 'ready'
69
+ stage: 'download' | 'read' | 'initialize' | 'ready'
60
70
  loadedBytes: number
61
71
  totalBytes: number
62
72
  }
@@ -65,13 +75,68 @@ export interface OperationOptions {
65
75
  signal?: AbortSignal
66
76
  }
67
77
 
78
+ export type CachePolicy = 'prefer' | 'require' | 'memory-only'
79
+
80
+ export interface LoadErrorDetails {
81
+ kind: 'cache' | 'quota' | 'download-interrupted' | 'download-http' | 'integrity'
82
+ | 'local-file' | 'device' | 'gpu-allocation' | 'initialize'
83
+ stage: 'preflight' | 'cache-read' | 'cache-write' | 'download' | 'verify' | 'read' | 'initialize'
84
+ file?: string
85
+ retryable: boolean
86
+ httpStatus?: number
87
+ }
88
+
89
+ export interface CacheResult {
90
+ readonly policy: CachePolicy
91
+ readonly status: 'local' | 'cached' | 'memory' | 'mixed'
92
+ readonly hits: number
93
+ readonly writes: number
94
+ readonly bypassed: number
95
+ readonly warning?: LoadErrorDetails & { message: string }
96
+ }
97
+
98
+ export interface PreflightReport {
99
+ device: DeviceInfo
100
+ requirements: {
101
+ secureContext: boolean
102
+ webgpu: boolean
103
+ webassembly: boolean
104
+ worker: boolean
105
+ shaderFp16: boolean
106
+ offscreenCanvas: boolean
107
+ persistentCache: boolean
108
+ }
109
+ blockers: { code: string; message: string }[]
110
+ files: { path: string; size: number; state: 'cached' | 'missing' | 'unknown' | 'local' | 'bypassed' }[]
111
+ totalBytes: number
112
+ downloadBytes: number | null
113
+ knownDownloadBytes: number
114
+ }
115
+
68
116
  export interface OpenModelOptions<T extends ModelTask = ModelTask> extends OperationOptions {
69
117
  task?: T
118
+ cache?: CachePolicy
119
+ maxOutputTokens?: T extends 'chat' ? number : never
70
120
  onProgress?: (progress: LoadProgress) => void
71
121
  }
72
122
 
123
+ export interface ChatSettings {
124
+ readonly requestedMaxOutputTokens: number
125
+ readonly effectiveMaxOutputTokens: number
126
+ }
127
+
128
+ export interface ChatFinish extends ChatSettings {
129
+ finishReason: 'stop' | 'length' | 'unknown'
130
+ }
131
+
73
132
  export interface ChatOptions extends OperationOptions {
74
133
  onToken?: (text: string) => void
134
+ onFinish?: (event: ChatFinish) => void
135
+ }
136
+
137
+ export interface ResetChatOptions extends OperationOptions {
138
+ instructions?: string
139
+ history?: readonly { role: 'user' | 'assistant'; content: string }[]
75
140
  }
76
141
 
77
142
  export interface ImageOptions extends OperationOptions {
@@ -103,12 +168,14 @@ export type ClassificationChoice = string | { readonly label: string; readonly d
103
168
  interface Session<T extends ModelTask> {
104
169
  readonly task: T
105
170
  readonly model: ModelDescriptor<T>
171
+ readonly cache: CacheResult
106
172
  dispose(): void
107
173
  }
108
174
 
109
175
  export interface ChatSession extends Session<'chat'> {
176
+ readonly chatSettings: ChatSettings
110
177
  chat(prompt: string, options?: ChatOptions): Promise<string>
111
- reset(options?: OperationOptions): Promise<void>
178
+ reset(options?: ResetChatOptions): Promise<void>
112
179
  }
113
180
 
114
181
  export interface ImageSession extends Session<'image'> {
@@ -126,17 +193,22 @@ type SessionByTask = {
126
193
  }
127
194
 
128
195
  export type ModelSession<T extends ModelTask = ModelTask> = SessionByTask[T]
196
+ type LocalSessionByTask = {
197
+ [T in ModelTask]: Omit<SessionByTask[T], 'model'> & { readonly model: LocalModelDescriptor<T> }
198
+ }
199
+ export type LocalModelSession<T extends ModelTask = ModelTask> = LocalSessionByTask[T]
129
200
 
130
201
  export type ModelErrorCode =
131
202
  | 'INVALID_MODEL' | 'INVALID_ARGUMENT' | 'HUB_REQUEST_FAILED' | 'ACCESS_REQUIRED'
132
203
  | 'UNSUPPORTED_MODEL' | 'DEVICE_UNSUPPORTED' | 'WORKER_FAILED' | 'LOAD_FAILED'
133
- | 'INFERENCE_FAILED' | 'BUSY' | 'DISPOSED' | 'ABORTED' | 'CALLBACK_FAILED'
204
+ | 'INFERENCE_FAILED' | 'LOCAL_READ_FAILED' | 'BUSY' | 'DISPOSED' | 'ABORTED' | 'CALLBACK_FAILED'
134
205
 
135
206
  export class ModelError extends Error {
136
- constructor(code: ModelErrorCode, message: string, context?: { operation?: string; repo?: string; cause?: unknown })
207
+ constructor(code: ModelErrorCode, message: string, context?: { operation?: string; repo?: string; cause?: unknown; details?: LoadErrorDetails })
137
208
  readonly code: ModelErrorCode
138
209
  readonly operation?: string
139
210
  readonly repo?: string
211
+ readonly details?: LoadErrorDetails
140
212
  }
141
213
 
142
214
  export const HUGGING_FACE_BROWSE_URL: string
@@ -148,8 +220,20 @@ export function listModels<T extends ModelTask = ModelTask>(filter?: {
148
220
  }): Promise<ModelDescriptor<T>[]>
149
221
 
150
222
  export function inspectModel(url: string, options?: InspectOptions): Promise<InspectReport>
223
+ export function scanLocalModels<T extends ModelTask = ModelTask>(
224
+ input: FileSystemDirectoryHandle | FileList | Iterable<File>, options?: OperationOptions & { task?: T },
225
+ ): Promise<LocalModelReport<T>>
151
226
  export function getDeviceInfo(): Promise<DeviceInfo>
227
+ export function preflightModel(
228
+ input: ModelRegistration | LocalModelDescriptor, options?: OperationOptions & { cache?: CachePolicy },
229
+ ): Promise<PreflightReport>
152
230
 
231
+ export function openModel<T extends ModelTask>(
232
+ input: LocalModelDescriptor, options: OpenModelOptions<T> & { task: T },
233
+ ): Promise<LocalModelSession<T>>
234
+ export function openModel<T extends ModelTask>(
235
+ input: LocalModelDescriptor<T>, options?: OpenModelOptions<T>,
236
+ ): Promise<LocalModelSession<T>>
153
237
  export function openModel<T extends ModelTask>(
154
238
  input: string | ModelRegistration, options: OpenModelOptions<T> & { task: T },
155
239
  ): Promise<ModelSession<T>>
@@ -159,3 +243,6 @@ export function openModel<T extends ModelTask>(
159
243
  export function openModel(
160
244
  input: string | ModelRegistration, options?: OpenModelOptions,
161
245
  ): Promise<ModelSession>
246
+ export function openModel<T extends ModelTask>(
247
+ input: ModelDescriptor<T> | LocalModelDescriptor<T>, options?: OpenModelOptions<T>,
248
+ ): Promise<ModelSession<T> | LocalModelSession<T>>
package/package.json CHANGED
@@ -1,7 +1,27 @@
1
1
  {
2
2
  "name": "@p2arthur/webinference-sdk",
3
- "version": "0.1.0",
4
- "description": "Inspect and run browser-ready Hugging Face models for chat, image generation, and text classification.",
3
+ "version": "0.1.1",
4
+ "description": "Run browser-ready models from local files or Hugging Face for chat, image generation, and text classification.",
5
+ "homepage": "https://github.com/p2arthur/webinference-sdk#readme",
6
+ "keywords": [
7
+ "webgpu",
8
+ "webassembly",
9
+ "browser-inference",
10
+ "local-ai",
11
+ "on-device-ai",
12
+ "gemma",
13
+ "litert-lm",
14
+ "onnx",
15
+ "image-generation",
16
+ "text-classification"
17
+ ],
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/p2arthur/webinference-sdk.git"
21
+ },
22
+ "bugs": {
23
+ "url": "https://github.com/p2arthur/webinference-sdk/issues"
24
+ },
5
25
  "type": "module",
6
26
  "exports": {
7
27
  ".": {
@@ -11,7 +31,7 @@
11
31
  }
12
32
  },
13
33
  "types": "./index.d.ts",
14
- "files": ["dist", "index.d.ts", "third-party-licenses"],
34
+ "files": ["dist", "index.d.ts", "third-party-licenses", "CHANGELOG.md"],
15
35
  "publishConfig": {
16
36
  "access": "public",
17
37
  "registry": "https://registry.npmjs.org/"
@@ -21,6 +41,9 @@
21
41
  "build": "vite build",
22
42
  "prepack": "npm run build",
23
43
  "test": "node --test",
44
+ "examples": "npm run build && vite --config examples/vite.config.js",
45
+ "examples:build": "npm run build && vite build --config examples/vite.config.js",
46
+ "benchmark": "npm run build && node scripts/benchmark-browser.mjs",
24
47
  "refresh:catalog": "node scripts/refresh-model-catalog.mjs"
25
48
  },
26
49
  "engines": {
@@ -31,6 +54,7 @@
31
54
  "@litert-lm/core": "0.20.0",
32
55
  "@noble/hashes": "2.0.1",
33
56
  "onnxruntime-web": "1.31.1",
57
+ "playwright-core": "1.65.1",
34
58
  "vite": "8.4.0"
35
59
  }
36
60
  }
@@ -1,15 +0,0 @@
1
- // src/inference.worker.js?worker&inline
2
- var e = "(function(){var e=class extends Error{constructor(){super(`LiteRT-LM is not initialized yet. Please call loadLiteRtLm() and wait for its promise to resolve to load the LiteRT-LM WASM module.`)}};let t,n;function r(){if(!t)throw new e;return t}function i(e){t=e}function a(){return n}function o(){return!!n}function s(e){n=e}var c=class{liteRtLmWasm;static DEFAULT_WASM_PATH=`https://cdn.jsdelivr.net/npm/@litert-lm/core@0.20.0/wasm`;constructor(e){this.liteRtLmWasm=e,this.liteRtLmWasm.setupLogging()}async setupDefaultWebGpuDevice(){this.liteRtLmWasm.preinitializedWebGPUDevice||(this.liteRtLmWasm.preinitializedWebGPUDevice=await u())}delete(){}};let l=[`shader-f16`,`subgroups`];async function u(){let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`No GPU adapter found.`);let t={maxBufferSize:e.limits.maxBufferSize,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxStorageBuffersPerShaderStage:e.limits.maxStorageBuffersPerShaderStage,maxTextureDimension2D:e.limits.maxTextureDimension2D},n=[];for(let t of l)e.features.has(t)&&n.push(t);return await e.requestDevice({requiredFeatures:n,requiredLimits:t})}async function d(e){if(typeof importScripts==`function`)importScripts(e.toString());else{let t=document.createElement(`script`);return t.src=e.toString(),t.crossOrigin=`anonymous`,new Promise((e,n)=>{t.addEventListener(`load`,()=>{e()},!1),t.addEventListener(`error`,e=>{n(e)},!1),document.body.appendChild(t)})}}var f=async(e,t,n,r,i)=>{if(t&&await d(t),!self.ModuleFactory||n&&(await d(n),!self.ModuleFactory))throw Error(`ModuleFactory not set.`);if(self.Module&&i){let e=self.Module;e.locateFile=i.locateFile,i.mainScriptUrlOrBlob&&(e.mainScriptUrlOrBlob=i.mainScriptUrlOrBlob)}let a=await self.ModuleFactory(self.Module||i);return self.ModuleFactory=self.Module=void 0,new e(a,r)};function p(e){return e}function m(e,t){return e?t?(e.endsWith(`/`)?e:e+`/`)+(t.startsWith(`/`)?t.substring(1):t):e:t}let h=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,15,1,13,0,65,1,253,15,65,2,253,15,253,128,2,11]),ee=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]),g={relaxedSimd:void 0,threads:void 0,jspi:void 0};function te(){return`Suspending`in WebAssembly}async function _(e){try{return await WebAssembly.instantiate(e),{supported:!0}}catch(e){return{supported:!1,error:e}}}let ne={relaxedSimd:()=>(g.relaxedSimd===void 0&&(g.relaxedSimd=_(h)),g.relaxedSimd),threads:()=>{if(g.threads===void 0)try{typeof MessageChannel<`u`&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),g.threads=_(ee)}catch(e){g.threads=Promise.resolve({supported:!1,error:e})}return g.threads},jspi:()=>{if(g.jspi===void 0)try{let e=te();g.jspi=Promise.resolve({supported:e,error:e?void 0:/* @__PURE__ */ Error(`JSPI is not supported`)})}catch(e){g.jspi=Promise.resolve({supported:!1,error:e})}return g.jspi}};async function v(e){let t=ne[e]?.();if(!t)throw Error(`Unknown feature: ${e}`);return(await t).supported}async function re(e,t){let n=p(e),r=await v(`relaxedSimd`),i=await v(`jspi`),a=``;a=r?i?`litertlm_wasm_internal.js`:`litertlm_wasm_asyncify_internal.js`:i?`litertlm_wasm_compat_internal.js`:`litertlm_wasm_compat_asyncify_internal.js`;let o=e;if(n.endsWith(`.wasm`))throw Error(\"Please load the `.js` file corresponding to the `.wasm` file, or load the directory containing it.\");return n.endsWith(`.js`)||(o=m(e,a)),f(c,o)}let y;function b(e,t){if(o())throw Error(`LiteRT-LM is already loading / loaded.`);return s(re(e,t).then(async e=>(i(e),e)).catch(e=>{throw s(void 0),e})),a()}function ie(e){let t=a();if(t){if(e&&y!==e)throw Error(`LiteRT-LM is already loading / loaded with a different path ${y} but was requested to load ${e}. To reload with a different path, call unloadLiteRtLm() first.`);return t}return y=e??c.DEFAULT_WASM_PATH,t??b(y)}var ae=class{ranges=[];add(e,t){if(e>=t)return;let n=this.firstIndexWhereEndIsAtLeast(e),r=n;for(;r<this.ranges.length&&this.ranges[r][0]<=t;)e=Math.min(e,this.ranges[r][0]),t=Math.max(t,this.ranges[r][1]),r++;this.ranges.splice(n,r-n,[e,t])}overlapping(e,t){let n=[];for(let r=this.firstIndexWhereEndIsAtLeast(e+1);r<this.ranges.length&&this.ranges[r][0]<t;r++)n.push(this.ranges[r]);return n}covers(e,t){if(e>=t)return!0;let n=this.firstIndexWhereEndIsAtLeast(t);return n<this.ranges.length&&this.ranges[n][0]<=e}gaps(e,t){let n=[],r=e;for(let[i,a]of this.overlapping(e,t))i>r&&n.push([r,i]),r=Math.max(r,a);return r<t&&n.push([r,t]),n}firstIndexWhereEndIsAtLeast(e){let t=0,n=this.ranges.length;for(;t<n;){let r=t+n>>>1;this.ranges[r][1]<e?t=r+1:n=r}return t}},oe=class{getWasmHeap;bytesPerSlice;slices=/* @__PURE__ */ new Map;discarded=new ae;freeBuffers=[];reader;leftover;byobScratch;streamPosition=0;streamLength;cachedBytes=0;peakCachedBytes=0;warnedAboutCacheSize=!1;maxCachedBytes;warnCachedBytes;isReading=!1;closed=!1;failure;constructor(e,t,n=1e7,r={}){if(this.getWasmHeap=t,this.bytesPerSlice=n,!Number.isSafeInteger(n)||n<=0)throw Error(`bytesPerSlice must be a positive integer, got ${n}`);this.maxCachedBytes=r.maxCachedBytes??1/0,this.warnCachedBytes=r.warnCachedBytes??1e9;try{this.reader={byobReader:e.getReader({mode:`byob`})}}catch{this.reader={defaultReader:e.getReader()}}}async readAndDiscard(e,t,n){try{return await this.read(e>>>0,x(t),x(n),!0),{}}catch(e){return{error:S(e)}}}async readAndPreserve(e,t,n){try{return await this.read(e>>>0,x(t),x(n),!1),{}}catch(e){return{error:S(e)}}}discard(e,t){try{let n=x(e),r=x(t);return r>0&&this.discardRange(n,n+r),{}}catch(e){return{error:S(e)}}}close(){this.closed||(this.closed=!0,this.slices.clear(),this.freeBuffers.length=0,this.cachedBytes=0,this.leftover=void 0,this.byobScratch=void 0,(this.reader.byobReader??this.reader.defaultReader).cancel().catch(()=>{}))}getStats(){return{streamPosition:this.streamPosition,cachedBytes:this.cachedBytes,peakCachedBytes:this.peakCachedBytes}}async read(e,t,n,r){if(this.checkUsable(),this.isReading)throw Error(`Concurrent reads are not supported`);if(n<=0)return;let i=t+n;this.checkNotDiscarded(t,i),this.isReading=!0;try{this.streamPosition<t&&await this.consume(t-this.streamPosition,(e,t)=>{this.cache(e,t)});let n=Math.min(this.streamPosition,i);for(let{index:r,start:i,end:a}of this.sliceViews(t,n)){let n=this.slices.get(r);if(!n)throw Error(`No cached data for [${i}, ${a})`);let o=r*this.bytesPerSlice;this.getWasmHeap().set(n.subarray(i-o,a-o),e+i-t)}let a=Math.max(t,this.streamPosition);a<i&&await this.consume(i-a,(n,i)=>{this.getWasmHeap().set(n,e+i-t),r||this.cache(n,i)}),r&&this.discardRange(t,i)}finally{this.isReading=!1}}async consume(e,t){try{let n=e;for(;n>0;){let e=await this.readChunk(n);if(this.closed)throw Error(`ReadableStreamDataStreamWrapper was closed`);if(!e)throw this.streamLength=this.streamPosition,Error(`Read from stream returned early EOF at position ${this.streamPosition}. Expected ${n} more bytes.`);t(e,this.streamPosition),this.streamPosition+=e.length,n-=e.length}}catch(e){throw this.failure??=S(e),e}}async readChunk(e){for(;;)if(this.reader.byobReader){this.byobScratch??=/* @__PURE__ */ new ArrayBuffer(4194304);let t=new Uint8Array(this.byobScratch,0,Math.min(e,this.byobScratch.byteLength)),{done:n,value:r}=await this.reader.byobReader.read(t);if(this.byobScratch=r?.buffer,r&&r.byteLength>0)return r;if(n)return}else{let t=this.leftover;if(this.leftover=void 0,!t){let{done:e,value:n}=await this.reader.defaultReader.read();if(e)return;t=n}if(t.length>e)return this.leftover=t.subarray(e),t.subarray(0,e);if(t.length>0)return t}}cache(e,t){let n=t+e.length;for(let[r,i]of this.discarded.gaps(t,n))for(let{index:n,start:a,end:o}of this.sliceViews(r,i))(this.slices.get(n)??this.allocateSlice(n)).set(e.subarray(a-t,o-t),a-n*this.bytesPerSlice)}allocateSlice(e){let t=this.cachedBytes+this.bytesPerSlice;if(t>this.maxCachedBytes)throw Error(`Reading position ${this.streamPosition} would cache ${t} bytes, more than ${this.maxCachedBytes} allowed. The model is being read too far out of order.`);let n=this.freeBuffers.pop()??new Uint8Array(this.bytesPerSlice);return this.slices.set(e,n),this.cachedBytes=t,this.peakCachedBytes=Math.max(this.peakCachedBytes,t),!this.warnedAboutCacheSize&&t>this.warnCachedBytes&&(this.warnedAboutCacheSize=!0,console.warn(`Streamed model loading has cached ${t} bytes because the model is being read out of order.`)),n}discardRange(e,t){this.discarded.add(e,t);for(let{index:n}of this.sliceViews(e,t)){let e=this.slices.get(n);if(!e)continue;let t=n*this.bytesPerSlice,r=Math.min(t+this.bytesPerSlice,this.streamLength??1/0);this.discarded.covers(t,r)&&(this.slices.delete(n),this.cachedBytes-=this.bytesPerSlice,this.freeBuffers.length<2&&this.freeBuffers.push(e))}}checkUsable(){if(this.closed)throw Error(`ReadableStreamDataStreamWrapper is closed`);if(this.failure)throw Error(`Reading from the stream previously failed: ${this.failure.message}`)}checkNotDiscarded(e,t){let n=C(this.discarded,e,t);if(n)throw n}*sliceViews(e,t){let n=e;for(;n<t;){let e=Math.floor(n/this.bytesPerSlice),r=Math.min((e+1)*this.bytesPerSlice,t);yield{index:e,start:n,end:r},n=r}}};function x(e){if(typeof e==`number`)return e;if(e>2**53-1)throw Error(`BigInt value ${e} too large to be represented as a number`);return Number(e)}function S(e){return e instanceof Error?e:Error(String(e))}function C(e,t,n){let r=e.overlapping(t,n);if(r.length!==0)return/* @__PURE__ */ Error(`Read of [${t}, ${n}) overlaps discarded regions: [${r.map(([e,t])=>`[${e}, ${t}]`).join(`, `)}]`)}let w={UNSPECIFIED:0,GPU_ARTISAN:1,CPU:2,GPU:3,GOOGLE_TENSOR_ARTISAN:4,NPU:5};function T(e){if(e instanceof Error)throw e;return e}function se(e){if(e.lenience!==void 0&&!(e.lenience>=0&&e.lenience<=1))throw Error(`lenience must be in [0, 1] or undefined, but got ${e.lenience}.`);return{mode:e.mode===void 0?void 0:{value:e.mode},lenience:e.lenience}}function ce(e){let t={};return e.mode!==void 0&&(t.mode=e.mode.value),e.lenience!==void 0&&(t.lenience=e.lenience),t}function E(){let e=globalThis.navigator;return{caches:globalThis.caches,storageBuckets:e?.storageBuckets,storage:e?.storage,locks:e?.locks,fetch:(e,t)=>globalThis.fetch(e,t),baseUrl:globalThis.document?.baseURI??globalThis.location?.href}}let D=`hf://`,le=/^refs\\/(pr\\/\\d+|convert\\/\\w+)(?=\\/|$)/;function O(e){if(!e.startsWith(D))return;let t=/^([^/@]+)\\/([^/@]+)(@?)(.*)$/.exec(e.slice(5));if(!t)return;let[,n,r,i]=t,a=t[4];if(n===`datasets`||n===`spaces`)return;let o={repo:`${n}/${r}`};if(i){let e=le.exec(a)?.[0]??a.split(`/`)[0];a=a.slice(e.length);let t;try{t=decodeURIComponent(e)}catch{return}if(!t)return;o.revision=t}let s=a.slice(1);return s&&(o.path=s),o}function k(e){let t=e.revision===void 0?``:`@${encodeURIComponent(e.revision)}`,n=e.path?`/${e.path}`:``;return`${D}${e.repo}${t}${n}`}let A=`https://huggingface.co`;async function ue(e,t={}){let n=typeof e==`string`?O(e):e;if(!n)throw Error(`Not a Hugging Face model URI: ${e}`);let{repo:r,path:i}=n,a=n.revision===void 0?t.defaultRevisions??[`main`]:[n.revision];if(a.length===0)throw Error(`defaultRevisions must not be empty`);let o=a.map(e=>de(r,e,i,t));for(let e of o)e.catch(()=>{});let s,c;for(let[e,t]of o.entries())if(c=await t,c!==void 0){s=a[e];break}if(s===void 0||c===void 0)throw Error(`Couldn't resolve ${k({repo:r,path:i})}: no revision named ${a.map(e=>`'${e}'`).join(` or `)} exists`);let{commit:l,files:u}=c,d=k({repo:r,revision:s,path:i}),f;if(i){if(f=u.find(e=>e.path===i),!f)throw Error(`${d} doesn't exist`)}else{if(!t.selectFile)throw Error(`${d} doesn't give a file path`);let e=u.filter(e=>!e.path.includes(`/`));if(f=t.selectFile(e,s),!f)throw Error(`No suitable model file in ${d}. Its files are: ${e.map(e=>e.path).join(`, `)}`)}let p={url:`${A}/${j(r)}/resolve/${l}/${j(f.path)}`,size:f.size};return f.sha256!==void 0&&(p.sha256=f.sha256),t.accessToken&&(p.accessToken=t.accessToken),{source:p,repo:r,revision:s,commit:l,path:f.path}}async function de(e,t,n,r){let i=k({repo:e,revision:t,path:n}),a=await fe(`${A}/api/models/${j(e)}/revision/${encodeURIComponent(t)}?blobs=true`,r);if(a.status===404&&a.headers.get(`X-Error-Code`)===`RevisionNotFound`)return;pe(a,i);let o=await a.json();if(!o.sha)throw Error(`The Hugging Face Hub didn't return a commit for ${i}`);let s=[];for(let e of o.siblings??[]){if(e.rfilename===void 0)continue;let t={path:e.rfilename,size:e.lfs?.size??e.size??0};e.lfs?.sha256!==void 0&&(t.sha256=e.lfs.sha256),s.push(t)}return{commit:o.sha,files:s}}async function fe(e,t){let n={};return t.signal&&(n.signal=t.signal),t.accessToken&&(n.headers={Authorization:`Bearer ${t.accessToken}`}),E().fetch(e,n)}function pe(e,t){if(e.ok)return;let n=e.headers.get(`X-Error-Message`)??`${e.status} ${e.statusText}`;throw e.status===401||e.status===403?Error(`Couldn't access ${t}: ${n}. The repo may not exist, or it may be private or gated, which needs the access token of a user who can access it (e.g. from Sign in with Hugging Face).`):Error(`Couldn't resolve ${t}: ${n}`)}function j(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function me(e){if(e.startsWith(`hf://`))throw Error(`Resolve hf:// URIs with resolveHuggingFaceModel() first: ${e}`);return new URL(e,E().baseUrl).href}async function he(e,t,n){n?.throwIfAborted();let r=typeof e==`string`?{url:e}:e instanceof Blob||e instanceof ReadableStream?void 0:e;if(!r?.url.startsWith(`hf://`))return{model:e,checkBackend:()=>{}};let i=O(r.url);if(!i)throw Error(`Invalid Hugging Face model URI: ${r.url}. Expected hf://<org>/<repo>[@<revision>][/<path>]`);let a={selectFile:(e,n)=>{let r=k({repo:i.repo,revision:n}),a=be(e,i.repo,t);if(!a)throw Error(Se(r,e,t));return a.others.length>0&&console.warn(`Loading ${r}/${a.file.path}. Other model files in the repo, which can be loaded by URI: ${a.others.map(e=>`${r}/${e.path}`).join(`, `)}`),a.file}};r.accessToken&&(a.accessToken=r.accessToken),n&&(a.signal=n),i.repo.toLowerCase().startsWith(`litert-community/`)&&(a.defaultRevisions=[`web`,`main`]);let o=await ue(i,a),s={...o.source},c=k(o);if(r.sha256!==void 0){let e=r.sha256.toLowerCase();if(s.sha256!==void 0&&s.sha256!==e)throw Error(`${c} has SHA-256 ${s.sha256}, not ${e}`);s.sha256=e}if(r.size!==void 0&&r.size!==s.size)throw Error(`${c} is ${s.size} bytes, not ${r.size} bytes`);return r.cacheKey!==void 0&&(s.cacheKey=r.cacheKey),{model:s,huggingFace:o,checkBackend:e=>{Ce(o,t,e)}}}let ge=/(^|[-_.])(google_tensor|intel|qualcomm|mediatek|npu)([-_.]|$)/i,_e=/-web\\.litertlm$/i,M=/-gpu\\.litertlm$/i,ve=/[-_](litert[-_]?lm|litert)$/i,ye=/int4/i;function be(e,t,n){let r=e.filter(e=>e.path.toLowerCase().endsWith(`.litertlm`)&&!ge.test(e.path)&&!_e.test(e.path)),i=r.filter(e=>M.test(e.path)),a=r.filter(e=>!M.test(e.path)),[o,...s]=xe(n===w.GPU_ARTISAN||n===void 0&&i.length>0?i:a,i,t);return o?{file:o,others:s}:void 0}function xe(e,t,n){let r=new Set(t.map(e=>e.path.toLowerCase().replace(M,`.litertlm`))),i=n.slice(n.indexOf(`/`)+1).replace(ve,``).toLowerCase(),a=e=>{let t=e.path.toLowerCase(),n=t.replace(M,``).replace(/\\.litertlm$/,``);return[+!r.has(t),n===i?0:1,n===`model`?0:1,+!ye.test(n),t.length]},o=e.map(e=>({file:e,key:a(e)}));return o.sort((e,t)=>{for(let n=0;n<e.key.length;n++)if(e.key[n]!==t.key[n])return e.key[n]-t.key[n];return e.file.path<t.file.path?-1:+(e.file.path>t.file.path)}),o.map(({file:e})=>e)}function Se(e,t,n){let r=t.map(e=>e.path).filter(e=>/\\.litertlm$/i.test(e)),i=n===void 0?``:` for ${N(n)}`;return r.length===0?`${e} has no .litertlm model file${i}`:`${e} has no suitable model file${i}. Add one of ${r.join(`, `)} to the URI, e.g. ${e}/${r[0]}`}function Ce(e,t,n){if(t!==void 0&&t!==n)throw Error(`${k(e)} is a ${N(n)} model, but ${N(t)} was requested. Choose another file, or leave \\`backend\\` unset to use the model's backend.`)}function N(e){let t=Object.entries(w).find(([,t])=>t===e)?.[0];return t===void 0?`backend ${e}`:`Backend.${t}`}function P(e){let t=Array(e.size());for(let n=0;n<e.size();++n)t[n]=e.get(n);return e.delete(),t}function F(e,t){for(let n of e)t.push_back(n)}function we(e,t,n,i=r().liteRtLmWasm){let a=e.getMutableMainExecutorSettings();if(a.setCacheDir(`:nocache`),t.benchmarkEnabled&&e.enableBenchmark(),t.activationDataType!==void 0&&a.setActivationDataType({value:t.activationDataType}),t.visionActivationDataType!==void 0&&e.getMutableVisionExecutorSettings()?.setActivationDataType({value:t.visionActivationDataType}),t.audioActivationDataType!==void 0&&e.getMutableAudioExecutorSettings()?.setActivationDataType({value:t.audioActivationDataType}),t.maxVisionTokensPerImage!==void 0&&e.setMaxVisionTokensPerImage(t.maxVisionTokensPerImage),t.minVisionTokensPerImage!==void 0&&e.setMinVisionTokensPerImage(t.minVisionTokensPerImage),t.mainExecutorSettings){let e=t.mainExecutorSettings;if(e.maxNumTokens!==void 0&&a.setMaxNumTokens(e.maxNumTokens),e.maxNumImages!==void 0&&a.setMaxNumImages(e.maxNumImages),e.samplerBackend!==void 0&&a.setSamplerBackend({value:e.samplerBackend}),e.backendConfig!==void 0){let t=e.backendConfig;if(n===w.CPU){let e=t,n={kv_increment_size:e.kv_increment_size??0,prefill_chunk_size:e.prefill_chunk_size??0,number_of_threads:e.number_of_threads??0};a.setBackendConfigCpu(n)}else if(n===w.GPU){let e=t,n={max_top_k:e.max_top_k??1,external_tensor_mode:e.external_tensor_mode??!1};a.setBackendConfigGpu(n)}else if(n===w.GPU_ARTISAN){let e=t,n=new i.VectorUint32;F(e.supported_lora_ranks??[],n);let r={num_output_candidates:e.num_output_candidates??1,wait_for_weight_uploads:e.wait_for_weight_uploads??!0,num_decode_steps_per_sync:e.num_decode_steps_per_sync??1,sequence_batch_size:e.sequence_batch_size??0,supported_lora_ranks:n,max_top_k:e.max_top_k??1,enable_decode_logits:e.enable_decode_logits??!1,enable_external_embeddings:e.enable_external_embeddings??!1,use_submodel:e.use_submodel??!0,use_autosized_ringbuffers:e.use_autosized_ringbuffers??!0};a.setBackendConfigGpuArtisan(r),n.delete()}}if(e.advancedSettings!==void 0){let t={...a.getAdvancedSettings()??i.createDefaultAdvancedSettings(),...e.advancedSettings};a.setAdvancedSettings(t)}}t.speculativeDecodingConfig!==void 0&&e.setSpeculativeDecodingConfig(se(t.speculativeDecodingConfig))}function Te(e,t=r().liteRtLmWasm){let n=e.getMutableMainExecutorSettings(),i,a,o=n.getBackendConfigCpu();if(!(o instanceof Error))i=o,a=w.CPU;else{let e=n.getBackendConfigGpu();if(!(e instanceof Error))i=e,a=w.GPU;else{let e=n.getBackendConfigGpuArtisan();if(e instanceof Error)throw Error(`Unsupported backend config`);i={...e,supported_lora_ranks:P(e.supported_lora_ranks)},a=w.GPU_ARTISAN}}let s=e.getMutableVisionExecutorSettings(),c=e.getMutableAudioExecutorSettings();return{backend:a,activationDataType:n.getActivationDataType()?.value,visionBackend:e.getVisionBackend()?.value,visionActivationDataType:s?.getActivationDataType()?.value,maxVisionTokensPerImage:e.getMaxVisionTokensPerImage(),minVisionTokensPerImage:e.getMinVisionTokensPerImage(),audioBackend:e.getAudioBackend()?.value,audioActivationDataType:c?.getActivationDataType()?.value,mainExecutorSettings:{maxNumTokens:n.getMaxNumTokens(),maxNumImages:n.getMaxNumImages(),samplerBackend:n.getSamplerBackend().value,backendConfig:i,advancedSettings:n.getAdvancedSettings()??t.createDefaultAdvancedSettings()},benchmarkEnabled:!1,speculativeDecodingConfig:ce(e.getSpeculativeDecodingConfig())}}var Ee=class{callbacks=/* @__PURE__ */ new Set;add(e){return this.callbacks.add(e),()=>{this.callbacks.delete(e),e()}}run(){for(let e of this.callbacks)e();this.callbacks.clear()}};let I=`Conversation is busy. A generation is already in progress.`;var De=class e{conversation;engine;mutexes;visualTokenBudget;isBusy=!1;constructor(e,t,n,r=0){this.conversation=e,this.engine=t,this.mutexes=n,this.visualTokenBudget=r}async sendMessage(e){if(this.isBusy)throw Error(I);this.isBusy=!0;try{let{json:t,blobs:n}=await L(e);return await this.mutexes.executor.acquireAndRun(async()=>{let e=T(await this.conversation.sendMessage(t,n,this.visualTokenBudget));return JSON.parse(e)})}finally{this.isBusy=!1}}sendMessageStreaming(e){if(this.isBusy)throw Error(I);this.isBusy=!0;let t=!1,n=!1;return new ReadableStream({start:r=>{(async()=>{let{json:i,blobs:a}=await L(e);await this.mutexes.executor.acquireAndRun(async()=>{await this.conversation.sendMessageAsync(i,a,(e,i,a)=>{if(!(t||n)){if(a)n=!0,this.isBusy=!1,r.error(Error(a));else if(e)try{let t=JSON.parse(e);r.enqueue(t)}catch(e){n=!0,this.isBusy=!1,r.error(e)}}},this.visualTokenBudget),T(await this.engine.waitUntilDone())}),t||n||(this.isBusy=!1,r.close())})().catch(e=>{t||n||(this.isBusy=!1,r.error(e))})},cancel:()=>{t=!0,this.isBusy=!1,this.cancel()}})}cancel(){this.conversation.cancelProcess()}async getHistory(){return this.mutexes.executor.acquireAndRun(()=>{let e=this.conversation.getHistory();return JSON.parse(e)})}async getTokenCount(){return this.mutexes.executor.acquireAndRun(()=>T(this.conversation.getTokenCount()))}async getBenchmarkInfo(){return this.mutexes.executor.acquireAndRun(()=>this.conversation.getBenchmarkInfo())}async clone(){if(this.isBusy)throw Error(I);this.isBusy=!0;try{return await this.mutexes.executor.acquireAndRun(()=>{let t=T(this.conversation.clone());return new e(t,this.engine,this.mutexes,this.visualTokenBudget)})}finally{this.isBusy=!1}}async delete(){await this.mutexes.executor.acquireAndRun(()=>{this.conversation.delete()})}};async function L(e){let t=[],n=await ke(e,t);return{json:JSON.stringify(n),blobs:t}}function Oe(e){return typeof e==`string`?{role:`user`,content:e}:e}async function ke(e,t){let n=Oe(e);if(!Array.isArray(n.content))return n;let r=[];for(let e of n.content){if(e.type!==`image`&&e.type!==`audio`||!(`data`in e)||e.data===void 0){r.push(e);continue}let{data:n,...i}=e;if(typeof n==`string`){r.push({...i,blob:n});continue}let a=await Ae(n),o=t.length;t.push(a),r.push({...i,blob_index:o})}return{...n,content:r}}async function Ae(e){return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof ArrayBuffer?new Uint8Array(e):e}var R=class{mutexPromise=Promise.resolve();async acquireAndRun(e){let t=this.mutexPromise,n;this.mutexPromise=new Promise(e=>{n=e});try{return await t,await e()}finally{n()}}};let z=/* @__PURE__ */ new WeakMap;function je(e,t){let n=z.get(e);return n||(n=new R,z.set(e,n)),n.acquireAndRun(t)}function B(e,t=r().liteRtLmWasm){let n=t.SessionConfig.createDefault();if(e.audioModalityEnabled!==void 0&&n.setAudioModalityEnabled(e.audioModalityEnabled),e.visionModalityEnabled!==void 0&&n.setVisionModalityEnabled(e.visionModalityEnabled),e.samplerParams!==void 0){let t=n.getMutableSamplerParams();e.samplerParams.type!==void 0&&t.setType({value:e.samplerParams.type}),e.samplerParams.k!==void 0&&t.setK(e.samplerParams.k),e.samplerParams.p!==void 0&&t.setP(e.samplerParams.p),e.samplerParams.temperature!==void 0&&t.setTemperature(e.samplerParams.temperature),e.samplerParams.seed!==void 0&&t.setSeed(e.samplerParams.seed)}if(e.startTokenId!==void 0&&n.setStartTokenId(e.startTokenId),e.numOutputCandidates!==void 0&&n.setNumOutputCandidates(e.numOutputCandidates),e.samplerBackend!==void 0&&n.setSamplerBackend({value:e.samplerBackend}),e.applyPromptTemplateInSession!==void 0&&n.setApplyPromptTemplateInSession(e.applyPromptTemplateInSession),e.useExternalSampler!==void 0&&n.setUseExternalSampler(e.useExternalSampler),e.maxOutputTokens!==void 0&&n.setMaxOutputTokens(e.maxOutputTokens),e.speculativeDecodingConfig!==void 0&&n.setSpeculativeDecodingConfig(se(e.speculativeDecodingConfig)),e.stopTokenIds!==void 0){let r=new t.VectorVectorInt;for(let n of e.stopTokenIds){let e=new t.VectorInt;F(n,e),r.push_back(e),e.delete()}n.setStopTokenIds(r),r.delete()}return n}function Me(e){let t=e.getMutableSamplerParams();return{audioModalityEnabled:e.getAudioModalityEnabled(),visionModalityEnabled:e.getVisionModalityEnabled(),samplerParams:{type:t.type().value,k:t.k(),p:t.p(),temperature:t.temperature(),seed:t.seed()},stopTokenIds:P(e.getStopTokenIds()).map(P),startTokenId:e.getStartTokenId(),numOutputCandidates:e.getNumOutputCandidates(),samplerBackend:e.getSamplerBackend().value,applyPromptTemplateInSession:e.getApplyPromptTemplateInSession(),useExternalSampler:e.getUseExternalSampler(),maxOutputTokens:e.getMaxOutputTokens(),speculativeDecodingConfig:ce(e.getSpeculativeDecodingConfig())}}let V=`Session is busy. An operation is already in progress.`;var Ne=class e{session;mutexes;config;isBusy=!1;constructor(e,t){this.session=e,this.mutexes=t;let n=e.getSessionConfig();this.config=Me(n),n.delete()}async runPrefill(e){if(this.isBusy)throw Error(V);this.isBusy=!0;try{await this.mutexes.executor.acquireAndRun(async()=>{T(await this.session.runPrefill(e))})}finally{this.isBusy=!1}}async runDecode(){if(this.isBusy)throw Error(V);this.isBusy=!0;try{return await this.mutexes.executor.acquireAndRun(async()=>new Pe(T(await this.session.runDecode())))}finally{this.isBusy=!1}}cancel(){this.session.cancelProcess()}async clone(){if(this.isBusy)throw Error(V);this.isBusy=!0;try{return await this.mutexes.executor.acquireAndRun(()=>{let t=T(this.session.clone());return new e(t,this.mutexes)})}finally{this.isBusy=!1}}async delete(){await this.mutexes.executor.acquireAndRun(()=>{this.session.delete()})}},Pe=class{responses;constructor(e){this.responses=e}getTexts(){return P(this.responses.getTexts())}delete(){this.responses.delete()}},Fe=class{blob;getWasmHeap;discarded=new ae;maxBytesPerRead;isReading=!1;constructor(e,t,n={}){if(this.blob=e,this.getWasmHeap=t,this.maxBytesPerRead=n.maxBytesPerRead??16777216,!Number.isSafeInteger(this.maxBytesPerRead)||this.maxBytesPerRead<=0)throw Error(`maxBytesPerRead must be a positive integer, got ${this.maxBytesPerRead}`)}readAndDiscard(e,t,n){return this.read(e,t,n,!0)}readAndPreserve(e,t,n){return this.read(e,t,n,!1)}discard(e,t){try{let n=x(e);return this.discarded.add(n,n+x(t)),{}}catch(e){return{error:S(e)}}}close(){}async read(e,t,n,r){try{let i=e>>>0,a=x(t),o=a+x(n);if(this.isReading)throw Error(`Concurrent reads are not supported`);if(o<=a)return{};if(o>this.blob.size)throw Error(`Read of [${a}, ${o}) exceeds the model size of ${this.blob.size} bytes`);this.checkNotDiscarded(a,o),this.isReading=!0;try{for(let e=a;e<o;e+=this.maxBytesPerRead){let t=Math.min(e+this.maxBytesPerRead,o),n=new Uint8Array(await this.blob.slice(e,t).arrayBuffer());if(n.length!==t-e)throw Error(`Read of [${e}, ${t}) returned ${n.length} bytes`);this.getWasmHeap().set(n,i+e-a)}}finally{this.isReading=!1}return r&&this.discarded.add(a,o),{}}catch(e){return{error:S(e)}}}checkNotDiscarded(e,t){let n=C(this.discarded,e,t);if(n)throw n}};async function Ie(e){if(e instanceof ReadableStream)return e;if(e instanceof Blob)return e.stream();let t=typeof e==`string`?{url:e}:e,n={credentials:`same-origin`};t.accessToken&&(n.headers={Authorization:`Bearer ${t.accessToken}`});let r=await fetch(me(t.url),n);if(!r.ok)throw Error(`Failed to fetch model file from ${t.url}`);return r.body}async function Le(e,t,n){let r=e instanceof Blob?new Fe(e,()=>t.HEAPU8):new oe(await Ie(e),()=>t.HEAPU8),i=t.ReadableStreamDataStream.create(r);n.add(()=>{i.delete(),r.close()});let a=T(t.ModelAssets.createStreaming(i));return{modelAssets:a,cleanupModelAssets:n.add(()=>{a.delete()})}}var Re=class e{wasm;engine;deleteCallback;settings;mutexes={executor:new R};constructor(e,t,n,r){this.wasm=e,this.engine=t,this.deleteCallback=r;let i=t.getEngineSettings(),a=Te(i,e);this.settings={...a,model:n},i.delete()}static async create(t,n=``){let[r,i]=await Promise.all([ie(),he(t.model,t.backend)]);return je(r.liteRtLmWasm,()=>e.createExclusive(r,t,i,n))}static async createExclusive(t,n,r,i){let a=t.liteRtLmWasm,o=n.backend??w.GPU;n={...n,backend:o};let s=n.mainExecutorSettings?.samplerBackend,c=n.visionBackend,l=n.audioBackend;(o===w.GPU||o===w.GPU_ARTISAN||s===w.GPU||s===w.GPU_ARTISAN||c===w.GPU||l===w.GPU)&&await t.setupDefaultWebGpuDevice();let u=new Ee,d;try{let{modelAssets:t,cleanupModelAssets:s}=await Le(r.model,a,u),f=c===void 0&&l===void 0?await a.EngineSettings.createDefault(t,{value:o}):await a.EngineSettings.createDefaultMultimodal(t,{value:o},c===void 0?void 0:{value:c},l===void 0?void 0:{value:l});s();let p=T(f),m=u.add(()=>{p.delete()}),h=p.getMutableMainExecutorSettings().getBackend().value;return r.checkBackend(h),we(p,n,h,a),p.setParallelFileSectionLoading(!1),p.setSingleThreadedExecution(!0),d=h===w.GPU_ARTISAN?T(await a.Engine.createLegacyEngine(p,i)):T(await a.Engine.createEngine(p,i)),m(),u.add(()=>{d.delete()}),new e(a,d,n.model,()=>u.run())}catch(e){throw u.run(),e}}withDefaultModalities(e){let t={...e};return this.settings.visionBackend!==void 0&&t.visionModalityEnabled===void 0&&(t.visionModalityEnabled=!0),this.settings.audioBackend!==void 0&&t.audioModalityEnabled===void 0&&(t.audioModalityEnabled=!0),t}async createSession(e={}){return this.mutexes.executor.acquireAndRun(()=>{let t=B(this.withDefaultModalities(e),this.wasm),n=this.engine.createSession(t);return t.delete(),new Ne(T(n),this.mutexes)})}async createConversation(e){return e||this.settings.visionBackend===void 0&&this.settings.audioBackend===void 0||(e={filterChannelContentFromKvCache:!0}),this.mutexes.executor.acquireAndRun(async()=>{let t,n;if(e){n=B(this.withDefaultModalities(e.sessionConfig||{}),this.wasm);let r=e.preface?JSON.stringify(e.preface):``,i=this.settings.backend===w.GPU_ARTISAN&&!!this.settings.mainExecutorSettings?.backendConfig?.use_autosized_ringbuffers,a=e.filterChannelContentFromKvCache??i;t=this.wasm.ConversationConfig.createCustom(this.engine,n,!!e.enableConstrainedDecoding,!!e.prefillPrefaceOnInit,a,r)}else t=this.wasm.ConversationConfig.createDefault(this.engine);let r;try{let e=T(t);try{r=T(await this.wasm.Conversation.create(this.engine,e))}finally{e.delete()}}finally{n?.delete()}return new De(r,this.engine,this.mutexes,this.settings.maxVisionTokensPerImage??0)})}async delete(){await this.mutexes.executor.acquireAndRun(()=>{this.deleteCallback()})}};\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nfunction ze(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function H(e,t,n=``){let r=ze(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`\"${n}\" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function U(e,t=!0){if(e.destroyed)throw Error(`Hash instance has been destroyed`);if(t&&e.finished)throw Error(`Hash#digest() has already been called`)}function Be(e,t){H(e,void 0,`digestInto() output`);let n=t.outputLen;if(e.length<n)throw Error(`\"digestInto() output\" expected to be of length >=`+n)}function W(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function G(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function K(e,t){return e<<32-t|e>>>t}let Ve=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,He=/* @__PURE__ */ Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Ue(e){if(H(e),Ve)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=He[e[n]];return t}function We(e,t={}){let n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}let Ge=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Ke(e,t,n){return e&t^~e&n}function qe(e,t,n){return e&t^e&n^t&n}var Je=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=G(this.buffer)}update(e){U(this),H(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let a=0;a<i;){let o=Math.min(r-this.pos,i-a);if(o===r){let t=G(e);for(;r<=i-a;a+=r)this.process(t,a)}else n.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){U(this),Be(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,W(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(n,0),a=0);for(let e=a;e<r;e++)t[e]=0;n.setBigUint64(r-8,BigInt(this.length*8),i),this.process(n,0);let o=G(e),s=this.outputLen;if(s%4)throw Error(`_sha2: outputLen must be aligned to 32bit`);let c=s/4,l=this.get();if(c>l.length)throw Error(`_sha2: outputLen bigger than state`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}};let q=/* @__PURE__ */ Uint32Array.from([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,528734635,0x5be0cd19]),Ye=/* @__PURE__ */ Uint32Array.from([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,961987163,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,310598401,607225278,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,604807628,770255983,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,338241895,666307205,773529912,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,275423344,430227734,506948616,659060556,883997877,958139571,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),J=/* @__PURE__ */ new Uint32Array(64);var Xe=class extends Je{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}process(e,t){for(let n=0;n<16;n++,t+=4)J[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=J[e-15],n=J[e-2],r=K(t,7)^K(t,18)^t>>>3,i=K(n,17)^K(n,19)^n>>>10;J[e]=i+J[e-7]+r+J[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=K(o,6)^K(o,11)^K(o,25),u=l+t+Ke(o,s,c)+Ye[e]+J[e]|0,d=(K(n,2)^K(n,13)^K(n,22))+qe(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){W(J)}destroy(){this.set(0,0,0,0,0,0,0,0),W(this.buffer)}},Ze=class extends Xe{A=q[0]|0;B=q[1]|0;C=q[2]|0;D=q[3]|0;E=q[4]|0;F=q[5]|0;G=q[6]|0;H=q[7]|0;constructor(){super(32)}};let Qe=/* @__PURE__ */ We(()=>new Ze,/* @__PURE__ */ Ge(1)),$e=/^[\\w.-]+\\/[\\w.-]+$/,et=/^[a-f0-9]{40}$/,Y=/^[a-f0-9]{64}$/,X=/^(?!.*(?:^|\\/)\\.{1,2}(?:\\/|$))[\\w.@-]+(?:\\/[\\w.@-]+)*$/,tt={\"litert-chat\":{task:`chat`},\"onnx-chat\":{task:`chat`},\"laya-choice\":{task:`classification`},\"janus-image\":{task:`image`},\"sd-turbo\":{task:`image`}},nt=[`config.json`,`tokenizer.json`,`tokenizer_config.json`,`onnx/model_fp16.onnx`,`onnx/model_fp16.onnx_data`],rt=[`config.json`,`tokenizer.json`,`tokenizer_config.json`,`processor_config.json`,`preprocessor_config.json`,`onnx/prepare_inputs_embeds_q4.onnx`,`onnx/language_model_q4f16.onnx`,`onnx/lm_head_fp16.onnx`,`onnx/gen_head_fp16.onnx`,`onnx/gen_img_embeds_fp16.onnx`,`onnx/image_decode.onnx`],it=[`text_encoder/model.onnx`,`unet/model.onnx`,`vae_decoder/model.onnx`],at=[`config.json`,`tokenizer.json`,`tokenizer_config.json`];function ot(e){let t=/^onnx\\/(model|decoder_model_merged)(?:_(q4f16|q4|quantized|fp16))?\\.onnx$/.exec(e);if(t)return{modelFile:t[1],dtype:t[2]===`quantized`?`q8`:t[2]??`fp32`}}function st(e,t){let n=`${e}_data`,r=t.filter(e=>e===n||e.startsWith(`${n}_`)&&/^[1-9]\\d*$/.test(e.slice(n.length+1)));if(!r.length)return[];let i=r.map((e,t)=>t===0?n:`${n}_${t}`);return i.every(e=>r.includes(e))?i:void 0}function ct(e){return typeof e==`string`&&$e.test(e)&&e.split(`/`).every(e=>X.test(e))}function lt(e){return typeof e==`string`&&X.test(e)}function ut(e,t,n){return`https://huggingface.co/${e}/resolve/${t}/${n.split(`/`).map(encodeURIComponent).join(`/`)}`}function dt(e){if(!e||e.version!==1||!Object.hasOwn(tt,e.adapter)||!ct(e.repo)||typeof e.revision!=`string`||!et.test(e.revision)||!Array.isArray(e.files)||e.files.length===0||e.files.length>24||!e.files.every(e=>e&&lt(e.path)&&Number.isSafeInteger(e.size)&&e.size>0&&(e.sha256===void 0||typeof e.sha256==`string`&&Y.test(e.sha256))))return!1;let t=new Set(e.files.map(({path:e})=>e));if(t.size!==e.files.length)return!1;switch(e.adapter){case`litert-chat`:return e.files.length===1&&/\\.litertlm$/i.test(e.files[0].path)&&Y.test(e.files[0].sha256);case`onnx-chat`:{let n=e.files[0].path;return!!(ot(n)&&at.every(e=>t.has(e))&&st(n,[...t]))}case`laya-choice`:return nt.every(e=>t.has(e));case`janus-image`:return rt.every(e=>t.has(e));case`sd-turbo`:return e.repo.toLowerCase()===`schmuell/sd-turbo-ort-web`&&it.every(e=>t.has(e))}}let ft=/* @__PURE__ */ new Map([[`3a08e8d94e23b814ae5414469c370c503813949acb8ceaa17e4ebf8a35af35b5`,4096],[`3904d826d5dddd25ea173e85204caec09e68ba038116e9b992b69cbdc94f57a0`,4096],[`d37f9392b4f093b470b50b72624c9a752cc0b288ed549b769037cbbd04024449`,4096],[`4523b2de695a7f22dc675b716253ba9a8512ca9f4852fb6a682fe4c2eb859c16`,1280],[`5131b21f70265632e7545abe21dc6b52ff6a690779033eef48d368957374035b`,1280]]);function pt(e){if(!dt(e)||e.adapter!==`litert-chat`)throw Error(`Choose a compatible LiteRT-LM browser export.`);let{path:t,size:n,sha256:r}=e.files[0];return{url:ut(e.repo,e.revision,t),size:n,sha256:r,contextTokens:ft.get(r)??1024,disableThinking:/gemma-4/i.test(e.repo)}}let Z,Q,mt=!0;function $(e,t={}){self.postMessage({type:e,...t})}function ht(e){return e?.name===`QuotaExceededError`?`Browser storage is full. Free up space and try again.`:e instanceof Error?e.message:String(e)}function gt(e){return`browser-model-sdk-${e.sha256}.litertlm`}async function _t(e,t){try{let n=await(await e.getFileHandle(gt(t))).getFile();return n.size===t.size?n:void 0}catch(e){if(e.name!==`NotFoundError`)throw e}}function vt(e){let t=Qe.create(),n=4*1024**2,r=new Uint8Array(n),i=0,a=0,o=0;return $(`progress`,{loaded:a}),new TransformStream({transform(s,c){if(a+=s.byteLength,a>e.size)throw Error(`The model file exceeded its expected size.`);t.update(s);let l=performance.now();(l-o>=125||a===e.size)&&($(`progress`,{loaded:a}),o=l);for(let e=0;e<s.length;){let t=Math.min(n-i,s.length-e);r.set(s.subarray(e,e+t),i),e+=t,i+=t,i===n&&(c.enqueue(r),r=new Uint8Array(n),i=0)}},flush(n){if(a!==e.size||Ue(t.digest())!==e.sha256)throw Error(`The model file failed its integrity check. Use a fresh copy of the selected model.`);i&&n.enqueue(r.subarray(0,i))}})}async function yt(e){let t=await navigator.storage.getDirectory(),n=gt(e);return navigator.locks.request(n,async()=>{let r=await _t(t,e);if(r)return r;let i=vt(e),a=await fetch(e.url,{credentials:`omit`,cache:`no-store`});if(!a.ok||!a.body)throw Error(`Couldn't download the model from Hugging Face (HTTP ${a.status}).`);let o=await t.getFileHandle(n,{create:!0}),s=await o.createWritable();return await a.body.pipeThrough(i).pipeTo(s),o.getFile()})}function bt(){return Z.createConversation({...mt?{preface:{extra_context:{enable_thinking:!1}}}:{},sessionConfig:{maxOutputTokens:256}})}async function xt(e){let t=pt(e);mt=t.disableThinking;let n=await yt(t);$(`initializing`);let r=c.DEFAULT_WASM_PATH;self.Module={locateFile:e=>new URL(e,`${r}/`).href};let i=await b(r);await i.setupDefaultWebGpuDevice(),i.liteRtLmWasm.preinitializedWebGPUDevice.lost.then(()=>{$(`error`,{fatal:!0,message:`The WebGPU device was lost. Open the model again to reconnect.`})}),Z=await Re.create({model:n,backend:w.GPU,mainExecutorSettings:{maxNumTokens:t.contextTokens}}),Q=await bt(),$(`ready`)}async function St(e){let t=Q.sendMessageStreaming(e).getReader();try{for(;;){let{done:e,value:n}=await t.read();if(e)break;let r=n.content?.filter(e=>e.type===`text`).map(e=>e.text).join(``);r&&$(`delta`,{text:r})}await Q.getTokenCount(),$(`done`)}catch(e){$(`generation-error`,{message:ht(e)})}finally{t.releaseLock()}}async function Ct({data:e}){switch(e.type){case`load`:await xt(e.registration);break;case`generate`:await St(e.prompt);break;case`reset`:await Q.delete(),Q=await bt(),$(`reset`)}}self.addEventListener(`message`,e=>{Ct(e).catch(e=>$(`error`,{message:ht(e)}))})})();", t = typeof self < "u" && self.Blob && new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);", e], { type: "text/javascript;charset=utf-8" });
3
- function n(n) {
4
- let r;
5
- try {
6
- if (r = t && (self.URL || self.webkitURL).createObjectURL(t), !r) throw "";
7
- let e = new Worker(r, { name: n?.name });
8
- return e.addEventListener("error", () => {
9
- (self.URL || self.webkitURL).revokeObjectURL(r);
10
- }), e;
11
- } catch {
12
- return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(e), { name: n?.name });
13
- }
14
- }
15
- export { n as default };