@zerogpu/browser-extension-sdk 0.2.0 → 0.2.1-dev.202608031041.g7fab469

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/loader.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e){"use strict";const t="ZeroGpuBrowserSdk",r="ZeroGpuSdk",n=e=>{const{script:n,documentRef:o,windowRef:i,fetchImpl:s}=e;if(i[t]?.initZeroGpuSdk)return Promise.resolve();const c=n.getAttribute("src")??"";let d;try{d=new URL(c,e.baseUri)}catch{d=new URL(e.baseUri)}const a=new URL("manifest.json",d).toString(),u=new URL("zerogpu-browser-sdk.umd.js",d).toString(),l=[];let m=()=>{};const f=new Promise(e=>{m=e}),w=()=>{const e=i[t];if(e&&"function"==typeof e.initZeroGpuSdk){for(i[r]=e;l.length>0;){const t=l.shift();try{Promise.resolve(e[t.method]?.(...t.args)).then(t.resolve,t.reject)}catch(e){t.reject(e)}}m()}else console.error("[ZeroGpuSdk] Core bundle loaded but global API is missing.")};i[r]||(i[r]={ready:f,initZeroGpuSdk:(...e)=>new Promise((t,r)=>{l.push({method:"initZeroGpuSdk",args:e,resolve:t,reject:r})})});const p=(e,t)=>{const r=o.createElement("script");for(const e of Array.from(n.attributes))"src"!==e.name&&"integrity"!==e.name&&r.setAttribute(e.name,e.value);r.src=e,r.async=!0,r.setAttribute("data-zerogpu-core","true"),t&&(r.integrity=t,r.crossOrigin=n.crossOrigin??"anonymous"),r.addEventListener("load",w),r.addEventListener("error",()=>{console.error("[ZeroGpuSdk] Failed to load core bundle from",e)}),(o.head??o.documentElement).appendChild(r)};return(async()=>{try{const e=await s(a,{credentials:"omit"});if(!e.ok)throw new Error(`manifest HTTP ${e.status}`);const t=await e.json();if(!t?.coreBundleUrl)throw new Error("manifest missing coreBundleUrl");const r=new URL(t.coreBundleUrl,a).toString();p(r,t.integrity)}catch(e){console.warn("[ZeroGpuSdk] Manifest unavailable, falling back to stable bundle.",e),p(u)}})()};(()=>{if("undefined"==typeof document||"undefined"==typeof window)return;const e=document.currentScript instanceof HTMLScriptElement?document.currentScript:null;e&&n({script:e,documentRef:document,windowRef:window,fetchImpl:window.fetch.bind(window),baseUri:document.baseURI})})(),e.bootZeroGpuLoader=n}({});
1
+ !function(e){"use strict";const t="ZeroGpuBrowserSdk",r="ZeroGpuSdk",n=e=>{const{script:n,documentRef:o,windowRef:i,fetchImpl:s}=e;if(i[t]?.initZeroGpuSdk)return Promise.resolve();const c=/^(true|1)$/i.test((n.getAttribute("data-enable-console-logs")??n.getAttribute("enableConsoleLogs")??"").trim()),d=(...e)=>{c&&console.warn(...e)},a=(...e)=>{c&&console.error(...e)},u=n.getAttribute("src")??"";let l;try{l=new URL(u,e.baseUri)}catch{l=new URL(e.baseUri)}const m=new URL("manifest.json",l).toString(),f=new URL("zerogpu-browser-sdk.umd.js",l).toString(),w=[];let p=()=>{};const b=new Promise(e=>{p=e}),g=()=>{const e=i[t];if(e&&"function"==typeof e.initZeroGpuSdk){for(i[r]=e;w.length>0;){const t=w.shift();try{const r=e[t.method];Promise.resolve(r?.(...t.args)).then(t.resolve,t.reject)}catch(e){t.reject(e)}}p()}else a("[ZeroGpuSdk] Core bundle loaded but global API is missing.")};i[r]||(i[r]={ready:b,initZeroGpuSdk:(...e)=>new Promise((t,r)=>{w.push({method:"initZeroGpuSdk",args:e,resolve:t,reject:r})})});const h=(e,t)=>{const r=o.createElement("script");for(const e of Array.from(n.attributes))"src"!==e.name&&"integrity"!==e.name&&r.setAttribute(e.name,e.value);r.src=e,r.async=!0,r.setAttribute("data-zerogpu-core","true"),t&&(r.integrity=t,r.crossOrigin=n.crossOrigin??"anonymous"),r.addEventListener("load",g),r.addEventListener("error",()=>{a("[ZeroGpuSdk] Failed to load core bundle from",e)}),(o.head??o.documentElement).appendChild(r)};return(async()=>{try{const e=await s(m,{credentials:"omit"});if(!e.ok)throw new Error(`manifest HTTP ${e.status}`);const t=await e.json();if(!t?.coreBundleUrl)throw new Error("manifest missing coreBundleUrl");const r=new URL(t.coreBundleUrl,m).toString();h(r,t.integrity)}catch(e){d("[ZeroGpuSdk] Manifest unavailable, falling back to stable bundle.",e),h(f)}})()};(()=>{if("undefined"==typeof document||"undefined"==typeof window)return;const e=document.currentScript instanceof HTMLScriptElement?document.currentScript:null;e&&n({script:e,documentRef:document,windowRef:window,fetchImpl:window.fetch.bind(window),baseUri:document.baseURI})})(),e.bootZeroGpuLoader=n}({});
2
2
  //# sourceMappingURL=loader.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loader.js","sources":["../../src/loader.ts"],"sourcesContent":[null],"names":["GLOBAL_NAME","STUB_NAME","bootZeroGpuLoader","env","script","documentRef","windowRef","fetchImpl","initZeroGpuSdk","Promise","resolve","loaderSrc","getAttribute","baseUrl","URL","baseUri","manifestUrl","toString","fallbackBundleUrl","queue","resolveReady","ready","flushQueue","api","length","call","shift","method","args","then","reject","error","console","push","injectCoreBundle","bundleUrl","integrity","core","createElement","attr","Array","from","attributes","name","setAttribute","value","src","async","crossOrigin","addEventListener","head","documentElement","appendChild","response","credentials","ok","Error","status","manifest","json","coreBundleUrl","warn","document","window","currentScript","HTMLScriptElement","fetch","bind","baseURI"],"mappings":"0BA2CA,MAAMA,EAAc,oBACdC,EAAY,aAELC,EAAqBC,IAChC,MAAMC,OAAEA,EAAMC,YAAEA,EAAWC,UAAEA,EAASC,UAAEA,GAAcJ,EAItD,GAAIG,EAAUN,IAAcQ,eAC1B,OAAOC,QAAQC,UAGjB,MAAMC,EAAYP,EAAOQ,aAAa,QAAU,GAChD,IAAIC,EACJ,IACEA,EAAU,IAAIC,IAAIH,EAAWR,EAAIY,QACnC,CACA,MACEF,EAAU,IAAIC,IAAIX,EAAIY,QACxB,CACA,MAAMC,EAAc,IAAIF,IAAI,gBAAiBD,GAASI,WAGhDC,EAAoB,IAAIJ,IAC5B,6BACAD,GACAI,WAIIE,EAAsB,GAC5B,IAAIC,EAA2B,OAC/B,MAAMC,EAAQ,IAA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,kCAElB,MAAMrB,EAAY,IAAIrB,IAAI4C,EAASE,cAAe5C,GAAaC,WAC/DiB,EAAiBC,EAAWuB,EAAStB,UACvC,CACA,MAAOL,GACLC,QAAQ6B,KACN,oEACA9B,GAEFG,EAAiBhB,EACnB,CACD,EApBM,IAwBT,MACE,GAAwB,oBAAb4C,UAA8C,oBAAXC,OAC5C,OAEF,MAAM3D,EACJ0D,SAASE,yBAAyBC,kBAC9BH,SAASE,cACT,KACD5D,GAGAF,EAAkB,CACrBE,SACAC,YAAayD,SACbxD,UAAWyD,OACXxD,UAAWwD,OAAOG,MAAMC,KAAKJ,QAC7BhD,QAAS+C,SAASM,SAErB,EAlBD"}
