@data-client/core 0.16.0 → 0.18.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 +165 -0
- package/README.md +1 -1
- package/dist/index.js +17 -14
- package/dist/index.umd.min.js +1 -1
- package/dist/mock.js +17 -14
- package/legacy/controller/Controller.js +19 -16
- package/lib/controller/Controller.d.ts.map +1 -1
- package/lib/controller/Controller.js +19 -16
- package/package.json +3 -3
- package/src/controller/Controller.ts +17 -16
- package/src/controller/__tests__/getResponse.ts +144 -1
- package/src/controller/__tests__/getResponseMeta-countRef.ts +93 -0
- package/src/controller/__tests__/getResponseMeta-paths.ts +88 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,170 @@
|
|
|
1
1
|
# @data-client/core
|
|
2
2
|
|
|
3
|
+
## 0.18.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#3931](https://github.com/reactive/data-client/pull/3931) [`959465a`](https://github.com/reactive/data-client/commit/959465a064db687176e483932987b083f19718eb) - Allow one `Collection` schema to be used both top-level and nested.
|
|
8
|
+
|
|
9
|
+
Before:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
const getTodos = new Collection([Todo], { argsKey });
|
|
13
|
+
const userTodos = new Collection([Todo], { nestKey });
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
After:
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
const userTodos = new Collection([Todo], { argsKey, nestKey });
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
- [#3887](https://github.com/reactive/data-client/pull/3887) [`84078d7`](https://github.com/reactive/data-client/commit/84078d7d36bf5cf0fd16a479ce16c48c5d804f32) - **BREAKING**: `Schema.denormalize()` is now `(input, delegate)` instead
|
|
23
|
+
of the previous `(input, args, unvisit)` 3-parameter signature.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
// before
|
|
27
|
+
denormalize(input, args, unvisit) {
|
|
28
|
+
return unvisit(this.schema, input);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// after
|
|
32
|
+
denormalize(input, delegate) {
|
|
33
|
+
return delegate.unvisit(this.schema, input);
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The new [`IDenormalizeDelegate`](https://dataclient.io/rest/api/CustomSchema)
|
|
38
|
+
exposes `unvisit`, `args`, and a new `argsKey(fn)` helper that registers
|
|
39
|
+
a memoization dimension when output varies with endpoint args. Reading
|
|
40
|
+
`delegate.args` directly does _not_ contribute to cache invalidation —
|
|
41
|
+
schemas that branch on args must call `argsKey`. The `fn` reference
|
|
42
|
+
doubles as the cache path key, so it must be **referentially stable**
|
|
43
|
+
— define it on the instance or at module scope, not inline per call:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
class LensSchema {
|
|
47
|
+
constructor({ lens }) {
|
|
48
|
+
this.lensSelector = lens; // stable reference across calls
|
|
49
|
+
}
|
|
50
|
+
denormalize(input, delegate) {
|
|
51
|
+
const portfolio = delegate.argsKey(this.lensSelector);
|
|
52
|
+
return this.lookup(input, portfolio);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
All built-in schemas (`Array`, `Object`, `Values`, `Union`, `Query`,
|
|
58
|
+
`Invalidate`, `Lazy`, `Collection`) have been updated. Custom schemas
|
|
59
|
+
implementing `SchemaSimple` must update their `denormalize` signature.
|
|
60
|
+
|
|
61
|
+
`Schema.normalize()` and the `visit()` callback also gain an optional
|
|
62
|
+
trailing `parentEntity` argument tracking the nearest enclosing
|
|
63
|
+
entity-like schema. This is additive — existing schemas don't need
|
|
64
|
+
changes unless they want to use it.
|
|
65
|
+
|
|
66
|
+
- [#3887](https://github.com/reactive/data-client/pull/3887) [`84078d7`](https://github.com/reactive/data-client/commit/84078d7d36bf5cf0fd16a479ce16c48c5d804f32) - Add [Scalar](https://dataclient.io/rest/api/Scalar) schema for lens-dependent entity fields.
|
|
67
|
+
|
|
68
|
+
`Scalar` models entity fields whose values vary by a runtime "lens" (such as the
|
|
69
|
+
selected portfolio, currency, or locale). Multiple components can render the
|
|
70
|
+
same entity through different lenses simultaneously — each sees the correct
|
|
71
|
+
values without the entity itself ever being mutated. Lens-dependent values are
|
|
72
|
+
stored in a separate cell table and joined at denormalize time from endpoint
|
|
73
|
+
args.
|
|
74
|
+
|
|
75
|
+
New exports: `Scalar`, `schema.Scalar`.
|
|
76
|
+
|
|
77
|
+
A single `Scalar` instance can serve both as an `Entity.schema` field (parent
|
|
78
|
+
entity inferred from the visit) and standalone — inside `Values(Scalar)`,
|
|
79
|
+
`[Scalar]`, or `Collection([Scalar])` — for cheap column-only refreshes
|
|
80
|
+
(entity bound explicitly via `entity`). Cell pks are derived from the map key
|
|
81
|
+
or via `Scalar.entityPk()`, which defaults to `Entity.pk()` so custom and
|
|
82
|
+
composite primary keys work with no override:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { Collection, Entity, RestEndpoint, Scalar } from '@data-client/rest';
|
|
86
|
+
|
|
87
|
+
class Company extends Entity {
|
|
88
|
+
id = '';
|
|
89
|
+
price = 0;
|
|
90
|
+
pct_equity = 0;
|
|
91
|
+
shares = 0;
|
|
92
|
+
}
|
|
93
|
+
const PortfolioScalar = new Scalar({
|
|
94
|
+
lens: args => args[0]?.portfolio,
|
|
95
|
+
key: 'portfolio',
|
|
96
|
+
entity: Company,
|
|
97
|
+
});
|
|
98
|
+
Company.schema = {
|
|
99
|
+
pct_equity: PortfolioScalar,
|
|
100
|
+
shares: PortfolioScalar,
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
// Full load — Company rows + scalar cells for the current portfolio
|
|
104
|
+
export const getCompanies = new RestEndpoint({
|
|
105
|
+
path: '/companies',
|
|
106
|
+
searchParams: {} as { portfolio: string },
|
|
107
|
+
schema: new Collection([Company], { argsKey: () => ({}) }),
|
|
108
|
+
});
|
|
109
|
+
// Lens-only refresh — writes to the same Scalar(portfolio) cell table
|
|
110
|
+
export const getPortfolioColumns = new RestEndpoint({
|
|
111
|
+
path: '/companies/columns',
|
|
112
|
+
searchParams: {} as { portfolio: string },
|
|
113
|
+
schema: new Collection([PortfolioScalar], {
|
|
114
|
+
argsKey: ({ portfolio }) => ({ portfolio }),
|
|
115
|
+
}),
|
|
116
|
+
});
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`useSuspense(getCompanies, { portfolio: 'A' })` and
|
|
120
|
+
`useSuspense(getCompanies, { portfolio: 'B' })` resolve to different
|
|
121
|
+
`pct_equity` / `shares` while sharing the same `Company` row.
|
|
122
|
+
|
|
123
|
+
`Scalar.queryKey` enumerates cells in its table for the current lens, so
|
|
124
|
+
endpoints that use `Scalar` directly as their top-level schema reconstruct
|
|
125
|
+
from cache without a network round-trip once the cells are present.
|
|
126
|
+
|
|
127
|
+
### Patch Changes
|
|
128
|
+
|
|
129
|
+
- [#3925](https://github.com/reactive/data-client/pull/3925) [`6e8e499`](https://github.com/reactive/data-client/commit/6e8e499441741b58ad35127b517e8d83fc7a58fd) - Fix cached journey being mutated on repeated result-cache hits.
|
|
130
|
+
|
|
131
|
+
`GlobalCache.getResults` called `paths.shift()` on a cache hit, mutating
|
|
132
|
+
the `journey` array stored by reference on the `WeakDependencyMap` `Link`
|
|
133
|
+
node. After the first hit stripped the placeholder input slot, every
|
|
134
|
+
subsequent hit on the same cached entry would shift off a real
|
|
135
|
+
`EntityPath`, progressively losing subscription entries. This could cause
|
|
136
|
+
missed `countRef` tracking (premature GC of still-referenced entities)
|
|
137
|
+
and incorrect `entityExpiresAt` calculations. The hit path now returns a
|
|
138
|
+
non-mutating copy.
|
|
139
|
+
|
|
140
|
+
- Updated dependencies [[`959465a`](https://github.com/reactive/data-client/commit/959465a064db687176e483932987b083f19718eb), [`84078d7`](https://github.com/reactive/data-client/commit/84078d7d36bf5cf0fd16a479ce16c48c5d804f32), [`6e8e499`](https://github.com/reactive/data-client/commit/6e8e499441741b58ad35127b517e8d83fc7a58fd), [`396d163`](https://github.com/reactive/data-client/commit/396d163e6f4991818519ec33d903a85437483dfd), [`84078d7`](https://github.com/reactive/data-client/commit/84078d7d36bf5cf0fd16a479ce16c48c5d804f32)]:
|
|
141
|
+
- @data-client/normalizr@0.18.0
|
|
142
|
+
|
|
143
|
+
## 0.16.7
|
|
144
|
+
|
|
145
|
+
### Patch Changes
|
|
146
|
+
|
|
147
|
+
- [`fd64b41`](https://github.com/reactive/data-client/commit/fd64b41a9de266af51708622ea8991060fd788a5) - Include `@data-client/normalizr@0.16.6` performance improvements:
|
|
148
|
+
- [#3875](https://github.com/reactive/data-client/pull/3875) [`467a5f6`](https://github.com/reactive/data-client/commit/467a5f6f9d4cdaf0927fa7e22520c5d2c1462ff5) - Fix deepClone to only copy own properties
|
|
149
|
+
|
|
150
|
+
`deepClone` in the immutable store path now uses `Object.keys()` instead of `for...in`, preventing inherited properties from being copied into cloned state.
|
|
151
|
+
|
|
152
|
+
- [#3877](https://github.com/reactive/data-client/pull/3877) [`e9e96f1`](https://github.com/reactive/data-client/commit/e9e96f1751895c17e046461a1c38bb4bb093c141) - Replace megamorphic computed dispatch in getDependency with switch
|
|
153
|
+
|
|
154
|
+
`getDependency` used `delegate[array[index]](...spread)` which creates a temporary array, a computed property lookup, and a spread call on every invocation — a megamorphic pattern that prevents V8 from inlining or type-specializing the call site. Replaced with a `switch` on `path.length` for monomorphic dispatch.
|
|
155
|
+
|
|
156
|
+
- [#3876](https://github.com/reactive/data-client/pull/3876) [`7d28629`](https://github.com/reactive/data-client/commit/7d28629d07f6cade43e36f3cf1956f175f98d84f) - Improve denormalization performance by pre-allocating the dependency tracking slot
|
|
157
|
+
|
|
158
|
+
Replace `Array.prototype.unshift()` in `GlobalCache.getResults()` with a pre-allocated slot at index 0, avoiding O(n) element shifting on every cache-miss denormalization.
|
|
159
|
+
|
|
160
|
+
- [#3884](https://github.com/reactive/data-client/pull/3884) [`7df6a49`](https://github.com/reactive/data-client/commit/7df6a49ee9fcdac10f9f24ec48c4df0931efa0b0) - Move entity table POJO clone from getNewEntities to setEntity
|
|
161
|
+
|
|
162
|
+
Lazy-clone entity and meta tables on first write per entity type instead of eagerly in getNewEntities. This keeps getNewEntities as a pure Map operation, eliminating its V8 Maglev bailout ("Insufficient type feedback for generic named access" on `this.entities`).
|
|
163
|
+
|
|
164
|
+
- [#3878](https://github.com/reactive/data-client/pull/3878) [`98a7831`](https://github.com/reactive/data-client/commit/98a78318770feaa8433708693bec90b81cbcb1b2) - Avoid hidden class mutation in normalize() return object
|
|
165
|
+
|
|
166
|
+
The normalize result object was constructed with `result: '' as any` then mutated via `ret.result = visit(...)`, causing a V8 hidden class transition when the property type changed from string to the actual result type. Restructured to compute the result first and construct the final object in a single step.
|
|
167
|
+
|
|
3
168
|
## 0.16.0
|
|
4
169
|
|
|
5
170
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -18,7 +18,7 @@ automatic expiry policies, data normalization. Consumes [TypeScript Standard End
|
|
|
18
18
|
|
|
19
19
|
<div align="center">
|
|
20
20
|
|
|
21
|
-
**[📖Read The Docs](https://dataclient.io/docs)** | [🏁Getting Started](https://dataclient.io/docs/getting-started/
|
|
21
|
+
**[📖Read The Docs](https://dataclient.io/docs)** | [🏁Getting Started](https://dataclient.io/docs/getting-started/agent-skills) |
|
|
22
22
|
[🎮Todo Demo](https://stackblitz.com/github/reactive/data-client/tree/master/examples/todo-app?file=src%2Fpages%2FHome%2FTodoList.tsx) |
|
|
23
23
|
[🎮Github Demo](https://stackblitz.com/github/reactive/data-client/tree/master/examples/github-app?file=src%2Fpages%2FIssueList.tsx) |
|
|
24
24
|
[🎮NextJS SSR Demo](https://stackblitz.com/github/reactive/data-client/tree/master/examples/nextjs?file=components%2Ftodo%2FTodoList.tsx)
|
package/dist/index.js
CHANGED
|
@@ -912,7 +912,7 @@ class Controller {
|
|
|
912
912
|
if (shouldQuery) {
|
|
913
913
|
isInvalid = !normalizr.validateQueryKey(input);
|
|
914
914
|
// endpoint without entities
|
|
915
|
-
} else if (!schema || !
|
|
915
|
+
} else if (!schema || !requiresDenormalize(schema)) {
|
|
916
916
|
return {
|
|
917
917
|
data: cacheEndpoints,
|
|
918
918
|
expiryStatus: this.getExpiryStatus(!cacheEndpoints, !!endpoint.invalidIfStale, meta),
|
|
@@ -996,21 +996,24 @@ function entityExpiresAt(paths, entitiesMeta) {
|
|
|
996
996
|
return expiresAt;
|
|
997
997
|
}
|
|
998
998
|
|
|
999
|
-
/**
|
|
999
|
+
/** Whether `denormalize()` must run to reconstruct the response.
|
|
1000
1000
|
*
|
|
1001
|
-
*
|
|
1001
|
+
* True iff some node in the schema tree defines `normalize` — meaning it
|
|
1002
|
+
* transforms the response when written (entity write, polymorphic hoist,
|
|
1003
|
+
* lazy delegation, etc.), so the cached value differs from the response.
|
|
1004
|
+
* Mirrors the dispatch in `getVisit.ts`: schema classes are detected here
|
|
1005
|
+
* by the same hook the visit walker uses, so we never need to walk their
|
|
1006
|
+
* instance fields.
|
|
1002
1007
|
*/
|
|
1003
|
-
function
|
|
1004
|
-
if (
|
|
1005
|
-
if (Array.isArray(schema)) return schema.length !== 0 &&
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
}
|
|
1013
|
-
return false;
|
|
1008
|
+
function requiresDenormalize(schema) {
|
|
1009
|
+
if (!schema) return false;
|
|
1010
|
+
if (Array.isArray(schema)) return schema.length !== 0 && requiresDenormalize(schema[0]);
|
|
1011
|
+
// Must reject primitives before probing `.normalize` — `String.prototype.normalize` exists.
|
|
1012
|
+
const t = typeof schema;
|
|
1013
|
+
if (t !== 'object' && t !== 'function') return false;
|
|
1014
|
+
if (typeof schema.normalize === 'function') return true;
|
|
1015
|
+
// Plain-object schema map (e.g. `{ data: [Tacos], page: { ... } }`).
|
|
1016
|
+
return Object.values(schema).some(x => requiresDenormalize(x));
|
|
1014
1017
|
}
|
|
1015
1018
|
class Snapshot {
|
|
1016
1019
|
static abort = new AbortOptimistic();
|
package/dist/index.umd.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).RDC=e.RDC||{},e.RDC.Core={}))}(this,(function(e){"use strict";class t{constructor(){this.localCache=new Map}getEntity(e,t,n,i){const s=t.key;this.localCache.has(s)||this.localCache.set(s,new Map);const r=this.localCache.get(s);return r.get(e)||i(r),r.get(e)}getResults(e,t,n){return{data:n(),paths:[]}}}const n=Symbol("INVALID"),i={};function s(e){return null!==e&&void 0!==e.pk}const r=e=>e[0],o=e=>void 0!==e&&"symbol"!=typeof e,a=(e,t,n,i,s,o)=>{e=r(e);const a=(e=>Array.isArray(e)?e:Object.keys(e).map((t=>e[t])))(t);return a.map((t=>o(e,t,n,i,s)))},c=(e,t,n,i)=>(e=r(e),t.map?t.map((t=>i(e,t))).filter(o):t);function h(){}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},l.apply(null,arguments)}const u=(e,t,n,i,s,r)=>{const o=l({},t),a=Object.keys(e);for(let n=0;n<a.length;n++){const i=a[n],c=r(e[i],t[i],t,i,s);void 0===c?delete o[i]:o[i]=c}return o},d=(e,t,i,s)=>{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,i,s){let r=!1;const o=Object.keys(e).reduce(((t,n)=>{const i=`${n}`,o=s(e[i],t.get(i));return"symbol"==typeof o&&(r=!0),t.has(i)?t.set(i,o):t}),t);return r?n:o}(e,t,0,s);const r=l({},t);let o=!1;const a=Object.keys(e);for(let t=0;t<a.length;t++){const n=a[t],i=s(e[n],r[n]);void 0!==r[n]&&(r[n]=i),"symbol"==typeof i&&(o=!0)}return o?n:r};function p(e,t,n,i){const s={};for(const r of Object.keys(e))s[r]=n(e[r],t,i);return s}const f=(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 h=a?o:r.pk(c,void 0,void 0,n);return void 0===h||""===h||"undefined"===h?function(e){const t=new Map;return e(t),t.get("")}((e=>y(r,c,"",e,n,s))):("string"!=typeof h&&(h=`${h}`),t.getEntity(h,r,c,(e=>y(r,c,h,e,n,s))))};function y(e,t,i,s,r,o){const a=e.createIfValid(t);void 0===a?s.set(i,n):(s.set(i,a),s.set(i,e.denormalize(a,r,o)))}const g=(e,t,i)=>{let r=0;const o=f(e,t,i,a);function a(t,h){if(!t)return h;if(null==h)return h;if("function"==typeof t.denormalize){if(s(t)){var l;if(r>=(null!=(l=t.maxEntityDepth)?l:64))return function(e,t,i){var s;const r="object"!=typeof i?e({key:t.key,pk:i}):i;return"object"!=typeof r||null===r?r:null!=(s=t.createIfValid(r))?s:n}(e,t,h);r++;const i=o(t,h);return r--,i}return t.denormalize(h,i,a)}if("function"==typeof t)return t(h);if("object"==typeof t){return(Array.isArray(t)?c:d)(t,h,i,a)}return h}return(e,n)=>{const i=Object(n)===n&&Object(e)===e;return t.getResults(n,i,(()=>a(e,n)))}};class m{constructor({entities:e,indexes:t}){this.entities=e,this.indexes=t}tracked(e){const t=this,i=[{path:[""],entity:e}];return[{INVALID:n,getIndex(...e){const n=t.getIndex(...e);return i.push({path:e,entity:n}),t.getIndexEnd(n,e[2])},getEntity(...e){const n=t.getEntity(...e);return i.push({path:e,entity:n}),n},getEntities(e){const n=t.getEntitiesObject(e);return i.push({path:[e],entity:n}),t.getEntities(e)}},i]}}class v extends m{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 E={QueryDelegate:v,getEntities:e=>({key:t,pk:n})=>{var i;return null==(i=e[t])?void 0:i[n]}};class w{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 k;let n=this;for(const{path:t,entity:s}of e){let e=n.next.get(s);e||(e=new b,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 b{constructor(){this.next=new WeakMap,this.nextPath=void 0,this.value=void 0,this.journey=[]}}class k extends Error{constructor(...e){super(...e),this.message="Keys must include at least one member"}}class I extends v{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,i){let s=e.get(t);s||(s=new Map,e.set(t,s));let r=s.get(n);return r||(r=new Set,s.set(n,r)),!!r.has(i)||(r.add(i),!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]=l({},this.entities[e]),this.entitiesMeta[e]=l({},this.entitiesMeta[e])),this.newEntities.get(e)}getNewIndexes(e){return this.newIndexes.has(e)||(this.newIndexes.set(e,new Map),this.indexes[e]=l({},this.indexes[e])),this.newIndexes.get(e)}mergeEntity(e,t,n){const i=e.key;let s=n,r=this.meta,o=this.getNewEntity(i,t);if(o)s=e.merge(o,n);else if(o=this.getEntity(i,t),o){const a=this.getMeta(i,t);s=e.mergeWithStore(a,r,o,n),r=e.mergeMetaWithStore(a,r,o,n)}this.setEntity(e,t,s,r)}setEntity(e,t,i,s=this.meta){const r=e.key,o=this.getNewEntities(r),a=!o.has(t);o.set(t,i),e.indexes&&function(e,t,i,s,r,o){for(const a of t){i.has(a)||i.set(a,s[a]={});const t=i.get(a);o[e]&&delete t[o[e][a]],o&&o[e]&&o[e][a]!==r[a]&&(t[o[e][a]]=n),a in r&&(t[r[a]]=e)}}(t,e.indexes,this.getNewIndexes(r),this.indexes[r],i,this.entities[r]),this._setEntity(r,t,i),a&&this._setMeta(r,t,s)}invalidate({key:e},t){this.setEntity({key:e},t,n)}_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:i,indexes:s,entitiesMeta:r}=L,o={fetchedAt:0,date:Date.now(),expiresAt:1/0})=>{if(null==e)return{result:t,entities:i,indexes:s,entitiesMeta:r};const c=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(e);if(null===t||typeof t!==c&&(void 0===e.key||void 0!==e.pk||"string"!=typeof t))throw new Error(`Unexpected input given to normalize. Expected type to be "${c}", found "${null===t?"null":typeof t}".`);const h={result:"",entities:l({},i),indexes:l({},s),entitiesMeta:l({},r)},d=(e=>{const t=(n,i,s,r,o)=>i&&n?n.normalize&&"function"==typeof n.normalize?"object"!=typeof i?n.pk?`${i}`:i:n.normalize(i,s,r,o,t,e):"object"!=typeof i||"object"!=typeof n?i:(Array.isArray(n)?a:u)(n,i,s,r,o,t):i;return t})(new I(h,o));return h.result=d(e,t,t,void 0,n),h};const L={entities:{},indexes:{},entitiesMeta:{}};class S{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,i){const s=t.key,{localCacheKey:r,cycleCacheKey:o}=this.getCacheKey(s);if(r.get(e))o.has(e)?this.cycleIndex=o.get(e):this.dependencies.push({path:{key:s,pk:e},entity:n});else{const a=this._getCache(e,t),[c,h]=a.get(n,this._getEntity);if(h)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:s,pk:e},entity:n}),i(r),o.delete(e);const c=this.dependencies.slice(-1===this.cycleIndex?t:this.cycleIndex),h={dependencies:c,value:r.get(e)};a.set(c,h),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[i,s]=this._resultCache.get(e,this._getEntity);return void 0===s?(i=n(),s=this.paths(),this.dependencies.unshift({path:{key:"",pk:""},entity:e}),this._resultCache.set(this.dependencies,i)):s.shift(),{data:i,paths:s}}paths(){return this.dependencies.map((e=>e.path))}}function M(e){return void 0!==e&&(!(e&&"object"==typeof e&&!Array.isArray(e))||Object.values(e).every(M))}class C{constructor(e=E){var t;this.endpoints=new w,this.queryKeys=new Map,this.policy=e,this._getCache=(t=new Map,(e,n)=>{var i;const s=n.key,r=null!=(i=n.cacheWith)?i:n;t.has(s)||t.set(s,new Map);const o=t.get(s);o.has(e)||o.set(e,new WeakMap);const a=o.get(e);let c=a.get(r);return c||(c=new w,a.set(r,c)),c})}denormalize(e,t,n,i=[]){if(void 0===e)return{data:t,paths:[]};if(void 0===t)return{data:void 0,paths:[]};const s=this.policy.getEntities(n);return g(s,new S(s,this._getCache,this.endpoints),i)(e,t)}query(e,t,n,i=JSON.stringify(t)){const s=this.buildQueryKey(e,t,n,i);return s?this.denormalize(e,s,n.entities,t):{data:void 0,paths:[]}}buildQueryKey(e,t,n,i=JSON.stringify(t)){if("object"!=typeof e&&"function"!=typeof e.queryKey||!e)return e;let s=this.queryKeys.get(i);s||(s=new w,this.queryKeys.set(i,s));const r=new this.policy.QueryDelegate(n);let[o,a]=s.get(e,(c=r,e=>c[["","getEntitiesObject","getEntity","getIndex"][e.length]](...e)));var c;if(!a){const[n,i]=r.tracked(e);o=function(e){return function t(n,i){return function(e){return!!e&&"function"==typeof e.queryKey}(n)?n.queryKey(i,t,e):"object"==typeof n&&n?(Array.isArray(n)?h:p)(n,i,t,e):n}}(n)(e,t),s.set(i,o)}return o}}var O={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 R="rdc/fetch",j="rdc/set",P="rdc/setresponse",T="rdc/optimistic",q="rdc/reset",D="rdc/subscribe",N="rdc/unsubscribe",K="rdc/invalidate",z="rdc/invalidateall",Q="rdc/expireall",H="rdc/gc",F=R,V=j,B=P,U=T,Y=q,$=D,W=N,X=K,G=z,J=Q,Z=H;var ee=Object.freeze({__proto__:null,EXPIREALL:Q,EXPIREALL_TYPE:J,FETCH:R,FETCH_TYPE:F,GC:H,GC_TYPE:Z,INVALIDATE:K,INVALIDATEALL:z,INVALIDATEALL_TYPE:G,INVALIDATE_TYPE:X,OPTIMISTIC:T,OPTIMISTIC_TYPE:U,RESET:q,RESET_TYPE:Y,SET:j,SET_RESPONSE:P,SET_RESPONSE_TYPE:B,SET_TYPE:V,SUBSCRIBE:D,SUBSCRIBE_TYPE:$,UNSUBSCRIBE:N,UNSUBSCRIBE_TYPE:W});const te="undefined"!=typeof FormData?e=>e instanceof FormData?Object.fromEntries(e.entries()):e:e=>e;function ne(e,t,n){var i;return{type:T,key:e.key(...t),args:t.map(te),endpoint:e,meta:_(null!=(i=e.dataExpiryLength)?i:6e4,n)}}class ie extends Error{}function se(e,t,n){return"AbortError"===n.name?l({},e,{optimistic:re(e,t)}):l({},e,{meta:l({},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===T?e.meta.fetchedAt!==t.meta.fetchedAt:e.meta.date>t.meta.date)))}const oe={entities:{},endpoints:{},indexes:{},meta:{},entitiesMeta:{},optimistic:[],lastReset:0};var ae=Object.freeze({__proto__:null,INVALID:n,MemoCache:C,initialState:oe});function ce(e,{args:t}){return{type:D,key:e.key(...t),args:t,endpoint:e}}function he(e,{args:t}){return{type:N,key:e.key(...t),args:t,endpoint:e}}function le(e,{args:t,fetchedAt:n,response:i,error:s=!1}){var r,o;const a=s?null!=(r=e.errorExpiryLength)?r:1e3:null!=(o=e.dataExpiryLength)?o:6e4;return{type:P,key:e.key(...t),response:i,args:t.map(te),endpoint:e,meta:_(a,n),error:s}}function ue(e,{args:t,fetchedAt:n,value:i}){return{type:j,value:i,args:t.map(te),schema:e,meta:_(6e4,n)}}function de(){return{type:q,date:Date.now()}}function pe(e){return{type:z,testKey:e}}function fe(e,{args:t}){return{type:K,key:e.key(...t)}}function ye(e,{args:t}){let n=0,i=0;const s=new Promise(((e,t)=>{[n,i]=[e,t]})),r={fetchedAt:Date.now(),resolve:n,reject:i,promise:s};return{type:R,key:e.key(...t),args:t,endpoint:e,meta:r}}function ge(e){return{type:Q,testKey:e}}var me=Object.freeze({__proto__:null,createExpireAll:ge,createFetch:ye,createInvalidate:fe,createInvalidateAll:pe,createMeta:_,createOptimistic:ne,createReset:de,createSet:ue,createSetResponse:le,createSubscription:ce,createUnsubscription:he});class ve{init(){}cleanup(){}createCountRef(){return()=>()=>{}}}function Ee(e,t){return e.meta[t]}const we=e=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")},xe=()=>oe;class be{constructor({dispatch:e=we,getState:n=xe,memo:i=new C,gcPolicy:s=new ve}={}){this.fetch=(e,...n)=>{const i=ye(e,{args:n});return this.dispatch(i),e.schema?i.meta.promise.then((i=>function(e,n,i,s=[]){return void 0===e||void 0===n?n:g(E.getEntities(i),new t,s)(e,n).data}(e.schema,i,{},n))):i.meta.promise},this.fetchIfStale=(e,...t)=>{const{data:n,expiresAt:i,expiryStatus:s}=this.getResponseMeta(e,...t,this.getState());return s!==O.Invalid&&Date.now()<=i?n:this.fetch(e,...t)},this.invalidate=(e,...t)=>null!==t[0]?this.dispatch(fe(e,{args:t})):Promise.resolve(),this.invalidateAll=e=>this.dispatch(pe((t=>e.testKey(t)))),this.expireAll=e=>this.dispatch(ge((t=>e.testKey(t)))),this.resetEntireStore=()=>this.dispatch(de()),this.setResponse=(e,...t)=>{const n=t[t.length-1],i=le(e,{args:t.slice(0,t.length-1),response:n});return this.dispatch(i)},this.setError=(e,...t)=>{const n=t[t.length-1],i=le(e,{args:t.slice(0,t.length-1),response:n,error:!0});return this.dispatch(i)},this.resolve=(e,t)=>this.dispatch(le(e,t)),this.subscribe=(e,...t)=>null!==t[0]?this.dispatch(ce(e,{args:t})):Promise.resolve(),this.unsubscribe=(e,...t)=>null!==t[0]?this.dispatch(he(e,{args:t})):Promise.resolve(),this.snapshot=(e,t)=>new Ie(this,e,t),this._dispatch=e,this.getState=n,this.memo=i,this.gcPolicy=s}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],i=ue(e,{args:t.slice(0,t.length-1),value:n});return this.dispatch(i)}getError(e,...t){if(null===t[0])return;const n=t[t.length-1],i=t.slice(0,t.length-1),s=e.key(...i),r=Ee(n,s);return void 0===n.endpoints[s]||"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,i]=Ae(t),s=1!==i.length||null!==i[0],r=s?e.key(...i):"",o=s?n.endpoints[r]:void 0,a=e.schema,c=Ee(n,r);let h=null==c?void 0:c.expiresAt;const l=void 0===o&&void 0!==a,u=l?this.memo.buildQueryKey(a,i,n,r):o;if(!s)return{data:u,expiryStatus:O.Valid,expiresAt:1/0,countRef:()=>()=>{}};let d=!1;if(l)d=!M(u);else if(!a||!ke(a))return{data:o,expiryStatus:this.getExpiryStatus(!o,!!e.invalidIfStale,c),expiresAt:h||0,countRef:this.gcPolicy.createCountRef({key:r})};const{data:p,paths:f}=this.memo.denormalize(a,u,n.entities,i);return h||(h=d?1:function(e,t){let n=1/0;for(const{key:s,pk:r}of e){var i;const e=null==(i=t[s])||null==(i=i[r])?void 0:i.expiresAt;e<n&&(n=e)}return n}(f,n.entitiesMeta)),{data:p,expiryStatus:this.getExpiryStatus("symbol"==typeof p,!!e.invalidIfStale||d,c),expiresAt:h,countRef:this.gcPolicy.createCountRef({key:r,paths:f})}}get(e,...t){const[n,i]=Ae(t),{data:s}=this.memo.query(e,i,n);return"symbol"==typeof s?void 0:s}getQueryMeta(e,...t){const[n,i]=Ae(t),{data:s,paths:r}=this.memo.query(e,i,n);return{data:"symbol"==typeof s?void 0:s,countRef:this.gcPolicy.createCountRef({paths:r})}}getExpiryStatus(e,t,n={}){return n.invalidated||e&&!n.error?O.Invalid:e||t?O.InvalidIfStale:O.Valid}}function ke(e){if(s(e))return!0;if(Array.isArray(e))return 0!==e.length&&ke(e[0]);if(e&&("object"==typeof e||"function"==typeof e)){const t="schema"in e?e.schema:e;return"function"==typeof t?ke(t):Object.values(t).some((e=>ke(e)))}return!1}class Ie{constructor(e,t,n=0){this.state=void 0,this.controller=void 0,this.fetchedAt=void 0,this.abort=Ie.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)}}function Ae(e){const t=e.length,n=new Array(t-1);for(let i=0;i<t-1;i++)n[i]=te(e[i]);return[e[t-1],n]}Ie.abort=new ie;class Le extends Error{constructor(){super("Aborted due to RESET"),this.name="ResetError"}}class Se{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 Me{isOnline(){return!0}addOnlineListener(){}removeOnlineListener(){}addOfflineListener(){}removeOfflineListener(){}}let Ce;Ce="undefined"!=typeof navigator&&"function"==typeof addEventListener?Se:Me;var Oe=Ce;let _e={};class Re{constructor(e,t){var n,i;this.started=!1,this.actions=[],this.maxBufferLength=100;const s=l({},_e,e);this.devtoolsName=null!=(n=s.name)?n:`Data Client: ${null==(i=globalThis.document)?void 0:i.title}`,this.devTools="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__.connect(s),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(){}}Re.prototype.middleware=()=>e=>t=>e(t);e.Controller=be,e.DefaultConnectionListener=Oe,e.DevToolsManager=Re,e.ExpiryStatus=O,e.GCPolicy=class{constructor({intervalMS:e=3e5,expiryMultiplier:t=2,expiresAt:n}={}){this.endpointCount=new Map,this.entityCount=new Map,this.endpointsQ=new Set,this.entitiesQ=[],n&&(this.expiresAt=n.bind(this)),this.options={intervalMS:e,expiryMultiplier:t}}init(e){this.controller=e,this.intervalId=setInterval((()=>{this.idleCallback((()=>this.runSweep()),{timeout:1e3})}),this.options.intervalMS),"object"==typeof this.intervalId&&"unref"in this.intervalId&&this.intervalId.unref()}cleanup(){clearInterval(this.intervalId)}createCountRef({key:e,paths:t=[]}){return()=>{var n;return e&&this.endpointCount.set(e,(null!=(n=this.endpointCount.get(e))?n:0)+1),t.forEach((e=>{var t;const{key:n,pk:i}=e;this.entityCount.has(n)||this.entityCount.set(n,new Map);const s=this.entityCount.get(n);s.set(i,(null!=(t=s.get(i))?t:0)+1)})),()=>{if(e){const t=this.endpointCount.get(e);void 0!==t&&(t<=1?(this.endpointCount.delete(e),this.endpointsQ.add(e)):this.endpointCount.set(e,t-1))}t.forEach((e=>{const{key:t,pk:n}=e;if(!this.entityCount.has(t))return;const i=this.entityCount.get(t),s=i.get(n);void 0!==s&&(s<=1?(i.delete(n),this.entitiesQ.push(e)):i.set(n,s-1))}))}}}expiresAt({fetchedAt:e,expiresAt:t}){return Math.max((t-e)*this.options.expiryMultiplier,12e4)+e}runSweep(){const e=this.controller.getState(),t=[],n=[],i=Date.now(),s=new Set;for(const t of this.endpointsQ){var r;!this.endpointCount.has(t)&&this.expiresAt(null!=(r=e.meta[t])?r:{fetchedAt:0,date:0,expiresAt:0})<i?n.push(t):s.add(t)}this.endpointsQ=s;const o=[];for(const n of this.entitiesQ){var a,c,h;(null==(a=this.entityCount.get(n.key))||!a.has(n.pk))&&this.expiresAt(null!=(c=null==(h=e.entitiesMeta[n.key])?void 0:h[n.pk])?c:{fetchedAt:0,date:0,expiresAt:0})<i?t.push(n):o.push(n)}this.entitiesQ=o,(t.length||n.length)&&this.controller.dispatch({type:H,entities:t,endpoints:n})}idleCallback(e,t){"function"==typeof requestIdleCallback?requestIdleCallback(e,t):e()}},e.ImmortalGCPolicy=ve,e.LogoutManager=class{constructor({handleLogout:e,shouldLogout:t}={}){this.middleware=e=>t=>async n=>{await t(n),n.type===P&&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=class{constructor({dataExpiryLength:e=6e4,errorExpiryLength:t=1e3}={}){this.fetching=new Map,this.controller=new be,this.middleware=e=>(this.controller=e,t=>n=>{switch(n.type){case R:return this.handleFetch(n),void 0!==n.endpoint.getOptimisticResponse&&n.endpoint.sideEffect?t(n):Promise.resolve();case P:return t(n).then((()=>{if(this.fetching.has(n.key)){var t;const i=null==(t=e.getState().meta[n.key])?void 0:t.error;i?this.handleSet(le(n.endpoint,{args:n.args,response:i,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 Le)}))}default:return t(n)}}),this.dataExpiryLength=e,this.errorExpiryLength=t}init(){delete this.cleanupDate}cleanup(){this.cleanupDate=Date.now()}skipLogging(e){return e.type===R&&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:i}=e.meta,s=!e.endpoint.sideEffect,r=()=>{let r=e.endpoint(...e.args);return s||(r=(e=>e.then((e=>(t(e),e))).catch((e=>{throw n(e),e})))(r)),r=r.then((t=>{let n=this.getLastReset();return i>=n&&this.controller.resolve(e.endpoint,{args:e.args,response:t,fetchedAt:i}),t})).catch((t=>{const n=this.getLastReset();throw i>=n&&this.controller.resolve(e.endpoint,{args:e.args,response:t,fetchedAt:i,error:!0}),t})),r};return s?this.throttle(e.key,r,i).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 i=this.getLastReset();let s=this.fetching.get(e);return s&&s.fetchedAt>i||(s=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,s),this.idleCallback((()=>{t().catch((()=>null))}),{timeout:500})),s.promise}idleCallback(e,t){e()}},e.PollingSubscription=class{constructor(e,t,n){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===e.endpoint.pollFrequency)throw new Error("frequency needed for polling subscription");this.endpoint=e.endpoint,this.frequency=e.endpoint.pollFrequency,this.args=e.args,this.key=e.key,this.frequencyHistogram.set(this.frequency,1),this.controller=t,this.connectionListener=n||new Oe,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}},e.ResetError=Le,e.SubscriptionManager=class{constructor(e){this.subscriptions={},this.controller=new be,this.middleware=e=>(this.controller=e,e=>t=>{switch(t.type){case D:try{this.handleSubscribe(t)}catch(e){console.error(e)}return Promise.resolve();case N: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]}}},e.__INTERNAL__=ae,e.actionTypes=ee,e.actions=me,e.applyManager=function(e,t){return e.map(((e,n)=>(e.middleware||(e.middleware=null==e.getMiddleware?void 0:e.getMiddleware()),i=>(0===n&&t.bindMiddleware(i),e.middleware(t)))))},e.createReducer=function(e){return function(t,n){switch(t||(t=oe),n.type){case H:return n.entities.forEach((({key:e,pk:n})=>{var i,s;null==(i=t.entities[e])||delete i[n],null==(s=t.entitiesMeta[e])||delete s[n]})),n.endpoints.forEach((e=>{delete t.endpoints[e],delete t.meta[e]})),t;case R:return function(e,t){if(t.endpoint.getOptimisticResponse&&t.endpoint.sideEffect){const n=ne(t.endpoint,t.args,t.meta.fetchedAt);return l({},e,{optimistic:[...e.optimistic,n]})}return e}(t,n);case T:case P:return function(e,t,n){if(t.error)return se(e,t,t.response);try{var i;let s;if(t.type===T){if(!t.endpoint.getOptimisticResponse)return e;try{s=t.endpoint.getOptimisticResponse.call(t.endpoint,n.snapshot(e,t.meta.fetchedAt),...t.args)}catch(t){if(t.constructor===ie)return e;throw t}}else s=t.response;const{result:r,entities:o,indexes:a,entitiesMeta:c}=A(t.endpoint.schema,s,t.args,e,t.meta),h=l({},e.endpoints,{[t.key]:r});try{if(t.endpoint.update){const e=t.endpoint.update(r,...t.args);Object.keys(e).forEach((t=>{h[t]=e[t](h[t])}))}}catch(e){console.error(`Endpoint.update() error: ${t.key}`),console.error(e)}return{entities:o,endpoints:h,indexes:a,meta:l({},e.meta,{[t.key]:{date:t.meta.date,fetchedAt:t.meta.fetchedAt,expiresAt:t.meta.expiresAt,prevExpiresAt:null==(i=e.meta[t.key])?void 0:i.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),se(e,t,n)}}(t,n,e);case j:return function(e,t,n){let i;if("function"==typeof t.value){const s=n.get(t.schema,...t.args,e);if(void 0===s)return e;i=t.value(s)}else i=t.value;try{const{entities:n,indexes:s,entitiesMeta:r}=A(t.schema,i,t.args,e,t.meta);return{entities:n,endpoints:e.endpoints,indexes:s,meta:e.meta,entitiesMeta:r,optimistic:e.optimistic,lastReset:e.lastReset}}catch(t){return e}}(t,n,e);case z:case K:return function(e,t){const n=l({},e.endpoints),i=l({},e.meta),s=e=>{delete n[e];const t=l({},i[e],{expiresAt:0,invalidated:!0});delete t.error,i[e]=t};return t.type===K?s(t.key):Object.keys(n).forEach((e=>{t.testKey(e)&&s(e)})),l({},e,{endpoints:n,meta:i})}(t,n);case Q:return function(e,t){const n=l({},e.meta);return Object.keys(n).forEach((e=>{t.testKey(e)&&(n[e]=l({},n[e],{expiresAt:1}))})),l({},e,{meta:n})}(t,n);case q:return l({},oe,{lastReset:n.date});default:return t}}},e.initManager=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()})},e.initialState=oe}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(((e="undefined"!=typeof globalThis?globalThis:e||self).RDC=e.RDC||{},e.RDC.Core={}))}(this,(function(e){"use strict";class t{constructor(e=[]){this.localCache=new Map,this._args=e}getEntity(e,t,n,i){const s=t.key;this.localCache.has(s)||this.localCache.set(s,new Map);const r=this.localCache.get(s);return r.get(e)||i(r),r.get(e)}getResults(e,t,n){return{data:n(),paths:[]}}argsKey(e){return e(this._args)}}const n=Symbol("INVALID"),i={};const s=e=>e[0],r=e=>void 0!==e&&"symbol"!=typeof e,o=(e,t,n,i,r)=>{e=s(e);const o=(e=>Array.isArray(e)?e:Object.keys(e).map((t=>e[t])))(t);return o.map((t=>r.visit(e,t,n,i)))},a=(e,t,n)=>(e=s(e),t.map?t.map((t=>n.unvisit(e,t))).filter(r):t);function c(){}function h(){return h=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)({}).hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},h.apply(null,arguments)}const l=(e,t,n,i,s)=>{const r=h({},t),o=Object.keys(e);for(let n=0;n<o.length;n++){const i=o[n],a=e[i],c=s.visit(a,t[i],t,i);void 0===c?delete r[i]:r[i]=c}return r},u=(e,t,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,i){let s=!1;const r=Object.keys(e).reduce(((t,n)=>{const r=`${n}`,o=i.unvisit(e[r],t.get(r));return"symbol"==typeof o&&(s=!0),t.has(r)?t.set(r,o):t}),t);return s?n:r}(e,t,i);const s=h({},t);let r=!1;const o=Object.keys(e);for(let t=0;t<o.length;t++){const n=o[t],a=i.unvisit(e[n],s[n]);void 0!==s[n]&&(s[n]=a),"symbol"==typeof a&&(r=!0)}return r?n:s};function d(e,t,n,i){const s={};for(const r of Object.keys(e))s[r]=n(e[r],t,i);return s}const p=(e,t,n)=>function(s,r){const o="object"!=typeof r,a=o?e({key:s.key,pk:r}):r;if("symbol"==typeof a)return s.denormalize(a,n);if(void 0===a&&o&&""!==r&&"undefined"!==r)return t.getEntity(r,s,i,(e=>{e.set(r,void 0)}));if("object"!=typeof a||null===a)return a;let c=o?r:s.pk(a,void 0,void 0,n.args);return void 0===c||""===c||"undefined"===c?function(e){const t=new Map;return e(t),t.get("")}((e=>f(s,a,"",e,n))):("string"!=typeof c&&(c=`${c}`),t.getEntity(c,s,a,(e=>f(s,a,c,e,n))))};function f(e,t,i,s,r){const o=e.createIfValid(t);void 0===o?s.set(i,n):(s.set(i,o),s.set(i,e.denormalize(o,r)))}const y=(e,t,i)=>{let s=0;const r={args:i,unvisit:c,argsKey:e=>t.argsKey(e)},o=p(e,t,r);function c(t,i){if(!t)return i;if(null==i)return i;if("function"==typeof t.denormalize){if(function(e){return null!==e&&void 0!==e.pk}(t)){var c;if(s>=(null!=(c=t.maxEntityDepth)?c:64))return function(e,t,i){var s;const r="object"!=typeof i?e({key:t.key,pk:i}):i;return"object"!=typeof r||null===r?r:null!=(s=t.createIfValid(r))?s:n}(e,t,i);s++;const r=o(t,i);return s--,r}return"function"==typeof t.createIfValid&&"string"==typeof i?o(t,i):t.denormalize(i,r)}if("function"==typeof t)return t(i);if("object"==typeof t){return(Array.isArray(t)?a:u)(t,i,r)}return i}return(e,n)=>{const i=Object(n)===n&&Object(e)===e;return t.getResults(n,i,(()=>c(e,n)))}};class g{constructor({entities:e,indexes:t}){this.entities=e,this.indexes=t}tracked(e){const t=this,i=[{path:[""],entity:e}];return[{INVALID:n,getIndex(...e){const n=t.getIndex(...e);return i.push({path:e,entity:n}),t.getIndexEnd(n,e[2])},getEntity(...e){const n=t.getEntity(...e);return i.push({path:e,entity:n}),n},getEntities(e){const n=t.getEntitiesObject(e);return i.push({path:[e],entity:n}),t.getEntities(e)}},i]}}class v extends g{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 m={QueryDelegate:v,getEntities:e=>({key:t,pk:n})=>{var i;return null==(i=e[t])?void 0:i[n]}};class E{constructor(){this.next=new WeakMap,this.nextPath=void 0,this.hasStr=!1}get(e,t,n=[]){let s=this.next.get(e);if(!s)return x;if(this.hasStr)return this._getMixed(s,t,n);for(;s.nextPath;){var r;const e=null!=(r=t(s.nextPath))?r:i,n=s.next.get(e);if(!n)return x;s=n}return[s.value,s.journey]}_getMixed(e,t,n){for(;e.nextPath;){let a;if("function"==typeof e.nextPath){var s,r;const t=null!=(s=e.nextPath(n))?s:"\0";a=null==(r=e.nextStr)?void 0:r.get(t)}else{var o;const n=null!=(o=t(e.nextPath))?o:i;a=e.next.get(n)}if(!a)return x;e=a}return[e.value,e.journey]}set(e,t,n=[],s){if(e.length<1)throw new k;let r=this;for(const t of e){let e;if("function"==typeof t.path){var o;this.hasStr=!0,r.nextStr||(r.nextStr=new Map);const i=null!=(o=t.path(n))?o:"\0";e=r.nextStr.get(i),e||(e=new w,r.nextStr.set(i,e))}else{var a;if(e=r.next.get(t.entity),!e)e=new w,r.next.set(null!=(a=t.entity)?a:i,e)}r.nextPath=t.path,r=e}r.nextPath=void 0,r.value=t,r.journey=null!=s?s:e.map((e=>e.path))}get hasStringDeps(){return this.hasStr}}const x=[void 0,void 0];class w{constructor(){this.next=new WeakMap,this.nextStr=void 0,this.nextPath=void 0,this.value=void 0,this.journey=[]}}class k extends Error{constructor(...e){super(...e),this.message="Keys must include at least one member"}}class b extends v{constructor(e,t,n){super(e),this.newEntities=new Map,this.newIndexes=new Map,this.entitiesMeta=e.entitiesMeta,this.args=t,this.meta=n,this.checkLoop=function(){const e=new Map;return function(t,n,i){let s=e.get(t);s||(s=new Map,e.set(t,s));let r=s.get(n);return r||(r=new Set,s.set(n,r)),!!r.has(i)||(r.add(i),!1)}}()}getNewEntity(e,t){return this.getNewEntities(e).get(t)}getNewEntities(e){let t=this.newEntities.get(e);return void 0===t&&(t=new Map,this.newEntities.set(e,t)),t}getNewIndexes(e){return this.newIndexes.has(e)||(this.newIndexes.set(e,new Map),this.indexes[e]=h({},this.indexes[e])),this.newIndexes.get(e)}mergeEntity(e,t,n){const i=e.key;let s=n,r=this.meta,o=this.getNewEntity(i,t);if(o)s=e.merge(o,n);else if(o=this.getEntity(i,t),o){const a=this.getMeta(i,t);s=e.mergeWithStore(a,r,o,n),r=e.mergeMetaWithStore(a,r,o,n)}this.setEntity(e,t,s,r)}setEntity(e,t,i,s=this.meta){const r=e.key,o=this.getNewEntities(r),a=!o.has(t);a&&0===o.size&&(this.entities[r]=h({},this.entities[r]),this.entitiesMeta[r]=h({},this.entitiesMeta[r])),o.set(t,i),e.indexes&&function(e,t,i,s,r,o){for(const a of t){i.has(a)||i.set(a,s[a]={});const t=i.get(a);o[e]&&delete t[o[e][a]],o&&o[e]&&o[e][a]!==r[a]&&(t[o[e][a]]=n),a in r&&(t[r[a]]=e)}}(t,e.indexes,this.getNewIndexes(r),this.indexes[r],i,this.entities[r]),this._setEntity(r,t,i),a&&this._setMeta(r,t,s)}invalidate({key:e},t){this.setEntity({key:e},t,n)}_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 I=(e,t,n=[],{entities:i,indexes:s,entitiesMeta:r}=A,a={fetchedAt:0,date:Date.now(),expiresAt:1/0})=>{if(null==e)return{result:t,entities:i,indexes:s,entitiesMeta:r};const c=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(e);if(null===t||typeof t!==c&&(void 0===e.key||void 0!==e.pk||"string"!=typeof t))throw new Error(`Unexpected input given to normalize. Expected type to be "${c}", found "${null===t?"null":typeof t}".`);const u={entities:h({},i),indexes:h({},s),entitiesMeta:h({},r)},d=(e=>{let t;const n=(n,i,s,r)=>{if(null==i||!n)return i;if("object"!=typeof i){if("function"!=typeof n.normalize)return i;if(!n.acceptsPrimitives)return i&&n.pk?`${i}`:i}if("function"==typeof n.normalize){const o=t;n.pk&&(t=n);const a=n.normalize(i,s,r,e,o);return t=o,a}return"object"!=typeof n?i:(Array.isArray(n)?o:l)(n,i,s,r,e)};return e.visit=n,n})(new b(u,n,a));return{result:d(e,t,t,void 0),entities:u.entities,indexes:u.indexes,entitiesMeta:u.entitiesMeta}};const A={entities:{},indexes:{},entitiesMeta:{}},S={path:{key:"",pk:""},entity:void 0};class L{constructor(e,t,n,i=[]){this.dependencies=[S],this.cycleCache=new Map,this.cycleIndex=-1,this.localCache=new Map,this._hasArgsKey=!1,this._getEntity=e,this._getCache=t,this._resultCache=n,this._args=i}argsKey(e){return this._hasArgsKey=!0,this.dependencies.push({path:e,entity:void 0}),e(this._args)}getEntity(e,t,n,i){const s=t.key,r=this.getOrCreateLocalCache(s);if(r.get(e)){const t=this.cycleCache.get(s);null!=t&&t.has(e)?this.cycleIndex=t.get(e):this.dependencies.push({path:{key:s,pk:e},entity:n})}else{const o=this._getCache(e,t),[a,c]=o.get(n,this._getEntity,this._args);if(c){r.set(e,a.value);const t=a.dependencies;for(let e=0;e<t.length;e++)this.dependencies.push(t[e]);return o.hasStringDeps&&(this._hasArgsKey=!0),a.value}{const t=this.dependencies.length,a=this.getOrCreateCycleCache(s);a.set(e,t),this.dependencies.push({path:{key:s,pk:e},entity:n}),i(r),a.delete(e);const c=this.dependencies.slice(-1===this.cycleIndex?t:this.cycleIndex),h={dependencies:c,value:r.get(e)};o.set(c,h,this._args),this.cycleIndex===t&&(this.cycleIndex=-1)}}return r.get(e)}getOrCreateLocalCache(e){let t=this.localCache.get(e);return t||(t=new Map,this.localCache.set(e,t)),t}getOrCreateCycleCache(e){let t=this.cycleCache.get(e);return t||(t=new Map,this.cycleCache.set(e,t)),t}getResults(e,t,n){if(!t)return{data:n(),paths:this.paths()};let[i,s]=this._resultCache.get(e,this._getEntity,this._args);return void 0===s&&(i=n(),s=this.paths(),this.dependencies[0]={path:{key:"",pk:""},entity:e},this._resultCache.set(this.dependencies,i,this._args,s)),{data:i,paths:s}}paths(){const e=this.dependencies;if(!this._hasArgsKey){const t=new Array(e.length-1);for(let n=1;n<e.length;n++)t[n-1]=e[n].path;return t}const t=[];for(let n=1;n<e.length;n++){const i=e[n].path;"function"!=typeof i&&t.push(i)}return t}}function M(e){return void 0!==e&&(!(e&&"object"==typeof e&&!Array.isArray(e))||Object.values(e).every(M))}class _{constructor(e=m){var t;this.endpoints=new E,this.queryKeys=new Map,this.policy=e,this._getCache=(t=new Map,(e,n)=>{var i;const s=n.key,r=null!=(i=n.cacheWith)?i:n;t.has(s)||t.set(s,new Map);const o=t.get(s);o.has(e)||o.set(e,new WeakMap);const a=o.get(e);let c=a.get(r);return c||(c=new E,a.set(r,c)),c})}denormalize(e,t,n,i=[]){if(void 0===e)return{data:t,paths:[]};if(void 0===t)return{data:void 0,paths:[]};const s=this.policy.getEntities(n);return y(s,new L(s,this._getCache,this.endpoints,i),i)(e,t)}query(e,t,n,i=JSON.stringify(t)){const s=this.buildQueryKey(e,t,n,i);return s?this.denormalize(e,s,n.entities,t):{data:void 0,paths:[]}}buildQueryKey(e,t,n,i=JSON.stringify(t)){if("object"!=typeof e&&"function"!=typeof e.queryKey||!e)return e;let s=this.queryKeys.get(i);s||(s=new E,this.queryKeys.set(i,s));const r=new this.policy.QueryDelegate(n);let[o,a]=s.get(e,(h=r,e=>{switch(e.length){case 1:return h.getEntitiesObject(e[0]);case 2:return h.getEntity(e[0],e[1]);case 3:return h.getIndex(e[0],e[1],e[2])}}));var h;if(!a){const[n,i]=r.tracked(e);o=function(e){return function t(n,i){if(function(e){return!!e&&"function"==typeof e.queryKey}(n)){if(1===i.length&&null===i[0])return;return n.queryKey(i,t,e)}return"object"==typeof n&&n?(Array.isArray(n)?c:d)(n,i,t,e):n}}(n)(e,t),s.set(i,o)}return o}}var C={Invalid:1,InvalidIfStale:2,Valid:3};function O(e,t){const n=Date.now();return{fetchedAt:null!=t?t:n,date:n,expiresAt:n+e}}const R="rdc/fetch",P="rdc/set",j="rdc/setresponse",T="rdc/optimistic",q="rdc/reset",D="rdc/subscribe",N="rdc/unsubscribe",K="rdc/invalidate",z="rdc/invalidateall",Q="rdc/expireall",H="rdc/gc",V=R,F=P,B=j,U=T,Y=q,$=D,W=N,X=K,G=z,J=Q,Z=H;var ee=Object.freeze({__proto__:null,EXPIREALL:Q,EXPIREALL_TYPE:J,FETCH:R,FETCH_TYPE:V,GC:H,GC_TYPE:Z,INVALIDATE:K,INVALIDATEALL:z,INVALIDATEALL_TYPE:G,INVALIDATE_TYPE:X,OPTIMISTIC:T,OPTIMISTIC_TYPE:U,RESET:q,RESET_TYPE:Y,SET:P,SET_RESPONSE:j,SET_RESPONSE_TYPE:B,SET_TYPE:F,SUBSCRIBE:D,SUBSCRIBE_TYPE:$,UNSUBSCRIBE:N,UNSUBSCRIBE_TYPE:W});const te="undefined"!=typeof FormData?e=>e instanceof FormData?Object.fromEntries(e.entries()):e:e=>e;function ne(e,t,n){var i;return{type:T,key:e.key(...t),args:t.map(te),endpoint:e,meta:O(null!=(i=e.dataExpiryLength)?i:6e4,n)}}class ie extends Error{}function se(e,t,n){return"AbortError"===n.name?h({},e,{optimistic:re(e,t)}):h({},e,{meta:h({},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===T?e.meta.fetchedAt!==t.meta.fetchedAt:e.meta.date>t.meta.date)))}const oe={entities:{},endpoints:{},indexes:{},meta:{},entitiesMeta:{},optimistic:[],lastReset:0};var ae=Object.freeze({__proto__:null,INVALID:n,MemoCache:_,initialState:oe});function ce(e,{args:t}){return{type:D,key:e.key(...t),args:t,endpoint:e}}function he(e,{args:t}){return{type:N,key:e.key(...t),args:t,endpoint:e}}function le(e,{args:t,fetchedAt:n,response:i,error:s=!1}){var r,o;const a=s?null!=(r=e.errorExpiryLength)?r:1e3:null!=(o=e.dataExpiryLength)?o:6e4;return{type:j,key:e.key(...t),response:i,args:t.map(te),endpoint:e,meta:O(a,n),error:s}}function ue(e,{args:t,fetchedAt:n,value:i}){return{type:P,value:i,args:t.map(te),schema:e,meta:O(6e4,n)}}function de(){return{type:q,date:Date.now()}}function pe(e){return{type:z,testKey:e}}function fe(e,{args:t}){return{type:K,key:e.key(...t)}}function ye(e,{args:t}){let n=0,i=0;const s=new Promise(((e,t)=>{[n,i]=[e,t]})),r={fetchedAt:Date.now(),resolve:n,reject:i,promise:s};return{type:R,key:e.key(...t),args:t,endpoint:e,meta:r}}function ge(e){return{type:Q,testKey:e}}var ve=Object.freeze({__proto__:null,createExpireAll:ge,createFetch:ye,createInvalidate:fe,createInvalidateAll:pe,createMeta:O,createOptimistic:ne,createReset:de,createSet:ue,createSetResponse:le,createSubscription:ce,createUnsubscription:he});class me{init(){}cleanup(){}createCountRef(){return()=>()=>{}}}function Ee(e,t){return e.meta[t]}const xe=e=>{throw new Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")},we=()=>oe;class ke{constructor({dispatch:e=xe,getState:n=we,memo:i=new _,gcPolicy:s=new me}={}){this.fetch=(e,...n)=>{const i=ye(e,{args:n});return this.dispatch(i),e.schema?i.meta.promise.then((i=>function(e,n,i,s=[]){return void 0===e||void 0===n?n:y(m.getEntities(i),new t(s),s)(e,n).data}(e.schema,i,{},n))):i.meta.promise},this.fetchIfStale=(e,...t)=>{const{data:n,expiresAt:i,expiryStatus:s}=this.getResponseMeta(e,...t,this.getState());return s!==C.Invalid&&Date.now()<=i?n:this.fetch(e,...t)},this.invalidate=(e,...t)=>null!==t[0]?this.dispatch(fe(e,{args:t})):Promise.resolve(),this.invalidateAll=e=>this.dispatch(pe((t=>e.testKey(t)))),this.expireAll=e=>this.dispatch(ge((t=>e.testKey(t)))),this.resetEntireStore=()=>this.dispatch(de()),this.setResponse=(e,...t)=>{const n=t[t.length-1],i=le(e,{args:t.slice(0,t.length-1),response:n});return this.dispatch(i)},this.setError=(e,...t)=>{const n=t[t.length-1],i=le(e,{args:t.slice(0,t.length-1),response:n,error:!0});return this.dispatch(i)},this.resolve=(e,t)=>this.dispatch(le(e,t)),this.subscribe=(e,...t)=>null!==t[0]?this.dispatch(ce(e,{args:t})):Promise.resolve(),this.unsubscribe=(e,...t)=>null!==t[0]?this.dispatch(he(e,{args:t})):Promise.resolve(),this.snapshot=(e,t)=>new Ie(this,e,t),this._dispatch=e,this.getState=n,this.memo=i,this.gcPolicy=s}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],i=ue(e,{args:t.slice(0,t.length-1),value:n});return this.dispatch(i)}getError(e,...t){if(null===t[0])return;const n=t[t.length-1],i=t.slice(0,t.length-1),s=e.key(...i),r=Ee(n,s);return void 0===n.endpoints[s]||"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,i]=Ae(t),s=1!==i.length||null!==i[0],r=s?e.key(...i):"",o=s?n.endpoints[r]:void 0,a=e.schema,c=Ee(n,r);let h=null==c?void 0:c.expiresAt;const l=void 0===o&&void 0!==a,u=l?this.memo.buildQueryKey(a,i,n,r):o;if(!s)return{data:u,expiryStatus:C.Valid,expiresAt:1/0,countRef:()=>()=>{}};let d=!1;if(l)d=!M(u);else if(!a||!be(a))return{data:o,expiryStatus:this.getExpiryStatus(!o,!!e.invalidIfStale,c),expiresAt:h||0,countRef:this.gcPolicy.createCountRef({key:r})};const{data:p,paths:f}=this.memo.denormalize(a,u,n.entities,i);return h||(h=d?1:function(e,t){let n=1/0;for(const{key:s,pk:r}of e){var i;const e=null==(i=t[s])||null==(i=i[r])?void 0:i.expiresAt;e<n&&(n=e)}return n}(f,n.entitiesMeta)),{data:p,expiryStatus:this.getExpiryStatus("symbol"==typeof p,!!e.invalidIfStale||d,c),expiresAt:h,countRef:this.gcPolicy.createCountRef({key:r,paths:f})}}get(e,...t){const[n,i]=Ae(t),{data:s}=this.memo.query(e,i,n);return"symbol"==typeof s?void 0:s}getQueryMeta(e,...t){const[n,i]=Ae(t),{data:s,paths:r}=this.memo.query(e,i,n);return{data:"symbol"==typeof s?void 0:s,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 be(e){if(!e)return!1;if(Array.isArray(e))return 0!==e.length&&be(e[0]);const t=typeof e;return("object"===t||"function"===t)&&("function"==typeof e.normalize||Object.values(e).some((e=>be(e))))}class Ie{constructor(e,t,n=0){this.state=void 0,this.controller=void 0,this.fetchedAt=void 0,this.abort=Ie.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)}}function Ae(e){const t=e.length,n=new Array(t-1);for(let i=0;i<t-1;i++)n[i]=te(e[i]);return[e[t-1],n]}Ie.abort=new ie;class Se extends Error{constructor(){super("Aborted due to RESET"),this.name="ResetError"}}class Le{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 Me{isOnline(){return!0}addOnlineListener(){}removeOnlineListener(){}addOfflineListener(){}removeOfflineListener(){}}let _e;_e="undefined"!=typeof navigator&&"function"==typeof addEventListener?Le:Me;var Ce=_e;let Oe={};class Re{constructor(e,t){var n,i;this.started=!1,this.actions=[],this.maxBufferLength=100;const s=h({},Oe,e);this.devtoolsName=null!=(n=s.name)?n:`Data Client: ${null==(i=globalThis.document)?void 0:i.title}`,this.devTools="undefined"!=typeof window&&window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__.connect(s),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(){}}Re.prototype.middleware=()=>e=>t=>e(t);e.Controller=ke,e.DefaultConnectionListener=Ce,e.DevToolsManager=Re,e.ExpiryStatus=C,e.GCPolicy=class{constructor({intervalMS:e=3e5,expiryMultiplier:t=2,expiresAt:n}={}){this.endpointCount=new Map,this.entityCount=new Map,this.endpointsQ=new Set,this.entitiesQ=[],n&&(this.expiresAt=n.bind(this)),this.options={intervalMS:e,expiryMultiplier:t}}init(e){this.controller=e,this.intervalId=setInterval((()=>{this.idleCallback((()=>this.runSweep()),{timeout:1e3})}),this.options.intervalMS),"object"==typeof this.intervalId&&"unref"in this.intervalId&&this.intervalId.unref()}cleanup(){clearInterval(this.intervalId)}createCountRef({key:e,paths:t=[]}){return()=>{var n;return e&&this.endpointCount.set(e,(null!=(n=this.endpointCount.get(e))?n:0)+1),t.forEach((e=>{var t;const{key:n,pk:i}=e;this.entityCount.has(n)||this.entityCount.set(n,new Map);const s=this.entityCount.get(n);s.set(i,(null!=(t=s.get(i))?t:0)+1)})),()=>{if(e){const t=this.endpointCount.get(e);void 0!==t&&(t<=1?(this.endpointCount.delete(e),this.endpointsQ.add(e)):this.endpointCount.set(e,t-1))}t.forEach((e=>{const{key:t,pk:n}=e;if(!this.entityCount.has(t))return;const i=this.entityCount.get(t),s=i.get(n);void 0!==s&&(s<=1?(i.delete(n),this.entitiesQ.push(e)):i.set(n,s-1))}))}}}expiresAt({fetchedAt:e,expiresAt:t}){return Math.max((t-e)*this.options.expiryMultiplier,12e4)+e}runSweep(){const e=this.controller.getState(),t=[],n=[],i=Date.now(),s=new Set;for(const t of this.endpointsQ){var r;!this.endpointCount.has(t)&&this.expiresAt(null!=(r=e.meta[t])?r:{fetchedAt:0,date:0,expiresAt:0})<i?n.push(t):s.add(t)}this.endpointsQ=s;const o=[];for(const n of this.entitiesQ){var a,c,h;(null==(a=this.entityCount.get(n.key))||!a.has(n.pk))&&this.expiresAt(null!=(c=null==(h=e.entitiesMeta[n.key])?void 0:h[n.pk])?c:{fetchedAt:0,date:0,expiresAt:0})<i?t.push(n):o.push(n)}this.entitiesQ=o,(t.length||n.length)&&this.controller.dispatch({type:H,entities:t,endpoints:n})}idleCallback(e,t){"function"==typeof requestIdleCallback?requestIdleCallback(e,t):e()}},e.ImmortalGCPolicy=me,e.LogoutManager=class{constructor({handleLogout:e,shouldLogout:t}={}){this.middleware=e=>t=>async n=>{await t(n),n.type===j&&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=class{constructor({dataExpiryLength:e=6e4,errorExpiryLength:t=1e3}={}){this.fetching=new Map,this.controller=new ke,this.middleware=e=>(this.controller=e,t=>n=>{switch(n.type){case R:return this.handleFetch(n),void 0!==n.endpoint.getOptimisticResponse&&n.endpoint.sideEffect?t(n):Promise.resolve();case j:return t(n).then((()=>{if(this.fetching.has(n.key)){var t;const i=null==(t=e.getState().meta[n.key])?void 0:t.error;i?this.handleSet(le(n.endpoint,{args:n.args,response:i,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 Se)}))}default:return t(n)}}),this.dataExpiryLength=e,this.errorExpiryLength=t}init(){delete this.cleanupDate}cleanup(){this.cleanupDate=Date.now()}skipLogging(e){return e.type===R&&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:i}=e.meta,s=!e.endpoint.sideEffect,r=()=>{let r=e.endpoint(...e.args);return s||(r=(e=>e.then((e=>(t(e),e))).catch((e=>{throw n(e),e})))(r)),r=r.then((t=>{let n=this.getLastReset();return i>=n&&this.controller.resolve(e.endpoint,{args:e.args,response:t,fetchedAt:i}),t})).catch((t=>{const n=this.getLastReset();throw i>=n&&this.controller.resolve(e.endpoint,{args:e.args,response:t,fetchedAt:i,error:!0}),t})),r};return s?this.throttle(e.key,r,i).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 i=this.getLastReset();let s=this.fetching.get(e);return s&&s.fetchedAt>i||(s=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,s),this.idleCallback((()=>{t().catch((()=>null))}),{timeout:500})),s.promise}idleCallback(e,t){e()}},e.PollingSubscription=class{constructor(e,t,n){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===e.endpoint.pollFrequency)throw new Error("frequency needed for polling subscription");this.endpoint=e.endpoint,this.frequency=e.endpoint.pollFrequency,this.args=e.args,this.key=e.key,this.frequencyHistogram.set(this.frequency,1),this.controller=t,this.connectionListener=n||new Ce,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}},e.ResetError=Se,e.SubscriptionManager=class{constructor(e){this.subscriptions={},this.controller=new ke,this.middleware=e=>(this.controller=e,e=>t=>{switch(t.type){case D:try{this.handleSubscribe(t)}catch(e){console.error(e)}return Promise.resolve();case N: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]}}},e.__INTERNAL__=ae,e.actionTypes=ee,e.actions=ve,e.applyManager=function(e,t){return e.map(((e,n)=>(e.middleware||(e.middleware=null==e.getMiddleware?void 0:e.getMiddleware()),i=>(0===n&&t.bindMiddleware(i),e.middleware(t)))))},e.createReducer=function(e){return function(t,n){switch(t||(t=oe),n.type){case H:return n.entities.forEach((({key:e,pk:n})=>{var i,s;null==(i=t.entities[e])||delete i[n],null==(s=t.entitiesMeta[e])||delete s[n]})),n.endpoints.forEach((e=>{delete t.endpoints[e],delete t.meta[e]})),t;case R:return function(e,t){if(t.endpoint.getOptimisticResponse&&t.endpoint.sideEffect){const n=ne(t.endpoint,t.args,t.meta.fetchedAt);return h({},e,{optimistic:[...e.optimistic,n]})}return e}(t,n);case T:case j:return function(e,t,n){if(t.error)return se(e,t,t.response);try{var i;let s;if(t.type===T){if(!t.endpoint.getOptimisticResponse)return e;try{s=t.endpoint.getOptimisticResponse.call(t.endpoint,n.snapshot(e,t.meta.fetchedAt),...t.args)}catch(t){if(t.constructor===ie)return e;throw t}}else s=t.response;const{result:r,entities:o,indexes:a,entitiesMeta:c}=I(t.endpoint.schema,s,t.args,e,t.meta),l=h({},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(`Endpoint.update() error: ${t.key}`),console.error(e)}return{entities:o,endpoints:l,indexes:a,meta:h({},e.meta,{[t.key]:{date:t.meta.date,fetchedAt:t.meta.fetchedAt,expiresAt:t.meta.expiresAt,prevExpiresAt:null==(i=e.meta[t.key])?void 0:i.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),se(e,t,n)}}(t,n,e);case P:return function(e,t,n){let i;if("function"==typeof t.value){const s=n.get(t.schema,...t.args,e);if(void 0===s)return e;i=t.value(s)}else i=t.value;try{const{entities:n,indexes:s,entitiesMeta:r}=I(t.schema,i,t.args,e,t.meta);return{entities:n,endpoints:e.endpoints,indexes:s,meta:e.meta,entitiesMeta:r,optimistic:e.optimistic,lastReset:e.lastReset}}catch(t){return e}}(t,n,e);case z:case K:return function(e,t){const n=h({},e.endpoints),i=h({},e.meta),s=e=>{delete n[e];const t=h({},i[e],{expiresAt:0,invalidated:!0});delete t.error,i[e]=t};return t.type===K?s(t.key):Object.keys(n).forEach((e=>{t.testKey(e)&&s(e)})),h({},e,{endpoints:n,meta:i})}(t,n);case Q:return function(e,t){const n=h({},e.meta);return Object.keys(n).forEach((e=>{t.testKey(e)&&(n[e]=h({},n[e],{expiresAt:1}))})),h({},e,{meta:n})}(t,n);case q:return h({},oe,{lastReset:n.date});default:return t}}},e.initManager=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()})},e.initialState=oe}));
|
package/dist/mock.js
CHANGED
|
@@ -709,7 +709,7 @@ class Controller {
|
|
|
709
709
|
if (shouldQuery) {
|
|
710
710
|
isInvalid = !normalizr.validateQueryKey(input);
|
|
711
711
|
// endpoint without entities
|
|
712
|
-
} else if (!schema || !
|
|
712
|
+
} else if (!schema || !requiresDenormalize(schema)) {
|
|
713
713
|
return {
|
|
714
714
|
data: cacheEndpoints,
|
|
715
715
|
expiryStatus: this.getExpiryStatus(!cacheEndpoints, !!endpoint.invalidIfStale, meta),
|
|
@@ -793,21 +793,24 @@ function entityExpiresAt(paths, entitiesMeta) {
|
|
|
793
793
|
return expiresAt;
|
|
794
794
|
}
|
|
795
795
|
|
|
796
|
-
/**
|
|
796
|
+
/** Whether `denormalize()` must run to reconstruct the response.
|
|
797
797
|
*
|
|
798
|
-
*
|
|
798
|
+
* True iff some node in the schema tree defines `normalize` — meaning it
|
|
799
|
+
* transforms the response when written (entity write, polymorphic hoist,
|
|
800
|
+
* lazy delegation, etc.), so the cached value differs from the response.
|
|
801
|
+
* Mirrors the dispatch in `getVisit.ts`: schema classes are detected here
|
|
802
|
+
* by the same hook the visit walker uses, so we never need to walk their
|
|
803
|
+
* instance fields.
|
|
799
804
|
*/
|
|
800
|
-
function
|
|
801
|
-
if (
|
|
802
|
-
if (Array.isArray(schema)) return schema.length !== 0 &&
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
}
|
|
810
|
-
return false;
|
|
805
|
+
function requiresDenormalize(schema) {
|
|
806
|
+
if (!schema) return false;
|
|
807
|
+
if (Array.isArray(schema)) return schema.length !== 0 && requiresDenormalize(schema[0]);
|
|
808
|
+
// Must reject primitives before probing `.normalize` — `String.prototype.normalize` exists.
|
|
809
|
+
const t = typeof schema;
|
|
810
|
+
if (t !== 'object' && t !== 'function') return false;
|
|
811
|
+
if (typeof schema.normalize === 'function') return true;
|
|
812
|
+
// Plain-object schema map (e.g. `{ data: [Tacos], page: { ... } }`).
|
|
813
|
+
return Object.values(schema).some(x => requiresDenormalize(x));
|
|
811
814
|
}
|
|
812
815
|
class Snapshot {
|
|
813
816
|
static abort = new AbortOptimistic();
|