@zerogpu/browser-extension-sdk 0.1.0

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.
Files changed (72) hide show
  1. package/README.md +264 -0
  2. package/bin/zerogpu.mjs +331 -0
  3. package/dist/assets/ort-wasm-simd-threaded.wasm +0 -0
  4. package/dist/assets/ort-wasm-simd.wasm +0 -0
  5. package/dist/assets/ort-wasm-threaded.wasm +0 -0
  6. package/dist/assets/ort-wasm.wasm +0 -0
  7. package/dist/assets/transformers.min.js +107 -0
  8. package/dist/assets/wllama/index.js +3374 -0
  9. package/dist/assets/wllama/multi-thread/wllama.wasm +0 -0
  10. package/dist/assets/wllama/single-thread/wllama.wasm +0 -0
  11. package/dist/assets/zerogpu-assets.json +17 -0
  12. package/dist/extension/zerogpu-offscreen.js +2904 -0
  13. package/dist/extension/zerogpu-offscreen.js.map +1 -0
  14. package/dist/loader.js +2 -0
  15. package/dist/loader.js.map +1 -0
  16. package/dist/manifest.json +7 -0
  17. package/dist/types/adapters/gguf/adapter.d.ts +3 -0
  18. package/dist/types/adapters/gguf/factory.d.ts +3 -0
  19. package/dist/types/adapters/gguf/index.d.ts +2 -0
  20. package/dist/types/adapters/gguf/runtime.d.ts +16 -0
  21. package/dist/types/adapters/index.d.ts +5 -0
  22. package/dist/types/adapters/onnx/adapter.d.ts +3 -0
  23. package/dist/types/adapters/onnx/env-fetch.d.ts +1 -0
  24. package/dist/types/adapters/onnx/factory.d.ts +3 -0
  25. package/dist/types/adapters/onnx/index.d.ts +2 -0
  26. package/dist/types/adapters/onnx/runtime.d.ts +15 -0
  27. package/dist/types/adapters/registry.d.ts +5 -0
  28. package/dist/types/adapters/transformers/adapter.d.ts +10 -0
  29. package/dist/types/adapters/transformers/factory.d.ts +3 -0
  30. package/dist/types/adapters/transformers/index.d.ts +2 -0
  31. package/dist/types/adapters/types.d.ts +64 -0
  32. package/dist/types/auto-init.d.ts +1 -0
  33. package/dist/types/config/defaults.d.ts +2 -0
  34. package/dist/types/config/env.d.ts +7 -0
  35. package/dist/types/config/orchestrator-url.d.ts +1 -0
  36. package/dist/types/config/types.d.ts +34 -0
  37. package/dist/types/device/fingerprint.d.ts +2 -0
  38. package/dist/types/device/telemetry.d.ts +3 -0
  39. package/dist/types/device/types.d.ts +58 -0
  40. package/dist/types/extension/offscreen.d.ts +49 -0
  41. package/dist/types/index.d.ts +1 -0
  42. package/dist/types/loader.d.ts +25 -0
  43. package/dist/types/public-api.d.ts +13 -0
  44. package/dist/types/runtime/lifecycle.d.ts +8 -0
  45. package/dist/types/runtime/router.d.ts +2 -0
  46. package/dist/types/runtime/sdk-state.d.ts +56 -0
  47. package/dist/types/sdk-version.d.ts +1 -0
  48. package/dist/types/storage/cached-model.d.ts +29 -0
  49. package/dist/types/storage/index.d.ts +4 -0
  50. package/dist/types/storage/meta-store.d.ts +2 -0
  51. package/dist/types/storage/model-store.d.ts +9 -0
  52. package/dist/types/storage/types.d.ts +19 -0
  53. package/dist/types/transport/http.d.ts +54 -0
  54. package/dist/types/transport/protocol.d.ts +47 -0
  55. package/dist/types/transport/status.d.ts +1 -0
  56. package/dist/types/transport/websocket.d.ts +25 -0
  57. package/dist/types/utils/errors.d.ts +4 -0
  58. package/dist/types/utils/logger.d.ts +15 -0
  59. package/dist/types/utils/timers.d.ts +7 -0
  60. package/dist/types/utils/uuid.d.ts +1 -0
  61. package/dist/v/zerogpu-browser-sdk.f47bae4f15c9.umd.js +2855 -0
  62. package/dist/v/zerogpu-browser-sdk.f47bae4f15c9.umd.js.map +1 -0
  63. package/dist/zerogpu-browser-sdk.cjs +2849 -0
  64. package/dist/zerogpu-browser-sdk.cjs.map +1 -0
  65. package/dist/zerogpu-browser-sdk.esm.js +2847 -0
  66. package/dist/zerogpu-browser-sdk.esm.js.map +1 -0
  67. package/dist/zerogpu-browser-sdk.umd.js +2855 -0
  68. package/dist/zerogpu-browser-sdk.umd.js.map +1 -0
  69. package/docs/INTEGRATION.md +213 -0
  70. package/docs/auto-update-loader.md +451 -0
  71. package/docs/multi-model-support.md +537 -0
  72. package/package.json +91 -0
