@busy-app/busy-lib 0.12.0 → 0.13.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.
- package/dist/index.cjs +41 -1
- package/dist/index.d.ts +1034 -2
- package/dist/index.js +875 -446
- package/dist/index.worker.cjs +11 -0
- package/dist/index.worker.d.ts +1 -0
- package/dist/index.worker.js +4025 -0
- package/dist/types.status-BeqxtQVd.cjs +1 -0
- package/dist/types.status-gCPe7MrJ.js +16 -0
- package/package.json +5 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1,41 @@
|
|
|
1
|
-
"use strict";var v=Object.defineProperty;var O=(n,t,e)=>t in n?v(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var u=(n,t,e)=>O(n,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("openapi-fetch"),L=(n,t)=>{if(typeof FormData<"u"&&n instanceof FormData||typeof Buffer<"u"&&typeof Buffer.isBuffer=="function"&&Buffer.isBuffer(n)||typeof File<"u"&&n instanceof File||typeof Blob<"u"&&n instanceof Blob||typeof ArrayBuffer<"u"&&n instanceof ArrayBuffer||typeof ArrayBuffer<"u"&&ArrayBuffer.isView&&ArrayBuffer.isView(n))return n;let e;return t&&(t instanceof Headers?e=t.get("Content-Type")??t.get("content-type")??void 0:typeof t=="object"&&(e=t["Content-Type"]??t["content-type"]),e==="application/x-www-form-urlencoded")?n&&typeof n=="object"&&!(n instanceof URLSearchParams)?new URLSearchParams(n).toString():String(n):JSON.stringify(n)};async function p(n){const i=(n.headers.get("content-type")||"").includes("application/json")?await n.clone().json():await n.clone().text(),r=typeof i=="object"&&i!==null?i.error||i.message:typeof i=="string"?i:void 0;return Object.assign(new Error(r||`HTTP ${n.status} ${n.statusText}`),{status:n.status,statusText:n.statusText,body:i})}async function s(n,t=3e3){if(t<=0)return await n();const e=new AbortController,i=setTimeout(()=>e.abort(),t);try{return await n(e.signal)}catch(r){throw r instanceof DOMException&&r.name==="AbortError"?new Error(`Request timed out after ${t}ms`):r}finally{clearTimeout(i)}}function D(n,t,e){let i,r=e??void 0,o,a=null;const c=async()=>{i||(a||(a=(async()=>{const h=await t();if(!h.api_semver)throw new Error("Empty API version");i=h.api_semver})().finally(()=>{a=null})),await a)},d={async onRequest({request:h,schemaPath:l}){return r&&h.headers.set("Authorization",`Bearer ${r}`),l!=="/version"&&(await c(),i&&h.headers.set("X-API-Sem-Ver",i),o&&h.headers.set("X-API-Token",o)),h},async onResponse({request:h,response:l,options:P,schemaPath:G}){if(l.ok)return l;if(G==="/version")throw await p(l);if(l.status!==405)throw await p(l);i=void 0,await c(),i&&h.headers.set("X-API-Sem-Ver",i),r&&h.headers.set("Authorization",`Bearer ${r}`);const y=await(P.fetch??fetch)(h);if(y.ok)return y;throw await p(y)}},w=E({baseUrl:n,bodySerializer:L});return w.use(d),{client:w,setApiKey:h=>{o=h},setToken:h=>{r=h}}}async function U(n,t){const{data:e,error:i}=await s(r=>n.GET("/version",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function B(n,t){const{data:e,error:i}=await s(r=>n.GET("/status",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function _(n,t){const{data:e,error:i}=await s(r=>n.GET("/status/system",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function $(n,t){const{data:e,error:i}=await s(r=>n.GET("/status/power",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function I(n,t){const{data:e,error:i}=await s(r=>n.GET("/status/device",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function R(n,t){const{data:e,error:i}=await s(r=>n.GET("/status/firmware",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}class K{async SystemVersionGet(t){const e=await U(this.apiClient,t);return this.apiSemver=e.api_semver,e}async SystemStatusGet(t){return await B(this.apiClient,t)}async SystemInfoGet(t){return await _(this.apiClient,t)}async SystemStatusPowerGet(t){return await $(this.apiClient,t)}async SystemStatusDeviceGet(t){return await I(this.apiClient,t)}async SystemStatusFirmwareGet(t){return await R(this.apiClient,t)}}async function F(n,t){const{file:e}=t,{data:i,error:r}=await s(o=>n.POST("/update",{headers:{"Content-Type":"application/octet-stream"},body:e,signal:o}),t.timeout);if(r)throw r;return i}async function W(n,t){const{data:e,error:i}=await s(r=>n.POST("/update/check",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function M(n,t){const{data:e,error:i}=await s(r=>n.GET("/update/status",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function q(n,t){const{version:e}=t,{data:i,error:r}=await s(o=>n.GET("/update/changelog",{params:{query:{version:e}},signal:o}),t.timeout);if(r)throw r;return i}async function N(n,t){const{version:e}=t,{data:i,error:r}=await s(o=>n.POST("/update/install",{params:{query:{version:e}},signal:o}),t.timeout);if(r)throw r;return i}async function x(n,t){const{data:e,error:i}=await s(r=>n.POST("/update/abort_download",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function H(n,t){const{data:e,error:i}=await s(r=>n.GET("/update/autoupdate",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function V(n,t){const{is_enabled:e,interval_start:i,interval_end:r}=t,{data:o,error:a}=await s(c=>n.POST("/update/autoupdate",{body:{is_enabled:e,interval_start:i,interval_end:r},signal:c}),t.timeout);if(a)throw a;return o}class j{async UpdateFromFile(t){return await F(this.apiClient,t)}async UpdateCheck(t){return await W(this.apiClient,t)}async UpdateStatusGet(t){return await M(this.apiClient,t)}async UpdateChangelogGet(t){return await q(this.apiClient,t)}async UpdateInstall(t){return await N(this.apiClient,t)}async UpdateAbort(t){return await x(this.apiClient,t)}async UpdateAutoUpdateGet(t){return await H(this.apiClient,t)}async UpdateAutoUpdateSet(t){return await V(this.apiClient,t)}}async function z(n,t){const{data:e,error:i}=await s(r=>n.GET("/time",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function J(n,t){const{timestamp:e}=t,{data:i,error:r}=await s(o=>n.POST("/time/timestamp",{params:{query:{timestamp:e}},signal:o}),t.timeout);if(r)throw r;return i}async function X(n,t){const{data:e,error:i}=await s(r=>n.GET("/time/timezone",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function Y(n,t){const{timezone:e}=t,{data:i,error:r}=await s(o=>n.POST("/time/timezone",{params:{query:{timezone:e}},signal:o}),t.timeout);if(r)throw r;return i}async function Q(n,t){const{data:e,error:i}=await s(r=>n.GET("/time/tzlist",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}class Z{async TimeGet(t){return await z(this.apiClient,t)}async TimeTimestampSet(t){return await J(this.apiClient,t)}async TimeTimezoneGet(t){return await X(this.apiClient,t)}async TimeTimezoneSet(t){return await Y(this.apiClient,t)}async TimeTzListGet(t){return await Q(this.apiClient,t)}}async function tt(n,t){const{data:e,error:i}=await s(r=>n.GET("/account/status",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function et(n,t){const{data:e,error:i}=await s(r=>n.GET("/account/info",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function it(n,t){const{data:e,error:i}=await s(r=>n.GET("/account/profile",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function nt(n,t){const{profile:e,custom_url:i}=t,{data:r,error:o}=await s(a=>n.POST("/account/profile",{params:{query:{profile:e,custom_url:i}},signal:a}),t.timeout);if(o)throw o;return r}async function rt(n,t){const{data:e,error:i}=await s(r=>n.DELETE("/account",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function ot(n,t){const{data:e,error:i}=await s(r=>n.POST("/account/link",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}class st{async AccountInfoGet(t){return await et(this.apiClient,t)}async AccountStateGet(t){return await tt(this.apiClient,t)}async AccountProfileGet(t){return await it(this.apiClient,t)}async AccountProfileSet(t){return await nt(this.apiClient,t)}async AccountUnlink(t){return await rt(this.apiClient,t)}async AccountLink(t){return await ot(this.apiClient,t)}}async function at(n,t){const{application_name:e,elements:i,priority:r=50,timeout:o}=t,{data:a,error:c}=await s(d=>n.POST("/display/draw",{body:{application_name:e,priority:r,elements:i},signal:d}),o);if(c)throw c;return a}async function ct(n,t){const{data:e,error:i}=await s(r=>n.DELETE("/display/draw",{params:{query:{application_name:t==null?void 0:t.application_name}},signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function ut(n,t){const{display:e,timeout:i}=t,{data:r,error:o}=await s(a=>n.GET("/screen",{params:{query:{display:e}},parseAs:"blob",signal:a}),i);if(o)throw o;return r}async function ht(n,t){const{data:e,error:i}=await s(r=>n.GET("/display/brightness",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function dt(n,t){const{value:e}=t,r=(c=>{if(typeof c=="number"){if(c<0||c>100)throw new Error("Brightness value must be between 0 and 100 or 'auto'");return String(c)}return"auto"})(e),{data:o,error:a}=await s(c=>n.POST("/display/brightness",{params:{query:{value:r}},signal:c}),t.timeout);if(a)throw a;return o}class lt{async DisplayDraw(t){return await at(this.apiClient,t)}async DisplayClear(t){return await ct(this.apiClient,t)}async DisplayScreenFrameGet(t){return await ut(this.apiClient,t)}async DisplayBrightnessGet(t){return await ht(this.apiClient,t)}async DisplayBrightnessSet(t){return await dt(this.apiClient,t)}}async function wt(n,t){const{application_name:e,path:i}=t,{data:r,error:o}=await s(a=>n.POST("/audio/play",{params:{query:{application_name:e,path:i}},signal:a}),t.timeout);if(o)throw o;return r}async function ft(n,t){const{data:e,error:i}=await s(r=>n.DELETE("/audio/play",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function yt(n,t){const{data:e,error:i}=await s(r=>n.GET("/audio/volume",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function pt(n,t){const{volume:e}=t;if(typeof e!="number"||e<0||e>100)throw new Error("Volume must be a number between 0 and 100");const{data:i,error:r}=await s(o=>n.POST("/audio/volume",{params:{query:{volume:e}},signal:o}),t.timeout);if(r)throw r;return i}class St{async AudioPlay(t){return await wt(this.apiClient,t)}async AudioStop(t){return await ft(this.apiClient,t)}async AudioVolumeGet(t){return await yt(this.apiClient,t)}async AudioVolumeSet(t){return await pt(this.apiClient,t)}}async function Tt(n,t){const{data:e,error:i}=await s(r=>n.GET("/wifi/status",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function mt(n,t){const{ssid:e,password:i,security:r,ip_config:o}=t,{data:a,error:c}=await s(d=>n.POST("/wifi/connect",{body:{ssid:e,password:i,security:r,ip_config:o},signal:d}),t.timeout);if(c)throw c;return a}async function Et(n,t){const{data:e,error:i}=await s(r=>n.POST("/wifi/disconnect",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function Ct(n,t){const{data:e,error:i}=await s(r=>n.GET("/wifi/networks",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}class kt{async WifiStatusGet(t){return await Tt(this.apiClient,t)}async WifiConnect(t){return await mt(this.apiClient,t)}async WifiDisconnect(t){return await Et(this.apiClient,t)}async WifiNetworksGet(t){return await Ct(this.apiClient,t)}}async function gt(n,t){const{path:e,file:i}=t,{data:r,error:o}=await s(a=>n.POST("/storage/write",{params:{query:{path:e}},headers:{"Content-Type":"application/octet-stream"},body:i,signal:a}),t.timeout);if(o)throw o;return r}async function bt(n,t){const{path:e,as_array_buffer:i}=t,{data:r,error:o}=await s(a=>n.GET("/storage/read",{params:{query:{path:e}},parseAs:i?"arrayBuffer":"blob",signal:a}),t.timeout);if(o)throw o;return r}async function At(n,t){const{path:e}=t,{data:i,error:r}=await s(o=>n.GET("/storage/list",{params:{query:{path:e}},signal:o}),t.timeout);if(r)throw r;return i}async function Pt(n,t){const{path:e}=t,{data:i,error:r}=await s(o=>n.DELETE("/storage/remove",{params:{query:{path:e}},signal:o}),t.timeout);if(r)throw r;return i}async function Gt(n,t){const{path:e}=t,{data:i,error:r}=await s(o=>n.POST("/storage/mkdir",{params:{query:{path:e}},signal:o}),t.timeout);if(r)throw r;return i}async function vt(n,t){const{data:e,error:i}=await s(r=>n.GET("/storage/status",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function Ot(n,t){const{path:e,new_path:i}=t,{data:r,error:o}=await s(a=>n.POST("/storage/rename",{params:{query:{path:e,new_path:i}},signal:a}),t.timeout);if(o)throw o;return r}class Lt{async StorageWrite(t){return await gt(this.apiClient,t)}async StorageRead(t){return await bt(this.apiClient,t)}async StorageListGet(t){return await At(this.apiClient,t)}async StorageRemove(t){return await Pt(this.apiClient,t)}async StorageMkdir(t){return await Gt(this.apiClient,t)}async StorageStatusGet(t){return await vt(this.apiClient,t)}async StorageRename(t){return await Ot(this.apiClient,t)}}async function Dt(n,t){const{data:e,error:i}=await s(r=>n.GET("/access",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function Ut(n,t){const{mode:e,key:i}=t,r=i??"";if(String(r).trim()&&!/^\d{4,10}$/.test(String(r)))throw new Error("Key must be a string of 4 to 10 digits");const{data:o,error:a}=await s(c=>n.POST("/access",{params:{query:{mode:e,key:r}},signal:c}),t.timeout);if(a)throw a;return o}async function Bt(n,t){const{data:e,error:i}=await s(r=>n.GET("/name",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function _t(n,t){const{name:e}=t,{data:i,error:r}=await s(o=>n.POST("/name",{body:{name:e},signal:o}),t.timeout);if(r)throw r;return i}class $t{async SettingsAccessGet(t){return await Dt(this.apiClient,t)}async SettingsAccessSet(t){const e=await Ut(this.apiClient,t);return t.mode==="key"&&t.key&&this.setApiKey(t.key),e}async SettingsNameGet(t){return await Bt(this.apiClient,t)}async SettingsNameSet(t){return await _t(this.apiClient,t)}}async function It(n,t){const{data:e,error:i}=await s(r=>n.POST("/ble/enable",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function Rt(n,t){const{data:e,error:i}=await s(r=>n.POST("/ble/disable",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function Kt(n,t){const{data:e,error:i}=await s(r=>n.DELETE("/ble/pairing",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function Ft(n,t){const{data:e,error:i}=await s(r=>n.GET("/ble/status",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}class Wt{async BleEnable(t){return await It(this.apiClient,t)}async BleDisable(t){return await Rt(this.apiClient,t)}async BleUnpair(t){return await Kt(this.apiClient,t)}async BleStatusGet(t){return await Ft(this.apiClient,t)}}async function Mt(n,t){const{key:e}=t,{data:i,error:r}=await s(o=>n.POST("/input",{params:{query:{key:e}},signal:o}),t.timeout);if(r)throw r;return i}class qt{async InputSend(t){return await Mt(this.apiClient,t)}}async function Nt(n,t){const{data:e,error:i}=await s(r=>n.GET("/smart_home/pairing",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function xt(n,t){const{data:e,error:i}=await s(r=>n.POST("/smart_home/pairing",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function Ht(n,t){const{data:e,error:i}=await s(r=>n.DELETE("/smart_home/pairing",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function Vt(n,t){const{data:e,error:i}=await s(r=>n.GET("/smart_home/switch",{signal:r}),t==null?void 0:t.timeout);if(i)throw i;return e}async function jt(n,t){const{timeout:e,...i}=t,{data:r,error:o}=await s(a=>n.POST("/smart_home/switch",{body:i,signal:a}),e);if(o)throw o;return r}class zt{async SmartHomePairingGet(t){return await Nt(this.apiClient,t)}async SmartHomePair(t){return await xt(this.apiClient,t)}async SmartHomeErase(t){return await Ht(this.apiClient,t)}async SmartHomeSwitchStateGet(t){return await Vt(this.apiClient,t)}async SmartHomeSwitchStateSet(t){return await jt(this.apiClient,t)}async MatterStatusGet(t){return await this.SmartHomePairingGet(t)}async MatterPair(t){return await this.SmartHomePair(t)}async MatterErase(t){return await this.SmartHomeErase(t)}}async function Jt(n,t){const{application_name:e,file:i,data:r}=t,{data:o,error:a}=await s(c=>n.POST("/assets/upload",{params:{query:{application_name:e,file:i}},headers:{"Content-Type":"application/octet-stream"},body:r,signal:c}),t.timeout);if(a)throw a;return o}async function Xt(n,t){const{application_name:e}=t,{data:i,error:r}=await s(o=>n.DELETE("/assets/upload",{params:{query:{application_name:e}},signal:o}),t.timeout);if(r)throw r;return i}class Yt{async AssetsUpload(t){return await Jt(this.apiClient,t)}async AssetsDelete(t){return await Xt(this.apiClient,t)}}const S="http://10.0.4.20",Qt="https://proxy.busy.app",Zt=/^https?:\/\/proxy(?:\.(?:dev|test|stage))?\.busy\.app$/i;function T(n){const t=n.split(".");if(t.length!==4)return!1;for(const e of t){if(e.length===0||e.length>1&&e[0]==="0"||!/^\d+$/.test(e))return!1;const i=Number(e);if(i<0||i>255)return!1}return!0}function m(n){return/\.local$/i.test(n)}class C{constructor(t){u(this,"addr");u(this,"apiSemver");u(this,"apiClient");u(this,"setApiKeyFn");u(this,"setTokenFn");u(this,"connectionType","unknown");if(!t||!t.addr&&!t.token)this.addr=S;else if(!t.addr)this.addr=Qt;else{let o=t.addr.trim();if(/^https?:\/\//i.test(o)||(o=`http://${o}`),Zt.test(o)&&!t.token)throw new Error("Token is required. Please provide it.");this.addr=o}this.apiSemver="";const{client:e,setApiKey:i,setToken:r}=D(`${this.addr}/api/`,this.SystemVersionGet.bind(this),t==null?void 0:t.token);this.apiClient=e,this.setApiKeyFn=i,this.setTokenFn=r,this.detectConnectionType()}async detectConnectionType(){const t=new URL(this.addr).hostname;if(!T(t)&&!m(t)){this.connectionType="wifi";return}const e=E({baseUrl:`${this.addr}/api/`});try{const{response:i}=await e.GET("/name");if(i.status===401||i.status===403)this.connectionType="wifi";else if(i.ok)this.connectionType="usb";else throw new Error(`Failed to detect connection type. Status: ${i.status}`)}catch(i){throw i}}setApiKey(t){this.setApiKeyFn(t)}setToken(t){this.setTokenFn(t)}}function te(n,t){t.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(i=>{Object.defineProperty(n.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i)||Object.create(null))})})}te(C,[K,j,Z,st,lt,St,kt,Lt,$t,Wt,qt,zt,Yt]);var f=(n=>(n[n.FRONT=0]="FRONT",n[n.BACK=1]="BACK",n))(f||{});const k=3e3,g=new Set([1001,1006,1012,1013,1014,3008]);function b(n,t){if(t<0||t>=n.length)throw new Error(`Index ${t} is out of bounds (0…${n.length-1})`);const e=n[t];if(e===void 0)throw new Error(`Unexpected undefined at index ${t}`);return e}function ee(n,t){let e=0;const i=n.length,r=[];for(;e<i;){const o=b(n,e);if(e+=1,(o&128)!==0){const a=o&127;for(let c=0;c<a*t;c++)r.push(n[e+c]);e+=a*t}else{const a=o,c=n.slice(e,e+t);for(let d=0;d<a;d++)for(let w=0;w<t;w++)r.push(c[w]);e+=t}}return new Uint8Array(r)}function ie(n){const t=new Uint8Array(n.length*2);let e=0,i=0;for(;e<n.length;){const r=b(n,e),o=r&15,a=r>>4&15;t[i]=o,t[i+1]=a,e+=1,i+=2}return t}const A=()=>typeof window<"u"&&typeof window.document<"u";class ne{constructor(t){u(this,"addr");u(this,"connected",!1);u(this,"apiKey");u(this,"apiSemver");u(this,"dataListeners",[]);u(this,"stopListeners",[]);u(this,"errorListeners",[]);u(this,"socket",null);if(this.config=t,!A())throw new Error("not browser");if(t.apiKey&&(this.apiKey=t.apiKey),t.apiSemver&&(this.apiSemver=t.apiSemver),!t||!t.addr)this.addr=S;else{let e=t.addr.trim();/^https?:\/\//i.test(e)||(e=`http://${e}`);try{const r=new URL(e).hostname;if(!T(r)&&!m(r))throw new Error(`Invalid address: "${t.addr}". Only IP addresses and mDNS names (ending in .local) are supported.`)}catch(i){throw i instanceof Error&&i.message.startsWith("Invalid address")?i:new Error(`Invalid URL format: "${t.addr}"`)}this.addr=e}}onData(t){this.dataListeners.push(t)}onStop(t){this.stopListeners.push(t)}onError(t){this.errorListeners.push(t)}emitData(t){for(const e of this.dataListeners)e(t)}emitStop(){for(const t of this.stopListeners)t()}emitError(t){for(const e of this.errorListeners)e(t)}async openWebsocket(){this.socket&&await this.closeWebsocket();const t=new URL(`${this.addr}/api/screen/ws`);if(this.apiKey&&t.searchParams.append("x-api-token",this.apiKey),this.apiSemver&&t.searchParams.append("x-api-sem-ver",this.apiSemver),!t)throw new Error("The WebSocket URL is not specified");this.socket=new WebSocket(t),this.socket.onopen=()=>{this.socket&&(this.socket.send(JSON.stringify({display:this.config.deviceScreen})),this.connected=!0)},this.socket.binaryType="arraybuffer",this.socket.onmessage=e=>{try{if(typeof e.data=="string")return;const i=new Uint8Array(e.data);let r;const o=this.config.deviceScreen===f.FRONT?3:2;try{const a=ee(i,o);this.config.deviceScreen===f.BACK?r=ie(a):r=a,this.emitData(r)}catch{this.emitData(i)}}catch{this.connected=!1,this.emitStop()}},this.socket.onerror=e=>{this.connected=!1,this.emitError({code:1006,message:"WebSocket error occurred",raw:e}),this.emitStop()},this.socket.onclose=async e=>{if(this.socket=null,this.connected=!1,e.code===k||g.has(e.code)){this.emitError({code:e.code,message:e.reason,raw:e});return}this.emitStop()}}closeWebsocket(){return this.connected=!1,new Promise(t=>{this.socket?(this.socket.onclose=()=>{t()},this.socket.close(),this.socket=null):t(),this.emitStop()})}}class re{constructor(t){u(this,"addr");u(this,"connected",!1);u(this,"apiKey");u(this,"apiSemver");u(this,"inputEvent");u(this,"dataListeners",[]);u(this,"stopListeners",[]);u(this,"errorListeners",[]);u(this,"socket",null);if(!A())throw new Error("not browser");if(t!=null&&t.apiKey&&(this.apiKey=t.apiKey),t!=null&&t.apiSemver&&(this.apiSemver=t.apiSemver),!t||!t.addr)this.addr=S;else{let e=t.addr.trim();/^https?:\/\//i.test(e)||(e=`http://${e}`);try{const r=new URL(e).hostname;if(!T(r)&&!m(r))throw new Error(`Invalid address: "${t.addr}". Only IP addresses and mDNS names (ending in .local) are supported.`)}catch(i){throw i instanceof Error&&i.message.startsWith("Invalid address")?i:new Error(`Invalid URL format: "${t.addr}"`)}this.addr=e}this.inputEvent={}}onData(t){this.dataListeners.push(t)}onStop(t){this.stopListeners.push(t)}onError(t){this.errorListeners.push(t)}emitData(t){for(const e of this.dataListeners)e(t)}emitStop(){for(const t of this.stopListeners)t()}emitError(t){for(const e of this.errorListeners)e(t)}async openWebsocket(){this.socket&&await this.closeWebsocket();const t=new URL(`${this.addr}/api/input`);if(this.apiKey&&t.searchParams.append("x-api-token",this.apiKey),this.apiSemver&&t.searchParams.append("x-api-sem-ver",this.apiSemver),!t)throw new Error("The WebSocket URL is not specified");this.socket=new WebSocket(t),this.socket.onopen=()=>{this.socket&&(this.connected=!0)},this.socket.binaryType="arraybuffer",this.socket.onmessage=e=>{try{if(typeof e.data=="string")return;const i=new Uint8Array(e.data);this.emitData(i)}catch{this.connected=!1,this.emitStop()}},this.socket.onerror=e=>{this.connected=!1,this.emitError({code:1006,message:"WebSocket error occurred",raw:e}),this.emitStop()},this.socket.onclose=async e=>{if(this.socket=null,this.connected=!1,e.code===k||g.has(e.code)){this.emitError({code:e.code,message:e.reason,raw:e});return}this.emitStop()}}sendInput({keyName:t,value:e}){if(!this.socket||!this.connected)throw new Error("WebSocket: Not connected");this.inputEvent[t]=e,this.socket.send(JSON.stringify(this.inputEvent)),e===0&&delete this.inputEvent[t]}closeWebsocket(){return this.connected=!1,new Promise(t=>{this.socket?(this.socket.onclose=()=>{t()},this.socket.close(),this.socket=null):t(),this.emitStop()})}}exports.BusyBar=C;exports.DeviceScreen=f;exports.Input=re;exports.ScreenStream=ne;
|
|
1
|
+
"use strict";var I=Object.defineProperty;var N=(i,t,e)=>t in i?I(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var h=(i,t,e)=>N(i,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("openapi-fetch"),c=require("./types.status-BeqxtQVd.cjs");var T=typeof document<"u"?document.currentScript:null;const G=(i,t)=>{if(typeof FormData<"u"&&i instanceof FormData||typeof Buffer<"u"&&typeof Buffer.isBuffer=="function"&&Buffer.isBuffer(i)||typeof File<"u"&&i instanceof File||typeof Blob<"u"&&i instanceof Blob||typeof ArrayBuffer<"u"&&i instanceof ArrayBuffer||typeof ArrayBuffer<"u"&&ArrayBuffer.isView&&ArrayBuffer.isView(i))return i;let e;return t&&(t instanceof Headers?e=t.get("Content-Type")??t.get("content-type")??void 0:typeof t=="object"&&(e=t["Content-Type"]??t["content-type"]),e==="application/x-www-form-urlencoded")?i&&typeof i=="object"&&!(i instanceof URLSearchParams)?new URLSearchParams(i).toString():String(i):JSON.stringify(i)};async function C(i){const r=(i.headers.get("content-type")||"").includes("application/json")?await i.clone().json():await i.clone().text(),n=typeof r=="object"&&r!==null?r.error||r.message:typeof r=="string"?r:void 0;return Object.assign(new Error(n||`HTTP ${i.status} ${i.statusText}`),{status:i.status,statusText:i.statusText,body:r})}async function s(i,t=3e3){if(t<=0)return await i();const e=new AbortController,r=setTimeout(()=>e.abort(),t);try{return await i(e.signal)}catch(n){throw n instanceof DOMException&&n.name==="AbortError"?new Error(`Request timed out after ${t}ms`):n}finally{clearTimeout(r)}}function B(i,t,e){let r,n=e??void 0,a,o=null;const l=async()=>{r||(o||(o=(async()=>{const d=await t();if(!d.api_semver)throw new Error("Empty API version");r=d.api_semver})().finally(()=>{o=null})),await o)},u={async onRequest({request:d,schemaPath:f}){return n&&d.headers.set("Authorization",`Bearer ${n}`),f!=="/version"&&(await l(),r&&d.headers.set("X-API-Sem-Ver",r),a&&d.headers.set("X-API-Token",a)),d},async onResponse({request:d,response:f,options:U,schemaPath:O}){if(f.ok)return f;if(O==="/version")throw await C(f);if(f.status!==405)throw await C(f);r=void 0,await l(),r&&d.headers.set("X-API-Sem-Ver",r),n&&d.headers.set("Authorization",`Bearer ${n}`);const E=await(U.fetch??fetch)(d);if(E.ok)return E;throw await C(E)}},w=_({baseUrl:i,bodySerializer:G});return w.use(u),{client:w,setApiKey:d=>{a=d},setToken:d=>{n=d}}}async function x(i,t){const{data:e,error:r}=await s(n=>i.GET("/version",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function F(i,t){const{data:e,error:r}=await s(n=>i.GET("/status",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function W(i,t){const{data:e,error:r}=await s(n=>i.GET("/status/system",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function M(i,t){const{data:e,error:r}=await s(n=>i.GET("/status/power",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function $(i,t){const{data:e,error:r}=await s(n=>i.GET("/status/device",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function K(i,t){const{data:e,error:r}=await s(n=>i.GET("/status/firmware",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}class z{async SystemVersionGet(t){const e=await x(this.apiClient,t);return this.apiSemver=e.api_semver,e}async SystemStatusGet(t){return await F(this.apiClient,t)}async SystemInfoGet(t){return await W(this.apiClient,t)}async SystemStatusPowerGet(t){return await M(this.apiClient,t)}async SystemStatusDeviceGet(t){return await $(this.apiClient,t)}async SystemStatusFirmwareGet(t){return await K(this.apiClient,t)}}async function H(i,t){const{file:e}=t,{data:r,error:n}=await s(a=>i.POST("/update",{headers:{"Content-Type":"application/octet-stream"},body:e,signal:a}),t.timeout);if(n)throw n;return r}async function q(i,t){const{data:e,error:r}=await s(n=>i.POST("/update/check",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function V(i,t){const{data:e,error:r}=await s(n=>i.GET("/update/status",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function X(i,t){const{version:e}=t,{data:r,error:n}=await s(a=>i.GET("/update/changelog",{params:{query:{version:e}},signal:a}),t.timeout);if(n)throw n;return r}async function j(i,t){const{version:e}=t,{data:r,error:n}=await s(a=>i.POST("/update/install",{params:{query:{version:e}},signal:a}),t.timeout);if(n)throw n;return r}async function Y(i,t){const{data:e,error:r}=await s(n=>i.POST("/update/abort_download",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function J(i,t){const{data:e,error:r}=await s(n=>i.GET("/update/autoupdate",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function Q(i,t){const{is_enabled:e,interval_start:r,interval_end:n}=t,{data:a,error:o}=await s(l=>i.POST("/update/autoupdate",{body:{is_enabled:e,interval_start:r,interval_end:n},signal:l}),t.timeout);if(o)throw o;return a}class Z{async UpdateFromFile(t){return await H(this.apiClient,t)}async UpdateCheck(t){return await q(this.apiClient,t)}async UpdateStatusGet(t){return await V(this.apiClient,t)}async UpdateChangelogGet(t){return await X(this.apiClient,t)}async UpdateInstall(t){return await j(this.apiClient,t)}async UpdateAbort(t){return await Y(this.apiClient,t)}async UpdateAutoUpdateGet(t){return await J(this.apiClient,t)}async UpdateAutoUpdateSet(t){return await Q(this.apiClient,t)}}async function tt(i,t){const{data:e,error:r}=await s(n=>i.GET("/time",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function et(i,t){const{timestamp:e}=t,{data:r,error:n}=await s(a=>i.POST("/time/timestamp",{params:{query:{timestamp:e}},signal:a}),t.timeout);if(n)throw n;return r}async function rt(i,t){const{data:e,error:r}=await s(n=>i.GET("/time/timezone",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function it(i,t){const{timezone:e}=t,{data:r,error:n}=await s(a=>i.POST("/time/timezone",{params:{query:{timezone:e}},signal:a}),t.timeout);if(n)throw n;return r}async function nt(i,t){const{data:e,error:r}=await s(n=>i.GET("/time/tzlist",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}class at{async TimeGet(t){return await tt(this.apiClient,t)}async TimeTimestampSet(t){return await et(this.apiClient,t)}async TimeTimezoneGet(t){return await rt(this.apiClient,t)}async TimeTimezoneSet(t){return await it(this.apiClient,t)}async TimeTzListGet(t){return await nt(this.apiClient,t)}}async function st(i,t){const{data:e,error:r}=await s(n=>i.GET("/account/status",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function ot(i,t){const{data:e,error:r}=await s(n=>i.GET("/account/info",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function ct(i,t){const{data:e,error:r}=await s(n=>i.GET("/account/profile",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function ut(i,t){const{profile:e,custom_url:r}=t,{data:n,error:a}=await s(o=>i.POST("/account/profile",{params:{query:{profile:e,custom_url:r}},signal:o}),t.timeout);if(a)throw a;return n}async function ht(i,t){const{data:e,error:r}=await s(n=>i.DELETE("/account",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function lt(i,t){const{data:e,error:r}=await s(n=>i.POST("/account/link",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}class dt{async AccountInfoGet(t){return await ot(this.apiClient,t)}async AccountStateGet(t){return await st(this.apiClient,t)}async AccountProfileGet(t){return await ct(this.apiClient,t)}async AccountProfileSet(t){return await ut(this.apiClient,t)}async AccountUnlink(t){return await ht(this.apiClient,t)}async AccountLink(t){return await lt(this.apiClient,t)}}async function ft(i,t){const{application_name:e,elements:r,priority:n=50,timeout:a}=t,{data:o,error:l}=await s(u=>i.POST("/display/draw",{body:{application_name:e,priority:n,elements:r},signal:u}),a);if(l)throw l;return o}async function wt(i,t){const{data:e,error:r}=await s(n=>i.DELETE("/display/draw",{params:{query:{application_name:t==null?void 0:t.application_name}},signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function mt(i,t){const{display:e,timeout:r}=t,{data:n,error:a}=await s(o=>i.GET("/screen",{params:{query:{display:e}},parseAs:"blob",signal:o}),r);if(a)throw a;return n}async function yt(i,t){const{data:e,error:r}=await s(n=>i.GET("/display/brightness",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function St(i,t){const{value:e}=t,n=(l=>{if(typeof l=="number"){if(l<0||l>100)throw new Error("Brightness value must be between 0 and 100 or 'auto'");return String(l)}return"auto"})(e),{data:a,error:o}=await s(l=>i.POST("/display/brightness",{params:{query:{value:n}},signal:l}),t.timeout);if(o)throw o;return a}class pt{async DisplayDraw(t){return await ft(this.apiClient,t)}async DisplayClear(t){return await wt(this.apiClient,t)}async DisplayScreenFrameGet(t){return await mt(this.apiClient,t)}async DisplayBrightnessGet(t){return await yt(this.apiClient,t)}async DisplayBrightnessSet(t){return await St(this.apiClient,t)}}async function Et(i,t){const{application_name:e,path:r}=t,{data:n,error:a}=await s(o=>i.POST("/audio/play",{params:{query:{application_name:e,path:r}},signal:o}),t.timeout);if(a)throw a;return n}async function Tt(i,t){const{data:e,error:r}=await s(n=>i.DELETE("/audio/play",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function Ct(i,t){const{data:e,error:r}=await s(n=>i.GET("/audio/volume",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function kt(i,t){const{volume:e}=t;if(typeof e!="number"||e<0||e>100)throw new Error("Volume must be a number between 0 and 100");const{data:r,error:n}=await s(a=>i.POST("/audio/volume",{params:{query:{volume:e}},signal:a}),t.timeout);if(n)throw n;return r}class At{async AudioPlay(t){return await Et(this.apiClient,t)}async AudioStop(t){return await Tt(this.apiClient,t)}async AudioVolumeGet(t){return await Ct(this.apiClient,t)}async AudioVolumeSet(t){return await kt(this.apiClient,t)}}async function gt(i,t){const{data:e,error:r}=await s(n=>i.GET("/wifi/status",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function bt(i,t){const{ssid:e,password:r,security:n,ip_config:a}=t,{data:o,error:l}=await s(u=>i.POST("/wifi/connect",{body:{ssid:e,password:r,security:n,ip_config:a},signal:u}),t.timeout);if(l)throw l;return o}async function _t(i,t){const{data:e,error:r}=await s(n=>i.POST("/wifi/disconnect",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function Rt(i,t){const{data:e,error:r}=await s(n=>i.GET("/wifi/networks",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}class Dt{async WifiStatusGet(t){return await gt(this.apiClient,t)}async WifiConnect(t){return await bt(this.apiClient,t)}async WifiDisconnect(t){return await _t(this.apiClient,t)}async WifiNetworksGet(t){return await Rt(this.apiClient,t)}}async function vt(i,t){const{path:e,file:r}=t,{data:n,error:a}=await s(o=>i.POST("/storage/write",{params:{query:{path:e}},headers:{"Content-Type":"application/octet-stream"},body:r,signal:o}),t.timeout);if(a)throw a;return n}async function Pt(i,t){const{path:e,as_array_buffer:r}=t,{data:n,error:a}=await s(o=>i.GET("/storage/read",{params:{query:{path:e}},parseAs:r?"arrayBuffer":"blob",signal:o}),t.timeout);if(a)throw a;return n}async function Lt(i,t){const{path:e}=t,{data:r,error:n}=await s(a=>i.GET("/storage/list",{params:{query:{path:e}},signal:a}),t.timeout);if(n)throw n;return r}async function Ut(i,t){const{path:e}=t,{data:r,error:n}=await s(a=>i.DELETE("/storage/remove",{params:{query:{path:e}},signal:a}),t.timeout);if(n)throw n;return r}async function Ot(i,t){const{path:e}=t,{data:r,error:n}=await s(a=>i.POST("/storage/mkdir",{params:{query:{path:e}},signal:a}),t.timeout);if(n)throw n;return r}async function It(i,t){const{data:e,error:r}=await s(n=>i.GET("/storage/status",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function Nt(i,t){const{path:e,new_path:r}=t,{data:n,error:a}=await s(o=>i.POST("/storage/rename",{params:{query:{path:e,new_path:r}},signal:o}),t.timeout);if(a)throw a;return n}class Gt{async StorageWrite(t){return await vt(this.apiClient,t)}async StorageRead(t){return await Pt(this.apiClient,t)}async StorageListGet(t){return await Lt(this.apiClient,t)}async StorageRemove(t){return await Ut(this.apiClient,t)}async StorageMkdir(t){return await Ot(this.apiClient,t)}async StorageStatusGet(t){return await It(this.apiClient,t)}async StorageRename(t){return await Nt(this.apiClient,t)}}async function Bt(i,t){const{data:e,error:r}=await s(n=>i.GET("/access",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function xt(i,t){const{mode:e,key:r}=t,n=r??"";if(String(n).trim()&&!/^\d{4,10}$/.test(String(n)))throw new Error("Key must be a string of 4 to 10 digits");const{data:a,error:o}=await s(l=>i.POST("/access",{params:{query:{mode:e,key:n}},signal:l}),t.timeout);if(o)throw o;return a}async function Ft(i,t){const{data:e,error:r}=await s(n=>i.GET("/name",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function Wt(i,t){const{name:e}=t,{data:r,error:n}=await s(a=>i.POST("/name",{body:{name:e},signal:a}),t.timeout);if(n)throw n;return r}class Mt{async SettingsAccessGet(t){return await Bt(this.apiClient,t)}async SettingsAccessSet(t){const e=await xt(this.apiClient,t);return t.mode==="key"&&t.key&&this.setApiKey(t.key),e}async SettingsNameGet(t){return await Ft(this.apiClient,t)}async SettingsNameSet(t){return await Wt(this.apiClient,t)}}async function $t(i,t){const{data:e,error:r}=await s(n=>i.POST("/ble/enable",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function Kt(i,t){const{data:e,error:r}=await s(n=>i.POST("/ble/disable",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function zt(i,t){const{data:e,error:r}=await s(n=>i.DELETE("/ble/pairing",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function Ht(i,t){const{data:e,error:r}=await s(n=>i.GET("/ble/status",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}class qt{async BleEnable(t){return await $t(this.apiClient,t)}async BleDisable(t){return await Kt(this.apiClient,t)}async BleUnpair(t){return await zt(this.apiClient,t)}async BleStatusGet(t){return await Ht(this.apiClient,t)}}async function Vt(i,t){const{key:e}=t,{data:r,error:n}=await s(a=>i.POST("/input",{params:{query:{key:e}},signal:a}),t.timeout);if(n)throw n;return r}class Xt{async InputSend(t){return await Vt(this.apiClient,t)}}async function jt(i,t){const{data:e,error:r}=await s(n=>i.GET("/smart_home/pairing",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function Yt(i,t){const{data:e,error:r}=await s(n=>i.POST("/smart_home/pairing",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function Jt(i,t){const{data:e,error:r}=await s(n=>i.DELETE("/smart_home/pairing",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function Qt(i,t){const{data:e,error:r}=await s(n=>i.GET("/smart_home/switch",{signal:n}),t==null?void 0:t.timeout);if(r)throw r;return e}async function Zt(i,t){const{timeout:e,...r}=t,{data:n,error:a}=await s(o=>i.POST("/smart_home/switch",{body:r,signal:o}),e);if(a)throw a;return n}class te{async SmartHomePairingGet(t){return await jt(this.apiClient,t)}async SmartHomePair(t){return await Yt(this.apiClient,t)}async SmartHomeErase(t){return await Jt(this.apiClient,t)}async SmartHomeSwitchStateGet(t){return await Qt(this.apiClient,t)}async SmartHomeSwitchStateSet(t){return await Zt(this.apiClient,t)}async MatterStatusGet(t){return await this.SmartHomePairingGet(t)}async MatterPair(t){return await this.SmartHomePair(t)}async MatterErase(t){return await this.SmartHomeErase(t)}}async function ee(i,t){const{application_name:e,file:r,data:n}=t,{data:a,error:o}=await s(l=>i.POST("/assets/upload",{params:{query:{application_name:e,file:r}},headers:{"Content-Type":"application/octet-stream"},body:n,signal:l}),t.timeout);if(o)throw o;return a}async function re(i,t){const{application_name:e}=t,{data:r,error:n}=await s(a=>i.DELETE("/assets/upload",{params:{query:{application_name:e}},signal:a}),t.timeout);if(n)throw n;return r}class ie{async AssetsUpload(t){return await ee(this.apiClient,t)}async AssetsDelete(t){return await re(this.apiClient,t)}}const A="http://10.0.4.20",ne="https://proxy.busy.app",ae=/^https?:\/\/proxy(?:\.(?:dev|test|stage))?\.busy\.app$/i;function g(i){const t=i.split(".");if(t.length!==4)return!1;for(const e of t){if(e.length===0||e.length>1&&e[0]==="0"||!/^\d+$/.test(e))return!1;const r=Number(e);if(r<0||r>255)return!1}return!0}function b(i){return/\.local$/i.test(i)}class R{constructor(t){h(this,"addr");h(this,"apiSemver");h(this,"apiClient");h(this,"setApiKeyFn");h(this,"setTokenFn");h(this,"connectionType","unknown");if(!t||!t.addr&&!t.token)this.addr=A;else if(!t.addr)this.addr=ne;else{let a=t.addr.trim();if(/^https?:\/\//i.test(a)||(a=`http://${a}`),ae.test(a)&&!t.token)throw new Error("Token is required. Please provide it.");this.addr=a}this.apiSemver="";const{client:e,setApiKey:r,setToken:n}=B(`${this.addr}/api/`,this.SystemVersionGet.bind(this),t==null?void 0:t.token);this.apiClient=e,this.setApiKeyFn=r,this.setTokenFn=n,this.detectConnectionType()}async detectConnectionType(){const t=new URL(this.addr).hostname;if(!g(t)&&!b(t)){this.connectionType="wifi";return}const e=_({baseUrl:`${this.addr}/api/`});try{const{response:r}=await e.GET("/name");if(r.status===401||r.status===403)this.connectionType="wifi";else if(r.ok)this.connectionType="usb";else throw new Error(`Failed to detect connection type. Status: ${r.status}`)}catch(r){throw r}}setApiKey(t){this.setApiKeyFn(t)}setToken(t){this.setTokenFn(t)}}function se(i,t){t.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(r=>{Object.defineProperty(i.prototype,r,Object.getOwnPropertyDescriptor(e.prototype,r)||Object.create(null))})})}se(R,[z,Z,at,dt,pt,At,Dt,Gt,Mt,qt,Xt,te,ie]);var S=(i=>(i[i.FRONT=0]="FRONT",i[i.BACK=1]="BACK",i))(S||{});const D=3e3,v=new Set([1001,1006,1012,1013,1014,3008]);function P(i,t){if(t<0||t>=i.length)throw new Error(`Index ${t} is out of bounds (0…${i.length-1})`);const e=i[t];if(e===void 0)throw new Error(`Unexpected undefined at index ${t}`);return e}function oe(i,t){let e=0;const r=i.length,n=[];for(;e<r;){const a=P(i,e);if(e+=1,(a&128)!==0){const o=a&127;for(let l=0;l<o*t;l++)n.push(i[e+l]);e+=o*t}else{const o=a,l=i.slice(e,e+t);for(let u=0;u<o;u++)for(let w=0;w<t;w++)n.push(l[w]);e+=t}}return new Uint8Array(n)}function ce(i){const t=new Uint8Array(i.length*2);let e=0,r=0;for(;e<i.length;){const n=P(i,e),a=n&15,o=n>>4&15;t[r]=a,t[r+1]=o,e+=1,r+=2}return t}const L=()=>typeof window<"u"&&typeof window.document<"u";class ue{constructor(t){h(this,"addr");h(this,"connected",!1);h(this,"apiKey");h(this,"apiSemver");h(this,"dataListeners",[]);h(this,"stopListeners",[]);h(this,"errorListeners",[]);h(this,"socket",null);if(this.config=t,!L())throw new Error("not browser");if(t.apiKey&&(this.apiKey=t.apiKey),t.apiSemver&&(this.apiSemver=t.apiSemver),!t||!t.addr)this.addr=A;else{let e=t.addr.trim();/^https?:\/\//i.test(e)||(e=`http://${e}`);try{const n=new URL(e).hostname;if(!g(n)&&!b(n))throw new Error(`Invalid address: "${t.addr}". Only IP addresses and mDNS names (ending in .local) are supported.`)}catch(r){throw r instanceof Error&&r.message.startsWith("Invalid address")?r:new Error(`Invalid URL format: "${t.addr}"`)}this.addr=e}}onData(t){this.dataListeners.push(t)}onStop(t){this.stopListeners.push(t)}onError(t){this.errorListeners.push(t)}emitData(t){for(const e of this.dataListeners)e(t)}emitStop(){for(const t of this.stopListeners)t()}emitError(t){for(const e of this.errorListeners)e(t)}async openWebsocket(){this.socket&&await this.closeWebsocket();const t=new URL(`${this.addr}/api/screen/ws`);if(this.apiKey&&t.searchParams.append("x-api-token",this.apiKey),this.apiSemver&&t.searchParams.append("x-api-sem-ver",this.apiSemver),!t)throw new Error("The WebSocket URL is not specified");this.socket=new WebSocket(t),this.socket.onopen=()=>{this.socket&&(this.socket.send(JSON.stringify({display:this.config.deviceScreen})),this.connected=!0)},this.socket.binaryType="arraybuffer",this.socket.onmessage=e=>{try{if(typeof e.data=="string")return;const r=new Uint8Array(e.data);let n;const a=this.config.deviceScreen===S.FRONT?3:2;try{const o=oe(r,a);this.config.deviceScreen===S.BACK?n=ce(o):n=o,this.emitData(n)}catch{this.emitData(r)}}catch{this.connected=!1,this.emitStop()}},this.socket.onerror=e=>{this.connected=!1,this.emitError({code:1006,message:"WebSocket error occurred",raw:e}),this.emitStop()},this.socket.onclose=async e=>{if(this.socket=null,this.connected=!1,e.code===D||v.has(e.code)){this.emitError({code:e.code,message:e.reason,raw:e});return}this.emitStop()}}closeWebsocket(){return this.connected=!1,new Promise(t=>{this.socket?(this.socket.onclose=()=>{t()},this.socket.close(),this.socket=null):t(),this.emitStop()})}}class he{constructor(t){h(this,"addr");h(this,"connected",!1);h(this,"apiKey");h(this,"apiSemver");h(this,"inputEvent");h(this,"dataListeners",[]);h(this,"stopListeners",[]);h(this,"errorListeners",[]);h(this,"socket",null);if(!L())throw new Error("not browser");if(t!=null&&t.apiKey&&(this.apiKey=t.apiKey),t!=null&&t.apiSemver&&(this.apiSemver=t.apiSemver),!t||!t.addr)this.addr=A;else{let e=t.addr.trim();/^https?:\/\//i.test(e)||(e=`http://${e}`);try{const n=new URL(e).hostname;if(!g(n)&&!b(n))throw new Error(`Invalid address: "${t.addr}". Only IP addresses and mDNS names (ending in .local) are supported.`)}catch(r){throw r instanceof Error&&r.message.startsWith("Invalid address")?r:new Error(`Invalid URL format: "${t.addr}"`)}this.addr=e}this.inputEvent={}}onData(t){this.dataListeners.push(t)}onStop(t){this.stopListeners.push(t)}onError(t){this.errorListeners.push(t)}emitData(t){for(const e of this.dataListeners)e(t)}emitStop(){for(const t of this.stopListeners)t()}emitError(t){for(const e of this.errorListeners)e(t)}async openWebsocket(){this.socket&&await this.closeWebsocket();const t=new URL(`${this.addr}/api/input`);if(this.apiKey&&t.searchParams.append("x-api-token",this.apiKey),this.apiSemver&&t.searchParams.append("x-api-sem-ver",this.apiSemver),!t)throw new Error("The WebSocket URL is not specified");this.socket=new WebSocket(t),this.socket.onopen=()=>{this.socket&&(this.connected=!0)},this.socket.binaryType="arraybuffer",this.socket.onmessage=e=>{try{if(typeof e.data=="string")return;const r=new Uint8Array(e.data);this.emitData(r)}catch{this.connected=!1,this.emitStop()}},this.socket.onerror=e=>{this.connected=!1,this.emitError({code:1006,message:"WebSocket error occurred",raw:e}),this.emitStop()},this.socket.onclose=async e=>{if(this.socket=null,this.connected=!1,e.code===D||v.has(e.code)){this.emitError({code:e.code,message:e.reason,raw:e});return}this.emitStop()}}sendInput({keyName:t,value:e}){if(!this.socket||!this.connected)throw new Error("WebSocket: Not connected");this.inputEvent[t]=e,this.socket.send(JSON.stringify(this.inputEvent)),e===0&&delete this.inputEvent[t]}closeWebsocket(){return this.connected=!1,new Promise(t=>{this.socket?(this.socket.onclose=()=>{t()},this.socket.close(),this.socket=null):t(),this.emitStop()})}}const m=class m{constructor(t,e){h(this,"addr");h(this,"token");h(this,"isBinary");h(this,"connectTimeout");h(this,"dataTimeout");h(this,"worker",null);h(this,"connectionTimer",null);h(this,"dataTimer",null);h(this,"_status");h(this,"dataCallback");h(this,"rawDataCallback");h(this,"errorCallback");h(this,"statusCallback");this.addr=t.addr||"",this.token=t.token,this.isBinary=t.isBinary??!0,this.connectTimeout=(e==null?void 0:e.timeout)??5e3,this.dataTimeout=(e==null?void 0:e.dataTimeout)??15e3,this._status={main:{status:c.StreamLifecycle.IDLE},connection:{status:c.ConnectionStatus.DISCONNECTED},auth:{status:c.AuthStatus.UNAUTHENTICATED},data:{status:c.DataStatus.NONE},worker:{status:c.WorkerStatus.OFF}}}get status(){return this._status}resolveProtocol(t){let e=t.trim();if(e.startsWith("https://"))return e.replace("https://","wss://");if(e.startsWith("http://"))return e.replace("http://","ws://");if(e.startsWith("wss://")||e.startsWith("ws://"))return e;let r="ws:";return typeof window<"u"&&window.location.protocol==="https:"&&(r="wss:"),`${r}//${e}`}start({dataCallback:t,rawDataCallback:e,errorCallback:r,statusCallback:n}){if(this._status.main.status===c.StreamLifecycle.STARTING||this._status.main.status===c.StreamLifecycle.RUNNING){const a=new c.StateStreamError(c.StateStreamErrorCode.STREAM_ALREADY_STARTED,"StateStream is already running. Call stop() before starting again.");if(n&&n({...this._status,main:{...this._status.main,lastError:a}}),r)r(a);else throw a;return}this.dataCallback=t,this.rawDataCallback=e,this.errorCallback=r,this.statusCallback=n,this.updateStatusComponent("main",{status:c.StreamLifecycle.STARTING,lastError:void 0});try{this.ensureWorker(),this.sendCommand({type:"START",addr:this.normalizeUrl(this.addr),token:this.token,isBinary:this.isBinary,mode:this.streamMode}),this.clearConnectionTimer(),this.connectionTimer=setTimeout(()=>{const a=new c.StateStreamError(c.StateStreamErrorCode.CONNECTION_TIMEOUT,`Connection timed out after ${this.connectTimeout}ms`);this.mapErrorToStatus(a),this.errorCallback&&this.errorCallback(a),this.stop()},this.connectTimeout)}catch(a){const o=a instanceof c.StateStreamError?a:new c.StateStreamError(c.StateStreamErrorCode.UNKNOWN_ERROR,String(a));this.errorCallback&&this.errorCallback(o)}}stop(){this.clearConnectionTimer(),this.clearDataTimer(),!(this._status.main.status===c.StreamLifecycle.IDLE||this._status.main.status===c.StreamLifecycle.STOPPED)&&(this.updateStatusComponent("main",{status:c.StreamLifecycle.STOPPED}),this.updateStatusComponent("connection",{status:c.ConnectionStatus.DISCONNECTED}),this.sendCommand({type:"STOP"}),this.clearCallbacks())}destroy(){this.stop(),this.worker&&(this.worker.terminate?this.worker.terminate():"close"in this.worker.port&&this.worker.port.close(),this.worker=null)}clearCallbacks(){this.dataCallback=void 0,this.rawDataCallback=void 0,this.errorCallback=void 0,this.statusCallback=void 0}sendToken(t){this.token=t,this.sendCommand({type:"UPDATE_TOKEN",token:t})}sendCommand(t){this.worker&&this.worker.port.postMessage(t)}ensureWorker(){if(this.worker||typeof window>"u")return;const t=btoa(this.addr);try{this.updateStatusComponent("worker",{status:c.WorkerStatus.INITIALIZING,lastError:void 0});const e=new URL("./index.worker.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:T&&T.tagName.toUpperCase()==="SCRIPT"&&T.src||new URL("index.cjs",document.baseURI).href);if(window.SharedWorker){const r=new SharedWorker(e,{name:t,type:"module"});this.worker={port:r.port},r.port.onmessage=n=>{this.handleWorkerMessage(n.data)},r.port.start()}else{const r=new Worker(e,{type:"module"});this.worker={port:r,terminate:()=>r.terminate()},r.onmessage=n=>{this.handleWorkerMessage(n.data)}}this.updateStatusComponent("worker",{status:c.WorkerStatus.READY})}catch(e){const r=new c.StateStreamError(c.StateStreamErrorCode.WORKER_INIT_FAILED,`Failed to initialize worker: ${String(e)}`);throw this.updateStatusComponent("worker",{status:c.WorkerStatus.ERROR,lastError:r}),this.updateStatusComponent("main",{status:c.StreamLifecycle.FAILED,lastError:r}),r}}handleWorkerMessage(t){switch(t.type){case"DATA":this.resetDataTimer(),this.dataCallback&&this.dataCallback(this.normalizeState(t.data));break;case"RAW_DATA":this.resetDataTimer(),this.rawDataCallback&&this.rawDataCallback(t.data);break;case"CONNECTED":this.clearConnectionTimer(),this.updateStatusComponent("connection",{status:c.ConnectionStatus.CONNECTED}),this.streamMode==="local"&&this.updateStatusComponent("main",{status:c.StreamLifecycle.RUNNING});break;case"STATUS_UPDATE":t.connection&&this.updateStatusComponent("connection",{status:t.connection}),t.auth&&(this.updateStatusComponent("auth",{status:t.auth}),t.auth===c.AuthStatus.AUTHENTICATED&&this.updateStatusComponent("main",{status:c.StreamLifecycle.RUNNING}));break;case"ERROR":{this.clearConnectionTimer();const e=new c.StateStreamError(t.code,t.message,t.data);this.mapErrorToStatus(e),this.errorCallback&&this.errorCallback(e);break}case"TOKEN_EXPIRED":this.updateStatusComponent("auth",{status:c.AuthStatus.AUTHENTICATING}),this.handleTokenExpiredInternal();break;case"DISCONNECTED":this.updateStatusComponent("connection",{status:c.ConnectionStatus.DISCONNECTED});break}}mapErrorToStatus(t){const e=t.code;(e===c.StateStreamErrorCode.CONNECTION_FAILED||e===c.StateStreamErrorCode.CONNECTION_LOST||e===c.StateStreamErrorCode.RECONNECT_FAILED||e===c.StateStreamErrorCode.CONNECTION_TIMEOUT)&&(this.updateStatusComponent("connection",{status:c.ConnectionStatus.DISCONNECTED,lastError:t}),this.updateStatusComponent("main",{status:c.StreamLifecycle.FAILED,lastError:t})),(e===c.StateStreamErrorCode.AUTH_FAILED||e===c.StateStreamErrorCode.AUTH_REFRESH_FAILED)&&(this.updateStatusComponent("auth",{status:c.AuthStatus.FAILED,lastError:t}),this.updateStatusComponent("main",{status:c.StreamLifecycle.FAILED,lastError:t})),(e===c.StateStreamErrorCode.DEVICE_ERROR||e===c.StateStreamErrorCode.DECODE_ERROR)&&this.updateStatusComponent("main",{lastError:t})}updateStatusComponent(t,e){const r=this._status[t];this._status[t]={...r,...e},this.statusCallback&&this.statusCallback({...this._status})}clearConnectionTimer(){this.connectionTimer&&(clearTimeout(this.connectionTimer),this.connectionTimer=null)}resetDataTimer(){this.clearDataTimer(),this._status.data.status!==c.DataStatus.ACTIVE?this.updateStatusComponent("data",{status:c.DataStatus.ACTIVE,lastActivity:Date.now()}):this._status.data.lastActivity=Date.now(),this.dataTimer=setTimeout(()=>{this.updateStatusComponent("data",{status:c.DataStatus.STALE})},this.dataTimeout)}clearDataTimer(){this.dataTimer&&(clearTimeout(this.dataTimer),this.dataTimer=null)}normalizeState(t){let e,r;"bar_id"in t&&"state"in t?(e=t.state,r=t.bar_id):e=t;let n=e.updates;return n&&(n=n.map(a=>{const o=Object.keys(a).find(l=>a[l]!=null);return{...a,state:o}})),{...e,updates:n,bar_id:r}}async handleTokenExpiredInternal(){const t=this.addr;let e=m.tokenRefreshPromises.get(t);if(!e&&this.onTokenExpired&&(e=(async()=>{try{const n=this.onTokenExpired();return n instanceof Promise?await n:""}finally{m.tokenRefreshPromises.delete(t)}})(),m.tokenRefreshPromises.set(t,e)),e){const r=await e;r&&this.sendToken(r)}}};h(m,"tokenRefreshPromises",new Map);let p=m;class le extends p{constructor(e={},r){let n=e.addr;n||(typeof window<"u"?n=window.location.origin:n="10.0.4.20");super({isBinary:!0,...e,addr:n},r);h(this,"streamMode","local")}normalizeUrl(e){const r=this.resolveProtocol(e),n=new URL(r);return(n.pathname==="/"||!n.pathname)&&(n.pathname="/api/status/ws"),n.toString()}}class de extends p{constructor(e,r){super({isBinary:!1,...e},r);h(this,"streamMode","remote");h(this,"tokenProvider");this.tokenProvider=e.tokenProvider}subscribe(e){this.sendCommand({type:"SUBSCRIBE",guid:e})}unsubscribe(e){this.sendCommand({type:"UNSUBSCRIBE",guid:e})}normalizeUrl(e){return this.resolveProtocol(e)}onTokenExpired(){if(this.tokenProvider)return this.tokenProvider().then(e=>(this.sendToken(e),e)).catch(e=>{const r=`Failed to refresh token: ${e.message}`;throw this.errorCallback&&this.errorCallback(new c.StateStreamError(c.StateStreamErrorCode.AUTH_REFRESH_FAILED,r)),e})}}const y=class y{constructor(){h(this,"gl",null);h(this,"program",null);h(this,"texture",null);h(this,"vs",`#version 300 es
|
|
2
|
+
in vec2 position;
|
|
3
|
+
out vec2 v_uv;
|
|
4
|
+
void main() {
|
|
5
|
+
v_uv = position * 0.5 + 0.5;
|
|
6
|
+
v_uv.y = 1.0 - v_uv.y;
|
|
7
|
+
gl_Position = vec4(position, 0, 1);
|
|
8
|
+
}
|
|
9
|
+
`);h(this,"fs",`#version 300 es
|
|
10
|
+
precision highp float;
|
|
11
|
+
in vec2 v_uv;
|
|
12
|
+
out vec4 outColor;
|
|
13
|
+
uniform sampler2D u_texture;
|
|
14
|
+
uniform vec2 u_dataRes;
|
|
15
|
+
uniform vec2 u_canvasRes;
|
|
16
|
+
uniform float u_pixelSize;
|
|
17
|
+
uniform float u_radius;
|
|
18
|
+
uniform float u_darkThreshold;
|
|
19
|
+
void main() {
|
|
20
|
+
vec2 gridPos = v_uv * u_dataRes;
|
|
21
|
+
vec2 localUv = fract(gridPos);
|
|
22
|
+
vec2 cellCoords = (floor(gridPos) + 0.5) / u_dataRes;
|
|
23
|
+
vec4 color = texture(u_texture, cellCoords);
|
|
24
|
+
if (dot(color.rgb, vec3(1.0)) < u_darkThreshold) discard;
|
|
25
|
+
float halfSize = u_pixelSize * 0.5;
|
|
26
|
+
float visualRadius = sqrt(clamp(u_radius, 0.0, 1.0));
|
|
27
|
+
float r = visualRadius * halfSize;
|
|
28
|
+
vec2 q = abs(localUv - 0.5) - (halfSize - r);
|
|
29
|
+
float dist = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
|
|
30
|
+
float unitsPerPixel = (u_dataRes.y / u_canvasRes.y);
|
|
31
|
+
float delta = unitsPerPixel * 1.5;
|
|
32
|
+
float effectRes = (1.0 - u_pixelSize) + u_radius;
|
|
33
|
+
float effectStrength = smoothstep(0.0, 0.02, effectRes);
|
|
34
|
+
float edgeOffset = mix(0.0, -delta, effectStrength);
|
|
35
|
+
float mask = 1.0 - smoothstep(edgeOffset, edgeOffset + delta * 2.0, dist);
|
|
36
|
+
float vignette = smoothstep(0.7, 0.3, length(localUv - 0.5));
|
|
37
|
+
vec3 finalColor = color.rgb * (1.0 - (0.15 * effectStrength * (1.0 - vignette)));
|
|
38
|
+
if (mask < 0.001) discard;
|
|
39
|
+
outColor = vec4(finalColor, color.a * mask);
|
|
40
|
+
}
|
|
41
|
+
`);if(y.instance)return y.instance;y.instance=this}init(){if(this.gl||typeof window>"u")return;const e=document.createElement("canvas").getContext("webgl2",{antialias:!0,alpha:!0,preserveDrawingBuffer:!0});if(!e)throw new Error("WebGL 2.0 not supported");this.gl=e,this.program=this.createProgram(this.vs,this.fs);const r=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,r),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),e.STATIC_DRAW);const n=e.getAttribLocation(this.program,"position");e.enableVertexAttribArray(n),e.vertexAttribPointer(n,2,e.FLOAT,!1,0,0),this.texture=e.createTexture(),e.bindTexture(e.TEXTURE_2D,this.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}render(t,e,r,n){const{pixelSize:a=.85,radius:o=.5,darkThreshold:l=.04}=n,u=this.gl;u.viewport(0,0,u.canvas.width,u.canvas.height),u.useProgram(this.program),u.bindTexture(u.TEXTURE_2D,this.texture),u.texImage2D(u.TEXTURE_2D,0,u.RGBA8,e,r,0,u.RGBA,u.UNSIGNED_BYTE,t),u.uniform2f(u.getUniformLocation(this.program,"u_dataRes"),e,r),u.uniform2f(u.getUniformLocation(this.program,"u_canvasRes"),u.canvas.width,u.canvas.height),u.uniform1f(u.getUniformLocation(this.program,"u_pixelSize"),a),u.uniform1f(u.getUniformLocation(this.program,"u_radius"),o),u.uniform1f(u.getUniformLocation(this.program,"u_darkThreshold"),l),u.clearColor(0,0,0,0),u.clear(u.COLOR_BUFFER_BIT),u.enable(u.BLEND),u.blendFunc(u.SRC_ALPHA,u.ONE_MINUS_SRC_ALPHA),u.drawArrays(u.TRIANGLES,0,6)}renderFrame(t,e,r,n,a={}){if(this.init(),typeof window>"u"||!this.gl)return;(this.gl.canvas.width!==t.width||this.gl.canvas.height!==t.height)&&(this.gl.canvas.width=t.width,this.gl.canvas.height=t.height),this.render(e,r,n,a);const o=t.getContext("2d");o&&(o.clearRect(0,0,t.width,t.height),o.drawImage(this.gl.canvas,0,0))}createProgram(t,e){const r=this.gl,n=(o,l)=>{const u=r.createShader(o);if(r.shaderSource(u,l),r.compileShader(u),!r.getShaderParameter(u,r.COMPILE_STATUS))throw new Error(r.getShaderInfoLog(u)||"Shader Error");return u},a=r.createProgram();return r.attachShader(a,n(r.VERTEX_SHADER,t)),r.attachShader(a,n(r.FRAGMENT_SHADER,e)),r.linkProgram(a),a}};h(y,"instance",null);let k=y;const fe=new k;exports.AuthStatus=c.AuthStatus;exports.ConnectionStatus=c.ConnectionStatus;exports.DataStatus=c.DataStatus;exports.StateStreamError=c.StateStreamError;exports.StateStreamErrorCode=c.StateStreamErrorCode;exports.StreamLifecycle=c.StreamLifecycle;exports.WorkerStatus=c.WorkerStatus;exports.BusyBar=R;exports.DeviceScreen=S;exports.Input=he;exports.LEDRenderer=fe;exports.LocalStateStream=le;exports.RemoteStateStream=de;exports.ScreenStream=ue;
|