@data-client/vue 0.0.1 → 0.0.3

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 (48) hide show
  1. package/README.md +22 -24
  2. package/dist/index.js +112 -6
  3. package/dist/index.umd.min.js +1 -1
  4. package/lib/consumers/index.d.ts +4 -1
  5. package/lib/consumers/index.d.ts.map +1 -1
  6. package/lib/consumers/index.js +5 -2
  7. package/lib/consumers/useDebounce.d.ts +16 -0
  8. package/lib/consumers/useDebounce.d.ts.map +1 -0
  9. package/lib/consumers/useDebounce.js +50 -0
  10. package/lib/consumers/useLive.d.ts +13 -0
  11. package/lib/consumers/useLive.d.ts.map +1 -0
  12. package/lib/consumers/useLive.js +17 -0
  13. package/lib/consumers/useLoading.d.ts +18 -0
  14. package/lib/consumers/useLoading.d.ts.map +1 -0
  15. package/lib/consumers/useLoading.js +44 -0
  16. package/lib/consumers/useQuery.js +3 -3
  17. package/lib/consumers/useSubscription.js +3 -3
  18. package/lib/consumers/useSuspense.js +3 -3
  19. package/lib/context.d.ts +1 -1
  20. package/lib/context.d.ts.map +1 -1
  21. package/lib/context.js +2 -2
  22. package/package.json +1 -6
  23. package/src/__tests__/useDebounce.web.ts +264 -0
  24. package/src/__tests__/useLive.web.ts +162 -0
  25. package/src/__tests__/useLoading.web.ts +238 -0
  26. package/src/consumers/index.ts +4 -4
  27. package/src/consumers/useDebounce.ts +78 -0
  28. package/src/consumers/useLive.ts +64 -0
  29. package/src/consumers/useLoading.ts +47 -0
  30. package/src/consumers/useQuery.ts +2 -2
  31. package/src/consumers/useSubscription.ts +2 -2
  32. package/src/consumers/useSuspense.ts +2 -2
  33. package/src/context.ts +1 -1
  34. package/ts3.4/consumers/index.d.ts +4 -1
  35. package/ts3.4/consumers/useDebounce.d.ts +19 -0
  36. package/ts3.4/consumers/useLive.d.ts +19 -0
  37. package/ts3.4/consumers/useLoading.d.ts +22 -0
  38. package/ts3.4/context.d.ts +1 -1
  39. package/lib/components/DataProvider.d.ts +0 -11
  40. package/lib/components/DataProvider.d.ts.map +0 -1
  41. package/lib/components/DataProvider.js +0 -18
  42. package/lib/consumers/useInjects.d.ts +0 -5
  43. package/lib/consumers/useInjects.d.ts.map +0 -1
  44. package/lib/consumers/useInjects.js +0 -8
  45. package/src/components/DataProvider.ts +0 -26
  46. package/src/consumers/useInjects.ts +0 -12
  47. package/ts3.4/components/DataProvider.d.ts +0 -11
  48. package/ts3.4/consumers/useInjects.d.ts +0 -5
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  The scalable way to build applications with [dynamic data](https://dataclient.io/docs/getting-started/mutations).
10
10
 
11
11
  [Declarative resouce definitons](https://dataclient.io/docs/getting-started/resource) for [REST](https://dataclient.io/rest), [GraphQL](https://dataclient.io/graphql), [Websockets+SSE](https://dataclient.io/docs/concepts/managers#data-stream) and [more](https://dataclient.io/rest/api/Endpoint)
12
- <br/>[Performant rendering](https://dataclient.io/docs/getting-started/data-dependency) in [Vue 3](https://vuejs.org/), [Nuxt](https://nuxt.com/)
12
+ <br/>[Performant rendering](https://dataclient.io/docs/getting-started/data-dependency) in [Vue 3](https://vuejs.org/)
13
13
 
14
14
  Schema driven. Zero updater functions.
15
15
 
@@ -113,7 +113,7 @@ provideDataClient({
113
113
 
114
114
  <script setup lang="ts">
115
115
  const props = defineProps<{ id: string }>();
116
- const article = useSuspense(ArticleResource.get, { id: props.id });
116
+ const article = await useSuspense(ArticleResource.get, { id: props.id });
117
117
  </script>
118
118
  ```
119
119
 
@@ -272,30 +272,28 @@ const fixtures = [
272
272
 
273
273
  For the small price of 9kb gziped. &nbsp;&nbsp; [🏁Get started now](https://dataclient.io/docs/getting-started/installation)
274
274
 
275
- ## Planned Features
275
+ ## Features
276
276
 
277
277
  - [x] ![TS](./typescript.svg?sanitize=true) Strong [Typescript](https://www.typescriptlang.org/) inference
278
- - [ ] 🔄 Vue 3 [Composition API](https://vuejs.org/guide/extras/composition-api-faq.html) composables
279
- - [ ] 🏪 [Pinia](https://pinia.vuejs.org/) store integration
280
- - [ ] 💦 [Server Side Rendering](https://nuxt.com/) with Nuxt
281
- - [ ] 🎣 [Declarative API](https://dataclient.io/docs/getting-started/data-dependency)
282
- - [ ] 📝 Composition over configuration
283
- - [ ] 💰 [Normalized](https://dataclient.io/docs/concepts/normalization) caching
284
- - [ ] 💥 Tiny bundle footprint
285
- - [ ] 🛑 Automatic overfetching elimination
286
- - [ ] ✨ Fast [optimistic updates](https://dataclient.io/rest/guides/optimistic-updates)
287
- - [ ] 🧘 [Flexible](https://dataclient.io/docs/getting-started/resource) to fit any API design (one size fits all)
288
- - [ ] 🔧 [Debugging and inspection](https://dataclient.io/docs/getting-started/debugging) via browser extension
289
- - [ ] 🌳 Tree-shakable (only use what you need)
290
- - [ ] 🔁 [Subscriptions](https://dataclient.io/docs/api/useSubscription)
291
- - [ ] 📙 [Storybook mocking](https://dataclient.io/docs/guides/storybook)
292
- - [ ] 🚯 [Declarative cache lifetime policy](https://dataclient.io/docs/concepts/expiry-policy)
293
- - [ ] 🧅 [Composable middlewares](https://dataclient.io/docs/api/Manager)
294
- - [ ] 💽 Global data consistency guarantees
295
- - [ ] 🏇 Automatic race condition elimination
296
- - [ ] 👯 Global referential equality guarantees
297
-
298
- ## Planned API
278
+ - [x] 🔄 Vue 3 [Composition API](https://vuejs.org/guide/extras/composition-api-faq.html) composables
279
+ - [x] 🎣 [Declarative API](https://dataclient.io/docs/getting-started/data-dependency)
280
+ - [x] 📝 Composition over configuration
281
+ - [x] 💰 [Normalized](https://dataclient.io/docs/concepts/normalization) caching
282
+ - [x] 💥 Tiny bundle footprint
283
+ - [x] 🛑 Automatic overfetching elimination
284
+ - [x] ✨ Fast [optimistic updates](https://dataclient.io/rest/guides/optimistic-updates)
285
+ - [x] 🧘 [Flexible](https://dataclient.io/docs/getting-started/resource) to fit any API design (one size fits all)
286
+ - [x] 🔧 [Debugging and inspection](https://dataclient.io/docs/getting-started/debugging) via browser extension
287
+ - [x] 🌳 Tree-shakable (only use what you need)
288
+ - [x] 🔁 [Subscriptions](https://dataclient.io/docs/api/useSubscription)
289
+ - [x] 📙 [Storybook mocking](https://dataclient.io/docs/guides/storybook)
290
+ - [x] 🚯 [Declarative cache lifetime policy](https://dataclient.io/docs/concepts/expiry-policy)
291
+ - [x] 🧅 [Composable middlewares](https://dataclient.io/docs/api/Manager)
292
+ - [x] 💽 Global data consistency guarantees
293
+ - [x] 🏇 Automatic race condition elimination
294
+ - [x] 👯 Global referential equality guarantees
295
+
296
+ ## API
299
297
 
300
298
  - Rendering: `useSuspense()`, `useLive()`, `useCache()`, `useDLE()`, `useQuery()`, `useLoading()`, `useDebounce()`, `useCancelling()`
301
299
  - Event handling: `useController()` returns [Controller](https://dataclient.io/docs/api/Controller)
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ const ControllerKey = Symbol('DataClientController');
8
8
 
9
9
  /** Fallback state ref used when no provider is found. */
10
10
  const FallbackStateRef = vue.shallowRef(core.initialState);
11
- function injectController() {
11
+ function useController() {
12
12
  const ctrl = vue.inject(ControllerKey, null);
13
13
  if (!ctrl) {
14
14
  if (process.env.NODE_ENV !== 'production') {
@@ -31,7 +31,7 @@ function injectState() {
31
31
 
32
32
  async function useSuspense(endpoint, ...args) {
33
33
  const stateRef = injectState();
34
- const controller = injectController();
34
+ const controller = useController();
35
35
  const key = args[0] !== null ? endpoint.key(...args) : '';
36
36
  const responseMeta = vue.computed(() => controller.getResponseMeta(endpoint, ...args, stateRef.value));
37
37
 
@@ -61,7 +61,7 @@ async function useSuspense(endpoint, ...args) {
61
61
  * @see https://dataclient.io/docs/api/useSubscription
62
62
  */
63
63
  function useSubscription(endpoint, ...args) {
64
- const controller = injectController();
64
+ const controller = useController();
65
65
 
66
66
  // Track top-level reactive args (Refs are unwrapped). This allows props/refs to trigger resubscribe.
67
67
  const resolvedArgs = vue.computed(() => args.map(a => vue.unref(a)));
@@ -93,7 +93,7 @@ function useSubscription(endpoint, ...args) {
93
93
  */
94
94
  function useQuery(schema, ...args) {
95
95
  const stateRef = injectState();
96
- const controller = injectController();
96
+ const controller = useController();
97
97
 
98
98
  // Compute query meta based on state and args. This mirrors React's memoization
99
99
  // that keys off state.entities/indexes and args.
@@ -109,6 +109,110 @@ function useQuery(schema, ...args) {
109
109
  return vue.computed(() => queryMeta.value.data);
110
110
  }
111
111
 
112
+ /**
113
+ * Ensure an endpoint is available. Keeps it fresh once it is.
114
+ *
115
+ * useSuspense() + useSubscription()
116
+ * @see https://dataclient.io/docs/api/useLive
117
+ * @throws {Promise} If data is not yet available.
118
+ * @throws {NetworkError} If fetch fails.
119
+ */
120
+
121
+ async function useLive(endpoint, ...args) {
122
+ useSubscription(endpoint, ...args);
123
+ return useSuspense(endpoint, ...args);
124
+ }
125
+
126
+ /**
127
+ * Takes an async function and tracks resolution as a boolean.
128
+ *
129
+ * @see https://dataclient.io/docs/api/useLoading
130
+ * @param func A function returning a promise
131
+ * @example
132
+ ```
133
+ function Button({ onClick, children, ...props }) {
134
+ const [clickHandler, loading] = useLoading(onClick);
135
+ return h('button', { onClick: clickHandler, ...props },
136
+ loading.value ? 'Loading...' : children
137
+ );
138
+ }
139
+ ```
140
+ */
141
+ function useLoading(func) {
142
+ const loading = vue.ref(false);
143
+ const error = vue.ref(undefined);
144
+ const isMounted = vue.ref(true);
145
+ vue.onUnmounted(() => {
146
+ isMounted.value = false;
147
+ });
148
+
149
+ // Create the wrapped function directly - no need for computed in Vue
150
+ const wrappedFunc = async (...args) => {
151
+ loading.value = true;
152
+ error.value = undefined;
153
+ let ret;
154
+ try {
155
+ ret = await func(...args);
156
+ } catch (e) {
157
+ error.value = e;
158
+ } finally {
159
+ if (isMounted.value) {
160
+ loading.value = false;
161
+ }
162
+ }
163
+ return ret;
164
+ };
165
+ return [wrappedFunc, loading, error];
166
+ }
167
+
168
+ /**
169
+ * Keeps value updated after delay time
170
+ *
171
+ * @see https://dataclient.io/docs/api/useDebounce
172
+ * @param value Any immutable value (can be a ref)
173
+ * @param delay Time in milliseconds to wait til updating the value
174
+ * @param updatable Whether to update at all
175
+ * @example
176
+ ```
177
+ const [debouncedQuery, isPending] = useDebounce(query, 200);
178
+ const list = useSuspense(getThings, { query: debouncedQuery.value });
179
+ ```
180
+ */
181
+ function useDebounce(value, delay, updatable = true) {
182
+ const debouncedValue = vue.ref(typeof value === 'object' && value !== null && 'value' in value ? value.value : value);
183
+ const isPending = vue.ref(false);
184
+ let timeoutId = null;
185
+ const clearExistingTimeout = () => {
186
+ if (timeoutId !== null) {
187
+ clearTimeout(timeoutId);
188
+ timeoutId = null;
189
+ }
190
+ };
191
+
192
+ // Watch the input value and debounce updates
193
+ vue.watch([() => typeof value === 'object' && value !== null && 'value' in value ? value.value : value, () => typeof updatable === 'object' && updatable !== null && 'value' in updatable ? updatable.value : updatable, () => delay], ([newValue, isUpdatable]) => {
194
+ clearExistingTimeout();
195
+ if (!isUpdatable) {
196
+ isPending.value = false;
197
+ return;
198
+ }
199
+ isPending.value = true;
200
+ timeoutId = setTimeout(() => {
201
+ debouncedValue.value = newValue;
202
+ isPending.value = false;
203
+ timeoutId = null;
204
+ }, delay);
205
+ }, {
206
+ immediate: false
207
+ });
208
+
209
+ // Cleanup on unmount
210
+ vue.onUnmounted(() => {
211
+ clearExistingTimeout();
212
+ });
213
+ return [debouncedValue, isPending];
214
+ }
215
+
112
216
  /* istanbul ignore next */
113
217
  /** Returns the default Managers used by DataProvider. */
114
218
  exports.getDefaultManagers = (options = {}) => {
@@ -283,8 +387,10 @@ Object.defineProperty(exports, "actionTypes", {
283
387
  get: function () { return core.actionTypes; }
284
388
  });
285
389
  exports.provideDataClient = provideDataClient;
286
- exports.useController = injectController;
390
+ exports.useController = useController;
391
+ exports.useDebounce = useDebounce;
392
+ exports.useLive = useLive;
393
+ exports.useLoading = useLoading;
287
394
  exports.useQuery = useQuery;
288
- exports.useStateRef = injectState;
289
395
  exports.useSubscription = useSubscription;
290
396
  exports.useSuspense = useSuspense;
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("vue")):"function"==typeof define&&define.amd?define(["exports","vue"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).VDC={},e.Vue)}(this,(function(e,t){"use strict";class n{constructor(){this.localCache=new Map}getEntity(e,t,n,s){const i=t.key;this.localCache.has(i)||this.localCache.set(i,new Map);const r=this.localCache.get(i);return r.get(e)||s(r),r.get(e)}getResults(e,t,n){return{data:n(),paths:[]}}}const s=Symbol("INVALID"),i={};function r(e){return null!==e&&void 0!==e.pk}const o=e=>e[0],a=e=>void 0!==e&&"symbol"!=typeof e,c=(e,t,n,s,i,r)=>{e=o(e);const a=(e=>Array.isArray(e)?e:Object.keys(e).map((t=>e[t])))(t);return a.map((t=>r(e,t,n,s,i)))},l=(e,t,n,s)=>(e=o(e),t.map?t.map((t=>s(e,t))).filter(a):t);function h(){}function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var s in n)({}).hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},u.apply(null,arguments)}const d=(e,t,n,s,i,r)=>{const o=u({},t);return Object.keys(e).forEach((n=>{const s=e[n],a=r(s,t[n],t,n,i);void 0===a?delete o[n]:o[n]=a})),o},p=(e,t,n,i)=>{if(function(e){return!("function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}(t))return function(e,t,n,i){let r=!1;const o=Object.keys(e).reduce(((t,n)=>{const s=`${n}`,o=i(e[s],t.get(s));return"symbol"==typeof o&&(r=!0),t.has(s)?t.set(s,o):t}),t);return r?s:o}(e,t,0,i);const r=u({},t);let o=!1;return Object.keys(e).forEach((t=>{const n=i(e[t],r[t]);void 0!==r[t]&&(r[t]=n),"symbol"==typeof n&&(o=!0)})),o?s:r};function f(e,t,n,s){const i={};for(const r of Object.keys(e))i[r]=n(e[r],t,s);return i}const y=(e,t,n,s)=>function(r,o){const a="object"!=typeof o,c=a?e({key:r.key,pk:o}):o;if("symbol"==typeof c)return r.denormalize(c,n,s);if(void 0===c&&a&&""!==o&&"undefined"!==o)return t.getEntity(o,r,i,(e=>{e.set(o,void 0)}));if("object"!=typeof c||null===c)return c;let l=a?o:r.pk(c,void 0,void 0,n);return void 0===l||""===l||"undefined"===l?function(e){const t=new Map;return e(t),t.get("")}((e=>g(r,c,"",e,n,s))):("string"!=typeof l&&(l=`${l}`),t.getEntity(l,r,c,(e=>g(r,c,l,e,n,s))))};function g(e,t,n,i,r,o){const a=e.createIfValid(t);void 0===a?i.set(n,s):(i.set(n,a),i.set(n,e.denormalize(a,r,o)))}const m=(e,t,n)=>{const s=y(e,t,n,i);function i(e,t){if(!e)return t;if(null==t)return t;if("function"==typeof e.denormalize)return r(e)?s(e,t):e.denormalize(t,n,i);if("function"==typeof e)return e(t);if("object"==typeof e){return(Array.isArray(e)?l:p)(e,t,n,i)}return t}return(e,n)=>{const s=Object(n)===n&&Object(e)===e;return t.getResults(n,s,(()=>i(e,n)))}};class v{constructor({entities:e,indexes:t}){this.entities=e,this.indexes=t}tracked(e){const t=this,n=[{path:[""],entity:e}];return[{INVALID:s,getIndex(...e){const s=t.getIndex(...e);return n.push({path:e,entity:s}),t.getIndexEnd(s,e[2])},getEntity(...e){const s=t.getEntity(...e);return n.push({path:e,entity:s}),s},getEntities(e){const s=t.getEntitiesObject(e);return n.push({path:[e],entity:s}),t.getEntities(e)}},n]}}class E extends v{constructor(e){super(e)}getEntitiesObject(e){return this.entities[e]}getEntities(e){const t=this.entities[e];if(void 0!==t)return{keys:()=>Object.keys(t),entries:()=>Object.entries(t)}}getEntity(e,t){var n;return null==(n=this.entities[e])?void 0:n[t]}getIndex(e,t){var n;return null==(n=this.indexes[e])?void 0:n[t]}getIndexEnd(e,t){return null==e?void 0:e[t]}}const w={QueryDelegate:E,getEntities:e=>({key:t,pk:n})=>{var s;return null==(s=e[t])?void 0:s[n]}};class b{constructor(){this.next=new WeakMap,this.nextPath=void 0}get(e,t){let n=this.next.get(e);if(!n)return x;for(;n.nextPath;){var s;const e=null!=(s=t(n.nextPath))?s:i;if(n=n.next.get(e),!n)return x}return[n.value,n.journey]}set(e,t){if(e.length<1)throw new I;let n=this;for(const{path:t,entity:s}of e){let e=n.next.get(s);e||(e=new k,n.next.set(null!=s?s:i,e)),n.nextPath=t,n=e}n.nextPath=void 0,n.value=t,n.journey=e.map((e=>e.path))}}const x=[void 0,void 0];class k{constructor(){this.next=new WeakMap,this.nextPath=void 0,this.value=void 0,this.journey=[]}}class I extends Error{constructor(...e){super(...e),this.message="Keys must include at least one member"}}class L extends E{constructor(e,t){super(e),this.newEntities=new Map,this.newIndexes=new Map,this.entitiesMeta=e.entitiesMeta,this.meta=t,this.checkLoop=function(){const e=new Map;return function(t,n,s){e.has(t)||e.set(t,new Map);const i=e.get(t);i.has(n)||i.set(n,[]);const r=i.get(n);return!!r.some((e=>e===s))||(r.push(s),!1)}}()}getNewEntity(e,t){return this.getNewEntities(e).get(t)}getNewEntities(e){return this.newEntities.has(e)||(this.newEntities.set(e,new Map),this.entities[e]=u({},this.entities[e]),this.entitiesMeta[e]=u({},this.entitiesMeta[e])),this.newEntities.get(e)}getNewIndexes(e){return this.newIndexes.has(e)||(this.newIndexes.set(e,new Map),this.indexes[e]=u({},this.indexes[e])),this.newIndexes.get(e)}mergeEntity(e,t,n){const s=e.key;let i=n,r=this.meta,o=this.getNewEntity(s,t);if(o)i=e.merge(o,n);else if(o=this.getEntity(s,t),o){const a=this.getMeta(s,t);i=e.mergeWithStore(a,r,o,n),r=e.mergeMetaWithStore(a,r,o,n)}this.setEntity(e,t,i,r)}setEntity(e,t,n,i=this.meta){const r=e.key,o=this.getNewEntities(r),a=!o.has(t);o.set(t,n),e.indexes&&function(e,t,n,i,r,o){for(const a of t){n.has(a)||n.set(a,i[a]={});const t=n.get(a);o[e]&&delete t[o[e][a]],o&&o[e]&&o[e][a]!==r[a]&&(t[o[e][a]]=s),a in r&&(t[r[a]]=e)}}(t,e.indexes,this.getNewIndexes(r),this.indexes[r],n,this.entities[r]),this._setEntity(r,t,n),a&&this._setMeta(r,t,i)}invalidate(e,t){this.setEntity(e,t,s)}_setEntity(e,t,n){this.entities[e][t]=n}_setMeta(e,t,n){this.entitiesMeta[e][t]=n}getMeta(e,t){return this.entitiesMeta[e][t]}}const S=(e,t,n=[],{entities:s,indexes:i,entitiesMeta:r}=A,o={fetchedAt:0,date:Date.now(),expiresAt:1/0})=>{if(null==e)return{result:t,entities:s,indexes:i,entitiesMeta:r};const a=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(e);if(null===t||typeof t!==a&&(void 0===e.key||void 0!==e.pk||"string"!=typeof t))throw new Error(`Unexpected input given to normalize. Expected type to be "${a}", found "${null===t?"null":typeof t}".`);const l={result:"",entities:u({},s),indexes:u({},i),entitiesMeta:u({},r)},h=(e=>{const t=(n,s,i,r,o)=>s&&n?n.normalize&&"function"==typeof n.normalize?"object"!=typeof s?n.pk?`${s}`:s:n.normalize(s,i,r,o,t,e):"object"!=typeof s||"object"!=typeof n?s:(Array.isArray(n)?c:d)(n,s,i,r,o,t):s;return t})(new L(l,o));return l.result=h(e,t,t,void 0,n),l};const A={entities:{},indexes:{},entitiesMeta:{}};class M{constructor(e,t,n){this.dependencies=[],this.cycleCache=new Map,this.cycleIndex=-1,this.localCache=new Map,this._getEntity=e,this._getCache=t,this._resultCache=n}getEntity(e,t,n,s){const i=t.key,{localCacheKey:r,cycleCacheKey:o}=this.getCacheKey(i);if(r.get(e))o.has(e)?this.cycleIndex=o.get(e):this.dependencies.push({path:{key:i,pk:e},entity:n});else{const a=this._getCache(e,t),[c,l]=a.get(n,this._getEntity);if(l)return r.set(e,c.value),this.dependencies.push(...c.dependencies),c.value;{const t=this.dependencies.length;o.set(e,t),this.dependencies.push({path:{key:i,pk:e},entity:n}),s(r),o.delete(e);const c=this.dependencies.slice(-1===this.cycleIndex?t:this.cycleIndex),l={dependencies:c,value:r.get(e)};a.set(c,l),this.cycleIndex===t&&(this.cycleIndex=-1)}}return r.get(e)}getCacheKey(e){this.localCache.has(e)||this.localCache.set(e,new Map),this.cycleCache.has(e)||this.cycleCache.set(e,new Map);return{localCacheKey:this.localCache.get(e),cycleCacheKey:this.cycleCache.get(e)}}getResults(e,t,n){if(!t)return{data:n(),paths:this.paths()};let[s,i]=this._resultCache.get(e,this._getEntity);return void 0===i?(s=n(),i=this.paths(),this.dependencies.unshift({path:{key:"",pk:""},entity:e}),this._resultCache.set(this.dependencies,s)):i.shift(),{data:s,paths:i}}paths(){return this.dependencies.map((e=>e.path))}}function O(e){return void 0!==e&&(!(e&&"object"==typeof e&&!Array.isArray(e))||Object.values(e).every(O))}class R{constructor(e=w){var t;this.endpoints=new b,this.queryKeys=new Map,this.policy=e,this._getCache=(t=new Map,(e,n)=>{var s;const i=n.key,r=null!=(s=n.cacheWith)?s:n;t.has(i)||t.set(i,new Map);const o=t.get(i);o.has(e)||o.set(e,new WeakMap);const a=o.get(e);let c=a.get(r);return c||(c=new b,a.set(r,c)),c})}denormalize(e,t,n,s=[]){if(void 0===e)return{data:t,paths:[]};if(void 0===t)return{data:void 0,paths:[]};const i=this.policy.getEntities(n);return m(i,new M(i,this._getCache,this.endpoints),s)(e,t)}query(e,t,n,s=JSON.stringify(t)){const i=this.buildQueryKey(e,t,n,s);return i?this.denormalize(e,i,n.entities,t):{data:void 0,paths:[]}}buildQueryKey(e,t,n,s=JSON.stringify(t)){if("object"!=typeof e&&"function"!=typeof e.queryKey||!e)return e;this.queryKeys.get(s)||this.queryKeys.set(s,new b);const i=this.queryKeys.get(s),r=new this.policy.QueryDelegate(n);let[o,a]=i.get(e,(c=r,e=>c[["","getEntitiesObject","getEntity","getIndex"][e.length]](...e)));var c;if(!a){const[n,s]=r.tracked(e);o=function(e){return function t(n,s){return function(e){return!!e&&"function"==typeof e.queryKey}(n)?n.queryKey(s,t,e):"object"==typeof n&&n?(Array.isArray(n)?h:f)(n,s,t,e):n}}(n)(e,t),i.set(s,o)}return o}}var C={Invalid:1,InvalidIfStale:2,Valid:3};function _(e,t){const n=Date.now();return{fetchedAt:null!=t?t:n,date:n,expiresAt:n+e}}const P="rdc/fetch",j="rdc/set",T="rdc/setresponse",q="rdc/optimistic",D="rdc/reset",N="rdc/subscribe",K="rdc/unsubscribe",H="rdc/invalidate",z="rdc/invalidateall",V="rdc/expireall",F="rdc/gc",B=P,U=j,Y=T,Q=q,$=D,W=N,X=K,J=H,G=z,Z=V,ee=F;var te=Object.freeze({__proto__:null,EXPIREALL:V,EXPIREALL_TYPE:Z,FETCH:P,FETCH_TYPE:B,GC:F,GC_TYPE:ee,INVALIDATE:H,INVALIDATEALL:z,INVALIDATEALL_TYPE:G,INVALIDATE_TYPE:J,OPTIMISTIC:q,OPTIMISTIC_TYPE:Q,RESET:D,RESET_TYPE:$,SET:j,SET_RESPONSE:T,SET_RESPONSE_TYPE:Y,SET_TYPE:U,SUBSCRIBE:N,SUBSCRIBE_TYPE:W,UNSUBSCRIBE:K,UNSUBSCRIBE_TYPE:X});function ne(e,t){if(t.endpoint.getOptimisticResponse&&t.endpoint.sideEffect){const o=(n=t.endpoint,s=t.args,i=t.meta.fetchedAt,{type:q,key:n.key(...s),args:s,endpoint:n,meta:_(null!=(r=n.dataExpiryLength)?r:6e4,i)});return u({},e,{optimistic:[...e.optimistic,o]})}var n,s,i,r;return e}class se extends Error{}function ie(e,t,n){return"AbortError"===n.name?u({},e,{optimistic:re(e,t)}):u({},e,{meta:u({},e.meta,{[t.key]:{date:t.meta.date,fetchedAt:t.meta.fetchedAt,expiresAt:t.meta.expiresAt,error:n,errorPolicy:null==t.endpoint.errorPolicy?void 0:t.endpoint.errorPolicy(n)}}),optimistic:re(e,t)})}function re(e,t){return e.optimistic.filter((e=>e.key!==t.key||(e.type===q?e.meta.fetchedAt!==t.meta.fetchedAt:e.meta.date>t.meta.date)))}function oe(e){return function(t,n){switch(t||(t=ae),n.type){case F:return n.entities.forEach((({key:e,pk:n})=>{var s,i;null==(s=t.entities[e])||delete s[n],null==(i=t.entitiesMeta[e])||delete i[n]})),n.endpoints.forEach((e=>{delete t.endpoints[e],delete t.meta[e]})),t;case P:return ne(t,n);case q:case T:return function(e,t,n){if(t.error)return ie(e,t,t.response);try{var s;let i;if(t.type===q){if(!t.endpoint.getOptimisticResponse)return e;try{i=t.endpoint.getOptimisticResponse.call(t.endpoint,n.snapshot(e,t.meta.fetchedAt),...t.args)}catch(t){if(t.constructor===se)return e;throw t}}else i=t.response;const{result:r,entities:o,indexes:a,entitiesMeta:c}=S(t.endpoint.schema,i,t.args,e,t.meta),l=u({},e.endpoints,{[t.key]:r});try{if(t.endpoint.update){const e=t.endpoint.update(r,...t.args);Object.keys(e).forEach((t=>{l[t]=e[t](l[t])}))}}catch(e){console.error(`The following error occured during Endpoint.update() for ${t.key}`),console.error(e)}return{entities:o,endpoints:l,indexes:a,meta:u({},e.meta,{[t.key]:{date:t.meta.date,fetchedAt:t.meta.fetchedAt,expiresAt:t.meta.expiresAt,prevExpiresAt:null==(s=e.meta[t.key])?void 0:s.expiresAt}}),entitiesMeta:c,optimistic:re(e,t),lastReset:e.lastReset}}catch(n){return"object"==typeof n&&(n.message=`Error processing ${t.key}\n\nFull Schema: ${JSON.stringify(t.endpoint.schema,void 0,2)}\n\nError:\n${n.message}`,"response"in t&&(n.response=t.response),n.status=400),ie(e,t,n)}}(t,n,e);case j:return function(e,t,n){let s;if("function"==typeof t.value){const i=n.get(t.schema,...t.args,e);if(void 0===i)return e;s=t.value(i)}else s=t.value;try{const{entities:n,indexes:i,entitiesMeta:r}=S(t.schema,s,t.args,e,t.meta);return{entities:n,endpoints:e.endpoints,indexes:i,meta:e.meta,entitiesMeta:r,optimistic:e.optimistic,lastReset:e.lastReset}}catch(t){return e}}(t,n,e);case z:case H:return function(e,t){const n=u({},e.endpoints),s=u({},e.meta),i=e=>{delete n[e];const t=u({},s[e],{expiresAt:0,invalidated:!0});delete t.error,s[e]=t};return t.type===H?i(t.key):Object.keys(n).forEach((e=>{t.testKey(e)&&i(e)})),u({},e,{endpoints:n,meta:s})}(t,n);case V:return function(e,t){const n=u({},e.meta);return Object.keys(n).forEach((e=>{t.testKey(e)&&(n[e]=u({},n[e],{expiresAt:1}))})),u({},e,{meta:n})}(t,n);case D:return u({},ae,{lastReset:n.date});default:return t}}}const ae={entities:{},endpoints:{},indexes:{},meta:{},entitiesMeta:{},optimistic:[],lastReset:0};const ce="undefined"!=typeof FormData?e=>e instanceof FormData?Object.fromEntries(e.entries()):e:e=>e;function le(e,{args:t,fetchedAt:n,response:s,error:i=!1}){var r,o;const a=i?null!=(r=e.errorExpiryLength)?r:1e3:null!=(o=e.dataExpiryLength)?o:6e4;return{type:T,key:e.key(...t),response:s,args:t.map(ce),endpoint:e,meta:_(a,n),error:i}}class he{init(){}cleanup(){}createCountRef(){return()=>()=>{}}}function ue(e,t){return e.meta[t]}const de=e=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")},pe=()=>ae;class fe{constructor({dispatch:e=de,getState:t=pe,memo:s=new R,gcPolicy:i=new he}={}){this.fetch=(e,...t)=>{const s=function(e,{args:t}){let n=0,s=0;const i=new Promise(((e,t)=>{[n,s]=[e,t]})),r={fetchedAt:Date.now(),resolve:n,reject:s,promise:i};return{type:P,key:e.key(...t),args:t,endpoint:e,meta:r}}(e,{args:t});return this.dispatch(s),e.schema?s.meta.promise.then((s=>function(e,t,s,i=[]){return void 0===e||void 0===t?t:m(w.getEntities(s),new n,i)(e,t).data}(e.schema,s,{},t))):s.meta.promise},this.fetchIfStale=(e,...t)=>{const{data:n,expiresAt:s,expiryStatus:i}=this.getResponseMeta(e,...t,this.getState());return i!==C.Invalid&&Date.now()<=s?n:this.fetch(e,...t)},this.invalidate=(e,...t)=>null!==t[0]?this.dispatch(function(e,{args:t}){return{type:H,key:e.key(...t)}}(e,{args:t})):Promise.resolve(),this.invalidateAll=e=>this.dispatch({type:z,testKey:t=>e.testKey(t)}),this.expireAll=e=>this.dispatch({type:V,testKey:t=>e.testKey(t)}),this.resetEntireStore=()=>this.dispatch({type:D,date:Date.now()}),this.setResponse=(e,...t)=>{const n=t[t.length-1],s=le(e,{args:t.slice(0,t.length-1),response:n});return this.dispatch(s)},this.setError=(e,...t)=>{const n=t[t.length-1],s=le(e,{args:t.slice(0,t.length-1),response:n,error:!0});return this.dispatch(s)},this.resolve=(e,t)=>this.dispatch(le(e,t)),this.subscribe=(e,...t)=>null!==t[0]?this.dispatch(function(e,{args:t}){return{type:N,key:e.key(...t),args:t,endpoint:e}}(e,{args:t})):Promise.resolve(),this.unsubscribe=(e,...t)=>null!==t[0]?this.dispatch(function(e,{args:t}){return{type:K,key:e.key(...t),args:t,endpoint:e}}(e,{args:t})):Promise.resolve(),this.snapshot=(e,t)=>new ge(this,e,t),this._dispatch=e,this.getState=t,this.memo=s,this.gcPolicy=i}set dispatch(e){this._dispatch=e}get dispatch(){return this._dispatch}bindMiddleware({dispatch:e,getState:t}){this._dispatch=e,this.getState=t}set(e,...t){const n=t[t.length-1],s=function(e,{args:t,fetchedAt:n,value:s}){return{type:j,value:s,args:t.map(ce),schema:e,meta:_(6e4,n)}}(e,{args:t.slice(0,t.length-1),value:n});return this.dispatch(s)}getError(e,...t){if(null===t[0])return;const n=t[t.length-1],s=t.slice(0,t.length-1),i=e.key(...s),r=ue(n,i);return void 0===n.endpoints[i]||"soft"!==(null==r?void 0:r.errorPolicy)?null==r?void 0:r.error:void 0}getResponse(e,...t){return this.getResponseMeta(e,...t)}getResponseMeta(e,...t){const n=t[t.length-1],s=t.slice(0,t.length-1).map(ce),i=1!==s.length||null!==s[0],r=i?e.key(...s):"",o=i?n.endpoints[r]:void 0,a=e.schema,c=ue(n,r);let l=null==c?void 0:c.expiresAt;const h=void 0===o&&void 0!==a,u=h?this.memo.buildQueryKey(a,s,n,r):o;if(!i)return{data:u,expiryStatus:C.Valid,expiresAt:1/0,countRef:()=>()=>{}};let d=!1;if(h)d=!O(u);else if(!a||!ye(a))return{data:o,expiryStatus:this.getExpiryStatus(!o,!!e.invalidIfStale,c),expiresAt:l||0,countRef:this.gcPolicy.createCountRef({key:r})};const{data:p,paths:f}=this.memo.denormalize(a,u,n.entities,s);return l||(l=d?1:function(e,t){let n=1/0;for(const{key:i,pk:r}of e){var s;const e=null==(s=t[i])||null==(s=s[r])?void 0:s.expiresAt;e<n&&(n=e)}return n}(f,n.entitiesMeta)),{data:p,expiryStatus:this.getExpiryStatus("symbol"==typeof p,!!e.invalidIfStale||d,c),expiresAt:l,countRef:this.gcPolicy.createCountRef({key:r,paths:f})}}get(e,...t){const n=t[t.length-1],s=t.slice(0,t.length-1).map(ce),{data:i}=this.memo.query(e,s,n);return"symbol"==typeof i?void 0:i}getQueryMeta(e,...t){const n=t[t.length-1],s=t.slice(0,t.length-1).map(ce),{data:i,paths:r}=this.memo.query(e,s,n);return{data:"symbol"==typeof i?void 0:i,countRef:this.gcPolicy.createCountRef({paths:r})}}getExpiryStatus(e,t,n={}){return n.invalidated||e&&!n.error?C.Invalid:e||t?C.InvalidIfStale:C.Valid}}function ye(e){if(r(e))return!0;if(Array.isArray(e))return 0!==e.length&&ye(e[0]);if(e&&("object"==typeof e||"function"==typeof e)){const t="schema"in e?e.schema:e;return"function"==typeof t?ye(t):Object.values(t).some((e=>ye(e)))}return!1}class ge{constructor(e,t,n=0){this.state=void 0,this.controller=void 0,this.fetchedAt=void 0,this.abort=ge.abort,this.state=t,this.controller=e,this.fetchedAt=n}getResponse(e,...t){return this.controller.getResponse(e,...t,this.state)}getResponseMeta(e,...t){return this.controller.getResponseMeta(e,...t,this.state)}getError(e,...t){return this.controller.getError(e,...t,this.state)}get(e,...t){return this.controller.get(e,...t,this.state)}getQueryMeta(e,...t){return this.controller.getQueryMeta(e,...t,this.state)}}ge.abort=new se;class me extends Error{constructor(){super("Aborted due to RESET"),this.name="ResetError"}}class ve{constructor({dataExpiryLength:e=6e4,errorExpiryLength:t=1e3}={}){this.fetching=new Map,this.controller=new fe,this.middleware=e=>(this.controller=e,t=>n=>{switch(n.type){case P:return this.handleFetch(n),void 0!==n.endpoint.getOptimisticResponse&&n.endpoint.sideEffect?t(n):Promise.resolve();case T:return t(n).then((()=>{if(this.fetching.has(n.key)){var t;const s=null==(t=e.getState().meta[n.key])?void 0:t.error;s?this.handleSet(le(n.endpoint,{args:n.args,response:s,fetchedAt:n.meta.fetchedAt,error:!0})):this.handleSet(n)}}));case D:{const e=Array.from(this.fetching.values());return this.clearAll(),t(n).then((()=>{for(const{reject:t}of e)t(new me)}))}default:return t(n)}}),this.dataExpiryLength=e,this.errorExpiryLength=t}init(){delete this.cleanupDate}cleanup(){this.cleanupDate=Date.now()}skipLogging(e){return e.type===P&&this.fetching.has(e.key)}allSettled(){if(this.fetching.size)return Promise.allSettled(this.fetching.values().map((({promise:e})=>e)))}clearAll(){for(const e of this.fetching.keys())this.clear(e)}clear(e){this.fetching.has(e)&&(this.fetching.get(e).promise.catch((()=>{})),this.fetching.delete(e))}getLastReset(){return this.cleanupDate?this.cleanupDate:this.controller.getState().lastReset}handleFetch(e){const{resolve:t,reject:n,fetchedAt:s}=e.meta,i=!e.endpoint.sideEffect,r=()=>{let r=e.endpoint(...e.args);return i||(r=(e=>e.then((e=>(t(e),e))).catch((e=>{throw n(e),e})))(r)),r=r.then((t=>{let n=this.getLastReset();return s>=n&&this.controller.resolve(e.endpoint,{args:e.args,response:t,fetchedAt:s}),t})).catch((t=>{const n=this.getLastReset();throw s>=n&&this.controller.resolve(e.endpoint,{args:e.args,response:t,fetchedAt:s,error:!0}),t})),r};return i?this.throttle(e.key,r,s).then((e=>t(e))).catch((e=>n(e))):r().catch((()=>{}))}handleSet(e){if(this.fetching.has(e.key)){const{reject:t,resolve:n}=this.fetching.get(e.key);e.error?t(e.response):n(e.response),this.clear(e.key)}}throttle(e,t,n){const s=this.getLastReset();let i=this.fetching.get(e);return i&&i.fetchedAt>s||(i=function(e){const t={fetchedAt:e};return t.promise=new Promise(((e,n)=>{t.resolve=e,t.reject=n})),t}(n),this.fetching.set(e,i),this.idleCallback((()=>{t().catch((()=>null))}),{timeout:500})),i.promise}idleCallback(e,t){e()}}class Ee{isOnline(){return void 0===navigator.onLine||navigator.onLine}addOnlineListener(e){addEventListener("online",e)}removeOnlineListener(e){removeEventListener("online",e)}addOfflineListener(e){addEventListener("offline",e)}removeOfflineListener(e){removeEventListener("offline",e)}}class we{isOnline(){return!0}addOnlineListener(){}removeOnlineListener(){}addOfflineListener(){}removeOfflineListener(){}}e.DefaultConnectionListener=void 0,"undefined"!=typeof navigator&&"function"==typeof addEventListener?e.DefaultConnectionListener=Ee:e.DefaultConnectionListener=we;class be{constructor(t,n,s){if(this.frequencyHistogram=new Map,this.offlineListener=()=>{this.cleanup(),this.connectionListener.addOnlineListener(this.onlineListener)},this.onlineListener=()=>{this.connectionListener.removeOnlineListener(this.onlineListener);const e=Date.now();this.startId=setTimeout((()=>{this.startId&&(delete this.startId,this.update(),this.run())}),Math.max(0,this.lastFetchTime()-e+this.frequency)),this.connectionListener.addOfflineListener(this.offlineListener)},void 0===t.endpoint.pollFrequency)throw new Error("frequency needed for polling subscription");this.endpoint=t.endpoint,this.frequency=t.endpoint.pollFrequency,this.args=t.args,this.key=t.key,this.frequencyHistogram.set(this.frequency,1),this.controller=n,this.connectionListener=s||new e.DefaultConnectionListener,this.connectionListener.isOnline()?this.onlineListener():this.offlineListener()}add(e){void 0!==e&&(this.frequencyHistogram.has(e)?this.frequencyHistogram.set(e,this.frequencyHistogram.get(e)+1):(this.frequencyHistogram.set(e,1),e<this.frequency&&(this.frequency=e,this.run())))}remove(e){if(void 0===e)return!1;if(this.frequencyHistogram.has(e)&&(this.frequencyHistogram.set(e,this.frequencyHistogram.get(e)-1),this.frequencyHistogram.get(e)<1)){if(this.frequencyHistogram.delete(e),0===this.frequencyHistogram.size)return this.cleanup(),!0;e<=this.frequency&&(this.frequency=Math.min(...this.frequencyHistogram.keys()),this.run())}return!1}cleanup(){this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId),this.lastIntervalId&&(clearInterval(this.lastIntervalId),delete this.lastIntervalId),this.startId&&(clearTimeout(this.startId),delete this.startId),this.connectionListener.removeOnlineListener(this.onlineListener),this.connectionListener.removeOfflineListener(this.offlineListener)}update(){const e=this.endpoint,t=function(...t){return e.call(this,...t)};Object.assign(t,this.endpoint),t.dataExpiryLength=this.frequency/2,t.errorExpiryLength=this.frequency/10,t.errorPolicy=()=>"soft",t.key=()=>this.key,this.controller.fetch(t,...this.args).catch((()=>null))}run(){this.startId||(this.intervalId&&(this.lastIntervalId=this.intervalId),this.intervalId=setInterval((()=>{this.lastIntervalId&&(clearInterval(this.lastIntervalId),delete this.lastIntervalId),this.intervalId&&this.update()}),this.frequency))}lastFetchTime(){var e,t;return null!=(e=null==(t=this.controller.getState().meta[this.key])?void 0:t.date)?e:0}}class xe{constructor(e){this.subscriptions={},this.controller=new fe,this.middleware=e=>(this.controller=e,e=>t=>{switch(t.type){case N:try{this.handleSubscribe(t)}catch(e){console.error(e)}return Promise.resolve();case K:return this.handleUnsubscribe(t),Promise.resolve();default:return e(t)}}),this.Subscription=e}cleanup(){for(const e in this.subscriptions)this.subscriptions[e].cleanup()}handleSubscribe(e){const t=e.key;if(t in this.subscriptions){const n=e.endpoint.pollFrequency;this.subscriptions[t].add(n)}else this.subscriptions[t]=new this.Subscription(e,this.controller)}handleUnsubscribe(e){const t=e.key;if(t in this.subscriptions){const n=e.endpoint.pollFrequency;this.subscriptions[t].remove(n)&&delete this.subscriptions[t]}}}let ke={};class Ie{constructor(e,t){this.started=!1,this.actions=[],this.maxBufferLength=100,this.devTools="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__.connect(u({},ke,e)),null!=e&&e.maxAge&&(this.maxBufferLength=2*e.maxAge),t&&(this.skipLogging=t)}handleAction(e,t){this.started?this.devTools.send(e,t):(this.actions.length>this.maxBufferLength&&(this.actions=this.actions.slice(this.maxBufferLength/2)),this.actions.push([e,t]))}init(e){}cleanup(){}}Ie.prototype.middleware=()=>e=>t=>e(t);const Le=Symbol("DataClientState"),Se=Symbol("DataClientController"),Ae=t.shallowRef(ae);function Me(){const e=t.inject(Se,null);return e||new fe}function Oe(){const e=t.inject(Le,null);return e||Ae}let Re=(e={})=>{const{networkManager:t,subscriptionManager:n=be}=e;return null===n?[Ce(ve,null!=t?t:{})]:[Ce(ve,null!=t?t:{}),Ce(xe,n)]};function Ce(e,t){return t instanceof e?t:new e(t)}e.Controller=fe,e.DevToolsManager=Ie,e.ExpiryStatus=C,e.LogoutManager=class{constructor({handleLogout:e,shouldLogout:t}={}){this.middleware=e=>t=>async n=>{await t(n),n.type===T&&n.error&&this.shouldLogout(n.response)&&this.handleLogout(e)},e&&(this.handleLogout=e),t&&(this.shouldLogout=t)}cleanup(){}shouldLogout(e){return 401===e.status}handleLogout(e){e.resetEntireStore()}},e.NetworkManager=ve,e.PollingSubscription=be,e.SubscriptionManager=xe,e.actionTypes=te,e.getDefaultManagers=Re,e.provideDataClient=function(e={}){var n,s;const{Controller:i=fe,gcPolicy:r}=e,o=new i({gcPolicy:r}),a=null!=(n=e.managers)?n:Re(),c=null!=(s=e.initialState)?s:ae,l=function(e,t,n){return()=>(e.forEach((e=>{null==e.init||e.init(n)})),t.gcPolicy.init(t),()=>{e.forEach((e=>{e.cleanup()})),t.gcPolicy.cleanup()})}(a,o,c),h=function(e,t){return e.map(((e,n)=>(e.middleware||(e.middleware=null==e.getMiddleware?void 0:e.getMiddleware()),s=>(0===n&&t.bindMiddleware(s),e.middleware(t)))))}(a,o),u=oe(o),d=t.shallowRef(c),p=t.shallowRef(w(c));let f=null;const y=()=>d.value,g=h.map((e=>e({getState:y,dispatch:e=>m(e)}))),m=(v=g,e=>v.reduceRight(((e,t)=>t(e)),e))((async e=>{const t=new Promise((e=>{f=e}));return await(async e=>{const t=u(d.value,e);if(d.value=t,p.value=w(t),f){const e=f;f=null,e()}})(e),t}));var v;let E;return o.bindMiddleware({getState:y,dispatch:e=>m(e)}),t.provide(Le,p),t.provide(Se,o),t.onMounted((()=>{E=l()})),t.onUnmounted((()=>{E&&E()})),{controller:o,stateRef:p};function w(e){return e.optimistic.reduce(u,e)}},e.useController=Me,e.useQuery=function(e,...n){const s=Oe(),i=Me(),r=t.computed((()=>i.getQueryMeta(e,...n,s.value)));return t.watch((()=>r.value.data),((e,t,n)=>{const s=r.value.countRef();n((()=>s()))}),{immediate:!0}),t.computed((()=>r.value.data))},e.useStateRef=Oe,e.useSubscription=function(e,...n){const s=Me(),i=t.computed((()=>n.map((e=>t.unref(e))))),r=t.computed((()=>null===i.value[0]?"":e.key(...i.value)));t.watch(r,((t,n,o)=>{if(!r.value)return;const a=i.value;s.subscribe(e,...a),o((()=>{s.unsubscribe(e,...a)}))}),{immediate:!0})},e.useSuspense=async function(e,...n){const s=Oe(),i=Me(),r=null!==n[0]?e.key(...n):"",o=t.computed((()=>i.getResponseMeta(e,...n,s.value))),a=o.value.expiryStatus===C.Invalid||Date.now()>o.value.expiresAt;r&&a&&await i.fetch(e,...n);const c=i.getError(e,...n,s.value);if(c)throw c;return t.watch((()=>o.value.data),((e,t,n)=>{const s=o.value.countRef();n((()=>s()))}),{immediate:!0}),t.readonly(t.computed((()=>o.value.data)))}}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("vue")):"function"==typeof define&&define.amd?define(["exports","vue"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).VDC={},e.Vue)}(this,(function(e,t){"use strict";class n{constructor(){this.localCache=new Map}getEntity(e,t,n,s){const i=t.key;this.localCache.has(i)||this.localCache.set(i,new Map);const r=this.localCache.get(i);return r.get(e)||s(r),r.get(e)}getResults(e,t,n){return{data:n(),paths:[]}}}const s=Symbol("INVALID"),i={};function r(e){return null!==e&&void 0!==e.pk}const o=e=>e[0],a=e=>void 0!==e&&"symbol"!=typeof e,c=(e,t,n,s,i,r)=>{e=o(e);const a=(e=>Array.isArray(e)?e:Object.keys(e).map((t=>e[t])))(t);return a.map((t=>r(e,t,n,s,i)))},l=(e,t,n,s)=>(e=o(e),t.map?t.map((t=>s(e,t))).filter(a):t);function h(){}function u(){return u=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var s in n)({}).hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},u.apply(null,arguments)}const d=(e,t,n,s,i,r)=>{const o=u({},t);return Object.keys(e).forEach((n=>{const s=e[n],a=r(s,t[n],t,n,i);void 0===a?delete o[n]:o[n]=a})),o},p=(e,t,n,i)=>{if(function(e){return!("function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}(t))return function(e,t,n,i){let r=!1;const o=Object.keys(e).reduce(((t,n)=>{const s=`${n}`,o=i(e[s],t.get(s));return"symbol"==typeof o&&(r=!0),t.has(s)?t.set(s,o):t}),t);return r?s:o}(e,t,0,i);const r=u({},t);let o=!1;return Object.keys(e).forEach((t=>{const n=i(e[t],r[t]);void 0!==r[t]&&(r[t]=n),"symbol"==typeof n&&(o=!0)})),o?s:r};function f(e,t,n,s){const i={};for(const r of Object.keys(e))i[r]=n(e[r],t,s);return i}const y=(e,t,n,s)=>function(r,o){const a="object"!=typeof o,c=a?e({key:r.key,pk:o}):o;if("symbol"==typeof c)return r.denormalize(c,n,s);if(void 0===c&&a&&""!==o&&"undefined"!==o)return t.getEntity(o,r,i,(e=>{e.set(o,void 0)}));if("object"!=typeof c||null===c)return c;let l=a?o:r.pk(c,void 0,void 0,n);return void 0===l||""===l||"undefined"===l?function(e){const t=new Map;return e(t),t.get("")}((e=>g(r,c,"",e,n,s))):("string"!=typeof l&&(l=`${l}`),t.getEntity(l,r,c,(e=>g(r,c,l,e,n,s))))};function g(e,t,n,i,r,o){const a=e.createIfValid(t);void 0===a?i.set(n,s):(i.set(n,a),i.set(n,e.denormalize(a,r,o)))}const m=(e,t,n)=>{const s=y(e,t,n,i);function i(e,t){if(!e)return t;if(null==t)return t;if("function"==typeof e.denormalize)return r(e)?s(e,t):e.denormalize(t,n,i);if("function"==typeof e)return e(t);if("object"==typeof e){return(Array.isArray(e)?l:p)(e,t,n,i)}return t}return(e,n)=>{const s=Object(n)===n&&Object(e)===e;return t.getResults(n,s,(()=>i(e,n)))}};class v{constructor({entities:e,indexes:t}){this.entities=e,this.indexes=t}tracked(e){const t=this,n=[{path:[""],entity:e}];return[{INVALID:s,getIndex(...e){const s=t.getIndex(...e);return n.push({path:e,entity:s}),t.getIndexEnd(s,e[2])},getEntity(...e){const s=t.getEntity(...e);return n.push({path:e,entity:s}),s},getEntities(e){const s=t.getEntitiesObject(e);return n.push({path:[e],entity:s}),t.getEntities(e)}},n]}}class E extends v{constructor(e){super(e)}getEntitiesObject(e){return this.entities[e]}getEntities(e){const t=this.entities[e];if(void 0!==t)return{keys:()=>Object.keys(t),entries:()=>Object.entries(t)}}getEntity(e,t){var n;return null==(n=this.entities[e])?void 0:n[t]}getIndex(e,t){var n;return null==(n=this.indexes[e])?void 0:n[t]}getIndexEnd(e,t){return null==e?void 0:e[t]}}const w={QueryDelegate:E,getEntities:e=>({key:t,pk:n})=>{var s;return null==(s=e[t])?void 0:s[n]}};class b{constructor(){this.next=new WeakMap,this.nextPath=void 0}get(e,t){let n=this.next.get(e);if(!n)return x;for(;n.nextPath;){var s;const e=null!=(s=t(n.nextPath))?s:i;if(n=n.next.get(e),!n)return x}return[n.value,n.journey]}set(e,t){if(e.length<1)throw new I;let n=this;for(const{path:t,entity:s}of e){let e=n.next.get(s);e||(e=new k,n.next.set(null!=s?s:i,e)),n.nextPath=t,n=e}n.nextPath=void 0,n.value=t,n.journey=e.map((e=>e.path))}}const x=[void 0,void 0];class k{constructor(){this.next=new WeakMap,this.nextPath=void 0,this.value=void 0,this.journey=[]}}class I extends Error{constructor(...e){super(...e),this.message="Keys must include at least one member"}}class L extends E{constructor(e,t){super(e),this.newEntities=new Map,this.newIndexes=new Map,this.entitiesMeta=e.entitiesMeta,this.meta=t,this.checkLoop=function(){const e=new Map;return function(t,n,s){e.has(t)||e.set(t,new Map);const i=e.get(t);i.has(n)||i.set(n,[]);const r=i.get(n);return!!r.some((e=>e===s))||(r.push(s),!1)}}()}getNewEntity(e,t){return this.getNewEntities(e).get(t)}getNewEntities(e){return this.newEntities.has(e)||(this.newEntities.set(e,new Map),this.entities[e]=u({},this.entities[e]),this.entitiesMeta[e]=u({},this.entitiesMeta[e])),this.newEntities.get(e)}getNewIndexes(e){return this.newIndexes.has(e)||(this.newIndexes.set(e,new Map),this.indexes[e]=u({},this.indexes[e])),this.newIndexes.get(e)}mergeEntity(e,t,n){const s=e.key;let i=n,r=this.meta,o=this.getNewEntity(s,t);if(o)i=e.merge(o,n);else if(o=this.getEntity(s,t),o){const a=this.getMeta(s,t);i=e.mergeWithStore(a,r,o,n),r=e.mergeMetaWithStore(a,r,o,n)}this.setEntity(e,t,i,r)}setEntity(e,t,n,i=this.meta){const r=e.key,o=this.getNewEntities(r),a=!o.has(t);o.set(t,n),e.indexes&&function(e,t,n,i,r,o){for(const a of t){n.has(a)||n.set(a,i[a]={});const t=n.get(a);o[e]&&delete t[o[e][a]],o&&o[e]&&o[e][a]!==r[a]&&(t[o[e][a]]=s),a in r&&(t[r[a]]=e)}}(t,e.indexes,this.getNewIndexes(r),this.indexes[r],n,this.entities[r]),this._setEntity(r,t,n),a&&this._setMeta(r,t,i)}invalidate(e,t){this.setEntity(e,t,s)}_setEntity(e,t,n){this.entities[e][t]=n}_setMeta(e,t,n){this.entitiesMeta[e][t]=n}getMeta(e,t){return this.entitiesMeta[e][t]}}const A=(e,t,n=[],{entities:s,indexes:i,entitiesMeta:r}=S,o={fetchedAt:0,date:Date.now(),expiresAt:1/0})=>{if(null==e)return{result:t,entities:s,indexes:i,entitiesMeta:r};const a=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(e);if(null===t||typeof t!==a&&(void 0===e.key||void 0!==e.pk||"string"!=typeof t))throw new Error(`Unexpected input given to normalize. Expected type to be "${a}", found "${null===t?"null":typeof t}".`);const l={result:"",entities:u({},s),indexes:u({},i),entitiesMeta:u({},r)},h=(e=>{const t=(n,s,i,r,o)=>s&&n?n.normalize&&"function"==typeof n.normalize?"object"!=typeof s?n.pk?`${s}`:s:n.normalize(s,i,r,o,t,e):"object"!=typeof s||"object"!=typeof n?s:(Array.isArray(n)?c:d)(n,s,i,r,o,t):s;return t})(new L(l,o));return l.result=h(e,t,t,void 0,n),l};const S={entities:{},indexes:{},entitiesMeta:{}};class M{constructor(e,t,n){this.dependencies=[],this.cycleCache=new Map,this.cycleIndex=-1,this.localCache=new Map,this._getEntity=e,this._getCache=t,this._resultCache=n}getEntity(e,t,n,s){const i=t.key,{localCacheKey:r,cycleCacheKey:o}=this.getCacheKey(i);if(r.get(e))o.has(e)?this.cycleIndex=o.get(e):this.dependencies.push({path:{key:i,pk:e},entity:n});else{const a=this._getCache(e,t),[c,l]=a.get(n,this._getEntity);if(l)return r.set(e,c.value),this.dependencies.push(...c.dependencies),c.value;{const t=this.dependencies.length;o.set(e,t),this.dependencies.push({path:{key:i,pk:e},entity:n}),s(r),o.delete(e);const c=this.dependencies.slice(-1===this.cycleIndex?t:this.cycleIndex),l={dependencies:c,value:r.get(e)};a.set(c,l),this.cycleIndex===t&&(this.cycleIndex=-1)}}return r.get(e)}getCacheKey(e){this.localCache.has(e)||this.localCache.set(e,new Map),this.cycleCache.has(e)||this.cycleCache.set(e,new Map);return{localCacheKey:this.localCache.get(e),cycleCacheKey:this.cycleCache.get(e)}}getResults(e,t,n){if(!t)return{data:n(),paths:this.paths()};let[s,i]=this._resultCache.get(e,this._getEntity);return void 0===i?(s=n(),i=this.paths(),this.dependencies.unshift({path:{key:"",pk:""},entity:e}),this._resultCache.set(this.dependencies,s)):i.shift(),{data:s,paths:i}}paths(){return this.dependencies.map((e=>e.path))}}function O(e){return void 0!==e&&(!(e&&"object"==typeof e&&!Array.isArray(e))||Object.values(e).every(O))}class R{constructor(e=w){var t;this.endpoints=new b,this.queryKeys=new Map,this.policy=e,this._getCache=(t=new Map,(e,n)=>{var s;const i=n.key,r=null!=(s=n.cacheWith)?s:n;t.has(i)||t.set(i,new Map);const o=t.get(i);o.has(e)||o.set(e,new WeakMap);const a=o.get(e);let c=a.get(r);return c||(c=new b,a.set(r,c)),c})}denormalize(e,t,n,s=[]){if(void 0===e)return{data:t,paths:[]};if(void 0===t)return{data:void 0,paths:[]};const i=this.policy.getEntities(n);return m(i,new M(i,this._getCache,this.endpoints),s)(e,t)}query(e,t,n,s=JSON.stringify(t)){const i=this.buildQueryKey(e,t,n,s);return i?this.denormalize(e,i,n.entities,t):{data:void 0,paths:[]}}buildQueryKey(e,t,n,s=JSON.stringify(t)){if("object"!=typeof e&&"function"!=typeof e.queryKey||!e)return e;this.queryKeys.get(s)||this.queryKeys.set(s,new b);const i=this.queryKeys.get(s),r=new this.policy.QueryDelegate(n);let[o,a]=i.get(e,(c=r,e=>c[["","getEntitiesObject","getEntity","getIndex"][e.length]](...e)));var c;if(!a){const[n,s]=r.tracked(e);o=function(e){return function t(n,s){return function(e){return!!e&&"function"==typeof e.queryKey}(n)?n.queryKey(s,t,e):"object"==typeof n&&n?(Array.isArray(n)?h:f)(n,s,t,e):n}}(n)(e,t),i.set(s,o)}return o}}var C={Invalid:1,InvalidIfStale:2,Valid:3};function _(e,t){const n=Date.now();return{fetchedAt:null!=t?t:n,date:n,expiresAt:n+e}}const P="rdc/fetch",j="rdc/set",T="rdc/setresponse",D="rdc/optimistic",q="rdc/reset",N="rdc/subscribe",K="rdc/unsubscribe",H="rdc/invalidate",z="rdc/invalidateall",U="rdc/expireall",V="rdc/gc",F=P,B=j,Y=T,Q=D,$=q,W=N,X=K,J=H,G=z,Z=U,ee=V;var te=Object.freeze({__proto__:null,EXPIREALL:U,EXPIREALL_TYPE:Z,FETCH:P,FETCH_TYPE:F,GC:V,GC_TYPE:ee,INVALIDATE:H,INVALIDATEALL:z,INVALIDATEALL_TYPE:G,INVALIDATE_TYPE:J,OPTIMISTIC:D,OPTIMISTIC_TYPE:Q,RESET:q,RESET_TYPE:$,SET:j,SET_RESPONSE:T,SET_RESPONSE_TYPE:Y,SET_TYPE:B,SUBSCRIBE:N,SUBSCRIBE_TYPE:W,UNSUBSCRIBE:K,UNSUBSCRIBE_TYPE:X});function ne(e,t){if(t.endpoint.getOptimisticResponse&&t.endpoint.sideEffect){const o=(n=t.endpoint,s=t.args,i=t.meta.fetchedAt,{type:D,key:n.key(...s),args:s,endpoint:n,meta:_(null!=(r=n.dataExpiryLength)?r:6e4,i)});return u({},e,{optimistic:[...e.optimistic,o]})}var n,s,i,r;return e}class se extends Error{}function ie(e,t,n){return"AbortError"===n.name?u({},e,{optimistic:re(e,t)}):u({},e,{meta:u({},e.meta,{[t.key]:{date:t.meta.date,fetchedAt:t.meta.fetchedAt,expiresAt:t.meta.expiresAt,error:n,errorPolicy:null==t.endpoint.errorPolicy?void 0:t.endpoint.errorPolicy(n)}}),optimistic:re(e,t)})}function re(e,t){return e.optimistic.filter((e=>e.key!==t.key||(e.type===D?e.meta.fetchedAt!==t.meta.fetchedAt:e.meta.date>t.meta.date)))}function oe(e){return function(t,n){switch(t||(t=ae),n.type){case V:return n.entities.forEach((({key:e,pk:n})=>{var s,i;null==(s=t.entities[e])||delete s[n],null==(i=t.entitiesMeta[e])||delete i[n]})),n.endpoints.forEach((e=>{delete t.endpoints[e],delete t.meta[e]})),t;case P:return ne(t,n);case D:case T:return function(e,t,n){if(t.error)return ie(e,t,t.response);try{var s;let i;if(t.type===D){if(!t.endpoint.getOptimisticResponse)return e;try{i=t.endpoint.getOptimisticResponse.call(t.endpoint,n.snapshot(e,t.meta.fetchedAt),...t.args)}catch(t){if(t.constructor===se)return e;throw t}}else i=t.response;const{result:r,entities:o,indexes:a,entitiesMeta:c}=A(t.endpoint.schema,i,t.args,e,t.meta),l=u({},e.endpoints,{[t.key]:r});try{if(t.endpoint.update){const e=t.endpoint.update(r,...t.args);Object.keys(e).forEach((t=>{l[t]=e[t](l[t])}))}}catch(e){console.error(`The following error occured during Endpoint.update() for ${t.key}`),console.error(e)}return{entities:o,endpoints:l,indexes:a,meta:u({},e.meta,{[t.key]:{date:t.meta.date,fetchedAt:t.meta.fetchedAt,expiresAt:t.meta.expiresAt,prevExpiresAt:null==(s=e.meta[t.key])?void 0:s.expiresAt}}),entitiesMeta:c,optimistic:re(e,t),lastReset:e.lastReset}}catch(n){return"object"==typeof n&&(n.message=`Error processing ${t.key}\n\nFull Schema: ${JSON.stringify(t.endpoint.schema,void 0,2)}\n\nError:\n${n.message}`,"response"in t&&(n.response=t.response),n.status=400),ie(e,t,n)}}(t,n,e);case j:return function(e,t,n){let s;if("function"==typeof t.value){const i=n.get(t.schema,...t.args,e);if(void 0===i)return e;s=t.value(i)}else s=t.value;try{const{entities:n,indexes:i,entitiesMeta:r}=A(t.schema,s,t.args,e,t.meta);return{entities:n,endpoints:e.endpoints,indexes:i,meta:e.meta,entitiesMeta:r,optimistic:e.optimistic,lastReset:e.lastReset}}catch(t){return e}}(t,n,e);case z:case H:return function(e,t){const n=u({},e.endpoints),s=u({},e.meta),i=e=>{delete n[e];const t=u({},s[e],{expiresAt:0,invalidated:!0});delete t.error,s[e]=t};return t.type===H?i(t.key):Object.keys(n).forEach((e=>{t.testKey(e)&&i(e)})),u({},e,{endpoints:n,meta:s})}(t,n);case U:return function(e,t){const n=u({},e.meta);return Object.keys(n).forEach((e=>{t.testKey(e)&&(n[e]=u({},n[e],{expiresAt:1}))})),u({},e,{meta:n})}(t,n);case q:return u({},ae,{lastReset:n.date});default:return t}}}const ae={entities:{},endpoints:{},indexes:{},meta:{},entitiesMeta:{},optimistic:[],lastReset:0};const ce="undefined"!=typeof FormData?e=>e instanceof FormData?Object.fromEntries(e.entries()):e:e=>e;function le(e,{args:t,fetchedAt:n,response:s,error:i=!1}){var r,o;const a=i?null!=(r=e.errorExpiryLength)?r:1e3:null!=(o=e.dataExpiryLength)?o:6e4;return{type:T,key:e.key(...t),response:s,args:t.map(ce),endpoint:e,meta:_(a,n),error:i}}class he{init(){}cleanup(){}createCountRef(){return()=>()=>{}}}function ue(e,t){return e.meta[t]}const de=e=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")},pe=()=>ae;class fe{constructor({dispatch:e=de,getState:t=pe,memo:s=new R,gcPolicy:i=new he}={}){this.fetch=(e,...t)=>{const s=function(e,{args:t}){let n=0,s=0;const i=new Promise(((e,t)=>{[n,s]=[e,t]})),r={fetchedAt:Date.now(),resolve:n,reject:s,promise:i};return{type:P,key:e.key(...t),args:t,endpoint:e,meta:r}}(e,{args:t});return this.dispatch(s),e.schema?s.meta.promise.then((s=>function(e,t,s,i=[]){return void 0===e||void 0===t?t:m(w.getEntities(s),new n,i)(e,t).data}(e.schema,s,{},t))):s.meta.promise},this.fetchIfStale=(e,...t)=>{const{data:n,expiresAt:s,expiryStatus:i}=this.getResponseMeta(e,...t,this.getState());return i!==C.Invalid&&Date.now()<=s?n:this.fetch(e,...t)},this.invalidate=(e,...t)=>null!==t[0]?this.dispatch(function(e,{args:t}){return{type:H,key:e.key(...t)}}(e,{args:t})):Promise.resolve(),this.invalidateAll=e=>this.dispatch({type:z,testKey:t=>e.testKey(t)}),this.expireAll=e=>this.dispatch({type:U,testKey:t=>e.testKey(t)}),this.resetEntireStore=()=>this.dispatch({type:q,date:Date.now()}),this.setResponse=(e,...t)=>{const n=t[t.length-1],s=le(e,{args:t.slice(0,t.length-1),response:n});return this.dispatch(s)},this.setError=(e,...t)=>{const n=t[t.length-1],s=le(e,{args:t.slice(0,t.length-1),response:n,error:!0});return this.dispatch(s)},this.resolve=(e,t)=>this.dispatch(le(e,t)),this.subscribe=(e,...t)=>null!==t[0]?this.dispatch(function(e,{args:t}){return{type:N,key:e.key(...t),args:t,endpoint:e}}(e,{args:t})):Promise.resolve(),this.unsubscribe=(e,...t)=>null!==t[0]?this.dispatch(function(e,{args:t}){return{type:K,key:e.key(...t),args:t,endpoint:e}}(e,{args:t})):Promise.resolve(),this.snapshot=(e,t)=>new ge(this,e,t),this._dispatch=e,this.getState=t,this.memo=s,this.gcPolicy=i}set dispatch(e){this._dispatch=e}get dispatch(){return this._dispatch}bindMiddleware({dispatch:e,getState:t}){this._dispatch=e,this.getState=t}set(e,...t){const n=t[t.length-1],s=function(e,{args:t,fetchedAt:n,value:s}){return{type:j,value:s,args:t.map(ce),schema:e,meta:_(6e4,n)}}(e,{args:t.slice(0,t.length-1),value:n});return this.dispatch(s)}getError(e,...t){if(null===t[0])return;const n=t[t.length-1],s=t.slice(0,t.length-1),i=e.key(...s),r=ue(n,i);return void 0===n.endpoints[i]||"soft"!==(null==r?void 0:r.errorPolicy)?null==r?void 0:r.error:void 0}getResponse(e,...t){return this.getResponseMeta(e,...t)}getResponseMeta(e,...t){const n=t[t.length-1],s=t.slice(0,t.length-1).map(ce),i=1!==s.length||null!==s[0],r=i?e.key(...s):"",o=i?n.endpoints[r]:void 0,a=e.schema,c=ue(n,r);let l=null==c?void 0:c.expiresAt;const h=void 0===o&&void 0!==a,u=h?this.memo.buildQueryKey(a,s,n,r):o;if(!i)return{data:u,expiryStatus:C.Valid,expiresAt:1/0,countRef:()=>()=>{}};let d=!1;if(h)d=!O(u);else if(!a||!ye(a))return{data:o,expiryStatus:this.getExpiryStatus(!o,!!e.invalidIfStale,c),expiresAt:l||0,countRef:this.gcPolicy.createCountRef({key:r})};const{data:p,paths:f}=this.memo.denormalize(a,u,n.entities,s);return l||(l=d?1:function(e,t){let n=1/0;for(const{key:i,pk:r}of e){var s;const e=null==(s=t[i])||null==(s=s[r])?void 0:s.expiresAt;e<n&&(n=e)}return n}(f,n.entitiesMeta)),{data:p,expiryStatus:this.getExpiryStatus("symbol"==typeof p,!!e.invalidIfStale||d,c),expiresAt:l,countRef:this.gcPolicy.createCountRef({key:r,paths:f})}}get(e,...t){const n=t[t.length-1],s=t.slice(0,t.length-1).map(ce),{data:i}=this.memo.query(e,s,n);return"symbol"==typeof i?void 0:i}getQueryMeta(e,...t){const n=t[t.length-1],s=t.slice(0,t.length-1).map(ce),{data:i,paths:r}=this.memo.query(e,s,n);return{data:"symbol"==typeof i?void 0:i,countRef:this.gcPolicy.createCountRef({paths:r})}}getExpiryStatus(e,t,n={}){return n.invalidated||e&&!n.error?C.Invalid:e||t?C.InvalidIfStale:C.Valid}}function ye(e){if(r(e))return!0;if(Array.isArray(e))return 0!==e.length&&ye(e[0]);if(e&&("object"==typeof e||"function"==typeof e)){const t="schema"in e?e.schema:e;return"function"==typeof t?ye(t):Object.values(t).some((e=>ye(e)))}return!1}class ge{constructor(e,t,n=0){this.state=void 0,this.controller=void 0,this.fetchedAt=void 0,this.abort=ge.abort,this.state=t,this.controller=e,this.fetchedAt=n}getResponse(e,...t){return this.controller.getResponse(e,...t,this.state)}getResponseMeta(e,...t){return this.controller.getResponseMeta(e,...t,this.state)}getError(e,...t){return this.controller.getError(e,...t,this.state)}get(e,...t){return this.controller.get(e,...t,this.state)}getQueryMeta(e,...t){return this.controller.getQueryMeta(e,...t,this.state)}}ge.abort=new se;class me extends Error{constructor(){super("Aborted due to RESET"),this.name="ResetError"}}class ve{constructor({dataExpiryLength:e=6e4,errorExpiryLength:t=1e3}={}){this.fetching=new Map,this.controller=new fe,this.middleware=e=>(this.controller=e,t=>n=>{switch(n.type){case P:return this.handleFetch(n),void 0!==n.endpoint.getOptimisticResponse&&n.endpoint.sideEffect?t(n):Promise.resolve();case T:return t(n).then((()=>{if(this.fetching.has(n.key)){var t;const s=null==(t=e.getState().meta[n.key])?void 0:t.error;s?this.handleSet(le(n.endpoint,{args:n.args,response:s,fetchedAt:n.meta.fetchedAt,error:!0})):this.handleSet(n)}}));case q:{const e=Array.from(this.fetching.values());return this.clearAll(),t(n).then((()=>{for(const{reject:t}of e)t(new me)}))}default:return t(n)}}),this.dataExpiryLength=e,this.errorExpiryLength=t}init(){delete this.cleanupDate}cleanup(){this.cleanupDate=Date.now()}skipLogging(e){return e.type===P&&this.fetching.has(e.key)}allSettled(){if(this.fetching.size)return Promise.allSettled(this.fetching.values().map((({promise:e})=>e)))}clearAll(){for(const e of this.fetching.keys())this.clear(e)}clear(e){this.fetching.has(e)&&(this.fetching.get(e).promise.catch((()=>{})),this.fetching.delete(e))}getLastReset(){return this.cleanupDate?this.cleanupDate:this.controller.getState().lastReset}handleFetch(e){const{resolve:t,reject:n,fetchedAt:s}=e.meta,i=!e.endpoint.sideEffect,r=()=>{let r=e.endpoint(...e.args);return i||(r=(e=>e.then((e=>(t(e),e))).catch((e=>{throw n(e),e})))(r)),r=r.then((t=>{let n=this.getLastReset();return s>=n&&this.controller.resolve(e.endpoint,{args:e.args,response:t,fetchedAt:s}),t})).catch((t=>{const n=this.getLastReset();throw s>=n&&this.controller.resolve(e.endpoint,{args:e.args,response:t,fetchedAt:s,error:!0}),t})),r};return i?this.throttle(e.key,r,s).then((e=>t(e))).catch((e=>n(e))):r().catch((()=>{}))}handleSet(e){if(this.fetching.has(e.key)){const{reject:t,resolve:n}=this.fetching.get(e.key);e.error?t(e.response):n(e.response),this.clear(e.key)}}throttle(e,t,n){const s=this.getLastReset();let i=this.fetching.get(e);return i&&i.fetchedAt>s||(i=function(e){const t={fetchedAt:e};return t.promise=new Promise(((e,n)=>{t.resolve=e,t.reject=n})),t}(n),this.fetching.set(e,i),this.idleCallback((()=>{t().catch((()=>null))}),{timeout:500})),i.promise}idleCallback(e,t){e()}}class Ee{isOnline(){return void 0===navigator.onLine||navigator.onLine}addOnlineListener(e){addEventListener("online",e)}removeOnlineListener(e){removeEventListener("online",e)}addOfflineListener(e){addEventListener("offline",e)}removeOfflineListener(e){removeEventListener("offline",e)}}class we{isOnline(){return!0}addOnlineListener(){}removeOnlineListener(){}addOfflineListener(){}removeOfflineListener(){}}e.DefaultConnectionListener=void 0,"undefined"!=typeof navigator&&"function"==typeof addEventListener?e.DefaultConnectionListener=Ee:e.DefaultConnectionListener=we;class be{constructor(t,n,s){if(this.frequencyHistogram=new Map,this.offlineListener=()=>{this.cleanup(),this.connectionListener.addOnlineListener(this.onlineListener)},this.onlineListener=()=>{this.connectionListener.removeOnlineListener(this.onlineListener);const e=Date.now();this.startId=setTimeout((()=>{this.startId&&(delete this.startId,this.update(),this.run())}),Math.max(0,this.lastFetchTime()-e+this.frequency)),this.connectionListener.addOfflineListener(this.offlineListener)},void 0===t.endpoint.pollFrequency)throw new Error("frequency needed for polling subscription");this.endpoint=t.endpoint,this.frequency=t.endpoint.pollFrequency,this.args=t.args,this.key=t.key,this.frequencyHistogram.set(this.frequency,1),this.controller=n,this.connectionListener=s||new e.DefaultConnectionListener,this.connectionListener.isOnline()?this.onlineListener():this.offlineListener()}add(e){void 0!==e&&(this.frequencyHistogram.has(e)?this.frequencyHistogram.set(e,this.frequencyHistogram.get(e)+1):(this.frequencyHistogram.set(e,1),e<this.frequency&&(this.frequency=e,this.run())))}remove(e){if(void 0===e)return!1;if(this.frequencyHistogram.has(e)&&(this.frequencyHistogram.set(e,this.frequencyHistogram.get(e)-1),this.frequencyHistogram.get(e)<1)){if(this.frequencyHistogram.delete(e),0===this.frequencyHistogram.size)return this.cleanup(),!0;e<=this.frequency&&(this.frequency=Math.min(...this.frequencyHistogram.keys()),this.run())}return!1}cleanup(){this.intervalId&&(clearInterval(this.intervalId),delete this.intervalId),this.lastIntervalId&&(clearInterval(this.lastIntervalId),delete this.lastIntervalId),this.startId&&(clearTimeout(this.startId),delete this.startId),this.connectionListener.removeOnlineListener(this.onlineListener),this.connectionListener.removeOfflineListener(this.offlineListener)}update(){const e=this.endpoint,t=function(...t){return e.call(this,...t)};Object.assign(t,this.endpoint),t.dataExpiryLength=this.frequency/2,t.errorExpiryLength=this.frequency/10,t.errorPolicy=()=>"soft",t.key=()=>this.key,this.controller.fetch(t,...this.args).catch((()=>null))}run(){this.startId||(this.intervalId&&(this.lastIntervalId=this.intervalId),this.intervalId=setInterval((()=>{this.lastIntervalId&&(clearInterval(this.lastIntervalId),delete this.lastIntervalId),this.intervalId&&this.update()}),this.frequency))}lastFetchTime(){var e,t;return null!=(e=null==(t=this.controller.getState().meta[this.key])?void 0:t.date)?e:0}}class xe{constructor(e){this.subscriptions={},this.controller=new fe,this.middleware=e=>(this.controller=e,e=>t=>{switch(t.type){case N:try{this.handleSubscribe(t)}catch(e){console.error(e)}return Promise.resolve();case K:return this.handleUnsubscribe(t),Promise.resolve();default:return e(t)}}),this.Subscription=e}cleanup(){for(const e in this.subscriptions)this.subscriptions[e].cleanup()}handleSubscribe(e){const t=e.key;if(t in this.subscriptions){const n=e.endpoint.pollFrequency;this.subscriptions[t].add(n)}else this.subscriptions[t]=new this.Subscription(e,this.controller)}handleUnsubscribe(e){const t=e.key;if(t in this.subscriptions){const n=e.endpoint.pollFrequency;this.subscriptions[t].remove(n)&&delete this.subscriptions[t]}}}let ke={};class Ie{constructor(e,t){this.started=!1,this.actions=[],this.maxBufferLength=100,this.devTools="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__.connect(u({},ke,e)),null!=e&&e.maxAge&&(this.maxBufferLength=2*e.maxAge),t&&(this.skipLogging=t)}handleAction(e,t){this.started?this.devTools.send(e,t):(this.actions.length>this.maxBufferLength&&(this.actions=this.actions.slice(this.maxBufferLength/2)),this.actions.push([e,t]))}init(e){}cleanup(){}}Ie.prototype.middleware=()=>e=>t=>e(t);const Le=Symbol("DataClientState"),Ae=Symbol("DataClientController"),Se=t.shallowRef(ae);function Me(){const e=t.inject(Ae,null);return e||new fe}function Oe(){const e=t.inject(Le,null);return e||Se}async function Re(e,...n){const s=Oe(),i=Me(),r=null!==n[0]?e.key(...n):"",o=t.computed((()=>i.getResponseMeta(e,...n,s.value))),a=o.value.expiryStatus===C.Invalid||Date.now()>o.value.expiresAt;r&&a&&await i.fetch(e,...n);const c=i.getError(e,...n,s.value);if(c)throw c;return t.watch((()=>o.value.data),((e,t,n)=>{const s=o.value.countRef();n((()=>s()))}),{immediate:!0}),t.readonly(t.computed((()=>o.value.data)))}function Ce(e,...n){const s=Me(),i=t.computed((()=>n.map((e=>t.unref(e))))),r=t.computed((()=>null===i.value[0]?"":e.key(...i.value)));t.watch(r,((t,n,o)=>{if(!r.value)return;const a=i.value;s.subscribe(e,...a),o((()=>{s.unsubscribe(e,...a)}))}),{immediate:!0})}let _e=(e={})=>{const{networkManager:t,subscriptionManager:n=be}=e;return null===n?[Pe(ve,null!=t?t:{})]:[Pe(ve,null!=t?t:{}),Pe(xe,n)]};function Pe(e,t){return t instanceof e?t:new e(t)}e.Controller=fe,e.DevToolsManager=Ie,e.ExpiryStatus=C,e.LogoutManager=class{constructor({handleLogout:e,shouldLogout:t}={}){this.middleware=e=>t=>async n=>{await t(n),n.type===T&&n.error&&this.shouldLogout(n.response)&&this.handleLogout(e)},e&&(this.handleLogout=e),t&&(this.shouldLogout=t)}cleanup(){}shouldLogout(e){return 401===e.status}handleLogout(e){e.resetEntireStore()}},e.NetworkManager=ve,e.PollingSubscription=be,e.SubscriptionManager=xe,e.actionTypes=te,e.getDefaultManagers=_e,e.provideDataClient=function(e={}){var n,s;const{Controller:i=fe,gcPolicy:r}=e,o=new i({gcPolicy:r}),a=null!=(n=e.managers)?n:_e(),c=null!=(s=e.initialState)?s:ae,l=function(e,t,n){return()=>(e.forEach((e=>{null==e.init||e.init(n)})),t.gcPolicy.init(t),()=>{e.forEach((e=>{e.cleanup()})),t.gcPolicy.cleanup()})}(a,o,c),h=function(e,t){return e.map(((e,n)=>(e.middleware||(e.middleware=null==e.getMiddleware?void 0:e.getMiddleware()),s=>(0===n&&t.bindMiddleware(s),e.middleware(t)))))}(a,o),u=oe(o),d=t.shallowRef(c),p=t.shallowRef(w(c));let f=null;const y=()=>d.value,g=h.map((e=>e({getState:y,dispatch:e=>m(e)}))),m=(v=g,e=>v.reduceRight(((e,t)=>t(e)),e))((async e=>{const t=new Promise((e=>{f=e}));return await(async e=>{const t=u(d.value,e);if(d.value=t,p.value=w(t),f){const e=f;f=null,e()}})(e),t}));var v;let E;return o.bindMiddleware({getState:y,dispatch:e=>m(e)}),t.provide(Le,p),t.provide(Ae,o),t.onMounted((()=>{E=l()})),t.onUnmounted((()=>{E&&E()})),{controller:o,stateRef:p};function w(e){return e.optimistic.reduce(u,e)}},e.useController=Me,e.useDebounce=function(e,n,s=!0){const i=t.ref("object"==typeof e&&null!==e&&"value"in e?e.value:e),r=t.ref(!1);let o=null;const a=()=>{null!==o&&(clearTimeout(o),o=null)};return t.watch([()=>"object"==typeof e&&null!==e&&"value"in e?e.value:e,()=>"object"==typeof s&&null!==s&&"value"in s?s.value:s,()=>n],(([e,t])=>{a(),t?(r.value=!0,o=setTimeout((()=>{i.value=e,r.value=!1,o=null}),n)):r.value=!1}),{immediate:!1}),t.onUnmounted((()=>{a()})),[i,r]},e.useLive=async function(e,...t){return Ce(e,...t),Re(e,...t)},e.useLoading=function(e){const n=t.ref(!1),s=t.ref(void 0),i=t.ref(!0);return t.onUnmounted((()=>{i.value=!1})),[async(...t)=>{let r;n.value=!0,s.value=void 0;try{r=await e(...t)}catch(e){s.value=e}finally{i.value&&(n.value=!1)}return r},n,s]},e.useQuery=function(e,...n){const s=Oe(),i=Me(),r=t.computed((()=>i.getQueryMeta(e,...n,s.value)));return t.watch((()=>r.value.data),((e,t,n)=>{const s=r.value.countRef();n((()=>s()))}),{immediate:!0}),t.computed((()=>r.value.data))},e.useSubscription=Ce,e.useSuspense=Re}));
@@ -1,5 +1,8 @@
1
1
  export { default as useSuspense } from './useSuspense.js';
2
2
  export { default as useSubscription } from './useSubscription.js';
3
3
  export { default as useQuery } from './useQuery.js';
4
- export { injectController as useController, injectState as useStateRef, } from '../context.js';
4
+ export { default as useLive } from './useLive.js';
5
+ export { default as useLoading } from './useLoading.js';
6
+ export { default as useDebounce } from './useDebounce.js';
7
+ export { useController as useController } from '../context.js';
5
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/consumers/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAClE,OAAO,EAAE,OAAO,IAAI,QAAQ,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EACL,gBAAgB,IAAI,aAAa,EACjC,WAAW,IAAI,WAAW,GAC3B,MAAM,eAAe,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/consumers/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAClE,OAAO,EAAE,OAAO,IAAI,QAAQ,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,OAAO,IAAI,OAAO,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,eAAe,CAAC"}
@@ -1,5 +1,8 @@
1
1
  export { default as useSuspense } from './useSuspense.js';
2
2
  export { default as useSubscription } from './useSubscription.js';
3
3
  export { default as useQuery } from './useQuery.js';
4
- export { injectController as useController, injectState as useStateRef } from '../context.js';
5
- //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJkZWZhdWx0IiwidXNlU3VzcGVuc2UiLCJ1c2VTdWJzY3JpcHRpb24iLCJ1c2VRdWVyeSIsImluamVjdENvbnRyb2xsZXIiLCJ1c2VDb250cm9sbGVyIiwiaW5qZWN0U3RhdGUiLCJ1c2VTdGF0ZVJlZiJdLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb25zdW1lcnMvaW5kZXgudHMiXSwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IHsgZGVmYXVsdCBhcyB1c2VTdXNwZW5zZSB9IGZyb20gJy4vdXNlU3VzcGVuc2UuanMnO1xuZXhwb3J0IHsgZGVmYXVsdCBhcyB1c2VTdWJzY3JpcHRpb24gfSBmcm9tICcuL3VzZVN1YnNjcmlwdGlvbi5qcyc7XG5leHBvcnQgeyBkZWZhdWx0IGFzIHVzZVF1ZXJ5IH0gZnJvbSAnLi91c2VRdWVyeS5qcyc7XG5leHBvcnQge1xuICBpbmplY3RDb250cm9sbGVyIGFzIHVzZUNvbnRyb2xsZXIsXG4gIGluamVjdFN0YXRlIGFzIHVzZVN0YXRlUmVmLFxufSBmcm9tICcuLi9jb250ZXh0LmpzJztcbiJdLCJtYXBwaW5ncyI6IkFBQUEsU0FBU0EsT0FBTyxJQUFJQyxXQUFXLFFBQVEsa0JBQWtCO0FBQ3pELFNBQVNELE9BQU8sSUFBSUUsZUFBZSxRQUFRLHNCQUFzQjtBQUNqRSxTQUFTRixPQUFPLElBQUlHLFFBQVEsUUFBUSxlQUFlO0FBQ25ELFNBQ0VDLGdCQUFnQixJQUFJQyxhQUFhLEVBQ2pDQyxXQUFXLElBQUlDLFdBQVcsUUFDckIsZUFBZSIsImlnbm9yZUxpc3QiOltdfQ==
4
+ export { default as useLive } from './useLive.js';
5
+ export { default as useLoading } from './useLoading.js';
6
+ export { default as useDebounce } from './useDebounce.js';
7
+ export { useController } from '../context.js';
8
+ //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJkZWZhdWx0IiwidXNlU3VzcGVuc2UiLCJ1c2VTdWJzY3JpcHRpb24iLCJ1c2VRdWVyeSIsInVzZUxpdmUiLCJ1c2VMb2FkaW5nIiwidXNlRGVib3VuY2UiLCJ1c2VDb250cm9sbGVyIl0sInNvdXJjZXMiOlsiLi4vLi4vc3JjL2NvbnN1bWVycy9pbmRleC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see https://dataclient.io/docs/api/useDebounce
6
+ * @param value Any immutable value (can be a ref)
7
+ * @param delay Time in milliseconds to wait til updating the value
8
+ * @param updatable Whether to update at all
9
+ * @example
10
+ ```
11
+ const [debouncedQuery, isPending] = useDebounce(query, 200);
12
+ const list = useSuspense(getThings, { query: debouncedQuery.value });
13
+ ```
14
+ */
15
+ export default function useDebounce<T>(value: T | Ref<T>, delay: number, updatable?: boolean | Ref<boolean>): [Ref<T>, Ref<boolean>];
16
+ //# sourceMappingURL=useDebounce.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useDebounce.d.ts","sourceRoot":"","sources":["../../src/consumers/useDebounce.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2B,KAAK,GAAG,EAAE,MAAM,KAAK,CAAC;AAExD;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,OAAO,UAAU,WAAW,CAAC,CAAC,EACnC,KAAK,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,EACjB,KAAK,EAAE,MAAM,EACb,SAAS,GAAE,OAAO,GAAG,GAAG,CAAC,OAAO,CAAQ,GACvC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CA0DxB"}
@@ -0,0 +1,50 @@
1
+ import { ref, watch, onUnmounted } from 'vue';
2
+
3
+ /**
4
+ * Keeps value updated after delay time
5
+ *
6
+ * @see https://dataclient.io/docs/api/useDebounce
7
+ * @param value Any immutable value (can be a ref)
8
+ * @param delay Time in milliseconds to wait til updating the value
9
+ * @param updatable Whether to update at all
10
+ * @example
11
+ ```
12
+ const [debouncedQuery, isPending] = useDebounce(query, 200);
13
+ const list = useSuspense(getThings, { query: debouncedQuery.value });
14
+ ```
15
+ */
16
+ export default function useDebounce(value, delay, updatable = true) {
17
+ const debouncedValue = ref(typeof value === 'object' && value !== null && 'value' in value ? value.value : value);
18
+ const isPending = ref(false);
19
+ let timeoutId = null;
20
+ const clearExistingTimeout = () => {
21
+ if (timeoutId !== null) {
22
+ clearTimeout(timeoutId);
23
+ timeoutId = null;
24
+ }
25
+ };
26
+
27
+ // Watch the input value and debounce updates
28
+ watch([() => typeof value === 'object' && value !== null && 'value' in value ? value.value : value, () => typeof updatable === 'object' && updatable !== null && 'value' in updatable ? updatable.value : updatable, () => delay], ([newValue, isUpdatable]) => {
29
+ clearExistingTimeout();
30
+ if (!isUpdatable) {
31
+ isPending.value = false;
32
+ return;
33
+ }
34
+ isPending.value = true;
35
+ timeoutId = setTimeout(() => {
36
+ debouncedValue.value = newValue;
37
+ isPending.value = false;
38
+ timeoutId = null;
39
+ }, delay);
40
+ }, {
41
+ immediate: false
42
+ });
43
+
44
+ // Cleanup on unmount
45
+ onUnmounted(() => {
46
+ clearExistingTimeout();
47
+ });
48
+ return [debouncedValue, isPending];
49
+ }
50
+ //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJyZWYiLCJ3YXRjaCIsIm9uVW5tb3VudGVkIiwidXNlRGVib3VuY2UiLCJ2YWx1ZSIsImRlbGF5IiwidXBkYXRhYmxlIiwiZGVib3VuY2VkVmFsdWUiLCJpc1BlbmRpbmciLCJ0aW1lb3V0SWQiLCJjbGVhckV4aXN0aW5nVGltZW91dCIsImNsZWFyVGltZW91dCIsIm5ld1ZhbHVlIiwiaXNVcGRhdGFibGUiLCJzZXRUaW1lb3V0IiwiaW1tZWRpYXRlIl0sInNvdXJjZXMiOlsiLi4vLi4vc3JjL2NvbnN1bWVycy91c2VEZWJvdW5jZS50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyByZWYsIHdhdGNoLCBvblVubW91bnRlZCwgdHlwZSBSZWYgfSBmcm9tICd2dWUnO1xuXG4vKipcbiAqIEtlZXBzIHZhbHVlIHVwZGF0ZWQgYWZ0ZXIgZGVsYXkgdGltZVxuICpcbiAqIEBzZWUgaHR0cHM6Ly9kYXRhY2xpZW50LmlvL2RvY3MvYXBpL3Vz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KSB7XG4gICAgICBjbGVhclRpbWVvdXQodGltZW91dElkKTtcbiAgICAgIHRpbWVvdXRJZCA9IG51bGw7XG4gICAgfVxuICB9O1xuXG4gIC8vIFdhdGNoIHRoZSBpbnB1dCB2YWx1ZSBhbmQgZGVib3VuY2UgdXBkYXRlc1xuICB3YXRjaChcbiAgICBbXG4gICAgICAoKSA9PlxuICAgICAgICB0eXBlb2YgdmFsdWUgPT09ICdvYmplY3QnICYmIHZhbHVlICE9PSBudWxsICYmICd2YWx1ZScgaW4gdmFsdWUgP1xuICAgICAgICAgIHZhbHVlLnZhbHVlXG4gICAgICAgIDogdmFsdWUsXG4gICAgICAoKSA9PlxuICAgICAgICAoXG4gICAgICAgICAgdHlwZW9mIHVwZGF0YWJsZSA9PT0gJ29iamVjdCcgJiZcbiAgICAgICAgICB1cGRhdGFibGUgIT09IG51bGwgJiZcbiAgICAgICAgICAndmFsdWUnIGluIHVwZGF0YWJsZVxuICAgICAgICApID9cbiAgICAgICAgICB1cGRhdGFibGUudmFsdWVcbiAgICAgICAgOiB1cGRhdGFibGUsXG4gICAgICAoKSA9PiBkZWxheSxcbiAgICBdLFxuICAgIChbbmV3VmFsdWUsIGlzVXBkYXRhYmxlXSkgPT4ge1xuICAgICAgY2xlYXJFeGlzdGluZ1RpbWVvdXQoKTtcblxuICAgICAgaWYgKCFpc1VwZGF0YWJsZSkge1xuICAgICAgICBpc1BlbmRpbmcudmFsdWUgPSBmYWxzZTtcbiAgICAgICAgcmV0dXJuO1xuICAgICAgfVxuXG4gICAgICBpc1BlbmRpbmcudmFsdWUgPSB0cnVlO1xuXG4gICAgICB0aW1lb3V0SWQgPSBzZXRUaW1lb3V0KCgpID0+IHtcbiAgICAgICAgZGVib3VuY2VkVmFsdWUudmFsdWUgPSBuZXdWYWx1ZTtcbiAgICAgICAgaXNQZW5kaW5nLnZhbHVlID0gZmFsc2U7XG4gICAgICAgIHRpbWVvdXRJZCA9IG51bGw7XG4gICAgICB9LCBkZWxheSk7XG4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LLElBQUksSUFBSSxPQUFPLElBQUlBLEtBQUssR0FDN0RBLEtBQUssQ0FBQ0EsS0FBSyxHQUNYQSxLQUFLLEVBQ1QsTUFFSSxPQUFPRSxTQUFTLEtBQUssUUFBUSxJQUM3QkEsU0FBUyxLQUFLLElBQUksSUFDbEIsT0FBTyxJQUFJQSxTQUFTLEdBRXBCQSxTQUFTLENBQUNGLEtBQUssR0FDZkUsU0FBUyxFQUNiLE1BQU1ELEtBQUssQ0FDWixFQUNELENBQUMsQ0FBQ08sUUFBUSxFQUFFQyxXQUFXLENBQUMsS0FBSztJQUMzQkgsb0JBQW9CLENBQUMsQ0FBQztJQUV0QixJQUFJLENBQUNHLFdBQVcsRUFBRTtNQUNoQkwsU0FBUyxDQUFDSixLQUFLLEdBQUcsS0FBSztNQUN2QjtJQUNGO0lBRUFJLFNBQVMsQ0FBQ0osS0FBSyxHQUFHLElBQUk7SUFFdEJLLFNBQVMsR0FBR0ssVUFBVSxDQUFDLE1BQU07TUFDM0JQLGNBQWMsQ0FBQ0gsS0FBSyxHQUFHUSxRQUFRO01BQy9CSixTQUFTLENBQUNKLEtBQUssR0FBRyxLQUFLO01BQ3ZCSyxTQUFTLEdBQUcsSUFBSTtJQUNsQixDQUFDLEVBQUVKLEtBQUssQ0FBQztFQUNYLENBQUMsRUFDRDtJQUFFVSxTQUFTLEVBQUU7RUFBTSxDQUNyQixDQUFDOztFQUVEO0VBQ0FiLFdBQVcsQ0FBQyxNQUFNO0lBQ2hCUSxvQkFBb0IsQ0FBQyxDQUFDO0VBQ3hCLENBQUMsQ0FBQztFQUVGLE9BQU8sQ0FBQ0gsY0FBYyxFQUFFQyxTQUFTLENBQUM7QUFDcEMiLCJpZ25vcmVMaXN0IjpbXX0=
@@ -0,0 +1,13 @@
1
+ import type { EndpointInterface, Denormalize, Schema, FetchFunction, ResolveType, DenormalizeNullable } from '@data-client/core';
2
+ import type { DeepReadonly, ComputedRef } from 'vue';
3
+ /**
4
+ * Ensure an endpoint is available. Keeps it fresh once it is.
5
+ *
6
+ * useSuspense() + useSubscription()
7
+ * @see https://dataclient.io/docs/api/useLive
8
+ * @throws {Promise} If data is not yet available.
9
+ * @throws {NetworkError} If fetch fails.
10
+ */
11
+ export default function useLive<E extends EndpointInterface<FetchFunction, Schema | undefined, undefined | false>>(endpoint: E, ...args: readonly [...Parameters<E>]): Promise<DeepReadonly<ComputedRef<E['schema'] extends undefined | null ? ResolveType<E> : Denormalize<E['schema']>>>>;
12
+ export default function useLive<E extends EndpointInterface<FetchFunction, Schema | undefined, undefined | false>>(endpoint: E, ...args: readonly [...Parameters<E>] | readonly [null]): Promise<DeepReadonly<ComputedRef<E['schema'] extends undefined | null ? ResolveType<E> | undefined : DenormalizeNullable<E['schema']>>>>;
13
+ //# sourceMappingURL=useLive.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useLive.d.ts","sourceRoot":"","sources":["../../src/consumers/useLive.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EACjB,WAAW,EACX,MAAM,EACN,aAAa,EACb,WAAW,EACX,mBAAmB,EACpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,KAAK,CAAC;AAKrD;;;;;;;GAOG;AACH,MAAM,CAAC,OAAO,UAAU,OAAO,CAC7B,CAAC,SAAS,iBAAiB,CACzB,aAAa,EACb,MAAM,GAAG,SAAS,EAClB,SAAS,GAAG,KAAK,CAClB,EAED,QAAQ,EAAE,CAAC,EACX,GAAG,IAAI,EAAE,SAAS,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC,GACnC,OAAO,CACR,YAAY,CACV,WAAW,CACT,CAAC,CAAC,QAAQ,CAAC,SAAS,SAAS,GAAG,IAAI,GAAG,WAAW,CAAC,CAAC,CAAC,GACnD,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAC3B,CACF,CACF,CAAC;AAEF,MAAM,CAAC,OAAO,UAAU,OAAO,CAC7B,CAAC,SAAS,iBAAiB,CACzB,aAAa,EACb,MAAM,GAAG,SAAS,EAClB,SAAS,GAAG,KAAK,CAClB,EAED,QAAQ,EAAE,CAAC,EACX,GAAG,IAAI,EAAE,SAAS,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,IAAI,CAAC,GACrD,OAAO,CACR,YAAY,CACV,WAAW,CACT,CAAC,CAAC,QAAQ,CAAC,SAAS,SAAS,GAAG,IAAI,GAAG,WAAW,CAAC,CAAC,CAAC,GAAG,SAAS,GAC/D,mBAAmB,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CACnC,CACF,CACF,CAAC"}
@@ -0,0 +1,17 @@
1
+ import useSubscription from './useSubscription.js';
2
+ import useSuspense from './useSuspense.js';
3
+
4
+ /**
5
+ * Ensure an endpoint is available. Keeps it fresh once it is.
6
+ *
7
+ * useSuspense() + useSubscription()
8
+ * @see https://dataclient.io/docs/api/useLive
9
+ * @throws {Promise} If data is not yet available.
10
+ * @throws {NetworkError} If fetch fails.
11
+ */
12
+
13
+ export default async function useLive(endpoint, ...args) {
14
+ useSubscription(endpoint, ...args);
15
+ return useSuspense(endpoint, ...args);
16
+ }
17
+ //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJ1c2VTdWJzY3JpcHRpb24iLCJ1c2VTdXNwZW5zZSIsInVzZUxpdmUiLCJlbmRwb2ludCIsImFyZ3MiXSwic291cmNlcyI6WyIuLi8uLi9zcmMvY29uc3VtZXJzL3VzZUxpdmUudHMiXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHR5cGUge1xuICBFbmRwb2ludEludGVyZmFjZSxcbiAgRGVub3JtYWxpemUsXG4gIFNjaGVtYSxcbiAgRmV0Y2hGdW5jdGlvbixcbiAgUmVzb2x2ZVR5cGUsXG4gIERlbm9ybWFsaXplTnVsbGFibGUsXG59IGZyb20gJ0BkYX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Q2xDLE9BQU9ILFdBQVcsQ0FBQ0UsUUFBUSxFQUFFLEdBQUdDLElBQUksQ0FBQztBQUN2QyIsImlnbm9yZUxpc3QiOltdfQ==
@@ -0,0 +1,18 @@
1
+ import { type Ref } from 'vue';
2
+ /**
3
+ * Takes an async function and tracks resolution as a boolean.
4
+ *
5
+ * @see https://dataclient.io/docs/api/useLoading
6
+ * @param func A function returning a promise
7
+ * @example
8
+ ```
9
+ function Button({ onClick, children, ...props }) {
10
+ const [clickHandler, loading] = useLoading(onClick);
11
+ return h('button', { onClick: clickHandler, ...props },
12
+ loading.value ? 'Loading...' : children
13
+ );
14
+ }
15
+ ```
16
+ */
17
+ export default function useLoading<F extends (...args: any) => Promise<any>>(func: F): [F, Ref<boolean>, Ref<Error | undefined>];
18
+ //# sourceMappingURL=useLoading.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useLoading.d.ts","sourceRoot":"","sources":["../../src/consumers/useLoading.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,GAAG,EAAE,MAAM,KAAK,CAAC;AAEjD;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,OAAO,UAAU,UAAU,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC,EACzE,IAAI,EAAE,CAAC,GACN,CAAC,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,EAAE,GAAG,CAAC,KAAK,GAAG,SAAS,CAAC,CAAC,CA2B3C"}
@@ -0,0 +1,44 @@
1
+ import { ref, onUnmounted } from 'vue';
2
+
3
+ /**
4
+ * Takes an async function and tracks resolution as a boolean.
5
+ *
6
+ * @see https://dataclient.io/docs/api/useLoading
7
+ * @param func A function returning a promise
8
+ * @example
9
+ ```
10
+ function Button({ onClick, children, ...props }) {
11
+ const [clickHandler, loading] = useLoading(onClick);
12
+ return h('button', { onClick: clickHandler, ...props },
13
+ loading.value ? 'Loading...' : children
14
+ );
15
+ }
16
+ ```
17
+ */
18
+ export default function useLoading(func) {
19
+ const loading = ref(false);
20
+ const error = ref(undefined);
21
+ const isMounted = ref(true);
22
+ onUnmounted(() => {
23
+ isMounted.value = false;
24
+ });
25
+
26
+ // Create the wrapped function directly - no need for computed in Vue
27
+ const wrappedFunc = async (...args) => {
28
+ loading.value = true;
29
+ error.value = undefined;
30
+ let ret;
31
+ try {
32
+ ret = await func(...args);
33
+ } catch (e) {
34
+ error.value = e;
35
+ } finally {
36
+ if (isMounted.value) {
37
+ loading.value = false;
38
+ }
39
+ }
40
+ return ret;
41
+ };
42
+ return [wrappedFunc, loading, error];
43
+ }
44
+ //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJyZWYiLCJvblVubW91bnRlZCIsInVzZUxvYWRpbmciLCJmdW5jIiwibG9hZGluZyIsImVycm9yIiwidW5kZWZpbmVkIiwiaXNNb3VudGVkIiwidmFsdWUiLCJ3cmFwcGVkRnVuYyIsImFyZ3MiLCJyZXQiLCJlIl0sInNvdXJjZXMiOlsiLi4vLi4vc3JjL2NvbnN1bWVycy91c2VMb2FkaW5nLnRzIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7IHJlZiwgb25Vbm1vdW50ZWQsIHR5cGUgUmVmIH0gZnJvbSAndnVlJztcblxuLyoqXG4gKiBUYWtlcyBhbiBhc3luYyBmdW5jdGlvbiBhbmQgdHJhY2tzIHJlc29sdXRpb24gYXMgYSBib29sZWFuLlxuICpcbiAqIEBzZWUgaHR0cHM6Ly9kYXRhY2xpZW50LmlvL2RvY3MvYXBpL3VzZUxvYWRpbmdcbiAqIEBwYXJhbSBmdW5jIEEgZnVuY3Rpb24gcmV0dXJuaW5nIGEgcHJvbWlzZVxuICogQGV4YW1wbGVcbiBgYGBcbiBmdW5jdGlvbiBCdXR0b24oeyBvbkNsaWNrLCBjaGlsZHJlbiwgLi4ucHJvcHMgfSkge1xuICAgY29uc3QgW2NsaWNrSGF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