@coasys/ad4m-connect 0.11.2-dev-multi-user → 0.11.2-dev-multi-user-2

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
@@ -1518,6 +1518,6 @@ WHERE ${l.join(" AND ")}
1518
1518
  - options.namespace
1519
1519
  - schema["x-ad4m"].namespace
1520
1520
  - schema.title
1521
- - valid schema.$id`)}static determinePredicate(t,e,r,n,i){if(i.propertyMapping?.[e])return i.propertyMapping[e];if(r["x-ad4m"]?.through)return r["x-ad4m"].through;if(i.predicateTemplate){let o=Sd(n),[s,u]=o.includes("://")?o.split("://"):["",o],c=u||"";return i.predicateTemplate.replace("${namespace}",c).replace("${scheme}",s).replace("${ns}",c).replace("${title}",t.title||"").replace("${property}",e)}if(i.predicateGenerator)return i.predicateGenerator(t.title||"",e);let a=Sd(n);return a.includes("://")?`${a}${e}`:`${a}://${e}`}static getPropertyOption(t,e,r,n,i){return r.propertyOptions?.[t]?.[n]!==void 0?r.propertyOptions[t][n]:e["x-ad4m"]?.[n]!==void 0?e["x-ad4m"][n]:r[n]!==void 0?r[n]:i}static getDefaultValueForType(t){switch(t){case"string":return"";case"number":return 0;case"integer":return 0;case"boolean":return!1;case"array":return[];case"object":return{};default:return""}}};pt=new WeakMap,Yt=new WeakMap,cs=new WeakMap,xe=new WeakMap;_Ad4mModel.classNamesByClass=new WeakMap;var zu=class{constructor(e,r,n){this.queryParams={},this.modelClassName=null,this.useSurrealDBFlag=!0,this.perspective=e,this.ctor=r,n&&(this.queryParams=n)}dispose(){this.currentSubscription&&(this.currentSubscription.dispose(),this.currentSubscription=void 0)}where(e){return this.queryParams.where=e,this}order(e){return this.queryParams.order=e,this}limit(e){return this.queryParams.limit=e,this}offset(e){return this.queryParams.offset=e,this}source(e){return this.queryParams.source=e,this}properties(e){return this.queryParams.properties=e,this}collections(e){return this.queryParams.collections=e,this}overrideModelClassName(e){return this.modelClassName=e,this}useSurrealDB(e=!0){return this.useSurrealDBFlag=e,this}async get(){if(this.useSurrealDBFlag){let e=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams),r=await this.perspective.querySurrealDB(e),{results:n}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,r);return n}else{let e=await this.ctor.queryToProlog(this.perspective,this.queryParams,this.modelClassName),r=await this.perspective.infer(e),{results:n}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,r);return n}}async subscribe(e){if(this.dispose(),this.useSurrealDBFlag){let r=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams);this.currentSubscription=await this.perspective.subscribeSurrealDB(r);let n=async a=>{let{results:o}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,a);e(o)};this.currentSubscription.onResult(n);let{results:i}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,this.currentSubscription.result);return i}else{let r=await this.ctor.queryToProlog(this.perspective,this.queryParams,this.modelClassName);this.currentSubscription=await this.perspective.subscribeInfer(r);let n=async a=>{let{results:o}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,a);e(o)};this.currentSubscription.onResult(n);let{results:i}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,this.currentSubscription.result);return i}}async count(){if(this.useSurrealDBFlag){let e=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams),r=await this.perspective.querySurrealDB(e),{totalCount:n}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,r);return n}else{let e=await this.ctor.countQueryToProlog(this.perspective,this.queryParams,this.modelClassName);return(await this.perspective.infer(e))?.[0]?.TotalCount||0}}async countSubscribe(e){if(this.dispose(),this.useSurrealDBFlag){let r=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams);this.currentSubscription=await this.perspective.subscribeSurrealDB(r);let n=async a=>{let{totalCount:o}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,a);e(o)};this.currentSubscription.onResult(n);let{totalCount:i}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,this.currentSubscription.result);return i}else{let r=await this.ctor.countQueryToProlog(this.perspective,this.queryParams,this.modelClassName);this.currentSubscription=await this.perspective.subscribeInfer(r);let n=async i=>{let a=i?.[0]?.TotalCount||0;e(a)};return this.currentSubscription.onResult(n),this.currentSubscription.result?.[0]?.TotalCount||0}}async paginate(e,r){let n={...this.queryParams||{},limit:e,offset:e*(r-1),count:!0};if(this.useSurrealDBFlag){let i=await this.ctor.queryToSurrealQL(this.perspective,n),a=await this.perspective.querySurrealDB(i),{results:o,totalCount:s}=await this.ctor.instancesFromSurrealResult(this.perspective,n,a);return{results:o,totalCount:s,pageSize:e,pageNumber:r}}else{let i=await this.ctor.queryToProlog(this.perspective,n,this.modelClassName),a=await this.perspective.infer(i),{results:o,totalCount:s}=await this.ctor.instancesFromPrologResult(this.perspective,n,a);return{results:o,totalCount:s,pageSize:e,pageNumber:r}}}async paginateSubscribe(e,r,n){this.dispose();let i={...this.queryParams||{},limit:e,offset:e*(r-1),count:!0};if(this.useSurrealDBFlag){let a=await this.ctor.queryToSurrealQL(this.perspective,i);this.currentSubscription=await this.perspective.subscribeSurrealDB(a);let o=async c=>{let{results:l,totalCount:d}=await this.ctor.instancesFromSurrealResult(this.perspective,i,c);n({results:l,totalCount:d,pageSize:e,pageNumber:r})};this.currentSubscription.onResult(o);let{results:s,totalCount:u}=await this.ctor.instancesFromSurrealResult(this.perspective,i,this.currentSubscription.result);return{results:s,totalCount:u,pageSize:e,pageNumber:r}}else{let a=await this.ctor.queryToProlog(this.perspective,i,this.modelClassName);this.currentSubscription=await this.perspective.subscribeInfer(a);let o=async c=>{let{results:l,totalCount:d}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,c);n({results:l,totalCount:d,pageSize:e,pageNumber:r})};this.currentSubscription.onResult(o);let{results:s,totalCount:u}=await this.ctor.instancesFromPrologResult(this.perspective,i,this.currentSubscription.result);return{results:s,totalCount:u,pageSize:e,pageNumber:r}}}};var Ih="0.11.2-dev-multi-user";var qs=12e3;function U_(){let t=new AbortController;return setTimeout(()=>t.abort(),20),t}function Ga(t,e=1e4){return We(this,null,function*(){return Promise.race([new Promise((r,n)=>{let i;try{i=new WebSocket(t,"graphql-transport-ws"),i.onopen=()=>{i.close(),r(i)},i.onerror=a=>{n(a)},i.onclose=a=>{a.code!==1e3&&n(new Error(`WebSocket closed with code ${a.code}: ${a.reason}`))}}catch(a){i&&i.close(),n(a)}}),new Promise((r,n)=>{setTimeout(()=>{n(new Error("WebSocket connection timed out"))},e)})])})}function cl(t){return We(this,null,function*(){try{let e=yield fetch(`http://localhost:${t}/graphql/`,{signal:U_().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 q_(){try{localStorage.setItem("test",""),localStorage.removeItem("test")}catch(t){return!1}return!0}function Th(t,e){q_()&&localStorage.setItem(`${Ih}/${t}`,e)}var B_=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 ul(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 B_(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 ll=class{constructor(e){this.activeSocket=null;this.requestedRestart=!1;this.authState="unauthenticated";this.connectionState="not_connected";this.port=qs;this.capabilities=[];this.isHosting=!1;this.listeners={authstatechange:[],configstatechange:[],connectionstatechange:[]};ul(this);this.options=e,this.appName=e.appName,this.appDesc=e.appDesc,this.appDomain=e.appDomain,this.appUrl=e.appUrl,this.appIconPath=e.appIconPath,this.capabilities=e.capabilities,this.port=e.port||this.port,this.url=e.url||`ws://localhost:${this.port}/graphql`,this.token=e.token||this.token,this.isHosting=e.hosting||!1}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)}buildTempClient(e){let r=Yc({url:e,connectionParams:()=>We(this,null,function*(){return{headers:{authorization:""}}})}),n=new No({link:new Zc(r),cache:new Yi({resultCaching:!1,addTypename:!1}),defaultOptions:{watchQuery:{fetchPolicy:"no-cache"},query:{fetchPolicy:"no-cache"}}});return new Ma(n)}connect(e){return We(this,null,function*(){try{if(e){yield Ga(e),this.setUrl(e);let r=this.buildClient();return yield this.checkAuth(),r}else{let r=`ws://localhost:${this.port}/graphql`;yield Ga(r),this.setUrl(r);let n=this.buildClient();return yield this.checkAuth(),n}}catch(r){this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}})}connectMultiUser(){return We(this,null,function*(){try{let e=this.options.backendUrl;console.debug("[Ad4m Connect] Connecting to backend:",e),yield Ga(e),this.setUrl(e);let r=this.buildClient();console.debug("[Ad4m Connect] Built client:",r);let n;try{console.debug("[Ad4m Connect] Logging in user:",this.options.userEmail),n=yield r.agent.loginUser(this.options.userEmail,this.options.userPassword),console.debug("[Ad4m Connect] Login successful")}catch(a){console.debug("[Ad4m Connect] Login error:",a),console.debug("[Ad4m Connect] User does not exist, trying to create user:",this.options.userEmail);try{console.debug("[Ad4m Connect] Creating user:",this.options.userEmail);try{let o=yield r.agent.createUser(this.options.userEmail,this.options.userPassword);if(console.debug("[Ad4m Connect] Create result:",o),!o.success)throw new Error(o.error||"Failed to create user")}catch(o){console.log("[Ad4m Connect] Failed to create user:",o)}console.debug("[Ad4m Connect] Logging in user after creation:",this.options.userEmail),n=yield r.agent.loginUser(this.options.userEmail,this.options.userPassword),console.log("[Ad4m Connect] Successfully created and logged in user")}catch(o){throw new Error(`Failed to create/login user: ${o.message}`)}}this.setToken(n);let i=this.buildClient();return yield i.agent.status(),this.notifyAuthChange("authenticated"),this.notifyConnectionChange("connected"),i}catch(e){throw this.notifyConnectionChange("error"),this.notifyAuthChange("unauthenticated"),e}})}loginToHosting(e,r){return We(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,Th("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 We(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 We(this,null,function*(){try{if(e){let r=yield cl(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 We(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 Ga(this.url),this.buildClient()}catch(i){return this.notifyConnectionChange("not_connected"),this.connectToPort()}})}findPort(){return We(this,null,function*(){let e=[...Array(10).keys()].map((i,a)=>cl(qs+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,"graphql-transport-ws")}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=Yc({url:this.url,connectionParams:()=>We(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=>We(this,null,function*(){if(!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 No({link:new Zc(this.wsClient),cache:new Yi({resultCaching:!1,addTypename:!1}),defaultOptions:{watchQuery:{fetchPolicy:"no-cache"},query:{fetchPolicy:"no-cache"},mutate:{fetchPolicy:"no-cache"}}}),this.ad4mClient=new Ma(this.apolloClient),this.ad4mClient}checkAuth(){return We(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 We(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 We(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(qs),this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}};export{ll as default};
1521
+ - valid schema.$id`)}static determinePredicate(t,e,r,n,i){if(i.propertyMapping?.[e])return i.propertyMapping[e];if(r["x-ad4m"]?.through)return r["x-ad4m"].through;if(i.predicateTemplate){let o=Sd(n),[s,u]=o.includes("://")?o.split("://"):["",o],c=u||"";return i.predicateTemplate.replace("${namespace}",c).replace("${scheme}",s).replace("${ns}",c).replace("${title}",t.title||"").replace("${property}",e)}if(i.predicateGenerator)return i.predicateGenerator(t.title||"",e);let a=Sd(n);return a.includes("://")?`${a}${e}`:`${a}://${e}`}static getPropertyOption(t,e,r,n,i){return r.propertyOptions?.[t]?.[n]!==void 0?r.propertyOptions[t][n]:e["x-ad4m"]?.[n]!==void 0?e["x-ad4m"][n]:r[n]!==void 0?r[n]:i}static getDefaultValueForType(t){switch(t){case"string":return"";case"number":return 0;case"integer":return 0;case"boolean":return!1;case"array":return[];case"object":return{};default:return""}}};pt=new WeakMap,Yt=new WeakMap,cs=new WeakMap,xe=new WeakMap;_Ad4mModel.classNamesByClass=new WeakMap;var zu=class{constructor(e,r,n){this.queryParams={},this.modelClassName=null,this.useSurrealDBFlag=!0,this.perspective=e,this.ctor=r,n&&(this.queryParams=n)}dispose(){this.currentSubscription&&(this.currentSubscription.dispose(),this.currentSubscription=void 0)}where(e){return this.queryParams.where=e,this}order(e){return this.queryParams.order=e,this}limit(e){return this.queryParams.limit=e,this}offset(e){return this.queryParams.offset=e,this}source(e){return this.queryParams.source=e,this}properties(e){return this.queryParams.properties=e,this}collections(e){return this.queryParams.collections=e,this}overrideModelClassName(e){return this.modelClassName=e,this}useSurrealDB(e=!0){return this.useSurrealDBFlag=e,this}async get(){if(this.useSurrealDBFlag){let e=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams),r=await this.perspective.querySurrealDB(e),{results:n}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,r);return n}else{let e=await this.ctor.queryToProlog(this.perspective,this.queryParams,this.modelClassName),r=await this.perspective.infer(e),{results:n}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,r);return n}}async subscribe(e){if(this.dispose(),this.useSurrealDBFlag){let r=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams);this.currentSubscription=await this.perspective.subscribeSurrealDB(r);let n=async a=>{let{results:o}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,a);e(o)};this.currentSubscription.onResult(n);let{results:i}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,this.currentSubscription.result);return i}else{let r=await this.ctor.queryToProlog(this.perspective,this.queryParams,this.modelClassName);this.currentSubscription=await this.perspective.subscribeInfer(r);let n=async a=>{let{results:o}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,a);e(o)};this.currentSubscription.onResult(n);let{results:i}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,this.currentSubscription.result);return i}}async count(){if(this.useSurrealDBFlag){let e=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams),r=await this.perspective.querySurrealDB(e),{totalCount:n}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,r);return n}else{let e=await this.ctor.countQueryToProlog(this.perspective,this.queryParams,this.modelClassName);return(await this.perspective.infer(e))?.[0]?.TotalCount||0}}async countSubscribe(e){if(this.dispose(),this.useSurrealDBFlag){let r=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams);this.currentSubscription=await this.perspective.subscribeSurrealDB(r);let n=async a=>{let{totalCount:o}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,a);e(o)};this.currentSubscription.onResult(n);let{totalCount:i}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,this.currentSubscription.result);return i}else{let r=await this.ctor.countQueryToProlog(this.perspective,this.queryParams,this.modelClassName);this.currentSubscription=await this.perspective.subscribeInfer(r);let n=async i=>{let a=i?.[0]?.TotalCount||0;e(a)};return this.currentSubscription.onResult(n),this.currentSubscription.result?.[0]?.TotalCount||0}}async paginate(e,r){let n={...this.queryParams||{},limit:e,offset:e*(r-1),count:!0};if(this.useSurrealDBFlag){let i=await this.ctor.queryToSurrealQL(this.perspective,n),a=await this.perspective.querySurrealDB(i),{results:o,totalCount:s}=await this.ctor.instancesFromSurrealResult(this.perspective,n,a);return{results:o,totalCount:s,pageSize:e,pageNumber:r}}else{let i=await this.ctor.queryToProlog(this.perspective,n,this.modelClassName),a=await this.perspective.infer(i),{results:o,totalCount:s}=await this.ctor.instancesFromPrologResult(this.perspective,n,a);return{results:o,totalCount:s,pageSize:e,pageNumber:r}}}async paginateSubscribe(e,r,n){this.dispose();let i={...this.queryParams||{},limit:e,offset:e*(r-1),count:!0};if(this.useSurrealDBFlag){let a=await this.ctor.queryToSurrealQL(this.perspective,i);this.currentSubscription=await this.perspective.subscribeSurrealDB(a);let o=async c=>{let{results:l,totalCount:d}=await this.ctor.instancesFromSurrealResult(this.perspective,i,c);n({results:l,totalCount:d,pageSize:e,pageNumber:r})};this.currentSubscription.onResult(o);let{results:s,totalCount:u}=await this.ctor.instancesFromSurrealResult(this.perspective,i,this.currentSubscription.result);return{results:s,totalCount:u,pageSize:e,pageNumber:r}}else{let a=await this.ctor.queryToProlog(this.perspective,i,this.modelClassName);this.currentSubscription=await this.perspective.subscribeInfer(a);let o=async c=>{let{results:l,totalCount:d}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,c);n({results:l,totalCount:d,pageSize:e,pageNumber:r})};this.currentSubscription.onResult(o);let{results:s,totalCount:u}=await this.ctor.instancesFromPrologResult(this.perspective,i,this.currentSubscription.result);return{results:s,totalCount:u,pageSize:e,pageNumber:r}}}};var Ih="0.11.2-dev-multi-user-2";var qs=12e3;function U_(){let t=new AbortController;return setTimeout(()=>t.abort(),20),t}function Ga(t,e=1e4){return We(this,null,function*(){return Promise.race([new Promise((r,n)=>{let i;try{i=new WebSocket(t,"graphql-transport-ws"),i.onopen=()=>{i.close(),r(i)},i.onerror=a=>{n(a)},i.onclose=a=>{a.code!==1e3&&n(new Error(`WebSocket closed with code ${a.code}: ${a.reason}`))}}catch(a){i&&i.close(),n(a)}}),new Promise((r,n)=>{setTimeout(()=>{n(new Error("WebSocket connection timed out"))},e)})])})}function cl(t){return We(this,null,function*(){try{let e=yield fetch(`http://localhost:${t}/graphql/`,{signal:U_().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 q_(){try{localStorage.setItem("test",""),localStorage.removeItem("test")}catch(t){return!1}return!0}function Th(t,e){q_()&&localStorage.setItem(`${Ih}/${t}`,e)}var B_=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 ul(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 B_(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 ll=class{constructor(e){this.activeSocket=null;this.requestedRestart=!1;this.authState="unauthenticated";this.connectionState="not_connected";this.port=qs;this.capabilities=[];this.isHosting=!1;this.listeners={authstatechange:[],configstatechange:[],connectionstatechange:[]};ul(this);this.options=e,this.appName=e.appName,this.appDesc=e.appDesc,this.appDomain=e.appDomain,this.appUrl=e.appUrl,this.appIconPath=e.appIconPath,this.capabilities=e.capabilities,this.port=e.port||this.port,this.url=e.url||`ws://localhost:${this.port}/graphql`,this.token=e.token||this.token,this.isHosting=e.hosting||!1}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)}buildTempClient(e){let r=Yc({url:e,connectionParams:()=>We(this,null,function*(){return{headers:{authorization:""}}})}),n=new No({link:new Zc(r),cache:new Yi({resultCaching:!1,addTypename:!1}),defaultOptions:{watchQuery:{fetchPolicy:"no-cache"},query:{fetchPolicy:"no-cache"}}});return new Ma(n)}connect(e){return We(this,null,function*(){try{if(e){yield Ga(e),this.setUrl(e);let r=this.buildClient();return yield this.checkAuth(),r}else{let r=`ws://localhost:${this.port}/graphql`;yield Ga(r),this.setUrl(r);let n=this.buildClient();return yield this.checkAuth(),n}}catch(r){this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}})}connectMultiUser(){return We(this,null,function*(){try{let e=this.options.backendUrl;console.debug("[Ad4m Connect] Connecting to backend:",e),yield Ga(e),this.setUrl(e);let r=this.buildClient();console.debug("[Ad4m Connect] Built client:",r);let n;try{console.debug("[Ad4m Connect] Logging in user:",this.options.userEmail),n=yield r.agent.loginUser(this.options.userEmail,this.options.userPassword),console.debug("[Ad4m Connect] Login successful")}catch(a){console.debug("[Ad4m Connect] Login error:",a),console.debug("[Ad4m Connect] User does not exist, trying to create user:",this.options.userEmail);try{console.debug("[Ad4m Connect] Creating user:",this.options.userEmail);try{let o=yield r.agent.createUser(this.options.userEmail,this.options.userPassword);if(console.debug("[Ad4m Connect] Create result:",o),!o.success)throw new Error(o.error||"Failed to create user")}catch(o){console.log("[Ad4m Connect] Failed to create user:",o)}console.debug("[Ad4m Connect] Logging in user after creation:",this.options.userEmail),n=yield r.agent.loginUser(this.options.userEmail,this.options.userPassword),console.log("[Ad4m Connect] Successfully created and logged in user")}catch(o){throw new Error(`Failed to create/login user: ${o.message}`)}}this.setToken(n);let i=this.buildClient();return yield i.agent.status(),this.ad4mClient=i,this.notifyAuthChange("authenticated"),this.notifyConnectionChange("connected"),i}catch(e){throw this.notifyConnectionChange("error"),this.notifyAuthChange("unauthenticated"),e}})}loginToHosting(e,r){return We(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,Th("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 We(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 We(this,null,function*(){try{if(e){let r=yield cl(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 We(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 Ga(this.url),this.buildClient()}catch(i){return this.notifyConnectionChange("not_connected"),this.connectToPort()}})}findPort(){return We(this,null,function*(){let e=[...Array(10).keys()].map((i,a)=>cl(qs+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,"graphql-transport-ws")}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=Yc({url:this.url,connectionParams:()=>We(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=>We(this,null,function*(){if(!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 No({link:new Zc(this.wsClient),cache:new Yi({resultCaching:!1,addTypename:!1}),defaultOptions:{watchQuery:{fetchPolicy:"no-cache"},query:{fetchPolicy:"no-cache"},mutate:{fetchPolicy:"no-cache"}}}),this.ad4mClient=new Ma(this.apolloClient),this.ad4mClient}checkAuth(){return We(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 We(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 We(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(qs),this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}};export{ll as default};
1522
1522
  /*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */
