@based/client
Advanced tools
Comparing version 2.5.1 to 2.6.0
import { Connection } from './websocket/types'; | ||
import { GenericObject, RequestMessage, SubscriptionMessage, FunctionCallMessage, Configuration, TrackMessage, SendTokenOptions } from '@based/types'; | ||
import { RequestTypes, GenericObject, RequestMessage, SubscriptionMessage, FunctionCallMessage, Configuration, TrackMessage, SendTokenOptions, AuthMessage } from '@based/types'; | ||
import { Based } from './'; | ||
@@ -10,3 +10,5 @@ export * from '@based/types'; | ||
sendTokenOptions: SendTokenOptions; | ||
retryingRenewToken: boolean; | ||
beingAuth: boolean; | ||
isLogginIn: boolean; | ||
auth: ((x?: any) => void)[]; | ||
@@ -41,4 +43,14 @@ subscriptions: { | ||
reject: (err: Error) => void; | ||
type?: Exclude<RequestTypes, RequestTypes.Subscription | RequestTypes.SubscriptionDiff | RequestTypes.SendSubscriptionData | RequestTypes.Unsubscribe | RequestTypes.GetSubscription | RequestTypes.Token | RequestTypes.Track>; | ||
payload?: any; | ||
name?: string; | ||
isRetry?: boolean; | ||
}; | ||
}; | ||
authCallbacks: { | ||
[reqId: string]: { | ||
resolve: (val?: any) => void; | ||
reject: (err: Error) => void; | ||
}; | ||
}; | ||
tracking: Set<string>; | ||
@@ -49,3 +61,3 @@ configuration: Configuration; | ||
subscriptionQueue: SubscriptionMessage[]; | ||
queue: (RequestMessage | FunctionCallMessage | TrackMessage)[]; | ||
queue: (RequestMessage | FunctionCallMessage | TrackMessage | AuthMessage)[]; | ||
drainInProgress: boolean; | ||
@@ -52,0 +64,0 @@ drainTimeout: ReturnType<typeof setTimeout>; |
@@ -26,2 +26,4 @@ "use strict"; | ||
const token_1 = __importDefault(require("./token")); | ||
const auth_1 = require("./auth"); | ||
const auth_2 = require("./auth"); | ||
__exportStar(require("@based/types"), exports); | ||
@@ -34,2 +36,3 @@ class BasedClient { | ||
this.requestCallbacks = {}; | ||
this.authCallbacks = {}; | ||
this.connected = false; | ||
@@ -76,10 +79,11 @@ this.subscriptionQueue = []; | ||
const data = JSON.parse(d.data); | ||
if (data[0] === types_1.RequestTypes.Token) { | ||
const [type, reqId, payload, err] = data; | ||
if (type === types_1.RequestTypes.Token) { | ||
this.retryingRenewToken = false; | ||
// means stomething got de-auth wrong | ||
if (data[1].length) { | ||
if (reqId.length) { | ||
(0, subscriptions_1.logoutSubscriptions)(this, data); | ||
} | ||
// console.info(data, data[2]) | ||
for (const fn of this.auth) { | ||
fn(!data[2]); | ||
fn(!payload); | ||
} | ||
@@ -89,20 +93,44 @@ this.beingAuth = false; | ||
} | ||
else if (data[0] === types_1.RequestTypes.Set || | ||
data[0] === types_1.RequestTypes.Get || | ||
data[0] === types_1.RequestTypes.Configuration || | ||
data[0] === types_1.RequestTypes.GetConfiguration || | ||
data[0] === types_1.RequestTypes.Call || | ||
data[0] === types_1.RequestTypes.Delete || | ||
data[0] === types_1.RequestTypes.Copy || | ||
data[0] === types_1.RequestTypes.Digest || | ||
data[0] === types_1.RequestTypes.RemoveType || | ||
data[0] === types_1.RequestTypes.RemoveField) { | ||
(0, request_1.incomingRequest)(this, data); | ||
else if (type === types_1.RequestTypes.Auth) { | ||
(0, auth_1.incomingAuthRequest)(this, data); | ||
} | ||
else if (data[0] === types_1.RequestTypes.Subscription) { | ||
(0, subscriptions_1.incomingSubscription)(this, data); | ||
else { | ||
if (err?.code === types_1.BasedErrorCodes.TokenExpired && | ||
!this.retryingRenewToken) { | ||
this.retryingRenewToken = true; | ||
const refreshToken = this.sendTokenOptions?.refreshToken; | ||
(0, auth_2.renewToken)(this, { | ||
refreshToken, | ||
}) | ||
.then((result) => { | ||
(0, token_1.default)(this, result.token, this.sendTokenOptions); | ||
(0, request_1.addRequest)(this, | ||
// @ts-ignore | ||
type, err?.payload, this.requestCallbacks[reqId].resolve, this.requestCallbacks[reqId].reject); | ||
}) | ||
.catch((err) => { | ||
this.requestCallbacks[reqId].reject(err); | ||
}); | ||
} | ||
else { | ||
if (type === types_1.RequestTypes.Set || | ||
type === types_1.RequestTypes.Get || | ||
type === types_1.RequestTypes.Configuration || | ||
type === types_1.RequestTypes.GetConfiguration || | ||
type === types_1.RequestTypes.Call || | ||
type === types_1.RequestTypes.Delete || | ||
type === types_1.RequestTypes.Copy || | ||
type === types_1.RequestTypes.Digest || | ||
type === types_1.RequestTypes.RemoveType || | ||
type === types_1.RequestTypes.RemoveField) { | ||
(0, request_1.incomingRequest)(this, data); | ||
} | ||
else if (type === types_1.RequestTypes.Subscription) { | ||
(0, subscriptions_1.incomingSubscription)(this, data); | ||
} | ||
else if (type === types_1.RequestTypes.SubscriptionDiff) { | ||
(0, subscriptions_1.incomingSubscriptionDiff)(this, data); | ||
} | ||
} | ||
} | ||
else if (data[0] === types_1.RequestTypes.SubscriptionDiff) { | ||
(0, subscriptions_1.incomingSubscriptionDiff)(this, data); | ||
} | ||
} | ||
@@ -109,0 +137,0 @@ catch (err) { |
@@ -1,5 +0,3 @@ | ||
import { ErrorObject } from '@based/types'; | ||
declare const _default: (err: ErrorObject) => Error & { | ||
code?: string; | ||
}; | ||
import { ErrorObject, BasedError } from '@based/types'; | ||
declare const _default: (err: ErrorObject) => BasedError; | ||
export default _default; |
@@ -26,5 +26,6 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const types_1 = require("@based/types"); | ||
const printBasedObject_1 = __importStar(require("./printBasedObject")); | ||
exports.default = (err) => { | ||
const x = new Error(err.message); | ||
const x = new types_1.BasedError(err.message); | ||
x.name = err.name ? `${err.type} from ${err.name}` : err.type; | ||
@@ -31,0 +32,0 @@ x.stack = null; |
import Emitter from './Emitter'; | ||
import { GenericObject, Configuration, Query, DigestOptions, SetOptions, Copy, SendTokenOptions, TrackOpts, AnalyticsTypes, AnalyticsResult, AnalyticsOpts, AnalyticsTypesOpts, AnalyticsHistoryOpts, FileUploadOptions, FileUploadSrc, FileUploadPath, FileUploadStream, AnalyticsHistoryResult } from '@based/types'; | ||
import { GenericObject, Configuration, Query, DigestOptions, SetOptions, Copy, SendTokenOptions, TrackOpts, AnalyticsTypes, AnalyticsResult, AnalyticsOpts, AnalyticsTypesOpts, AnalyticsHistoryOpts, FileUploadOptions, FileUploadSrc, FileUploadPath, FileUploadStream, AnalyticsHistoryResult, LoginOpts } from '@based/types'; | ||
import { addSubscriber, generateSubscriptionId, addGetSubscriber, removeSubscriber } from './subscriptions'; | ||
@@ -102,2 +102,4 @@ import { addRequest } from './request'; | ||
auth(token: string | false, options?: SendTokenOptions): Promise<false | string | number>; | ||
login(opts: LoginOpts): Promise<GenericObject>; | ||
logout(): Promise<GenericObject>; | ||
} | ||
@@ -104,0 +106,0 @@ export declare type BasedOpts = { |
@@ -1,15 +0,15 @@ | ||
var ze=Object.create;var D=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames,ye=Object.getOwnPropertySymbols,We=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty,Ve=Object.prototype.propertyIsEnumerable;var ve=(t,s,e)=>s in t?D(t,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[s]=e,ke=(t,s)=>{for(var e in s||(s={}))Se.call(s,e)&&ve(t,e,s[e]);if(ye)for(var e of ye(s))Ve.call(s,e)&&ve(t,e,s[e]);return t};var Te=(t,s)=>{for(var e in s)D(t,e,{get:s[e],enumerable:!0})},M=(t,s,e,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of Ke(s))!Se.call(t,r)&&r!==e&&D(t,r,{get:()=>s[r],enumerable:!(i=Je(s,r))||i.enumerable});return t},d=(t,s,e)=>(M(t,s,"default"),e&&M(e,s,"default")),L=(t,s,e)=>(e=t!=null?ze(We(t)):{},M(s||!t||!t.__esModule?D(e,"default",{value:t,enumerable:!0}):e,t)),Xe=t=>M(D({},"__esModule",{value:!0}),t);var b={};Te(b,{Based:()=>te,BasedClient:()=>U,BasedGraphQL:()=>S.BasedGraphQL,Observable:()=>C,addGetSubscriber:()=>_,addRequest:()=>T,addSubscriber:()=>F,createGraphqlOperations:()=>S.createOperations,default:()=>lt,generateSubscriptionId:()=>w,generateTrackingKey:()=>pe,handleGraphqlVariables:()=>S.handleGraphqlVariables,parseGraphql:()=>S.parseGraphql,removeSubscriber:()=>g});module.exports=Xe(b);var re=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}}}},Oe=re;var Ce=(t,s)=>{typeof t=="function"?t().then(e=>{s(e)}):s(t)};var Pe=L(require("isomorphic-ws")),I=new Map,we;typeof window!="undefined"&&document.addEventListener("visibilitychange",function(){clearTimeout(we),document.hidden?we=setTimeout(()=>{I.forEach(t=>{t(!1)})},3e4):I.forEach(t=>{t(!0)})});var ie=(t,s,e={destroy:()=>{I.delete(e)}},i=0,r=!1)=>(Ce(s,n=>{setTimeout(()=>{if(e.disconnected)return;let o=!0;I.set(e,a=>{e.disconnected||(!a&&o?(console.warn("Send to background - close connection"),o=!1,t.onClose(),c.close()):!o&&a&&(I.delete(e),ie(t,s,e,0,!0)))});let c=e.ws=new Pe.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(),ie(t,s,e,Math.min(1250,Math.min(i+500)),!0)}}},i)}),e),ne=ie;var v=require("@based/types");var E=require("@based/types");var A=require("@based/types");var Ye=t=>{clearTimeout(t.idlePing),t.idlePing=setTimeout(()=>{t.connection&&t.connected&&!t.connection.disconnected&&t.connection.ws.send("1")},6e4)},H=Ye;var m=(t,s)=>{s[0]===A.RequestTypes.Unsubscribe||s[0]===A.RequestTypes.Subscription||s[0]===A.RequestTypes.SendSubscriptionData||s[0]===A.RequestTypes.GetSubscription?t.subscriptionQueue.push(s):t.queue.push(s),t.connected&&!t.drainInProgress&&oe(t)},oe=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)),H(t)}},0))},Be=t=>{t.drainInProgress&&(clearTimeout(t.drainTimeout),t.drainInProgress=!1)};var ae=require("@saulx/hash"),w=(t,s)=>s?(0,ae.hashObjectIgnoreKeyOrder)([s,t]):(0,ae.hashObjectIgnoreKeyOrder)(t);var _=(t,s,e,i,r)=>{i||(i=w(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 P=require("@based/types");var F=(t,s,e,i,r,n,o)=>{n||(n=w(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 f=0;f<t.subscriptionQueue.length;f++){let[h,k]=t.subscriptionQueue[f];h===P.RequestTypes.GetSubscription&&k===n&&(t.subscriptionQueue.splice(f,1),f--)}let p=[P.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,f;for(let h=0;h<t.subscriptionQueue.length;h++){let[k,B,,R]=t.subscriptionQueue[h];(k===P.RequestTypes.Unsubscribe||k===P.RequestTypes.SendSubscriptionData||k===P.RequestTypes.GetSubscription)&&B===n?(k===P.RequestTypes.GetSubscription&&(p=!0),f&&(f[4]=2),t.subscriptionQueue.splice(h,1),h--):k===P.RequestTypes.Subscription&&B===n&&(l=!0,f=t.subscriptionQueue[h],R!==a.checksum&&(f[3]=a.checksum),!f[4]&&p&&(f[4]=2))}if(!l){let h=[P.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 G=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===G.RequestTypes.Unsubscribe&&a===s?n=!0:(c===G.RequestTypes.Subscription||c===G.RequestTypes.SendSubscriptionData)&&a===s&&(t.subscriptionQueue.splice(o,1),o--)}n||m(t,[G.RequestTypes.Unsubscribe,s])}}};var Fe=require("@based/types"),qe=t=>{for(let s=0;s<t.subscriptionQueue.length;s++)t.subscriptionQueue[s][0]===Fe.RequestTypes.Unsubscribe&&(t.subscriptionQueue.splice(s,1),s--)};var Ee=require("@based/types"),Qe=t=>{for(let s=0;s<t.subscriptionQueue.length;s++)t.subscriptionQueue[s][0]===Ee.RequestTypes.SendSubscriptionData&&(t.subscriptionQueue.splice(s,1),s--)};var Q=require("@based/types");var z=(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,f]=t.subscriptionQueue[l];f===i&&(p===Q.RequestTypes.GetSubscription?(c=l,n=t.subscriptionQueue[l]):p===Q.RequestTypes.Subscription&&(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,[Q.RequestTypes.Subscription,i,p,a.checksum,n?2:0,l]):m(t,[Q.RequestTypes.Subscription,i,p,0,n?2:0,l]):a?m(t,[Q.RequestTypes.Subscription,i,p,a.checksum,n?2:0]):m(t,[Q.RequestTypes.Subscription,i,p,0,n?2:0])}}};var J=(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}`},ce=(t,s=0,e=!1,i="",r=!1)=>{let n="";for(let a=0;a<s;a++)n+=" ";let o=e?[]:i?[n+`${J(i,r?"brightRed":"white")} {`]:[n+"{"],c=!1;e||(n+=" ",s+=1);for(let a in t){let u=t[a],l=a[0]==="$"?J(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 f=u[p];o.push(...f&&typeof f=="object"?ce(f,s+4):[`${n} ${f}`]),p!==u.length-1&&(o[o.length-1]+=",")}o.push(`${n} ]`)}else u&&typeof u=="object"?(o.push(`${n} ${l}: {`),o.push(...ce(u,s+2,!0)),o.push(`${n} }`)):o.push(`${n} ${l}: ${u}`);c=!0}return e||o.push(n.slice(0,-1)+"}"),o},K=ce;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=` | ||
var Ze=Object.create;var U=Object.defineProperty;var et=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames,ke=Object.getOwnPropertySymbols,st=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty,rt=Object.prototype.propertyIsEnumerable;var Se=(e,s,t)=>s in e?U(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t,Oe=(e,s)=>{for(var t in s||(s={}))Te.call(s,t)&&Se(e,t,s[t]);if(ke)for(var t of ke(s))rt.call(s,t)&&Se(e,t,s[t]);return e};var Ce=(e,s)=>{for(var t in s)U(e,t,{get:s[t],enumerable:!0})},L=(e,s,t,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of tt(s))!Te.call(e,r)&&r!==t&&U(e,r,{get:()=>s[r],enumerable:!(i=et(s,r))||i.enumerable});return e},d=(e,s,t)=>(L(e,s,"default"),t&&L(t,s,"default")),H=(e,s,t)=>(t=e!=null?Ze(st(e)):{},L(s||!e||!e.__esModule?U(t,"default",{value:e,enumerable:!0}):t,e)),it=e=>L(U({},"__esModule",{value:!0}),e);var m={};Ce(m,{Based:()=>se,BasedClient:()=>D,BasedGraphQL:()=>S.BasedGraphQL,Observable:()=>P,addGetSubscriber:()=>z,addRequest:()=>k,addSubscriber:()=>E,createGraphqlOperations:()=>S.createOperations,default:()=>gt,generateSubscriptionId:()=>q,generateTrackingKey:()=>be,handleGraphqlVariables:()=>S.handleGraphqlVariables,parseGraphql:()=>S.parseGraphql,removeSubscriber:()=>y});module.exports=it(m);var ie=class{constructor(){this.listeners={};Object.defineProperty(this,"listeners",{enumerable:!1,writable:!0})}emit(s,t){this.listeners[s]&&this.listeners[s].forEach(i=>i(t))}on(s,t){this.listeners[s]||(this.listeners[s]=[]),this.listeners[s].push(t)}removeAllListeners(){this.listeners={}}once(s,t){this.on(s,i=>{t(i),this.removeListener(s,t)})}removeListener(s,t){let i=this.listeners[s];if(i){if(!t)delete this.listeners[s];else for(let r=0,n=i.length;r<n;r++)if(i[r]===t){i.splice(r,1);break}}}},we=ie;var Pe=(e,s)=>{typeof e=="function"?e().then(t=>{s(t)}):s(e)};var Be=H(require("isomorphic-ws")),G=new Map,qe;typeof window!="undefined"&&document.addEventListener("visibilitychange",function(){clearTimeout(qe),document.hidden?qe=setTimeout(()=>{G.forEach(e=>{e(!1)})},3e4):G.forEach(e=>{e(!0)})});var ne=(e,s,t={destroy:()=>{G.delete(t)}},i=0,r=!1)=>(Pe(s,n=>{setTimeout(()=>{if(t.disconnected)return;let o=!0;G.set(t,a=>{t.disconnected||(!a&&o?(console.warn("Send to background - close connection"),o=!1,e.onClose(),c.close()):!o&&a&&(G.delete(t),ne(e,s,t,0,!0)))});let c=t.ws=new Be.default(n);c.onerror=()=>{},c.onmessage=a=>e.onData(a),c.onopen=()=>{if(o){if(t.disconnected)return;i=100,r&&e.onReconnect(),e.onOpen()}},c.onclose=()=>{if(o){if(t.disconnected)return;e.onClose(),ne(e,s,t,Math.min(1250,Math.min(i+500)),!0)}}},i)}),t),oe=ne;var v=require("@based/types");var Q=require("@based/types");var j=require("@based/types");var nt=e=>{clearTimeout(e.idlePing),e.idlePing=setTimeout(()=>{e.connection&&e.connected&&!e.connection.disconnected&&e.connection.ws.send("1")},6e4)},_=nt;var f=(e,s)=>{s[0]===j.RequestTypes.Unsubscribe||s[0]===j.RequestTypes.Subscription||s[0]===j.RequestTypes.SendSubscriptionData||s[0]===j.RequestTypes.GetSubscription?e.subscriptionQueue.push(s):e.queue.push(s),e.connected&&!e.drainInProgress&&ae(e)},ae=e=>{e.connected&&!e.drainInProgress&&(e.queue.length||e.subscriptionQueue.length)&&!e.isLogginIn&&(e.drainInProgress=!0,e.drainTimeout=setTimeout(()=>{if(e.drainInProgress=!1,e.queue.length||e.subscriptionQueue.length){let s=[...e.queue,...e.subscriptionQueue];e.queue=[],e.subscriptionQueue=[],e.connection.ws.send(JSON.stringify(s)),_(e)}},0))},Re=e=>{e.drainInProgress&&(clearTimeout(e.drainTimeout),e.drainInProgress=!1)};var ce=require("@saulx/hash"),q=(e,s)=>s?(0,ce.hashObjectIgnoreKeyOrder)([s,e]):(0,ce.hashObjectIgnoreKeyOrder)(e);var z=(e,s,t,i,r)=>{i||(i=q(s,r));let n=e.subscriptions[i],o=e.cache[i];if(n)if(n.authError)if(!e.beingAuth)t(n.authError.error,i,0);else{let c=++n.cnt;n.subscribers[c]={onInitial:t}}else if(o)t(null,i,0,o.value);else{let c=++n.cnt;n.subscribers[c]={onInitial:t}}else{n=e.subscriptions[i]={query:s,cnt:1,name:r,subscribers:{1:{onInitial:t}}};let c;for(let a=0;a<e.subscriptionQueue.length;a++){let[u,l,,p]=e.subscriptionQueue[a];(u===Q.RequestTypes.Unsubscribe||u===Q.RequestTypes.SendSubscriptionData)&&l===i?(e.subscriptionQueue.splice(a,1),a--):(u===Q.RequestTypes.Subscription||u===Q.RequestTypes.GetSubscription)&&l===i&&(c=!0,u===Q.RequestTypes.Subscription&&(p!==o.checksum&&(e.subscriptionQueue[a][3]=o.checksum),e.subscriptionQueue[a][4]=2))}if(!c){let a=[Q.RequestTypes.GetSubscription,i,s];o&&a.push(o.checksum),r&&(o||a.push(0),a.push(r)),f(e,a)}}};var B=require("@based/types");var E=(e,s,t,i,r,n,o)=>{n||(n=q(s,o));let c=e.subscriptions[n],a=e.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:t,onInitial:i},l){for(let b=0;b<e.subscriptionQueue.length;b++){let[h,T]=e.subscriptionQueue[b];h===B.RequestTypes.GetSubscription&&T===n&&(e.subscriptionQueue.splice(b,1),b--)}let p=[B.RequestTypes.Subscription,n,s];a&&(p.push(a.checksum),p.push(2)),o&&(a||p.push(0,2),p.push(o)),f(e,p)}}else{u=1,c=e.subscriptions[n]={query:s,cnt:1,name:o,subscribers:{1:{onError:r,onData:t,onInitial:i}}};let l=!1,p=!1,b;for(let h=0;h<e.subscriptionQueue.length;h++){let[T,R,,A]=e.subscriptionQueue[h];(T===B.RequestTypes.Unsubscribe||T===B.RequestTypes.SendSubscriptionData||T===B.RequestTypes.GetSubscription)&&R===n?(T===B.RequestTypes.GetSubscription&&(p=!0),b&&(b[4]=2),e.subscriptionQueue.splice(h,1),h--):T===B.RequestTypes.Subscription&&R===n&&(l=!0,b=e.subscriptionQueue[h],A!==a.checksum&&(b[3]=a.checksum),!b[4]&&p&&(b[4]=2))}if(!l){let h=[B.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)),f(e,h)}}return a&&(i&&(i(null,n,u),delete c.subscribers[u].onInitial),t&&t(a.value,a.checksum)),[n,u]};var $=require("@based/types");var y=(e,s,t)=>{let i=e.subscriptions[s];if(i){let r=!1;if(t?i.subscribers[t]&&(delete i.subscribers[t],i.cnt--,i.cnt===0&&(r=!0)):r=!0,r){delete e.subscriptions[s];let n=!1;for(let o=0;o<e.subscriptionQueue.length;o++){let[c,a]=e.subscriptionQueue[o];c===$.RequestTypes.Unsubscribe&&a===s?n=!0:(c===$.RequestTypes.Subscription||c===$.RequestTypes.SendSubscriptionData)&&a===s&&(e.subscriptionQueue.splice(o,1),o--)}n||f(e,[$.RequestTypes.Unsubscribe,s])}}};var Ee=require("@based/types"),Fe=e=>{for(let s=0;s<e.subscriptionQueue.length;s++)e.subscriptionQueue[s][0]===Ee.RequestTypes.Unsubscribe&&(e.subscriptionQueue.splice(s,1),s--)};var Qe=require("@based/types"),xe=e=>{for(let s=0;s<e.subscriptionQueue.length;s++)e.subscriptionQueue[s][0]===Qe.RequestTypes.SendSubscriptionData&&(e.subscriptionQueue.splice(s,1),s--)};var x=require("@based/types");var J=(e,s=!1)=>{for(let t in e.subscriptions){let i=Number(t),r=e.subscriptions[t];if(s&&!r.authError)continue;let n,o,c;for(let l=0;l<e.subscriptionQueue.length;l++){let[p,b]=e.subscriptionQueue[l];b===i&&(p===x.RequestTypes.GetSubscription?(c=l,n=e.subscriptionQueue[l]):p===x.RequestTypes.Subscription&&(o=e.subscriptionQueue[l]))}n&&o&&console.error("GET IN Q AND SUB IN Q SHOULD BE IMPOSSIBLE");let a=e.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"),e.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}=e.subscriptions[i];l?a?f(e,[x.RequestTypes.Subscription,i,p,a.checksum,n?2:0,l]):f(e,[x.RequestTypes.Subscription,i,p,0,n?2:0,l]):a?f(e,[x.RequestTypes.Subscription,i,p,a.checksum,n?2:0]):f(e,[x.RequestTypes.Subscription,i,p,0,n?2:0])}}};var Ae=require("@based/types");var K=(e,s)=>{if(typeof window!="undefined")return e;let t={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`${t[s]}${e}${t.reset}`},ue=(e,s=0,t=!1,i="",r=!1)=>{let n="";for(let a=0;a<s;a++)n+=" ";let o=t?[]:i?[n+`${K(i,r?"brightRed":"white")} {`]:[n+"{"],c=!1;t||(n+=" ",s+=1);for(let a in e){let u=e[a],l=a[0]==="$"?K(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 b=u[p];o.push(...b&&typeof b=="object"?ue(b,s+4):[`${n} ${b}`]),p!==u.length-1&&(o[o.length-1]+=",")}o.push(`${n} ]`)}else u&&typeof u=="object"?(o.push(`${n} ${l}: {`),o.push(...ue(u,s+2,!0)),o.push(`${n} }`)):o.push(`${n} ${l}: ${u}`);c=!0}return t||o.push(n.slice(0,-1)+"}"),o},W=ue;var C=e=>{let s=new Ae.BasedError(e.message);if(s.name=e.name?`${e.type} from ${e.name}`:e.type,s.stack=null,e.query||e.payload){let t=s.message.split(` | ||
`),i=0;t[0]===""&&t.shift();let r=t[0];for(let n=0;n<r.length;n++)if(r[n]!==" "){i=n-2;break}i>0?t=t.map(n=>n.slice(i)):t=t.map(n=>" "+n),e.code&&(s.code=e.code),s.message=` | ||
`+(t.payload&&typeof t.payload!="object"?` ${J("Payload","brightRed")} ${t.payload}`:K(t.payload||t.query,0,!1,t.payload?"Payload":"Query",!0).map(n=>" "+n).join(` | ||
`+(e.payload&&typeof e.payload!="object"?` ${K("Payload","brightRed")} ${e.payload}`:W(e.payload||e.query,0,!1,e.payload?"Payload":"Query",!0).map(n=>" "+n).join(` | ||
`))+` | ||
`+e.join(` | ||
`+t.join(` | ||
`)+` | ||
`}return s};var Re=(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 Ue=require("@saulx/diff"),W=require("@based/types");var xe=(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,[W.RequestTypes.SendSubscriptionData,e]);else m(t,[W.RequestTypes.SendSubscriptionData,e]);else{let a=!1;try{c.value=(0,Ue.applyPatch)(c.value,i),c.value===null&&(a=!0)}catch(u){a=!0}if(a)console.warn(` | ||
`}return s};var De=(e,s)=>{let[,t,i,r,n]=s,o=e.subscriptions[t];if(o){let c=e.cache[t]&&e.cache[t].checksum;if(n){let a=C(n);n.auth&&(o.authError={token:e.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(t),Number(u),void 0,!0),delete l.onInitial):(l.onInitial(a,Number(t),Number(u)),delete l.onInitial,y(e,t,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(t),Number(a),e.cache[t].value),delete u.onInitial,u.onData||y(e,t,Number(a)))}}else{o.authError&&delete o.authError,e.cache[t]={value:i,checksum:r};for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(t),Number(a),i),delete u.onInitial,u.onData||y(e,t,Number(a))),u.onData&&u.onData(i,r)}}}};var Ie=require("@saulx/diff"),V=require("@based/types");var Ue=(e,s)=>{let[,t,i,[r,n]]=s,o=e.subscriptions[t];if(o){let c=e.cache[t];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(t),Number(a),c.value),delete u.onInitial,u.onData||y(e,t,Number(a)))}else f(e,[V.RequestTypes.SendSubscriptionData,t]);else f(e,[V.RequestTypes.SendSubscriptionData,t]);else{let a=!1;try{c.value=(0,Ie.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(K(o.query,2,!1,"Query").join(` | ||
`),console.warn(W(o.query,2,!1,"Query").join(` | ||
`)+` | ||
`),delete t.cache[e],m(t,[W.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 De=(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 Ie=require("@based/types");var Ze=0,T=(t,s,e,i,r,n)=>{let o=++Ze;t.requestCallbacks[o]={resolve:i,reject:r},s===Ie.RequestTypes.Call?m(t,[s,n,o,e]):m(t,[s,o,e])};var Ae=(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 O={};Te(O,{BasedClient:()=>U});var y=require("@based/types");var ue=require("@based/types");var et=t=>typeof t!="undefined"&&t!==null,tt=(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?[ue.RequestTypes.Token,s,e].filter(et):[ue.RequestTypes.Token];t.connection.ws.send(JSON.stringify(i)),H(t),z(t,!0)}},$=tt;d(O,require("@based/types"));var U=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,Be(this),qe(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,[y.RequestTypes.Track,{t:s}])}onOpen(){this.connected=!0,this.based.listeners.connect&&this.based.listeners.connect.forEach(s=>s()),this.token&&$(this,this.token,this.sendTokenOptions),z(this),oe(this)}onData(s){try{let e=JSON.parse(s.data);if(e[0]===y.RequestTypes.Token){e[1].length&&De(this,e);for(let i of this.auth)i(!e[2]);this.beingAuth=!1,this.auth=[]}else e[0]===y.RequestTypes.Set||e[0]===y.RequestTypes.Get||e[0]===y.RequestTypes.Configuration||e[0]===y.RequestTypes.GetConfiguration||e[0]===y.RequestTypes.Call||e[0]===y.RequestTypes.Delete||e[0]===y.RequestTypes.Copy||e[0]===y.RequestTypes.Digest||e[0]===y.RequestTypes.RemoveType||e[0]===y.RequestTypes.RemoveField?Ae(this,e):e[0]===y.RequestTypes.Subscription?Re(this,e):e[0]===y.RequestTypes.SubscriptionDiff&&xe(this,e)}catch(e){console.error("Received incorrect data ",s)}}};var le=(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 me=require("@saulx/hash");var $e=require("@based/types"),je=require("@saulx/hash"),Ge=new Set,st=t=>{if(typeof window!="undefined"){if(Ge.has(t))return!1;Ge.add(t);try{let s="_ba:"+(0,je.hashCompact)(t);return localStorage.getItem(s)?!1:(localStorage.setItem(s,"1"),!0)}catch(s){return!1}}return!1},pe=(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},j=(t,s,e,i,r,n,o)=>{let c=pe(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)),st(c)&&(a.u=1)),m(t,[$e.RequestTypes.Track,a])};var de=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)}},fe=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()}}},V=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 fe(this.client,n)}},C=class{constructor(s,e,i){this.client=s,this.subId=typeof e=="string"?w(i,e):w(e),this.name=typeof e=="string"?e:null,this.payload=typeof e=="string"?i:e}subscribe(s,e,i){let[,r]=F(this.client,this.payload,s,n=>{n&&(console.error(n),e&&e(n))},e,this.subId,this.name);return new de(this.client,r,this.subId)}};var be={},N={},rt=(t,s)=>{be[t]||(be[t]=!0,setTimeout(()=>{console.info("Drain file q"),be[t]=!1;let e=N[t];N[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))},Ne=async(t,s,e,i,r,n,o)=>{N[e]||(N[e]=[]),N[e].push({file:s,id:i,url:e,raw:r,name:n,functionName:o}),rt(e,t.getToken())};var Me=L(require("@based/get-service")),X={},Y={},it=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(X[n])return X[n];if(Y[n])return(await Y[n]).url;let o=await(Y[n]=(0,Me.default)({env:e,project:i,org:r,name:"@based/hub",key:"file-upload",optionalKey:!0},0,t.opts.cluster));return delete Y[n],setTimeout(()=>{delete X[n]},2e3),X[n]=o.url},Le=it;var He=L(require("cross-fetch")),Z=(t,s,e)=>((0,He.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 x=require("./file/stream"),ee=typeof window!="undefined",nt=t=>"src"in t&&typeof t.src=="string",ot=t=>"path"in t&&typeof t.path=="string",at=t=>"contents"in t&&(0,x.isStream)(t.contents),_e=async(t,s)=>{if(nt(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 Le(t,s)).replace(/^ws/,"http");if(ot(s))return(0,x.uploadFilePath)(t,i,s),{id:e};if(at(s))return(0,x.uploadFileStream)(t,i,s),{id:e};if(s.contents instanceof ArrayBuffer)return s.contents=ee?new global.Blob([s.contents],{type:s.mimeType||"text/plain"}):global.Buffer.from(s.contents),Z(t,i+"/file",s);if(ee&&s.contents instanceof global.Blob)return s.mimeType||(s.mimeType=s.contents.type),Z(t,i+"/file",s);if(typeof s.contents=="string"||!ee&&s.contents instanceof global.Buffer)return Z(t,i+"/file",s);if(ee&&s.contents instanceof File)return Ne(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 se=L(require("@based/get-service")),he=require("@saulx/utils"),S=require("@based/graphql");d(b,require("@based/types"),module.exports);var te=class extends Oe{constructor(e){super();this.client=new U(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=ne(this.client,this._url)):(this._url=e,this.client.connection=ne(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,S.createOperations)({schemas:this.client.configuration.schema},(0,S.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,S.createOperations)({schemas:this.client.configuration.schema,db:e},(0,S.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;F(this.client,a?void 0:i,u,(p,f,h,k,B)=>{p&&!B?c(p):o(()=>{g(this.client,f,h)})},l,void 0,e)}):new Promise((o,c)=>{F(this.client,e,i,(a,u,l,p,f)=>{a&&!f?c(a):o(()=>{g(this.client,u,l)})},r)})}createObservable(e,i){return typeof e=="string"?new C(this.client,e,i):new C(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;F(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,f,h,k)=>{l&&!k?o(l):n(()=>{g(this.client,p,f)})},u)})}get(e,i){return typeof e=="string"?new Promise((r,n)=>{_(this.client,i,(o,c,a,u)=>{o?n(o):r(u)},0,e)}):new Promise((r,n)=>{T(this.client,v.RequestTypes.Get,e,r,n)})}file(e){return global.File&&e instanceof File&&(e={contents:e}),_e(this,e)}call(e,i){return new Promise((r,n)=>{T(this.client,v.RequestTypes.Call,i,r,n,e)})}async id(e,i){let r=le(this.client,e);if(r||(await this.schema(),r=le(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,me.hashCompact)(i,8,!0);return r+n}else return r+(0,me.hashCompact)(Math.floor(Math.random()*99999999999)+""+Date.now())}digest(e){return new Promise((i,r)=>{T(this.client,v.RequestTypes.Digest,e,i,r)})}set(e){return new Promise((i,r)=>{T(this.client,v.RequestTypes.Set,e,i,r)})}copy(e){return new Promise((i,r)=>{T(this.client,v.RequestTypes.Copy,e,i,r)})}async gqlQuery(e,i={}){let r;typeof e=="string"?r=this.gql(e):r=e;try{if(r=(0,S.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,f,h,k,B;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 R={};R.id=a;let ge=(B=(k=(h=(f=(p=this.client)==null?void 0:p.configuration)==null?void 0:f.schema)==null?void 0:h[r.db])==null?void 0:k.prefixToTypeMapping)==null?void 0:B[a.slice(0,2)];ge&&(R.type=ge),n[o]=R;return}let u=(0,he.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,S.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 C(this.client,l.fn.name,l.fn.payload),key:l.key})),u=new C(this.client,ke({$db:r.db},c));return a.push({key:"",obs:u}),new V(this.client,a)}return new C(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,he.deepCopy)(c.get);u.$id=a,n[o]=u})),new C(this.client,{$db:r.db,data:n})}analytics(e,i){return new Promise((r,n)=>{i?F(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"):_(this.client,e,(o,c,a,u)=>{o?n(o):((0,v.isAnalyticsHistoryOpts)(e)||(0,v.isAnalyticsTypesOpts)(e),r(u))},0,"analytics")})}track(e,i){j(this.client,e,i)}clearAnalytics(e,i){j(this.client,e,i,!1,!1,void 0,!0)}untrack(e,i){j(this.client,e,i,!0)}event(e,i,r){j(this.client,e,i,!1,!0,r)}delete(e){return new Promise((i,r)=>{T(this.client,v.RequestTypes.Delete,e,i,r)})}schema(){return new Promise((e,i)=>{let r=n=>{this.client.configuration=n,e(n)};T(this.client,v.RequestTypes.GetConfiguration,0,r,i)})}removeType(e,i="default"){return new Promise((r,n)=>{T(this.client,v.RequestTypes.RemoveType,{type:e,db:i},r,n)})}removeField(e,i,r="default"){return new Promise((n,o)=>{!i||i.length===0?o(new Error("Path cannot be empty")):(Array.isArray(i)||(i=[i]),T(this.client,v.RequestTypes.RemoveField,{type:e,db:r,path:i},n,o))})}updateSchema(e){return new Promise((i,r)=>{T(this.client,v.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"?$(this.client,e,i):$(this.client),this.emit("auth",e))})}},ct=(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},ut=(t,s=te)=>{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,se.getClusterUrl)(a),n=async()=>{let{url:l}=await(0,se.default)({env:e,project:i,org:r,key:o,name:c},0,a);return ct(l,u)}),n){let l=new s;return l.opts=t,l.connect(n),l}},lt=ut;0&&(module.exports={Based,BasedClient,BasedGraphQL,Observable,addGetSubscriber,addRequest,addSubscriber,createGraphqlOperations,generateSubscriptionId,generateTrackingKey,handleGraphqlVariables,parseGraphql,removeSubscriber}); | ||
`),delete e.cache[t],f(e,[V.RequestTypes.SendSubscriptionData,t]);else{c.checksum=n;for(let u in o.subscribers){let l=o.subscribers[u];l.onInitial&&(l.onInitial(null,Number(t),Number(u),c.value),delete l.onInitial,l.onData||y(e,t,Number(u))),l.onData&&l.onData(c.value,c.checksum)}}}}};var Ge=(e,s)=>{for(let t of s[1]){delete e.cache[t];let i=e.subscriptions[t];if(i){let r={type:"AuthorizationError",name:i.name?`observe "${i.name}"`:"observe",message:"Unauthorized request",payload:i.query,auth:!0},n=C(r);i.authError={token:e.token,error:n};for(let o in i.subscribers){let c=i.subscribers[o];c.onError&&c.onError(n)}}}};var je=require("@based/types");var ot=0,k=(e,s,t,i,r,n,o)=>{let c=++ot;e.requestCallbacks[c]={resolve:i,reject:r,type:s,payload:t,name:n,isRetry:o},s===je.RequestTypes.Call?f(e,[s,n,c,t]):f(e,[s,c,t])};var $e=(e,s)=>{let[,t,i,r]=s,n=e.requestCallbacks[t];n&&(delete e.requestCallbacks[t],r?n.reject(C(r)):n.resolve(i))};var O={};Ce(O,{BasedClient:()=>D});var g=require("@based/types");var le=require("@based/types");var at=e=>typeof e!="undefined"&&e!==null,ct=(e,s,t)=>{if(e.beingAuth=!0,s)e.token=s,e.sendTokenOptions=t;else{for(let i in e.cache)e.subscriptions[i]||delete e.cache[i];delete e.token,delete e.sendTokenOptions}if(e.connected){let i=s?[le.RequestTypes.Token,s,t].filter(at):[le.RequestTypes.Token];e.connection.ws.send(JSON.stringify(i)),_(e),J(e,!0)}},w=ct;var F=require("@based/types");var pe=0,Me=(e,s)=>{let t=++pe;return f(e,[F.RequestTypes.Auth,F.AuthRequestTypes.Login,t,s]),new Promise((i,r)=>{e.authCallbacks[t]={resolve:n=>{w(e,n.token,{refreshToken:n.refreshToken}),i(n)},reject:r}})},Ne=(e,s)=>{let t=++pe;return f(e,[F.RequestTypes.Auth,F.AuthRequestTypes.RenewToken,t,s]),new Promise((i,r)=>{e.authCallbacks[t]={resolve:n=>{w(e,n.token),i(n)},reject:r}})},Le=(e,s)=>{let[,t,i,r]=s,n=e.authCallbacks[t];n&&(delete e.authCallbacks[t],r?n.reject(C(r)):n.resolve(i))},He=e=>{let s=++pe;return f(e,[F.RequestTypes.Auth,F.AuthRequestTypes.Logout,s]),new Promise((t,i)=>{e.authCallbacks[s]={resolve:r=>{w(e),t(r)},reject:i}})};d(O,require("@based/types"));var D=class{constructor(s){this.auth=[];this.subscriptions={};this.cache={};this.requestCallbacks={};this.authCallbacks={};this.connected=!1;this.subscriptionQueue=[];this.queue=[];this.drainInProgress=!1;this.based=s}onClose(){this.connected=!1,Re(this),Fe(this),xe(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)f(this,[g.RequestTypes.Track,{t:s}])}onOpen(){this.connected=!0,this.based.listeners.connect&&this.based.listeners.connect.forEach(s=>s()),this.token&&w(this,this.token,this.sendTokenOptions),J(this),ae(this)}onData(s){var t;try{let i=JSON.parse(s.data),[r,n,o,c]=i;if(r===g.RequestTypes.Token){this.retryingRenewToken=!1,n.length&&Ge(this,i);for(let a of this.auth)a(!o);this.beingAuth=!1,this.auth=[]}else if(r===g.RequestTypes.Auth)Le(this,i);else if((c==null?void 0:c.code)===g.BasedErrorCodes.TokenExpired&&!this.retryingRenewToken){this.retryingRenewToken=!0;let a=(t=this.sendTokenOptions)==null?void 0:t.refreshToken;Ne(this,{refreshToken:a}).then(u=>{w(this,u.token,this.sendTokenOptions),k(this,r,c==null?void 0:c.payload,this.requestCallbacks[n].resolve,this.requestCallbacks[n].reject)}).catch(u=>{this.requestCallbacks[n].reject(u)})}else r===g.RequestTypes.Set||r===g.RequestTypes.Get||r===g.RequestTypes.Configuration||r===g.RequestTypes.GetConfiguration||r===g.RequestTypes.Call||r===g.RequestTypes.Delete||r===g.RequestTypes.Copy||r===g.RequestTypes.Digest||r===g.RequestTypes.RemoveType||r===g.RequestTypes.RemoveField?$e(this,i):r===g.RequestTypes.Subscription?De(this,i):r===g.RequestTypes.SubscriptionDiff&&Ue(this,i)}catch(i){console.error("Received incorrect data ",s)}}};var de=(e,s)=>{let t;if(e.configuration&&e.configuration.schema)for(let i in e.configuration.schema){let r=e.configuration.schema[i];if(r.prefixToTypeMapping){for(let n in r.prefixToTypeMapping)if(r.prefixToTypeMapping[n]===s){t=n;break}}}return t};var ge=require("@saulx/hash");var ze=require("@based/types"),Je=require("@saulx/hash"),_e=new Set,ut=e=>{if(typeof window!="undefined"){if(_e.has(e))return!1;_e.add(e);try{let s="_ba:"+(0,Je.hashCompact)(e);return localStorage.getItem(s)?!1:(localStorage.setItem(s,"1"),!0)}catch(s){return!1}}return!1},be=(e,s)=>{if(s){let t=`${e}`,i=Object.keys(s).sort();for(let r of i)t+="_"+r+"_"+s[r];return t}else return e},M=(e,s,t,i,r,n,o)=>{let c=be(s,t),a={t:c};o&&(a.r=1),r&&(a.e=1,n&&(a.o=n)),i?(a.s=1,e.tracking.delete(c)):o||(r||(e.tracking||(e.tracking=new Set),e.tracking.add(c)),ut(c)&&(a.u=1)),f(e,[ze.RequestTypes.Track,a])};var fe=class{constructor(s,t,i){this.closed=!1;this.client=s,this.subId=i,this.subscriberId=t}unsubscribe(){this.closed=!0,y(this.client,this.subId,this.subscriberId)}},me=class{constructor(s,t){this.closed=!1;this.client=s,this.subs=t}unsubscribe(){if(!this.closed){this.closed=!0;for(let s of this.subs)s.unsubscribe()}}},X=class{constructor(s,t){this.client=s,this.components=t}subscribe(s,t,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)},t);n.push(a)}return new me(this.client,n)}},P=class{constructor(s,t,i){this.client=s,this.subId=typeof t=="string"?q(i,t):q(t),this.name=typeof t=="string"?t:null,this.payload=typeof t=="string"?i:t}subscribe(s,t,i){let[,r]=E(this.client,this.payload,s,n=>{n&&(console.error(n),t&&t(n))},t,this.subId,this.name);return new fe(this.client,r,this.subId)}};var he={},N={},lt=(e,s)=>{he[e]||(he[e]=!0,setTimeout(()=>{console.info("Drain file q"),he[e]=!1;let t=N[e];N[e]=[];let i=new global.FormData;for(let r of t){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",e+"/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))},Ke=async(e,s,t,i,r,n,o)=>{N[t]||(N[t]=[]),N[t].push({file:s,id:i,url:t,raw:r,name:n,functionName:o}),lt(t,e.getToken())};var We=H(require("@based/get-service")),Y={},Z={},pt=async(e,s)=>{if(s.url)return typeof s.url=="string"?s.url:await s.url();if(!e.opts.env&&e.opts.url)return typeof e.opts.url=="string"?e.opts.url:await e.opts.url();let{env:t,project:i,org:r}=e.opts,n=t+"/"+i+"/"+r+"/"+e.opts.cluster;if(Y[n])return Y[n];if(Z[n])return(await Z[n]).url;let o=await(Z[n]=(0,We.default)({env:t,project:i,org:r,name:"@based/hub",key:"file-upload",optionalKey:!0},0,e.opts.cluster));return delete Z[n],setTimeout(()=>{delete Y[n]},2e3),Y[n]=o.url},Ve=pt;var Xe=H(require("cross-fetch")),ee=(e,s,t)=>((0,Xe.default)(s,{method:"POST",cache:"no-cache",headers:{"Content-Type":t.mimeType||"text/plain","File-Id":t.id,"File-Is-Raw":t.raw?"1":"0","File-Name":t.name||"","Function-Name":t.functionName||"",Authorization:e.getToken()},body:t.contents}).then(i=>{}).catch(i=>{console.error("Error while uploading file",i)}),{id:t.id});var I=require("./file/stream"),te=typeof window!="undefined",dt=e=>"src"in e&&typeof e.src=="string",bt=e=>"path"in e&&typeof e.path=="string",ft=e=>"contents"in e&&(0,I.isStream)(e.contents),Ye=async(e,s)=>{if(dt(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 e.set(r)):void 0}let t=s.id;if(!t){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),t=(await e.set(r)).id}s.id=t;let i=(await Ve(e,s)).replace(/^ws/,"http");if(bt(s))return(0,I.uploadFilePath)(e,i,s),{id:t};if(ft(s))return(0,I.uploadFileStream)(e,i,s),{id:t};if(s.contents instanceof ArrayBuffer)return s.contents=te?new global.Blob([s.contents],{type:s.mimeType||"text/plain"}):global.Buffer.from(s.contents),ee(e,i+"/file",s);if(te&&s.contents instanceof global.Blob)return s.mimeType||(s.mimeType=s.contents.type),ee(e,i+"/file",s);if(typeof s.contents=="string"||!te&&s.contents instanceof global.Buffer)return ee(e,i+"/file",s);if(te&&s.contents instanceof File)return Ke(e,s.contents,i,s.id,s.raw||!1,s.name,s.functionName),{id:t};throw s.id||await e.delete({$id:t}),new Error(`Invalid contents for file api ${JSON.stringify(s,null,2)}`)};var re=H(require("@based/get-service")),ye=require("@saulx/utils"),S=require("@based/graphql");d(m,require("@based/types"),module.exports);var se=class extends we{constructor(t){super();this.client=new D(this),Object.defineProperty(this,"client",{enumerable:!1,writable:!0}),t&&t.url&&this.connect(t.url),this.graphql={query:this.gqlQuery.bind(this),live:this.gqlLive.bind(this)}}connect(t){!t&&this._url?this.client.connection||(this.client.connection=oe(this.client,this._url)):(this._url=t,this.client.connection=oe(this.client,t))}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(t,i,r){return new Promise((n,o)=>{let c,a=!1;this.observe(t,(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(t,...i){typeof t=="string"&&(t=[t]);let r=t[0];return i.forEach((n,o)=>{n&&n.kind==="Document"?r+=n.loc.source.body:r+=n,r+=t[o+1]}),(0,S.createOperations)({schemas:this.client.configuration.schema},(0,S.parseGraphql)(r))}gqlDb(t="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,S.createOperations)({schemas:this.client.configuration.schema,db:t},(0,S.parseGraphql)(n))}}observe(t,i,r,n){return typeof t=="string"?new Promise((o,c)=>{let a=typeof i=="function",u=a?i:r,l=a?r:n;E(this.client,a?void 0:i,u,(p,b,h,T,R)=>{p&&!R?c(p):o(()=>{y(this.client,b,h)})},l,void 0,t)}):new Promise((o,c)=>{E(this.client,t,i,(a,u,l,p,b)=>{a&&!b?c(a):o(()=>{y(this.client,u,l)})},r)})}createObservable(t,i){return typeof t=="string"?new P(this.client,t,i):new P(this.client,t)}observeSchema(t,i,r){return new Promise((n,o)=>{let c=typeof t=="string"?t:"default",a=typeof t=="string"?i:t,u=typeof t=="string"?r:i;E(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,b,h,T)=>{l&&!T?o(l):n(()=>{y(this.client,p,b)})},u)})}get(t,i){return typeof t=="string"?new Promise((r,n)=>{z(this.client,i,(o,c,a,u)=>{o?n(o):r(u)},0,t)}):new Promise((r,n)=>{k(this.client,v.RequestTypes.Get,t,r,n)})}file(t){return global.File&&t instanceof File&&(t={contents:t}),Ye(this,t)}call(t,i){return new Promise((r,n)=>{k(this.client,v.RequestTypes.Call,i,r,n,t)})}async id(t,i){let r=de(this.client,t);if(r||(await this.schema(),r=de(this.client,t)),!r)throw C({message:`Type does not exist ${t}`,type:"Invalid type",payload:i?{type:t,opts:i}:{type:t}});if(i){let n=(0,ge.hashCompact)(i,8,!0);return r+n}else return r+(0,ge.hashCompact)(Math.floor(Math.random()*99999999999)+""+Date.now())}digest(t){return new Promise((i,r)=>{k(this.client,v.RequestTypes.Digest,t,i,r)})}set(t){return new Promise((i,r)=>{k(this.client,v.RequestTypes.Set,t,i,r)})}copy(t){return new Promise((i,r)=>{k(this.client,v.RequestTypes.Copy,t,i,r)})}async gqlQuery(t,i={}){let r;typeof t=="string"?r=this.gql(t):r=t;try{if(r=(0,S.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,b,h,T,R;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 A={};A.id=a;let ve=(R=(T=(h=(b=(p=this.client)==null?void 0:p.configuration)==null?void 0:b.schema)==null?void 0:h[r.db])==null?void 0:T.prefixToTypeMapping)==null?void 0:R[a.slice(0,2)];ve&&(A.type=ve),n[o]=A;return}let u=(0,ye.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(t,i={}){let r;if(typeof t=="string"?r=this.gql(t):r=t,r=(0,S.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 P(this.client,l.fn.name,l.fn.payload),key:l.key})),u=new P(this.client,Oe({$db:r.db},c));return a.push({key:"",obs:u}),new X(this.client,a)}return new P(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,ye.deepCopy)(c.get);u.$id=a,n[o]=u})),new P(this.client,{$db:r.db,data:n})}analytics(t,i){return new Promise((r,n)=>{i?E(this.client,t,i,(o,c,a,u,l)=>{o&&!l?n(o):r(()=>{y(this.client,c,a)})},o=>console.error(o),void 0,"analytics"):z(this.client,t,(o,c,a,u)=>{o?n(o):((0,v.isAnalyticsHistoryOpts)(t)||(0,v.isAnalyticsTypesOpts)(t),r(u))},0,"analytics")})}track(t,i){M(this.client,t,i)}clearAnalytics(t,i){M(this.client,t,i,!1,!1,void 0,!0)}untrack(t,i){M(this.client,t,i,!0)}event(t,i,r){M(this.client,t,i,!1,!0,r)}delete(t){return new Promise((i,r)=>{k(this.client,v.RequestTypes.Delete,t,i,r)})}schema(){return new Promise((t,i)=>{let r=n=>{this.client.configuration=n,t(n)};k(this.client,v.RequestTypes.GetConfiguration,0,r,i)})}removeType(t,i="default"){return new Promise((r,n)=>{k(this.client,v.RequestTypes.RemoveType,{type:t,db:i},r,n)})}removeField(t,i,r="default"){return new Promise((n,o)=>{!i||i.length===0?o(new Error("Path cannot be empty")):(Array.isArray(i)||(i=[i]),k(this.client,v.RequestTypes.RemoveField,{type:t,db:r,path:i},n,o))})}updateSchema(t){return new Promise((i,r)=>{k(this.client,v.RequestTypes.Configuration,t,i,r)})}getToken(){return this.client.token}auth(t,i){return new Promise(r=>{this.client.auth.push(r),(t&&t!==this.client.token||t===!1&&this.client.token)&&(typeof t=="string"?w(this.client,t,i):w(this.client),this.emit("auth",t))})}async login(t){return Me(this.client,t)}logout(){return He(this.client)}},mt=(e,s)=>{if(s){let t;e+=/\?/.test(e)?"&":"?";for(let i in s){let r=s[i];e+=t?`&${i}=${r}`:`${i}=${r}`,t=!0}}return e},ht=(e,s=se)=>{let{env:t,project:i,org:r,url:n,key:o,name:c="@based/hub",cluster:a,params:u}=e;if(n||(a=e.cluster=(0,re.getClusterUrl)(a),n=async()=>{let{url:l}=await(0,re.default)({env:t,project:i,org:r,key:o,name:c},0,a);return mt(l,u)}),n){let l=new s;return l.opts=e,l.connect(n),l}},gt=ht;0&&(module.exports={Based,BasedClient,BasedGraphQL,Observable,addGetSubscriber,addRequest,addSubscriber,createGraphqlOperations,generateSubscriptionId,generateTrackingKey,handleGraphqlVariables,parseGraphql,removeSubscriber}); |
import { BasedClient, TrackMessage } from '.'; | ||
import { Message } from '@based/types'; | ||
export declare const addToQueue: (client: BasedClient, msg: Message | TrackMessage) => void; | ||
import { AuthMessage, Message } from '@based/types'; | ||
export declare const addToQueue: (client: BasedClient, msg: Message | TrackMessage | AuthMessage) => void; | ||
export declare const drainQueue: (client: BasedClient) => void; | ||
export declare const stopDrainQueue: (client: BasedClient) => void; |
@@ -27,3 +27,4 @@ "use strict"; | ||
!client.drainInProgress && | ||
(client.queue.length || client.subscriptionQueue.length)) { | ||
(client.queue.length || client.subscriptionQueue.length) && | ||
!client.isLogginIn) { | ||
client.drainInProgress = true; | ||
@@ -30,0 +31,0 @@ client.drainTimeout = setTimeout(() => { |
import { BasedClient } from '.'; | ||
import { RequestData, RequestTypes } from '@based/types'; | ||
export declare const addRequest: (client: BasedClient, type: RequestTypes.Set | RequestTypes.Get | RequestTypes.Configuration | RequestTypes.GetConfiguration | RequestTypes.Delete | RequestTypes.Copy | RequestTypes.Digest | RequestTypes.Call | RequestTypes.RemoveType | RequestTypes.RemoveField, payload: any, resolve: (val?: any) => void, reject: (err: Error) => void, name?: string) => void; | ||
export declare const addRequest: (client: BasedClient, type: Exclude<RequestTypes, RequestTypes.Subscription | RequestTypes.SubscriptionDiff | RequestTypes.SendSubscriptionData | RequestTypes.Unsubscribe | RequestTypes.GetSubscription | RequestTypes.Token | RequestTypes.Track>, payload: any, resolve: (val?: any) => void, reject: (err: Error) => void, name?: string, isRetry?: boolean) => void; | ||
export declare const abortRequest: () => void; | ||
export declare const cleanUpRequests: () => void; | ||
export declare const incomingRequest: (client: BasedClient, data: RequestData) => void; |
@@ -11,3 +11,19 @@ "use strict"; | ||
let requestIdCnt = 0; | ||
const addRequest = (client, type, payload, resolve, reject, name) => { | ||
const addRequest = (client, type, | ||
// TODO: Changed to Exclude so don't have to update | ||
// these lists every time. | ||
// Check why the above should not be here. Maybe create it's own type | ||
// old: | ||
// | RequestTypes.Set | ||
// | RequestTypes.Get | ||
// | RequestTypes.Configuration | ||
// | RequestTypes.GetConfiguration | ||
// | RequestTypes.Delete | ||
// | RequestTypes.Copy | ||
// | RequestTypes.Digest | ||
// | RequestTypes.Call | ||
// | RequestTypes.RemoveType | ||
// | RequestTypes.RemoveField | ||
// | RequestTypes.Auth, | ||
payload, resolve, reject, name, isRetry) => { | ||
const id = ++requestIdCnt; | ||
@@ -17,2 +33,6 @@ client.requestCallbacks[id] = { | ||
reject, | ||
type, | ||
payload, | ||
name, | ||
isRetry, | ||
}; | ||
@@ -19,0 +39,0 @@ if (type === types_1.RequestTypes.Call) { |
{ | ||
"name": "@based/client", | ||
"version": "2.5.1", | ||
"version": "2.6.0", | ||
"license": "MIT", | ||
@@ -12,3 +12,3 @@ "main": "dist/index.js", | ||
"build": "npx tsc && npm run buildBundle", | ||
"watch": "npm run build -- --watch", | ||
"watch": "concurrently \"tsc --watch\" \"npm run buildBundle -- --watch\"", | ||
"test": "ava --timeout 1m --verbose", | ||
@@ -43,7 +43,9 @@ "watchTest": "ava --color --watch --verbose", | ||
"devDependencies": { | ||
"concurrently": "^7.1.0", | ||
"esbuild": "^0.14.29", | ||
"@saulx/hash": "^1.1.0", | ||
"@saulx/selva": "10.6.3", | ||
"@based/server": "^2.6.0", | ||
"@saulx/selva": "^11.0.0", | ||
"@saulx/utils": "^2.2.1", | ||
"@saulx/selva-server": "10.6.3", | ||
"@saulx/selva-server": "11.0.0", | ||
"@types/jsonwebtoken": "^8.5.6", | ||
@@ -50,0 +52,0 @@ "@types/node": "^17.0.23", |
339
README.md
# @based/client | ||
## 🔗 Links | ||
- [GitHub](https://github.com/atelier-saulx/based#readme) | ||
### Index | ||
- [Modify data](#modify-data) | ||
- [Observe data](#observe-data) | ||
- [Upload files](#upload-files) | ||
- [Schema](#schema) | ||
- [Analytics](#analytics) | ||
--- | ||
## Description | ||
This package allows to interact with a Based environment, set and observe data, upload files, track and see analytics, and authenticate users. | ||
## .observe(query, cb, err?) | ||
This page provides a quick first look at the main methods this package offers. Detailed information about each method is linked in the appropriate paragraph. | ||
###### Example: | ||
```js | ||
import based from '@based/client' | ||
const client = based({ | ||
org: 'my-org', | ||
project: 'someproject', | ||
env: 'production', | ||
}) | ||
// create a schema | ||
await client.updateSchema({ | ||
schema: { | ||
types: { | ||
thing: { | ||
fields: { | ||
name: { type: 'string' }, | ||
quantity: { type: 'number' }, | ||
reason: { type: 'string' }, | ||
otherThings: { type: 'references' }, | ||
favouriteThing: { type: 'reference' }, | ||
}, | ||
}, | ||
}, | ||
}, | ||
}) | ||
// observe some data | ||
await client.observe( | ||
{ $id: 'root', children: { $all: true, $list: true } }, | ||
(data) => { | ||
console.log(data) | ||
} | ||
) | ||
// set data | ||
await client.set({ | ||
type: 'thing', | ||
name: 'book', | ||
quantity: 3, | ||
}) | ||
``` | ||
const unobserve = await b.observe({ | ||
$id: 'sp1', | ||
title: true | ||
}, (data) => { | ||
}, (err) => { | ||
## Modify data | ||
> Read more about `set` and its operators [here](docs/set.md) | ||
### `set` | ||
The `based.set()` method allows to create new nodes or modify data on existing nodes. To change an existing one, one can do the following: | ||
###### Example: | ||
<!-- prettier-ignore-start --> | ||
```js | ||
/* | ||
Let's assume the following node in database: | ||
{ | ||
id: 'maASxsd3', | ||
type: 'match', | ||
value: 10, | ||
title: { | ||
en: 'yes' | ||
} | ||
} | ||
*/ | ||
const result = await client.set({ // Value of result: maASxsd3 | ||
$id: 'maASxsd3', // Resulting node in database: | ||
type: 'match', // { id: 'maASxsd3', | ||
title: { // type: 'match', | ||
en: 'hello', // value: 10, // existing value remains | ||
de: 'hallo', // title: { | ||
}, // en: 'hello', // .en is overwritten | ||
name: 'match', // de: 'hallo' // .de is added | ||
// }, | ||
// name: 'match' // name is added | ||
}) | ||
``` | ||
<!-- prettier-ignore-end --> | ||
## .get(query) | ||
Omitting the `$id` field would **create a new node instead**. | ||
``` | ||
const result = await b.get({ | ||
$id: 'sp1', | ||
title: true | ||
> :exclamation: **All set operations must still respect the schema, otherwise the set won't take effect.** | ||
### `delete` | ||
A node can be removed using `client.delete()`, by passing an object with a property named `$id` containing the node's ID. | ||
###### Example: | ||
```js | ||
await client.delete({ | ||
$id: 'maASxsd3', | ||
}) | ||
``` | ||
## .set(payload) | ||
## Observe data | ||
> Read more about `observe` and the query language [here](docs/get.md) | ||
Based is built from the ground up with realtime updates in mind. This is why the best way to retrieve data for the database is to _observe_ it. This allows to pass an `onData` function that will get called any time the data that the query points to changes. | ||
> ❗ Warning: The `data` object that gets passed to the onData function should **NOT** be modified in place since, due to performance reasons, the object gets reused between calls. | ||
Using this same method, it is also possible to observe a data function. | ||
This method returns a `close` function that must be called in order to allow the subscription to close gracefully. | ||
###### Example: | ||
```js | ||
// This query observes all nodes of type `thing` and counts how many times any of them | ||
// changes, is removed, or is added, while also logging all the entries every time. | ||
let receivedCnt = 0 | ||
const close = await client.observe( | ||
{ | ||
things: { | ||
name: true, | ||
id: true, | ||
nested: true, | ||
$list: { | ||
$find: { | ||
$traverse: 'children', | ||
$filter: { | ||
$operator: '=', | ||
$value: 'thing', | ||
$field: 'type', | ||
}, | ||
}, | ||
}, | ||
}, | ||
}, | ||
(data) => { | ||
console.log(data) | ||
receivedCnt++ | ||
} | ||
) | ||
// when done ... | ||
close() | ||
``` | ||
const { id } = await b.set({ | ||
$id: 'sp1', | ||
title: 'Yes, the best' | ||
**To observe a data function instead**, one can simply replace the query with the name of the function: | ||
###### Example: | ||
```js | ||
let receivedCnt = 0 | ||
const close = await client.observe('observeAllThings', (data) => { | ||
console.log(data) | ||
receivedCnt++ | ||
}) | ||
// when done ... | ||
close() | ||
``` | ||
## .delete(payload) | ||
#### `get` | ||
It's also possible to simply get the data once, instead of observing it, using the `based.get()` method, which accepts a query or data function name as argument. | ||
###### Example: | ||
```js | ||
// Gets every child of `root` | ||
const data = await client.get({ | ||
$id: 'root', | ||
children: { $all: true, $list: true }, | ||
}) | ||
``` | ||
const { ids } = await b.delete({ | ||
$id: 'sp1' | ||
## Upload files | ||
> Details [here](docs/files.md) | ||
Based provides a way to upload and serve user content without hassle using the `client.file()` API. | ||
This sets a new node of type `file` in the database, which contains all its relevant information | ||
###### Example: | ||
```js | ||
const fileId = await client.file({ | ||
contents: 'This is a string I want to store as plain text!', | ||
mimeType: 'text/plain', | ||
name: 'my-file-name', | ||
}) | ||
``` | ||
## .copy(payload) | ||
Also supports browser file objects | ||
```jsx | ||
<input | ||
type="file" | ||
onChange={async (e) => { | ||
const id = await client.file(e.target.files[0]) | ||
// const id = await client.file({ contents: e.target.files[0], name: 'custom name' }); | ||
}} | ||
/> | ||
``` | ||
const { ids } = await b.copy({ | ||
$id: 'sp1' | ||
Or streams in node | ||
```js | ||
import fs from 'fs' | ||
const id = await client.file(fs.createReadStream(aFile)) | ||
``` | ||
###### Retrieve the file node: | ||
```js | ||
const data = await client.get({ | ||
$id: fileId, | ||
$all: true, | ||
}) | ||
/* | ||
data = { | ||
id: "fi6a535226", | ||
name: "eb3f67a3bc65325bf739ebddd94403e5", | ||
mimeType: "text/plain", | ||
version: "eb3f67a3bc65325bf739ebddd94403e5", | ||
origin: "https://based-env-files-do-usproduction-enb-xz-apz--orn-t-v-...98446afcb87d", | ||
src: "https://based-2129034536588.imgix.net/fi6a535226/84e62df3-75...98446afcb87d", | ||
progress: 1, | ||
size: 31, | ||
type: "file", | ||
createdAt: 1650360875043, | ||
updatedAt: 1650360882865, | ||
} | ||
*/ | ||
``` | ||
## .call(name, payload) | ||
## Schema | ||
> Read more about schemas [here](docs/schema.md) | ||
The schema describes what types of nodes can exist on the database. Each `type` can have several named `fields`, each with its own data type (i.e. `string`, `number`, `object`, and so on). Based on the data type, Based will validate the value passed. | ||
One of the first things a Based user will have to do is set a schema for its database. This is done using the `client.updateSchema()` method. | ||
###### Example: | ||
```js | ||
await client.updateSchema({ | ||
types: { | ||
thing: { | ||
fields: { | ||
name: { type: 'string' }, | ||
nested: { | ||
type: 'object', | ||
properties: { | ||
something: { type: 'string' }, | ||
}, | ||
}, | ||
}, | ||
}, | ||
}, | ||
}) | ||
``` | ||
const res = await b.call('email', { | ||
from: 'x', | ||
to: 'y' | ||
## Analytics | ||
Based is capable of tracking a client in realtime using the included `client.track()` method (and `client.untrack()`). | ||
This method allows to track any user defined event, attaching a payload to it. The client stops being tracked when `client.untrack()` is called, or when the connection is closed. | ||
###### Example: | ||
<!-- prettier-ignore-start --> | ||
```js | ||
client.track('view', { | ||
edition: '2022', | ||
language: 'en', | ||
}) | ||
// when the event is no longer happening (e.g. the user moves to a different view)... | ||
client.untrack('view', { | ||
edition: '2022', // The payload needs to be specified again, since it defines a unique event type | ||
language: 'en', | ||
}) | ||
``` | ||
<!-- prettier-ignore-end --> | ||
# auth | ||
To then retrieve the analytics data, Based provides the `client.analytics()` method, which takes as argument an object containg the event type and its payload. | ||
This method can also take a `onData` function as a second argument, which turns it into an observer. | ||
###### Example: | ||
<!-- prettier-ignore-start --> | ||
```js | ||
const data = await client.analytics({ type: 'view' }) | ||
console.log(data) // prints an object { all, unique, active } | ||
// `all` represents the total count of how many times the event was fired overall | ||
// `unique` represents the total count of unique users that fired the event | ||
// `active` are the users that are active right now (real time visitors) | ||
// it's also possible to observe the analytics by passing an onData function to it | ||
const close = await client.analytics( | ||
{ type: 'view' }, | ||
(analyticsInfo) => console.log(analyticsInfo) | ||
) | ||
``` | ||
try { | ||
await b.auth(token) | ||
<!-- prettier-ignore-end --> | ||
await b.auth(false) | ||
} catch (e) { | ||
### `$geo` and `$history` | ||
} | ||
Based analytics can provide more specific data by using the `$geo` and `$history` operators, which give information about the location of the user and the historical values of the event tracked, respectively. | ||
###### Example: | ||
<!-- prettier-ignore-start --> | ||
```js | ||
const data = await client.analytics({ type: 'view', $geo: true, $history: 30 }) | ||
console.log(data) // prints an object containing all the information as the normal | ||
// client.analytics call, but with a geo property containig ISO value counts, | ||
// and with the total counts turned into an array of max 30 tuples, | ||
// with the first item in the tuple being a timestamp and the second one being the value at the time | ||
// it's also possible to observe the analytics by passing an onData function to it | ||
const close = await client.analytics( | ||
{ type: 'view' }, | ||
(analyticsInfo) => console.log(analyticsInfo) | ||
) | ||
``` | ||
<!-- prettier-ignore-end --> | ||
@@ -78,0 +349,0 @@ --- |
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
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
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
266222
120
2850
356
15