@based/client 2.7.5 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Client.d.ts CHANGED
@@ -5,6 +5,9 @@ export * from '@based/types';
5
5
  export declare class BasedClient {
6
6
  based: Based;
7
7
  constructor(based: Based);
8
+ debugInternal?: (message: any, type: 'incoming' | 'outgoing') => void;
9
+ get debug(): true | ((message: any, type: 'incoming' | 'outgoing') => void);
10
+ set debug(v: true | ((message: any, type: 'incoming' | 'outgoing') => void));
8
11
  token: string;
9
12
  renewOptions: {
10
13
  refreshToken?: string;
package/dist/Client.js CHANGED
@@ -24,6 +24,7 @@ const queue_1 = require("./queue");
24
24
  const request_1 = require("./request");
25
25
  const token_1 = __importDefault(require("./token"));
26
26
  const auth_1 = require("./auth");
27
+ const debug_1 = __importDefault(require("./debug"));
27
28
  __exportStar(require("@based/types"), exports);
28
29
  class BasedClient {
29
30
  constructor(based) {
@@ -39,6 +40,17 @@ class BasedClient {
39
40
  this.drainInProgress = false;
40
41
  this.based = based;
41
42
  }
43
+ get debug() {
44
+ return this.debugInternal;
45
+ }
46
+ set debug(v) {
47
+ if (v === true) {
48
+ this.debugInternal = debug_1.default;
49
+ }
50
+ else {
51
+ this.debugInternal = v;
52
+ }
53
+ }
42
54
  onClose() {
43
55
  this.connected = false;
44
56
  (0, queue_1.stopDrainQueue)(this);
@@ -73,6 +85,9 @@ class BasedClient {
73
85
  onData(d) {
74
86
  try {
75
87
  const data = JSON.parse(d.data);
88
+ if (this.debugInternal) {
89
+ this.debugInternal(data, 'incoming');
90
+ }
76
91
  const [type, reqId, payload, err, subscriptionErr] = data;
77
92
  if (type === types_1.RequestTypes.Token) {
78
93
  this.retryingRenewToken = false;
@@ -141,7 +156,7 @@ class BasedClient {
141
156
  }
142
157
  }
143
158
  catch (err) {
144
- console.error('Received incorrect data ', d);
159
+ console.error('Received incorrect data ', d.data);
145
160
  }
146
161
  }
147
162
  }
@@ -1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,CAAC,CAAA;oBAC3C,CAAC,CAAC,CAAA;iBACL;qBAAM;oBACL,IACE,IAAI,KAAK,oBAAY,CAAC,GAAG;wBACzB,IAAI,KAAK,oBAAY,CAAC,GAAG;wBACzB,IAAI,KAAK,oBAAY,CAAC,aAAa;wBACnC,IAAI,KAAK,oBAAY,CAAC,gBAAgB;wBACtC,IAAI,KAAK,oBAAY,CAAC,IAAI;wBAC1B,IAAI,KAAK,oBAAY,CAAC,MAAM;wBAC5B,IAAI,KAAK,oBAAY,CAAC,IAAI;wBAC1B,IAAI,KAAK,oBAAY,CAAC,MAAM;wBAC5B,IAAI,KAAK,oBAAY,CAAC,UAAU;wBAChC,IAAI,KAAK,oBAAY,CAAC,WAAW,EACjC;wBACA,IAAA,yBAAe,EAAC,IAAI,EAAE,IAAI,CAAC,CAAA;qBAC5B;yBAAM,IAAI,IAAI,KAAK,oBAAY,CAAC,YAAY,EAAE;wBAC7C,IAAA,oCAAoB,EAAC,IAAI,EAAE,IAAI,CAAC,CAAA;qBACjC;yBAAM,IAAI,IAAI,KAAK,oBAAY,CAAC,gBAAgB,EAAE;wBACjD,IAAA,wCAAwB,EAAC,IAAI,EAAE,IAAI,CAAC,CAAA;qBACrC;iBACF;aACF;SACF;QAAC,OAAO,GAAG,EAAE;YACZ,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,CAAC,CAAC,IAAI,CAAC,CAAA;SAClD;IACH,CAAC;CACF;AA7OD,kCA6OC"}
@@ -0,0 +1,2 @@
1
+ declare const _default: (msg: any, type: 'incoming' | 'outgoing') => void;
2
+ export default _default;
package/dist/debug.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = (msg, type) => {
4
+ const t = new Date();
5
+ const now = t.getHours() +
6
+ ':' +
7
+ t.getMinutes() +
8
+ ':' +
9
+ t.getSeconds() +
10
+ ':' +
11
+ t.getMilliseconds();
12
+ if (type === 'incoming') {
13
+ const str = `▼ ${now} -- `;
14
+ console.info(str, msg);
15
+ }
16
+ else {
17
+ const str = `▲ ${now} -- `;
18
+ console.info(str, msg);
19
+ }
20
+ };
21
+ //# sourceMappingURL=debug.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"debug.js","sourceRoot":"","sources":["../src/debug.ts"],"names":[],"mappings":";;AAAA,kBAAe,CAAC,GAAQ,EAAE,IAA6B,EAAE,EAAE;IACzD,MAAM,CAAC,GAAG,IAAI,IAAI,EAAE,CAAA;IACpB,MAAM,GAAG,GACP,CAAC,CAAC,QAAQ,EAAE;QACZ,GAAG;QACH,CAAC,CAAC,UAAU,EAAE;QACd,GAAG;QACH,CAAC,CAAC,UAAU,EAAE;QACd,GAAG;QACH,CAAC,CAAC,eAAe,EAAE,CAAA;IAErB,IAAI,IAAI,KAAK,UAAU,EAAE;QACvB,MAAM,GAAG,GAAG,OAAO,GAAG,QAAQ,CAAA;QAC9B,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;KACvB;SAAM;QACL,MAAM,GAAG,GAAG,OAAO,GAAG,QAAQ,CAAA;QAC9B,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;KACvB;AACH,CAAC,CAAA"}
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
- var st=Object.create;var U=Object.defineProperty,rt=Object.defineProperties,it=Object.getOwnPropertyDescriptor,nt=Object.getOwnPropertyDescriptors,ot=Object.getOwnPropertyNames,H=Object.getOwnPropertySymbols,at=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty,Ce=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))Ce.call(s,t)&&Oe(e,t,s[t]);return e},we=(e,s)=>rt(e,nt(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&&Ce.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 i of ot(s))!ne.call(e,i)&&i!==t&&U(e,i,{get:()=>s[i],enumerable:!(n=it(s,i))||n.enumerable});return e},d=(e,s,t)=>(_(e,s,"default"),t&&_(t,s,"default")),z=(e,s,t)=>(t=e!=null?st(at(e)):{},_(s||!e||!e.__esModule?U(t,"default",{value:e,enumerable:!0}):t,e)),ct=e=>_(U({},"__esModule",{value:!0}),e);var m={};qe(m,{Based:()=>re,BasedClient:()=>D,BasedGraphQL:()=>S.BasedGraphQL,Observable:()=>P,addGetSubscriber:()=>K,addRequest:()=>k,addSubscriber:()=>E,createGraphqlOperations:()=>S.createOperations,default:()=>St,generateSubscriptionId:()=>q,generateTrackingKey:()=>he,handleGraphqlVariables:()=>S.handleGraphqlVariables,parseGraphql:()=>S.parseGraphql,removeSubscriber:()=>y});module.exports=ct(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 i=0,r=n.length;i<r;i++)if(n[i]===t){n.splice(i,1);break}}}},Be=ae;var Re=(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,i=!1)=>(Re(s,r=>{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(r);c.onerror=()=>{},c.onmessage=a=>e.onData(a),c.onopen=()=>{if(o){if(t.disconnected)return;n=100,i&&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 v=require("@based/types");var Q=require("@based/types");var j=require("@based/types");var ut=e=>{clearTimeout(e.idlePing),e.idlePing=setTimeout(()=>{e.connection&&e.connected&&!e.connection.disconnected&&e.connection.ws.send("1")},6e4)},J=ut;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.connection.ws.send(JSON.stringify(s)),J(e)}},0))},Qe=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,i)=>{n||(n=q(s,i));let r=e.subscriptions[n],o=e.cache[n];if(r)if(r.authError)if(!e.beingAuth)t(r.authError.error,n,0);else{let c=++r.cnt;r.subscribers[c]={onInitial:t}}else if(o)t(null,n,0,o.value);else{let c=++r.cnt;r.subscribers[c]={onInitial:t}}else{r=e.subscriptions[n]={query:s,cnt:1,name:i,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===n?(e.subscriptionQueue.splice(a,1),a--):(u===Q.RequestTypes.Subscription||u===Q.RequestTypes.GetSubscription)&&l===n&&(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,n,s];o&&a.push(o.checksum),i&&(o||a.push(0),a.push(i)),f(e,a)}}};var B=require("@based/types");var E=(e,s,t,n,i,r,o)=>{r||(r=q(s,o));let c=e.subscriptions[r],a=e.cache[r],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:i,onData:t,onInitial:n},l){for(let b=0;b<e.subscriptionQueue.length;b++){let[h,T]=e.subscriptionQueue[b];h===B.RequestTypes.GetSubscription&&T===r&&(e.subscriptionQueue.splice(b,1),b--)}let p=[B.RequestTypes.Subscription,r,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[r]={query:s,cnt:1,name:o,subscribers:{1:{onError:i,onData:t,onInitial:n}}};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===r?(T===B.RequestTypes.GetSubscription&&(p=!0),b&&(b[4]=2),e.subscriptionQueue.splice(h,1),h--):T===B.RequestTypes.Subscription&&R===r&&(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,r,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,r,u),delete c.subscribers[u].onInitial),t&&t(a.value,a.checksum)),[r,u]};var $=require("@based/types");var y=(e,s,t)=>{let n=e.subscriptions[s];if(n){let i=!1;if(t?n.subscribers[t]&&(delete n.subscribers[t],n.cnt--,n.cnt===0&&(i=!0)):i=!0,i){delete e.subscriptions[s];let r=!1;for(let o=0;o<e.subscriptionQueue.length;o++){let[c,a]=e.subscriptionQueue[o];c===$.RequestTypes.Unsubscribe&&a===s?r=!0:(c===$.RequestTypes.Subscription||c===$.RequestTypes.SendSubscriptionData)&&a===s&&(e.subscriptionQueue.splice(o,1),o--)}r||f(e,[$.RequestTypes.Unsubscribe,s])}}};var xe=require("@based/types"),Ae=e=>{for(let s=0;s<e.subscriptionQueue.length;s++)e.subscriptionQueue[s][0]===xe.RequestTypes.Unsubscribe&&(e.subscriptionQueue.splice(s,1),s--)};var De=require("@based/types"),Ie=e=>{for(let s=0;s<e.subscriptionQueue.length;s++)e.subscriptionQueue[s][0]===De.RequestTypes.SendSubscriptionData&&(e.subscriptionQueue.splice(s,1),s--)};var x=require("@based/types");var M=(e,s=!1)=>{for(let t in e.subscriptions){let n=Number(t),i=e.subscriptions[t];if(s&&!i.authError)continue;let r,o,c;for(let l=0;l<e.subscriptionQueue.length;l++){let[p,b]=e.subscriptionQueue[l];b===n&&(p===x.RequestTypes.GetSubscription?(c=l,r=e.subscriptionQueue[l]):p===x.RequestTypes.Subscription&&(o=e.subscriptionQueue[l]))}r&&o&&console.error("GET IN Q AND SUB IN Q SHOULD BE IMPOSSIBLE");let a=e.cache[n],u=!1;if(r){let l=!0;for(let p in i.subscribers)if(i.subscribers[p].onData){l=!1;break}l?u=!0:(console.info("not only gets remove get"),e.subscriptionQueue.splice(c,1)),a&&r[3]!==a.checksum&&(r[3]=a.checksum)}if(!u)if(o)a&&o[3]!==a.checksum&&(o[3]=a.checksum,r&&(o[4]=2));else{let{name:l,query:p}=e.subscriptions[n];l?a?f(e,[x.RequestTypes.Subscription,n,p,a.checksum,r?2:0,l]):f(e,[x.RequestTypes.Subscription,n,p,0,r?2:0,l]):a?f(e,[x.RequestTypes.Subscription,n,p,a.checksum,r?2:0]):f(e,[x.RequestTypes.Subscription,n,p,0,r?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="",i=!1)=>{let r="";for(let a=0;a<s;a++)r+=" ";let o=t?[]:n?[r+`${W(n,i?"brightRed":"white")} {`]:[r+"{"],c=!1;t||(r+=" ",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(`${r} ${l}: [`);for(let p=0;p<u.length;p++){let b=u[p];o.push(...b&&typeof b=="object"?de(b,s+4):[`${r} ${b}`]),p!==u.length-1&&(o[o.length-1]+=",")}o.push(`${r} ]`)}else u&&typeof u=="object"?(o.push(`${r} ${l}: {`),o.push(...de(u,s+2,!0)),o.push(`${r} }`)):o.push(`${r} ${l}: ${u}`);c=!0}return t||o.push(r.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(`
2
- `),n=0;t[0]===""&&t.shift();let i=t[0];for(let r=0;r<i.length;r++)if(i[r]!==" "){n=r-2;break}n>0?t=t.map(r=>r.slice(n)):t=t.map(r=>" "+r),e.code&&(s.code=e.code),s.message=`
1
+ var rt=Object.create;var U=Object.defineProperty,it=Object.defineProperties,nt=Object.getOwnPropertyDescriptor,ot=Object.getOwnPropertyDescriptors,at=Object.getOwnPropertyNames,H=Object.getOwnPropertySymbols,ct=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)=>it(e,ot(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 at(s))!ne.call(e,r)&&r!==t&&U(e,r,{get:()=>s[r],enumerable:!(n=nt(s,r))||n.enumerable});return e},d=(e,s,t)=>(_(e,s,"default"),t&&_(t,s,"default")),z=(e,s,t)=>(t=e!=null?rt(ct(e)):{},_(s||!e||!e.__esModule?U(t,"default",{value:e,enumerable:!0}):t,e)),ut=e=>_(U({},"__esModule",{value:!0}),e);var m={};qe(m,{Based:()=>re,BasedClient:()=>D,BasedGraphQL:()=>S.BasedGraphQL,Observable:()=>P,addGetSubscriber:()=>K,addRequest:()=>k,addSubscriber:()=>E,createGraphqlOperations:()=>S.createOperations,default:()=>Tt,generateSubscriptionId:()=>q,generateTrackingKey:()=>he,handleGraphqlVariables:()=>S.handleGraphqlVariables,parseGraphql:()=>S.parseGraphql,removeSubscriber:()=>y});module.exports=ut(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}}}},Be=ae;var Re=(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)=>(Re(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 v=require("@based/types");var I=require("@based/types");var j=require("@based/types");var lt=e=>{clearTimeout(e.idlePing),e.idlePing=setTimeout(()=>{e.connection&&e.connected&&!e.connection.disconnected&&e.connection.ws.send("1")},6e4)},J=lt;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 B=require("@based/types");var E=(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===B.RequestTypes.GetSubscription&&T===i&&(e.subscriptionQueue.splice(b,1),b--)}let p=[B.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,R,,x]=e.subscriptionQueue[h];(T===B.RequestTypes.Unsubscribe||T===B.RequestTypes.SendSubscriptionData||T===B.RequestTypes.GetSubscription)&&R===i?(T===B.RequestTypes.GetSubscription&&(p=!0),b&&(b[4]=2),e.subscriptionQueue.splice(h,1),h--):T===B.RequestTypes.Subscription&&R===i&&(l=!0,b=e.subscriptionQueue[h],x!==a.checksum&&(b[3]=a.checksum),!b[4]&&p&&(b[4]=2))}if(!l){let h=[B.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 y=(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 w=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(`
2
+ `),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=`
3
3
 
4
- `+(e.payload&&typeof e.payload!="object"?` ${W("Payload","brightRed")} ${e.payload}`:V(e.payload||e.query,0,!1,e.payload?"Payload":"Query",!0).map(r=>" "+r).join(`
4
+ `+(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(`
5
5
  `))+`
6
6
 
7
7
  `+t.join(`
8
8
  `)+`
9
9
 
10
- `}return s};var Ge=(e,s)=>{let[,t,n,i,r]=s,o=e.subscriptions[t];if(o){let c=e.cache[t]&&e.cache[t].checksum;if(r){let a=C(r);r.auth&&(o.authError={token:e.token,error:a});for(let u in o.subscribers){let l=o.subscribers[u];l.onInitial?r.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===i){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:n,checksum:i};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||y(e,t,Number(a))),u.onData&&u.onData(n,i)}}}};var je=require("@saulx/diff"),X=require("@based/types");var $e=(e,s)=>{let[,t,n,[i,r]]=s,o=e.subscriptions[t];if(o){let c=e.cache[t];if(!c||c.checksum!==i)if(c)if(c.checksum===r)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,[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(`
10
+ `}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=w(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,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: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||y(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||y(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(`
11
11
  Found corrupt data while applying diff to subscription need to re-fetch
12
12
  `),console.warn(V(o.query,2,!1,"Query").join(`
13
13
  `)+`
14
14
 
15
- `),delete e.cache[t],f(e,[X.RequestTypes.SendSubscriptionData,t]);else{c.checksum=r;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 Me=(e,s)=>{for(let t of s[1]){delete e.cache[t];let n=e.subscriptions[t];if(n){let i={type:"AuthorizationError",name:n.name?`observe "${n.name}"`:"observe",message:"Unauthorized request",payload:n.query,auth:!0},r=C(i);n.authError={token:e.token,error:r};for(let o in n.subscribers){let c=n.subscribers[o];c.onError&&c.onError(r)}}}};var Ne=require("@based/types");var lt=0,k=(e,s,t,n,i,r,o)=>{let c=++lt;e.requestCallbacks[c]={resolve:n,reject:i,type:s,payload:t,name:r,isRetry:o},s===Ne.RequestTypes.Call?f(e,[s,r,c,t]):f(e,[s,c,t])};var Le=(e,s)=>{let[,t,n,i]=s,r=e.requestCallbacks[t];r&&(delete e.requestCallbacks[t],i?r.reject(C(i)):r.resolve(n))};var O={};qe(O,{BasedClient:()=>D});var g=require("@based/types");var be=require("@based/types");var pt=e=>typeof e!="undefined"&&e!==null,dt=(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(pt):[be.RequestTypes.Token];e.connection.ws.send(JSON.stringify(n)),J(e),M(e,!0)}},w=dt;var F=require("@based/types");var fe=0,He=(e,s)=>{let t=++fe;return f(e,[F.RequestTypes.Auth,F.AuthRequestTypes.Login,t,s]),new Promise((n,i)=>{e.authCallbacks[t]={resolve:r=>{w(e,r.token,{refreshToken:r.refreshToken}),n(r)},reject:i}})},_e=(e,s)=>{let t=++fe;return f(e,[F.RequestTypes.Auth,F.AuthRequestTypes.RenewToken,t,s]),new Promise((n,i)=>{e.authCallbacks[t]={resolve:r=>{w(e,r.token),n(r)},reject:i}})},ze=(e,s)=>{let[,t,n,i]=s,r=e.authCallbacks[t];r&&(delete e.authCallbacks[t],i?r.reject(C(i)):r.resolve(n))},Je=e=>{let s=++fe;return f(e,[F.RequestTypes.Auth,F.AuthRequestTypes.Logout,s]),new Promise((t,n)=>{e.authCallbacks[s]={resolve:i=>{w(e),t(i)},reject:n}})};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,Qe(this),Ae(this),Ie(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 i=JSON.parse(s.data),[r,o,c,a,u]=i;if(r===g.RequestTypes.Token){this.retryingRenewToken=!1,o.length&&Me(this,i);for(let l of this.auth)l(!c);this.beingAuth=!1,this.auth=[]}else r===g.RequestTypes.Auth?ze(this,i):(((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,_e(this,this.renewOptions).then(l=>{w(this,l.token,this.sendTokenOptions),r===g.RequestTypes.Subscription||r===g.RequestTypes.SubscriptionDiff?M(this):k(this,r,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)})):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?Le(this,i):r===g.RequestTypes.Subscription?Ge(this,i):r===g.RequestTypes.SubscriptionDiff&&$e(this,i)}catch(i){console.error("Received incorrect data ",s)}}};var me=(e,s)=>{let t;if(e.configuration&&e.configuration.schema)for(let n in e.configuration.schema){let i=e.configuration.schema[n];if(i.prefixToTypeMapping){for(let r in i.prefixToTypeMapping)if(i.prefixToTypeMapping[r]===s){t=r;break}}}return t};var ke=require("@saulx/hash");var We=require("@based/types"),Ve=require("@saulx/hash"),Ke=new Set,bt=e=>{if(typeof window!="undefined"){if(Ke.has(e))return!1;Ke.add(e);try{let s="_ba:"+(0,Ve.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 i of n)t+="_"+i+"_"+s[i];return t}else return e},N=(e,s,t,n,i,r,o)=>{let c=he(s,t),a={t:c};o&&(a.r=1),i&&(a.e=1,r&&(a.o=r)),n?(a.s=1,e.tracking.delete(c)):o||(i||(e.tracking||(e.tracking=new Set),e.tracking.add(c)),bt(c)&&(a.u=1)),f(e,[We.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,y(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 i={data:{}},r=[];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)},t);r.push(a)}return new ye(this.client,r)}},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[,i]=E(this.client,this.payload,s,r=>{r&&(console.error(r),t&&t(r))},t,this.subId,this.name);return new ge(this.client,i,this.subId)}};var ve={},L={},ft=(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 i of t){let{raw:r,name:o,id:c,file:a,functionName:u}=i,l=`${u||""}|${r?1:0}|${c}|${a.size}${o?`|${o}`:""}`;n.append(l,a)}try{let i=new global.XMLHttpRequest;i.upload.onprogress=r=>{let o=100*(r.loaded||r.position)/(r.totalSize||r.total);console.info(o,"upload...")},i.onerror=r=>{console.error("error!",r,"flap",i.responseText)},i.timeout=1e3*60*60*24,i.onabort=r=>{console.error("abort",r)},i.ontimeout=r=>{console.error("on timeout",r)},i.onload=()=>{let r={};try{r=JSON.parse(i.response),console.info("SUCCESS",r)}catch(o){console.error("something wrong with file upload",o)}},i.open("POST",e+"/file"),i.setRequestHeader("Content-Type","multipart/form-data"),i.setRequestHeader("Authorization",s),i.send(n)}catch(i){console.error("Something wrong with xhr upload",i)}},500))},Xe=async(e,s,t,n,i,r,o)=>{L[t]||(L[t]=[]),L[t].push({file:s,id:n,url:t,raw:i,name:r,functionName:o}),ft(t,e.getToken())};var Ye=z(require("@based/get-service")),Z={},ee={},mt=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:i}=e.opts,r=t+"/"+n+"/"+i+"/"+e.opts.cluster;if(Z[r])return Z[r];if(ee[r])return(await ee[r]).url;let o=await(ee[r]=(0,Ye.default)({env:t,project:n,org:i,name:"@based/hub",key:"file-upload",optionalKey:!0},0,e.opts.cluster));return delete ee[r],setTimeout(()=>{delete Z[r]},2e3),Z[r]=o.url},Ze=mt;var et=z(require("cross-fetch")),te=(e,s,t)=>((0,et.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 I=require("./file/stream"),se=typeof window!="undefined",ht=e=>"src"in e&&typeof e.src=="string",gt=e=>"path"in e&&typeof e.path=="string",yt=e=>"contents"in e&&(0,I.isStream)(e.contents),tt=async(e,s)=>{if(ht(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 e.set(i)):void 0}let t=s.id;if(!t){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),t=(await e.set(i)).id}s.id=t;let n=(await Ze(e,s)).replace(/^ws/,"http");if(gt(s))return(0,I.uploadFilePath)(e,n,s),{id:t};if(yt(s))return(0,I.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 Xe(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 Be{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,i){return new Promise((r,o)=>{let c,a=!1;this.observe(t,(u,l)=>{i&&i(u,l),n(u,l)&&(a=!0,c&&c(),r(u))}).then(u=>{a?c():c=u}).catch(u=>{o(u)})})}gql(t,...n){typeof t=="string"&&(t=[t]);let i=t[0];return n.forEach((r,o)=>{r&&r.kind==="Document"?i+=r.loc.source.body:i+=r,i+=t[o+1]}),(0,S.createOperations)({schemas:this.client.configuration.schema},(0,S.parseGraphql)(i))}gqlDb(t="default"){return(n,...i)=>{typeof n=="string"&&(n=[n]);let r=n[0];return i.forEach((o,c)=>{o&&o.kind==="Document"?r+=o.loc.source.body:r+=o,r+=n[c+1]}),(0,S.createOperations)({schemas:this.client.configuration.schema,db:t},(0,S.parseGraphql)(r))}}observe(t,n,i,r){return typeof t=="string"?new Promise((o,c)=>{let a=typeof n=="function",u=a?n:i,l=a?i:r;E(this.client,a?void 0:n,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,n,(a,u,l,p,b)=>{a&&!b?c(a):o(()=>{y(this.client,u,l)})},i)})}createObservable(t,n){return typeof t=="string"?new P(this.client,t,n):new P(this.client,t)}observeSchema(t,n,i){return new Promise((r,o)=>{let c=typeof t=="string"?t:"default",a=typeof t=="string"?n:t,u=typeof t=="string"?i:n;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):r(()=>{y(this.client,p,b)})},u)})}get(t,n){return typeof t=="string"?new Promise((i,r)=>{K(this.client,n,(o,c,a,u)=>{o?r(o):i(u)},0,t)}):new Promise((i,r)=>{k(this.client,v.RequestTypes.Get,t,i,r)})}file(t){return global.File&&t instanceof File&&(t={contents:t}),tt(this,t)}call(t,n){return new Promise((i,r)=>{k(this.client,v.RequestTypes.Call,n,i,r,t)})}async id(t,n){let i=me(this.client,t);if(i||(await this.schema(),i=me(this.client,t)),!i)throw C({message:`Type does not exist ${t}`,type:"Invalid type",payload:n?{type:t,opts:n}:{type:t}});if(n){let r=(0,ke.hashCompact)(n,8,!0);return i+r}else return i+(0,ke.hashCompact)(Math.floor(Math.random()*99999999999)+""+Date.now())}digest(t){return new Promise((n,i)=>{k(this.client,v.RequestTypes.Digest,t,n,i)})}set(t){return new Promise((n,i)=>{k(this.client,v.RequestTypes.Set,t,n,i)})}copy(t){return new Promise((n,i)=>{k(this.client,v.RequestTypes.Copy,t,n,i)})}async gqlQuery(t,n={}){let i;typeof t=="string"?i=this.gql(t):i=t;try{if(i=(0,S.handleGraphqlVariables)(i,i,n),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 r={};return await Promise.all(Object.entries(i.ops).map(async([o,c])=>{var p,b,h,T,R;if(c.delete){r[o]=await this.delete(c.delete);return}else if(c.fnCall){r[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 Te=(R=(T=(h=(b=(p=this.client)==null?void 0:p.configuration)==null?void 0:b.schema)==null?void 0:h[i.db])==null?void 0:T.prefixToTypeMapping)==null?void 0:R[a.slice(0,2)];Te&&(A.type=Te),r[o]=A;return}let u=(0,Se.deepCopy)(c.get);u.$id=a;let l=await this.get(u);r[o]=l})),{data:r}}catch(r){return{errors:[{message:r.message,locations:r.locations}]}}}async gqlLive(t,n={}){let i;if(typeof t=="string"?i=this.gql(t):i=t,i=(0,S.handleGraphqlVariables)(i,i,n),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 P(this.client,l.fn.name,l.fn.payload),key:l.key})),u=new P(this.client,oe({$db:i.db},c));return a.push({key:"",obs:u}),new Y(this.client,a)}return new P(this.client,{$db:i.db,data:c})}let r={};return await Promise.all(Object.entries(i.ops).map(async([o,c])=>{if(c.delete){r[o]=await this.delete(c.delete);return}else if(c.fnCall){r[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,r[o]=u})),new P(this.client,{$db:i.db,data:r})}analytics(t,n){return new Promise((i,r)=>{n?E(this.client,t,n,(o,c,a,u,l)=>{o&&!l?r(o):i(()=>{y(this.client,c,a)})},o=>console.error(o),void 0,"analytics"):K(this.client,t,(o,c,a,u)=>{o?r(o):((0,v.isAnalyticsHistoryOpts)(t)||(0,v.isAnalyticsTypesOpts)(t),i(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,i){N(this.client,t,n,!1,!0,i)}delete(t){return new Promise((n,i)=>{k(this.client,v.RequestTypes.Delete,t,n,i)})}schema(){return new Promise((t,n)=>{let i=r=>{this.client.configuration=r,t(r)};k(this.client,v.RequestTypes.GetConfiguration,0,i,n)})}removeType(t,n="default"){return new Promise((i,r)=>{k(this.client,v.RequestTypes.RemoveType,{type:t,db:n},i,r)})}removeField(t,n,i="default"){return new Promise((r,o)=>{!n||n.length===0?o(new Error("Path cannot be empty")):(Array.isArray(n)||(n=[n]),k(this.client,v.RequestTypes.RemoveField,{type:t,db:i,path:n},r,o))})}updateSchema(t){return new Promise((n,i)=>{k(this.client,v.RequestTypes.Configuration,t,n,i)})}getToken(){return this.client.token}auth(t,n){return new Promise(i=>{if(this.client.auth.push(i),t&&t!==this.client.token||t===!1&&this.client.token){if(typeof t=="string"){let r=n||{},{renewOptions:o,refreshToken:c}=r,a=Pe(r,["renewOptions","refreshToken"]);o&&(this.client.renewOptions=o),c&&(this.client.renewOptions=we(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)}logout(){return Je(this.client)}},vt=(e,s)=>{if(s){let t;e+=/\?/.test(e)?"&":"?";for(let n in s){let i=s[n];e+=t?`&${n}=${i}`:`${n}=${i}`,t=!0}}return e},kt=(e,s=re)=>{let{env:t,project:n,org:i,url:r,key:o,name:c="@based/hub",cluster:a,params:u}=e;if(r||(a=e.cluster=(0,ie.getClusterUrl)(a),r=async()=>{let{url:l}=await(0,ie.default)({env:t,project:n,org:i,key:o,name:c},0,a);return vt(l,u)}),r){let l=new s;return l.opts=e,l.connect(r),l}},St=kt;0&&(module.exports={Based,BasedClient,BasedGraphQL,Observable,addGetSubscriber,addRequest,addSubscriber,createGraphqlOperations,generateSubscriptionId,generateTrackingKey,handleGraphqlVariables,parseGraphql,removeSubscriber});
15
+ `),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||y(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=w(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 pt=0,k=(e,s,t,n,r,i,o)=>{let c=++pt;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(w(r)):i.resolve(n))};var O={};qe(O,{BasedClient:()=>D});var g=require("@based/types");var be=require("@based/types");var dt=e=>typeof e!="undefined"&&e!==null,bt=(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(dt):[be.RequestTypes.Token];e.connection.ws.send(JSON.stringify(n)),J(e),M(e,!0)}},C=bt;var F=require("@based/types");var fe=0,He=(e,s)=>{let t=++fe;return f(e,[F.RequestTypes.Auth,F.AuthRequestTypes.Login,t,s]),new Promise((n,r)=>{e.authCallbacks[t]={resolve:i=>{C(e,i.token,{refreshToken:i.refreshToken}),n(i)},reject:r}})},_e=(e,s)=>{let t=++fe;return f(e,[F.RequestTypes.Auth,F.AuthRequestTypes.RenewToken,t,s]),new Promise((n,r)=>{e.authCallbacks[t]={resolve:i=>{C(e,i.token),n(i)},reject:r}})},ze=(e,s)=>{let[,t,n,r]=s,i=e.authCallbacks[t];i&&(delete e.authCallbacks[t],r?i.reject(w(r)):i.resolve(n))},Je=e=>{let s=++fe;return f(e,[F.RequestTypes.Auth,F.AuthRequestTypes.Logout,s]),new Promise((t,n)=>{e.authCallbacks[s]={resolve:r=>{C(e),t(r)},reject:n}})};var Ke=(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=Ke: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&&C(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?ze(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,_e(this,this.renewOptions).then(l=>{C(this,l.token,this.sendTokenOptions),i===g.RequestTypes.Subscription||i===g.RequestTypes.SubscriptionDiff?M(this):k(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 Ve=require("@based/types"),Xe=require("@saulx/hash"),We=new Set,ft=e=>{if(typeof window!="undefined"){if(We.has(e))return!1;We.add(e);try{let s="_ba:"+(0,Xe.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)),ft(c)&&(a.u=1)),f(e,[Ve.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,y(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]=E(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={},mt=(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))},Ye=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}),mt(t,e.getToken())};var Ze=z(require("@based/get-service")),Z={},ee={},ht=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,Ze.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},et=ht;var tt=z(require("cross-fetch")),te=(e,s,t)=>((0,tt.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",gt=e=>"src"in e&&typeof e.src=="string",yt=e=>"path"in e&&typeof e.path=="string",vt=e=>"contents"in e&&(0,A.isStream)(e.contents),st=async(e,s)=>{if(gt(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 et(e,s)).replace(/^ws/,"http");if(yt(s))return(0,A.uploadFilePath)(e,n,s),{id:t};if(vt(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 Ye(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 Be{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;E(this.client,a?void 0:n,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,n,(a,u,l,p,b)=>{a&&!b?c(a):o(()=>{y(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;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):i(()=>{y(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)=>{k(this.client,v.RequestTypes.Get,t,r,i)})}file(t){return global.File&&t instanceof File&&(t={contents:t}),st(this,t)}call(t,n){return new Promise((r,i)=>{k(this.client,v.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 w({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)=>{k(this.client,v.RequestTypes.Digest,t,n,r)})}set(t){return new Promise((n,r)=>{k(this.client,v.RequestTypes.Set,t,n,r)})}copy(t){return new Promise((n,r)=>{k(this.client,v.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,R;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=(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)];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?E(this.client,t,n,(o,c,a,u,l)=>{o&&!l?i(o):r(()=>{y(this.client,c,a)})},o=>console.error(o),void 0,"analytics"):K(this.client,t,(o,c,a,u)=>{o?i(o):((0,v.isAnalyticsHistoryOpts)(t)||(0,v.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)=>{k(this.client,v.RequestTypes.Delete,t,n,r)})}schema(){return new Promise((t,n)=>{let r=i=>{this.client.configuration=i,t(i)};k(this.client,v.RequestTypes.GetConfiguration,0,r,n)})}removeType(t,n="default"){return new Promise((r,i)=>{k(this.client,v.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]),k(this.client,v.RequestTypes.RemoveField,{type:t,db:r,path:n},i,o))})}updateSchema(t){return new Promise((n,r)=>{k(this.client,v.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})),C(this.client,t,a)}else C(this.client);this.emit("auth",t)}})}async login(t){return He(this.client,t)}logout(){return Je(this.client)}},kt=(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},St=(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 kt(l,u)}),i){let l=new s;return l.opts=e,l.connect(i),l}},Tt=St;0&&(module.exports={Based,BasedClient,BasedGraphQL,Observable,addGetSubscriber,addRequest,addSubscriber,createGraphqlOperations,generateSubscriptionId,generateTrackingKey,handleGraphqlVariables,parseGraphql,removeSubscriber});
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.color = void 0;
4
4
  const color = (str, color) => {
5
5
  if (typeof window !== 'undefined') {
6
+ // can also add colors / styling in console
6
7
  return str;
7
8
  }
8
9
  const colors = {
@@ -1 +1 @@
1
- {"version":3,"file":"printBasedObject.js","sourceRoot":"","sources":["../src/printBasedObject.ts"],"names":[],"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AK,QAAQ;oBAC5B,CAAC,CAAC,gBAAgB,CAAC,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC;oBACjC,CAAC,CAAC,CAAC,GAAG,MAAM,OAAO,CAAC,EAAE,CAAC,CAAC,CAC3B,CAAA;gBACD,IAAI,CAAC,KAAK,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;oBAC1B,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,GAAG,CAAA;iBAC/B;aACF;YACD,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,KAAK,CAAC,CAAA;SAC3B;aAAM,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7C,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,KAAK,KAAK,KAAK,CAAC,CAAA;YACpC,KAAK,CAAC,IAAI,CAAC,GAAG,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC,CAAA;YACxD,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,KAAK,CAAC,CAAA;SAC3B;aAAM;YACL,qCAAqC;YACrC,4CAA4C;YAC5C,oDAAoD;YACpD,4CAA4C;YAC5C,MAAM;YACN,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,KAAK,KAAK,KAAK,KAAK,EAAE,CAAC,CAAA;SAC5C;QACD,SAAS,GAAG,IAAI,CAAA;KACjB;IACD,IAAI,CAAC,UAAU,EAAE;QACf,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAA;KACtC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA;AAED,kBAAe,gBAAgB,CAAA"}
package/dist/queue.js CHANGED
@@ -33,6 +33,9 @@ const drainQueue = (client) => {
33
33
  const queue = [...client.queue, ...client.subscriptionQueue];
34
34
  client.queue = [];
35
35
  client.subscriptionQueue = [];
36
+ if (client.debugInternal) {
37
+ client.debugInternal(queue, 'outgoing');
38
+ }
36
39
  client.connection.ws.send(JSON.stringify(queue));
37
40
  (0, idleTimeout_1.default)(client);
38
41
  }
package/dist/queue.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"queue.js","sourceRoot":"","sources":["../src/queue.ts"],"names":[],"mappings":";;;;;;AACA,wCAAiE;AACjE,gEAAuC;AAEhC,MAAM,UAAU,GAAG,CACxB,MAAmB,EACnB,GAAyC,EACzC,EAAE;IACF,IACE,GAAG,CAAC,CAAC,CAAC,KAAK,oBAAY,CAAC,WAAW;QACnC,GAAG,CAAC,CAAC,CAAC,KAAK,oBAAY,CAAC,YAAY;QACpC,GAAG,CAAC,CAAC,CAAC,KAAK,oBAAY,CAAC,oBAAoB;QAC5C,GAAG,CAAC,CAAC,CAAC,KAAK,oBAAY,CAAC,eAAe,EACvC;QACA,MAAM,CAAC,iBAAiB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;KACnC;SAAM;QACL,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;KACvB;IACD,IAAI,MAAM,CAAC,SAAS,IAAI,CAAC,MAAM,CAAC,eAAe,EAAE;QAC/C,IAAA,kBAAU,EAAC,MAAM,CAAC,CAAA;KACnB;AACH,CAAC,CAAA;AAjBY,QAAA,UAAU,cAiBtB;AAEM,MAAM,UAAU,GAAG,CAAC,MAAmB,EAAE,EAAE;IAChD,IACE,MAAM,CAAC,SAAS;QAChB,CAAC,MAAM,CAAC,eAAe;QACvB,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,IAAI,MAAM,CAAC,iBAAiB,CAAC,MAAM,CAAC;QACxD,CAAC,MAAM,CAAC,UAAU,EAClB;QACA,MAAM,CAAC,eAAe,GAAG,IAAI,CAAA;QAC7B,MAAM,CAAC,YAAY,GAAG,UAAU,CAAC,GAAG,EAAE;YACpC,MAAM,CAAC,eAAe,GAAG,KAAK,CAAA;YAC9B,IAAI,MAAM,C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ACpD,IAAI,MAAM,CAAC,eAAe,EAAE;QAC1B,YAAY,CAAC,MAAM,CAAC,YAAY,CAAC,CAAA;QACjC,MAAM,CAAC,eAAe,GAAG,KAAK,CAAA;KAC/B;AACH,CAAC,CAAA;AALY,QAAA,cAAc,kBAK1B"}
@@ -0,0 +1,166 @@
1
+ ## JWT Auth Flow HowTo
2
+
3
+ A short guide to setting up the JWT authentication flow using based.
4
+ An example with the info on this guide can be foud [here](https://github.com/atelier-saulx/auth-demo)
5
+
6
+ If you created an environment using the based website, the JWT auth flow template is installed by default. This template includes the `user` type schema, the public and private keys, and the default `authorize`, `login`, `logout`, and `renewToken` data functions.
7
+
8
+ These default data functions can be customized to your needs. Add them to your project from [here](https://github.com/atelier-saulx/based/tree/main/packages/auth-templates/jwt) and deploy with the [based cli `deploy` command](https://github.com/atelier-saulx/based/tree/main/packages/cli#deploy).
9
+
10
+ ### Adding a user to the database
11
+
12
+ You now need to add a user to the database so that he can log in.
13
+ There are several ways to do this, including the data editor in the Based website admin area.
14
+ We'll add it through a script from the developer's computer environment as it also shows how you can add this functionality from your own apps.
15
+
16
+ The `user` type installed by default has the following schema:
17
+
18
+ ```
19
+ ...
20
+ types: {
21
+ user: {
22
+ prefix: 'us',
23
+ fields: {
24
+ name: { type: 'string' },
25
+ email: { type: 'email' },
26
+ password: { type: 'digest' },
27
+ },
28
+ },
29
+ },
30
+ ```
31
+
32
+ It is ready to accept users with an email, name string, and hashed password.
33
+ Let's create a user from a script.
34
+
35
+ #### Setting up an apiKey
36
+
37
+ If we try to add a user now from a script, we get into a chicken and the egg issue. We don't have an authenticated user to add the user itself. You can work around this while developing using the apiKey functionality.
38
+ This feature lets us create an apikey so we can use based in utility scripts and commands using the [based cli](https://github.com/atelier-saulx/based/tree/main/packages/cli).
39
+
40
+ ```bash
41
+ $ npx based apiKeys add --name auth-demo-api-key --file ./apiKey.key
42
+ ```
43
+
44
+ This command will create an apiKey called "auth-demo-api-key" and saves its value to a file we can load from the script or use as an argument in the [based cli](https://github.com/atelier-saulx/based/tree/main/packages/cli).
45
+
46
+ **Note:** You should never store apiKeys as plain text in repositories or use them to make based connections client side.
47
+
48
+ #### Setting a user with a script
49
+
50
+ With the apiKey, we can now run a simple script to add a new user:
51
+
52
+ ```javascript
53
+ // scripts/createUser.ts
54
+
55
+ import fs from 'fs'
56
+ import based from '@based/client'
57
+
58
+ // Loads the based config file that sets up your based connection
59
+ const basedConfig = JSON.parse(fs.readFileSync('../based.json', 'utf8'))
60
+
61
+ // Loads apiKey so we can have based access from a script
62
+ // Note: apiKeys should only be used for util scripts or server/server connections
63
+ const apiKey = fs.readFileSync('../apiKey.key', 'utf8')
64
+
65
+ ;(async () => {
66
+ // Create a based client
67
+ const client = based(basedConfig)
68
+
69
+ // Authenticate client with an apiKey
70
+ await client.auth(apiKey, { isApiKey: true })
71
+
72
+ // Add our user
73
+ const { id } = await client.set({
74
+ type: 'user',
75
+ name: 'Demo User',
76
+ email: 'demo@wawa.com',
77
+ password: 'superStrongPassword',
78
+ })
79
+ console.log('Added user ' + id)
80
+
81
+ process.exit()
82
+ })()
83
+ ```
84
+
85
+ And lets run it:
86
+ ```bash
87
+ $ cd scripts
88
+ $ npx ts-node scripts/createUser.ts
89
+ Added user us1b3d5a36
90
+ ```
91
+
92
+ ## Adding login functionality to your app.
93
+
94
+ To login a user from your app, you should create a login UI, and use the based client `.login()` method to validate your user and password.
95
+ Example:
96
+
97
+ ```javascript
98
+ import based from '@based/client'
99
+
100
+ // ...
101
+
102
+
103
+ <button
104
+ onClick={async () => {
105
+ const { token, refreshToken } = await client.login({
106
+ email,
107
+ password,
108
+ })
109
+ setToken(token)
110
+ setRefreshToken(refreshToken)
111
+ }}
112
+ >
113
+ Login
114
+ </button>
115
+ ```
116
+
117
+ The `.login()` method takes the email and password supplied by the user, passes it to the `login` data function, and returns the result. Usually, a token and refreshToken if it was successful.
118
+ You should also store your token and refreshToken if you want the session to persist.
119
+
120
+ ## Authenticating the user with a persisted token
121
+
122
+ If your user already logged in and you persisted the tokens, you can authenticate it with the still valid token instead of login in.
123
+ Example:
124
+ ```javascript
125
+ // ...
126
+ if (token) {
127
+ await client.auth(token, { refreshToken })
128
+ }
129
+ ```
130
+
131
+ The `refreshToken` is also stored by the based client so it can be requested by the based servers if the token is expired and it tries to renew the token automatically.
132
+
133
+ ## Login out user
134
+
135
+ You should run the based client `.logout()` method to explicitly log out a user. This method will clear the tokens on the based client and run the `logout` data function meant to perform clean-up actions like invalidating the current refreshToken.
136
+
137
+ Example:
138
+ ```javascript
139
+ // ...
140
+ <button
141
+ onClick={async () => {
142
+ await client.logout()
143
+ setToken(null)
144
+ setRefreshToken(null)
145
+ }}
146
+ >
147
+ Logout
148
+ </button>
149
+ ```
150
+
151
+ You should also clean the stored token and refreshToken from the browser.
152
+
153
+ ## Handling automatic token renewal
154
+
155
+ The default template already has in place JWT token renewal using a refreshToken. You should however store the new token locally when this happens.
156
+ For this we have the `renewToken` based client event that we can listen.
157
+ Example:
158
+
159
+ ```javascript
160
+ // ...
161
+ const renewHandler = ({ token: newToken }: { token: string }) => {
162
+ setToken(newToken)
163
+ }
164
+
165
+ client.on('renewToken', renewHandler)
166
+ ```
package/docs/auth.md ADDED
@@ -0,0 +1,91 @@
1
+ # The Auth System
2
+
3
+ The *Based Auth* system helps developers add a security layer to their data. It does not enforce any logic itself, instead relies on a set of user-configurable *data functions* that restrict data access and implement whatever security strategy the user needs. Be it a 3rd party implementation or its own.
4
+
5
+ The central concept is that all messages through based go through a [`authorize`](https://github.com/atelier-saulx/based/blob/main/packages/client/docs/authorize.md) function that implements the security logic and decides if each specific call to data should continue or be blocked.
6
+ Within the data request, a "token" is also sent. This token is passed along to the `authorize` function for context, and it is what identifies the user in most implementations.
7
+
8
+ There are no assumptions about the "token" format. It is up to the user to choose what implementation it wants or needs. However, we provide templates for JSON Web Tokens (JWT) authorization and will soon offer session-based authentication templates. These templates provide minimal authorization strategy implementation and are meant to be tweaked and updated by the user.
9
+ Along with the `authorize` function, these templates also implement more optional functions that make a login flow more straightforward and more semantic. `login`, `logout`, and `renewToken`.
10
+
11
+ The *Based* client also catches exceptions triggered by token expiration. When this happens, it tries to call a `renewToken` function sending it a renew payload that includes, for example, the "refreshToken" used for JWT authorization flow. If that's successful and it returns a new token, it will re-request the data with the new token for transparent renewal.
12
+
13
+ ## Auth data functions
14
+
15
+ ### `authorize`
16
+
17
+ This data function runs every time the based client tries to call, get, modify or observe data.
18
+ It approves or denies the request depending on its context. See [`authorize`](https://github.com/atelier-saulx/based/blob/main/packages/client/docs/authorize.md)
19
+ Returns boolean value allowing or disallowing the connection.
20
+
21
+ Example: see [here](https://github.com/atelier-saulx/based/blob/main/packages/auth-templates/jwt/authorize/authorize.ts)
22
+
23
+ ### `login`
24
+
25
+ Called then the client [login()]() method is called. It should authenticate the user and generate the tokens. Authentication flow is up to the user.
26
+ For example, in a JWT flow, this function will validate the user in the data, sign a token and refreshToken returning them to the client.
27
+
28
+ Example: see [here](https://github.com/atelier-saulx/based/blob/main/packages/auth-templates/jwt/login/login.ts)
29
+
30
+ ### `logout`
31
+
32
+ When your app logs out a user, it should call the `client.logout()` method. This method calls this data function if it exists. It is meant to have token invalidation and any cleanup that should happen when a user logs out.
33
+
34
+ Example: see [here](https://github.com/atelier-saulx/based/blob/main/packages/auth-templates/jwt/logout/logout.ts)
35
+
36
+ ### `renewToken`
37
+
38
+ For auth flows that rely on token renewal. This data function runs when a specific error is triggered in the `authorize` function.
39
+ The result is returned to the client using the `renewToken` client event.
40
+
41
+ Example: see [here](https://github.com/atelier-saulx/based/blob/main/packages/auth-templates/jwt/renewToken/renewToken.ts)
42
+
43
+ ## Based client methods
44
+
45
+ ### `client.auth()`
46
+
47
+ Sets the token to be sent during client/server messages. The token will be passed to the `authorize` function and can be decoded from it with `based.token()`.
48
+
49
+ #### Usage
50
+ ```javascript
51
+ // Setting token
52
+ await client.auth(token)
53
+
54
+ // Setting token and refreshToken for JWT flow
55
+ await client.auth(token, {
56
+ renewOptions: { refreshToken }
57
+ })
58
+ ```
59
+
60
+ ### `client.login()`
61
+
62
+ This data function sends the email and password to the `login` data function for authentication.
63
+ Returns tokens if successful. Also, it will automatically set the returned token on the current client connection.
64
+
65
+ #### Usage
66
+ ```javascript
67
+ const tokens = await client.login({email, password})
68
+ ```
69
+
70
+ ### `client.logout()`
71
+
72
+ Clears the tokens stored by the client and calls the `logout` data function if it exists.
73
+
74
+ #### Usage
75
+ ```javascript
76
+ await client.logout()
77
+ ```
78
+
79
+ ### `client.on('renewToken', fn)`
80
+
81
+ This event is called when the renewToken data function is run. It is used to handle and persist the newly generated tokens.
82
+
83
+ #### Usage
84
+ ```javascript
85
+ client.on('renewToken', (renewTokenResult) => {})
86
+ ```
87
+
88
+
89
+ ## How to use
90
+
91
+ Check [this guide](https://github.com/atelier-saulx/based/blob/main/packages/client/docs/auth-howto.md) for an example of how the use.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@based/client",
3
- "version": "2.7.5",
3
+ "version": "2.8.0",
4
4
  "license": "MIT",
5
5
  "main": "dist/index.js",
6
6
  "browser": {
package/dist/types.d.ts DELETED
@@ -1,253 +0,0 @@
1
- /// <reference types="node" />
2
- import type { GetOptions } from './selvaTypes/get';
3
- import type { SetOptions } from './selvaTypes/set';
4
- import type { Schema } from './selvaTypes/schema';
5
- import { Readable } from 'stream';
6
- export { GetOptions, SetOptions, Schema };
7
- export declare type DigestOptions = string;
8
- export declare enum RequestTypes {
9
- Subscription = 1,
10
- SubscriptionDiff = 2,
11
- SendSubscriptionData = 3,
12
- Unsubscribe = 4,
13
- Set = 5,
14
- Get = 6,
15
- Configuration = 7,
16
- GetConfiguration = 8,
17
- Call = 9,
18
- GetSubscription = 10,
19
- Delete = 11,
20
- Copy = 12,
21
- Digest = 13,
22
- Token = 14,
23
- Track = 15,
24
- Auth = 16
25
- }
26
- export declare enum AuthRequestTypes {
27
- Login = 1,
28
- Logout = 2,
29
- RenewToken = 3
30
- }
31
- export declare type Configuration = {
32
- schema: {
33
- [db: string]: Schema;
34
- };
35
- dbs: string[];
36
- };
37
- export declare type Query = GetOptions;
38
- export declare type GenericObject = {
39
- [key: string]: any;
40
- };
41
- export declare type Copy = {
42
- $id: string;
43
- db?: string;
44
- deep?: boolean;
45
- parents?: string[];
46
- excludeFields?: string[];
47
- };
48
- export declare type ErrorObject = {
49
- type: string;
50
- message: string;
51
- name?: string;
52
- query?: GenericObject;
53
- payload?: any;
54
- auth?: boolean;
55
- code?: string;
56
- };
57
- export declare type FunctionCallMessage = [RequestTypes.Call, string, number, any?];
58
- export declare type TrackMessage = [RequestTypes.Track, TrackPayload];
59
- export declare type RequestMessage<T = GenericObject> = [
60
- (RequestTypes.Set | RequestTypes.Get | RequestTypes.Configuration | RequestTypes.GetConfiguration | RequestTypes.Delete | RequestTypes.Copy | RequestTypes.Digest),
61
- number,
62
- T
63
- ];
64
- export declare type TokenMessage = [RequestTypes.Token, string?, boolean?];
65
- export declare type AuthMessage = [
66
- RequestTypes.Auth,
67
- AuthRequestTypes,
68
- number,
69
- GenericObject?
70
- ];
71
- export declare type SubscribeMessage = [
72
- RequestTypes.Subscription,
73
- number,
74
- GenericObject?,
75
- number?,
76
- (2 | 1 | 0)?,
77
- string?
78
- ];
79
- export declare type SendSubscriptionDataMessage = [
80
- RequestTypes.SendSubscriptionData,
81
- number,
82
- number?
83
- ];
84
- export declare type SendSubscriptionGetDataMessage = [
85
- RequestTypes.GetSubscription,
86
- number,
87
- GenericObject?,
88
- number?,
89
- string?
90
- ];
91
- export declare type UnsubscribeMessage = [
92
- RequestTypes.Unsubscribe,
93
- number
94
- ];
95
- export declare type SubscriptionMessage = SubscribeMessage | SendSubscriptionDataMessage | UnsubscribeMessage | SendSubscriptionGetDataMessage;
96
- export declare type Message = RequestMessage | SubscriptionMessage | FunctionCallMessage | AuthMessage;
97
- export declare type SubscriptionDiffData = [
98
- RequestTypes.SubscriptionDiff,
99
- number,
100
- GenericObject,
101
- [
102
- number,
103
- number
104
- ]
105
- ];
106
- export declare type SubscriptionData = [
107
- RequestTypes.Subscription,
108
- number,
109
- GenericObject,
110
- number?,
111
- ErrorObject?
112
- ];
113
- export declare type RequestData = [
114
- (RequestTypes.Set | RequestTypes.Get | RequestTypes.Configuration | RequestTypes.GetConfiguration | RequestTypes.Call | RequestTypes.Delete | RequestTypes.Copy | RequestTypes.Digest),
115
- number,
116
- any,
117
- ErrorObject?
118
- ];
119
- export declare type AuthorizedData = [RequestTypes.Token, number[], boolean?];
120
- export declare type AuthData = [
121
- RequestTypes.Auth,
122
- number,
123
- GenericObject,
124
- ErrorObject?
125
- ];
126
- export declare type ResponseData = SubscriptionDiffData | SubscriptionData | RequestData | AuthorizedData | AuthData;
127
- export declare type TrackPayload = {
128
- t: string;
129
- u?: 1;
130
- s?: 1;
131
- e?: 1;
132
- r?: 1;
133
- o?: TrackOpts;
134
- };
135
- export declare type TrackOpts = {
136
- amount?: number;
137
- };
138
- export declare type SendTokenOptions = {
139
- isBasedUser?: boolean;
140
- isApiKey?: boolean;
141
- refreshToken?: string;
142
- };
143
- export declare type AnalyticsResult = {
144
- all: {
145
- total: number;
146
- geo?: {
147
- [isoCode: string]: number;
148
- };
149
- };
150
- unique: {
151
- total: number;
152
- geo?: {
153
- [isoCode: string]: number;
154
- };
155
- };
156
- active: {
157
- total: number;
158
- max: number;
159
- geo?: {
160
- [isoCode: string]: number;
161
- };
162
- };
163
- };
164
- export declare type AnalyticsHistoryResult = {
165
- all: {
166
- total: [number, number][];
167
- geo?: {
168
- [isoCode: string]: [number, number][];
169
- };
170
- };
171
- unique: {
172
- total: [number, number][];
173
- geo?: {
174
- [isoCode: string]: [number, number][];
175
- };
176
- };
177
- active: {
178
- total: [number, number][];
179
- geo?: {
180
- [isoCode: string]: [number, number][];
181
- };
182
- };
183
- };
184
- export declare type AnalyticsTypes = string[];
185
- export declare type AnalyticsTypesOpts = {
186
- type?: string;
187
- $types: true;
188
- };
189
- export declare function isAnalyticsTypesOpts(opts: AnalyticsOpts | AnalyticsTypesOpts): opts is AnalyticsTypesOpts;
190
- export declare function isAnalyticsHistoryOpts(opts: AnalyticsOpts | AnalyticsTypesOpts): opts is AnalyticsHistoryOpts;
191
- export declare type AnalyticsOpts = {
192
- type: string;
193
- params?: {
194
- [key: string]: number | string | boolean;
195
- };
196
- $geo?: string[] | boolean;
197
- };
198
- export declare type AnalyticsHistoryOpts = {
199
- type: string;
200
- params?: {
201
- [key: string]: number | string | boolean;
202
- };
203
- $geo?: string[] | boolean;
204
- $history: boolean | number;
205
- };
206
- export declare type LoginOpts = {
207
- email: string;
208
- password: string;
209
- };
210
- export declare type RenewTokenOpts = {
211
- refreshToken: string;
212
- };
213
- export declare type FileUploadOptions = {
214
- contents: Buffer | ArrayBuffer | string | File | Blob;
215
- mimeType?: string;
216
- name?: string;
217
- url?: string | (() => Promise<string>);
218
- id?: string;
219
- raw?: boolean;
220
- parents?: string[];
221
- functionName?: string;
222
- };
223
- export declare type FileUploadStream = {
224
- contents: Readable;
225
- mimeType?: string;
226
- extension?: string;
227
- size: number;
228
- name?: string;
229
- url?: string | (() => Promise<string>);
230
- id?: string;
231
- raw?: boolean;
232
- parents?: string[];
233
- functionName?: string;
234
- };
235
- export declare type FileUploadPath = {
236
- path: string;
237
- mimeType?: string;
238
- extension?: string;
239
- name?: string;
240
- url?: string | (() => Promise<string>);
241
- id?: string;
242
- raw?: boolean;
243
- parents?: string[];
244
- functionName?: string;
245
- };
246
- export declare type FileUploadSrc = {
247
- src: string;
248
- mimeType?: string;
249
- name?: string;
250
- id?: string;
251
- parents?: string[];
252
- size?: number;
253
- };
package/dist/types.js DELETED
@@ -1,58 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isAnalyticsHistoryOpts = exports.isAnalyticsTypesOpts = exports.AuthRequestTypes = exports.RequestTypes = void 0;
4
- // eslint-disable-next-line
5
- var RequestTypes;
6
- (function (RequestTypes) {
7
- // eslint-disable-next-line
8
- RequestTypes[RequestTypes["Subscription"] = 1] = "Subscription";
9
- // eslint-disable-next-line
10
- RequestTypes[RequestTypes["SubscriptionDiff"] = 2] = "SubscriptionDiff";
11
- // eslint-disable-next-line
12
- RequestTypes[RequestTypes["SendSubscriptionData"] = 3] = "SendSubscriptionData";
13
- // eslint-disable-next-line
14
- RequestTypes[RequestTypes["Unsubscribe"] = 4] = "Unsubscribe";
15
- // eslint-disable-next-line
16
- RequestTypes[RequestTypes["Set"] = 5] = "Set";
17
- // eslint-disable-next-line
18
- RequestTypes[RequestTypes["Get"] = 6] = "Get";
19
- // eslint-disable-next-line
20
- RequestTypes[RequestTypes["Configuration"] = 7] = "Configuration";
21
- // eslint-disable-next-line
22
- RequestTypes[RequestTypes["GetConfiguration"] = 8] = "GetConfiguration";
23
- // eslint-disable-next-line
24
- RequestTypes[RequestTypes["Call"] = 9] = "Call";
25
- // eslint-disable-next-line
26
- RequestTypes[RequestTypes["GetSubscription"] = 10] = "GetSubscription";
27
- // eslint-disable-next-line
28
- RequestTypes[RequestTypes["Delete"] = 11] = "Delete";
29
- // eslint-disable-next-line
30
- RequestTypes[RequestTypes["Copy"] = 12] = "Copy";
31
- // eslint-disable-next-line
32
- RequestTypes[RequestTypes["Digest"] = 13] = "Digest";
33
- // eslint-disable-next-line
34
- RequestTypes[RequestTypes["Token"] = 14] = "Token";
35
- // eslint-disable-next-line
36
- RequestTypes[RequestTypes["Track"] = 15] = "Track";
37
- // eslint-disable-next-line
38
- RequestTypes[RequestTypes["Auth"] = 16] = "Auth";
39
- })(RequestTypes = exports.RequestTypes || (exports.RequestTypes = {}));
40
- var AuthRequestTypes;
41
- (function (AuthRequestTypes) {
42
- // eslint-disable-next-line
43
- AuthRequestTypes[AuthRequestTypes["Login"] = 1] = "Login";
44
- // eslint-disable-next-line
45
- AuthRequestTypes[AuthRequestTypes["Logout"] = 2] = "Logout";
46
- // eslint-disable-next-line
47
- AuthRequestTypes[AuthRequestTypes["RenewToken"] = 3] = "RenewToken";
48
- })(AuthRequestTypes = exports.AuthRequestTypes || (exports.AuthRequestTypes = {}));
49
- function isAnalyticsTypesOpts(opts) {
50
- return opts.$types === true;
51
- }
52
- exports.isAnalyticsTypesOpts = isAnalyticsTypesOpts;
53
- function isAnalyticsHistoryOpts(opts) {
54
- const hasHistory = opts.$history;
55
- return !!hasHistory;
56
- }
57
- exports.isAnalyticsHistoryOpts = isAnalyticsHistoryOpts;
58
- //# sourceMappingURL=types.js.map
package/dist/types.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AASA,2BAA2B;AAC3B,IAAY,YAiCX;AAjCD,WAAY,YAAY;IACtB,2BAA2B;IAC3B,+DAAgB,CAAA;IAChB,2BAA2B;IAC3B,uEAAoB,CAAA;IACpB,2BAA2B;IAC3B,+EAAwB,CAAA;IACxB,2BAA2B;IAC3B,6DAAe,CAAA;IACf,2BAA2B;IAC3B,6CAAO,CAAA;IACP,2BAA2B;IAC3B,6CAAO,CAAA;IACP,2BAA2B;IAC3B,iEAAiB,CAAA;IACjB,2BAA2B;IAC3B,uEAAoB,CAAA;IACpB,2BAA2B;IAC3B,+CAAQ,CAAA;IACR,2BAA2B;IAC3B,sEAAoB,CAAA;IACpB,2BAA2B;IAC3B,oDAAW,CAAA;IACX,2BAA2B;IAC3B,gDAAS,CAAA;IACT,2BAA2B;IAC3B,oDAAW,CAAA;IACX,2BAA2B;IAC3B,kDAAU,CAAA;IACV,2BAA2B;IAC3B,kDAAU,CAAA;IACV,2BAA2B;IAC3B,gDAAS,CAAA;AACX,CAAC,EAjCW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAiCvB;AAED,IAAY,gBAOX;AAPD,WAAY,gBAAgB;IAC1B,2BAA2B;IAC3B,yDAAS,CAAA;IACT,2BAA2B;IAC3B,2DAAU,CAAA;IACV,2BAA2B;IAC3B,mEAAc,CAAA;AAChB,CAAC,EAPW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAg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