1523
1523
  //! @fayeed - make it support node.js
package/dist/utils.js CHANGED
@@ -1 +1 @@
1
- var a=(e,t,o)=>new Promise((s,n)=>{var r=i=>{try{l(o.next(i))}catch(u){n(u)}},p=i=>{try{l(o.throw(i))}catch(u){n(u)}},l=i=>i.done?s(i.value):Promise.resolve(i.value).then(r,p);l((o=o.apply(e,t)).next())});var c="0.11.2-dev-multi-user";var h=12e3;function b(){let e=new AbortController;return setTimeout(()=>e.abort(),20),e}function j(e,t=1e4){return a(this,null,function*(){return Promise.race([new Promise((o,s)=>{let n;try{n=new WebSocket(e,"graphql-transport-ws"),n.onopen=()=>{n.close(),o(n)},n.onerror=r=>{s(r)},n.onclose=r=>{r.code!==1e3&&s(new Error(`WebSocket closed with code ${r.code}: ${r.reason}`))}}catch(r){n&&n.close(),s(r)}}),new Promise((o,s)=>{setTimeout(()=>{s(new Error("WebSocket connection timed out"))},t)})])})}function v(e){return a(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 y(){return new Promise((e,t)=>{let o=document.querySelector("ad4m-connect"),s=o==null?void 0:o.getAd4mClient();s?e(s):t("No Ad4mClient found")})}function S(e){let t=document.querySelector("ad4m-connect");t==null||t.addEventListener("authstatechange",o=>{e(o.detail)})}function x(){let e=navigator.userAgent,t="";return e.search("Windows")!==-1?t="Windows":e.search("Mac")!==-1?t="MacOS":e.search("X11")!==-1&&e.search("Linux")===-1?t="UNIX":e.search("Linux")!==-1&&e.search("X11")!==-1&&(t="Linux"),t}function d(){try{localStorage.setItem("test",""),localStorage.removeItem("test")}catch(e){return!1}return!0}function A(e,t){d()&&localStorage.setItem(`${c}/${e}`,t)}function C(e){return d()?localStorage.getItem(`${c}/${e}`):null}function $(e){d()&&localStorage.removeItem(`${c}/${e}`)}export{h as DEFAULT_PORT,v as checkPort,j as connectWebSocket,x as detectOS,y as getAd4mClient,C as getForVersion,S as onAuthStateChanged,$ as removeForVersion,A as setForVersion};
1
+ var a=(e,t,o)=>new Promise((s,n)=>{var r=i=>{try{l(o.next(i))}catch(u){n(u)}},p=i=>{try{l(o.throw(i))}catch(u){n(u)}},l=i=>i.done?s(i.value):Promise.resolve(i.value).then(r,p);l((o=o.apply(e,t)).next())});var c="0.11.2-dev-multi-user-2";var h=12e3;function b(){let e=new AbortController;return setTimeout(()=>e.abort(),20),e}function j(e,t=1e4){return a(this,null,function*(){return Promise.race([new Promise((o,s)=>{let n;try{n=new WebSocket(e,"graphql-transport-ws"),n.onopen=()=>{n.close(),o(n)},n.onerror=r=>{s(r)},n.onclose=r=>{r.code!==1e3&&s(new Error(`WebSocket closed with code ${r.code}: ${r.reason}`))}}catch(r){n&&n.close(),s(r)}}),new Promise((o,s)=>{setTimeout(()=>{s(new Error("WebSocket connection timed out"))},t)})])})}function v(e){return a(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 y(){return new Promise((e,t)=>{let o=document.querySelector("ad4m-connect"),s=o==null?void 0:o.getAd4mClient();s?e(s):t("No Ad4mClient found")})}function S(e){let t=document.querySelector("ad4m-connect");t==null||t.addEventListener("authstatechange",o=>{e(o.detail)})}function x(){let e=navigator.userAgent,t="";return e.search("Windows")!==-1?t="Windows":e.search("Mac")!==-1?t="MacOS":e.search("X11")!==-1&&e.search("Linux")===-1?t="UNIX":e.search("Linux")!==-1&&e.search("X11")!==-1&&(t="Linux"),t}function d(){try{localStorage.setItem("test",""),localStorage.removeItem("test")}catch(e){return!1}return!0}function A(e,t){d()&&localStorage.setItem(`${c}/${e}`,t)}function C(e){return d()?localStorage.getItem(`${c}/${e}`):null}function $(e){d()&&localStorage.removeItem(`${c}/${e}`)}export{h as DEFAULT_PORT,v as checkPort,j as connectWebSocket,x as detectOS,y as getAd4mClient,C as getForVersion,S as onAuthStateChanged,$ as removeForVersion,A as setForVersion};
package/dist/web.js CHANGED
@@ -1520,7 +1520,7 @@ WHERE ${l.join(" AND ")}
1520
1520
  - options.namespace
1521
1521
  - schema["x-ad4m"].namespace
1522
1522
  - schema.title
1523
- - valid schema.$id`)}static determinePredicate(t,e,r,n,i){if(i.propertyMapping?.[e])return i.propertyMapping[e];if(r["x-ad4m"]?.through)return r["x-ad4m"].through;if(i.predicateTemplate){let o=o1(n),[s,u]=o.includes("://")?o.split("://"):["",o],c=u||"";return i.predicateTemplate.replace("${namespace}",c).replace("${scheme}",s).replace("${ns}",c).replace("${title}",t.title||"").replace("${property}",e)}if(i.predicateGenerator)return i.predicateGenerator(t.title||"",e);let a=o1(n);return a.includes("://")?`${a}${e}`:`${a}://${e}`}static getPropertyOption(t,e,r,n,i){return r.propertyOptions?.[t]?.[n]!==void 0?r.propertyOptions[t][n]:e["x-ad4m"]?.[n]!==void 0?e["x-ad4m"][n]:r[n]!==void 0?r[n]:i}static getDefaultValueForType(t){switch(t){case"string":return"";case"number":return 0;case"integer":return 0;case"boolean":return!1;case"array":return[];case"object":return{};default:return""}}};_t=new WeakMap,or=new WeakMap,Qs=new WeakMap,De=new WeakMap;_Ad4mModel.classNamesByClass=new WeakMap;var Hl=class{constructor(e,r,n){this.queryParams={},this.modelClassName=null,this.useSurrealDBFlag=!0,this.perspective=e,this.ctor=r,n&&(this.queryParams=n)}dispose(){this.currentSubscription&&(this.currentSubscription.dispose(),this.currentSubscription=void 0)}where(e){return this.queryParams.where=e,this}order(e){return this.queryParams.order=e,this}limit(e){return this.queryParams.limit=e,this}offset(e){return this.queryParams.offset=e,this}source(e){return this.queryParams.source=e,this}properties(e){return this.queryParams.properties=e,this}collections(e){return this.queryParams.collections=e,this}overrideModelClassName(e){return this.modelClassName=e,this}useSurrealDB(e=!0){return this.useSurrealDBFlag=e,this}async get(){if(this.useSurrealDBFlag){let e=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams),r=await this.perspective.querySurrealDB(e),{results:n}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,r);return n}else{let e=await this.ctor.queryToProlog(this.perspective,this.queryParams,this.modelClassName),r=await this.perspective.infer(e),{results:n}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,r);return n}}async subscribe(e){if(this.dispose(),this.useSurrealDBFlag){let r=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams);this.currentSubscription=await this.perspective.subscribeSurrealDB(r);let n=async a=>{let{results:o}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,a);e(o)};this.currentSubscription.onResult(n);let{results:i}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,this.currentSubscription.result);return i}else{let r=await this.ctor.queryToProlog(this.perspective,this.queryParams,this.modelClassName);this.currentSubscription=await this.perspective.subscribeInfer(r);let n=async a=>{let{results:o}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,a);e(o)};this.currentSubscription.onResult(n);let{results:i}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,this.currentSubscription.result);return i}}async count(){if(this.useSurrealDBFlag){let e=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams),r=await this.perspective.querySurrealDB(e),{totalCount:n}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,r);return n}else{let e=await this.ctor.countQueryToProlog(this.perspective,this.queryParams,this.modelClassName);return(await this.perspective.infer(e))?.[0]?.TotalCount||0}}async countSubscribe(e){if(this.dispose(),this.useSurrealDBFlag){let r=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams);this.currentSubscription=await this.perspective.subscribeSurrealDB(r);let n=async a=>{let{totalCount:o}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,a);e(o)};this.currentSubscription.onResult(n);let{totalCount:i}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,this.currentSubscription.result);return i}else{let r=await this.ctor.countQueryToProlog(this.perspective,this.queryParams,this.modelClassName);this.currentSubscription=await this.perspective.subscribeInfer(r);let n=async i=>{let a=i?.[0]?.TotalCount||0;e(a)};return this.currentSubscription.onResult(n),this.currentSubscription.result?.[0]?.TotalCount||0}}async paginate(e,r){let n={...this.queryParams||{},limit:e,offset:e*(r-1),count:!0};if(this.useSurrealDBFlag){let i=await this.ctor.queryToSurrealQL(this.perspective,n),a=await this.perspective.querySurrealDB(i),{results:o,totalCount:s}=await this.ctor.instancesFromSurrealResult(this.perspective,n,a);return{results:o,totalCount:s,pageSize:e,pageNumber:r}}else{let i=await this.ctor.queryToProlog(this.perspective,n,this.modelClassName),a=await this.perspective.infer(i),{results:o,totalCount:s}=await this.ctor.instancesFromPrologResult(this.perspective,n,a);return{results:o,totalCount:s,pageSize:e,pageNumber:r}}}async paginateSubscribe(e,r,n){this.dispose();let i={...this.queryParams||{},limit:e,offset:e*(r-1),count:!0};if(this.useSurrealDBFlag){let a=await this.ctor.queryToSurrealQL(this.perspective,i);this.currentSubscription=await this.perspective.subscribeSurrealDB(a);let o=async c=>{let{results:l,totalCount:f}=await this.ctor.instancesFromSurrealResult(this.perspective,i,c);n({results:l,totalCount:f,pageSize:e,pageNumber:r})};this.currentSubscription.onResult(o);let{results:s,totalCount:u}=await this.ctor.instancesFromSurrealResult(this.perspective,i,this.currentSubscription.result);return{results:s,totalCount:u,pageSize:e,pageNumber:r}}else{let a=await this.ctor.queryToProlog(this.perspective,i,this.modelClassName);this.currentSubscription=await this.perspective.subscribeInfer(a);let o=async c=>{let{results:l,totalCount:f}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,c);n({results:l,totalCount:f,pageSize:e,pageNumber:r})};this.currentSubscription.onResult(o);let{results:s,totalCount:u}=await this.ctor.instancesFromPrologResult(this.perspective,i,this.currentSubscription.result);return{results:s,totalCount:u,pageSize:e,pageNumber:r}}}};var Cc="0.11.2-dev-multi-user";var Tr=12e3;function F3(){let t=new AbortController;return setTimeout(()=>t.abort(),20),t}function dn(t,e=1e4){return X(this,null,function*(){return Promise.race([new Promise((r,n)=>{let i;try{i=new WebSocket(t,"graphql-transport-ws"),i.onopen=()=>{i.close(),r(i)},i.onerror=a=>{n(a)},i.onclose=a=>{a.code!==1e3&&n(new Error(`WebSocket closed with code ${a.code}: ${a.reason}`))}}catch(a){i&&i.close(),n(a)}}),new Promise((r,n)=>{setTimeout(()=>{n(new Error("WebSocket connection timed out"))},e)})])})}function lp(t){return X(this,null,function*(){try{let e=yield fetch(`http://localhost:${t}/graphql/`,{signal:F3().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 M3(){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 pp(){try{localStorage.setItem("test",""),localStorage.removeItem("test")}catch(t){return!1}return!0}function Ec(t,e){pp()&&localStorage.setItem(`${Cc}/${t}`,e)}function Kt(t){return pp()?localStorage.getItem(`${Cc}/${t}`):null}function fp(t){pp()&&localStorage.removeItem(`${Cc}/${t}`)}var U3=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 Co(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 U3(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 Eo=class{constructor(e){this.activeSocket=null;this.requestedRestart=!1;this.authState="unauthenticated";this.connectionState="not_connected";this.port=Tr;this.capabilities=[];this.isHosting=!1;this.listeners={authstatechange:[],configstatechange:[],connectionstatechange:[]};Co(this);this.options=e,this.appName=e.appName,this.appDesc=e.appDesc,this.appDomain=e.appDomain,this.appUrl=e.appUrl,this.appIconPath=e.appIconPath,this.capabilities=e.capabilities,this.port=e.port||this.port,this.url=e.url||`ws://localhost:${this.port}/graphql`,this.token=e.token||this.token,this.isHosting=e.hosting||!1}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)}buildTempClient(e){let r=Xu({url:e,connectionParams:()=>X(this,null,function*(){return{headers:{authorization:""}}})}),n=new ds({link:new el(r),cache:new Aa({resultCaching:!1,addTypename:!1}),defaultOptions:{watchQuery:{fetchPolicy:"no-cache"},query:{fetchPolicy:"no-cache"}}});return new ho(n)}connect(e){return X(this,null,function*(){try{if(e){yield dn(e),this.setUrl(e);let r=this.buildClient();return yield this.checkAuth(),r}else{let r=`ws://localhost:${this.port}/graphql`;yield dn(r),this.setUrl(r);let n=this.buildClient();return yield this.checkAuth(),n}}catch(r){this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}})}connectMultiUser(){return X(this,null,function*(){try{let e=this.options.backendUrl;console.debug("[Ad4m Connect] Connecting to backend:",e),yield dn(e),this.setUrl(e);let r=this.buildClient();console.debug("[Ad4m Connect] Built client:",r);let n;try{console.debug("[Ad4m Connect] Logging in user:",this.options.userEmail),n=yield r.agent.loginUser(this.options.userEmail,this.options.userPassword),console.debug("[Ad4m Connect] Login successful")}catch(a){console.debug("[Ad4m Connect] Login error:",a),console.debug("[Ad4m Connect] User does not exist, trying to create user:",this.options.userEmail);try{console.debug("[Ad4m Connect] Creating user:",this.options.userEmail);try{let o=yield r.agent.createUser(this.options.userEmail,this.options.userPassword);if(console.debug("[Ad4m Connect] Create result:",o),!o.success)throw new Error(o.error||"Failed to create user")}catch(o){console.log("[Ad4m Connect] Failed to create user:",o)}console.debug("[Ad4m Connect] Logging in user after creation:",this.options.userEmail),n=yield r.agent.loginUser(this.options.userEmail,this.options.userPassword),console.log("[Ad4m Connect] Successfully created and logged in user")}catch(o){throw new Error(`Failed to create/login user: ${o.message}`)}}this.setToken(n);let i=this.buildClient();return yield i.agent.status(),this.notifyAuthChange("authenticated"),this.notifyConnectionChange("connected"),i}catch(e){throw this.notifyConnectionChange("error"),this.notifyAuthChange("unauthenticated"),e}})}loginToHosting(e,r){return X(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,Ec("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 X(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 X(this,null,function*(){try{if(e){let r=yield lp(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 X(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 dn(this.url),this.buildClient()}catch(i){return this.notifyConnectionChange("not_connected"),this.connectToPort()}})}findPort(){return X(this,null,function*(){let e=[...Array(10).keys()].map((i,a)=>lp(Tr+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,"graphql-transport-ws")}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=Xu({url:this.url,connectionParams:()=>X(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=>X(this,null,function*(){if(!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 ds({link:new el(this.wsClient),cache:new Aa({resultCaching:!1,addTypename:!1}),defaultOptions:{watchQuery:{fetchPolicy:"no-cache"},query:{fetchPolicy:"no-cache"},mutate:{fetchPolicy:"no-cache"}}}),this.ad4mClient=new ho(this.apolloClient),this.ad4mClient}checkAuth(){return X(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 X(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 X(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(Tr),this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}};function dp({unlockAgent:t,reconnect:e}){return F`
1523
+ - valid schema.$id`)}static determinePredicate(t,e,r,n,i){if(i.propertyMapping?.[e])return i.propertyMapping[e];if(r["x-ad4m"]?.through)return r["x-ad4m"].through;if(i.predicateTemplate){let o=o1(n),[s,u]=o.includes("://")?o.split("://"):["",o],c=u||"";return i.predicateTemplate.replace("${namespace}",c).replace("${scheme}",s).replace("${ns}",c).replace("${title}",t.title||"").replace("${property}",e)}if(i.predicateGenerator)return i.predicateGenerator(t.title||"",e);let a=o1(n);return a.includes("://")?`${a}${e}`:`${a}://${e}`}static getPropertyOption(t,e,r,n,i){return r.propertyOptions?.[t]?.[n]!==void 0?r.propertyOptions[t][n]:e["x-ad4m"]?.[n]!==void 0?e["x-ad4m"][n]:r[n]!==void 0?r[n]:i}static getDefaultValueForType(t){switch(t){case"string":return"";case"number":return 0;case"integer":return 0;case"boolean":return!1;case"array":return[];case"object":return{};default:return""}}};_t=new WeakMap,or=new WeakMap,Qs=new WeakMap,De=new WeakMap;_Ad4mModel.classNamesByClass=new WeakMap;var Hl=class{constructor(e,r,n){this.queryParams={},this.modelClassName=null,this.useSurrealDBFlag=!0,this.perspective=e,this.ctor=r,n&&(this.queryParams=n)}dispose(){this.currentSubscription&&(this.currentSubscription.dispose(),this.currentSubscription=void 0)}where(e){return this.queryParams.where=e,this}order(e){return this.queryParams.order=e,this}limit(e){return this.queryParams.limit=e,this}offset(e){return this.queryParams.offset=e,this}source(e){return this.queryParams.source=e,this}properties(e){return this.queryParams.properties=e,this}collections(e){return this.queryParams.collections=e,this}overrideModelClassName(e){return this.modelClassName=e,this}useSurrealDB(e=!0){return this.useSurrealDBFlag=e,this}async get(){if(this.useSurrealDBFlag){let e=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams),r=await this.perspective.querySurrealDB(e),{results:n}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,r);return n}else{let e=await this.ctor.queryToProlog(this.perspective,this.queryParams,this.modelClassName),r=await this.perspective.infer(e),{results:n}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,r);return n}}async subscribe(e){if(this.dispose(),this.useSurrealDBFlag){let r=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams);this.currentSubscription=await this.perspective.subscribeSurrealDB(r);let n=async a=>{let{results:o}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,a);e(o)};this.currentSubscription.onResult(n);let{results:i}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,this.currentSubscription.result);return i}else{let r=await this.ctor.queryToProlog(this.perspective,this.queryParams,this.modelClassName);this.currentSubscription=await this.perspective.subscribeInfer(r);let n=async a=>{let{results:o}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,a);e(o)};this.currentSubscription.onResult(n);let{results:i}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,this.currentSubscription.result);return i}}async count(){if(this.useSurrealDBFlag){let e=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams),r=await this.perspective.querySurrealDB(e),{totalCount:n}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,r);return n}else{let e=await this.ctor.countQueryToProlog(this.perspective,this.queryParams,this.modelClassName);return(await this.perspective.infer(e))?.[0]?.TotalCount||0}}async countSubscribe(e){if(this.dispose(),this.useSurrealDBFlag){let r=await this.ctor.queryToSurrealQL(this.perspective,this.queryParams);this.currentSubscription=await this.perspective.subscribeSurrealDB(r);let n=async a=>{let{totalCount:o}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,a);e(o)};this.currentSubscription.onResult(n);let{totalCount:i}=await this.ctor.instancesFromSurrealResult(this.perspective,this.queryParams,this.currentSubscription.result);return i}else{let r=await this.ctor.countQueryToProlog(this.perspective,this.queryParams,this.modelClassName);this.currentSubscription=await this.perspective.subscribeInfer(r);let n=async i=>{let a=i?.[0]?.TotalCount||0;e(a)};return this.currentSubscription.onResult(n),this.currentSubscription.result?.[0]?.TotalCount||0}}async paginate(e,r){let n={...this.queryParams||{},limit:e,offset:e*(r-1),count:!0};if(this.useSurrealDBFlag){let i=await this.ctor.queryToSurrealQL(this.perspective,n),a=await this.perspective.querySurrealDB(i),{results:o,totalCount:s}=await this.ctor.instancesFromSurrealResult(this.perspective,n,a);return{results:o,totalCount:s,pageSize:e,pageNumber:r}}else{let i=await this.ctor.queryToProlog(this.perspective,n,this.modelClassName),a=await this.perspective.infer(i),{results:o,totalCount:s}=await this.ctor.instancesFromPrologResult(this.perspective,n,a);return{results:o,totalCount:s,pageSize:e,pageNumber:r}}}async paginateSubscribe(e,r,n){this.dispose();let i={...this.queryParams||{},limit:e,offset:e*(r-1),count:!0};if(this.useSurrealDBFlag){let a=await this.ctor.queryToSurrealQL(this.perspective,i);this.currentSubscription=await this.perspective.subscribeSurrealDB(a);let o=async c=>{let{results:l,totalCount:f}=await this.ctor.instancesFromSurrealResult(this.perspective,i,c);n({results:l,totalCount:f,pageSize:e,pageNumber:r})};this.currentSubscription.onResult(o);let{results:s,totalCount:u}=await this.ctor.instancesFromSurrealResult(this.perspective,i,this.currentSubscription.result);return{results:s,totalCount:u,pageSize:e,pageNumber:r}}else{let a=await this.ctor.queryToProlog(this.perspective,i,this.modelClassName);this.currentSubscription=await this.perspective.subscribeInfer(a);let o=async c=>{let{results:l,totalCount:f}=await this.ctor.instancesFromPrologResult(this.perspective,this.queryParams,c);n({results:l,totalCount:f,pageSize:e,pageNumber:r})};this.currentSubscription.onResult(o);let{results:s,totalCount:u}=await this.ctor.instancesFromPrologResult(this.perspective,i,this.currentSubscription.result);return{results:s,totalCount:u,pageSize:e,pageNumber:r}}}};var Cc="0.11.2-dev-multi-user-2";var Tr=12e3;function F3(){let t=new AbortController;return setTimeout(()=>t.abort(),20),t}function dn(t,e=1e4){return X(this,null,function*(){return Promise.race([new Promise((r,n)=>{let i;try{i=new WebSocket(t,"graphql-transport-ws"),i.onopen=()=>{i.close(),r(i)},i.onerror=a=>{n(a)},i.onclose=a=>{a.code!==1e3&&n(new Error(`WebSocket closed with code ${a.code}: ${a.reason}`))}}catch(a){i&&i.close(),n(a)}}),new Promise((r,n)=>{setTimeout(()=>{n(new Error("WebSocket connection timed out"))},e)})])})}function lp(t){return X(this,null,function*(){try{let e=yield fetch(`http://localhost:${t}/graphql/`,{signal:F3().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 M3(){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 pp(){try{localStorage.setItem("test",""),localStorage.removeItem("test")}catch(t){return!1}return!0}function Ec(t,e){pp()&&localStorage.setItem(`${Cc}/${t}`,e)}function Kt(t){return pp()?localStorage.getItem(`${Cc}/${t}`):null}function fp(t){pp()&&localStorage.removeItem(`${Cc}/${t}`)}var U3=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 Co(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 U3(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 Eo=class{constructor(e){this.activeSocket=null;this.requestedRestart=!1;this.authState="unauthenticated";this.connectionState="not_connected";this.port=Tr;this.capabilities=[];this.isHosting=!1;this.listeners={authstatechange:[],configstatechange:[],connectionstatechange:[]};Co(this);this.options=e,this.appName=e.appName,this.appDesc=e.appDesc,this.appDomain=e.appDomain,this.appUrl=e.appUrl,this.appIconPath=e.appIconPath,this.capabilities=e.capabilities,this.port=e.port||this.port,this.url=e.url||`ws://localhost:${this.port}/graphql`,this.token=e.token||this.token,this.isHosting=e.hosting||!1}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)}buildTempClient(e){let r=Xu({url:e,connectionParams:()=>X(this,null,function*(){return{headers:{authorization:""}}})}),n=new ds({link:new el(r),cache:new Aa({resultCaching:!1,addTypename:!1}),defaultOptions:{watchQuery:{fetchPolicy:"no-cache"},query:{fetchPolicy:"no-cache"}}});return new ho(n)}connect(e){return X(this,null,function*(){try{if(e){yield dn(e),this.setUrl(e);let r=this.buildClient();return yield this.checkAuth(),r}else{let r=`ws://localhost:${this.port}/graphql`;yield dn(r),this.setUrl(r);let n=this.buildClient();return yield this.checkAuth(),n}}catch(r){this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}})}connectMultiUser(){return X(this,null,function*(){try{let e=this.options.backendUrl;console.debug("[Ad4m Connect] Connecting to backend:",e),yield dn(e),this.setUrl(e);let r=this.buildClient();console.debug("[Ad4m Connect] Built client:",r);let n;try{console.debug("[Ad4m Connect] Logging in user:",this.options.userEmail),n=yield r.agent.loginUser(this.options.userEmail,this.options.userPassword),console.debug("[Ad4m Connect] Login successful")}catch(a){console.debug("[Ad4m Connect] Login error:",a),console.debug("[Ad4m Connect] User does not exist, trying to create user:",this.options.userEmail);try{console.debug("[Ad4m Connect] Creating user:",this.options.userEmail);try{let o=yield r.agent.createUser(this.options.userEmail,this.options.userPassword);if(console.debug("[Ad4m Connect] Create result:",o),!o.success)throw new Error(o.error||"Failed to create user")}catch(o){console.log("[Ad4m Connect] Failed to create user:",o)}console.debug("[Ad4m Connect] Logging in user after creation:",this.options.userEmail),n=yield r.agent.loginUser(this.options.userEmail,this.options.userPassword),console.log("[Ad4m Connect] Successfully created and logged in user")}catch(o){throw new Error(`Failed to create/login user: ${o.message}`)}}this.setToken(n);let i=this.buildClient();return yield i.agent.status(),this.ad4mClient=i,this.notifyAuthChange("authenticated"),this.notifyConnectionChange("connected"),i}catch(e){throw this.notifyConnectionChange("error"),this.notifyAuthChange("unauthenticated"),e}})}loginToHosting(e,r){return X(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,Ec("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 X(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 X(this,null,function*(){try{if(e){let r=yield lp(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 X(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 dn(this.url),this.buildClient()}catch(i){return this.notifyConnectionChange("not_connected"),this.connectToPort()}})}findPort(){return X(this,null,function*(){let e=[...Array(10).keys()].map((i,a)=>lp(Tr+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,"graphql-transport-ws")}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=Xu({url:this.url,connectionParams:()=>X(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=>X(this,null,function*(){if(!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 ds({link:new el(this.wsClient),cache:new Aa({resultCaching:!1,addTypename:!1}),defaultOptions:{watchQuery:{fetchPolicy:"no-cache"},query:{fetchPolicy:"no-cache"},mutate:{fetchPolicy:"no-cache"}}}),this.ad4mClient=new ho(this.apolloClient),this.ad4mClient}checkAuth(){return X(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 X(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 X(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(Tr),this.notifyConnectionChange("not_connected"),this.notifyAuthChange("unauthenticated")}};function dp({unlockAgent:t,reconnect:e}){return F`
1524
1524
  <div class="text-center">
1525
1525
  <div class="items">
1526
1526
  <div>
@@ -2901,7 +2901,7 @@ WHERE ${l.join(" AND ")}
2901
2901
  width: 100vw;
2902
2902
  object-fit: cover;
2903
2903
  }
2904
- `,Z=class extends Rr{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._multiUserEmail="";this._multiUserPassword="";this._multiUserError=null;this._multiUserLoading=!1;this._multiUserTab="login";this._localDetected=!1;this._remoteUrl="";this._remoteMultiUserDetected=null;this._remoteDetecting=!1;this._remoteError=null;this.uiState="connection_overview";this.appName=null;this.appDesc=null;this.appDomain=null;this.appIconPath=null;this.mobile=null;this.capabilities=[];this.hosting=Kt("ad4mhosting")==="true"||!1;this.token=Kt("ad4mToken")||"";this.port=parseInt(Kt("ad4mport"))||Tr;this.url=Kt("ad4murl")||"";this.multiUser=!1;this.backendUrl=""}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(),Co(this),this.injectFont(),this._isMobile=j3(),this._client=new Eo({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(Kt("ad4mport"))||Tr,token:this.token||Kt("ad4mtoken"),url:this.url||Kt("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.token||Kt("ad4mtoken")?this._client.connect():(this.detectLocal(),this.changeUIState("connection_overview"),this._isOpen=!0)}checkEmail(){return X(this,null,function*(){try{(yield this._client.checkEmail(this._email))?this._hostingStep=1:this._hostingStep=2}catch(r){console.log(r)}})}handleMultiUserSignup(){return X(this,null,function*(){try{this._multiUserLoading=!0,this._multiUserError=null,this._client.options.userEmail=this._multiUserEmail,this._client.options.userPassword=this._multiUserPassword,this._client.options.backendUrl=this.backendUrl;let r=yield this._client.connectMultiUser();this._multiUserEmail="",this._multiUserPassword="",this._isOpen=!1,this.changeUIState("connected")}catch(r){this._multiUserError=r.message||"Failed to create account. Please try again."}finally{this._multiUserLoading=!1}})}handleMultiUserLogin(){return X(this,null,function*(){try{this._multiUserLoading=!0,this._multiUserError=null,this._client.options.userEmail=this._multiUserEmail,this._client.options.userPassword=this._multiUserPassword,this._client.options.backendUrl=this.backendUrl;let r=yield this._client.connectMultiUser();this._multiUserEmail="",this._multiUserPassword="",this._isOpen=!1,this.changeUIState("connected")}catch(r){this._multiUserError=r.message||"Failed to log in. Please check your credentials."}finally{this._multiUserLoading=!1}})}changeMultiUserEmail(r){this._multiUserEmail=r,this._multiUserError=null}changeMultiUserPassword(r){this._multiUserPassword=r,this._multiUserError=null}setMultiUserTab(r){this._multiUserTab=r,this._multiUserError=null}detectLocal(){return X(this,null,function*(){try{yield dn(`ws://localhost:${this.port}/graphql`,3e3),this._localDetected=!0}catch(r){console.log("[Ad4m Connect] Local detection failed:",r),this._localDetected=!1}})}verifyAd4mApi(r){return X(this,null,function*(){console.log("[Ad4m Connect] Verifying AD4M API at URL:",r);let n=this._client.buildTempClient(r);try{yield n.runtime.info(),console.log("[Ad4m Connect] AD4M API verified")}catch(i){throw console.error("[Ad4m Connect] Failed to verify AD4M API:",i),new Error("Server is reachable but doesn't appear to be an AD4M executor. Make sure the URL includes '/graphql'.")}})}detectRemoteMultiUser(r){return X(this,null,function*(){console.log("[Ad4m Connect] Detecting multi-user mode for URL:",r);let n=this._client.buildTempClient(r);try{let i=yield n.runtime.multiUserEnabled();return console.log("[Ad4m Connect] Multi-user detection result:",i),i}catch(i){return console.error("[Ad4m Connect] Failed to detect multi-user mode:",i),console.error("[Ad4m Connect] Error details:",i.message,i.stack),!1}})}handleConnectLocal(){return X(this,null,function*(){try{this.changeUIState("requestcap"),yield this._client.connect()}catch(r){console.error("Failed to connect to local AD4M:",r),this.changeUIState("connection_overview")}})}handleShowRemoteConnection(){this._remoteUrl=this.backendUrl||this.url||"",this._remoteMultiUserDetected=null,this._remoteError=null,this.changeUIState("remote_connection")}handleRemoteUrlChange(r){this._remoteUrl=r,this._remoteError=null}handleRemoteConnect(){return X(this,null,function*(){if(!this._remoteUrl){this._remoteError="Please enter a URL";return}this._remoteDetecting=!0,this._remoteError=null,this._remoteMultiUserDetected=null;try{console.log("[Ad4m Connect] Checking if server is reachable:",this._remoteUrl),yield dn(this._remoteUrl,5e3),console.log("[Ad4m Connect] Server is reachable"),yield this.verifyAd4mApi(this._remoteUrl);let r=yield this.detectRemoteMultiUser(this._remoteUrl);this._remoteMultiUserDetected=r,this._remoteDetecting=!1}catch(r){console.error("[Ad4m Connect] Connection/detection failed:",r),this._remoteError=r.message||"Cannot reach server at this URL. Please check the URL and try again.",this._remoteMultiUserDetected=null,this._remoteDetecting=!1}})}handleRemoteMultiUserAuth(){return X(this,null,function*(){this.backendUrl=this._remoteUrl,this.changeUIState("multiuser_auth")})}handleRemoteRequestCapability(){return X(this,null,function*(){try{this.changeUIState("requestcap"),yield this._client.connect(this._remoteUrl)}catch(r){this._remoteError=r.message||"Failed to connect",this.changeUIState("remote_connection")}})}loginToHosting(){return X(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 X(this,null,function*(){yield this._client.ad4mClient.agent.unlock(r,n)})}verifyCode(r){return X(this,null,function*(){try{yield this._client.verifyCode(r)}catch(n){this._verifyCodeError="Invalid code"}})}changeUrl(r){r!==this._client.url&&(fp("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?Ec("ad4m"+r,n):fp("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.multiUser&&this.backendUrl?this.changeUIState("multiuser_auth"):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 X(this,null,function*(){try{window.BarcodeDetector.getSupportedFormats()}catch(n){window.BarcodeDetector=Dr}yield this.changeUIState("qr"),setTimeout(()=>X(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 X(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 X(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 X(this,null,function*(){try{yield this._client.requestCapability(r),this.changeUIState("verifycode")}catch(n){console.warn(n)}})}isAuthenticated(){return X(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 bp();if(this.uiState==="connection_overview")return hp({localDetected:this._localDetected,multiUserConfigured:this.multiUser&&!!this.backendUrl,backendUrl:this.backendUrl,configuredUrl:this.url,isMobile:this._isMobile,onConnectLocal:this.handleConnectLocal,onConnectRemote:this.handleShowRemoteConnection,onScanQR:()=>{this.startCamera(null)},onDownloadAd4m:()=>{window.open("https://github.com/coasys/ad4m/releases")}});if(this.uiState==="remote_connection")return Sp({initialUrl:this._remoteUrl,detecting:this._remoteDetecting,multiUserDetected:this._remoteMultiUserDetected,error:this._remoteError,onBack:()=>this.changeUIState("connection_overview"),onUrlChange:this.handleRemoteUrlChange,onConnect:this.handleRemoteConnect,onMultiUserAuth:this.handleRemoteMultiUserAuth,onRequestCapability:this.handleRemoteRequestCapability});if(this.uiState==="multiuser_auth")return wp({email:this._multiUserEmail,password:this._multiUserPassword,error:this._multiUserError,isLoading:this._multiUserLoading,backendUrl:this.backendUrl,changeEmail:this.changeMultiUserEmail,changePassword:this.changeMultiUserPassword,onLogin:this.handleMultiUserLogin,onSignup:this.handleMultiUserSignup,activeTab:this._multiUserTab,setActiveTab:this.setMultiUserTab});if(this.uiState==="hosting")return vp({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 Ep({changeState:this.changeUIState,onSuccess:r=>{this.changeUrl(r),this._client.connect(r)},uiState:this.uiState});if(this.authState==="locked")return dp({unlockAgent:this.unlockAgent,reconnect:this.connect});if(this.uiState==="settings")return xp({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 Ap({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"?kp({code:this._code,changeCode:this.changeCode,changeState:this.changeUIState,verifyCode:this.verifyCode,isHosting:this._client.isHosting,verifyCodeError:this._verifyCodeError}):Cp({changeState:this.changeUIState,requestCapability:this.requestCapability,capabilities:this.capabilities,appname:this.appName,setOpen:this.setOpen,appiconpath:this.appIconPath});if(this.connectionState==="disconnected")return gp({reconnect:this.connect});if(this.connectionState==="port_not_found")return mp()}mobileView(){return this.mobile?_p({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:F`
2904
+ `,Z=class extends Rr{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._multiUserEmail="";this._multiUserPassword="";this._multiUserError=null;this._multiUserLoading=!1;this._multiUserTab="login";this._localDetected=!1;this._remoteUrl="";this._remoteMultiUserDetected=null;this._remoteDetecting=!1;this._remoteError=null;this.uiState="connection_overview";this.appName=null;this.appDesc=null;this.appDomain=null;this.appIconPath=null;this.mobile=null;this.capabilities=[];this.hosting=Kt("ad4mhosting")==="true"||!1;this.token=Kt("ad4mToken")||"";this.port=parseInt(Kt("ad4mport"))||Tr;this.url=Kt("ad4murl")||"";this.multiUser=!1;this.backendUrl=""}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(),Co(this),this.injectFont(),this._isMobile=j3(),this._client=new Eo({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(Kt("ad4mport"))||Tr,token:this.token||Kt("ad4mtoken"),url:this.url||Kt("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.token||Kt("ad4mtoken")?this.multiUser&&this.backendUrl?this._client.connect(this.backendUrl):this._client.connect():(this.detectLocal(),this.changeUIState("connection_overview"),this._isOpen=!0)}checkEmail(){return X(this,null,function*(){try{(yield this._client.checkEmail(this._email))?this._hostingStep=1:this._hostingStep=2}catch(r){console.log(r)}})}handleMultiUserSignup(){return X(this,null,function*(){try{this._multiUserLoading=!0,this._multiUserError=null,this._client.options.userEmail=this._multiUserEmail,this._client.options.userPassword=this._multiUserPassword,this._client.options.backendUrl=this.backendUrl;let r=yield this._client.connectMultiUser();this._multiUserEmail="",this._multiUserPassword="",this._isOpen=!1,this.changeUIState("connected")}catch(r){this._multiUserError=r.message||"Failed to create account. Please try again."}finally{this._multiUserLoading=!1}})}handleMultiUserLogin(){return X(this,null,function*(){try{this._multiUserLoading=!0,this._multiUserError=null,this._client.options.userEmail=this._multiUserEmail,this._client.options.userPassword=this._multiUserPassword,this._client.options.backendUrl=this.backendUrl;let r=yield this._client.connectMultiUser();this._multiUserEmail="",this._multiUserPassword="",this._isOpen=!1,this.changeUIState("connected")}catch(r){this._multiUserError=r.message||"Failed to log in. Please check your credentials."}finally{this._multiUserLoading=!1}})}changeMultiUserEmail(r){this._multiUserEmail=r,this._multiUserError=null}changeMultiUserPassword(r){this._multiUserPassword=r,this._multiUserError=null}setMultiUserTab(r){this._multiUserTab=r,this._multiUserError=null}detectLocal(){return X(this,null,function*(){try{yield dn(`ws://localhost:${this.port}/graphql`,3e3),this._localDetected=!0}catch(r){console.log("[Ad4m Connect] Local detection failed:",r),this._localDetected=!1}})}verifyAd4mApi(r){return X(this,null,function*(){console.log("[Ad4m Connect] Verifying AD4M API at URL:",r);let n=this._client.buildTempClient(r);try{yield n.runtime.info(),console.log("[Ad4m Connect] AD4M API verified")}catch(i){throw console.error("[Ad4m Connect] Failed to verify AD4M API:",i),new Error("Server is reachable but doesn't appear to be an AD4M executor. Make sure the URL includes '/graphql'.")}})}detectRemoteMultiUser(r){return X(this,null,function*(){console.log("[Ad4m Connect] Detecting multi-user mode for URL:",r);let n=this._client.buildTempClient(r);try{let i=yield n.runtime.multiUserEnabled();return console.log("[Ad4m Connect] Multi-user detection result:",i),i}catch(i){return console.error("[Ad4m Connect] Failed to detect multi-user mode:",i),console.error("[Ad4m Connect] Error details:",i.message,i.stack),!1}})}handleConnectLocal(){return X(this,null,function*(){try{this.changeUIState("requestcap"),yield this._client.connect()}catch(r){console.error("Failed to connect to local AD4M:",r),this.changeUIState("connection_overview")}})}handleShowRemoteConnection(){this._remoteUrl=this.backendUrl||this.url||"",this._remoteMultiUserDetected=null,this._remoteError=null,this.changeUIState("remote_connection")}handleRemoteUrlChange(r){this._remoteUrl=r,this._remoteError=null}handleRemoteConnect(){return X(this,null,function*(){if(!this._remoteUrl){this._remoteError="Please enter a URL";return}this._remoteDetecting=!0,this._remoteError=null,this._remoteMultiUserDetected=null;try{console.log("[Ad4m Connect] Checking if server is reachable:",this._remoteUrl),yield dn(this._remoteUrl,5e3),console.log("[Ad4m Connect] Server is reachable"),yield this.verifyAd4mApi(this._remoteUrl);let r=yield this.detectRemoteMultiUser(this._remoteUrl);this._remoteMultiUserDetected=r,this._remoteDetecting=!1}catch(r){console.error("[Ad4m Connect] Connection/detection failed:",r),this._remoteError=r.message||"Cannot reach server at this URL. Please check the URL and try again.",this._remoteMultiUserDetected=null,this._remoteDetecting=!1}})}handleRemoteMultiUserAuth(){return X(this,null,function*(){this.backendUrl=this._remoteUrl,this.changeUIState("multiuser_auth")})}handleRemoteRequestCapability(){return X(this,null,function*(){try{this.changeUIState("requestcap"),yield this._client.connect(this._remoteUrl)}catch(r){this._remoteError=r.message||"Failed to connect",this.changeUIState("remote_connection")}})}loginToHosting(){return X(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 X(this,null,function*(){yield this._client.ad4mClient.agent.unlock(r,n)})}verifyCode(r){return X(this,null,function*(){try{yield this._client.verifyCode(r)}catch(n){this._verifyCodeError="Invalid code"}})}changeUrl(r){r!==this._client.url&&(fp("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?Ec("ad4m"+r,n):fp("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.multiUser&&this.backendUrl?this.changeUIState("multiuser_auth"):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 X(this,null,function*(){try{window.BarcodeDetector.getSupportedFormats()}catch(n){window.BarcodeDetector=Dr}yield this.changeUIState("qr"),setTimeout(()=>X(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 X(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 X(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 X(this,null,function*(){try{yield this._client.requestCapability(r),this.changeUIState("verifycode")}catch(n){console.warn(n)}})}isAuthenticated(){return X(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 bp();if(this.uiState==="connection_overview")return hp({localDetected:this._localDetected,multiUserConfigured:this.multiUser&&!!this.backendUrl,backendUrl:this.backendUrl,configuredUrl:this.url,isMobile:this._isMobile,onConnectLocal:this.handleConnectLocal,onConnectRemote:this.handleShowRemoteConnection,onScanQR:()=>{this.startCamera(null)},onDownloadAd4m:()=>{window.open("https://github.com/coasys/ad4m/releases")}});if(this.uiState==="remote_connection")return Sp({initialUrl:this._remoteUrl,detecting:this._remoteDetecting,multiUserDetected:this._remoteMultiUserDetected,error:this._remoteError,onBack:()=>this.changeUIState("connection_overview"),onUrlChange:this.handleRemoteUrlChange,onConnect:this.handleRemoteConnect,onMultiUserAuth:this.handleRemoteMultiUserAuth,onRequestCapability:this.handleRemoteRequestCapability});if(this.uiState==="multiuser_auth")return wp({email:this._multiUserEmail,password:this._multiUserPassword,error:this._multiUserError,isLoading:this._multiUserLoading,backendUrl:this.backendUrl,changeEmail:this.changeMultiUserEmail,changePassword:this.changeMultiUserPassword,onLogin:this.handleMultiUserLogin,onSignup:this.handleMultiUserSignup,activeTab:this._multiUserTab,setActiveTab:this.setMultiUserTab});if(this.uiState==="hosting")return vp({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 Ep({changeState:this.changeUIState,onSuccess:r=>{this.changeUrl(r),this._client.connect(r)},uiState:this.uiState});if(this.authState==="locked")return dp({unlockAgent:this.unlockAgent,reconnect:this.connect});if(this.uiState==="settings")return xp({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 Ap({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"?kp({code:this._code,changeCode:this.changeCode,changeState:this.changeUIState,verifyCode:this.verifyCode,isHosting:this._client.isHosting,verifyCodeError:this._verifyCodeError}):Cp({changeState:this.changeUIState,requestCapability:this.requestCapability,capabilities:this.capabilities,appname:this.appName,setOpen:this.setOpen,appiconpath:this.appIconPath});if(this.connectionState==="disconnected")return gp({reconnect:this.connect});if(this.connectionState==="port_not_found")return mp()}mobileView(){return this.mobile?_p({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:F`
2905
2905
  <div class="wrapper">
2906
2906
  <div class="dialog">
2907
2907
  ${yp()}
package/package.json CHANGED
@@ -65,5 +65,5 @@
65
65
  "esbuild-plugin-replace": "^1.4.0",
66
66
  "lit": "^2.3.1"
67
67
  },
68
- "version": "0.11.2-dev-multi-user"
68
+ "version": "0.11.2-dev-multi-user-2"
69
69
  }