@@ -0,0 +1,2847 @@
1
+ const SDK_VERSION = typeof "0.1.0+2fdfb71" === 'string' && "0.1.0+2fdfb71".length > 0
2
+ ? "0.1.0+2fdfb71"
3
+ : '0.0.0-dev';
4
+
5
+ const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
6
+ ? "https://devices.zerogpu.ai"
7
+ : 'https://dev.devices.zerogpu.ai';
8
+
9
+ // The orchestrator URL is baked in at build time per deployment (develop/staging/
10
+ // production). See ./orchestrator-url for the env-var injection and fallback.
11
+ const DEFAULT_CONFIG = {
12
+ sdkVersion: SDK_VERSION,
13
+ orchestrator: {
14
+ baseUrl: ORCHESTRATOR_BASE_URL,
15
+ registerPath: '/register'
16
+ },
17
+ telemetry: {
18
+ enableConsoleLogs: false,
19
+ locationData: false,
20
+ cameraData: false
21
+ }
22
+ };
23
+
24
+ const resolveConfig = (overrides) => {
25
+ const base = DEFAULT_CONFIG;
26
+ const merged = deepMerge(base, overrides ?? {});
27
+ return {
28
+ sdkVersion: asNonEmptyString(merged.sdkVersion, base.sdkVersion),
29
+ orchestrator: {
30
+ baseUrl: asNonEmptyString(merged.orchestrator?.baseUrl, base.orchestrator.baseUrl),
31
+ registerPath: asNonEmptyString(merged.orchestrator?.registerPath, base.orchestrator.registerPath)
32
+ },
33
+ telemetry: {
34
+ enableConsoleLogs: asBoolean(merged.telemetry?.enableConsoleLogs, base.telemetry.enableConsoleLogs),
35
+ locationData: asBoolean(merged.telemetry?.locationData, base.telemetry.locationData),
36
+ cameraData: asBoolean(merged.telemetry?.cameraData, base.telemetry.cameraData)
37
+ }
38
+ };
39
+ };
40
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
41
+ const deepMerge = (target, source) => {
42
+ const result = Array.isArray(target) ? [...target] : { ...target };
43
+ for (const key of Object.keys(source)) {
44
+ const srcValue = source[key];
45
+ if (srcValue === undefined)
46
+ continue;
47
+ const tgtValue = result[key];
48
+ if (isObject(srcValue) && isObject(tgtValue)) {
49
+ result[key] = deepMerge(tgtValue, srcValue);
50
+ }
51
+ else {
52
+ result[key] = srcValue;
53
+ }
54
+ }
55
+ return result;
56
+ };
57
+ const asNonEmptyString = (value, fallback) => typeof value === 'string' && value.length > 0 ? value : fallback;
58
+ const asBoolean = (value, fallback) => typeof value === 'boolean' ? value : fallback;
59
+
60
+ class Logger {
61
+ constructor(config) {
62
+ this.enabled = config.enableConsoleLogs;
63
+ }
64
+ setEnabled(enabled) {
65
+ this.enabled = enabled;
66
+ }
67
+ isEnabled() {
68
+ return this.enabled;
69
+ }
70
+ debug(...args) {
71
+ if (this.enabled)
72
+ console.debug('[ZeroGPU]', ...args);
73
+ }
74
+ info(...args) {
75
+ if (this.enabled)
76
+ console.debug('[ZeroGPU]', ...args);
77
+ }
78
+ warn(...args) {
79
+ if (this.enabled)
80
+ console.warn('[ZeroGPU]', ...args);
81
+ }
82
+ error(...args) {
83
+ if (this.enabled)
84
+ console.error('[ZeroGPU]', ...args);
85
+ }
86
+ }
87
+ let singleton = null;
88
+ const initLogger = (config) => {
89
+ singleton = new Logger(config);
90
+ return singleton;
91
+ };
92
+ const getLogger = () => {
93
+ if (!singleton) {
94
+ singleton = new Logger({
95
+ enableConsoleLogs: false,
96
+ locationData: false,
97
+ cameraData: false
98
+ });
99
+ }
100
+ return singleton;
101
+ };
102
+
103
+ const DEVICE_ID_KEY = 'zerogpu_device_id';
104
+ const getStoredDeviceId = () => {
105
+ try {
106
+ return window.localStorage.getItem(DEVICE_ID_KEY);
107
+ }
108
+ catch {
109
+ return null;
110
+ }
111
+ };
112
+ const setStoredDeviceId = (deviceId) => {
113
+ try {
114
+ window.localStorage.setItem(DEVICE_ID_KEY, deviceId);
115
+ }
116
+ catch {
117
+ // ignored
118
+ }
119
+ };
120
+
121
+ const createUuid = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
122
+ const r = (crypto.getRandomValues(new Uint8Array(1))[0] & 0xf) >> 0;
123
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
124
+ return v.toString(16);
125
+ });
126
+
127
+ const getDeviceId = () => {
128
+ const existing = getStoredDeviceId();
129
+ if (existing)
130
+ return existing;
131
+ const fresh = createUuid();
132
+ setStoredDeviceId(fresh);
133
+ return fresh;
134
+ };
135
+ const setDeviceId = (deviceId) => {
136
+ setStoredDeviceId(deviceId);
137
+ };
138
+
139
+ const getPlatform = () => {
140
+ const ua = navigator.userAgent.toLowerCase();
141
+ const tg = window.Telegram?.WebApp;
142
+ if (tg?.platform)
143
+ return tg.platform;
144
+ if (tg)
145
+ return 'telegram-webapp';
146
+ if (ua.includes('android'))
147
+ return 'android-web';
148
+ if (ua.includes('iphone') || ua.includes('ipad'))
149
+ return 'ios-web';
150
+ if (ua.includes('mac os'))
151
+ return 'macos-web';
152
+ if (ua.includes('windows'))
153
+ return 'windows-web';
154
+ return 'web';
155
+ };
156
+ const getDeviceType = () => {
157
+ const ua = navigator.userAgent ?? '';
158
+ const uaData = navigator.userAgentData;
159
+ if (uaData?.mobile === true)
160
+ return 'mobile';
161
+ const isTablet = /iPad|Tablet|PlayBook|Silk/i.test(ua) || (navigator.maxTouchPoints > 1 && window.innerWidth >= 768);
162
+ if (isTablet)
163
+ return 'tablet';
164
+ const isMobile = /Mobi|Android|iPhone|iPod/i.test(ua);
165
+ return isMobile ? 'mobile' : 'desktop';
166
+ };
167
+ const getWebGLRenderer = () => {
168
+ try {
169
+ const canvas = document.createElement('canvas');
170
+ const gl = canvas.getContext('webgl') ||
171
+ canvas.getContext('experimental-webgl');
172
+ if (!gl)
173
+ return undefined;
174
+ const dbg = gl.getExtension('WEBGL_debug_renderer_info');
175
+ return dbg ? gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);
176
+ }
177
+ catch {
178
+ return undefined;
179
+ }
180
+ };
181
+ const getBatteryInfo = async () => {
182
+ try {
183
+ if ('getBattery' in navigator) {
184
+ const battery = await navigator.getBattery();
185
+ return {
186
+ level: battery.level,
187
+ charging: battery.charging
188
+ };
189
+ }
190
+ }
191
+ catch {
192
+ // ignored
193
+ }
194
+ return undefined;
195
+ };
196
+ const getNetworkInfo = () => {
197
+ const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
198
+ if (conn) {
199
+ return {
200
+ type: conn.effectiveType || 'unknown',
201
+ downlink: conn.downlink || 0,
202
+ rtt: conn.rtt || 0
203
+ };
204
+ }
205
+ return undefined;
206
+ };
207
+ const getLocation = async () => {
208
+ if (!navigator.geolocation)
209
+ return undefined;
210
+ return new Promise((resolve) => {
211
+ navigator.geolocation.getCurrentPosition((pos) => {
212
+ resolve({
213
+ lat: pos.coords.latitude,
214
+ lon: pos.coords.longitude,
215
+ accuracy: pos.coords.accuracy
216
+ });
217
+ }, () => resolve(undefined), { timeout: 5000, maximumAge: 60000 });
218
+ });
219
+ };
220
+ const parseTelegramUserFromHash = () => {
221
+ try {
222
+ const hash = window.location?.hash || '';
223
+ if (!hash.includes('tgWebAppData'))
224
+ return undefined;
225
+ const hashParams = new URLSearchParams(hash.startsWith('#') ? hash.substring(1) : hash);
226
+ const encodedData = hashParams.get('tgWebAppData');
227
+ if (!encodedData)
228
+ return undefined;
229
+ const decodedData = decodeURIComponent(encodedData);
230
+ const dataParams = new URLSearchParams(decodedData);
231
+ const userJson = dataParams.get('user');
232
+ if (!userJson)
233
+ return undefined;
234
+ return JSON.parse(userJson);
235
+ }
236
+ catch {
237
+ return undefined;
238
+ }
239
+ };
240
+ const getTelegramUser = () => {
241
+ const tg = window.Telegram?.WebApp;
242
+ const user = tg?.initDataUnsafe?.user;
243
+ if (user) {
244
+ return user;
245
+ }
246
+ return parseTelegramUserFromHash();
247
+ };
248
+ const collectDeviceInfo = async (config, appUserId, sdkDeviceId) => {
249
+ const screen = window.screen || { width: null, height: null };
250
+ const tg = window.Telegram?.WebApp;
251
+ const telegramUser = getTelegramUser();
252
+ const telegramFullName = telegramUser?.first_name || telegramUser?.last_name
253
+ ? [telegramUser?.first_name, telegramUser?.last_name].filter(Boolean).join(' ')
254
+ : undefined;
255
+ const resolvedAppUserId = telegramUser?.id?.toString() || appUserId;
256
+ const baseInfo = {
257
+ // Identity
258
+ appUserId: resolvedAppUserId,
259
+ appUsername: telegramUser?.username,
260
+ appFirstName: telegramUser?.first_name,
261
+ appLastName: telegramUser?.last_name,
262
+ appFullName: telegramFullName,
263
+ sdkDeviceId: sdkDeviceId ?? getDeviceId(),
264
+ // Platform
265
+ platform: getPlatform(),
266
+ deviceType: getDeviceType(),
267
+ userAgent: navigator.userAgent,
268
+ language: navigator.language,
269
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
270
+ appPlatform: tg?.platform,
271
+ appVersion: tg?.version,
272
+ appLanguage: telegramUser?.language_code,
273
+ themeParams: tg?.themeParams,
274
+ // Hardware
275
+ cpuCores: navigator.hardwareConcurrency || 1,
276
+ memoryGb: navigator.deviceMemory,
277
+ gpuRenderer: getWebGLRenderer(),
278
+ webglFingerprint: getWebGLRenderer(), // Using renderer as simple fingerprint for now
279
+ screen: {
280
+ width: screen?.width ?? null,
281
+ height: screen?.height ?? null,
282
+ pixelRatio: window.devicePixelRatio ?? null
283
+ },
284
+ battery: await getBatteryInfo(),
285
+ // Network
286
+ connection: getNetworkInfo(),
287
+ // Context
288
+ pageUrl: window.location?.href,
289
+ referrer: document.referrer,
290
+ // Optional permissions
291
+ location: config.locationData ? await getLocation() : undefined
292
+ };
293
+ if (config.cameraData) {
294
+ baseInfo.camera = await captureCameraSample();
295
+ }
296
+ return baseInfo;
297
+ };
298
+ const captureCameraSample = async () => {
299
+ if (!navigator.mediaDevices?.getUserMedia) {
300
+ return { permission: 'error', error: 'mediaDevices unavailable' };
301
+ }
302
+ let stream = null;
303
+ let video = null;
304
+ let canvas = null;
305
+ try {
306
+ stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } });
307
+ video = document.createElement('video');
308
+ video.setAttribute('playsinline', 'true');
309
+ video.playsInline = true;
310
+ video.muted = true;
311
+ video.style.cssText = 'position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0';
312
+ document.body.appendChild(video);
313
+ video.srcObject = stream;
314
+ await video.play().catch(() => { });
315
+ await new Promise((resolve) => {
316
+ const ready = () => resolve();
317
+ video.onloadeddata = ready;
318
+ video.oncanplay = ready;
319
+ setTimeout(ready, 800);
320
+ });
321
+ const vw = video.videoWidth || 640;
322
+ const vh = video.videoHeight || 480;
323
+ canvas = document.createElement('canvas');
324
+ canvas.width = vw;
325
+ canvas.height = vh;
326
+ const ctx = canvas.getContext('2d');
327
+ ctx?.drawImage(video, 0, 0, vw, vh);
328
+ const mime = 'image/jpeg';
329
+ const dataUrl = canvas.toDataURL(mime, 0.85);
330
+ const bytes = Math.floor((dataUrl.length * 3) / 4);
331
+ return {
332
+ permission: 'granted',
333
+ width: vw,
334
+ height: vh,
335
+ bytes,
336
+ mime,
337
+ timestamp: Date.now(),
338
+ previewDataUrl: dataUrl
339
+ };
340
+ }
341
+ catch (err) {
342
+ const errorObj = err;
343
+ return {
344
+ permission: errorObj?.name === 'NotAllowedError' ? 'denied' : 'error',
345
+ error: errorObj?.message || String(err)
346
+ };
347
+ }
348
+ finally {
349
+ try {
350
+ stream?.getTracks().forEach((track) => track.stop());
351
+ }
352
+ catch {
353
+ // Best-effort cleanup.
354
+ }
355
+ try {
356
+ video?.remove();
357
+ }
358
+ catch {
359
+ // Best-effort cleanup.
360
+ }
361
+ canvas = null;
362
+ }
363
+ };
364
+
365
+ class RegisterError extends Error {
366
+ constructor(status, body) {
367
+ super(`Register failed: ${status} ${body ?? ''}`.trim());
368
+ this.status = status;
369
+ this.body = body;
370
+ }
371
+ }
372
+ const parseRegisterResponseBody = async (response) => {
373
+ try {
374
+ return await response.clone().json();
375
+ }
376
+ catch {
377
+ return null;
378
+ }
379
+ };
380
+ const isEdgeSdkTypeNotAllowedResponse = (payload) => {
381
+ if (!payload || typeof payload !== 'object') {
382
+ return false;
383
+ }
384
+ const body = payload;
385
+ const status = typeof body.status === 'string' ? body.status.toLowerCase() : '';
386
+ if (status !== 'ok') {
387
+ return false;
388
+ }
389
+ const nestedError = body.error;
390
+ const candidateCodes = [body.code, body.errorCode, body.reason, nestedError?.code];
391
+ return candidateCodes.some((value) => typeof value === 'string' && value.toLowerCase() === 'edge_sdk_type_not_allowed');
392
+ };
393
+ const escapeShellSingleQuotes = (value) => value.replace(/'/g, "'\\''");
394
+ const buildCurl = (url, body, headers) => {
395
+ const payload = escapeShellSingleQuotes(JSON.stringify(body));
396
+ const headerFlags = Object.entries(headers)
397
+ .map(([key, value]) => `-H '${escapeShellSingleQuotes(`${key}: ${value}`)}'`)
398
+ .join(' ');
399
+ return `curl -X POST '${url}' ${headerFlags} -d '${payload}'`;
400
+ };
401
+ const registerDevice = async (config, payload, auth) => {
402
+ const logger = getLogger();
403
+ const orchestrator = config?.orchestrator;
404
+ if (!orchestrator?.baseUrl || !orchestrator?.registerPath) {
405
+ throw new Error('Invalid SDK config: orchestrator.baseUrl and orchestrator.registerPath are required');
406
+ }
407
+ const url = `${orchestrator.baseUrl}${orchestrator.registerPath}`;
408
+ const headers = { 'Content-Type': 'application/json' };
409
+ const edgeOperatorKey = auth?.edgeOperatorKey?.trim();
410
+ if (edgeOperatorKey)
411
+ headers['x-edge-operator-key'] = edgeOperatorKey;
412
+ const response = await fetch(url, {
413
+ method: 'POST',
414
+ headers,
415
+ body: JSON.stringify(payload)
416
+ });
417
+ logger.info('Register request sent:', { url, status: response.status });
418
+ getLogger().debug('Register API blueprint (curl):', buildCurl(url, payload, headers));
419
+ const registerResponseBody = await parseRegisterResponseBody(response);
420
+ const edgeSdkTypeNotAllowed = isEdgeSdkTypeNotAllowedResponse(registerResponseBody);
421
+ if (!response.ok && !edgeSdkTypeNotAllowed) {
422
+ const text = typeof registerResponseBody === 'string'
423
+ ? registerResponseBody
424
+ : JSON.stringify(registerResponseBody ?? '');
425
+ logger.error('Register request failed:', { status: response.status, text });
426
+ throw new RegisterError(response.status, text);
427
+ }
428
+ if (registerResponseBody && typeof registerResponseBody === 'object' && !edgeSdkTypeNotAllowed) {
429
+ const registerResponse = registerResponseBody;
430
+ logger.info('Register response parsed:', registerResponse);
431
+ return registerResponse;
432
+ }
433
+ if (edgeSdkTypeNotAllowed) {
434
+ const responseObject = registerResponseBody && typeof registerResponseBody === 'object'
435
+ ? registerResponseBody
436
+ : {};
437
+ const acceptedResponse = {
438
+ deviceId: typeof responseObject.deviceId === 'string' && responseObject.deviceId
439
+ ? responseObject.deviceId
440
+ : payload.deviceId,
441
+ sessionKey: typeof responseObject.sessionKey === 'string' ? responseObject.sessionKey : '',
442
+ wsUrl: typeof responseObject.wsUrl === 'string' ? responseObject.wsUrl : '',
443
+ active: typeof responseObject.active === 'boolean' ? responseObject.active : false,
444
+ ttlSeconds: typeof responseObject.ttlSeconds === 'number' ? responseObject.ttlSeconds : 0,
445
+ slmConfig: typeof responseObject.slmConfig !== 'undefined'
446
+ ? responseObject.slmConfig
447
+ : typeof responseObject.modelInfo !== 'undefined'
448
+ ? [responseObject.modelInfo]
449
+ : undefined
450
+ };
451
+ logger.info('Handled edge_sdk_type_not_allowed register response');
452
+ return acceptedResponse;
453
+ }
454
+ throw new RegisterError(response.status, 'Register response body is not valid JSON');
455
+ };
456
+
457
+ class WebSocketClient {
458
+ constructor(options) {
459
+ this.options = options;
460
+ this.logger = getLogger();
461
+ this.consoleWithVerbose = console;
462
+ this.handleOpen = () => {
463
+ this.logger.info('WebSocket connection opened');
464
+ this.logger.debug('Sending hello message:', this.options.hello);
465
+ this.logger.info('[WS OUT] hello:', JSON.stringify(this.options.hello));
466
+ this.send(this.options.hello);
467
+ if (this.options.ack) {
468
+ // Send readiness/error ack immediately after hello.
469
+ this.logger.info('[WS OUT] hello_ack:', JSON.stringify(this.options.ack));
470
+ this.send(this.options.ack);
471
+ if (this.options.closeAfterAck) {
472
+ // Optionally close after ack (used for error cases).
473
+ const code = this.options.closeCode ?? 4000;
474
+ const reason = (this.options.closeReason ?? '').slice(0, 120);
475
+ this.logger.warn('Closing WebSocket after ack', { code, reason });
476
+ window.setTimeout(() => {
477
+ this.socket.close(code, reason);
478
+ }, 50);
479
+ }
480
+ }
481
+ };
482
+ this.handleMessage = (event) => {
483
+ try {
484
+ const data = JSON.parse(event.data);
485
+ if (this.logger.isEnabled()) {
486
+ if (typeof this.consoleWithVerbose.verbose === 'function') {
487
+ this.consoleWithVerbose.verbose('[ZeroGPU]', '[WS IN] payload:', data);
488
+ }
489
+ else {
490
+ console.debug('[ZeroGPU]', '[WS IN] payload:', data);
491
+ }
492
+ }
493
+ this.options.onMessage(data);
494
+ }
495
+ catch (error) {
496
+ this.logger.error('Failed to parse WS message', error);
497
+ }
498
+ };
499
+ this.handleError = (event) => {
500
+ const ws = event.target;
501
+ this.logger.error('WebSocket error', {
502
+ url: ws.url,
503
+ readyState: ws.readyState,
504
+ event: event.type
505
+ });
506
+ this.options.onError(event);
507
+ };
508
+ this.handleClose = (event) => {
509
+ const ws = event.target;
510
+ this.logger.warn('WebSocket closed', {
511
+ url: ws.url,
512
+ code: event.code,
513
+ reason: event.reason || 'No reason provided',
514
+ wasClean: event.wasClean
515
+ });
516
+ this.options.onClose(event);
517
+ };
518
+ this.logger.info('Creating WebSocket connection to:', options.url);
519
+ this.socket = new WebSocket(options.url);
520
+ this.socket.onopen = this.handleOpen;
521
+ this.socket.onmessage = this.handleMessage;
522
+ this.socket.onerror = this.handleError;
523
+ this.socket.onclose = this.handleClose;
524
+ }
525
+ send(payload) {
526
+ this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
527
+ this.socket.send(JSON.stringify(payload));
528
+ }
529
+ close() {
530
+ this.socket.close();
531
+ }
532
+ }
533
+
534
+ const state = { status: 'idle' };
535
+ const setConfig = (config) => {
536
+ state.config = config;
537
+ };
538
+ const setDeviceContext = (deviceId, deviceInfo) => {
539
+ state.deviceId = deviceId;
540
+ state.deviceInfo = deviceInfo;
541
+ };
542
+ const setAdapter = (modelId, adapter) => {
543
+ if (!state.adaptersByModelId) {
544
+ state.adaptersByModelId = {};
545
+ }
546
+ if (adapter) {
547
+ state.adaptersByModelId[modelId] = adapter;
548
+ }
549
+ else {
550
+ delete state.adaptersByModelId[modelId];
551
+ }
552
+ };
553
+ const setAdaptersByModelId = (adapters) => {
554
+ state.adaptersByModelId = adapters ?? {};
555
+ };
556
+ const setModelInfo = (modelInfo) => {
557
+ state.modelInfo = modelInfo;
558
+ state.taskType = modelInfo?.taskType;
559
+ if (!state.modelInfosByModelId) {
560
+ state.modelInfosByModelId = {};
561
+ }
562
+ if (modelInfo?.modelId) {
563
+ state.modelInfosByModelId[modelInfo.modelId] = modelInfo;
564
+ }
565
+ };
566
+ const setModelInfosByModelId = (modelInfos) => {
567
+ state.modelInfosByModelId = modelInfos ?? {};
568
+ };
569
+ const setSample = (sample) => {
570
+ state.sample = sample;
571
+ };
572
+ const setCachedModelId = (cachedModelId) => {
573
+ state.cachedModelId = cachedModelId ?? null;
574
+ };
575
+ const setSessionKey = (sessionKey) => {
576
+ state.sessionKey = sessionKey;
577
+ };
578
+ const setWebSocket = (ws) => {
579
+ state.ws = ws;
580
+ };
581
+ const setStatus = (status) => {
582
+ state.status = status;
583
+ };
584
+ const getState = () => {
585
+ if (!state.config || !state.deviceId || !state.deviceInfo) {
586
+ throw new Error('SDK state not initialized');
587
+ }
588
+ return state;
589
+ };
590
+
591
+ const factories = [];
592
+ const registerAdapter = (factory) => {
593
+ factories.push(factory);
594
+ };
595
+ const matches = (capability, framework, taskType) => capability.inferenceFramework.toLowerCase() === framework.toLowerCase() &&
596
+ capability.taskType.toLowerCase() === taskType.toLowerCase();
597
+ const getAdapterFactory = (framework, taskType) => {
598
+ if (!framework || !taskType)
599
+ return undefined;
600
+ return factories.find((factory) => factory.capabilities.some((capability) => matches(capability, framework, taskType)));
601
+ };
602
+
603
+ let executing = false;
604
+ const buildInferenceInput = (request) => {
605
+ const input = request.input ?? {};
606
+ return {
607
+ ...input,
608
+ text: typeof input.text === 'string' ? input.text : '',
609
+ usecase: typeof input.usecase === 'string' ? input.usecase : undefined
610
+ };
611
+ };
612
+ const lazyLoadAdapter = async (modelId) => {
613
+ const logger = getLogger();
614
+ const { modelInfosByModelId } = getState();
615
+ const info = modelInfosByModelId?.[modelId];
616
+ if (!info)
617
+ return undefined;
618
+ const factory = getAdapterFactory(info.inferenceFramework, info.taskType);
619
+ if (!factory) {
620
+ logger.warn('No adapter factory registered for assigned model', {
621
+ modelId,
622
+ inferenceFramework: info.inferenceFramework,
623
+ taskType: info.taskType
624
+ });
625
+ return undefined;
626
+ }
627
+ const slmConfig = {
628
+ modelId: info.modelId,
629
+ modelVersion: info.modelVersion ?? '',
630
+ modelUrl: info.modelUrl,
631
+ modelRepoId: info.modelRepoId,
632
+ modelType: info.modelType,
633
+ inferenceFramework: info.inferenceFramework,
634
+ requiredFiles: info.requiredFiles,
635
+ quantized: info.quantized ?? false,
636
+ quantization: info.quantization,
637
+ taskType: info.taskType,
638
+ maxInputTokens: info.maxTokens
639
+ };
640
+ const result = await factory.load(slmConfig);
641
+ if (!result.adapter) {
642
+ logger.warn('Lazy adapter load failed', {
643
+ modelId,
644
+ error: result.error?.message
645
+ });
646
+ return undefined;
647
+ }
648
+ setAdapter(modelId, result.adapter);
649
+ return result.adapter;
650
+ };
651
+ const executeSingleRequest = async (request) => {
652
+ const logger = getLogger();
653
+ const start = performance.now();
654
+ const { adaptersByModelId } = getState();
655
+ let adapter = adaptersByModelId?.[request.modelId];
656
+ if (!adapter) {
657
+ adapter = await lazyLoadAdapter(request.modelId);
658
+ }
659
+ if (!adapter) {
660
+ return {
661
+ requestId: request.requestId,
662
+ modelId: request.modelId,
663
+ modelVersion: request.modelVersion,
664
+ response: { text: '' },
665
+ error: true,
666
+ errorMessage: 'model_not_ready',
667
+ metadata: {
668
+ processingTime: Math.round(performance.now() - start)
669
+ }
670
+ };
671
+ }
672
+ try {
673
+ const input = buildInferenceInput(request);
674
+ const result = await adapter.runInference(input);
675
+ return {
676
+ requestId: request.requestId,
677
+ modelId: request.modelId,
678
+ modelVersion: request.modelVersion,
679
+ response: result.output,
680
+ error: false,
681
+ errorMessage: '',
682
+ metadata: {
683
+ processingTime: Math.round(performance.now() - start)
684
+ }
685
+ };
686
+ }
687
+ catch (error) {
688
+ logger.error('Task failed', error);
689
+ return {
690
+ requestId: request.requestId,
691
+ modelId: request.modelId,
692
+ modelVersion: request.modelVersion,
693
+ response: { text: '' },
694
+ error: true,
695
+ errorMessage: error.message,
696
+ metadata: {
697
+ processingTime: Math.round(performance.now() - start)
698
+ }
699
+ };
700
+ }
701
+ };
702
+ const handleIncomingMessage = async (msg) => {
703
+ const { ws, sessionKey, deviceId } = getState();
704
+ const logger = getLogger();
705
+ const sendBatchResponse = (requests) => {
706
+ const payload = {
707
+ requests,
708
+ deviceId,
709
+ sessionKey
710
+ };
711
+ ws?.send(payload);
712
+ };
713
+ if (msg.requests.length === 0) {
714
+ return;
715
+ }
716
+ if (executing) {
717
+ sendBatchResponse(msg.requests.map((request) => ({
718
+ requestId: request.requestId,
719
+ modelId: request.modelId,
720
+ modelVersion: request.modelVersion,
721
+ response: { text: '' },
722
+ error: true,
723
+ errorMessage: 'device_busy',
724
+ metadata: { processingTime: 0 }
725
+ })));
726
+ return;
727
+ }
728
+ executing = true;
729
+ setStatus('busy');
730
+ try {
731
+ const results = [];
732
+ for (const request of msg.requests) {
733
+ const result = await executeSingleRequest(request);
734
+ logger.info('[WS OUT] task result:', {
735
+ requestId: result.requestId,
736
+ modelId: result.modelId,
737
+ response: result.response,
738
+ error: result.error,
739
+ errorMessage: result.errorMessage
740
+ });
741
+ results.push(result);
742
+ }
743
+ sendBatchResponse(results);
744
+ }
745
+ finally {
746
+ executing = false;
747
+ setStatus('idle');
748
+ }
749
+ };
750
+
751
+ const DB_NAME = 'zerogpu-slm-cache';
752
+ const STORE_NAME = 'models';
753
+ const DB_VERSION = 1;
754
+ const openDb = () => new Promise((resolve, reject) => {
755
+ const req = indexedDB.open(DB_NAME, DB_VERSION);
756
+ req.onupgradeneeded = () => {
757
+ const db = req.result;
758
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
759
+ db.createObjectStore(STORE_NAME, { keyPath: 'key' });
760
+ }
761
+ };
762
+ req.onsuccess = () => resolve(req.result);
763
+ req.onerror = () => reject(req.error);
764
+ });
765
+ const runTx = async (mode, handler) => {
766
+ const db = await openDb();
767
+ return new Promise((resolve, reject) => {
768
+ const tx = db.transaction(STORE_NAME, mode);
769
+ const store = tx.objectStore(STORE_NAME);
770
+ handler(store)
771
+ .then((val) => {
772
+ tx.oncomplete = () => resolve(val);
773
+ tx.onerror = () => reject(tx.error);
774
+ })
775
+ .catch(reject);
776
+ });
777
+ };
778
+ const buildKey = (modelId, version) => `${modelId}:${version}`;
779
+ const putModelComplete = async (modelId, version, metadata, files) => {
780
+ const finalMeta = {
781
+ ...metadata,
782
+ modelId,
783
+ modelVersion: version,
784
+ status: 'complete',
785
+ updatedAt: Date.now(),
786
+ sizeBytes: metadata.sizeBytes
787
+ };
788
+ await runTx('readwrite', async (store) => {
789
+ const record = { key: buildKey(modelId, version), metadata: finalMeta, files };
790
+ store.put(record);
791
+ });
792
+ };
793
+ const getModel = async (modelId, version) => {
794
+ const key = buildKey(modelId, version);
795
+ return runTx('readonly', async (store) => {
796
+ return new Promise((resolve, reject) => {
797
+ const req = store.get(key);
798
+ req.onsuccess = () => {
799
+ const record = req.result;
800
+ if (!record || record.metadata.status !== 'complete') {
801
+ resolve(null);
802
+ return;
803
+ }
804
+ resolve({ metadata: record.metadata, files: record.files });
805
+ };
806
+ req.onerror = () => reject(req.error);
807
+ });
808
+ });
809
+ };
810
+ const clearModel = async (modelId, version) => {
811
+ await runTx('readwrite', async (store) => {
812
+ store.delete(buildKey(modelId, version));
813
+ });
814
+ };
815
+ const clearAllModels = async () => {
816
+ await runTx('readwrite', async (store) => {
817
+ store.clear();
818
+ });
819
+ };
820
+
821
+ const CACHED_MODEL_ID_KEY = 'zerogpu_cached_model_id';
822
+ const safeGetItem = (key) => {
823
+ try {
824
+ return window.localStorage.getItem(key);
825
+ }
826
+ catch {
827
+ return null;
828
+ }
829
+ };
830
+ const safeSetItem = (key, value) => {
831
+ try {
832
+ window.localStorage.setItem(key, value);
833
+ }
834
+ catch {
835
+ // ignore storage failures
836
+ }
837
+ };
838
+ const safeRemoveItem = (key) => {
839
+ try {
840
+ window.localStorage.removeItem(key);
841
+ }
842
+ catch {
843
+ // ignore storage failures
844
+ }
845
+ };
846
+ const getCachedModelId = () => safeGetItem(CACHED_MODEL_ID_KEY);
847
+ const getCachedModelInfo = (modelId) => {
848
+ const raw = safeGetItem(modelId);
849
+ if (!raw)
850
+ return null;
851
+ try {
852
+ return JSON.parse(raw);
853
+ }
854
+ catch {
855
+ return null;
856
+ }
857
+ };
858
+ const setCachedModelInfo = (info) => {
859
+ safeSetItem(CACHED_MODEL_ID_KEY, info.modelId);
860
+ safeSetItem(info.modelId, JSON.stringify(info));
861
+ };
862
+ const clearCachedModelInfo = (modelId) => {
863
+ const existing = modelId ?? getCachedModelId();
864
+ if (existing) {
865
+ safeRemoveItem(existing);
866
+ }
867
+ safeRemoveItem(CACHED_MODEL_ID_KEY);
868
+ };
869
+
870
+ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: providedDeviceId }) => {
871
+ initLogger(config.telemetry);
872
+ const logger = getLogger();
873
+ setConfig(config);
874
+ const storedDeviceId = providedDeviceId ? null : getStoredDeviceId();
875
+ const isFreshDevice = !providedDeviceId && !storedDeviceId;
876
+ const deviceId = providedDeviceId ?? storedDeviceId ?? getDeviceId();
877
+ if (providedDeviceId) {
878
+ setDeviceId(providedDeviceId);
879
+ }
880
+ const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
881
+ const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
882
+ setDeviceContext(deviceId, sanitizedDeviceInfo);
883
+ if (!edgeOperatorKey) {
884
+ throw new Error('Missing required header: x-edge-operator-key');
885
+ }
886
+ if (rawDeviceInfo.camera?.previewDataUrl) {
887
+ try {
888
+ window.dispatchEvent(new CustomEvent('zerogpu:cameraPreview', {
889
+ detail: {
890
+ deviceId,
891
+ previewDataUrl: rawDeviceInfo.camera.previewDataUrl,
892
+ camera: sanitizedDeviceInfo.camera
893
+ }
894
+ }));
895
+ }
896
+ catch {
897
+ logger.warn('Unable to dispatch camera preview event');
898
+ }
899
+ }
900
+ const cachedModelId = isFreshDevice ? null : getCachedModelId();
901
+ setCachedModelId(cachedModelId);
902
+ let cachedInfo = cachedModelId ? getCachedModelInfo(cachedModelId) : null;
903
+ if (!isFreshDevice) {
904
+ logger.info('Cache lookup', {
905
+ cachedModelId,
906
+ hasCachedInfo: Boolean(cachedInfo)
907
+ });
908
+ }
909
+ let cachedAdapter;
910
+ let cachedSampleMetrics;
911
+ let cacheInvalid = false;
912
+ const logFlow = (flow, details) => {
913
+ logger.info(`[Flow] ${flow}`, details ?? {});
914
+ };
915
+ if (isFreshDevice) {
916
+ logFlow('Fresh device detected; skip cache checks');
917
+ cachedInfo = null;
918
+ cachedAdapter = undefined;
919
+ cachedSampleMetrics = undefined;
920
+ cacheInvalid = false;
921
+ }
922
+ else if (cachedInfo &&
923
+ cachedInfo.modelId &&
924
+ cachedInfo.modelUrl &&
925
+ cachedInfo.taskType &&
926
+ cachedInfo.requiredFiles) {
927
+ logFlow('Cache detected; validating cached model', {
928
+ modelId: cachedInfo.modelId,
929
+ taskType: cachedInfo.taskType
930
+ });
931
+ if (!cachedInfo.modelVersion || !cachedInfo.sample?.text || !cachedInfo.requiredFiles) {
932
+ cacheInvalid = true;
933
+ cachedSampleMetrics = {
934
+ taskType: cachedInfo.taskType,
935
+ processingTimeMs: 0,
936
+ error: true,
937
+ errorMessage: 'response from processing sample'
938
+ };
939
+ logger.warn('Pre-register cache invalid: missing metadata', {
940
+ modelId: cachedInfo.modelId,
941
+ taskType: cachedInfo.taskType
942
+ });
943
+ }
944
+ else {
945
+ const hasCachedFiles = await hasCachedFilesForModel(cachedInfo);
946
+ if (!hasCachedFiles) {
947
+ cacheInvalid = true;
948
+ cachedSampleMetrics = {
949
+ taskType: cachedInfo.taskType,
950
+ processingTimeMs: 0,
951
+ error: true,
952
+ errorMessage: 'response from processing sample'
953
+ };
954
+ logger.warn('Pre-register cache invalid: required files missing', {
955
+ modelId: cachedInfo.modelId,
956
+ taskType: cachedInfo.taskType
957
+ });
958
+ }
959
+ else {
960
+ const slmConfig = buildSlmConfigFromCached(cachedInfo);
961
+ const factory = getAdapterFactory(slmConfig.inferenceFramework, slmConfig.taskType);
962
+ if (!factory) {
963
+ cacheInvalid = true;
964
+ cachedSampleMetrics = {
965
+ taskType: cachedInfo.taskType,
966
+ processingTimeMs: 0,
967
+ error: true,
968
+ errorMessage: 'no_adapter_factory'
969
+ };
970
+ logger.warn('No adapter factory for cached model', {
971
+ framework: slmConfig.inferenceFramework,
972
+ taskType: slmConfig.taskType
973
+ });
974
+ }
975
+ else {
976
+ const loadResult = await factory.load(slmConfig, { allowDownload: hasCachedFiles });
977
+ if (!loadResult.adapter || loadResult.error) {
978
+ cacheInvalid = true;
979
+ cachedSampleMetrics = {
980
+ taskType: cachedInfo.taskType,
981
+ processingTimeMs: 0,
982
+ error: true,
983
+ errorMessage: 'response from processing sample'
984
+ };
985
+ logger.warn('Pre-register cache invalid: adapter load failed', {
986
+ modelId: cachedInfo.modelId,
987
+ taskType: cachedInfo.taskType,
988
+ error: loadResult.error?.message
989
+ });
990
+ }
991
+ else {
992
+ cachedAdapter = loadResult.adapter;
993
+ setAdapter(cachedInfo.modelId, cachedAdapter);
994
+ const sample = cachedInfo.sample;
995
+ const sampleResult = await cachedAdapter.runSample(sample);
996
+ cachedSampleMetrics = {
997
+ taskType: cachedInfo.taskType,
998
+ processingTimeMs: sampleResult.processingTimeMs,
999
+ error: sampleResult.error,
1000
+ errorMessage: sampleResult.error
1001
+ ? (sampleResult.errorMessage ?? 'response from processing sample')
1002
+ : undefined
1003
+ };
1004
+ if (!sampleResult.ok) {
1005
+ cacheInvalid = true;
1006
+ logFlow('Cache invalid; sample test failed', {
1007
+ reason: 'sample_failed'
1008
+ });
1009
+ }
1010
+ }
1011
+ }
1012
+ }
1013
+ }
1014
+ }
1015
+ else if (cachedModelId) {
1016
+ cacheInvalid = true;
1017
+ cachedSampleMetrics = {
1018
+ taskType: cachedInfo?.taskType ?? 'summary',
1019
+ processingTimeMs: 0,
1020
+ error: true,
1021
+ errorMessage: 'response from processing sample'
1022
+ };
1023
+ logFlow('Cache metadata missing; will purge before register', {
1024
+ modelId: cachedModelId
1025
+ });
1026
+ }
1027
+ else {
1028
+ logFlow('No cache detected; first run flow');
1029
+ }
1030
+ if (cachedSampleMetrics) {
1031
+ logFlow('Cached sample evaluated', cachedSampleMetrics);
1032
+ }
1033
+ if (cacheInvalid) {
1034
+ await clearAllModels().catch(() => { });
1035
+ await clearTransformersCaches().catch(() => { });
1036
+ clearCachedModelInfo(cachedModelId);
1037
+ setCachedModelId(null);
1038
+ cachedInfo = null;
1039
+ cachedAdapter = undefined;
1040
+ setAdaptersByModelId({});
1041
+ setModelInfosByModelId({});
1042
+ }
1043
+ const registerPayload = {
1044
+ deviceId,
1045
+ sdkVersion: config.sdkVersion,
1046
+ cachedModels: cachedInfo && !cacheInvalid
1047
+ ? [{ modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion || '1' }]
1048
+ : [],
1049
+ device: sanitizedDeviceInfo
1050
+ };
1051
+ let registerResponse;
1052
+ let assignedModels = [];
1053
+ const adaptersByModelId = {};
1054
+ const modelInfosByModelId = {};
1055
+ const modelStatuses = {};
1056
+ let loadErrorMessage;
1057
+ let postRegisterSample;
1058
+ try {
1059
+ registerResponse = await registerDevice(config, registerPayload, {
1060
+ edgeOperatorKey
1061
+ });
1062
+ }
1063
+ catch (err) {
1064
+ if (err instanceof RegisterError && (err.status === 401 || err.status === 403)) {
1065
+ logger.warn('Register auth failed, stopping lifecycle');
1066
+ logFlow('Auth failure; no WS connection', { status: err.status });
1067
+ return;
1068
+ }
1069
+ throw err;
1070
+ }
1071
+ logger.info('Register response received:', {
1072
+ deviceId: registerResponse.deviceId,
1073
+ wsUrl: registerResponse.wsUrl
1074
+ });
1075
+ if (!registerResponse.wsUrl) {
1076
+ return;
1077
+ }
1078
+ assignedModels = normalizeAssignedModels(registerResponse.slmConfig);
1079
+ const primaryModel = assignedModels[0];
1080
+ for (const model of assignedModels) {
1081
+ modelStatuses[getModelStatusKey(model)] = 'idle';
1082
+ modelInfosByModelId[model.modelId] = model;
1083
+ }
1084
+ if (!primaryModel) {
1085
+ await clearAllModels().catch(() => { });
1086
+ await clearTransformersCaches().catch(() => { });
1087
+ clearCachedModelInfo(cachedModelId);
1088
+ setCachedModelId(null);
1089
+ return;
1090
+ }
1091
+ setSessionKey(registerResponse.sessionKey);
1092
+ setModelInfosByModelId(modelInfosByModelId);
1093
+ setModelInfo(primaryModel);
1094
+ setSample(primaryModel.sample);
1095
+ logger.info('Runtime globals updated from register response', {
1096
+ sessionKey: registerResponse.sessionKey,
1097
+ taskType: primaryModel.taskType,
1098
+ sample: primaryModel.sample
1099
+ });
1100
+ if (!cachedInfo || cachedInfo.modelId !== primaryModel.modelId || cacheInvalid) {
1101
+ if (cachedInfo && cachedInfo.modelId !== primaryModel.modelId) {
1102
+ logFlow('Server assigned different model; refreshing cache', {
1103
+ cachedModelId: cachedInfo.modelId,
1104
+ assignedModelId: primaryModel.modelId
1105
+ });
1106
+ }
1107
+ await clearAllModels().catch(() => { });
1108
+ await clearTransformersCaches().catch(() => { });
1109
+ clearCachedModelInfo(cachedModelId);
1110
+ setCachedModelId(null);
1111
+ setAdaptersByModelId({});
1112
+ const slmConfig = buildSlmConfigFromAssigned(primaryModel);
1113
+ const factory = getAdapterFactory(slmConfig.inferenceFramework, slmConfig.taskType);
1114
+ if (!factory) {
1115
+ modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1116
+ loadErrorMessage = `no_adapter_factory:${slmConfig.inferenceFramework ?? 'unknown'}:${slmConfig.taskType}`;
1117
+ }
1118
+ else {
1119
+ const loadResult = await factory.load(slmConfig);
1120
+ loadErrorMessage = loadResult.error?.message;
1121
+ if (loadResult.adapter) {
1122
+ adaptersByModelId[primaryModel.modelId] = loadResult.adapter;
1123
+ setAdapter(primaryModel.modelId, loadResult.adapter);
1124
+ setCachedModelId(primaryModel.modelId);
1125
+ setCachedModelInfo({
1126
+ modelId: primaryModel.modelId,
1127
+ modelVersion: primaryModel.modelVersion ?? '1',
1128
+ modelUrl: primaryModel.modelUrl,
1129
+ modelRepoId: primaryModel.modelRepoId,
1130
+ maxInputTokens: primaryModel.maxTokens,
1131
+ quantized: primaryModel.quantized,
1132
+ quantization: primaryModel.quantization,
1133
+ taskType: primaryModel.taskType,
1134
+ sizeBytes: primaryModel.sizeBytes,
1135
+ sample: primaryModel.sample,
1136
+ requiredFiles: primaryModel.requiredFiles
1137
+ });
1138
+ }
1139
+ else {
1140
+ modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1141
+ }
1142
+ }
1143
+ }
1144
+ else if (cachedInfo && cachedInfo.modelId === primaryModel.modelId && cachedAdapter) {
1145
+ logFlow('Cache reuse flow; modelId matches assigned', { modelId: primaryModel.modelId });
1146
+ setCachedModelId(primaryModel.modelId);
1147
+ adaptersByModelId[primaryModel.modelId] = cachedAdapter;
1148
+ setAdapter(primaryModel.modelId, cachedAdapter);
1149
+ setCachedModelInfo({
1150
+ modelId: primaryModel.modelId,
1151
+ modelVersion: primaryModel.modelVersion ?? '1',
1152
+ modelUrl: primaryModel.modelUrl,
1153
+ modelRepoId: primaryModel.modelRepoId,
1154
+ maxInputTokens: primaryModel.maxTokens,
1155
+ quantized: primaryModel.quantized,
1156
+ quantization: primaryModel.quantization,
1157
+ taskType: primaryModel.taskType,
1158
+ sizeBytes: primaryModel.sizeBytes,
1159
+ sample: primaryModel.sample,
1160
+ requiredFiles: primaryModel.requiredFiles
1161
+ });
1162
+ }
1163
+ // Load secondary models
1164
+ for (const model of assignedModels) {
1165
+ if (model.modelId === primaryModel.modelId)
1166
+ continue;
1167
+ const slmConfig = buildSlmConfigFromAssigned(model);
1168
+ const factory = getAdapterFactory(slmConfig.inferenceFramework, slmConfig.taskType);
1169
+ if (!factory) {
1170
+ modelStatuses[getModelStatusKey(model)] = 'error';
1171
+ logger.warn('No adapter factory for secondary model', {
1172
+ modelId: model.modelId,
1173
+ framework: slmConfig.inferenceFramework,
1174
+ taskType: slmConfig.taskType
1175
+ });
1176
+ continue;
1177
+ }
1178
+ const loadResult = await factory.load(slmConfig);
1179
+ if (loadResult.adapter) {
1180
+ adaptersByModelId[model.modelId] = loadResult.adapter;
1181
+ setAdapter(model.modelId, loadResult.adapter);
1182
+ }
1183
+ else {
1184
+ modelStatuses[getModelStatusKey(model)] = 'error';
1185
+ logger.warn('Failed to load secondary model', {
1186
+ modelId: model.modelId,
1187
+ taskType: model.taskType,
1188
+ error: loadResult.error?.message
1189
+ });
1190
+ }
1191
+ }
1192
+ const primaryAdapter = adaptersByModelId[primaryModel.modelId];
1193
+ if (!primaryAdapter) {
1194
+ setStatus('error');
1195
+ const reason = loadErrorMessage || 'model_not_ready';
1196
+ if (registerResponse?.wsUrl) {
1197
+ await reportInitFailureOverWebSocket({
1198
+ wsUrl: registerResponse.wsUrl,
1199
+ hello: {
1200
+ type: 'hello',
1201
+ deviceId: registerResponse.deviceId,
1202
+ sessionKey: registerResponse.sessionKey,
1203
+ sdkVersion: config.sdkVersion,
1204
+ slmConfig: assignedModels.map((model) => ({
1205
+ modelId: model.modelId,
1206
+ modelVersion: model.modelVersion ?? '1',
1207
+ status: modelStatuses[getModelStatusKey(model)] || 'idle'
1208
+ }))
1209
+ },
1210
+ ack: {
1211
+ type: 'hello_ack',
1212
+ deviceId: registerResponse.deviceId,
1213
+ sdkVersion: config.sdkVersion,
1214
+ sessionKey: registerResponse.sessionKey,
1215
+ status: 'error',
1216
+ timestamp: Date.now(),
1217
+ errorMessage: `primary_model_load_failed:${reason}`
1218
+ }
1219
+ }).catch(() => { });
1220
+ }
1221
+ logger.error('Primary model failed to initialize; aborting lifecycle before WebSocket connect', {
1222
+ modelId: primaryModel.modelId,
1223
+ modelVersion: primaryModel.modelVersion,
1224
+ taskType: primaryModel.taskType,
1225
+ reason
1226
+ });
1227
+ throw new Error(`primary_model_load_failed:${reason}`);
1228
+ }
1229
+ if (primaryAdapter && primaryModel.sample?.text) {
1230
+ postRegisterSample = await primaryAdapter.runSample(primaryModel.sample);
1231
+ logger.info('Post-register sample test result', {
1232
+ taskType: primaryModel.taskType,
1233
+ ok: postRegisterSample.ok,
1234
+ error: postRegisterSample.error,
1235
+ errorMessage: postRegisterSample.errorMessage,
1236
+ processingTimeMs: postRegisterSample.processingTimeMs
1237
+ });
1238
+ if (postRegisterSample.error) {
1239
+ modelStatuses[getModelStatusKey(primaryModel)] = 'error';
1240
+ }
1241
+ }
1242
+ const helloDeviceId = registerResponse.deviceId;
1243
+ const helloSlmConfig = assignedModels.map((model) => ({
1244
+ modelId: model.modelId,
1245
+ modelVersion: model.modelVersion ?? '1',
1246
+ status: modelStatuses[getModelStatusKey(model)] || 'idle'
1247
+ }));
1248
+ const hello = {
1249
+ type: 'hello',
1250
+ deviceId: helloDeviceId,
1251
+ sessionKey: registerResponse.sessionKey,
1252
+ sdkVersion: config.sdkVersion,
1253
+ slmConfig: helloSlmConfig
1254
+ };
1255
+ const client = new WebSocketClient({
1256
+ url: registerResponse.wsUrl,
1257
+ hello,
1258
+ onMessage: (message) => {
1259
+ if ('requests' in message && Array.isArray(message.requests)) {
1260
+ handleIncomingMessage(message);
1261
+ }
1262
+ else if ('type' in message && message.type === 'hello_ack') {
1263
+ const ack = message;
1264
+ logger.info('Received WS hello_ack', ack);
1265
+ setStatus(ack.status === 'error' ? 'error' : 'idle');
1266
+ }
1267
+ else {
1268
+ logger.debug('Unhandled WS message', message);
1269
+ }
1270
+ },
1271
+ onClose: () => {
1272
+ setStatus('error');
1273
+ },
1274
+ onError: () => {
1275
+ setStatus('error');
1276
+ }
1277
+ });
1278
+ setWebSocket(client);
1279
+ setStatus('idle');
1280
+ };
1281
+ const normalizeAssignedModels = (slmConfig) => {
1282
+ if (!Array.isArray(slmConfig))
1283
+ return [];
1284
+ const normalized = [];
1285
+ for (const model of slmConfig) {
1286
+ if (!model?.modelId || !model?.modelVersion || !model?.modelUrl)
1287
+ continue;
1288
+ const taskType = pickTaskType(model);
1289
+ if (!taskType)
1290
+ continue;
1291
+ normalized.push({
1292
+ modelId: model.modelId,
1293
+ modelType: model.modelType,
1294
+ modelVersion: model.modelVersion,
1295
+ modelUrl: model.modelUrl,
1296
+ modelRepoId: model.modelRepoId,
1297
+ maxTokens: model.maxTokens,
1298
+ requiredFiles: model.requiredFiles,
1299
+ inferenceFramework: model.inferenceFramework,
1300
+ quantized: Boolean(model.quantized),
1301
+ quantization: model.quantization,
1302
+ taskType,
1303
+ sizeBytes: model.sizeBytes,
1304
+ sample: model.sample
1305
+ });
1306
+ }
1307
+ return normalized;
1308
+ };
1309
+ const pickTaskType = (model) => {
1310
+ const declared = model.taskType;
1311
+ if (typeof declared === 'string' && declared.length > 0) {
1312
+ return declared;
1313
+ }
1314
+ return null;
1315
+ };
1316
+ const getModelStatusKey = (model) => `${model.modelId}@${model.modelVersion ?? '1'}`;
1317
+ const buildSlmConfigFromCached = (cached) => ({
1318
+ modelId: cached.modelId,
1319
+ modelVersion: cached.modelVersion || '1',
1320
+ modelUrl: cached.modelUrl,
1321
+ modelRepoId: cached.modelRepoId,
1322
+ modelType: cached.modelType,
1323
+ inferenceFramework: cached.inferenceFramework,
1324
+ requiredFiles: cached.requiredFiles,
1325
+ quantized: Boolean(cached.quantized),
1326
+ quantization: cached.quantization,
1327
+ taskType: cached.taskType,
1328
+ maxInputTokens: cached.maxInputTokens
1329
+ });
1330
+ const buildSlmConfigFromAssigned = (modelInfo) => ({
1331
+ modelId: modelInfo.modelId,
1332
+ modelVersion: modelInfo.modelVersion ?? '1',
1333
+ modelUrl: modelInfo.modelUrl,
1334
+ modelRepoId: modelInfo.modelRepoId,
1335
+ modelType: modelInfo.modelType,
1336
+ inferenceFramework: modelInfo.inferenceFramework,
1337
+ requiredFiles: modelInfo.requiredFiles,
1338
+ quantized: modelInfo.quantized ?? false,
1339
+ quantization: modelInfo.quantization,
1340
+ taskType: modelInfo.taskType,
1341
+ maxInputTokens: modelInfo.maxTokens
1342
+ });
1343
+ const hasCachedFilesForModel = async (cached) => {
1344
+ if (!Array.isArray(cached.requiredFiles))
1345
+ return false;
1346
+ if (cached.requiredFiles.length === 0)
1347
+ return true;
1348
+ const requiredFiles = normalizeRequiredFiles(cached.requiredFiles);
1349
+ if (!requiredFiles.length)
1350
+ return false;
1351
+ try {
1352
+ const model = await getModel(cached.modelId, cached.modelVersion || '1');
1353
+ if (!model?.files)
1354
+ return false;
1355
+ const storedKeys = new Set();
1356
+ for (const key of Object.keys(model.files)) {
1357
+ const normalized = key.replace(/^\/+/, '').replace(/^resolve\/main\//, '');
1358
+ storedKeys.add(normalized);
1359
+ const modelScopedPrefix = `${cached.modelId}/`;
1360
+ if (normalized.startsWith(modelScopedPrefix)) {
1361
+ storedKeys.add(normalized.slice(modelScopedPrefix.length));
1362
+ }
1363
+ }
1364
+ return requiredFiles.every((file) => {
1365
+ if (storedKeys.has(file))
1366
+ return true;
1367
+ if (storedKeys.has(`onnx/${file}`))
1368
+ return true;
1369
+ if (file.startsWith('onnx/') && storedKeys.has(file.slice('onnx/'.length)))
1370
+ return true;
1371
+ return false;
1372
+ });
1373
+ }
1374
+ catch {
1375
+ return false;
1376
+ }
1377
+ };
1378
+ const normalizeRequiredFiles = (requiredFiles) => requiredFiles
1379
+ .filter((file) => typeof file === 'object' && file !== null && typeof file.name === 'string')
1380
+ .map((file) => file.name.trim().replace(/^\/+/, ''))
1381
+ .filter((name) => typeof name === 'string' && name.length > 0);
1382
+ const clearTransformersCaches = async () => {
1383
+ if (typeof caches === 'undefined')
1384
+ return;
1385
+ const cacheNames = await caches.keys();
1386
+ const targetNames = cacheNames.filter((name) => name.includes('transformers-cache'));
1387
+ await Promise.all(targetNames.map((name) => caches.delete(name)));
1388
+ };
1389
+ const reportInitFailureOverWebSocket = async (options) => {
1390
+ await new Promise((resolve) => {
1391
+ let settled = false;
1392
+ const settle = () => {
1393
+ if (settled)
1394
+ return;
1395
+ settled = true;
1396
+ resolve();
1397
+ };
1398
+ const timeout = window.setTimeout(settle, 1500);
1399
+ try {
1400
+ new WebSocketClient({
1401
+ url: options.wsUrl,
1402
+ hello: options.hello,
1403
+ ack: options.ack,
1404
+ closeAfterAck: true,
1405
+ closeCode: 4001,
1406
+ closeReason: 'primary_model_load_failed',
1407
+ onMessage: () => { },
1408
+ onClose: () => {
1409
+ window.clearTimeout(timeout);
1410
+ settle();
1411
+ },
1412
+ onError: () => {
1413
+ window.clearTimeout(timeout);
1414
+ settle();
1415
+ }
1416
+ });
1417
+ }
1418
+ catch {
1419
+ window.clearTimeout(timeout);
1420
+ settle();
1421
+ }
1422
+ });
1423
+ };
1424
+ const stripCameraPreview = (info) => {
1425
+ if (!info.camera?.previewDataUrl) {
1426
+ return info;
1427
+ }
1428
+ return {
1429
+ ...info,
1430
+ camera: { ...info.camera, previewDataUrl: undefined }
1431
+ };
1432
+ };
1433
+
1434
+ const measure = async (fn) => {
1435
+ const start = performance.now();
1436
+ const result = await fn();
1437
+ return { result, ms: Math.round(performance.now() - start) };
1438
+ };
1439
+
1440
+ const TRANSFORMERS_CDN = 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js';
1441
+ let transformersRuntimePromise = null;
1442
+ const serializeError$5 = (error) => {
1443
+ if (error instanceof Error) {
1444
+ return { name: error.name, message: error.message, stack: error.stack };
1445
+ }
1446
+ return { message: String(error) };
1447
+ };
1448
+ const ensureTransformersRuntime = () => {
1449
+ if (window.TransformersPipeline) {
1450
+ return Promise.resolve();
1451
+ }
1452
+ if (!transformersRuntimePromise) {
1453
+ transformersRuntimePromise = (async () => {
1454
+ try {
1455
+ const runtimeUrl = TRANSFORMERS_CDN;
1456
+ const transformersModule = await import(/* @vite-ignore */ runtimeUrl);
1457
+ const pipeline = transformersModule?.pipeline;
1458
+ const env = transformersModule?.env;
1459
+ if (typeof pipeline !== 'function' || !env) {
1460
+ throw new Error('Transformers runtime missing pipeline/env exports');
1461
+ }
1462
+ env.allowLocalModels = true;
1463
+ env.allowRemoteModels = true;
1464
+ if (env?.backends?.onnx?.env) {
1465
+ env.backends.onnx.env.logLevel = 'warning';
1466
+ }
1467
+ if ('logLevel' in env) {
1468
+ env.logLevel = 'warning';
1469
+ }
1470
+ window.TransformersPipeline = pipeline;
1471
+ window.TransformersEnv = env;
1472
+ }
1473
+ catch (error) {
1474
+ transformersRuntimePromise = null;
1475
+ console.error('[ZeroGPU][SLM] Failed to import Transformers runtime', {
1476
+ runtimeUrl: TRANSFORMERS_CDN,
1477
+ error: serializeError$5(error)
1478
+ });
1479
+ throw error;
1480
+ }
1481
+ })();
1482
+ }
1483
+ return transformersRuntimePromise;
1484
+ };
1485
+ const sanitizeBaseUrl = (url) => url.replace(/\/$/, '');
1486
+ const HUGGING_FACE_BASE = 'https://huggingface.co';
1487
+ const isHttpUrl = (value) => /^https?:\/\//i.test(value.trim());
1488
+ const normalizeRepoId = (value) => {
1489
+ const trimmed = value.trim();
1490
+ if (!trimmed)
1491
+ return '';
1492
+ if (isHttpUrl(trimmed)) {
1493
+ try {
1494
+ const url = new URL(trimmed);
1495
+ return url.pathname.replace(/^\/+|\/+$/g, '');
1496
+ }
1497
+ catch {
1498
+ return '';
1499
+ }
1500
+ }
1501
+ return trimmed.replace(/^\/+|\/+$/g, '');
1502
+ };
1503
+ const buildRepoResolveBase = (repoId) => {
1504
+ const normalizedRepoId = normalizeRepoId(repoId);
1505
+ if (!normalizedRepoId)
1506
+ return '';
1507
+ return sanitizeBaseUrl(`${HUGGING_FACE_BASE}/${normalizedRepoId}/resolve/main`);
1508
+ };
1509
+ const buildFileBase = (modelUrl, modelRepoId) => {
1510
+ const trimmed = (modelUrl || '').trim();
1511
+ if (isHttpUrl(trimmed)) {
1512
+ return sanitizeBaseUrl(trimmed);
1513
+ }
1514
+ const repoBase = buildRepoResolveBase(modelRepoId || trimmed);
1515
+ if (repoBase)
1516
+ return repoBase;
1517
+ return sanitizeBaseUrl(trimmed);
1518
+ };
1519
+ const normalizeCacheRelativePath = (value) => value.replace(/^\/+/, '').replace(/^resolve\/main\//, '').split('?')[0];
1520
+ const buildModelFileCacheKey = (modelId, relative) => `${modelId}/${normalizeCacheRelativePath(relative)}`;
1521
+ const resolveOnnxWasmPath = () => {
1522
+ try {
1523
+ return new URL('/onnx-wasm/', window.location.origin).toString();
1524
+ }
1525
+ catch {
1526
+ return '/onnx-wasm/';
1527
+ }
1528
+ };
1529
+ const ONNX_WASM_MAGIC = [0x00, 0x61, 0x73, 0x6d];
1530
+ const ONNX_WASM_PROBE_FILES = [
1531
+ 'ort-wasm-simd-threaded.wasm',
1532
+ 'ort-wasm-simd.wasm',
1533
+ 'ort-wasm-threaded.wasm',
1534
+ 'ort-wasm.wasm'
1535
+ ];
1536
+ const normalizeWasmBase = (value) => (value.endsWith('/') ? value : `${value}/`);
1537
+ const buildTransformersDistBaseFromCdn = () => {
1538
+ try {
1539
+ const url = new URL(TRANSFORMERS_CDN);
1540
+ const pathname = url.pathname;
1541
+ const index = pathname.lastIndexOf('/');
1542
+ const directory = index >= 0 ? pathname.slice(0, index + 1) : '/';
1543
+ return `${url.origin}${directory}`;
1544
+ }
1545
+ catch {
1546
+ return 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/';
1547
+ }
1548
+ };
1549
+ const hasWasmMagic = (bytes) => bytes.length >= ONNX_WASM_MAGIC.length &&
1550
+ ONNX_WASM_MAGIC.every((expected, index) => bytes[index] === expected);
1551
+ let onnxWasmOverrideProbePromise = null;
1552
+ const probeOnnxWasmOverridePath = async (fetchImpl) => {
1553
+ const candidateBases = [
1554
+ resolveOnnxWasmPath(),
1555
+ buildTransformersDistBaseFromCdn(),
1556
+ 'https://unpkg.com/@xenova/transformers@2.17.2/dist/'
1557
+ ].map(normalizeWasmBase);
1558
+ for (const baseWithSlash of candidateBases) {
1559
+ let sawNonWasmPayloadAtBase = false;
1560
+ for (const filename of ONNX_WASM_PROBE_FILES) {
1561
+ const requestUrl = (() => {
1562
+ try {
1563
+ return new URL(filename, baseWithSlash).toString();
1564
+ }
1565
+ catch {
1566
+ return `${baseWithSlash}${filename}`;
1567
+ }
1568
+ })();
1569
+ try {
1570
+ const response = await fetchImpl(requestUrl, { cache: 'no-store' });
1571
+ if (!response.ok)
1572
+ continue;
1573
+ const bytes = new Uint8Array(await response.arrayBuffer());
1574
+ if (hasWasmMagic(bytes)) {
1575
+ return baseWithSlash;
1576
+ }
1577
+ sawNonWasmPayloadAtBase = true;
1578
+ break;
1579
+ }
1580
+ catch {
1581
+ // ignore probe failures
1582
+ }
1583
+ }
1584
+ if (sawNonWasmPayloadAtBase) {
1585
+ console.warn('[ZeroGPU][SLM] ONNX wasm probe got non-wasm payload', {
1586
+ wasmBase: baseWithSlash
1587
+ });
1588
+ }
1589
+ }
1590
+ return null;
1591
+ };
1592
+ const getUsableOnnxWasmOverridePath = (fetchImpl) => {
1593
+ if (!onnxWasmOverrideProbePromise) {
1594
+ onnxWasmOverrideProbePromise = probeOnnxWasmOverridePath(fetchImpl);
1595
+ }
1596
+ return onnxWasmOverrideProbePromise;
1597
+ };
1598
+ let transformersEnvMutationChain = Promise.resolve();
1599
+ const withTransformersEnvLock = async (work) => {
1600
+ const previous = transformersEnvMutationChain;
1601
+ let release = () => { };
1602
+ transformersEnvMutationChain = new Promise((resolve) => {
1603
+ release = resolve;
1604
+ });
1605
+ await previous;
1606
+ try {
1607
+ return await work();
1608
+ }
1609
+ finally {
1610
+ release();
1611
+ }
1612
+ };
1613
+
1614
+ const serializeError$4 = (error) => {
1615
+ if (error instanceof Error) {
1616
+ return { name: error.name, message: error.message, stack: error.stack };
1617
+ }
1618
+ return { message: String(error) };
1619
+ };
1620
+ const sessionCache = {};
1621
+ const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requiredFiles, originalFetch) => {
1622
+ const requiredFileList = requiredFiles
1623
+ .map((name) => normalizeCacheRelativePath(name.trim()))
1624
+ .filter((name) => name.length > 0);
1625
+ const requiredFileSet = new Set(requiredFileList);
1626
+ const logger = getLogger();
1627
+ const resolveRequestedRelative = (requestedRelative) => {
1628
+ const normalized = normalizeCacheRelativePath(requestedRelative);
1629
+ if (!normalized)
1630
+ return null;
1631
+ if (requiredFileSet.size === 0 || requiredFileSet.has(normalized)) {
1632
+ return normalized;
1633
+ }
1634
+ if (normalized.startsWith('onnx/') &&
1635
+ normalized.endsWith('.onnx') &&
1636
+ !normalized.endsWith('_quantized.onnx')) {
1637
+ const quantizedCandidate = normalized.replace(/\.onnx$/, '_quantized.onnx');
1638
+ if (requiredFileSet.has(quantizedCandidate)) {
1639
+ return quantizedCandidate;
1640
+ }
1641
+ }
1642
+ return null;
1643
+ };
1644
+ const buildModelRequestUrls = (relative) => {
1645
+ const normalized = normalizeCacheRelativePath(relative);
1646
+ const urls = [];
1647
+ const pushUrl = (value) => {
1648
+ if (!urls.includes(value))
1649
+ urls.push(value);
1650
+ };
1651
+ try {
1652
+ const base = new URL(fileBase);
1653
+ const baseWithSlash = base.toString().endsWith('/') ? base.toString() : `${base.toString()}/`;
1654
+ if (fileBase.endsWith('/resolve/main')) {
1655
+ pushUrl(new URL(normalized, baseWithSlash).toString());
1656
+ }
1657
+ else {
1658
+ pushUrl(new URL(normalized, baseWithSlash).toString());
1659
+ pushUrl(new URL(`resolve/main/${normalized}`, baseWithSlash).toString());
1660
+ }
1661
+ }
1662
+ catch {
1663
+ if (fileBase.endsWith('/resolve/main')) {
1664
+ pushUrl(`${fileBase}/${normalized}`);
1665
+ }
1666
+ else {
1667
+ pushUrl(`${fileBase}/${normalized}`);
1668
+ pushUrl(`${fileBase}/resolve/main/${normalized}`);
1669
+ }
1670
+ }
1671
+ return urls;
1672
+ };
1673
+ const fileBaseUrl = (() => {
1674
+ try {
1675
+ return new URL(fileBase);
1676
+ }
1677
+ catch {
1678
+ return null;
1679
+ }
1680
+ })();
1681
+ const extractModelRelativePath = (requestUrl) => {
1682
+ const pathname = (() => {
1683
+ try {
1684
+ return new URL(requestUrl).pathname;
1685
+ }
1686
+ catch {
1687
+ return requestUrl.split('?')[0] || '';
1688
+ }
1689
+ })();
1690
+ const resolveMainSegment = '/resolve/main/';
1691
+ const resolveMainIndex = pathname.indexOf(resolveMainSegment);
1692
+ if (resolveMainIndex >= 0) {
1693
+ const resolved = pathname.slice(resolveMainIndex + resolveMainSegment.length);
1694
+ return normalizeCacheRelativePath(resolved);
1695
+ }
1696
+ if (!fileBaseUrl)
1697
+ return null;
1698
+ const basePath = fileBaseUrl.pathname.replace(/\/$/, '');
1699
+ if (!pathname.startsWith(`${basePath}/`))
1700
+ return null;
1701
+ const relative = pathname.slice(basePath.length + 1);
1702
+ return normalizeCacheRelativePath(relative);
1703
+ };
1704
+ return async (url, init) => {
1705
+ const originalRequestUrl = typeof url === 'string' ? url : url instanceof URL ? url.toString() : url.url;
1706
+ const requestedRelative = extractModelRelativePath(originalRequestUrl);
1707
+ if (!requestedRelative) {
1708
+ const isWasmOrOrtRequest = /\.wasm(?:\?|$)/i.test(originalRequestUrl) || /onnxruntime|ort-wasm/i.test(originalRequestUrl);
1709
+ if (!isWasmOrOrtRequest) {
1710
+ return originalFetch(url, init);
1711
+ }
1712
+ try {
1713
+ return await originalFetch(url, init);
1714
+ }
1715
+ catch (error) {
1716
+ console.error('[ZeroGPU][SLM][fetch] non-model wasm/ort request failed', {
1717
+ modelId,
1718
+ requestUrl: originalRequestUrl,
1719
+ error: serializeError$4(error)
1720
+ });
1721
+ throw error;
1722
+ }
1723
+ }
1724
+ const relative = resolveRequestedRelative(requestedRelative);
1725
+ if (!relative) {
1726
+ logger.warn('[SLM] Unexpected model file request; falling back to original fetch', {
1727
+ requestedRelative,
1728
+ modelId
1729
+ });
1730
+ return originalFetch(url, init);
1731
+ }
1732
+ const requestUrls = buildModelRequestUrls(relative);
1733
+ const normalizedRelative = normalizeCacheRelativePath(relative);
1734
+ const modelScopedKey = buildModelFileCacheKey(modelId, normalizedRelative);
1735
+ let blob = sessionCache[modelScopedKey] ||
1736
+ cachedFiles[modelScopedKey] ||
1737
+ sessionCache[normalizedRelative] ||
1738
+ cachedFiles[normalizedRelative] ||
1739
+ cachedFiles[`onnx/${normalizedRelative}`] ||
1740
+ sessionCache[`onnx/${normalizedRelative}`];
1741
+ if (!blob && normalizedRelative.startsWith('onnx/')) {
1742
+ const trimmed = normalizedRelative.replace('onnx/', '');
1743
+ blob =
1744
+ cachedFiles[trimmed] ||
1745
+ sessionCache[trimmed] ||
1746
+ cachedFiles[buildModelFileCacheKey(modelId, trimmed)] ||
1747
+ sessionCache[buildModelFileCacheKey(modelId, trimmed)];
1748
+ }
1749
+ if (blob) {
1750
+ return new Response(blob);
1751
+ }
1752
+ try {
1753
+ for (const requestUrl of requestUrls) {
1754
+ const response = await originalFetch(requestUrl, init);
1755
+ if (response.ok) {
1756
+ const downloadedBlob = await response.blob();
1757
+ sessionCache[modelScopedKey] = downloadedBlob;
1758
+ if (onFileDownloaded) {
1759
+ onFileDownloaded(modelScopedKey, downloadedBlob);
1760
+ }
1761
+ return new Response(downloadedBlob);
1762
+ }
1763
+ }
1764
+ return new Response('required_file_not_found', { status: 404, statusText: 'Not Found' });
1765
+ }
1766
+ catch (err) {
1767
+ logger.warn(`[ZeroGPU] Failed to fetch ${relative}:`, err);
1768
+ return new Response('model_file_fetch_failed', { status: 502, statusText: 'Bad Gateway' });
1769
+ }
1770
+ };
1771
+ };
1772
+
1773
+ const TASK_PIPELINE_MAP = {
1774
+ summary: 'summarization',
1775
+ iab_classify: 'text-classification',
1776
+ classification: 'zero-shot-classification',
1777
+ text_generation: 'text2text-generation'
1778
+ };
1779
+ const serializeError$3 = (error) => {
1780
+ if (error instanceof Error) {
1781
+ return { name: error.name, message: error.message, stack: error.stack };
1782
+ }
1783
+ return { message: String(error) };
1784
+ };
1785
+ const isInvalidArrayLengthError = (error) => {
1786
+ const message = error instanceof Error ? error.message : String(error);
1787
+ return message.toLowerCase().includes('invalid array length');
1788
+ };
1789
+ const extractTextFromRaw = (raw) => {
1790
+ if (typeof raw === 'string')
1791
+ return raw;
1792
+ if (Array.isArray(raw) && raw.length) {
1793
+ const first = raw[0];
1794
+ if (first && typeof first.summary_text === 'string')
1795
+ return first.summary_text;
1796
+ if (first && typeof first.generated_text === 'string')
1797
+ return first.generated_text;
1798
+ if (first && typeof first.label === 'string')
1799
+ return first.label;
1800
+ try {
1801
+ return JSON.stringify(first);
1802
+ }
1803
+ catch {
1804
+ return String(first ?? '');
1805
+ }
1806
+ }
1807
+ if (raw && typeof raw === 'object') {
1808
+ const obj = raw;
1809
+ if (typeof obj.summary_text === 'string')
1810
+ return obj.summary_text;
1811
+ if (typeof obj.generated_text === 'string')
1812
+ return obj.generated_text;
1813
+ if (typeof obj.label === 'string')
1814
+ return obj.label;
1815
+ try {
1816
+ return JSON.stringify(obj);
1817
+ }
1818
+ catch {
1819
+ return String(obj);
1820
+ }
1821
+ }
1822
+ return '';
1823
+ };
1824
+ const isZeroShotClassificationOutput = (output) => {
1825
+ if (!output || typeof output !== 'object' || Array.isArray(output))
1826
+ return false;
1827
+ const candidate = output;
1828
+ return Array.isArray(candidate.labels) && Array.isArray(candidate.scores);
1829
+ };
1830
+ const mapLabelsToScores = (output) => {
1831
+ const labels = output.labels;
1832
+ const scores = output.scores;
1833
+ if (!Array.isArray(labels) || !Array.isArray(scores))
1834
+ return null;
1835
+ const entries = labels.flatMap((label, index) => {
1836
+ const score = scores[index];
1837
+ return typeof label === 'string' && typeof score === 'number'
1838
+ ? [[label, score]]
1839
+ : [];
1840
+ });
1841
+ return entries.length > 0 ? Object.fromEntries(entries) : null;
1842
+ };
1843
+ const normalizeCategories = (value) => {
1844
+ if (Array.isArray(value)) {
1845
+ const categories = value.filter((category) => typeof category === 'string');
1846
+ return categories.length > 0 ? categories : undefined;
1847
+ }
1848
+ if (typeof value === 'string' && value.length > 0)
1849
+ return [value];
1850
+ return undefined;
1851
+ };
1852
+ const sanitizeText = (text, fallback) => {
1853
+ const trimmed = (text ?? '').trim();
1854
+ if (!trimmed)
1855
+ return fallback;
1856
+ return trimmed.slice(0, 1024);
1857
+ };
1858
+ const hasMeaningfulOutput = (output) => {
1859
+ if (output == null)
1860
+ return false;
1861
+ if (typeof output === 'string')
1862
+ return output.trim().length > 0;
1863
+ if (Array.isArray(output))
1864
+ return output.length > 0;
1865
+ if (typeof output === 'object')
1866
+ return Object.keys(output).length > 0;
1867
+ return true;
1868
+ };
1869
+ const runPipeline = async (state, text, options) => {
1870
+ const { pipeline, pipelineTask } = state;
1871
+ const { result, ms } = await measure(async () => {
1872
+ if (pipelineTask === 'zero-shot-classification') {
1873
+ if (!options?.categories || options.categories.length === 0) {
1874
+ throw new Error('classification_categories_required');
1875
+ }
1876
+ return pipeline(text, options.categories);
1877
+ }
1878
+ if (pipelineTask === 'summarization') {
1879
+ return pipeline(text, {
1880
+ max_new_tokens: options?.maxNewTokens ?? 64,
1881
+ min_length: 1,
1882
+ do_sample: false
1883
+ });
1884
+ }
1885
+ if (pipelineTask === 'text2text-generation') {
1886
+ return pipeline(text, {
1887
+ max_new_tokens: options?.maxNewTokens ?? 128,
1888
+ do_sample: false
1889
+ });
1890
+ }
1891
+ return pipeline(text);
1892
+ });
1893
+ return { raw: result, ms };
1894
+ };
1895
+ const runWithFallback = async (state, text, options) => {
1896
+ try {
1897
+ return await runPipeline(state, text, options);
1898
+ }
1899
+ catch (error) {
1900
+ if (!isInvalidArrayLengthError(error) || text.length <= 256)
1901
+ throw error;
1902
+ const truncated = text.slice(0, 256);
1903
+ return await runPipeline(state, truncated, options);
1904
+ }
1905
+ };
1906
+ class OnnxAdapter {
1907
+ constructor(config, state, metrics) {
1908
+ this.config = config;
1909
+ this.capability = {
1910
+ inferenceFramework: 'ONNX',
1911
+ taskType: config.taskType,
1912
+ modelType: config.modelType
1913
+ };
1914
+ this.state = state;
1915
+ this.metrics = metrics;
1916
+ }
1917
+ async runInference(input) {
1918
+ const taskType = this.config.taskType;
1919
+ const text = sanitizeText(input.text, 'summarize this text');
1920
+ if (taskType === 'classification') {
1921
+ const categories = normalizeCategories(input.categories) ?? normalizeCategories(input.category);
1922
+ const { raw, ms } = await runWithFallback(this.state, text, { categories });
1923
+ if (isZeroShotClassificationOutput(raw)) {
1924
+ const scoreDict = mapLabelsToScores(raw);
1925
+ return { output: scoreDict ?? raw, inferenceMs: ms };
1926
+ }
1927
+ return { output: raw, inferenceMs: ms };
1928
+ }
1929
+ if (taskType === 'iab_classify') {
1930
+ const { raw, ms } = await runWithFallback(this.state, text);
1931
+ return { output: raw, inferenceMs: ms };
1932
+ }
1933
+ if (taskType === 'summary') {
1934
+ const { raw, ms } = await runWithFallback(this.state, text, {
1935
+ maxNewTokens: input.maxNewTokens
1936
+ });
1937
+ return { output: { text: extractTextFromRaw(raw) }, inferenceMs: ms };
1938
+ }
1939
+ if (taskType === 'text_generation') {
1940
+ const { raw, ms } = await runWithFallback(this.state, text, {
1941
+ maxNewTokens: input.maxNewTokens
1942
+ });
1943
+ return { output: { text: extractTextFromRaw(raw) }, inferenceMs: ms };
1944
+ }
1945
+ const { raw, ms } = await runWithFallback(this.state, text);
1946
+ return { output: raw, inferenceMs: ms };
1947
+ }
1948
+ async runSample(sample) {
1949
+ const start = performance.now();
1950
+ if (typeof sample.text !== 'string') {
1951
+ return {
1952
+ ok: false,
1953
+ processingTimeMs: Math.round(performance.now() - start),
1954
+ error: true,
1955
+ errorMessage: 'response from processing sample'
1956
+ };
1957
+ }
1958
+ try {
1959
+ const result = await this.runInference({
1960
+ text: sample.text,
1961
+ categories: sample.categories,
1962
+ category: sample.category,
1963
+ usecase: sample.usecase
1964
+ });
1965
+ const processingTimeMs = Math.round(performance.now() - start);
1966
+ if (!hasMeaningfulOutput(result.output)) {
1967
+ return {
1968
+ ok: false,
1969
+ processingTimeMs,
1970
+ error: true,
1971
+ errorMessage: 'response from processing sample'
1972
+ };
1973
+ }
1974
+ return { ok: true, processingTimeMs, error: false };
1975
+ }
1976
+ catch (err) {
1977
+ return {
1978
+ ok: false,
1979
+ processingTimeMs: Math.round(performance.now() - start),
1980
+ error: true,
1981
+ errorMessage: err instanceof Error ? err.message : String(err)
1982
+ };
1983
+ }
1984
+ }
1985
+ }
1986
+ const instantiatePipeline = async (slm, cachedFiles, onFileDownloaded) => {
1987
+ const logger = getLogger();
1988
+ try {
1989
+ await ensureTransformersRuntime();
1990
+ }
1991
+ catch (error) {
1992
+ const message = error instanceof Error ? error.message : String(error);
1993
+ throw new Error(`transformers_runtime_load_failed:${message}`);
1994
+ }
1995
+ const fileBase = sanitizeBaseUrl(buildFileBase(slm.modelUrl, slm.modelRepoId));
1996
+ const pipelineTask = TASK_PIPELINE_MAP[slm.taskType] ?? slm.taskType;
1997
+ const modelSource = isHttpUrl(slm.modelUrl || '')
1998
+ ? (slm.modelUrl || '').trim()
1999
+ : (slm.modelRepoId || slm.modelUrl || '').trim();
2000
+ if (!modelSource) {
2001
+ throw new Error('[SLM] Invalid modelSource: expected non-empty modelRepoId or modelUrl');
2002
+ }
2003
+ const loadResult = await withTransformersEnvLock(async () => {
2004
+ const env = window.TransformersEnv || {};
2005
+ env.allowRemoteModels = true;
2006
+ env.allowLocalModels = true;
2007
+ if (!env.backends)
2008
+ env.backends = {};
2009
+ if (!env.backends.onnx)
2010
+ env.backends.onnx = {};
2011
+ if (!env.backends.onnx.wasm)
2012
+ env.backends.onnx.wasm = {};
2013
+ const transformersLogLevel = logger.isEnabled() ? 'error' : 'fatal';
2014
+ if (env?.backends?.onnx?.env) {
2015
+ env.backends.onnx.env.logLevel = transformersLogLevel;
2016
+ }
2017
+ env.backends.onnx.wasm.proxy = false;
2018
+ env.backends.onnx.wasm.numThreads = 1;
2019
+ const originalFetch = window.fetch.bind(window);
2020
+ const wasmOverridePath = await getUsableOnnxWasmOverridePath(originalFetch);
2021
+ if (wasmOverridePath) {
2022
+ env.backends.onnx.wasm.wasmPaths = wasmOverridePath;
2023
+ }
2024
+ else {
2025
+ try {
2026
+ delete env.backends.onnx.wasm.wasmPaths;
2027
+ }
2028
+ catch {
2029
+ env.backends.onnx.wasm.wasmPaths = undefined;
2030
+ }
2031
+ }
2032
+ if ('logLevel' in env) {
2033
+ env.logLevel = transformersLogLevel;
2034
+ }
2035
+ const ort = window.ort;
2036
+ if (ort?.env) {
2037
+ ort.env.logLevel = transformersLogLevel;
2038
+ }
2039
+ env.fetch = createEnvFetch(slm.modelId, fileBase, cachedFiles, onFileDownloaded, (slm.requiredFiles ?? []).map((file) => file.name), originalFetch);
2040
+ window.TransformersEnv = env;
2041
+ window.fetch = env.fetch;
2042
+ const runPipelineLoad = () => measure(() => window.TransformersPipeline(pipelineTask, modelSource, {
2043
+ device: 'wasm',
2044
+ quantized: slm.quantized,
2045
+ progress_callback: () => { }
2046
+ }));
2047
+ try {
2048
+ return await runPipelineLoad();
2049
+ }
2050
+ catch (firstError) {
2051
+ const wasmEnv = env?.backends?.onnx?.wasm;
2052
+ const hadWasmPathOverride = Boolean(wasmEnv && 'wasmPaths' in wasmEnv && wasmEnv.wasmPaths);
2053
+ let lastError = firstError;
2054
+ if (wasmEnv) {
2055
+ const previousSimd = wasmEnv.simd;
2056
+ const previousThreads = wasmEnv.numThreads;
2057
+ const previousProxy = wasmEnv.proxy;
2058
+ wasmEnv.simd = false;
2059
+ wasmEnv.numThreads = 1;
2060
+ wasmEnv.proxy = false;
2061
+ try {
2062
+ return await runPipelineLoad();
2063
+ }
2064
+ catch (compatError) {
2065
+ lastError = compatError;
2066
+ wasmEnv.simd = previousSimd;
2067
+ wasmEnv.numThreads = previousThreads;
2068
+ wasmEnv.proxy = previousProxy;
2069
+ }
2070
+ }
2071
+ if (!hadWasmPathOverride || !wasmEnv) {
2072
+ const message = lastError instanceof Error ? lastError.message : String(lastError);
2073
+ throw new Error(`pipeline_load_failed:${message}`);
2074
+ }
2075
+ const previousWasmPaths = wasmEnv.wasmPaths;
2076
+ try {
2077
+ delete wasmEnv.wasmPaths;
2078
+ }
2079
+ catch {
2080
+ wasmEnv.wasmPaths = undefined;
2081
+ }
2082
+ try {
2083
+ return await runPipelineLoad();
2084
+ }
2085
+ catch (secondError) {
2086
+ const message = secondError instanceof Error ? secondError.message : String(secondError);
2087
+ throw new Error(`pipeline_load_failed:${message}`);
2088
+ }
2089
+ finally {
2090
+ wasmEnv.wasmPaths = previousWasmPaths;
2091
+ }
2092
+ }
2093
+ finally {
2094
+ window.fetch = originalFetch;
2095
+ }
2096
+ });
2097
+ const { result: pipeline, ms: loadModelMs } = loadResult;
2098
+ return { pipeline: pipeline, pipelineTask, loadModelMs };
2099
+ };
2100
+ const loadOnnxAdapter = async (slm, options) => {
2101
+ const logger = getLogger();
2102
+ const startTime = performance.now();
2103
+ const downloadedFiles = {};
2104
+ try {
2105
+ const cached = await getModel(slm.modelId, slm.modelVersion);
2106
+ const cachedFiles = cached?.files || {};
2107
+ if (!cached && options?.allowDownload === false) {
2108
+ return { error: new Error('model_not_cached'), metrics: {} };
2109
+ }
2110
+ const onFileDownloaded = (filename, blob) => {
2111
+ downloadedFiles[filename] = blob;
2112
+ };
2113
+ const baseMetrics = cached
2114
+ ? {
2115
+ downloadMs: cached.metadata.downloadMs,
2116
+ loadModelMs: cached.metadata.loadModelMs,
2117
+ sizeBytes: cached.metadata.sizeBytes
2118
+ }
2119
+ : {};
2120
+ const state = await instantiatePipeline(slm, cachedFiles, onFileDownloaded);
2121
+ const metrics = { ...baseMetrics, loadModelMs: state.loadModelMs };
2122
+ if (Object.keys(downloadedFiles).length > 0) {
2123
+ const allFiles = { ...cachedFiles, ...downloadedFiles };
2124
+ const calculatedSize = Object.values(allFiles).reduce((sum, blob) => sum + blob.size, 0);
2125
+ const downloadMs = Math.round(performance.now() - startTime);
2126
+ await putModelComplete(slm.modelId, slm.modelVersion, {
2127
+ modelId: slm.modelId,
2128
+ modelVersion: slm.modelVersion,
2129
+ sizeBytes: calculatedSize,
2130
+ downloadMs: cached ? 0 : downloadMs,
2131
+ loadModelMs: state.loadModelMs
2132
+ }, allFiles);
2133
+ metrics.sizeBytes = calculatedSize;
2134
+ if (!cached)
2135
+ metrics.downloadMs = downloadMs;
2136
+ }
2137
+ const adapter = new OnnxAdapter(slm, state, metrics);
2138
+ return { adapter, metrics };
2139
+ }
2140
+ catch (error) {
2141
+ const message = error instanceof Error ? error.message : String(error);
2142
+ if (message.includes("Unexpected token '<'")) {
2143
+ console.error('[ZeroGPU][SLM][loadOnnxAdapter] Parse error suggests HTML returned where JSON expected', { modelId: slm.modelId, modelUrl: slm.modelUrl });
2144
+ }
2145
+ console.error('[ZeroGPU][SLM][loadOnnxAdapter] failed', {
2146
+ modelId: slm.modelId,
2147
+ modelVersion: slm.modelVersion,
2148
+ modelRepoId: slm.modelRepoId,
2149
+ modelUrl: slm.modelUrl,
2150
+ requiredFiles: (slm.requiredFiles ?? []).map((file) => file.name),
2151
+ error: serializeError$3(error)
2152
+ });
2153
+ logger.error('ONNX adapter load failed', error);
2154
+ await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
2155
+ return { error: error, metrics: {} };
2156
+ }
2157
+ };
2158
+
2159
+ const capabilities$2 = [
2160
+ { inferenceFramework: 'ONNX', taskType: 'summary' },
2161
+ { inferenceFramework: 'ONNX', taskType: 'iab_classify' },
2162
+ { inferenceFramework: 'ONNX', taskType: 'classification' },
2163
+ { inferenceFramework: 'ONNX', taskType: 'text_generation' }
2164
+ ];
2165
+ const factory$2 = {
2166
+ capabilities: capabilities$2,
2167
+ load: (config, options) => loadOnnxAdapter(config, options)
2168
+ };
2169
+ registerAdapter(factory$2);
2170
+
2171
+ const DEFAULT_THRESHOLD = 0.4;
2172
+ const DEFAULT_MASK = '[REDACTED]';
2173
+ const serializeError$2 = (error) => {
2174
+ if (error instanceof Error) {
2175
+ return { name: error.name, message: error.message, stack: error.stack };
2176
+ }
2177
+ return { message: String(error) };
2178
+ };
2179
+ const parseTokenClassificationOutput = (raw, sourceText) => {
2180
+ if (!Array.isArray(raw))
2181
+ return [];
2182
+ return raw.flatMap((item) => {
2183
+ if (!item || typeof item !== 'object')
2184
+ return [];
2185
+ const obj = item;
2186
+ const label = typeof obj.entity_group === 'string'
2187
+ ? obj.entity_group
2188
+ : typeof obj.entity === 'string'
2189
+ ? obj.entity
2190
+ : typeof obj.label === 'string'
2191
+ ? obj.label
2192
+ : null;
2193
+ if (!label)
2194
+ return [];
2195
+ const score = typeof obj.score === 'number' ? obj.score : 0;
2196
+ const start = typeof obj.start === 'number' ? obj.start : -1;
2197
+ const end = typeof obj.end === 'number' ? obj.end : -1;
2198
+ const word = typeof obj.word === 'string'
2199
+ ? obj.word
2200
+ : typeof obj.text === 'string'
2201
+ ? obj.text
2202
+ : start >= 0 && end > start
2203
+ ? sourceText.slice(start, end)
2204
+ : '';
2205
+ if (!word)
2206
+ return [];
2207
+ return [{ text: word, label, score, start, end }];
2208
+ });
2209
+ };
2210
+ const filterByThreshold = (entities, threshold) => entities.filter((entity) => entity.score >= threshold);
2211
+ const filterByLabels = (entities, labels) => {
2212
+ if (!labels || labels.length === 0)
2213
+ return entities;
2214
+ const allowed = new Set(labels.map((label) => label.toLowerCase()));
2215
+ return entities.filter((entity) => allowed.has(entity.label.toLowerCase()));
2216
+ };
2217
+ const redactEntities = (text, entities, mask) => {
2218
+ if (entities.length === 0)
2219
+ return text;
2220
+ const sorted = [...entities].sort((a, b) => b.start - a.start);
2221
+ let result = text;
2222
+ for (const entity of sorted) {
2223
+ if (entity.start < 0 || entity.end <= entity.start)
2224
+ continue;
2225
+ const replacement = mask.includes('LABEL') ? mask.replace('LABEL', entity.label) : mask;
2226
+ result = result.slice(0, entity.start) + replacement + result.slice(entity.end);
2227
+ }
2228
+ return result;
2229
+ };
2230
+ const buildJsonFromSchema = (schema, entities) => {
2231
+ if (!schema || typeof schema !== 'object')
2232
+ return {};
2233
+ const result = {};
2234
+ for (const [groupKey, groupValue] of Object.entries(schema)) {
2235
+ const fields = Array.isArray(groupValue) ? groupValue : [];
2236
+ const subResult = {};
2237
+ for (const field of fields) {
2238
+ if (typeof field !== 'string')
2239
+ continue;
2240
+ const name = field.split('::')[0];
2241
+ const match = entities.find((entity) => entity.label.toLowerCase() === name.toLowerCase());
2242
+ if (match)
2243
+ subResult[name] = match.text;
2244
+ }
2245
+ result[groupKey] = subResult;
2246
+ }
2247
+ return result;
2248
+ };
2249
+ const computeClassificationScores = (entities, labels) => {
2250
+ const scores = {};
2251
+ for (const label of labels) {
2252
+ const best = entities
2253
+ .filter((entity) => entity.label.toLowerCase() === label.toLowerCase())
2254
+ .reduce((max, entity) => Math.max(max, entity.score), 0);
2255
+ scores[label] = best;
2256
+ }
2257
+ return scores;
2258
+ };
2259
+ class TransformersAdapter {
2260
+ constructor(config, state, metrics) {
2261
+ this.config = config;
2262
+ this.capability = {
2263
+ inferenceFramework: 'Transformers',
2264
+ taskType: config.taskType,
2265
+ modelType: config.modelType
2266
+ };
2267
+ this.state = state;
2268
+ this.metrics = metrics;
2269
+ }
2270
+ async runInference(input) {
2271
+ const text = (input.text ?? '').trim();
2272
+ if (!text) {
2273
+ return { output: { entities: [] }, inferenceMs: 0 };
2274
+ }
2275
+ const threshold = typeof input.threshold === 'number' && Number.isFinite(input.threshold)
2276
+ ? input.threshold
2277
+ : DEFAULT_THRESHOLD;
2278
+ const usecase = (input.usecase ?? 'ner').toLowerCase();
2279
+ const { result, ms } = await measure(async () => this.state.pipeline(text));
2280
+ const allEntities = parseTokenClassificationOutput(result, text);
2281
+ const thresholded = filterByThreshold(allEntities, threshold);
2282
+ const labels = Array.isArray(input.labels) ? input.labels : undefined;
2283
+ const filtered = filterByLabels(thresholded, labels);
2284
+ if (usecase === 'redact') {
2285
+ const mask = typeof input.mask === 'string' && input.mask.length > 0 ? input.mask : DEFAULT_MASK;
2286
+ const redacted = redactEntities(text, filtered, mask);
2287
+ return { output: { text: redacted, entities: filtered }, inferenceMs: ms };
2288
+ }
2289
+ if (usecase === 'json') {
2290
+ const json = buildJsonFromSchema(input.schema, filtered);
2291
+ return { output: json, inferenceMs: ms };
2292
+ }
2293
+ if (usecase === 'classification') {
2294
+ const classificationLabels = labels ?? [];
2295
+ const scores = computeClassificationScores(thresholded, classificationLabels);
2296
+ return { output: scores, inferenceMs: ms };
2297
+ }
2298
+ // ner, extract-pii, extract-entities, default
2299
+ return { output: { entities: filtered }, inferenceMs: ms };
2300
+ }
2301
+ async runSample(sample) {
2302
+ const start = performance.now();
2303
+ if (typeof sample.text !== 'string') {
2304
+ return {
2305
+ ok: false,
2306
+ processingTimeMs: Math.round(performance.now() - start),
2307
+ error: true,
2308
+ errorMessage: 'response from processing sample'
2309
+ };
2310
+ }
2311
+ try {
2312
+ await this.runInference({
2313
+ text: sample.text,
2314
+ labels: sample.labels,
2315
+ threshold: sample.threshold,
2316
+ usecase: sample.usecase ?? 'ner',
2317
+ schema: sample.schema,
2318
+ mask: sample.mask,
2319
+ categories: sample.categories
2320
+ });
2321
+ return {
2322
+ ok: true,
2323
+ processingTimeMs: Math.round(performance.now() - start),
2324
+ error: false,
2325
+ errorMessage: undefined
2326
+ };
2327
+ }
2328
+ catch (err) {
2329
+ return {
2330
+ ok: false,
2331
+ processingTimeMs: Math.round(performance.now() - start),
2332
+ error: true,
2333
+ errorMessage: err instanceof Error ? err.message : String(err)
2334
+ };
2335
+ }
2336
+ }
2337
+ }
2338
+ const instantiateTokenPipeline = async (slm, cachedFiles, onFileDownloaded) => {
2339
+ const logger = getLogger();
2340
+ try {
2341
+ await ensureTransformersRuntime();
2342
+ }
2343
+ catch (error) {
2344
+ const message = error instanceof Error ? error.message : String(error);
2345
+ throw new Error(`transformers_runtime_load_failed:${message}`);
2346
+ }
2347
+ const fileBase = sanitizeBaseUrl(buildFileBase(slm.modelUrl, slm.modelRepoId));
2348
+ const modelSource = isHttpUrl(slm.modelUrl || '')
2349
+ ? (slm.modelUrl || '').trim()
2350
+ : (slm.modelRepoId || slm.modelUrl || '').trim();
2351
+ if (!modelSource) {
2352
+ throw new Error('[Transformers] Invalid modelSource: expected non-empty modelRepoId or modelUrl');
2353
+ }
2354
+ const loadResult = await withTransformersEnvLock(async () => {
2355
+ const env = window.TransformersEnv || {};
2356
+ env.allowRemoteModels = true;
2357
+ env.allowLocalModels = true;
2358
+ if (!env.backends)
2359
+ env.backends = {};
2360
+ if (!env.backends.onnx)
2361
+ env.backends.onnx = {};
2362
+ if (!env.backends.onnx.wasm)
2363
+ env.backends.onnx.wasm = {};
2364
+ env.backends.onnx.wasm.proxy = false;
2365
+ env.backends.onnx.wasm.numThreads = 1;
2366
+ const originalFetch = window.fetch.bind(window);
2367
+ const wasmOverridePath = await getUsableOnnxWasmOverridePath(originalFetch);
2368
+ if (wasmOverridePath) {
2369
+ env.backends.onnx.wasm.wasmPaths = wasmOverridePath;
2370
+ }
2371
+ env.fetch = createEnvFetch(slm.modelId, fileBase, cachedFiles, onFileDownloaded, (slm.requiredFiles ?? []).map((file) => file.name), originalFetch);
2372
+ window.TransformersEnv = env;
2373
+ window.fetch = env.fetch;
2374
+ const runPipelineLoad = () => measure(() => window.TransformersPipeline('token-classification', modelSource, {
2375
+ device: 'wasm',
2376
+ quantized: slm.quantized,
2377
+ aggregation_strategy: 'simple',
2378
+ progress_callback: () => { }
2379
+ }));
2380
+ try {
2381
+ return await runPipelineLoad();
2382
+ }
2383
+ catch (firstError) {
2384
+ const message = firstError instanceof Error ? firstError.message : String(firstError);
2385
+ logger.warn('[Transformers] token-classification pipeline load failed', { message });
2386
+ throw new Error(`transformers_pipeline_load_failed:${message}`);
2387
+ }
2388
+ finally {
2389
+ window.fetch = originalFetch;
2390
+ }
2391
+ });
2392
+ const { result: pipeline, ms: loadModelMs } = loadResult;
2393
+ return { pipeline: pipeline, loadModelMs };
2394
+ };
2395
+ const loadTransformersAdapter = async (slm, options) => {
2396
+ const logger = getLogger();
2397
+ const startTime = performance.now();
2398
+ const downloadedFiles = {};
2399
+ try {
2400
+ const cached = await getModel(slm.modelId, slm.modelVersion);
2401
+ const cachedFiles = cached?.files || {};
2402
+ if (!cached && options?.allowDownload === false) {
2403
+ return { error: new Error('model_not_cached'), metrics: {} };
2404
+ }
2405
+ const onFileDownloaded = (filename, blob) => {
2406
+ downloadedFiles[filename] = blob;
2407
+ };
2408
+ const baseMetrics = cached
2409
+ ? {
2410
+ downloadMs: cached.metadata.downloadMs,
2411
+ loadModelMs: cached.metadata.loadModelMs,
2412
+ sizeBytes: cached.metadata.sizeBytes
2413
+ }
2414
+ : {};
2415
+ const state = await instantiateTokenPipeline(slm, cachedFiles, onFileDownloaded);
2416
+ const metrics = { ...baseMetrics, loadModelMs: state.loadModelMs };
2417
+ if (Object.keys(downloadedFiles).length > 0) {
2418
+ const allFiles = { ...cachedFiles, ...downloadedFiles };
2419
+ const calculatedSize = Object.values(allFiles).reduce((sum, blob) => sum + blob.size, 0);
2420
+ const downloadMs = Math.round(performance.now() - startTime);
2421
+ await putModelComplete(slm.modelId, slm.modelVersion, {
2422
+ modelId: slm.modelId,
2423
+ modelVersion: slm.modelVersion,
2424
+ sizeBytes: calculatedSize,
2425
+ downloadMs: cached ? 0 : downloadMs,
2426
+ loadModelMs: state.loadModelMs
2427
+ }, allFiles);
2428
+ metrics.sizeBytes = calculatedSize;
2429
+ if (!cached)
2430
+ metrics.downloadMs = downloadMs;
2431
+ }
2432
+ const adapter = new TransformersAdapter(slm, state, metrics);
2433
+ return { adapter, metrics };
2434
+ }
2435
+ catch (error) {
2436
+ console.error('[ZeroGPU][Transformers][load] failed', {
2437
+ modelId: slm.modelId,
2438
+ modelVersion: slm.modelVersion,
2439
+ modelRepoId: slm.modelRepoId,
2440
+ modelUrl: slm.modelUrl,
2441
+ error: serializeError$2(error)
2442
+ });
2443
+ logger.error('Transformers adapter load failed', error);
2444
+ await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
2445
+ return { error: error, metrics: {} };
2446
+ }
2447
+ };
2448
+
2449
+ const capabilities$1 = [
2450
+ { inferenceFramework: 'Transformers', taskType: 'gliner' },
2451
+ { inferenceFramework: 'Transformers', taskType: 'gliner2' }
2452
+ ];
2453
+ const factory$1 = {
2454
+ capabilities: capabilities$1,
2455
+ load: (config, options) => loadTransformersAdapter(config, options)
2456
+ };
2457
+ registerAdapter(factory$1);
2458
+
2459
+ const WLLAMA_CDN = 'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.5/esm/index.js';
2460
+ let wllamaRuntimePromise = null;
2461
+ const serializeError$1 = (error) => {
2462
+ if (error instanceof Error) {
2463
+ return { name: error.name, message: error.message, stack: error.stack };
2464
+ }
2465
+ return { message: String(error) };
2466
+ };
2467
+ const ensureWllamaRuntime = () => {
2468
+ if (window.WllamaModule) {
2469
+ return Promise.resolve(window.WllamaModule);
2470
+ }
2471
+ if (!wllamaRuntimePromise) {
2472
+ wllamaRuntimePromise = (async () => {
2473
+ try {
2474
+ const mod = await import(/* @vite-ignore */ WLLAMA_CDN);
2475
+ if (!mod?.Wllama) {
2476
+ throw new Error('Wllama runtime missing Wllama export');
2477
+ }
2478
+ window.WllamaModule = mod;
2479
+ return mod;
2480
+ }
2481
+ catch (error) {
2482
+ wllamaRuntimePromise = null;
2483
+ console.error('[ZeroGPU][GGUF] Failed to import wllama runtime', {
2484
+ runtimeUrl: WLLAMA_CDN,
2485
+ error: serializeError$1(error)
2486
+ });
2487
+ throw error;
2488
+ }
2489
+ })();
2490
+ }
2491
+ return wllamaRuntimePromise;
2492
+ };
2493
+ const WLLAMA_CDN_BASE = WLLAMA_CDN.replace(/\/esm\/index\.js$/, '/esm');
2494
+
2495
+ const DEFAULT_MAX_NEW_TOKENS = 128;
2496
+ const serializeError = (error) => {
2497
+ if (error instanceof Error) {
2498
+ return { name: error.name, message: error.message, stack: error.stack };
2499
+ }
2500
+ return { message: String(error) };
2501
+ };
2502
+ const pickGgufFileName = (requiredFiles) => {
2503
+ if (!Array.isArray(requiredFiles) || requiredFiles.length === 0)
2504
+ return null;
2505
+ const ggufFile = requiredFiles.find((file) => file?.name?.toLowerCase().endsWith('.gguf'));
2506
+ return ggufFile?.name ?? requiredFiles[0]?.name ?? null;
2507
+ };
2508
+ const buildPrompt = (text, modelType) => {
2509
+ const trimmed = (text ?? '').trim();
2510
+ if (!trimmed)
2511
+ return '';
2512
+ if (modelType && modelType.toLowerCase().includes('instruct')) {
2513
+ return `<|im_start|>user\n${trimmed}<|im_end|>\n<|im_start|>assistant\n`;
2514
+ }
2515
+ return trimmed;
2516
+ };
2517
+ class GgufAdapter {
2518
+ constructor(config, state, metrics) {
2519
+ this.config = config;
2520
+ this.capability = {
2521
+ inferenceFramework: 'GGUF',
2522
+ taskType: config.taskType,
2523
+ modelType: config.modelType
2524
+ };
2525
+ this.state = state;
2526
+ this.metrics = metrics;
2527
+ }
2528
+ async runInference(input) {
2529
+ const prompt = buildPrompt(input.text ?? '', this.config.modelType);
2530
+ if (!prompt) {
2531
+ return { output: { text: '' }, inferenceMs: 0 };
2532
+ }
2533
+ const maxNewTokens = typeof input.maxNewTokens === 'number' && input.maxNewTokens > 0
2534
+ ? input.maxNewTokens
2535
+ : DEFAULT_MAX_NEW_TOKENS;
2536
+ const { result, ms } = await measure(async () => this.state.wllama.createCompletion(prompt, { nPredict: maxNewTokens }));
2537
+ const text = typeof result === 'string' ? result : extractCompletionText(result);
2538
+ return { output: { text }, inferenceMs: ms };
2539
+ }
2540
+ async runSample(sample) {
2541
+ const start = performance.now();
2542
+ if (typeof sample.text !== 'string') {
2543
+ return {
2544
+ ok: false,
2545
+ processingTimeMs: Math.round(performance.now() - start),
2546
+ error: true,
2547
+ errorMessage: 'response from processing sample'
2548
+ };
2549
+ }
2550
+ try {
2551
+ const result = await this.runInference({
2552
+ text: sample.text,
2553
+ maxNewTokens: 32,
2554
+ usecase: sample.usecase
2555
+ });
2556
+ const output = result.output;
2557
+ const text = typeof output?.text === 'string' ? output.text.trim() : '';
2558
+ if (!text) {
2559
+ return {
2560
+ ok: false,
2561
+ processingTimeMs: Math.round(performance.now() - start),
2562
+ error: true,
2563
+ errorMessage: 'response from processing sample'
2564
+ };
2565
+ }
2566
+ return {
2567
+ ok: true,
2568
+ processingTimeMs: Math.round(performance.now() - start),
2569
+ error: false
2570
+ };
2571
+ }
2572
+ catch (err) {
2573
+ return {
2574
+ ok: false,
2575
+ processingTimeMs: Math.round(performance.now() - start),
2576
+ error: true,
2577
+ errorMessage: err instanceof Error ? err.message : String(err)
2578
+ };
2579
+ }
2580
+ }
2581
+ }
2582
+ const extractCompletionText = (raw) => {
2583
+ if (!raw)
2584
+ return '';
2585
+ if (typeof raw === 'string')
2586
+ return raw;
2587
+ if (typeof raw === 'object') {
2588
+ const obj = raw;
2589
+ if (typeof obj.text === 'string')
2590
+ return obj.text;
2591
+ if (typeof obj.content === 'string')
2592
+ return obj.content;
2593
+ if (typeof obj.completion === 'string')
2594
+ return obj.completion;
2595
+ }
2596
+ try {
2597
+ return JSON.stringify(raw);
2598
+ }
2599
+ catch {
2600
+ return String(raw);
2601
+ }
2602
+ };
2603
+ const fetchGgufBlob = async (slm, ggufFileName, cachedFiles, onFileDownloaded) => {
2604
+ const modelScopedKey = `${slm.modelId}/${ggufFileName}`;
2605
+ const existing = cachedFiles[modelScopedKey] ||
2606
+ cachedFiles[ggufFileName];
2607
+ if (existing)
2608
+ return existing;
2609
+ const rawUrl = (slm.modelUrl || '').replace(/\/$/, '');
2610
+ if (!rawUrl) {
2611
+ throw new Error('gguf_model_url_missing');
2612
+ }
2613
+ // Strip Hugging Face browser-view paths (/tree/<branch>, /blob/<branch>) so we
2614
+ // can rebuild the correct /resolve/<branch>/ download URL.
2615
+ const hfViewMatch = rawUrl.match(/^(.*?\/huggingface\.co\/[^/]+\/[^/]+)\/(?:tree|blob)\/([^/]+)(?:\/.*)?$/i);
2616
+ const baseUrl = hfViewMatch ? hfViewMatch[1] : rawUrl;
2617
+ const branch = hfViewMatch ? hfViewMatch[2] : 'main';
2618
+ const candidates = [
2619
+ `${baseUrl}/resolve/${branch}/${ggufFileName}`,
2620
+ `${baseUrl}/${ggufFileName}`
2621
+ ];
2622
+ const failures = [];
2623
+ for (const url of candidates) {
2624
+ try {
2625
+ const response = await fetch(url);
2626
+ if (response.ok) {
2627
+ const blob = await response.blob();
2628
+ onFileDownloaded(modelScopedKey, blob);
2629
+ return blob;
2630
+ }
2631
+ failures.push(`${url} → HTTP ${response.status}`);
2632
+ }
2633
+ catch (err) {
2634
+ failures.push(`${url} → ${err instanceof Error ? err.message : String(err)}`);
2635
+ }
2636
+ }
2637
+ throw new Error(`gguf_file_fetch_failed: ${failures.join('; ')}`);
2638
+ };
2639
+ const instantiateWllama = async (slm, cachedFiles, onFileDownloaded) => {
2640
+ const ggufFileName = pickGgufFileName(slm.requiredFiles);
2641
+ if (!ggufFileName) {
2642
+ throw new Error('gguf_required_file_missing');
2643
+ }
2644
+ const mod = await ensureWllamaRuntime();
2645
+ const blob = await fetchGgufBlob(slm, ggufFileName, cachedFiles, onFileDownloaded);
2646
+ // A host that vendors wllama locally (e.g. an MV3 extension offscreen document)
2647
+ // can point the wasm at packaged files via `window.WllamaWasmPaths`; otherwise
2648
+ // fall back to the jsDelivr CDN used on the web/Telegram.
2649
+ const wllamaConfig = window.WllamaWasmPaths ?? {
2650
+ 'single-thread/wllama.wasm': `${WLLAMA_CDN_BASE}/single-thread/wllama.wasm`,
2651
+ 'multi-thread/wllama.wasm': `${WLLAMA_CDN_BASE}/multi-thread/wllama.wasm`
2652
+ };
2653
+ const wllama = new mod.Wllama(wllamaConfig);
2654
+ const { ms: loadModelMs } = await measure(async () => {
2655
+ await wllama.loadModel([blob], {
2656
+ n_ctx: slm.maxInputTokens && slm.maxInputTokens > 0 ? slm.maxInputTokens : 2048
2657
+ });
2658
+ });
2659
+ return { wllama, loadModelMs };
2660
+ };
2661
+ const loadGgufAdapter = async (slm, options) => {
2662
+ const logger = getLogger();
2663
+ const startTime = performance.now();
2664
+ const downloadedFiles = {};
2665
+ try {
2666
+ const cached = await getModel(slm.modelId, slm.modelVersion);
2667
+ const cachedFiles = cached?.files || {};
2668
+ if (!cached && options?.allowDownload === false) {
2669
+ return { error: new Error('model_not_cached'), metrics: {} };
2670
+ }
2671
+ const onFileDownloaded = (filename, blob) => {
2672
+ downloadedFiles[filename] = blob;
2673
+ };
2674
+ const baseMetrics = cached
2675
+ ? {
2676
+ downloadMs: cached.metadata.downloadMs,
2677
+ loadModelMs: cached.metadata.loadModelMs,
2678
+ sizeBytes: cached.metadata.sizeBytes
2679
+ }
2680
+ : {};
2681
+ const state = await instantiateWllama(slm, cachedFiles, onFileDownloaded);
2682
+ const metrics = { ...baseMetrics, loadModelMs: state.loadModelMs };
2683
+ if (Object.keys(downloadedFiles).length > 0) {
2684
+ const allFiles = { ...cachedFiles, ...downloadedFiles };
2685
+ const calculatedSize = Object.values(allFiles).reduce((sum, blob) => sum + blob.size, 0);
2686
+ const downloadMs = Math.round(performance.now() - startTime);
2687
+ await putModelComplete(slm.modelId, slm.modelVersion, {
2688
+ modelId: slm.modelId,
2689
+ modelVersion: slm.modelVersion,
2690
+ sizeBytes: calculatedSize,
2691
+ downloadMs: cached ? 0 : downloadMs,
2692
+ loadModelMs: state.loadModelMs
2693
+ }, allFiles);
2694
+ metrics.sizeBytes = calculatedSize;
2695
+ if (!cached)
2696
+ metrics.downloadMs = downloadMs;
2697
+ }
2698
+ const adapter = new GgufAdapter(slm, state, metrics);
2699
+ return { adapter, metrics };
2700
+ }
2701
+ catch (error) {
2702
+ console.error('[ZeroGPU][GGUF][load] failed', {
2703
+ modelId: slm.modelId,
2704
+ modelVersion: slm.modelVersion,
2705
+ modelUrl: slm.modelUrl,
2706
+ error: serializeError(error)
2707
+ });
2708
+ logger.error('GGUF adapter load failed', error);
2709
+ await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
2710
+ return { error: error, metrics: {} };
2711
+ }
2712
+ };
2713
+
2714
+ const capabilities = [
2715
+ { inferenceFramework: 'GGUF', taskType: 'text_generation' },
2716
+ { inferenceFramework: 'GGUF', taskType: 'summary' }
2717
+ ];
2718
+ const factory = {
2719
+ capabilities,
2720
+ load: (config, options) => loadGgufAdapter(config, options)
2721
+ };
2722
+ registerAdapter(factory);
2723
+
2724
+ let initialized = false;
2725
+ const initZeroGpuSdk = async (options) => {
2726
+ if (initialized) {
2727
+ return;
2728
+ }
2729
+ const config = resolveConfig(options?.overrides);
2730
+ await startLifecycle({
2731
+ config,
2732
+ appUserId: options?.appUserId,
2733
+ edgeOperatorKey: options?.edgeOperatorKey,
2734
+ deviceId: options?.deviceId
2735
+ });
2736
+ initialized = true;
2737
+ };
2738
+
2739
+ const readAttr = (script, names) => {
2740
+ for (const name of names) {
2741
+ const value = script.getAttribute(name)?.trim();
2742
+ if (value) {
2743
+ return value;
2744
+ }
2745
+ }
2746
+ return undefined;
2747
+ };
2748
+ const readSearchParam = (searchParams, names) => {
2749
+ if (!searchParams) {
2750
+ return undefined;
2751
+ }
2752
+ for (const name of names) {
2753
+ const value = searchParams.get(name)?.trim();
2754
+ if (value) {
2755
+ return value;
2756
+ }
2757
+ }
2758
+ return undefined;
2759
+ };
2760
+ const getCurrentScript = () => {
2761
+ if (typeof document === 'undefined') {
2762
+ return null;
2763
+ }
2764
+ return document.currentScript instanceof HTMLScriptElement
2765
+ ? document.currentScript
2766
+ : null;
2767
+ };
2768
+ const readBooleanAttr = (script, names) => {
2769
+ for (const name of names) {
2770
+ const value = script.getAttribute(name);
2771
+ if (value === null) {
2772
+ continue;
2773
+ }
2774
+ const normalized = value.trim().toLowerCase();
2775
+ if (normalized === '') {
2776
+ return true; // Valueless attribute treated as true
2777
+ }
2778
+ else if (normalized === 'true' || normalized === '1') {
2779
+ return true;
2780
+ }
2781
+ if (normalized === 'false' || normalized === '0') {
2782
+ return false;
2783
+ }
2784
+ }
2785
+ return undefined;
2786
+ };
2787
+ const autoInitFromScriptTag = () => {
2788
+ const script = getCurrentScript();
2789
+ if (!script) {
2790
+ return;
2791
+ }
2792
+ let searchParams;
2793
+ const src = script.getAttribute('src')?.trim();
2794
+ if (src) {
2795
+ try {
2796
+ const url = new URL(src, typeof document !== 'undefined' ? document.baseURI : undefined);
2797
+ searchParams = url.searchParams;
2798
+ }
2799
+ catch {
2800
+ searchParams = undefined;
2801
+ }
2802
+ }
2803
+ const edgeOperatorKey = readAttr(script, ['data-edge-operator-key', 'edgeOperatorKey']) ??
2804
+ readSearchParam(searchParams, ['edge-operator-key', 'edgeOperatorKey']);
2805
+ if (!edgeOperatorKey) {
2806
+ return;
2807
+ }
2808
+ const options = {
2809
+ appUserId: readAttr(script, ['data-app-user-id', 'appUserId']) ??
2810
+ readSearchParam(searchParams, ['app-user-id', 'appUserId']),
2811
+ deviceId: readAttr(script, ['data-device-id', 'deviceId']) ??
2812
+ readSearchParam(searchParams, ['device-id', 'deviceId']),
2813
+ edgeOperatorKey
2814
+ };
2815
+ const enableConsoleLogs = readBooleanAttr(script, ['data-enable-console-logs', 'enableConsoleLogs']) ??
2816
+ (() => {
2817
+ const value = readSearchParam(searchParams, ['enable-console-logs', 'enableConsoleLogs']);
2818
+ if (value === undefined) {
2819
+ return undefined;
2820
+ }
2821
+ const normalized = value.toLowerCase();
2822
+ if (normalized === 'true' || normalized === '1') {
2823
+ return true;
2824
+ }
2825
+ if (normalized === 'false' || normalized === '0') {
2826
+ return false;
2827
+ }
2828
+ return undefined;
2829
+ })();
2830
+ if (enableConsoleLogs !== undefined) {
2831
+ options.overrides = {
2832
+ telemetry: {
2833
+ enableConsoleLogs,
2834
+ locationData: false,
2835
+ cameraData: false
2836
+ }
2837
+ };
2838
+ }
2839
+ void initZeroGpuSdk(options).catch((error) => {
2840
+ console.error('[ZeroGpuSdk] Auto-init failed', error);
2841
+ });
2842
+ };
2843
+
2844
+ autoInitFromScriptTag();
2845
+
2846
+ export { initZeroGpuSdk };
2847
+ //# sourceMappingURL=zerogpu-browser-sdk.esm.js.map