@quiltt/core 3.1.2 → 3.2.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/CHANGELOG.md +12 -0
- package/dist/Storage/index.cjs +2 -2
- package/dist/Storage/index.cjs.map +1 -1
- package/dist/Storage/index.d.ts +1 -1
- package/dist/Storage/index.js +2 -2
- package/dist/Storage/index.js.map +1 -1
- package/dist/api/graphql/index.cjs +1 -1
- package/dist/api/graphql/index.cjs.map +1 -1
- package/dist/api/graphql/index.js +1 -1
- package/dist/api/graphql/index.js.map +1 -1
- package/dist/api/graphql/links/actioncable/index.cjs.map +1 -1
- package/dist/api/graphql/links/actioncable/index.js.map +1 -1
- package/dist/api/graphql/links/index.cjs +1 -1
- package/dist/api/graphql/links/index.cjs.map +1 -1
- package/dist/api/graphql/links/index.js +1 -1
- package/dist/api/graphql/links/index.js.map +1 -1
- package/dist/api/index.cjs +3 -3
- package/dist/api/index.cjs.map +1 -1
- package/dist/api/index.js +2 -2
- package/dist/api/index.js.map +1 -1
- package/dist/api/rest/index.cjs.map +1 -1
- package/dist/api/rest/index.js.map +1 -1
- package/dist/{index-5e7ddbfe.d.ts → index-f53b61b3.d.ts} +5 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/Storage/Local.ts +3 -3
- package/src/types.ts +5 -0
package/CHANGELOG.md
CHANGED
package/dist/Storage/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
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
|
|
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
4
|
|
|
5
5
|
exports.GlobalStorage = E;
|
|
6
|
-
exports.LocalStorage =
|
|
6
|
+
exports.LocalStorage = a;
|
|
7
7
|
exports.MemoryStorage = b;
|
|
8
8
|
exports.Storage = l;
|
|
9
9
|
//# sourceMappingURL=out.js.map
|
|
@@ -1 +1 @@
|
|
|
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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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') {\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') 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') 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
|
+
{"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,KA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AAIC,EAAQ,KAAK,YAAY,IAAID,CAAG,EAEpC,OAAIC,IAAU,SACZA,EAAQ,KAAK,WAAW,IAAID,CAAG,GAG1BC,CACT,GAQAH,EAAA,WAAM,CAACE,EAAaM,IAAmC,CAtCzD,IAAAH,EAuCI,KAAK,2BAA2BH,CAAG,EAEnC,KAAK,WAAW,IAAIA,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"]}
|
package/dist/Storage/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { G as GlobalStorage, L as LocalStorage, b as MemoryStorage, S as Storage } from '../index-
|
|
1
|
+
export { G as GlobalStorage, L as LocalStorage, b as MemoryStorage, S as Storage } from '../index-f53b61b3.js';
|
|
2
2
|
import 'react';
|
package/dist/Storage/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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
|
|
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
2
|
|
|
3
|
-
export { E as GlobalStorage,
|
|
3
|
+
export { E as GlobalStorage, a as LocalStorage, b as MemoryStorage, l as Storage };
|
|
4
4
|
//# sourceMappingURL=out.js.map
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
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,OAAO,QAAW,YAEtB,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,OAAO,QAAW,YAEtB,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,EAAP,CACA,QAAQ,KAAK,+BAA+BC,MAASD,CAAK,CAC5D,CACF,GAEAD,EAAA,iBAAY,CAACE,EAAaE,IAA0B,CAC7C,KAAK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Q,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') {\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') 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') 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
|
+
{"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,kB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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"]}
|
|
@@ -13,7 +13,7 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
13
13
|
|
|
14
14
|
var Tt__default = /*#__PURE__*/_interopDefault(Tt);
|
|
15
15
|
|
|
16
|
-
var dt=Object.defineProperty,mt=Object.defineProperties;var ft=Object.getOwnPropertyDescriptors;var Q=Object.getOwnPropertySymbols;var bt=Object.prototype.hasOwnProperty,gt=Object.prototype.propertyIsEnumerable;var N=(o,t,e)=>t in o?dt(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,u=(o,t)=>{for(var e in t||(t={}))bt.call(t,e)&&N(o,e,t[e]);if(Q)for(var e of Q(t))gt.call(t,e)&&N(o,e,t[e]);return o},x=(o,t)=>mt(o,ft(t));var r=(o,t,e)=>(N(o,typeof t!="symbol"?t+"":t,e),e);var w=class{constructor(){r(this,"observers",{});r(this,"isEnabled",()=>{try{return localStorage.setItem("quiltt.ping","pong"),localStorage.removeItem("quiltt.ping"),!0}catch(t){return !1}});r(this,"isDisabled",()=>!this.isEnabled());r(this,"get",t=>{if(typeof window!="undefined")try{let e=window.localStorage.getItem(`quiltt.${t}`);return e&&JSON.parse(e)}catch(e){console.warn(`localStorage Error: "quiltt.${t}"`,e);return}});r(this,"set",(t,e)=>{if(typeof window!="undefined")try{e?window.localStorage.setItem(`quiltt.${t}`,JSON.stringify(e)):window.localStorage.removeItem(`quiltt.${t}`);}catch(i){console.warn(`localStorage Error: "quiltt.${t}"`,i);}});r(this,"remove",t=>{try{window.localStorage.removeItem(`quiltt.${t}`);}catch(e){console.warn(`localStorage Error: "quiltt.${t}">`,e);}});r(this,"subscribe",(t,e)=>{this.observers[t]||(this.observers[t]=[]),this.observers[t].push(e);});r(this,"unsubscribe",(t,e)=>{var i;this.observers[t]=(i=this.observers[t])==null?void 0:i.filter(n=>n!==e);});r(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(i=>i(e));}else Object.entries(this.observers).forEach(([e,i])=>{i.forEach(n=>n(this.get(e)));});});typeof window!="undefined"&&window.addEventListener("storage",this.handleStorageEvent.bind(this));}};var f=class{constructor(t){r(this,"state");r(this,"observers",[]);r(this,"get",()=>this.state);r(this,"set",t=>{this.state!==t&&(this.state=t,this.observers.forEach(e=>e(t)));});r(this,"subscribe",t=>{this.observers.push(t);});r(this,"unsubscribe",t=>{this.observers=this.observers.filter(e=>e!==t);});this.state=t;}};var T=class{constructor(){r(this,"observables",{});r(this,"get",t=>{if(this.observables[t])return this.observables[t].get()});r(this,"set",(t,e)=>{this.observables[t]?this.observables[t].set(e):this.observables[t]=new f(e);});r(this,"subscribe",(t,e)=>{this.observables[t]||(this.observables[t]=new f),this.observables[t].subscribe(e);});r(this,"unsubscribe",(t,e)=>{this.observables[t]&&this.observables[t].unsubscribe(e);});}};var $=class{constructor(){r(this,"memoryStore",new T);r(this,"localStore",new w);r(this,"observers",{});r(this,"monitors",new Set);r(this,"get",t=>{this.monitorLocalStorageChanges(t);let e=this.memoryStore.get(t);return e===void 0&&(e=this.localStore.get(t)),e});r(this,"set",(t,e)=>{var i;this.monitorLocalStorageChanges(t),this.localStore.set(t,e),this.memoryStore.set(t,e),(i=this.observers[t])==null||i.forEach(n=>n(e));});r(this,"subscribe",(t,e)=>{this.observers[t]||(this.observers[t]=[]),this.observers[t].push(e);});r(this,"unsubscribe",(t,e)=>{var i;this.observers[t]=(i=this.observers[t])==null?void 0:i.filter(n=>n!==e);});r(this,"monitorLocalStorageChanges",t=>{this.monitors.has(t)||(this.monitors.add(t),this.localStore.subscribe(t,e=>{var c;let i=this.memoryStore.get(t),n=e instanceof Function?e(i):e;this.memoryStore.set(t,n),(c=this.observers[t])==null||c.forEach(d=>d(n));}));});}},h=new $;var A=class extends index_js.ApolloLink{request(t,e){let i=h.get("session");return i?(t.setContext(({headers:n={}})=>({headers:x(u({},n),{authorization:`Bearer ${i}`})})),e(t)):(console.warn("QuilttLink attempted to send an unauthenticated Query"),null)}};var U="@quiltt/core",B="3.1.2";var St=(()=>{try{return process.env.QUILTT_API_INSECURE}catch(o){return}})(),V=(()=>{try{return process.env.QUILTT_API_DOMAIN}catch(o){return}})(),yt=(()=>{try{return !!process.env.QUILTT_DEBUG||process.env.NODE_ENV!=="production"}catch(o){return !1}})(),R=V||"quiltt.io",F=`http${St?"":"s"}`,xt=`ws${V?"":"s"}`,k=yt,C=`${F}://api.${R}/v1/graphql`,J=`${xt}://api.${R}/websockets`,z=`${U}: v${B}`;var K=new index_js$1.BatchHttpLink({uri:C,fetch:Tt__default.default});var X=index_js$2.onError(({graphQLErrors:o,networkError:t})=>{o&&o.forEach(({message:e,locations:i,path:n})=>{console.log(`[GraphQL error]: Message: ${e}, Location: ${i}, Path: ${n}`);}),t&&(t.statusCode===401?(console.warn("[Authentication error]:",t),h.set("session",null)):console.warn("[Network error]:",t));});var Y=new index_js.ApolloLink((o,t)=>t(o));var Z=new index_js$3.HttpLink({uri:C,fetch:Tt__default.default});var tt=new index_js$4.RetryLink({attempts:{retryIf:(o,t)=>o.statusCode>=500}});var l={logger:typeof globalThis!="undefined"?globalThis.console:void 0,WebSocket:typeof globalThis!="undefined"?globalThis.WebSocket:void 0};var I=class{constructor(){r(this,"enabled",k);}log(...t){l.logger&&this.enabled&&(t.push(Date.now().toString()),l.logger.log("[ActionCable]",...t));}},Et=new I,s=Et;var b=()=>new Date().getTime(),O=o=>(b()-o)/1e3,g=class{constructor(t){this.visibilityDidChange=this.visibilityDidChange.bind(this),this.connection=t,this.reconnectAttempts=0;}start(){this.isRunning()||(this.startedAt=b(),delete this.stoppedAt,this.startPolling(),addEventListener("visibilitychange",this.visibilityDidChange),s.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`));}stop(){this.isRunning()&&(this.stoppedAt=b(),this.stopPolling(),removeEventListener("visibilitychange",this.visibilityDidChange),s.log("ConnectionMonitor stopped"));}isRunning(){return this.startedAt&&!this.stoppedAt}recordPing(){this.pingedAt=b();}recordConnect(){this.reconnectAttempts=0,this.recordPing(),delete this.disconnectedAt,s.log("ConnectionMonitor recorded connect");}recordDisconnect(){this.disconnectedAt=b(),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,i=Math.pow(1+e,Math.min(this.reconnectAttempts,10)),c=(this.reconnectAttempts===0?1:e)*Math.random();return t*1e3*i*(1+c)}reconnectIfStale(){this.connectionIsStale()&&(s.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${O(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`),this.reconnectAttempts++,this.disconnectedRecently()?s.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${O(this.disconnectedAt)} s`):(s.log("ConnectionMonitor reopening"),this.connection.reopen()));}get refreshedAt(){return this.pingedAt?this.pingedAt:this.startedAt}connectionIsStale(){return O(this.refreshedAt)>this.constructor.staleThreshold}disconnectedRecently(){return this.disconnectedAt&&O(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);}};g.staleThreshold=6;g.reconnectionBackoffRate=.15;var et=g;var Nt={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=Nt;var{message_types:v,protocols:M}=L,$t=M.slice(0,M.length-1),ot=[].indexOf,S=class{constructor(t){this.open=this.open.bind(this),this.consumer=t,this.subscriptions=this.consumer.subscriptions,this.monitor=new et(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=[...M,...this.consumer.subprotocols||[]];return s.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${t}`),this.webSocket&&this.uninstallEventHandlers(),this.webSocket=new l.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 ot.call($t,this.getProtocol())>=0}isState(...t){return ot.call(t,this.getState())>=0}getState(){if(this.webSocket){for(let t in l.WebSocket)if(l.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(){};}};S.reopenDelay=500;S.prototype.events={message(o){if(!this.isProtocolSupported())return;let{identifier:t,message:e,reason:i,reconnect:n,type:c}=JSON.parse(o.data);switch(c){case v.welcome:return this.triedToReconnect()&&(this.reconnectAttempted=!0),this.monitor.recordConnect(),this.subscriptions.reload();case v.disconnect:return s.log(`Disconnecting. Reason: ${i}`),this.close({allowReconnect:n});case v.ping:return this.monitor.recordPing();case v.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 v.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 rt=S;var Rt=function(o,t){if(t!==null)for(let e in t){let i=t[e];o[e]=i;}return o},q=class{constructor(t,e={},i){r(this,"consumer");r(this,"identifier");this.consumer=t,this.identifier=JSON.stringify(e),Rt(this,i);}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)}},it=q;var P=class{constructor(t){r(this,"subscriptions");r(this,"pendingSubscriptions");r(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);}},nt=P;var D=class{constructor(t){r(this,"consumer");r(this,"guarantor");r(this,"subscriptions");this.consumer=t,this.guarantor=new nt(this),this.subscriptions=[];}create(t,e){let i=t,n=typeof i=="object"?i:{channel:i},c=new it(this.consumer,n,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(i=>this.notify(i,t,...e))}notify(t,e,...i){let n;return typeof t=="string"?n=this.findAll(t):n=[t],n.map(c=>typeof c[e]=="function"?c[e](...i):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:i}=t;return this.consumer.send({command:e,identifier:i})}},st=D;var j=class{constructor(t){r(this,"_url");r(this,"subscriptions");r(this,"connection");r(this,"subprotocols");this._url=t,this.subscriptions=new st(this),this.connection=new rt(this),this.subprotocols=[];}get url(){return ct(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 ct(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 at=j;function lt(o=It("url")||L.default_mount_path){return new at(o)}function It(o){let t=document.head.querySelector(`meta[name='action-cable-${o}']`);if(t)return t.getAttribute("content")}var _=class extends index_js$5.ApolloLink{constructor(e){super();r(this,"cables");r(this,"channelName");r(this,"actionName");r(this,"connectionParams");this.cables={},this.channelName=e.channelName||"GraphqlChannel",this.actionName=e.actionName||"execute",this.connectionParams=e.connectionParams||{};}request(e,i){let n=h.get("session");return n?(this.cables[n]||(this.cables[n]=lt(J+(n?`?token=${n}`:""))),new index_js$5.Observable(c=>{let d=Math.round(Date.now()+Math.random()*1e5).toString(16),m=this.actionName,p=typeof this.connectionParams=="function"?this.connectionParams(e):this.connectionParams,y=this.cables[n].subscriptions.create(Object.assign({},{channel:this.channelName,channelId:d},p),{connected:()=>{y.perform(m,{query:e.query?graphql.print(e.query):null,variables:e.variables,operationId:e.operationId,operationName:e.operationName});},received:a=>{var G,W;((G=a==null?void 0:a.result)!=null&&G.data||(W=a==null?void 0:a.result)!=null&&W.errors)&&c.next(a.result),a.more||c.complete();}});return Object.assign(y,{closed:!1})})):(console.warn("QuilttLink attempted to send an unauthenticated Subscription"),null)}},pt=_;var E=class extends pt{constructor(){super({channelName:"GraphQLChannel"});}};var po=new index_js.ApolloLink(()=>null);var ut=new index_js.ApolloLink((o,t)=>(o.setContext(({headers:e={}})=>({headers:x(u({},e),{"Quiltt-Client-Version":z})})),t(o)));var ht=class extends index_js.ApolloClient{constructor(t){t.connectToDevTools||(t.connectToDevTools=k);let e=m=>m.query.definitions.some(({kind:p,operation:y})=>p==="OperationDefinition"&&y==="subscription"),i=m=>{var p;return (p=m.getContext().batchable)!=null?p:!0},n=new A,c=new E,d=index_js.ApolloLink.from([ut,n,X,tt]).split(e,c,Y).split(i,K,Z);super(u({link:d},t));}};
|
|
16
|
+
var dt=Object.defineProperty,mt=Object.defineProperties;var ft=Object.getOwnPropertyDescriptors;var Q=Object.getOwnPropertySymbols;var bt=Object.prototype.hasOwnProperty,gt=Object.prototype.propertyIsEnumerable;var N=(o,t,e)=>t in o?dt(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e,u=(o,t)=>{for(var e in t||(t={}))bt.call(t,e)&&N(o,e,t[e]);if(Q)for(var e of Q(t))gt.call(t,e)&&N(o,e,t[e]);return o},x=(o,t)=>mt(o,ft(t));var r=(o,t,e)=>(N(o,typeof t!="symbol"?t+"":t,e),e);var w=class{constructor(){r(this,"observers",{});r(this,"isEnabled",()=>{try{return localStorage.setItem("quiltt.ping","pong"),localStorage.removeItem("quiltt.ping"),!0}catch(t){return !1}});r(this,"isDisabled",()=>!this.isEnabled());r(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}});r(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(i){console.warn(`localStorage Error: "quiltt.${t}"`,i);}});r(this,"remove",t=>{try{window.localStorage.removeItem(`quiltt.${t}`);}catch(e){console.warn(`localStorage Error: "quiltt.${t}">`,e);}});r(this,"subscribe",(t,e)=>{this.observers[t]||(this.observers[t]=[]),this.observers[t].push(e);});r(this,"unsubscribe",(t,e)=>{var i;this.observers[t]=(i=this.observers[t])==null?void 0:i.filter(n=>n!==e);});r(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(i=>i(e));}else Object.entries(this.observers).forEach(([e,i])=>{i.forEach(n=>n(this.get(e)));});});typeof window!="undefined"&&!(window!=null&&window.expo)&&window.addEventListener("storage",this.handleStorageEvent.bind(this));}};var f=class{constructor(t){r(this,"state");r(this,"observers",[]);r(this,"get",()=>this.state);r(this,"set",t=>{this.state!==t&&(this.state=t,this.observers.forEach(e=>e(t)));});r(this,"subscribe",t=>{this.observers.push(t);});r(this,"unsubscribe",t=>{this.observers=this.observers.filter(e=>e!==t);});this.state=t;}};var T=class{constructor(){r(this,"observables",{});r(this,"get",t=>{if(this.observables[t])return this.observables[t].get()});r(this,"set",(t,e)=>{this.observables[t]?this.observables[t].set(e):this.observables[t]=new f(e);});r(this,"subscribe",(t,e)=>{this.observables[t]||(this.observables[t]=new f),this.observables[t].subscribe(e);});r(this,"unsubscribe",(t,e)=>{this.observables[t]&&this.observables[t].unsubscribe(e);});}};var $=class{constructor(){r(this,"memoryStore",new T);r(this,"localStore",new w);r(this,"observers",{});r(this,"monitors",new Set);r(this,"get",t=>{this.monitorLocalStorageChanges(t);let e=this.memoryStore.get(t);return e===void 0&&(e=this.localStore.get(t)),e});r(this,"set",(t,e)=>{var i;this.monitorLocalStorageChanges(t),this.localStore.set(t,e),this.memoryStore.set(t,e),(i=this.observers[t])==null||i.forEach(n=>n(e));});r(this,"subscribe",(t,e)=>{this.observers[t]||(this.observers[t]=[]),this.observers[t].push(e);});r(this,"unsubscribe",(t,e)=>{var i;this.observers[t]=(i=this.observers[t])==null?void 0:i.filter(n=>n!==e);});r(this,"monitorLocalStorageChanges",t=>{this.monitors.has(t)||(this.monitors.add(t),this.localStore.subscribe(t,e=>{var c;let i=this.memoryStore.get(t),n=e instanceof Function?e(i):e;this.memoryStore.set(t,n),(c=this.observers[t])==null||c.forEach(d=>d(n));}));});}},h=new $;var A=class extends index_js.ApolloLink{request(t,e){let i=h.get("session");return i?(t.setContext(({headers:n={}})=>({headers:x(u({},n),{authorization:`Bearer ${i}`})})),e(t)):(console.warn("QuilttLink attempted to send an unauthenticated Query"),null)}};var U="@quiltt/core",B="3.2.0";var St=(()=>{try{return process.env.QUILTT_API_INSECURE}catch(o){return}})(),V=(()=>{try{return process.env.QUILTT_API_DOMAIN}catch(o){return}})(),yt=(()=>{try{return !!process.env.QUILTT_DEBUG||process.env.NODE_ENV!=="production"}catch(o){return !1}})(),R=V||"quiltt.io",F=`http${St?"":"s"}`,xt=`ws${V?"":"s"}`,k=yt,C=`${F}://api.${R}/v1/graphql`,J=`${xt}://api.${R}/websockets`,z=`${U}: v${B}`;var K=new index_js$1.BatchHttpLink({uri:C,fetch:Tt__default.default});var X=index_js$2.onError(({graphQLErrors:o,networkError:t})=>{o&&o.forEach(({message:e,locations:i,path:n})=>{console.log(`[GraphQL error]: Message: ${e}, Location: ${i}, Path: ${n}`);}),t&&(t.statusCode===401?(console.warn("[Authentication error]:",t),h.set("session",null)):console.warn("[Network error]:",t));});var Y=new index_js.ApolloLink((o,t)=>t(o));var Z=new index_js$3.HttpLink({uri:C,fetch:Tt__default.default});var tt=new index_js$4.RetryLink({attempts:{retryIf:(o,t)=>o.statusCode>=500}});var l={logger:typeof globalThis!="undefined"?globalThis.console:void 0,WebSocket:typeof globalThis!="undefined"?globalThis.WebSocket:void 0};var I=class{constructor(){r(this,"enabled",k);}log(...t){l.logger&&this.enabled&&(t.push(Date.now().toString()),l.logger.log("[ActionCable]",...t));}},Et=new I,s=Et;var b=()=>new Date().getTime(),O=o=>(b()-o)/1e3,g=class{constructor(t){this.visibilityDidChange=this.visibilityDidChange.bind(this),this.connection=t,this.reconnectAttempts=0;}start(){this.isRunning()||(this.startedAt=b(),delete this.stoppedAt,this.startPolling(),addEventListener("visibilitychange",this.visibilityDidChange),s.log(`ConnectionMonitor started. stale threshold = ${this.constructor.staleThreshold} s`));}stop(){this.isRunning()&&(this.stoppedAt=b(),this.stopPolling(),removeEventListener("visibilitychange",this.visibilityDidChange),s.log("ConnectionMonitor stopped"));}isRunning(){return this.startedAt&&!this.stoppedAt}recordPing(){this.pingedAt=b();}recordConnect(){this.reconnectAttempts=0,this.recordPing(),delete this.disconnectedAt,s.log("ConnectionMonitor recorded connect");}recordDisconnect(){this.disconnectedAt=b(),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,i=Math.pow(1+e,Math.min(this.reconnectAttempts,10)),c=(this.reconnectAttempts===0?1:e)*Math.random();return t*1e3*i*(1+c)}reconnectIfStale(){this.connectionIsStale()&&(s.log(`ConnectionMonitor detected stale connection. reconnectAttempts = ${this.reconnectAttempts}, time stale = ${O(this.refreshedAt)} s, stale threshold = ${this.constructor.staleThreshold} s`),this.reconnectAttempts++,this.disconnectedRecently()?s.log(`ConnectionMonitor skipping reopening recent disconnect. time disconnected = ${O(this.disconnectedAt)} s`):(s.log("ConnectionMonitor reopening"),this.connection.reopen()));}get refreshedAt(){return this.pingedAt?this.pingedAt:this.startedAt}connectionIsStale(){return O(this.refreshedAt)>this.constructor.staleThreshold}disconnectedRecently(){return this.disconnectedAt&&O(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);}};g.staleThreshold=6;g.reconnectionBackoffRate=.15;var et=g;var Nt={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=Nt;var{message_types:v,protocols:M}=L,$t=M.slice(0,M.length-1),ot=[].indexOf,S=class{constructor(t){this.open=this.open.bind(this),this.consumer=t,this.subscriptions=this.consumer.subscriptions,this.monitor=new et(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=[...M,...this.consumer.subprotocols||[]];return s.log(`Opening WebSocket, current state is ${this.getState()}, subprotocols: ${t}`),this.webSocket&&this.uninstallEventHandlers(),this.webSocket=new l.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 ot.call($t,this.getProtocol())>=0}isState(...t){return ot.call(t,this.getState())>=0}getState(){if(this.webSocket){for(let t in l.WebSocket)if(l.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(){};}};S.reopenDelay=500;S.prototype.events={message(o){if(!this.isProtocolSupported())return;let{identifier:t,message:e,reason:i,reconnect:n,type:c}=JSON.parse(o.data);switch(c){case v.welcome:return this.triedToReconnect()&&(this.reconnectAttempted=!0),this.monitor.recordConnect(),this.subscriptions.reload();case v.disconnect:return s.log(`Disconnecting. Reason: ${i}`),this.close({allowReconnect:n});case v.ping:return this.monitor.recordPing();case v.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 v.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 rt=S;var Rt=function(o,t){if(t!==null)for(let e in t){let i=t[e];o[e]=i;}return o},q=class{constructor(t,e={},i){r(this,"consumer");r(this,"identifier");this.consumer=t,this.identifier=JSON.stringify(e),Rt(this,i);}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)}},it=q;var P=class{constructor(t){r(this,"subscriptions");r(this,"pendingSubscriptions");r(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);}},nt=P;var D=class{constructor(t){r(this,"consumer");r(this,"guarantor");r(this,"subscriptions");this.consumer=t,this.guarantor=new nt(this),this.subscriptions=[];}create(t,e){let i=t,n=typeof i=="object"?i:{channel:i},c=new it(this.consumer,n,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(i=>this.notify(i,t,...e))}notify(t,e,...i){let n;return typeof t=="string"?n=this.findAll(t):n=[t],n.map(c=>typeof c[e]=="function"?c[e](...i):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:i}=t;return this.consumer.send({command:e,identifier:i})}},st=D;var j=class{constructor(t){r(this,"_url");r(this,"subscriptions");r(this,"connection");r(this,"subprotocols");this._url=t,this.subscriptions=new st(this),this.connection=new rt(this),this.subprotocols=[];}get url(){return ct(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 ct(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 at=j;function lt(o=It("url")||L.default_mount_path){return new at(o)}function It(o){let t=document.head.querySelector(`meta[name='action-cable-${o}']`);if(t)return t.getAttribute("content")}var _=class extends index_js$5.ApolloLink{constructor(e){super();r(this,"cables");r(this,"channelName");r(this,"actionName");r(this,"connectionParams");this.cables={},this.channelName=e.channelName||"GraphqlChannel",this.actionName=e.actionName||"execute",this.connectionParams=e.connectionParams||{};}request(e,i){let n=h.get("session");return n?(this.cables[n]||(this.cables[n]=lt(J+(n?`?token=${n}`:""))),new index_js$5.Observable(c=>{let d=Math.round(Date.now()+Math.random()*1e5).toString(16),m=this.actionName,p=typeof this.connectionParams=="function"?this.connectionParams(e):this.connectionParams,y=this.cables[n].subscriptions.create(Object.assign({},{channel:this.channelName,channelId:d},p),{connected:()=>{y.perform(m,{query:e.query?graphql.print(e.query):null,variables:e.variables,operationId:e.operationId,operationName:e.operationName});},received:a=>{var G,W;((G=a==null?void 0:a.result)!=null&&G.data||(W=a==null?void 0:a.result)!=null&&W.errors)&&c.next(a.result),a.more||c.complete();}});return Object.assign(y,{closed:!1})})):(console.warn("QuilttLink attempted to send an unauthenticated Subscription"),null)}},pt=_;var E=class extends pt{constructor(){super({channelName:"GraphQLChannel"});}};var po=new index_js.ApolloLink(()=>null);var ut=new index_js.ApolloLink((o,t)=>(o.setContext(({headers:e={}})=>({headers:x(u({},e),{"Quiltt-Client-Version":z})})),t(o)));var ht=class extends index_js.ApolloClient{constructor(t){t.connectToDevTools||(t.connectToDevTools=k);let e=m=>m.query.definitions.some(({kind:p,operation:y})=>p==="OperationDefinition"&&y==="subscription"),i=m=>{var p;return (p=m.getContext().batchable)!=null?p:!0},n=new A,c=new E,d=index_js.ApolloLink.from([ut,n,X,tt]).split(e,c,Y).split(i,K,Z);super(u({link:d},t));}};
|
|
17
17
|
|
|
18
18
|
Object.defineProperty(exports, 'InMemoryCache', {
|
|
19
19
|
enumerable: true,
|