@based/client
Advanced tools
Comparing version 2.10.1 to 3.0.0
@@ -10,3 +10,2 @@ "use strict"; | ||
const createError_1 = __importDefault(require("./createError")); | ||
const token_1 = __importDefault(require("./token")); | ||
const request_1 = require("./request"); | ||
@@ -20,5 +19,8 @@ let loginCbId = 0; | ||
resolve: (response) => { | ||
(0, token_1.default)(client, response.token, { | ||
refreshToken: response.refreshToken, | ||
}); | ||
if (response.id && response.token) { | ||
client.updateUserState(response.id, response.token, response.refreshToken); | ||
} | ||
else { | ||
client.updateUserState(false); | ||
} | ||
resolve(response); | ||
@@ -33,5 +35,8 @@ }, | ||
(0, request_1.addRequest)(client, types_1.RequestTypes.Call, opts, (response) => { | ||
(0, token_1.default)(client, response.token, { | ||
refreshToken: response.refreshToken, | ||
}); | ||
if (response.id && response.token) { | ||
client.updateUserState(response.id, response.token, response.refreshToken); | ||
} | ||
else { | ||
client.updateUserState(false); | ||
} | ||
resolve(response); | ||
@@ -51,6 +56,3 @@ }, reject, 'registerUser'); | ||
client.authCallbacks[reqId] = { | ||
resolve: (response) => { | ||
(0, token_1.default)(client, response.token); | ||
resolve(response); | ||
}, | ||
resolve, | ||
reject, | ||
@@ -81,3 +83,3 @@ }; | ||
resolve: (response) => { | ||
(0, token_1.default)(client); | ||
client.updateUserState(false); | ||
resolve(response); | ||
@@ -84,0 +86,0 @@ }, |
@@ -11,3 +11,6 @@ import { Connection } from './websocket/types'; | ||
set debug(v: true | ((message: any, type: 'incoming' | 'outgoing') => void)); | ||
user: string | false; | ||
optsId: number; | ||
token: string; | ||
tokenToLocalStorage: boolean; | ||
renewOptions: { | ||
@@ -23,2 +26,4 @@ refreshToken?: string; | ||
auth: ((x?: any) => void)[]; | ||
initUserState(): void; | ||
updateUserState(id: string | false, token?: string, refreshToken?: string): void; | ||
subscriptions: { | ||
@@ -25,0 +30,0 @@ [subscriptionId: string]: { |
@@ -28,5 +28,7 @@ "use strict"; | ||
const debug_1 = __importDefault(require("./debug")); | ||
const hash_1 = require("@saulx/hash"); | ||
__exportStar(require("@based/types"), exports); | ||
class BasedClient { | ||
constructor(based) { | ||
this.tokenToLocalStorage = false; | ||
this.auth = []; | ||
@@ -55,2 +57,95 @@ this.subscriptions = {}; | ||
} | ||
initUserState() { | ||
if (typeof window !== 'undefined') { | ||
if (this.based.opts) { | ||
const optsId = (0, hash_1.hash)({ | ||
cluster: this.based.opts.cluster, | ||
project: this.based.opts.project, | ||
env: this.based.opts.project, | ||
org: this.based.opts.org, | ||
}); | ||
this.optsId = optsId; | ||
} | ||
else { | ||
this.optsId = (0, hash_1.hash)('un-specified-env'); | ||
} | ||
try { | ||
const userString = global.localStorage.getItem('based-' + this.optsId + '-uid'); | ||
if (userString) { | ||
this.tokenToLocalStorage = true; | ||
try { | ||
const [id, token, refreshToken] = JSON.parse(userString); | ||
if (token && id) { | ||
this.updateUserState(id, token, refreshToken); | ||
} | ||
} | ||
catch (err) { | ||
global.localStorage.removeItem('based-' + this.optsId + '-uid'); | ||
} | ||
} | ||
} | ||
catch (err) { } | ||
} | ||
} | ||
updateUserState(id, token, refreshToken) { | ||
this.user = id; | ||
if (!this.tokenToLocalStorage && typeof window !== 'undefined') { | ||
try { | ||
global.localStorage.removeItem('based-' + this.optsId + '-uid'); | ||
} | ||
catch (err) { } | ||
} | ||
if (token) { | ||
if (refreshToken) { | ||
this.renewOptions = { refreshToken }; | ||
} | ||
if (refreshToken) { | ||
this.renewOptions = { | ||
...this.renewOptions, | ||
refreshToken, | ||
}; | ||
} | ||
(0, token_1.default)(this, token, { | ||
refreshToken: refreshToken, | ||
}); | ||
this.auth.push((isValid) => { | ||
if (isValid) { | ||
if (typeof window !== 'undefined') { | ||
try { | ||
if (this.tokenToLocalStorage) { | ||
global.localStorage.setItem('based-' + this.optsId + '-uid', JSON.stringify([id, token, refreshToken])); | ||
} | ||
} | ||
catch (err) { } | ||
} | ||
this.based.emit('auth', token); | ||
} | ||
else { | ||
if (typeof window !== 'undefined') { | ||
try { | ||
if (this.tokenToLocalStorage) { | ||
global.localStorage.removeItem('based-' + this.optsId + '-uid'); | ||
} | ||
} | ||
catch (err) { } | ||
} | ||
this.based.emit('auth', false); | ||
} | ||
}); | ||
} | ||
else { | ||
if (typeof window !== 'undefined') { | ||
this.user = false; | ||
try { | ||
if (this.tokenToLocalStorage) { | ||
global.localStorage.removeItem('based-' + this.optsId + '-uid'); | ||
} | ||
} | ||
catch (err) { } | ||
} | ||
(0, token_1.default)(this); | ||
this.based.emit('auth', false); | ||
} | ||
// handle dat localstorage | ||
} | ||
onClose() { | ||
@@ -93,4 +188,6 @@ this.connected = false; | ||
} | ||
// @ts-ignore | ||
const [type, reqId, payload, err, subscriptionErr] = data; | ||
if (type === types_1.RequestTypes.Token) { | ||
console.info(err); | ||
this.retryingRenewToken = false; | ||
@@ -101,2 +198,8 @@ // means stomething got de-auth wrong | ||
} | ||
if (!payload && | ||
typeof err === 'string' && | ||
this.user && | ||
this.renewOptions.refreshToken) { | ||
this.token = err; | ||
} | ||
for (const fn of this.auth) { | ||
@@ -120,2 +223,3 @@ fn(!payload); | ||
this.retryingRenewToken = true; | ||
const userId = this.user; | ||
(0, auth_1.renewToken)(this, this.renewOptions) | ||
@@ -136,2 +240,5 @@ .then((result) => { | ||
this.based.emit('renewToken', result); | ||
if (result) { | ||
this.updateUserState(userId, result.token, this.renewOptions.refreshToken); | ||
} | ||
}) | ||
@@ -138,0 +245,0 @@ .catch((err) => { |
@@ -38,6 +38,5 @@ "use strict"; | ||
xhr.onload = () => { | ||
let res = {}; | ||
// let res: any = {} | ||
try { | ||
res = JSON.parse(xhr.response); | ||
console.info('SUCCESS', res); | ||
JSON.parse(xhr.response); | ||
} | ||
@@ -44,0 +43,0 @@ catch (err) { |
@@ -104,5 +104,13 @@ import Emitter from './Emitter'; | ||
auth(token: string | false, options?: SendTokenOptions): Promise<false | string | number>; | ||
login(opts: LoginOpts): Promise<GenericObject>; | ||
register(opts: RegisterOpts): Promise<GenericObject>; | ||
login(opts: LoginOpts & { | ||
localStorage?: boolean; | ||
}): Promise<GenericObject>; | ||
register(opts: RegisterOpts & { | ||
localStorage?: boolean; | ||
}): Promise<GenericObject>; | ||
logout(): Promise<GenericObject>; | ||
observeAuth(userDataListener: (data: { | ||
id: string; | ||
token: string; | ||
} | false) => void): Promise<() => void>; | ||
} | ||
@@ -109,0 +117,0 @@ export declare type BasedOpts = { |
@@ -1,15 +0,15 @@ | ||
var it=Object.create;var U=Object.defineProperty,nt=Object.defineProperties,ot=Object.getOwnPropertyDescriptor,at=Object.getOwnPropertyDescriptors,ct=Object.getOwnPropertyNames,H=Object.getOwnPropertySymbols,ut=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty,we=Object.prototype.propertyIsEnumerable;var Oe=(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={}))ne.call(s,t)&&Oe(e,t,s[t]);if(H)for(var t of H(s))we.call(s,t)&&Oe(e,t,s[t]);return e},Ce=(e,s)=>nt(e,at(s));var Pe=(e,s)=>{var t={};for(var n in e)ne.call(e,n)&&s.indexOf(n)<0&&(t[n]=e[n]);if(e!=null&&H)for(var n of H(e))s.indexOf(n)<0&&we.call(e,n)&&(t[n]=e[n]);return t};var qe=(e,s)=>{for(var t in s)U(e,t,{get:s[t],enumerable:!0})},_=(e,s,t,n)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of ct(s))!ne.call(e,r)&&r!==t&&U(e,r,{get:()=>s[r],enumerable:!(n=ot(s,r))||n.enumerable});return e},d=(e,s,t)=>(_(e,s,"default"),t&&_(t,s,"default")),z=(e,s,t)=>(t=e!=null?it(ut(e)):{},_(s||!e||!e.__esModule?U(t,"default",{value:e,enumerable:!0}):t,e)),lt=e=>_(U({},"__esModule",{value:!0}),e);var m={};qe(m,{Based:()=>re,BasedClient:()=>D,BasedGraphQL:()=>S.BasedGraphQL,Observable:()=>P,addGetSubscriber:()=>K,addRequest:()=>y,addSubscriber:()=>F,createGraphqlOperations:()=>S.createOperations,default:()=>Ot,generateSubscriptionId:()=>q,generateTrackingKey:()=>he,handleGraphqlVariables:()=>S.handleGraphqlVariables,parseGraphql:()=>S.parseGraphql,removeSubscriber:()=>v});module.exports=lt(m);var ae=class{constructor(){this.listeners={};Object.defineProperty(this,"listeners",{enumerable:!1,writable:!0})}emit(s,t){this.listeners[s]&&this.listeners[s].forEach(n=>n(t))}on(s,t){this.listeners[s]||(this.listeners[s]=[]),this.listeners[s].push(t)}removeAllListeners(){this.listeners={}}once(s,t){this.on(s,n=>{t(n),this.removeListener(s,t)})}removeListener(s,t){let n=this.listeners[s];if(n){if(!t)delete this.listeners[s];else for(let r=0,i=n.length;r<i;r++)if(n[r]===t){n.splice(r,1);break}}}},Re=ae;var Be=(e,s)=>{typeof e=="function"?e().then(t=>{s(t)}):s(e)};var Fe=z(require("isomorphic-ws")),G=new Map,Ee;typeof window!="undefined"&&document.addEventListener("visibilitychange",function(){clearTimeout(Ee),document.hidden?Ee=setTimeout(()=>{G.forEach(e=>{e(!1)})},3e4):G.forEach(e=>{e(!0)})});var ce=(e,s,t={destroy:()=>{G.delete(t)}},n=0,r=!1)=>(Be(s,i=>{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),ce(e,s,t,0,!0)))});let c=t.ws=new Fe.default(i);c.onerror=()=>{},c.onmessage=a=>e.onData(a),c.onopen=()=>{if(o){if(t.disconnected)return;n=100,r&&e.onReconnect(),e.onOpen()}},c.onclose=()=>{if(o){if(t.disconnected)return;e.onClose(),ce(e,s,t,Math.min(1250,Math.min(n+500)),!0)}}},n)}),t),ue=ce;var k=require("@based/types");var I=require("@based/types");var j=require("@based/types");var pt=e=>{clearTimeout(e.idlePing),e.idlePing=setTimeout(()=>{e.connection&&e.connected&&!e.connection.disconnected&&e.connection.ws.send("1")},6e4)},J=pt;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&&le(e)},le=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.debugInternal&&e.debugInternal(s,"outgoing"),e.connection.ws.send(JSON.stringify(s)),J(e)}},0))},Ie=e=>{e.drainInProgress&&(clearTimeout(e.drainTimeout),e.drainInProgress=!1)};var pe=require("@saulx/hash"),q=(e,s)=>s?(0,pe.hashObjectIgnoreKeyOrder)([s,e]):(0,pe.hashObjectIgnoreKeyOrder)(e);var K=(e,s,t,n,r)=>{n||(n=q(s,r));let i=e.subscriptions[n],o=e.cache[n];if(i)if(i.authError)if(!e.beingAuth)t(i.authError.error,n,0);else{let c=++i.cnt;i.subscribers[c]={onInitial:t}}else if(o)t(null,n,0,o.value);else{let c=++i.cnt;i.subscribers[c]={onInitial:t}}else{i=e.subscriptions[n]={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===I.RequestTypes.Unsubscribe||u===I.RequestTypes.SendSubscriptionData)&&l===n?(e.subscriptionQueue.splice(a,1),a--):(u===I.RequestTypes.Subscription||u===I.RequestTypes.GetSubscription)&&l===n&&(c=!0,u===I.RequestTypes.Subscription&&(p!==o.checksum&&(e.subscriptionQueue[a][3]=o.checksum),e.subscriptionQueue[a][4]=2))}if(!c){let a=[I.RequestTypes.GetSubscription,n,s];o&&a.push(o.checksum),r&&(o||a.push(0),a.push(r)),f(e,a)}}};var R=require("@based/types");var F=(e,s,t,n,r,i,o)=>{i||(i=q(s,o));let c=e.subscriptions[i],a=e.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:r,onData:t,onInitial:n},l){for(let b=0;b<e.subscriptionQueue.length;b++){let[h,T]=e.subscriptionQueue[b];h===R.RequestTypes.GetSubscription&&T===i&&(e.subscriptionQueue.splice(b,1),b--)}let p=[R.RequestTypes.Subscription,i,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[i]={query:s,cnt:1,name:o,subscribers:{1:{onError:r,onData:t,onInitial:n}}};let l=!1,p=!1,b;for(let h=0;h<e.subscriptionQueue.length;h++){let[T,E,,x]=e.subscriptionQueue[h];(T===R.RequestTypes.Unsubscribe||T===R.RequestTypes.SendSubscriptionData||T===R.RequestTypes.GetSubscription)&&E===i?(T===R.RequestTypes.GetSubscription&&(p=!0),b&&(b[4]=2),e.subscriptionQueue.splice(h,1),h--):T===R.RequestTypes.Subscription&&E===i&&(l=!0,b=e.subscriptionQueue[h],x!==a.checksum&&(b[3]=a.checksum),!b[4]&&p&&(b[4]=2))}if(!l){let h=[R.RequestTypes.Subscription,i,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&&(n&&(n(null,i,u),delete c.subscribers[u].onInitial),t&&t(a.value,a.checksum)),[i,u]};var $=require("@based/types");var v=(e,s,t)=>{let n=e.subscriptions[s];if(n){let r=!1;if(t?n.subscribers[t]&&(delete n.subscribers[t],n.cnt--,n.cnt===0&&(r=!0)):r=!0,r){delete e.subscriptions[s];let i=!1;for(let o=0;o<e.subscriptionQueue.length;o++){let[c,a]=e.subscriptionQueue[o];c===$.RequestTypes.Unsubscribe&&a===s?i=!0:(c===$.RequestTypes.Subscription||c===$.RequestTypes.SendSubscriptionData)&&a===s&&(e.subscriptionQueue.splice(o,1),o--)}i||f(e,[$.RequestTypes.Unsubscribe,s])}}};var Qe=require("@based/types"),xe=e=>{for(let s=0;s<e.subscriptionQueue.length;s++)e.subscriptionQueue[s][0]===Qe.RequestTypes.Unsubscribe&&(e.subscriptionQueue.splice(s,1),s--)};var De=require("@based/types"),Ae=e=>{for(let s=0;s<e.subscriptionQueue.length;s++)e.subscriptionQueue[s][0]===De.RequestTypes.SendSubscriptionData&&(e.subscriptionQueue.splice(s,1),s--)};var Q=require("@based/types");var M=(e,s=!1)=>{for(let t in e.subscriptions){let n=Number(t),r=e.subscriptions[t];if(s&&!r.authError)continue;let i,o,c;for(let l=0;l<e.subscriptionQueue.length;l++){let[p,b]=e.subscriptionQueue[l];b===n&&(p===Q.RequestTypes.GetSubscription?(c=l,i=e.subscriptionQueue[l]):p===Q.RequestTypes.Subscription&&(o=e.subscriptionQueue[l]))}i&&o&&console.error("GET IN Q AND SUB IN Q SHOULD BE IMPOSSIBLE");let a=e.cache[n],u=!1;if(i){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&&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}=e.subscriptions[n];l?a?f(e,[Q.RequestTypes.Subscription,n,p,a.checksum,i?2:0,l]):f(e,[Q.RequestTypes.Subscription,n,p,0,i?2:0,l]):a?f(e,[Q.RequestTypes.Subscription,n,p,a.checksum,i?2:0]):f(e,[Q.RequestTypes.Subscription,n,p,0,i?2:0])}}};var Ue=require("@based/types");var W=(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}`},de=(e,s=0,t=!1,n="",r=!1)=>{let i="";for(let a=0;a<s;a++)i+=" ";let o=t?[]:n?[i+`${W(n,r?"brightRed":"white")} {`]:[i+"{"],c=!1;t||(i+=" ",s+=1);for(let a in e){let u=e[a],l=a[0]==="$"?W(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 b=u[p];o.push(...b&&typeof b=="object"?de(b,s+4):[`${i} ${b}`]),p!==u.length-1&&(o[o.length-1]+=",")}o.push(`${i} ]`)}else u&&typeof u=="object"?(o.push(`${i} ${l}: {`),o.push(...de(u,s+2,!0)),o.push(`${i} }`)):o.push(`${i} ${l}: ${u}`);c=!0}return t||o.push(i.slice(0,-1)+"}"),o},V=de;var C=e=>{let s=new Ue.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(` | ||
`),n=0;t[0]===""&&t.shift();let r=t[0];for(let i=0;i<r.length;i++)if(r[i]!==" "){n=i-2;break}n>0?t=t.map(i=>i.slice(n)):t=t.map(i=>" "+i),e.code&&(s.code=e.code),s.message=` | ||
var nt=Object.create;var D=Object.defineProperty,ot=Object.defineProperties,at=Object.getOwnPropertyDescriptor,ct=Object.getOwnPropertyDescriptors,ut=Object.getOwnPropertyNames,_=Object.getOwnPropertySymbols,lt=Object.getPrototypeOf,ae=Object.prototype.hasOwnProperty,Pe=Object.prototype.propertyIsEnumerable;var Ce=(t,s,e)=>s in t?D(t,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[s]=e,G=(t,s)=>{for(var e in s||(s={}))ae.call(s,e)&&Ce(t,e,s[e]);if(_)for(var e of _(s))Pe.call(s,e)&&Ce(t,e,s[e]);return t},J=(t,s)=>ot(t,ct(s));var qe=(t,s)=>{var e={};for(var r in t)ae.call(t,r)&&s.indexOf(r)<0&&(e[r]=t[r]);if(t!=null&&_)for(var r of _(t))s.indexOf(r)<0&&Pe.call(t,r)&&(e[r]=t[r]);return e};var Re=(t,s)=>{for(var e in s)D(t,e,{get:s[e],enumerable:!0})},z=(t,s,e,r)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of ut(s))!ae.call(t,i)&&i!==e&&D(t,i,{get:()=>s[i],enumerable:!(r=at(s,i))||r.enumerable});return t},p=(t,s,e)=>(z(t,s,"default"),e&&z(e,s,"default")),K=(t,s,e)=>(e=t!=null?nt(lt(t)):{},z(s||!t||!t.__esModule?D(e,"default",{value:t,enumerable:!0}):e,t)),dt=t=>z(D({},"__esModule",{value:!0}),t);var m={};Re(m,{Based:()=>ne,BasedClient:()=>x,BasedGraphQL:()=>T.BasedGraphQL,Observable:()=>C,addGetSubscriber:()=>V,addRequest:()=>y,addSubscriber:()=>I,createGraphqlOperations:()=>T.createOperations,default:()=>wt,generateSubscriptionId:()=>P,generateTrackingKey:()=>ye,handleGraphqlVariables:()=>T.handleGraphqlVariables,parseGraphql:()=>T.parseGraphql,removeSubscriber:()=>v});module.exports=dt(m);var ce=class{constructor(){this.listeners={};Object.defineProperty(this,"listeners",{enumerable:!1,writable:!0})}emit(s,e){this.listeners[s]&&this.listeners[s].forEach(r=>r(e))}on(s,e){this.listeners[s]||(this.listeners[s]=[]),this.listeners[s].push(e)}removeAllListeners(){this.listeners={}}once(s,e){this.on(s,r=>{e(r),this.removeListener(s,e)})}removeListener(s,e){let r=this.listeners[s];if(r){if(!e)delete this.listeners[s];else for(let i=0,n=r.length;i<n;i++)if(r[i]===e){r.splice(i,1);break}}}},Be=ce;var Ie=(t,s)=>{typeof t=="function"?t().then(e=>{s(e)}):s(t)};var Fe=K(require("isomorphic-ws")),j=new Map,Ee;typeof window!="undefined"&&document.addEventListener("visibilitychange",function(){clearTimeout(Ee),document.hidden?Ee=setTimeout(()=>{j.forEach(t=>{t(!1)})},3e4):j.forEach(t=>{t(!0)})});var ue=(t,s,e={destroy:()=>{j.delete(e)}},r=0,i=!1)=>(Ie(s,n=>{setTimeout(()=>{if(e.disconnected)return;let o=!0;j.set(e,a=>{e.disconnected||(!a&&o?(console.warn("Send to background - close connection"),o=!1,t.onClose(),c.close()):!o&&a&&(j.delete(e),ue(t,s,e,0,!0)))});let c=e.ws=new Fe.default(n);c.onerror=()=>{},c.onmessage=a=>t.onData(a),c.onopen=()=>{if(o){if(e.disconnected)return;r=100,i&&t.onReconnect(),t.onOpen()}},c.onclose=()=>{if(o){if(e.disconnected)return;t.onClose(),ue(t,s,e,Math.min(1250,Math.min(r+500)),!0)}}},r)}),e),le=ue;var k=require("@based/types");var F=require("@based/types");var $=require("@based/types");var pt=t=>{clearTimeout(t.idlePing),t.idlePing=setTimeout(()=>{t.connection&&t.connected&&!t.connection.disconnected&&t.connection.ws.send("1")},6e4)},W=pt;var b=(t,s)=>{s[0]===$.RequestTypes.Unsubscribe||s[0]===$.RequestTypes.Subscription||s[0]===$.RequestTypes.SendSubscriptionData||s[0]===$.RequestTypes.GetSubscription?t.subscriptionQueue.push(s):t.queue.push(s),t.connected&&!t.drainInProgress&&de(t)},de=t=>{t.connected&&!t.drainInProgress&&(t.queue.length||t.subscriptionQueue.length)&&!t.isLogginIn&&(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.debugInternal&&t.debugInternal(s,"outgoing"),t.connection.ws.send(JSON.stringify(s)),W(t)}},0))},Ue=t=>{t.drainInProgress&&(clearTimeout(t.drainTimeout),t.drainInProgress=!1)};var pe=require("@saulx/hash"),P=(t,s)=>s?(0,pe.hashObjectIgnoreKeyOrder)([s,t]):(0,pe.hashObjectIgnoreKeyOrder)(t);var V=(t,s,e,r,i)=>{r||(r=P(s,i));let n=t.subscriptions[r],o=t.cache[r];if(n)if(n.authError)if(!t.beingAuth)e(n.authError.error,r,0);else{let c=++n.cnt;n.subscribers[c]={onInitial:e}}else if(o)e(null,r,0,o.value);else{let c=++n.cnt;n.subscribers[c]={onInitial:e}}else{n=t.subscriptions[r]={query:s,cnt:1,name:i,subscribers:{1:{onInitial:e}}};let c;for(let a=0;a<t.subscriptionQueue.length;a++){let[u,l,,d]=t.subscriptionQueue[a];(u===F.RequestTypes.Unsubscribe||u===F.RequestTypes.SendSubscriptionData)&&l===r?(t.subscriptionQueue.splice(a,1),a--):(u===F.RequestTypes.Subscription||u===F.RequestTypes.GetSubscription)&&l===r&&(c=!0,u===F.RequestTypes.Subscription&&(d!==o.checksum&&(t.subscriptionQueue[a][3]=o.checksum),t.subscriptionQueue[a][4]=2))}if(!c){let a=[F.RequestTypes.GetSubscription,r,s];o&&a.push(o.checksum),i&&(o||a.push(0),a.push(i)),b(t,a)}}};var q=require("@based/types");var I=(t,s,e,r,i,n,o)=>{n||(n=P(s,o));let c=t.subscriptions[n],a=t.cache[n],u;if(c){u=++c.cnt;let l=!0;for(let d in c.subscribers)if(c.subscribers[d].onData){l=!1;break}if(c.subscribers[u]={onError:i,onData:e,onInitial:r},l){for(let f=0;f<t.subscriptionQueue.length;f++){let[h,O]=t.subscriptionQueue[f];h===q.RequestTypes.GetSubscription&&O===n&&(t.subscriptionQueue.splice(f,1),f--)}let d=[q.RequestTypes.Subscription,n,s];a&&(d.push(a.checksum),d.push(2)),o&&(a||d.push(0,2),d.push(o)),b(t,d)}}else{u=1,c=t.subscriptions[n]={query:s,cnt:1,name:o,subscribers:{1:{onError:i,onData:e,onInitial:r}}};let l=!1,d=!1,f;for(let h=0;h<t.subscriptionQueue.length;h++){let[O,B,,Q]=t.subscriptionQueue[h];(O===q.RequestTypes.Unsubscribe||O===q.RequestTypes.SendSubscriptionData||O===q.RequestTypes.GetSubscription)&&B===n?(O===q.RequestTypes.GetSubscription&&(d=!0),f&&(f[4]=2),t.subscriptionQueue.splice(h,1),h--):O===q.RequestTypes.Subscription&&B===n&&(l=!0,f=t.subscriptionQueue[h],Q!==a.checksum&&(f[3]=a.checksum),!f[4]&&d&&(f[4]=2))}if(!l){let h=[q.RequestTypes.Subscription,n,s];a&&(h.push(a.checksum),d&&h.push(2)),o&&(a?!d&&a&&h.push(2):h.push(0,0),h.push(o)),b(t,h)}}return a&&(r&&(r(null,n,u),delete c.subscribers[u].onInitial),e&&e(a.value,a.checksum)),[n,u]};var L=require("@based/types");var v=(t,s,e)=>{let r=t.subscriptions[s];if(r){let i=!1;if(e?r.subscribers[e]&&(delete r.subscribers[e],r.cnt--,r.cnt===0&&(i=!0)):i=!0,i){delete t.subscriptions[s];let n=!1;for(let o=0;o<t.subscriptionQueue.length;o++){let[c,a]=t.subscriptionQueue[o];c===L.RequestTypes.Unsubscribe&&a===s?n=!0:(c===L.RequestTypes.Subscription||c===L.RequestTypes.SendSubscriptionData)&&a===s&&(t.subscriptionQueue.splice(o,1),o--)}n||b(t,[L.RequestTypes.Unsubscribe,s])}}};var Qe=require("@based/types"),xe=t=>{for(let s=0;s<t.subscriptionQueue.length;s++)t.subscriptionQueue[s][0]===Qe.RequestTypes.Unsubscribe&&(t.subscriptionQueue.splice(s,1),s--)};var Ae=require("@based/types"),De=t=>{for(let s=0;s<t.subscriptionQueue.length;s++)t.subscriptionQueue[s][0]===Ae.RequestTypes.SendSubscriptionData&&(t.subscriptionQueue.splice(s,1),s--)};var U=require("@based/types");var M=(t,s=!1)=>{for(let e in t.subscriptions){let r=Number(e),i=t.subscriptions[e];if(s&&!i.authError)continue;let n,o,c;for(let l=0;l<t.subscriptionQueue.length;l++){let[d,f]=t.subscriptionQueue[l];f===r&&(d===U.RequestTypes.GetSubscription?(c=l,n=t.subscriptionQueue[l]):d===U.RequestTypes.Subscription&&(o=t.subscriptionQueue[l]))}n&&o&&console.error("GET IN Q AND SUB IN Q SHOULD BE IMPOSSIBLE");let a=t.cache[r],u=!1;if(n){let l=!0;for(let d in i.subscribers)if(i.subscribers[d].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:d}=t.subscriptions[r];l?a?b(t,[U.RequestTypes.Subscription,r,d,a.checksum,n?2:0,l]):b(t,[U.RequestTypes.Subscription,r,d,0,n?2:0,l]):a?b(t,[U.RequestTypes.Subscription,r,d,a.checksum,n?2:0]):b(t,[U.RequestTypes.Subscription,r,d,0,n?2:0])}}};var Ge=require("@based/types");var X=(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}`},fe=(t,s=0,e=!1,r="",i=!1)=>{let n="";for(let a=0;a<s;a++)n+=" ";let o=e?[]:r?[n+`${X(r,i?"brightRed":"white")} {`]:[n+"{"],c=!1;e||(n+=" ",s+=1);for(let a in t){let u=t[a],l=a[0]==="$"?X(a,"white"):a;if(c&&(o[o.length-1]+=","),Array.isArray(u)){o.push(`${n} ${l}: [`);for(let d=0;d<u.length;d++){let f=u[d];o.push(...f&&typeof f=="object"?fe(f,s+4):[`${n} ${f}`]),d!==u.length-1&&(o[o.length-1]+=",")}o.push(`${n} ]`)}else u&&typeof u=="object"?(o.push(`${n} ${l}: {`),o.push(...fe(u,s+2,!0)),o.push(`${n} }`)):o.push(`${n} ${l}: ${u}`);c=!0}return e||o.push(n.slice(0,-1)+"}"),o},Y=fe;var w=t=>{let s=new Ge.BasedError(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(` | ||
`),r=0;e[0]===""&&e.shift();let i=e[0];for(let n=0;n<i.length;n++)if(i[n]!==" "){r=n-2;break}r>0?e=e.map(n=>n.slice(r)):e=e.map(n=>" "+n),t.code&&(s.code=t.code),s.message=` | ||
`+(e.payload&&typeof e.payload!="object"?` ${W("Payload","brightRed")} ${e.payload}`:V(e.payload||e.query,0,!1,e.payload?"Payload":"Query",!0).map(i=>" "+i).join(` | ||
`+(t.payload&&typeof t.payload!="object"?` ${X("Payload","brightRed")} ${t.payload}`:Y(t.payload||t.query,0,!1,t.payload?"Payload":"Query",!0).map(n=>" "+n).join(` | ||
`))+` | ||
`+t.join(` | ||
`+e.join(` | ||
`)+` | ||
`}return s};var Ge=(e,s)=>{let[,t,n,r,i]=s,o=e.subscriptions[t];if(o){let c=e.cache[t]&&e.cache[t].checksum;if(i){let a=C(i);i.auth&&(o.authError={token:e.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(t),Number(u),void 0,!0),delete l.onInitial):(l.onInitial(a,Number(t),Number(u)),delete l.onInitial,v(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||v(e,t,Number(a)))}}else{o.authError&&delete o.authError,e.cache[t]={value:n,checksum:r};for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(t),Number(a),n),delete u.onInitial,u.onData||v(e,t,Number(a))),u.onData&&u.onData(n,r)}}}};var je=require("@saulx/diff"),X=require("@based/types");var $e=(e,s)=>{let[,t,n,[r,i]]=s,o=e.subscriptions[t];if(o){let c=e.cache[t];if(!c||c.checksum!==r)if(c)if(c.checksum===i)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||v(e,t,Number(a)))}else f(e,[X.RequestTypes.SendSubscriptionData,t]);else f(e,[X.RequestTypes.SendSubscriptionData,t]);else{let a=!1;try{c.value=(0,je.applyPatch)(c.value,n),c.value===null&&(a=!0)}catch(u){a=!0}if(a)console.warn(` | ||
`}return s};var je=(t,s)=>{let[,e,r,i,n]=s,o=t.subscriptions[e];if(o){let c=t.cache[e]&&t.cache[e].checksum;if(n){let a=w(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,v(t,e,Number(u))):l.onError&&l.onError(a)}}else if(c===i){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||v(t,e,Number(a)))}}else{o.authError&&delete o.authError,t.cache[e]={value:r,checksum:i};for(let a in o.subscribers){let u=o.subscribers[a];u.onInitial&&(u.onInitial(null,Number(e),Number(a),r),delete u.onInitial,u.onData||v(t,e,Number(a))),u.onData&&u.onData(r,i)}}}};var $e=require("@saulx/diff"),Z=require("@based/types");var Le=(t,s)=>{let[,e,r,[i,n]]=s,o=t.subscriptions[e];if(o){let c=t.cache[e];if(!c||c.checksum!==i)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||v(t,e,Number(a)))}else b(t,[Z.RequestTypes.SendSubscriptionData,e]);else b(t,[Z.RequestTypes.SendSubscriptionData,e]);else{let a=!1;try{c.value=(0,$e.applyPatch)(c.value,r),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(V(o.query,2,!1,"Query").join(` | ||
`),console.warn(Y(o.query,2,!1,"Query").join(` | ||
`)+` | ||
`),delete e.cache[t],f(e,[X.RequestTypes.SendSubscriptionData,t]);else{c.checksum=i;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||v(e,t,Number(u))),l.onData&&l.onData(c.value,c.checksum)}}}}};var Me=(e,s)=>{for(let t of s[1]){delete e.cache[t];let n=e.subscriptions[t];if(n){let r={type:"AuthorizationError",name:n.name?`observe "${n.name}"`:"observe",message:"Unauthorized request",payload:n.query,auth:!0},i=C(r);n.authError={token:e.token,error:i};for(let o in n.subscribers){let c=n.subscribers[o];c.onError&&c.onError(i)}}}};var Ne=require("@based/types");var dt=0,y=(e,s,t,n,r,i,o)=>{let c=++dt;e.requestCallbacks[c]={resolve:n,reject:r,type:s,payload:t,name:i,isRetry:o},s===Ne.RequestTypes.Call?f(e,[s,i,c,t]):f(e,[s,c,t])};var Le=(e,s)=>{let[,t,n,r]=s,i=e.requestCallbacks[t];i&&(delete e.requestCallbacks[t],r?i.reject(C(r)):i.resolve(n))};var O={};qe(O,{BasedClient:()=>D});var g=require("@based/types");var be=require("@based/types");var bt=e=>typeof e!="undefined"&&e!==null,ft=(e,s,t)=>{if(e.beingAuth=!0,s)e.token=s,e.sendTokenOptions=t;else{for(let n in e.cache)e.subscriptions[n]||delete e.cache[n];delete e.token,delete e.sendTokenOptions}if(e.connected){let n=s?[be.RequestTypes.Token,s,t].filter(bt):[be.RequestTypes.Token];e.connection.ws.send(JSON.stringify(n)),J(e),M(e,!0)}},w=ft;var B=require("@based/types");var fe=0,He=(e,s)=>{let t=++fe;return f(e,[B.RequestTypes.Auth,B.AuthRequestTypes.Login,t,s]),new Promise((n,r)=>{e.authCallbacks[t]={resolve:i=>{w(e,i.token,{refreshToken:i.refreshToken}),n(i)},reject:r}})},_e=(e,s)=>new Promise((t,n)=>{y(e,B.RequestTypes.Call,s,r=>{w(e,r.token,{refreshToken:r.refreshToken}),t(r)},n,"registerUser")}),ze=(e,s)=>{let t=++fe;return f(e,[B.RequestTypes.Auth,B.AuthRequestTypes.RenewToken,t,s]),new Promise((n,r)=>{e.authCallbacks[t]={resolve:i=>{w(e,i.token),n(i)},reject:r}})},Je=(e,s)=>{let[,t,n,r]=s,i=e.authCallbacks[t];i&&(delete e.authCallbacks[t],r?i.reject(C(r)):i.resolve(n))},Ke=e=>{let s=++fe;return f(e,[B.RequestTypes.Auth,B.AuthRequestTypes.Logout,s]),new Promise((t,n)=>{e.authCallbacks[s]={resolve:r=>{w(e),t(r)},reject:n}})};var We=(e,s)=>{let t=new Date,n=t.getHours()+":"+t.getMinutes()+":"+t.getSeconds()+":"+t.getMilliseconds();if(s==="incoming"){let r=`\u25BC ${n} -- `;console.info(r,e)}else{let r=`\u25B2 ${n} -- `;console.info(r,e)}};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}get debug(){return this.debugInternal}set debug(s){s===!0?this.debugInternal=We:this.debugInternal=s}onClose(){this.connected=!1,Ie(this),xe(this),Ae(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),M(this),le(this)}onData(s){var t,n;try{let r=JSON.parse(s.data);this.debugInternal&&this.debugInternal(r,"incoming");let[i,o,c,a,u]=r;if(i===g.RequestTypes.Token){this.retryingRenewToken=!1,o.length&&Me(this,r);for(let l of this.auth)l(!c);this.beingAuth=!1,this.auth=[]}else i===g.RequestTypes.Auth?Je(this,r):(((t=u||a)==null?void 0:t.code)===g.BasedErrorCodes.TokenExpired||((n=u||a)==null?void 0:n.message)==="Token expired")&&!this.retryingRenewToken?(this.retryingRenewToken=!0,ze(this,this.renewOptions).then(l=>{w(this,l.token,this.sendTokenOptions),i===g.RequestTypes.Subscription||i===g.RequestTypes.SubscriptionDiff?M(this):y(this,i,a==null?void 0:a.payload,this.requestCallbacks[o].resolve,this.requestCallbacks[o].reject),this.based.emit("renewToken",l)}).catch(l=>{var p;(p=this.requestCallbacks[o])==null||p.reject(l)})):i===g.RequestTypes.Set||i===g.RequestTypes.Get||i===g.RequestTypes.Configuration||i===g.RequestTypes.GetConfiguration||i===g.RequestTypes.Call||i===g.RequestTypes.Delete||i===g.RequestTypes.Copy||i===g.RequestTypes.Digest||i===g.RequestTypes.RemoveType||i===g.RequestTypes.RemoveField?Le(this,r):i===g.RequestTypes.Subscription?Ge(this,r):i===g.RequestTypes.SubscriptionDiff&&$e(this,r)}catch(r){console.error("Received incorrect data ",s.data)}}};var me=(e,s)=>{let t;if(e.configuration&&e.configuration.schema)for(let n in e.configuration.schema){let r=e.configuration.schema[n];if(r.prefixToTypeMapping){for(let i in r.prefixToTypeMapping)if(r.prefixToTypeMapping[i]===s){t=i;break}}}return t};var ke=require("@saulx/hash");var Xe=require("@based/types"),Ye=require("@saulx/hash"),Ve=new Set,mt=e=>{if(typeof window!="undefined"){if(Ve.has(e))return!1;Ve.add(e);try{let s="_ba:"+(0,Ye.hashCompact)(e);return localStorage.getItem(s)?!1:(localStorage.setItem(s,"1"),!0)}catch(s){return!1}}return!1},he=(e,s)=>{if(s){let t=`${e}`,n=Object.keys(s).sort();for(let r of n)t+="_"+r+"_"+s[r];return t}else return e},N=(e,s,t,n,r,i,o)=>{let c=he(s,t),a={t:c};o&&(a.r=1),r&&(a.e=1,i&&(a.o=i)),n?(a.s=1,e.tracking.delete(c)):o||(r||(e.tracking||(e.tracking=new Set),e.tracking.add(c)),mt(c)&&(a.u=1)),f(e,[Xe.RequestTypes.Track,a])};var ge=class{constructor(s,t,n){this.closed=!1;this.client=s,this.subId=n,this.subscriberId=t}unsubscribe(){this.closed=!0,v(this.client,this.subId,this.subscriberId)}},ye=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()}}},Y=class{constructor(s,t){this.client=s,this.components=t}subscribe(s,t,n){let r={data:{}},i=[];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);i.push(a)}return new ye(this.client,i)}},P=class{constructor(s,t,n){this.client=s,this.subId=typeof t=="string"?q(n,t):q(t),this.name=typeof t=="string"?t:null,this.payload=typeof t=="string"?n:t}subscribe(s,t,n){let[,r]=F(this.client,this.payload,s,i=>{i&&(console.error(i),t&&t(i))},t,this.subId,this.name);return new ge(this.client,r,this.subId)}};var ve={},L={},ht=(e,s)=>{ve[e]||(ve[e]=!0,setTimeout(()=>{console.info("Drain file q"),ve[e]=!1;let t=L[e];L[e]=[];let n=new global.FormData;for(let r of t){let{raw:i,name:o,id:c,file:a,functionName:u}=r,l=`${u||""}|${i?1:0}|${c}|${a.size}${o?`|${o}`:""}`;n.append(l,a)}try{let r=new global.XMLHttpRequest;r.upload.onprogress=i=>{let o=100*(i.loaded||i.position)/(i.totalSize||i.total);console.info(o,"upload...")},r.onerror=i=>{console.error("error!",i,"flap",r.responseText)},r.timeout=1e3*60*60*24,r.onabort=i=>{console.error("abort",i)},r.ontimeout=i=>{console.error("on timeout",i)},r.onload=()=>{let i={};try{i=JSON.parse(r.response),console.info("SUCCESS",i)}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(n)}catch(r){console.error("Something wrong with xhr upload",r)}},500))},Ze=async(e,s,t,n,r,i,o)=>{L[t]||(L[t]=[]),L[t].push({file:s,id:n,url:t,raw:r,name:i,functionName:o}),ht(t,e.getToken())};var et=z(require("@based/get-service")),Z={},ee={},gt=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:n,org:r}=e.opts,i=t+"/"+n+"/"+r+"/"+e.opts.cluster;if(Z[i])return Z[i];if(ee[i])return(await ee[i]).url;let o=await(ee[i]=(0,et.default)({env:t,project:n,org:r,name:"@based/hub",key:"file-upload",optionalKey:!0},0,e.opts.cluster));return delete ee[i],setTimeout(()=>{delete Z[i]},2e3),Z[i]=o.url},tt=gt;var st=z(require("cross-fetch")),te=(e,s,t)=>((0,st.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(n=>{}).catch(n=>{console.error("Error while uploading file",n)}),{id:t.id});var A=require("./file/stream"),se=typeof window!="undefined",yt=e=>"src"in e&&typeof e.src=="string",vt=e=>"path"in e&&typeof e.path=="string",kt=e=>"contents"in e&&(0,A.isStream)(e.contents),rt=async(e,s)=>{if(yt(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 n=(await tt(e,s)).replace(/^ws/,"http");if(vt(s))return(0,A.uploadFilePath)(e,n,s),{id:t};if(kt(s))return(0,A.uploadFileStream)(e,n,s),{id:t};if(s.contents instanceof ArrayBuffer)return s.contents=se?new global.Blob([s.contents],{type:s.mimeType||"text/plain"}):global.Buffer.from(s.contents),te(e,n+"/file",s);if(se&&s.contents instanceof global.Blob)return s.mimeType||(s.mimeType=s.contents.type),te(e,n+"/file",s);if(typeof s.contents=="string"||!se&&s.contents instanceof global.Buffer)return te(e,n+"/file",s);if(se&&s.contents instanceof File)return Ze(e,s.contents,n,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 ie=z(require("@based/get-service")),Se=require("@saulx/utils"),S=require("@based/graphql");d(m,require("@based/types"),module.exports);var re=class extends Re{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=ue(this.client,this._url)):(this._url=t,this.client.connection=ue(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,n,r){return new Promise((i,o)=>{let c,a=!1;this.observe(t,(u,l)=>{r&&r(u,l),n(u,l)&&(a=!0,c&&c(),i(u))}).then(u=>{a?c():c=u}).catch(u=>{o(u)})})}gql(t,...n){typeof t=="string"&&(t=[t]);let r=t[0];return n.forEach((i,o)=>{i&&i.kind==="Document"?r+=i.loc.source.body:r+=i,r+=t[o+1]}),(0,S.createOperations)({schemas:this.client.configuration.schema},(0,S.parseGraphql)(r))}gqlDb(t="default"){return(n,...r)=>{typeof n=="string"&&(n=[n]);let i=n[0];return r.forEach((o,c)=>{o&&o.kind==="Document"?i+=o.loc.source.body:i+=o,i+=n[c+1]}),(0,S.createOperations)({schemas:this.client.configuration.schema,db:t},(0,S.parseGraphql)(i))}}observe(t,n,r,i){return typeof t=="string"?new Promise((o,c)=>{let a=typeof n=="function",u=a?n:r,l=a?r:i;F(this.client,a?void 0:n,u,(p,b,h,T,E)=>{p&&!E?c(p):o(()=>{v(this.client,b,h)})},l,void 0,t)}):new Promise((o,c)=>{F(this.client,t,n,(a,u,l,p,b)=>{a&&!b?c(a):o(()=>{v(this.client,u,l)})},r)})}createObservable(t,n){return typeof t=="string"?new P(this.client,t,n):new P(this.client,t)}observeSchema(t,n,r){return new Promise((i,o)=>{let c=typeof t=="string"?t:"default",a=typeof t=="string"?n:t,u=typeof t=="string"?r:n;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,b,h,T)=>{l&&!T?o(l):i(()=>{v(this.client,p,b)})},u)})}get(t,n){return typeof t=="string"?new Promise((r,i)=>{K(this.client,n,(o,c,a,u)=>{o?i(o):r(u)},0,t)}):new Promise((r,i)=>{y(this.client,k.RequestTypes.Get,t,r,i)})}file(t){return global.File&&t instanceof File&&(t={contents:t}),rt(this,t)}call(t,n){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Call,n,r,i,t)})}async id(t,n){let r=me(this.client,t);if(r||(await this.schema(),r=me(this.client,t)),!r)throw C({message:`Type does not exist ${t}`,type:"Invalid type",payload:n?{type:t,opts:n}:{type:t}});if(n){let i=(0,ke.hashCompact)(n,8,!0);return r+i}else return r+(0,ke.hashCompact)(Math.floor(Math.random()*99999999999)+""+Date.now())}digest(t){return new Promise((n,r)=>{y(this.client,k.RequestTypes.Digest,t,n,r)})}set(t){return new Promise((n,r)=>{y(this.client,k.RequestTypes.Set,t,n,r)})}copy(t){return new Promise((n,r)=>{y(this.client,k.RequestTypes.Copy,t,n,r)})}async gqlQuery(t,n={}){let r;typeof t=="string"?r=this.gql(t):r=t;try{if(r=(0,S.handleGraphqlVariables)(r,r,n),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 i={};return await Promise.all(Object.entries(r.ops).map(async([o,c])=>{var p,b,h,T,E;if(c.delete){i[o]=await this.delete(c.delete);return}else if(c.fnCall){i[o]=await this.call(c.fnCall.name,c.fnCall.payload);return}let{id:a}=await this.set(c.set);if(!c.get){let x={};x.id=a;let Te=(E=(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:E[a.slice(0,2)];Te&&(x.type=Te),i[o]=x;return}let u=(0,Se.deepCopy)(c.get);u.$id=a;let l=await this.get(u);i[o]=l})),{data:i}}catch(i){return{errors:[{message:i.message,locations:i.locations}]}}}async gqlLive(t,n={}){let r;if(typeof t=="string"?r=this.gql(t):r=t,r=(0,S.handleGraphqlVariables)(r,r,n),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 Y(this.client,a)}return new P(this.client,{$db:r.db,data:c})}let i={};return await Promise.all(Object.entries(r.ops).map(async([o,c])=>{if(c.delete){i[o]=await this.delete(c.delete);return}else if(c.fnCall){i[o]=await this.call(c.fnCall.name,c.fnCall.payload);return}let{id:a}=await this.set(c.set),u=(0,Se.deepCopy)(c.get);u.$id=a,i[o]=u})),new P(this.client,{$db:r.db,data:i})}analytics(t,n){return new Promise((r,i)=>{n?F(this.client,t,n,(o,c,a,u,l)=>{o&&!l?i(o):r(()=>{v(this.client,c,a)})},o=>console.error(o),void 0,"analytics"):K(this.client,t,(o,c,a,u)=>{o?i(o):((0,k.isAnalyticsHistoryOpts)(t)||(0,k.isAnalyticsTypesOpts)(t),r(u))},0,"analytics")})}track(t,n){N(this.client,t,n)}clearAnalytics(t,n){N(this.client,t,n,!1,!1,void 0,!0)}untrack(t,n){N(this.client,t,n,!0)}event(t,n,r){N(this.client,t,n,!1,!0,r)}delete(t){return new Promise((n,r)=>{y(this.client,k.RequestTypes.Delete,t,n,r)})}schema(){return new Promise((t,n)=>{let r=i=>{this.client.configuration=i,t(i)};y(this.client,k.RequestTypes.GetConfiguration,0,r,n)})}removeType(t,n="default"){return new Promise((r,i)=>{y(this.client,k.RequestTypes.RemoveType,{type:t,db:n},r,i)})}removeField(t,n,r="default"){return new Promise((i,o)=>{!n||n.length===0?o(new Error("Path cannot be empty")):(Array.isArray(n)||(n=[n]),y(this.client,k.RequestTypes.RemoveField,{type:t,db:r,path:n},i,o))})}updateSchema(t){return new Promise((n,r)=>{y(this.client,k.RequestTypes.Configuration,t,n,r)})}getToken(){return this.client.token}auth(t,n){return new Promise(r=>{if(this.client.auth.push(r),t&&t!==this.client.token||t===!1&&this.client.token){if(typeof t=="string"){let i=n||{},{renewOptions:o,refreshToken:c}=i,a=Pe(i,["renewOptions","refreshToken"]);o&&(this.client.renewOptions=o),c&&(this.client.renewOptions=Ce(oe({},this.client.renewOptions),{refreshToken:c})),w(this.client,t,a)}else w(this.client);this.emit("auth",t)}})}async login(t){return He(this.client,t)}async register(t){return _e(this.client,t)}logout(){return Ke(this.client)}},St=(e,s)=>{if(s){let t;e+=/\?/.test(e)?"&":"?";for(let n in s){let r=s[n];e+=t?`&${n}=${r}`:`${n}=${r}`,t=!0}}return e},Tt=(e,s=re)=>{let{env:t,project:n,org:r,url:i,key:o,name:c="@based/hub",cluster:a,params:u}=e;if(i||(a=e.cluster=(0,ie.getClusterUrl)(a),i=async()=>{let{url:l}=await(0,ie.default)({env:t,project:n,org:r,key:o,name:c},0,a);return St(l,u)}),i){let l=new s;return l.opts=e,l.connect(i),l}},Ot=Tt;0&&(module.exports={Based,BasedClient,BasedGraphQL,Observable,addGetSubscriber,addRequest,addSubscriber,createGraphqlOperations,generateSubscriptionId,generateTrackingKey,handleGraphqlVariables,parseGraphql,removeSubscriber}); | ||
`),delete t.cache[e],b(t,[Z.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||v(t,e,Number(u))),l.onData&&l.onData(c.value,c.checksum)}}}}};var Me=(t,s)=>{for(let e of s[1]){delete t.cache[e];let r=t.subscriptions[e];if(r){let i={type:"AuthorizationError",name:r.name?`observe "${r.name}"`:"observe",message:"Unauthorized request",payload:r.query,auth:!0},n=w(i);r.authError={token:t.token,error:n};for(let o in r.subscribers){let c=r.subscribers[o];c.onError&&c.onError(n)}}}};var Ne=require("@based/types");var ft=0,y=(t,s,e,r,i,n,o)=>{let c=++ft;t.requestCallbacks[c]={resolve:r,reject:i,type:s,payload:e,name:n,isRetry:o},s===Ne.RequestTypes.Call?b(t,[s,n,c,e]):b(t,[s,c,e])};var He=(t,s)=>{let[,e,r,i]=s,n=t.requestCallbacks[e];n&&(delete t.requestCallbacks[e],i?n.reject(w(i)):n.resolve(r))};var S={};Re(S,{BasedClient:()=>x});var g=require("@based/types");var be=require("@based/types");var bt=t=>typeof t!="undefined"&&t!==null,mt=(t,s,e)=>{if(t.beingAuth=!0,s)t.token=s,t.sendTokenOptions=e;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=s?[be.RequestTypes.Token,s,e].filter(bt):[be.RequestTypes.Token];t.connection.ws.send(JSON.stringify(r)),W(t),M(t,!0)}},E=mt;var R=require("@based/types");var me=0,_e=(t,s)=>{let e=++me;return b(t,[R.RequestTypes.Auth,R.AuthRequestTypes.Login,e,s]),new Promise((r,i)=>{t.authCallbacks[e]={resolve:n=>{n.id&&n.token?t.updateUserState(n.id,n.token,n.refreshToken):t.updateUserState(!1),r(n)},reject:i}})},ze=(t,s)=>new Promise((e,r)=>{y(t,R.RequestTypes.Call,s,i=>{i.id&&i.token?t.updateUserState(i.id,i.token,i.refreshToken):t.updateUserState(!1),e(i)},r,"registerUser")}),Je=(t,s)=>{let e=++me;return b(t,[R.RequestTypes.Auth,R.AuthRequestTypes.RenewToken,e,s]),new Promise((r,i)=>{t.authCallbacks[e]={resolve:r,reject:i}})},Ke=(t,s)=>{let[,e,r,i]=s,n=t.authCallbacks[e];n&&(delete t.authCallbacks[e],i?n.reject(w(i)):n.resolve(r))},We=t=>{let s=++me;return b(t,[R.RequestTypes.Auth,R.AuthRequestTypes.Logout,s]),new Promise((e,r)=>{t.authCallbacks[s]={resolve:i=>{t.updateUserState(!1),e(i)},reject:r}})};var Ve=(t,s)=>{let e=new Date,r=e.getHours()+":"+e.getMinutes()+":"+e.getSeconds()+":"+e.getMilliseconds();if(s==="incoming"){let i=`\u25BC ${r} -- `;console.info(i,t)}else{let i=`\u25B2 ${r} -- `;console.info(i,t)}};var he=require("@saulx/hash");p(S,require("@based/types"));var x=class{constructor(s){this.tokenToLocalStorage=!1;this.auth=[];this.subscriptions={};this.cache={};this.requestCallbacks={};this.authCallbacks={};this.connected=!1;this.subscriptionQueue=[];this.queue=[];this.drainInProgress=!1;this.based=s}get debug(){return this.debugInternal}set debug(s){s===!0?this.debugInternal=Ve:this.debugInternal=s}initUserState(){if(typeof window!="undefined"){if(this.based.opts){let s=(0,he.hash)({cluster:this.based.opts.cluster,project:this.based.opts.project,env:this.based.opts.project,org:this.based.opts.org});this.optsId=s}else this.optsId=(0,he.hash)("un-specified-env");try{let s=global.localStorage.getItem("based-"+this.optsId+"-uid");if(s){this.tokenToLocalStorage=!0;try{let[e,r,i]=JSON.parse(s);r&&e&&this.updateUserState(e,r,i)}catch(e){global.localStorage.removeItem("based-"+this.optsId+"-uid")}}}catch(s){}}}updateUserState(s,e,r){if(this.user=s,!this.tokenToLocalStorage&&typeof window!="undefined")try{global.localStorage.removeItem("based-"+this.optsId+"-uid")}catch(i){}if(e)r&&(this.renewOptions={refreshToken:r}),r&&(this.renewOptions=J(G({},this.renewOptions),{refreshToken:r})),E(this,e,{refreshToken:r}),this.auth.push(i=>{if(i){if(typeof window!="undefined")try{this.tokenToLocalStorage&&global.localStorage.setItem("based-"+this.optsId+"-uid",JSON.stringify([s,e,r]))}catch(n){}this.based.emit("auth",e)}else{if(typeof window!="undefined")try{this.tokenToLocalStorage&&global.localStorage.removeItem("based-"+this.optsId+"-uid")}catch(n){}this.based.emit("auth",!1)}});else{if(typeof window!="undefined"){this.user=!1;try{this.tokenToLocalStorage&&global.localStorage.removeItem("based-"+this.optsId+"-uid")}catch(i){}}E(this),this.based.emit("auth",!1)}}onClose(){this.connected=!1,Ue(this),xe(this),De(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)b(this,[g.RequestTypes.Track,{t:s}])}onOpen(){this.connected=!0,this.based.listeners.connect&&this.based.listeners.connect.forEach(s=>s()),this.token&&E(this,this.token,this.sendTokenOptions),M(this),de(this)}onData(s){var e,r;try{let i=JSON.parse(s.data);this.debugInternal&&this.debugInternal(i,"incoming");let[n,o,c,a,u]=i;if(n===g.RequestTypes.Token){console.info(a),this.retryingRenewToken=!1,o.length&&Me(this,i),!c&&typeof a=="string"&&this.user&&this.renewOptions.refreshToken&&(this.token=a);for(let l of this.auth)l(!c);this.beingAuth=!1,this.auth=[]}else if(n===g.RequestTypes.Auth)Ke(this,i);else if((((e=u||a)==null?void 0:e.code)===g.BasedErrorCodes.TokenExpired||((r=u||a)==null?void 0:r.message)==="Token expired")&&!this.retryingRenewToken){this.retryingRenewToken=!0;let l=this.user;Je(this,this.renewOptions).then(d=>{E(this,d.token,this.sendTokenOptions),n===g.RequestTypes.Subscription||n===g.RequestTypes.SubscriptionDiff?M(this):y(this,n,a==null?void 0:a.payload,this.requestCallbacks[o].resolve,this.requestCallbacks[o].reject),this.based.emit("renewToken",d),d&&this.updateUserState(l,d.token,this.renewOptions.refreshToken)}).catch(d=>{var f;(f=this.requestCallbacks[o])==null||f.reject(d)})}else n===g.RequestTypes.Set||n===g.RequestTypes.Get||n===g.RequestTypes.Configuration||n===g.RequestTypes.GetConfiguration||n===g.RequestTypes.Call||n===g.RequestTypes.Delete||n===g.RequestTypes.Copy||n===g.RequestTypes.Digest||n===g.RequestTypes.RemoveType||n===g.RequestTypes.RemoveField?He(this,i):n===g.RequestTypes.Subscription?je(this,i):n===g.RequestTypes.SubscriptionDiff&&Le(this,i)}catch(i){console.error("Received incorrect data ",s.data)}}};var ge=(t,s)=>{let e;if(t.configuration&&t.configuration.schema)for(let r in t.configuration.schema){let i=t.configuration.schema[r];if(i.prefixToTypeMapping){for(let n in i.prefixToTypeMapping)if(i.prefixToTypeMapping[n]===s){e=n;break}}}return e};var Te=require("@saulx/hash");var Ye=require("@based/types"),Ze=require("@saulx/hash"),Xe=new Set,ht=t=>{if(typeof window!="undefined"){if(Xe.has(t))return!1;Xe.add(t);try{let s="_ba:"+(0,Ze.hashCompact)(t);return localStorage.getItem(s)?!1:(localStorage.setItem(s,"1"),!0)}catch(s){return!1}}return!1},ye=(t,s)=>{if(s){let e=`${t}`,r=Object.keys(s).sort();for(let i of r)e+="_"+i+"_"+s[i];return e}else return t},N=(t,s,e,r,i,n,o)=>{let c=ye(s,e),a={t:c};o&&(a.r=1),i&&(a.e=1,n&&(a.o=n)),r?(a.s=1,t.tracking.delete(c)):o||(i||(t.tracking||(t.tracking=new Set),t.tracking.add(c)),ht(c)&&(a.u=1)),b(t,[Ye.RequestTypes.Track,a])};var ve=class{constructor(s,e,r){this.closed=!1;this.client=s,this.subId=r,this.subscriberId=e}unsubscribe(){this.closed=!0,v(this.client,this.subId,this.subscriberId)}},ke=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()}}},ee=class{constructor(s,e){this.client=s,this.components=e}subscribe(s,e,r){let i={data:{}},n=[];for(let{key:o,obs:c}of this.components){let a=c.subscribe(u=>{if(o===""){Object.assign(i.data,u),s(i);return}i.data[o]=u,s(i)},e);n.push(a)}return new ke(this.client,n)}},C=class{constructor(s,e,r){this.client=s,this.subId=typeof e=="string"?P(r,e):P(e),this.name=typeof e=="string"?e:null,this.payload=typeof e=="string"?r:e}subscribe(s,e,r){let[,i]=I(this.client,this.payload,s,n=>{n&&(console.error(n),e&&e(n))},e,this.subId,this.name);return new ve(this.client,i,this.subId)}};var Se={},H={},gt=(t,s)=>{Se[t]||(Se[t]=!0,setTimeout(()=>{console.info("Drain file q"),Se[t]=!1;let e=H[t];H[t]=[];let r=new global.FormData;for(let i of e){let{raw:n,name:o,id:c,file:a,functionName:u}=i,l=`${u||""}|${n?1:0}|${c}|${a.size}${o?`|${o}`:""}`;r.append(l,a)}try{let i=new global.XMLHttpRequest;i.upload.onprogress=n=>{let o=100*(n.loaded||n.position)/(n.totalSize||n.total);console.info(o,"upload...")},i.onerror=n=>{console.error("error!",n,"flap",i.responseText)},i.timeout=1e3*60*60*24,i.onabort=n=>{console.error("abort",n)},i.ontimeout=n=>{console.error("on timeout",n)},i.onload=()=>{try{JSON.parse(i.response)}catch(n){console.error("something wrong with file upload",n)}},i.open("POST",t+"/file"),i.setRequestHeader("Content-Type","multipart/form-data"),i.setRequestHeader("Authorization",s),i.send(r)}catch(i){console.error("Something wrong with xhr upload",i)}},500))},et=async(t,s,e,r,i,n,o)=>{H[e]||(H[e]=[]),H[e].push({file:s,id:r,url:e,raw:i,name:n,functionName:o}),gt(e,t.getToken())};var tt=K(require("@based/get-service")),te={},se={},yt=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:r,org:i}=t.opts,n=e+"/"+r+"/"+i+"/"+t.opts.cluster;if(te[n])return te[n];if(se[n])return(await se[n]).url;let o=await(se[n]=(0,tt.default)({env:e,project:r,org:i,name:"@based/hub",key:"file-upload",optionalKey:!0},0,t.opts.cluster));return delete se[n],setTimeout(()=>{delete te[n]},2e3),te[n]=o.url},st=yt;var it=K(require("cross-fetch")),ie=(t,s,e)=>((0,it.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(r=>{}).catch(r=>{console.error("Error while uploading file",r)}),{id:e.id});var A=require("./file/stream"),re=typeof window!="undefined",vt=t=>"src"in t&&typeof t.src=="string",kt=t=>"path"in t&&typeof t.path=="string",St=t=>"contents"in t&&(0,A.isStream)(t.contents),rt=async(t,s)=>{if(vt(s)){let i=s.id?{$id:s.id}:{type:"file"};return s.src?(i.src=s.src,i.origin=s.src,s.size&&(i.size=s.size),s.name&&(i.name=s.name),s.parents&&(i.parents=s.parents),await t.set(i)):void 0}let e=s.id;if(!e){let i={type:"file",progress:0};s.name?i.name=s.name:global.File&&"contents"in s&&s.contents instanceof global.File&&(i.name=s.contents.name),s.parents&&(i.parents=s.parents),e=(await t.set(i)).id}s.id=e;let r=(await st(t,s)).replace(/^ws/,"http");if(kt(s))return(0,A.uploadFilePath)(t,r,s),{id:e};if(St(s))return(0,A.uploadFileStream)(t,r,s),{id:e};if(s.contents instanceof ArrayBuffer)return s.contents=re?new global.Blob([s.contents],{type:s.mimeType||"text/plain"}):global.Buffer.from(s.contents),ie(t,r+"/file",s);if(re&&s.contents instanceof global.Blob)return s.mimeType||(s.mimeType=s.contents.type),ie(t,r+"/file",s);if(typeof s.contents=="string"||!re&&s.contents instanceof global.Buffer)return ie(t,r+"/file",s);if(re&&s.contents instanceof File)return et(t,s.contents,r,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 oe=K(require("@based/get-service")),Oe=require("@saulx/utils"),T=require("@based/graphql");p(m,require("@based/types"),module.exports);var ne=class extends Be{constructor(e){super();this.client=new x(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=le(this.client,this._url)):(this._url=e,this.client.connection=le(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,r,i){return new Promise((n,o)=>{let c,a=!1;this.observe(e,(u,l)=>{i&&i(u,l),r(u,l)&&(a=!0,c&&c(),n(u))}).then(u=>{a?c():c=u}).catch(u=>{o(u)})})}gql(e,...r){typeof e=="string"&&(e=[e]);let i=e[0];return r.forEach((n,o)=>{n&&n.kind==="Document"?i+=n.loc.source.body:i+=n,i+=e[o+1]}),(0,T.createOperations)({schemas:this.client.configuration.schema},(0,T.parseGraphql)(i))}gqlDb(e="default"){return(r,...i)=>{typeof r=="string"&&(r=[r]);let n=r[0];return i.forEach((o,c)=>{o&&o.kind==="Document"?n+=o.loc.source.body:n+=o,n+=r[c+1]}),(0,T.createOperations)({schemas:this.client.configuration.schema,db:e},(0,T.parseGraphql)(n))}}observe(e,r,i,n){return typeof e=="string"?new Promise((o,c)=>{let a=typeof r=="function",u=a?r:i,l=a?i:n;I(this.client,a?void 0:r,u,(d,f,h,O,B)=>{d&&!B?c(d):o(()=>{v(this.client,f,h)})},l,void 0,e)}):new Promise((o,c)=>{I(this.client,e,r,(a,u,l,d,f)=>{a&&!f?c(a):o(()=>{v(this.client,u,l)})},i)})}createObservable(e,r){return typeof e=="string"?new C(this.client,e,r):new C(this.client,e)}observeSchema(e,r,i){return new Promise((n,o)=>{let c=typeof e=="string"?e:"default",a=typeof e=="string"?r:e,u=typeof e=="string"?i:r;I(this.client,{$subscribe_schema:c},(l,d)=>{this.client.configuration||(this.client.configuration={dbs:[],schema:{},functions:{}}),this.client.configuration.schema[c]=l,a(l,d)},(l,d,f,h,O)=>{l&&!O?o(l):n(()=>{v(this.client,d,f)})},u)})}get(e,r){return typeof e=="string"?new Promise((i,n)=>{V(this.client,r,(o,c,a,u)=>{o?n(o):i(u)},0,e)}):new Promise((i,n)=>{y(this.client,k.RequestTypes.Get,e,i,n)})}file(e){return global.File&&e instanceof File&&(e={contents:e}),rt(this,e)}call(e,r){return new Promise((i,n)=>{y(this.client,k.RequestTypes.Call,r,i,n,e)})}async id(e,r){let i=ge(this.client,e);if(i||(await this.schema(),i=ge(this.client,e)),!i)throw w({message:`Type does not exist ${e}`,type:"Invalid type",payload:r?{type:e,opts:r}:{type:e}});if(r){let n=(0,Te.hashCompact)(r,8,!0);return i+n}else return i+(0,Te.hashCompact)(Math.floor(Math.random()*99999999999)+""+Date.now())}digest(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Digest,e,r,i)})}set(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Set,e,r,i)})}copy(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Copy,e,r,i)})}async gqlQuery(e,r={}){let i;typeof e=="string"?i=this.gql(e):i=e;try{if(i=(0,T.handleGraphqlVariables)(i,i,r),i.opType==="GET"){let o={$db:i.db},c=[];for(let u in i.ops){if(i.ops[u].fnObserve){let l=await this.get(i.ops[u].fnObserve.name,i.ops[u].fnObserve.payload);c.push({key:u,reply:l});continue}i.ops[u].get&&(o[u]=i.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(i.ops).map(async([o,c])=>{var d,f,h,O,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 Q={};Q.id=a;let we=(B=(O=(h=(f=(d=this.client)==null?void 0:d.configuration)==null?void 0:f.schema)==null?void 0:h[i.db])==null?void 0:O.prefixToTypeMapping)==null?void 0:B[a.slice(0,2)];we&&(Q.type=we),n[o]=Q;return}let u=(0,Oe.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,r={}){let i;if(typeof e=="string"?i=this.gql(e):i=e,i=(0,T.handleGraphqlVariables)(i,i,r),i.opType==="GET"){let o=[],c={};for(let a in i.ops){if(i.ops[a].fnObserve){let{name:u,payload:l}=i.ops[a].fnObserve;o.push({key:a,fn:{name:u,payload:l}});continue}c[a]=i.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,G({$db:i.db},c));return a.push({key:"",obs:u}),new ee(this.client,a)}return new C(this.client,{$db:i.db,data:c})}let n={};return await Promise.all(Object.entries(i.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,Oe.deepCopy)(c.get);u.$id=a,n[o]=u})),new C(this.client,{$db:i.db,data:n})}analytics(e,r){return new Promise((i,n)=>{r?I(this.client,e,r,(o,c,a,u,l)=>{o&&!l?n(o):i(()=>{v(this.client,c,a)})},o=>console.error(o),void 0,"analytics"):V(this.client,e,(o,c,a,u)=>{o?n(o):((0,k.isAnalyticsHistoryOpts)(e)||(0,k.isAnalyticsTypesOpts)(e),i(u))},0,"analytics")})}track(e,r){N(this.client,e,r)}clearAnalytics(e,r){N(this.client,e,r,!1,!1,void 0,!0)}untrack(e,r){N(this.client,e,r,!0)}event(e,r,i){N(this.client,e,r,!1,!0,i)}delete(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Delete,e,r,i)})}schema(){return new Promise((e,r)=>{let i=n=>{this.client.configuration=n,e(n)};y(this.client,k.RequestTypes.GetConfiguration,0,i,r)})}removeType(e,r="default"){return new Promise((i,n)=>{y(this.client,k.RequestTypes.RemoveType,{type:e,db:r},i,n)})}removeField(e,r,i="default"){return new Promise((n,o)=>{!r||r.length===0?o(new Error("Path cannot be empty")):(Array.isArray(r)||(r=[r]),y(this.client,k.RequestTypes.RemoveField,{type:e,db:i,path:r},n,o))})}updateSchema(e){return new Promise((r,i)=>{y(this.client,k.RequestTypes.Configuration,e,r,i)})}getToken(){return this.client.token}auth(e,r){return new Promise(i=>{if(this.client.auth.push(i),e&&e!==this.client.token||e===!1&&this.client.token){if(typeof e=="string"){let n=r||{},{renewOptions:o,refreshToken:c}=n,a=qe(n,["renewOptions","refreshToken"]);o&&(this.client.renewOptions=o),c&&(this.client.renewOptions=J(G({},this.client.renewOptions),{refreshToken:c})),E(this.client,e,a)}else E(this.client);this.emit("auth",e)}})}async login(e){return e.localStorage===!1?this.client.tokenToLocalStorage=!1:this.client.tokenToLocalStorage=!0,_e(this.client,e)}async register(e){return e.localStorage===!1?this.client.tokenToLocalStorage=!1:this.client.tokenToLocalStorage=!0,ze(this.client,e)}logout(){return We(this.client)}observeAuth(e){return new Promise(r=>{this.client.user&&this.client.token?e({id:this.client.user,token:this.client.token}):e(!1);let i=n=>{n&&this.client.user&&this.client.token?e({id:this.client.user,token:this.client.token}):e(!1)};this.on("auth",i),r(()=>{this.removeListener("auth",i)})})}},Tt=(t,s)=>{if(s){let e;t+=/\?/.test(t)?"&":"?";for(let r in s){let i=s[r];t+=e?`&${r}=${i}`:`${r}=${i}`,e=!0}}return t},Ot=(t,s=ne)=>{let{env:e,project:r,org:i,url:n,key:o,name:c="@based/hub",cluster:a,params:u}=t;if(n||(a=t.cluster=(0,oe.getClusterUrl)(a),n=async()=>{let{url:l}=await(0,oe.default)({env:e,project:r,org:i,key:o,name:c},0,a);return Tt(l,u)}),n){let l=new s;return l.opts=t,l.client.initUserState(),l.connect(n),l}},wt=Ot;0&&(module.exports={Based,BasedClient,BasedGraphQL,Observable,addGetSubscriber,addRequest,addSubscriber,createGraphqlOperations,generateSubscriptionId,generateTrackingKey,handleGraphqlVariables,parseGraphql,removeSubscriber}); |
{ | ||
"name": "@based/client", | ||
"version": "2.10.1", | ||
"version": "3.0.0", | ||
"license": "MIT", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
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
286949
2748