1
+ {"version":3,"file":"loader.js","sources":["../../src/loader.ts"],"sourcesContent":[null],"names":["GLOBAL_NAME","STUB_NAME","bootZeroGpuLoader","env","script","documentRef","windowRef","fetchImpl","initZeroGpuSdk","Promise","resolve","consoleLogsEnabled","test","getAttribute","trim","loaderLog","args","console","warn","error","loaderSrc","baseUrl","URL","baseUri","manifestUrl","toString","fallbackBundleUrl","queue","resolveReady","ready","flushQueue","api","length","call","shift","method","then","reject","push","injectCoreBundle","bundleUrl","integrity","core","createElement","attr","Array","from","attributes","name","setAttribute","value","src","async","crossOrigin","addEventListener","head","documentElement","appendChild","response","credentials","ok","Error","status","manifest","json","coreBundleUrl","document","window","currentScript","HTMLScriptElement","fetch","bind","baseURI"],"mappings":"0BAwDA,MAAMA,EAAc,oBACdC,EAAY,aAELC,EAAqBC,IAChC,MAAMC,OAAEA,EAAMC,YAAEA,EAAWC,UAAEA,EAASC,UAAEA,GAAcJ,EAItD,GAAIG,EAAUN,IAAcQ,eAC1B,OAAOC,QAAQC,UAQjB,MAAMC,EAAqB,cAAcC,MAErCR,EAAOS,aAAa,6BACpBT,EAAOS,aAAa,sBACpB,IACAC,QAEEC,EACE,IAAIC,KACJL,GAAoBM,QAAQC,QAAQF,IAFtCD,EAIG,IAAIC,KACLL,GAAoBM,QAAQE,SAASH,I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B,OAAQxB,GAC9BY,EAAKY,iBAAiB,QAAS,KAC7BvC,EAAgB,+CAAgDyB,MAEjEnC,EAAYkD,MAAQlD,EAAYmD,iBAAiBC,YAAYf,IAGhE,MAAO,WACL,IACE,MAAMgB,QAAiBnD,EAAUiB,EAAa,CAAEmC,YAAa,SAC7D,IAAKD,EAASE,GACZ,MAAM,IAAIC,MAAM,iBAAiBH,EAASI,UAE5C,MAAMC,QAAkBL,EAASM,OACjC,IAAKD,GAAUE,cACb,MAAM,IAAIJ,MAAM,kCAElB,MAAMrB,EAAY,IAAIlB,IAAIyC,EAASE,cAAezC,GAAaC,WAC/Dc,EAAiBC,EAAWuB,EAAStB,UACvC,CACA,MAAOtB,GACLJ,EACE,oEACAI,GAEFoB,EAAiBb,EACnB,CACD,EApBM,IAwBT,MACE,GAAwB,oBAAbwC,UAA8C,oBAAXC,OAC5C,OAEF,MAAM/D,EACJ8D,SAASE,yBAAyBC,kBAC9BH,SAASE,cACT,KACDhE,GAGAF,EAAkB,CACrBE,SACAC,YAAa6D,SACb5D,UAAW6D,OACX5D,UAAW4D,OAAOG,MAAMC,KAAKJ,QAC7B5C,QAAS2C,SAASM,SAErB,EAlBD"}
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "0.2.0+12c5b00",
3
- "channel": "official",
4
- "buildId": "af4825958dcb",
5
- "coreBundleUrl": "v/zerogpu-browser-sdk.af4825958dcb.umd.js",
6
- "integrity": "sha384-ExHvkUH6N4JKKRVxyQ81XCh2w6UGICAL085F9/veTAS300PslrNBk/gN3A1r2q/Q",
7
- "builtAt": "2026-07-24T18:44:23.675Z"
2
+ "version": "0.2.1-dev.202608031041.g7fab469+7fab469",
3
+ "channel": "development",
4
+ "buildId": "71504e330923",
5
+ "coreBundleUrl": "v/zerogpu-browser-sdk.71504e330923.umd.js",
6
+ "integrity": "sha384-QO79xr1BETinP7NKYqVKUsLZFdsxowL2bPAVMmWSCm73FmKhmTJ1j7Q8wwXtGhZ9",
7
+ "builtAt": "2026-08-03T10:43:17.265Z"
8
8
  }
