@depup/reduxjs__toolkit 2.12.0-depup.28

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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/changes.json +18 -0
  4. package/dist/cjs/index.js +6 -0
  5. package/dist/cjs/redux-toolkit.development.cjs +2406 -0
  6. package/dist/cjs/redux-toolkit.development.cjs.map +1 -0
  7. package/dist/cjs/redux-toolkit.production.min.cjs +3 -0
  8. package/dist/cjs/redux-toolkit.production.min.cjs.map +1 -0
  9. package/dist/index.d.mts +2665 -0
  10. package/dist/index.d.ts +2665 -0
  11. package/dist/query/cjs/index.js +6 -0
  12. package/dist/query/cjs/rtk-query.development.cjs +3092 -0
  13. package/dist/query/cjs/rtk-query.development.cjs.map +1 -0
  14. package/dist/query/cjs/rtk-query.production.min.cjs +2 -0
  15. package/dist/query/cjs/rtk-query.production.min.cjs.map +1 -0
  16. package/dist/query/index.d.mts +3066 -0
  17. package/dist/query/index.d.ts +3066 -0
  18. package/dist/query/react/cjs/index.js +6 -0
  19. package/dist/query/react/cjs/rtk-query-react.development.cjs +748 -0
  20. package/dist/query/react/cjs/rtk-query-react.development.cjs.map +1 -0
  21. package/dist/query/react/cjs/rtk-query-react.production.min.cjs +2 -0
  22. package/dist/query/react/cjs/rtk-query-react.production.min.cjs.map +1 -0
  23. package/dist/query/react/index.d.mts +1009 -0
  24. package/dist/query/react/index.d.ts +1009 -0
  25. package/dist/query/react/rtk-query-react.browser.mjs +2 -0
  26. package/dist/query/react/rtk-query-react.browser.mjs.map +1 -0
  27. package/dist/query/react/rtk-query-react.legacy-esm.js +740 -0
  28. package/dist/query/react/rtk-query-react.legacy-esm.js.map +1 -0
  29. package/dist/query/react/rtk-query-react.modern.mjs +705 -0
  30. package/dist/query/react/rtk-query-react.modern.mjs.map +1 -0
  31. package/dist/query/rtk-query.browser.mjs +2 -0
  32. package/dist/query/rtk-query.browser.mjs.map +1 -0
  33. package/dist/query/rtk-query.legacy-esm.js +3117 -0
  34. package/dist/query/rtk-query.legacy-esm.js.map +1 -0
  35. package/dist/query/rtk-query.modern.mjs +3052 -0
  36. package/dist/query/rtk-query.modern.mjs.map +1 -0
  37. package/dist/react/cjs/index.js +6 -0
  38. package/dist/react/cjs/redux-toolkit-react.development.cjs +55 -0
  39. package/dist/react/cjs/redux-toolkit-react.development.cjs.map +1 -0
  40. package/dist/react/cjs/redux-toolkit-react.production.min.cjs +2 -0
  41. package/dist/react/cjs/redux-toolkit-react.production.min.cjs.map +1 -0
  42. package/dist/react/index.d.mts +22 -0
  43. package/dist/react/index.d.ts +22 -0
  44. package/dist/react/redux-toolkit-react.browser.mjs +2 -0
  45. package/dist/react/redux-toolkit-react.browser.mjs.map +1 -0
  46. package/dist/react/redux-toolkit-react.legacy-esm.js +47 -0
  47. package/dist/react/redux-toolkit-react.legacy-esm.js.map +1 -0
  48. package/dist/react/redux-toolkit-react.modern.mjs +28 -0
  49. package/dist/react/redux-toolkit-react.modern.mjs.map +1 -0
  50. package/dist/redux-toolkit.browser.mjs +3 -0
  51. package/dist/redux-toolkit.browser.mjs.map +1 -0
  52. package/dist/redux-toolkit.legacy-esm.js +2351 -0
  53. package/dist/redux-toolkit.legacy-esm.js.map +1 -0
  54. package/dist/redux-toolkit.modern.mjs +2330 -0
  55. package/dist/redux-toolkit.modern.mjs.map +1 -0
  56. package/dist/uncheckedindexed.ts +16 -0
  57. package/package.json +310 -0
  58. package/query/package.json +13 -0
  59. package/query/react/package.json +13 -0
  60. package/react/package.json +13 -0
  61. package/skills/build-modern-redux-apps/modern-redux/SKILL.md +304 -0
  62. package/skills/build-modern-redux-apps/modern-redux/references/store-lifetime.md +53 -0
  63. package/skills/build-modern-redux-apps/redux-dataflow/SKILL.md +264 -0
  64. package/skills/evolve-and-diagnose-redux-apps/debug-redux-toolkit-apps/SKILL.md +269 -0
  65. package/skills/evolve-and-diagnose-redux-apps/migrate-to-modern-redux/SKILL.md +226 -0
  66. package/skills/manage-server-data/adopt-rtk-query/SKILL.md +385 -0
  67. package/skills/manage-server-data/adopt-rtk-query/references/endpoint-lifecycle.md +36 -0
  68. package/skills/model-redux-state/build-slices-and-selectors/SKILL.md +364 -0
  69. package/skills/model-redux-state/build-slices-and-selectors/references/slice-patterns.md +59 -0
  70. package/skills/model-redux-state/design-state-ownership/SKILL.md +322 -0
  71. package/skills/model-redux-state/design-state-ownership/references/state-ownership.md +28 -0
  72. package/skills/orchestrate-side-effects/handle-side-effects/SKILL.md +271 -0
  73. package/skills/orchestrate-side-effects/handle-side-effects/references/listener-workflows.md +34 -0
  74. package/src/actionCreatorInvariantMiddleware.ts +34 -0
  75. package/src/autoBatchEnhancer.ts +146 -0
  76. package/src/combineSlices.ts +487 -0
  77. package/src/configureStore.ts +248 -0
  78. package/src/createAction.ts +324 -0
  79. package/src/createAsyncThunk.ts +791 -0
  80. package/src/createDraftSafeSelector.ts +30 -0
  81. package/src/createReducer.ts +217 -0
  82. package/src/createSlice.ts +1079 -0
  83. package/src/devtoolsExtension.ts +241 -0
  84. package/src/dynamicMiddleware/index.ts +93 -0
  85. package/src/dynamicMiddleware/react/index.ts +101 -0
  86. package/src/dynamicMiddleware/types.ts +82 -0
  87. package/src/entities/create_adapter.ts +47 -0
  88. package/src/entities/entity_state.ts +38 -0
  89. package/src/entities/index.ts +8 -0
  90. package/src/entities/models.ts +198 -0
  91. package/src/entities/sorted_state_adapter.ts +266 -0
  92. package/src/entities/state_adapter.ts +58 -0
  93. package/src/entities/state_selectors.ts +73 -0
  94. package/src/entities/unsorted_state_adapter.ts +204 -0
  95. package/src/entities/utils.ts +68 -0
  96. package/src/formatProdErrorMessage.ts +13 -0
  97. package/src/getDefaultEnhancers.ts +31 -0
  98. package/src/getDefaultMiddleware.ts +113 -0
  99. package/src/immerImports.ts +7 -0
  100. package/src/immutableStateInvariantMiddleware.ts +274 -0
  101. package/src/index.ts +213 -0
  102. package/src/listenerMiddleware/exceptions.ts +20 -0
  103. package/src/listenerMiddleware/index.ts +562 -0
  104. package/src/listenerMiddleware/task.ts +100 -0
  105. package/src/listenerMiddleware/types.ts +886 -0
  106. package/src/listenerMiddleware/utils.ts +30 -0
  107. package/src/mapBuilders.ts +298 -0
  108. package/src/matchers.ts +365 -0
  109. package/src/nanoid.ts +20 -0
  110. package/src/query/HandledError.ts +6 -0
  111. package/src/query/apiTypes.ts +120 -0
  112. package/src/query/baseQueryTypes.ts +101 -0
  113. package/src/query/core/apiState.ts +377 -0
  114. package/src/query/core/buildInitiate.ts +596 -0
  115. package/src/query/core/buildMiddleware/batchActions.ts +207 -0
  116. package/src/query/core/buildMiddleware/cacheCollection.ts +204 -0
  117. package/src/query/core/buildMiddleware/cacheLifecycle.ts +379 -0
  118. package/src/query/core/buildMiddleware/devMiddleware.ts +34 -0
  119. package/src/query/core/buildMiddleware/index.ts +162 -0
  120. package/src/query/core/buildMiddleware/invalidationByTags.ts +139 -0
  121. package/src/query/core/buildMiddleware/polling.ts +187 -0
  122. package/src/query/core/buildMiddleware/queryLifecycle.ts +508 -0
  123. package/src/query/core/buildMiddleware/types.ts +173 -0
  124. package/src/query/core/buildMiddleware/windowEventHandling.ts +64 -0
  125. package/src/query/core/buildSelectors.ts +413 -0
  126. package/src/query/core/buildSlice.ts +735 -0
  127. package/src/query/core/buildThunks.ts +1124 -0
  128. package/src/query/core/index.ts +58 -0
  129. package/src/query/core/module.ts +727 -0
  130. package/src/query/core/rtkImports.ts +24 -0
  131. package/src/query/core/setupListeners.ts +118 -0
  132. package/src/query/createApi.ts +506 -0
  133. package/src/query/defaultSerializeQueryArgs.ts +52 -0
  134. package/src/query/endpointDefinitions.ts +1717 -0
  135. package/src/query/fakeBaseQuery.ts +21 -0
  136. package/src/query/fetchBaseQuery.ts +385 -0
  137. package/src/query/index.ts +105 -0
  138. package/src/query/react/ApiProvider.tsx +69 -0
  139. package/src/query/react/buildHooks.ts +2297 -0
  140. package/src/query/react/constants.ts +2 -0
  141. package/src/query/react/index.ts +45 -0
  142. package/src/query/react/module.ts +275 -0
  143. package/src/query/react/namedHooks.ts +59 -0
  144. package/src/query/react/reactImports.ts +10 -0
  145. package/src/query/react/reactReduxImports.ts +1 -0
  146. package/src/query/react/rtkqImports.ts +8 -0
  147. package/src/query/react/useSerializedStableValue.ts +17 -0
  148. package/src/query/react/useShallowStableValue.ts +13 -0
  149. package/src/query/retry.ts +233 -0
  150. package/src/query/standardSchema.ts +35 -0
  151. package/src/query/tsHelpers.ts +48 -0
  152. package/src/query/utils/capitalize.ts +3 -0
  153. package/src/query/utils/copyWithStructuralSharing.ts +27 -0
  154. package/src/query/utils/countObjectKeys.ts +14 -0
  155. package/src/query/utils/filterMap.ts +27 -0
  156. package/src/query/utils/getCurrent.ts +6 -0
  157. package/src/query/utils/getOrInsert.ts +41 -0
  158. package/src/query/utils/immerImports.ts +9 -0
  159. package/src/query/utils/index.ts +11 -0
  160. package/src/query/utils/isAbsoluteUrl.ts +9 -0
  161. package/src/query/utils/isDocumentVisible.ts +12 -0
  162. package/src/query/utils/isNotNullish.ts +7 -0
  163. package/src/query/utils/isOnline.ts +12 -0
  164. package/src/query/utils/isValidUrl.ts +9 -0
  165. package/src/query/utils/joinUrls.ts +26 -0
  166. package/src/query/utils/signals.ts +33 -0
  167. package/src/react/index.ts +7 -0
  168. package/src/reduxImports.ts +8 -0
  169. package/src/reselectImports.ts +1 -0
  170. package/src/serializableStateInvariantMiddleware.ts +285 -0
  171. package/src/tsHelpers.ts +214 -0
  172. package/src/uncheckedindexed.ts +16 -0
  173. package/src/utils.ts +125 -0
