@quiltt/core 3.5.3 → 3.5.5

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.
Files changed (47) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/SubscriptionLink-client-B5Tmyqw7.js +300 -0
  3. package/dist/index-client-BY-d8Msy.js +561 -0
  4. package/dist/index.d.ts +395 -15
  5. package/dist/index.js +248 -11
  6. package/package.json +11 -11
  7. package/src/api/graphql/links/actioncable/logger.ts +3 -1
  8. package/src/api/graphql/links/actioncable/subscription_guarantor.ts +1 -1
  9. package/dist/AuthAPI-eba95598.d.ts +0 -70
  10. package/dist/Storage/index.cjs +0 -10
  11. package/dist/Storage/index.cjs.map +0 -1
  12. package/dist/Storage/index.d.ts +0 -2
  13. package/dist/Storage/index.js +0 -5
  14. package/dist/Storage/index.js.map +0 -1
  15. package/dist/VersionLink-b7dfbaba.d.ts +0 -56
  16. package/dist/api/graphql/index.cjs +0 -49
  17. package/dist/api/graphql/index.cjs.map +0 -1
  18. package/dist/api/graphql/index.d.ts +0 -9
  19. package/dist/api/graphql/index.js +0 -15
  20. package/dist/api/graphql/index.js.map +0 -1
  21. package/dist/api/graphql/links/actioncable/index.cjs +0 -18
  22. package/dist/api/graphql/links/actioncable/index.cjs.map +0 -1
  23. package/dist/api/graphql/links/actioncable/index.d.ts +0 -62
  24. package/dist/api/graphql/links/actioncable/index.js +0 -5
  25. package/dist/api/graphql/links/actioncable/index.js.map +0 -1
  26. package/dist/api/graphql/links/index.cjs +0 -28
  27. package/dist/api/graphql/links/index.cjs.map +0 -1
  28. package/dist/api/graphql/links/index.d.ts +0 -8
  29. package/dist/api/graphql/links/index.js +0 -14
  30. package/dist/api/graphql/links/index.js.map +0 -1
  31. package/dist/api/index.cjs +0 -54
  32. package/dist/api/index.cjs.map +0 -1
  33. package/dist/api/index.d.ts +0 -12
  34. package/dist/api/index.js +0 -16
  35. package/dist/api/index.js.map +0 -1
  36. package/dist/api/rest/index.cjs +0 -14
  37. package/dist/api/rest/index.cjs.map +0 -1
  38. package/dist/api/rest/index.d.ts +0 -2
  39. package/dist/api/rest/index.js +0 -7
  40. package/dist/api/rest/index.js.map +0 -1
  41. package/dist/browser-e775a2b2.d.ts +0 -66
  42. package/dist/client-abcf98d8.d.ts +0 -8
  43. package/dist/consumer-c13efb94.d.ts +0 -78
  44. package/dist/index-f53b61b3.d.ts +0 -129
  45. package/dist/index.cjs +0 -67
  46. package/dist/index.cjs.map +0 -1
  47. package/dist/index.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,16 +1,253 @@
1
+ import { G as GlobalStorage, e as endpointGraphQL, v as version, d as debugging, S as SubscriptionLink, a as endpointAuth } from './SubscriptionLink-client-B5Tmyqw7.js';
2
+ export { L as LocalStorage, M as MemoryStorage, O as Observable, f as Storage, c as cdnBase, b as endpointWebsockets } from './SubscriptionLink-client-B5Tmyqw7.js';
1
3
  import { ApolloLink, ApolloClient } from '@apollo/client/index.js';
2
4
  export { InMemoryCache, gql, useMutation, useQuery, useSubscription } from '@apollo/client/index.js';
3
- import { BatchHttpLink } from '@apollo/client/link/batch-http/index.js';
4
- import Rt from 'cross-fetch';
5
+ import { BatchHttpLink as BatchHttpLink$1 } from '@apollo/client/link/batch-http/index.js';
6
+ import fetch from 'cross-fetch';
5
7
  import { onError } from '@apollo/client/link/error/index.js';
6
- import { HttpLink } from '@apollo/client/link/http/index.js';
7
- import { RetryLink } from '@apollo/client/link/retry/index.js';
8
- import { ApolloLink as ApolloLink$1, Observable } from '@apollo/client/core/index.js';
9
- import { print } from 'graphql';
10
- import zt from 'axios';
8
+ import { HttpLink as HttpLink$1 } from '@apollo/client/link/http/index.js';
9
+ import { RetryLink as RetryLink$1 } from '@apollo/client/link/retry/index.js';
10
+ import Axios from 'axios';
11
11
 