@@ -1,7 +1,21 @@
1
+ /**
2
+ * wllama ships no bundled types and is loaded at runtime from a CDN (or a
3
+ * vendored copy under MV3), so it cannot be imported for its types. These are
4
+ * structural stand-ins: `unknown`-valued bags that force narrowing at the call
5
+ * site rather than `any`, which would silently disable checking everywhere the
6
+ * instance travels.
7
+ */
8
+ export interface WllamaInstance {
9
+ loadModel: (blobs: Blob[], options?: Record<string, unknown>) => Promise<void>;
10
+ createCompletion: (prompt: string, options?: Record<string, unknown>) => Promise<string>;
11
+ }
12
+ export interface WllamaModule {
13
+ Wllama: new (config?: Record<string, string>) => WllamaInstance;
14
+ }
1
15
  declare global {
2
16
  interface Window {
3
- WllamaModule?: any;
4
- WllamaInstance?: any;
17
+ WllamaModule?: WllamaModule;
18
+ WllamaInstance?: WllamaInstance;
5
19
  /**
6
20
  * Optional override for the wllama wasm asset paths. When set (e.g. by a
7
21
  * Chrome-extension offscreen host that vendors wllama locally), the GGUF
@@ -12,5 +26,5 @@ declare global {
12
26
  WllamaWasmPaths?: Record<string, string>;
13
27
  }
14
28
  }
15
- export declare const ensureWllamaRuntime: () => Promise<any>;
29
+ export declare const ensureWllamaRuntime: () => Promise<WllamaModule>;
16
30
  export declare const WLLAMA_CDN_BASE: string;
@@ -1,7 +1,35 @@
1
+ /**
2
+ * transformers.js is loaded at runtime from a CDN (or a vendored copy under
3
+ * MV3) and ships no types we can import, so these describe only the surface
4
+ * this SDK actually touches. Everything is optional because the shape differs
5
+ * across transformers.js versions and the SDK must degrade rather than throw.
6
+ */
7
+ export type TransformersPipelineFn = (input: string | string[], options?: unknown) => Promise<unknown>;
8
+ export interface TransformersOnnxWasmEnv {
9
+ proxy?: boolean;
10
+ numThreads?: number;
11
+ wasmPaths?: string;
12
+ /** Present only on builds that expose SIMD detection; probed before use. */
13
+ simd?: boolean;
14
+ }
15
+ export interface TransformersEnv {
16
+ allowLocalModels?: boolean;
17
+ allowRemoteModels?: boolean;
18
+ logLevel?: string;
19
+ fetch?: typeof fetch;
20
+ backends?: {
21
+ onnx?: {
22
+ env?: {
23
+ logLevel?: string;
24
+ };
25
+ wasm?: TransformersOnnxWasmEnv;
26
+ };
27
+ };
28
+ }
1
29
  declare global {
2
30
  interface Window {
3
- TransformersPipeline?: (task: string, modelPath: string, options?: Record<string, unknown>) => Promise<any>;
4
- TransformersEnv?: Record<string, any>;
31
+ TransformersPipeline?: (task: string, modelPath: string, options?: Record<string, unknown>) => Promise<TransformersPipelineFn>;
32
+ TransformersEnv?: TransformersEnv;
5
33
  }
6
34
  }
7
35
  export declare const TRANSFORMERS_CDN = "https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js";
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Server-driven connection policy — the `connection` block of
3
+ * `configSettings.<sdkType>` (device-registry docs/CONNECTION_POLICY_DESIGN.md §2).
4
+ *
5
+ * Same philosophy as the guardrails contract (runtime/guardrails.ts): lenient
6
+ * parse, every numeric field individually validated and CLAMPED into a safe
7
+ * range, absent/invalid fields fall back to built-in defaults — never to
8
+ * "check disabled" and never to the raw served value. A typo of
9
+ * `"ping_interval_seconds": 1` must not make 50 000 devices ping every second.
10
+ *
11
+ * When no `connection` block is served at all (`served: false`), the SDK keeps
12
+ * its exact legacy behavior: no keepalive ping, no staleness safety net, and
13
+ * the flat `device_timeout_interval_seconds`-or-600 s re-register delay.
14
+ * Rollout is therefore pure opt-in via settings data.
15
+ */
16
+ export interface ConnectionPolicyInput {
17
+ v?: number;
18
+ keep_alive?: {
19
+ ping_interval_seconds?: number;
20
+ transport?: string;
21
+ [key: string]: unknown;
22
+ };
23
+ reconnect?: {
24
+ strategy?: string;
25
+ initial_delay_ms?: number;
26
+ multiplier?: number;
27
+ max_delay_ms?: number;
28
+ jitter_ms?: number;
29
+ give_up_after_attempts?: number;
30
+ [key: string]: unknown;
31
+ };
32
+ reregister?: {
33
+ max_staleness_seconds?: number;
34
+ on_refusal_retry_seconds?: number;
35
+ on_auth_failure?: string;
36
+ [key: string]: unknown;
37
+ };
38
+ socket?: {
39
+ idle_timeout_seconds?: number;
40
+ session_resume?: boolean;
41
+ [key: string]: unknown;
42
+ };
43
+ [key: string]: unknown;
44
+ }
45
+ export interface ResolvedReconnectPolicy {
46
+ strategy: 'exponential' | 'fixed';
47
+ initialDelayMs: number;
48
+ multiplier: number;
49
+ maxDelayMs: number;
50
+ jitterMs: number;
51
+ /** 0 = never give up (keep retrying at maxDelayMs). */
52
+ giveUpAfterAttempts: number;
53
+ }
54
+ export interface ResolvedConnectionPolicy {
55
+ /**
56
+ * True when the server actually served a `connection` block. False keeps
57
+ * every legacy code path (flat re-register delay, no ping, no staleness
58
+ * net) byte-for-byte identical to the shipped SDK.
59
+ */
60
+ served: boolean;
61
+ keepAlive: {
62
+ pingIntervalSeconds: number;
63
+ };
64
+ reconnect: ResolvedReconnectPolicy;
65
+ reregister: {
66
+ maxStalenessSeconds: number;
67
+ onRefusalRetrySeconds: number;
68
+ onAuthFailure: 'stop' | 'retry_slow';
69
+ };
70
+ /** Server-enforced lifetime, echoed for awareness only — never self-close. */
71
+ socket: {
72
+ idleTimeoutSeconds: number;
73
+ };
74
+ }
75
+ export declare const CONNECTION_POLICY_DEFAULTS: {
76
+ pingIntervalSeconds: number;
77
+ strategy: "exponential";
78
+ initialDelayMs: number;
79
+ multiplier: number;
80
+ maxDelayMs: number;
81
+ jitterMs: number;
82
+ giveUpAfterAttempts: number;
83
+ maxStalenessSeconds: number;
84
+ onRefusalRetrySeconds: number;
85
+ onAuthFailure: "stop";
86
+ idleTimeoutSeconds: number;
87
+ };
88
+ export declare const CONNECTION_POLICY_CLAMPS: {
89
+ pingIntervalSeconds: {
90
+ min: number;
91
+ max: number;
92
+ };
93
+ initialDelayMs: {
94
+ min: number;
95
+ max: number;
96
+ };
97
+ multiplier: {
98
+ min: number;
99
+ max: number;
100
+ };
101
+ maxDelayMs: {
102
+ min: number;
103
+ max: number;
104
+ };
105
+ jitterMs: {
106
+ min: number;
107
+ max: number;
108
+ };
109
+ maxStalenessSeconds: {
110
+ min: number;
111
+ max: number;
112
+ };
113
+ onRefusalRetrySeconds: {
114
+ min: number;
115
+ max: number;
116
+ };
117
+ };
118
+ /** Cap on a served `reregister` directive's `delay_jitter_ms`; invalid → 60 s. */
119
+ export declare const DEFAULT_REREGISTER_DIRECTIVE_JITTER_MS = 60000;
120
+ /**
121
+ * Pure resolver: raw served `connection` block (or anything at all) →
122
+ * fully-defaulted, fully-clamped policy. Unknown fields are ignored.
123
+ */
124
+ export declare const resolveConnectionPolicy: (raw: unknown) => ResolvedConnectionPolicy;
125
+ /**
126
+ * Reconnect delay for the given zero-based attempt:
127
+ * min(initial × multiplier^attempt, max) + uniform(0..jitter).
128
+ * `fixed` strategy pins the base at initialDelayMs (still capped + jittered).
129
+ * Math.pow overflow to Infinity is absorbed by the min() cap.
130
+ */
131
+ export declare const computeReconnectDelayMs: (reconnect: ResolvedReconnectPolicy, attempt: number, random?: () => number) => number;
132
+ /** Flat retry (refusal / auth retry_slow) with the mandatory uniform jitter. */
133
+ export declare const computeRetryDelayMs: (retrySeconds: number, jitterMs: number, random?: () => number) => number;
134
+ /**
135
+ * Delay for a server `reregister` directive: uniform(0..delay_jitter_ms),
136
+ * defaulting the cap to 60 s when absent/invalid so a fleet-wide push never
137
+ * becomes a register stampede. The cap itself is bounded at one hour.
138
+ */
139
+ export declare const computeReregisterDirectiveDelayMs: (delayJitterMs: unknown, random?: () => number) => number;
140
+ /**
141
+ * Flattened field-level diff between two resolved policies — feeds the
142
+ * `changed` list for logging (and, once available in the shared vocabulary,
143
+ * the `ws.policy_applied` event payload).
144
+ */
145
+ export declare const diffConnectionPolicies: (before: ResolvedConnectionPolicy, after: ResolvedConnectionPolicy) => string[];
@@ -1,6 +1,6 @@
1
1
  import { SdkConfig } from './types';
2
2
  type DeepPartial<T> = {
3
- [K in keyof T]?: T[K] extends Array<infer U> ? Array<DeepPartial<U>> : T[K] extends Record<string, any> ? DeepPartial<T[K]> : T[K];
3
+ [K in keyof T]?: T[K] extends Array<infer U> ? Array<DeepPartial<U>> : T[K] extends object ? DeepPartial<T[K]> : T[K];
4
4
  };
5
5
  export type ConfigOverrides = DeepPartial<SdkConfig>;
6
6
  export declare const resolveConfig: (overrides?: ConfigOverrides) => SdkConfig;
@@ -1,3 +1,4 @@
1
+ import { ConnectionPolicyInput } from './connection-policy';
1
2
  export type TaskType = string;
2
3
  export interface RequiredFileSpec {
3
4
  name: string;
@@ -46,6 +47,7 @@ export interface RegistrationSettings {
46
47
  websocket_timeout_seconds?: number;
47
48
  device_timeout_interval_seconds?: number;
48
49
  guardrails?: GuardrailSettings;
50
+ connection?: ConnectionPolicyInput;
49
51
  [key: string]: unknown;
50
52
  }
51
53
  export interface OrchestratorConfig {
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Typed accessors for the non-standard browser surfaces this SDK reads.
3
+ *
4
+ * None of these are in TypeScript's DOM lib: the Telegram Mini App bridge is
5
+ * injected by the host, and `userAgentData` / `deviceMemory` / `getBattery` /
6
+ * `connection` are all optional vendor extensions that may be absent on any
7
+ * given engine. Declaring them here once — rather than casting to `any` at each
8
+ * read — keeps the optionality visible at the call site, which matters because
9
+ * every one of these fields feeds a guardrail decision.
10
+ */
11
+ export interface TelegramUser {
12
+ id?: number;
13
+ username?: string;
14
+ first_name?: string;
15
+ last_name?: string;
16
+ language_code?: string;
17
+ }
18
+ export interface TelegramWebApp {
19
+ platform?: string;
20
+ version?: string;
21
+ themeParams?: Record<string, unknown>;
22
+ initDataUnsafe?: {
23
+ user?: TelegramUser;
24
+ };
25
+ }
26
+ /** Chromium-only; absent on Safari and Firefox. */
27
+ export interface NavigatorUserAgentData {
28
+ mobile?: boolean;
29
+ platform?: string;
30
+ }
31
+ /** Battery Status API — removed from Firefox, gated in Safari. */
32
+ export interface BatteryManager {
33
+ level: number;
34
+ charging: boolean;
35
+ }
36
+ /** Network Information API — Chromium-only, and vendor-prefixed on older builds. */
37
+ export interface NetworkInformation {
38
+ effectiveType?: string;
39
+ downlink?: number;
40
+ rtt?: number;
41
+ }
42
+ type ExtendedNavigator = Navigator & {
43
+ userAgentData?: NavigatorUserAgentData;
44
+ /** Approximate device RAM in GiB, rounded down to a power of two. Chromium-only. */
45
+ deviceMemory?: number;
46
+ getBattery?: () => Promise<BatteryManager>;
47
+ connection?: NetworkInformation;
48
+ mozConnection?: NetworkInformation;
49
+ webkitConnection?: NetworkInformation;
50
+ };
51
+ export declare const extendedNavigator: () => ExtendedNavigator;
52
+ /** The injected Telegram bridge, or undefined when not running inside a Mini App. */
53
+ export declare const telegramWebApp: () => TelegramWebApp | undefined;
54
+ export {};
@@ -14,12 +14,24 @@
14
14
  *
15
15
  * The loader has no runtime imports — it must stay self-contained and minifiable.
16
16
  */
17
+ /**
18
+ * The SDK's own window globals, as the loader sees them before the core bundle
19
+ * has replaced the stub. Methods are indexed by name because the queue replays
20
+ * arbitrary calls, so the value type stays callable rather than `unknown`.
21
+ */
22
+ type LoaderApiMethod = (...args: unknown[]) => unknown;
23
+ interface ZeroGpuGlobal {
24
+ ready?: Promise<void>;
25
+ initZeroGpuSdk?: LoaderApiMethod;
26
+ [method: string]: LoaderApiMethod | Promise<void> | undefined;
27
+ }
17
28
  /** Injected dependencies so the loader is unit-testable without a real browser. */
18
29
  export interface LoaderEnv {
19
30
  script: HTMLScriptElement;
20
31
  documentRef: Document;
21
- windowRef: Record<string, any>;
32
+ windowRef: Record<string, ZeroGpuGlobal | undefined>;
22
33
  fetchImpl: typeof fetch;
23
34
  baseUri: string;
24
35
  }
25
36
  export declare const bootZeroGpuLoader: (env: LoaderEnv) => Promise<void>;
37
+ export {};
@@ -0,0 +1,32 @@
1
+ import { ResolvedConnectionPolicy } from '../config/connection-policy';
2
+ /**
3
+ * Live connection-policy state, guardrails-style: the most recent policy wins
4
+ * (WS `policy_update` beats the register-time value beats built-in defaults),
5
+ * applied atomically by swapping one resolved object. Also owns the reconnect
6
+ * attempt counter and the last-successful-register timestamp that backs the
7
+ * `max_staleness_seconds` safety net.
8
+ */
9
+ export type ConnectionPolicySource = 'register' | 'ws';
10
+ export interface AppliedConnectionPolicy {
11
+ policy: ResolvedConnectionPolicy;
12
+ source: ConnectionPolicySource;
13
+ /** Flattened names of fields that differ from the previously active policy. */
14
+ changed: string[];
15
+ }
16
+ /** Resolve (clamp/default) a served `connection` block and make it active. */
17
+ export declare const applyConnectionPolicy: (raw: unknown, source: ConnectionPolicySource) => AppliedConnectionPolicy;
18
+ export declare const getConnectionPolicy: () => ResolvedConnectionPolicy;
19
+ /** Zero-based attempt index for the next reconnect being scheduled. */
20
+ export declare const getReconnectAttempt: () => number;
21
+ export declare const bumpReconnectAttempt: () => void;
22
+ /** A successful register+connect resets the backoff curve. */
23
+ export declare const resetReconnectAttempts: () => void;
24
+ export declare const markRegisterSuccess: (now?: number) => void;
25
+ /**
26
+ * Safety net only (design §2): true when a policy was served and more than
27
+ * `max_staleness_seconds` has passed since the last successful register.
28
+ * With no served policy there is no net — exactly the shipped behavior.
29
+ */
30
+ export declare const isRegistrationStale: (now?: number) => boolean;
31
+ /** Test-only: reset all module state. */
32
+ export declare const __resetConnectionState: () => void;
@@ -49,7 +49,26 @@ export interface HelloAckMessage {
49
49
  status: 'idle' | 'error';
50
50
  timestamp: number;
51
51
  }
52
- export type IncomingMessage = ServerTaskBatchMessage | HelloAckMessage | {
52
+ /**
53
+ * Server→device mid-session policy push: the same `connection` object served
54
+ * in `configSettings` at register time, applied in place (no disconnect).
55
+ */
56
+ export interface PolicyUpdateMessage {
57
+ type: 'policy_update';
58
+ v?: number;
59
+ connection?: unknown;
60
+ }
61
+ /**
62
+ * Server→device directive to run the full register flow again (register-owned
63
+ * config changed). The SDK waits uniform(0..delay_jitter_ms) so a fleet-wide
64
+ * push does not become a register stampede.
65
+ */
66
+ export interface ReregisterDirectiveMessage {
67
+ type: 'reregister';
68
+ reason?: string;
69
+ delay_jitter_ms?: number;
70
+ }
71
+ export type IncomingMessage = ServerTaskBatchMessage | HelloAckMessage | PolicyUpdateMessage | ReregisterDirectiveMessage | {
53
72
  type: string;
54
73
  [key: string]: unknown;
55
74
  };
@@ -6,6 +6,18 @@ export interface WebSocketClientOptions {
6
6
  closeAfterAck?: boolean;
7
7
  closeCode?: number;
8
8
  closeReason?: string;
9
+ /**
10
+ * App-level keepalive: send a bare-text `ping` frame at this cadence while
11
+ * the socket is open (the registry DO answers `pong` and refreshes
12
+ * lastSeen). 0/absent = no keepalive — the legacy behavior.
13
+ */
14
+ pingIntervalSeconds?: number;
15
+ /**
16
+ * Invoked after each keepalive ping is sent — lets the lifecycle piggyback
17
+ * cheap periodic checks (the max_staleness safety net) without owning a
18
+ * second timer.
19
+ */
20
+ onPingTick?: () => void;
9
21
  onOpen?: () => void;
10
22
  onMessage: (message: IncomingMessage) => void;
11
23
  onClose: (event: CloseEvent) => void;
@@ -15,12 +27,21 @@ export declare class WebSocketClient {
15
27
  private options;
16
28
  private socket;
17
29
  private logger;
30
+ private pingTimer;
31
+ private pingIntervalMs;
18
32
  private consoleWithVerbose;
19
33
  constructor(options: WebSocketClientOptions);
20
34
  private handleOpen;
21
35
  private handleMessage;
22
36
  private handleError;
23
37
  private handleClose;
38
+ /**
39
+ * Live retune (e.g. a `policy_update` mid-session): restarts the keepalive
40
+ * timer at the new cadence while the socket is open; 0/invalid stops it.
41
+ */
42
+ setPingIntervalSeconds(seconds: number | undefined): void;
43
+ private startPing;
44
+ private stopPing;
24
45
  isActive(): boolean;
25
46
  send(payload: Record<string, unknown>): void;
26
47
  close(code?: number, reason?: string): void;