@@ -0,0 +1,21 @@
1
+ import type { BaseQueryFn } from './baseQueryTypes'
2
+
3
+ export const _NEVER = /* @__PURE__ */ Symbol()
4
+ export type NEVER = typeof _NEVER
5
+
6
+ /**
7
+ * Creates a "fake" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.
8
+ * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.
9
+ */
10
+ export function fakeBaseQuery<ErrorType>(): BaseQueryFn<
11
+ void,
12
+ NEVER,
13
+ ErrorType,
14
+ {}
15
+ > {
16
+ return function () {
17
+ throw new Error(
18
+ 'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.',
19
+ )
20
+ }
21
+ }
@@ -0,0 +1,385 @@
1
+ import { joinUrls } from './utils'
2
+ import { isPlainObject } from './core/rtkImports'
3
+ import type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes'
4
+ import type { MaybePromise, Override } from './tsHelpers'
5
+ import { anySignal, timeoutSignal } from './utils/signals'
6
+
7
+ export type ResponseHandler =
8
+ | 'content-type'
9
+ | 'json'
10
+ | 'text'
11
+ | ((response: Response) => Promise<any>)
12
+
13
+ type CustomRequestInit = Override<
14
+ RequestInit,
15
+ {
16
+ headers?:
17
+ | Headers
18
+ | string[][]
19
+ | Record<string, string | undefined>
20
+ | undefined
21
+ }
22
+ >
23
+
24
+ export interface FetchArgs extends CustomRequestInit {
25
+ url: string
26
+ params?: Record<string, any>
27
+ body?: any
28
+ responseHandler?: ResponseHandler
29
+ validateStatus?: (response: Response, body: any) => boolean
30
+ /**
31
+ * A number in milliseconds that represents that maximum time a request can take before timing out.
32
+ */
33
+ timeout?: number
34
+ }
35
+
36
+ /**
37
+ * A mini-wrapper that passes arguments straight through to
38
+ * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.
39
+ * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.
40
+ */
41
+ const defaultFetchFn: typeof fetch = (...args) => fetch(...args)
42
+
43
+ const defaultValidateStatus = (response: Response) =>
44
+ response.status >= 200 && response.status <= 299
45
+
46
+ const defaultIsJsonContentType = (headers: Headers) =>
47
+ /*applicat*/ /ion\/(vnd\.api\+)?json/.test(headers.get('content-type') || '')
48
+
49
+ export type FetchBaseQueryError =
50
+ | {
51
+ /**
52
+ * * `number`:
53
+ * HTTP status code
54
+ */
55
+ status: number
56
+ data: unknown
57
+ }
58
+ | {
59
+ /**
60
+ * * `"FETCH_ERROR"`:
61
+ * An error that occurred during execution of `fetch` or the `fetchFn` callback option
62
+ **/
63
+ status: 'FETCH_ERROR'
64
+ data?: undefined
65
+ error: string
66
+ }
67
+ | {
68
+ /**
69
+ * * `"PARSING_ERROR"`:
70
+ * An error happened during parsing.
71
+ * Most likely a non-JSON-response was returned with the default `responseHandler` "JSON",
72
+ * or an error occurred while executing a custom `responseHandler`.
73
+ **/
74
+ status: 'PARSING_ERROR'
75
+ originalStatus: number
76
+ data: string
77
+ error: string
78
+ }
79
+ | {
80
+ /**
81
+ * * `"TIMEOUT_ERROR"`:
82
+ * Request timed out
83
+ **/
84
+ status: 'TIMEOUT_ERROR'
85
+ data?: undefined
86
+ error: string
87
+ }
88
+ | {
89
+ /**
90
+ * * `"CUSTOM_ERROR"`:
91
+ * A custom error type that you can return from your `queryFn` where another error might not make sense.
92
+ **/
93
+ status: 'CUSTOM_ERROR'
94
+ data?: unknown
95
+ error: string
96
+ }
97
+
98
+ function stripUndefined(obj: any) {
99
+ if (!isPlainObject(obj)) {
100
+ return obj
101
+ }
102
+ const copy: Record<string, any> = { ...obj }
103
+ for (const [k, v] of Object.entries(copy)) {
104
+ if (v === undefined) delete copy[k]
105
+ }
106
+ return copy
107
+ }
108
+
109
+ // Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.
110
+ const isJsonifiable = (body: any) =>
111
+ typeof body === 'object' &&
112
+ (isPlainObject(body) ||
113
+ Array.isArray(body) ||
114
+ typeof body.toJSON === 'function')
115
+
116
+ export type FetchBaseQueryArgs = {
117
+ baseUrl?: string
118
+ prepareHeaders?: (
119
+ headers: Headers,
120
+ api: Pick<
121
+ BaseQueryApi,
122
+ 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'
123
+ > & { arg: string | FetchArgs; extraOptions: unknown },
124
+ ) => MaybePromise<Headers | void>
125
+ fetchFn?: (
126
+ input: RequestInfo,
127
+ init?: RequestInit | undefined,
128
+ ) => Promise<Response>
129
+ paramsSerializer?: (params: Record<string, any>) => string
130
+ /**
131
+ * By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass
132
+ * in a predicate function for your given api to get the same automatic stringifying behavior
133
+ * @example
134
+ * ```ts
135
+ * const isJsonContentType = (headers: Headers) => ["application/vnd.api+json", "application/json", "application/vnd.hal+json"].includes(headers.get("content-type")?.trim());
136
+ * ```
137
+ */
138
+ isJsonContentType?: (headers: Headers) => boolean
139
+ /**
140
+ * Defaults to `application/json`;
141
+ */
142
+ jsonContentType?: string
143
+
144
+ /**
145
+ * Custom replacer function used when calling `JSON.stringify()`;
146
+ */
147
+ jsonReplacer?: (this: any, key: string, value: any) => any
148
+ } & RequestInit &
149
+ Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>
150
+
151
+ export type FetchBaseQueryMeta = { request: Request; response?: Response }
152
+
153
+ /**
154
+ * This is a very small wrapper around fetch that aims to simplify requests.
155
+ *
156
+ * @example
157
+ * ```ts
158
+ * const baseQuery = fetchBaseQuery({
159
+ * baseUrl: 'https://api.your-really-great-app.com/v1/',
160
+ * prepareHeaders: (headers, { getState }) => {
161
+ * const token = (getState() as RootState).auth.token;
162
+ * // If we have a token set in state, let's assume that we should be passing it.
163
+ * if (token) {
164
+ * headers.set('authorization', `Bearer ${token}`);
165
+ * }
166
+ * return headers;
167
+ * },
168
+ * })
169
+ * ```
170
+ *
171
+ * @param {string} baseUrl
172
+ * The base URL for an API service.
173
+ * Typically in the format of https://example.com/
174
+ *
175
+ * @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders
176
+ * An optional function that can be used to inject headers on requests.
177
+ * Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.
178
+ * Useful for setting authentication or headers that need to be set conditionally.
179
+ *
180
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers
181
+ *
182
+ * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn
183
+ * Accepts a custom `fetch` function if you do not want to use the default on the window.
184
+ * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`
185
+ *
186
+ * @param {(params: Record<string, unknown>) => string} paramsSerializer
187
+ * An optional function that can be used to stringify querystring parameters.
188
+ *
189
+ * @param {(headers: Headers) => boolean} isJsonContentType
190
+ * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`
191
+ *
192
+ * @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.
193
+ *
194
+ * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.
195
+ *
196
+ * @param {number} timeout
197
+ * A number in milliseconds that represents the maximum time a request can take before timing out.
198
+ */
199
+
200
+ export function fetchBaseQuery({
201
+ baseUrl,
202
+ prepareHeaders = (x) => x,
203
+ fetchFn = defaultFetchFn,
204
+ paramsSerializer,
205
+ isJsonContentType = defaultIsJsonContentType,
206
+ jsonContentType = 'application/json',
207
+ jsonReplacer,
208
+ timeout: defaultTimeout,
209
+ responseHandler: globalResponseHandler,
210
+ validateStatus: globalValidateStatus,
211
+ ...baseFetchOptions
212
+ }: FetchBaseQueryArgs = {}): BaseQueryFn<
213
+ string | FetchArgs,
214
+ unknown,
215
+ FetchBaseQueryError,
216
+ {},
217
+ FetchBaseQueryMeta
218
+ > {
219
+ if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {
220
+ console.warn(
221
+ 'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.',
222
+ )
223
+ }
224
+ return async (arg, api, extraOptions) => {
225
+ const { getState, extra, endpoint, forced, type } = api
226
+ let meta: FetchBaseQueryMeta | undefined
227
+ let {
228
+ url,
229
+ headers = new Headers(baseFetchOptions.headers),
230
+ params = undefined,
231
+ responseHandler = globalResponseHandler ?? ('json' as const),
232
+ validateStatus = globalValidateStatus ?? defaultValidateStatus,
233
+ timeout = defaultTimeout,
234
+ ...rest
235
+ } = typeof arg == 'string' ? { url: arg } : arg
236
+
237
+ let config: RequestInit = {
238
+ ...baseFetchOptions,
239
+ signal: timeout
240
+ ? anySignal(api.signal, timeoutSignal(timeout))
241
+ : api.signal,
242
+ ...rest,
243
+ }
244
+
245
+ headers = new Headers(stripUndefined(headers))
246
+ config.headers =
247
+ (await prepareHeaders(headers, {
248
+ getState,
249
+ arg,
250
+ extra,
251
+ endpoint,
252
+ forced,
253
+ type,
254
+ extraOptions,
255
+ })) || headers
256
+
257
+ const bodyIsJsonifiable = isJsonifiable(config.body)
258
+
259
+ // Remove content-type for non-jsonifiable bodies to let the browser set it automatically
260
+ // Exception: keep content-type for string bodies as they might be intentional (text/plain, text/html, etc.)
261
+ if (
262
+ config.body != null &&
263
+ !bodyIsJsonifiable &&
264
+ typeof config.body !== 'string'
265
+ ) {
266
+ config.headers.delete('content-type')
267
+ }
268
+
269
+ if (!config.headers.has('content-type') && bodyIsJsonifiable) {
270
+ config.headers.set('content-type', jsonContentType)
271
+ }
272
+
273
+ if (bodyIsJsonifiable && isJsonContentType(config.headers)) {
274
+ config.body = JSON.stringify(config.body, jsonReplacer)
275
+ }
276
+
277
+ // Set Accept header based on responseHandler if not already set
278
+ if (!config.headers.has('accept')) {
279
+ if (responseHandler === 'json') {
280
+ config.headers.set('accept', 'application/json')
281
+ } else if (responseHandler === 'text') {
282
+ config.headers.set('accept', 'text/plain, text/html, */*')
283
+ }
284
+ // For 'content-type' responseHandler, don't set Accept (let server decide)
285
+ }
286
+
287
+ if (params) {
288
+ const divider = ~url.indexOf('?') ? '&' : '?'
289
+ const query = paramsSerializer
290
+ ? paramsSerializer(params)
291
+ : new URLSearchParams(stripUndefined(params))
292
+ url += divider + query
293
+ }
294
+
295
+ url = joinUrls(baseUrl, url)
296
+
297
+ const request = new Request(url, config)
298
+ const requestClone = new Request(url, config)
299
+ meta = { request: requestClone }
300
+
301
+ let response
302
+ try {
303
+ response = await fetchFn(request)
304
+ } catch (e) {
305
+ return {
306
+ error: {
307
+ status:
308
+ (e instanceof Error ||
309
+ (typeof DOMException !== 'undefined' &&
310
+ e instanceof DOMException)) &&
311
+ e.name === 'TimeoutError'
312
+ ? 'TIMEOUT_ERROR'
313
+ : 'FETCH_ERROR',
314
+ error: String(e),
315
+ },
316
+ meta,
317
+ }
318
+ }
319
+ const responseClone = response.clone()
320
+
321
+ meta.response = responseClone
322
+
323
+ let resultData: any
324
+ let responseText: string = ''
325
+ try {
326
+ let handleResponseError
327
+ await Promise.all([
328
+ handleResponse(response, responseHandler).then(
329
+ (r) => (resultData = r),
330
+ (e) => (handleResponseError = e),
331
+ ),
332
+ // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182
333
+ // we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios
334
+ responseClone.text().then(
335
+ (r) => (responseText = r),
336
+ () => {},
337
+ ),
338
+ ])
339
+ if (handleResponseError) throw handleResponseError
340
+ } catch (e) {
341
+ return {
342
+ error: {
343
+ status: 'PARSING_ERROR',
344
+ originalStatus: response.status,
345
+ data: responseText,
346
+ error: String(e),
347
+ },
348
+ meta,
349
+ }
350
+ }
351
+
352
+ return validateStatus(response, resultData)
353
+ ? {
354
+ data: resultData,
355
+ meta,
356
+ }
357
+ : {
358
+ error: {
359
+ status: response.status,
360
+ data: resultData,
361
+ },
362
+ meta,
363
+ }
364
+ }
365
+
366
+ async function handleResponse(
367
+ response: Response,
368
+ responseHandler: ResponseHandler,
369
+ ) {
370
+ if (typeof responseHandler === 'function') {
371
+ return responseHandler(response)
372
+ }
373
+
374
+ if (responseHandler === 'content-type') {
375
+ responseHandler = isJsonContentType(response.headers) ? 'json' : 'text'
376
+ }
377
+
378
+ if (responseHandler === 'json') {
379
+ const text = await response.text()
380
+ return text.length ? JSON.parse(text) : null
381
+ }
382
+
383
+ return response.text()
384
+ }
385
+ }
@@ -0,0 +1,105 @@
1
+ // This must remain here so that the `mangleErrors.cjs` build script
2
+ // does not have to import this into each source file it rewrites.
3
+ import { formatProdErrorMessage } from '@reduxjs/toolkit'
4
+
5
+ export type {
6
+ CombinedState,
7
+ QueryCacheKey,
8
+ QueryKeys,
9
+ QuerySubState,
10
+ RootState,
11
+ SubscriptionOptions,
12
+ } from './core/apiState'
13
+ export { QueryStatus } from './core/apiState'
14
+ export type { Api, ApiContext, Module } from './apiTypes'
15
+
16
+ export type {
17
+ BaseQueryApi,
18
+ BaseQueryArg,
19
+ BaseQueryEnhancer,
20
+ BaseQueryError,
21
+ BaseQueryExtraOptions,
22
+ BaseQueryFn,
23
+ BaseQueryMeta,
24
+ BaseQueryResult,
25
+ QueryReturnValue,
26
+ } from './baseQueryTypes'
27
+ export type {
28
+ BaseEndpointDefinition,
29
+ EndpointDefinitions,
30
+ EndpointDefinition,
31
+ EndpointBuilder,
32
+ QueryDefinition,
33
+ MutationDefinition,
34
+ MutationExtraOptions,
35
+ InfiniteQueryArgFrom,
36
+ InfiniteQueryDefinition,
37
+ InfiniteQueryExtraOptions,
38
+ PageParamFrom,
39
+ TagDescription,
40
+ QueryArgFrom,
41
+ QueryExtraOptions,
42
+ ResultTypeFrom,
43
+ DefinitionType,
44
+ DefinitionsFromApi,
45
+ OverrideResultType,
46
+ ResultDescription,
47
+ TagTypesFromApi,
48
+ UpdateDefinitions,
49
+ SchemaFailureHandler,
50
+ SchemaFailureConverter,
51
+ SchemaFailureInfo,
52
+ SchemaType,
53
+ } from './endpointDefinitions'
54
+ export { fetchBaseQuery } from './fetchBaseQuery'
55
+ export type {
56
+ FetchBaseQueryArgs,
57
+ FetchBaseQueryError,
58
+ FetchBaseQueryMeta,
59
+ FetchArgs,
60
+ } from './fetchBaseQuery'
61
+ export { retry } from './retry'
62
+ export type { RetryOptions } from './retry'
63
+ export { setupListeners } from './core/setupListeners'
64
+ export { skipToken } from './core/buildSelectors'
65
+ export type {
66
+ QueryResultSelectorResult,
67
+ MutationResultSelectorResult,
68
+ SkipToken,
69
+ } from './core/buildSelectors'
70
+ export type {
71
+ QueryActionCreatorResult,
72
+ MutationActionCreatorResult,
73
+ StartQueryActionCreatorOptions,
74
+ } from './core/buildInitiate'
75
+ export type { CreateApi, CreateApiOptions } from './createApi'
76
+ export { buildCreateApi } from './createApi'
77
+ export { _NEVER, fakeBaseQuery } from './fakeBaseQuery'
78
+ export { copyWithStructuralSharing } from './utils/copyWithStructuralSharing'
79
+ export { createApi, coreModule, coreModuleName } from './core/index'
80
+ export type {
81
+ InfiniteData,
82
+ InfiniteQueryActionCreatorResult,
83
+ InfiniteQueryConfigOptions,
84
+ InfiniteQueryResultSelectorResult,
85
+ InfiniteQuerySubState,
86
+ TypedMutationOnQueryStarted,
87
+ TypedQueryOnQueryStarted,
88
+ } from './core/index'
89
+ export type {
90
+ ApiEndpointMutation,
91
+ ApiEndpointQuery,
92
+ ApiEndpointInfiniteQuery,
93
+ ApiModules,
94
+ CoreModule,
95
+ PrefetchOptions,
96
+ } from './core/module'
97
+ export { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'
98
+ export type { SerializeQueryArgs } from './defaultSerializeQueryArgs'
99
+
100
+ export type {
101
+ Id as TSHelpersId,
102
+ Override as TSHelpersOverride,
103
+ } from './tsHelpers'
104
+
105
+ export { NamedSchemaError } from './standardSchema'
@@ -0,0 +1,69 @@
1
+ import { configureStore } from '@reduxjs/toolkit'
2
+ import type { Context } from 'react'
3
+ import { useContext, useEffect } from './reactImports'
4
+ import * as React from 'react'
5
+ import type { ReactReduxContextValue } from 'react-redux'
6
+ import { Provider, ReactReduxContext } from './reactReduxImports'
7
+ import { setupListeners } from './rtkqImports'
8
+ import type { Api } from '@reduxjs/toolkit/query'
9
+
10
+ /**
11
+ * Can be used as a `Provider` if you **do not already have a Redux store**.
12
+ *
13
+ * @example
14
+ * ```tsx
15
+ * // codeblock-meta no-transpile title="Basic usage - wrap your App with ApiProvider"
16
+ * import * as React from 'react';
17
+ * import { ApiProvider } from '@reduxjs/toolkit/query/react';
18
+ * import { Pokemon } from './features/Pokemon';
19
+ *
20
+ * function App() {
21
+ * return (
22
+ * <ApiProvider api={api}>
23
+ * <Pokemon />
24
+ * </ApiProvider>
25
+ * );
26
+ * }
27
+ * ```
28
+ *
29
+ * @remarks
30
+ * Using this together with an existing redux store, both will
31
+ * conflict with each other - please use the traditional redux setup
32
+ * in that case.
33
+ */
34
+ export function ApiProvider(props: {
35
+ children: any
36
+ api: Api<any, {}, any, any>
37
+ setupListeners?: Parameters<typeof setupListeners>[1] | false
38
+ context?: Context<ReactReduxContextValue | null>
39
+ }) {
40
+ const context = props.context || ReactReduxContext
41
+ const existingContext = useContext(context)
42
+ if (existingContext) {
43
+ throw new Error(
44
+ 'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.',
45
+ )
46
+ }
47
+ const [store] = React.useState(() =>
48
+ configureStore({
49
+ reducer: {
50
+ [props.api.reducerPath]: props.api.reducer,
51
+ },
52
+ middleware: (gDM) => gDM().concat(props.api.middleware),
53
+ }),
54
+ )
55
+ // Adds the event listeners for online/offline/focus/etc
56
+ useEffect(
57
+ (): undefined | (() => void) =>
58
+ props.setupListeners === false
59
+ ? undefined
60
+ : setupListeners(store.dispatch, props.setupListeners),
61
+ [props.setupListeners, store.dispatch],
62
+ )
63
+
64
+ return (
65
+ <Provider store={store} context={context}>
66
+ {props.children}
67
+ </Provider>
68
+ )
69
+ }