@coasys/ad4m-connect 0.10.1-rc9-dev5 → 0.10.1-rc9-dev6

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/core.js CHANGED
@@ -1365,6 +1365,6 @@ input VoiceActivityParamsInput {
1365
1365
  startWindow: Float
1366
1366
  timeBeforeSpeech: Float
1367
1367
  }
1368
- `;function xp(e){return e?.length?e.length===1?e.toString():e.length===2?e.join(" and "):e.slice(0,-1).join(", ")+", and "+e.slice(-1):""}function Ek(e){let t=e.can.includes("*")?["READ","WRITE","UPDATE"]:e.can,r=e.with.domain==="*"?"":e.with.domain,n=e.with.pointers.includes("*")?["all AD4M data"]:e.with.pointers;return`${xp(t)} your ${r} actions, with access to ${xp(n)}`}var Br=function(e,t,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r},V=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},We,It,Eo,me,Tp=class{constructor(e,t,r){We.set(this,void 0),It.set(this,void 0),Eo.set(this,void 0),me.set(this,void 0),Br(this,We,t||kt.from(Td(24)).toUrl(),"f"),Br(this,me,e,"f"),Br(this,Eo,r||"ad4m://self","f")}get baseExpression(){return V(this,We,"f")}get perspective(){return V(this,me,"f")}async getData(e){let t=e??V(this,We,"f"),r=await V(this,me,"f").getSubjectData(V(this,It,"f"),t);return Object.assign(this,r),Br(this,We,t,"f"),this}async setProperty(key,value){let setters=await V(this,me,"f").infer(`subject_class("${V(this,It,"f")}", C), property_setter(C, "${key}", Setter)`);if(setters&&setters.length>0){let actions=eval(setters[0].Setter),resolveLanguageResults=await V(this,me,"f").infer(`subject_class("${V(this,It,"f")}", C), property_resolve_language(C, "${key}", Language)`),resolveLanguage;resolveLanguageResults&&resolveLanguageResults.length>0&&(resolveLanguage=resolveLanguageResults[0].Language),resolveLanguage&&(value=await V(this,me,"f").createExpression(value,resolveLanguage)),await V(this,me,"f").executeAction(actions,V(this,We,"f"),[{name:"value",value}])}}async setCollectionSetter(key,value){let collectionSetters=await V(this,me,"f").infer(`subject_class("${V(this,It,"f")}", C), collection_setter(C, "${Xt(key)}", Setter)`);if(collectionSetters||(collectionSetters=[]),collectionSetters.length>0){let actions=eval(collectionSetters[0].Setter);value&&(Array.isArray(value)?await V(this,me,"f").executeAction(actions,V(this,We,"f"),value.map(e=>({name:"value",value:e}))):await V(this,me,"f").executeAction(actions,V(this,We,"f"),[{name:"value",value}]))}}async setCollectionAdder(key,value){let adders=await V(this,me,"f").infer(`subject_class("${V(this,It,"f")}", C), collection_adder(C, "${Xt(key)}", Adder)`);if(adders||(adders=[]),adders.length>0){let actions=eval(adders[0].Adder);value&&(Array.isArray(value)?await Promise.all(value.map(e=>V(this,me,"f").executeAction(actions,V(this,We,"f"),[{name:"value",value:e}]))):await V(this,me,"f").executeAction(actions,V(this,We,"f"),[{name:"value",value}]))}}async setCollectionRemover(key,value){let removers=await V(this,me,"f").infer(`subject_class("${V(this,It,"f")}", C), collection_remover(C, "${Xt(key)}", Remover)`);if(removers||(removers=[]),removers.length>0){let actions=eval(removers[0].Remover);value&&(Array.isArray(value)?await Promise.all(value.map(e=>V(this,me,"f").executeAction(actions,V(this,We,"f"),[{name:"value",value:e}]))):await V(this,me,"f").executeAction(actions,V(this,We,"f"),[{name:"value",value}]))}}async save(){Br(this,It,await V(this,me,"f").stringOrTemplateObjectToSubjectClass(this),"f"),await V(this,me,"f").createSubject(this,V(this,We,"f")),await V(this,me,"f").add(new nn({source:V(this,Eo,"f"),predicate:"ad4m://has_child",target:this.baseExpression})),await this.update()}async update(){Br(this,It,await V(this,me,"f").stringOrTemplateObjectToSubjectClass(this),"f");let e=Object.entries(this);for(let[t,r]of e)if(r!=null)if(r?.action)switch(r.action){case"setter":await this.setCollectionSetter(t,r.value);break;case"adder":await this.setCollectionAdder(t,r.value);break;case"remover":await this.setCollectionRemover(t,r.value);default:await this.setCollectionSetter(t,r.value);break}else Array.isArray(r)&&r.length>0?await this.setCollectionSetter(t,r):r!=null&&r!==""&&await this.setProperty(t,r);await this.getData()}async get(){return Br(this,It,await V(this,me,"f").stringOrTemplateObjectToSubjectClass(this),"f"),await this.getData()}async delete(){await V(this,me,"f").removeSubject(this,V(this,We,"f"))}static async all(e){let t=await e.stringOrTemplateObjectToSubjectClass(this),r=await e.getAllSubjectProxies(t),n=[];if(r){for(let i of r){let a=new this(e,i.X);n.push(await a.get())}return n}return[]}static async query(e,t){let r=t?.source||"ad4m://self",n=await e.stringOrTemplateObjectToSubjectClass(this),i=[],a=`subject_class("${n}", C), instance(C, Base), link("${r}", Predicate, Base, Timestamp, Author)`;if(t){if(t.where)if(t.where.condition)a+=", "+t.where.condition;else{let s=Object.entries(t.where);for(let u of s){let c=u[0],l=u[1];a+=`, property_getter(C, Base, "${c}", "${l}")`}}try{if((await e.infer(`findall([Timestamp, Base], (${a}), AllData), sort(AllData, SortedData), length(SortedData, DataLength).`))[0].DataLength>=t.size){let u=`findall([Timestamp, Base], (${a}), AllData), sort(AllData, SortedData), reverse(SortedData, ReverseSortedData), paginate(ReverseSortedData, ${t.page}, ${t.size}, PageData).`;i=await e.infer(u),i=i[0].PageData.map(c=>({Base:c[1],Timestamp:c[0]}))}else i=await e.infer(a)}catch(s){console.log("Query failed",s)}}else i=await e.infer(a);return i?await Promise.all(i.map(async s=>await new this(e,s.Base).get())):[]}};We=new WeakMap,It=new WeakMap,Eo=new WeakMap,me=new WeakMap;var Id="0.10.1-rc9-dev5";var Xo=12e3;function $b(){let e=new AbortController;return setTimeout(()=>e.abort(),20),e}function es(e,t=1e4){return Ve(this,null,function*(){return Promise.race([new Promise((r,n)=>{try{e.includes("localhost")||r(new WebSocket(e));let i=new WebSocket(e);i.onopen=()=>{r(i)},i.onerror=a=>{n(a)}}catch(i){n(i)}}),new Promise((r,n)=>{setTimeout(()=>{n(new Error("WebSocket connection timed out"))},t)})])})}function yu(e){return Ve(this,null,function*(){try{let t=yield fetch(`http://localhost:${e}/graphql/`,{signal:$b().signal,mode:"cors"});if(t.status===400||t.status===0||t.status===200)return e;throw new Error(`Could not connect to port ${e}`)}catch(t){throw new Error(`Could not connect to port ${e}`)}})}function jb(){try{localStorage.setItem("test",""),localStorage.removeItem("test")}catch(e){return!1}return!0}function kd(e,t){jb()&&localStorage.setItem(`${Id}/${e}`,t)}var Ub=e=>{let t=new Set;do for(let r of Reflect.ownKeys(e))t.add([e,r]);while((e=Reflect.getPrototypeOf(e))&&e!==Object.prototype);return t};function vu(e,{include:t,exclude:r}={}){let n=i=>{let a=o=>typeof o=="string"?i===o:o.test(i);return t?t.some(a):r?!r.some(a):!0};for(let[i,a]of Ub(e.constructor.prototype)){if(a==="constructor"||!n(a))continue;let o=Reflect.getOwnPropertyDescriptor(i,a);o&&typeof o.value=="function"&&(e[a]=e[a].bind(e))}return e}var bu=class{constructor({appName:t,appDesc:r,appIconPath:n,appUrl:i,appDomain:a,capabilities:o,port:s,token:u,url:c,hosting:l}){this.activeSocket=null;this.requestedRestart=!1;this.authState="unauthenticated";this.connectionState="not_connected";this.port=Xo;this.capabilities=[];this.isHosting=!1;this.listeners={authstatechange:[],configstatechange:[],connectionstatechange:[]};vu(this);this.appName=t,this.appDesc=r,this.appDomain=a,this.appUrl=i,this.appIconPath=n,this.capabilities=o,this.port=s||this.port,this.url=c||`ws://localhost:${this.port}/graphql`,this.token=u||this.token,this.isHosting=l||!1,this.buildClient()}notifyConfigChange(t,r){this.listeners.configstatechange.forEach(n=>{n(t,r)})}notifyConnectionChange(t){this.connectionState!==t&&(this.connectionState=t,this.listeners.connectionstatechange.forEach(r=>{r(t)}))}notifyAuthChange(t){this.authState!==t&&(this.authState=t,this.listeners.authstatechange.forEach(r=>{r(t)}))}setPort(t){this.port!==t&&(this.port=t,this.setUrl(`ws://localhost:${this.port}/graphql`),this.notifyConfigChange("port",t))}setUrl(t){this.url!==t&&(this.url=t,this.notifyConfigChange("url",t))}setToken(t){this.token!==t&&(this.token=t,this.notifyConfigChange("token",t))}on(t,r){this.listeners[t].push(r)}connect(t){return Ve(this,null,function*(){try{if(t){yield es(t),this.setUrl(t);let r=this.buildClient();return yield this.checkAuth(),r}else{this.notifyConnectionChange("checking_local");try{yield es(`ws://localhost:${this.port}/graphql`,2e3);let r=this.buildClient();return yield this.checkAuth(),r}catch(r){let n=yield this.ensureConnection();return yield this.checkAuth(),n}}}catch(r){this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}})}loginToHosting(t,r){return Ve(this,null,function*(){try{let n=yield fetch("https://hosting.ad4m.dev/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t,password:r})});if(n.status===200){let i=yield n.json();localStorage.setItem("hosting_token",i.token);let a=localStorage.getItem("hosting_token"),o=yield fetch("https://hosting.ad4m.dev/api/service/info",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+a}});if(o.status===200){let s=yield o.json();if(s.serviceId)if(this.setPort(s.port),this.setUrl(s.url),this.isHosting=!0,kd("ad4mhosting","true"),!s.paused)this.connect();else throw new Error("Hosting is not running")}}else if((yield n.json()).message==="Passwords did not match")throw new Error("Passwords did not match")}catch(n){throw console.log(n),new Error(`Error logging in ${n}`)}})}checkEmail(t){return Ve(this,null,function*(){try{return(yield fetch(`https://hosting.ad4m.dev/api/auth/check-email?email=${t}`,{method:"GET",headers:{"Content-Type":"application/json"}})).status===200}catch(r){console.log(r)}})}connectToPort(t){return Ve(this,null,function*(){try{if(t){let r=yield yu(t);return this.setPort(r),this.buildClient()}else if(this.url.includes("localhost")){let r=yield this.findPort();return this.setPort(r),this.buildClient()}}catch(r){this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}})}ensureConnection(){return Ve(this,null,function*(){var r,n;if(((r=this.activeSocket)==null?void 0:r.readyState)===WebSocket.OPEN&&((n=this.activeSocket)==null?void 0:n.url)===this.url&&this.ad4mClient)return this.ad4mClient;try{return this.notifyConnectionChange("connecting"),yield es(this.url),this.buildClient()}catch(i){return this.notifyConnectionChange("not_connected"),this.connectToPort()}})}findPort(){return Ve(this,null,function*(){let t=[...Array(10).keys()].map((i,a)=>yu(Xo+a)),n=(yield Promise.allSettled(t)).find(i=>i.status==="fulfilled");if(n)return n.value;throw Error("Couldn't find an open port")})}buildClient(){this.notifyConnectionChange("connecting");try{let t=new WebSocket(this.url)}catch(t){this.notifyConnectionChange("not_connected");return}return this.apolloClient&&this.wsClient&&(this.requestedRestart=!0,this.wsClient.dispose(),this.apolloClient.stop(),this.wsClient=null,this.apolloClient=null),this.wsClient=mf({url:this.url,connectionParams:()=>Ve(this,null,function*(){return{headers:{authorization:this.token}}}),on:{opened:t=>{this.activeSocket=t},error:t=>{this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")},connected:()=>{this.notifyConnectionChange("connected"),this.checkAuth()},closed:t=>Ve(this,null,function*(){if(console.log("buildClient closed:",t),!this.requestedRestart)if(!this.token)this.notifyConnectionChange(this.token?"disconnected":"not_connected"),this.notifyAuthChange("unauthenticated"),this.requestedRestart=!1;else{let r=yield this.connect();r?this.ad4mClient=r:(this.notifyConnectionChange(this.token?"disconnected":"not_connected"),this.notifyAuthChange("unauthenticated"),this.requestedRestart=!1)}})}}),this.apolloClient=new uc({link:new gf(this.wsClient),cache:new Qa({resultCaching:!1,addTypename:!1}),defaultOptions:{watchQuery:{fetchPolicy:"no-cache"},query:{fetchPolicy:"no-cache"},mutate:{fetchPolicy:"no-cache"}}}),this.ad4mClient=new Uo(this.apolloClient),this.ad4mClient}checkAuth(){return Ve(this,null,function*(){try{return(yield this.ad4mClient.agent.isLocked())?this.notifyAuthChange("locked"):(yield this.ad4mClient.agent.status(),this.notifyAuthChange("authenticated")),!0}catch(t){return t.message==="Socket closed with event 4500 Cannot extractByTags from a ciphered wallet. You must unlock first."?(this.notifyAuthChange("locked"),!0):(this.notifyAuthChange("unauthenticated"),!1)}})}requestCapability(t=!1){return Ve(this,null,function*(){var r;if(t&&this.setToken(null),this.isHosting){let n=localStorage.getItem("hosting_token");(yield fetch("https://hosting.ad4m.dev/api/service/checkStatus",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+n}})).status!==200&&console.error("Looks like the client is not running you might not recieve the mail with the code, please check your dashboard logs.")}return this.requestId=yield(r=this.ad4mClient)==null?void 0:r.agent.requestCapability({appName:this.appName,appDesc:this.appDesc,appUrl:this.appUrl,appIconPath:this.appIconPath,appDomain:this.appDomain,capabilities:this.capabilities}),this.requestId})}verifyCode(t){return Ve(this,null,function*(){var r;try{let n=yield(r=this.ad4mClient)==null?void 0:r.agent.generateJwt(this.requestId,t);return this.setToken(n),yield this.buildClient(),yield this.checkAuth(),this.token}catch(n){throw new Error("Invalid code")}})}clearState(){this.setToken(null),this.setPort(Xo),this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}};export{bu as default};
1368
+ `;function xp(e){return e?.length?e.length===1?e.toString():e.length===2?e.join(" and "):e.slice(0,-1).join(", ")+", and "+e.slice(-1):""}function Ek(e){let t=e.can.includes("*")?["READ","WRITE","UPDATE"]:e.can,r=e.with.domain==="*"?"":e.with.domain,n=e.with.pointers.includes("*")?["all AD4M data"]:e.with.pointers;return`${xp(t)} your ${r} actions, with access to ${xp(n)}`}var Br=function(e,t,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r},V=function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},We,It,Eo,me,Tp=class{constructor(e,t,r){We.set(this,void 0),It.set(this,void 0),Eo.set(this,void 0),me.set(this,void 0),Br(this,We,t||kt.from(Td(24)).toUrl(),"f"),Br(this,me,e,"f"),Br(this,Eo,r||"ad4m://self","f")}get baseExpression(){return V(this,We,"f")}get perspective(){return V(this,me,"f")}async getData(e){let t=e??V(this,We,"f"),r=await V(this,me,"f").getSubjectData(V(this,It,"f"),t);return Object.assign(this,r),Br(this,We,t,"f"),this}async setProperty(key,value){let setters=await V(this,me,"f").infer(`subject_class("${V(this,It,"f")}", C), property_setter(C, "${key}", Setter)`);if(setters&&setters.length>0){let actions=eval(setters[0].Setter),resolveLanguageResults=await V(this,me,"f").infer(`subject_class("${V(this,It,"f")}", C), property_resolve_language(C, "${key}", Language)`),resolveLanguage;resolveLanguageResults&&resolveLanguageResults.length>0&&(resolveLanguage=resolveLanguageResults[0].Language),resolveLanguage&&(value=await V(this,me,"f").createExpression(value,resolveLanguage)),await V(this,me,"f").executeAction(actions,V(this,We,"f"),[{name:"value",value}])}}async setCollectionSetter(key,value){let collectionSetters=await V(this,me,"f").infer(`subject_class("${V(this,It,"f")}", C), collection_setter(C, "${Xt(key)}", Setter)`);if(collectionSetters||(collectionSetters=[]),collectionSetters.length>0){let actions=eval(collectionSetters[0].Setter);value&&(Array.isArray(value)?await V(this,me,"f").executeAction(actions,V(this,We,"f"),value.map(e=>({name:"value",value:e}))):await V(this,me,"f").executeAction(actions,V(this,We,"f"),[{name:"value",value}]))}}async setCollectionAdder(key,value){let adders=await V(this,me,"f").infer(`subject_class("${V(this,It,"f")}", C), collection_adder(C, "${Xt(key)}", Adder)`);if(adders||(adders=[]),adders.length>0){let actions=eval(adders[0].Adder);value&&(Array.isArray(value)?await Promise.all(value.map(e=>V(this,me,"f").executeAction(actions,V(this,We,"f"),[{name:"value",value:e}]))):await V(this,me,"f").executeAction(actions,V(this,We,"f"),[{name:"value",value}]))}}async setCollectionRemover(key,value){let removers=await V(this,me,"f").infer(`subject_class("${V(this,It,"f")}", C), collection_remover(C, "${Xt(key)}", Remover)`);if(removers||(removers=[]),removers.length>0){let actions=eval(removers[0].Remover);value&&(Array.isArray(value)?await Promise.all(value.map(e=>V(this,me,"f").executeAction(actions,V(this,We,"f"),[{name:"value",value:e}]))):await V(this,me,"f").executeAction(actions,V(this,We,"f"),[{name:"value",value}]))}}async save(){Br(this,It,await V(this,me,"f").stringOrTemplateObjectToSubjectClass(this),"f"),await V(this,me,"f").createSubject(this,V(this,We,"f")),await V(this,me,"f").add(new nn({source:V(this,Eo,"f"),predicate:"ad4m://has_child",target:this.baseExpression})),await this.update()}async update(){Br(this,It,await V(this,me,"f").stringOrTemplateObjectToSubjectClass(this),"f");let e=Object.entries(this);for(let[t,r]of e)if(r!=null)if(r?.action)switch(r.action){case"setter":await this.setCollectionSetter(t,r.value);break;case"adder":await this.setCollectionAdder(t,r.value);break;case"remover":await this.setCollectionRemover(t,r.value);default:await this.setCollectionSetter(t,r.value);break}else Array.isArray(r)&&r.length>0?await this.setCollectionSetter(t,r):r!=null&&r!==""&&await this.setProperty(t,r);await this.getData()}async get(){return Br(this,It,await V(this,me,"f").stringOrTemplateObjectToSubjectClass(this),"f"),await this.getData()}async delete(){await V(this,me,"f").removeSubject(this,V(this,We,"f"))}static async all(e){let t=await e.stringOrTemplateObjectToSubjectClass(this),r=await e.getAllSubjectProxies(t),n=[];if(r){for(let i of r){let a=new this(e,i.X);n.push(await a.get())}return n}return[]}static async query(e,t){let r=t?.source||"ad4m://self",n=await e.stringOrTemplateObjectToSubjectClass(this),i=[],a=`subject_class("${n}", C), instance(C, Base), link("${r}", Predicate, Base, Timestamp, Author)`;if(t){if(t.where)if(t.where.condition)a+=", "+t.where.condition;else{let s=Object.entries(t.where);for(let u of s){let c=u[0],l=u[1];a+=`, property_getter(C, Base, "${c}", "${l}")`}}try{if((await e.infer(`findall([Timestamp, Base], (${a}), AllData), sort(AllData, SortedData), length(SortedData, DataLength).`))[0].DataLength>=t.size){let u=`findall([Timestamp, Base], (${a}), AllData), sort(AllData, SortedData), reverse(SortedData, ReverseSortedData), paginate(ReverseSortedData, ${t.page}, ${t.size}, PageData).`;i=await e.infer(u),i=i[0].PageData.map(c=>({Base:c[1],Timestamp:c[0]}))}else i=await e.infer(a)}catch(s){console.log("Query failed",s)}}else i=await e.infer(a);return i?await Promise.all(i.map(async s=>await new this(e,s.Base).get())):[]}};We=new WeakMap,It=new WeakMap,Eo=new WeakMap,me=new WeakMap;var Id="0.10.1-rc9-dev5";var Xo=12e3;function $b(){let e=new AbortController;return setTimeout(()=>e.abort(),20),e}function es(e,t=1e4){return Ve(this,null,function*(){return Promise.race([new Promise((r,n)=>{try{e.includes("localhost")||r(new WebSocket(e));let i=new WebSocket(e);i.onopen=()=>{r(i)},i.onerror=a=>{n(a)}}catch(i){n(i)}}),new Promise((r,n)=>{setTimeout(()=>{n(new Error("WebSocket connection timed out"))},t)})])})}function yu(e){return Ve(this,null,function*(){try{let t=yield fetch(`http://localhost:${e}/graphql/`,{signal:$b().signal,mode:"cors"});if(t.status===400||t.status===0||t.status===200)return e;throw new Error(`Could not connect to port ${e}`)}catch(t){throw new Error(`Could not connect to port ${e}`)}})}function jb(){try{localStorage.setItem("test",""),localStorage.removeItem("test")}catch(e){return!1}return!0}function kd(e,t){jb()&&localStorage.setItem(`${Id}/${e}`,t)}var Ub=e=>{let t=new Set;do for(let r of Reflect.ownKeys(e))t.add([e,r]);while((e=Reflect.getPrototypeOf(e))&&e!==Object.prototype);return t};function vu(e,{include:t,exclude:r}={}){let n=i=>{let a=o=>typeof o=="string"?i===o:o.test(i);return t?t.some(a):r?!r.some(a):!0};for(let[i,a]of Ub(e.constructor.prototype)){if(a==="constructor"||!n(a))continue;let o=Reflect.getOwnPropertyDescriptor(i,a);o&&typeof o.value=="function"&&(e[a]=e[a].bind(e))}return e}var bu=class{constructor({appName:t,appDesc:r,appIconPath:n,appUrl:i,appDomain:a,capabilities:o,port:s,token:u,url:c,hosting:l}){this.activeSocket=null;this.requestedRestart=!1;this.authState="unauthenticated";this.connectionState="not_connected";this.port=Xo;this.capabilities=[];this.isHosting=!1;this.listeners={authstatechange:[],configstatechange:[],connectionstatechange:[]};vu(this);this.appName=t,this.appDesc=r,this.appDomain=a,this.appUrl=i,this.appIconPath=n,this.capabilities=o,this.port=s||this.port,this.url=c||`ws://localhost:${this.port}/graphql`,this.token=u||this.token,this.isHosting=l||!1,this.buildClient()}notifyConfigChange(t,r){this.listeners.configstatechange.forEach(n=>{n(t,r)})}notifyConnectionChange(t){this.connectionState!==t&&(this.connectionState=t,this.listeners.connectionstatechange.forEach(r=>{r(t)}))}notifyAuthChange(t){this.authState!==t&&(this.authState=t,this.listeners.authstatechange.forEach(r=>{r(t)}))}setPort(t){this.port!==t&&(this.port=t,this.setUrl(`ws://localhost:${this.port}/graphql`),this.notifyConfigChange("port",t))}setUrl(t){this.url!==t&&(this.url=t,this.notifyConfigChange("url",t))}setToken(t){this.token!==t&&(this.token=t,this.notifyConfigChange("token",t))}on(t,r){this.listeners[t].push(r)}connect(t){return Ve(this,null,function*(){try{if(t){yield es(t),this.setUrl(t);let r=this.buildClient();return yield this.checkAuth(),r}else{this.notifyConnectionChange("checking_local");try{yield es(`ws://localhost:${this.port}/graphql`,2e3);let r=this.buildClient();return yield this.checkAuth(),r}catch(r){let n=yield this.ensureConnection();return yield this.checkAuth(),n}}}catch(r){this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}})}loginToHosting(t,r){return Ve(this,null,function*(){try{let n=yield fetch("https://hosting.ad4m.dev/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t,password:r})});if(n.status===200){let i=yield n.json();localStorage.setItem("hosting_token",i.token);let a=localStorage.getItem("hosting_token"),o=yield fetch("https://hosting.ad4m.dev/api/service/info",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+a}});if(o.status===200){let s=yield o.json();if(s.serviceId)if(this.setPort(s.port),this.setUrl(s.url),this.isHosting=!0,kd("ad4mhosting","true"),!s.paused)this.connect();else throw new Error("Hosting is not running")}}else if((yield n.json()).message==="Passwords did not match")throw new Error("Passwords did not match")}catch(n){throw console.log(n),new Error(`Error logging in ${n}`)}})}checkEmail(t){return Ve(this,null,function*(){try{return(yield fetch(`https://hosting.ad4m.dev/api/auth/check-email?email=${t}`,{method:"GET",headers:{"Content-Type":"application/json"}})).status===200}catch(r){console.log(r)}})}connectToPort(t){return Ve(this,null,function*(){try{if(t){let r=yield yu(t);return this.setPort(r),this.buildClient()}else if(this.url.includes("localhost")){let r=yield this.findPort();return this.setPort(r),this.buildClient()}}catch(r){this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}})}ensureConnection(){return Ve(this,null,function*(){var r,n;if(((r=this.activeSocket)==null?void 0:r.readyState)===WebSocket.OPEN&&((n=this.activeSocket)==null?void 0:n.url)===this.url&&this.ad4mClient)return this.ad4mClient;try{return this.notifyConnectionChange("connecting"),yield es(this.url),this.buildClient()}catch(i){return this.notifyConnectionChange("not_connected"),this.connectToPort()}})}findPort(){return Ve(this,null,function*(){let t=[...Array(10).keys()].map((i,a)=>yu(Xo+a)),n=(yield Promise.allSettled(t)).find(i=>i.status==="fulfilled");if(n)return n.value;throw Error("Couldn't find an open port")})}buildClient(){this.notifyConnectionChange("connecting");try{let t=new WebSocket(this.url)}catch(t){this.notifyConnectionChange("not_connected");return}return this.apolloClient&&this.wsClient&&(this.requestedRestart=!0,this.wsClient.dispose(),this.apolloClient.stop(),this.wsClient=null,this.apolloClient=null),this.wsClient=mf({url:this.url,connectionParams:()=>Ve(this,null,function*(){return{headers:{authorization:this.token}}}),on:{opened:t=>{this.activeSocket=t},error:t=>{this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")},connected:()=>{this.notifyConnectionChange("connected"),this.checkAuth()},closed:t=>Ve(this,null,function*(){if(console.log("buildClient closed:",t),!t.wasClean&&!this.requestedRestart)if(!this.token)this.notifyConnectionChange(this.token?"disconnected":"not_connected"),this.notifyAuthChange("unauthenticated"),this.requestedRestart=!1;else{let r=yield this.connect();r?this.ad4mClient=r:(this.notifyConnectionChange(this.token?"disconnected":"not_connected"),this.notifyAuthChange("unauthenticated"),this.requestedRestart=!1)}})}}),this.apolloClient=new uc({link:new gf(this.wsClient),cache:new Qa({resultCaching:!1,addTypename:!1}),defaultOptions:{watchQuery:{fetchPolicy:"no-cache"},query:{fetchPolicy:"no-cache"},mutate:{fetchPolicy:"no-cache"}}}),this.ad4mClient=new Uo(this.apolloClient),this.ad4mClient}checkAuth(){return Ve(this,null,function*(){try{return(yield this.ad4mClient.agent.isLocked())?this.notifyAuthChange("locked"):(yield this.ad4mClient.agent.status(),this.notifyAuthChange("authenticated")),!0}catch(t){return t.message==="Socket closed with event 4500 Cannot extractByTags from a ciphered wallet. You must unlock first."?(this.notifyAuthChange("locked"),!0):(this.notifyAuthChange("unauthenticated"),!1)}})}requestCapability(t=!1){return Ve(this,null,function*(){var r;if(t&&this.setToken(null),this.isHosting){let n=localStorage.getItem("hosting_token");(yield fetch("https://hosting.ad4m.dev/api/service/checkStatus",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+n}})).status!==200&&console.error("Looks like the client is not running you might not recieve the mail with the code, please check your dashboard logs.")}return this.requestId=yield(r=this.ad4mClient)==null?void 0:r.agent.requestCapability({appName:this.appName,appDesc:this.appDesc,appUrl:this.appUrl,appIconPath:this.appIconPath,appDomain:this.appDomain,capabilities:this.capabilities}),this.requestId})}verifyCode(t){return Ve(this,null,function*(){var r;try{let n=yield(r=this.ad4mClient)==null?void 0:r.agent.generateJwt(this.requestId,t);return this.setToken(n),yield this.buildClient(),yield this.checkAuth(),this.token}catch(n){throw new Error("Invalid code")}})}clearState(){this.setToken(null),this.setPort(Xo),this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}};export{bu as default};
1369
1369
  /*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */
1370
1370
  //! @fayeed - make it support node.js
package/dist/web.js CHANGED
@@ -1367,7 +1367,7 @@ input VoiceActivityParamsInput {
1367
1367
  startWindow: Float
1368
1368
  timeBeforeSpeech: Float
1369
1369
  }
1370
- `;function oh(t){return t?.length?t.length===1?t.toString():t.length===2?t.join(" and "):t.slice(0,-1).join(", ")+", and "+t.slice(-1):""}function cm(t){let e=t.can.includes("*")?["READ","WRITE","UPDATE"]:t.can,r=t.with.domain==="*"?"":t.with.domain,n=t.with.pointers.includes("*")?["all AD4M data"]:t.with.pointers;return`${oh(e)} your ${r} actions, with access to ${oh(n)}`}var un=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},Q=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},tt,Pt,as,we,sh=class{constructor(t,e,r){tt.set(this,void 0),Pt.set(this,void 0),as.set(this,void 0),we.set(this,void 0),un(this,tt,e||Lt.from(sm(24)).toUrl(),"f"),un(this,we,t,"f"),un(this,as,r||"ad4m://self","f")}get baseExpression(){return Q(this,tt,"f")}get perspective(){return Q(this,we,"f")}async getData(t){let e=t??Q(this,tt,"f"),r=await Q(this,we,"f").getSubjectData(Q(this,Pt,"f"),e);return Object.assign(this,r),un(this,tt,e,"f"),this}async setProperty(key,value){let setters=await Q(this,we,"f").infer(`subject_class("${Q(this,Pt,"f")}", C), property_setter(C, "${key}", Setter)`);if(setters&&setters.length>0){let actions=eval(setters[0].Setter),resolveLanguageResults=await Q(this,we,"f").infer(`subject_class("${Q(this,Pt,"f")}", C), property_resolve_language(C, "${key}", Language)`),resolveLanguage;resolveLanguageResults&&resolveLanguageResults.length>0&&(resolveLanguage=resolveLanguageResults[0].Language),resolveLanguage&&(value=await Q(this,we,"f").createExpression(value,resolveLanguage)),await Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),[{name:"value",value}])}}async setCollectionSetter(key,value){let collectionSetters=await Q(this,we,"f").infer(`subject_class("${Q(this,Pt,"f")}", C), collection_setter(C, "${ur(key)}", Setter)`);if(collectionSetters||(collectionSetters=[]),collectionSetters.length>0){let actions=eval(collectionSetters[0].Setter);value&&(Array.isArray(value)?await Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),value.map(t=>({name:"value",value:t}))):await Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),[{name:"value",value}]))}}async setCollectionAdder(key,value){let adders=await Q(this,we,"f").infer(`subject_class("${Q(this,Pt,"f")}", C), collection_adder(C, "${ur(key)}", Adder)`);if(adders||(adders=[]),adders.length>0){let actions=eval(adders[0].Adder);value&&(Array.isArray(value)?await Promise.all(value.map(t=>Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),[{name:"value",value:t}]))):await Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),[{name:"value",value}]))}}async setCollectionRemover(key,value){let removers=await Q(this,we,"f").infer(`subject_class("${Q(this,Pt,"f")}", C), collection_remover(C, "${ur(key)}", Remover)`);if(removers||(removers=[]),removers.length>0){let actions=eval(removers[0].Remover);value&&(Array.isArray(value)?await Promise.all(value.map(t=>Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),[{name:"value",value:t}]))):await Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),[{name:"value",value}]))}}async save(){un(this,Pt,await Q(this,we,"f").stringOrTemplateObjectToSubjectClass(this),"f"),await Q(this,we,"f").createSubject(this,Q(this,tt,"f")),await Q(this,we,"f").add(new En({source:Q(this,as,"f"),predicate:"ad4m://has_child",target:this.baseExpression})),await this.update()}async update(){un(this,Pt,await Q(this,we,"f").stringOrTemplateObjectToSubjectClass(this),"f");let t=Object.entries(this);for(let[e,r]of t)if(r!=null)if(r?.action)switch(r.action){case"setter":await this.setCollectionSetter(e,r.value);break;case"adder":await this.setCollectionAdder(e,r.value);break;case"remover":await this.setCollectionRemover(e,r.value);default:await this.setCollectionSetter(e,r.value);break}else Array.isArray(r)&&r.length>0?await this.setCollectionSetter(e,r):r!=null&&r!==""&&await this.setProperty(e,r);await this.getData()}async get(){return un(this,Pt,await Q(this,we,"f").stringOrTemplateObjectToSubjectClass(this),"f"),await this.getData()}async delete(){await Q(this,we,"f").removeSubject(this,Q(this,tt,"f"))}static async all(t){let e=await t.stringOrTemplateObjectToSubjectClass(this),r=await t.getAllSubjectProxies(e),n=[];if(r){for(let i of r){let a=new this(t,i.X);n.push(await a.get())}return n}return[]}static async query(t,e){let r=e?.source||"ad4m://self",n=await t.stringOrTemplateObjectToSubjectClass(this),i=[],a=`subject_class("${n}", C), instance(C, Base), link("${r}", Predicate, Base, Timestamp, Author)`;if(e){if(e.where)if(e.where.condition)a+=", "+e.where.condition;else{let s=Object.entries(e.where);for(let u of s){let c=u[0],l=u[1];a+=`, property_getter(C, Base, "${c}", "${l}")`}}try{if((await t.infer(`findall([Timestamp, Base], (${a}), AllData), sort(AllData, SortedData), length(SortedData, DataLength).`))[0].DataLength>=e.size){let u=`findall([Timestamp, Base], (${a}), AllData), sort(AllData, SortedData), reverse(SortedData, ReverseSortedData), paginate(ReverseSortedData, ${e.page}, ${e.size}, PageData).`;i=await t.infer(u),i=i[0].PageData.map(c=>({Base:c[1],Timestamp:c[0]}))}else i=await t.infer(a)}catch(s){console.log("Query failed",s)}}else i=await t.infer(a);return i?await Promise.all(i.map(async s=>await new this(t,s.Base).get())):[]}};tt=new WeakMap,Pt=new WeakMap,as=new WeakMap,we=new WeakMap;var Ls="0.10.1-rc9-dev5";var fr=12e3;function N2(){let t=new AbortController;return setTimeout(()=>t.abort(),20),t}function $s(t,e=1e4){return pe(this,null,function*(){return Promise.race([new Promise((r,n)=>{try{t.includes("localhost")||r(new WebSocket(t));let i=new WebSocket(t);i.onopen=()=>{r(i)},i.onerror=a=>{n(a)}}catch(i){n(i)}}),new Promise((r,n)=>{setTimeout(()=>{n(new Error("WebSocket connection timed out"))},e)})])})}function bl(t){return pe(this,null,function*(){try{let e=yield fetch(`http://localhost:${t}/graphql/`,{signal:N2().signal,mode:"cors"});if(e.status===400||e.status===0||e.status===200)return t;throw new Error(`Could not connect to port ${t}`)}catch(e){throw new Error(`Could not connect to port ${t}`)}})}function R2(){return new Promise((t,e)=>{let r=document.querySelector("ad4m-connect"),n=r==null?void 0:r.getAd4mClient();n?t(n):e("No Ad4mClient found")})}function _l(){try{localStorage.setItem("test",""),localStorage.removeItem("test")}catch(t){return!1}return!0}function Fs(t,e){_l()&&localStorage.setItem(`${Ls}/${t}`,e)}function Jt(t){return _l()?localStorage.getItem(`${Ls}/${t}`):null}function wl(t){_l()&&localStorage.removeItem(`${Ls}/${t}`)}var P2=t=>{let e=new Set;do for(let r of Reflect.ownKeys(t))e.add([t,r]);while((t=Reflect.getPrototypeOf(t))&&t!==Object.prototype);return e};function ja(t,{include:e,exclude:r}={}){let n=i=>{let a=o=>typeof o=="string"?i===o:o.test(i);return e?e.some(a):r?!r.some(a):!0};for(let[i,a]of P2(t.constructor.prototype)){if(a==="constructor"||!n(a))continue;let o=Reflect.getOwnPropertyDescriptor(i,a);o&&typeof o.value=="function"&&(t[a]=t[a].bind(t))}return t}var qa=class{constructor({appName:e,appDesc:r,appIconPath:n,appUrl:i,appDomain:a,capabilities:o,port:s,token:u,url:c,hosting:l}){this.activeSocket=null;this.requestedRestart=!1;this.authState="unauthenticated";this.connectionState="not_connected";this.port=fr;this.capabilities=[];this.isHosting=!1;this.listeners={authstatechange:[],configstatechange:[],connectionstatechange:[]};ja(this);this.appName=e,this.appDesc=r,this.appDomain=a,this.appUrl=i,this.appIconPath=n,this.capabilities=o,this.port=s||this.port,this.url=c||`ws://localhost:${this.port}/graphql`,this.token=u||this.token,this.isHosting=l||!1,this.buildClient()}notifyConfigChange(e,r){this.listeners.configstatechange.forEach(n=>{n(e,r)})}notifyConnectionChange(e){this.connectionState!==e&&(this.connectionState=e,this.listeners.connectionstatechange.forEach(r=>{r(e)}))}notifyAuthChange(e){this.authState!==e&&(this.authState=e,this.listeners.authstatechange.forEach(r=>{r(e)}))}setPort(e){this.port!==e&&(this.port=e,this.setUrl(`ws://localhost:${this.port}/graphql`),this.notifyConfigChange("port",e))}setUrl(e){this.url!==e&&(this.url=e,this.notifyConfigChange("url",e))}setToken(e){this.token!==e&&(this.token=e,this.notifyConfigChange("token",e))}on(e,r){this.listeners[e].push(r)}connect(e){return pe(this,null,function*(){try{if(e){yield $s(e),this.setUrl(e);let r=this.buildClient();return yield this.checkAuth(),r}else{this.notifyConnectionChange("checking_local");try{yield $s(`ws://localhost:${this.port}/graphql`,2e3);let r=this.buildClient();return yield this.checkAuth(),r}catch(r){let n=yield this.ensureConnection();return yield this.checkAuth(),n}}}catch(r){this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}})}loginToHosting(e,r){return pe(this,null,function*(){try{let n=yield fetch("https://hosting.ad4m.dev/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,password:r})});if(n.status===200){let i=yield n.json();localStorage.setItem("hosting_token",i.token);let a=localStorage.getItem("hosting_token"),o=yield fetch("https://hosting.ad4m.dev/api/service/info",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+a}});if(o.status===200){let s=yield o.json();if(s.serviceId)if(this.setPort(s.port),this.setUrl(s.url),this.isHosting=!0,Fs("ad4mhosting","true"),!s.paused)this.connect();else throw new Error("Hosting is not running")}}else if((yield n.json()).message==="Passwords did not match")throw new Error("Passwords did not match")}catch(n){throw console.log(n),new Error(`Error logging in ${n}`)}})}checkEmail(e){return pe(this,null,function*(){try{return(yield fetch(`https://hosting.ad4m.dev/api/auth/check-email?email=${e}`,{method:"GET",headers:{"Content-Type":"application/json"}})).status===200}catch(r){console.log(r)}})}connectToPort(e){return pe(this,null,function*(){try{if(e){let r=yield bl(e);return this.setPort(r),this.buildClient()}else if(this.url.includes("localhost")){let r=yield this.findPort();return this.setPort(r),this.buildClient()}}catch(r){this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}})}ensureConnection(){return pe(this,null,function*(){var r,n;if(((r=this.activeSocket)==null?void 0:r.readyState)===WebSocket.OPEN&&((n=this.activeSocket)==null?void 0:n.url)===this.url&&this.ad4mClient)return this.ad4mClient;try{return this.notifyConnectionChange("connecting"),yield $s(this.url),this.buildClient()}catch(i){return this.notifyConnectionChange("not_connected"),this.connectToPort()}})}findPort(){return pe(this,null,function*(){let e=[...Array(10).keys()].map((i,a)=>bl(fr+a)),n=(yield Promise.allSettled(e)).find(i=>i.status==="fulfilled");if(n)return n.value;throw Error("Couldn't find an open port")})}buildClient(){this.notifyConnectionChange("connecting");try{let e=new WebSocket(this.url)}catch(e){this.notifyConnectionChange("not_connected");return}return this.apolloClient&&this.wsClient&&(this.requestedRestart=!0,this.wsClient.dispose(),this.apolloClient.stop(),this.wsClient=null,this.apolloClient=null),this.wsClient=Yp({url:this.url,connectionParams:()=>pe(this,null,function*(){return{headers:{authorization:this.token}}}),on:{opened:e=>{this.activeSocket=e},error:e=>{this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")},connected:()=>{this.notifyConnectionChange("connected"),this.checkAuth()},closed:e=>pe(this,null,function*(){if(console.log("buildClient closed:",e),!this.requestedRestart)if(!this.token)this.notifyConnectionChange(this.token?"disconnected":"not_connected"),this.notifyAuthChange("unauthenticated"),this.requestedRestart=!1;else{let r=yield this.connect();r?this.ad4mClient=r:(this.notifyConnectionChange(this.token?"disconnected":"not_connected"),this.notifyAuthChange("unauthenticated"),this.requestedRestart=!1)}})}}),this.apolloClient=new fu({link:new Jp(this.wsClient),cache:new To({resultCaching:!1,addTypename:!1}),defaultOptions:{watchQuery:{fetchPolicy:"no-cache"},query:{fetchPolicy:"no-cache"},mutate:{fetchPolicy:"no-cache"}}}),this.ad4mClient=new Ss(this.apolloClient),this.ad4mClient}checkAuth(){return pe(this,null,function*(){try{return(yield this.ad4mClient.agent.isLocked())?this.notifyAuthChange("locked"):(yield this.ad4mClient.agent.status(),this.notifyAuthChange("authenticated")),!0}catch(e){return e.message==="Socket closed with event 4500 Cannot extractByTags from a ciphered wallet. You must unlock first."?(this.notifyAuthChange("locked"),!0):(this.notifyAuthChange("unauthenticated"),!1)}})}requestCapability(e=!1){return pe(this,null,function*(){var r;if(e&&this.setToken(null),this.isHosting){let n=localStorage.getItem("hosting_token");(yield fetch("https://hosting.ad4m.dev/api/service/checkStatus",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+n}})).status!==200&&console.error("Looks like the client is not running you might not recieve the mail with the code, please check your dashboard logs.")}return this.requestId=yield(r=this.ad4mClient)==null?void 0:r.agent.requestCapability({appName:this.appName,appDesc:this.appDesc,appUrl:this.appUrl,appIconPath:this.appIconPath,appDomain:this.appDomain,capabilities:this.capabilities}),this.requestId})}verifyCode(e){return pe(this,null,function*(){var r;try{let n=yield(r=this.ad4mClient)==null?void 0:r.agent.generateJwt(this.requestId,e);return this.setToken(n),yield this.buildClient(),yield this.checkAuth(),this.token}catch(n){throw new Error("Invalid code")}})}clearState(){this.setToken(null),this.setPort(fr),this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}};function Sl({unlockAgent:t,reconnect:e}){return B`
1370
+ `;function oh(t){return t?.length?t.length===1?t.toString():t.length===2?t.join(" and "):t.slice(0,-1).join(", ")+", and "+t.slice(-1):""}function cm(t){let e=t.can.includes("*")?["READ","WRITE","UPDATE"]:t.can,r=t.with.domain==="*"?"":t.with.domain,n=t.with.pointers.includes("*")?["all AD4M data"]:t.with.pointers;return`${oh(e)} your ${r} actions, with access to ${oh(n)}`}var un=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},Q=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},tt,Pt,as,we,sh=class{constructor(t,e,r){tt.set(this,void 0),Pt.set(this,void 0),as.set(this,void 0),we.set(this,void 0),un(this,tt,e||Lt.from(sm(24)).toUrl(),"f"),un(this,we,t,"f"),un(this,as,r||"ad4m://self","f")}get baseExpression(){return Q(this,tt,"f")}get perspective(){return Q(this,we,"f")}async getData(t){let e=t??Q(this,tt,"f"),r=await Q(this,we,"f").getSubjectData(Q(this,Pt,"f"),e);return Object.assign(this,r),un(this,tt,e,"f"),this}async setProperty(key,value){let setters=await Q(this,we,"f").infer(`subject_class("${Q(this,Pt,"f")}", C), property_setter(C, "${key}", Setter)`);if(setters&&setters.length>0){let actions=eval(setters[0].Setter),resolveLanguageResults=await Q(this,we,"f").infer(`subject_class("${Q(this,Pt,"f")}", C), property_resolve_language(C, "${key}", Language)`),resolveLanguage;resolveLanguageResults&&resolveLanguageResults.length>0&&(resolveLanguage=resolveLanguageResults[0].Language),resolveLanguage&&(value=await Q(this,we,"f").createExpression(value,resolveLanguage)),await Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),[{name:"value",value}])}}async setCollectionSetter(key,value){let collectionSetters=await Q(this,we,"f").infer(`subject_class("${Q(this,Pt,"f")}", C), collection_setter(C, "${ur(key)}", Setter)`);if(collectionSetters||(collectionSetters=[]),collectionSetters.length>0){let actions=eval(collectionSetters[0].Setter);value&&(Array.isArray(value)?await Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),value.map(t=>({name:"value",value:t}))):await Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),[{name:"value",value}]))}}async setCollectionAdder(key,value){let adders=await Q(this,we,"f").infer(`subject_class("${Q(this,Pt,"f")}", C), collection_adder(C, "${ur(key)}", Adder)`);if(adders||(adders=[]),adders.length>0){let actions=eval(adders[0].Adder);value&&(Array.isArray(value)?await Promise.all(value.map(t=>Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),[{name:"value",value:t}]))):await Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),[{name:"value",value}]))}}async setCollectionRemover(key,value){let removers=await Q(this,we,"f").infer(`subject_class("${Q(this,Pt,"f")}", C), collection_remover(C, "${ur(key)}", Remover)`);if(removers||(removers=[]),removers.length>0){let actions=eval(removers[0].Remover);value&&(Array.isArray(value)?await Promise.all(value.map(t=>Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),[{name:"value",value:t}]))):await Q(this,we,"f").executeAction(actions,Q(this,tt,"f"),[{name:"value",value}]))}}async save(){un(this,Pt,await Q(this,we,"f").stringOrTemplateObjectToSubjectClass(this),"f"),await Q(this,we,"f").createSubject(this,Q(this,tt,"f")),await Q(this,we,"f").add(new En({source:Q(this,as,"f"),predicate:"ad4m://has_child",target:this.baseExpression})),await this.update()}async update(){un(this,Pt,await Q(this,we,"f").stringOrTemplateObjectToSubjectClass(this),"f");let t=Object.entries(this);for(let[e,r]of t)if(r!=null)if(r?.action)switch(r.action){case"setter":await this.setCollectionSetter(e,r.value);break;case"adder":await this.setCollectionAdder(e,r.value);break;case"remover":await this.setCollectionRemover(e,r.value);default:await this.setCollectionSetter(e,r.value);break}else Array.isArray(r)&&r.length>0?await this.setCollectionSetter(e,r):r!=null&&r!==""&&await this.setProperty(e,r);await this.getData()}async get(){return un(this,Pt,await Q(this,we,"f").stringOrTemplateObjectToSubjectClass(this),"f"),await this.getData()}async delete(){await Q(this,we,"f").removeSubject(this,Q(this,tt,"f"))}static async all(t){let e=await t.stringOrTemplateObjectToSubjectClass(this),r=await t.getAllSubjectProxies(e),n=[];if(r){for(let i of r){let a=new this(t,i.X);n.push(await a.get())}return n}return[]}static async query(t,e){let r=e?.source||"ad4m://self",n=await t.stringOrTemplateObjectToSubjectClass(this),i=[],a=`subject_class("${n}", C), instance(C, Base), link("${r}", Predicate, Base, Timestamp, Author)`;if(e){if(e.where)if(e.where.condition)a+=", "+e.where.condition;else{let s=Object.entries(e.where);for(let u of s){let c=u[0],l=u[1];a+=`, property_getter(C, Base, "${c}", "${l}")`}}try{if((await t.infer(`findall([Timestamp, Base], (${a}), AllData), sort(AllData, SortedData), length(SortedData, DataLength).`))[0].DataLength>=e.size){let u=`findall([Timestamp, Base], (${a}), AllData), sort(AllData, SortedData), reverse(SortedData, ReverseSortedData), paginate(ReverseSortedData, ${e.page}, ${e.size}, PageData).`;i=await t.infer(u),i=i[0].PageData.map(c=>({Base:c[1],Timestamp:c[0]}))}else i=await t.infer(a)}catch(s){console.log("Query failed",s)}}else i=await t.infer(a);return i?await Promise.all(i.map(async s=>await new this(t,s.Base).get())):[]}};tt=new WeakMap,Pt=new WeakMap,as=new WeakMap,we=new WeakMap;var Ls="0.10.1-rc9-dev5";var fr=12e3;function N2(){let t=new AbortController;return setTimeout(()=>t.abort(),20),t}function $s(t,e=1e4){return pe(this,null,function*(){return Promise.race([new Promise((r,n)=>{try{t.includes("localhost")||r(new WebSocket(t));let i=new WebSocket(t);i.onopen=()=>{r(i)},i.onerror=a=>{n(a)}}catch(i){n(i)}}),new Promise((r,n)=>{setTimeout(()=>{n(new Error("WebSocket connection timed out"))},e)})])})}function bl(t){return pe(this,null,function*(){try{let e=yield fetch(`http://localhost:${t}/graphql/`,{signal:N2().signal,mode:"cors"});if(e.status===400||e.status===0||e.status===200)return t;throw new Error(`Could not connect to port ${t}`)}catch(e){throw new Error(`Could not connect to port ${t}`)}})}function R2(){return new Promise((t,e)=>{let r=document.querySelector("ad4m-connect"),n=r==null?void 0:r.getAd4mClient();n?t(n):e("No Ad4mClient found")})}function _l(){try{localStorage.setItem("test",""),localStorage.removeItem("test")}catch(t){return!1}return!0}function Fs(t,e){_l()&&localStorage.setItem(`${Ls}/${t}`,e)}function Jt(t){return _l()?localStorage.getItem(`${Ls}/${t}`):null}function wl(t){_l()&&localStorage.removeItem(`${Ls}/${t}`)}var P2=t=>{let e=new Set;do for(let r of Reflect.ownKeys(t))e.add([t,r]);while((t=Reflect.getPrototypeOf(t))&&t!==Object.prototype);return e};function ja(t,{include:e,exclude:r}={}){let n=i=>{let a=o=>typeof o=="string"?i===o:o.test(i);return e?e.some(a):r?!r.some(a):!0};for(let[i,a]of P2(t.constructor.prototype)){if(a==="constructor"||!n(a))continue;let o=Reflect.getOwnPropertyDescriptor(i,a);o&&typeof o.value=="function"&&(t[a]=t[a].bind(t))}return t}var qa=class{constructor({appName:e,appDesc:r,appIconPath:n,appUrl:i,appDomain:a,capabilities:o,port:s,token:u,url:c,hosting:l}){this.activeSocket=null;this.requestedRestart=!1;this.authState="unauthenticated";this.connectionState="not_connected";this.port=fr;this.capabilities=[];this.isHosting=!1;this.listeners={authstatechange:[],configstatechange:[],connectionstatechange:[]};ja(this);this.appName=e,this.appDesc=r,this.appDomain=a,this.appUrl=i,this.appIconPath=n,this.capabilities=o,this.port=s||this.port,this.url=c||`ws://localhost:${this.port}/graphql`,this.token=u||this.token,this.isHosting=l||!1,this.buildClient()}notifyConfigChange(e,r){this.listeners.configstatechange.forEach(n=>{n(e,r)})}notifyConnectionChange(e){this.connectionState!==e&&(this.connectionState=e,this.listeners.connectionstatechange.forEach(r=>{r(e)}))}notifyAuthChange(e){this.authState!==e&&(this.authState=e,this.listeners.authstatechange.forEach(r=>{r(e)}))}setPort(e){this.port!==e&&(this.port=e,this.setUrl(`ws://localhost:${this.port}/graphql`),this.notifyConfigChange("port",e))}setUrl(e){this.url!==e&&(this.url=e,this.notifyConfigChange("url",e))}setToken(e){this.token!==e&&(this.token=e,this.notifyConfigChange("token",e))}on(e,r){this.listeners[e].push(r)}connect(e){return pe(this,null,function*(){try{if(e){yield $s(e),this.setUrl(e);let r=this.buildClient();return yield this.checkAuth(),r}else{this.notifyConnectionChange("checking_local");try{yield $s(`ws://localhost:${this.port}/graphql`,2e3);let r=this.buildClient();return yield this.checkAuth(),r}catch(r){let n=yield this.ensureConnection();return yield this.checkAuth(),n}}}catch(r){this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}})}loginToHosting(e,r){return pe(this,null,function*(){try{let n=yield fetch("https://hosting.ad4m.dev/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,password:r})});if(n.status===200){let i=yield n.json();localStorage.setItem("hosting_token",i.token);let a=localStorage.getItem("hosting_token"),o=yield fetch("https://hosting.ad4m.dev/api/service/info",{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer "+a}});if(o.status===200){let s=yield o.json();if(s.serviceId)if(this.setPort(s.port),this.setUrl(s.url),this.isHosting=!0,Fs("ad4mhosting","true"),!s.paused)this.connect();else throw new Error("Hosting is not running")}}else if((yield n.json()).message==="Passwords did not match")throw new Error("Passwords did not match")}catch(n){throw console.log(n),new Error(`Error logging in ${n}`)}})}checkEmail(e){return pe(this,null,function*(){try{return(yield fetch(`https://hosting.ad4m.dev/api/auth/check-email?email=${e}`,{method:"GET",headers:{"Content-Type":"application/json"}})).status===200}catch(r){console.log(r)}})}connectToPort(e){return pe(this,null,function*(){try{if(e){let r=yield bl(e);return this.setPort(r),this.buildClient()}else if(this.url.includes("localhost")){let r=yield this.findPort();return this.setPort(r),this.buildClient()}}catch(r){this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}})}ensureConnection(){return pe(this,null,function*(){var r,n;if(((r=this.activeSocket)==null?void 0:r.readyState)===WebSocket.OPEN&&((n=this.activeSocket)==null?void 0:n.url)===this.url&&this.ad4mClient)return this.ad4mClient;try{return this.notifyConnectionChange("connecting"),yield $s(this.url),this.buildClient()}catch(i){return this.notifyConnectionChange("not_connected"),this.connectToPort()}})}findPort(){return pe(this,null,function*(){let e=[...Array(10).keys()].map((i,a)=>bl(fr+a)),n=(yield Promise.allSettled(e)).find(i=>i.status==="fulfilled");if(n)return n.value;throw Error("Couldn't find an open port")})}buildClient(){this.notifyConnectionChange("connecting");try{let e=new WebSocket(this.url)}catch(e){this.notifyConnectionChange("not_connected");return}return this.apolloClient&&this.wsClient&&(this.requestedRestart=!0,this.wsClient.dispose(),this.apolloClient.stop(),this.wsClient=null,this.apolloClient=null),this.wsClient=Yp({url:this.url,connectionParams:()=>pe(this,null,function*(){return{headers:{authorization:this.token}}}),on:{opened:e=>{this.activeSocket=e},error:e=>{this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")},connected:()=>{this.notifyConnectionChange("connected"),this.checkAuth()},closed:e=>pe(this,null,function*(){if(console.log("buildClient closed:",e),!e.wasClean&&!this.requestedRestart)if(!this.token)this.notifyConnectionChange(this.token?"disconnected":"not_connected"),this.notifyAuthChange("unauthenticated"),this.requestedRestart=!1;else{let r=yield this.connect();r?this.ad4mClient=r:(this.notifyConnectionChange(this.token?"disconnected":"not_connected"),this.notifyAuthChange("unauthenticated"),this.requestedRestart=!1)}})}}),this.apolloClient=new fu({link:new Jp(this.wsClient),cache:new To({resultCaching:!1,addTypename:!1}),defaultOptions:{watchQuery:{fetchPolicy:"no-cache"},query:{fetchPolicy:"no-cache"},mutate:{fetchPolicy:"no-cache"}}}),this.ad4mClient=new Ss(this.apolloClient),this.ad4mClient}checkAuth(){return pe(this,null,function*(){try{return(yield this.ad4mClient.agent.isLocked())?this.notifyAuthChange("locked"):(yield this.ad4mClient.agent.status(),this.notifyAuthChange("authenticated")),!0}catch(e){return e.message==="Socket closed with event 4500 Cannot extractByTags from a ciphered wallet. You must unlock first."?(this.notifyAuthChange("locked"),!0):(this.notifyAuthChange("unauthenticated"),!1)}})}requestCapability(e=!1){return pe(this,null,function*(){var r;if(e&&this.setToken(null),this.isHosting){let n=localStorage.getItem("hosting_token");(yield fetch("https://hosting.ad4m.dev/api/service/checkStatus",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+n}})).status!==200&&console.error("Looks like the client is not running you might not recieve the mail with the code, please check your dashboard logs.")}return this.requestId=yield(r=this.ad4mClient)==null?void 0:r.agent.requestCapability({appName:this.appName,appDesc:this.appDesc,appUrl:this.appUrl,appIconPath:this.appIconPath,appDomain:this.appDomain,capabilities:this.capabilities}),this.requestId})}verifyCode(e){return pe(this,null,function*(){var r;try{let n=yield(r=this.ad4mClient)==null?void 0:r.agent.generateJwt(this.requestId,e);return this.setToken(n),yield this.buildClient(),yield this.checkAuth(),this.token}catch(n){throw new Error("Invalid code")}})}clearState(){this.setToken(null),this.setPort(fr),this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}};function Sl({unlockAgent:t,reconnect:e}){return B`
1371
1371
  <div class="text-center">
