@lemoncloud/chatic-apps-sdk 0.1.0 → 0.3.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.
@@ -1 +1 @@
1
- var ChaticAppsSDK=(function(y){"use strict";class p extends Error{code;constructor(t,r){super(r),this.name="ChaticAppsError",this.code=t}}const O="2.19.0",M=1e4,x=2e3;let W=0;const U=()=>`cas-${Date.now().toString(36)}-${(++W).toString(36)}`,R=()=>typeof document<"u"&&document.visibilityState==="hidden",G=(e,t=M)=>{const r=new Map,o=new Map;let c=!1;const h=(i,s)=>{s.remaining===null||R()||(s.startedAt=Date.now(),s.timer=setTimeout(()=>{r.delete(i),s.reject(new p("TIMEOUT","The app did not answer in time."))},s.remaining))},d=()=>{for(const[i,s]of r)s.remaining!==null&&(R()?(s.timer&&clearTimeout(s.timer),s.timer=null,s.remaining=Math.max(0,s.remaining-(Date.now()-s.startedAt))):s.timer||(s.remaining=Math.max(s.remaining,x),h(i,s)))};typeof document<"u"&&document.addEventListener("visibilitychange",d);const f=e.listen(i=>{let s;try{s=JSON.parse(i)}catch{return}if(!s||typeof s!="object"||typeof s.type!="string")return;const l=typeof s.refId=="string"?r.get(s.refId):void 0;if(l&&typeof s.refId=="string"){if(r.delete(s.refId),l.timer&&clearTimeout(l.timer),s.success===!0)l.resolve(s.data);else{const g=typeof s.error?.code=="string"?s.error.code:"INTERNAL_ERROR",v=typeof s.error?.message=="string"?s.error.message:g;l.reject(new p(g,v))}return}o.get(s.type)?.forEach(g=>{try{g(s.data)}catch{}})});return{request:(i,s={},l={})=>new Promise((g,v)=>{if(c){v(new p("DISCONNECTED","The connection to the app was closed."));return}const w=U(),n=l.timeoutMs===void 0?t:l.timeoutMs,a={resolve:g,reject:v,remaining:n,startedAt:Date.now(),timer:null};r.set(w,a),h(w,a),e.send(JSON.stringify({type:i,data:s,refId:w,version:O}))}),onPush:(i,s)=>{let l=o.get(i);return l||o.set(i,l=new Set),l.add(s),()=>l?.delete(s)},close:()=>{if(!c){c=!0,f(),typeof document<"u"&&document.removeEventListener("visibilitychange",d);for(const i of r.values())i.timer&&clearTimeout(i.timer),i.reject(new p("DISCONNECTED","The connection to the app was closed."));r.clear(),o.clear()}}}},I=e=>{try{return JSON.stringify(e)??null}catch{return null}},L=e=>{const t=r=>Object.values(r??{}).every(o=>I(o)!==null)?e.set(r).then(()=>{}):Promise.reject(new p("INVALID","Values must be JSON; remove a key rather than storing undefined."));return{get:r=>e.get([r]).then(o=>o.entries[r]),getMany:r=>e.get(r).then(o=>o.entries),set:(r,o)=>t({[r]:o}),setMany:t,remove:r=>e.remove(typeof r=="string"?[r]:r).then(()=>{}),keys:()=>e.info().then(r=>r.keys),clear:()=>e.clear().then(()=>{}),usage:()=>e.info().then(({used:r,limit:o})=>({used:r,limit:o}))}},P=1024*1024,q=200,$=64*1024,T=e=>typeof e=="string"&&e.length>=1&&e.length<=q&&e!=="__proto__",K=e=>{const t=()=>e.keys().reduce((o,c)=>o+c.length+(e.read(c)?.length??0),0),r=()=>({used:t(),limit:P});return{get(o){if(!Array.isArray(o)||!o.every(T))return{ok:!1,code:"INVALID"};const c={};for(const h of o){const d=e.read(h);if(d!==void 0)try{c[h]=JSON.parse(d)}catch{}}return{ok:!0,value:{entries:c}}},set(o){if(!o||typeof o!="object"||Array.isArray(o))return{ok:!1,code:"INVALID"};const c=[];let h=t();for(const[d,f]of Object.entries(o)){const i=I(f);if(!T(d)||i===null)return{ok:!1,code:"INVALID"};const s=e.read(d);h+=i.length-(s===void 0?-d.length:s.length),c.push([d,i])}return h>P?{ok:!1,code:"QUOTA_EXCEEDED"}:(c.forEach(([d,f])=>e.write(d,f)),{ok:!0,value:r()})},remove(o){return!Array.isArray(o)||!o.every(T)?{ok:!1,code:"INVALID"}:(o.forEach(c=>e.delete(c)),{ok:!0,value:r()})},clear(){return e.keys().forEach(o=>e.delete(o)),{ok:!0,value:{}}},info(){return{ok:!0,value:{keys:e.keys(),...r()}}}}},b="chatic-apps.storage:",B=e=>({read:t=>e.getItem(b+t)??void 0,write:(t,r)=>e.setItem(b+t,r),delete:t=>e.removeItem(b+t),keys:()=>{const t=[];for(let r=0;r<e.length;r++){const o=e.key(r);o?.startsWith(b)&&t.push(o.slice(b.length))}return t}}),F=()=>{const e=t=>{let r;try{r=t(K(B(window.localStorage)))}catch(o){return o?.name==="QuotaExceededError"?Promise.reject(new p("QUOTA_EXCEEDED","The browser's own storage is full.")):Promise.reject(new p("NOT_SUPPORTED","This browser refuses local storage."))}return r.ok?Promise.resolve(r.value):Promise.reject(new p(r.code,`The storage refused the call: ${r.code}.`))};return L({get:t=>e(r=>r.get(t)),set:t=>(I({entries:t})?.length??0)>$?Promise.reject(new p("TOO_LARGE","One call carries at most 65,536 characters.")):e(r=>r.set(t)),remove:t=>e(r=>r.remove(t)),clear:()=>e(t=>t.clear()),info:()=>e(t=>t.info())})},k=()=>typeof window<"u"&&!!window.ReactNativeWebView,J=()=>({send:e=>window.ReactNativeWebView?.postMessage(e),listen:e=>{const t=r=>{const o=r.data;typeof o=="string"&&e(o)};return window.addEventListener("message",t),document.addEventListener("message",t),()=>{window.removeEventListener("message",t),document.removeEventListener("message",t)}}}),E={finish:"FinishSubWebView",title:"SetSubWebViewTitle",haptic:"TriggerHaptic",clipboard:"CopyToClipboard",share:"OpenShareSheet",openUrl:"OpenURL",userKey:"GetSubWebViewUserKey",back:"SetCanGoBack",closeGuard:"SetSubWebViewCloseGuard",errorReport:"ReportSubWebViewError",storage:"GetSubWebViewStorage"},C=1,Q=1e3,H=4e3,V=()=>typeof window<"u"&&window.ChaticSubWebView||null,X=()=>new Promise(e=>{if(typeof document>"u"||document.readyState==="complete"){e(V());return}window.addEventListener("load",()=>e(V()),{once:!0})}),z=e=>{let t,r;try{e instanceof Error?(t=e.message||e.name,r=typeof e.stack=="string"?e.stack:void 0):typeof e=="string"?t=e:t=`A non-Error value was thrown: ${Object.prototype.toString.call(e)}`}catch{t="An error that could not be read was thrown"}return{message:(t||"Unknown error").slice(0,Q),...r?{stack:r.slice(0,H)}:{}}},A=e=>new p("NOT_SUPPORTED",`${e} is not available here: an older app, or not granted.`),_=e=>Promise.reject(new p("NOT_IN_APP",`${e} needs the app; this page is in a browser.`)),D=(e={})=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new p("INVALID","link() takes an object of query params, such as { level: 3 }.");const t=new URLSearchParams;for(const[o,c]of Object.entries(e))t.append(o,String(c));const r=t.toString();return r?`?${r}`:""},N=e=>typeof location>"u"?`/${e}`:`${location.origin}/${e}`;let S=null;const Y=(e={})=>(S||(S=(k()?Z(J(),e):Promise.resolve(te())).catch(t=>{throw S=null,t})),S),Z=async(e,t={})=>{const r=G(e,t.timeoutMs);try{const o=await j(r,!0);return ee(r,o,t)}catch(o){throw r.close(),o}},j=async(e,t)=>{const r=await e.request("WebAppReady",{}),o=r.subWebView??(t?await X():null);if(o&&o.protocolVersion!==C)throw new p("UNSUPPORTED_PROTOCOL",`The app speaks protocol ${String(o.protocolVersion)}; this library speaks ${C}.`);return{supported:new Set(Array.isArray(r.supportedWebMessages)?r.supportedWebMessages:[]),context:o}},ee=(e,t,r)=>{let o=null,c=null;const h=new Set,d=[],f=n=>t.supported.has(E[n]),i=(n,a,u)=>f(n)?e.request(E[n],a,u===void 0?{}:{timeoutMs:u}):Promise.reject(A(n)),s=(n,a)=>f("storage")?e.request(n,a):Promise.reject(A("storage")),l=n=>h.forEach(a=>{try{a(n)}catch(u){w.reportError(u)}}),g=()=>{f("back")&&e.request(E.back,{canGoBack:!!o}).catch(()=>{}),f("closeGuard")&&e.request(E.closeGuard,{enabled:!!c}).catch(()=>{})},v=n=>{if(!n.persisted){g();return}j(e,!1).then(a=>{const u=t.context;t.supported=a.supported,a.context&&(t.context=a.context),g();const m=t.context;m&&(m.theme!==u?.theme||m.locale!==u?.locale)&&l(m)}).catch(()=>{})};typeof window<"u"&&(window.addEventListener("pageshow",v),d.push(()=>window.removeEventListener("pageshow",v))),d.push(e.onPush("OnBackPressed",()=>{try{o?.()}catch(n){w.reportError(n)}})),d.push(e.onPush("OnSubWebViewCloseRequested",n=>{const a=c;if(!a)return;const u=n?.trigger??"control";Promise.resolve().then(()=>a(u)).then(m=>m?w.finish():void 0).catch(m=>w.reportError(m))})),d.push(e.onPush("OnSubWebViewContextChanged",n=>{t.context&&(t.context={...t.context,...n},l(t.context))}));const w={inApp:!0,get context(){return t.context},supports:f,finish:n=>i("finish",n===void 0?{}:{result:n}).then(()=>{}),setTitle:n=>i("title",{title:n}).then(()=>{}),haptic:n=>{f("haptic")&&e.request(E.haptic,{kind:n}).catch(()=>{})},copy:n=>i("clipboard",{text:n}).then(()=>{}),openUrl:n=>i("openUrl",{url:n}).then(()=>{}),share:n=>i("share",n,null).then(a=>a?.action==="dismissedAction"?"dismissed":"shared"),getUserKey:()=>i("userKey").then(n=>n.key),reportError:n=>f("errorReport")?e.request(E.errorReport,z(n)).then(a=>!!a?.recorded).catch(()=>!1):Promise.resolve(!1),storage:L({get:n=>s("GetSubWebViewStorage",{keys:n}),set:n=>s("SetSubWebViewStorage",{entries:n}),remove:n=>s("RemoveSubWebViewStorage",{keys:n}),clear:()=>s("ClearSubWebViewStorage",{}),info:()=>s("GetSubWebViewStorageInfo",{})}),onBack:n=>{o=n,g()},onCloseRequest:n=>{c=n,g()},onContextChange:n=>(h.add(n),()=>h.delete(n)),link:n=>{const a=D(n),u=t.context?.appLink;return u?`${u}${a}`:N(a)},disconnect:()=>{d.forEach(n=>n()),e.close(),S=null}};if(r.reportErrors!==!1&&typeof window<"u"){const n=u=>{w.reportError(u.error??u.message)},a=u=>{w.reportError(u.reason)};window.addEventListener("error",n),window.addEventListener("unhandledrejection",a),d.push(()=>{window.removeEventListener("error",n),window.removeEventListener("unhandledrejection",a)})}return w},te=()=>{const e=t=>typeof navigator<"u"&&navigator.clipboard?navigator.clipboard.writeText(t):Promise.reject(A("The clipboard"));return{inApp:!1,context:null,supports:()=>!1,finish:()=>_("Finishing the view"),setTitle:async t=>{typeof document<"u"&&(document.title=t)},haptic:()=>{typeof navigator<"u"&&navigator.vibrate?.(10)},copy:e,openUrl:async t=>{typeof window<"u"&&window.open(t,"_blank","noopener,noreferrer")},share:async t=>{const r=[t.message,t.url].filter(Boolean).join(" ");if(!r)throw new p("INVALID","Share a message or a url.");if(typeof navigator<"u"&&navigator.share)try{return await navigator.share(t),"shared"}catch(o){if(o?.name==="AbortError")return"dismissed"}return await e(r),"copied"},getUserKey:()=>_("A user key"),reportError:async t=>(console.error(t),!1),storage:F(),onBack:()=>{},onCloseRequest:()=>{},onContextChange:()=>()=>{},link:t=>N(D(t)),disconnect:()=>{S=null}}};return y.ChaticAppsError=p,y.SDK_BRIDGE_VERSION=O,y.connect=Y,y.isInApp=k,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"}),y})({});
1
+ var ChaticAppsSDK=(function(A){"use strict";class u extends Error{code;details;constructor(t,r,n){super(r),this.name="ChaticAppsError",this.code=t,n!==void 0&&(this.details=n)}}const V="2.33.0",te=1e4,re=2e3;let ne=0;const oe=()=>`cas-${Date.now().toString(36)}-${(++ne).toString(36)}`,U=()=>typeof document<"u"&&document.visibilityState==="hidden",se=(e,t=te)=>{const r=new Map,n=new Map;let p=!1;const w=(c,s)=>{s.remaining===null||U()||(s.startedAt=Date.now(),s.timer=setTimeout(()=>{r.delete(c),s.reject(new u("TIMEOUT","The app did not answer in time."))},s.remaining))},d=()=>{for(const[c,s]of r)s.remaining!==null&&(U()?(s.timer&&clearTimeout(s.timer),s.timer=null,s.remaining=Math.max(0,s.remaining-(Date.now()-s.startedAt))):s.timer||(s.remaining=Math.max(s.remaining,re),w(c,s)))};typeof document<"u"&&document.addEventListener("visibilitychange",d);const y=e.listen(c=>{let s;try{s=JSON.parse(c)}catch{return}if(!s||typeof s!="object"||typeof s.type!="string")return;const f=typeof s.refId=="string"?r.get(s.refId):void 0;if(f&&typeof s.refId=="string"){if(r.delete(s.refId),f.timer&&clearTimeout(f.timer),s.success===!0)f.resolve(s.data);else{const b=typeof s.error?.code=="string"?s.error.code:"INTERNAL_ERROR",v=typeof s.error?.message=="string"?s.error.message:b;f.reject(new u(b,v,s.error?.details))}return}n.get(s.type)?.forEach(b=>{try{b(s.data)}catch{}})});return{request:(c,s={},f={})=>new Promise((b,v)=>{if(p){v(new u("DISCONNECTED","The connection to the app was closed."));return}const T=oe(),E=f.timeoutMs===void 0?t:f.timeoutMs,o={resolve:b,reject:v,remaining:E,startedAt:Date.now(),timer:null};r.set(T,o),w(T,o),e.send(JSON.stringify({type:c,data:s,refId:T,version:V}))}),onPush:(c,s)=>{let f=n.get(c);return f||n.set(c,f=new Set),f.add(s),()=>f?.delete(s)},close:()=>{if(!p){p=!0,y(),typeof document<"u"&&document.removeEventListener("visibilitychange",d);for(const c of r.values())c.timer&&clearTimeout(c.timer),c.reject(new u("DISCONNECTED","The connection to the app was closed."));r.clear(),n.clear()}}}},j=[1],q=Object.freeze({$listener:!0}),$="data",ie=e=>typeof e=="object"&&e!==null&&e.$listener===!0,ae=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return null;const t=e.$ended;return t&&typeof t=="object"?t:null},ce=(e,t,r)=>{let n=null,p=null,w=null,d=null,y=!1,c=0;const s=new Map,f=new Set,b=new Set,v=i=>{try{i()}catch(a){r(a)}},T=()=>{y||(y=!0,b.forEach(i=>v(i)))},E=i=>{throw i instanceof u&&i.code==="CLOUD_CHANGED"&&T(),i},o=i=>{const a=[...s.values()];s.clear(),a.forEach(h=>v(()=>h.onEnd?.(i)))},l=e.onPush("OnRuntimeEvent",i=>{const{subscriptionId:a,event:h}=i??{},O=typeof a=="string"?s.get(a):void 0;if(!O||typeof a!="string")return;const S=ae(h);if(S){s.delete(a);const L=typeof S.code=="string"?S.code:"INTERNAL_ERROR",Ae=typeof S.message=="string"?S.message:L;L==="CLOUD_CHANGED"&&T(),v(()=>O.onEnd?.(new u(L,Ae)));return}v(()=>O.listener(...Array.isArray(h)?h:[h]))}),g=e.onPush("OnRuntimeSessionChanged",i=>{const{seq:a,session:h}=i??{};!w||typeof a!="number"||a<=w.seq||(w={...w,seq:a},d=h??null,f.forEach(O=>v(()=>O(d))))}),m=()=>{if(!t())return Promise.reject(new u("NOT_SUPPORTED","This app does not answer this page's cloud data requests."));if(!n){const i=new Promise((h,O)=>{p=O}),a=Promise.race([e.request("RuntimeHello",{contracts:[...j]},{timeoutMs:null}),i]).then(h=>(n===a&&(w=h,d=h.session??null),h)).catch(h=>(n===a&&(n=null),E(h)));n=a}return n},R=async(i,a)=>{if(!(await m()).allowed[i].includes(a))throw new u("RUNTIME_NOT_ALLOWED",`${a} is not one this page may ${i==="calls"?"call":"subscribe to"}.`)},N=async(i,...a)=>(await R("calls",i),(await e.request("RuntimeCall",{target:$,method:i,args:a}).catch(E)).value),Q=async(i,a,h,O)=>{await R("streams",i);const S=`cas-s${(++c).toString(36)}`;s.set(S,{listener:h,onEnd:O});try{await e.request("RuntimeSubscribe",{subscriptionId:S,target:$,topic:i,args:a.some(ie)?a:[...a,q]})}catch(L){s.delete(S),E(L)}return{stop:async()=>{s.delete(S)&&await e.request("RuntimeUnsubscribe",{subscriptionId:S}).catch(()=>{})}}},X=async()=>{await m();const i=d?.committedSiteId;if(!i)throw new u("NOT_SUPPORTED","A place profile needs the session permission, while the session is on a place.");return i},z=async()=>{await m();const i=d?.context.identity.userId;if(!i)throw new u("NOT_SUPPORTED","The user's own profile needs the session permission.");return i},Y=async i=>`${await X()}@${i}`,Z=async i=>N("profile.cacheRead",await Y(i)),ee=async(i,a,h)=>Q("profile.observeItem",[await Y(i)],a,h?.onEnd);return{connect:()=>m().then(({contract:i,allowed:a})=>({contract:i,allowed:a})),can:i=>!!w&&(w.allowed.calls.includes(i)||w.allowed.streams.includes(i)),call:N,subscribe:Q,sendMessage:(i,a)=>N("chat.sendChat",{channelId:i,content:a}),react:(i,a,h)=>N("chat.setReaction",{chatId:i,emoji:a,action:h?"on":"off"}),placeProfile:Z,placeProfiles:async()=>N("profile.cacheReadList",{sid:await X()}),observePlaceProfile:ee,myProfile:async()=>Z(await z()),observeMyProfile:async(i,a)=>ee(await z(),i,a),session:()=>d,onSessionChange:i=>(f.add(i),()=>f.delete(i)),onCloudChanged:i=>(b.add(i),()=>b.delete(i)),reset:()=>{p?.(new u("DISCONNECTED","The page was restored before the app answered. Connect again.")),p=null,n=null,w=null,d=null,o(new u("DISCONNECTED","The page was restored; its streams ended. Subscribe again."))},dispose:()=>{l(),g(),s.clear()}}},de=()=>{const e=()=>Promise.reject(new u("NOT_IN_APP","The app's data is read only in the app."));return{connect:e,can:()=>!1,call:e,subscribe:e,sendMessage:e,react:e,placeProfile:e,placeProfiles:e,observePlaceProfile:e,myProfile:e,observeMyProfile:e,session:()=>null,onSessionChange:()=>()=>{},onCloudChanged:()=>()=>{}}},D=e=>{try{return JSON.stringify(e)??null}catch{return null}},W=e=>{const t=r=>Object.values(r??{}).every(n=>D(n)!==null)?e.set(r).then(()=>{}):Promise.reject(new u("INVALID","Values must be JSON; remove a key rather than storing undefined."));return{get:r=>e.get([r]).then(n=>n.entries[r]),getMany:r=>e.get(r).then(n=>n.entries),set:(r,n)=>t({[r]:n}),setMany:t,remove:r=>e.remove(typeof r=="string"?[r]:r).then(()=>{}),keys:()=>e.info().then(r=>r.keys),clear:()=>e.clear().then(()=>{}),usage:()=>e.info().then(({used:r,limit:n})=>({used:r,limit:n}))}},x=1024*1024,le=200,ue=64*1024,_=e=>typeof e=="string"&&e.length>=1&&e.length<=le&&e!=="__proto__",pe=e=>{const t=()=>e.keys().reduce((n,p)=>n+p.length+(e.read(p)?.length??0),0),r=()=>({used:t(),limit:x});return{get(n){if(!Array.isArray(n)||!n.every(_))return{ok:!1,code:"INVALID"};const p={};for(const w of n){const d=e.read(w);if(d!==void 0)try{p[w]=JSON.parse(d)}catch{}}return{ok:!0,value:{entries:p}}},set(n){if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,code:"INVALID"};const p=[];let w=t();for(const[d,y]of Object.entries(n)){const c=D(y);if(!_(d)||c===null)return{ok:!1,code:"INVALID"};const s=e.read(d);w+=c.length-(s===void 0?-d.length:s.length),p.push([d,c])}return w>x?{ok:!1,code:"QUOTA_EXCEEDED"}:(p.forEach(([d,y])=>e.write(d,y)),{ok:!0,value:r()})},remove(n){return!Array.isArray(n)||!n.every(_)?{ok:!1,code:"INVALID"}:(n.forEach(p=>e.delete(p)),{ok:!0,value:r()})},clear(){return e.keys().forEach(n=>e.delete(n)),{ok:!0,value:{}}},info(){return{ok:!0,value:{keys:e.keys(),...r()}}}}},C="chatic-apps.storage:",fe=e=>({read:t=>e.getItem(C+t)??void 0,write:(t,r)=>e.setItem(C+t,r),delete:t=>e.removeItem(C+t),keys:()=>{const t=[];for(let r=0;r<e.length;r++){const n=e.key(r);n?.startsWith(C)&&t.push(n.slice(C.length))}return t}}),he=()=>{const e=t=>{let r;try{r=t(pe(fe(window.localStorage)))}catch(n){return n?.name==="QuotaExceededError"?Promise.reject(new u("QUOTA_EXCEEDED","The browser's own storage is full.")):Promise.reject(new u("NOT_SUPPORTED","This browser refuses local storage."))}return r.ok?Promise.resolve(r.value):Promise.reject(new u(r.code,`The storage refused the call: ${r.code}.`))};return W({get:t=>e(r=>r.get(t)),set:t=>(D({entries:t})?.length??0)>ue?Promise.reject(new u("TOO_LARGE","One call carries at most 65,536 characters.")):e(r=>r.set(t)),remove:t=>e(r=>r.remove(t)),clear:()=>e(t=>t.clear()),info:()=>e(t=>t.info())})},G=()=>typeof window<"u"&&!!window.ReactNativeWebView,we=()=>({send:e=>window.ReactNativeWebView?.postMessage(e),listen:e=>{const t=r=>{const n=r.data;typeof n=="string"&&e(n)};return window.addEventListener("message",t),document.addEventListener("message",t),()=>{window.removeEventListener("message",t),document.removeEventListener("message",t)}}}),I={finish:"FinishSubWebView",title:"SetSubWebViewTitle",haptic:"TriggerHaptic",clipboard:"CopyToClipboard",share:"OpenShareSheet",openUrl:"OpenURL",userKey:"GetSubWebViewUserKey",back:"SetCanGoBack",closeGuard:"SetSubWebViewCloseGuard",errorReport:"ReportSubWebViewError",storage:"GetSubWebViewStorage",permissions:"RequestSubWebViewPermission",data:"RuntimeHello"},K=1,ge=1e3,me=4e3,B=()=>typeof window<"u"&&window.ChaticSubWebView||null,ye=()=>new Promise(e=>{if(typeof document>"u"||document.readyState==="complete"){e(B());return}window.addEventListener("load",()=>e(B()),{once:!0})}),ve=e=>{let t,r;try{e instanceof Error?(t=e.message||e.name,r=typeof e.stack=="string"?e.stack:void 0):typeof e=="string"?t=e:t=`A non-Error value was thrown: ${Object.prototype.toString.call(e)}`}catch{t="An error that could not be read was thrown"}return{message:(t||"Unknown error").slice(0,ge),...r?{stack:r.slice(0,me)}:{}}},k=e=>new u("NOT_SUPPORTED",`${e} is not available here: an older app, or not granted.`),M=e=>Promise.reject(new u("NOT_IN_APP",`${e} needs the app; this page is in a browser.`)),H=(e={})=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new u("INVALID","link() takes an object of query params, such as { level: 3 }.");const t=new URLSearchParams;for(const[n,p]of Object.entries(e))t.append(n,String(p));const r=t.toString();return r?`?${r}`:""},F=e=>typeof location>"u"?`/${e}`:`${location.origin}/${e}`;let P=null;const Ee=(e={})=>(P||(P=(G()?be(we(),e):Promise.resolve(Oe())).catch(t=>{throw P=null,t})),P),be=async(e,t={})=>{const r=se(e,t.timeoutMs);try{const n=await J(r,!0);return Se(r,n,t)}catch(n){throw r.close(),n}},J=async(e,t)=>{const r=await e.request("WebAppReady",{}),n=r.subWebView??(t?await ye():null);if(n&&n.protocolVersion!==K)throw new u("UNSUPPORTED_PROTOCOL",`The app speaks protocol ${String(n.protocolVersion)}; this library speaks ${K}.`);return{supported:new Set(Array.isArray(r.supportedWebMessages)?r.supportedWebMessages:[]),context:n}},Se=(e,t,r)=>{let n=null,p=null;const w=new Set,d=[],y=o=>t.supported.has(I[o]),c=(o,l,g,m)=>{const R=m??I[o];return t.supported.has(R)?e.request(R,l,g===void 0?{}:{timeoutMs:g}):Promise.reject(k(o))},s=ce(e,()=>y("data"),o=>{E.reportError(o)});d.push(()=>s.dispose());const f=(o,l)=>y("storage")?e.request(o,l):Promise.reject(k("storage")),b=o=>w.forEach(l=>{try{l(o)}catch(g){E.reportError(g)}}),v=()=>{y("back")&&e.request(I.back,{canGoBack:!!n}).catch(()=>{}),y("closeGuard")&&e.request(I.closeGuard,{enabled:!!p}).catch(()=>{})},T=o=>{if(!o.persisted){v();return}J(e,!1).then(l=>{const g=t.context;t.supported=l.supported,l.context&&(t.context=l.context),v(),s.reset();const m=t.context,R=m&&(m.theme!==g?.theme||m.locale!==g?.locale||JSON.stringify(m.safeArea)!==JSON.stringify(g?.safeArea));m&&R&&b(m)}).catch(()=>{})};typeof window<"u"&&(window.addEventListener("pageshow",T),d.push(()=>window.removeEventListener("pageshow",T))),d.push(e.onPush("OnBackPressed",()=>{try{n?.()}catch(o){E.reportError(o)}})),d.push(e.onPush("OnSubWebViewCloseRequested",o=>{const l=p;if(!l)return;const g=o?.trigger??"control";Promise.resolve().then(()=>l(g)).then(m=>m?E.finish():void 0).catch(m=>E.reportError(m))})),d.push(e.onPush("OnSubWebViewContextChanged",o=>{t.context&&(t.context={...t.context,...o},b(t.context))}));const E={inApp:!0,get context(){return t.context},supports:y,finish:o=>c("finish",o===void 0?{}:{result:o}).then(()=>{}),setTitle:o=>c("title",{title:o}).then(()=>{}),haptic:o=>{y("haptic")&&e.request(I.haptic,{kind:o}).catch(()=>{})},copy:o=>c("clipboard",{text:o}).then(()=>{}),openUrl:o=>c("openUrl",{url:o}).then(()=>{}),share:o=>c("share",o,null).then(l=>l?.action==="dismissedAction"?"dismissed":"shared"),getUserKey:()=>c("userKey").then(o=>o.key),permissions:{query:o=>c("permissions",{kind:o},void 0,"GetSubWebViewPermission").then(l=>l.state),request:o=>c("permissions",{kind:o},null).then(l=>l.state)},openSettings:()=>c("permissions",{},void 0,"OpenSettings").then(()=>{}),reportError:o=>y("errorReport")?e.request(I.errorReport,ve(o)).then(l=>!!l?.recorded).catch(()=>!1):Promise.resolve(!1),data:s,storage:W({get:o=>f("GetSubWebViewStorage",{keys:o}),set:o=>f("SetSubWebViewStorage",{entries:o}),remove:o=>f("RemoveSubWebViewStorage",{keys:o}),clear:()=>f("ClearSubWebViewStorage",{}),info:()=>f("GetSubWebViewStorageInfo",{})}),onBack:o=>{n=o,v()},onCloseRequest:o=>{p=o,v()},onContextChange:o=>(w.add(o),()=>w.delete(o)),link:o=>{const l=H(o),g=t.context?.appLink;return g?`${g}${l}`:F(l)},disconnect:()=>{d.forEach(o=>o()),e.close(),P=null}};if(r.reportErrors!==!1&&typeof window<"u"){const o=g=>{E.reportError(g.error??g.message)},l=g=>{E.reportError(g.reason)};window.addEventListener("error",o),window.addEventListener("unhandledrejection",l),d.push(()=>{window.removeEventListener("error",o),window.removeEventListener("unhandledrejection",l)})}return E},Te=()=>{const e=async t=>{try{const r=await navigator.permissions.query({name:t});return r.state==="granted"?"granted":r.state==="denied"?"blocked":"prompt"}catch{return"prompt"}};return{query:e,request:async t=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new u("NOT_SUPPORTED",`This browser cannot capture the ${t}.`);try{return(await navigator.mediaDevices.getUserMedia(t==="camera"?{video:!0}:{audio:!0})).getTracks().forEach(n=>n.stop()),"granted"}catch(r){const n=r?.name;if(n==="NotFoundError"||n==="OverconstrainedError")throw new u("UNAVAILABLE",`This device has no ${t}.`);if(n==="NotReadableError"||n==="SecurityError"||n==="TypeError"||n==="AbortError")throw new u("INTERNAL_ERROR",`The ${t} could not be used: ${n}.`);return await e(t)==="blocked"?"blocked":"prompt"}}}},Oe=()=>{const e=t=>typeof navigator<"u"&&navigator.clipboard?navigator.clipboard.writeText(t):Promise.reject(k("The clipboard"));return{inApp:!1,context:null,supports:()=>!1,finish:()=>M("Finishing the view"),setTitle:async t=>{typeof document<"u"&&(document.title=t)},haptic:()=>{typeof navigator<"u"&&navigator.vibrate?.(10)},copy:e,openUrl:async t=>{typeof window<"u"&&window.open(t,"_blank","noopener,noreferrer")},share:async t=>{const r=[t.message,t.url].filter(Boolean).join(" ");if(!r)throw new u("INVALID","Share a message or a url.");if(typeof navigator<"u"&&navigator.share)try{return await navigator.share(t),"shared"}catch(n){if(n?.name==="AbortError")return"dismissed"}return await e(r),"copied"},getUserKey:()=>M("A user key"),permissions:Te(),data:de(),openSettings:()=>M("Opening the settings"),reportError:async t=>(console.error(t),!1),storage:he(),onBack:()=>{},onCloseRequest:()=>{},onContextChange:()=>()=>{},link:t=>F(H(t)),disconnect:()=>{P=null}}};return A.ChaticAppsError=u,A.LISTENER=q,A.SDK_BRIDGE_VERSION=V,A.SDK_DATA_CONTRACTS=j,A.connect=Ee,A.isInApp=G,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"}),A})({});
package/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./storage-yeS4HWKZ.cjs"),R="2.19.0",P=1e4,V=2e3;let x=0;const W=()=>`cas-${Date.now().toString(36)}-${(++x).toString(36)}`,S=()=>typeof document<"u"&&document.visibilityState==="hidden",M=(t,r=P)=>{const n=new Map,i=new Map;let f=!1;const v=(a,o)=>{o.remaining===null||S()||(o.startedAt=Date.now(),o.timer=setTimeout(()=>{n.delete(a),o.reject(new p.ChaticAppsError("TIMEOUT","The app did not answer in time."))},o.remaining))},h=()=>{for(const[a,o]of n)o.remaining!==null&&(S()?(o.timer&&clearTimeout(o.timer),o.timer=null,o.remaining=Math.max(0,o.remaining-(Date.now()-o.startedAt))):o.timer||(o.remaining=Math.max(o.remaining,V),v(a,o)))};typeof document<"u"&&document.addEventListener("visibilitychange",h);const w=t.listen(a=>{let o;try{o=JSON.parse(a)}catch{return}if(!o||typeof o!="object"||typeof o.type!="string")return;const d=typeof o.refId=="string"?n.get(o.refId):void 0;if(d&&typeof o.refId=="string"){if(n.delete(o.refId),d.timer&&clearTimeout(d.timer),o.success===!0)d.resolve(o.data);else{const u=typeof o.error?.code=="string"?o.error.code:"INTERNAL_ERROR",m=typeof o.error?.message=="string"?o.error.message:u;d.reject(new p.ChaticAppsError(u,m))}return}i.get(o.type)?.forEach(u=>{try{u(o.data)}catch{}})});return{request:(a,o={},d={})=>new Promise((u,m)=>{if(f){m(new p.ChaticAppsError("DISCONNECTED","The connection to the app was closed."));return}const l=W(),e=d.timeoutMs===void 0?r:d.timeoutMs,s={resolve:u,reject:m,remaining:e,startedAt:Date.now(),timer:null};n.set(l,s),v(l,s),t.send(JSON.stringify({type:a,data:o,refId:l,version:R}))}),onPush:(a,o)=>{let d=i.get(a);return d||i.set(a,d=new Set),d.add(o),()=>d?.delete(o)},close:()=>{if(!f){f=!0,w(),typeof document<"u"&&document.removeEventListener("visibilitychange",h);for(const a of n.values())a.timer&&clearTimeout(a.timer),a.reject(new p.ChaticAppsError("DISCONNECTED","The connection to the app was closed."));n.clear(),i.clear()}}}},O=()=>typeof window<"u"&&!!window.ReactNativeWebView,N=()=>({send:t=>window.ReactNativeWebView?.postMessage(t),listen:t=>{const r=n=>{const i=n.data;typeof i=="string"&&t(i)};return window.addEventListener("message",r),document.addEventListener("message",r),()=>{window.removeEventListener("message",r),document.removeEventListener("message",r)}}}),b={finish:"FinishSubWebView",title:"SetSubWebViewTitle",haptic:"TriggerHaptic",clipboard:"CopyToClipboard",share:"OpenShareSheet",openUrl:"OpenURL",userKey:"GetSubWebViewUserKey",back:"SetCanGoBack",closeGuard:"SetSubWebViewCloseGuard",errorReport:"ReportSubWebViewError",storage:"GetSubWebViewStorage"},A=1,_=1e3,U=4e3,C=()=>typeof window<"u"&&window.ChaticSubWebView||null,D=()=>new Promise(t=>{if(typeof document>"u"||document.readyState==="complete"){t(C());return}window.addEventListener("load",()=>t(C()),{once:!0})}),j=t=>{let r,n;try{t instanceof Error?(r=t.message||t.name,n=typeof t.stack=="string"?t.stack:void 0):typeof t=="string"?r=t:r=`A non-Error value was thrown: ${Object.prototype.toString.call(t)}`}catch{r="An error that could not be read was thrown"}return{message:(r||"Unknown error").slice(0,_),...n?{stack:n.slice(0,U)}:{}}},E=t=>new p.ChaticAppsError("NOT_SUPPORTED",`${t} is not available here: an older app, or not granted.`),T=t=>Promise.reject(new p.ChaticAppsError("NOT_IN_APP",`${t} needs the app; this page is in a browser.`)),I=(t={})=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new p.ChaticAppsError("INVALID","link() takes an object of query params, such as { level: 3 }.");const r=new URLSearchParams;for(const[i,f]of Object.entries(t))r.append(i,String(f));const n=r.toString();return n?`?${n}`:""},k=t=>typeof location>"u"?`/${t}`:`${location.origin}/${t}`;let y=null;const q=(t={})=>(y||(y=(O()?G(N(),t):Promise.resolve(B())).catch(r=>{throw y=null,r})),y),G=async(t,r={})=>{const n=M(t,r.timeoutMs);try{const i=await L(n,!0);return $(n,i,r)}catch(i){throw n.close(),i}},L=async(t,r)=>{const n=await t.request("WebAppReady",{}),i=n.subWebView??(r?await D():null);if(i&&i.protocolVersion!==A)throw new p.ChaticAppsError("UNSUPPORTED_PROTOCOL",`The app speaks protocol ${String(i.protocolVersion)}; this library speaks ${A}.`);return{supported:new Set(Array.isArray(n.supportedWebMessages)?n.supportedWebMessages:[]),context:i}},$=(t,r,n)=>{let i=null,f=null;const v=new Set,h=[],w=e=>r.supported.has(b[e]),a=(e,s,c)=>w(e)?t.request(b[e],s,c===void 0?{}:{timeoutMs:c}):Promise.reject(E(e)),o=(e,s)=>w("storage")?t.request(e,s):Promise.reject(E("storage")),d=e=>v.forEach(s=>{try{s(e)}catch(c){l.reportError(c)}}),u=()=>{w("back")&&t.request(b.back,{canGoBack:!!i}).catch(()=>{}),w("closeGuard")&&t.request(b.closeGuard,{enabled:!!f}).catch(()=>{})},m=e=>{if(!e.persisted){u();return}L(t,!1).then(s=>{const c=r.context;r.supported=s.supported,s.context&&(r.context=s.context),u();const g=r.context;g&&(g.theme!==c?.theme||g.locale!==c?.locale)&&d(g)}).catch(()=>{})};typeof window<"u"&&(window.addEventListener("pageshow",m),h.push(()=>window.removeEventListener("pageshow",m))),h.push(t.onPush("OnBackPressed",()=>{try{i?.()}catch(e){l.reportError(e)}})),h.push(t.onPush("OnSubWebViewCloseRequested",e=>{const s=f;if(!s)return;const c=e?.trigger??"control";Promise.resolve().then(()=>s(c)).then(g=>g?l.finish():void 0).catch(g=>l.reportError(g))})),h.push(t.onPush("OnSubWebViewContextChanged",e=>{r.context&&(r.context={...r.context,...e},d(r.context))}));const l={inApp:!0,get context(){return r.context},supports:w,finish:e=>a("finish",e===void 0?{}:{result:e}).then(()=>{}),setTitle:e=>a("title",{title:e}).then(()=>{}),haptic:e=>{w("haptic")&&t.request(b.haptic,{kind:e}).catch(()=>{})},copy:e=>a("clipboard",{text:e}).then(()=>{}),openUrl:e=>a("openUrl",{url:e}).then(()=>{}),share:e=>a("share",e,null).then(s=>s?.action==="dismissedAction"?"dismissed":"shared"),getUserKey:()=>a("userKey").then(e=>e.key),reportError:e=>w("errorReport")?t.request(b.errorReport,j(e)).then(s=>!!s?.recorded).catch(()=>!1):Promise.resolve(!1),storage:p.storageOver({get:e=>o("GetSubWebViewStorage",{keys:e}),set:e=>o("SetSubWebViewStorage",{entries:e}),remove:e=>o("RemoveSubWebViewStorage",{keys:e}),clear:()=>o("ClearSubWebViewStorage",{}),info:()=>o("GetSubWebViewStorageInfo",{})}),onBack:e=>{i=e,u()},onCloseRequest:e=>{f=e,u()},onContextChange:e=>(v.add(e),()=>v.delete(e)),link:e=>{const s=I(e),c=r.context?.appLink;return c?`${c}${s}`:k(s)},disconnect:()=>{h.forEach(e=>e()),t.close(),y=null}};if(n.reportErrors!==!1&&typeof window<"u"){const e=c=>{l.reportError(c.error??c.message)},s=c=>{l.reportError(c.reason)};window.addEventListener("error",e),window.addEventListener("unhandledrejection",s),h.push(()=>{window.removeEventListener("error",e),window.removeEventListener("unhandledrejection",s)})}return l},B=()=>{const t=r=>typeof navigator<"u"&&navigator.clipboard?navigator.clipboard.writeText(r):Promise.reject(E("The clipboard"));return{inApp:!1,context:null,supports:()=>!1,finish:()=>T("Finishing the view"),setTitle:async r=>{typeof document<"u"&&(document.title=r)},haptic:()=>{typeof navigator<"u"&&navigator.vibrate?.(10)},copy:t,openUrl:async r=>{typeof window<"u"&&window.open(r,"_blank","noopener,noreferrer")},share:async r=>{const n=[r.message,r.url].filter(Boolean).join(" ");if(!n)throw new p.ChaticAppsError("INVALID","Share a message or a url.");if(typeof navigator<"u"&&navigator.share)try{return await navigator.share(r),"shared"}catch(i){if(i?.name==="AbortError")return"dismissed"}return await t(n),"copied"},getUserKey:()=>T("A user key"),reportError:async r=>(console.error(r),!1),storage:p.browserStorage(),onBack:()=>{},onCloseRequest:()=>{},onContextChange:()=>()=>{},link:r=>k(I(r)),disconnect:()=>{y=null}}};exports.ChaticAppsError=p.ChaticAppsError;exports.SDK_BRIDGE_VERSION=R;exports.connect=q;exports.isInApp=O;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("./storage-C42PwRjA.cjs"),j=[1],G=Object.freeze({$listener:!0}),W="data",J=e=>typeof e=="object"&&e!==null&&e.$listener===!0,z=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return null;const t=e.$ended;return t&&typeof t=="object"?t:null},Q=(e,t,a)=>{let n=null,m=null,h=null,u=null,y=!1,g=0;const f=new Map,v=new Set,C=new Set,E=o=>{try{o()}catch(s){a(s)}},O=()=>{y||(y=!0,C.forEach(o=>E(o)))},w=o=>{throw o instanceof d.ChaticAppsError&&o.code==="CLOUD_CHANGED"&&O(),o},r=o=>{const s=[...f.values()];f.clear(),s.forEach(c=>E(()=>c.onEnd?.(o)))},i=e.onPush("OnRuntimeEvent",o=>{const{subscriptionId:s,event:c}=o??{},S=typeof s=="string"?f.get(s):void 0;if(!S||typeof s!="string")return;const b=z(c);if(b){f.delete(s);const N=typeof b.code=="string"?b.code:"INTERNAL_ERROR",F=typeof b.message=="string"?b.message:N;N==="CLOUD_CHANGED"&&O(),E(()=>S.onEnd?.(new d.ChaticAppsError(N,F)));return}E(()=>S.listener(...Array.isArray(c)?c:[c]))}),l=e.onPush("OnRuntimeSessionChanged",o=>{const{seq:s,session:c}=o??{};!h||typeof s!="number"||s<=h.seq||(h={...h,seq:s},u=c??null,v.forEach(S=>E(()=>S(u))))}),p=()=>{if(!t())return Promise.reject(new d.ChaticAppsError("NOT_SUPPORTED","This app does not answer this page's cloud data requests."));if(!n){const o=new Promise((c,S)=>{m=S}),s=Promise.race([e.request("RuntimeHello",{contracts:[...j]},{timeoutMs:null}),o]).then(c=>(n===s&&(h=c,u=c.session??null),c)).catch(c=>(n===s&&(n=null),w(c)));n=s}return n},A=async(o,s)=>{if(!(await p()).allowed[o].includes(s))throw new d.ChaticAppsError("RUNTIME_NOT_ALLOWED",`${s} is not one this page may ${o==="calls"?"call":"subscribe to"}.`)},P=async(o,...s)=>(await A("calls",o),(await e.request("RuntimeCall",{target:W,method:o,args:s}).catch(w)).value),_=async(o,s,c,S)=>{await A("streams",o);const b=`cas-s${(++g).toString(36)}`;f.set(b,{listener:c,onEnd:S});try{await e.request("RuntimeSubscribe",{subscriptionId:b,target:W,topic:o,args:s.some(J)?s:[...s,G]})}catch(N){f.delete(b),w(N)}return{stop:async()=>{f.delete(b)&&await e.request("RuntimeUnsubscribe",{subscriptionId:b}).catch(()=>{})}}},q=async()=>{await p();const o=u?.committedSiteId;if(!o)throw new d.ChaticAppsError("NOT_SUPPORTED","A place profile needs the session permission, while the session is on a place.");return o},k=async()=>{await p();const o=u?.context.identity.userId;if(!o)throw new d.ChaticAppsError("NOT_SUPPORTED","The user's own profile needs the session permission.");return o},D=async o=>`${await q()}@${o}`,V=async o=>P("profile.cacheRead",await D(o)),U=async(o,s,c)=>_("profile.observeItem",[await D(o)],s,c?.onEnd);return{connect:()=>p().then(({contract:o,allowed:s})=>({contract:o,allowed:s})),can:o=>!!h&&(h.allowed.calls.includes(o)||h.allowed.streams.includes(o)),call:P,subscribe:_,sendMessage:(o,s)=>P("chat.sendChat",{channelId:o,content:s}),react:(o,s,c)=>P("chat.setReaction",{chatId:o,emoji:s,action:c?"on":"off"}),placeProfile:V,placeProfiles:async()=>P("profile.cacheReadList",{sid:await q()}),observePlaceProfile:U,myProfile:async()=>V(await k()),observeMyProfile:async(o,s)=>U(await k(),o,s),session:()=>u,onSessionChange:o=>(v.add(o),()=>v.delete(o)),onCloudChanged:o=>(C.add(o),()=>C.delete(o)),reset:()=>{m?.(new d.ChaticAppsError("DISCONNECTED","The page was restored before the app answered. Connect again.")),m=null,n=null,h=null,u=null,r(new d.ChaticAppsError("DISCONNECTED","The page was restored; its streams ended. Subscribe again."))},dispose:()=>{i(),l(),f.clear()}}},X=()=>{const e=()=>Promise.reject(new d.ChaticAppsError("NOT_IN_APP","The app's data is read only in the app."));return{connect:e,can:()=>!1,call:e,subscribe:e,sendMessage:e,react:e,placeProfile:e,placeProfiles:e,observePlaceProfile:e,myProfile:e,observeMyProfile:e,session:()=>null,onSessionChange:()=>()=>{},onCloudChanged:()=>()=>{}}},M=()=>typeof window<"u"&&!!window.ReactNativeWebView,Y=()=>({send:e=>window.ReactNativeWebView?.postMessage(e),listen:e=>{const t=a=>{const n=a.data;typeof n=="string"&&e(n)};return window.addEventListener("message",t),document.addEventListener("message",t),()=>{window.removeEventListener("message",t),document.removeEventListener("message",t)}}}),R={finish:"FinishSubWebView",title:"SetSubWebViewTitle",haptic:"TriggerHaptic",clipboard:"CopyToClipboard",share:"OpenShareSheet",openUrl:"OpenURL",userKey:"GetSubWebViewUserKey",back:"SetCanGoBack",closeGuard:"SetSubWebViewCloseGuard",errorReport:"ReportSubWebViewError",storage:"GetSubWebViewStorage",permissions:"RequestSubWebViewPermission",data:"RuntimeHello"},$=1,Z=1e3,ee=4e3,x=()=>typeof window<"u"&&window.ChaticSubWebView||null,te=()=>new Promise(e=>{if(typeof document>"u"||document.readyState==="complete"){e(x());return}window.addEventListener("load",()=>e(x()),{once:!0})}),re=e=>{let t,a;try{e instanceof Error?(t=e.message||e.name,a=typeof e.stack=="string"?e.stack:void 0):typeof e=="string"?t=e:t=`A non-Error value was thrown: ${Object.prototype.toString.call(e)}`}catch{t="An error that could not be read was thrown"}return{message:(t||"Unknown error").slice(0,Z),...a?{stack:a.slice(0,ee)}:{}}},I=e=>new d.ChaticAppsError("NOT_SUPPORTED",`${e} is not available here: an older app, or not granted.`),L=e=>Promise.reject(new d.ChaticAppsError("NOT_IN_APP",`${e} needs the app; this page is in a browser.`)),B=(e={})=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new d.ChaticAppsError("INVALID","link() takes an object of query params, such as { level: 3 }.");const t=new URLSearchParams;for(const[n,m]of Object.entries(e))t.append(n,String(m));const a=t.toString();return a?`?${a}`:""},K=e=>typeof location>"u"?`/${e}`:`${location.origin}/${e}`;let T=null;const oe=(e={})=>(T||(T=(M()?ne(Y(),e):Promise.resolve(ie())).catch(t=>{throw T=null,t})),T),ne=async(e,t={})=>{const a=d.createBridgeClient(e,t.timeoutMs);try{const n=await H(a,!0);return se(a,n,t)}catch(n){throw a.close(),n}},H=async(e,t)=>{const a=await e.request("WebAppReady",{}),n=a.subWebView??(t?await te():null);if(n&&n.protocolVersion!==$)throw new d.ChaticAppsError("UNSUPPORTED_PROTOCOL",`The app speaks protocol ${String(n.protocolVersion)}; this library speaks ${$}.`);return{supported:new Set(Array.isArray(a.supportedWebMessages)?a.supportedWebMessages:[]),context:n}},se=(e,t,a)=>{let n=null,m=null;const h=new Set,u=[],y=r=>t.supported.has(R[r]),g=(r,i,l,p)=>{const A=p??R[r];return t.supported.has(A)?e.request(A,i,l===void 0?{}:{timeoutMs:l}):Promise.reject(I(r))},f=Q(e,()=>y("data"),r=>{w.reportError(r)});u.push(()=>f.dispose());const v=(r,i)=>y("storage")?e.request(r,i):Promise.reject(I("storage")),C=r=>h.forEach(i=>{try{i(r)}catch(l){w.reportError(l)}}),E=()=>{y("back")&&e.request(R.back,{canGoBack:!!n}).catch(()=>{}),y("closeGuard")&&e.request(R.closeGuard,{enabled:!!m}).catch(()=>{})},O=r=>{if(!r.persisted){E();return}H(e,!1).then(i=>{const l=t.context;t.supported=i.supported,i.context&&(t.context=i.context),E(),f.reset();const p=t.context,A=p&&(p.theme!==l?.theme||p.locale!==l?.locale||JSON.stringify(p.safeArea)!==JSON.stringify(l?.safeArea));p&&A&&C(p)}).catch(()=>{})};typeof window<"u"&&(window.addEventListener("pageshow",O),u.push(()=>window.removeEventListener("pageshow",O))),u.push(e.onPush("OnBackPressed",()=>{try{n?.()}catch(r){w.reportError(r)}})),u.push(e.onPush("OnSubWebViewCloseRequested",r=>{const i=m;if(!i)return;const l=r?.trigger??"control";Promise.resolve().then(()=>i(l)).then(p=>p?w.finish():void 0).catch(p=>w.reportError(p))})),u.push(e.onPush("OnSubWebViewContextChanged",r=>{t.context&&(t.context={...t.context,...r},C(t.context))}));const w={inApp:!0,get context(){return t.context},supports:y,finish:r=>g("finish",r===void 0?{}:{result:r}).then(()=>{}),setTitle:r=>g("title",{title:r}).then(()=>{}),haptic:r=>{y("haptic")&&e.request(R.haptic,{kind:r}).catch(()=>{})},copy:r=>g("clipboard",{text:r}).then(()=>{}),openUrl:r=>g("openUrl",{url:r}).then(()=>{}),share:r=>g("share",r,null).then(i=>i?.action==="dismissedAction"?"dismissed":"shared"),getUserKey:()=>g("userKey").then(r=>r.key),permissions:{query:r=>g("permissions",{kind:r},void 0,"GetSubWebViewPermission").then(i=>i.state),request:r=>g("permissions",{kind:r},null).then(i=>i.state)},openSettings:()=>g("permissions",{},void 0,"OpenSettings").then(()=>{}),reportError:r=>y("errorReport")?e.request(R.errorReport,re(r)).then(i=>!!i?.recorded).catch(()=>!1):Promise.resolve(!1),data:f,storage:d.storageOver({get:r=>v("GetSubWebViewStorage",{keys:r}),set:r=>v("SetSubWebViewStorage",{entries:r}),remove:r=>v("RemoveSubWebViewStorage",{keys:r}),clear:()=>v("ClearSubWebViewStorage",{}),info:()=>v("GetSubWebViewStorageInfo",{})}),onBack:r=>{n=r,E()},onCloseRequest:r=>{m=r,E()},onContextChange:r=>(h.add(r),()=>h.delete(r)),link:r=>{const i=B(r),l=t.context?.appLink;return l?`${l}${i}`:K(i)},disconnect:()=>{u.forEach(r=>r()),e.close(),T=null}};if(a.reportErrors!==!1&&typeof window<"u"){const r=l=>{w.reportError(l.error??l.message)},i=l=>{w.reportError(l.reason)};window.addEventListener("error",r),window.addEventListener("unhandledrejection",i),u.push(()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",i)})}return w},ae=()=>{const e=async t=>{try{const a=await navigator.permissions.query({name:t});return a.state==="granted"?"granted":a.state==="denied"?"blocked":"prompt"}catch{return"prompt"}};return{query:e,request:async t=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new d.ChaticAppsError("NOT_SUPPORTED",`This browser cannot capture the ${t}.`);try{return(await navigator.mediaDevices.getUserMedia(t==="camera"?{video:!0}:{audio:!0})).getTracks().forEach(n=>n.stop()),"granted"}catch(a){const n=a?.name;if(n==="NotFoundError"||n==="OverconstrainedError")throw new d.ChaticAppsError("UNAVAILABLE",`This device has no ${t}.`);if(n==="NotReadableError"||n==="SecurityError"||n==="TypeError"||n==="AbortError")throw new d.ChaticAppsError("INTERNAL_ERROR",`The ${t} could not be used: ${n}.`);return await e(t)==="blocked"?"blocked":"prompt"}}}},ie=()=>{const e=t=>typeof navigator<"u"&&navigator.clipboard?navigator.clipboard.writeText(t):Promise.reject(I("The clipboard"));return{inApp:!1,context:null,supports:()=>!1,finish:()=>L("Finishing the view"),setTitle:async t=>{typeof document<"u"&&(document.title=t)},haptic:()=>{typeof navigator<"u"&&navigator.vibrate?.(10)},copy:e,openUrl:async t=>{typeof window<"u"&&window.open(t,"_blank","noopener,noreferrer")},share:async t=>{const a=[t.message,t.url].filter(Boolean).join(" ");if(!a)throw new d.ChaticAppsError("INVALID","Share a message or a url.");if(typeof navigator<"u"&&navigator.share)try{return await navigator.share(t),"shared"}catch(n){if(n?.name==="AbortError")return"dismissed"}return await e(a),"copied"},getUserKey:()=>L("A user key"),permissions:ae(),data:X(),openSettings:()=>L("Opening the settings"),reportError:async t=>(console.error(t),!1),storage:d.browserStorage(),onBack:()=>{},onCloseRequest:()=>{},onContextChange:()=>()=>{},link:t=>K(B(t)),disconnect:()=>{T=null}}};exports.ChaticAppsError=d.ChaticAppsError;exports.SDK_BRIDGE_VERSION=d.SDK_BRIDGE_VERSION;exports.LISTENER=G;exports.SDK_DATA_CONTRACTS=j;exports.connect=oe;exports.isInApp=M;