12
- var vt=Object.defineProperty,St=Object.defineProperties;var xt=Object.getOwnPropertyDescriptors;var H=Object.getOwnPropertySymbols;var yt=Object.prototype.hasOwnProperty,Ct=Object.prototype.propertyIsEnumerable;var P=(o,t,e)=>t in o?vt(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,l=(o,t)=>{for(var e in t||(t={}))yt.call(t,e)&&P(o,e,t[e]);if(H)for(var e of H(t))Ct.call(t,e)&&P(o,e,t[e]);return o},k=(o,t)=>St(o,xt(t));var n=(o,t,e)=>(P(o,typeof t!="symbol"?t+"":t,e),e);var B="@quiltt/core",z="3.5.3";var kt=(()=>{try{return process.env.QUILTT_API_INSECURE}catch(o){return}})(),V=(()=>{try{return process.env.QUILTT_API_DOMAIN}catch(o){return}})(),Tt=(()=>{try{return !!process.env.QUILTT_DEBUG||process.env.NODE_ENV!=="production"}catch(o){return !1}})(),T=V||"quiltt.io",M=`http${kt?"":"s"}`,At=`ws${V?"":"s"}`,A=Tt,F=`${B}: v${z}`,te=`${M}://cdn.${T}`,f=`${M}://auth.${T}/v1/users/session`,D=`${M}://api.${T}/v1/graphql`,Y=`${At}://api.${T}/websockets`;var Dt=/^(?:[\w-]+\.){2}[\w-]+$/,oe=o=>{if(typeof o=="undefined"||o===null)return o;if(!Dt.test(o)){console.error(`Invalid Session Token: ${o}`);return}let[t,e,r]=o.split(".");try{return {token:o,claims:JSON.parse(atob(e))}}catch(i){console.error(`Invalid Session Token: ${i}`);}};var g=class{constructor(t){n(this,"state");n(this,"observers",[]);n(this,"get",()=>this.state);n(this,"set",t=>{this.state!==t&&(this.state=t,this.observers.forEach(e=>e(t)));});n(this,"subscribe",t=>{this.observers.push(t);});n(this,"unsubscribe",t=>{this.observers=this.observers.filter(e=>e!==t);});this.state=t;}};var E=class{constructor(){n(this,"observers",{});n(this,"isEnabled",()=>{try{return localStorage.setItem("quiltt.ping","pong"),localStorage.removeItem("quiltt.ping"),!0}catch(t){return !1}});n(this,"isDisabled",()=>!this.isEnabled());n(this,"get",t=>{if(!(typeof window=="undefined"||window.expo))try{let e=window.localStorage.getItem(`quiltt.${t}`);return e&&JSON.parse(e)}catch(e){console.warn(`localStorage Error: "quiltt.${t}"`,e);return}});n(this,"set",(t,e)=>{if(!(typeof window=="undefined"||window.expo))try{e?window.localStorage.setItem(`quiltt.${t}`,JSON.stringify(e)):window.localStorage.removeItem(`quiltt.${t}`);}catch(r){console.warn(`localStorage Error: "quiltt.${t}"`,r);}});n(this,"remove",t=>{try{window.localStorage.removeItem(`quiltt.${t}`);}catch(e){console.warn(`localStorage Error: "quiltt.${t}">`,e);}});n(this,"subscribe",(t,e)=>{this.observers[t]||(this.observers[t]=[]),this.observers[t].push(e);});n(this,"unsubscribe",(t,e)=>{var r;this.observers[t]=(r=this.observers[t])==null?void 0:r.filter(i=>i!==e);});n(this,"handleStorageEvent",t=>{if(t.key&&t.key.includes("quiltt.")){let e=t.newValue?JSON.parse(t.newValue):null;this.observers[t.key]&&this.observers[t.key].forEach(r=>r(e));}else Object.entries(this.observers).forEach(([e,r])=>{r.forEach(i=>i(this.get(e)));});});typeof window!="undefined"&&!(window!=null&&window.expo)&&window.addEventListener("storage",this.handleStorageEvent.bind(this));}};var O=class{constructor(){n(this,"observables",{});n(this,"get",t=>{if(this.observables[t])return this.observables[t].get()});n(this,"set",(t,e)=>{this.observables[t]?this.observables[t].set(e):this.observables[t]=new g(e);});n(this,"subscribe",(t,e)=>{this.observables[t]||(this.observables[t]=new g),this.observables[t].subscribe(e);});n(this,"unsubscribe",(t,e)=>{this.observables[t]&&this.observables[t].unsubscribe(e);});}};var $=class{constructor(){n(this,"memoryStore",new O);n(this,"localStore",new E);n(this,"observers",{});n(this,"monitors",new Set);n(this,"get",t=>{this.monitorLocalStorageChanges(t);let e=this.memoryStore.get(t);return e===void 0&&(e=this.localStore.get(t)),e});n(this,"set",(t,e)=>{var r;this.monitorLocalStorageChanges(t),this.localStore.set(t,e),this.memoryStore.set(t,e),(r=this.observers[t])==null||r.forEach(i=>i(e));});n(this,"subscribe",(t,e)=>{this.observers[t]||(this.observers[t]=[]),this.observers[t].push(e);});n(this,"unsubscribe",(t,e)=>{var r;this.observers[t]=(r=this.observers[t])==null?void 0:r.filter(i=>i!==e);});n(this,"monitorLocalStorageChanges",t=>{this.monitors.has(t)||(this.monitors.add(t),this.localStore.subscribe(t,e=>{var c;let r=this.memoryStore.get(t),i=e instanceof Function?e(r):e;this.memoryStore.set(t,i),(c=this.observers[t])==null||c.forEach(p=>p(i));}));});}},m=new $;var X=class{constructor(){n(this,"timeout");n(this,"observers",[]);n(this,"set",(t,e)=>{this.timeout&&clearTimeout(this.timeout),this.observers.push(t),this.timeout=setTimeout(this.broadcast.bind(this),e);});n(this,"clear",t=>{this.observers=this.observers.filter(e=>e!==t);});n(this,"broadcast",()=>{this.observers.length!==0&&this.observers[0](void 0);});}};var Et=(i=>(i.Load="loaded",i.ExitSuccess="exited.successful",i.ExitAbort="exited.aborted",i.ExitError="exited.errored",i))(Et||{});var w=class extends ApolloLink{request(t,e){let r=m.get("session");return r?(t.setContext(({headers:i={}})=>({headers:k(l({},i),{authorization:`Bearer ${r}`})})),e(t)):(console.warn("QuilttLink attempted to send an unauthenticated Query"),null)}};var Z=new BatchHttpLink({uri:D,fetch:Rt});var tt=onError(({graphQLErrors:o,networkError:t})=>{o&&o.forEach(({message:e,locations:r,path:i})=>{console.log(`[GraphQL error]: Message: ${e}, Location: ${r}, Path: ${i}`);}),t&&(t.statusCode===401?(console.warn("[Authentication error]:",t),m.set("session",null)):console.warn("[Network error]:",t));});var et=new ApolloLink((o,t)=>t(o));var ot=new HttpLink({uri:D,fetch:Rt});var nt=new RetryLink({attempts:{retryIf:(o,t)=>!!o&&(!o.statusCode||o.statusCode>=500)}});var u={logger:typeof globalThis!="undefined"?globalThis.console:void 0,WebSocket:typeof globalThis!="undefined"?globalThis.WebSocket:void 0};var N=class{constructor(){n(this,"enabled",A);}log(...t){u.logger&&this.enabled&&(t.push(Date.now().toString()),u.logger.log("[ActionCable]",...t));}},Nt=new N,s=Nt;var v=()=>new Date().getTime(),R=o=>(v()-o)/1e3,S=class{constructor(t){this.visibilityDidChange=this.visibilityDidChange.bind(this),this.connection=t,this.reconnectAttempts=0;}start(){this.isRunning()||(this.startedAt=v(),delete this.stoppedAt,this.startPolling(),addEventListener("visibilitychange",this.visibilityDidChange),s.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`));}stop(){this.isRunning()&&(this.stoppedAt=v(),this.stopPolling(),removeEventListener("visibilitychange",this.visibilityDidChange),s.log("ConnectionMonitor stopped"));}isRunning(){return this.startedAt&&!this.stoppedAt}recordPing(){this.pingedAt=v();}recordConnect(){this.reconnectAttempts=0,this.recordPing(),delete this.disconnectedAt,s.log("ConnectionMonitor recorded connect");}recordDisconnect(){this.disconnectedAt=v(),s.log("ConnectionMonitor recorded disconnect");}startPolling(){this.stopPolling(),this.poll();}stopPolling(){clearTimeout(this.pollTimeout);}poll(){this.pollTimeout=setTimeout(()=>{this.reconnectIfStale(),this.poll();},this.getPollInterval());}getPollInterval(){let{staleThreshold:t,reconnectionBackoffRate:e}=this.constructor,r=Math.pow(1+e,Math.min(this.reconnectAttempts,10)),c=(this.reconnectAttempts===0?1:e)*Math.random();return t*1e3*r*(1+c)}reconnectIfStale(){this.connectionIsStale()&&(s.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${R(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`),this.reconnectAttempts++,this.disconnectedRecently()?s.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${R(this.disconnectedAt)} s`):(s.log("ConnectionMonitor reopening"),this.connection.reopen()));}get refreshedAt(){return this.pingedAt?this.pingedAt:this.startedAt}connectionIsStale(){return R(this.refreshedAt)>this.constructor.staleThreshold}disconnectedRecently(){return this.disconnectedAt&&R(this.disconnectedAt)<this.constructor.staleThreshold}visibilityDidChange(){document.visibilityState==="visible"&&setTimeout(()=>{(this.connectionIsStale()||!this.connection.isOpen())&&(s.log(`ConnectionMonitor reopening stale connection on visibilitychange. visibilityState = ${document.visibilityState}`),this.connection.reopen());},200);}};S.staleThreshold=6;S.reconnectionBackoffRate=.15;var rt=S;var qt={message_types:{welcome:"welcome",disconnect:"disconnect",ping:"ping",confirmation:"confirm_subscription",rejection:"reject_subscription"},disconnect_reasons:{unauthorized:"unauthorized",invalid_request:"invalid_request",server_restart:"server_restart",remote:"remote"},default_mount_path:"/cable",protocols:["actioncable-v1-json","actioncable-unsupported"]},L=qt;var{message_types:x,protocols:q}=L,Kt=q.slice(0,q.length-1),it=[].indexOf,y=class{constructor(t){this.open=this.open.bind(this),this.consumer=t,this.subscriptions=this.consumer.subscriptions,this.monitor=new rt(this),this.disconnected=!0;}send(t){return this.isOpen()?(this.webSocket.send(JSON.stringify(t)),!0):!1}open(){if(this.isActive())return s.log(`Attempted to open WebSocket, but existing socket is ${this.getState()}`),!1;{let t=[...q,...this.consumer.subprotocols||[]];return s.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${t}`),this.webSocket&&this.uninstallEventHandlers(),this.webSocket=new u.WebSocket(this.consumer.url,t),this.installEventHandlers(),this.monitor.start(),!0}}close({allowReconnect:t}={allowReconnect:!0}){if(t||this.monitor.stop(),this.isOpen())return this.webSocket.close()}reopen(){if(s.log(`Reopening WebSocket, current state is ${this.getState()}`),this.isActive())try{return this.close()}catch(t){s.log("Failed to reopen WebSocket",t);}finally{s.log(`Reopening WebSocket in ${this.constructor.reopenDelay}ms`),setTimeout(this.open,this.constructor.reopenDelay);}else return this.open()}getProtocol(){if(this.webSocket)return this.webSocket.protocol}isOpen(){return this.isState("open")}isActive(){return this.isState("open","connecting")}triedToReconnect(){return this.monitor.reconnectAttempts>0}isProtocolSupported(){return it.call(Kt,this.getProtocol())>=0}isState(...t){return it.call(t,this.getState())>=0}getState(){if(this.webSocket){for(let t in u.WebSocket)if(u.WebSocket[t]===this.webSocket.readyState)return t.toLowerCase()}return null}installEventHandlers(){for(let t in this.events){let e=this.events[t].bind(this);this.webSocket[`on${t}`]=e;}}uninstallEventHandlers(){for(let t in this.events)this.webSocket[`on${t}`]=function(){};}};y.reopenDelay=500;y.prototype.events={message(o){if(!this.isProtocolSupported())return;let{identifier:t,message:e,reason:r,reconnect:i,type:c}=JSON.parse(o.data);switch(c){case x.welcome:return this.triedToReconnect()&&(this.reconnectAttempted=!0),this.monitor.recordConnect(),this.subscriptions.reload();case x.disconnect:return s.log(`Disconnecting. Reason: ${r}`),this.close({allowReconnect:i});case x.ping:return this.monitor.recordPing();case x.confirmation:return this.subscriptions.confirmSubscription(t),this.reconnectAttempted?(this.reconnectAttempted=!1,this.subscriptions.notify(t,"connected",{reconnected:!0})):this.subscriptions.notify(t,"connected",{reconnected:!1});case x.rejection:return this.subscriptions.reject(t);default:return this.subscriptions.notify(t,"received",e)}},open(){if(s.log(`WebSocket onopen event, using '${this.getProtocol()}' subprotocol`),this.disconnected=!1,!this.isProtocolSupported())return s.log("Protocol is unsupported. Stopping monitor and disconnecting."),this.close({allowReconnect:!1})},close(o){if(s.log("WebSocket onclose event"),!this.disconnected)return this.disconnected=!0,this.monitor.recordDisconnect(),this.subscriptions.notifyAll("disconnected",{willAttemptReconnect:this.monitor.isRunning()})},error(){s.log("WebSocket onerror event");}};var st=y;var jt=function(o,t){if(t!==null)for(let e in t){let r=t[e];o[e]=r;}return o},K=class{constructor(t,e={},r){n(this,"consumer");n(this,"identifier");this.consumer=t,this.identifier=JSON.stringify(e),jt(this,r);}perform(t,e={}){return e.action=t,this.send(e)}send(t){return this.consumer.send({command:"message",identifier:this.identifier,data:JSON.stringify(t)})}unsubscribe(){return this.consumer.subscriptions.remove(this)}},ct=K;var j=class{constructor(t){n(this,"subscriptions");n(this,"pendingSubscriptions");n(this,"retryTimeout");this.subscriptions=t,this.pendingSubscriptions=[];}guarantee(t){this.pendingSubscriptions.indexOf(t)==-1?(s.log(`SubscriptionGuarantor guaranteeing ${t.identifier}`),this.pendingSubscriptions.push(t)):s.log(`SubscriptionGuarantor already guaranteeing ${t.identifier}`),this.startGuaranteeing();}forget(t){s.log(`SubscriptionGuarantor forgetting ${t.identifier}`),this.pendingSubscriptions=this.pendingSubscriptions.filter(e=>e!==t);}startGuaranteeing(){this.stopGuaranteeing(),this.retrySubscribing();}stopGuaranteeing(){clearTimeout(this.retryTimeout);}retrySubscribing(){this.retryTimeout=setTimeout(()=>{this.subscriptions&&typeof this.subscriptions.subscribe=="function"&&this.pendingSubscriptions.map(t=>{s.log(`SubscriptionGuarantor resubscribing ${t.identifier}`),this.subscriptions.subscribe(t);});},500);}},at=j;var _=class{constructor(t){n(this,"consumer");n(this,"guarantor");n(this,"subscriptions");this.consumer=t,this.guarantor=new at(this),this.subscriptions=[];}create(t,e){let r=t,i=typeof r=="object"?r:{channel:r},c=new ct(this.consumer,i,e);return this.add(c)}add(t){return this.subscriptions.push(t),this.consumer.ensureActiveConnection(),this.notify(t,"initialized"),this.subscribe(t),t}remove(t){return this.forget(t),this.findAll(t.identifier).length||this.sendCommand(t,"unsubscribe"),t}reject(t){return this.findAll(t).map(e=>(this.forget(e),this.notify(e,"rejected"),e))}forget(t){return this.guarantor.forget(t),this.subscriptions=this.subscriptions.filter(e=>e!==t),t}findAll(t){return this.subscriptions.filter(e=>e.identifier===t)}reload(){return this.subscriptions.map(t=>this.subscribe(t))}notifyAll(t,...e){return this.subscriptions.map(r=>this.notify(r,t,...e))}notify(t,e,...r){let i;return typeof t=="string"?i=this.findAll(t):i=[t],i.map(c=>typeof c[e]=="function"?c[e](...r):void 0)}subscribe(t){this.sendCommand(t,"subscribe")&&this.guarantor.guarantee(t);}confirmSubscription(t){s.log(`Subscription confirmed ${t}`),this.findAll(t).map(e=>this.guarantor.forget(e));}sendCommand(t,e){let{identifier:r}=t;return this.consumer.send({command:e,identifier:r})}},lt=_;var G=class{constructor(t){n(this,"_url");n(this,"subscriptions");n(this,"connection");n(this,"subprotocols");this._url=t,this.subscriptions=new lt(this),this.connection=new st(this),this.subprotocols=[];}get url(){return pt(this._url)}send(t){return this.connection.send(t)}connect(){return this.connection.open()}disconnect(){return this.connection.close({allowReconnect:!1})}ensureActiveConnection(){if(!this.connection.isActive())return this.connection.open()}addSubProtocol(t){this.subprotocols=[...this.subprotocols,t];}};function pt(o){if(typeof o=="function"&&(o=o()),o&&!/^wss?:/i.test(o)){let t=document.createElement("a");return t.href=o,t.href=t.href,t.protocol=t.protocol.replace("http","ws"),t.href}else return o}var ut=G;function dt(o=_t("url")||L.default_mount_path){return new ut(o)}function _t(o){let t=document.head.querySelector(`meta[name='action-cable-${o}']`);if(t)return t.getAttribute("content")}var U=class extends ApolloLink$1{constructor(e){super();n(this,"cables");n(this,"channelName");n(this,"actionName");n(this,"connectionParams");this.cables={},this.channelName=e.channelName||"GraphqlChannel",this.actionName=e.actionName||"execute",this.connectionParams=e.connectionParams||{};}request(e,r){let i=m.get("session");return i?(this.cables[i]||(this.cables[i]=dt(Y+(i?`?token=${i}`:""))),new Observable(c=>{let p=Math.round(Date.now()+Math.random()*1e5).toString(16),b=this.actionName,h=typeof this.connectionParams=="function"?this.connectionParams(e):this.connectionParams,C=this.cables[i].subscriptions.create(Object.assign({},{channel:this.channelName,channelId:p},h),{connected:()=>{C.perform(b,{query:e.query?print(e.query):null,variables:e.variables,operationId:e.operationId,operationName:e.operationName});},received:a=>{var W,Q;((W=a==null?void 0:a.result)!=null&&W.data||(Q=a==null?void 0:a.result)!=null&&Q.errors)&&c.next(a.result),a.more||c.complete();}});return Object.assign(C,{closed:!1})})):(console.warn("QuilttClient attempted to send an unauthenticated Subscription"),null)}},ht=U;var I=class extends ht{constructor(){super({channelName:"GraphQLChannel"});}};var Do=new ApolloLink(()=>null);var mt=new ApolloLink((o,t)=>(o.setContext(({headers:e={}})=>({headers:k(l({},e),{"Quiltt-Client-Version":F})})),t(o)));var bt=class extends ApolloClient{constructor(t){t.connectToDevTools||(t.connectToDevTools=A);let e=b=>b.query.definitions.some(({kind:h,operation:C})=>h==="OperationDefinition"&&C==="subscription"),r=b=>{var h;return (h=b.getContext().batchable)!=null?h:!0},i=new w,c=new I,p=ApolloLink.from([mt,i,tt,nt]).split(e,c,et).split(r,Z,ot);super(l({link:p},t));}};var Vt=150,ft=10,d=zt.create();d.interceptors.response.use(void 0,o=>{let{config:t,message:e,response:r}=o,i=e.toLowerCase();if(!t||!t.retry||!(i.includes("timeout")||i.includes("network error")||(r==null?void 0:r.status)===429))return Promise.reject(o);if(t.retriesRemaining===void 0)t.retriesRemaining=ft-1;else {if(t.retriesRemaining===1)return Promise.reject(o);t.retriesRemaining-=1;}return new Promise(p=>{setTimeout(()=>p(),Vt*(ft-t.retriesRemaining));}).then(()=>d(t))});var Ft=(e=>(e.Email="email",e.Phone="phone",e))(Ft||{}),gt=class{constructor(t){n(this,"clientId");n(this,"ping",t=>d.get(f,this.config(t)));n(this,"identify",t=>d.post(f,this.body(t),this.config()));n(this,"authenticate",t=>d.put(f,this.body(t),this.config()));n(this,"revoke",t=>d.delete(f,this.config(t)));n(this,"config",t=>{let e={"Content-Type":"application/json",Accept:"application/json"};return t&&(e.Authorization=`Bearer ${t}`),{headers:e,validateStatus:this.validateStatus,retry:!0}});n(this,"validateStatus",t=>t<500);n(this,"body",t=>(this.clientId||console.error("Quiltt Client ID is not set. Unable to identify & authenticate"),{session:l({clientId:this.clientId},t)}));this.clientId=t;}};
12
+ const MATCHER = /^(?:[\w-]+\.){2}[\w-]+$/;
13
+ const JsonWebTokenParse = (token)=>{
14
+ if (typeof token === 'undefined' || token === null) return token;
15
+ if (!MATCHER.test(token)) {
16
+ console.error(`Invalid Session Token: ${token}`);
17
+ return;
18
+ }
19
+ const [_header, payload, _signature] = token.split('.');
20
+ try {
21
+ return {
22
+ token: token,
23
+ claims: JSON.parse(atob(payload))
24
+ };
25
+ } catch (error) {
26
+ console.error(`Invalid Session Token: ${error}`);
27
+ }
28
+ };
13
29
 