1372
1372
  <div class="items">
1373
1373
  <div>
@@ -2141,7 +2141,7 @@ input VoiceActivityParamsInput {
2141
2141
  width: 100vw;
2142
2142
  object-fit: cover;
2143
2143
  }
2144
- `,ce=class extends mr{constructor(){super(...arguments);this._code=null;this._isMobile=null;this._hasClickedDownload=null;this._isRemote=!1;this._isOpen=!1;this._hostingStep=0;this._email="";this._passowrd="";this._passwordError=null;this._hostingNotRunningError=null;this._verifyCodeError=null;this._isHostingLoading=!1;this.uiState="start";this.appName=null;this.appDesc=null;this.appDomain=null;this.appIconPath=null;this.mobile=null;this.capabilities=[];this.hosting=Jt("ad4mhosting")==="true"||!1;this.token=Jt("ad4mToken")||"";this.port=parseInt(Jt("ad4mport"))||fr;this.url=Jt("ad4murl")||""}get authState(){return this._client.authState}get connectionState(){return this._client.connectionState}injectFont(){let r=document.createElement("link");r.setAttribute("rel","stylesheet"),r.setAttribute("href","https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&display=swap"),document.head.appendChild(r)}connectedCallback(){super.connectedCallback(),ja(this),this.injectFont(),this._isMobile=L2(),this._client=new qa({appName:this.appName,appDesc:this.appDesc,appDomain:this.appDomain,appUrl:window.location.origin,appIconPath:this.appIconPath,capabilities:Array.isArray(this.capabilities)?this.capabilities:JSON.parse(this.capabilities),port:this.port||parseInt(Jt("ad4mport"))||fr,token:this.token||Jt("ad4mtoken"),url:this.url||Jt("ad4murl"),hosting:this.hosting}),this._client.on("configstatechange",this.handleConfigChange),this._client.on("authstatechange",this.handleAuthChange),this._client.on("connectionstatechange",this.handleConnectionChange),this.loadFont(),this._client.connect()}checkEmail(){return pe(this,null,function*(){try{(yield this._client.checkEmail(this._email))?this._hostingStep=1:this._hostingStep=2}catch(r){console.log(r)}})}loginToHosting(){return pe(this,null,function*(){try{yield this._client.loginToHosting(this._email,this._passowrd),this.changeUIState("connected")}catch(r){r.message.includes("Passwords did not match")?this._passwordError="Passwords did not match":this._hostingNotRunningError="Hosting is not running"}})}changeEmail(r){this._email=r}changePassword(r){this._passowrd=r}unlockAgent(r,n=!0){return pe(this,null,function*(){yield this._client.ad4mClient.agent.unlock(r,n)})}verifyCode(r){return pe(this,null,function*(){try{yield this._client.verifyCode(r)}catch(n){this._verifyCodeError="Invalid code"}})}changeUrl(r){r!==this._client.url&&(wl("ad4mtoken"),this._client.setToken(null)),this._client.setUrl(r)}changePort(r){this._client.setPort(r)}changeUIState(r){this.uiState=r,this.requestUpdate()}setIsHostingRunning(r){this._hostingNotRunningError=r}changeIsRemote(r){this._isRemote=r}changeCode(r){this._code=r}onDownloaded(){this._hasClickedDownload=!0}handleAuthChange(r){let n=new CustomEvent("authstatechange",{detail:r});r==="locked"&&(this._isOpen=!0),r==="authenticated"&&(this._isOpen=!1),this.dispatchEvent(n),this.requestUpdate()}handleConfigChange(r,n){this[r]=n,n?Fs("ad4m"+r,n):wl("ad4m"+r),this.requestUpdate()}handleConnectionChange(r){if(r==="checking_local"){this._isOpen=!1;return}r==="connected"&&(this.authState!=="authenticated"?(this.changeUIState("requestcap"),this._isOpen=!0):(this.changeUIState("connected"),this._isOpen=!1)),r==="disconnected"&&(this._isOpen=!0),r==="not_connected"&&(this._isOpen=!0,this.changeUIState("start"));let n=new CustomEvent("connectionstatechange",{detail:r});this.dispatchEvent(n),this.requestUpdate()}loadFont(){let r=document.createElement("link");r.rel="stylesheet",r.type="text/css",r.crossOrigin="anonymous",r.href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&display=swap",document.head.appendChild(r)}startCamera(r){return pe(this,null,function*(){try{window.BarcodeDetector.getSupportedFormats()}catch(n){window.BarcodeDetector=dr}yield this.changeUIState("qr"),setTimeout(()=>pe(this,null,function*(){let n=this.shadowRoot.querySelector("video");if(!n)return;let i=yield navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:"environment"}});n.srcObject=i,n.autoplay=!0}),100)})}connect(){return pe(this,null,function*(){this._isOpen=!0,this.requestUpdate();let r=yield this._client.connect();try{let n=yield r.agent.status();n.isUnlocked&&n.isInitialized&&window.location.reload()}catch(n){console.warn(n)}return r})}getAd4mClient(){return this._client.ad4mClient}connectRemote(r){return pe(this,null,function*(){try{this.changeUrl(r);let n=yield this._client.connect(r),i=yield n.agent.status();return i.isUnlocked&&i.isInitialized||this.changeUIState("requestcap"),n}catch(n){this.changeUIState("requestcap"),this._isOpen=!0}})}requestCapability(r){return pe(this,null,function*(){try{yield this._client.requestCapability(r),this.changeUIState("verifycode")}catch(n){console.warn(n)}})}isAuthenticated(){return pe(this,null,function*(){return this._client.checkAuth()})}setOpen(r){this._isOpen=r}setHostingStep(r){this._hostingStep=r}clearState(){this.handleConfigChange("port",null),this.handleConfigChange("url",null),this.handleConfigChange("token",null),this.handleConnectionChange("not_connected"),this.handleAuthChange("unauthenticated"),this.changeUIState("start"),this._client.clearState()}renderViews(){if(this.connectionState==="connecting")return Tl();if(this.uiState==="hosting")return kl({email:this._email,password:this._passowrd,changeEmail:this.changeEmail,changePassword:this.changePassword,changeState:this.changeUIState,step:this._hostingStep,setHostingStep:this.setHostingStep,login:this.loginToHosting,checkEmail:this.checkEmail,passwordError:this._passwordError,isHostingRunning:this._hostingNotRunningError,setIsHostingRunning:this.setIsHostingRunning});if(this.uiState==="qr")return Ol({changeState:this.changeUIState,onSuccess:r=>{this.changeUrl(r),this._client.connect(r)},uiState:this.uiState});if(this.authState==="locked")return Sl({unlockAgent:this.unlockAgent,reconnect:this.connect});if(this.uiState==="settings")return Dl({port:this.port,changePort:this.changePort,isRemote:this._isRemote,changeIsRemote:this.changeIsRemote,url:this.url,changeState:this.changeUIState,changeUrl:this.changeUrl,connectToPort:this._client.connectToPort,connectRemote:this.connectRemote,clearState:this.clearState});if(this.connectionState==="not_connected")return Nl({scanQrcode:this.startCamera,connect:this.connect,isMobile:this._isMobile,hasClickedDownload:this._hasClickedDownload,onDownloaded:this.onDownloaded,changeState:this.changeUIState,hosting:this.hosting});if(this.connectionState==="connected")return this.uiState==="verifycode"?Rl({code:this._code,changeCode:this.changeCode,changeState:this.changeUIState,verifyCode:this.verifyCode,isHosting:this._client.isHosting,verifyCodeError:this._verifyCodeError}):Il({changeState:this.changeUIState,requestCapability:this.requestCapability,capabilities:this.capabilities,appname:this.appName,setOpen:this.setOpen,appiconpath:this.appIconPath});if(this.connectionState==="disconnected")return El({reconnect:this.connect});if(this.connectionState==="port_not_found")return Cl()}mobileView(){return this.mobile?Al({openModal:()=>{this.changeUIState("settings"),this._isOpen=!this._isOpen}}):null}render(){return console.log(this.authState,this.connectionState,this.uiState,this._isOpen),this._isOpen===!1?this.authState==="authenticated"?this.mobileView():null:B`
2144
+ `,ce=class extends mr{constructor(){super(...arguments);this._code=null;this._isMobile=null;this._hasClickedDownload=null;this._isRemote=!1;this._isOpen=!1;this._hostingStep=0;this._email="";this._passowrd="";this._passwordError=null;this._hostingNotRunningError=null;this._verifyCodeError=null;this._isHostingLoading=!1;this.uiState="start";this.appName=null;this.appDesc=null;this.appDomain=null;this.appIconPath=null;this.mobile=null;this.capabilities=[];this.hosting=Jt("ad4mhosting")==="true"||!1;this.token=Jt("ad4mToken")||"";this.port=parseInt(Jt("ad4mport"))||fr;this.url=Jt("ad4murl")||""}get authState(){return this._client.authState}get connectionState(){return this._client.connectionState}injectFont(){let r=document.createElement("link");r.setAttribute("rel","stylesheet"),r.setAttribute("href","https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,200..800&display=swap"),document.head.appendChild(r)}connectedCallback(){super.connectedCallback(),ja(this),this.injectFont(),this._isMobile=L2(),this._client=new qa({appName:this.appName,appDesc:this.appDesc,appDomain:this.appDomain,appUrl:window.location.origin,appIconPath:this.appIconPath,capabilities:Array.isArray(this.capabilities)?this.capabilities:JSON.parse(this.capabilities),port:this.port||parseInt(Jt("ad4mport"))||fr,token:this.token||Jt("ad4mtoken"),url:this.url||Jt("ad4murl"),hosting:this.hosting}),this._client.on("configstatechange",this.handleConfigChange),this._client.on("authstatechange",this.handleAuthChange),this._client.on("connectionstatechange",this.handleConnectionChange),this.loadFont(),this._client.connect()}checkEmail(){return pe(this,null,function*(){try{(yield this._client.checkEmail(this._email))?this._hostingStep=1:this._hostingStep=2}catch(r){console.log(r)}})}loginToHosting(){return pe(this,null,function*(){try{yield this._client.loginToHosting(this._email,this._passowrd),this.changeUIState("connected")}catch(r){r.message.includes("Passwords did not match")?this._passwordError="Passwords did not match":this._hostingNotRunningError="Hosting is not running"}})}changeEmail(r){this._email=r}changePassword(r){this._passowrd=r}unlockAgent(r,n=!0){return pe(this,null,function*(){yield this._client.ad4mClient.agent.unlock(r,n)})}verifyCode(r){return pe(this,null,function*(){try{yield this._client.verifyCode(r)}catch(n){this._verifyCodeError="Invalid code"}})}changeUrl(r){r!==this._client.url&&(wl("ad4mtoken"),this._client.setToken(null)),this._client.setUrl(r)}changePort(r){this._client.setPort(r)}changeUIState(r){this.uiState=r}setIsHostingRunning(r){this._hostingNotRunningError=r}changeIsRemote(r){this._isRemote=r}changeCode(r){this._code=r}onDownloaded(){this._hasClickedDownload=!0}handleAuthChange(r){let n=new CustomEvent("authstatechange",{detail:r});r==="locked"&&(this._isOpen=!0),r==="authenticated"&&(this._isOpen=!1),this.dispatchEvent(n),this.requestUpdate()}handleConfigChange(r,n){this[r]=n,n?Fs("ad4m"+r,n):wl("ad4m"+r),this.requestUpdate()}handleConnectionChange(r){if(r==="checking_local"){this._isOpen=!1;return}r==="connected"&&(this.authState!=="authenticated"?(this.changeUIState("requestcap"),this._isOpen=!0):(this.changeUIState("connected"),this._isOpen=!1)),r==="disconnected"&&(this._isOpen=!0),r==="not_connected"&&(this._isOpen=!0,this.changeUIState("start"));let n=new CustomEvent("connectionstatechange",{detail:r});this.dispatchEvent(n),this.requestUpdate()}loadFont(){let r=document.createElement("link");r.rel="stylesheet",r.type="text/css",r.crossOrigin="anonymous",r.href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&display=swap",document.head.appendChild(r)}startCamera(r){return pe(this,null,function*(){try{window.BarcodeDetector.getSupportedFormats()}catch(n){window.BarcodeDetector=dr}yield this.changeUIState("qr"),setTimeout(()=>pe(this,null,function*(){let n=this.shadowRoot.querySelector("video");if(!n)return;let i=yield navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:"environment"}});n.srcObject=i,n.autoplay=!0}),100)})}connect(){return pe(this,null,function*(){this._isOpen=!0,this.requestUpdate();let r=yield this._client.connect();try{let n=yield r.agent.status();n.isUnlocked&&n.isInitialized&&window.location.reload()}catch(n){console.warn(n)}return r})}getAd4mClient(){return this._client.ad4mClient}connectRemote(r){return pe(this,null,function*(){try{this.changeUrl(r);let n=yield this._client.connect(r),i=yield n.agent.status();return i.isUnlocked&&i.isInitialized||this.changeUIState("requestcap"),n}catch(n){this.changeUIState("requestcap"),this._isOpen=!0}})}requestCapability(r){return pe(this,null,function*(){try{yield this._client.requestCapability(r),this.changeUIState("verifycode")}catch(n){console.warn(n)}})}isAuthenticated(){return pe(this,null,function*(){return this._client.checkAuth()})}setOpen(r){this._isOpen=r}setHostingStep(r){this._hostingStep=r}clearState(){this.handleConfigChange("port",null),this.handleConfigChange("url",null),this.handleConfigChange("token",null),this.handleConnectionChange("not_connected"),this.handleAuthChange("unauthenticated"),this.changeUIState("start"),this._client.clearState()}renderViews(){if(this.connectionState==="connecting")return Tl();if(this.uiState==="hosting")return kl({email:this._email,password:this._passowrd,changeEmail:this.changeEmail,changePassword:this.changePassword,changeState:this.changeUIState,step:this._hostingStep,setHostingStep:this.setHostingStep,login:this.loginToHosting,checkEmail:this.checkEmail,passwordError:this._passwordError,isHostingRunning:this._hostingNotRunningError,setIsHostingRunning:this.setIsHostingRunning});if(this.uiState==="qr")return Ol({changeState:this.changeUIState,onSuccess:r=>{this.changeUrl(r),this._client.connect(r)},uiState:this.uiState});if(this.authState==="locked")return Sl({unlockAgent:this.unlockAgent,reconnect:this.connect});if(this.uiState==="settings")return Dl({port:this.port,changePort:this.changePort,isRemote:this._isRemote,changeIsRemote:this.changeIsRemote,url:this.url,changeState:this.changeUIState,changeUrl:this.changeUrl,connectToPort:this._client.connectToPort,connectRemote:this.connectRemote,clearState:this.clearState});if(this.connectionState==="not_connected")return Nl({scanQrcode:this.startCamera,connect:this.connect,isMobile:this._isMobile,hasClickedDownload:this._hasClickedDownload,onDownloaded:this.onDownloaded,changeState:this.changeUIState,hosting:this.hosting});if(this.connectionState==="connected")return this.uiState==="verifycode"?Rl({code:this._code,changeCode:this.changeCode,changeState:this.changeUIState,verifyCode:this.verifyCode,isHosting:this._client.isHosting,verifyCodeError:this._verifyCodeError}):Il({changeState:this.changeUIState,requestCapability:this.requestCapability,capabilities:this.capabilities,appname:this.appName,setOpen:this.setOpen,appiconpath:this.appIconPath});if(this.connectionState==="disconnected")return El({reconnect:this.connect});if(this.connectionState==="port_not_found")return Cl()}mobileView(){return this.mobile?Al({openModal:()=>{this.changeUIState("settings"),this._isOpen=!this._isOpen}}):null}render(){return console.log(this.authState,this.connectionState,this.uiState,this._isOpen),this._isOpen===!1?this.authState==="authenticated"?this.mobileView():null:B`
2145
2145
  <div class="wrapper">
2146
2146
  <div class="dialog">
2147
2147
  ${xl()}
package/package.json CHANGED
@@ -66,5 +66,5 @@
66
66
  "esbuild-plugin-replace": "^1.4.0",
67
67
  "lit": "^2.3.1"
68
68
  },
69
- "version": "0.10.1-rc9-dev5"
69
+ "version": "0.10.1-rc9-dev6"
70
70
  }