fetchium 0.0.0 → 0.1.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.
Files changed (127) hide show
  1. package/CHANGELOG.md +249 -0
  2. package/README.md +287 -0
  3. package/dist/cjs/development/QueryClient-CpmwggOn.js +2 -0
  4. package/dist/cjs/development/QueryClient-CpmwggOn.js.map +1 -0
  5. package/dist/cjs/development/index.js +2 -0
  6. package/dist/cjs/development/index.js.map +1 -0
  7. package/dist/cjs/development/package.json +3 -0
  8. package/dist/cjs/development/react/index.js +2 -0
  9. package/dist/cjs/development/react/index.js.map +1 -0
  10. package/dist/cjs/development/shared-Ct5zKrt4.js +2 -0
  11. package/dist/cjs/development/shared-Ct5zKrt4.js.map +1 -0
  12. package/dist/cjs/development/stores/async.js +2 -0
  13. package/dist/cjs/development/stores/async.js.map +1 -0
  14. package/dist/cjs/development/stores/sync.js +2 -0
  15. package/dist/cjs/development/stores/sync.js.map +1 -0
  16. package/dist/cjs/development/subscriptions/polling.js +2 -0
  17. package/dist/cjs/development/subscriptions/polling.js.map +1 -0
  18. package/dist/cjs/production/QueryClient-qi3bR0eD.js +2 -0
  19. package/dist/cjs/production/QueryClient-qi3bR0eD.js.map +1 -0
  20. package/dist/cjs/production/index.js +2 -0
  21. package/dist/cjs/production/index.js.map +1 -0
  22. package/dist/cjs/production/package.json +3 -0
  23. package/dist/cjs/production/react/index.js +2 -0
  24. package/dist/cjs/production/react/index.js.map +1 -0
  25. package/dist/cjs/production/shared-Ct5zKrt4.js +2 -0
  26. package/dist/cjs/production/shared-Ct5zKrt4.js.map +1 -0
  27. package/dist/cjs/production/stores/async.js +2 -0
  28. package/dist/cjs/production/stores/async.js.map +1 -0
  29. package/dist/cjs/production/stores/sync.js +2 -0
  30. package/dist/cjs/production/stores/sync.js.map +1 -0
  31. package/dist/cjs/production/subscriptions/polling.js +2 -0
  32. package/dist/cjs/production/subscriptions/polling.js.map +1 -0
  33. package/dist/esm/ConstraintMatcher.d.ts +42 -0
  34. package/dist/esm/ConstraintMatcher.d.ts.map +1 -0
  35. package/dist/esm/EntityInstance.d.ts +38 -0
  36. package/dist/esm/EntityInstance.d.ts.map +1 -0
  37. package/dist/esm/EntityStore.d.ts +14 -0
  38. package/dist/esm/EntityStore.d.ts.map +1 -0
  39. package/dist/esm/GcManager.d.ts +38 -0
  40. package/dist/esm/GcManager.d.ts.map +1 -0
  41. package/dist/esm/LiveCollection.d.ts +86 -0
  42. package/dist/esm/LiveCollection.d.ts.map +1 -0
  43. package/dist/esm/MutationResult.d.ts +23 -0
  44. package/dist/esm/MutationResult.d.ts.map +1 -0
  45. package/dist/esm/NetworkManager.d.ts +62 -0
  46. package/dist/esm/NetworkManager.d.ts.map +1 -0
  47. package/dist/esm/QueryClient.d.ts +76 -0
  48. package/dist/esm/QueryClient.d.ts.map +1 -0
  49. package/dist/esm/QueryResult.d.ts +67 -0
  50. package/dist/esm/QueryResult.d.ts.map +1 -0
  51. package/dist/esm/applyEntities.d.ts +12 -0
  52. package/dist/esm/applyEntities.d.ts.map +1 -0
  53. package/dist/esm/development/QueryClient-DRZtPKFD.js +2568 -0
  54. package/dist/esm/development/QueryClient-DRZtPKFD.js.map +1 -0
  55. package/dist/esm/development/index.js +103 -0
  56. package/dist/esm/development/index.js.map +1 -0
  57. package/dist/esm/development/react/index.js +40 -0
  58. package/dist/esm/development/react/index.js.map +1 -0
  59. package/dist/esm/development/shared-Dq2yW78d.js +15 -0
  60. package/dist/esm/development/shared-Dq2yW78d.js.map +1 -0
  61. package/dist/esm/development/stores/async.js +214 -0
  62. package/dist/esm/development/stores/async.js.map +1 -0
  63. package/dist/esm/development/stores/sync.js +149 -0
  64. package/dist/esm/development/stores/sync.js.map +1 -0
  65. package/dist/esm/development/subscriptions/polling.js +25 -0
  66. package/dist/esm/development/subscriptions/polling.js.map +1 -0
  67. package/dist/esm/errors.d.ts +4 -0
  68. package/dist/esm/errors.d.ts.map +1 -0
  69. package/dist/esm/fieldRef.d.ts +15 -0
  70. package/dist/esm/fieldRef.d.ts.map +1 -0
  71. package/dist/esm/index.d.ts +14 -0
  72. package/dist/esm/index.d.ts.map +1 -0
  73. package/dist/esm/mutation.d.ts +47 -0
  74. package/dist/esm/mutation.d.ts.map +1 -0
  75. package/dist/esm/parseEntities.d.ts +44 -0
  76. package/dist/esm/parseEntities.d.ts.map +1 -0
  77. package/dist/esm/production/QueryClient-BP0Z1rQV.js +2453 -0
  78. package/dist/esm/production/QueryClient-BP0Z1rQV.js.map +1 -0
  79. package/dist/esm/production/index.js +103 -0
  80. package/dist/esm/production/index.js.map +1 -0
  81. package/dist/esm/production/react/index.js +40 -0
  82. package/dist/esm/production/react/index.js.map +1 -0
  83. package/dist/esm/production/shared-Dq2yW78d.js +15 -0
  84. package/dist/esm/production/shared-Dq2yW78d.js.map +1 -0
  85. package/dist/esm/production/stores/async.js +214 -0
  86. package/dist/esm/production/stores/async.js.map +1 -0
  87. package/dist/esm/production/stores/sync.js +149 -0
  88. package/dist/esm/production/stores/sync.js.map +1 -0
  89. package/dist/esm/production/subscriptions/polling.js +25 -0
  90. package/dist/esm/production/subscriptions/polling.js.map +1 -0
  91. package/dist/esm/proxy.d.ts +20 -0
  92. package/dist/esm/proxy.d.ts.map +1 -0
  93. package/dist/esm/proxyId.d.ts +8 -0
  94. package/dist/esm/proxyId.d.ts.map +1 -0
  95. package/dist/esm/query-types.d.ts +62 -0
  96. package/dist/esm/query-types.d.ts.map +1 -0
  97. package/dist/esm/query.d.ts +86 -0
  98. package/dist/esm/query.d.ts.map +1 -0
  99. package/dist/esm/react/index.d.ts +2 -0
  100. package/dist/esm/react/index.d.ts.map +1 -0
  101. package/dist/esm/react/use-query.d.ts +5 -0
  102. package/dist/esm/react/use-query.d.ts.map +1 -0
  103. package/dist/esm/retry.d.ts +4 -0
  104. package/dist/esm/retry.d.ts.map +1 -0
  105. package/dist/esm/stores/async.d.ts +80 -0
  106. package/dist/esm/stores/async.d.ts.map +1 -0
  107. package/dist/esm/stores/shared.d.ts +12 -0
  108. package/dist/esm/stores/shared.d.ts.map +1 -0
  109. package/dist/esm/stores/sync.d.ts +41 -0
  110. package/dist/esm/stores/sync.d.ts.map +1 -0
  111. package/dist/esm/subscriptions/polling.d.ts +6 -0
  112. package/dist/esm/subscriptions/polling.d.ts.map +1 -0
  113. package/dist/esm/type-utils.d.ts +16 -0
  114. package/dist/esm/type-utils.d.ts.map +1 -0
  115. package/dist/esm/typeDefs.d.ts +86 -0
  116. package/dist/esm/typeDefs.d.ts.map +1 -0
  117. package/dist/esm/types.d.ts +272 -0
  118. package/dist/esm/types.d.ts.map +1 -0
  119. package/dist/esm/utils.d.ts +38 -0
  120. package/dist/esm/utils.d.ts.map +1 -0
  121. package/index.d.ts +1 -0
  122. package/package.json +134 -5
  123. package/stores/async.d.ts +1 -0
  124. package/stores/async.js +15 -0
  125. package/stores/sync.d.ts +1 -0
  126. package/stores/sync.js +15 -0
  127. package/index.js +0 -1
