UNPKG

@connectifi/agent-web

Version:

A simple web implementation of a connectifi agent

2 lines 2.02 kB
"use strict";async function f(){if(!document.requestStorageAccess||await document.hasStorageAccess())return!0;try{let e=await navigator.permissions.query({name:"storage-access"});if(!e)return!1;if(e.state==="granted")try{return await document.requestStorageAccess(),!0}catch{return!1}}catch(e){console.error("failed to check storage access:",e)}return!1}var m=typeof window!="undefined"?new URL(window.location.href):void 0,c=m==null?void 0:m.pathname.split("/"),u=c==null?void 0:c[c.length-2];async function d({instanceId:e,instanceTitle:s,instanceUrl:n}){let r=`/api/tunnel/${u}?title=${encodeURIComponent(s||"")}&src=${encodeURIComponent(n||"")}&instanceId=${encodeURIComponent(e||"")}`;try{return(await fetch(r)).json()}catch(t){console.error("failed to call tunnel:",t)}}var g="subDirectory",l="directory";var E=new Error("timed out waiting for iframe message");function o(e,s){s&&e.postMessage(JSON.stringify(s))}function h(e,{directory:s,namespace:n,instanceId:r}){let t=`/interop/?instanceId=${r}&${g}=${s}&${l}=${n}`,w=window.location.protocol==="https:"?"wss://":"ws://",I=window.location.host,M=`${w}${I}${t}`,a=new WebSocket(M);return a.onopen=()=>o(e,{topic:"open"}),a.onmessage=({data:i})=>o(e,{topic:"message",data:i}),a.onerror=()=>o(e,{topic:"error"}),a.onclose=({code:i})=>o(e,{topic:"close",code:i,directory:s,namespace:n,instanceId:r}),a}function R(){let e;return async function(n,{data:r}){let t=JSON.parse(r);switch(t.topic){case"connect":e==null||e.close(),e=h(n,t);break;case"send":e==null||e.send(JSON.stringify({action:"send",message:t.message}));break;case"close":e==null||e.close();break;case"has-storage-access":o(n,{topic:"has-storage-access",hasStorageAccess:await f()});break;case"tunnel":o(n,await d(t));break}}}var y=R();function p({ports:e}){if(!e.length)return;window.removeEventListener("message",p);let s=e[0];s.addEventListener("message",y.bind(void 0,s)),s.start(),o(s,{topic:"handshake"})}window.addEventListener("message",p); //# sourceMappingURL=agent-iframe.bundle.cjs.map