14
- export { gt as AuthAPI, w as AuthLink, Ft as AuthStrategies, Z as BatchHttpLink, Et as ConnectorSDKEventType, tt as ErrorLink, et as ForwardableLink, m as GlobalStorage, ot as HttpLink, oe as JsonWebTokenParse, E as LocalStorage, O as MemoryStorage, g as Observable, bt as QuilttClient, nt as RetryLink, $ as Storage, I as SubscriptionLink, Do as TerminatingLink, X as Timeoutable, mt as VersionLink, te as cdnBase, A as debugging, f as endpointAuth, D as endpointGraphQL, Y as endpointWebsockets, F as version };
15
- //# sourceMappingURL=out.js.map
16
- //# sourceMappingURL=index.js.map
30
+ /**
31
+ * This is designed to support singletons to timeouts that can broadcast
32
+ * to any observers, preventing race conditions with multiple timeouts.
33
+ */ class Timeoutable {
34
+ constructor(){
35
+ this.observers = [];
36
+ this.set = (callback, delay)=>{
37
+ if (this.timeout) {
38
+ clearTimeout(this.timeout);
39
+ }
40
+ this.observers.push(callback);
41
+ this.timeout = setTimeout(this.broadcast.bind(this), delay);
42
+ };
43
+ this.clear = (observer)=>{
44
+ this.observers = this.observers.filter((callback)=>callback !== observer);
45
+ };
46
+ // Only sends to the 1st listener, but ensures that someone is notified
47
+ this.broadcast = ()=>{
48
+ if (this.observers.length === 0) return;
49
+ this.observers[0](undefined);
50
+ };
51
+ }
52
+ }
53
+
54
+ var ConnectorSDKEventType;
55
+ (function(ConnectorSDKEventType) {
56
+ ConnectorSDKEventType["Load"] = "loaded";
57
+ ConnectorSDKEventType["ExitSuccess"] = "exited.successful";
58
+ ConnectorSDKEventType["ExitAbort"] = "exited.aborted";
59
+ ConnectorSDKEventType["ExitError"] = "exited.errored";
60
+ })(ConnectorSDKEventType || (ConnectorSDKEventType = {}));
61
+
62
+ /**
63
+ * unauthorizedCallback only triggers in the event the token is present, and
64
+ * returns the token; This allows sessions to be forgotten without race conditions
65
+ * causing null sessions to kill valid sessions, or invalid sessions for killing
66
+ * valid sessions during rotation and networking weirdness.
67
+ */ class AuthLink extends ApolloLink {
68
+ request(operation, forward) {
69
+ const token = GlobalStorage.get('session');
70
+ if (!token) {
71
+ console.warn(`QuilttLink attempted to send an unauthenticated Query`);
72
+ return null;
73
+ }
74
+ operation.setContext(({ headers = {} })=>({
75
+ headers: {
76
+ ...headers,
77
+ authorization: `Bearer ${token}`
78
+ }
79
+ }));
80
+ return forward(operation);
81
+ }
82
+ }
83
+
84
+ const BatchHttpLink = new BatchHttpLink$1({
85
+ uri: endpointGraphQL,
86
+ fetch
87
+ });
88
+
89
+ const ErrorLink = onError(({ graphQLErrors, networkError })=>{
90
+ if (graphQLErrors) {
91
+ graphQLErrors.forEach(({ message, locations, path })=>{
92
+ console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`);
93
+ });
94
+ }
95
+ if (networkError) {
96
+ if (networkError.statusCode === 401) {
97
+ console.warn('[Authentication error]:', networkError);
98
+ GlobalStorage.set('session', null);
99
+ } else {
100
+ console.warn('[Network error]:', networkError);
101
+ }
102
+ }
103
+ });
104
+
105
+ const ForwardableLink = new ApolloLink((operation, forward)=>forward(operation));
106
+
107
+ const HttpLink = new HttpLink$1({
108
+ uri: endpointGraphQL,
109
+ fetch
110
+ });
111
+
112
+ const RetryLink = new RetryLink$1({
113
+ attempts: {
114
+ retryIf: (error, _operation)=>!!error && (!error.statusCode || error.statusCode >= 500)
115
+ }
116
+ });
117
+
118
+ const TerminatingLink = new ApolloLink(()=>null);
119
+
120
+ const VersionLink = new ApolloLink((operation, forward)=>{
121
+ operation.setContext(({ headers = {} })=>({
122
+ headers: {
123
+ ...headers,
124
+ 'Quiltt-Client-Version': version
125
+ }
126
+ }));
127
+ return forward(operation);
128
+ });
129
+
130
+ class QuilttClient extends ApolloClient {
131
+ constructor(options){
132
+ if (!options.connectToDevTools) options.connectToDevTools = debugging;
133
+ const isSubscriptionOperation = (operation)=>{
134
+ return operation.query.definitions.some(// @ts-ignore
135
+ ({ kind, operation })=>kind === 'OperationDefinition' && operation === 'subscription');
136
+ };
137
+ const isBatchable = (operation)=>{
138
+ return operation.getContext().batchable ?? true;
139
+ };
140
+ const authLink = new AuthLink();
141
+ const subscriptionsLink = new SubscriptionLink();
142
+ const quilttLink = ApolloLink.from([
143
+ VersionLink,
144
+ authLink,
145
+ ErrorLink,
146
+ RetryLink
147
+ ]).split(isSubscriptionOperation, subscriptionsLink, ForwardableLink).split(isBatchable, BatchHttpLink, HttpLink);
148
+ super({
149
+ link: quilttLink,
150
+ ...options
151
+ });
152
+ }
153
+ }
154
+
155
+ const RETRY_DELAY = 150 // ms
156
+ ;
157
+ const RETRIES = 10 // 150, 300, 450, 600, 750, 900, 1050, 1200, 1350, 1500 = 8.250s
158
+ ;
159
+ // Create an axios singleton for Quiltt, to prevent mutating other instances
160
+ const axios = Axios.create();
161
+ // Example: axios.get(url, { retry: true })
162
+ axios.interceptors.response.use(undefined, (error)=>{
163
+ const { config, message, response } = error;
164
+ const messageLower = message.toLowerCase();
165
+ if (!config || !config.retry) {
166
+ return Promise.reject(error);
167
+ }
168
+ // Retry Network timeout, Network errors, and Too Many Requests
169
+ if (!(messageLower.includes('timeout') || messageLower.includes('network error') || response?.status === 429)) {
170
+ return Promise.reject(error);
171
+ }
172
+ if (config.retriesRemaining === undefined) {
173
+ config.retriesRemaining = RETRIES - 1;
174
+ } else if (config.retriesRemaining === 1) {
175
+ return Promise.reject(error);
176
+ } else {
177
+ config.retriesRemaining -= 1;
178
+ }
179
+ const delay = new Promise((resolve)=>{
180
+ setTimeout(()=>resolve(), RETRY_DELAY * (RETRIES - config.retriesRemaining));
181
+ });
182
+ return delay.then(()=>axios(config));
183
+ });
184
+
185
+ var AuthStrategies;
186
+ (function(AuthStrategies) {
187
+ AuthStrategies["Email"] = "email";
188
+ AuthStrategies["Phone"] = "phone";
189
+ })(AuthStrategies || (AuthStrategies = {}));
190
+ // https://www.quiltt.dev/api-reference/rest/auth#
191
+ class AuthAPI {
192
+ constructor(clientId){
193
+ /**
194
+ * Response Statuses:
195
+ * - 200: OK -> Session is Valid
196
+ * - 401: Unauthorized -> Session is Invalid
197
+ */ this.ping = (token)=>{
198
+ return axios.get(endpointAuth, this.config(token));
199
+ };
200
+ /**
201
+ * Response Statuses:
202
+ * - 201: Created -> Profile Created, New Session Returned
203
+ * - 202: Accepted -> Profile Found, MFA Code Sent for `authenticate`
204
+ * - 422: Unprocessable Entity -> Invalid Payload
205
+ */ this.identify = (payload)=>{
206
+ return axios.post(endpointAuth, this.body(payload), this.config());
207
+ };
208
+ /**
209
+ * Response Statuses:
210
+ * - 201: Created -> MFA Validated, New Session Returned
211
+ * - 401: Unauthorized -> MFA Invalid
212
+ * - 422: Unprocessable Entity -> Invalid Payload
213
+ */ this.authenticate = (payload)=>{
214
+ return axios.put(endpointAuth, this.body(payload), this.config());
215
+ };
216
+ /**
217
+ * Response Statuses:
218
+ * - 204: No Content -> Session Revoked
219
+ * - 401: Unauthorized -> Session Not Found
220
+ */ this.revoke = (token)=>{
221
+ return axios.delete(endpointAuth, this.config(token));
222
+ };
223
+ this.config = (token)=>{
224
+ const headers = {
225
+ 'Content-Type': 'application/json',
226
+ Accept: 'application/json'
227
+ };
228
+ if (token) {
229
+ headers.Authorization = `Bearer ${token}`;
230
+ }
231
+ return {
232
+ headers: headers,
233
+ validateStatus: this.validateStatus,
234
+ retry: true
235
+ };
236
+ };
237
+ this.validateStatus = (status)=>status < 500;
238
+ this.body = (payload)=>{
239
+ if (!this.clientId) {
240
+ console.error('Quiltt Client ID is not set. Unable to identify & authenticate');
241
+ }
242
+ return {
243
+ session: {
244
+ clientId: this.clientId,
245
+ ...payload
246
+ }
247
+ };
248
+ };
249
+ this.clientId = clientId;
250
+ }
251
+ }
252
+
253
+ export { AuthAPI, AuthLink, AuthStrategies, BatchHttpLink, ConnectorSDKEventType, ErrorLink, ForwardableLink, GlobalStorage, HttpLink, JsonWebTokenParse, QuilttClient, RetryLink, SubscriptionLink, TerminatingLink, Timeoutable, VersionLink, debugging, endpointAuth, endpointGraphQL, version };
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@quiltt/core",
3
- "version": "3.5.3",
3
+ "version": "3.5.5",
4
4
  "description": "Javascript API client and utilities for Quiltt",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/quiltt/quiltt-public.git",
8
- "directory": "ECMAScript/core"
8
+ "directory": "packages/core"
9
9
  },
10
- "homepage": "https://github.com/quiltt/quiltt-public/tree/main/ECMAScript/core#readme",
10
+ "homepage": "https://github.com/quiltt/quiltt-public/tree/main/packages/core#readme",
11
11
  "keywords": [
12
12
  "quiltt",
13
13
  "typescript"
@@ -21,11 +21,10 @@
21
21
  "exports": {
22
22
  ".": {
23
23
  "import": "./dist/index.js",
24
- "require": "./dist/index.cjs",
25
24
  "types": "./dist/index.d.ts"
26
25
  }
27
26
  },
28
- "main": "./dist/index.cjs",
27
+ "main": "./dist/index.js",
29
28
  "module": "./dist/index.js",
30
29
  "types": "./dist/index.d.ts",
31
30
  "files": [
@@ -42,24 +41,25 @@
42
41
  },
43
42
  "devDependencies": {
44
43
  "@trivago/prettier-plugin-sort-imports": "4.1.1",
45
- "@types/node": "20.11.4",
46
- "@types/react": "18.2.7",
44
+ "@types/node": "20.11.25",
45
+ "@types/react": "18.2.64",
47
46
  "@typescript-eslint/eslint-plugin": "5.60.1",
48
47
  "@typescript-eslint/parser": "5.60.1",
48
+ "bunchee": "4.4.8",
49
49
  "eslint": "8.43.0",
50
50
  "eslint-config-prettier": "8.8.0",
51
51
  "eslint-plugin-prettier": "4.2.1",
52
52
  "prettier": "2.8.8",
53
- "tsup": "6.7.0",
54
- "typescript": "5.1.3"
53
+ "rimraf": "5.0.5",
54
+ "typescript": "5.4.2"
55
55
  },
56
56
  "publishConfig": {
57
57
  "access": "public"
58
58
  },
59
59
  "scripts": {
60
- "build": "tsup",
60
+ "build": "bunchee",
61
61
  "clean": "rimraf .turbo dist",
62
- "dev": "tsup --watch",
62
+ "dev": "bunchee --watch",
63
63
  "lint": "TIMING=1 eslint --ext .js,.jsx,.ts,.tsx src/ --fix",
64
64
  "typecheck": "tsc --project tsconfig.json --noEmit"
65
65
  }
@@ -2,7 +2,9 @@ import { debugging } from '../../../../configuration'
2
2
  import adapters from './adapters'
3
3
 
4
4
  class Logger {
5
- enabled = debugging
5
+ get enabled() {
6
+ return debugging
7
+ }
6
8
 
7
9
  log(...messages: Array<string>) {
8
10
  if (adapters.logger && this.enabled) {
@@ -16,7 +16,7 @@ class SubscriptionGuarantor {
16
16
  }
17
17
 
18
18
  guarantee(subscription: Subscription) {
19
- if (this.pendingSubscriptions.indexOf(subscription) == -1) {
19
+ if (this.pendingSubscriptions.indexOf(subscription) === -1) {
20
20
  logger.log(`SubscriptionGuarantor guaranteeing ${subscription.identifier}`)
21
21
  this.pendingSubscriptions.push(subscription)
22
22
  } else {
@@ -1,70 +0,0 @@
1
- import { AxiosResponse } from 'axios';
2
-
3
- declare enum AuthStrategies {
4
- Email = "email",
5
- Phone = "phone"
6
- }
7
- interface EmailInput {
8
- email: string;
9
- phone?: never;
10
- }
11
- interface PhoneInput {
12
- phone: string;
13
- email?: never;
14
- }
15
- type UsernamePayload = EmailInput | PhoneInput;
16
- type PasscodePayload = UsernamePayload & {
17
- passcode: string;
18
- };
19
- type SessionData = {
20
- token: string;
21
- };
22
- type NoContentData = void;
23
- type UnauthorizedData = {
24
- message: string;
25
- instruction: string;
26
- };
27
- type UnprocessableData = {
28
- [attribute: string]: Array<string>;
29
- };
30
- type Ping = SessionData | UnauthorizedData;
31
- type Identify = SessionData | NoContentData | UnprocessableData;
32
- type Authenticate = SessionData | UnauthorizedData | UnprocessableData;
33
- type Revoke = NoContentData | UnauthorizedData;
34
- type SessionResponse = AxiosResponse<SessionData>;
35
- type UnprocessableResponse = AxiosResponse<UnprocessableData>;
36
- declare class AuthAPI {
37
- clientId: string | undefined;
38
- constructor(clientId?: string | undefined);
39
- /**
40
- * Response Statuses:
41
- * - 200: OK -> Session is Valid
42
- * - 401: Unauthorized -> Session is Invalid
43
- */
44
- ping: (token: string) => Promise<AxiosResponse<Ping, any>>;
45
- /**
46
- * Response Statuses:
47
- * - 201: Created -> Profile Created, New Session Returned
48
- * - 202: Accepted -> Profile Found, MFA Code Sent for `authenticate`
49
- * - 422: Unprocessable Entity -> Invalid Payload
50
- */
51
- identify: (payload: UsernamePayload) => Promise<AxiosResponse<Identify, any>>;
52
- /**
53
- * Response Statuses:
54
- * - 201: Created -> MFA Validated, New Session Returned
55
- * - 401: Unauthorized -> MFA Invalid
56
- * - 422: Unprocessable Entity -> Invalid Payload
57
- */
58
- authenticate: (payload: PasscodePayload) => Promise<AxiosResponse<Authenticate, any>>;
59
- /**
60
- * Response Statuses:
61
- * - 204: No Content -> Session Revoked
62
- * - 401: Unauthorized -> Session Not Found
63
- */
64
- revoke: (token: string) => Promise<AxiosResponse<Revoke, any>>;
65
- private config;
66
- private validateStatus;
67
- private body;
68
- }
69
-
70
- export { AuthStrategies as A, PasscodePayload as P, SessionResponse as S, UsernamePayload as U, UnprocessableData as a, UnprocessableResponse as b, AuthAPI as c };
@@ -1,10 +0,0 @@
1
- 'use strict';
2
-
3
- var u=Object.defineProperty;var c=(i,e,r)=>e in i?u(i,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):i[e]=r;var t=(i,e,r)=>(c(i,typeof e!="symbol"?e+"":e,r),r);var a=class{constructor(){t(this,"observers",{});t(this,"isEnabled",()=>{try{return localStorage.setItem("quiltt.ping","pong"),localStorage.removeItem("quiltt.ping"),!0}catch(e){return !1}});t(this,"isDisabled",()=>!this.isEnabled());t(this,"get",e=>{if(!(typeof window=="undefined"||window.expo))try{let r=window.localStorage.getItem(`quiltt.${e}`);return r&&JSON.parse(r)}catch(r){console.warn(`localStorage Error: "quiltt.${e}"`,r);return}});t(this,"set",(e,r)=>{if(!(typeof window=="undefined"||window.expo))try{r?window.localStorage.setItem(`quiltt.${e}`,JSON.stringify(r)):window.localStorage.removeItem(`quiltt.${e}`);}catch(s){console.warn(`localStorage Error: "quiltt.${e}"`,s);}});t(this,"remove",e=>{try{window.localStorage.removeItem(`quiltt.${e}`);}catch(r){console.warn(`localStorage Error: "quiltt.${e}">`,r);}});t(this,"subscribe",(e,r)=>{this.observers[e]||(this.observers[e]=[]),this.observers[e].push(r);});t(this,"unsubscribe",(e,r)=>{var s;this.observers[e]=(s=this.observers[e])==null?void 0:s.filter(o=>o!==r);});t(this,"handleStorageEvent",e=>{if(e.key&&e.key.includes("quiltt.")){let r=e.newValue?JSON.parse(e.newValue):null;this.observers[e.key]&&this.observers[e.key].forEach(s=>s(r));}else Object.entries(this.observers).forEach(([r,s])=>{s.forEach(o=>o(this.get(r)));});});typeof window!="undefined"&&!(window!=null&&window.expo)&&window.addEventListener("storage",this.handleStorageEvent.bind(this));}};var n=class{constructor(e){t(this,"state");t(this,"observers",[]);t(this,"get",()=>this.state);t(this,"set",e=>{this.state!==e&&(this.state=e,this.observers.forEach(r=>r(e)));});t(this,"subscribe",e=>{this.observers.push(e);});t(this,"unsubscribe",e=>{this.observers=this.observers.filter(r=>r!==e);});this.state=e;}};var b=class{constructor(){t(this,"observables",{});t(this,"get",e=>{if(this.observables[e])return this.observables[e].get()});t(this,"set",(e,r)=>{this.observables[e]?this.observables[e].set(r):this.observables[e]=new n(r);});t(this,"subscribe",(e,r)=>{this.observables[e]||(this.observables[e]=new n),this.observables[e].subscribe(r);});t(this,"unsubscribe",(e,r)=>{this.observables[e]&&this.observables[e].unsubscribe(r);});}};var l=class{constructor(){t(this,"memoryStore",new b);t(this,"localStore",new a);t(this,"observers",{});t(this,"monitors",new Set);t(this,"get",e=>{this.monitorLocalStorageChanges(e);let r=this.memoryStore.get(e);return r===void 0&&(r=this.localStore.get(e)),r});t(this,"set",(e,r)=>{var s;this.monitorLocalStorageChanges(e),this.localStore.set(e,r),this.memoryStore.set(e,r),(s=this.observers[e])==null||s.forEach(o=>o(r));});t(this,"subscribe",(e,r)=>{this.observers[e]||(this.observers[e]=[]),this.observers[e].push(r);});t(this,"unsubscribe",(e,r)=>{var s;this.observers[e]=(s=this.observers[e])==null?void 0:s.filter(o=>o!==r);});t(this,"monitorLocalStorageChanges",e=>{this.monitors.has(e)||(this.monitors.add(e),this.localStore.subscribe(e,r=>{var v;let s=this.memoryStore.get(e),o=r instanceof Function?r(s):r;this.memoryStore.set(e,o),(v=this.observers[e])==null||v.forEach(h=>h(o));}));});}},E=new l;
4
-
5
- exports.GlobalStorage = E;
6
- exports.LocalStorage = a;
7
- exports.MemoryStorage = b;
8
- exports.Storage = l;
9
- //# sourceMappingURL=out.js.map
10
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/Storage/Local.ts","../../src/Observable.ts","../../src/Storage/Memory.ts","../../src/Storage/index.ts"],"names":["LocalStorage","__publicField","error","key","state","observer","_a","update","event","newState","observers","Observable","initalState","nextState","MemoryStorage","Storage","prevValue","GlobalStorage"],"mappings":"wKASO,IAAMA,EAAN,KAAsB,CAG3B,aAAc,CAFdC,EAAA,KAAQ,YAA8C,CAAC,GAQvDA,EAAA,iBAAY,IAAe,CACzB,GAAI,CACF,oBAAa,QAAQ,cAAe,MAAM,EAC1C,aAAa,WAAW,aAAa,EAC9B,EACT,OAASC,EAAP,CACA,MAAO,EACT,CACF,GAEAD,EAAA,kBAAa,IAAe,CAAC,KAAK,UAAU,GAE5CA,EAAA,WAAOE,GAAsC,CAC3C,GAAI,SAAO,QAAW,aAAiB,OAAO,MAE9C,GAAI,CACF,IAAMC,EAAQ,OAAO,aAAa,QAAQ,UAAUD,GAAK,EACzD,OAAOC,GAAQ,KAAK,MAAMA,CAAK,CACjC,OAASF,EAAP,CACA,QAAQ,KAAK,+BAA+BC,KAAQD,CAAK,EACzD,MACF,CACF,GAEAD,EAAA,WAAM,CAACE,EAAaC,IAAsC,CACxD,GAAI,SAAO,QAAW,aAAiB,OAAO,MAE9C,GAAI,CACEA,EACF,OAAO,aAAa,QAAQ,UAAUD,IAAO,KAAK,UAAUC,CAAK,CAAC,EAElE,OAAO,aAAa,WAAW,UAAUD,GAAK,CAElD,OAASD,EAAP,CACA,QAAQ,KAAK,+BAA+BC,KAAQD,CAAK,CAC3D,CACF,GAEAD,EAAA,cAAUE,GAAgB,CACxB,GAAI,CACF,OAAO,aAAa,WAAW,UAAUA,GAAK,CAChD,OAASD,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EAAKM,CAAQ,EACjC,KAAK,YAAY,IAAIN,EAAKM,CAAQ,GAElCH,EAAA,KAAK,UAAUH,CAAG,IAAlB,MAAAG,EAAqB,QAASC,GAAWA,EAAOE,CAAQ,EAC1D,GAMAR,EAAA,iBAAY,CAACE,EAAaE,IAA0B,CAC7C,KAAK,UAAUF,CAAG,IAAG,KAAK,UAAUA,CAAG,EAAI,CAAC,GAEjD,KAAK,UAAUA,CAAG,EAAE,KAAKE,CAAQ,CACnC,GAEAJ,EAAA,mBAAc,CAACE,EAAaE,IAA0B,CAzDxD,IAAAC,EA0DI,KAAK,UAAUH,CAAG,GAAIG,EAAA,KAAK,UAAUH,CAAG,IAAlB,YAAAG,EAAqB,OAAQC,GAAWA,IAAWF,EAC3E,GAYAJ,EAAA,KAAQ,6BAA8BE,GAAgB,CAChD,KAAK,SAAS,IAAIA,CAAG,IACzB,KAAK,SAAS,IAAIA,CAAG,EAErB,KAAK,WAAW,UAAUA,EAAMU,GAAc,CA3ElD,IAAAP,EA4EM,IAAMU,EAAY,KAAK,YAAY,IAAIb,CAAG,EACpCM,EAAWI,aAAqB,SAAWA,EAAUG,CAAS,EAAIH,EAExE,KAAK,YAAY,IAAIV,EAAKM,CAAQ,GAClCH,EAAA,KAAK,UAAUH,CAAG,IAAlB,MAAAG,EAAqB,QAASC,GAAWA,EAAOE,CAAQ,EAC1D,CAAC,EACH,GACF,EASaQ,EAAgB,IAAIF","sourcesContent":["import type { Maybe } from '../types'\nimport type { Observer } from '../Observable'\n\n/**\n * An error and type safe wrapper for localStorage.\n * It allows you to subscribe to changes;\n * but localStorage changes only fire with another\n * window updates the record.\n */\nexport class LocalStorage<T> {\n private observers: { [key: string]: Observer<T>[] } = {}\n\n constructor() {\n if (typeof window !== 'undefined' && !window?.expo) {\n window.addEventListener('storage', this.handleStorageEvent.bind(this))\n }\n }\n\n isEnabled = (): boolean => {\n try {\n localStorage.setItem(`quiltt.ping`, 'pong')\n localStorage.removeItem(`quiltt.ping`)\n return true\n } catch (error) {\n return false\n }\n }\n\n isDisabled = (): boolean => !this.isEnabled()\n\n get = (key: string): Maybe<T> | undefined => {\n if (typeof window === 'undefined' || !!window.expo) return undefined\n\n try {\n const state = window.localStorage.getItem(`quiltt.${key}`)\n return state ? JSON.parse(state) : state\n } catch (error) {\n console.warn(`localStorage Error: \"quiltt.${key}\"`, error)\n return undefined\n }\n }\n\n set = (key: string, state: Maybe<T> | undefined): void => {\n if (typeof window === 'undefined' || !!window.expo) return\n\n try {\n if (state) {\n window.localStorage.setItem(`quiltt.${key}`, JSON.stringify(state))\n } else {\n window.localStorage.removeItem(`quiltt.${key}`)\n }\n } catch (error) {\n console.warn(`localStorage Error: \"quiltt.${key}\"`, error)\n }\n }\n\n remove = (key: string) => {\n try {\n window.localStorage.removeItem(`quiltt.${key}`)\n } catch (error) {\n console.warn(`localStorage Error: \"quiltt.${key}\">`, error)\n }\n }\n\n subscribe = (key: string, observer: Observer<T>) => {\n if (!this.observers[key]) this.observers[key] = []\n\n this.observers[key].push(observer)\n }\n\n unsubscribe = (key: string, observer: Observer<T>) => {\n this.observers[key] = this.observers[key]?.filter((update) => update !== observer)\n }\n\n // if there is a key, then trigger the related updates. If there is not key\n // it means that a record has been removed and everything needs to be rechecked.\n private handleStorageEvent = (event: StorageEvent) => {\n if (event.key && event.key.includes('quiltt.')) {\n const newState = event.newValue ? JSON.parse(event.newValue) : null\n\n if (this.observers[event.key]) {\n this.observers[event.key].forEach((update) => update(newState))\n }\n } else {\n Object.entries(this.observers).forEach(([key, observers]) => {\n observers.forEach((update) => update(this.get(key)))\n })\n }\n }\n}\n\nexport default LocalStorage\n","import type { Dispatch, SetStateAction } from 'react'\nimport type { Maybe } from './types'\n\nexport type Observer<T> = Dispatch<SetStateAction<Maybe<T> | undefined>>\n\n/**\n * This is designed to support singletons to share the memory states across all\n * instance of hooks to ensure that updates only process once, by storing a value\n * then notifying all subscribers when it's updated.\n */\nexport class Observable<T> {\n private state?: Maybe<T>\n private observers: Observer<T>[] = []\n\n constructor(initalState?: Maybe<T>) {\n this.state = initalState\n }\n\n get = () => {\n return this.state\n }\n\n set = (nextState: Maybe<T> | undefined) => {\n if (this.state === nextState) return\n\n this.state = nextState\n this.observers.forEach((update) => update(nextState))\n }\n\n subscribe = (observer: Observer<T>) => {\n this.observers.push(observer)\n }\n\n unsubscribe = (observer: Observer<T>) => {\n this.observers = this.observers.filter((update) => update !== observer)\n }\n}\n\nexport default Observable\n","import type { Maybe } from '../types'\n\nimport { Observable } from '../Observable'\nimport type { Observer } from '../Observable'\n\n/**\n * This is designed to support effectively an in memory key value store singleton,\n * similar to localstorage, but allows you to subscribe to changes within the current\n * window.\n */\nexport class MemoryStorage<T> {\n private observables: { [key: string]: Observable<T> } = {}\n\n get = (key: string) => {\n if (this.observables[key]) {\n return this.observables[key].get()\n } else {\n return undefined\n }\n }\n\n set = (key: string, state: Maybe<T> | undefined): void => {\n if (!this.observables[key]) {\n this.observables[key] = new Observable<T>(state)\n } else {\n this.observables[key].set(state)\n }\n }\n\n subscribe = (key: string, observer: Observer<T>): void => {\n if (!this.observables[key]) this.observables[key] = new Observable<T>()\n\n this.observables[key].subscribe(observer)\n }\n\n unsubscribe = (key: string, observer: Observer<T>): void => {\n if (this.observables[key]) {\n this.observables[key].unsubscribe(observer)\n }\n }\n}\n\nexport default MemoryStorage\n","import type { Maybe } from '../types'\n\nimport type { Observer } from '../Observable'\nimport { LocalStorage } from './Local'\nimport { MemoryStorage } from './Memory'\n\n/**\n * This is wraps both local and memory storage to create a unified interface, that\n * allows you to subscribe to all either changes made within this window, or changes\n * made by other windows.\n */\nexport class Storage<T> {\n private memoryStore = new MemoryStorage<T>()\n private localStore = new LocalStorage<T>()\n private observers: { [key: string]: Observer<T>[] } = {}\n private monitors: Set<string> = new Set()\n\n /**\n * Checks memoryStorage before falling back to localStorage.\n */\n get = (key: string): Maybe<T> | undefined => {\n this.monitorLocalStorageChanges(key)\n\n let state = this.memoryStore.get(key)\n\n if (state === undefined) {\n state = this.localStore.get(key)\n }\n\n return state\n }\n\n /**\n * We don't trust localStorage to always be present, so we can't rely on it to\n * update memoryStorage based on emitted changes. So we manage our own\n * emitting while using the underlying events to keep memoryStore in sync with\n * localStore.\n */\n set = (key: string, newState: Maybe<T> | undefined) => {\n this.monitorLocalStorageChanges(key)\n\n this.localStore.set(key, newState)\n this.memoryStore.set(key, newState)\n\n this.observers[key]?.forEach((update) => update(newState))\n }\n\n /**\n * Allows you to subscribe to all changes in memory or local storage as a\n * single event.\n */\n subscribe = (key: string, observer: Observer<T>) => {\n if (!this.observers[key]) this.observers[key] = []\n\n this.observers[key].push(observer)\n }\n\n unsubscribe = (key: string, observer: Observer<T>) => {\n this.observers[key] = this.observers[key]?.filter((update) => update !== observer)\n }\n\n /**\n * Sets bubble the changes down the stack starting with memoryStore and then\n * localStore. memoryStore will emit changes to everything within the current\n * window context, while localStore will emit changes to every other window\n * context.\n *\n * To ensure that the other windows are updated correctly, changes to localStore\n * need to be subscribed and updated to in memory store, which then may be subscribed\n * to outside of storage.\n */\n private monitorLocalStorageChanges = (key: string) => {\n if (this.monitors.has(key)) return\n this.monitors.add(key)\n\n this.localStore.subscribe(key, (nextState) => {\n const prevValue = this.memoryStore.get(key)\n const newState = nextState instanceof Function ? nextState(prevValue) : nextState\n\n this.memoryStore.set(key, newState)\n this.observers[key]?.forEach((update) => update(newState))\n })\n }\n}\n\nexport * from './Local'\nexport * from './Memory'\n\n/**\n * This is an singleton to share the memory states across all instances; This\n * basically acts like shared memory when there is no localStorage.\n */\nexport const GlobalStorage = new Storage<any>()\n"]}
@@ -1,2 +0,0 @@
1
- export { G as GlobalStorage, L as LocalStorage, b as MemoryStorage, S as Storage } from '../index-f53b61b3.js';
2
- import 'react';
@@ -1,5 +0,0 @@
1
- var u=Object.defineProperty;var c=(i,e,r)=>e in i?u(i,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):i[e]=r;var t=(i,e,r)=>(c(i,typeof e!="symbol"?e+"":e,r),r);var a=class{constructor(){t(this,"observers",{});t(this,"isEnabled",()=>{try{return localStorage.setItem("quiltt.ping","pong"),localStorage.removeItem("quiltt.ping"),!0}catch(e){return !1}});t(this,"isDisabled",()=>!this.isEnabled());t(this,"get",e=>{if(!(typeof window=="undefined"||window.expo))try{let r=window.localStorage.getItem(`quiltt.${e}`);return r&&JSON.parse(r)}catch(r){console.warn(`localStorage Error: "quiltt.${e}"`,r);return}});t(this,"set",(e,r)=>{if(!(typeof window=="undefined"||window.expo))try{r?window.localStorage.setItem(`quiltt.${e}`,JSON.stringify(r)):window.localStorage.removeItem(`quiltt.${e}`);}catch(s){console.warn(`localStorage Error: "quiltt.${e}"`,s);}});t(this,"remove",e=>{try{window.localStorage.removeItem(`quiltt.${e}`);}catch(r){console.warn(`localStorage Error: "quiltt.${e}">`,r);}});t(this,"subscribe",(e,r)=>{this.observers[e]||(this.observers[e]=[]),this.observers[e].push(r);});t(this,"unsubscribe",(e,r)=>{var s;this.observers[e]=(s=this.observers[e])==null?void 0:s.filter(o=>o!==r);});t(this,"handleStorageEvent",e=>{if(e.key&&e.key.includes("quiltt.")){let r=e.newValue?JSON.parse(e.newValue):null;this.observers[e.key]&&this.observers[e.key].forEach(s=>s(r));}else Object.entries(this.observers).forEach(([r,s])=>{s.forEach(o=>o(this.get(r)));});});typeof window!="undefined"&&!(window!=null&&window.expo)&&window.addEventListener("storage",this.handleStorageEvent.bind(this));}};var n=class{constructor(e){t(this,"state");t(this,"observers",[]);t(this,"get",()=>this.state);t(this,"set",e=>{this.state!==e&&(this.state=e,this.observers.forEach(r=>r(e)));});t(this,"subscribe",e=>{this.observers.push(e);});t(this,"unsubscribe",e=>{this.observers=this.observers.filter(r=>r!==e);});this.state=e;}};var b=class{constructor(){t(this,"observables",{});t(this,"get",e=>{if(this.observables[e])return this.observables[e].get()});t(this,"set",(e,r)=>{this.observables[e]?this.observables[e].set(r):this.observables[e]=new n(r);});t(this,"subscribe",(e,r)=>{this.observables[e]||(this.observables[e]=new n),this.observables[e].subscribe(r);});t(this,"unsubscribe",(e,r)=>{this.observables[e]&&this.observables[e].unsubscribe(r);});}};var l=class{constructor(){t(this,"memoryStore",new b);t(this,"localStore",new a);t(this,"observers",{});t(this,"monitors",new Set);t(this,"get",e=>{this.monitorLocalStorageChanges(e);let r=this.memoryStore.get(e);return r===void 0&&(r=this.localStore.get(e)),r});t(this,"set",(e,r)=>{var s;this.monitorLocalStorageChanges(e),this.localStore.set(e,r),this.memoryStore.set(e,r),(s=this.observers[e])==null||s.forEach(o=>o(r));});t(this,"subscribe",(e,r)=>{this.observers[e]||(this.observers[e]=[]),this.observers[e].push(r);});t(this,"unsubscribe",(e,r)=>{var s;this.observers[e]=(s=this.observers[e])==null?void 0:s.filter(o=>o!==r);});t(this,"monitorLocalStorageChanges",e=>{this.monitors.has(e)||(this.monitors.add(e),this.localStore.subscribe(e,r=>{var v;let s=this.memoryStore.get(e),o=r instanceof Function?r(s):r;this.memoryStore.set(e,o),(v=this.observers[e])==null||v.forEach(h=>h(o));}));});}},E=new l;
2
-
3
- export { E as GlobalStorage, a as LocalStorage, b as MemoryStorage, l as Storage };
4
- //# sourceMappingURL=out.js.map
5
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/Storage/Local.ts","../../src/Observable.ts","../../src/Storage/Memory.ts","../../src/Storage/index.ts"],"names":["LocalStorage","__publicField","error","key","state","observer","_a","update","event","newState","observers","Observable","initalState","nextState","MemoryStorage","Storage","prevValue","GlobalStorage"],"mappings":"wKASO,IAAMA,EAAN,KAAsB,CAG3B,aAAc,CAFdC,EAAA,KAAQ,YAA8C,CAAC,GAQvDA,EAAA,iBAAY,IAAe,CACzB,GAAI,CACF,oBAAa,QAAQ,cAAe,MAAM,EAC1C,aAAa,WAAW,aAAa,EAC9B,EACT,OAASC,EAAP,CACA,MAAO,EACT,CACF,GAEAD,EAAA,kBAAa,IAAe,CAAC,KAAK,UAAU,GAE5CA,EAAA,WAAOE,GAAsC,CAC3C,GAAI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pCM,EAAWI,aAAqB,SAAWA,EAAUG,CAAS,EAAIH,EAExE,KAAK,YAAY,IAAIV,EAAKM,CAAQ,GAClCH,EAAA,KAAK,UAAUH,CAAG,IAAlB,MAAAG,EAAqB,QAASC,GAAWA,EAAOE,CAAQ,EAC1D,CAAC,EACH,GACF,EASaQ,EAAgB,IAAIF","sourcesContent":["import type { Maybe } from '../types'\nimport type { Observer } from '../Observable'\n\n/**\n * An error and type safe wrapper for localStorage.\n * It allows you to subscribe to changes;\n * but localStorage changes only fire with another\n * window updates the record.\n */\nexport class LocalStorage<T> {\n private observers: { [key: string]: Observer<T>[] } = {}\n\n constructor() {\n if (typeof window !== 'undefined' && !window?.expo) {\n window.addEventListener('storage', this.handleStorageEvent.bind(this))\n }\n }\n\n isEnabled = (): boolean => {\n try {\n localStorage.setItem(`quiltt.ping`, 'pong')\n localStorage.removeItem(`quiltt.ping`)\n return true\n } catch (error) {\n return false\n }\n }\n\n isDisabled = (): boolean => !this.isEnabled()\n\n get = (key: string): Maybe<T> | undefined => {\n if (typeof window === 'undefined' || !!window.expo) return undefined\n\n try {\n const state = window.localStorage.getItem(`quiltt.${key}`)\n return state ? JSON.parse(state) : state\n } catch (error) {\n console.warn(`localStorage Error: \"quiltt.${key}\"`, error)\n return undefined\n }\n }\n\n set = (key: string, state: Maybe<T> | undefined): void => {\n if (typeof window === 'undefined' || !!window.expo) return\n\n try {\n if (state) {\n window.localStorage.setItem(`quiltt.${key}`, JSON.stringify(state))\n } else {\n window.localStorage.removeItem(`quiltt.${key}`)\n }\n } catch (error) {\n console.warn(`localStorage Error: \"quiltt.${key}\"`, error)\n }\n }\n\n remove = (key: string) => {\n try {\n window.localStorage.removeItem(`quiltt.${key}`)\n } catch (error) {\n console.warn(`localStorage Error: \"quiltt.${key}\">`, error)\n }\n }\n\n subscribe = (key: string, observer: Observer<T>) => {\n if (!this.observers[key]) this.observers[key] = []\n\n this.observers[key].push(observer)\n }\n\n unsubscribe = (key: string, observer: Observer<T>) => {\n this.observers[key] = this.observers[key]?.filter((update) => update !== observer)\n }\n\n // if there is a key, then trigger the related updates. If there is not key\n // it means that a record has been removed and everything needs to be rechecked.\n private handleStorageEvent = (event: StorageEvent) => {\n if (event.key && event.key.includes('quiltt.')) {\n const newState = event.newValue ? JSON.parse(event.newValue) : null\n\n if (this.observers[event.key]) {\n this.observers[event.key].forEach((update) => update(newState))\n }\n } else {\n Object.entries(this.observers).forEach(([key, observers]) => {\n observers.forEach((update) => update(this.get(key)))\n })\n }\n }\n}\n\nexport default LocalStorage\n","import type { Dispatch, SetStateAction } from 'react'\nimport type { Maybe } from './types'\n\nexport type Observer<T> = Dispatch<SetStateAction<Maybe<T> | undefined>>\n\n/**\n * This is designed to support singletons to share the memory states across all\n * instance of hooks to ensure that updates only process once, by storing a value\n * then notifying all subscribers when it's updated.\n */\nexport class Observable<T> {\n private state?: Maybe<T>\n private observers: Observer<T>[] = []\n\n constructor(initalState?: Maybe<T>) {\n this.state = initalState\n }\n\n get = () => {\n return this.state\n }\n\n set = (nextState: Maybe<T> | undefined) => {\n if (this.state === nextState) return\n\n this.state = nextState\n this.observers.forEach((update) => update(nextState))\n }\n\n subscribe = (observer: Observer<T>) => {\n this.observers.push(observer)\n }\n\n unsubscribe = (observer: Observer<T>) => {\n this.observers = this.observers.filter((update) => update !== observer)\n }\n}\n\nexport default Observable\n","import type { Maybe } from '../types'\n\nimport { Observable } from '../Observable'\nimport type { Observer } from '../Observable'\n\n/**\n * This is designed to support effectively an in memory key value store singleton,\n * similar to localstorage, but allows you to subscribe to changes within the current\n * window.\n */\nexport class MemoryStorage<T> {\n private observables: { [key: string]: Observable<T> } = {}\n\n get = (key: string) => {\n if (this.observables[key]) {\n return this.observables[key].get()\n } else {\n return undefined\n }\n }\n\n set = (key: string, state: Maybe<T> | undefined): void => {\n if (!this.observables[key]) {\n this.observables[key] = new Observable<T>(state)\n } else {\n this.observables[key].set(state)\n }\n }\n\n subscribe = (key: string, observer: Observer<T>): void => {\n if (!this.observables[key]) this.observables[key] = new Observable<T>()\n\n this.observables[key].subscribe(observer)\n }\n\n unsubscribe = (key: string, observer: Observer<T>): void => {\n if (this.observables[key]) {\n this.observables[key].unsubscribe(observer)\n }\n }\n}\n\nexport default MemoryStorage\n","import type { Maybe } from '../types'\n\nimport type { Observer } from '../Observable'\nimport { LocalStorage } from './Local'\nimport { MemoryStorage } from './Memory'\n\n/**\n * This is wraps both local and memory storage to create a unified interface, that\n * allows you to subscribe to all either changes made within this window, or changes\n * made by other windows.\n */\nexport class Storage<T> {\n private memoryStore = new MemoryStorage<T>()\n private localStore = new LocalStorage<T>()\n private observers: { [key: string]: Observer<T>[] } = {}\n private monitors: Set<string> = new Set()\n\n /**\n * Checks memoryStorage before falling back to localStorage.\n */\n get = (key: string): Maybe<T> | undefined => {\n this.monitorLocalStorageChanges(key)\n\n let state = this.memoryStore.get(key)\n\n if (state === undefined) {\n state = this.localStore.get(key)\n }\n\n return state\n }\n\n /**\n * We don't trust localStorage to always be present, so we can't rely on it to\n * update memoryStorage based on emitted changes. So we manage our own\n * emitting while using the underlying events to keep memoryStore in sync with\n * localStore.\n */\n set = (key: string, newState: Maybe<T> | undefined) => {\n this.monitorLocalStorageChanges(key)\n\n this.localStore.set(key, newState)\n this.memoryStore.set(key, newState)\n\n this.observers[key]?.forEach((update) => update(newState))\n }\n\n /**\n * Allows you to subscribe to all changes in memory or local storage as a\n * single event.\n */\n subscribe = (key: string, observer: Observer<T>) => {\n if (!this.observers[key]) this.observers[key] = []\n\n this.observers[key].push(observer)\n }\n\n unsubscribe = (key: string, observer: Observer<T>) => {\n this.observers[key] = this.observers[key]?.filter((update) => update !== observer)\n }\n\n /**\n * Sets bubble the changes down the stack starting with memoryStore and then\n * localStore. memoryStore will emit changes to everything within the current\n * window context, while localStore will emit changes to every other window\n * context.\n *\n * To ensure that the other windows are updated correctly, changes to localStore\n * need to be subscribed and updated to in memory store, which then may be subscribed\n * to outside of storage.\n */\n private monitorLocalStorageChanges = (key: string) => {\n if (this.monitors.has(key)) return\n this.monitors.add(key)\n\n this.localStore.subscribe(key, (nextState) => {\n const prevValue = this.memoryStore.get(key)\n const newState = nextState instanceof Function ? nextState(prevValue) : nextState\n\n this.memoryStore.set(key, newState)\n this.observers[key]?.forEach((update) => update(newState))\n })\n }\n}\n\nexport * from './Local'\nexport * from './Memory'\n\n/**\n * This is an singleton to share the memory states across all instances; This\n * basically acts like shared memory when there is no localStorage.\n */\nexport const GlobalStorage = new Storage<any>()\n"]}
@@ -1,56 +0,0 @@
1
- import { ApolloLink, Operation, NextLink, Observable, FetchResult } from '@apollo/client/index.js';
2
- import { BatchHttpLink as BatchHttpLink$1 } from '@apollo/client/link/batch-http/index.js';
3
- import * as _apollo_client from '@apollo/client';
4
- import { HttpLink as HttpLink$1 } from '@apollo/client/link/http/index.js';
5
- import { RetryLink as RetryLink$1 } from '@apollo/client/link/retry/index.js';
6
- import { ApolloLink as ApolloLink$1, Operation as Operation$1, NextLink as NextLink$1, Observable as Observable$1, FetchResult as FetchResult$1 } from '@apollo/client/core/index.js';
7
- import { C as Consumer } from './consumer-c13efb94.js';
8
-
9
- /**
10
- * unauthorizedCallback only triggers in the event the token is present, and
11
- * returns the token; This allows sessions to be forgotten without race conditions
12
- * causing null sessions to kill valid sessions, or invalid sessions for killing
13
- * valid sessions during rotation and networking weirdness.
14
- */
15
- declare class AuthLink extends ApolloLink {
16
- request(operation: Operation, forward: NextLink): Observable<FetchResult> | null;
17
- }
18
-
19
- declare const BatchHttpLink: BatchHttpLink$1;
20
-
21
- declare const ErrorLink: _apollo_client.ApolloLink;
22
-
23
- declare const ForwardableLink: ApolloLink;
24
-
25
- declare const HttpLink: HttpLink$1;
26
-
27
- declare const RetryLink: RetryLink$1;
28
-
29
- type RequestResult = FetchResult$1<{
30
- [key: string]: unknown;
31
- }, Record<string, unknown>, Record<string, unknown>>;
32
- type ConnectionParams = object | ((operation: Operation$1) => object);
33
- declare class ActionCableLink extends ApolloLink$1 {
34
- cables: {
35
- [id: string]: Consumer;
36
- };
37
- channelName: string;
38
- actionName: string;
39
- connectionParams: ConnectionParams;
40
- constructor(options: {
41
- channelName?: string;
42
- actionName?: string;
43
- connectionParams?: ConnectionParams;
44
- });
45
- request(operation: Operation$1, _next: NextLink$1): Observable$1<RequestResult> | null;
46
- }
47
-
48
- declare class SubscriptionLink extends ActionCableLink {
49
- constructor();
50
- }
51
-
52
- declare const TerminatingLink: ApolloLink;
53
-
54
- declare const VersionLink: ApolloLink;
55
-
56
- export { AuthLink as A, BatchHttpLink as B, ErrorLink as E, ForwardableLink as F, HttpLink as H, RetryLink as R, SubscriptionLink as S, TerminatingLink as T, VersionLink as V };