package/CHANGELOG.md ADDED
@@ -0,0 +1,249 @@
1
+ # fetchium
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - c92035c: Initial pre-release of Fetchium
8
+
9
+ ## 1.1.2
10
+
11
+ ### Patch Changes
12
+
13
+ - 0b6b650: Add setSuspended API for more explicit suspension support
14
+
15
+ ## 1.1.1
16
+
17
+ ### Patch Changes
18
+
19
+ - bb0a5a9: Fix entity proxies not being created for preloaded entities from cache, and `__entityRef` not being resolved in proxy get handler. This fixes validation errors when accessing nested entities loaded from persistent cache.
20
+
21
+ ## 1.1.0
22
+
23
+ ### Minor Changes
24
+
25
+ - af443c5: Add request body support to query() function
26
+
27
+ Queries can now send JSON request bodies for POST requests, enabling read-like operations that require complex data structures (e.g., fetching prices for an array of tokens).
28
+
29
+ **New features:**
30
+
31
+ - Added `body` field to query definitions for specifying request body schema
32
+ - Body parameters are automatically serialized as JSON with `Content-Type: application/json` header
33
+ - Body params work alongside path params and search params
34
+ - All query features (caching, staleTime, deduplication) work with body queries
35
+
36
+ **API changes:**
37
+
38
+ - Query methods are now restricted to `GET` and `POST` only (PUT, PATCH, DELETE should use `mutation()`)
39
+
40
+ **Example:**
41
+
42
+ ```typescript
43
+ const getPrices = query(() => ({
44
+ path: '/prices',
45
+ method: 'POST',
46
+ body: {
47
+ tokens: t.array(t.string),
48
+ },
49
+ searchParams: {
50
+ currency: t.string,
51
+ },
52
+ response: {
53
+ prices: t.array(t.object({ token: t.string, price: t.number })),
54
+ },
55
+ cache: { staleTime: 30_000 },
56
+ }));
57
+
58
+ // Usage: POST /prices?currency=USD with body: {"tokens":["ETH","BTC"]}
59
+ const result = getPrices({ tokens: ['ETH', 'BTC'], currency: 'USD' });
60
+ ```
61
+
62
+ ## 1.0.18
63
+
64
+ ### Patch Changes
65
+
66
+ - 395730a: Fix entity cache keys to include shapeKey, preventing stale entity validation errors after schema changes
67
+
68
+ ## 1.0.17
69
+
70
+ ### Patch Changes
71
+
72
+ - b244daa: Fix infinite query cache hydration and Hermes Uint32Array compatibility
73
+
74
+ - Fix Hermes (React Native) compatibility by spreading Set to Array before Uint32Array conversion, which prevents empty refIds buffers
75
+ - Fix infinite query cache loading by properly handling the array of pages when parsing entities, ensuring entity proxies resolve correctly after app restart
76
+
77
+ ## 1.0.16
78
+
79
+ ### Patch Changes
80
+
81
+ - 4a3bc06: Fix union parseValue check
82
+
83
+ ## 1.0.15
84
+
85
+ ### Patch Changes
86
+
87
+ - a95ed74: Ensure entities have a unique prototype
88
+ - aa50869: Fix Record parsing and reorganize/expand parsing tests
89
+
90
+ ## 1.0.14
91
+
92
+ ### Patch Changes
93
+
94
+ - 7462836: Add mutation support
95
+ - 84265ca: Add API resilience features:
96
+ - Array filtering for parse failures
97
+ - Undefined fallback for optional types
98
+ - `t.result` wrapper for handling and exposing parse errors directly
99
+ - f07ed0e: Add separate dev-mode and prod-mode builds
100
+ - 093cbb2: Add baseUrl and ability to override baseUrl + other request options
101
+ - Updated dependencies [f07ed0e]
102
+ - signalium@2.1.6
103
+
104
+ ## 1.0.13
105
+
106
+ ### Patch Changes
107
+
108
+ - d2d633e: Ensure Entity methods can call other methods
109
+
110
+ ## 1.0.12
111
+
112
+ ### Patch Changes
113
+
114
+ - f3e1ef0: Fix case-insensitive enum type inference
115
+ - 11116da: Add more tests for shapeKey and fix some small issues
116
+ - 0219742: Fix initialization error handling
117
+ - Updated dependencies [985abb0]
118
+ - signalium@2.1.5
119
+
120
+ ## 1.0.11
121
+
122
+ ### Patch Changes
123
+
124
+ - 7f94377: Fixup format registry and add global format type registry
125
+ - d1f9def: Add ability to defined cached methods to entities
126
+ - e0a4844: Add ability for Entities to subscribe to streams when in use
127
+ - 6b961f0: Add support for Signal query parameters and debounced updates
128
+ - Updated dependencies [2cf6766]
129
+ - signalium@2.1.4
130
+
131
+ ## 1.0.10
132
+
133
+ ### Patch Changes
134
+
135
+ - 24495ac: Add t.enum.caseInsensitive()
136
+ - 047d4dc: Allow all primitive types in search params
137
+ - 9b2c2f3: Add extend to Entity and Object typedefs
138
+ - c8fc4b8: Allow typenames to be optional on entities
139
+ - 0245106: Add streamOrphans and optimisticInserts
140
+
141
+ ## 1.0.9
142
+
143
+ ### Patch Changes
144
+
145
+ - 9257412: Add t.optional/t.nullable/t.nullish
146
+ - Updated dependencies [7350348]
147
+ - Updated dependencies [c78b461]
148
+ - signalium@2.1.2
149
+
150
+ ## 1.0.8
151
+
152
+ ### Patch Changes
153
+
154
+ - f76ade3: Add support for stream and infinite queries for useQuery results
155
+
156
+ ## 1.0.7
157
+
158
+ ### Patch Changes
159
+
160
+ - 82e7818: Add useQuery for reading query results. Calling `useReactive` on a query result
161
+ will cause the result itself to entangle, but not the value of the result (e.g.
162
+ the entities inside the result). This can lead to cases where the result is not
163
+ re-rendered when the entities inside the result change. By cloning the result,
164
+ we effectively reify it and force it to flatten, entangling all of the nested
165
+ entities with that read from React.
166
+
167
+ ## 1.0.6
168
+
169
+ ### Patch Changes
170
+
171
+ - c883a52: Add no-op implementations of MemoryEvictionManager, RefetchManager, and NetworkManager for SSR environments. These can be injected into QueryClient constructor to avoid creating timers and event listeners in server-side rendering contexts.
172
+
173
+ ## 1.0.5
174
+
175
+ ### Patch Changes
176
+
177
+ - 00ae954: Signalium:
178
+
179
+ - Add support for Sets, Maps, and Dates in the `hashValue` function
180
+ - Note: This may cause some _minor_ differences in reactive functions that receive these types as parameters, they should essentially run less often in those cases. The impact of this should be minimal, so we're not considering it a breaking change.
181
+
182
+ Query:
183
+
184
+ - Add shape checking to make sure that if the shape of a query is changed, the query key will change as well, preventing stale data with a different shape from being returned from the query store
185
+ - Fix an issue where shrinking the `maxCount` of a query would cause an error when trying to activate the query
186
+
187
+ - Updated dependencies [00ae954]
188
+ - signalium@2.1.1
189
+
190
+ ## 1.0.4
191
+
192
+ ### Patch Changes
193
+
194
+ - e202f05: Fix package.json main export
195
+
196
+ ## 1.0.3
197
+
198
+ ### Patch Changes
199
+
200
+ - cfe249d: Export QueryClientContext
201
+
202
+ ## 1.0.2
203
+
204
+ ### Patch Changes
205
+
206
+ - 5f34de3: Add exports for entity and registerFormat
207
+
208
+ ## 1.0.1
209
+
210
+ ### Patch Changes
211
+
212
+ - 39d3df8: Export type definitions for queries
213
+
214
+ ## 1.0.0
215
+
216
+ ### Minor Changes
217
+
218
+ - 1a94943: Add NetworkManager and network mode options
219
+ - 0f609e4: Adds infinite query, includes some minor breaking API changes
220
+ - 4c35e93: Add Stream Query support
221
+ - f59a776: Add async store and split out stores into separate import paths
222
+
223
+ ### Patch Changes
224
+
225
+ - Updated dependencies [e64597d]
226
+ - Updated dependencies [4c35e93]
227
+ - signalium@2.1.0
228
+
229
+ ## 0.1.0
230
+
231
+ ### Minor Changes
232
+
233
+ - 919ecd9: Remove unused decoders dependency and prepare for initial pre-release
234
+
235
+ ## 0.0.2
236
+
237
+ ### Patch Changes
238
+
239
+ - 6eddfdc: Adds `staleTime`, `gcTime`, and `refetchInterval` options to queries.
240
+ - Updated dependencies [6eddfdc]
241
+ - signalium@2.0.9
242
+
243
+ ## 0.0.1
244
+
245
+ ### Patch Changes
246
+
247
+ - e6c39ee: Initial Signalium Query release
248
+ - Updated dependencies [e6c39ee]
249
+ - signalium@2.0.7
package/README.md ADDED
@@ -0,0 +1,287 @@
1
+ # fetchium
2
+
3
+ A reactive query client built on [Signalium](https://signalium.dev) that provides powerful data fetching, caching, and entity management with automatic reactivity.
4
+
5
+ ## IMPORTANT NOTE: This package is still in development and the API is subject to change.
6
+
7
+ v1.0.0 was published prematurely and we are not treating it as the stable v1 release from a semver perspective. APIs are not expected to change dramatically, but breaking changes may occur, and v1.1.0 will be the first stable release.
8
+
9
+ ## Features
10
+
11
+ - **Entity-Based Caching**: Global entity map with automatic deduplication across queries
12
+ - **Signalium Reactivity**: Automatic reactive updates when entities change
13
+ - **REST Query API**: Type-safe REST queries with path and search parameter interpolation
14
+ - **Infinite Queries**: Built-in support for paginated data fetching
15
+ - **Stream Queries**: Real-time updates via subscriptions
16
+ - **Smart Refetching**: Configurable stale-time, refetch intervals, and network-aware fetching
17
+ - **Request Deduplication**: Automatic deduplication of in-flight requests
18
+ - **Offline Support**: Response caching with configurable garbage collection
19
+ - **TypeScript First**: Full type inference for queries and responses
20
+ - **Framework Agnostic**: Works with React, or use standalone
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npm install fetchium signalium
26
+ ```
27
+
28
+ For React support:
29
+
30
+ ```bash
31
+ npm install fetchium signalium react
32
+ ```
33
+
34
+ ## Quick Start
35
+
36
+ ### Basic Query
37
+
38
+ ```typescript
39
+ import { QueryClient, SyncQueryStore, MemoryPersistentStore, query, t } from 'fetchium';
40
+
41
+ // Create a query client
42
+ const store = new SyncQueryStore(new MemoryPersistentStore());
43
+ const client = new QueryClient(store, {
44
+ fetch: globalThis.fetch,
45
+ });
46
+
47
+ // Define a query
48
+ const getUser = query(() => ({
49
+ path: '/users/[id]',
50
+ response: {
51
+ id: t.number,
52
+ name: t.string,
53
+ email: t.string,
54
+ },
55
+ }));
56
+
57
+ // Use the query with standard async/await syntax
58
+ const user = await getUser({ id: '123' });
59
+ console.log(user.name); // Fully typed!
60
+ ```
61
+
62
+ ### Entity Queries
63
+
64
+ Define entities to enable automatic caching and deduplication:
65
+
66
+ ```typescript
67
+ import { entity, t } from 'fetchium';
68
+
69
+ // Define an entity
70
+ const User = entity('User', () => ({
71
+ id: t.number,
72
+ name: t.string,
73
+ email: t.string,
74
+ }));
75
+
76
+ // Use in a query
77
+ const getUser = query(() => ({
78
+ path: '/users/[id]',
79
+ response: User,
80
+ }));
81
+
82
+ // Multiple queries returning the same entity will share cached data
83
+ const user1 = await getUser({ id: '123' });
84
+ const user2 = await getUserFromTeam({ teamId: '456' }); // May return same User entity
85
+
86
+ // Both references will update reactively when the entity changes!
87
+ ```
88
+
89
+ ### Search Parameters
90
+
91
+ ```typescript
92
+ const listUsers = query(() => ({
93
+ path: '/users',
94
+ searchParams: {
95
+ page: t.number,
96
+ limit: t.number,
97
+ status: t.string.optional,
98
+ },
99
+ response: {
100
+ users: t.array(User),
101
+ total: t.number,
102
+ },
103
+ }));
104
+
105
+ // Use with search params
106
+ const result = await listUsers({
107
+ page: 1,
108
+ limit: 10,
109
+ status: 'active',
110
+ });
111
+ ```
112
+
113
+ ### Stream Options
114
+
115
+ For real-time updates on queries, use the `stream` option:
116
+
117
+ ```typescript
118
+ import { query } from 'fetchium';
119
+
120
+ const getUser = query(() => ({
121
+ path: '/users/[id]',
122
+ response: { user: User },
123
+ stream: {
124
+ type: User,
125
+ subscribe: (context, params, onUpdate) => {
126
+ const ws = new WebSocket(`wss://api.example.com/users/${params.id}`);
127
+
128
+ ws.onmessage = event => {
129
+ const update = JSON.parse(event.data);
130
+ onUpdate(update);
131
+ };
132
+
133
+ // Return unsubscribe function
134
+ return () => ws.close();
135
+ },
136
+ }));
137
+
138
+ // Subscribe to updates
139
+ const userStream = subscribeToUser({ id: '123' });
140
+ const user = await userStream;
141
+ // User will reactively update when new data arrives
142
+ ```
143
+
144
+ ## Caching Options
145
+
146
+ Configure caching behavior per query:
147
+
148
+ ```typescript
149
+ const getUser = query(() => ({
150
+ path: '/users/[id]',
151
+ response: User,
152
+ cache: {
153
+ staleTime: 5000, // Data is fresh for 5 seconds
154
+ gcTime: 300000, // Cache persists for 5 minutes after last use
155
+ networkMode: 'online', // Only fetch when online
156
+ retry: 3, // Retry failed requests 3 times
157
+ refreshStaleOnReconnect: true, // Refetch stale data on reconnect
158
+ },
159
+ }));
160
+ ```
161
+
162
+ ## React Integration
163
+
164
+ ```typescript
165
+ import { QueryClientContext } from 'fetchium';
166
+ import { reactive } from 'signalium/react';
167
+
168
+ // Provide the client
169
+ function App() {
170
+ return (
171
+ <QueryClientContext.Provider value={client}>
172
+ <UserProfile userId="123" />
173
+ </QueryClientContext.Provider>
174
+ );
175
+ }
176
+
177
+ // Use queries in components
178
+ const UserProfile = reactive(({ userId }) => {
179
+ const user = getUser({ id: userId });
180
+
181
+ // While the user is loading initially, show a loading state
182
+ if (!user.isReady) {
183
+ return <div>Loading...</div>;
184
+ }
185
+
186
+ // Once the user is loaded and the result is ready, `user.value` is guaranteed
187
+ // to be defined and have a loaded user value.
188
+ return (
189
+ <div>
190
+ <h1>{user.value.name}</h1>
191
+ <p>{user.value.email}</p>
192
+ </div>
193
+ );
194
+ });
195
+ ```
196
+
197
+ ## Store Types
198
+
199
+ ### Synchronous Store
200
+
201
+ For in-memory only or synchronous persistence:
202
+
203
+ ```typescript
204
+ import { SyncQueryStore, MemoryPersistentStore } from 'fetchium';
205
+
206
+ const store = new SyncQueryStore(new MemoryPersistentStore());
207
+ ```
208
+
209
+ ### Asynchronous Store
210
+
211
+ For async persistence (IndexedDB, AsyncStorage, etc.):
212
+
213
+ ```typescript
214
+ import { AsyncQueryStore } from 'fetchium/stores/async';
215
+
216
+ const store = new AsyncQueryStore({
217
+ async get(key) {
218
+ /* ... */
219
+ },
220
+ async set(key, value) {
221
+ /* ... */
222
+ },
223
+ async delete(key) {
224
+ /* ... */
225
+ },
226
+ async clear() {
227
+ /* ... */
228
+ },
229
+ });
230
+ ```
231
+
232
+ ## Type Definitions
233
+
234
+ The `t` object provides type-safe validators:
235
+
236
+ - **Primitives**: `t.string`, `t.number`, `t.boolean`, `t.null`, `t.undefined`
237
+ - **Collections**: `t.array(type)`, `t.record(type)`, `t.object({ ... })`
238
+ - **Unions**: `t.union(t.string, t.number, t.null)`
239
+ - **Entities**: `entity(() => ({ ... }))`
240
+
241
+ ## Network Management
242
+
243
+ Control network status and behavior:
244
+
245
+ ```typescript
246
+ import { NetworkManager } from 'fetchium';
247
+
248
+ const networkManager = new NetworkManager();
249
+
250
+ // Manually control network status
251
+ networkManager.setOnline(false);
252
+
253
+ // Listen to browser events (default)
254
+ networkManager.listen();
255
+
256
+ // Use in QueryClient
257
+ const client = new QueryClient(store, {
258
+ fetch,
259
+ networkManager,
260
+ });
261
+ ```
262
+
263
+ ## API Reference
264
+
265
+ ### Core Exports
266
+
267
+ - `QueryClient` - Main query client class
268
+ - `QueryClientContext` - React context for client
269
+ - `query()` - Define a query
270
+ - `t` - Type definition helpers
271
+ - `entity()` - Define an entity type
272
+ - `SyncQueryStore` / `AsyncQueryStore` - Store implementations
273
+ - `NetworkManager` - Network status manager
274
+
275
+ ### Type Utilities
276
+
277
+ - `QueryResult<T>` - Result type for queries
278
+ - `QueryContext` - Context passed to fetch functions
279
+ - `QueryCacheOptions` - Cache configuration options
280
+
281
+ ## License
282
+
283
+ ISC
284
+
285
+ ## Contributing
286
+
287
+ See the main [Signalium repository](https://github.com/Signalium/signalium) for contributing guidelines.
@@ -0,0 +1,2 @@
1
+ "use strict";const C=require("signalium"),D=require("signalium/utils"),Vt=require("./shared-Ct5zKrt4.js");var U=(e=>(e.Always="always",e.Online="online",e.OfflineFirst="offlineFirst",e))(U||{}),u=(e=>(e[e.UNDEFINED=1]="UNDEFINED",e[e.NULL=2]="NULL",e[e.NUMBER=4]="NUMBER",e[e.STRING=8]="STRING",e[e.BOOLEAN=16]="BOOLEAN",e[e.OBJECT=32]="OBJECT",e[e.ARRAY=64]="ARRAY",e[e.ID=128]="ID",e[e.RECORD=256]="RECORD",e[e.UNION=512]="UNION",e[e.ENTITY=1024]="ENTITY",e[e.HAS_FORMAT=4096]="HAS_FORMAT",e[e.IS_EAGER_FORMAT=8192]="IS_EAGER_FORMAT",e[e.PARSE_RESULT=16384]="PARSE_RESULT",e[e.LIVE=32768]="LIVE",e))(u||{});const T=Symbol("array"),M=Symbol("record"),lt=Symbol("QUERY_ID");var X=(e=>(e[e.Array=0]="Array",e[e.Value=1]="Value",e))(X||{});class ${type;entityDefs;constraintFieldRefs;sort;valueType;onCreate;onUpdate;onDelete;constructor(t,i,n,s,r,o,a,c){this.type=t,this.entityDefs=i,this.constraintFieldRefs=n,this.sort=s,this.valueType=r,this.onCreate=o,this.onUpdate=a,this.onDelete=c}static array(t,i,n){return new $(0,t,i,n,void 0,void 0,void 0,void 0)}static value(t,i,n,s,r,o){return new $(1,t,i,void 0,n,s,r,o)}}const S=new WeakMap;function L(e){return S.get(e)}var Z=(e=>(e[e.Query=0]="Query",e[e.Entity=1]="Entity",e))(Z||{});class xe{constructor(t,i,n){this._onEvict=i,this._intervalId=setInterval(this._tick,t*6e4*n)}_currentFlush=new Map;_nextFlush=new Map;_intervalId;schedule(t,i){this._nextFlush.set(t,i)}cancel(t){this._currentFlush.delete(t),this._nextFlush.delete(t)}_tick=()=>{const{_currentFlush:t,_nextFlush:i,_onEvict:n}=this;for(const[s,r]of t)n(s,r);this._currentFlush=i,this._nextFlush=new Map};destroy(){clearInterval(this._intervalId)}}class Kt{_buckets=new Map;_nextTickEntries=new Map;_nextTickScheduled=!1;_onEvict;_multiplier;constructor(t,i=1){this._onEvict=t,this._multiplier=i}schedule(t,i,n){if(i===1/0)return;if(i===0){const{_nextTickEntries:o}=this;o.set(t,n),this._nextTickScheduled||(this._nextTickScheduled=!0,setTimeout(this._flushNextTick,0));return}const{_buckets:s}=this;let r=s.get(i);r||(r=new xe(i,this._onEvict,this._multiplier),s.set(i,r)),r.schedule(t,n)}cancel(t,i){if(i!==1/0){if(i===0){this._nextTickEntries.delete(t);return}this._buckets.get(i)?.cancel(t)}}_flushNextTick=()=>{const{_nextTickEntries:t,_onEvict:i}=this;this._nextTickScheduled=!1;for(const[n,s]of t)i(n,s);t.clear()};destroy(){const{_buckets:t,_nextTickEntries:i}=this;for(const n of t.values())n.destroy();t.clear(),i.clear()}}class Bt{schedule(t,i,n){}cancel(t,i){}destroy(){}}const W=Symbol("fieldRef"),k=Symbol("fieldRefPath"),ht=Symbol("DEFINITION_TARGET"),J=Symbol("CANCEL_PROXY"),Oe=/\[([^\]]+)\]/g;function Qt(e){const t={[W]:!0,[k]:e};return new Proxy(t,Se)}const Se={get(e,t){if(t===W)return!0;if(t===k)return e[k];if(t===Symbol.toPrimitive||t==="toString"||t==="valueOf"){const n=e[k];return()=>`[${n.join(".")}]`}if(typeof t=="symbol")return;const i=e[k];return Qt([...i,t])},has(e,t){return t===W||t===k}};function Yt(e){return typeof e=="object"&&e!==null&&e[W]===!0}function Gt(e){return e[k]}function yt(e){let t=!1;return new Proxy(e,{set(i,n,s){return i[n]=s,!0},get(i,n){if(t)throw new Error("Definition proxy accessed after extraction. Avoid arrow functions that capture `this`.");return n===ht?i:n===J?()=>{t=!0}:typeof n=="symbol"?i[n]:Qt([n])}})}function Ht(e){const t=e[ht];e[J]();const i={};for(const r of Object.getOwnPropertyNames(t))i[r]=t[r];const n={};let s=Object.getPrototypeOf(t);for(;s&&s!==Object.prototype;){for(const r of Object.getOwnPropertyNames(s)){if(r==="constructor")continue;const o=Object.getOwnPropertyDescriptor(s,r);typeof o.value=="function"&&!(r in n)&&(n[r]=o.value)}s=Object.getPrototypeOf(s)}return{fields:i,methods:n}}function pt(e,t){let i=t;for(const n of e){if(i==null)return;i=i[n]}return i}function Ne(e,t){return e.replace(Oe,(i,n)=>{const s=n.split("."),r=pt(s,t);return r!=null?encodeURIComponent(String(r)):""})}function q(e,t){if(Yt(e))return pt(Gt(e),t);if(typeof e=="string")return Ne(e,t);if(Array.isArray(e))return e.map(i=>q(i,t));if(typeof e=="object"&&e!==null&&Object.getPrototypeOf(e)===Object.prototype){const i={};for(const n of Object.keys(e))i[n]=q(e[n],t);return i}return e}function rt(e,t,i){const n=e.fields,s=e.methods,r={params:t},o={};for(const[a,c]of Object.entries(n))o[a]=q(c,r);o.params=t,o.context=i;for(const[a,c]of Object.entries(s))o[a]=c.bind(o);return o}class gt{static cache;constructor(){return yt(this)}}const zt=Object.entries,ot=Object.keys;let Wt=()=>{};{const t=(n,s)=>{if(n.size!==s.size)return!1;for(const r of n)if(!s.has(r))return!1;return!0},i=(n,s)=>{if(n===s)return!0;if(typeof n!=typeof s)return!1;if(typeof n=="number"){const r=s;if((n&65535)!==(r&65535))return!1;const o=n>>16,a=r>>16;return!(o!==0&&a!==0&&o!==a)}if(typeof n=="string")return n===s;if(n instanceof Set&&s instanceof Set)return t(n,s);if(n instanceof v&&s instanceof v){const r=n.mask,o=s.mask;if((r&65535)!==(o&65535))return!1;const a=r>>16,c=o>>16;if(a!==0&&c!==0&&a!==c)return!1;if(n.shape===s.shape)return!0;if(n.shape!==void 0&&s.shape!==void 0&&typeof n.shape=="object"&&typeof s.shape=="object"){const f=n.shape,l=s.shape;for(const d of Object.keys(f))if(d in l&&!i(f[d],l[d]))return!1;for(const d of Object.keys(l))if(d in f&&!i(f[d],l[d]))return!1}return!0}return!1};Wt=(n,s,r,o)=>{if(!i(r,o))throw new Error(`[fetchium] Entity typename '${n}' has incompatible type for field '${s}' across different entity definitions`)}}function Dt(e){return typeof e=="number"?e|u.UNDEFINED:e instanceof v?(e.mask&u.UNDEFINED)!==0?e:v.cloneWith(e,u.UNDEFINED):e}function It(e){return e instanceof v&&(e.mask&u.OBJECT)!==0&&(e.mask&(u.ENTITY|u.ARRAY|u.UNION|u.RECORD|u.LIVE))===0}function Jt(e,t,i){const n=new Set;for(const r of e)if(r!==void 0)for(const o of Object.keys(r))n.add(o);const s={};for(const r of n){let o=0,a;const c=[];let f=!0;for(const l of e){const d=l?.[r];d!==void 0?(o++,a===void 0&&(a=d),a!==void 0&&d!==a&&!It(d)&&Wt(i,r,a,d),It(d)?c.push(d.shape):(f=!1,c.push(void 0))):(f=!1,c.push(void 0))}if(f&&o>0){const l=Jt(c,t,i),d=new v(u.OBJECT,l);s[r]=o<t?Dt(d):d}else s[r]=o<t?Dt(a):a}return s}class v{mask;shape;typenameField=void 0;typenameValue=void 0;idField=void 0;values=void 0;_methods=void 0;_entityConfig=void 0;_entityClass=void 0;_entityCache=void 0;_liveConfig=void 0;constructor(t,i,n,s,r,o){this.mask=t,this.shape=i,this.values=n,this.typenameField=s,this.typenameValue=r,this.idField=o}static merge(t){if(t.length===1)return t[0];const i=t.length,n=t.map(f=>f.shape),s=t[0].typenameValue??"(unknown)",r=Jt(n,i,s);let o,a,c;for(const f of t){if(o===void 0&&f.idField!==void 0)o=f.idField;else if(o!==void 0&&f.idField!==void 0&&f.idField!==o)throw new Error(`[fetchium] Entity typename '${f.typenameValue}' has conflicting id fields: '${String(o)}' vs '${String(f.idField)}'`);a===void 0&&(a=f.typenameField),c===void 0&&(c=f.typenameValue)}return new v(u.ENTITY|u.OBJECT,r,void 0,a,c,o)}static cloneWith(t,i){const n=new v(i|t.mask,t.shape,t.values,t.typenameField,t.typenameValue,t.idField);return n._methods=t._methods,n._entityConfig=t._entityConfig,n._entityClass=t._entityClass,n._entityCache=t._entityCache,n._liveConfig=t._liveConfig,n}}class K extends Set{lowercaseMap;constructor(t){super(t),this.lowercaseMap=new Map;for(const i of t)if(typeof i=="string"){const n=i.toLowerCase(),s=this.lowercaseMap.get(n);if(s!==void 0)throw new Error(`Case-insensitive enum cannot have multiple values with the same lowercase form: '${s}' and '${i}' both become '${n}'`);this.lowercaseMap.set(n,i)}}has(t){return this.get(t)!==void 0}get(t){if(typeof t=="string")return this.lowercaseMap.get(t.toLowerCase());if(super.has(t))return t}}const Ae=1128875347;D.registerCustomHash(K,e=>{let t=Ae;for(const i of e)t+=D.hashValue(i);return t>>>0});function vt(e,t){return new v(e,t)}function De(e){return vt(u.ARRAY,e)}function Ie(e){return vt(u.RECORD|u.OBJECT,e)}function Fe(e){return vt(u.PARSE_RESULT,e)}function Xt(e,t){let i=e,n,s,r;for(const[o,a]of zt(t))switch(typeof a){case"number":if((a&u.ID)!==0){if(n!==void 0)throw new Error(`Duplicate id field: ${o}`);n=o}break;case"string":if(s!==void 0&&s!==o)throw new Error(`Duplicate typename field: ${o}`);s=o,r=a;break;case"object":if(a instanceof K||a instanceof Set)break;a.mask&u.LIVE&&(i|=u.LIVE);break}return new v(i,t,void 0,s,r,n)}function Te(e){return Xt(u.OBJECT,e)}function Ft(e,t,i){const n=e.mask;if((n&u.UNION)!==0){const s=e;if(s.typenameField!==void 0){if(i!==void 0&&i!==s.typenameField)throw new Error(`Union typename field conflict: Cannot merge unions with different typename fields ('${i}' vs '${s.typenameField}')`);i=s.typenameField}const r=s.shape;if(r!==void 0)for(const o of[...ot(r),T,M]){const a=r[o];if(t[o]!==void 0&&t[o]!==a)throw new Error(`Union merge conflict: Duplicate typename value '${String(o)}' found when merging nested unions (${String(t[o])} vs ${String(a)})`);t[o]=a}}else if((n&u.ARRAY)!==0){if(t[T]!==void 0)throw new Error("Array shape already defined");t[T]=e.shape}else if((n&u.RECORD)!==0){if(t[M]!==void 0)throw new Error("Record shape already defined");t[M]=e.shape}else{const s=e.typenameField,r=e.typenameValue;if(r===void 0)throw new Error("Object definitions must have a typename to be in a union with other objects, records, or arrays");if(i!==void 0&&s!==i)throw new Error("Object definitions must have the same typename field to be in the same union");i=s,t[r]=e}return i}function mt(...e){const t=e;let i=0,n=0,s,r,o,a,c=0;for(const l of t){if(typeof l=="number"){i|=l;continue}if(l instanceof Set){if(r===void 0)r=new Set(l);else for(const d of l)r.add(d);continue}if(n++,c|=l.mask,n===1){s=l;continue}n===2&&(o=Object.create(null),a=Ft(s,o,a)),a=Ft(l,o,a)}if(n===0)return r===void 0?i:i===0?r:new v(i|u.UNION,void 0,r);if(n===1)return v.cloneWith(s,i);const f=i|c|u.UNION;return new v(f,o,r,a)}function _t(e,t,i){const n=e;if(typeof n=="number")return n|t;if(n instanceof Set)return mt(e,t);let s=i.get(n);return s===void 0&&(s=v.cloneWith(n,t),i.set(n,s)),s}const Me=new WeakMap,ke=new WeakMap,Pe=new WeakMap;function Le(e){return _t(e,u.UNDEFINED|u.NULL,Pe)}function je(e){return _t(e,u.UNDEFINED,Me)}function Ue(e){return _t(e,u.NULL,ke)}function $e(e){return e}function qe(e){return new Set([e])}const Zt=((...e)=>new Set(e));Zt.caseInsensitive=(...e)=>new K(e);const Et=16;let Ve=0;const at=[],te=[],ee=new Map,ie=new Map,tt=new WeakSet;class G{_raw;_formatted;_parsed;_formatId;constructor(t,i,n){this._raw=t,this._formatId=i,n?(this._formatted=at[i](t),this._parsed=!0):this._parsed=!1,tt.add(this)}getValue(){return this._parsed||(this._formatted=at[this._formatId](this._raw),this._parsed=!0),this._formatted}toJSON(){return this._parsed?te[this._formatId](this._formatted):this._raw}}function Ke(e){const t=ee.get(e);if(t===void 0)throw new Error(`Format ${e} not registered`);return t}function Tt(e){const t=e>>Et;return ie.get(t)}function wt(e,t,i,n,s){const r=Ve++;at[r]=i,te[r]=n,ie.set(r,e);const o=s?.eager??!0,c=r<<Et|t|u.HAS_FORMAT|(o?u.IS_EAGER_FORMAT:0);ee.set(e,c)}wt("date",u.STRING,e=>{const t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)throw new Error(`Invalid date string: ${e}. Expected YYYY-MM-DD format.`);const[,i,n,s]=t,r=new Date(Date.UTC(parseInt(i,10),parseInt(n,10)-1,parseInt(s,10)));if(isNaN(r.getTime()))throw new Error(`Invalid date string: ${e}`);return r},e=>{const t=e.getUTCFullYear(),i=String(e.getUTCMonth()+1).padStart(2,"0"),n=String(e.getUTCDate()).padStart(2,"0");return`${t}-${i}-${n}`});wt("date-time",u.STRING,e=>{const t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date-time string: ${e}`);return t},e=>e.toISOString());const Mt=new WeakMap;function V(e){let t=Mt.get(e);if(t===void 0){const i=new e,n=i[ht]??i;i[J]&&i[J]();const s={};for(const[f,l]of zt(n)){if(!(typeof l=="number"||typeof l=="string"||l instanceof Set||l instanceof v||l instanceof K))throw new Error(`[fetchium] Entity '${e.name}' field '${f}' has an invalid type definition. All entity fields must be type definitions (e.g. t.string, t.number, t.entity(...), etc). Got: ${typeof l=="object"?l?.constructor?.name??typeof l:typeof l}`);s[f]=l}const r=Object.getPrototypeOf(e.prototype);if(r!=null){const f=r.constructor;if(f!==gt&&typeof f=="function"){const d=V(f).shape;for(const y of ot(d))if(y in s&&s[y]!==d[y])throw new Error(`Cannot extend: field '${y}' already exists in type definition`)}}const o={},a=e.prototype;for(const f of Object.getOwnPropertyNames(a))f!=="constructor"&&typeof a[f]=="function"&&(o[f]=a[f]);t=Xt(u.ENTITY|u.OBJECT,s),t._entityClass=e,ot(o).length>0&&(t._methods=o),typeof o.__subscribe=="function"&&(t._entityConfig={hasSubscribe:!0});const c=e;c.cache&&(t._entityCache=c.cache),Mt.set(e,t)}return t}function Be(e){return V(e)}function ne(e,t){if(t==null)return;const i=new Map;if(Array.isArray(t))for(const n of t){const[s,r]=n,a=V(s).typenameValue;if(a===void 0)continue;const c=[];for(const[f,l]of Object.entries(r))c.push([f,l]);c.length>0&&i.set(a,c)}else{const s=Object.entries(t);if(s.length===0)return;const r=s.map(([o,a])=>[o,a]);for(const o of e){const a=o.typenameValue;a!==void 0&&i.set(a,r)}}return i.size>0?i:void 0}function se(e){return Array.isArray(e)?e.map(t=>V(t)):[V(e)]}function Qe(e,t){const i=se(e),n=i.length===1?i[0]:mt(...i.map(o=>o)),s=u.ARRAY|u.LIVE,r=new v(s,n);return r._liveConfig=$.array(i,ne(i,t?.constraints),t?.sort),r}function Ye(e,t,i){const n=se(t),s=e,r=u.LIVE,o=new v(r,void 0);return o._liveConfig=$.value(n,ne(n,i?.constraints),s,i.onCreate,i.onUpdate,i.onDelete),o}const re={format:Ke,typename:$e,const:qe,enum:Zt,id:u.ID|u.STRING|u.NUMBER,string:u.STRING,number:u.NUMBER,boolean:u.BOOLEAN,null:u.NULL,undefined:u.UNDEFINED,array:De,object:Te,record:Ie,union:mt,nullish:Le,optional:je,nullable:Ue,result:Fe,entity:Be,liveArray:Qe,liveValue:Ye};function Y(e){if(e instanceof K)return Array.from(e).map(n=>typeof n=="string"?`"${n}"`:String(n)).join(" | ");if(e instanceof Set)return Array.from(e).map(n=>typeof n=="string"?`"${n}"`:String(n)).join(" | ");if(typeof e=="string")return`"${e}"`;if(typeof e=="boolean")return String(e);if(typeof e=="number"){if((e&u.HAS_FORMAT)!==0){const s=Tt(e);if(s)return`"${s}"`}const n=[];return e&u.UNDEFINED&&n.push("undefined"),e&u.NULL&&n.push("null"),e&u.NUMBER&&n.push("number"),e&u.STRING&&n.push("string"),e&u.BOOLEAN&&n.push("boolean"),e&u.OBJECT&&n.push("object"),e&u.ARRAY&&n.push("array"),n.length===0?"unknown":n.length===1?n[0]:n.join(" | ")}let t=e.mask;if(t&u.UNION){const i=e,n=[];if(i.values!==void 0&&i.values.size>0)for(const r of i.values){const o=typeof r=="string"?`"${r}"`:String(r);n.push(o)}if(i.shape!==void 0){i.shape[T]!==void 0&&n.push(`Array<${Y(i.shape[T])}>`),i.shape[M]!==void 0&&n.push(`Record<string, ${Y(i.shape[M])}>`);for(const[r,o]of Object.entries(i.shape))r!==T&&r!==M&&n.push(r)}if(t=i.mask,(t&u.HAS_FORMAT)!==0){const r=Tt(t);r&&n.push(`"${r}"`)}return t&u.UNDEFINED&&n.push("undefined"),t&u.NULL&&n.push("null"),t&u.NUMBER&&n.push("number"),t&u.STRING&&n.push("string"),t&u.BOOLEAN&&n.push("boolean"),n.length===0?"union":n.join(" | ")}if(t&u.ENTITY)return`Entity<${e.typenameValue}>`;if(t&u.ARRAY){const i=e.shape;return`Array<${Y(i)}>`}if(t&u.RECORD){const i=e.shape;return`Record<string, ${Y(i)}>`}if(t&u.OBJECT){const i=e.typenameValue;return i?`Object<${i}>`:"object"}return"unknown"}function Q(e,t,i){return new TypeError(`Validation error at ${e}: expected ${Y(t)}, got ${typeof i=="object"?i===null?"null":Array.isArray(i)?"array":"object":typeof i}`)}const oe=Array.isArray;function kt(e){if(e===null)return u.NULL;switch(typeof e){case"number":return u.NUMBER;case"string":return u.STRING;case"boolean":return u.BOOLEAN;case"undefined":return u.UNDEFINED;case"object":return oe(e)?u.ARRAY:u.OBJECT;default:throw new Error(`Invalid type: ${typeof e}`)}}function Ge(e){return j(e)}function j(e){if(e===null||typeof e!="object")return e;if(oe(e))return e.map(i=>j(i));if(e instanceof Date)return new Date(e.getTime());if(e instanceof Map){const i=new Map;for(const[n,s]of e)i.set(j(n),j(s));return i}if(e instanceof Set){const i=new Set;for(const n of e)i.add(j(n));return i}const t={};for(const i of Object.keys(e))t[i]=j(e[i]);return t}const bt=Object.entries,He=()=>{};class ct{queryClient=void 0;preloadedEntities=void 0;warn=He;isPartialEvent=!1;seen=void 0;seenByKey=void 0;reset(t,i,n,s=!1){this.queryClient=t,this.preloadedEntities=i,this.warn=n,this.isPartialEvent=s,t!==void 0&&(this.seen===void 0?(this.seen=new Map,this.seenByKey=new Map):(this.seen.clear(),this.seenByKey.clear()))}}function ae(e,t,i){return P(e,t,i,"")}function ze(e,t,i){return Ct(e,t,i)}function Pt(e,t,i,n){const s=e>>Et;if((e&u.IS_EAGER_FORMAT)!==0)try{return new G(t,s,!0)}catch(o){if((e&u.UNDEFINED)!==0){i.warn("Invalid formatted value for optional type, defaulting to undefined",{value:t,path:n,error:o instanceof Error?o.message:String(o)});return}throw o}return new G(t,s,!1)}function P(e,t,i,n){const s=t;if(s instanceof K){const c=s.get(e);if(c===void 0)throw Q(n,s,e);return c}if(s instanceof Set){if(!s.has(e))throw Q(n,s,e);return e}if(typeof s=="string"){if(e==null)return s;if(e!==s)throw Q(n,s,e);return e}if(typeof s=="number"){const c=kt(e);if((s&c)===0){if((s&u.UNDEFINED)!==0){i.warn("Invalid value for optional type, defaulting to undefined",{value:e,path:n});return}throw Q(n,s,e)}return(s&u.HAS_FORMAT)!==0&&e!==null&&e!==void 0?Pt(s,e,i,n):e}const r=s.mask,o=s._liveConfig;if(o!==void 0&&o.type===X.Value)return o.valueType!==void 0?P(e,o.valueType,i,n):e;if((r&u.PARSE_RESULT)!==0)try{return{success:!0,value:P(e,s.shape,i,n)}}catch(c){return{success:!1,error:c instanceof Error?c:new Error(String(c))}}const a=kt(e);if((r&a)===0&&!s.values?.has(e)){if((r&u.UNDEFINED)!==0){i.warn("Invalid value for optional type, defaulting to undefined",{value:e,path:n});return}throw Q(n,r,e)}return a<u.OBJECT?(r&u.HAS_FORMAT)!==0&&e!==null&&e!==void 0?Pt(r,e,i,n):e:(r&u.UNION)!==0?We(a,e,s,i,n):a===u.ARRAY?ce(e,s.shape,i,n):(r&u.RECORD)!==0?fe(e,s.shape,i,n):(r&u.ENTITY)!==0&&i.queryClient!==void 0?Ct(e,s,i):ue(e,s,i,n)}function We(e,t,i,n,s){if(e===u.ARRAY){const r=i.shape[T];return r===void 0||typeof r=="number"?t:ce(t,r,n,s)}else{const r=i.typenameField,o=r?t[r]:void 0;if(o===void 0||typeof o!="string"){const c=i.shape[M];if(c===void 0)throw new Error(`Typename field '${r}' is required for union discrimination but was not found in the data`);return fe(t,c,n,s)}const a=i.shape[o];if(a===void 0||typeof a=="number")throw new Error(`Unknown typename '${o}' in union`);return a.mask&u.ENTITY&&n.queryClient!==void 0?Ct(t,a,n):ue(t,a,n,s)}}function ce(e,t,i,n){const s=[];for(let r=0;r<e.length;r++)try{s.push(P(e[r],t,i,`${n}[${r}]`))}catch(o){i.warn("Failed to parse array item, filtering out",{index:r,value:e[r],error:o instanceof Error?o.message:String(o)})}return s}function fe(e,t,i,n){for(const[s,r]of bt(e))e[s]=P(r,t,i,`${n}["${s}"]`);return e}function ue(e,t,i,n){if(S.has(e))return e;const s=t.shape;for(const[r,o]of bt(s))e[r]=P(e[r],o,i,`${n}.${r}`);return e}function Ct(e,t,i){const n=i.queryClient,s=i.preloadedEntities;let r,o;if(s!==void 0)r=e.__entityRef,o=r;else{const p=e[t.idField];if(p==null||typeof p!="string"&&typeof p!="number")throw new Error(`Entity id must be a string or number: ${t.typenameValue} (got ${typeof p})`);o=p,r=D.hashValue([t.typenameValue,o])}const a=i.seenByKey.get(r);if(a!==void 0)return a.data;if(s!==void 0){const _=n.entityMap.getEntity(r)?.data??s.get(r);if(_===void 0)throw new Error(`Cached entity ${r} not found in preloaded map`);e=_}const c={};typeof t.idField=="symbol"&&(c[t.idField]=o);const f=n.entityMap.getEntity(r),l=i.isPartialEvent&&f!==void 0,d={key:r,shape:t,data:c,rawKeys:l?new Set(Object.keys(e)):void 0};i.seen.set(c,d),i.seenByKey.set(r,d);const y=`[[${t.typenameValue}:${o}]]`,g=t.shape;for(const[p,_]of bt(g))l&&!(p in e)||(c[p]=P(e[p],_,i,`${y}.${p}`));return c}function Je(e,t){return Xe(e,t.shape,t.typenameField)}function Xe(e,t,i){if(t===void 0)return!0;for(const n of Object.keys(t)){if(n===i)continue;const s=t[n];if(s instanceof v){if((s.mask&u.UNDEFINED)!==0)continue;if(!(n in e)||e[n]===void 0)return!1}else if(typeof s=="number"){if((s&u.UNDEFINED)!==0)continue;if(!(n in e)||e[n]===void 0)return!1}else if(!(n in e)||e[n]===void 0)return!1}return!0}const Ze=Object.prototype,z=new WeakMap;function F(e){if(typeof e!="object"||e===null)return e;if(tt.has(e))return F(e.getValue());if(S.has(e))return e;if(Array.isArray(e)){let t=z.get(e);return t===void 0&&(t=new Proxy(e,ti),z.set(e,t)),t}if(Object.getPrototypeOf(e)===Ze){let t=z.get(e);return t===void 0&&(t=new Proxy(e,ei),z.set(e,t)),t}return e}const ti={get(e,t,i){if(typeof t=="string"){const n=Number(t);if(Number.isInteger(n)&&n>=0&&n<e.length)return F(e[n])}return Reflect.get(e,t,i)},set(){throw new Error("Cannot mutate a read-only array")},deleteProperty(){throw new Error("Cannot mutate a read-only array")}},ei={get(e,t,i){return typeof t=="string"?F(e[t]):Reflect.get(e,t,i)},set(){throw new Error("Cannot mutate a read-only object")},deleteProperty(){throw new Error("Cannot mutate a read-only object")},has(e,t){return t in e},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(e,t)}};class ii{_notifier;_queryClient;_proxies=new Map;key;typename;id;idField;data;refCount=0;entityRefs;liveCollections=[];satisfiedDefs=new WeakSet;parseId=-1;_entityCache;_extraMethods;_extraGetters;constructor(t,i,n,s,r,o){this._notifier=C.notifier(),this._queryClient=o,this.key=t,this.typename=i,this.id=n,this.idField=s,this.data=r,this.entityRefs=void 0}retain(){this.refCount++;const t=this._entityCache?.gcTime;t!==void 0&&this._queryClient.gcManager.cancel(this.key,t)}release(){if(--this.refCount>0)return;if(this.refCount<0)throw new Error(`Entity ${this.typename}:${this.id} released more times than retained`);const t=this._entityCache?.gcTime;t!==void 0?this._queryClient.gcManager.schedule(this.key,t,Z.Entity):this.evict()}evict(){const t=this.liveCollections.slice();this.liveCollections.length=0;for(const n of t)n.destroy();this._queryClient.entityMap.remove(this.key);const i=this.entityRefs;if(this.entityRefs=void 0,i)for(const n of i.keys())n.release()}setChildRefs(t,i){const n=this.entityRefs;if(t!==void 0&&t.size>0)for(const s of t.keys())(n===void 0||!n.has(s))&&s.retain();if(n!==void 0&&n.size>0)for(const s of n.keys())(t===void 0||!t.has(s))&&s.release();this.entityRefs=t,i&&this.save()}addChildRef(t){this.entityRefs===void 0&&(this.entityRefs=new Map);const i=this.entityRefs.get(t)??0;this.entityRefs.set(t,i+1),i===0&&t.retain(),this.save()}removeChildRef(t){if(this.entityRefs===void 0)return;const i=this.entityRefs.get(t);i!==void 0&&(i<=1?(this.entityRefs.delete(t),t.release()):this.entityRefs.set(t,i-1),this.save())}getProxy(t){const i=t;let n=this._proxies.get(i);return n===void 0&&(n=si(this,this.key,t,this._notifier,this._queryClient),this._proxies.set(i,n)),n}get proxy(){return this._proxies.values().next().value}satisfiesDef(t){return this.satisfiedDefs.has(t)?!0:Je(this.data,t)?(this.satisfiedDefs.add(t),!0):!1}save(){this._queryClient.entityMap.save(this)}notify(){this._notifier.notify()}consume(){this._notifier.consume()}}function ni(e,t,i){const n=[];for(const s of e){if(typeof s!="object"||s===null)continue;const r=S.get(s);if(r===void 0)continue;const o=i.entityMap.getEntity(r);o!==void 0&&o.satisfiesDef(t)&&n.push(s)}return n}function si(e,t,i,n,s){const r=i.shape??{},o=i,a=o._methods,c=o._entityClass,f=o._entityConfig,l=c?c.prototype:gt.prototype,d=i.typenameField,y=new Map,g=new Map,p=()=>({__entityRef:t});let _;f?.hasSubscribe&&a&&"__subscribe"in a&&(_=C.relay(w=>{const h=b=>{b.__eventSource=t,s.applyMutationEvent(b)},E=a.__subscribe.call(m,h);return w.value=m,E}));let m;if(d&&!(d in r))throw new Error(`typenameField "${d}" must be declared in the entity shape`);const R=Object.keys(r);if(R.includes("__typename")||R.push("__typename"),a)for(const w of Object.keys(a))R.includes(w)||R.push(w);let N,x=R;function A(){const w=e._extraMethods;if(w!==N){if(N=w,x=R.slice(),w!==void 0)for(const E of Object.keys(w))x.includes(E)||x.push(E);const h=e._extraGetters;if(h!==void 0)for(const E of Object.keys(h))x.includes(E)||x.push(E)}return x}const B={getPrototypeOf(){return l},get(w,h){if(typeof h=="symbol")return;if(h==="toJSON")return p;if(h==="__context")return s.getContext();if(h==="__typename")return e.typename;if(_?.value,n.consume(),typeof h=="string"){const b=e._extraGetters;if(b!==void 0&&h in b)return b[h]();const I=e._extraMethods;if(I!==void 0&&h in I){let O=y.get(h);return O||(O=I[h].bind(m),y.set(h,O)),O}if(a&&h in a){let O=y.get(h);return O||(O=C.reactiveMethod(m,a[h].bind(m)),y.set(h,O)),O}}const E=e.data[h];if(typeof E=="object"&&E!==null&&tt.has(E))return F(E.getValue());if(Array.isArray(E)&&typeof h=="string"){const b=r[h];if(b instanceof v&&(b.mask&u.ARRAY)!==0){const I=b.shape;if(I instanceof v&&(I.mask&u.ENTITY)!==0){const O=I.typenameValue;if(O!==void 0){const Nt=s.getEntityDefsForTypename(O);if(Nt!==void 0&&Nt.length>1){const it=g.get(h);if(it!==void 0&&it.source===E)return F(it.filtered);const At=ni(E,I,s);return g.set(h,{source:E,filtered:At}),F(At)}}}}return F(E)}return F(E)},set(){throw new Error("Entity properties are read-only")},has(w,h){if(h==="__typename")return!0;if(typeof h=="string"){const E=e._extraGetters;if(E&&h in E)return!0;const b=e._extraMethods;if(b&&h in b||a&&h in a)return!0}return h in r},ownKeys(){return A()},getOwnPropertyDescriptor(w,h){if(h==="__typename")return{enumerable:!0,configurable:!0,value:e.typename,writable:!1};if(h in r)return{enumerable:!0,configurable:!0,value:B.get(w,h,m),writable:!1};if(typeof h=="string"){const E=e._extraGetters;if(E&&h in E)return{enumerable:!0,configurable:!0,value:B.get(w,h,m),writable:!1};const b=e._extraMethods;if(b&&h in b)return{enumerable:!0,configurable:!0,value:B.get(w,h,m),writable:!1};if(a&&h in a)return{enumerable:!1,configurable:!0,value:B.get(w,h,m),writable:!1}}}};return m=new Proxy({},B),S.set(m,t),C.setScopeOwner(m,s),m}class ri{instances=new Map;persistEntity;constructor(t){this.persistEntity=t}hasEntity(t){return this.instances.has(t)}getEntity(t){return this.instances.get(t)}getOrCreateEntity(t,i,n,s){let r=this.instances.get(t);if(r===void 0){const o=n.idField;if(o===void 0)throw new Error(`Entity id field is required ${n.typenameValue}`);const a=i[o];if(typeof a!="string"&&typeof a!="number")throw new Error(`Entity id must be string or number: ${n.typenameValue}`);const c=n;r=new ii(t,n.typenameValue,a,o,i,s),r._entityCache=c._entityCache,this.instances.set(t,r)}return r.parseId=s.currentParseId,r}remove(t){this.instances.delete(t)}save(t){let i;if(t.entityRefs){i=new Set;for(const n of t.entityRefs.keys())i.add(n.key)}this.persistEntity(t.key,t.data,i)}}class Rt{onlineSignal;manualOverride=void 0;eventListenersAttached=!1;constructor(t){const i=t??this.detectOnlineStatus();this.onlineSignal=C.signal(i),this.canAttachListeners()&&this.attachEventListeners()}get isOnline(){return this.manualOverride!==void 0?this.manualOverride:this.onlineSignal.value}setNetworkStatus(t){this.manualOverride=t,this.onlineSignal.value=t}clearManualOverride(){this.manualOverride=void 0,this.onlineSignal.value=this.detectOnlineStatus()}getOnlineSignal(){return this.onlineSignal}detectOnlineStatus(){return typeof navigator<"u"&&"onLine"in navigator?navigator.onLine:!0}canAttachListeners(){return typeof window<"u"&&typeof window.addEventListener=="function"}destroy(){this.eventListenersAttached&&this.handleOnline&&this.handleOffline&&(window.removeEventListener("online",this.handleOnline),window.removeEventListener("offline",this.handleOffline),this.eventListenersAttached=!1)}handleOnline=void 0;handleOffline=void 0;attachEventListeners(){this.eventListenersAttached||(this.handleOnline=()=>{this.manualOverride===void 0&&(this.onlineSignal.value=!0)},this.handleOffline=()=>{this.manualOverride===void 0&&(this.onlineSignal.value=!1)},window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline),this.eventListenersAttached=!0)}}class xt{static onlineSignal=C.signal(!0);get isOnline(){return!0}setNetworkStatus(t){}clearManualOverride(){}getOnlineSignal(){return xt.onlineSignal}destroy(){}}const de=new Rt,oi=C.context(de);function Ot(e,t=typeof window>"u"){let i;e===!1?i=0:e===void 0||e===!0?i=t?0:3:typeof e=="number"?i=e:i=e.retries;const n=typeof e=="object"&&e.retryDelay?e.retryDelay:s=>1e3*Math.pow(2,s);return{retries:i,retryDelay:n}}class le{static cache;params;config;constructor(){return yt(this)}}class ai extends le{method="GET";path;searchParams;body;headers;requestOptions;loadNext;getStorageKey(){return`${this.method??"GET"}:${this.path??""}`}async send(){return this.executeRequest()}resolveLoadNext(){const i=(this.getLoadNext?this.getLoadNext():void 0)??this.rawLoadNext;if(i===void 0)return;const n={params:this.params??{},result:this.resultData};return{url:i.url!==void 0?q(i.url,n):void 0,searchParams:i.searchParams!==void 0?q(i.searchParams,n):void 0}}hasNext(){const t=this.resolveLoadNext();if(t===void 0)return!1;if(t.url!==void 0&&t.url!==null)return!0;if(t.searchParams!==void 0){const i=Object.keys(t.searchParams);if(i.length===0)return!1;for(const n of i)if(t.searchParams[n]===void 0||t.searchParams[n]===null)return!1;return!0}return!1}async sendNext(){const t=this.resolveLoadNext();if(t===void 0)throw new Error("loadNext is not configured for this query");return this.executeRequest(t)}async executeRequest(t){const i=t?.url??(this.getPath?this.getPath():this.path),n=this.getMethod?this.getMethod():this.method,s=this.getSearchParams?this.getSearchParams():this.searchParams,r=t?.searchParams?{...s,...t.searchParams}:s,o=this.getBody?this.getBody():this.body,a=this.getRequestOptions?this.getRequestOptions():this.requestOptions;if(!i)throw new Error("RESTQuery requires a path. Define `path` as a field or override `getPath()`.");let c=i;if(r){const R=new URLSearchParams;for(const x in r){const A=r[x];A!=null&&R.append(x,String(A))}const N=R.toString();N&&(c+="?"+N)}const f=dt(a?.baseUrl)??dt(this.context.baseUrl),l=f?`${f}${c}`:c,{baseUrl:d,signal:y,...g}=a??{},_=o||this.headers?{...o?{"Content-Type":"application/json"}:void 0,...this.headers}:void 0,m=await this.context.fetch(l,{method:n,headers:_,body:o?JSON.stringify(o):void 0,signal:this.signal,...g});return this.response=m,m.json()}}const Lt=new WeakMap;class et{constructor(t,i){this.captured=i,this.statics=t}statics;createExecutionContext(t,i){return rt(this.captured,t,i)}resolveOptions(t){const{methods:i}=this.captured,n=i.getConfig?i.getConfig.call(t):t.config,s=Ot(n?.retry);return{config:n,retryConfig:s}}static for(t){let i=Lt.get(t);if(i!==void 0)return i;const n=new t,s=Ht(n),r=String(s.methods.getStorageKey.call(s.fields)),o=s.fields.result,a=o instanceof v?o:re.object(o),c=(a.mask&u.ENTITY)!==0,f=t.cache,l=s.fields.loadNext,d=typeof s.methods.sendNext=="function",y=c?a:new v(u.ENTITY|u.OBJECT,a.shape,void 0,void 0,r,lt);return i=new et({id:r,shape:y,cache:f,rawLoadNext:l,hasSendNext:d,isEntityResult:c},s),Lt.set(t,i),i}}const ci=(e,t)=>{const i=et.for(e);return St(i,t)};function fi(e,...t){const i=et.for(e),n=C.getContext(Re);if(n===void 0)throw new Error("QueryClient not found");const s=t[0];return n.getQuery(i,s)}function he(e,t){return new Promise((i,n)=>{if(t?.aborted){n(t.reason);return}const s=setTimeout(i,e);t?.addEventListener("abort",()=>{clearTimeout(s),n(t.reason)},{once:!0})})}async function ft(e,t,i){if(t.retries<0)throw new Error("retries must be non-negative");const n=Math.max(0,t.retries);let s;for(let r=0;r<=n;r++){i?.throwIfAborted();try{return await e()}catch(o){if(s=o,r>=n)throw o;await he(t.retryDelay(r),i)}}throw s}class ui{def;queryKey;storageKey=-1;relay;queryClient;initialized=!1;updatedAt=void 0;params=void 0;unsubscribe=void 0;_relayState=void 0;wasPaused=!1;currentParams=void 0;debounceTimer=void 0;config=void 0;retryConfig=Ot(void 0);_lastResponse=void 0;_abortController=void 0;_executionCtx=void 0;_executionCtxKey=-1;rootEntity;_extraMethods={};_queryId=0;get key(){return this.queryKey}get relayState(){if(!this._relayState)throw new Error("Relay state not initialized");return this._relayState}constructor(t,i,n,s){this.def=t,this.queryClient=i,this.queryKey=n,this.params=s,this._extraMethods={__refetch:this.refetch},t.statics.hasSendNext&&(this._extraMethods.__loadNext=this.loadNext);const r=qt(s);this._queryId=r!==void 0?D.hashValue(r):0,this.relay=C.relay(o=>{this._relayState=o;const a=()=>{clearTimeout(this.debounceTimer),this.debounceTimer=void 0,this._abortController?.abort(),this._abortController=void 0,this._loadNextAbort?.abort(),this._loadNextAbort=void 0,this._loadNextPromise=void 0,this.unsubscribe?.(),this.unsubscribe=void 0;const f=this.config?.gcTime??Vt.DEFAULT_GC_TIME;this.queryClient.gcManager.schedule(this.queryKey,f,Z.Query)},c=(f=!1)=>{const{wasPaused:l,isPaused:d,initialized:y}=this;if(this.wasPaused=d,d&&!l&&y){a();return}const g=qt(this.params),p=St(this.def,g),_=p!==this.storageKey;_&&(this.currentParams=g,this.storageKey=p),this.getOrCreateExecutionContext(),this.initialized?l||f?(this.queryClient.activateQuery(this),f&&this.updatedAt!==void 0&&this.setupSubscription(),(this.config?.refreshStaleOnReconnect??!0)&&this.isStale&&this.runDebounced()):_&&(this.setupSubscription(),this.runDebounced()):(this.queryClient.activateQuery(this),this.initialize())};return c(!0),{update:c,deactivate:a}},{desc:`Query(${t.statics.id})`})}applyData(t,i,n=!1,s){const r=this.def;return this.rootEntity=this.queryClient.parseAndApplyRootEntity(t,this._queryId,r.statics.shape,i,n,s),this.rootEntity._extraMethods===void 0&&(this.rootEntity._extraMethods=this._extraMethods,this.rootEntity._extraGetters={__hasNext:()=>this.hasNext,__isLoadingNext:()=>this._loadNextPromise!==void 0}),this.rootEntity.getProxy(r.statics.shape)}saveQueryMetadata(){if(this.rootEntity===void 0||this.updatedAt===void 0)return;const t=new Map(this.rootEntity.entityRefs??[]);t.set(this.rootEntity,1),this.queryClient.saveQueryData(this.def,this.storageKey,{__entityRef:this.rootEntity.key},this.updatedAt,t)}async initialize(){const t=this.queryClient,i=this.relayState;this.initialized=!0;let n;try{n=await t.loadCachedQuery(this.def,this.storageKey),n!==void 0&&(this.updatedAt=n.updatedAt,i.value=this.applyData(n.value,!1,!1,n.preloadedEntities))}catch(s){t.store.deleteQuery(this.storageKey),t.getContext().log?.warn?.("Failed to initialize query, the query cache may be corrupted or invalid",s)}if(!this.isPaused)try{if(n!==void 0&&this.setupSubscription(),n===void 0||this.isStale){if(await he(0),this.isPaused)return;this.runQueryImmediately()}}catch(s){i.setError(s)}}setupSubscription(){this.unsubscribe?.(),this.unsubscribe=void 0;const t=this.config?.subscribe;if(!t)return;const i=this._executionCtx;this.unsubscribe=t.call(i,n=>{n.__eventSource=this.queryKey,this.queryClient.applyMutationEvent(n)})}getOrCreateExecutionContext(){return(this._executionCtx===void 0||this._executionCtxKey!==this.storageKey)&&(this._executionCtxKey=this.storageKey,this._executionCtx=this.def.createExecutionContext(this.currentParams??{},this.queryClient.getContext()),this._executionCtx.refetch=()=>this.refetch(),this._executionCtx.rawLoadNext=this.def.statics.rawLoadNext),this._executionCtx.response=this._lastResponse,this.resolveAndApplyOptions(),this._executionCtx}resolveAndApplyOptions(){const t=this.def.resolveOptions(this._executionCtx);this.config=t.config,this.retryConfig=t.retryConfig}async runQuery(){const t=this.def;if(this.isPaused)throw new Error("Query is paused due to network status");const i=this.getOrCreateExecutionContext(),{send:n}=t.captured.methods,s=this._abortController?.signal;return i.signal=s,ft(async()=>{const r=await n.call(i);this._lastResponse=i.response,this._executionCtx.response=this._lastResponse,this.resolveAndApplyOptions(),this.updatedAt=Date.now();const o=this.applyData(r,!0);return this.saveQueryMetadata(),this.unsubscribe===void 0&&this.setupSubscription(),o},this.retryConfig,s)}runQueryImmediately(){this._abortController?.abort(),this._abortController=new AbortController,this._loadNextAbort?.abort(),this._loadNextAbort=void 0,this._loadNextPromise=void 0,this.relayState.setPromise(this.runQuery())}runDebounced(){if(this.relayState.isPending)return;const t=this.config?.debounce??0;clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runQueryImmediately()},t)}refetch=()=>this.relayState.isPending?this.relay:(this.runQueryImmediately(),this.relay);_loadNextPromise=void 0;_loadNextAbort=void 0;loadNext=()=>{if(this.updatedAt===void 0)throw new Error("Cannot call __loadNext before initial data has loaded");return this._loadNextPromise!==void 0?this._loadNextPromise:(queueMicrotask(()=>this.rootEntity?.notify()),this._loadNextPromise=this.runLoadNext().then(t=>(this._loadNextPromise=void 0,this.rootEntity?.notify(),t),t=>{throw this._loadNextPromise=void 0,this.rootEntity?.notify(),t}),this._loadNextPromise)};get hasNext(){if(this.rootEntity===void 0||!this._executionCtx)return!1;const t=this.def.captured.methods.hasNext;return t?(this._executionCtx.resultData=this.rootEntity.data,t.call(this._executionCtx)):!1}async runLoadNext(){const t=this.def;this._loadNextAbort=new AbortController;const i=this._loadNextAbort.signal,n=this.getOrCreateExecutionContext();n.signal=i,n.resultData=this.rootEntity.data;const s=t.captured.methods.sendNext;return ft(async()=>{const r=await s.call(n);this._lastResponse=n.response,this._executionCtx.response=this._lastResponse,this.resolveAndApplyOptions(),this.updatedAt=Date.now();const o=this.applyData(r,!0,!0);return this.saveQueryMetadata(),o},this.retryConfig,i)}get isStale(){if(this.updatedAt===void 0)return!0;const t=this.config?.staleTime??0;return Date.now()-this.updatedAt>=t}get isPaused(){const t=this.config?.networkMode??U.Online;if(t===U.Always)return!1;const i=this.queryClient.networkManager.getOnlineSignal().value;switch(t){case U.Online:return!i;case U.OfflineFirst:return!i&&this.updatedAt===void 0;default:return!1}}}class di{def;queryClient;_lastResponse;_inFlight=!1;task;constructor(t,i){this.def=t,this.queryClient=i,this.task=this.createTask()}createTask(){return C.task(async t=>{if(this._inFlight)throw new Error("A mutation is already in progress. Await the previous call before starting a new one.");this._inFlight=!0;try{const i=await this.executeWithRetry(t),n=this.validateResponse(i);return this.processEffects(t,n),n}finally{this._inFlight=!1}},{desc:`Mutation(${this.def.id})`})}validateResponse(t){const i=this.def.responseShape;if(!(i instanceof v))return t;const n=this.queryClient.getContext().log?.warn??(()=>{}),s=new ct;return s.reset(void 0,void 0,n),ae(t,i,s)}processEffects(t,i){let n;if(this.def.hasGetEffects){const r=rt(this.def.captured,t??{},this.queryClient.getContext());r.result=i,r.response=this._lastResponse,n=r.getEffects()}else if(this.def.effects!==void 0){const r={params:t,result:i};n=q(this.def.effects,r)}if(n===void 0)return;const s=this.queryClient;nt(n.creates,"create",s),nt(n.updates,"update",s),nt(n.deletes,"delete",s)}executeWithRetry(t){const i=Ot(this.def.config?.retry,!0);return ft(async()=>{const n=rt(this.def.captured,t??{},this.queryClient.getContext()),s=await this.def.captured.methods.send.call(n);return this._lastResponse=n.response,s},i)}}function li(e){return typeof e=="string"?e:V(e).typenameValue}function nt(e,t,i){if(e)for(const[n,s]of e){const r=li(n);r!==void 0&&i.applyMutationEvent({type:t,typename:r,data:s})}}const ye="__eventSource";function pe(e){return{field:e,segments:e.indexOf(".")!==-1?e.split("."):void 0}}function hi(e){return e.map(pe)}function yi(e,t){if(t.segments===void 0)return e[t.field];let i=e;for(const n of t.segments){if(i==null)return;i=i[n]}return i}function ge(e,t){const i=[];for(let n=0;n<t.length;n++){const s=t[n],r=yi(e,s);if(r===void 0)return;i.push(s.field,r)}return D.hashValue(i)}function pi(e,t){if(e===void 0)return;const i=new Map;for(const[n,s]of e){const r=s.slice().sort((c,f)=>c[0]<f[0]?-1:c[0]>f[0]?1:0),o=[];let a=!0;for(const[c,f]of r){let l;if(Yt(f)){const d=Gt(f);l=pt(d,t)}else l=f;if(l===void 0){a=!1;break}o.push(c,l)}a&&i.set(n,D.hashValue(o))}return i.size>0?i:void 0}function jt(e,t){const i=e.get(t);if(i!==void 0)return i.map(([n])=>n).sort()}class gi{fields;fieldPaths;_bindings=new Map;constructor(t){this.fields=t,this.fieldPaths=t.map(pe)}register(t,i){let n=this._bindings.get(t);n===void 0&&(n=new Set,this._bindings.set(t,n)),n.add(i)}unregister(t,i){const n=this._bindings.get(t);n!==void 0&&(n.delete(i),n.size===0&&this._bindings.delete(t))}getMatching(t){return this._bindings.get(t)}get isEmpty(){return this._bindings.size===0}}function Ut(e){return D.hashValue(e)}class vi{_groups=new Map;getOrCreateGroup(t){const i=Ut(t);let n=this._groups.get(i);return n===void 0&&(n=new gi(t),this._groups.set(i,n)),n}register(t,i,n){this.getOrCreateGroup(i).register(t,n)}unregister(t,i,n){const s=Ut(i),r=this._groups.get(s);r!==void 0&&(r.unregister(t,n),r.isEmpty&&this._groups.delete(s))}registerBinding(t,i){const n=t._constraintHashes.get(i);if(n===void 0)return;const s=jt(t._constraintFieldRefs,i);s!==void 0&&this.register(n,s,t)}unregisterBinding(t,i){const n=t._constraintHashes.get(i);if(n===void 0)return;const s=jt(t._constraintFieldRefs,i);s!==void 0&&this.unregister(n,s,t)}routeEvent(t,i,n,s,r,o){for(const a of this._groups.values()){const c=ge(i,a.fieldPaths);if(c===void 0)continue;const f=a.getMatching(c);if(f!==void 0)for(const l of f)l.onEvent(t,n,s,r,o)}}}function $t(e){const t=new Set;for(const i of e)if(typeof i=="object"&&i!==null){const n=L(i);n!==void 0&&t.add(n)}return t}class ve{_queryClient;_parent;_constraintHashes;_entityDefsByTypename;_constraintFieldRefs;instance;constructor(t,i,n,s,r,o){this._queryClient=n,this._parent=s,this._constraintHashes=r,this._constraintFieldRefs=i,this.instance=o,this._entityDefsByTypename=new Map;for(const a of t)a.typenameValue!==void 0&&this._entityDefsByTypename.set(a.typenameValue,a);tt.add(this)}getValue(){return this.instance.getValue()}toJSON(){return this.instance.getRawValue()}reset(t){this.instance.reset(t)}append(t){this.instance.append(t)}onEvent(t,i,n,s,r){const o=this._entityDefsByTypename.get(t);if(o===void 0)return;const a=this._queryClient.entityMap.getEntity(i);if(n==="delete"){const f=a!==void 0?a.getProxy(o):r;f!==void 0&&(this.instance.onEvent(i,f,r??a?.data??{},"delete"),s?.());return}if(a===void 0||!a.satisfiesDef(o))return;s?.();const c=a.getProxy(o);this.instance.onEvent(i,c,a.data,n)}destroy(){this._queryClient.unregisterLiveCollection(this);const t=this._parent.liveCollections,i=t.indexOf(this);i!==-1&&t.splice(i,1)}}class mi{_notifier;_items;_keys;_outputSignal;_queryClient;_parent;constructor(t,i,n,s,r,o){this._notifier=C.notifier(),this._items=n,this._keys=$t(n),this._queryClient=t,this._parent=i;const a=s!==void 0&&r!==void 0,c=o!==void 0;(a||c)&&(this._outputSignal=C.reactiveSignal(()=>{this._notifier.consume();let f=this._items;if(a){const l=[];for(const d of f){if(typeof d!="object"||d===null){l.push(d);continue}const y=L(d);if(y===void 0){l.push(d);continue}const g=t.entityMap.getEntity(y);if(g===void 0){l.push(d);continue}g.consume(),ge(g.data,s)===r&&l.push(d)}f=l}return c&&(f=(f===this._items?f.slice():f).sort(o)),f}))}onEvent(t,i,n,s){switch(s){case"create":this.add(t,i);break;case"update":!this.has(t)&&i!==void 0&&this.add(t,i);break;case"delete":this.remove(t);break}}getValue(){return this._outputSignal!==void 0?this._outputSignal.value:(this._notifier.consume(),this._items)}getRawValue(){return this._items}add(t,i){if(this._keys.has(t))return!1;this._keys.add(t),this._items.push(i);const n=this._queryClient.entityMap.getEntity(t);return n!==void 0&&(this._parent.addChildRef(n),n.save()),this._notifier.notify(),!0}remove(t){if(!this._keys.has(t))return!1;this._keys.delete(t);const i=this._findIndex(t);i!==-1&&this._items.splice(i,1);const n=this._queryClient.entityMap.getEntity(t);return n!==void 0&&this._parent.removeChildRef(n),this._notifier.notify(),!0}has(t){return this._keys.has(t)}reset(t){const i=this._items,n=Array.isArray(t)?t:[];this._items=n,this._keys=$t(n);for(const s of n)if(typeof s=="object"&&s!==null){const r=L(s);if(r!==void 0){const o=this._queryClient.entityMap.getEntity(r);o!==void 0&&this._parent.addChildRef(o)}}for(const s of i)if(typeof s=="object"&&s!==null){const r=L(s);if(r!==void 0){const o=this._queryClient.entityMap.getEntity(r);o!==void 0&&this._parent.removeChildRef(o)}}this._notifier.notify()}append(t){if(Array.isArray(t))for(const i of t){if(typeof i!="object"||i===null)continue;const n=L(i);n!==void 0&&this.add(n,i)}}_findIndex(t){for(let i=0;i<this._items.length;i++){const n=this._items[i];if(typeof n=="object"&&n!==null&&L(n)===t)return i}return-1}}class _i{_notifier;_value;_createdKeys;_deletedKeys;_queryClient;_parent;_onCreate;_onUpdate;_onDelete;constructor(t,i,n,s,r,o){this._notifier=C.notifier(),this._value=n,this._createdKeys=new Set,this._deletedKeys=new Set,this._queryClient=t,this._parent=i,this._onCreate=s,this._onUpdate=r,this._onDelete=o}onEvent(t,i,n,s){switch(s){case"create":if(this._createdKeys.has(t))return;this._createdKeys.add(t),this._value=this._onCreate(this._value,i);break;case"update":this._value=this._onUpdate(this._value,i??n);break;case"delete":if(this._deletedKeys.has(t))return;this._deletedKeys.add(t),this._value=this._onDelete(this._value,i??n);break}this._notifier.notify()}getValue(){return this._notifier.consume(),this._value}getRawValue(){return this._value}reset(t){this._value=t,this._createdKeys.clear(),this._deletedKeys.clear(),this._notifier.notify()}append(t){}}function me(e,t,i,n,s){let r=e.constraintFieldRefs;if(r===void 0){r=new Map;for(const f of e.entityDefs){const l=f.typenameValue;l!==void 0&&r.set(l,[[ye,i.key]])}}const o=pi(r,n)??new Map;let a;if(e.type===X.Array){let f,l;if(e.constraintFieldRefs!==void 0&&o.size>0&&o.size===1)for(const[d]of e.constraintFieldRefs){const y=o.get(d);if(y!==void 0){l=y;const g=e.constraintFieldRefs.get(d);g!==void 0&&(f=hi(g.map(([p])=>p)));break}}a=new mi(s,i,Array.isArray(t)?t:[],f,l,e.sort)}else a=new _i(s,i,t,e.onCreate,e.onUpdate,e.onDelete);const c=new ve(e.entityDefs,r,s,i,o,a);return i.liveCollections.push(c),s.registerLiveCollection(c),c}const _e=Object.entries,Ee=Object.prototype;function st(e,t,i,n=!1){const s=e.queryClient;s.currentParseId++;const r=e.seen,o=new Map;return{data:H(t,r,s,i,o,n),entityRefs:o}}function H(e,t,i,n,s,r){if(typeof e!="object"||e===null)return e;const o=t.get(e);if(o!==void 0)return Ei(o,t,i,n,s,r);if(Array.isArray(e)){for(let a=0;a<e.length;a++){const c=e[a];typeof c=="object"&&c!==null&&!(c instanceof G)&&!S.has(c)&&(e[a]=H(c,t,i,n,s,r))}return e}if(Object.getPrototypeOf(e)===Ee&&!S.has(e)){const a=e;for(const c of Object.keys(a)){const f=a[c];typeof f=="object"&&f!==null&&!(f instanceof G)&&!S.has(f)&&(a[c]=H(f,t,i,n,s,r))}}return e}function we(e){return typeof e=="object"&&e!==null&&!(e instanceof G)&&!S.has(e)}function Ei(e,t,i,n,s,r){const{key:o,data:a,shape:c,rawKeys:f}=e,l=c.shape,d=i.prepareEntity(o,a,c),y=d.data,g=y!==a,p=g&&f!==void 0&&d.entityRefs!==void 0?new Map(d.entityRefs):new Map;if(g?(be(l,a,y,f,d,y,t,i,n,p,r),d.notify()):Ce(l,a,d,a,t,i,n,p,r),r&&d.liveCollections.length>0)for(const m of d.liveCollections){const R=m.instance.getRawValue();if(Array.isArray(R))for(const N of R){if(typeof N!="object"||N===null)continue;const x=S.get(N);if(x===void 0)continue;const A=i.entityMap.getEntity(x);A!==void 0&&p.set(A,(p.get(A)??0)+1)}}d.setChildRefs(p.size>0?p:void 0,n);const _=d.getProxy(c);return s.set(d,(s.get(d)??0)+1),_}function be(e,t,i,n,s,r,o,a,c,f,l){for(const[d,y]of _e(e))if(!(n!==void 0&&!n.has(d)))if(we(t[d])&&(t[d]=H(t[d],o,a,c,f,l)),y instanceof v&&y._liveConfig!==void 0){const g=i[d];g instanceof ve?l?g.append(t[d]):g.reset(t[d]):i[d]=me(y._liveConfig,t[d],s,r,a)}else{const g=t[d],p=i[d];if(ut(g)&&ut(p)){const _=y instanceof v&&y.shape!==void 0?y.shape:void 0;if(_!==void 0)be(_,g,p,void 0,s,r,o,a,c,f,l);else for(const m of Object.keys(g))p[m]=g[m];i[d]=p}else i[d]=g}}function Ce(e,t,i,n,s,r,o,a,c){for(const[f,l]of _e(e))if(f in t)if(we(t[f])&&(t[f]=H(t[f],s,r,o,a,c)),l instanceof v&&l._liveConfig!==void 0)t[f]=me(l._liveConfig,t[f],i,n,r);else{const d=t[f];if(ut(d)){const y=l instanceof v&&l.shape!==void 0?l.shape:void 0;y!==void 0&&Ce(y,d,i,n,s,r,o,a,c)}}}function ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Ee&&!S.has(e)}function dt(e){if(e!==void 0)return typeof e=="string"?e:typeof e=="function"?e():e.value}function wi(e){return C.isSignal(e)}function qt(e){if(e===void 0)return;const t={};for(const[i,n]of Object.entries(e))wi(n)?t[i]=n.value:t[i]=n;return t}const St=(e,t)=>D.hashValue([e.statics.id,t]);class bi{constructor(t,i={fetch,log:console},n,s){this.context=i,this.isServer=typeof window>"u",this.store=t,this.gcManager=s??(this.isServer?new Bt:new Kt(this.handleEviction,this.context.evictionMultiplier)),this.networkManager=n??new Rt,this.entityMap=new ri((r,o,a)=>this.store.saveEntity(r,o,a)),this.store.purgeStaleQueries?.()}entityMap;queryInstances=new Map;mutationInstances=new Map;gcManager;networkManager;isServer;store;currentParseId=0;typenameRegistry=new Map;constraintRegistry=new Map;mergedDefCache=new Map;getContext(){return this.context}registerEntityDef(t){const i=t.typenameValue;if(i===void 0||t._entityClass===void 0)return;const n=this.typenameRegistry.get(i);if(n!==void 0){if(n.indexOf(t)!==-1)return;n.push(t),this.mergedDefCache.delete(i),this.getMergedDef(i)}else this.typenameRegistry.set(i,[t])}getEntityDefsForTypename(t){return this.typenameRegistry.get(t)}getMergedDef(t){let i=this.mergedDefCache.get(t);if(i!==void 0)return i;const n=this.typenameRegistry.get(t);if(n!==void 0)return i=v.merge(n),this.mergedDefCache.set(t,i),i}saveQueryData(t,i,n,s,r){const o=r!==void 0&&r.size>0?new Set([...r.keys()].map(a=>a.key)):void 0;this.store.saveQuery(t,i,n,s,o)}activateQuery(t){const{def:i,queryKey:n,storageKey:s,config:r}=t;this.store.activateQuery(i,s);const o=r?.gcTime??Vt.DEFAULT_GC_TIME;this.gcManager.cancel(n,o)}loadCachedQuery(t,i){return this.store.loadQuery(t,i)}getQuery(t,i){const n=St(t,i);let s=this.queryInstances.get(n);return s===void 0&&(s=new ui(t,this,n,i),this.queryInstances.set(n,s)),s.relay}getMutation(t){const i=t.id;let n=this.mutationInstances.get(i);return n===void 0&&(n=new di(t,this),this.mutationInstances.set(i,n)),n.task}parseData(t,i,n){const s=this.context.log?.warn??(()=>{}),r=new ct;return r.reset(this,n,s),{data:ae(t,i,r),ctx:r}}applyRefs(t,i=!0,n=!1){return st(t.ctx,t.data,i,n)}parseAndApplyRootEntity(t,i,n,s,r=!1,o){typeof n.idField=="symbol"&&typeof t=="object"&&t!==null&&!("__entityRef"in t)&&(t[lt]=i);const a=this.parseData(t,n,o),c=st(a.ctx,a.data,s,r),f=S.get(c.data);return this.entityMap.getEntity(f)}prepareEntity(t,i,n){return this.registerEntityDef(n),this.entityMap.getOrCreateEntity(t,i,n,this)}applyMutationEvent(t){const{type:i,typename:n}=t,s=this.getMergedDef(n);if(s===void 0)return;const r=s.idField;if(r===void 0||typeof r=="symbol")return;const o=t.data,a=t.id!==void 0?t.id:i==="delete"&&(typeof o=="string"||typeof o=="number")?o:o[r];if(a===void 0)return;const c=D.hashValue([n,a]),f=t.__eventSource,l=typeof o=="object"&&o!==null?o:{},d=this.entityMap.getEntity(c);if(i==="delete"){const _=d!==void 0?d.data:l;this.routeEvent(n,_,c,i,f,void 0,_);return}try{const _=this.context.log?.warn??(()=>{}),m=new ct;m.reset(this,void 0,_,!0);const R=ze(l,s,m);st(m,R,!0)}catch(_){if(this.context.log?.warn?.("Failed to apply mutation event",_),d===void 0){const m=this.entityMap.getEntity(c);m!==void 0&&m.evict()}return}const y=this.entityMap.getEntity(c);if(y===void 0)return;this.entityMap.save(y);const g=d===void 0;let p=!1;this.routeEvent(n,y.data,c,i,f,()=>{p=!0}),g&&!p&&y.evict()}handleEviction=(t,i)=>{if(i===Z.Query){const s=this.queryInstances.get(t);if(s===void 0)return;s.rootEntity?.evict(),this.queryInstances.delete(t);return}const n=this.entityMap.getEntity(t);n!==void 0&&n.evict()};getOrCreateMatcher(t){let i=this.constraintRegistry.get(t);return i===void 0&&(i=new vi,this.constraintRegistry.set(t,i)),i}registerLiveCollection(t){for(const[i,n]of t._entityDefsByTypename)this.registerEntityDef(n),this.getOrCreateMatcher(i).registerBinding(t,i)}unregisterLiveCollection(t){for(const i of t._entityDefsByTypename.keys()){const n=this.constraintRegistry.get(i);n!==void 0&&n.unregisterBinding(t,i)}}routeEvent(t,i,n,s,r,o,a){const c=this.constraintRegistry.get(t);if(c===void 0)return;const f=r!==void 0?{...i,[ye]:r}:i;c.routeEvent(t,f,n,s,o,a)}destroy(){this.gcManager.destroy(),this.networkManager.destroy(),this.queryInstances.clear(),this.mutationInstances.clear(),this.constraintRegistry.clear(),this.typenameRegistry.clear(),this.mergedDefCache.clear()}}const Re=C.context(void 0);exports.ARRAY_KEY=T;exports.Entity=gt;exports.GcManager=Kt;exports.LiveFieldConfig=$;exports.LiveFieldType=X;exports.Mask=u;exports.NetworkManager=Rt;exports.NetworkManagerContext=oi;exports.NetworkMode=U;exports.NoOpGcManager=Bt;exports.NoOpNetworkManager=xt;exports.QUERY_ID=lt;exports.Query=le;exports.QueryClient=bi;exports.QueryClientContext=Re;exports.RECORD_KEY=M;exports.RESTQuery=ai;exports.ValidatorDef=v;exports.createDefinitionProxy=yt;exports.defaultNetworkManager=de;exports.draft=Ge;exports.extractDefinition=Ht;exports.fetchQuery=fi;exports.queryKeyForClass=ci;exports.registerFormat=wt;exports.resolveBaseUrl=dt;exports.t=re;
2
+ //# sourceMappingURL=QueryClient-CpmwggOn.js.map