@based/client
Advanced tools
Comparing version 1.2.5 to 2.2.0
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -6,0 +10,0 @@ if (k2 === undefined) k2 = k; |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -6,0 +10,0 @@ if (k2 === undefined) k2 = k; |
@@ -1,15 +0,15 @@ | ||
var Me=Object.create;var Q=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames,de=Object.getOwnPropertySymbols,_e=Object.getPrototypeOf,fe=Object.prototype.hasOwnProperty,ze=Object.prototype.propertyIsEnumerable;var be=(t,e,s)=>e in t?Q(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,me=(t,e)=>{for(var s in e||(e={}))fe.call(e,s)&&be(t,s,e[s]);if(de)for(var s of de(e))ze.call(e,s)&&be(t,s,e[s]);return t};var Je=(t,e)=>{for(var s in e)Q(t,s,{get:e[s],enumerable:!0})},$=(t,e,s,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of He(e))!fe.call(t,n)&&n!==s&&Q(t,n,{get:()=>e[n],enumerable:!(r=Le(e,n))||r.enumerable});return t},f=(t,e,s)=>($(t,e,"default"),s&&$(s,e,"default")),j=(t,e,s)=>(s=t!=null?Me(_e(t)):{},$(e||!t||!t.__esModule?Q(s,"default",{value:t,enumerable:!0}):s,t)),Ke=t=>$(Q({},"__esModule",{value:!0}),t);var b={};Je(b,{Based:()=>pe,BasedClient:()=>J,BasedGraphQL:()=>y.BasedGraphQL,Observable:()=>w,addGetSubscriber:()=>M,addRequest:()=>O,addSubscriber:()=>P,createGraphqlOperations:()=>y.createOperations,default:()=>at,generateSubscriptionId:()=>T,generateTrackingKey:()=>oe,handleGraphqlVariables:()=>y.handleGraphqlVariables,parseGraphql:()=>y.parseGraphql,removeSubscriber:()=>g});module.exports=Ke(b);var he=class{constructor(){this.listeners={};Object.defineProperty(this,"listeners",{enumerable:!1,writable:!0})}emit(e,s){this.listeners[e]&&this.listeners[e].forEach(r=>r(s))}on(e,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push(s)}removeAllListeners(){this.listeners={}}once(e,s){this.on(e,r=>{s(r),this.removeListener(e,s)})}removeListener(e,s){let r=this.listeners[e];if(r){if(!s)delete this.listeners[e];else for(let n=0,i=r.length;n<i;n++)if(r[n]===s){r.splice(n,1);break}}}},ge=he;var ye=(t,e)=>{typeof t=="function"?t().then(s=>{e(s)}):e(t)};var Se=j(require("isomorphic-ws")),R=new Map,ve;typeof window!="undefined"&&document.addEventListener("visibilitychange",function(t){clearTimeout(ve),document.hidden?ve=setTimeout(()=>{R.forEach(e=>{e(!1)})},3e4):R.forEach(e=>{e(!0)})});var Z=(t,e,s={destroy:()=>{R.delete(s)}},r=0,n=!1)=>(ye(e,i=>{setTimeout(()=>{if(s.disconnected)return;let o=!0;R.set(s,a=>{s.disconnected||(!a&&o?(console.warn("Send to background - close connection"),o=!1,t.onClose(),c.close()):!o&&a&&(R.delete(s),Z(t,e,s,0,!0)))});let c=s.ws=new Se.default(i);c.onerror=()=>{},c.onmessage=a=>t.onData(a),c.onopen=()=>{if(o){if(s.disconnected)return;r=100,n&&t.onReconnect(),t.onOpen()}},c.onclose=()=>{if(o){if(s.disconnected)return;t.onClose(),Z(t,e,s,Math.min(1250,Math.min(r+500)),!0)}}},r)}),s),ee=Z;var k=require("@based/types");var E=require("@based/types");var U=require("@based/types");var We=t=>{clearTimeout(t.idlePing),t.idlePing=setTimeout(()=>{t.connection&&t.connected&&!t.connection.disconnected&&t.connection.ws.send("1")},6e4)},N=We;var m=(t,e)=>{e[0]===U.RequestTypes.Unsubscribe||e[0]===U.RequestTypes.Subscription||e[0]===U.RequestTypes.SendSubscriptionData||e[0]===U.RequestTypes.GetSubscription?t.subscriptionQueue.push(e):t.queue.push(e),t.connected&&!t.drainInProgress&&te(t)},te=t=>{t.connected&&!t.drainInProgress&&(t.queue.length||t.subscriptionQueue.length)&&(t.drainInProgress=!0,t.drainTimeout=setTimeout(()=>{if(t.drainInProgress=!1,t.queue.length||t.subscriptionQueue.length){let e=[...t.queue,...t.subscriptionQueue];t.queue=[],t.subscriptionQueue=[],t.connection.ws.send(JSON.stringify(e)),N(t)}},0))},ke=t=>{t.drainInProgress&&(clearTimeout(t.drainTimeout),t.drainInProgress=!1)};var se=require("@saulx/hash"),T=(t,e)=>e?(0,se.hashObjectIgnoreKeyOrder)([e,t]):(0,se.hashObjectIgnoreKeyOrder)(t);var M=(t,e,s,r,n)=>{r||(r=T(e,n));let i=t.subscriptions[r],o=t.cache[r];if(i)if(i.authError)if(!t.beingAuth)s(i.authError.error,r,0);else{let c=++i.cnt;i.subscribers[c]={onInitial:s}}else if(o)s(null,r,0,o.value);else{let c=++i.cnt;i.subscribers[c]={onInitial:s}}else{i=t.subscriptions[r]={query:e,cnt:1,name:n,subscribers:{1:{onInitial:s}}};let c;for(let a=0;a<t.subscriptionQueue.length;a++){let[u,l,,p]=t.subscriptionQueue[a];(u===E.RequestTypes.Unsubscribe||u===E.RequestTypes.SendSubscriptionData)&&l===r?(t.subscriptionQueue.splice(a,1),a--):(u===E.RequestTypes.Subscription||u===E.RequestTypes.GetSubscription)&&l===r&&(c=!0,u===E.RequestTypes.Subscription&&(p!==o.checksum&&(t.subscriptionQueue[a][3]=o.checksum),t.subscriptionQueue[a][4]=2))}if(!c){let a=[E.RequestTypes.GetSubscription,r,e];o&&a.push(o.checksum),n&&(o||a.push(0),a.push(n)),m(t,a)}}};var C=require("@based/types");var P=(t,e,s,r,n,i,o)=>{i||(i=T(e,o));let c=t.subscriptions[i],a=t.cache[i],u;if(c){u=++c.cnt;let l=!0;for(let p in c.subscribers)if(c.subscribers[p].onData){l=!1;break}if(c.subscribers[u]={onError:n,onData:s,onInitial:r},l){for(let d=0;d<t.subscriptionQueue.length;d++){let[h,v]=t.subscriptionQueue[d];h===C.RequestTypes.GetSubscription&&v===i&&(t.subscriptionQueue.splice(d,1),d--)}let p=[C.RequestTypes.Subscription,i,e];a&&(p.push(a.checksum),p.push(2)),o&&(a||p.push(0,2),p.push(o)),m(t,p)}}else{u=1,c=t.subscriptions[i]={query:e,cnt:1,name:o,subscribers:{1:{onError:n,onData:s,onInitial:r}}};let l=!1,p=!1,d;for(let h=0;h<t.subscriptionQueue.length;h++){let[v,q,,G]=t.subscriptionQueue[h];(v===C.RequestTypes.Unsubscribe||v===C.RequestTypes.SendSubscriptionData||v===C.RequestTypes.GetSubscription)&&q===i?(v===C.RequestTypes.GetSubscription&&(p=!0),d&&(d[4]=2),t.subscriptionQueue.splice(h,1),h--):v===C.RequestTypes.Subscription&&q===i&&(l=!0,d=t.subscriptionQueue[h],G!==a.checksum&&(d[3]=a.checksum),!d[4]&&p&&(d[4]=2))}if(!l){let h=[C.RequestTypes.Subscription,i,e];a&&(h.push(a.checksum),p&&h.push(2)),o&&(a?!p&&a&&h.push(2):h.push(0,0),h.push(o)),m(t,h)}}return a&&(r&&(r(null,i,u),delete c.subscribers[u].onInitial),s&&s(a.value,a.checksum)),[i,u]};var x=require("@based/types");var g=(t,e,s)=>{let r=t.subscriptions[e];if(r){let n=!1;if(s?r.subscribers[s]&&(delete r.subscribers[s],r.cnt--,r.cnt===0&&(n=!0)):n=!0,n){delete t.subscriptions[e];let i=!1;for(let o=0;o<t.subscriptionQueue.length;o++){let[c,a]=t.subscriptionQueue[o];c===x.RequestTypes.Unsubscribe&&a===e?i=!0:(c===x.RequestTypes.Subscription||c===x.RequestTypes.SendSubscriptionData)&&a===e&&(t.subscriptionQueue.splice(o,1),o--)}i||m(t,[x.RequestTypes.Unsubscribe,e])}}};var Oe=require("@based/types"),Te=t=>{for(let e=0;e<t.subscriptionQueue.length;e++)t.subscriptionQueue[e][0]===Oe.RequestTypes.Unsubscribe&&(t.subscriptionQueue.splice(e,1),e--)};var Ce=require("@based/types"),we=t=>{for(let e=0;e<t.subscriptionQueue.length;e++)t.subscriptionQueue[e][0]===Ce.RequestTypes.SendSubscriptionData&&(t.subscriptionQueue.splice(e,1),e--)};var L=(t,e=!1)=>{for(let s in t.subscriptions){let r=Number(s),n=t.subscriptions[s];if(e&&!n.authError)continue;let i,o,c;for(let l=0;l<t.subscriptionQueue.length;l++){let[p,d]=t.subscriptionQueue[l];d===r&&(p===10?(c=l,i=t.subscriptionQueue[l]):p===1&&(o=t.subscriptionQueue[l]))}i&&o&&console.error("GET IN Q AND SUB IN Q SHOULD BE IMPOSSIBLE");let a=t.cache[r],u=!1;if(i){let l=!0;for(let p in n.subscribers)if(n.subscribers[p].onData){l=!1;break}l?u=!0:(console.info("not only gets remove get"),t.subscriptionQueue.splice(c,1)),a&&i[3]!==a.checksum&&(i[3]=a.checksum)}if(!u)if(o)a&&o[3]!==a.checksum&&(o[3]=a.checksum,i&&(o[4]=2));else{let{name:l,query:p}=t.subscriptions[r];l?a?m(t,[1,r,p,a.checksum,i?2:0,l]):m(t,[1,r,p,0,i?2:0,l]):a?m(t,[1,r,p,a.checksum,i?2:0]):m(t,[1,r,p,0,i?2:0])}}};var H=(t,e)=>{if(typeof window!="undefined")return t;let s={white:"\x1B[37;1m",reset:"\x1B[0m",blue:"\x1B[34m",red:"\x1B[31m",green:"\x1B[32m",brightBlue:"\x1B[34;1m",brightRed:"\x1B[31;1m"};return`${s[e]}${t}${s.reset}`},re=(t,e=0,s=!1,r="",n=!1)=>{let i="";for(let a=0;a<e;a++)i+=" ";let o=s?[]:r?[i+`${H(r,n?"brightRed":"white")} {`]:[i+"{"],c=!1;s||(i+=" ",e+=1);for(let a in t){let u=t[a],l=a[0]==="$"?H(a,"white"):a;if(c&&(o[o.length-1]+=","),Array.isArray(u)){o.push(`${i} ${l}: [`);for(let p=0;p<u.length;p++){let d=u[p];o.push(...d&&typeof d=="object"?re(d,e+4):[`${i} ${d}`]),p!==u.length-1&&(o[o.length-1]+=",")}o.push(`${i} ]`)}else u&&typeof u=="object"?(o.push(`${i} ${l}: {`),o.push(...re(u,e+2,!0)),o.push(`${i} }`)):o.push(`${i} ${l}: ${u}`);c=!0}return s||o.push(i.slice(0,-1)+"}"),o},_=re;var B=t=>{let e=new Error(t.message);if(e.name=t.name?`${t.type} from ${t.name}`:t.type,e.stack=null,t.query||t.payload){let s=e.message.split(` | ||
`),r=0;s[0]===""&&s.shift();let n=s[0];for(let i=0;i<n.length;i++)if(n[i]!==" "){r=i-2;break}r>0?s=s.map(i=>i.slice(r)):s=s.map(i=>" "+i),t.code&&(e.code=t.code),e.message=` | ||
var Le=Object.create;var R=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames,he=Object.getOwnPropertySymbols,ze=Object.getPrototypeOf,ye=Object.prototype.hasOwnProperty,Je=Object.prototype.propertyIsEnumerable;var ge=(t,s,e)=>s in t?R(t,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[s]=e,ve=(t,s)=>{for(var e in s||(s={}))ye.call(s,e)&&ge(t,e,s[e]);if(he)for(var e of he(s))Je.call(s,e)&&ge(t,e,s[e]);return t};var Ke=(t,s)=>{for(var e in s)R(t,e,{get:s[e],enumerable:!0})},j=(t,s,e,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of _e(s))!ye.call(t,r)&&r!==e&&R(t,r,{get:()=>s[r],enumerable:!(i=He(s,r))||i.enumerable});return t},b=(t,s,e)=>(j(t,s,"default"),e&&j(e,s,"default")),N=(t,s,e)=>(e=t!=null?Le(ze(t)):{},j(s||!t||!t.__esModule?R(e,"default",{value:t,enumerable:!0}):e,t)),We=t=>j(R({},"__esModule",{value:!0}),t);var f={};Ke(f,{Based:()=>Z,BasedClient:()=>A,BasedGraphQL:()=>y.BasedGraphQL,Observable:()=>T,addGetSubscriber:()=>L,addRequest:()=>O,addSubscriber:()=>B,createGraphqlOperations:()=>y.createOperations,default:()=>ct,generateSubscriptionId:()=>C,generateTrackingKey:()=>ue,handleGraphqlVariables:()=>y.handleGraphqlVariables,parseGraphql:()=>y.parseGraphql,removeSubscriber:()=>g});module.exports=We(f);var te=class{constructor(){this.listeners={};Object.defineProperty(this,"listeners",{enumerable:!1,writable:!0})}emit(s,e){this.listeners[s]&&this.listeners[s].forEach(i=>i(e))}on(s,e){this.listeners[s]||(this.listeners[s]=[]),this.listeners[s].push(e)}removeAllListeners(){this.listeners={}}once(s,e){this.on(s,i=>{e(i),this.removeListener(s,e)})}removeListener(s,e){let i=this.listeners[s];if(i){if(!e)delete this.listeners[s];else for(let r=0,n=i.length;r<n;r++)if(i[r]===e){i.splice(r,1);break}}}},Se=te;var ke=(t,s)=>{typeof t=="function"?t().then(e=>{s(e)}):s(t)};var Te=N(require("isomorphic-ws")),U=new Map,Oe;typeof window!="undefined"&&document.addEventListener("visibilitychange",function(t){clearTimeout(Oe),document.hidden?Oe=setTimeout(()=>{U.forEach(s=>{s(!1)})},3e4):U.forEach(s=>{s(!0)})});var se=(t,s,e={destroy:()=>{U.delete(e)}},i=0,r=!1)=>(ke(s,n=>{setTimeout(()=>{if(e.disconnected)return;let o=!0;U.set(e,a=>{e.disconnected||(!a&&o?(console.warn("Send to background - close connection"),o=!1,t.onClose(),c.close()):!o&&a&&(U.delete(e),se(t,s,e,0,!0)))});let c=e.ws=new Te.default(n);c.onerror=()=>{},c.onmessage=a=>t.onData(a),c.onopen=()=>{if(o){if(e.disconnected)return;i=100,r&&t.onReconnect(),t.onOpen()}},c.onclose=()=>{if(o){if(e.disconnected)return;t.onClose(),se(t,s,e,Math.min(1250,Math.min(i+500)),!0)}}},i)}),e),re=se;var k=require("@based/types");var E=require("@based/types");var x=require("@based/types");var Ve=t=>{clearTimeout(t.idlePing),t.idlePing=setTimeout(()=>{t.connection&&t.connected&&!t.connection.disconnected&&t.connection.ws.send("1")},6e4)},M=Ve;var m=(t,s)=>{s[0]===x.RequestTypes.Unsubscribe||s[0]===x.RequestTypes.Subscription||s[0]===x.RequestTypes.SendSubscriptionData||s[0]===x.RequestTypes.GetSubscription?t.subscriptionQueue.push(s):t.queue.push(s),t.connected&&!t.drainInProgress&&ie(t)},ie=t=>{t.connected&&!t.drainInProgress&&(t.queue.length||t.subscriptionQueue.length)&&(t.drainInProgress=!0,t.drainTimeout=setTimeout(()=>{if(t.drainInProgress=!1,t.queue.length||t.subscriptionQueue.length){let s=[...t.queue,...t.subscriptionQueue];t.queue=[],t.subscriptionQueue=[],t.connection.ws.send(JSON.stringify(s)),M(t)}},0))},Ce=t=>{t.drainInProgress&&(clearTimeout(t.drainTimeout),t.drainInProgress=!1)};var ne=require("@saulx/hash"),C=(t,s)=>s?(0,ne.hashObjectIgnoreKeyOrder)([s,t]):(0,ne.hashObjectIgnoreKeyOrder)(t);var L=(t,s,e,i,r)=>{i||(i=C(s,r));let n=t.subscriptions[i],o=t.cache[i];if(n)if(n.authError)if(!t.beingAuth)e(n.authError.error,i,0);else{let c=++n.cnt;n.subscribers[c]={onInitial:e}}else if(o)e(null,i,0,o.value);else{let c=++n.cnt;n.subscribers[c]={onInitial:e}}else{n=t.subscriptions[i]={query:s,cnt:1,name:r,subscribers:{1:{onInitial:e}}};let c;for(let a=0;a<t.subscriptionQueue.length;a++){let[u,l,,p]=t.subscriptionQueue[a];(u===E.RequestTypes.Unsubscribe||u===E.RequestTypes.SendSubscriptionData)&&l===i?(t.subscriptionQueue.splice(a,1),a--):(u===E.RequestTypes.Subscription||u===E.RequestTypes.GetSubscription)&&l===i&&(c=!0,u===E.RequestTypes.Subscription&&(p!==o.checksum&&(t.subscriptionQueue[a][3]=o.checksum),t.subscriptionQueue[a][4]=2))}if(!c){let a=[E.RequestTypes.GetSubscription,i,s];o&&a.push(o.checksum),r&&(o||a.push(0),a.push(r)),m(t,a)}}};var w=require("@based/types");var B=(t,s,e,i,r,n,o)=>{n||(n=C(s,o));let c=t.subscriptions[n],a=t.cache[n],u;if(c){u=++c.cnt;let l=!0;for(let p in c.subscribers)if(c.subscribers[p].onData){l=!1;break}if(c.subscribers[u]={onError:r,onData:e,onInitial:i},l){for(let d=0;d<t.subscriptionQueue.length;d++){let[h,v]=t.subscriptionQueue[d];h===w.RequestTypes.GetSubscription&&v===n&&(t.subscriptionQueue.splice(d,1),d--)}let p=[w.RequestTypes.Subscription,n,s];a&&(p.push(a.checksum),p.push(2)),o&&(a||p.push(0,2),p.push(o)),m(t,p)}}else{u=1,c=t.subscriptions[n]={query:s,cnt:1,name:o,subscribers:{1:{onError:r,onData:e,onInitial:i}}};let l=!1,p=!1,d;for(let h=0;h<t.subscriptionQueue.length;h++){let[v,P,,F]=t.subscriptionQueue[h];(v===w.RequestTypes.Unsubscribe||v===w.RequestTypes.SendSubscriptionData||v===w.RequestTypes.GetSubscription)&&P===n?(v===w.RequestTypes.GetSubscription&&(p=!0),d&&(d[4]=2),t.subscriptionQueue.splice(h,1),h--):v===w.RequestTypes.Subscription&&P===n&&(l=!0,d=t.subscriptionQueue[h],F!==a.checksum&&(d[3]=a.checksum),!d[4]&&p&&(d[4]=2))}if(!l){let h=[w.RequestTypes.Subscription,n,s];a&&(h.push(a.checksum),p&&h.push(2)),o&&(a?!p&&a&&h.push(2):h.push(0,0),h.push(o)),m(t,h)}}return a&&(i&&(i(null,n,u),delete c.subscribers[u].onInitial),e&&e(a.value,a.checksum)),[n,u]};var D=require("@based/types");var g=(t,s,e)=>{let i=t.subscriptions[s];if(i){let r=!1;if(e?i.subscribers[e]&&(delete i.subscribers[e],i.cnt--,i.cnt===0&&(r=!0)):r=!0,r){delete t.subscriptions[s];let n=!1;for(let o=0;o<t.subscriptionQueue.length;o++){let[c,a]=t.subscriptionQueue[o];c===D.RequestTypes.Unsubscribe&&a===s?n=!0:(c===D.RequestTypes.Subscription||c===D.RequestTypes.SendSubscriptionData)&&a===s&&(t.subscriptionQueue.splice(o,1),o--)}n||m(t,[D.RequestTypes.Unsubscribe,s])}}};var we=require("@based/types"),Pe=t=>{for(let s=0;s<t.subscriptionQueue.length;s++)t.subscriptionQueue[s][0]===we.RequestTypes.Unsubscribe&&(t.subscriptionQueue.splice(s,1),s--)};var Be=require("@based/types"),qe=t=>{for(let s=0;s<t.subscriptionQueue.length;s++)t.subscriptionQueue[s][0]===Be.RequestTypes.SendSubscriptionData&&(t.subscriptionQueue.splice(s,1),s--)};var H=(t,s=!1)=>{for(let e in t.subscriptions){let i=Number(e),r=t.subscriptions[e];if(s&&!r.authError)continue;let n,o,c;for(let l=0;l<t.subscriptionQueue.length;l++){let[p,d]=t.subscriptionQueue[l];d===i&&(p===10?(c=l,n=t.subscriptionQueue[l]):p===1&&(o=t.subscriptionQueue[l]))}n&&o&&console.error("GET IN Q AND SUB IN Q SHOULD BE IMPOSSIBLE");let a=t.cache[i],u=!1;if(n){let l=!0;for(let p in r.subscribers)if(r.subscribers[p].onData){l=!1;break}l?u=!0:(console.info("not only gets remove get"),t.subscriptionQueue.splice(c,1)),a&&n[3]!==a.checksum&&(n[3]=a.checksum)}if(!u)if(o)a&&o[3]!==a.checksum&&(o[3]=a.checksum,n&&(o[4]=2));else{let{name:l,query:p}=t.subscriptions[i];l?a?m(t,[1,i,p,a.checksum,n?2:0,l]):m(t,[1,i,p,0,n?2:0,l]):a?m(t,[1,i,p,a.checksum,n?2:0]):m(t,[1,i,p,0,n?2:0])}}};var _=(t,s)=>{if(typeof window!="undefined")return t;let e={white:"\x1B[37;1m",reset:"\x1B[0m",blue:"\x1B[34m",red:"\x1B[31m",green:"\x1B[32m",brightBlue:"\x1B[34;1m",brightRed:"\x1B[31;1m"};return`${e[s]}${t}${e.reset}`},oe=(t,s=0,e=!1,i="",r=!1)=>{let n="";for(let a=0;a<s;a++)n+=" ";let o=e?[]:i?[n+`${_(i,r?"brightRed":"white")} {`]:[n+"{"],c=!1;e||(n+=" ",s+=1);for(let a in t){let u=t[a],l=a[0]==="$"?_(a,"white"):a;if(c&&(o[o.length-1]+=","),Array.isArray(u)){o.push(`${n} ${l}: [`);for(let p=0;p<u.length;p++){let d=u[p];o.push(...d&&typeof d=="object"?oe(d,s+4):[`${n} ${d}`]),p!==u.length-1&&(o[o.length-1]+=",")}o.push(`${n} ]`)}else u&&typeof u=="object"?(o.push(`${n} ${l}: {`),o.push(...oe(u,s+2,!0)),o.push(`${n} }`)):o.push(`${n} ${l}: ${u}`);c=!0}return e||o.push(n.slice(0,-1)+"}"),o},z=oe;var q=t=>{let s=new Error(t.message);if(s.name=t.name?`${t.type} from ${t.name}`:t.type,s.stack=null,t.query||t.payload){let e=s.message.split(` | ||
`),i=0;e[0]===""&&e.shift();let r=e[0];for(let n=0;n<r.length;n++)if(r[n]!==" "){i=n-2;break}i>0?e=e.map(n=>n.slice(i)):e=e.map(n=>" "+n),t.code&&(s.code=t.code),s.message=` | ||
`+(t.payload&&typeof t.payload!="object"?` ${H("Payload","brightRed")} ${t.payload}`:_(t.payload||t.query,0,!1,t.payload?"Payload":"Query",!0).map(i=>" "+i).join(` | ||
`+(t.payload&&typeof t.payload!="object"?` ${_("Payload","brightRed")} ${t.payload}`:z(t.payload||t.query,0,!1,t.payload?"Payload":"Query",!0).map(n=>" "+n).join(` | ||
`))+` | ||
`+s.join(` | ||
`+e.join(` | ||
`)+` | ||
`}return e};var Pe=(t,e)=>{let[,s,r,n,i]=e,o=t.subscriptions[s];if(o){let c=t.cache[s]&&t.cache[s].checksum;if(i){let a=B(i);i.auth&&(o.authError={token:t.token,error:a});for(let u in o.subscribers){let l=o.subscribers[u];l.onInitial?i.auth?(l.onError&&l.onError(a),l.onInitial(a,Number(s),Number(u),void 0,!0),delete l.onInitial):(l.onInitial(a,Number(s),Number(u)),delete l.onInitial,g(t,s,Number(u))):l.onError&&l.onError(a)}}else if(c===n){o.authError&&delete o.authError;for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(s),Number(a),t.cache[s].value),delete u.onInitial,u.onData||g(t,s,Number(a)))}}else{o.authError&&delete o.authError,t.cache[s]={value:r,checksum:n};for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(s),Number(a),r),delete u.onInitial,u.onData||g(t,s,Number(a))),u.onData&&u.onData(r,n)}}}};var Be=require("@saulx/diff"),z=require("@based/types");var qe=(t,e)=>{let[,s,r,[n,i]]=e,o=t.subscriptions[s];if(o){let c=t.cache[s];if(!c||c.checksum!==n)if(c)if(c.checksum===i)for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(s),Number(a),c.value),delete u.onInitial,u.onData||g(t,s,Number(a)))}else m(t,[z.RequestTypes.SendSubscriptionData,s]);else m(t,[z.RequestTypes.SendSubscriptionData,s]);else{let a=!1;try{c.value=(0,Be.applyPatch)(c.value,r),c.value===null&&(a=!0)}catch(u){a=!0}if(a)console.warn(` | ||
`}return s};var Ee=(t,s)=>{let[,e,i,r,n]=s,o=t.subscriptions[e];if(o){let c=t.cache[e]&&t.cache[e].checksum;if(n){let a=q(n);n.auth&&(o.authError={token:t.token,error:a});for(let u in o.subscribers){let l=o.subscribers[u];l.onInitial?n.auth?(l.onError&&l.onError(a),l.onInitial(a,Number(e),Number(u),void 0,!0),delete l.onInitial):(l.onInitial(a,Number(e),Number(u)),delete l.onInitial,g(t,e,Number(u))):l.onError&&l.onError(a)}}else if(c===r){o.authError&&delete o.authError;for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(e),Number(a),t.cache[e].value),delete u.onInitial,u.onData||g(t,e,Number(a)))}}else{o.authError&&delete o.authError,t.cache[e]={value:i,checksum:r};for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(e),Number(a),i),delete u.onInitial,u.onData||g(t,e,Number(a))),u.onData&&u.onData(i,r)}}}};var Fe=require("@saulx/diff"),J=require("@based/types");var Qe=(t,s)=>{let[,e,i,[r,n]]=s,o=t.subscriptions[e];if(o){let c=t.cache[e];if(!c||c.checksum!==r)if(c)if(c.checksum===n)for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(e),Number(a),c.value),delete u.onInitial,u.onData||g(t,e,Number(a)))}else m(t,[J.RequestTypes.SendSubscriptionData,e]);else m(t,[J.RequestTypes.SendSubscriptionData,e]);else{let a=!1;try{c.value=(0,Fe.applyPatch)(c.value,i),c.value===null&&(a=!0)}catch(u){a=!0}if(a)console.warn(` | ||
Found corrupt data while applying diff to subscription need to re-fetch | ||
`),console.warn(_(o.query,2,!1,"Query").join(` | ||
`),console.warn(z(o.query,2,!1,"Query").join(` | ||
`)+` | ||
`),delete t.cache[s],m(t,[z.RequestTypes.SendSubscriptionData,s]);else{c.checksum=i;for(let u in o.subscribers){let l=o.subscribers[u];l.onInitial&&(l.onInitial(null,Number(s),Number(u),c.value),delete l.onInitial,l.onData||g(t,s,Number(u))),l.onData&&l.onData(c.value,c.checksum)}}}}};var Ee=(t,e)=>{for(let s of e[1]){delete t.cache[s];let r=t.subscriptions[s];if(r){let n={type:"AuthorizationError",name:r.name?`observe "${r.name}"`:"observe",message:"Unauthorized request",payload:r.query,auth:!0},i=B(n);r.authError={token:t.token,error:i};for(let o in r.subscribers){let c=r.subscribers[o];c.onError&&c.onError(i)}}}};var Fe=require("@based/types");var Ve=0,O=(t,e,s,r,n,i)=>{let o=++Ve;t.requestCallbacks[o]={resolve:r,reject:n},e===Fe.RequestTypes.Call?m(t,[e,i,o,s]):m(t,[e,o,s])};var Qe=(t,e)=>{let[,s,r,n]=e,i=t.requestCallbacks[s];i&&(delete t.requestCallbacks[s],n?i.reject(B(n)):i.resolve(r))};var S=require("@based/types");var ie=require("@based/types");var Xe=t=>typeof t!="undefined"&&t!==null,Ye=(t,e,s)=>{if(t.beingAuth=!0,e)t.token=e,t.sendTokenOptions=s;else{for(let r in t.cache)t.subscriptions[r]||delete t.cache[r];delete t.token,delete t.sendTokenOptions}if(t.connected){let r=e?[ie.RequestTypes.Token,e,s].filter(Xe):[ie.RequestTypes.Token];t.connection.ws.send(JSON.stringify(r)),N(t),L(t,!0)}},D=Ye;var J=class{constructor(e){this.auth=[];this.subscriptions={};this.cache={};this.requestCallbacks={};this.connected=!1;this.subscriptionQueue=[];this.queue=[];this.drainInProgress=!1;this.based=e}onClose(){this.connected=!1,ke(this),Te(this),we(this),this.based.listeners.disconnect&&this.based.listeners.disconnect.forEach(e=>e())}onReconnect(){if(this.based.listeners.reconnect&&this.based.listeners.reconnect.forEach(e=>e()),this.tracking)for(let e of this.tracking)m(this,[S.RequestTypes.Track,{t:e}])}onOpen(){this.connected=!0,this.based.listeners.connect&&this.based.listeners.connect.forEach(e=>e()),this.token&&D(this,this.token,this.sendTokenOptions),L(this),te(this)}onData(e){try{let s=JSON.parse(e.data);if(s[0]===S.RequestTypes.Token){s[1].length&&Ee(this,s);for(let r of this.auth)r(!s[2]);this.beingAuth=!1,this.auth=[]}else s[0]===S.RequestTypes.Set||s[0]===S.RequestTypes.Get||s[0]===S.RequestTypes.Configuration||s[0]===S.RequestTypes.GetConfiguration||s[0]===S.RequestTypes.Call||s[0]===S.RequestTypes.Delete||s[0]===S.RequestTypes.Copy||s[0]===S.RequestTypes.Digest?Qe(this,s):s[0]===S.RequestTypes.Subscription?Pe(this,s):s[0]===S.RequestTypes.SubscriptionDiff&&qe(this,s)}catch(s){console.error("Received incorrect data ",e)}}};var ne=(t,e)=>{let s;if(t.configuration&&t.configuration.schema)for(let r in t.configuration.schema){let n=t.configuration.schema[r];if(n.prefixToTypeMapping){for(let i in n.prefixToTypeMapping)if(n.prefixToTypeMapping[i]===e){s=i;break}}}return s};var ue=require("@saulx/hash");var Ue=require("@based/types"),xe=require("@saulx/hash"),Re=new Set,Ze=t=>{if(typeof window!="undefined"){if(Re.has(t))return!1;Re.add(t);try{let e="_ba:"+(0,xe.hashCompact)(t);return localStorage.getItem(e)?!1:(localStorage.setItem(e,"1"),!0)}catch(e){return!1}}return!1},oe=(t,e)=>{if(e){let s=`${t}`,r=Object.keys(e).sort();for(let n of r)s+="_"+n+"_"+e[n];return s}else return t},I=(t,e,s,r,n,i,o)=>{let c=oe(e,s),a={t:c};o&&(a.r=1),n&&(a.e=1,i&&(a.o=i)),r?(a.s=1,t.tracking.delete(c)):o||(n||(t.tracking||(t.tracking=new Set),t.tracking.add(c)),Ze(c)&&(a.u=1)),m(t,[Ue.RequestTypes.Track,a])};var De=class{constructor(e,s,r){this.closed=!1;this.client=e,this.subId=r,this.subscriberId=s}unsubscribe(){this.closed=!0,g(this.client,this.subId,this.subscriberId)}},Ie=class{constructor(e,s){this.closed=!1;this.client=e,this.subs=s}unsubscribe(){if(!this.closed){this.closed=!0;for(let e of this.subs)e.unsubscribe()}}},ae=class{constructor(e,s){this.client=e,this.components=s}subscribe(e,s,r){let n={data:{}},i=[];for(let{key:o,obs:c}of this.components){let a=c.subscribe(u=>{if(o===""){Object.assign(n.data,u),e(n);return}n.data[o]=u,e(n)},s);i.push(a)}return new Ie(this.client,i)}},w=class{constructor(e,s,r){this.client=e,this.subId=typeof s=="string"?T(r,s):T(s),this.name=typeof s=="string"?s:null,this.payload=typeof s=="string"?r:s}subscribe(e,s,r){let[,n]=P(this.client,this.payload,e,i=>{i&&(console.error(i),s&&s(i))},s,this.subId,this.name);return new De(this.client,n,this.subId)}};var ce={},A={},et=(t,e)=>{ce[t]||(ce[t]=!0,setTimeout(()=>{console.info("Drain file q"),ce[t]=!1;let s=A[t];A[t]=[];let r=new global.FormData;for(let n of s){let{raw:i,name:o,id:c,file:a,functionName:u}=n,l=`${u||""}|${i?1:0}|${c}|${a.size}${o?`|${o}`:""}`;r.append(l,a)}try{let n=new global.XMLHttpRequest;n.upload.onprogress=i=>{let o=100*(i.loaded||i.position)/(i.totalSize||i.total);console.info(o,"upload...")},n.onerror=i=>{console.error("error!",i,"flap",n.responseText)},n.timeout=1e3*60*60*24,n.onabort=i=>{console.error("abort",i)},n.ontimeout=i=>{console.error("on timeout",i)},n.onload=()=>{let i={};try{i=JSON.parse(n.response),console.info("SUCCESS",i)}catch(o){console.error("something wrong with file upload",o)}},n.open("POST",t+"/file"),n.setRequestHeader("Content-Type","multipart/form-data"),n.setRequestHeader("Authorization",e),n.send(r)}catch(n){console.error("Something wrong with xhr upload",n)}},500))},Ae=async(t,e,s,r,n,i,o)=>{A[s]||(A[s]=[]),A[s].push({file:e,id:r,url:s,raw:n,name:i,functionName:o}),et(s,t.getToken())};var Ge=j(require("@based/get-service")),K={},W={},tt=async(t,e)=>{if(e.url)return typeof e.url=="string"?e.url:await e.url();if(!t.opts.env&&t.opts.url)return typeof t.opts.url=="string"?t.opts.url:await t.opts.url();let{env:s,project:r,org:n}=t.opts,i=s+"/"+r+"/"+n+"/"+t.opts.cluster;if(K[i])return K[i];if(W[i])return(await W[i]).url;let o=await(W[i]=(0,Ge.default)({env:s,project:r,org:n,name:"@based/hub",key:"file-upload",optionalKey:!0},0,t.opts.cluster));return delete W[i],setTimeout(()=>{delete K[i]},2e3),K[i]=o.url},$e=tt;var je=j(require("cross-fetch")),V=(t,e,s)=>((0,je.default)(e,{method:"POST",cache:"no-cache",headers:{"Content-Type":s.mimeType||"text/plain","File-Id":s.id,"File-Is-Raw":s.raw?"1":"0","File-Name":s.name||"","Function-Name":s.functionName||"",Authorization:t.getToken()},body:s.contents}).then(r=>{}).catch(r=>{console.error("Error while uploading file",r)}),{id:s.id});var F=require("./file/stream"),X=typeof window!="undefined",st=t=>"src"in t&&typeof t.src=="string",rt=t=>"path"in t&&typeof t.path=="string",it=t=>"contents"in t&&(0,F.isStream)(t.contents),Ne=async(t,e)=>{if(st(e)){let n=e.id?{$id:e.id}:{type:"file"};return e.src?(n.src=e.src,n.origin=e.src,e.size&&(n.size=e.size),e.name&&(n.name=e.name),e.parents&&(n.parents=e.parents),await t.set(n)):void 0}let s=e.id;if(!s){let n={type:"file",progress:0};e.name?n.name=e.name:global.File&&"contents"in e&&e.contents instanceof global.File&&(n.name=e.contents.name),e.parents&&(n.parents=e.parents),s=(await t.set(n)).id}e.id=s;let r=(await $e(t,e)).replace(/^ws/,"http");if(rt(e))return(0,F.uploadFilePath)(t,r,e),{id:s};if(it(e))return(0,F.uploadFileStream)(t,r,e),{id:s};if(e.contents instanceof ArrayBuffer)return e.contents=X?new global.Blob([e.contents],{type:e.mimeType||"text/plain"}):global.Buffer.from(e.contents),V(t,r+"/file",e);if(X&&e.contents instanceof global.Blob)return e.mimeType||(e.mimeType=e.contents.type),V(t,r+"/file",e);if(typeof e.contents=="string"||!X&&e.contents instanceof global.Buffer)return V(t,r+"/file",e);if(X&&e.contents instanceof File)return Ae(t,e.contents,r,e.id,e.raw||!1,e.name,e.functionName),{id:s};throw e.id||await t.delete({$id:s}),new Error(`Invalid contents for file api ${JSON.stringify(e,null,2)}`)};var Y=j(require("@based/get-service")),le=require("@saulx/utils"),y=require("@based/graphql");f(b,require("@based/types"),module.exports);var pe=class extends ge{constructor(e){super();this.client=new J(this),Object.defineProperty(this,"client",{enumerable:!1,writable:!0}),e&&e.url&&this.connect(e.url),this.graphql={query:this.gqlQuery.bind(this),live:this.gqlLive.bind(this)}}connect(e){!e&&this._url?this.client.connection||(this.client.connection=ee(this.client,this._url)):(this._url=e,this.client.connection=ee(this.client,e))}disconnect(){this.client.connection&&(this.client.connection.disconnected=!0,this.client.connection.destroy(),this.client.connection.ws&&this.client.connection.ws.close(),this.client.connected&&this.client.onClose(),delete this.client.connection),this.client.connected=!1}observeUntil(e,s,r){return new Promise((n,i)=>{let o,c=!1;this.observe(e,(a,u)=>{r&&r(a,u),s(a,u)&&(c=!0,o&&o(),n(a))}).then(a=>{c?o():o=a}).catch(a=>{i(a)})})}gql(e,...s){typeof e=="string"&&(e=[e]);let r=e[0];return s.forEach((n,i)=>{n&&n.kind==="Document"?r+=n.loc.source.body:r+=n,r+=e[i+1]}),(0,y.createOperations)({schemas:this.client.configuration.schema},(0,y.parseGraphql)(r))}gqlDb(e="default"){return(s,...r)=>{typeof s=="string"&&(s=[s]);let n=s[0];return r.forEach((i,o)=>{i&&i.kind==="Document"?n+=i.loc.source.body:n+=i,n+=s[o+1]}),(0,y.createOperations)({schemas:this.client.configuration.schema,db:e},(0,y.parseGraphql)(n))}}observe(e,s,r,n){return typeof e=="string"?new Promise((i,o)=>{let c=typeof s=="function",a=c?s:r,u=c?r:n;P(this.client,c?void 0:s,a,(l,p,d,h,v)=>{l&&!v?o(l):i(()=>{g(this.client,p,d)})},u,void 0,e)}):new Promise((i,o)=>{P(this.client,e,s,(c,a,u,l,p)=>{c&&!p?o(c):i(()=>{g(this.client,a,u)})},r)})}createObservable(e,s){return typeof e=="string"?new w(this.client,e,s):new w(this.client,e)}observeSchema(e,s,r){return new Promise((n,i)=>{let o=typeof e=="string"?e:"default",c=typeof e=="string"?s:e,a=typeof e=="string"?r:s;P(this.client,{$subscribe_schema:o},(u,l)=>{this.client.configuration||(this.client.configuration={dbs:[],schema:{},functions:{}}),this.client.configuration.schema[o]=u,c(u,l)},(u,l,p,d,h)=>{u&&!h?i(u):n(()=>{g(this.client,l,p)})},a)})}get(e,s){return typeof e=="string"?new Promise((r,n)=>{M(this.client,s,(i,o,c,a)=>{i?n(i):r(a)},0,e)}):new Promise((r,n)=>{O(this.client,k.RequestTypes.Get,e,r,n)})}file(e){return global.File&&e instanceof File&&(e={contents:e}),Ne(this,e)}call(e,s){return new Promise((r,n)=>{O(this.client,k.RequestTypes.Call,s,r,n,e)})}async id(e,s){let r=ne(this.client,e);if(r||(await this.schema(),r=ne(this.client,e)),!r)throw B({message:`Type does not exist ${e}`,type:"Invalid type",payload:s?{type:e,opts:s}:{type:e}});if(s){let n=(0,ue.hashCompact)(s,8,!0);return r+n}else return r+(0,ue.hashCompact)(Math.floor(Math.random()*99999999999)+""+Date.now())}digest(e){return new Promise((s,r)=>{O(this.client,k.RequestTypes.Digest,e,s,r)})}set(e){return new Promise((s,r)=>{O(this.client,k.RequestTypes.Set,e,s,r)})}copy(e){return new Promise((s,r)=>{O(this.client,k.RequestTypes.Copy,e,s,r)})}async gqlQuery(e,s={}){let r;typeof e=="string"?r=this.gql(e):r=e;try{if(r=(0,y.handleGraphqlVariables)(r,r,s),r.opType==="GET"){let i={$db:r.db},o=[];for(let a in r.ops){if(r.ops[a].fnObserve){let u=await this.get(r.ops[a].fnObserve.name,r.ops[a].fnObserve.payload);o.push({key:a,reply:u});continue}r.ops[a].get&&(i[a]=r.ops[a].get)}let c=await this.get(i);for(let{key:a,reply:u}of o)c[a]=u;return{data:c}}let n={};return await Promise.all(Object.entries(r.ops).map(async([i,o])=>{var l,p,d,h,v;if(o.delete){n[i]=await this.delete(o.delete);return}else if(o.fnCall){n[i]=await this.call(o.fnCall.name,o.fnCall.payload);return}let{id:c}=await this.set(o.set);if(!o.get){let q={};q.id=c;let G=(v=(h=(d=(p=(l=this.client)==null?void 0:l.configuration)==null?void 0:p.schema)==null?void 0:d[r.db])==null?void 0:h.prefixToTypeMapping)==null?void 0:v[c.slice(0,2)];G&&(q.type=G),n[i]=q;return}let a=(0,le.deepCopy)(o.get);a.$id=c;let u=await this.get(a);n[i]=u})),{data:n}}catch(n){return{errors:[{message:n.message,locations:n.locations}]}}}async gqlLive(e,s={}){let r;if(typeof e=="string"?r=this.gql(e):r=e,r=(0,y.handleGraphqlVariables)(r,r,s),r.opType==="GET"){let i=[],o={};for(let c in r.ops){if(r.ops[c].fnObserve){let{name:a,payload:u}=r.ops[c].fnObserve;i.push({key:c,fn:{name:a,payload:u}});continue}o[c]=r.ops[c].get}if(i!=null&&i.length){let c=i.map(u=>({obs:new w(this.client,u.fn.name,u.fn.payload),key:u.key})),a=new w(this.client,me({$db:r.db},o));return c.push({key:"",obs:a}),new ae(this.client,c)}return new w(this.client,{$db:r.db,data:o})}let n={};return await Promise.all(Object.entries(r.ops).map(async([i,o])=>{if(o.delete){n[i]=await this.delete(o.delete);return}else if(o.fnCall){n[i]=await this.call(o.fnCall.name,o.fnCall.payload);return}let{id:c}=await this.set(o.set),a=(0,le.deepCopy)(o.get);a.$id=c,n[i]=a})),new w(this.client,{$db:r.db,data:n})}analytics(e,s){return new Promise((r,n)=>{s?P(this.client,e,s,(i,o,c,a,u)=>{i&&!u?n(i):r(()=>{g(this.client,o,c)})},i=>console.error(i),void 0,"analytics"):M(this.client,e,(i,o,c,a)=>{i?n(i):((0,k.isAnalyticsHistoryOpts)(e)||(0,k.isAnalyticsTypesOpts)(e),r(a))},0,"analytics")})}track(e,s){I(this.client,e,s)}clearAnalytics(e,s){I(this.client,e,s,!1,!1,void 0,!0)}untrack(e,s){I(this.client,e,s,!0)}event(e,s,r){I(this.client,e,s,!1,!0,r)}delete(e){return new Promise((s,r)=>{O(this.client,k.RequestTypes.Delete,e,s,r)})}schema(){return new Promise((e,s)=>{let r=n=>{this.client.configuration=n,e(n)};O(this.client,k.RequestTypes.GetConfiguration,0,r,s)})}updateSchema(e){return new Promise((s,r)=>{O(this.client,k.RequestTypes.Configuration,e,s,r)})}getToken(){return this.client.token}auth(e,s){return new Promise(r=>{this.client.auth.push(r),(e&&e!==this.client.token||e===!1&&this.client.token)&&(typeof e=="string"?D(this.client,e,s):D(this.client),this.emit("auth",e))})}},nt=(t,e)=>{if(e){let s;t+=/\?/.test(t)?"&":"?";for(let r in e){let n=e[r];t+=s?`&${r}=${n}`:`${r}=${n}`,s=!0}}return t},ot=(t,e=pe)=>{let{env:s,project:r,org:n,url:i,key:o,name:c="@based/hub",cluster:a,params:u}=t;if(i||(a=t.cluster=(0,Y.getClusterUrl)(a),i=async()=>{let{url:l}=await(0,Y.default)({env:s,project:r,org:n,key:o,name:c},0,a);return nt(l,u)}),i){let l=new e;return l.opts=t,l.connect(i),l}},at=ot;0&&(module.exports={Based,BasedClient,BasedGraphQL,Observable,addGetSubscriber,addRequest,addSubscriber,createGraphqlOperations,generateSubscriptionId,generateTrackingKey,handleGraphqlVariables,parseGraphql,removeSubscriber}); | ||
`),delete t.cache[e],m(t,[J.RequestTypes.SendSubscriptionData,e]);else{c.checksum=n;for(let u in o.subscribers){let l=o.subscribers[u];l.onInitial&&(l.onInitial(null,Number(e),Number(u),c.value),delete l.onInitial,l.onData||g(t,e,Number(u))),l.onData&&l.onData(c.value,c.checksum)}}}}};var Re=(t,s)=>{for(let e of s[1]){delete t.cache[e];let i=t.subscriptions[e];if(i){let r={type:"AuthorizationError",name:i.name?`observe "${i.name}"`:"observe",message:"Unauthorized request",payload:i.query,auth:!0},n=q(r);i.authError={token:t.token,error:n};for(let o in i.subscribers){let c=i.subscribers[o];c.onError&&c.onError(n)}}}};var Ue=require("@based/types");var Xe=0,O=(t,s,e,i,r,n)=>{let o=++Xe;t.requestCallbacks[o]={resolve:i,reject:r},s===Ue.RequestTypes.Call?m(t,[s,n,o,e]):m(t,[s,o,e])};var xe=(t,s)=>{let[,e,i,r]=s,n=t.requestCallbacks[e];n&&(delete t.requestCallbacks[e],r?n.reject(q(r)):n.resolve(i))};var S=require("@based/types");var ae=require("@based/types");var Ye=t=>typeof t!="undefined"&&t!==null,Ze=(t,s,e)=>{if(t.beingAuth=!0,s)t.token=s,t.sendTokenOptions=e;else{for(let i in t.cache)t.subscriptions[i]||delete t.cache[i];delete t.token,delete t.sendTokenOptions}if(t.connected){let i=s?[ae.RequestTypes.Token,s,e].filter(Ye):[ae.RequestTypes.Token];t.connection.ws.send(JSON.stringify(i)),M(t),H(t,!0)}},I=Ze;var A=class{constructor(s){this.auth=[];this.subscriptions={};this.cache={};this.requestCallbacks={};this.connected=!1;this.subscriptionQueue=[];this.queue=[];this.drainInProgress=!1;this.based=s}onClose(){this.connected=!1,Ce(this),Pe(this),qe(this),this.based.listeners.disconnect&&this.based.listeners.disconnect.forEach(s=>s())}onReconnect(){if(this.based.listeners.reconnect&&this.based.listeners.reconnect.forEach(s=>s()),this.tracking)for(let s of this.tracking)m(this,[S.RequestTypes.Track,{t:s}])}onOpen(){this.connected=!0,this.based.listeners.connect&&this.based.listeners.connect.forEach(s=>s()),this.token&&I(this,this.token,this.sendTokenOptions),H(this),ie(this)}onData(s){try{let e=JSON.parse(s.data);if(e[0]===S.RequestTypes.Token){e[1].length&&Re(this,e);for(let i of this.auth)i(!e[2]);this.beingAuth=!1,this.auth=[]}else e[0]===S.RequestTypes.Set||e[0]===S.RequestTypes.Get||e[0]===S.RequestTypes.Configuration||e[0]===S.RequestTypes.GetConfiguration||e[0]===S.RequestTypes.Call||e[0]===S.RequestTypes.Delete||e[0]===S.RequestTypes.Copy||e[0]===S.RequestTypes.Digest?xe(this,e):e[0]===S.RequestTypes.Subscription?Ee(this,e):e[0]===S.RequestTypes.SubscriptionDiff&&Qe(this,e)}catch(e){console.error("Received incorrect data ",s)}}};var ce=(t,s)=>{let e;if(t.configuration&&t.configuration.schema)for(let i in t.configuration.schema){let r=t.configuration.schema[i];if(r.prefixToTypeMapping){for(let n in r.prefixToTypeMapping)if(r.prefixToTypeMapping[n]===s){e=n;break}}}return e};var fe=require("@saulx/hash");var Ie=require("@based/types"),Ae=require("@saulx/hash"),De=new Set,et=t=>{if(typeof window!="undefined"){if(De.has(t))return!1;De.add(t);try{let s="_ba:"+(0,Ae.hashCompact)(t);return localStorage.getItem(s)?!1:(localStorage.setItem(s,"1"),!0)}catch(s){return!1}}return!1},ue=(t,s)=>{if(s){let e=`${t}`,i=Object.keys(s).sort();for(let r of i)e+="_"+r+"_"+s[r];return e}else return t},G=(t,s,e,i,r,n,o)=>{let c=ue(s,e),a={t:c};o&&(a.r=1),r&&(a.e=1,n&&(a.o=n)),i?(a.s=1,t.tracking.delete(c)):o||(r||(t.tracking||(t.tracking=new Set),t.tracking.add(c)),et(c)&&(a.u=1)),m(t,[Ie.RequestTypes.Track,a])};var le=class{constructor(s,e,i){this.closed=!1;this.client=s,this.subId=i,this.subscriberId=e}unsubscribe(){this.closed=!0,g(this.client,this.subId,this.subscriberId)}},pe=class{constructor(s,e){this.closed=!1;this.client=s,this.subs=e}unsubscribe(){if(!this.closed){this.closed=!0;for(let s of this.subs)s.unsubscribe()}}},K=class{constructor(s,e){this.client=s,this.components=e}subscribe(s,e,i){let r={data:{}},n=[];for(let{key:o,obs:c}of this.components){let a=c.subscribe(u=>{if(o===""){Object.assign(r.data,u),s(r);return}r.data[o]=u,s(r)},e);n.push(a)}return new pe(this.client,n)}},T=class{constructor(s,e,i){this.client=s,this.subId=typeof e=="string"?C(i,e):C(e),this.name=typeof e=="string"?e:null,this.payload=typeof e=="string"?i:e}subscribe(s,e,i){let[,r]=B(this.client,this.payload,s,n=>{n&&(console.error(n),e&&e(n))},e,this.subId,this.name);return new le(this.client,r,this.subId)}};var de={},$={},tt=(t,s)=>{de[t]||(de[t]=!0,setTimeout(()=>{console.info("Drain file q"),de[t]=!1;let e=$[t];$[t]=[];let i=new global.FormData;for(let r of e){let{raw:n,name:o,id:c,file:a,functionName:u}=r,l=`${u||""}|${n?1:0}|${c}|${a.size}${o?`|${o}`:""}`;i.append(l,a)}try{let r=new global.XMLHttpRequest;r.upload.onprogress=n=>{let o=100*(n.loaded||n.position)/(n.totalSize||n.total);console.info(o,"upload...")},r.onerror=n=>{console.error("error!",n,"flap",r.responseText)},r.timeout=1e3*60*60*24,r.onabort=n=>{console.error("abort",n)},r.ontimeout=n=>{console.error("on timeout",n)},r.onload=()=>{let n={};try{n=JSON.parse(r.response),console.info("SUCCESS",n)}catch(o){console.error("something wrong with file upload",o)}},r.open("POST",t+"/file"),r.setRequestHeader("Content-Type","multipart/form-data"),r.setRequestHeader("Authorization",s),r.send(i)}catch(r){console.error("Something wrong with xhr upload",r)}},500))},Ge=async(t,s,e,i,r,n,o)=>{$[e]||($[e]=[]),$[e].push({file:s,id:i,url:e,raw:r,name:n,functionName:o}),tt(e,t.getToken())};var $e=N(require("@based/get-service")),W={},V={},st=async(t,s)=>{if(s.url)return typeof s.url=="string"?s.url:await s.url();if(!t.opts.env&&t.opts.url)return typeof t.opts.url=="string"?t.opts.url:await t.opts.url();let{env:e,project:i,org:r}=t.opts,n=e+"/"+i+"/"+r+"/"+t.opts.cluster;if(W[n])return W[n];if(V[n])return(await V[n]).url;let o=await(V[n]=(0,$e.default)({env:e,project:i,org:r,name:"@based/hub",key:"file-upload",optionalKey:!0},0,t.opts.cluster));return delete V[n],setTimeout(()=>{delete W[n]},2e3),W[n]=o.url},je=st;var Ne=N(require("cross-fetch")),X=(t,s,e)=>((0,Ne.default)(s,{method:"POST",cache:"no-cache",headers:{"Content-Type":e.mimeType||"text/plain","File-Id":e.id,"File-Is-Raw":e.raw?"1":"0","File-Name":e.name||"","Function-Name":e.functionName||"",Authorization:t.getToken()},body:e.contents}).then(i=>{}).catch(i=>{console.error("Error while uploading file",i)}),{id:e.id});var Q=require("./file/stream"),Y=typeof window!="undefined",rt=t=>"src"in t&&typeof t.src=="string",it=t=>"path"in t&&typeof t.path=="string",nt=t=>"contents"in t&&(0,Q.isStream)(t.contents),Me=async(t,s)=>{if(rt(s)){let r=s.id?{$id:s.id}:{type:"file"};return s.src?(r.src=s.src,r.origin=s.src,s.size&&(r.size=s.size),s.name&&(r.name=s.name),s.parents&&(r.parents=s.parents),await t.set(r)):void 0}let e=s.id;if(!e){let r={type:"file",progress:0};s.name?r.name=s.name:global.File&&"contents"in s&&s.contents instanceof global.File&&(r.name=s.contents.name),s.parents&&(r.parents=s.parents),e=(await t.set(r)).id}s.id=e;let i=(await je(t,s)).replace(/^ws/,"http");if(it(s))return(0,Q.uploadFilePath)(t,i,s),{id:e};if(nt(s))return(0,Q.uploadFileStream)(t,i,s),{id:e};if(s.contents instanceof ArrayBuffer)return s.contents=Y?new global.Blob([s.contents],{type:s.mimeType||"text/plain"}):global.Buffer.from(s.contents),X(t,i+"/file",s);if(Y&&s.contents instanceof global.Blob)return s.mimeType||(s.mimeType=s.contents.type),X(t,i+"/file",s);if(typeof s.contents=="string"||!Y&&s.contents instanceof global.Buffer)return X(t,i+"/file",s);if(Y&&s.contents instanceof File)return Ge(t,s.contents,i,s.id,s.raw||!1,s.name,s.functionName),{id:e};throw s.id||await t.delete({$id:e}),new Error(`Invalid contents for file api ${JSON.stringify(s,null,2)}`)};var ee=N(require("@based/get-service")),be=require("@saulx/utils"),y=require("@based/graphql");b(f,require("@based/types"),module.exports);var Z=class extends Se{constructor(e){super();this.client=new A(this),Object.defineProperty(this,"client",{enumerable:!1,writable:!0}),e&&e.url&&this.connect(e.url),this.graphql={query:this.gqlQuery.bind(this),live:this.gqlLive.bind(this)}}connect(e){!e&&this._url?this.client.connection||(this.client.connection=re(this.client,this._url)):(this._url=e,this.client.connection=re(this.client,e))}disconnect(){this.client.connection&&(this.client.connection.disconnected=!0,this.client.connection.destroy(),this.client.connection.ws&&this.client.connection.ws.close(),this.client.connected&&this.client.onClose(),delete this.client.connection),this.client.connected=!1}observeUntil(e,i,r){return new Promise((n,o)=>{let c,a=!1;this.observe(e,(u,l)=>{r&&r(u,l),i(u,l)&&(a=!0,c&&c(),n(u))}).then(u=>{a?c():c=u}).catch(u=>{o(u)})})}gql(e,...i){typeof e=="string"&&(e=[e]);let r=e[0];return i.forEach((n,o)=>{n&&n.kind==="Document"?r+=n.loc.source.body:r+=n,r+=e[o+1]}),(0,y.createOperations)({schemas:this.client.configuration.schema},(0,y.parseGraphql)(r))}gqlDb(e="default"){return(i,...r)=>{typeof i=="string"&&(i=[i]);let n=i[0];return r.forEach((o,c)=>{o&&o.kind==="Document"?n+=o.loc.source.body:n+=o,n+=i[c+1]}),(0,y.createOperations)({schemas:this.client.configuration.schema,db:e},(0,y.parseGraphql)(n))}}observe(e,i,r,n){return typeof e=="string"?new Promise((o,c)=>{let a=typeof i=="function",u=a?i:r,l=a?r:n;B(this.client,a?void 0:i,u,(p,d,h,v,P)=>{p&&!P?c(p):o(()=>{g(this.client,d,h)})},l,void 0,e)}):new Promise((o,c)=>{B(this.client,e,i,(a,u,l,p,d)=>{a&&!d?c(a):o(()=>{g(this.client,u,l)})},r)})}createObservable(e,i){return typeof e=="string"?new T(this.client,e,i):new T(this.client,e)}observeSchema(e,i,r){return new Promise((n,o)=>{let c=typeof e=="string"?e:"default",a=typeof e=="string"?i:e,u=typeof e=="string"?r:i;B(this.client,{$subscribe_schema:c},(l,p)=>{this.client.configuration||(this.client.configuration={dbs:[],schema:{},functions:{}}),this.client.configuration.schema[c]=l,a(l,p)},(l,p,d,h,v)=>{l&&!v?o(l):n(()=>{g(this.client,p,d)})},u)})}get(e,i){return typeof e=="string"?new Promise((r,n)=>{L(this.client,i,(o,c,a,u)=>{o?n(o):r(u)},0,e)}):new Promise((r,n)=>{O(this.client,k.RequestTypes.Get,e,r,n)})}file(e){return global.File&&e instanceof File&&(e={contents:e}),Me(this,e)}call(e,i){return new Promise((r,n)=>{O(this.client,k.RequestTypes.Call,i,r,n,e)})}async id(e,i){let r=ce(this.client,e);if(r||(await this.schema(),r=ce(this.client,e)),!r)throw q({message:`Type does not exist ${e}`,type:"Invalid type",payload:i?{type:e,opts:i}:{type:e}});if(i){let n=(0,fe.hashCompact)(i,8,!0);return r+n}else return r+(0,fe.hashCompact)(Math.floor(Math.random()*99999999999)+""+Date.now())}digest(e){return new Promise((i,r)=>{O(this.client,k.RequestTypes.Digest,e,i,r)})}set(e){return new Promise((i,r)=>{O(this.client,k.RequestTypes.Set,e,i,r)})}copy(e){return new Promise((i,r)=>{O(this.client,k.RequestTypes.Copy,e,i,r)})}async gqlQuery(e,i={}){let r;typeof e=="string"?r=this.gql(e):r=e;try{if(r=(0,y.handleGraphqlVariables)(r,r,i),r.opType==="GET"){let o={$db:r.db},c=[];for(let u in r.ops){if(r.ops[u].fnObserve){let l=await this.get(r.ops[u].fnObserve.name,r.ops[u].fnObserve.payload);c.push({key:u,reply:l});continue}r.ops[u].get&&(o[u]=r.ops[u].get)}let a=await this.get(o);for(let{key:u,reply:l}of c)a[u]=l;return{data:a}}let n={};return await Promise.all(Object.entries(r.ops).map(async([o,c])=>{var p,d,h,v,P;if(c.delete){n[o]=await this.delete(c.delete);return}else if(c.fnCall){n[o]=await this.call(c.fnCall.name,c.fnCall.payload);return}let{id:a}=await this.set(c.set);if(!c.get){let F={};F.id=a;let me=(P=(v=(h=(d=(p=this.client)==null?void 0:p.configuration)==null?void 0:d.schema)==null?void 0:h[r.db])==null?void 0:v.prefixToTypeMapping)==null?void 0:P[a.slice(0,2)];me&&(F.type=me),n[o]=F;return}let u=(0,be.deepCopy)(c.get);u.$id=a;let l=await this.get(u);n[o]=l})),{data:n}}catch(n){return{errors:[{message:n.message,locations:n.locations}]}}}async gqlLive(e,i={}){let r;if(typeof e=="string"?r=this.gql(e):r=e,r=(0,y.handleGraphqlVariables)(r,r,i),r.opType==="GET"){let o=[],c={};for(let a in r.ops){if(r.ops[a].fnObserve){let{name:u,payload:l}=r.ops[a].fnObserve;o.push({key:a,fn:{name:u,payload:l}});continue}c[a]=r.ops[a].get}if(o!=null&&o.length){let a=o.map(l=>({obs:new T(this.client,l.fn.name,l.fn.payload),key:l.key})),u=new T(this.client,ve({$db:r.db},c));return a.push({key:"",obs:u}),new K(this.client,a)}return new T(this.client,{$db:r.db,data:c})}let n={};return await Promise.all(Object.entries(r.ops).map(async([o,c])=>{if(c.delete){n[o]=await this.delete(c.delete);return}else if(c.fnCall){n[o]=await this.call(c.fnCall.name,c.fnCall.payload);return}let{id:a}=await this.set(c.set),u=(0,be.deepCopy)(c.get);u.$id=a,n[o]=u})),new T(this.client,{$db:r.db,data:n})}analytics(e,i){return new Promise((r,n)=>{i?B(this.client,e,i,(o,c,a,u,l)=>{o&&!l?n(o):r(()=>{g(this.client,c,a)})},o=>console.error(o),void 0,"analytics"):L(this.client,e,(o,c,a,u)=>{o?n(o):((0,k.isAnalyticsHistoryOpts)(e)||(0,k.isAnalyticsTypesOpts)(e),r(u))},0,"analytics")})}track(e,i){G(this.client,e,i)}clearAnalytics(e,i){G(this.client,e,i,!1,!1,void 0,!0)}untrack(e,i){G(this.client,e,i,!0)}event(e,i,r){G(this.client,e,i,!1,!0,r)}delete(e){return new Promise((i,r)=>{O(this.client,k.RequestTypes.Delete,e,i,r)})}schema(){return new Promise((e,i)=>{let r=n=>{this.client.configuration=n,e(n)};O(this.client,k.RequestTypes.GetConfiguration,0,r,i)})}updateSchema(e){return new Promise((i,r)=>{O(this.client,k.RequestTypes.Configuration,e,i,r)})}getToken(){return this.client.token}auth(e,i){return new Promise(r=>{this.client.auth.push(r),(e&&e!==this.client.token||e===!1&&this.client.token)&&(typeof e=="string"?I(this.client,e,i):I(this.client),this.emit("auth",e))})}},ot=(t,s)=>{if(s){let e;t+=/\?/.test(t)?"&":"?";for(let i in s){let r=s[i];t+=e?`&${i}=${r}`:`${i}=${r}`,e=!0}}return t},at=(t,s=Z)=>{let{env:e,project:i,org:r,url:n,key:o,name:c="@based/hub",cluster:a,params:u}=t;if(n||(a=t.cluster=(0,ee.getClusterUrl)(a),n=async()=>{let{url:l}=await(0,ee.default)({env:e,project:i,org:r,key:o,name:c},0,a);return ot(l,u)}),n){let l=new s;return l.opts=t,l.connect(n),l}},ct=at;0&&(module.exports={Based,BasedClient,BasedGraphQL,Observable,addGetSubscriber,addRequest,addSubscriber,createGraphqlOperations,generateSubscriptionId,generateTrackingKey,handleGraphqlVariables,parseGraphql,removeSubscriber}); |
"use strict"; | ||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
if (k2 === undefined) k2 = k; | ||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | ||
var desc = Object.getOwnPropertyDescriptor(m, k); | ||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
desc = { enumerable: true, get: function() { return m[k]; } }; | ||
} | ||
Object.defineProperty(o, k2, desc); | ||
}) : (function(o, m, k, k2) { | ||
@@ -6,0 +10,0 @@ if (k2 === undefined) k2 = k; |
{ | ||
"name": "@based/client", | ||
"version": "1.2.5", | ||
"version": "2.2.0", | ||
"license": "MIT", | ||
"main": "dist/index.js", | ||
@@ -13,9 +14,10 @@ "browser": { | ||
"test": "ava --timeout 1m --verbose", | ||
"watchTest": "ava --color --watch --verbose" | ||
"watchTest": "ava --color --watch --verbose", | ||
"clean": "rimraf {.turbo,dist,node_modules}" | ||
}, | ||
"sideEffects": false, | ||
"dependencies": { | ||
"@based/get-service": "0.2.8", | ||
"@based/graphql": "^1.0.6", | ||
"@based/types": "^1.0.1", | ||
"@based/get-service": "*", | ||
"@based/graphql": "*", | ||
"@based/types": "*", | ||
"@saulx/diff": "^1.1.3", | ||
@@ -46,3 +48,3 @@ "@saulx/hash": "^1.1.0", | ||
"@types/jsonwebtoken": "^8.5.6", | ||
"@types/node": "^16.3.1", | ||
"@types/node": "^17.0.23", | ||
"@types/ws": "^7.4.6", | ||
@@ -52,4 +54,5 @@ "ava": "3.15.0", | ||
"ts-node": "^10.1.0", | ||
"typescript": "^4.3.5" | ||
"typescript": "^4.3.5", | ||
"rimraf": "^3.0.2" | ||
} | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Wildcard dependency
QualityPackage has a dependency with a floating version range. This can cause issues if the dependency publishes a new major version.
Found 3 instances in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No License Found
License(Experimental) License information could not be found.
Found 1 instance in 1 package
189797
0
2651
12
4
+ Added@based/get-service@2.4.3(transitive)
+ Added@based/graphql@3.0.0(transitive)
+ Added@based/types@3.0.0(transitive)
- Removed@based/get-service@0.2.8(transitive)
- Removed@based/graphql@1.0.8(transitive)
- Removed@based/types@1.0.1(transitive)
Updated@based/get-service@*
Updated@based/graphql@*
Updated@based/types@*